Skip to content

Commit

Permalink
feat: add useKeyStroke composable
Browse files Browse the repository at this point in the history
Signed-off-by: Maksim Sukharev <[email protected]>
  • Loading branch information
Antreesy committed Aug 19, 2024
1 parent 236debd commit c6522ad
Show file tree
Hide file tree
Showing 4 changed files with 217 additions and 0 deletions.
132 changes: 132 additions & 0 deletions docs/composables/usekeystroke.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
<!--
- SPDX-FileCopyrightText: 2024 Nextcloud GmbH and Nextcloud contributors
- SPDX-License-Identifier: AGPL-3.0-or-later
-->

Extended version of [VueUse onKeyStroke](https://vueuse.org/core/onKeyStroke/)

This composable allows to use keyboard shortcuts in the application.
It respects Nextcloud's value of ```OCP.Accessibility.disableKeyboardShortcuts``` parameter.

### Usage
```js static
import { useKeystroke } from '@nextcloud/vue/dist/Composables/useKeyStroke/index.js'

useKeystroke(keys, callback, modifiers)
```
where:
- `keys`: string / array of strings representing the key or keys to listen to (`true` to listen to any key)

See [KeyboardEvent.key Value column](https://developer.mozilla.org/en-US/docs/Web/API/UI_Events/Keyboard_event_key_values) for possible values
- `callback` is a function to be called when the key is pressed. Before called, it will be checked whether keyboard shortcuts are disabled, or interactive element is currently focused, or whether modifiers should be applied
- `modifiers`: modifiers to be applied to the shortcut:
- `target`: the HTML element (or Vue ref) to listen to the event (`document` by default)
- `push`: whether the event should be triggered on both keydown and keyup
- `press`: whether the event should be triggered, continuously generating events
- `ctrl`: whether the Ctrl key should be pressed
- `alt`: whether the Alt key should be pressed
- `shift`: whether the Shift key should be pressed
- `stop`: prevents propagation of the event in the capturing and bubbling phases
- `prevent`: prevents the default action of the event

### Playground
```vue
<template>
<div class="container">
<p class="description">Press <kbd>W</kbd> <kbd>S</kbd> <kbd>A</kbd> <kbd>D</kbd> keys to move the ball</p>
<p class="description">Hold <kbd>D</kbd> key to continue generate events</p>
<div class="square">
<div class="circle" :style="{ left: `${circleX}px`, top: `${circleY}px` }"></div>
</div>
<p class="description">Push <kbd>M</kbd> to highlight the red area </p>
<div ref="push"
class="push-square"
:class="{ 'push-square--highlighted': highlighted }"></div>
<p class="description">Use <kbd>Ctrl</kbd> + <kbd>F</kbd> to focus input</p>
<input ref="input"/>
</div>
</template>
<script>
import { ref } from 'vue'
import { useKeyStroke } from '../../src/composables/useKeyStroke/index.js'
export default {
setup() {
const circleX = ref(20)
const circleY = ref(20)
const highlighted = ref(false)
const moveUp = (event) => {
circleY.value = Math.max(0, circleY.value - 10)
}
const moveDown = (event) => {
circleY.value = Math.min(160, circleY.value + 10)
}
const moveLeft = (event) => {
circleX.value = Math.max(0, circleX.value - 10)
}
const moveRight = (event) => {
circleX.value = Math.min(160, circleX.value + 10)
}
const toggleHighlighted = (event) => {
highlighted.value = !highlighted.value
}
useKeyStroke('w', moveUp)
useKeyStroke('s', moveDown)
useKeyStroke('a', moveLeft)
useKeyStroke('d', moveRight, { press: true })
useKeyStroke(' ', toggleHighlighted, { push: true })
return {
circleX,
circleY,
highlighted,
}
},
created() {
useKeyStroke('f', this.focusInput, { ctrl: true, stop: true, prevent: true })
},
methods: {
focusInput(event) {
this.$refs.input.focus()
}
}
}
</script>
<style scoped>
.description {
margin-block: 10px;
}
.square {
position: relative;
width: 200px;
height: 200px;
outline: 4px solid var(--color-border-dark);
}
.circle {
position: absolute;
width: 40px;
height: 40px;
background-color: var(--color-primary-element);
border-radius: 50%;
}
.push-square {
width: 100px;
height: 20px;
background-color: var(--color-error);
}
.push-square--highlighted {
background-color: var(--color-success);
}
</style>
```
1 change: 1 addition & 0 deletions src/composables/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,4 @@
export * from './useIsFullscreen/index.js'
export * from './useIsMobile/index.js'
export * from './useFormatDateTime.ts'
export * from './useKeyStroke/index.js'
80 changes: 80 additions & 0 deletions src/composables/useKeyStroke/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
/**
* SPDX-FileCopyrightText: 2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
import { onKeyStroke } from '@vueuse/core'

const disableKeyboardShortcuts = window.OCP?.Accessibility?.disableKeyboardShortcuts?.()

/**
* Check if event target (active element) is interactive and should not trigger the directive callback
* @param {KeyboardEvent} event keyboard event
* @return {boolean} whether it should prevent callback
*/
function shouldPreventCallback(event) {
/** Abort the directive if active element is an input, textarea or contenteditable */
if (event.target instanceof HTMLInputElement
/**
* TODO discuss if we should abort on another interactive elements
* || event.target instanceof HTMLButtonElement
* || event.target instanceof HTMLAnchorElement
* || event.target instanceof HTMLSelectElement
* || (event.target as HTMLElement)?.hasAttribute('tabindex')
*/
|| event.target instanceof HTMLTextAreaElement
|| event.target?.isContentEditable) {
return true
}
/** Abort the directive if any modal/dialog opened */
return document.getElementsByClassName('modal-mask').length !== 0
}

const eventHandler = (callback, modifiers) => (event) => {
if (!!modifiers.ctrl !== event.ctrlKey) {
// Ctrl is required and not pressed, or the opposite
} else if (!!modifiers.alt !== event.altKey) {
// Alt is required and not pressed, or the opposite
} else if (!!modifiers.shift !== event.shiftKey) {
// Shift is required and not pressed, or the opposite
} else if (shouldPreventCallback(event)) {
// Keyboard shortcuts are disabled, because active element assumes input
} else {
if (modifiers.prevent) {
event.preventDefault()
}
if (modifiers.stop) {
event.stopPropagation()
}
callback(event)
}
}

/**
* @param {boolean|string|string[]} keys - keyboard key or keys to listen to
* @param {Function} callback - callback function
* @param {object} modifiers - modifiers
* @see docs/composables/usekeystroke.md
*/
export function useKeyStroke(
keys = true,
callback = () => {},
modifiers = {},
) {
if (disableKeyboardShortcuts) {
// Keyboard shortcuts are disabled
return
}

onKeyStroke(keys, eventHandler(callback, modifiers), {
eventName: 'keydown',
dedupe: !modifiers.press,
target: modifiers.target ?? document,
})

if (modifiers.push) {
onKeyStroke(keys, eventHandler(callback, modifiers), {
eventName: 'keyup',
target: modifiers.target ?? document,
})
}
}
4 changes: 4 additions & 0 deletions styleguide.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,10 @@ module.exports = async () => {
content: 'docs/composables.md',
sectionDepth: 1,
sections: [
{
name: 'useKeyStroke',
content: 'docs/composables/usekeystroke.md',
},
],
},
{
Expand Down

0 comments on commit c6522ad

Please sign in to comment.