Skip to content

Commit

Permalink
Desensitize hiding the autocomplete results on scroll. (datacommonsor…
Browse files Browse the repository at this point in the history
…g#4731)

Only hides the autocomplete results after 15% of window width has been
scrolled through.

https://screencast.googleplex.com/cast/NjMyMDgzNjY5MTYyMzkzNnxmNjAxODU2Yy0xZQ
  • Loading branch information
gmechali authored Nov 13, 2024
1 parent 8b7bdf7 commit bbd38ec
Showing 1 changed file with 20 additions and 4 deletions.
24 changes: 20 additions & 4 deletions static/js/components/nl_search_bar/auto_complete_input.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -79,23 +79,38 @@ export function AutoCompleteInput(
const [inputActive, setInputActive] = useState(false);
const [lastAutoCompleteSelection, setLastAutoCompleteSelection] =
useState("");
// Used to reduce sensitivity to scrolling for autocomplete result dismissal.
// Tracks the last scrollY value at time of autocomplete request.
const [lastScrollYOnTrigger, setLastScrollYOnTrigger] = useState(0);
// Tracks the last scrollY value for current height offsett.
const [lastScrollY, setLastScrollY] = useState(0);

const isHeaderBar = props.barType == "header";
let lang = "";

useEffect(() => {
// One time initialization of event listener to clear suggested results on scroll.
// It allows the user to navigate through the page without being annoyed by the results.
window.addEventListener("scroll", () => {
if (results.placeResults) {
setResults({ placeResults: [], svResults: [] });
}
setLastScrollY(window.scrollY);
});

const urlParams = new URLSearchParams(window.location.search);
lang = urlParams.has("hl") ? urlParams.get("hl") : "en";
}, []);

// Whenever any of the scrollY states change, recompute to see if we need to hide the results.
// We only hide the results when the user has scrolled past 15% of the window height since the autocomplete request.
// It allows the user to navigate through the page without being annoyed by the results,
// and to scroll through the results without them disappearing.
useEffect(() => {
if (
results.placeResults.length > 0 &&
Math.abs(lastScrollY - lastScrollYOnTrigger) > window.outerHeight * 0.15
) {
setResults({ placeResults: [], svResults: [] });
}
}, [lastScrollY, lastScrollYOnTrigger]);

useEffect(() => {
// For the first load when q= param is set, we want to ensure the
// props.value is propagated if it doesn't match input text.
Expand Down Expand Up @@ -172,6 +187,7 @@ export function AutoCompleteInput(
}

const triggerAutoCompleteRequest = useCallback(async (query: string) => {
setLastScrollYOnTrigger(window.scrollY);
await axios
.get(`/api/autocomplete?query=${query}&hl=${lang}`, {})
.then((response) => {
Expand Down

0 comments on commit bbd38ec

Please sign in to comment.