> For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt.

# `LynxMainThreadEvent`

A directive that binds [main-thread scripts](/guide/glossary.md#main-thread-script) to an element's native events, and passes them elements they can change directly. `import { LynxMainThreadEvent } from '@blotch/angular-lynx';`

:::info
Template handlers such as `(bindtap)` already run on the main thread. [Main-thread scripts](/guide/main-thread/index.md) explains when you need this API instead.
:::

## Usage

```typescript title="src/app/app.ts"
import { Component } from '@angular/core';
import {
  LYNX_ELEMENTS,
  LynxMainThreadEvent,
  mainThreadFn,
  type MainThread,
} from '@blotch/angular-lynx';

const follow = mainThreadFn((event: MainThread.TouchEvent) => {
  const touch = event.touches[0];
  if (!touch) return;
  event.currentTarget.setStyleProperty('opacity', String(touch.clientX / 300));
});

const reset = mainThreadFn((event: MainThread.TouchEvent) => {
  event.currentTarget.setStyleProperty('opacity', '1');
});

@Component({
  selector: 'app-root',
  imports: [LYNX_ELEMENTS, LynxMainThreadEvent],
  template: `
    <view [mainThreadBindtouchmove]="follow" [mainThreadBindtouchend]="reset">
      <text>Drag across me</text>
    </view>
  `,
})
export class App {
  readonly follow = follow;
  readonly reset = reset;
}
```

## API

### Inputs

```typescript
class LynxMainThreadEvent {
  mainThreadBindtap?: MainThreadFnHandle | ((...args: any[]) => any) | null;
  mainThreadCatchtap?: MainThreadFnHandle | ((...args: any[]) => any) | null;
  // … one input per cell in the table below
}
```

Each input takes a handle from [`mainThreadFn()`](/api/main-thread/main-thread-fn.md), or a function with the `'main thread'` directive.

- **Any other function works too,** such as a class method. The directive registers it on the main thread, and releases it when the input changes or the element is destroyed.
- **A method passed this way has no `this`.** Use an arrow function property if the handler needs one.
- **Set an input to `null` or `undefined`** to remove its handler.

`Bind` inputs let the event bubble to ancestors. `Catch` inputs stop it at this element.

| Event            | Bubbles                        | Stops bubbling               | Handler's event type           |
| ---------------- | ------------------------------ | ---------------------------- | ------------------------------ |
| `tap`            | `mainThreadBindtap`            | `mainThreadCatchtap`         | `MainThread.TouchEvent`        |
| `longpress`      | `mainThreadBindlongpress`      | `mainThreadCatchlongpress`   | `MainThread.TouchEvent`        |
| `touchstart`     | `mainThreadBindtouchstart`     | `mainThreadCatchtouchstart`  | `MainThread.TouchEvent`        |
| `touchmove`      | `mainThreadBindtouchmove`      | `mainThreadCatchtouchmove`   | `MainThread.TouchEvent`        |
| `touchend`       | `mainThreadBindtouchend`       | `mainThreadCatchtouchend`    | `MainThread.TouchEvent`        |
| `touchcancel`    | `mainThreadBindtouchcancel`    | `mainThreadCatchtouchcancel` | `MainThread.TouchEvent`        |
| `mousedown`      | `mainThreadBindmousedown`      | `mainThreadCatchmousedown`   | `MainThread.MouseEvent`        |
| `mousemove`      | `mainThreadBindmousemove`      | `mainThreadCatchmousemove`   | `MainThread.MouseEvent`        |
| `mouseup`        | `mainThreadBindmouseup`        | `mainThreadCatchmouseup`     | `MainThread.MouseEvent`        |
| `scroll`         | `mainThreadBindscroll`         | `mainThreadCatchscroll`      | No `MainThread` type           |
| `animationstart` | `mainThreadBindanimationstart` | —                            | `MainThread.AnimationEvent`    |
| `animationend`   | `mainThreadBindanimationend`   | —                            | `MainThread.AnimationEvent`    |
| `transitionend`  | `mainThreadBindtransitionend`  | —                            | `MainThread.TransitionEvent`   |
| `layoutchange`   | `mainThreadBindlayoutchange`   | —                            | `MainThread.LayoutChangeEvent` |

In the handler, `event.target` and `event.currentTarget` are [`MainThread.Element`](#types) objects. When the element is destroyed, its handlers are removed.

## Constraints

- **The web preview fires mouse events, not touch events.** A desktop browser never fires touch events, so bind the `mouse*` inputs too for a drag that works there. Phones fire touch events, plus a `mousedown` and `mouseup` after a tap.
- **A handler doesn't run change detection.** Change the element directly, through `event.currentTarget`.
- **Each input takes one handler.** Binding a new one replaces the old one, and `null` removes it.
- **A script runs beside the element's other listeners for its event.** A `(bindtap)` next to a `[mainThreadBindtap]` runs too, in the order Angular added them. So does a listener added later, such as an `IntersectionObserver`'s.
- **A `Catch` input stops the event at the element** after all of them have run.

## Types

```typescript
import type { MainThread } from '@blotch/angular-lynx';
```

`MainThread` is a namespace of the types from `@lynx-js/types/main-thread`, with `getBoundingClientRect()` added to `MainThread.Element`:

| Type                            | What it is                                                              |
| ------------------------------- | ----------------------------------------------------------------------- |
| `MainThread.Element`            | An element you can change directly (methods below)                      |
| `MainThread.TouchEvent`         | `tap`, `longpress` and `touch*` events. Has `touches`, `changedTouches` |
| `MainThread.MouseEvent`         | `mouse*` events                                                         |
| `MainThread.WheelEvent`         | Wheel events                                                            |
| `MainThread.KeyEvent`           | Key events                                                              |
| `MainThread.AnimationEvent`     | `animationstart`, `animationend`                                        |
| `MainThread.TransitionEvent`    | `transitionend`                                                         |
| `MainThread.LayoutChangeEvent`  | `layoutchange`                                                          |
| `MainThread.UIAppearanceEvent`  | Appear and disappear events                                             |
| `MainThread.BoundingClientRect` | What `getBoundingClientRect()` resolves with                            |

```typescript
// MainThread.Element
interface Element {
  getAttribute(name: string): any;
  getAttributeNames(): string[];
  setAttribute(name: string, value: any): void;
  setStyleProperty(name: string, value: string): void;
  setStyleProperties(styles: Record<string, string>): void;
  querySelector(selector: string): Element | null;
  querySelectorAll(selector: string): Element[];
  invoke(methodName: string, params?: Record<string, any>): Promise<any>;
  animate(
    keyframes: Record<string, number | string>[],
    options?: number | AnimationOptions,
  ): Animation;
  getBoundingClientRect(options?: {
    relativeTo?: string;
  }): Promise<BoundingClientRect>;
}

// MainThread.BoundingClientRect
type BoundingClientRect = {
  left: number;
  top: number;
  right: number;
  bottom: number;
  width: number;
  height: number;
};
```

- **`setStyleProperty()` and `setAttribute()`** batch their changes, and Lynx applies them together after your handler returns.
- **On an element of your templates, `setAttribute()` is a template attribute's equal:** a `data-*` goes into the element's dataset, an `id`, `class` or `style` does what it does in a template, an ARIA attribute gives VoiceOver and TalkBack theirs, and an attribute selector in your CSS matches it. The element keeps it when it's taken out and put back, as projected content in a toggled `@if` is. `null` removes it. A whole `style` sits under the styles set one at a time (`[style.x]` bindings and `setStyleProperty()`), as a template's `style="…"` does, so change one of those with `setStyleProperty()`.
- **That includes the elements the build creates without Angular,** the plain `<view>`, `<text>` and `<image>` elements of a subtree with no binding, listener, local reference or directive anywhere in it, which `event.target` and `querySelector()` can reach: the attributes and styles a script sets on one are kept as on any other.
- **`invoke()`** calls one of the element's [UI methods](/guide/glossary.md#ui-method), such as `scrollTo` on a `<scroll-view>`, and resolves with its result.
- **`getBoundingClientRect()`** resolves with the element's position and size, measured from the top-left corner of the [LynxView](/guide/glossary.md#lynxview). Pass `relativeTo: 'screen'`, or another element's `id`, to measure from there instead. Unlike the DOM's, it returns a promise: Lynx gives a script the layout position only through the `boundingClientRect` [UI method](/guide/glossary.md#ui-method), which this calls. Measure once when a gesture starts rather than on every move.

## Related

- [Main-thread scripts guide](/guide/main-thread/index.md)
- [`mainThreadFn`](/api/main-thread/main-thread-fn.md)
- [`MainThreadRef`](/api/main-thread/main-thread-ref.md)
- [Handling taps and events](/guide/elements/event-handling.md)
