Skip to content

Commit

Permalink
Merge pull request #4 from Collaborne/fix/3394
Browse files Browse the repository at this point in the history
Fix spaces in search term and input
  • Loading branch information
sudhons authored Dec 11, 2024
2 parents 50dde50 + b998833 commit 56ea370
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 9 deletions.
24 changes: 16 additions & 8 deletions src/search-editor/hooks/useSuggestInput.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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 {
Expand Down
13 changes: 12 additions & 1 deletion src/search-editor/utils/remove-text.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)}`), '');
}

0 comments on commit 56ea370

Please sign in to comment.