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)}; --very-deemphasized-text-color: #{rgba(#666, 0.6)};
--status-direct-background: #{darken($body-bg-color, 5%)}; --status-direct-background: #{darken($body-bg-color, 5%)};
--status-active-background: #{lighten($body-bg-color, 2%)};
--main-theme-color: #{$main-theme-color}; --main-theme-color: #{$main-theme-color};
--warning-color: #{#e01f19}; --warning-color: #{#e01f19};
--alt-input-bg: #{rgba($main-bg-color, 0.7)}; --alt-input-bg: #{rgba($main-bg-color, 0.7)};
--muted-modal-text: #{$secondary-text-color};
--muted-modal-bg: #{transparent}; --muted-modal-bg: #{transparent};
--muted-modal-focus: #{#999}; --muted-modal-focus: #{#999};
--muted-modal-hover: #{rgba(255, 255, 255, 0.2)}; --muted-modal-hover: #{rgba(255, 255, 255, 0.2)};

View file

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

View file

@ -10,8 +10,9 @@
<button type="button" <button type="button"
class="dynamic-page-go-back" class="dynamic-page-go-back"
aria-label="Go back" aria-label="Go back"
on:click="onGoBack(event)">Back</button> on:click|preventDefault="onGoBack()">Back</button>
</div> </div>
<Shortcut key="Backspace" on:pressed="onGoBack()"/>
<style> <style>
.dynamic-page-banner { .dynamic-page-banner {
display: grid; display: grid;
@ -62,14 +63,16 @@
} }
</style> </style>
<script> <script>
import Shortcut from './shortcut/Shortcut.html'
export default { export default {
data: () => ({ data: () => ({
icon: void 0, icon: void 0,
ariaTitle: '' ariaTitle: ''
}), }),
components: { Shortcut },
methods: { methods: {
onGoBack (e) { onGoBack () {
e.preventDefault()
window.history.back() 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"> <ul class="main-nav-ul">
{#each $navPages as navPage (navPage.href)} {#each $navPages as navPage (navPage.href)}
<li class="main-nav-li"> <li class="main-nav-li">
@ -13,6 +13,13 @@
{/each} {/each}
</ul> </ul>
</nav> </nav>
{#await importNavShortcuts}
<!-- awaiting nav shortcuts promise -->
{:then component}
<svelte:component this={component}/>
{:catch error}
<!-- nav shortcuts {error} -->
{/await}
<style> <style>
.main-nav { .main-nav {
@ -47,12 +54,16 @@
</style> </style>
<script> <script>
import NavItem from './NavItem' import NavItem from './NavItem'
import { importNavShortcuts } from '../_utils/asyncModules'
import { store } from '../_store/store' import { store } from '../_store/store'
export default { export default {
store: () => store, store: () => store,
components: { components: {
NavItem NavItem
} },
data: () => ({
importNavShortcuts: importNavShortcuts()
})
} }
</script> </script>

View file

@ -156,7 +156,7 @@
</style> </style>
<script> <script>
import { store } from '../_store/store' import { store } from '../_store/store'
import { smoothScrollToTop } from '../_utils/smoothScrollToTop' import { smoothScroll } from '../_utils/smoothScroll'
import { on, emit } from '../_utils/eventBus' import { on, emit } from '../_utils/eventBus'
import { mark, stop } from '../_utils/marks' import { mark, stop } from '../_utils/marks'
import { doubleRAF } from '../_utils/doubleRAF' import { doubleRAF } from '../_utils/doubleRAF'
@ -221,7 +221,7 @@
} }
e.preventDefault() e.preventDefault()
e.stopPropagation() 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( export const importShowCopyDialog = () => import(
/* webpackChunkName: 'showCopyDialog' */ './creators/showCopyDialog' /* 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> <slot></slot>
</div> </div>
</div> </div>
<Shortcut scope="modal" key="Backspace" on:pressed="closeDialog(id)"/>
<style> <style>
:global(.modal-dialog[aria-hidden='true']) { :global(.modal-dialog[aria-hidden='true']) {
display: none; display: none;
@ -136,9 +137,13 @@
} }
</style> </style>
<script> <script>
import Shortcut from '../../shortcut/Shortcut.html'
import { A11yDialog } from '../../../_thirdparty/a11y-dialog/a11y-dialog' import { A11yDialog } from '../../../_thirdparty/a11y-dialog/a11y-dialog'
import { classname } from '../../../_utils/classname' import { classname } from '../../../_utils/classname'
import { on, emit } from '../../../_utils/eventBus' import { on, emit } from '../../../_utils/eventBus'
import {
pushShortcutScope,
popShortcutScope } from '../../../_utils/shortcuts'
export default { export default {
oncreate () { oncreate () {
@ -154,7 +159,12 @@
}) })
on('showDialog', this, this.showDialog) on('showDialog', this, this.showDialog)
on('closeDialog', this, this.closeDialog) on('closeDialog', this, this.closeDialog)
pushShortcutScope('modal')
}, },
ondestroy () {
popShortcutScope('modal')
},
components: { Shortcut },
data: () => ({ data: () => ({
// don't animate if we're showing a modal dialog on top of another modal dialog. it looks ugly // 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, 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} {/each}
</div> </div>
<ScrollListShortcuts bind:items=safeItems/>
<style> <style>
.the-list { .the-list {
position: relative; position: relative;
@ -17,6 +18,7 @@
</style> </style>
<script> <script>
import ListLazyItem from './ListLazyItem.html' import ListLazyItem from './ListLazyItem.html'
import ScrollListShortcuts from '../shortcut/ScrollListShortcuts.html'
import { listStore } from './listStore' import { listStore } from './listStore'
import { getScrollContainer } from '../../_utils/scrollContainer' import { getScrollContainer } from '../../_utils/scrollContainer'
import { getMainTopMargin } from '../../_utils/getMainTopMargin' import { getMainTopMargin } from '../../_utils/getMainTopMargin'
@ -62,8 +64,9 @@
length: ({ safeItems }) => safeItems.length length: ({ safeItems }) => safeItems.length
}, },
components: { components: {
ListLazyItem ListLazyItem,
ScrollListShortcuts
}, },
store: () => listStore store: () => listStore
} }
</script> </script>

View file

@ -4,5 +4,14 @@
virtualProps={props} virtualProps={props}
virtualIndex={index} virtualIndex={index}
virtualLength={length} virtualLength={length}
virtualKey={key}
active={active}
/> />
</div> </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() const listStore = new ListStore()
listStore.computeForRealm('activeItem', null)
listStore.computeForRealm('intersectionStates', {}) listStore.computeForRealm('intersectionStates', {})
if (process.browser && process.env.NODE_ENV !== 'production') { 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} {#if status}
<Status {index} {length} {timelineType} {timelineValue} {focusSelector} <Status {index} {length} {timelineType} {timelineValue} {focusSelector}
{status} {notification} on:recalculateHeight {status} {notification} {active} on:recalculateHeight
/> />
{:else} {:else}
<article class="notification-article" <article class="notification-article {active ? 'active' : ''}"
tabindex="0" tabindex="0"
aria-posinset={index} aria-posinset={index}
aria-setsize={length} aria-setsize={length}
@ -20,6 +20,9 @@
padding: 10px 20px; padding: 10px 20px;
border-bottom: 1px solid var(--main-border); border-bottom: 1px solid var(--main-border);
} }
.notification-article.active {
background-color: var(--status-active-background);
}
@media (max-width: 767px) { @media (max-width: 767px) {
.notification-article { .notification-article {
padding: 10px 10px; padding: 10px 10px;
@ -54,4 +57,4 @@
) )
} }
} }
</script> </script>

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -18,6 +18,8 @@
{/if} {/if}
</div> </div>
</VirtualListContainer> </VirtualListContainer>
<ScrollListShortcuts bind:items=$visibleItems
itemToKey={(visibleItem) => visibleItem.key} />
<style> <style>
.virtual-list { .virtual-list {
position: relative; position: relative;
@ -28,6 +30,7 @@
import VirtualListLazyItem from './VirtualListLazyItem' import VirtualListLazyItem from './VirtualListLazyItem'
import VirtualListFooter from './VirtualListFooter.html' import VirtualListFooter from './VirtualListFooter.html'
import VirtualListHeader from './VirtualListHeader.html' import VirtualListHeader from './VirtualListHeader.html'
import ScrollListShortcuts from '../shortcut/ScrollListShortcuts.html'
import { virtualListStore } from './virtualListStore' import { virtualListStore } from './virtualListStore'
import throttle from 'lodash-es/throttle' import throttle from 'lodash-es/throttle'
import { mark, stop } from '../../_utils/marks' import { mark, stop } from '../../_utils/marks'
@ -64,6 +67,7 @@
stop('set items') stop('set items')
}) })
this.observe('allVisibleItemsHaveHeight', allVisibleItemsHaveHeight => { this.observe('allVisibleItemsHaveHeight', allVisibleItemsHaveHeight => {
this.calculateListOffset()
if (allVisibleItemsHaveHeight) { if (allVisibleItemsHaveHeight) {
this.fire('initializedVisibleItems') this.fire('initializedVisibleItems')
} }
@ -98,7 +102,8 @@
VirtualListContainer, VirtualListContainer,
VirtualListLazyItem, VirtualListLazyItem,
VirtualListFooter, VirtualListFooter,
VirtualListHeader VirtualListHeader,
ScrollListShortcuts
}, },
computed: { computed: {
distanceFromBottom: ({ $scrollHeight, $scrollTop, $offsetHeight }) => { 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' : ''}" <div class="virtual-list-item list-item {shown ? 'shown' : ''}"
id={`list-item-${key}`}
aria-hidden={!shown} aria-hidden={!shown}
virtual-list-key={key}
ref:node ref:node
style="transform: translateY({offset}px);" > style="transform: translateY({offset}px);" >
<svelte:component this={component} <svelte:component this={component}
virtualProps={props} virtualProps={props}
virtualIndex={index} virtualIndex={index}
virtualLength={$length} virtualLength={$length}
virtualKey={key}
active={active}
on:recalculateHeight="doRecalculateHeight()"/> on:recalculateHeight="doRecalculateHeight()"/>
</div> </div>
<style> <style>
@ -50,7 +52,8 @@
}, },
store: () => virtualListStore, store: () => virtualListStore,
computed: { computed: {
'shown': ({ $itemHeights, key }) => $itemHeights[key] > 0 'shown': ({ $itemHeights, key }) => $itemHeights[key] > 0,
'active': ({ $activeItem, key }) => $activeItem === key
}, },
methods: { methods: {
doRecalculateHeight () { doRecalculateHeight () {
@ -64,4 +67,4 @@
} }
} }
} }
</script> </script>

View file

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

View file

@ -36,6 +36,10 @@ export const importLoggedInObservers = () => import(
/* webpackChunkName: 'loggedInObservers.js' */ '../_store/observers/loggedInObservers.js' /* webpackChunkName: 'loggedInObservers.js' */ '../_store/observers/loggedInObservers.js'
).then(getDefault) ).then(getDefault)
export const importNavShortcuts = () => import(
/* webpackChunkName: 'NavShortcuts' */ '../_components/NavShortcuts.html'
).then(getDefault)
export const importEmojiMart = () => import( export const importEmojiMart = () => import(
/* webpackChunkName: 'createEmojiMartPickerFromData.js' */ '../_react/createEmojiMartPickerFromData.js' /* webpackChunkName: 'createEmojiMartPickerFromData.js' */ '../_react/createEmojiMartPickerFromData.js'
).then(getDefault) ).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() const smoothScrollSupported = process.browser && testSupportsSmoothScroll()
export function smoothScrollToTop (node) { export function smoothScroll (node, top) {
if (smoothScrollSupported) { if (smoothScrollSupported) {
console.log('using native smooth scroll')
return node.scrollTo({ return node.scrollTo({
top: 0, top: top,
behavior: 'smooth' behavior: 'smooth'
}) })
} else { } else {
console.log('using polyfilled smooth scroll') return smoothScrollPolyfill(node, 'scrollTop', top)
return smoothScrollPolyfill(node, 'scrollTop', 0)
} }
} }

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())
})
})