Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix spaces in search term and input #4

Merged
merged 1 commit into from
Dec 11, 2024
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
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)}`), '');
}
Loading