-
Notifications
You must be signed in to change notification settings - Fork 257
Expand file tree
/
Copy pathfocus.ts
More file actions
72 lines (62 loc) 路 1.91 KB
/
Copy pathfocus.ts
File metadata and controls
72 lines (62 loc) 路 1.91 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import {setUISelection} from '../document'
import {
delegatesFocus,
findClosest,
findFocusable,
getActiveElementOrBody,
hasOwnSelection,
isFocusable,
isFocusTarget,
} from '../utils'
import {updateSelectionOnFocus} from './selection'
import {wrapEvent} from './wrapEvent'
/**
* Focus closest focusable element.
*/
export function focusElement(element: Element, select: boolean = false) {
const target = findClosest(element, isFocusTarget)
const activeElement = getActiveElementOrBody(element.ownerDocument)
if ((target ?? element.ownerDocument.body) === activeElement) {
return
}
if (target) {
if (delegatesFocus(target)) {
const effectiveTarget = findFocusable(target.shadowRoot)
if (effectiveTarget) {
doFocus(effectiveTarget, true, element)
} else {
// This is not consistent across browsers if there is a focusable ancestor.
// Firefox falls back to the closest focusable ancestor
// of the shadow host as if `delegatesFocus` was `false`.
// Chrome falls back to `document.body`.
// We follow the minimal implementation of Chrome.
doBlur(activeElement, element)
}
} else {
doFocus(target, select, element)
}
} else {
doBlur(activeElement, element)
}
}
function doBlur(target: Element, source: Element) {
wrapEvent(() => (target as HTMLElement | null)?.blur(), source)
}
function doFocus(target: HTMLElement, select: boolean, source: Element) {
wrapEvent(() => target.focus(), source)
if (hasOwnSelection(target)) {
if (select) {
setUISelection(target, {
anchorOffset: 0,
focusOffset: target.value.length,
})
}
updateSelectionOnFocus(target)
}
}
export function blurElement(element: Element) {
if (!isFocusable(element)) return
const wasActive = getActiveElementOrBody(element.ownerDocument) === element
if (!wasActive) return
doBlur(element, element)
}