PluginProbe
aBlocks – Gutenberg Blocks, User Dashboard Builder, Popup Builder, Form Builder & Animation Builder / 2.14.0
aBlocks – Gutenberg Blocks, User Dashboard Builder, Popup Builder, Form Builder & Animation Builder v2.14.0
2.14.0 2.13.0 2.13.1 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 All 81 releases
ablocks / includes / assets.php

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

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