diff --git a/src/search-editor/hooks/useSuggestInput.ts b/src/search-editor/hooks/useSuggestInput.ts index ee15ec9..6f4369a 100644 --- a/src/search-editor/hooks/useSuggestInput.ts +++ b/src/search-editor/hooks/useSuggestInput.ts @@ -5,7 +5,11 @@ import { ProsemirrorNode } from 'remirror'; import { Fields } from '../types'; import { getLastTextNode, getTextFromNode } from '../utils/get-last-text-node'; import { remirrorToSearch } from '../utils/remirror-to-search'; -import { removeText } from '../utils/remove-text'; +import { + removeExtraSpaces, + removeTextFromEnd, + removeTextFromFront, +} from '../utils/remove-text'; export function useSuggestInput(props: { doc: ProsemirrorNode; @@ -17,14 +21,18 @@ export function useSuggestInput(props: { const prevSearchInput = usePrevious(searchInput); useEffect(() => { const lastNode = getLastTextNode(doc); - const lastNodeText = getTextFromNode(lastNode); - setSearchInput(lastNodeText); - const currentSearchTerm = remirrorToSearch({ doc, fields }); - setSearchedTerm( - lastNodeText - ? removeText(currentSearchTerm, lastNodeText) - : currentSearchTerm, + const lastNodeText = removeExtraSpaces(getTextFromNode(lastNode) ?? ''); + const currentSearchTerm = removeExtraSpaces( + remirrorToSearch({ doc, fields }), ); + const searched = lastNodeText + ? removeTextFromEnd(currentSearchTerm, lastNodeText) + : currentSearchTerm; + + const input = removeTextFromFront(lastNodeText, searched); + + setSearchInput(input); + setSearchedTerm(searched); }, [doc, fields]); return { diff --git a/src/search-editor/utils/remove-text.ts b/src/search-editor/utils/remove-text.ts index e527300..825e355 100644 --- a/src/search-editor/utils/remove-text.ts +++ b/src/search-editor/utils/remove-text.ts @@ -4,6 +4,17 @@ function escapeRegExp(text: string): string { return text.replace(SPECIAL_CHARACTERS_REGEX, '\\$&'); } -export function removeText(input: string, textToRemove: string): string { +export function removeExtraSpaces(input: string) { + return input.replace(/\s+/g, ' '); +} + +export function removeTextFromEnd(input: string, textToRemove: string): string { return input.replace(new RegExp(`${escapeRegExp(textToRemove)}$`), ''); } + +export function removeTextFromFront( + input: string, + textToRemove: string, +): string { + return input.replace(new RegExp(`^${escapeRegExp(textToRemove)}`), ''); +}