Second click removes focus

This commit is contained in:
Dejvino 2023-05-25 11:44:35 +02:00
parent 6dff62d61c
commit 902f7b289f

View File

@ -4,21 +4,25 @@ const focusUrlParamName = 'focus'
const focusChangedEventName = "focus-changed" const focusChangedEventName = "focus-changed"
const focusedElementClassName = 'focused-element' const focusedElementClassName = 'focused-element'
function triggerElementFocused(elementKey: string) { function triggerElementFocused(elementKey?: string) {
const url = new URL(window.location.href); const url = new URL(window.location.href);
url.searchParams.set(focusUrlParamName, elementKey); if (elementKey) {
const focusChangeEvent = new Event(focusChangedEventName); url.searchParams.set(focusUrlParamName, elementKey)
} else {
url.searchParams.delete(focusUrlParamName)
}
const focusChangeEvent = new Event(focusChangedEventName)
history.pushState({}, "", url); history.pushState({}, "", url);
window.dispatchEvent(focusChangeEvent) window.dispatchEvent(focusChangeEvent)
} }
export function useFocusedElement(elementKey: string) { export function useFocusedElement(elementKey: string) {
const [isFocusedElement, setFocusedElement] = useState(false); const [isFocusedElement, setFocusedElement] = useState(false)
const focusedClass = isFocusedElement ? focusedElementClassName : '' const focusedClass = isFocusedElement ? focusedElementClassName : ''
const elementRef = useRef<HTMLSpanElement>(null) const elementRef = useRef<HTMLSpanElement>(null)
function focusElement() { function focusElement() {
triggerElementFocused(elementKey) triggerElementFocused(isFocusedElement ? undefined : elementKey)
} }
useEffect(() => { useEffect(() => {