Skip to content

Commit

Permalink
feat: add useHotKey composable
Browse files Browse the repository at this point in the history
Signed-off-by: Maksim Sukharev <antreesy.web@gmail.com>
  • Loading branch information
Antreesy committed Aug 20, 2024
1 parent ddaeea8 commit 95dfaaa
Show file tree
Hide file tree
Showing 4 changed files with 219 additions and 0 deletions.
133 changes: 133 additions & 0 deletions docs/composables/useHotKey.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
<!--
- SPDX-FileCopyrightText: 2024 Nextcloud GmbH and Nextcloud contributors
- SPDX-License-Identifier: AGPL-3.0-or-later
-->

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

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

const stopCallback = useHotKey(key, callback, options)
```
where:
- `key`: string representing the keyboard key to listen to

See [KeyboardEvent.key Value column](https://developer.mozilla.org/en-US/docs/Web/API/UI_Events/Keyboard_event_key_values) for possible values
- `callback`: 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 options should be applied
- `options`: options to be applied to the shortcut:
- `push`: whether the event should be triggered on both keydown and keyup
- `prevent`: prevents the default action of the event
- `stop`: prevents propagation of the event in the capturing and bubbling phases
- `ctrl`: whether the Ctrl key should be pressed
- `alt`: whether the Alt key should be pressed
- `shift`: whether the Shift key should be pressed
- `stopCallback`: a callback to stop listening to 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>
<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
<button @click="stop">Stop listen to this event</button>
</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 { useHotKey } from '../../src/composables/useHotKey/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
}
useHotKey('w', moveUp)
useHotKey('s', moveDown)
useHotKey('a', moveLeft)
useHotKey('d', moveRight)
const stop = useHotKey('m', toggleHighlighted, { push: true })
return {
circleX,
circleY,
highlighted,
stop,
}
},
created() {
useHotKey('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 './useHotKey/index.js'
81 changes: 81 additions & 0 deletions src/composables/useHotKey/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
/**
* 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 editable (allows input from keyboard) or NcModal is open
* If true, a hot key should not trigger the callback
* TODO discuss if we should abort on another interactive elements (button, a, e.t.c)
*
* @param {KeyboardEvent} event keyboard event
* @return {boolean} whether it should prevent callback
*/
function shouldIgnoreEvent(event) {
if (event.target instanceof HTMLInputElement
|| event.target instanceof HTMLTextAreaElement
|| event.target instanceof HTMLSelectElement
|| event.target?.isContentEditable) {
return true
}
/** Abort if any modal/dialog opened */
return document.getElementsByClassName('modal-mask').length !== 0
}

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

if (options.prevent) {
event.preventDefault()
}
if (options.stop) {
event.stopPropagation()
}
callback(event)
}

/**
* @param {string} key - keyboard key or keys to listen to
* @param {Function} callback - callback function
* @param {object} options - composable options
* @see docs/composables/usekeystroke.md
*/
export function useHotKey(key, callback = () => {}, options = {}) {
if (disableKeyboardShortcuts) {
// Keyboard shortcuts are disabled
return () => {}
}

const stopKeyDown = onKeyStroke(key, eventHandler(callback, options), {
eventName: 'keydown',
dedupe: true,
passive: !options.prevent,
})

const stopKeyUp = options.push
? onKeyStroke(key, eventHandler(callback, options), {
eventName: 'keyup',
passive: !options.prevent,
})
: () => {}

return () => {
stopKeyDown()
stopKeyUp()
}
}
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: 'useHotKey',
content: 'docs/composables/useHotKey.md',
},
],
},
{
Expand Down

0 comments on commit 95dfaaa

Please sign in to comment.