register( 'rooster-one', __( 'Rooster One', 'ai-eshop-optimizer' ), $blocks, $args ); * * and each block becomes a widget named after it, "/" replaced by "-" (`aieo/toc` is `aieo-toc`): Elementor stores the * name in every page built with it, so it never changes. The widget's controls come from the block's attributes * (ControlMap, with the product's labels and rules), its option lists from the product's providers (Options), and its * output is the block's own render through WP_Block, with the page's post as context, so the widget prints exactly what * the block prints, escaped late (wp_kses() with \Rooster\Blocks\Kses::allowed(), or the product's own escaping printer). * * Elementor stays optional: without it, register() notes the product's blocks and adds no hook; with it, two callbacks * (the category, the widgets), and the widget class, which extends Elementor's own base class, is required only when * Elementor asks for the widgets. The package ships no Elementor code. * * @package RoosterBlocks */ namespace Rooster\Blocks\Elementor; use Rooster\Blocks\Tokens; defined( 'ABSPATH' ) || exit; /** * The registry of the products' blocks and Elementor's two callbacks. */ final class Factory { /** * A block's name, as core checks it (namespace/name, lowercase). */ public const BLOCK_NAME = '/^[a-z][a-z0-9-]*\/[a-z][a-z0-9-]*$/'; /** * Elementor's eicons for the dashicons blocks name most often (a block without an icon of its product's). */ public const DASHICONS = array( 'list-view' => 'eicon-bullet-list', 'slides' => 'eicon-slider-push', 'format-image' => 'eicon-image', 'grid-view' => 'eicon-gallery-grid', 'star-filled' => 'eicon-rating', 'cart' => 'eicon-cart', 'table-col-after' => 'eicon-table', 'admin-links' => 'eicon-link', 'heading' => 'eicon-heading', 'feedback' => 'eicon-form-horizontal', ); /** * The one factory of the process. * * @var Factory|null */ private static ?Factory $instance = null; /** * The registrations, in order: category, label, args (the product's rules), and their resolved labels. * * @var list, labels: array|null}> */ private array $registrations = array(); /** * The blocks: block name => its registration's index and its own options (eicon, tokens). * * @var array */ private array $blocks = array(); /** * The widget names: widget name => block name. * * @var array */ private array $widgets = array(); /** * Whether the two Elementor callbacks are hooked. * * @var bool */ private bool $hooked = false; /** * The factory of the process (the serving copy's). */ public static function instance(): self { if ( null === self::$instance ) { self::$instance = new self(); } return self::$instance; } /** * Registers a product's category and blocks. Call it from `init` (at 10 or earlier), once per product, or once per * add-on that brings blocks into its product's category. A block already registered, by this product or another, * keeps its first registration; a name that is not a block name is ignored. * * @param string $category The category's slug ('rooster-one', 'rooster-lms'). * @param string $label Its label in Elementor's panel (translated by the product). * @param array $blocks The blocks: full names ('aieo/toc'), or name => options: `eicon` * (Elementor's icon of its widget), `tokens` (true: the widget loads the * token sheet with the block's). * @param array $args The product's rules (docs/CONTRACT.md section 11): id, eicon, keywords, * labels, groups, skip, describe, sections, sources, max, strings, json, * domain, fallback, styles, scripts, style, controls, print. * @return list The widget names of the blocks this call registered. */ public function register( string $category, string $label, array $blocks, array $args = array() ): array { if ( 1 !== preg_match( '/^[a-z0-9-]+$/', $category ) ) { return array(); } $index = count( $this->registrations ); $this->registrations[] = array( 'category' => $category, 'label' => $label, 'args' => $args, 'labels' => null, ); $names = array(); foreach ( $blocks as $key => $value ) { $block = is_string( $key ) ? $key : ( is_string( $value ) ? $value : '' ); $options = is_string( $key ) && is_array( $value ) ? $value : array(); if ( 1 !== preg_match( self::BLOCK_NAME, $block ) || isset( $this->blocks[ $block ] ) ) { continue; } $this->blocks[ $block ] = array( 'registration' => $index, 'eicon' => is_string( $options['eicon'] ?? null ) ? $options['eicon'] : '', 'tokens' => ! empty( $options['tokens'] ), ); $this->widgets[ self::widget_name( $block ) ] = $block; $names[] = self::widget_name( $block ); } if ( ! $this->hooked && did_action( 'elementor/loaded' ) ) { $this->hooked = true; add_action( 'elementor/elements/categories_registered', array( $this, 'categories' ) ); add_action( 'elementor/widgets/register', array( $this, 'widgets' ), 20 ); // after the products' own widgets } return $names; } /** * A block's widget name: its name with "/" replaced by "-". Released names never change. * * @param string $block Block name ('aieo/toc'). */ public static function widget_name( string $block ): string { return str_replace( '/', '-', $block ); } /** * The block of a widget name ('' when the factory has none). * * @param string $widget Widget name. */ public function block_of( string $widget ): string { return $this->widgets[ $widget ] ?? ''; } /** * The registered blocks, in order: block name => widget name. * * @return array */ public function blocks(): array { $out = array(); foreach ( array_keys( $this->blocks ) as $block ) { $out[ $block ] = self::widget_name( $block ); } return $out; } /** * Whether the two Elementor callbacks are hooked (only once Elementor has loaded). */ public function hooked(): bool { return $this->hooked; } /** * Forgets every registration and unhooks (the tests' fresh start; a product never calls it). */ public function reset(): void { if ( $this->hooked ) { remove_action( 'elementor/elements/categories_registered', array( $this, 'categories' ) ); remove_action( 'elementor/widgets/register', array( $this, 'widgets' ), 20 ); } $this->registrations = array(); $this->blocks = array(); $this->widgets = array(); $this->hooked = false; } /** * Elementor's elements manager: each registration's category, once. * * @param mixed $manager Elementor's elements manager. */ public function categories( $manager ): void { if ( ! is_object( $manager ) || ! method_exists( $manager, 'add_category' ) ) { return; } $have = method_exists( $manager, 'get_categories' ) ? (array) $manager->get_categories() : array(); foreach ( $this->registrations as $registration ) { if ( isset( $have[ $registration['category'] ] ) ) { continue; } $manager->add_category( $registration['category'], array( 'title' => $registration['label'], 'icon' => 'eicon-folder', ) ); $have[ $registration['category'] ] = true; } } /** * Elementor's widgets manager: one widget per registered block whose block exists (a registered type, or its * block.json found through the product's `json`). A name another widget already holds (a product's own, released * outside the factory) is left to it. The widget class is required here, never earlier. * * @param mixed $manager Elementor's widgets manager. */ public function widgets( $manager ): void { if ( ! is_object( $manager ) || ! method_exists( $manager, 'register' ) || ! self::elementor() ) { return; } foreach ( array_keys( $this->blocks ) as $block ) { $name = self::widget_name( $block ); if ( ! $this->exists( $block ) || ( method_exists( $manager, 'get_widget_types' ) && null !== $manager->get_widget_types( $name ) ) ) { continue; } $manager->register( new Widget( array(), array( Widget::ARG => $block ) ) ); } } /** * Requires the classes that extend or call Elementor's (Controls, Widget) when Elementor's widget base exists; a * product's own widgets may call it to use Controls. False without Elementor. */ public static function elementor(): bool { if ( ! class_exists( '\Elementor\Widget_Base' ) ) { return false; } require_once __DIR__ . '/Controls.php'; require_once __DIR__ . '/Widget.php'; return class_exists( Widget::class, false ); } /** * Whether the factory has the block. * * @param string $block Block name. */ public function has( string $block ): bool { return isset( $this->blocks[ $block ] ); } /** * Whether the block exists: a registered type, or its block.json. * * @param string $block Block name. */ public function exists( string $block ): bool { return self::registered( $block ) || '' !== $this->json( $block ); } /** * Whether the block type is registered. * * @param string $block Block name. */ public static function registered( string $block ): bool { return \WP_Block_Type_Registry::get_instance()->is_registered( $block ); } /** * The block's block.json, through the product's `json` ('' when it gives none or the file is missing). * * @param string $block Block name. */ private function json( string $block ): string { $json = $this->arg( $block, 'json' ); $file = is_callable( $json ) ? (string) call_user_func( $json, $block ) : ''; return '' !== $file && is_file( $file ) ? $file : ''; } /** * One of the block's registration's arguments (null when absent). * * @param string $block Block name. * @param string $name Argument. * @return mixed */ public function arg( string $block, string $name ) { $index = $this->blocks[ $block ]['registration'] ?? null; return null === $index ? null : ( $this->registrations[ $index ]['args'][ $name ] ?? null ); } /** * The block's category. * * @param string $block Block name. */ public function category( string $block ): string { $index = $this->blocks[ $block ]['registration'] ?? null; return null === $index ? '' : $this->registrations[ $index ]['category']; } /** * The prefix of the widget's section and note ids (the product's `id`, else its category with "_" for "-"). * * @param string $block Block name. */ public function id( string $block ): string { $id = $this->arg( $block, 'id' ); return is_string( $id ) && '' !== $id ? $id : str_replace( '-', '_', $this->category( $block ) ); } /** * The block's metadata: title, keywords, icon (block.json's), attributes, style and script handles; from the * registered type, else from its block.json (translated with the product's `domain`). * * @param string $block Block name. * @return array{title: string, keywords: list, icon: string, attributes: array, styles: list, scripts: list} */ public function meta( string $block ): array { $type = \WP_Block_Type_Registry::get_instance()->get_registered( $block ); if ( $type instanceof \WP_Block_Type ) { return array( 'title' => (string) $type->title, 'keywords' => array_values( array_map( 'strval', (array) $type->keywords ) ), 'icon' => is_string( $type->icon ) ? $type->icon : '', 'attributes' => is_array( $type->attributes ) ? $type->attributes : array(), 'styles' => array_values( array_map( 'strval', array_merge( (array) $type->style_handles, (array) $type->view_style_handles ) ) ), 'scripts' => array_values( array_map( 'strval', (array) $type->view_script_handles ) ), ); } $file = $this->json( $block ); $json = '' !== $file ? wp_json_file_decode( $file, array( 'associative' => true ) ) : null; $json = is_array( $json ) ? $json : array(); $domain = $this->arg( $block, 'domain' ); if ( is_string( $domain ) && '' !== $domain && array() !== $json ) { $json = (array) translate_settings_using_i18n_schema( get_block_metadata_i18n_schema(), $json, $domain ); } return array( 'title' => isset( $json['title'] ) ? (string) $json['title'] : '', 'keywords' => array_values( array_map( 'strval', (array) ( $json['keywords'] ?? array() ) ) ), 'icon' => is_string( $json['icon'] ?? null ) ? $json['icon'] : '', 'attributes' => is_array( $json['attributes'] ?? null ) ? $json['attributes'] : array(), 'styles' => array(), 'scripts' => array(), ); } /** * The widget's title: the block's, else its short name. * * @param string $block Block name. */ public function title( string $block ): string { $title = $this->meta( $block )['title']; return '' !== $title ? $title : ControlMap::short( $block ); } /** * The widget's eicon: the block's own option, else block.json's dashicon mapped, else the product's, else eicon-apps. * * @param string $block Block name. */ public function icon( string $block ): string { $own = $this->blocks[ $block ]['eicon'] ?? ''; if ( '' !== $own ) { return $own; } $dash = $this->meta( $block )['icon']; if ( isset( self::DASHICONS[ $dash ] ) ) { return self::DASHICONS[ $dash ]; } $icon = $this->arg( $block, 'eicon' ); return is_string( $icon ) && '' !== $icon ? $icon : 'eicon-apps'; } /** * The widget's keywords: the product's, then the block's. * * @param string $block Block name. * @return list */ public function keywords( string $block ): array { return array_values( array_unique( array_merge( array_map( 'strval', (array) $this->arg( $block, 'keywords' ) ), $this->meta( $block )['keywords'] ) ) ); } /** * The style handles the widget declares: the block's (style, viewStyle), the token sheet first when the block reads * the tokens, then the product's `styles` (callable( block, handles ): handles) decides. * * @param string $block Block name. * @return list */ public function styles( string $block ): array { $handles = $this->meta( $block )['styles']; if ( ! empty( $this->blocks[ $block ]['tokens'] ) && Tokens::register() ) { array_unshift( $handles, Tokens::HANDLE ); } $styles = $this->arg( $block, 'styles' ); if ( is_callable( $styles ) ) { $handles = (array) call_user_func( $styles, $block, $handles ); } return array_values( array_unique( array_map( 'strval', $handles ) ) ); } /** * The script handles the widget declares: the block's view scripts, then the product's `scripts` decides. * * @param string $block Block name. * @return list */ public function scripts( string $block ): array { $handles = $this->meta( $block )['scripts']; $scripts = $this->arg( $block, 'scripts' ); if ( is_callable( $scripts ) ) { $handles = (array) call_user_func( $scripts, $block, $handles ); } return array_values( array_unique( array_map( 'strval', $handles ) ) ); } /** * The rules ControlMap reads for a block: the product's labels (its callable called once per request), groups, * skip list and describe hook. * * @param string $block Block name. * @return array */ public function rules( string $block ): array { $index = $this->blocks[ $block ]['registration'] ?? null; if ( null === $index ) { return array(); } $args = $this->registrations[ $index ]['args']; if ( null === $this->registrations[ $index ]['labels'] ) { $labels = $args['labels'] ?? array(); $labels = is_callable( $labels ) ? call_user_func( $labels ) : $labels; $this->registrations[ $index ]['labels'] = is_array( $labels ) ? $labels : array(); } return array( 'labels' => $this->registrations[ $index ]['labels'], 'groups' => (array) ( $args['groups'] ?? array() ), 'skip' => (array) ( $args['skip'] ?? array() ), 'describe' => $args['describe'] ?? null, ); } /** * The block's control descriptions. * * @param string $block Block name. * @return list> */ public function controls( string $block ): array { return ControlMap::controls( $block, $this->meta( $block )['attributes'], $this->rules( $block ) ); } /** * The block's sections: the product's `sections` (an array, or callable( block ): array; key => label), else one, * "Settings". * * @param string $block Block name. * @return array */ public function sections( string $block ): array { $sections = $this->arg( $block, 'sections' ); if ( is_callable( $sections ) ) { $sections = call_user_func( $sections, $block ); } $sections = is_array( $sections ) ? array_map( 'strval', $sections ) : array(); return array() !== $sections ? $sections : array( 'settings' => $this->strings( $block )['settings'] ); } /** * The factory's words for a block's widget: the package's, each replaceable by the product's `strings` (an array or a * callable), so a product's panel speaks its own catalogue. * * @param string $block Block name. * @return array */ public function strings( string $block ): array { $own = $this->arg( $block, 'strings' ); $own = is_callable( $own ) ? call_user_func( $own ) : $own; return array_merge( array( 'settings' => __( 'Settings', 'ai-eshop-optimizer' ), 'style' => __( 'Style', 'ai-eshop-optimizer' ), 'note' => __( 'This widget has no settings: it shows what the page and the viewer call for.', 'ai-eshop-optimizer' ), 'ids' => __( 'IDs, comma-separated.', 'ai-eshop-optimizer' ), 'current' => __( 'The current one', 'ai-eshop-optimizer' ), 'from_page' => __( 'From the page', 'ai-eshop-optimizer' ), /* translators: %d: post ID */ 'untitled' => __( '(no title) #%d', 'ai-eshop-optimizer' ), ), is_array( $own ) ? array_map( 'strval', $own ) : array() ); } /** * A select2 control's options (the editor only: a front-end render needs none): the control's own, the product's * provider of its source, or the package's posts and terms. Null above the list limit. * * @param string $block Block name. * @param array $control The control. * @return array|null */ public function options( string $block, array $control ): ?array { if ( ! self::editing() && ! isset( $control['options'] ) ) { return array(); } $max = $this->arg( $block, 'max' ); return Options::for_control( $control, (array) ( $this->arg( $block, 'sources' ) ?? array() ), is_int( $max ) && $max > 0 ? $max : ControlMap::MAX_ITEMS, $this->strings( $block ) ); } /** * Whether the controls are built for the editor (the select2 lists are needed). */ public static function editing(): bool { return is_admin() || wp_doing_ajax(); } /** * The block's attributes for a widget's settings (sanitised). * * @param string $block Block name. * @param array $settings The widget's settings for display. * @return array */ public function attrs( string $block, array $settings ): array { return ControlMap::attrs( $block, $this->meta( $block )['attributes'], $settings, $this->rules( $block ) ); } /** * The block's markup for a widget's settings: WP_Block with the page's post as context (the same render callback, * render_block filters, assets and directives as the block); the product's `fallback` while the type is not * registered, else ''. A block that reads the tokens gets the sheet here too (a render after the head: the editor). * * @param string $block Block name. * @param array $settings The widget's settings for display. */ public function markup( string $block, array $settings ): string { $attrs = $this->attrs( $block, $settings ); if ( self::registered( $block ) ) { $wp_block = new \WP_Block( array( 'blockName' => $block, 'attrs' => $attrs, 'innerHTML' => '', 'innerContent' => array(), 'innerBlocks' => array(), ), array( 'postId' => (int) get_the_ID(), 'postType' => (string) get_post_type(), ) ); $html = (string) $wp_block->render(); } else { $fallback = $this->arg( $block, 'fallback' ); $html = is_callable( $fallback ) ? (string) call_user_func( $fallback, $block, $attrs ) : ''; } if ( '' !== $html && ! empty( $this->blocks[ $block ]['tokens'] ) ) { Tokens::enqueue(); } return $html; } /** * Whether a post built with Elementor holds a widget of one of these blocks (its saved `_elementor_data`): the * Elementor counterpart of has_block(), for a product that loads a block's sheets before the page renders. One read * of the post's meta (primed for the queried post); false for a post Elementor does not build. * * @param \WP_Post|int|null $post The post (null: the current one). * @param list $blocks Block names. */ public static function post_has( $post, array $blocks ): bool { $post = get_post( $post ); if ( ! $post instanceof \WP_Post || 'builder' !== get_post_meta( $post->ID, '_elementor_edit_mode', true ) ) { return false; } $data = get_post_meta( $post->ID, '_elementor_data', true ); if ( ! is_string( $data ) || '' === $data ) { return false; } foreach ( $blocks as $block ) { if ( str_contains( $data, '"widgetType":"' . self::widget_name( (string) $block ) . '"' ) ) { return true; } } return false; } }