Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions docs/content/2.composables/define-shortcuts.md
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@ Each shortcut can be defined as a function or an object with the following prope
interface ShortcutConfig {
handler: () => void
usingInput?: boolean | string
cursorTarget?: MaybeRefOrGetter<MaybeElement>
}
```

Expand All @@ -73,6 +74,7 @@ interface ShortcutConfig {
- `false` (default): Shortcut only triggers when no input is focused
- `true`: Shortcut triggers even when any input is focused
- `string`: Shortcut only triggers when the specified input (by name) is focused
- `cursorTarget`: Element which needs to be hovered for the shortcut to trigger

## Examples

Expand Down Expand Up @@ -138,3 +140,35 @@ const items = [{
defineShortcuts(extractShortcuts(items))
</script>
```

### Scoping shortcuts to specific elements

The `cursorTarget` field can be used to scope the shortcut to a specific element:

```vue
<script setup lang="ts">
import { ref, useTemplateRef } from "vue"

const cursorTarget = useTemplateRef('cursorTarget')
const open = ref(false)

defineShortcuts({
i: {
handler: () => {
open.value = !open.value
},
cursorTarget
}
})
</script>

<template>
<div class="flex flex-col gap-4">
<UTooltip v-model:open="open" text="Open on GitHub">
<Placeholder ref="cursorTarget" class="px-4 py-3">
Cursor Target
</Placeholder>
</UTooltip>
</div>
</template>
```
74 changes: 68 additions & 6 deletions src/runtime/composables/defineShortcuts.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,18 @@
/* eslint-disable regexp/no-useless-quantifier */
/* eslint-disable regexp/no-super-linear-backtracking */
import { ref, computed, toValue } from 'vue'
import type { MaybeRef } from 'vue'
import { useEventListener, useActiveElement, useDebounceFn } from '@vueuse/core'
import { ref, computed, toValue, watchEffect } from 'vue'
import type { MaybeRef, MaybeRefOrGetter } from 'vue'
import { useEventListener, useActiveElement, useDebounceFn, unrefElement, type MaybeElement } from '@vueuse/core'
import { useKbd } from './useKbd'

const CURSOR_DATASET_ATTR = 'data-define-shortcuts-cursor'

type Handler = (e?: any) => void

export interface ShortcutConfig {
handler: Handler
usingInput?: string | boolean
cursorTarget?: MaybeRefOrGetter<MaybeElement>
}

export interface ShortcutsConfig {
Expand All @@ -32,11 +35,33 @@ interface Shortcut {
altKey: boolean
// code?: string
// keyCode?: number
cursorTarget: MaybeElement
}

const chainedShortcutRegex = /^[^-]+.*-.*[^-]+$/
const combinedShortcutRegex = /^[^_]+.*_.*[^_]+$/

/**
* Get the elements under the cursor.
*/
const getHoveredElements
= (() => {
let elements: readonly Element[] | null = null

return () => {
if (elements == null) {
elements
= [...document.querySelectorAll(`[${CURSOR_DATASET_ATTR}]:hover`)]

setTimeout((): void => {
elements = null
}, 50)
}

return elements
}
})()

export function extractShortcuts(items: any[] | any[][]) {
const shortcuts: Record<string, Handler> = {}

Expand Down Expand Up @@ -117,6 +142,10 @@ export function defineShortcuts(config: MaybeRef<ShortcutsConfig>, options: Shor
// alt modifier changes the combined key anyways
// if (e.altKey !== shortcut.altKey) { continue }

if (shortcut.cursorTarget && !getHoveredElements().includes(shortcut.cursorTarget as Element)) {
continue
}

if (shortcut.enabled) {
e.preventDefault()
shortcut.handler()
Expand Down Expand Up @@ -166,16 +195,18 @@ export function defineShortcuts(config: MaybeRef<ShortcutsConfig>, options: Shor
metaKey: false,
ctrlKey: false,
shiftKey: false,
altKey: false
altKey: false,
cursorTarget: null
}
} else {
const keySplit = key.toLowerCase().split('_').map(k => k)
shortcut = {
key: keySplit.filter(k => !['meta', 'command', 'ctrl', 'shift', 'alt', 'option'].includes(k)).join('_'),
key: keySplit.filter(k => !['meta', 'command', 'ctrl', 'shift', 'alt', 'option', 'cursor'].includes(k)).join('_'),
metaKey: keySplit.includes('meta') || keySplit.includes('command'),
ctrlKey: keySplit.includes('ctrl'),
shiftKey: keySplit.includes('shift'),
altKey: keySplit.includes('alt') || keySplit.includes('option')
altKey: keySplit.includes('alt') || keySplit.includes('option'),
cursorTarget: 'cursorTarget' in shortcutConfig ? unrefElement(shortcutConfig.cursorTarget) : null
}
}
shortcut.chained = chained
Expand Down Expand Up @@ -210,5 +241,36 @@ export function defineShortcuts(config: MaybeRef<ShortcutsConfig>, options: Shor
}).filter(Boolean) as Shortcut[]
})

watchEffect((onCleanup) => {
const cursorTargets = shortcuts.value.map(shortcut => unrefElement(shortcut.cursorTarget)).filter((cursorTarget) => {
// Ignore fragments.
if (cursorTarget?.nodeName === '#comment') {
console.trace(`[Shortcut] Invalid cursorTarget: "${cursorTarget}"`)
return false
}

return !!cursorTarget
})

if (cursorTargets.length < 1) {
return
}

cursorTargets.forEach((cursorTarget) => {
if (cursorTarget) {
cursorTarget.setAttribute(CURSOR_DATASET_ATTR, 'true')
}
})

onCleanup(() => {
cursorTargets.forEach((cursorTarget) => {
if (cursorTarget) {
cursorTarget.removeAttribute(CURSOR_DATASET_ATTR)
}
})
}
)
})

return useEventListener('keydown', onKeyDown)
}