*/ private static $contexts = []; /** * Stash a typed args array and get back a shortcode-safe token. * * @param array $args As accepted by Core\AIActions::render(). * @return string */ public static function push_context( array $args ) { $token = wp_unique_id( 'bd-ai-' ); self::$contexts[ $token ] = $args; return $token; } /** * Pop a stashed args array. Returns null when the token is unknown, so the * caller can tell "no context" from "context that happened to be empty". * * @param string $token * @return array|null */ private static function pull_context( $token ) { if ( ! isset( self::$contexts[ $token ] ) ) { return null; } $args = self::$contexts[ $token ]; unset( self::$contexts[ $token ] ); return $args; } public function get_name() { return 'betterdocs_ai_actions'; } public function get_style_depends() { return [ 'betterdocs-ai-actions' ]; } public function get_script_depends() { return [ 'betterdocs' ]; } public function default_attributes() { return [ 'enable' => true, 'post_id' => 0, 'actions' => '', 'button_label' => '', 'prompt_template' => '', 'context' => '' ]; } public function render( $atts, $content = null ) { if ( ! $this->isset( 'enable' ) ) { return; } $post_id = ! empty( $this->attributes['post_id'] ) ? (int) $this->attributes['post_id'] : get_the_ID(); if ( ! $post_id ) { return; } betterdocs()->ai_actions->render( $post_id, $this->render_args() ); } /** * Per-instance overrides for Core\AIActions::render(). * * @return array */ protected function render_args() { $context = '' !== (string) $this->attributes['context'] ? self::pull_context( (string) $this->attributes['context'] ) : null; if ( null !== $context ) { return $context; } $args = [ 'widget_type' => 'shortcode' ]; $enabled = $this->enabled_actions(); if ( null !== $enabled ) { $args['enabled_actions'] = $enabled; } // Blank means inherit, so an unset attribute is left out entirely rather // than passed as an empty string. foreach ( [ 'button_label', 'prompt_template' ] as $key ) { $value = (string) $this->attributes[ $key ]; if ( '' !== trim( $value ) ) { $args[ $key ] = $value; } } return $args; } /** * Turn the `actions` allow-list into the tri-state map render() expects. * * An author writing the shortcode by hand means "show exactly these", so a * non-empty list forces every known action on or off explicitly. An omitted * attribute returns null, leaving every action to its global setting. * * @return array|null */ protected function enabled_actions() { $list = trim( (string) $this->attributes['actions'] ); if ( '' === $list ) { return null; } $allowed = array_filter( array_map( 'trim', explode( ',', $list ) ) ); $enabled = []; foreach ( betterdocs()->ai_actions->catalog() as $action ) { $enabled[ $action['id'] ] = in_array( $action['id'], $allowed, true ); } return $enabled; } }