From 902f7b289f17bd2c62352d9554a9fa2dab06d5b1 Mon Sep 17 00:00:00 2001 From: Dejvino Date: Thu, 25 May 2023 11:44:35 +0200 Subject: [PATCH] Second click removes focus --- src/app/FocusedElement.tsx | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/src/app/FocusedElement.tsx b/src/app/FocusedElement.tsx index 1ee2c2b..1e7b9fa 100644 --- a/src/app/FocusedElement.tsx +++ b/src/app/FocusedElement.tsx @@ -4,23 +4,27 @@ const focusUrlParamName = 'focus' const focusChangedEventName = "focus-changed" const focusedElementClassName = 'focused-element' -function triggerElementFocused(elementKey: string) { +function triggerElementFocused(elementKey?: string) { const url = new URL(window.location.href); - url.searchParams.set(focusUrlParamName, elementKey); - const focusChangeEvent = new Event(focusChangedEventName); + if (elementKey) { + url.searchParams.set(focusUrlParamName, elementKey) + } else { + url.searchParams.delete(focusUrlParamName) + } + const focusChangeEvent = new Event(focusChangedEventName) history.pushState({}, "", url); window.dispatchEvent(focusChangeEvent) } export function useFocusedElement(elementKey: string) { - const [isFocusedElement, setFocusedElement] = useState(false); + const [isFocusedElement, setFocusedElement] = useState(false) const focusedClass = isFocusedElement ? focusedElementClassName : '' const elementRef = useRef(null) function focusElement() { - triggerElementFocused(elementKey) + triggerElementFocused(isFocusedElement ? undefined : elementKey) } - + useEffect(() => { function getFocusedState() { const params = new URLSearchParams(window.location.search)