Skip to content

Commit

Permalink
rename event listener function and fix autohide on stream
Browse files Browse the repository at this point in the history
  • Loading branch information
dhasilva committed Jun 12, 2024
1 parent 43baaa6 commit 870a402
Showing 1 changed file with 21 additions and 5 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,11 @@ import type {
} from '../components/ai-assistant-toolbar-dropdown/dropdown-content';
import type { ExtendedInlineBlockProp } from '../extensions/ai-assistant';
import type { PromptTypeProp } from '../lib/prompt';
import type { PromptMessagesProp, PromptItemProps } from '@automattic/jetpack-ai-client';
import type {
PromptMessagesProp,
PromptItemProps,
RequestingStateProp,
} from '@automattic/jetpack-ai-client';

const debug = debugFactory( 'jetpack-ai-assistant:extensions:with-ai-extension' );

Expand Down Expand Up @@ -82,6 +86,8 @@ const blockEditWithAiComponents = createHigherOrderComponent( BlockEdit => {
const [ action, setAction ] = useState< string >( '' );
// The last request made by the user, to be used when the user clicks the "Try Again" button.
const lastRequest = useRef< RequestOptions | null >( null );
// Ref to the requesting state to use it in the hideOnBlockFocus effect.
const requestingStateRef = useRef< RequestingStateProp | null >( null );
// Data and functions from the editor.
const { undo } = useDispatch( 'core/editor' ) as CoreEditorDispatch;
const { postId } = useSelect( select => {
Expand Down Expand Up @@ -288,6 +294,11 @@ const blockEditWithAiComponents = createHigherOrderComponent( BlockEdit => {
},
} );

// Save the requesting state to use it in the hideOnBlockFocus effect.
useEffect( () => {
requestingStateRef.current = requestingState;
}, [ requestingState ] );

// Called when a suggestion from the toolbar is requested, like "Change tone".
const handleRequestSuggestion = useCallback< OnRequestSuggestion >(
( promptType, options, humanText ) => {
Expand Down Expand Up @@ -460,15 +471,20 @@ const blockEditWithAiComponents = createHigherOrderComponent( BlockEdit => {
if ( showAiControl ) {
const element = ownerDocument.current.getElementById( id );

const handleKeyDown = () => {
const handleFocusInBlock = () => {
// If the AI Control is requesting or suggesting, don't hide it, as the block focus is programmatic.
if ( [ 'requesting', 'suggesting' ].includes( requestingStateRef.current as string ) ) {
return;
}

setShowAiControl( false );
element?.removeEventListener( 'focusin', handleKeyDown );
element?.removeEventListener( 'focusin', handleFocusInBlock );
};

element?.addEventListener( 'focusin', handleKeyDown );
element?.addEventListener( 'focusin', handleFocusInBlock );

return () => {
element?.removeEventListener( 'focusin', handleKeyDown );
element?.removeEventListener( 'focusin', handleFocusInBlock );
};
}
}, [ hideOnBlockFocus, showAiControl, id ] );
Expand Down

0 comments on commit 870a402

Please sign in to comment.