register_shortcodes(); } /** * Register shortcodes */ private function register_shortcodes(): void { add_shortcode('ai_botkit_widget', [$this, 'render_widget']); } /** * Render chat widget * * @param array|string $atts Shortcode attributes ('' when there are none) * @return string The container, or '' when this request already printed one */ public function render_widget($atts = []): string { $args = shortcode_atts([ 'id' => '', ], $atts); return self::container(sanitize_text_field($args['id'])); } /** * Prints the page's placement winner, on wp_footer. Prints nothing once * this request has printed a container (see container()). */ public function render_sitewide_chatbot(): void { $winner = self::page_winner(); if (null === $winner) { return; } echo self::container($winner); // Escaped in container(). } /** * The agent placement shows on this request, or null. Decided once after * `wp` and kept for the rest of the request; shortcodes are not counted. */ public static function page_winner(): ?string { if (null !== self::$winner) { return self::$winner[0]; } $winner = Placement_Resolver::winner(Request_Context::current()); if (did_action('wp')) { self::$winner = [$winner]; } return $winner; } /** * The agent whose container this request has printed so far, or null. */ public static function printed_agent(): ?string { return self::$printed; } /** Forget this request's state. For tests. */ public static function reset_request(): void { self::$printed = null; self::$winner = null; } /** * The container for one agent, and embed.js. Empty when the agent is * empty (embed.js would mount nothing) or a container is already out. */ private static function container(string $chatbot_id): string { if ('' === $chatbot_id || null !== self::$printed) { return ''; } self::$printed = $chatbot_id; global $ai_botkit_url; wp_enqueue_script( 'ai-botkit-chatbot', $ai_botkit_url . '/embed.js', [], AI_BOTKIT_VERSION, false ); return sprintf( '
', esc_attr(self::CONTAINER_ID), esc_attr($chatbot_id) ); } }