Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions packages/components/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
- `Autocomplete`: Fix value comparison to avoid resetting block inserter in RTC ([#76980](https://github.com/WordPress/gutenberg/pull/76980)).
- `ValidatedRangeControl`: Fix `aria-label` rendered as `[object Object]` when `required` or `markWhenOptional` is set ([#77042](https://github.com/WordPress/gutenberg/pull/77042)).
- `Autocomplete`: Fix matching logic to prefer longest overlapping trigger ([#77018](https://github.com/WordPress/gutenberg/pull/77018)).
- `Autocomplete`: Skip stale triggers from completed mentions ([#77185](https://github.com/WordPress/gutenberg/pull/77185)).

### Enhancements

Expand Down
29 changes: 25 additions & 4 deletions packages/components/src/autocomplete/get-autocomplete-match.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,21 @@ type AutocompleteMatch = {
filterValue: string;
};

type AutocompleteMatchOptions = {
matchCount: number;
isBackspacing: boolean;
getTextAfterSelection: () => string;
lastCompletion?: { name: string; value: string } | null;
};

export function getAutocompleteMatch(
textContent: string,
completers: WPCompleter[],
filteredOptionsLength: number,
isBackspacing: boolean,
getTextAfterSelection: () => string
options: AutocompleteMatchOptions
): AutocompleteMatch | null {
const { matchCount, isBackspacing, getTextAfterSelection, lastCompletion } =
options;

if ( ! textContent ) {
return null;
}
Expand Down Expand Up @@ -58,6 +66,7 @@ export function getAutocompleteMatch(
}

const { allowContext, triggerPrefix } = completer;

const textWithoutTrigger = textContent.slice(
triggerIndex + triggerPrefix.length
);
Expand All @@ -71,7 +80,7 @@ export function getAutocompleteMatch(
return null;
}

const mismatch = filteredOptionsLength === 0;
const mismatch = matchCount === 0;
const wordsFromTrigger = textWithoutTrigger.split( /\s/ );

// Allow matching when typing a trigger + the match string or when
Expand Down Expand Up @@ -108,6 +117,18 @@ export function getAutocompleteMatch(
return null;
}

// After a completion whose value starts with the trigger prefix
// (e.g. @username), the trigger remains in the text and would
// re-activate the autocompleter. Suppress the match when the
// filter value still corresponds to the recently completed text.
if (
lastCompletion &&
lastCompletion.name === completer.name &&
textWithoutTrigger.trimEnd() === lastCompletion.value
) {
return null;
}

Comment on lines +120 to +131

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The current logic can create a dead end where lastCompletionRef persists indefinitely for any text starting with the previous completion, since it doesn't get cleared when the match is suppressed.

We should add a test to confirm this issue, and look for a solution. I can think of two ideas:

  • move the clearing logic before the getAutocompleteMatch call (checking if text has meaningfully changed beyond just the completion),
  • replace startsWith with a stricter equality-only check (with trailing-space tolerance?). The startsWith check seems designed to handle @username (with trailing space), but trimEnd() already handles that? startsWith may not be needed at all?

return {
completer,
filterValue: removeAccents( textWithoutTrigger ),
Expand Down
90 changes: 69 additions & 21 deletions packages/components/src/autocomplete/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -108,38 +108,64 @@ export function useAutocomplete( {
state;

const backspacingRef = useRef( false );
const prevRecordTextRef = useRef( '' );
const lastCompletionRef = useRef< {
name: string;
value: string;
} | null >( null );

function insertCompletion( replacement: React.ReactNode ) {
if ( autocompleter === null ) {
return;
return '';
}
const end = record.start;
const start =
end - autocompleter.triggerPrefix.length - filterValue.length;
const toInsert = create( { html: renderToString( replacement ) } );

onChange( insert( record, toInsert, start, end ) );
return getTextContent( toInsert );
}

function select( option: KeyedOption ) {
const { getOptionCompletion } = autocompleter || {};
if ( option.isDisabled || ! autocompleter ) {
return;
}

if ( option.isDisabled ) {
const { getOptionCompletion } = autocompleter;
if ( ! getOptionCompletion ) {
Comment thread
Mamaduka marked this conversation as resolved.
Resolved
dispatch( { type: 'RESET' } );
contentRef.current?.focus();
return;
}

if ( getOptionCompletion ) {
const completionObject = getCompletionObject(
getOptionCompletion( option.value, filterValue )
);
const completionObject = getCompletionObject(
getOptionCompletion( option.value, filterValue )
);

if ( 'replace' === completionObject.action ) {
onReplace( [ completionObject.value ] );
// When replacing, the component will unmount, so don't reset
// state (below) on an unmounted component.
return;
}

if ( 'replace' === completionObject.action ) {
onReplace( [ completionObject.value ] );
// When replacing, the component will unmount, so don't reset
// state (below) on an unmounted component.
return;
} else if ( 'insert-at-caret' === completionObject.action ) {
insertCompletion( completionObject.value );
if ( 'insert-at-caret' === completionObject.action ) {
const completionText = insertCompletion( completionObject.value );
// When the completion value starts with the trigger prefix
// (e.g. @username), the trigger stays in the text and would
// re-activate the autocompleter. Store the completed text so
// the effect can suppress the stale re-match.
if ( completionText.startsWith( autocompleter.triggerPrefix ) ) {
const afterPrefix = completionText.slice(
autocompleter.triggerPrefix.length
);
if ( afterPrefix ) {
lastCompletionRef.current = {
name: autocompleter.name,
value: afterPrefix,
};
}
}
}

Expand Down Expand Up @@ -222,6 +248,9 @@ export function useAutocomplete( {
}, [ record ] );

useEffect( () => {
const isTextChange = record.text !== prevRecordTextRef.current;
prevRecordTextRef.current = record.text;

function getTextAfterSelection() {
return textContent
? getTextContent(
Expand All @@ -234,13 +263,12 @@ export function useAutocomplete( {
: '';
}

const match = getAutocompleteMatch(
textContent,
completers,
filteredOptions.length,
backspacingRef.current,
getTextAfterSelection
);
const match = getAutocompleteMatch( textContent, completers, {
matchCount: filteredOptions.length,
isBackspacing: backspacingRef.current,
getTextAfterSelection,
lastCompletion: lastCompletionRef.current,
} );

if ( ! match ) {
if ( autocompleter ) {
Expand All @@ -251,6 +279,26 @@ export function useAutocomplete( {

const { completer, filterValue: query } = match;

// Don't re-activate a dismissed autocompleter on cursor-only
// movement. `textContent` (text before cursor) changes with the
// caret, so the effect re-runs, but `record.text` does not.
// Complements the render-time `didUserInput` gate in
// `useAutocompleteProps` for callers using this hook directly.
if ( ! autocompleter && ! isTextChange ) {
return;
}

// Clear stale completion ref when the user types a new trigger
// for the same completer (the previous completion is no longer
// relevant). Must be after the cursor-only check so that mere
// cursor movement doesn't discard the suppression state.
if (
lastCompletionRef.current &&
lastCompletionRef.current.name === completer.name
) {
lastCompletionRef.current = null;
}

dispatch( { type: 'MATCH', completer, query } );
// We want to avoid introducing unexpected side effects.
// See https://github.com/WordPress/gutenberg/pull/41820
Expand Down
Loading
Loading