plugin = $plugin; } /** * Registers the wp_dashboard_setup and admin_enqueue_scripts hooks. */ public function register(): void { add_action( 'wp_dashboard_setup', array( $this, 'maybe_add_widget' ) ); add_action( 'admin_enqueue_scripts', array( $this, 'maybe_enqueue' ) ); } /** * Adds the widget, only when the user can view reports and the plugin * is connected with a property. */ public function maybe_add_widget(): void { if ( ! $this->enabled() ) { return; } if ( ! function_exists( 'wp_add_dashboard_widget' ) ) { require_once ABSPATH . 'wp-admin/includes/dashboard.php'; } wp_add_dashboard_widget( self::ID, __( 'Tagsmith', 'tagsmith' ), array( $this, 'render' ) ); } /** * Renders the widget's React mount point. */ public function render(): void { echo '
'; } /** * Enqueues build/widget.js, only on the wp-admin Dashboard screen * (index.php) and only when the widget itself would be shown. * * @param string $hook_suffix The current admin page's hook suffix. */ public function maybe_enqueue( string $hook_suffix ): void { if ( 'index.php' !== $hook_suffix || ! $this->enabled() ) { return; } $this->enqueue(); } /** * Whether the widget should be registered/enqueued on this request. */ private function enabled(): bool { return current_user_can( Capabilities::VIEW ) && $this->plugin->connection()->is_connected() && '' !== (string) $this->plugin->settings()->get( 'property_id' ); } /** * Enqueues the widget bundle, its style and the inline tagsmithConfig. */ private function enqueue(): void { $handle = 'tagsmith-widget'; $asset_php = TAGSMITH_DIR . 'build/widget.asset.php'; if ( ! is_readable( $asset_php ) ) { return; } $asset = require $asset_php; wp_enqueue_script( $handle, TAGSMITH_URL . 'build/widget.js', (array) ( $asset['dependencies'] ?? array() ), (string) ( $asset['version'] ?? TAGSMITH_VERSION ), true ); wp_set_script_translations( $handle, 'tagsmith' ); wp_enqueue_style( 'wp-components' ); $css_path = TAGSMITH_DIR . 'build/widget.css'; if ( is_readable( $css_path ) ) { wp_enqueue_style( $handle, TAGSMITH_URL . 'build/widget.css', array( 'wp-components' ), (string) ( $asset['version'] ?? TAGSMITH_VERSION ) ); } wp_add_inline_script( $handle, // This is printed inside a script block: < > and & leave as \u escapes. 'window.tagsmithConfig = ' . wp_json_encode( $this->plugin->assets()->config(), JSON_HEX_TAG | JSON_HEX_AMP ) . ';', 'before' ); } }