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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions docs/guides/host-core.md
Original file line number Diff line number Diff line change
Expand Up @@ -289,6 +289,22 @@ below.
a fact's.
- `ProjectionFeatures`, `featureOn`, `offeredModes` and `rendererLabel` are the
feature switches every UI takes.
- `playButton(projection, beforeLabel, afterLabel)` is the one play button:
`{action, direction, label}`, where `action` is `pause` while playing, else
`play`, or `show` under reduced motion ("Show <after label>"). The icon is the
UI's.

**Keyboard.** These take any keydown event (DOM, React or another framework's):

- `handlePlaybackShortcut(event, projection, keeps?)`: Space plays and pauses
(`togglePlayback`) from the listening element (a toolbar, the stage's chrome)
or an element in it that doesn't use Space itself, once per press.
`spaceKeeping` lists the elements that keep Space (fields, buttons, radios,
tabs, menus, dialogs…); `keeps` adds a design system's custom elements. An
element that keeps Space but encloses the listener, such as a dialog around
the view, doesn't count. `isPlaybackShortcut` only tests.
- `rovingIndex(key, index, count, orientation?)`: where an arrow, Home or End
key moves the choice in a radio group or tab list, wrapping at either end.

The default scope is Changes (`changesOnly`, which a definition's
`presentation.changesOnly: false` turns off).
Expand Down
14 changes: 13 additions & 1 deletion packages/host/core/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@ export {
featureOn,
offeredModes,
offeredViews,
playButton,
recoveryView,
rendererLabel,
scopeChoice,
Expand All @@ -81,8 +82,19 @@ export {
viewLabel,
viewNotices,
} from './view-model.js'
export type {FeatureName, ProjectionFeatures, ScopeChoice, ScopeOption, ViewControls, ViewControlsOptions, ViewKind} from './view-model.js'
export type {
FeatureName,
PlayButton,
ProjectionFeatures,
ScopeChoice,
ScopeOption,
ViewControls,
ViewControlsOptions,
ViewKind,
} from './view-model.js'
export {useViewChoice} from './view-choice.js'
export {handlePlaybackShortcut, isPlaybackShortcut, rovingIndex, spaceKeeping} from './keyboard.js'
export type {KeyEventLike} from './keyboard.js'
export type {ViewChoice} from './view-choice.js'
export {rowDetails} from './details.js'
export {changeContextItems} from './context-items.js'
Expand Down
105 changes: 105 additions & 0 deletions packages/host/core/src/keyboard.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
// Keyboard behaviour every host UI shares: the Space shortcut for playback and roving choice among radios or tabs.
// DOM-typed and framework-free: a React, Vue or plain DOM keydown event works as it is.
import type {ProjectionController} from './projection/types.js'

/**
* Elements whose own keyboard behaviour uses Space, or that hold text: the playback shortcut leaves Space to them.
* A UI adds its design system's custom elements with `keeps` (the VS Code UI adds VSCode Elements').
*/
export const spaceKeeping: readonly string[] = [
'input:not([type="range"])',
'textarea',
'select',
'button',
'a[href]',
'summary',
'iframe',
'[contenteditable]:not([contenteditable="false"])',
...[
'button',
'checkbox',
'radio',
'switch',
'tab',
'menu',
'menuitem',
'menuitemradio',
'menuitemcheckbox',
'listbox',
'option',
'combobox',
'textbox',
'searchbox',
'treeitem',
'gridcell',
'link',
'dialog',
].map(role => `[role="${role}"]`),
]

/** What the shortcuts read of a keydown event: a DOM `KeyboardEvent` or a framework's wrapper of one. */
export interface KeyEventLike {
key: string
altKey: boolean
ctrlKey: boolean
metaKey: boolean
shiftKey: boolean
defaultPrevented: boolean
/** The focused element. */
target: EventTarget | null
/** The element listening: a toolbar, or the stage's chrome. */
currentTarget: EventTarget | null
}

const isNode = (value: EventTarget | null): value is Node => typeof Node !== 'undefined' && value instanceof Node

/**
* Whether a keydown is the playback shortcut: Space without modifiers, not yet handled, from the listening element or
* an element in it that doesn't use Space itself (`spaceKeeping`, and `keeps`). An element that uses Space but
* encloses the listener (say, a dialog the page puts the view in) doesn't count; a key from outside the listener (an
* overlay portaled elsewhere) is never the shortcut.
*/
export function isPlaybackShortcut(event: KeyEventLike, keeps: readonly string[] = []): boolean {
if (event.key !== ' ' || event.defaultPrevented || event.altKey || event.ctrlKey || event.metaKey || event.shiftKey) return false
const {target, currentTarget} = event
if (!isNode(target) || !isNode(currentTarget) || !currentTarget.contains(target)) return false
const element = target instanceof Element ? target : target.parentElement
const keeper = element?.closest([...spaceKeeping, ...keeps].join(', '))
return !keeper || keeper.contains(currentTarget)
}

/**
* Handles the playback shortcut (`isPlaybackShortcut`) in a keydown: prevents its default, then plays or pauses
* (`togglePlayback`), once per press, so a held Space doesn't flicker. Returns whether the key was the shortcut.
*/
export function handlePlaybackShortcut(
event: KeyEventLike & {repeat: boolean; preventDefault(): void},
projection: Pick<ProjectionController, 'togglePlayback'>,
keeps?: readonly string[],
): boolean {
if (!isPlaybackShortcut(event, keeps)) return false
event.preventDefault()
if (!event.repeat) projection.togglePlayback()
Comment thread
agorischek marked this conversation as resolved.
Resolved
return true
}

/**
* Where an arrow, Home or End key moves the choice in a radio group or a tab list of `count` items, from `index`,
* wrapping at either end: Right and Down step forward, Left and Up back (`orientation` keeps to one axis), Home and End
* go to the first and last. Undefined for any other key, or when there is nothing to choose.
*/
export function rovingIndex(
key: string,
index: number,
count: number,
orientation: 'horizontal' | 'vertical' | 'both' = 'both',
): number | undefined {
if (count < 1) return undefined
const forward = (orientation !== 'vertical' && key === 'ArrowRight') || (orientation !== 'horizontal' && key === 'ArrowDown')
const back = (orientation !== 'vertical' && key === 'ArrowLeft') || (orientation !== 'horizontal' && key === 'ArrowUp')
if (forward) return (index + 1 + count) % count
if (back) return (index - 1 + count) % count
if (key === 'Home') return 0
if (key === 'End') return count - 1
return undefined
}
57 changes: 8 additions & 49 deletions packages/host/core/src/ui/playback.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,77 +2,36 @@ import {useId} from 'react'
import type {KeyboardEvent, KeyboardEventHandler} from 'react'
import {EllipsisVertical, Pause, Play, StepBack, StepForward} from 'lucide-react'
import {progressForKey} from '../projection.js'
import {handlePlaybackShortcut} from '../keyboard.js'
import {playButton} from '../view-model.js'
import type {ProjectionController} from '../projection.js'
import {Button} from './components/button.js'
import {Label} from './components/label.js'
import {Range} from './components/range.js'
import {cn} from './lib/utils.js'
import {ToolbarPopover} from './toolbar-popover.js'

/** Elements whose own keyboard behavior includes Space (or that hold text), where Space keeps its meaning. */
const spaceKeeping = [
'input:not([type="range"])',
'textarea',
'select',
'button',
'a[href]',
'summary',
'iframe',
'[contenteditable]:not([contenteditable="false"])',
'[role="dialog"]',
...[
'button',
'checkbox',
'radio',
'switch',
'tab',
'menuitem',
'menuitemradio',
'menuitemcheckbox',
'option',
'combobox',
'textbox',
'searchbox',
'treeitem',
'gridcell',
'link',
].map(role => `[role="${role}"]`),
].join(', ')

/**
* A keydown handler for a toolbar or stage container: Space toggles playback (`togglePlayback`) while focus is on
* the container itself or on an element that doesn't use Space, such as the Transition slider, and not in text
* fields, buttons, radios, tabs, menus or open popovers. Held keys and modified Space are ignored.
* fields, buttons, radios, tabs, menus or open popovers. Held keys and modified Space are ignored
* (`handlePlaybackShortcut`).
*/
export function spaceTogglesPlayback(p: Pick<ProjectionController, 'togglePlayback'>): KeyboardEventHandler<HTMLElement> {
return event => {
if (event.key !== ' ' || event.defaultPrevented || event.altKey || event.ctrlKey || event.metaKey || event.shiftKey) return
const target = event.target
if (!(target instanceof Element)) return
// A Space-keeping element counts unless it encloses the container (say, the page puts the view in a dialog).
const keeper = target.closest(spaceKeeping)
if (keeper && !keeper.contains(event.currentTarget)) return
event.preventDefault()
if (!event.repeat) p.togglePlayback()
handlePlaybackShortcut(event, p)
}
}

/** The icons playback draws (`data-icon` values), which no mode icon may match. */
export const playbackIcons = ['play', 'pause', 'step-back', 'step-forward'] as const

/**
* The one play button's name: "Pause" while playing, else "Play forward" or "Play backward" by `nextDirection`; under
* reduced motion, where playing shows the endpoint at once, "Show <after label>" or "Show <before label>".
*/
export function playLabel(
/** The one play button's name (`playButton`): "Pause", "Play forward", "Play backward", or "Show <label>" under reduced motion. */
export const playLabel = (
p: Pick<ProjectionController, 'playing' | 'nextDirection' | 'reducedMotion'>,
beforeLabel: string,
afterLabel: string,
): string {
if (p.playing) return 'Pause'
if (p.reducedMotion) return `Show ${p.nextDirection === 1 ? afterLabel : beforeLabel}`
return p.nextDirection === 1 ? 'Play forward' : 'Play backward'
}
): string => playButton(p, beforeLabel, afterLabel).label

/**
* The round play/pause button (the lens, theme.css: its face takes the lens tint while playing). It calls
Expand Down
13 changes: 2 additions & 11 deletions packages/host/core/src/ui/view-controls.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import {Button} from './components/button.js'
import {SegmentedControl, SegmentedControlItem} from './components/segmented-control.js'
import {cn} from './lib/utils.js'
import type {ViewKind} from '../view-model.js'
import {rovingIndex} from '../keyboard.js'
import {ToolbarPopover} from './toolbar-popover.js'
import {closeOn, MoreContext} from './toolbar.js'

Expand Down Expand Up @@ -368,17 +369,7 @@ export function ViewSwitch({
const close = useContext(MoreContext)
const label = (kind: ViewKind) => viewName(kind, rendererTitle)
function keys(event: KeyboardEvent<HTMLDivElement>) {
const index = views.indexOf(view)
const next =
event.key === 'ArrowRight'
? (index + 1) % views.length
: event.key === 'ArrowLeft'
? (index + views.length - 1) % views.length
: event.key === 'Home'
? 0
: event.key === 'End'
? views.length - 1
: undefined
const next = rovingIndex(event.key, views.indexOf(view), views.length, 'horizontal')
if (next === undefined) return
event.preventDefault()
onViewChange(views[next]!)
Expand Down
22 changes: 22 additions & 0 deletions packages/host/core/src/view-model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -198,3 +198,25 @@ export function scopeChoice(projection: Pick<ProjectionController, 'scope' | 'sc
})),
}
}

/** The one play button: what pressing it does (`togglePlayback`), the way it goes, and its name. */
export interface PlayButton {
/** `pause` while playing; else `play`, or under reduced motion `show`, which shows the endpoint at once. */
action: 'pause' | 'play' | 'show'
/** `nextDirection`: forward from the before end, backward from the after end, else the way playback last went. */
direction: 1 | -1
/** "Pause", "Play forward", "Play backward", or under reduced motion "Show <after label>" or "Show <before label>". */
label: string
}

/** The one play button for the controller's playback, naming the revisions with the host's labels. */
export function playButton(
projection: Pick<ProjectionController, 'playing' | 'nextDirection' | 'reducedMotion'>,
beforeLabel: string,
afterLabel: string,
): PlayButton {
const {playing, nextDirection: direction, reducedMotion} = projection
if (playing) return {action: 'pause', direction, label: 'Pause'}
if (reducedMotion) return {action: 'show', direction, label: `Show ${direction === 1 ? afterLabel : beforeLabel}`}
return {action: 'play', direction, label: direction === 1 ? 'Play forward' : 'Play backward'}
}
89 changes: 89 additions & 0 deletions packages/host/core/test/keyboard.test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
import {test} from 'node:test'
import assert from 'node:assert/strict'
import {handlePlaybackShortcut, isPlaybackShortcut, playButton, rovingIndex} from '../dist/index.js'

// Just enough DOM for the shortcut's containment rules: `keeps` marks an element that uses Space itself.
class FakeElement {
constructor(parent, keeps = false) {
this.parentElement = parent
this.keeps = keeps
}
contains(other) {
for (let node = other; node; node = node.parentElement) if (node === this) return true
return false
}
closest() {
if (this.keeps) return this
return this.parentElement?.closest() ?? null
}
}
globalThis.Node = FakeElement
globalThis.Element = FakeElement

const space = (target, currentTarget, extra = {}) => ({
key: ' ',
altKey: false,
ctrlKey: false,
metaKey: false,
shiftKey: false,
defaultPrevented: false,
target,
currentTarget,
...extra,
})

test('Space on the listener or an element that leaves Space alone is the playback shortcut', () => {
const toolbar = new FakeElement(null)
const slider = new FakeElement(toolbar)
assert.equal(isPlaybackShortcut(space(toolbar, toolbar)), true)
assert.equal(isPlaybackShortcut(space(slider, toolbar)), true)
assert.equal(isPlaybackShortcut(space(slider, toolbar, {shiftKey: true})), false)
assert.equal(isPlaybackShortcut(space(slider, toolbar, {defaultPrevented: true})), false)
assert.equal(isPlaybackShortcut({...space(slider, toolbar), key: 'Enter'}), false)
})

test('Space stays with fields and controls that use it, unless one encloses the listener', () => {
const dialog = new FakeElement(null, true)
const toolbar = new FakeElement(dialog)
const button = new FakeElement(toolbar, true)
assert.equal(isPlaybackShortcut(space(button, toolbar)), false)
assert.equal(isPlaybackShortcut(space(toolbar, toolbar)), true)
const portaled = new FakeElement(null)
assert.equal(isPlaybackShortcut(space(portaled, toolbar)), false)
})

test('the shortcut toggles once per press, preventing the default of every Space it takes and of nothing else', () => {
const toolbar = new FakeElement(null)
const field = new FakeElement(toolbar, true)
let toggles = 0
const projection = {togglePlayback: () => toggles++}
const press = (target, repeat) => {
let prevented = false
const event = {...space(target, toolbar), repeat, preventDefault: () => (prevented = true)}
return {handled: handlePlaybackShortcut(event, projection), prevented}
}
assert.deepEqual(press(toolbar, false), {handled: true, prevented: true})
assert.deepEqual(press(toolbar, true), {handled: true, prevented: true})
assert.deepEqual(press(toolbar, true), {handled: true, prevented: true})
assert.equal(toggles, 1)
assert.deepEqual(press(field, false), {handled: false, prevented: false})
assert.equal(toggles, 1)
})

test('roving choice wraps, keeps to its axis, and ignores other keys', () => {
assert.equal(rovingIndex('ArrowRight', 2, 3), 0)
assert.equal(rovingIndex('ArrowUp', 0, 3), 2)
assert.equal(rovingIndex('ArrowDown', 0, 3, 'horizontal'), undefined)
assert.equal(rovingIndex('ArrowLeft', 1, 3, 'vertical'), undefined)
assert.equal(rovingIndex('End', 0, 3), 2)
assert.equal(rovingIndex('Home', 2, 3), 0)
assert.equal(rovingIndex('a', 1, 3), undefined)
assert.equal(rovingIndex('ArrowRight', 0, 0), undefined)
})

test('the play button pauses while playing, plays in its direction, and shows an endpoint under reduced motion', () => {
const p = (playing, nextDirection, reducedMotion = false) => ({playing, nextDirection, reducedMotion})
assert.deepEqual(playButton(p(true, 1), 'main', 'head'), {action: 'pause', direction: 1, label: 'Pause'})
assert.equal(playButton(p(false, -1), 'main', 'head').label, 'Play backward')
assert.deepEqual(playButton(p(false, 1, true), 'main', 'head'), {action: 'show', direction: 1, label: 'Show head'})
})
Loading
Loading