Soundor

Events

The Web-style pointer, wheel, key and focus events node components take, and their coordinates.

The node components take event props: onPointerDown, onClick, onDoubleClick, onKeyDown, onWheel, onFocus and the others below. onPointerDown, onPointerMove, onPointerUp, onClick, onDoubleClick, onContextMenu, onLongPress, onWheel and onKeyDown also have …Capture variants. They receive soundor:ui's Web-style events, which capture and bubble through the view's nodes as in the DOM. Portal, Modal and FocusScope take their own props; put node event handlers on the content they render.

<View
  focusable
  onPointerDown={(event) => startDrag(event.pageY)}
  onWheel={(event) => nudge(-event.deltaY)}
  onKeyDown={(event) => {
    if (event.key === 'ArrowUp') {
      nudge(1);
      event.preventDefault();
    }
  }}
/>
  • Capture and bubble: an event goes down to its target through the …Capture props, then back up through the others. Enter, leave, focus, blur and focus-visible changes do not bubble.
  • preventDefault() stops the runtime's own response: a press focusing a node, a text input's editing, a key or wheel input going on to the plugin's host (a DAW's shortcuts).
  • stopPropagation() keeps other nodes from seeing the event; stopImmediatePropagation() keeps the target's other listeners from seeing it too.
  • Pointer capture is implicit: from a press to its release, the pressed node receives the moves, wherever the pointer goes. It starts before the pointerdown listeners run, so they can lock the press (Pointer lock).
  • movementX/movementY say how far the pointer moved since its previous event, so a drag needs no starting point.
  • screenX/screenY are where the pointer is on the screen, in the editor's logical pixels: they do not move when the editor resizes or, an editor that scales, zooms, as clientX/clientY do. A drag that resizes the editor measures with them (A resize grip). A wheel event's are its clientX/clientY.
  • The wheel with Control is a zoom, as browsers take it, and a trackpad's pinch arrives in a browser as one (ctrlKey, the zoom in deltaY). It never scrolls a scroll view. Unless a listener calls preventDefault(), it goes on to the host, which in a browser zooms the page. To zoom something of your own, a waveform say, handle onWheel when event.ctrlKey is set and call preventDefault().
  • Focus: a press focuses the nearest focusable node, unless its pointerdown is prevented; Tab and Shift+Tab move through focusable nodes, in tree order, except those with tabStop={false} (Roving focus). Keys go to the focused node. Show focus with focusVisible, not focused (Focus rings).
  • key and code: key is what a press types, which depends on the layout and the modifiers; code is the physical key, as the Web names it ('KeyS', 'Digit1', 'ShiftLeft'), whatever it types. Match text and named keys ('Enter', 'ArrowUp') by key, and a shortcut whose modifiers change what it types by code: Option+S on macOS has the key 'ß' and Shift+1 on a US layout '!', but their codes are 'KeyS' and 'Digit1' (Keyboard shortcuts).
  • onContextMenu is a request to open a context menu.
  • Double clicks are the platform's: onDoubleClick fires right after the second click's onClick (Double clicks).

Context menus

contextmenu is a request for a context menu, not a right-click event. The engine recognizes every way of asking for one on any view: a secondary click (Control-click on macOS), Shift+F10 or the Context Menu key on the focused node, a touch long press, and the showContextMenu accessibility action. All of them are the same contextmenu event, for soundor:ui listeners and the onContextMenu and onContextMenuCapture props; the plugin decides what to show. It works alongside primary interactions such as onPress.

const handleContextMenu = (event: PointerEvent) => {
  event.preventDefault(); // Suppress the browser's menu for this request.
  openMenu({ x: event.pageX, y: event.pageY });
};

<View
  focusable
  accessibilityLabel="Track options"
  accessibilityActions={[{ name: 'showContextMenu' }]}
  onContextMenu={handleContextMenu}
>
  <Text>Track options</Text>
</View>;

<Pressable onPress={openSettings} onContextMenu={handleContextMenu}>
  <Text>Settings</Text>
</Pressable>;

Use pageX/pageY (the same view-relative logical pixels as clientX/clientY) to position a menu in a portal. For a pointer request, these are the pointer's coordinates. For a keyboard or accessibility request, they are the bottom-left of the target's bounds; pointerType is '', button and pointerId are -1, and no buttons are held. offsetX/offsetY are relative to the original target, even when an ancestor handles the request.

The keyboard shortcuts act on the focused node. A plain view can opt into keyboard focus with focusable. preventDefault() on keydown cancels the request. preventDefault() on contextmenu says the plugin handled it: a browser does not show its own menu (where its event is cancelable), and in a plugin's editor the shortcut does not go on to the host. Repeats of a held shortcut make no new request.

A wrapper can observe requests without advertising an accessibility action:

<View onContextMenuCapture={observeRequest}>
  <Application />
</View>

A listener never offers a context menu to assistive technology, on its node or its descendants: declare showContextMenu in the accessibilityActions of the element that has one (Accessibility). A secondary click on a node that also handles presses does not press it.

RuntimePointer and keyboardAccessibility
macOSSecondary click, Control-click, Shift+F10, Context Menu keyAXShowMenu
LinuxSecondary click, Shift+F10, Context Menu keyAT-SPI action popup
WindowsSecondary click, Shift+F10, Context Menu keyUI Automation ShowContextMenu
iOSWhat the host deliversVoiceOver action "Show context menu"
WebThe browser's menu gestures (touch long press too), Shift+F10, Context Menu keyA contextmenu the browser sends unprompted

Long presses

longpress is a gesture event on any view, through soundor:ui and the onLongPress and onLongPressCapture props. The engine recognizes it: the primary pointer held 500 ms (a Pressable's delayLongPress) without moving more than 10 logical pixels. Releasing or canceling the pointer, moving further, scrolling, pointer lock, the node leaving the tree, and preventDefault() on its pointerdown (which claims the press) end it first. pointerType says where it came from: 'touch', 'mouse' or 'pen', and '' for the accessibility longpress action. A touch held in a text input is never a long press: it is the input's own (the caret, the selection, a phone's Paste), so neither longpress nor contextmenu comes from it. A mouse held there, a secondary click and the keyboard still ask.

Its default, for a touch long press only, is a contextmenu event at the same node and point, so onContextMenu alone opens a menu on a touch screen, with no onLongPress needed. A mouse long press and the accessibility longpress action (a different request from showContextMenu) have no default. To give a touch hold another meaning, cancel it; right-click, the keyboard and assistive technology still request the menu:

<View
  onLongPress={(event) => {
    event.preventDefault(); // No contextmenu follows this hold.
    resetValue();
  }}
  onContextMenu={handleContextMenu}
/>

Event order

InvocationEvent sequence
Secondary click or macOS Control-clickcontextmenu
Shift+F10 or Context Menu keykeydown → contextmenu
Touch long presslongpress → contextmenu
Mouse long presslongpress
Accessibility showContextMenuaccessibilityaction → contextmenu
Accessibility longpressaccessibilityaction → longpress

(Unrelated pointer and key events are left out.) Each event captures and bubbles, and each arrow is a default: it runs after the event before it has gone through every listener, unless one called preventDefault(). stopPropagation() does not cancel it, and neither the presence nor the absence of a listener changes it.

A long press canceled, or whose contextmenu was canceled, is consumed: its release does not click. An unhandled one still clicks, and a Pressable never presses after its onLongPress ran.

Touch long presses need a runtime that receives touch input: the web runtime does; the VST3 runtime's desktop editors get mouse input (a touch screen's emulated mouse included), so a held finger there is a mouse long press.

On the web, Soundor makes every request from the input itself, as natively: a secondary click asks on its press (also on Windows, where browsers open their menu on release), Control-click on macOS too, and a touch hold after its 500 ms, in every browser (iOS Safari sends no contextmenu for one; on iOS the view also hides Safari's callout, except in text inputs). As in a plugin's editor, text in the view cannot be selected, so a hold never starts a selection; text inputs keep theirs. The browser's own contextmenu for that input only says whether its menu may show: not if the request was canceled. A browser may still keep a gesture for itself (scrolling, text selection) before Soundor sees it, and a shortcut the host or the system takes before the editor gets it cannot request a menu.

Keyboard shortcuts

A shortcut handled by onKeyDown on a node that holds the focus (the editor's outermost view, say, made focusable) runs while the editor has the keyboard:

<View
  focusable
  accessibilityKeyShortcuts="Control+S Meta+S"
  onKeyDown={(event) => {
    if ((event.ctrlKey || event.metaKey) && event.code === 'KeyS') {
      save();
      announce('Preset saved'); // from soundor:ui
      event.preventDefault();
    }
  }}
/>
  • code for letters and digits with modifiers, since what they type changes with Alt (Option), Shift and the layout; key for named keys. code names the key where it is on a US keyboard, so on an AZERTY one 'KeyQ' is the key labelled A: match key where the label matters more than the place.
  • Every runtime gives it: the browser's on the web; natively the key's scan code (Windows), virtual key code (macOS) or keycode (X11). Soundor Driver's keys and Testing Library's user.keyboard have the US key that types them ('!' is 'Digit1'); fireEvent.keyDown has the code it is given, else ''.
  • preventDefault() keeps the key from the host: unprevented, a DAW may take it for its own shortcut.
  • Tell assistive technology with accessibilityKeyShortcuts and, for an action that changes nothing focused, announce() (Accessibility).

Double clicks

import { Text, View } from '@soundor/react';
import { useRef, useState } from 'react';

const DEFAULT = 0.5;
const WIDTH = 260;
const NAMES = ['', 'single click', 'double click', 'triple click'];

// Drag the fader to change it, double-click it to reset it: the platform
// decides what counts as a double click (its double-click time), and every
// click says which of a series it is in event.detail.
export default function DoubleClick() {
  const [value, setValue] = useState(0.8);
  const [last, setLast] = useState('none yet');
  const dragging = useRef(false);
  // A drag ends with a release on the fader too: not a click to report.
  const dragged = useRef(false);

  const end = () => {
    dragging.current = false;
  };
  return (
    <View style={{ alignItems: 'center', gap: 10 }}>
      <Text style={{ color: '#e6e7ea' }}>Mix {Math.round(value * 100)}%</Text>
      <View
        onPointerDown={() => {
          dragging.current = true;
          dragged.current = false;
        }}
        onPointerMove={(event) => {
          if (!dragging.current || event.movementX === 0) return;
          dragged.current = true;
          setValue((v) =>
            Math.min(1, Math.max(0, v + event.movementX / WIDTH)),
          );
        }}
        onPointerUp={end}
        onPointerCancel={end}
        onClick={(event) => {
          if (!dragged.current)
            setLast(NAMES[event.detail] ?? `${event.detail} clicks`);
        }}
        onDoubleClick={() => setValue(DEFAULT)}
        style={{
          width: WIDTH,
          height: 28,
          borderRadius: 14,
          backgroundColor: '#24262c',
          cursor: 'ew-resize',
        }}
      >
        <View
          style={{
            width: `${value * 100}%`,
            height: '100%',
            borderRadius: 14,
            backgroundColor: '#9473ca',
          }}
        />
      </View>
      <Text style={{ color: '#8b8f98' }}>
        Drag to change · double-click to reset
      </Text>
      <Text style={{ color: '#8b8f98' }}>Last click: {last}</Text>
    </View>
  );
}
double-click.tsxSource

The platform decides which clicks make a series: those close enough in time (its double-click time, which the user sets) and in place, of the same button. Every click says which of a series it is in event.detail: 1 for a single click, 2 for the second of a double click, 3 for a triple click. The second is followed at once by a dblclick, also with detail 2, on the same node:

<View
  onDoubleClick={() => setValue(DEFAULT)}
  onClick={(event) => {
    if (event.detail === 1) select();
  }}
/>
  • A double click is two clicks first: onClick runs for both, so code that should not run for a double click's first click (opening something, say) has to wait, or be harmless when undone by the double click.
  • The same node: dblclick goes where the second click went, the deepest node holding both its press and its release.
  • Other events have no count: detail is 0 for pointerdown, pointerup and the rest.
  • The platform's time: the VST3 runtime reads macOS's and Windows' setting, and on Linux the desktop's (Net/DoubleClickTime, as GNOME and KDE publish it), else 400 ms; in a browser it is the browser's count.
  • In tests there is no time: user.dblClick and Soundor Driver's dblclick() say which click of a series each one is.

Focus rings

A press focuses what it presses, so a ring drawn while a node is focused appears on every click. As CSS's :focus-visible, node.focusVisible says whether the focus should show: not when a press gave it, until a key is pressed (not a shortcut nor a modifier on its own); when Tab, a screen reader or code moved it after a key; and always in a text input. onFocusVisibleChange fires whenever it changes, with event.focusVisible, and a Pressable's state has it. Draw the ring with an outline, which takes no room, so nothing moves when it shows:

const [ring, setRing] = useState(false);

<View
  focusable
  onFocusVisibleChange={(event) => setRing(event.focusVisible)}
  style={{
    borderRadius: 42,
    outlineWidth: ring ? 2 : 0,
    outlineOffset: 2,
    outlineColor: '#9473ca',
  }}
/>;

Both runtimes decide it by these rules, the web runtime too, rather than by the browser's own.

Roving focus

A composite widget (a list, a radio group, a toolbar, a group of plot handles) is one Tab stop, and the arrow keys move focus among its items: the WAI-ARIA roving tabindex. Give every item focusable and all but one tabStop={false}: Tab and Shift+Tab skip those, in every runtime and in a FocusScope, while a press, focus() and assistive technology still focus them. A focused item still receives keys and has focusVisible, and assistive technology is told the same about it as about any other. From an item that is not a Tab stop, Tab goes on to the next Tab stop after it in the tree, and Shift+Tab to the one before, so focus leaves the widget either way:

const [active, setActive] = useState(0);
const items = useRef<(UiNode | null)[]>([]);

const move = (index: number) => {
  const next = Math.max(0, Math.min(presets.length - 1, index));
  setActive(next);
  items.current[next]?.focus();
};

<View accessibilityRole="listbox" accessibilityLabel="Presets">
  {presets.map((name, index) => (
    <Pressable
      key={name}
      ref={(node) => {
        items.current[index] = node;
      }}
      accessibilityRole="option"
      accessibilityState={{ selected: index === active }}
      tabStop={index === active}
      onFocus={() => setActive(index)}
      onKeyDown={(event) => {
        if (event.key === 'ArrowDown') move(index + 1);
        if (event.key === 'ArrowUp') move(index - 1);
      }}
      onPress={() => load(name)}
    >
      <Text>{name}</Text>
    </Pressable>
  ))}
</View>;

The item that stays a Tab stop is where Tab enters the widget: the selected one, or the one that last had focus.

Coordinates

Layout and view-relative positions use the view's logical pixels. Screen positions use the editor's logical pixels:

SpaceRelative toWhere
LocalThe event's targetevent.locationX, event.locationY
ParentThe parent's box (scrolling aside)node.layout
SurfaceThe plugin view's top-left cornerevent.pageX, event.pageY, node.getBoundingClientRect()
ScreenThe screen, in editor logical pixelsevent.screenX, event.screenY

getBoundingClientRect() is where the node shows, after its ancestors have scrolled. Device pixels (a Retina scale, a host that zooms the view) are the renderer's business and never show up in these numbers. Screen positions remain stable as the editor resizes or zooms: use their deltas for an editor resize grip. A wheel event falls back to clientX/clientY. (clientX/clientY and offsetX/offsetY are the Web names for pageX/pageY and locationX/locationY.)

Pointer lock

import { Text, View } from '@soundor/react';
import { useRef, useState } from 'react';
import type { PointerEvent } from 'soundor:ui';

// A knob that locks the pointer while it is dragged: the pointer hides, the
// screen's edges don't stop it, movementY turns the knob, and on release the
// pointer is back on the knob. The other one doesn't lock: it stops at the
// edge, and the pointer ends wherever you let go.
function Knob({ lock }: { lock: boolean }) {
  const [value, setValue] = useState(0.5);
  const dragging = useRef(false);

  const end = () => {
    dragging.current = false;
  };
  return (
    <View style={{ alignItems: 'center', gap: 8 }}>
      <View
        onPointerDown={(event: PointerEvent) => {
          dragging.current = true;
          // Turns without the lock too, if it is refused.
          if (lock) event.currentTarget?.requestPointerLock().catch(() => {});
        }}
        onPointerMove={(event: PointerEvent) => {
          if (!dragging.current) return;
          setValue((v) => Math.min(1, Math.max(0, v - event.movementY / 300)));
        }}
        onPointerUp={end}
        onPointerCancel={end}
        style={{
          width: 96,
          height: 96,
          borderRadius: 48,
          overflow: 'hidden',
          justifyContent: 'center',
          alignItems: 'center',
          backgroundColor: '#2a2c33',
          cursor: 'ns-resize',
        }}
      >
        <View
          style={{
            position: 'absolute',
            left: 0,
            right: 0,
            bottom: 0,
            height: `${value * 100}%`,
            backgroundColor: lock ? '#3a7bfd' : '#5b5e6b',
          }}
        />
        <Text style={{ color: 'white', fontSize: 16 }}>
          {Math.round(value * 100)}%
        </Text>
      </View>
      <Text style={{ color: '#9a9cab', fontSize: 12 }}>
        {lock ? 'Locks the pointer' : 'No lock'}
      </Text>
    </View>
  );
}

export default function PointerLock() {
  return (
    <View style={{ flexDirection: 'row', gap: 48 }}>
      <Knob lock />
      <Knob lock={false} />
    </View>
  );
}
pointer-lock.tsxSource

A knob or a fader can lock the pointer while it is dragged: event.currentTarget.requestPointerLock() in onPointerDown. While locked, the pointer is hidden and the screen's edges don't stop it; the events keep going to the node that locked it, their positions stay where the lock began, and movementX/movementY say how far it moved. The lock ends with the release, or exitPointerLock() from soundor:ui, and the pointer shows again where it began, on the knob.

import { View } from '@soundor/react';
import { useRef } from 'react';

function Knob({
  value,
  onChange,
}: {
  value: number;
  onChange(v: number): void;
}) {
  const dragging = useRef(false);
  return (
    <View
      style={{ cursor: 'ns-resize' }}
      onPointerDown={(event) => {
        dragging.current = true;
        event.currentTarget?.requestPointerLock().catch(() => {});
      }}
      onPointerMove={(event) => {
        if (dragging.current) onChange(value - event.movementY / 200);
      }}
      onPointerUp={() => (dragging.current = false)}
      onPointerCancel={() => (dragging.current = false)}
    />
  );
}
  • Only for a press: a lock needs a mouse or pen pressing the node (or a node in it), which is why it is asked for in onPointerDown. Otherwise requestPointerLock() rejects with a NotAllowedError; touches are never locked.
  • Keep your own drag state, as above: movementY works without the lock too, so a knob still turns if the lock is refused, stopping at the screen's edge.
  • pointerLockNode() is the node holding the lock, or null. The release still comes under the lock, which ends after it.
  • In a browser (the web runtime) the lock is the page's Pointer Lock: Escape ends it early, and Firefox says so in a banner.

Props

Prop

Type

On this page