For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt, and this page is available as Markdown at /api/angular-lynx/hardware/motion.md.

LynxMotion

Reads the phone's motion sensors and compass, and hears it shaken: the accelerometer, the gyroscope, the orientation they make together, and the heading. Lynx has no DeviceMotionEvent or DeviceOrientationEvent. import { LynxMotion } from '@blotch/angular-lynx';

Use it for shake to undo or to report a bug, cards that tilt with the phone, a level or a compass.

Turn it on

Add motion to the build target's options in angular.json:

angular.json
"options": {
  "motion": true
}

What it adds:

  • iOS: the module that reads Core Motion and CLLocationManager's heading. It needs no reason string: none of the sensors needs a permission.
  • Android: the module that reads SensorManager. It needs no permission either.

Without it, the native code is left out of both apps, so they never sample anything. A watch never calls back, and availability() reports no sensors. Nothing rejects. The web preview reads the browser's events either way.

See Turn on device features for every setting.

Usage

import { Component, inject, signal } from '@angular/core';
import { LYNX_ELEMENTS, LynxMotion } from '@blotch/angular-lynx';
import { Drafts } from './drafts';

@Component({
  selector: 'app-level',
  imports: [LYNX_ELEMENTS],
  template: `
    <view
      class="bubble"
      [style.transform]="'translateX(' + tilt() * 4 + 'px)'"
    ></view>
    <text>{{ tilt().toFixed(0) }}°</text>
  `,
})
export class Level {
  readonly #motion = inject(LynxMotion);
  readonly #drafts = inject(Drafts);
  protected readonly tilt = signal(0);

  constructor() {
    // Called from the constructor, both stop when the component is destroyed.
    this.#motion.watchOrientation({ interval: 50 }, ({ gamma }) =>
      this.tilt.set(gamma),
    );
    this.#motion.onShake(() => this.#drafts.undo());
  }
}

Drafts stands for the app's own service.

Ask for no more samples than the screen needs. Every sample is work for the thread Angular runs on, which also lays out the page and runs its animations. The default interval is 16 ms, about one a frame. A compass or a level is fine at 50 or 100.

API

LynxMotion

@Injectable({ providedIn: 'root' })
class LynxMotion {
  // Each watch also takes the handler alone: watchHeading(handler).
  watchAcceleration(
    options: LynxMotionOptions,
    handler: (sample: LynxAcceleration) => void,
  ): () => void;
  watchRotation(
    options: LynxMotionOptions,
    handler: (sample: LynxRotationRate) => void,
  ): () => void;
  watchOrientation(
    options: LynxMotionOptions,
    handler: (sample: LynxOrientation) => void,
  ): () => void;
  watchHeading(
    options: LynxMotionOptions,
    handler: (sample: LynxHeading) => void,
  ): () => void;
  onShake(handler: () => void, options?: LynxShakeOptions): () => void;
  availability(): Promise<LynxMotionAvailability>;
}

type LynxMotionOptions = { interval?: number; injector?: Injector };
type LynxShakeOptions = { injector?: Injector };

Each watch method calls handler with a sample about every interval milliseconds, until the function it returns is called. It takes the options or leaves them out (watchHeading(handler)).

  • interval is 16 unless it's given, at least 5, and at most 2,147,483,647 (about 24 days), the longest a timer waits.
  • interval is a target, not a guarantee. A sample up to a quarter of the interval early (4 ms at most) still counts, to allow for the sensor's jitter.
  • Each watch is spaced by its own interval. The sensor runs at the shortest interval any watch asks for, and a slower watch beside a faster one is spaced over every sample it sends. (iOS's compass reports as it turns rather than at a rate, and in the web preview the browser sets the rate.) Where the intervals don't divide, a sensor sampling at the faster interval gives the slower watch the first sample its interval lets through, a little early included: a 40 ms watch beside a 25 ms one gets one every 50 ms, and a 27 ms watch takes the sample at 25.
  • A sample that comes too soon isn't lost if it's the last. When nothing newer follows it within the interval, such as a compass held still, it arrives then, with its own timestamp.
  • A new watch only gets samples measured after it started, never one already on its way to the app.
  • Samples arrive in batches, up to one batch every 16 ms. So a fast watch's handler can run a few times in a row.
  • Called from an injection context, such as a constructor, a watch also stops when the component or service is destroyed. Pass an injector to tie it to another one.
  • A sensor runs only while something watches it, and stops while the app is in the background.
PlatformSensors
iOSCore Motion's CMMotionManager, and CLLocationManager's heading, which asks for no location permission. The Simulator has no motion sensors
AndroidSensorManager: the accelerometer, the gyroscope, the game rotation vector for the orientation, and the rotation vector for the heading
Web previewThe page's devicemotion and deviceorientation events
Unit tests with the testing libraryWhat emitMotion(), setHeading() and shakeDevice() send
Lynx ExplorerNone
  • The Android emulator's sensors are in its extended controls (Virtual sensors).
  • Safari on iOS sends the web events only after the page calls DeviceMotionEvent.requestPermission() from a tap. Desktop browsers send none.

The axes are the phone's own, as on the web: x to the right of the screen, y up it, and z out of its face. They don't turn with the screen in landscape.

watchAcceleration()

type LynxAcceleration = { x: number; y: number; z: number; timestamp: number };

The acceleration the phone measures in m/s², with gravity, as DeviceMotionEvent.accelerationIncludingGravity gives it. timestamp is when it was measured, in milliseconds since the epoch, as Date.now() counts.

A phone lying face up reads about { x: 0, y: 0, z: 9.81 } on both platforms. iOS measures in g the other way round, which the shell converts.

watchRotation()

type LynxRotationRate = { x: number; y: number; z: number; timestamp: number };

How fast the phone turns around each axis, in radians a second, counterclockwise as seen from the axis's positive end. On iOS it's Core Motion's rotation rate, which corrects the gyroscope's drift.

The web's rotationRate gives degrees a second, as alpha, beta and gamma. Here x is beta, y is gamma and z is alpha, in radians.

watchOrientation()

type LynxOrientation = {
  alpha: number;
  beta: number;
  gamma: number;
  timestamp: number;
};

Which way the phone faces, in degrees, as DeviceOrientationEvent gives it:

  • beta tilts it forward and back (-180 to 180).
  • gamma tilts it left and right (-90 to 90).
  • alpha turns it around z (0 to 360).

A phone lying flat reads 0 for beta and gamma.

alpha counts from wherever the phone faced when the sensor started, not from north, as a DeviceOrientationEvent whose absolute is false does. Neither platform uses the compass for it, so it doesn't swing near a magnet. Read north from watchHeading().

In the web preview, a browser that sends only absolute orientation gives an alpha that counts from north.

watchHeading()

type LynxHeading = {
  magneticHeading: number;
  trueHeading: number | null;
  accuracy: number | null;
  timestamp: number;
};

magneticHeading is where the top of the phone points, in degrees clockwise from magnetic north.

  • trueHeading is from true north. Only iOS gives it, and only while the app has location access. It's null otherwise.
  • accuracy is how far off the heading may be, in degrees, or null when the platform doesn't say. A large one means the compass needs calibrating: move the phone in a figure eight.

iOS reports a new heading each time it turns by a degree, so a phone held still sends none. The last heading still arrives: one that came too soon after the reading before it reaches the watch an interval later.

onShake()

Calls handler each time the person shakes the phone, until the function it returns is called or the caller is destroyed.

The shells hear shakes from the accelerometer themselves. So listening costs the thread Angular runs on nothing until one comes.

  • A shake is a sharp, repeated movement for a quarter of a second or more: three quarters of the samples of half a second past 13 m/s². Walking or putting the phone down isn't one.
  • A long shake is heard again every three quarters of a second.
  • A shake goes to the handlers listening when the phone heard it. A handler that starts after a shake, while it's on its way to the app, doesn't get it. The system clock changing doesn't affect which handlers get it.

availability()

type LynxMotionAvailability = {
  acceleration: boolean;
  rotation: boolean;
  orientation: boolean;
  heading: boolean;
};

Which sensors the phone has. It resolves with none in Lynx Explorer, in an app built without motion, and on the iOS Simulator. The web preview can't tell, and reports what the browser has events for. It never rejects.

Testing

The testing library stands in for a phone with every sensor. emitMotion() sends a sample, setHeading() a compass heading and shakeDevice() a shake, to the watches the app has:

import {
  emitMotion,
  render,
  screen,
  waitForUpdate,
} from '@blotch/angular-lynx-testing-library';

await render(Level);
emitMotion({ orientation: { alpha: 0, beta: 0, gamma: 12 } });
await waitForUpdate();
expect(screen.getByText('12°')).toBeInTheDocument();