feat: Add support for keyboard shortcuts (#870)

* Add support for keyboard shortcuts.

This change introduces a Shortcut component for defining global
keyboard shortcuts from whichever component makes more sense.

This change also adds an initial set of navigation shortcuts:
- Backspace to leave a modal dialog or to go back
- g t to go to the federated timeline
- g f to go to the favorite page
- g h to go to the home page
- g n to go to the notification page
- g c to go to the community page
- s to go to the search page

These shortcuts are loaded asynchronously from _layout.html

In modal dialogs, shortcuts are also modal, to avoid strange or
overly complex behavior. This is implemented by grouping
shortcuts into scopes, and activating a separate 'modal' scope
when entering a modal dialog, so a separate set of shortcuts can
be enabled in modal dialog. Modal dialogs can be exited by
pressing 'Backspace'.

* Navigate up/down lists using keyboard shortcuts.

This change introduces keyboard shortcuts for navigating in lists and
virtual lists. j or arrow up selects the next element, k or arrow down,
the previous element. Selecting an element scrolls the list up and down,
as necessary.

This change also allows directing keyboard shortcuts to the active
element and defines the following shortcuts, for the active status:
- f to favorite or unfavorite it
- b to boost or unboost it
- r to reply to it
- o to open its thread
- x to toggle the display of a CW
- y to toggle the display of sensitive medias

This works by defining a keyboard shortcut scope for each list element.
A new component, ScrollListShortcuts, keeps track of the active element,
based on list or virtual list elements and redirects shortcuts to the
active element's scope. ScrollListShortcuts keeps the active element in
the current realm of the store, so the active element is restored when
going back to the list.

* Typing h or ? displays the list of available keyboard shortcuts.

This change introduces a new modal dialog that documents the list of
available shortcuts.
This commit is contained in:
Stephane Zermatten 2019-01-13 19:03:29 +01:00 committed by Nolan Lawson
parent 981af04c6d
commit c2bd2f306a
32 changed files with 1083 additions and 52 deletions

View File

@ -80,10 +80,12 @@
--very-deemphasized-text-color: #{rgba(#666, 0.6)};
--status-direct-background: #{darken($body-bg-color, 5%)};
--status-active-background: #{lighten($body-bg-color, 2%)};
--main-theme-color: #{$main-theme-color};
--warning-color: #{#e01f19};
--alt-input-bg: #{rgba($main-bg-color, 0.7)};
--muted-modal-text: #{$secondary-text-color};
--muted-modal-bg: #{transparent};
--muted-modal-focus: #{#999};
--muted-modal-hover: #{rgba(255, 255, 255, 0.2)};

View File

@ -16,6 +16,7 @@
--very-deemphasized-text-color: #{lighten($main-bg-color, 32%)};
--status-direct-background: #{darken($body-bg-color, 5%)};
--status-active-background: #{lighten($body-bg-color, 10%)};
--main-theme-color: #{$main-theme-color};
--warning-color: #{#c7423d};
--alt-input-bg: #{rgba($main-bg-color, 0.7)};

View File

@ -10,8 +10,9 @@
<button type="button"
class="dynamic-page-go-back"
aria-label="Go back"
on:click="onGoBack(event)">Back</button>
on:click|preventDefault="onGoBack()">Back</button>
</div>
<Shortcut key="Backspace" on:pressed="onGoBack()"/>
<style>
.dynamic-page-banner {
display: grid;
@ -62,14 +63,16 @@
}
</style>
<script>
import Shortcut from './shortcut/Shortcut.html'
export default {
data: () => ({
icon: void 0,
ariaTitle: ''
}),
components: { Shortcut },
methods: {
onGoBack (e) {
e.preventDefault()
onGoBack () {
window.history.back()
}
}

View File

@ -1,4 +1,4 @@
<nav class="main-nav">
<nav id="main-nav" class="main-nav">
<ul class="main-nav-ul">
{#each $navPages as navPage (navPage.href)}
<li class="main-nav-li">
@ -13,6 +13,13 @@
{/each}
</ul>
</nav>
{#await importNavShortcuts}
<!-- awaiting nav shortcuts promise -->
{:then component}
<svelte:component this={component}/>
{:catch error}
<!-- nav shortcuts {error} -->
{/await}
<style>
.main-nav {
@ -47,12 +54,16 @@
</style>
<script>
import NavItem from './NavItem'
import { importNavShortcuts } from '../_utils/asyncModules'
import { store } from '../_store/store'
export default {
store: () => store,
components: {
NavItem
}
},
data: () => ({
importNavShortcuts: importNavShortcuts()
})
}
</script>
</script>

View File

@ -156,7 +156,7 @@
</style>
<script>
import { store } from '../_store/store'
import { smoothScrollToTop } from '../_utils/smoothScrollToTop'
import { smoothScroll } from '../_utils/smoothScroll'
import { on, emit } from '../_utils/eventBus'
import { mark, stop } from '../_utils/marks'
import { doubleRAF } from '../_utils/doubleRAF'
@ -221,7 +221,7 @@
}
e.preventDefault()
e.stopPropagation()
smoothScrollToTop(getScrollContainer())
smoothScroll(getScrollContainer(), 0)
}
}
}

View File

@ -0,0 +1,27 @@
<Shortcut key="g t" on:pressed="goto('/federated')"/>
<Shortcut key="g f" on:pressed="goto('/favorites')"/>
<Shortcut key="g l" on:pressed="goto('/local')"/>
<Shortcut key="g h" on:pressed="goto('/')"/>
<Shortcut key="g n" on:pressed="goto('/notifications')"/>
<Shortcut key="g c" on:pressed="goto('/community')"/>
<Shortcut key="s" on:pressed="goto('/search')"/>
<Shortcut key="h|?" on:pressed="showShortcutHelpDialog()"/>
<script>
import Shortcut from './shortcut/Shortcut'
import { goto } from '../../../__sapper__/client'
import { importShowShortcutHelpDialog } from './dialog/asyncDialogs'
export default {
components: {
Shortcut
},
methods: {
goto,
async showShortcutHelpDialog () {
let showShortcutHelpDialog = await importShowShortcutHelpDialog()
showShortcutHelpDialog()
}
}
}
</script>

View File

@ -32,4 +32,8 @@ export const importShowVideoDialog = () => import(
export const importShowCopyDialog = () => import(
/* webpackChunkName: 'showCopyDialog' */ './creators/showCopyDialog'
).then(mod => mod.default)
).then(mod => mod.default)
export const importShowShortcutHelpDialog = () => import(
/* webpackChunkName: 'showShortcutHelpDialog' */ './creators/showShortcutHelpDialog'
).then(mod => mod.default)

View File

@ -24,6 +24,7 @@
<slot></slot>
</div>
</div>
<Shortcut scope="modal" key="Backspace" on:pressed="closeDialog(id)"/>
<style>
:global(.modal-dialog[aria-hidden='true']) {
display: none;
@ -136,9 +137,13 @@
}
</style>
<script>
import Shortcut from '../../shortcut/Shortcut.html'
import { A11yDialog } from '../../../_thirdparty/a11y-dialog/a11y-dialog'
import { classname } from '../../../_utils/classname'
import { on, emit } from '../../../_utils/eventBus'
import {
pushShortcutScope,
popShortcutScope } from '../../../_utils/shortcuts'
export default {
oncreate () {
@ -154,7 +159,12 @@
})
on('showDialog', this, this.showDialog)
on('closeDialog', this, this.closeDialog)
pushShortcutScope('modal')
},
ondestroy () {
popShortcutScope('modal')
},
components: { Shortcut },
data: () => ({
// don't animate if we're showing a modal dialog on top of another modal dialog. it looks ugly
shouldAnimate: !process.browser || document.getElementsByClassName('modal-dialog').length < 2,

View File

@ -0,0 +1,67 @@
<ModalDialog
{id}
{label}
background="var(--muted-modal-bg)"
muted="true"
className="shortcut-help-modal-dialog">
<h1>Keyboard Shortcuts</h1>
<ul>
<li><kbd>s</kbd> to search</li>
<li><kbd>g</kbd> + <kbd>h</kbd> to go home</li>
<li><kbd>g</kbd> + <kbd>n</kbd> to go to the notifications page</li>
<li><kbd>g</kbd> + <kbd>l</kbd> to go to the local stream page</li>
<li><kbd>g</kbd> + <kbd>t</kbd> to go to the federated stream page</li>
<li><kbd>g</kbd> + <kbd>c</kbd> to go to the community page</li>
<li><kbd>j</kbd> or <kbd></kbd> to activate the next status</li>
<li><kbd>k</kbd> or <kbd></kbd> to activate the previous status</li>
<li><kbd>o</kbd> to open the active status</li>
<li><kbd>f</kbd> to favorite the active status</li>
<li><kbd>b</kbd> to boost the active status</li>
<li><kbd>r</kbd> to reply to the active status</li>
<li><kbd>x</kbd> to show or hide text behind content warning in the active status</li>
<li><kbd>y</kbd> to show or hide sensitive media in the active status</li>
<li><kbd>h</kbd> or <kbd>?</kbd> to toggle this dialog</li>
<li><kbd>Backspace</kbd> to go back, close dialogs</li>
</ul>
<Shortcut scope='modal' key='h|?' on:pressed='close()'/>
</ModalDialog>
<style>
h1 {
color: var(--muted-modal-text);
}
li {
list-style-type:none;
color: var(--muted-modal-text);
}
kbd {
color: #333;
display: inline-block;
border: 1px solid #333;
border-radius: 2px;
padding: 0.1em;
margin: 0.2em;
background-color: #dadada;
}
</style>
<script>
import ModalDialog from './ModalDialog.html'
import Shortcut from '../../shortcut/Shortcut.html'
import { show } from '../helpers/showDialog'
import { close } from '../helpers/closeDialog'
import { oncreate } from '../helpers/onCreateDialog'
export default {
oncreate,
components: {
ModalDialog,
Shortcut
},
methods: {
show,
close
}
}
</script>

View File

@ -0,0 +1,14 @@
import ShortcutHelpDialog from '../components/ShortcutHelpDialog.html'
import { createDialogElement } from '../helpers/createDialogElement'
import { createDialogId } from '../helpers/createDialogId'
export default function showShortcutHelpDialog (options) {
let dialog = new ShortcutHelpDialog({
target: createDialogElement(),
data: Object.assign({
id: createDialogId(),
label: 'shortcut help dialog'
}, options)
})
dialog.show()
}

View File

@ -10,6 +10,7 @@
/>
{/each}
</div>
<ScrollListShortcuts bind:items=safeItems/>
<style>
.the-list {
position: relative;
@ -17,6 +18,7 @@
</style>
<script>
import ListLazyItem from './ListLazyItem.html'
import ScrollListShortcuts from '../shortcut/ScrollListShortcuts.html'
import { listStore } from './listStore'
import { getScrollContainer } from '../../_utils/scrollContainer'
import { getMainTopMargin } from '../../_utils/getMainTopMargin'
@ -62,8 +64,9 @@
length: ({ safeItems }) => safeItems.length
},
components: {
ListLazyItem
ListLazyItem,
ScrollListShortcuts
},
store: () => listStore
}
</script>
</script>

View File

@ -4,5 +4,14 @@
virtualProps={props}
virtualIndex={index}
virtualLength={length}
virtualKey={key}
active={active}
/>
</div>
<script>
export default {
computed: {
'active': ({ $activeItem, key }) => $activeItem === key
}
}
</script>

View File

@ -8,6 +8,7 @@ class ListStore extends RealmStore {
const listStore = new ListStore()
listStore.computeForRealm('activeItem', null)
listStore.computeForRealm('intersectionStates', {})
if (process.browser && process.env.NODE_ENV !== 'production') {

View File

@ -0,0 +1,115 @@
<script>
import {
isVisible,
firstVisibleElementIndex,
scrollIntoViewIfNeeded } from '../../_utils/scrollIntoView'
import {
addShortcutFallback,
removeShortcutFallback,
onKeyDownInShortcutScope } from '../../_utils/shortcuts'
import { smoothScroll } from '../../_utils/smoothScroll'
import { getScrollContainer } from '../../_utils/scrollContainer'
const VISIBILITY_CHECK_DELAY_MS = 600
export default {
data: () => ({
scope: 'global',
itemToKey: (item) => item,
keyToElement: (key) => document.getElementById('list-item-' + key),
activeItemChangeTime: 0
}),
computed: {
itemToElement: ({ keyToElement, itemToKey }) => (item) => keyToElement(itemToKey(item))
},
oncreate () {
let { scope } = this.get()
addShortcutFallback(scope, this)
},
ondestroy () {
let { scope } = this.get()
removeShortcutFallback(scope, this)
},
methods: {
onKeyDown (event) {
if (event.key === 'j' || event.key === 'ArrowDown') {
event.stopPropagation()
event.preventDefault()
this.changeActiveItem(1, event.timeStamp)
return
}
if (event.key === 'k' || event.key === 'ArrowUp') {
event.stopPropagation()
event.preventDefault()
this.changeActiveItem(-1, event.timeStamp)
return
}
let activeItemKey = this.checkActiveItem(event.timeStamp)
if (!activeItemKey) {
let { items, itemToKey, itemToElement } = this.get()
let index = firstVisibleElementIndex(items, itemToElement).first
if (index >= 0) {
activeItemKey = itemToKey(items[index])
}
}
if (activeItemKey) {
onKeyDownInShortcutScope(activeItemKey, event)
}
},
changeActiveItem (movement, timeStamp) {
let {
items,
itemToElement,
itemToKey,
keyToElement } = this.get()
let index = -1
let activeItemKey = this.checkActiveItem(timeStamp)
if (activeItemKey) {
let len = items.length
let i = -1
while (++i < len) {
if (itemToKey(items[i]) === activeItemKey) {
index = i
break
}
}
}
if (index === 0 && movement === -1) {
activeItemKey = null
this.set({ activeItemKey })
smoothScroll(getScrollContainer(), 0)
return
}
if (index === -1) {
let { first, firstComplete } = firstVisibleElementIndex(
items, itemToElement)
index = (movement > 0) ? firstComplete : first
} else {
index += movement
}
if (index >= 0 && index < items.length) {
activeItemKey = itemToKey(items[index])
this.setActiveItem(activeItemKey, timeStamp)
scrollIntoViewIfNeeded(keyToElement(activeItemKey))
}
},
checkActiveItem (timeStamp) {
let { activeItem } = this.store.get()
if (!activeItem) {
return null
}
let { activeItemChangeTime, keyToElement } = this.get()
if ((timeStamp - activeItemChangeTime) > VISIBILITY_CHECK_DELAY_MS &&
!isVisible(keyToElement(activeItem))) {
this.setActiveItem(null, 0)
return null
}
return activeItem
},
setActiveItem (key, timeStamp) {
this.set({ activeItemChangeTime: timeStamp })
this.store.setForRealm({ activeItem: key })
}
}
}
</script>

View File

@ -0,0 +1,25 @@
<script>
import {
addToShortcutScope,
removeFromShortcutScope } from '../../_utils/shortcuts'
export default {
data: () => ({ scope: 'global', key: null }),
oncreate () {
let { scope, key } = this.get()
addToShortcutScope(scope, key, this)
},
ondestroy () {
let { scope, key } = this.get()
removeFromShortcutScope(scope, key, this)
},
methods: {
onKeyDown (event) {
event.stopPropagation()
event.preventDefault()
this.fire('pressed', {
key: event.key,
timeStamp: event.timeStamp })
}
}
}
</script>

View File

@ -1,9 +1,9 @@
{#if status}
<Status {index} {length} {timelineType} {timelineValue} {focusSelector}
{status} {notification} on:recalculateHeight
{status} {notification} {active} on:recalculateHeight
/>
{:else}
<article class="notification-article"
<article class="notification-article {active ? 'active' : ''}"
tabindex="0"
aria-posinset={index}
aria-setsize={length}
@ -20,6 +20,9 @@
padding: 10px 20px;
border-bottom: 1px solid var(--main-border);
}
.notification-article.active {
background-color: var(--status-active-background);
}
@media (max-width: 767px) {
.notification-article {
padding: 10px 10px;
@ -54,4 +57,4 @@
)
}
}
</script>
</script>

View File

@ -35,6 +35,9 @@
<StatusComposeBox {...params} on:recalculateHeight />
{/if}
</article>
{#if shortcutScope}
<Shortcut scope="{shortcutScope}" key="o" on:pressed="open()"/>
{/if}
<style>
.status-article {
@ -66,6 +69,10 @@
background-color: var(--status-direct-background);
}
.status-article.status-active {
background-color: var(--status-active-background);
}
.status-article.status-in-own-thread {
grid-template-areas:
"sidebar author-name"
@ -106,6 +113,7 @@
import StatusSpoiler from './StatusSpoiler.html'
import StatusComposeBox from './StatusComposeBox.html'
import StatusMentions from './StatusMentions.html'
import Shortcut from '../shortcut/Shortcut.html'
import { store } from '../../_store/store'
import { goto } from '../../../../__sapper__/client'
import { registerClickDelegate } from '../../_utils/delegate'
@ -149,12 +157,14 @@
StatusContent,
StatusSpoiler,
StatusComposeBox,
StatusMentions
StatusMentions,
Shortcut
},
data: () => ({
notification: void 0,
replyVisibility: void 0,
contentPreloaded: false
contentPreloaded: false,
shortcutScope: null
}),
store: () => store,
methods: {
@ -178,6 +188,9 @@
e.preventDefault()
e.stopPropagation()
this.open()
},
open () {
let { originalStatusId } = this.get()
goto(`/statuses/${originalStatusId}`)
}
@ -233,11 +246,12 @@
status.reblog ||
timelineType === 'pinned'
),
className: ({ visibility, timelineType, isStatusInOwnThread }) => (classname(
className: ({ visibility, timelineType, isStatusInOwnThread, active }) => (classname(
'status-article',
visibility === 'direct' && 'status-direct',
timelineType !== 'search' && 'status-in-timeline',
isStatusInOwnThread && 'status-in-own-thread'
isStatusInOwnThread && 'status-in-own-thread',
active && 'status-active'
)),
content: ({ originalStatus }) => originalStatus.content || '',
showContent: ({ spoilerText, spoilerShown }) => !spoilerText || spoilerShown,
@ -245,7 +259,7 @@
account, accountId, uuid, isStatusInNotification, isStatusInOwnThread,
originalAccount, originalAccountId, spoilerShown, visibility, replyShown,
replyVisibility, spoilerText, originalStatus, originalStatusId, inReplyToId,
createdAtDate, timeagoFormattedDate }) => ({
createdAtDate, timeagoFormattedDate, shortcutScope }) => ({
notification,
notificationId,
status,
@ -267,7 +281,8 @@
originalStatusId,
inReplyToId,
createdAtDate,
timeagoFormattedDate
timeagoFormattedDate,
shortcutScope
})
}
}

View File

@ -31,6 +31,9 @@
{/if}
</div>
</div>
{#if shortcutScope}
<Shortcut scope="{shortcutScope}" key="y" on:pressed="toggleSensitiveMedia()"/>
{/if}
{:else}
<MediaAttachments {mediaAttachments} {sensitive} {uuid} />
{/if}
@ -148,6 +151,7 @@
</style>
<script>
import MediaAttachments from './MediaAttachments.html'
import Shortcut from '../shortcut/Shortcut.html'
import { store } from '../../_store/store'
import { registerClickDelegate } from '../../_utils/delegate'
import { classname } from '../../_utils/classname'
@ -155,10 +159,11 @@
export default {
oncreate () {
let { delegateKey } = this.get()
registerClickDelegate(this, delegateKey, () => this.onClickSensitiveMediaButton())
registerClickDelegate(this, delegateKey, () => this.toggleSensitiveMedia())
},
components: {
MediaAttachments
MediaAttachments,
Shortcut
},
store: () => store,
computed: {
@ -181,7 +186,7 @@
}
},
methods: {
onClickSensitiveMediaButton () {
toggleSensitiveMedia () {
let { uuid } = this.get()
let { sensitivesShown } = this.store.get()
sensitivesShown[uuid] = !sensitivesShown[uuid]

View File

@ -6,6 +6,9 @@
{spoilerShown ? 'Show less' : 'Show more'}
</button>
</div>
{#if shortcutScope}
<Shortcut scope="{shortcutScope}" key="x" on:pressed="toggleSpoilers()"/>
{/if}
<style>
.status-spoiler {
grid-area: spoiler;
@ -39,6 +42,7 @@
}
</style>
<script>
import Shortcut from '../shortcut/Shortcut.html'
import { store } from '../../_store/store'
import { registerClickDelegate } from '../../_utils/delegate'
import { mark, stop } from '../../_utils/marks'
@ -48,9 +52,12 @@
export default {
oncreate () {
let { delegateKey } = this.get()
registerClickDelegate(this, delegateKey, () => this.onClickSpoilerButton())
registerClickDelegate(this, delegateKey, () => this.toggleSpoilers())
},
store: () => store,
components: {
Shortcut
},
computed: {
spoilerText: ({ originalStatus }) => originalStatus.spoiler_text,
emojis: ({ originalStatus }) => originalStatus.emojis,
@ -61,7 +68,7 @@
delegateKey: ({ uuid }) => `spoiler-${uuid}`
},
methods: {
onClickSpoilerButton () {
toggleSpoilers () {
requestAnimationFrame(() => {
mark('clickSpoilerButton')
let { uuid } = this.get()

View File

@ -24,13 +24,18 @@
href="#fa-star"
delegateKey={favoriteKey}
ref:favoriteIcon
/>
/>
<IconButton
label="Show more options"
href="#fa-ellipsis-h"
delegateKey={optionsKey}
/>
</div>
{#if shortcutScope}
<Shortcut scope="{shortcutScope}" key="f" on:pressed="toggleFavorite()"/>
<Shortcut scope="{shortcutScope}" key="r" on:pressed="reply()"/>
<Shortcut scope="{shortcutScope}" key="b" on:pressed="reblog()"/>
{/if}
<style>
.status-toolbar {
grid-area: toolbar;
@ -50,6 +55,7 @@
</style>
<script>
import IconButton from '../IconButton.html'
import Shortcut from '../shortcut/Shortcut.html'
import { store } from '../../_store/store'
import { registerClickDelegates } from '../../_utils/delegate'
import { setFavorited } from '../../_actions/favorite'
@ -68,21 +74,32 @@
optionsKey
} = this.get()
registerClickDelegates(this, {
[favoriteKey]: (e) => this.onFavoriteClick(e),
[reblogKey]: (e) => this.onReblogClick(e),
[replyKey]: (e) => this.onReplyClick(e),
[favoriteKey]: (e) => {
e.preventDefault()
e.stopPropagation()
this.toggleFavorite()
},
[reblogKey]: (e) => {
e.preventDefault()
e.stopPropagation()
this.reblog()
},
[replyKey]: (e) => {
e.preventDefault()
e.stopPropagation()
this.reply()
},
[optionsKey]: (e) => this.onOptionsClick(e)
})
on('postedStatus', this, this.onPostedStatus)
},
components: {
IconButton
IconButton,
Shortcut
},
store: () => store,
methods: {
onFavoriteClick (e) {
e.preventDefault()
e.stopPropagation()
toggleFavorite () {
let { originalStatusId, favorited } = this.get()
let newFavoritedValue = !favorited
/* no await */ setFavorited(originalStatusId, newFavoritedValue)
@ -90,9 +107,7 @@
this.refs.favoriteIcon.animate(FAVORITE_ANIMATION)
}
},
onReblogClick (e) {
e.preventDefault()
e.stopPropagation()
reblog () {
let { originalStatusId, reblogged } = this.get()
let newRebloggedValue = !reblogged
/* no await */ setReblogged(originalStatusId, newRebloggedValue)
@ -100,9 +115,7 @@
this.refs.reblogIcon.animate(REBLOG_ANIMATION)
}
},
onReplyClick (e) {
e.preventDefault()
e.stopPropagation()
reply () {
requestAnimationFrame(() => {
let { uuid } = this.get()
let { repliesShown } = this.store.get()
@ -185,4 +198,4 @@
optionsKey: ({ uuid }) => `options-${uuid}`
}
}
</script>
</script>

View File

@ -5,6 +5,7 @@
focusSelector={virtualProps.focusSelector}
index={virtualIndex}
length={virtualLength}
{active}
on:recalculateHeight />
<script>
import Notification from '../status/Notification.html'
@ -14,4 +15,4 @@
Notification
}
}
</script>
</script>

View File

@ -2,8 +2,10 @@
timelineType={virtualProps.timelineType}
timelineValue={virtualProps.timelineValue}
focusSelector={virtualProps.focusSelector}
shortcutScope={virtualKey}
index={virtualIndex}
length={virtualLength}
active={active}
on:recalculateHeight />
<script>
import Status from '../status/Status.html'
@ -13,4 +15,4 @@
Status
}
}
</script>
</script>

View File

@ -18,6 +18,8 @@
{/if}
</div>
</VirtualListContainer>
<ScrollListShortcuts bind:items=$visibleItems
itemToKey={(visibleItem) => visibleItem.key} />
<style>
.virtual-list {
position: relative;
@ -28,6 +30,7 @@
import VirtualListLazyItem from './VirtualListLazyItem'
import VirtualListFooter from './VirtualListFooter.html'
import VirtualListHeader from './VirtualListHeader.html'
import ScrollListShortcuts from '../shortcut/ScrollListShortcuts.html'
import { virtualListStore } from './virtualListStore'
import throttle from 'lodash-es/throttle'
import { mark, stop } from '../../_utils/marks'
@ -64,6 +67,7 @@
stop('set items')
})
this.observe('allVisibleItemsHaveHeight', allVisibleItemsHaveHeight => {
this.calculateListOffset()
if (allVisibleItemsHaveHeight) {
this.fire('initializedVisibleItems')
}
@ -98,7 +102,8 @@
VirtualListContainer,
VirtualListLazyItem,
VirtualListFooter,
VirtualListHeader
VirtualListHeader,
ScrollListShortcuts
},
computed: {
distanceFromBottom: ({ $scrollHeight, $scrollTop, $offsetHeight }) => {
@ -123,4 +128,4 @@
}
}
}
</script>
</script>

View File

@ -1,12 +1,14 @@
<div class="virtual-list-item list-item {shown ? 'shown' : ''}"
id={`list-item-${key}`}
aria-hidden={!shown}
virtual-list-key={key}
ref:node
style="transform: translateY({offset}px);" >
<svelte:component this={component}
virtualProps={props}
virtualIndex={index}
virtualLength={$length}
virtualKey={key}
active={active}
on:recalculateHeight="doRecalculateHeight()"/>
</div>
<style>
@ -50,7 +52,8 @@
},
store: () => virtualListStore,
computed: {
'shown': ({ $itemHeights, key }) => $itemHeights[key] > 0
'shown': ({ $itemHeights, key }) => $itemHeights[key] > 0,
'active': ({ $activeItem, key }) => $activeItem === key
},
methods: {
doRecalculateHeight () {
@ -64,4 +67,4 @@
}
}
}
</script>
</script>

View File

@ -22,6 +22,7 @@ virtualListStore.computeForRealm('scrollHeight', 0)
virtualListStore.computeForRealm('offsetHeight', 0)
virtualListStore.computeForRealm('listOffset', 0)
virtualListStore.computeForRealm('itemHeights', {})
virtualListStore.computeForRealm('activeItem', null)
virtualListStore.compute('rawVisibleItems',
['items', 'scrollTop', 'itemHeights', 'offsetHeight', 'showHeader', 'headerHeight', 'listOffset'],

View File

@ -36,6 +36,10 @@ export const importLoggedInObservers = () => import(
/* webpackChunkName: 'loggedInObservers.js' */ '../_store/observers/loggedInObservers.js'
).then(getDefault)
export const importNavShortcuts = () => import(
/* webpackChunkName: 'NavShortcuts' */ '../_components/NavShortcuts.html'
).then(getDefault)
export const importEmojiMart = () => import(
/* webpackChunkName: 'createEmojiMartPickerFromData.js' */ '../_react/createEmojiMartPickerFromData.js'
).then(getDefault)

View File

@ -0,0 +1,64 @@
import {
getScrollContainer,
getOffsetHeight } from './scrollContainer'
import { smoothScroll } from './smoothScroll'
function getTopOverlay () {
return document.getElementById('main-nav').clientHeight
}
export function isVisible (element) {
if (!element) {
return false
}
let rect = element.getBoundingClientRect()
let offsetHeight = getOffsetHeight()
let topOverlay = getTopOverlay()
return rect.top < offsetHeight && rect.bottom >= topOverlay
}
export function firstVisibleElementIndex (items, itemElementFunction) {
let offsetHeight = getOffsetHeight()
let topOverlay = getTopOverlay()
let len = items.length
let i = -1
while (++i < len) {
let element = itemElementFunction(items[i])
if (!element) {
continue
}
let rect = element.getBoundingClientRect()
if (rect.top < offsetHeight && rect.bottom >= topOverlay) {
let firstComplete = i
if (rect.top < topOverlay && i < (len - 1)) {
firstComplete = i + 1
}
return { first: i, firstComplete }
}
}
return -1
}
export function scrollIntoViewIfNeeded (element) {
let rect = element.getBoundingClientRect()
let topOverlay = getTopOverlay()
let offsetHeight = getOffsetHeight()
let scrollY = 0
if (rect.top < topOverlay) {
scrollY = topOverlay
} else if (rect.bottom > offsetHeight) {
let height = rect.bottom - rect.top
if ((offsetHeight - topOverlay) > height) {
scrollY = offsetHeight - height
} else {
// if element height is too great to fit,
// prefer showing the top of the element
scrollY = topOverlay
}
} else {
return // not needed
}
let scrollContainer = getScrollContainer()
let scrollTop = scrollContainer.scrollTop
smoothScroll(scrollContainer, scrollTop + rect.top - scrollY)
}

View File

@ -0,0 +1,181 @@
// A map of scopeKey to KeyMap
let scopeKeyMaps
// Current scope, starting with 'global'
let currentScopeKey
// Previous current scopes
let scopeStack
// Currently active prefix map
let prefixMap
// Scope in which prefixMap is valid
let prefixMapScope
// A map of key to components or other KeyMaps
function KeyMap () {}
export function initShortcuts () {
currentScopeKey = 'global'
scopeStack = []
scopeKeyMaps = null
prefixMap = null
prefixMapScope = null
}
initShortcuts()
// Sets scopeKey as current scope.
export function pushShortcutScope (scopeKey) {
scopeStack.push(currentScopeKey)
currentScopeKey = scopeKey
}
// Go back to previous current scope.
export function popShortcutScope (scopeKey) {
if (scopeKey !== currentScopeKey) {
return
}
currentScopeKey = scopeStack.pop()
}
// Call component.onKeyDown(event) when a key in keys is pressed
// in the given scope.
export function addToShortcutScope (scopeKey, keys, component) {
if (scopeKeyMaps == null) {
window.addEventListener('keydown', onKeyDown)
scopeKeyMaps = {}
}
let keyMap = scopeKeyMaps[scopeKey]
if (!keyMap) {
keyMap = new KeyMap()
scopeKeyMaps[scopeKey] = keyMap
}
mapKeys(keyMap, keys, component)
}
export function removeFromShortcutScope (scopeKey, keys, component) {
let keyMap = scopeKeyMaps[scopeKey]
if (!keyMap) {
return
}
unmapKeys(keyMap, keys, component)
if (Object.keys(keyMap).length === 0) {
delete scopeKeyMaps[scopeKey]
}
if (Object.keys(scopeKeyMaps).length === 0) {
scopeKeyMaps = null
window.removeEventListener('keydown', onKeyDown)
}
}
const FALLBACK_KEY = '__fallback__'
// Call component.onKeyDown(event) if no other shortcuts handled
// the current key.
export function addShortcutFallback (scopeKey, component) {
addToShortcutScope(scopeKey, FALLBACK_KEY, component)
}
export function removeShortcutFallback (scopeKey, component) {
removeFromShortcutScope(scopeKey, FALLBACK_KEY, component)
}
// Direct the given event to the appropriate component in the given
// scope for the event's key.
export function onKeyDownInShortcutScope (scopeKey, event) {
if (prefixMap) {
let handled = false
if (prefixMap && prefixMapScope === scopeKey) {
handled = handleEvent(scopeKey, prefixMap, event.key, event)
}
prefixMap = null
prefixMapScope = null
if (handled) {
return
}
}
let keyMap = scopeKeyMaps[scopeKey]
if (!keyMap) {
return
}
if (!handleEvent(scopeKey, keyMap, event.key, event)) {
handleEvent(scopeKey, keyMap, FALLBACK_KEY, event)
}
}
function handleEvent (scopeKey, keyMap, key, event) {
let value = keyMap[key]
if (!value) {
return false
}
if (KeyMap.prototype.isPrototypeOf(value)) {
prefixMap = value
prefixMapScope = scopeKey
} else {
value.onKeyDown(event)
}
return true
}
function onKeyDown (event) {
if (!acceptShortcutEvent(event)) {
return
}
onKeyDownInShortcutScope(currentScopeKey, event)
}
function mapKeys (keyMap, keys, component) {
keys.split('|').forEach(
(seq) => {
let seqArray = seq.split(' ')
let prefixLen = seqArray.length - 1
let currentMap = keyMap
let i = -1
while (++i < prefixLen) {
let prefixMap = currentMap[seqArray[i]]
if (!prefixMap) {
prefixMap = new KeyMap()
currentMap[seqArray[i]] = prefixMap
}
currentMap = prefixMap
}
currentMap[seqArray[prefixLen]] = component
})
}
function unmapKeys (keyMap, keys, component) {
keys.split('|').forEach(
(seq) => {
let seqArray = seq.split(' ')
let prefixLen = seqArray.length - 1
let currentMap = keyMap
let i = -1
while (++i < prefixLen) {
let prefixMap = currentMap[seqArray[i]]
if (!prefixMap) {
return
}
currentMap = prefixMap
}
let lastKey = seqArray[prefixLen]
if (currentMap[lastKey] === component) {
delete currentMap[lastKey]
}
})
}
function acceptShortcutEvent (event) {
if (event.metaKey || event.ctrlKey || event.shiftKey) {
return
}
let target = event.target
if (target && (target.isContentEditable ||
target.tagName === 'INPUT' ||
target.tagName === 'TEXTAREA' ||
target.tagName === 'SELECT')) {
return false
}
return true
}

View File

@ -61,15 +61,13 @@ function testSupportsSmoothScroll () {
const smoothScrollSupported = process.browser && testSupportsSmoothScroll()
export function smoothScrollToTop (node) {
export function smoothScroll (node, top) {
if (smoothScrollSupported) {
console.log('using native smooth scroll')
return node.scrollTo({
top: 0,
top: top,
behavior: 'smooth'
})
} else {
console.log('using polyfilled smooth scroll')
return smoothScrollPolyfill(node, 'scrollTop', 0)
return smoothScrollPolyfill(node, 'scrollTop', top)
}
}

View File

@ -0,0 +1,95 @@
import {
getUrl,
modalDialogContents,
notificationsNavButton } from '../utils'
import { loginAsFoobar } from '../roles'
fixture`024-shortcuts-navigation.js`
.page`http://localhost:4002`
test('Shortcut g+l goes to the local timeline', async t => {
await loginAsFoobar(t)
await t
.expect(getUrl()).eql('http://localhost:4002/')
.pressKey('g l')
.expect(getUrl()).contains('/local')
})
test('Shortcut g+t goes to the federated timeline', async t => {
await loginAsFoobar(t)
await t
.expect(getUrl()).eql('http://localhost:4002/')
.pressKey('g t')
.expect(getUrl()).contains('/federated')
})
test('Shortcut g+h goes back to the home timeline', async t => {
await loginAsFoobar(t)
await t
.expect(getUrl()).eql('http://localhost:4002/')
.click(notificationsNavButton)
.pressKey('g h')
})
test('Shortcut g+f goes to the favorites', async t => {
await loginAsFoobar(t)
await t
.expect(getUrl()).eql('http://localhost:4002/')
.pressKey('g f')
.expect(getUrl()).contains('/favorites')
})
test('Shortcut g+c goes to the community page', async t => {
await loginAsFoobar(t)
await t
.expect(getUrl()).eql('http://localhost:4002/')
.pressKey('g c')
.expect(getUrl()).contains('/community')
})
test('Shortcut s goes to the search page', async t => {
await loginAsFoobar(t)
await t
.expect(getUrl()).eql('http://localhost:4002/')
.pressKey('s')
.expect(getUrl()).contains('/search')
})
test('Shortcut backspace goes back from favorites', async t => {
await loginAsFoobar(t)
await t
.expect(getUrl()).eql('http://localhost:4002/')
.pressKey('g t')
.expect(getUrl()).contains('/federated')
.pressKey('g f')
.expect(getUrl()).contains('/favorites')
.pressKey('Backspace')
.expect(getUrl()).contains('/federated')
})
test('Shortcut h toggles shortcut help dialog', async t => {
await loginAsFoobar(t)
await t
.expect(getUrl()).eql('http://localhost:4002/')
.pressKey('h')
.expect(modalDialogContents.exists).ok()
.expect(modalDialogContents.hasClass('shortcut-help-modal-dialog')).ok()
.pressKey('h')
.expect(modalDialogContents.exists).notOk()
})
test('Global shortcut has no effects while in modal dialog', async t => {
await loginAsFoobar(t)
await t
.expect(getUrl()).eql('http://localhost:4002/')
.pressKey('g f')
.expect(getUrl()).contains('/favorites')
.pressKey('h')
.expect(modalDialogContents.exists).ok()
.pressKey('s') // does nothing
.expect(getUrl()).contains('/favorites')
.pressKey('Backspace')
.expect(modalDialogContents.exists).notOk()
.pressKey('s') // now works
.expect(getUrl()).contains('/search')
})

View File

@ -0,0 +1,128 @@
import { Selector as $ } from 'testcafe'
import {
getNthFavorited,
getNthStatus,
getNthStatusContent,
getNthStatusMedia,
getNthStatusSensitiveMediaButton,
getNthStatusSpoiler,
getUrl,
scrollToStatus } from '../utils'
import { homeTimeline } from '../fixtures'
import { loginAsFoobar } from '../roles'
import { indexWhere } from '../../src/routes/_utils/arrays'
fixture`025-shortcuts-status.js`
.page`http://localhost:4002`
function isNthStatusActive (idx) {
return getNthStatus(idx).hasClass('status-active')
}
async function activateStatus (t, idx) {
let timeout = 20000
for (let i = 0; i <= idx; i++) {
await t.expect(getNthStatus(i).exists).ok({ timeout })
.pressKey('j')
.expect(getNthStatus(i).hasClass('status-active')).ok()
}
}
test('Shortcut j/k change the active status', async t => {
await loginAsFoobar(t)
await t
.expect(getUrl()).eql('http://localhost:4002/')
.expect(getNthStatus(0).exists).ok({ timeout: 30000 })
.expect(isNthStatusActive(0)).notOk()
.pressKey('j')
.expect(isNthStatusActive(0)).ok()
.pressKey('j')
.expect(isNthStatusActive(1)).ok()
.pressKey('j')
.expect(isNthStatusActive(2)).ok()
.pressKey('j')
.expect(isNthStatusActive(3)).ok()
.pressKey('k')
.expect(isNthStatusActive(2)).ok()
.pressKey('k')
.expect(isNthStatusActive(1)).ok()
.pressKey('k')
.expect(isNthStatusActive(0)).ok()
.expect(isNthStatusActive(1)).notOk()
.expect(isNthStatusActive(2)).notOk()
.expect(isNthStatusActive(3)).notOk()
})
test('Shortcut j goes to the first visible status', async t => {
await loginAsFoobar(t)
await t
.expect(getUrl()).eql('http://localhost:4002/')
await scrollToStatus(t, 10)
await t
.expect(getNthStatus(10).exists).ok({ timeout: 30000 })
.pressKey('j')
.expect($('.status-active').exists).ok()
.expect($('.status-active').getBoundingClientRectProperty('top')).gte(0)
})
test('Shortcut o opens active status, backspace goes back', async t => {
await loginAsFoobar(t)
await t
.expect(getUrl()).eql('http://localhost:4002/')
.expect(getNthStatus(2).exists).ok({ timeout: 30000 })
.pressKey('j') // activates status 0
.pressKey('j') // activates status 1
.pressKey('j') // activates status 2
.expect(isNthStatusActive(2)).ok()
.pressKey('o')
.expect(getUrl()).contains('/statuses/')
.pressKey('Backspace')
.expect(isNthStatusActive(2)).ok()
})
test('Shortcut x shows/hides spoilers', async t => {
let idx = indexWhere(homeTimeline, _ => _.spoiler === 'kitten CW')
await loginAsFoobar(t)
await t
.expect(getUrl()).eql('http://localhost:4002/')
await activateStatus(t, idx)
await t
.expect(getNthStatus(idx).hasClass('status-active')).ok()
.expect(getNthStatusSpoiler(idx).innerText).contains('kitten CW')
.expect(getNthStatusContent(idx).hasClass('shown')).notOk()
.pressKey('x')
.expect(getNthStatusContent(idx).hasClass('shown')).ok()
.pressKey('x')
.expect(getNthStatusContent(idx).hasClass('shown')).notOk()
})
test('Shortcut y shows/hides sensitive image', async t => {
let idx = indexWhere(homeTimeline, _ => _.content === "here's a secret kitten")
await loginAsFoobar(t)
await t
.expect(getUrl()).eql('http://localhost:4002/')
await activateStatus(t, idx)
await t
.expect(getNthStatus(idx).hasClass('status-active')).ok()
.expect(getNthStatusSensitiveMediaButton(idx).exists).ok()
.expect(getNthStatusMedia(idx).exists).notOk()
.pressKey('y')
.expect(getNthStatusMedia(idx).exists).ok()
.pressKey('y')
.expect(getNthStatusMedia(idx).exists).notOk()
})
test('Shortcut f toggles favorite status', async t => {
let idx = indexWhere(homeTimeline, _ => _.content === 'this is unlisted')
await loginAsFoobar(t)
await t
.expect(getUrl()).eql('http://localhost:4002/')
.expect(getNthStatus(idx).exists).ok({ timeout: 30000 })
.expect(getNthFavorited(idx)).eql('false')
.pressKey('j '.repeat(idx + 1))
.expect(getNthStatus(idx).hasClass('status-active')).ok()
.pressKey('f')
.expect(getNthFavorited(idx)).eql('true')
.pressKey('f')
.expect(getNthFavorited(idx)).eql('false')
})

View File

@ -0,0 +1,214 @@
/* global describe, it, beforeEach, afterEach */
import {
initShortcuts,
addShortcutFallback,
addToShortcutScope,
onKeyDownInShortcutScope,
popShortcutScope,
pushShortcutScope,
removeFromShortcutScope } from '../../src/routes/_utils/shortcuts'
import assert from 'assert'
function KeyDownEvent (key) {
this.key = key
this.metaKey = false
this.ctrlKey = false
this.shiftKey = false
this.target = null
}
function Component (keyDownFunction) {
this.lastEvent = null
this.eventCount = 0
this.onKeyDown = function (event) {
this.lastEvent = event
this.eventCount++
}
this.pressed = function () {
return this.eventCount > 0
}
this.notPressed = function () {
return this.eventCount === 0
}
}
describe('test-shortcuts.js', function () {
let eventListener
let originalWindow
beforeEach(function () {
originalWindow = global.window
global.window = {
addEventListener: function (eventname, listener) {
assert.strictEqual(eventname, 'keydown')
eventListener = listener
},
removeEventListener: function (eventname, listener) {
assert.strictEqual(eventname, 'keydown')
if (listener === eventListener) {
eventListener = null
}
}
}
initShortcuts()
})
afterEach(function () {
global.window = originalWindow
})
it('sets and unsets event listener', function () {
let component = new Component()
addToShortcutScope('global', 'k', component)
assert(eventListener != null, 'event listener not set')
removeFromShortcutScope('global', 'k', component)
assert(eventListener == null, 'event listener not reset')
})
it('forwards the right global key event', function () {
let component = new Component()
addToShortcutScope('global', 'k', component)
eventListener(new KeyDownEvent('l'))
assert.ok(component.notPressed())
let kEvent = new KeyDownEvent('k')
eventListener(kEvent)
assert.ok(component.pressed())
assert.strictEqual(component.lastEvent, kEvent)
})
it('register multiple keys', function () {
let lmn = new Component()
addToShortcutScope('global', 'l|m|n', lmn)
eventListener(new KeyDownEvent('x'))
assert.strictEqual(lmn.eventCount, 0)
eventListener(new KeyDownEvent('m'))
assert.strictEqual(lmn.eventCount, 1)
eventListener(new KeyDownEvent('l'))
assert.strictEqual(lmn.eventCount, 2)
eventListener(new KeyDownEvent('n'))
assert.strictEqual(lmn.eventCount, 3)
})
it('skips events with modifiers', function () {
let component = new Component()
addToShortcutScope('global', 'k', component)
let kEvent = new KeyDownEvent('k')
kEvent.shiftKey = true
eventListener(kEvent)
assert.ok(component.notPressed())
kEvent = new KeyDownEvent('k')
kEvent.ctrlKey = true
eventListener(kEvent)
assert.ok(component.notPressed())
kEvent = new KeyDownEvent('k')
kEvent.metaKey = true
eventListener(kEvent)
assert.ok(component.notPressed())
})
it('skips events for editable elements', function () {
let component = new Component()
addToShortcutScope('global', 'k', component)
let kEvent = new KeyDownEvent('k')
kEvent.target = { isContentEditable: true }
eventListener(kEvent)
assert.ok(component.notPressed())
})
it('handles multi-key events', function () {
let a = new Component()
let ga = new Component()
let gb = new Component()
addToShortcutScope('global', 'a', a)
addToShortcutScope('global', 'g a', ga)
addToShortcutScope('global', 'g b', gb)
eventListener(new KeyDownEvent('g'))
eventListener(new KeyDownEvent('a'))
assert.ok(ga.pressed())
assert.ok(gb.notPressed())
assert.ok(a.notPressed())
})
it('falls back to single-key events if no sequence matches', function () {
let b = new Component()
let ga = new Component()
addToShortcutScope('global', 'b', b)
addToShortcutScope('global', 'g a', ga)
eventListener(new KeyDownEvent('g'))
eventListener(new KeyDownEvent('b'))
assert.ok(b.pressed())
assert.ok(ga.notPressed())
})
it('sends unhandled events to fallback', function () {
let fallback = new Component()
addToShortcutScope('global', 'b', new Component())
addShortcutFallback('global', fallback)
eventListener(new KeyDownEvent('x'))
assert.ok(fallback.pressed())
})
it('directs events to appropriate component in arbitrary scope', function () {
let globalB = new Component()
let inScopeB = new Component()
addToShortcutScope('global', 'b', globalB)
addToShortcutScope('inscope', 'b', inScopeB)
onKeyDownInShortcutScope('inscope', new KeyDownEvent('b'))
assert.ok(inScopeB.pressed())
assert.ok(globalB.notPressed())
})
it('makes shortcuts modal', function () {
let globalA = new Component()
let globalB = new Component()
let modal1A = new Component()
let modal2A = new Component()
addToShortcutScope('global', 'a', globalA)
addToShortcutScope('global', 'b', globalB)
addToShortcutScope('modal1', 'a', modal1A)
addToShortcutScope('modal2', 'a', modal2A)
pushShortcutScope('modal1')
pushShortcutScope('modal2')
eventListener(new KeyDownEvent('b'))
assert.ok(globalB.notPressed())
eventListener(new KeyDownEvent('a'))
assert.ok(globalA.notPressed())
assert.ok(modal1A.notPressed())
assert.ok(modal2A.pressed())
popShortcutScope('modal2')
eventListener(new KeyDownEvent('a'))
assert.ok(globalA.notPressed())
assert.ok(modal1A.pressed())
popShortcutScope('modal1')
eventListener(new KeyDownEvent('a'))
assert.ok(globalA.pressed())
})
})