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 debounce #4349

Merged
merged 8 commits into from
Jul 16, 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
130 changes: 78 additions & 52 deletions assets/js/dashboard/components/combobox.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import React, { Fragment, useState, useCallback, useEffect, useRef } from 'react'
import { Transition } from '@headlessui/react'
import { ChevronDownIcon } from '@heroicons/react/20/solid'
import debounce from 'debounce-promise'
import classNames from 'classnames'
import { useMountedEffect, useDebounce } from '../custom-hooks'

function Option({isHighlighted, onClick, onMouseEnter, text, id}) {
const className = classNames('relative cursor-pointer select-none py-2 px-3', {
Expand Down Expand Up @@ -35,23 +35,64 @@ function optionId(index) {
return `plausible-combobox-option-${index}`
}

export default function PlausibleCombobox(props) {
export default function PlausibleCombobox({
values,
fetchOptions,
singleOption,
isDisabled,
autoFocus,
freeChoice,
disabledOptions,
onSelect,
placeholder,
forceLoading,
className,
boxClass,
}) {
const isEmpty = values.length === 0
const [options, setOptions] = useState([])
const [isLoading, setLoading] = useState(false)
const [isOpen, setOpen] = useState(false)
const [input, setInput] = useState('')
const [search, setSearch] = useState('')
const [highlightedIndex, setHighlightedIndex] = useState(0)
const searchRef = useRef(null)
const containerRef = useRef(null)
const listRef = useRef(null)

const loading = isLoading || !!props.forceLoading
const loading = isLoading || !!forceLoading

const visibleOptions = [...options]
if (props.freeChoice && input.length > 0 && options.every(option => option.value !== input)) {
visibleOptions.push({value: input, label: input, freeChoice: true})
if (freeChoice && search.length > 0 && options.every(option => option.value !== search)) {
visibleOptions.push({value: search, label: search, freeChoice: true})
}

const afterFetchOptions = useCallback((loadedOptions) => {
setLoading(false)
setHighlightedIndex(0)
setOptions(loadedOptions)
}, [])

const initialFetchOptions = useCallback(() => {
fetchOptions('').then(afterFetchOptions)
}, [fetchOptions, afterFetchOptions])

const searchOptions = useCallback(() => {
if (isOpen) {
setLoading(true)
fetchOptions(search).then(afterFetchOptions)
}
}, [search, isOpen, fetchOptions, afterFetchOptions])

const debouncedSearchOptions = useDebounce(searchOptions)

useEffect(() => {
if (isOpen) { initialFetchOptions() }
}, [isOpen, initialFetchOptions])

useMountedEffect(() => {
debouncedSearchOptions()
}, [search])

function highLight(index) {
let newIndex = index

Expand Down Expand Up @@ -94,98 +135,83 @@ export default function PlausibleCombobox(props) {
}

function isOptionDisabled(option) {
const optionAlreadySelected = props.values.some((val) => val.value === option.value)
const optionDisabled = (props.disabledOptions || []).some((val) => val?.value === option.value)
const optionAlreadySelected = values.some((val) => val.value === option.value)
const optionDisabled = (disabledOptions || []).some((val) => val?.value === option.value)
return optionAlreadySelected || optionDisabled
}

function fetchOptions(query) {
setLoading(true)
setOpen(true)

return props.fetchOptions(query).then((loadedOptions) => {
setLoading(false)
setHighlightedIndex(0)
setOptions(loadedOptions)
})
}

const debouncedFetchOptions = useCallback(debounce(fetchOptions, 200), [fetchOptions])

function onInput(e) {
const newInput = e.target.value
setInput(newInput)
debouncedFetchOptions(newInput)
if (!isOpen) { setOpen(true) }
setSearch(e.target.value)
}

function toggleOpen() {
if (!isOpen) {
fetchOptions(input)
setOpen(true)
searchRef.current.focus()
} else {
setInput('')
setSearch('')
setOpen(false)
}
}

function selectOption(option) {
if (props.singleOption) {
props.onSelect([option])
if (singleOption) {
onSelect([option])
} else {
searchRef.current.focus()
props.onSelect([...props.values, option])
onSelect([...values, option])
}

setOpen(false)
setInput('')
setSearch('')
}

function removeOption(option, e) {
e.stopPropagation()
const newValues = props.values.filter((val) => val.value !== option.value)
props.onSelect(newValues)
const newValues = values.filter((val) => val.value !== option.value)
onSelect(newValues)
searchRef.current.focus()
setOpen(false)
}

const handleClick = useCallback((e) => {
if (containerRef.current && containerRef.current.contains(e.target)) { return }

setInput('')
setSearch('')
setOpen(false)
})
}, [])

useEffect(() => {
document.addEventListener("mousedown", handleClick, false)
return () => { document.removeEventListener("mousedown", handleClick, false) }
}, [])
}, [handleClick])

useEffect(() => {
if (props.singleOption && props.values.length === 0 && props.autoFocus) {
if (singleOption && isEmpty && autoFocus) {
searchRef.current.focus()
}
}, [props.values.length === 0, props.singleOption, props.autoFocus])
}, [isEmpty, singleOption, autoFocus])

const searchBoxClass = 'border-none py-1 px-0 w-full inline-block rounded-md focus:outline-none focus:ring-0 text-sm'

const containerClass = classNames('relative w-full', {
[props.className]: !!props.className,
'opacity-30 cursor-default pointer-events-none': props.isDisabled
[className]: !!className,
'opacity-30 cursor-default pointer-events-none': isDisabled
})

function renderSingleOptionContent() {
const itemSelected = props.values.length === 1
const placeholder = itemSelected ? '' : props.placeholder
const itemSelected = values.length === 1

return (
<div className='flex items-center truncate'>
{ itemSelected && renderSingleSelectedItem() }
<input
className={searchBoxClass}
ref={searchRef}
value={input}
value={search}
style={{backgroundColor: "inherit"}}
placeholder={placeholder}
placeholder={itemSelected ? '' : placeholder}
type="text"
onChange={onInput}>
</input>
Expand All @@ -194,10 +220,10 @@ export default function PlausibleCombobox(props) {
}

function renderSingleSelectedItem() {
if (input === '') {
if (search === '') {
return (
<span className="dark:text-gray-300 text-sm w-0">
{props.values[0].label}
{values[0].label}
</span>
)
}
Expand All @@ -206,7 +232,7 @@ export default function PlausibleCombobox(props) {
function renderMultiOptionContent() {
return (
<>
{ props.values.map((value) => {
{ values.map((value) => {
return (
<div key={value.value} className="bg-indigo-100 dark:bg-indigo-600 flex justify-between w-full rounded-sm px-2 py-0.5 m-0.5 text-sm">
<span className='break-all'>{value.label}</span>
Expand All @@ -215,7 +241,7 @@ export default function PlausibleCombobox(props) {
)
})
}
<input className={searchBoxClass} ref={searchRef} value={input} style={{backgroundColor: "inherit"}} placeholder={props.placeholder} type="text" onChange={onInput}></input>
<input className={searchBoxClass} ref={searchRef} value={search} style={{backgroundColor: "inherit"}} placeholder={placeholder} type="text" onChange={onInput}></input>
</>
)
}
Expand Down Expand Up @@ -246,7 +272,7 @@ export default function PlausibleCombobox(props) {
})
}

if (props.freeChoice) {
if (freeChoice) {
return <div className="relative cursor-default select-none py-2 px-4 text-gray-700 dark:text-gray-300">Start typing to apply filter</div>
}

Expand All @@ -258,15 +284,15 @@ export default function PlausibleCombobox(props) {
}

const defaultBoxClass = 'pl-2 pr-8 py-1 w-full dark:bg-gray-900 dark:text-gray-300 rounded-md shadow-sm border border-gray-300 dark:border-gray-700 focus-within:border-indigo-500 focus-within:ring-1 focus-within:ring-indigo-500'
const boxClass = classNames(props.boxClass || defaultBoxClass, {
const finalBoxClass = classNames(boxClass || defaultBoxClass, {
'border-indigo-500 ring-1 ring-indigo-500': isOpen,
})

return (
<div onKeyDown={onKeyDown} ref={containerRef} className={containerClass}>
<div onClick={toggleOpen} className={boxClass }>
{props.singleOption && renderSingleOptionContent()}
{!props.singleOption && renderMultiOptionContent()}
<div onClick={toggleOpen} className={finalBoxClass }>
{singleOption && renderSingleOptionContent()}
{!singleOption && renderMultiOptionContent()}
<div className="cursor-pointer absolute inset-y-0 right-0 flex items-center pr-2">
{!loading && <ChevronDownIcon className="h-4 w-4 text-gray-500" />}
{loading && <Spinner />}
Expand Down
27 changes: 18 additions & 9 deletions assets/js/dashboard/custom-hooks.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useCallback, useEffect, useRef } from 'react';
import { useEffect, useRef, useCallback } from 'react';

// A custom hook that behaves like `useEffect`, but
// the function does not run on the initial render.
Expand All @@ -11,17 +11,26 @@ export function useMountedEffect(fn, deps) {
} else {
mounted.current = true
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, deps)
}

// A custom hook that debounces the function calls by
// a given delay. Cancels all function calls that have
// a following call within `delay_ms`.
export function useDebouncedEffect(fn, deps, delay_ms) {
const callback = useCallback(fn, deps)
const DEBOUNCE_DELAY = 300

export function useDebounce(fn, delay = DEBOUNCE_DELAY) {
const timerRef = useRef(null)

useEffect(() => {
const timeout = setTimeout(callback, delay_ms)
return () => clearTimeout(timeout)
}, [callback, delay_ms])
return () => {
if (timerRef.current) { clearTimeout(timerRef.current) }
}
}, [])

return useCallback((...args) => {
clearTimeout(timerRef.current)

timerRef.current = setTimeout(() => {
fn(...args)
}, delay)
}, [fn, delay])
}
24 changes: 13 additions & 11 deletions assets/js/dashboard/stats/modals/breakdown-modal.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import React, { useState, useEffect, useCallback, useRef } from "react";

import * as api from '../../api';
import { useDebouncedEffect, useMountedEffect } from '../../custom-hooks';
import { trimURL } from '../../util/url';
import * as api from '../../api'
import { useMountedEffect, useDebounce } from '../../custom-hooks'
import { trimURL } from '../../util/url'
import { FilterLink } from "../reports/list";
import { useQueryContext } from "../../query-context";
import { useSiteContext } from "../../site-context";
Expand Down Expand Up @@ -91,20 +91,17 @@ export default function BreakdownModal({

const [initialLoading, setInitialLoading] = useState(true)
const [loading, setLoading] = useState(true)
const [searchInput, setSearchInput] = useState('')
const [search, setSearch] = useState('')
const [results, setResults] = useState([])
const [page, setPage] = useState(1)
const [moreResultsAvailable, setMoreResultsAvailable] = useState(false)
const searchBoxRef = useRef(null)

useMountedEffect(() => { fetchNextPage() }, [page])
useEffect(() => { fetchData() }, [])

useDebouncedEffect(() => {
setSearch(searchInput)
}, [searchInput], 300)

useEffect(() => { fetchData() }, [search])
useMountedEffect(() => { debouncedFetchData() }, [search])

useMountedEffect(() => { fetchNextPage() }, [page])

useEffect(() => {
if (!searchEnabled) { return }
Expand All @@ -127,6 +124,7 @@ export default function BreakdownModal({

const fetchData = useCallback(() => {
setLoading(true)

api.get(endpoint, withSearch(query), { limit: LIMIT, page: 1, detailed: true })
.then((response) => {
if (typeof afterFetchData === 'function') {
Expand All @@ -140,7 +138,11 @@ export default function BreakdownModal({
})
}, [search])

const debouncedFetchData = useDebounce(fetchData)

function fetchNextPage() {
setLoading(true)

if (page > 1) {
api.get(endpoint, withSearch(query), { limit: LIMIT, page, detailed: true })
.then((response) => {
Expand Down Expand Up @@ -236,7 +238,7 @@ export default function BreakdownModal({
}

function handleInputChange(e) {
setSearchInput(e.target.value)
setSearch(e.target.value)
}

function renderSearchInput() {
Expand Down
5 changes: 0 additions & 5 deletions assets/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 0 additions & 1 deletion assets/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@
"classnames": "^2.3.1",
"datamaps": "^0.5.9",
"dayjs": "^1.11.7",
"debounce-promise": "^3.1.2",
"iframe-resizer": "^4.3.2",
"phoenix": "^1.7.2",
"phoenix_html": "^3.3.1",
Expand Down
Loading