UNPKG

vuestic-ui

Version:
1 lines 3.13 kB
{"version":3,"file":"useFocusDeep.mjs","sources":["../../../../src/composables/useFocusDeep.ts"],"sourcesContent":["import { computed, Ref, DefineComponent, Component } from 'vue'\nimport { useHTMLElement } from './useHTMLElement'\nimport { useCurrentElement } from './useCurrentElement'\nimport { useActiveElement } from './useActiveElement'\n\n/**\n * `true` if `el` or any of his children are in focus\n *\n * if set to `true` set `el` focused, but if any of `el` children was focused before, set child focused instead\n *\n * @notice this will not trigger native `focus` event and you need to trigger it manually and handle infinite loop\n */\nexport const useFocusDeep = (el?: Ref<HTMLElement | DefineComponent | undefined | Component>) => {\n const focused = useActiveElement()\n const current = useCurrentElement(el ? useHTMLElement(el) : undefined)\n // Cache previouslyFocusedElement, so we can simply come back to it\n let previouslyFocusedElement: HTMLElement | null = null\n\n const isFocused = computed<boolean | undefined>({\n get () {\n if (!focused.value) { return false }\n if (focused.value === current.value) { return true }\n\n const isFocused = current.value?.contains(focused.value)\n if (isFocused) { previouslyFocusedElement = focused.value }\n return isFocused\n },\n set (value) {\n let target = previouslyFocusedElement ?? current.value\n\n if (!current.value?.contains(target!)) {\n target = current.value\n }\n\n // NOTICE: Focus and blur events will not be dispatched here to prevent infinite loop\n if (value) {\n (target)?.focus()\n } else {\n (target)?.blur()\n }\n },\n })\n\n return Object.assign(isFocused, {\n /** Focus `el` if focus is not set to any other element */\n focusIfNothingIfFocused: () => {\n // body if focused by default, but we assume it means nothing is focused\n // by nothing we mean elements like input, button, etc.\n if (focused.value === document.body) {\n isFocused.value = true\n }\n },\n\n focusPreviousElement: () => {\n if (previouslyFocusedElement) {\n previouslyFocusedElement.focus()\n } else {\n document.body.focus()\n }\n },\n })\n}\n"],"names":["isFocused"],"mappings":";;;;AAYa,MAAA,eAAe,CAAC,OAAoE;AAC/F,QAAM,UAAU;AAChB,QAAM,UAAU,kBAAkB,KAAK,eAAe,EAAE,IAAI,MAAS;AAErE,MAAI,2BAA+C;AAEnD,QAAM,YAAY,SAA8B;AAAA,IAC9C,MAAO;;AACD,UAAA,CAAC,QAAQ,OAAO;AAAS,eAAA;AAAA,MAAM;AAC/B,UAAA,QAAQ,UAAU,QAAQ,OAAO;AAAS,eAAA;AAAA,MAAK;AAEnD,YAAMA,cAAY,aAAQ,UAAR,mBAAe,SAAS,QAAQ;AAClD,UAAIA,YAAW;AAAE,mCAA2B,QAAQ;AAAA,MAAM;AACnDA,aAAAA;AAAAA,IACT;AAAA,IACA,IAAK,OAAO;;AACN,UAAA,SAAS,4BAA4B,QAAQ;AAEjD,UAAI,GAAC,aAAQ,UAAR,mBAAe,SAAS,UAAU;AACrC,iBAAS,QAAQ;AAAA,MACnB;AAGA,UAAI,OAAO;AACR,yCAAS;AAAA,MAAM,OACX;AACJ,yCAAS;AAAA,MACZ;AAAA,IACF;AAAA,EAAA,CACD;AAEM,SAAA,OAAO,OAAO,WAAW;AAAA;AAAA,IAE9B,yBAAyB,MAAM;AAGzB,UAAA,QAAQ,UAAU,SAAS,MAAM;AACnC,kBAAU,QAAQ;AAAA,MACpB;AAAA,IACF;AAAA,IAEA,sBAAsB,MAAM;AAC1B,UAAI,0BAA0B;AAC5B,iCAAyB,MAAM;AAAA,MAAA,OAC1B;AACL,iBAAS,KAAK;MAChB;AAAA,IACF;AAAA,EAAA,CACD;AACH;"}