# Routed events

The package `moonrockz/dependency-object/events`.

Routed events with the behavior of WPF, for the [elements](../README.mbt.md#the-logical-tree) of `moonrockz/dependency-object`.
`@events` in the examples is this package, and `@dependency` is `moonrockz/dependency-object`.

## A button with an event

A `Click` on a button goes up the logical tree, so the panel hears of the clicks of all its buttons:

```mbt check
///|
let button_type : @dependency.OwnerType = try! @dependency.register_owner_type(
  "Button",
  element=true,
)

///|
let panel_type : @dependency.OwnerType = try! @dependency.register_owner_type(
  "Panel",
  element=true,
)

///|
let click : @events.RoutedEvent[Unit] = try! @events.register_routed_event(
  "Click",
  Bubble,
  button_type,
  @dependency.unit_key,
)

///|
/// What a control does when the mouse or a key clicks it.
fn click_on(button : @dependency.DependencyObject) -> Unit raise {
  @events.raise_event(button, @events.RoutedEventArgs::new((), event=click))
}

///|
test "a panel hears of the clicks of its buttons" {
  let panel = @dependency.DependencyObject::new(panel_type)
  let ok = @dependency.DependencyObject::new(button_type)
  let cancel = @dependency.DependencyObject::new(button_type)
  let items = @dependency.ElementCollection::new(panel)
  items.add(ok)
  items.add(cancel)
  let log = []
  let token = @events.add_handler(ok, click, (_, args) => {
    log.push("OK")
    args.set_handled(true)
  })
  ignore(
    @events.add_handler(panel, click, (_, args) => {
      if args.source() is Some(Object(button)) && button == cancel {
        log.push("a click on Cancel")
      }
    }),
  )
  click_on(ok)
  click_on(cancel)
  assert_eq(log, ["OK", "a click on Cancel"])
  assert_true(@events.remove_handler(ok, token))
}
```

## Register events

A program registers each event on the type that raises it, with a routing strategy and the
[key](../README.mbt.md#value-keys) of its data. An event without data has the key `unit_key`.

```mbt check
///|
test "look up" {
  let toggle_button = @dependency.register_owner_type(
    "ToggleButton",
    base=button_type,
  )
  guard @events.lookup_routed_event(toggle_button, "Click") is Some(found) else {
    fail("no such event")
  }
  assert_eq(found, click.info())
  inspect(found, content="Button.Click")
}
```

| Strategy | The handlers run |
| --- | --- |
| `Bubble` | on the element that raises the event, and then on its ancestors up to the root |
| `Tunnel` | on the root first, and then down to the element |
| `Direct` | only on the element |

A `RoutedEvent[A]` has data of type `A`. Its `info` is the event without this type, a `RoutedEventInfo`, for code that has events
of many types. `lookup_routed_event` gives one too, and its `typed` gives the `RoutedEvent[A]` back for the right key. All handles
of one event are equal.

An owner type can have one event with a name. A type that derives from it can use the name for another event, and the lookup gives
the event of the nearest type. `add_owner` makes an event one of another type too, so that the lookup finds it there. When that
type has another event of the same name, `add_owner` is no error, as in WPF, and the lookup goes on to find the first one.

Events are in the registry of the process, unless you pass another one with `registry~`. See
[Registries](../README.mbt.md#registries).

## Raise events

`raise_event` runs the handlers for the event on the elements of its route, and goes on when they have run. It settles which
handlers run before the first one does, so a change of the tree or of the handlers is for the next raise.

All handlers of a raise get the same arguments, and what one changes is there for the next one:

| Function | What it is |
| --- | --- |
| `data` | the data of the raise, of the type of the event |
| `event` | the event that is raised |
| `handled`, `set_handled` | whether a handler has dealt with the event. Then only handlers with `handled_events_too` still run. A handler can also take this back |
| `source`, `set_source` | where the event comes from: the element on which it is raised, unless a handler says otherwise |
| `original_source` | the first source, which handlers cannot change |

```mbt check
///|
priv struct KeyInfo {
  key : Char
}

///|
let key_info_key : @dependency.ValueKey[KeyInfo] = @dependency.ValueKey::by_identity(
  "KeyInfo",
)

///|
let key_down : @events.RoutedEvent[KeyInfo] = try! @events.register_routed_event(
  "KeyDown",
  Bubble,
  button_type,
  key_info_key,
)

///|
test "an event with data" {
  let button = @dependency.DependencyObject::new(button_type)
  let log = []
  ignore(
    @events.add_handler(button, key_down, (_, args) => log.push(args.data.key)),
  )
  @events.raise_event(
    button,
    @events.RoutedEventArgs::new({ key: 'a', }, event=key_down),
  )
  assert_eq(log, ['a'])
}
```

- The `source` is a dependency object, which does not have to be an element, or an `AnyValue`. `RoutedEventArgs::new` can get one
  with `source`, such as the part of the button on which the mouse was. It is the `original_source` of the raise, and also the
  `source` after it.
- Arguments without an event need `set_event` before anything else. They can get another event later, also from a handler. The raise
  that runs then goes on with the handlers of its event. All events of one `RoutedEventArgs` have the same key for their data.
- A handler can raise events, also with the arguments that it gets. Such a raise is complete when the handler goes on. Raises and
  changes of properties count together for the [`nesting_limit`](../README.mbt.md#changes).
- An error of a handler ends the raise and reaches the code that made it. The arguments stay as they are at that moment, and can be
  raised again.
- A route can have 4,097 elements, as in WPF. When it gets longer, such as in a tree with a loop, the raise fails before a handler
  runs.

## Handlers of elements

`add_handler` adds a handler for any event to any element, also when the type of the element has nothing to do with the event, as
the panel above. Such an event is an attached event in XAML. The handler gets the element to which it was added and the arguments.

- Handlers of an element run in the order in which they were added. One that is added twice runs twice.
- `handled_events_too=true` is for a handler that also runs when the event is handled.
- `remove_handler` removes the handler with the token that `add_handler` gave. `release_handlers` removes all of an element, also
  those that a [XAML document](../../../xaml/src/schema/README.mbt.md) has added, for which there is no token.
- `add_routing_handler` is for a handler that does not need the data. It can be one of events with data of different types. It gets
  `RoutingArgs`, which have everything but the data and `set_event`.

```mbt check
///|
test "one handler for events with different data" {
  let button = @dependency.DependencyObject::new(button_type)
  let log = []
  for event in [click.info(), key_down.info()] {
    ignore(
      @events.add_routing_handler(button, event, (_, args) => {
        if args.event() is Some(event) {
          log.push(event.name())
        }
      }),
    )
  }
  click_on(button)
  @events.raise_event(
    button,
    @events.RoutedEventArgs::new({ key: 'a', }, event=key_down),
  )
  assert_eq(log, ["Click", "KeyDown"])
  @events.release_handlers(button)
}
```

## Handlers of types

`register_class_handler` runs a handler for each element of a type and of the types that derive from it. This is how a control
reacts to its own events, before the program that uses it does:

```mbt check
///|
let check_box_type : @dependency.OwnerType = try! @dependency.register_owner_type(
  "CheckBox",
  base=button_type,
)

///|
let is_checked : @dependency.DependencyProperty[Bool] = try! @dependency.register(
  "IsChecked",
  check_box_type,
  @dependency.bool_key,
  default_value=false,
)

///|
fn init {
  try! @events.register_class_handler(check_box_type, click, (check_box, _) => {
    check_box.set_value(is_checked, !check_box.get_value(is_checked))
  })
}

///|
test "a click checks a check box" {
  let check_box = @dependency.DependencyObject::new(check_box_type)
  let log = []
  ignore(
    @events.add_handler(check_box, click, (sender, _) => {
      log.push(sender.get_value(is_checked))
    }),
  )
  click_on(check_box)
  click_on(check_box)
  assert_eq(log, [true, false])
}
```

- On one element, the handlers of its type run first, then those of each base type, the nearest one first, and then those of the
  element. A tunnel event reverses only the order of the elements.
- A class handler that handles the event stops the handlers of the element too, unless these have `handled_events_too`.
- Only element types have class handlers. They are there from the next raise on, and cannot be removed.
- `register_class_routing_handler` is for a handler that does not need the data.

## Preview events

WPF has pairs of events such as `PreviewKeyDown` and `KeyDown`: one tunnels from the root to the element, and then the other bubbles
back. With the first one, a panel can handle a key before the element in it gets it. This is a convention, and not a strategy of
its own. The control raises both events with the same arguments, so the second raise starts with the `handled` of the first one:

```mbt check
///|
let preview_key_down : @events.RoutedEvent[KeyInfo] = try! @events.register_routed_event(
  "PreviewKeyDown",
  Tunnel,
  button_type,
  key_info_key,
)

///|
fn press(button : @dependency.DependencyObject, key : Char) -> Unit raise {
  let args = @events.RoutedEventArgs::new({ key, }, event=preview_key_down)
  @events.raise_event(button, args)
  args.set_event(key_down)
  @events.raise_event(button, args)
}

///|
test "a panel that accepts only digits" {
  let panel = @dependency.DependencyObject::new(panel_type)
  let button = @dependency.DependencyObject::new(button_type)
  panel.add_logical_child(button)
  let log = []
  ignore(
    @events.add_handler(panel, preview_key_down, (_, args) => {
      args.set_handled(!args.data.key.is_ascii_digit())
    }),
  )
  ignore(
    @events.add_handler(button, key_down, (_, args) => log.push(args.data.key)),
  )
  press(button, 'a')
  press(button, '1')
  assert_eq(log, ['1'])
  panel.remove_logical_child(button)
}
```

## Memory

An element holds its handlers, and a handler holds what it uses. js and wasm-gc free both together. native and wasm count references,
and never free a handler that uses its own element, or an ancestor of it. Use the element that the handler gets, which is no
circle, or call `remove_handler` or `release_handlers` before you drop the element.

Class handlers are in their registry. The registry of the process lives as long as the process. When a class handler uses a registry
of your own, call `release_class_handlers` before you drop the registry.

## Differences from WPF

MoonBit forces these:

1. **Handlers are removed with a token.** WPF compares the handlers, and functions of MoonBit have no equality. The handlers of a XAML
   document have no token, so `release_handlers` removes all handlers of an element.
2. **The arguments have data.** In WPF an event has a class of arguments that derives from `RoutedEventArgs`. Here it has
   `RoutedEventArgs[A]`, and the key of `A` stands for the type. `RoutingArgs` are what all arguments have in common.
3. **A lookup gives an event without the type of its data.** `typed` gives the type back.
4. **A source is an `EventSource`.** In WPF it is an `object`.
5. **An element is an object of an element type.** In WPF it is an object of `UIElement`, `ContentElement` or `UIElement3D`, and only
   these have `AddHandler` and `RaiseEvent`. Here these functions fail for other objects.
6. **A registry is a value**, and the events and elements of two registries cannot be used together. `release_class_handlers` is for
   a registry of your own.
7. **Raises nest at most `nesting_limit` levels deep**, together with changes of properties. WPF has no limit, and its process ends
   when the stack is full.

Avalonia differs from WPF and from this package. There an event can tunnel and bubble in one raise, and a class handler can be
removed.
