Skip to content

Open source, privacy-first web analytics. Lightweight, cookie-free Google Analytics alternative. Self-hosted or cloud.

Fix debounce (#4349)

RobertJoonas5a58b5cb99cf
diff --git a/assets/js/dashboard/components/combobox.js b/assets/js/dashboard/components/combobox.js
index b6f85098b2..bba20f5c7c 100644
--- a/assets/js/dashboard/components/combobox.js
+++ b/assets/js/dashboard/components/combobox.js
@@ -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', {
@@ -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
@@ -94,56 +135,42 @@ 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)
}
@@ -151,31 +178,30 @@ export default function PlausibleCombobox(props) {
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'>
@@ -183,9 +209,9 @@ export default function PlausibleCombobox(props) {
<input
className={searchBoxClass}
ref={searchRef}
- value={input}
+ value={search}
style={{backgroundColor: "inherit"}}
- placeholder={placeholder}
+ placeholder={itemSelected ? '' : placeholder}
type="text"
onChange={onInput}>
</input>
@@ -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>
)
}
@@ -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>
@@ -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>
</>
)
}
@@ -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>
}
@@ -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 />}
diff --git a/assets/js/dashboard/custom-hooks.js b/assets/js/dashboard/custom-hooks.js
index 4bbe92bdcc..bcd53af9e1 100644
--- a/assets/js/dashboard/custom-hooks.js
+++ b/assets/js/dashboard/custom-hooks.js
@@ -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.
@@ -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])
}
\ No newline at end of file
diff --git a/assets/js/dashboard/stats/modals/breakdown-modal.js b/assets/js/dashboard/stats/modals/breakdown-modal.js
index ce1ee390c9..138c1a9a37 100644
--- a/assets/js/dashboard/stats/modals/breakdown-modal.js
+++ b/assets/js/dashboard/stats/modals/breakdown-modal.js
@@ -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";
@@ -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 }
@@ -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') {
@@ -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) => {
@@ -236,7 +238,7 @@ export default function BreakdownModal({
}
function handleInputChange(e) {
- setSearchInput(e.target.value)
+ setSearch(e.target.value)
}
function renderSearchInput() {
diff --git a/assets/package-lock.json b/assets/package-lock.json
index 0d8b818621..6eebcc2e50 100644
--- a/assets/package-lock.json
+++ b/assets/package-lock.json
@@ -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",
@@ -1041,10 +1040,6 @@
"version": "1.11.7",
"license": "MIT"
},
- "node_modules/debounce-promise": {
- "version": "3.1.2",
- "license": "MIT"
- },
"node_modules/debug": {
"version": "4.3.3",
"dev": true,
diff --git a/assets/package.json b/assets/package.json
index 23971f0ddf..536561284a 100644
--- a/assets/package.json
+++ b/assets/package.json
@@ -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",