PluginProbe
aBlocks – Gutenberg Blocks, User Dashboard Builder, Popup Builder, Form Builder & Animation Builder / trunk
aBlocks – Gutenberg Blocks, User Dashboard Builder, Popup Builder, Form Builder & Animation Builder vtrunk
2.12.0 2.11.1 2.11.0 2.10.0 2.9.0 2.7.4 2.7.5 2.7.6 2.7.7 2.8.0 2.8.1 2.9.1 trunk 1.0 1.0-beta1 1.0-beta2 1.0-beta3 1.0.1 1.0.2 1.0.3 1.1.0 1.1.1 1.1.2 1.2.0 1.2.1 All 78 releases
ablocks / includes / assets.php

assets.php in aBlocks – Gutenberg Blocks, User Dashboard Builder, Popup Builder, Form Builder & Animation Builder trunk, at includes/assets.php

921 lines 39.2 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 namespace ABlocks;
3
4 if ( ! defined( 'ABSPATH' ) ) {
5 exit;
6 }
7
8 use ABlocks\Classes\FileUpload;
9 use ABlocks\Classes\AssetsGenerator;
10 use ABlocks\Classes\RegisterScripts;
11 use ABlocks\Classes\GlobalCssGenerator;
12 use ABlocks\Classes\GlobalClasses;
13 use ABlocks\Classes\FontLoadLocally;
14 use ABlocks\Admin\Menu;
15 use ABlocks\Helper;
16
17 class Assets {
18
19 /** Records which plugin version last generated the page stylesheets. */
20 const BUILD_OPTION = 'ablocks_assets_build';
21
22 public $current_page_template_part = [];
23 public $current_page_blocks = [];
24 private $FileUpload;
25 private $current_page_slug = '';
26 private $theme_builder_locations = [];
27 public static function init() {
28 $self = new self();
29 $self->FileUpload = new FileUpload();
30 $self->current_page_slug = '';
31 add_action( 'admin_enqueue_scripts', [ $self, 'dashboard_scripts' ], 10 );
32 add_action( 'admin_enqueue_scripts', [ $self, 'demo_importer_scripts' ], 10 );
33 add_action( 'enqueue_block_assets', [ $self, 'block_editor_assets' ] );
34 add_action( 'enqueue_block_assets', [ $self, 'register_scripts' ] );
35 // Frontend fonts are now emitted by core via CoreFontRegistry (theme.json
36 // @font-face) with a Google Fonts fallback. See docs/FONT-MANAGEMENT-PLAN.md.
37
38 add_action( 'wp_enqueue_scripts', [ $self, 'enqueue_frontend_assets' ], 99 );
39 // Global CSS
40 add_action( 'wp_enqueue_block_assets', [ $self, 'global_css_variable' ] );
41 add_action( 'wp_enqueue_scripts', [ $self, 'global_css_variable' ] );
42 add_action( 'enqueue_block_editor_assets', [ $self, 'global_css_variable' ] );
43 add_action( 'enqueue_block_editor_assets', [ $self, 'add_editor_inline_css' ] );
44 add_action( 'enqueue_block_editor_assets', [ $self, 'editor_google_fonts' ] );
45
46 // Detect page
47 add_action( 'wp', array( $self, 'detect_page' ) );
48
49 if ( ! is_admin() && Helper::is_enabled_assets_generation() ) {
50 if ( Helper::is_fse_theme() ) {
51 add_filter( 'pre_render_block', [ $self, 'set_current_page_template_part' ], 5, 2 );
52 add_action( 'ablocks/before_enqueue_frontend_scripts', [ $self, 'regenerate_missing_assets' ] );
53 } else {
54 add_action( 'ablocks_theme_builder_after_dispatch', [ $self, 'set_theme_builder_locations' ] );
55 add_action( 'wp', [ $self, 'regenerate_missing_assets' ], 20 );
56 }
57 }
58
59 }
60
61 public function detect_page() {
62 if ( is_404() ) {
63 $this->current_page_slug = '404';
64 } elseif ( is_search() ) {
65 $this->current_page_slug = 'search';
66 } elseif ( is_home() ) {
67 $posts_page_id = get_option( 'page_for_posts' );
68 $this->current_page_slug = $posts_page_id ? (string) $posts_page_id : 'blog';
69 } elseif ( is_post_type_archive() ) {
70 $this->current_page_slug = 'archive-' . get_post_type();
71 } elseif ( is_category() ) {
72 $term = get_queried_object();
73 $this->current_page_slug = 'category-' . $term->term_id; // or use slug
74 } elseif ( is_tag() ) {
75 $term = get_queried_object();
76 $this->current_page_slug = 'tag-' . $term->term_id;
77 } elseif ( is_tax() ) {
78 $term = get_queried_object();
79 $this->current_page_slug = 'tax-' . $term->taxonomy . '-' . $term->term_id;
80 } elseif ( is_author() ) {
81 $this->current_page_slug = 'author-' . get_the_author_meta( 'ID' );
82 } elseif ( is_date() ) {
83 $this->current_page_slug = 'date-archive';
84 } elseif ( is_singular() ) {
85 $this->current_page_slug = (string) get_the_ID(); // just the post/page/custom ID
86 } else {
87 $this->current_page_slug = (string) get_the_ID(); // fallback to ID
88 }//end if
89 }
90
91 public function get_current_archive_post_type() {
92 if ( is_post_type_archive() ) {
93 $post_type = get_query_var( 'post_type' );
94 if ( is_array( $post_type ) ) {
95 $post_type = reset( $post_type );
96 }
97 return $post_type;
98 }
99 return null;
100 }
101
102 public function get_localize_script_data() {
103 return [
104 'rest_url' => esc_url_raw( rest_url() ),
105 'namespace' => ABLOCKS_PLUGIN_SLUG . '/v1/',
106 'plugin_root_url' => ABLOCKS_ROOT_URL,
107 'plugin_root_path' => ABLOCKS_ROOT_DIR_PATH,
108 'admin_url' => admin_url(),
109 'site_url' => site_url(),
110 'route_path' => wp_parse_url( admin_url(), PHP_URL_PATH ),
111 'ajax_url' => esc_url( admin_url( 'admin-ajax.php' ) ),
112 'is_pro' => (bool) Helper::is_active_ablocks_pro(),
113 'is_archive' => (bool) is_archive(),
114 'archive_post_type' => $this->get_current_archive_post_type(),
115 // Responsive breakpoint widths (px) shared with the JS CSS generators
116 // and the block editor so media queries match the frontend.
117 'breakpoints' => Helper::get_breakpoints(),
118 // Ordered device list (Desktop + built-ins + custom breakpoints) for
119 // the atomic block's responsive device switcher. Widest-first, so
120 // the editor and the frontend agree on breakpoint precedence.
121 'responsive_devices' => Helper::get_responsive_devices(),
122 // Whether breakpoint queries overlap (cascade) or are exclusive
123 // bands (strict). The editor preview builds matching queries.
124 'breakpoint_mode' => Helper::get_breakpoint_mode(),
125 ];
126 }
127
128 public function get_localize_dashboard_data() {
129 // Anyone permitted to reach an aBlocks screen needs the nonce, or the
130 // dashboard loads and then 403s on every request it makes.
131 if ( ! current_user_can( Permissions::ACCESS ) ) {
132 return $this->get_localize_script_data();
133 }
134 return array_merge($this->get_localize_script_data(), [
135 'nonce' => wp_create_nonce( 'wp_rest' ),
136 'ablocks_nonce' => wp_create_nonce( 'ablocks_nonce' ),
137 'permissions' => Permissions::for_user(),
138 'is_admin_user' => Permissions::is_real_admin(),
139 ]);
140 }
141 public function get_localize_editor_data() {
142 if ( ! current_user_can( 'edit_posts' ) ) {
143 return $this->get_localize_script_data();
144 }
145 return array_merge($this->get_localize_script_data(), [
146 'nonce' => wp_create_nonce( 'wp_rest' ),
147 'ablocks_nonce' => wp_create_nonce( 'ablocks_nonce' ),
148 ]);
149 }
150 public function get_localize_frontend_data() {
151 $data = array_merge($this->get_localize_script_data(), [
152 'nonce' => wp_create_nonce( 'wp_rest' ),
153 'ablocks_nonce' => wp_create_nonce( 'ablocks_nonce' ),
154 ]);
155 // The absolute server path is only meaningful to admin-side code; on the
156 // frontend it would publish the filesystem layout in page source. No
157 // frontend script reads it (it is re-exported but never consumed).
158 unset( $data['plugin_root_path'] );
159 return $data;
160 }
161
162 /**
163 * Whether the frontend ABlocksGlobal payload has been attached this request.
164 *
165 * @var bool
166 */
167 private static $globals_localized = false;
168
169 /**
170 * Attach the frontend ABlocksGlobal payload to the shared data-only
171 * `ablocks-globals` handle, at most once per request.
172 *
173 * Previously each per-block script handle localized its own copy, so a page
174 * using N block types printed N identical `var ABlocksGlobal = {...}` blocks
175 * (and called wp_create_nonce() N times). Every aBlocks frontend script now
176 * depends on `ablocks-globals`, so WP prints the object once, before any
177 * consumer, in both asset-generation modes.
178 */
179 public static function localize_globals_once() {
180 if ( self::$globals_localized ) {
181 return;
182 }
183 self::$globals_localized = true;
184 // Self-register so callers never depend on RegisterScripts having run
185 // first — theme-builder templates and block render callbacks fire on
186 // different hooks, and a missing handle would drop the payload silently.
187 if ( ! wp_script_is( 'ablocks-globals', 'registered' ) ) {
188 wp_register_script( 'ablocks-globals', false, array(), ABLOCKS_VERSION, array() );
189 }
190 $self = new self();
191 wp_localize_script( 'ablocks-globals', 'ABlocksGlobal', $self->get_localize_frontend_data() );
192 }
193
194 public function get_dashboard_localize_script_data() {
195 $menu = new Menu();
196 $args = array(
197 'menu' => wp_json_encode( Helper::get_admin_menu_list() ),
198 'toplevel_menu_icon_url' => $menu->get_toplevel_menu_icon_url(),
199 'settings' => [
200 'default_container_width' => Helper::get_settings( 'default_container_width', 1280 ),
201 'container_padding' => Helper::get_settings( 'container_padding', 10 ),
202 'container_element_gap' => Helper::get_settings( 'container_element_gap', 20 ),
203 'enabled_assets_file_generation' => (bool) Helper::get_settings( 'enabled_assets_file_generation', false ),
204 'enabled_block_copy_paste_style' => (bool) Helper::get_settings( 'enabled_block_copy_paste_style', false ),
205 'enabled_load_google_font_locally' => (bool) Helper::get_settings( 'enabled_load_google_font_locally', false ),
206 'enabled_only_selected_fonts' => (bool) Helper::get_settings( 'enabled_only_selected_fonts', false ),
207 'selected_fonts' => (array) Helper::get_settings( 'selected_fonts', [] ),
208 'font_metric_fallback' => (bool) Helper::get_settings( 'font_metric_fallback', true ),
209 // Global typography picks from the same list the editor offers.
210 'theme_fonts' => \ABlocks\Classes\FontStack::get_theme_font_families(),
211 ],
212 'is_gutenberg_editor' => Helper::is_gutenberg_editor(),
213 'is_fse_theme' => Helper::is_fse_theme(),
214 'third_party_plugin_status' => [
215 'academy_lms' => Helper::is_active_academy(),
216 'storeengine' => Helper::is_active_storeengine(),
217 'wp_map_block' => Helper::is_active_wp_map_block(),
218 'easy_content_manager' => Helper::is_active_easy_content_manager(),
219 ]
220 );
221 return apply_filters(
222 'ablocks/assets/dashboard_scripts_data',
223 array_merge(
224 $this->get_localize_dashboard_data(),
225 $args
226 )
227 );
228 }
229 public function get_editor_localize_script_data() {
230 global $ablocks_blocks;
231 $post_types = Helper::get_public_post_type_options();
232 $args = array(
233 'settings' => [
234 'default_container_width' => Helper::get_settings( 'default_container_width', 1280 ),
235 'container_padding' => Helper::get_settings( 'container_padding', 10 ),
236 'container_element_gap' => Helper::get_settings( 'container_element_gap', 20 ),
237 'enabled_assets_file_generation' => (bool) Helper::get_settings( 'enabled_assets_file_generation', false ),
238 'enabled_block_copy_paste_style' => (bool) Helper::get_settings( 'enabled_block_copy_paste_style', false ),
239 'enabled_load_google_font_locally' => (bool) Helper::get_settings( 'enabled_load_google_font_locally', false ),
240 'enabled_only_selected_fonts' => (bool) Helper::get_settings( 'enabled_only_selected_fonts', false ),
241 'selected_fonts' => (array) Helper::get_settings( 'selected_fonts', [] ),
242 // Design system lock — the editor hides the custom pickers when these
243 // are on, leaving only the global presets.
244 'lock_global_typography' => (bool) Helper::get_settings( 'lock_global_typography', false ),
245 'lock_global_typography_strict' => (bool) Helper::get_settings( 'lock_global_typography_strict', false ),
246 'lock_global_colors' => (bool) Helper::get_settings( 'lock_global_colors', false ),
247 'frontend_dashboard_page' => (int) Helper::get_settings( 'frontend_dashboard_page' ),
248 'global_color' => (array) Helper::get_settings( 'global_color', [] ),
249 'global_typography' => (array) Helper::get_settings( 'global_typography', [] ),
250 'global_typography_list' => wp_list_pluck( Helper::get_settings( 'global_typography', [] ), 'value', 'id' ),
251 'global_font_family_fallback' => (string) Helper::get_settings( 'global_font_family_fallback', 'Sans-serif' ),
252 // Editor paste — see includes/api/paste-controller.php.
253 'paste_google_docs' => (bool) Helper::get_settings( 'paste_google_docs', true ),
254 'paste_convert_webp' => (bool) Helper::get_settings( 'paste_convert_webp', true ),
255 // Theme.json + Font Library families, so uploaded/theme fonts are
256 // selectable next to the Google catalog.
257 'theme_fonts' => \ABlocks\Classes\FontStack::get_theme_font_families(),
258 ],
259 'is_gutenberg_editor' => Helper::is_gutenberg_editor(),
260 'has_required_block_attribute_migration' => get_option( 'ablocks_has_required_block_attribute_migration' ),
261 'third_party_plugin_status' => [
262 'academy_lms' => Helper::is_active_academy(),
263 'storeengine' => Helper::is_active_storeengine(),
264 'wp_map_block' => Helper::is_active_wp_map_block(),
265 'quizpress' => Helper::is_active_quizpress(),
266 'easy_content_manager' => Helper::is_active_easy_content_manager(),
267 ],
268 'blocks_status' => $ablocks_blocks,
269 'post_types' => $post_types,
270 // What this user may do inside the editor. Read by
271 // src/utils/permissions.js to hide controls they cannot use.
272 'permissions' => Permissions::for_user(),
273 'is_admin_user' => Permissions::is_real_admin(),
274 );
275 return apply_filters(
276 'ablocks/assets/editor_scripts_data',
277 array_merge(
278 $this->get_localize_editor_data(),
279 $args
280 )
281 );
282 }
283
284 public function dashboard_scripts( $hook ) {
285 $demo_config = Helper::get_theme_demo_config();
286 if ( strpos( $hook, '_page_' . ABLOCKS_PLUGIN_SLUG ) !== false && strpos( $hook, $demo_config['menu_slug'] ) === false ) {
287 // Remove Notices
288 remove_all_actions( 'admin_notices' );
289 // dequeue third party plugin assets
290 add_action(
291 'wp_print_scripts',
292 function () {
293 $isSkip = apply_filters( 'ablocks/skip_no_conflict_backend_scripts', Helper::is_dev_mode_enable() );
294
295 if ( $isSkip ) {
296 return;
297 }
298
299 global $wp_scripts;
300 if ( ! $wp_scripts ) {
301 return;
302 }
303
304 $pluginUrl = plugins_url();
305 foreach ( $wp_scripts->queue as $script ) {
306 $src = $wp_scripts->registered[ $script ]->src;
307 if ( strpos( $src, $pluginUrl ) !== false && ! strpos( $src, ABLOCKS_PLUGIN_SLUG ) !== false ) {
308 wp_dequeue_script( $wp_scripts->registered[ $script ]->handle );
309 }
310 }
311 },
312 1
313 );
314
315 wp_enqueue_style( 'ablocks-fonts', $this->web_fonts_url( 'Roboto:ital,wght@0,300;0,400;0,500;0,700;1,300&display=swap' ), array(), ABLOCKS_VERSION );
316 wp_enqueue_style( 'ablocks-icon', ABLOCKS_ASSETS_URL . 'library/css/ablocks-icon/style.css', array( 'wp-components' ), filemtime( ABLOCKS_ASSETS_PATH . 'library/css/ablocks-icon/style.css' ), 'all' );
317 wp_enqueue_style( 'ablocks-dashboard-style', ABLOCKS_ASSETS_URL . 'build/dashboard.css', array( 'wp-components' ), filemtime( ABLOCKS_ASSETS_PATH . 'build/dashboard.css' ), 'all' );
318
319 $dependencies = include ABLOCKS_ASSETS_PATH . 'build/dashboard.asset.php';
320 wp_enqueue_script(
321 'ablocks-dashboard-scripts',
322 ABLOCKS_ASSETS_URL . 'build/dashboard.js',
323 $dependencies['dependencies'],
324 $dependencies['version'],
325 true
326 );
327 wp_localize_script( 'ablocks-dashboard-scripts', 'ABlocksGlobal', $this->get_dashboard_localize_script_data() );
328 wp_set_script_translations( 'ablocks-dashboard-scripts', 'ablocks', ABLOCKS_ROOT_DIR_PATH . 'languages' );
329 }//end if
330 }
331
332 public function demo_importer_scripts( $hook ) {
333 $demo_config = Helper::get_theme_demo_config();
334 if ( strpos( $hook, $demo_config['menu_slug'] ) !== false ) {
335 // Remove Notices
336 remove_all_actions( 'admin_notices' );
337 // dequeue third party plugin assets
338 add_action(
339 'wp_print_scripts',
340 function () {
341 $isSkip = apply_filters( 'ablocks/skip_no_conflict_demo_importer_scripts', Helper::is_dev_mode_enable() );
342
343 if ( $isSkip ) {
344 return;
345 }
346
347 global $wp_scripts;
348 if ( ! $wp_scripts ) {
349 return;
350 }
351
352 $pluginUrl = plugins_url();
353 foreach ( $wp_scripts->queue as $script ) {
354 $src = $wp_scripts->registered[ $script ]->src;
355 if ( strpos( $src, $pluginUrl ) !== false && ! strpos( $src, ABLOCKS_PLUGIN_SLUG ) !== false ) {
356 wp_dequeue_script( $wp_scripts->registered[ $script ]->handle );
357 }
358 }
359 },
360 1
361 );
362
363 $this->demo_template_importer_scripts();
364 }//end if
365 }
366
367 public function demo_template_importer_scripts() {
368 wp_enqueue_style( 'ablocks-fonts', $this->web_fonts_url( 'Roboto:ital,wght@0,300;0,400;0,500;0,700;1,300&display=swap' ), array(), ABLOCKS_VERSION );
369 wp_enqueue_style( 'ablocks-icon', ABLOCKS_ASSETS_URL . 'library/css/ablocks-icon/style.css', array( 'wp-components' ), filemtime( ABLOCKS_ASSETS_PATH . 'library/css/ablocks-icon/style.css' ), 'all' );
370 wp_enqueue_style( 'ablocks-dashboard-style', ABLOCKS_ASSETS_URL . 'build/demo-import.css', array( 'wp-components' ), filemtime( ABLOCKS_ASSETS_PATH . 'build/demo-import.css' ), 'all' );
371
372 $dependencies = include ABLOCKS_ASSETS_PATH . 'build/demo-import.asset.php';
373 wp_enqueue_script(
374 'ablocks-demo-import-scripts',
375 ABLOCKS_ASSETS_URL . 'build/demo-import.js',
376 $dependencies['dependencies'],
377 $dependencies['version'],
378 true
379 );
380 wp_localize_script( 'ablocks-demo-import-scripts', 'ABlocksGlobal', $this->get_dashboard_localize_script_data() );
381 wp_set_script_translations( 'ablocks-demo-import-scripts', 'ablocks', ABLOCKS_ROOT_DIR_PATH . 'languages' );
382 }
383
384 public function build_google_fonts_url( array $fonts ): string {
385 $family_strings = [];
386 foreach ( $fonts as $family => $weights ) {
387 $family_encoded = str_replace( ' ', '+', $family );
388 $weights = array_unique( array_map( 'strval', (array) $weights ) );
389 sort( $weights );
390 $family_strings[] = ! empty( $weights ) ? $family_encoded . ':wght@' . implode( ';', $weights ) : $family_encoded;
391 }
392 return '//fonts.googleapis.com/css2?family=' . implode( '&family=', $family_strings ) . '&display=swap';
393 }
394
395 public function web_fonts_url( $font ) {
396 if ( 'off' === _x( 'on', 'Google font: on or off', 'ablocks' ) ) {
397 return '';
398 }
399 return '//fonts.googleapis.com/css2?family=' . $font;
400 }
401
402
403
404 public function block_editor_assets() {
405 if ( is_admin() ) {
406 wp_enqueue_style( 'ablocks-editor-font-awesome', ABLOCKS_ASSETS_URL . 'library/font-awesome/css/all.min.css', array(), ABLOCKS_VERSION, 'all' );
407 wp_enqueue_style( 'ablocks-editor-fonts', $this->web_fonts_url( 'Roboto:ital,wght@0,300;0,400;0,500;0,700;1,300&display=swap' ), array(), ABLOCKS_VERSION );
408 wp_enqueue_style( 'ablocks-editor-icon', ABLOCKS_ASSETS_URL . 'library/css/ablocks-icon/style.css', array( 'wp-components' ), filemtime( ABLOCKS_ASSETS_PATH . 'library/css/ablocks-icon/style.css' ), 'all' );
409 wp_enqueue_style( 'ablocks-editor-style', ABLOCKS_ASSETS_URL . 'build/blocks.css', array( 'wp-components' ), filemtime( ABLOCKS_ASSETS_PATH . 'build/blocks.css' ), 'all' );
410
411 // js
412 $dependencies = include ABLOCKS_ASSETS_PATH . 'build/blocks.asset.php';
413 wp_enqueue_script(
414 'ablocks-editor-scripts',
415 ABLOCKS_ASSETS_URL . 'build/blocks.js',
416 $dependencies['dependencies'],
417 $dependencies['version'],
418 true
419 );
420 wp_localize_script( 'ablocks-editor-scripts', 'ABlocksGlobal', $this->get_editor_localize_script_data() );
421 wp_set_script_translations( 'ablocks-editor-scripts', 'ablocks', ABLOCKS_ROOT_DIR_PATH . 'languages' );
422 }
423 }
424 public function enqueue_frontend_assets() {
425 if ( ! Helper::is_enabled_assets_generation() ) {
426 return;
427 }
428
429 do_action( 'ablocks/before_enqueue_frontend_scripts' );
430
431 $script_loading_strategy = Helper::get_script_loading_strategy();
432
433 if ( ! $this->is_assets_generated() ) {
434 return;
435 }
436
437 if ( $this->current_page_slug ) {
438 // Enqueue google fonts
439 wp_enqueue_style( 'ablocks-frontend-google-fonts' );
440
441 $css_path = $this->FileUpload->get_file_path( $this->current_page_slug . '.min.css' );
442
443 // Performance Suite — inline the page CSS when it's small enough to
444 // avoid a render-blocking request; fall back to a normal <link> above
445 // the threshold. Opt-in via perf_inline_css.
446 $inline_css = (bool) apply_filters(
447 'ablocks/perf/perf_inline_css',
448 (bool) Helper::get_settings( 'perf_inline_css', true )
449 );
450 $inline_max = (int) apply_filters( 'ablocks/perf/inline_css_max_bytes', 50 * 1024 );
451 $css_size = file_exists( $css_path ) ? (int) filesize( $css_path ) : 0;
452
453 if ( $inline_css && $css_size > 0 && $css_size <= $inline_max ) {
454 wp_register_style( 'ablocks-blocks-combine-style', false, array(), ABLOCKS_VERSION );
455 wp_enqueue_style( 'ablocks-blocks-combine-style' );
456 // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents
457 wp_add_inline_style( 'ablocks-blocks-combine-style', (string) file_get_contents( $css_path ) );
458 } else {
459 wp_enqueue_style( 'ablocks-blocks-combine-style', $this->FileUpload->get_file_url( $this->current_page_slug . '.min.css' ), array(), filemtime( $css_path ), 'all' );
460
461 // Performance Suite — when the page stylesheet is too large to inline,
462 // load it non-blocking (media="print" + onload swap) so it no longer
463 // delays first paint. Opt-in via perf_async_css (default off: a too-
464 // aggressive critical set risks FOUC, so promote after QA). Editors
465 // viewing the frontend are bypassed so previews render immediately.
466 $async_css = (bool) apply_filters(
467 'ablocks/perf/perf_async_css',
468 (bool) Helper::get_settings( 'perf_async_css', false )
469 );
470 // Critical CSS — inline the above-the-fold/structural subset in
471 // <head> and load the full stylesheet non-blocking. This is a
472 // stronger form of async (it prevents the FOUC async alone can
473 // cause), so enabling it implies async delivery of the full file.
474 $critical_css = (bool) apply_filters(
475 'ablocks/perf/perf_critical_css',
476 (bool) Helper::get_settings( 'perf_critical_css', false )
477 );
478 $bypass_for_editor = is_user_logged_in() && current_user_can( 'edit_posts' )
479 && (bool) apply_filters( 'ablocks/perf/bypass_optimizations_for_editors', true );
480
481 if ( ( $async_css || $critical_css ) && ! $bypass_for_editor ) {
482 // Before deferring the full stylesheet, always inline the
483 // layout-critical CSS so the page paints with correct box
484 // sizes and never reflows when the deferred file loads. The
485 // split is property-based: the deferred remainder is cosmetic
486 // only (colors, shadows, hover states), so it cannot cause a
487 // layout shift (CLS). This makes async delivery safe.
488 // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents
489 list( $critical ) = \ABlocks\Classes\CriticalCss::split( (string) file_get_contents( $css_path ) );
490 if ( '' !== trim( (string) $critical ) ) {
491 wp_register_style( 'ablocks-critical-css', false, array(), ABLOCKS_VERSION );
492 wp_enqueue_style( 'ablocks-critical-css' );
493 wp_add_inline_style( 'ablocks-critical-css', $critical );
494 }
495 add_filter( 'style_loader_tag', [ $this, 'async_combined_style_tag' ], 20, 2 );
496 }
497 }
498
499 wp_enqueue_script( 'ablocks-blocks-combine-script', $this->FileUpload->get_file_url( $this->current_page_slug . '.min.js' ), array( 'ablocks-globals' ), filemtime( $this->FileUpload->get_file_path( $this->current_page_slug . '.min.js' ) ), true, [ 'strategy' => $script_loading_strategy ] );
500 self::localize_globals_once();
501 wp_set_script_translations( 'ablocks-blocks-combine-script', 'ablocks', ABLOCKS_ROOT_DIR_PATH . 'languages' );
502 } else {
503 // fallback if assets not available
504 add_filter( 'ablocks/is_allow_block_inline_assets', '__return_true' );
505 }
506 }
507
508 /**
509 * Rewrite the combined page stylesheet <link> so it loads without blocking
510 * render: fetch as media="print", then flip to media="all" on load, with a
511 * <noscript> fallback for JS-disabled clients. Only touches the aBlocks
512 * combined handle — third-party stylesheets are left untouched.
513 */
514 public function async_combined_style_tag( $tag, $handle ) {
515 if ( 'ablocks-blocks-combine-style' !== $handle ) {
516 return $tag;
517 }
518 $async_tag = preg_replace(
519 [ "/media=(['\"])[^'\"]*\\1/", '/>$/', '/\/>$/' ],
520 [ 'media="print" onload="this.media=\'all\'"', '>', '/>' ],
521 trim( $tag )
522 );
523 // Guarantee the print/onload attributes even if the original tag had no media.
524 if ( strpos( $async_tag, 'onload=' ) === false ) {
525 $async_tag = str_replace( '<link ', '<link media="print" onload="this.media=\'all\'" ', $async_tag );
526 }
527 $noscript = '<noscript>' . $tag . '</noscript>';
528 return $async_tag . "\n" . $noscript;
529 }
530
531 public function regenerate_missing_assets() {
532 if ( $this->is_assets_generated() ) {
533 return;
534 }
535
536 // classic
537 if ( ! Helper::is_fse_theme() ) {
538 $is_parse_main_content = false;
539 if ( is_array( $this->theme_builder_locations ) ) {
540 foreach ( $this->theme_builder_locations as $location_name => $location_id ) {
541 $post = get_post( $location_id );
542 if ( is_object( $post ) ) {
543 $this->set_current_page_template_part( $post->post_content, parse_blocks( $post->post_content ) );
544 }
545 if ( $location_name === 'header' ) {
546 $post = get_post( get_the_ID() );
547 if ( is_object( $post ) ) {
548 $this->set_current_page_template_part( $post->post_content, parse_blocks( $post->post_content ) );
549 }
550 $is_parse_main_content = true;
551 }
552 }
553 }
554 if ( false === $is_parse_main_content ) {
555 $post = get_post( get_the_ID() );
556 $this->set_current_page_template_part( $post->post_content, parse_blocks( $post->post_content ) );
557 }
558 }//end if
559
560 if ( count( $this->current_page_blocks ) ) {
561 $file_name = $this->current_page_slug;
562 AssetsGenerator::write_frontend_css_in_uploads_folder( $file_name, $this->current_page_blocks );
563 }
564 }
565 public function register_scripts() {
566 $register_styles = RegisterScripts::get_register_styles();
567 foreach ( $register_styles as $register_handler => $register_style ) {
568 wp_register_style( $register_handler, $register_style['url'], $register_style['deps'], ABLOCKS_VERSION, $register_style['media'] );
569 }
570 $register_scripts = RegisterScripts::get_register_scripts();
571 foreach ( $register_scripts as $register_handler => $register_script ) {
572 if ( isset( $register_script['dependencies'] ) ) {
573 $dependencies = include $register_script['dependencies'];
574 // Merge rather than overwrite: the generated asset.php only knows
575 // about build-time (@wordpress/*) dependencies, so replacing the
576 // declared list would silently drop hand-declared handles such as
577 // ablocks-globals.
578 $register_script['deps'] = array_values(
579 array_unique(
580 array_merge(
581 isset( $register_script['deps'] ) ? (array) $register_script['deps'] : array(),
582 $dependencies['dependencies']
583 )
584 )
585 );
586 $register_script['ver'] = $dependencies['version'];
587 }
588 wp_register_script(
589 $register_handler,
590 $register_script['url'],
591 $register_script['deps'],
592 $register_script['ver'],
593 $register_script['args']
594 );
595 }//end foreach
596 }
597 public function global_css_variable() {
598 wp_register_style( 'ablocks-editor-global-styles', false, array(), ABLOCKS_VERSION );
599 wp_enqueue_style( 'ablocks-editor-global-styles' );
600
601 // The :root variables only change when global settings change, so cache
602 // the generated string and rebuild it on settings save (see Blocks
603 // ::clear_global_css_cache) instead of looping settings on every request.
604 $css = get_transient( 'ablocks_global_css_vars' );
605 if ( false === $css ) {
606 $container_padding = Helper::get_settings( 'container_padding', 10 ) . 'px';
607 $css = ":root, body .editor-styles-wrapper {\n";
608 $css .= " --ablocks-container-padding: $container_padding;\n";
609
610 // Colors
611 $global_color = (array) Helper::get_settings( 'global_color', [] );
612 foreach ( $global_color as $color ) {
613 if ( isset( $color->id, $color->value ) ) {
614 $css .= " --ablocks-{$color->id}: {$color->value};\n";
615 }
616 }
617
618 // Typography
619 $global_typography = (array) Helper::get_settings( 'global_typography', [] );
620 foreach ( $global_typography as $typography ) {
621 if ( isset( $typography->id, $typography->value ) ) {
622 $id = $typography->id;
623 $value = $typography->value;
624
625 // Desktop values
626 if ( ! empty( $value->fontFamily ) ) {
627 // Every consumer of this variable drops it straight into
628 // font-family, so it has to carry the whole stack.
629 $font_stack = \ABlocks\Classes\FontStack::build(
630 $value->fontFamily,
631 isset( $value->fontFallback ) ? $value->fontFallback : ''
632 );
633 if ( '' !== $font_stack ) {
634 $css .= " --ablocks-{$id}-font-family: {$font_stack};\n";
635 }
636 }
637 if ( ! empty( $value->weight ) ) {
638 $css .= " --ablocks-{$id}-weight: {$value->weight};\n";
639 }
640 if ( ! empty( $value->transform ) ) {
641 $css .= " --ablocks-{$id}-transform: {$value->transform};\n";
642 }
643 if ( ! empty( $value->style ) ) {
644 $css .= " --ablocks-{$id}-style: {$value->style};\n";
645 }
646 if ( ! empty( $value->decoration ) ) {
647 $css .= " --ablocks-{$id}-decoration: {$value->decoration};\n";
648 }
649 if ( ! empty( $value->fontSize ) ) {
650 $unit = ! empty( $value->fontSizeUnit ) ? $value->fontSizeUnit : 'px';
651 $css .= " --ablocks-{$id}-font-size: {$value->fontSize}{$unit};\n";
652 }
653 if ( ! empty( $value->lineHeight ) ) {
654 $unit = ! empty( $value->lineHeightUnit ) ? $value->lineHeightUnit : 'px';
655 $css .= " --ablocks-{$id}-line-height: {$value->lineHeight}{$unit};\n";
656 }
657 if ( ! empty( $value->letterSpacing ) ) {
658 $unit = ! empty( $value->letterSpacingUnit ) ? $value->letterSpacingUnit : 'px';
659 $css .= " --ablocks-{$id}-letter-spacing: {$value->letterSpacing}{$unit};\n";
660 }
661 if ( ! empty( $value->wordSpacing ) ) {
662 $unit = ! empty( $value->wordSpacingUnit ) ? $value->wordSpacingUnit : 'px';
663 $css .= " --ablocks-{$id}-word-spacing: {$value->wordSpacing}{$unit};\n";
664 }
665
666 // Tablet values
667 if ( ! empty( $value->fontSizeTablet ) ) {
668 $unit = ! empty( $value->fontSizeUnitTablet ) ? $value->fontSizeUnitTablet : 'px';
669 $css .= " --ablocks-{$id}-font-size-tablet: {$value->fontSizeTablet}{$unit};\n";
670 }
671 if ( ! empty( $value->lineHeightTablet ) ) {
672 $unit = ! empty( $value->lineHeightUnitTablet ) ? $value->lineHeightUnitTablet : 'px';
673 $css .= " --ablocks-{$id}-line-height-tablet: {$value->lineHeightTablet}{$unit};\n";
674 }
675 if ( ! empty( $value->letterSpacingTablet ) ) {
676 $unit = ! empty( $value->letterSpacingUnitTablet ) ? $value->letterSpacingUnitTablet : 'px';
677 $css .= " --ablocks-{$id}-letter-spacing-tablet: {$value->letterSpacingTablet}{$unit};\n";
678 }
679 if ( ! empty( $value->wordSpacingTablet ) ) {
680 $unit = ! empty( $value->wordSpacingUnitTablet ) ? $value->wordSpacingUnitTablet : 'px';
681 $css .= " --ablocks-{$id}-word-spacing-tablet: {$value->wordSpacingTablet}{$unit};\n";
682 }
683
684 // Mobile values
685 if ( ! empty( $value->fontSizeMobile ) ) {
686 $unit = ! empty( $value->fontSizeUnitMobile ) ? $value->fontSizeUnitMobile : 'px';
687 $css .= " --ablocks-{$id}-font-size-mobile: {$value->fontSizeMobile}{$unit};\n";
688 }
689 if ( ! empty( $value->lineHeightMobile ) ) {
690 $unit = ! empty( $value->lineHeightUnitMobile ) ? $value->lineHeightUnitMobile : 'px';
691 $css .= " --ablocks-{$id}-line-height-mobile: {$value->lineHeightMobile}{$unit};\n";
692 }
693 if ( ! empty( $value->letterSpacingMobile ) ) {
694 $unit = ! empty( $value->letterSpacingUnitMobile ) ? $value->letterSpacingUnitMobile : 'px';
695 $css .= " --ablocks-{$id}-letter-spacing-mobile: {$value->letterSpacingMobile}{$unit};\n";
696 }
697 if ( ! empty( $value->wordSpacingMobile ) ) {
698 $unit = ! empty( $value->wordSpacingUnitMobile ) ? $value->wordSpacingUnitMobile : 'px';
699 $css .= " --ablocks-{$id}-word-spacing-mobile: {$value->wordSpacingMobile}{$unit};\n";
700 }
701 }//end if
702 }//end foreach
703
704 $css .= "}\n";
705 set_transient( 'ablocks_global_css_vars', $css, DAY_IN_SECONDS );
706 }
707
708 if ( ! is_admin() && ! Helper::is_gutenberg_editor() ) {
709 $css .= $this->get_common_css();
710 }
711 wp_add_inline_style( 'ablocks-editor-global-styles', $css );
712 wp_add_inline_style( 'ablocks-common-style', $css );
713 }
714
715 public function editor_google_fonts() {
716 // Load the fonts already used by the post being edited (plus globals) so
717 // existing content previews correctly on editor load. Live selections are
718 // handled client-side by the typography control.
719 $fonts = \ABlocks\Classes\FontCollector::get_global_fonts();
720
721 $post_id = 0;
722 if ( function_exists( 'get_the_ID' ) && get_the_ID() ) {
723 $post_id = (int) get_the_ID();
724 } elseif ( isset( $_GET['post'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
725 $post_id = absint( $_GET['post'] ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended
726 }
727 if ( $post_id ) {
728 $fonts = \ABlocks\Classes\FontCollector::merge( $fonts, \ABlocks\Classes\FontCollector::get_post_fonts( $post_id ) );
729 }
730
731 if ( empty( $fonts ) ) {
732 return;
733 }
734 $url = $this->build_google_fonts_url( $fonts );
735 wp_enqueue_style( 'ablocks-editor-google-fonts', $url, array(), null );
736 }
737
738 public function add_editor_inline_css() {
739 $custom_css = $this->get_common_css( '.editor-styles-wrapper ' );
740 add_theme_support( 'editor-styles' );
741 add_editor_style();
742 wp_add_inline_style( 'wp-block-library', $custom_css );
743 }
744
745 public function get_common_css( $parent_selector = '' ) {
746 global $ablocks_settings;
747 $attributes = [
748 'global_body_text_color' => $ablocks_settings->global_body_text_color,
749 'global_body_typography' => $ablocks_settings->global_body_typography,
750 'global_body_paragraph_space' => $ablocks_settings->global_body_paragraph_space,
751 'global_link_color' => $ablocks_settings->global_link_color,
752 'global_link_hover_color' => $ablocks_settings->global_link_hover_color,
753 'global_link_typography' => $ablocks_settings->global_link_typography,
754 'global_link_hover_typography' => $ablocks_settings->global_link_hover_typography,
755 'global_h1_color' => $ablocks_settings->global_h1_color,
756 'global_h1_typography' => $ablocks_settings->global_h1_typography,
757 'global_h2_color' => $ablocks_settings->global_h2_color,
758 'global_h2_typography' => $ablocks_settings->global_h2_typography,
759 'global_h3_color' => $ablocks_settings->global_h3_color,
760 'global_h3_typography' => $ablocks_settings->global_h3_typography,
761 'global_h4_color' => $ablocks_settings->global_h4_color,
762 'global_h4_typography' => $ablocks_settings->global_h4_typography,
763 'global_h5_color' => $ablocks_settings->global_h5_color,
764 'global_h5_typography' => $ablocks_settings->global_h5_typography,
765 'global_h6_color' => $ablocks_settings->global_h6_color,
766 'global_h6_typography' => $ablocks_settings->global_h6_typography,
767 ];
768 $css_generator = new GlobalCssGenerator( $attributes );
769
770 $css_generator->add_class_styles(
771 $parent_selector . 'body',
772 $css_generator->get_body_css( $attributes ),
773 $css_generator->get_body_css( $attributes, 'Tablet' ),
774 $css_generator->get_body_css( $attributes, 'Mobile' )
775 );
776 $css_generator->add_class_styles(
777 $parent_selector . 'p',
778 $css_generator->get_body_paragraph_css( $attributes ),
779 $css_generator->get_body_paragraph_css( $attributes, 'Tablet' ),
780 $css_generator->get_body_paragraph_css( $attributes, 'Mobile' )
781 );
782 $css_generator->add_class_styles(
783 $parent_selector . 'a',
784 $css_generator->get_body_anchor_css( $attributes ),
785 $css_generator->get_body_anchor_css( $attributes, 'Tablet' ),
786 $css_generator->get_body_anchor_css( $attributes, 'Mobile' )
787 );
788 $css_generator->add_class_styles(
789 $parent_selector . 'a:hover',
790 $css_generator->get_body_anchor_hover_css( $attributes ),
791 $css_generator->get_body_anchor_hover_css( $attributes, 'Tablet' ),
792 $css_generator->get_body_anchor_hover_css( $attributes, 'Mobile' )
793 );
794 $css_generator->add_class_styles(
795 $parent_selector . 'h1',
796 $css_generator->get_global_h1_css( $attributes ),
797 $css_generator->get_global_h1_css( $attributes, 'Tablet' ),
798 $css_generator->get_global_h1_css( $attributes, 'Mobile' )
799 );
800 $css_generator->add_class_styles(
801 $parent_selector . 'h2',
802 $css_generator->get_global_h2_css( $attributes ),
803 $css_generator->get_global_h2_css( $attributes, 'Tablet' ),
804 $css_generator->get_global_h2_css( $attributes, 'Mobile' )
805 );
806 $css_generator->add_class_styles(
807 $parent_selector . 'h3',
808 $css_generator->get_global_h3_css( $attributes ),
809 $css_generator->get_global_h3_css( $attributes, 'Tablet' ),
810 $css_generator->get_global_h3_css( $attributes, 'Mobile' )
811 );
812 $css_generator->add_class_styles(
813 $parent_selector . 'h4',
814 $css_generator->get_global_h4_css( $attributes ),
815 $css_generator->get_global_h4_css( $attributes, 'Tablet' ),
816 $css_generator->get_global_h4_css( $attributes, 'Mobile' )
817 );
818 $css_generator->add_class_styles(
819 $parent_selector . 'h5',
820 $css_generator->get_global_h5_css( $attributes ),
821 $css_generator->get_global_h5_css( $attributes, 'Tablet' ),
822 $css_generator->get_global_h5_css( $attributes, 'Mobile' )
823 );
824 $css_generator->add_class_styles(
825 $parent_selector . 'h6',
826 $css_generator->get_global_h6_css( $attributes ),
827 $css_generator->get_global_h6_css( $attributes, 'Tablet' ),
828 $css_generator->get_global_h6_css( $attributes, 'Mobile' )
829 );
830 return $css_generator->generate_css();
831 }
832
833
834 public function is_assets_generated() {
835 $file_name = $this->current_page_slug;
836 $css_file_path = $this->FileUpload->get_file_path( $file_name . '.min.css' );
837
838 if ( ! file_exists( $css_file_path ) ) {
839 return false;
840 }
841
842 // The file embeds the global-class CSS this page needs, so editing a
843 // class has to make every generated stylesheet stale. Comparing the
844 // file's mtime against the library's change stamp rebuilds them lazily,
845 // one page at a time on next visit, without stamping a revision into
846 // every file name (which the per-post delete in Blocks relies on).
847 //
848 // Strictly greater, not >=: mtime has one-second resolution, so a file
849 // written in the same second as a class edit is indistinguishable from
850 // one written just after it. Treating that tie as stale costs one extra
851 // regeneration; treating it as fresh would serve the old CSS until the
852 // next edit.
853 return filemtime( $css_file_path ) > max(
854 GlobalClasses::get_revision(),
855 self::build_revision()
856 );
857 }
858
859 /**
860 * When this plugin's own CSS last changed, as a timestamp.
861 *
862 * The generated file bakes in each block's static stylesheet (see
863 * AssetsGenerator, which concatenates get_static_css() into it), so a CSS
864 * fix shipped in an update reached nobody whose pages were generated before
865 * it: the file still existed, still parsed, and nothing about it looked
866 * stale, so it was served unchanged forever. Verified by planting a
867 * stylesheet carrying the previous release's rules — it survived every
868 * subsequent page load untouched. That is why a fix could land in the
869 * editor, which loads each block's style.css directly, and never appear on
870 * the front end.
871 *
872 * Keyed on the version rather than a file scan: it is one option read on
873 * the common path, and every shipped CSS change comes with a version bump.
874 * Each page then rebuilds once, on its next visit, exactly the way a
875 * global-class edit already makes them rebuild.
876 *
877 * @return int Timestamp of the running version's first request.
878 */
879 public static function build_revision() {
880 $stamp = get_option( self::BUILD_OPTION );
881
882 if (
883 is_array( $stamp ) &&
884 isset( $stamp['version'], $stamp['time'] ) &&
885 ABLOCKS_VERSION === $stamp['version']
886 ) {
887 return (int) $stamp['time'];
888 }
889
890 $now = time();
891 update_option(
892 self::BUILD_OPTION,
893 [
894 'version' => ABLOCKS_VERSION,
895 'time' => $now,
896 ],
897 true
898 );
899
900 return $now;
901 }
902
903 public function set_current_page_template_part( $content, $block ) {
904 if ( ! isset( $block['blockName'] ) && is_array( $block ) ) {
905 foreach ( $block as $block_item ) {
906 if ( ! empty( $block_item['blockName'] ) && strpos( $block_item['blockName'], 'ablocks/' ) !== false ) {
907 $this->current_page_blocks[] = $block_item;
908 }
909 }
910 }
911 if ( ! empty( $block['blockName'] ) && strpos( $block['blockName'], 'ablocks/' ) !== false ) {
912 $this->current_page_blocks[] = $block;
913 }
914 return $content;
915 }
916
917 public function set_theme_builder_locations( $args ) {
918 $this->theme_builder_locations = $args;
919 }
920 }
921