use-active-element
shadcn-hooks/use-active-elementFreeHook
A hook to track the currently focused element in the document
Install it
npx shadcn@latest add https://shadcn-hooks.com/r/use-active-element.jsonSource
1import { useCallback, useSyncExternalStore } from 'react'23export interface UseActiveElementOptions {4 /**5 * Whether to resolve the deepest focused node inside open shadow roots.6 * @default true7 */8 deep?: boolean9 /**10 * Whether to re-check active element when DOM nodes are removed.11 * @default false12 */13 triggerOnRemoval?: boolean14}1516function resolveActiveElement(deep: boolean): Element | null {17 if (typeof document === 'undefined') {18 return null19 }2021 let activeElement: Element | null = document.activeElement2223 if (!deep) {24 return activeElement25 }2627 while (activeElement?.shadowRoot?.activeElement) {28 activeElement = activeElement.shadowRoot.activeElement29 }3031 return activeElement32}3334export function useActiveElement<T extends Element = HTMLElement>(35 options: UseActiveElementOptions = {},36): T | null {37 const { deep = true, triggerOnRemoval = false } = options3839 const subscribe = useCallback(40 (onStoreChange: () => void) => {41 if (typeof window === 'undefined') {42 return () => {}43 }4445 const onFocus = () => {46 onStoreChange()47 }48 const onBlur = (event: FocusEvent) => {49 if (event.relatedTarget !== null) {50 return51 }52 onStoreChange()53 }5455 window.addEventListener('focus', onFocus, true)56 window.addEventListener('blur', onBlur, true)5758 const observer =59 triggerOnRemoval && typeof MutationObserver !== 'undefined'60 ? new MutationObserver(() => {61 onStoreChange()62 })63 : null6465 observer?.observe(document, {66 childList: true,67 subtree: true,68 })6970 return () => {71 window.removeEventListener('focus', onFocus, true)72 window.removeEventListener('blur', onBlur, true)73 observer?.disconnect()74 }75 },76 [triggerOnRemoval],77 )7879 const getSnapshot = useCallback(() => {80 return resolveActiveElement(deep) as T | null81 }, [deep])8283 const getServerSnapshot = useCallback(() => {84 return null as T | null85 }, [])8687 return useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot)88}
Files it writes
More from shadcn-hooks
All 58 items| Component | Registry | Kind | Access | Installs | Command |
|---|---|---|---|---|---|
| use-batteryuse-battery | shadcn-hooks | Hooks | Free | no deps | |
| use-booleanuse-boolean | shadcn-hooks | Hooks | Free | no deps | |
| use-click-any-whereuse-click-any-where | shadcn-hooks | Hooks | Free | no deps | |
| use-click-awayuse-click-away | shadcn-hooks | Hooks | Free | no deps | |
| use-clipboarduse-clipboard | shadcn-hooks | Hooks | Free | no deps | |
| use-controllable-valueuse-controllable-value | shadcn-hooks | Hooks | Free | 1 dep | |
| use-counteruse-counter | shadcn-hooks | Hooks | Free | no deps | |
| use-creationuse-creation | shadcn-hooks | Hooks | Free | 1 dep |
