Line data Source code
1 : import type { WatchSource } from 'vue'
2 : import { nextTick, watch } from 'vue'
3 :
4 2355 : const FOCUS_ROW_ATTRIBUTE = 'data-focus-row'
5 :
6 0 : function focusedRow() {
7 0 : const row = document.activeElement?.closest<HTMLElement>(
8 : `[${FOCUS_ROW_ATTRIBUTE}]`
9 : )
10 0 : const menu = row?.parentElement?.closest('[role="menu"]')
11 0 : const value = row?.getAttribute(FOCUS_ROW_ATTRIBUTE)
12 0 : return row && menu && value ? { row, menu, value } : null
13 : }
14 :
15 : /**
16 : * Puts focus back on the same menu row, matched by its `data-focus-row`,
17 : * when a change to `source` re-renders the rows.
18 : */
19 0 : export function useKeepRowFocus(source: WatchSource) {
20 0 : watch(
21 : source,
22 : async () => {
23 0 : const focused = focusedRow()
24 0 : if (!focused) return
25 0 : await nextTick()
26 0 : if (document.activeElement === focused.row) return
27 0 : focused.menu
28 : .querySelector<HTMLElement>(
29 : `[${FOCUS_ROW_ATTRIBUTE}="${CSS.escape(focused.value)}"]`
30 : )
31 : ?.focus()
32 : },
33 : { flush: 'pre' }
34 : )
35 : }
|