# Dependency objects

The package `moonrockz/dependency-object`.

Dependency objects and dependency properties with the behavior of WPF. `@dependency` in the examples is this package:
write `"moonrockz/dependency-object" @dependency` in your `moon.pkg`, because the name has a hyphen.

## A control with two properties

`Value` is never above `Maximum`. The coercion of `Value` sees to that when `Value` is set, and a function of the metadata
when `Maximum` changes. The two properties use each other, so `Maximum` gets its metadata after both are registered.

```mbt check
///|
let slider_type : @dependency.OwnerType = try! @dependency.register_owner_type(
  "Slider",
)

///|
let slider_maximum : @dependency.DependencyProperty[Double] = try! @dependency.register(
  "Maximum",
  slider_type,
  @dependency.double_key,
  default_value=100.0,
)

///|
let slider_value : @dependency.DependencyProperty[Double] = try! @dependency.register(
  "Value",
  slider_type,
  @dependency.double_key,
  default_value=0.0,
  validate=value => !value.is_nan(),
  metadata=@dependency.PropertyMetadata::new(coerce=(object, value) => {
    value.min(object.get_value(slider_maximum))
  }),
)

///|
fn init {
  try! slider_maximum.override_metadata(
    slider_type,
    @dependency.PropertyMetadata::new(changed=(object, _, _, _) => {
      object.coerce_value(slider_value)
    }),
  )
}

///|
test "a slider" {
  let slider = @dependency.DependencyObject::new(slider_type)
  let changes = Ref(0)
  ignore(slider.add_change_handler((_, _, _, _) => changes.val += 1))
  slider.set_value(slider_value, 80.0)
  slider.set_value(slider_maximum, 50.0)
  assert_eq(slider.get_value(slider_value), 50.0)
  // The value that was set is still there.
  slider.set_value(slider_maximum, 100.0)
  assert_eq(slider.get_value(slider_value), 80.0)
  slider.clear_value(slider_value)
  assert_eq(slider.get_value(slider_value), 0.0)
  // The handler also ran for the two changes of `Value` by its coercion.
  assert_eq(changes.val, 6)
}
```

## Register types and properties

MoonBit has no reflection, so a program registers its types of objects, and each property with the key of its value type
and its default value.

```mbt check
///|
test "register and look up" {
  let control = @dependency.register_owner_type("Control", element=true)
  let button = @dependency.register_owner_type("Button", base=control)
  let padding = @dependency.register(
    "Padding",
    control,
    @dependency.double_key,
    default_value=0.0,
    validate=value => value >= 0.0,
  )
  guard @dependency.lookup_property(button, "Padding") is Some(found) else {
    fail("no such property")
  }
  assert_eq(found, padding.info())
  inspect(found, content="Control.Padding")
}
```

| Function | What it registers |
| --- | --- |
| `register_owner_type` | a type of objects, with the type that it derives from |
| `register` | a property of a type |
| `register_attached` | a property that a type defines for objects of every type, such as `Grid.Row` |
| `register_read_only`, `register_attached_read_only` | a property that only code with the returned `DependencyPropertyKey` can change |
| `DependencyProperty::add_owner` | an existing property under its name on another type |

`default_value` is required, because MoonBit has no default value for every type. `validate` accepts or rejects values,
and the default value too. Two types can use one name for two properties, also when one derives from the other.
`lookup_property` finds the property of the nearest type. A failure is a `DependencyError`, whose text names the property
as `Owner.Name`.

Every property of a registry has a value on every object of the registry. The owner type decides only where the property is
found by its name, and which objects use its metadata.

## Metadata

`PropertyMetadata` says how a property behaves on the objects of a type:

| Argument | What it is | When an override does not have it |
| --- | --- | --- |
| `default_value` | the value of objects on which nothing is set | that of the base type |
| `coerce` | computes the effective value | that of the base type |
| `changed` | runs after a change | that of the base type, which also runs, and first, when there is one |
| `inherits` | whether elements use the value of their ancestors, see [Inherited values](#inherited-values) | that of the base type |
| `logical_content` | the element in a value, see [The logical tree](#the-logical-tree) | that of the base type |

The metadata of `register` is for objects of the owner type and of the types that derive from it. The metadata of an
attached property is for objects of every type. `override_metadata` gives a property metadata for one more type, and so does
`add_owner`. An object uses the metadata of its type, or else of the nearest base type that has some.

```mbt check
///|
let dial_type : @dependency.OwnerType = try! @dependency.register_owner_type(
  "Dial",
  base=slider_type,
)

///|
test "a type with other metadata" {
  slider_maximum.override_metadata(
    dial_type,
    @dependency.PropertyMetadata::new(default_value=360.0),
  )
  let dial = @dependency.DependencyObject::new(dial_type)
  dial.set_value(slider_value, 270.0)
  assert_eq(dial.get_value(slider_value), 270.0)
  // `Maximum` still coerces `Value`, because the override has the `changed` of the slider.
  dial.set_value(slider_maximum, 180.0)
  assert_eq(dial.get_value(slider_value), 180.0)
  assert_eq(slider_maximum.get_metadata(slider_type).default_value(), 100.0)
}
```

- A type can have metadata for a property once. The owner type has it when `register` got some, and always when a property is
  read-only and not attached. Both are so in WPF.
- An override takes what it does not have from the metadata that the base type has at that moment. So override the base type
  first. A later override of the base type does not change the type, as in WPF.
- Override before there are objects of the type. A later override is for values that objects have not stored, and nothing is
  notified. WPF says that the result is undefined, so do not depend on it.
- The default value of an override is validated.
- A read-only property needs its key: `override_metadata(owner, metadata, key~)`. `add_owner` cannot give it metadata.
- `get_metadata` gives what is in force for a type.

## Values

| Function | What it does |
| --- | --- |
| `get_value` | gives the effective value |
| `set_value` | sets the local value |
| `set_current_value` | changes the effective value and not the local value |
| `clear_value` | removes the local value and the current value |
| `coerce_value` | coerces the value again |
| `read_local_value` | gives the current value or the local value, or `None` |
| `local_values` | gives all properties that have such a value |
| `set_with_key`, `clear_with_key` | change a read-only property |

These are methods of `DependencyObject` with a `DependencyProperty[T]`. `PropertyInfo` has all but `local_values` too, with
`AnyValue`s, for code that does not know the type. Both fail in the same cases.

The effective value is the result of three steps:

1. The **base value** is the local value, or else the [inherited value](#inherited-values), or else the default value for the
   type of the object.
2. The **current value** replaces it when there is one. A control uses a current value for its own changes, such as a check
   box that is clicked, because the next `set_value` or `clear_value` discards it. A current value that equals the base value
   is none.
3. The **coercion** changes it. `get_value` gives what the coercion gave when the value was last set, cleared or coerced.

```mbt check
///|
test "a current value" {
  let slider = @dependency.DependencyObject::new(slider_type)
  slider.set_value(slider_value, 10.0)
  slider.set_current_value(slider_value, 20.0)
  assert_eq(slider.get_value(slider_value), 20.0)
  assert_eq(slider.read_local_value(slider_value), Some(20.0))
  // The coercion gives another value than 200, so 200 is not kept, and the next coercion starts with the local value.
  slider.set_current_value(slider_value, 200.0)
  assert_eq(slider.get_value(slider_value), 100.0)
  assert_eq(slider.read_local_value(slider_value), Some(10.0))
  slider.coerce_value(slider_value)
  assert_eq(slider.get_value(slider_value), 10.0)
}
```

- `validate` checks each value that is set, also a current value that `coerce_value` sets again. It does not check the
  result of a coercion. A value that it rejects changes nothing.
- A default value is not coerced when it is read or when `clear_value` brings it back. `coerce_value` coerces it, and the
  result stays until the next operation. An inherited value is always coerced.

## Changes

A change is notified when the old and the new effective value are not equal by the `equal` of the property, or else by its
key. An operation does this:

1. It validates the value.
2. It takes the old value.
3. It coerces the new value.
4. It stores the new value.
5. It compares the two. When they are equal, it is done.
6. It runs the `changed` functions of the metadata, that of the base type first.
7. It runs the handlers of the object, in the order in which they were added.

```mbt check
///|
test "handlers" {
  let slider = @dependency.DependencyObject::new(slider_type)
  let changes = []
  let token = slider.add_change_handler((_, property, old, new) => {
    guard @dependency.double_key.unwrap(old) is Some(old) &&
      @dependency.double_key.unwrap(new) is Some(new) else {
      return
    }
    changes.push("\{property}: \{old} -> \{new}")
  })
  slider.set_value(slider_value, 80.0)
  slider.set_value(slider_maximum, 50.0)
  assert_true(slider.remove_change_handler(token))
  slider.set_value(slider_maximum, 20.0)
  debug_inspect(
    changes,
    content=(
      #|[
      #|  "Slider.Value: 0 -> 80",
      #|  "Slider.Value: 80 -> 50",
      #|  "Slider.Maximum: 100 -> 50",
      #|]
    ),
  )
}
```

A change that a function or a handler makes runs at once and completely. So the handler above hears of `Value` before
`Maximum`, because the `changed` function of `Maximum` coerces `Value`.

A handler that a handler adds or removes is added or removed from the next change on. One that `changed` adds or removes
already is for this change.

An error of the coercion stops the operation before it stores the value. An error of `changed` or of a handler stops the
rest of the notification, and the new value stays. The caller of the operation gets the error as it is.

Changes can cause each other. At `nesting_limit` levels the next change fails with a `DependencyError`, before the stack is
full. Raises of [events](#events) count too, and other code that calls handlers takes part with `guard_nesting`.

## The logical tree

An **element** is an object of a type that was registered with `element=true`, or that derives from such a type. An element
can have a logical parent and logical children. Only a control changes them, for the elements that it contains: a panel for
its children, a button for its content. There are two ways to do this without code for each change:

- An `ElementCollection` is the list of the children of a panel. It links the elements that it gets and unlinks those that it
  loses.
- `logical_content` in the metadata of a property gives the element in a value. This element is a logical child of the object
  as long as the property has the value.

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

///|
let stack_type : @dependency.OwnerType = try! @dependency.register_owner_type(
  "StackPanel",
  base=element_type,
)

///|
let card_type : @dependency.OwnerType = try! @dependency.register_owner_type(
  "Card",
  base=element_type,
)

///|
let element_key : @dependency.ValueKey[@dependency.DependencyObject?] = @dependency.ValueKey::new(
  "Element",
)

///|
let card_content : @dependency.DependencyProperty[@dependency.DependencyObject?] = try! @dependency.register(
  "Content",
  card_type,
  element_key,
  default_value=None,
  metadata=@dependency.PropertyMetadata::new(logical_content=value => value),
)

///|
priv struct StackPanel {
  object : @dependency.DependencyObject
  children : @dependency.ElementCollection
}

///|
fn StackPanel::new() -> StackPanel raise {
  let object = @dependency.DependencyObject::new(stack_type)
  { object, children: @dependency.ElementCollection::new(object), }
}

///|
test "a panel and a card" {
  let panel = StackPanel::new()
  let card = @dependency.DependencyObject::new(card_type)
  let image = @dependency.DependencyObject::new(element_type)
  panel.children.add(card)
  card.set_value(card_content, Some(image))
  assert_eq(panel.object.logical_children(), [card])
  assert_eq(image.logical_parent(), Some(card))
  panel.children.clear()
  card.clear_value(card_content)
  assert_eq(card.logical_parent(), None)
  assert_eq(image.logical_parent(), None)
}
```

| Function | What it does |
| --- | --- |
| `logical_parent` | gives the parent, or `None` |
| `logical_children` | gives a copy of the list of the children |
| `route_parent` | gives the next element on the route of an event, which is the logical parent |
| `add_logical_child`, `insert_logical_child` | link a child |
| `remove_logical_child` | unlinks a child |

A control that has its elements in another form, such as two named parts, calls the last three itself. The tree has only
elements. Other objects that a control contains, such as text, are not in it: `add_logical_child` ignores them.

### What fails

An element has one parent at most, and both have the same registry. The messages of the first four cases are those of WPF.

| Case | Message |
| --- | --- |
| the element has another parent | Specified element is already the logical child of another element. Disconnect it first. |
| the element is the parent itself | Element cannot be its own parent. |
| a callback changes the children over which a walk goes | Cannot modify the logical children for this node at this time because a tree walk is in progress. |
| an element becomes a descendant of itself | Logical tree depth exceeded while traversing the tree. This could indicate a cycle in the tree. |
| the element is in another slot of the collection | names the element and the index |
| the parent or an item of a collection is not an element | names the type |
| the elements have two registries | names both types |

To add an element to the parent that it has already is no error, and changes nothing. To remove one that is no child is none
either.

The three functions above that link and unlink, and `add`, `insert` and `replace` of a collection, find all but the loop before
something changes. The other edits of a collection and a change of logical content consist of steps, which are described below.
The steps before the one that fails stay done.

As in WPF, a loop is linked first, and then the walk over the new child fails because it gets more than 4,096 levels deep. Remove
the child again to repair the tree.

### Collections

- `add` and `insert` store the element and then link it. MAUI and Avalonia do the same, and WPF links first.
- `remove` and `remove_at` remove the element from the collection and then unlink it.
- `replace` unlinks the old element while it still has the slot, then puts the new one in the slot, and then links it.
- `clear` empties the collection and then unlinks one element after the other.

The logical children have the order of the collection, as long as nothing else changes them.

### Logical content

When the effective value of a property with `logical_content` changes, three steps follow after the new value is stored and
before callbacks and handlers run. They are those of `ContentControl` in WPF:

1. The old element is unlinked, when it still is a child of the object.
2. The new element is unlinked from the parent that it has, so content moves from one parent to another without an error.
3. The new element is linked.

The former parent does not hear of step 2. An `ElementCollection` keeps the element in its slot, and the property of another
control keeps its value. Both leave the element alone when they lose it, because they are not its parent any more.

### Errors while the tree changes

A callback or a handler that hears of a new inherited value can fail. The edit then stops with this error. What it has done
stays, and it does not go on with the next step or the next element. So a `replace` can leave the old element in its slot
without a parent, and a `clear` can leave later elements linked that the collection does not have any more. A collection can
add those again or remove them.

## Inherited values

A property with `inherits=true` in its metadata goes down the logical tree. An element on which nothing is set uses the value
of its ancestors, as with a font size.

```mbt check
///|
let text_type : @dependency.OwnerType = try! @dependency.register_owner_type(
  "TextElement",
)

///|
let font_size : @dependency.DependencyProperty[Double] = try! @dependency.register_attached(
  "FontSize",
  text_type,
  @dependency.double_key,
  default_value=12.0,
  metadata=@dependency.PropertyMetadata::new(inherits=true),
)

///|
test "a font size for a panel and all that is in it" {
  let panel = StackPanel::new()
  let card = @dependency.DependencyObject::new(card_type)
  let caption = @dependency.DependencyObject::new(element_type)
  card.set_value(card_content, Some(caption))
  panel.object.set_value(font_size, 20.0)
  panel.children.add(card)
  assert_eq(caption.get_value(font_size), 20.0)
  assert_eq(caption.read_local_value(font_size), None)
  card.set_value(font_size, 16.0)
  assert_eq(caption.get_value(font_size), 16.0)
  card.clear_value(font_size)
  assert_eq(caption.get_value(font_size), 20.0)
  panel.children.remove(card)
  assert_eq(caption.get_value(font_size), 12.0)
}
```

- An element inherits from the nearest ancestor on which the property inherits. What it gets is the effective value there, with
  the current value and the coercion.
- An ancestor gives no value when it has only its default value. The element then uses the default value of its own type. So a
  button type with another default font size keeps it, until a font size is set above the button.
- A current value over an inherited value stays until the element inherits another value, or until the next `set_value` or
  `clear_value`.
- The metadata for the type of each element decides whether the property inherits there. So register a property as attached
  when it is for elements of unrelated types. One from `register` inherits on its owner type and the types that derive from it,
  and on others with an override. Do not depend on what it does below an element of another type. WPF does not define that
  either.
- An element on whose type an override has `inherits=false` has only its own value and gives none. What its parent gives passes
  it and reaches the elements below it.
- What an element inherits depends on the tree, and not on the order in which it was built and the values were set.

### The order of the changes

When the value that an element gives changes, the elements below it are evaluated one after the other: a child, then all that
is below this child, then the next child. This does not go below an element with a local value. When an element gets another
place, it is linked or unlinked first. Then the element and all that is below it are evaluated in the same order, also below
local values, with all properties of one element before the next element.

Each element stores its new value and notifies the change before the next one is evaluated. So a handler on the parent still
sees the old values of the children. A handler can change values, and these changes are complete when it goes on. It can change
the children of other elements, but not of one over whose children the evaluation goes at that moment.

An error of a callback or a handler stops the evaluation. The elements that it did not reach keep the values that they had, until
a later change of the value or of their place reaches them.

An evaluation fails when it gets more than 4,096 levels deep, and the search for an ancestor ends after as many. So a tree with a
loop gives an error and can be repaired.

## Events

The package [`events`](events/README.mbt.md) has routed events for elements: a button raises `Click`, and handlers on the button, its
panel and all other ancestors can run.

## Property paths

The package [`path`](path/README.mbt.md) has property paths: `Child.Width` reads, sets and observes the `Width` of whatever object is the
`Child`.

## Value keys

A `ValueKey[T]` stands for the type `T` at run time. It wraps a value as `AnyValue`, and only the same key gives the value
back. Keys that were made separately for one type do not match, so there is one shared key for each primitive type
(`bool_key`, `byte_key`, `int16_key`, `int_key`, `int64_key`, `float_key`, `double_key`, `char_key`, `string_key` and
`unit_key`) and `object_key` for dependency objects. Make one key for each type of your own:

- `ValueKey::new` compares values with `==`.
- `ValueKey::by_identity` compares objects by identity, as WPF does with the values of reference types.

`DependencyProperty::info` gives the handle of a property without its value type, a `PropertyInfo`, for code that has
properties of many types. Its `equal_values` compares two `AnyValue`s with the equality of the property. Two NaNs are equal
for `double_key` and `float_key`.

## Registries

Types and properties are in the registry of the process, as in WPF, unless you pass another one with `registry~`. A test
can make its own with `PropertyRegistry::new()`. Nothing is shared between registries. A function that gets a type of
another registry, or values of two registries, fails.

Other packages can keep their own tables in a registry, with `extension` and `set_extension` and a key of their own.

## Identities

These are equal and have a hash by identity, so that they can be keys of tables: `RegistryId`, `OwnerType`, `PropertyInfo`,
`PropertyKeyInfo` (the key of a read-only property without its value type), `ValueKeyId` and `DependencyObject`. All but the
last have no reference to the registry, so a table in a registry can hold them.

## The host of an object

A MoonBit struct cannot derive from `DependencyObject`. It has one in a field instead, and gives itself to the object as
its host value, so that code with only the object finds the control.

```mbt check
///|
priv struct Label {
  object : @dependency.DependencyObject
  caption : String
}

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

///|
test "from the object to the control" {
  let label_type = @dependency.register_owner_type("Label")
  let object = @dependency.DependencyObject::new(label_type)
  object.set_host(label_key.wrap({ object, caption: "Name", }))
  guard object.host() is Some(host) && label_key.unwrap(host) is Some(label) else {
    fail("no label")
  }
  assert_eq(label.caption, "Name")
  label.object.release_host()
  assert_true(object.host() is None)
}
```

An object has at most one host value in its life. Other packages can keep data on an object, with `extension`,
`set_extension` and `remove_extension` and a key of their own.

## Memory

js and wasm-gc free everything that a program no longer uses. native and wasm count references, and never free objects that
refer to each other in a circle. A control and its object are such a circle, so call `release_host` before you drop the
control on these targets. A handler that refers to the object on which it is needs `remove_change_handler`, so use the
object that the handler gets as its argument. A value that refers to the object needs `clear_value`.

A parent and its child are such a circle too. On native and wasm, nothing frees a tree that a program just drops. Unlink every
element of it, not only the root: `clear` each collection and `clear_value` each property with logical content. An element that
is unlinked is freed, also when the program goes on to use its former parent.

A registry of your own needs no such call, as long as your default values, your functions and your tables in it do not refer
to it. A dependency object refers to its registry.

## Differences from WPF

MoonBit forces these:

1. **A registry is a value.** WPF has one hidden table for the process. Here that table is the default of an argument, and
   values of two registries cannot be used together.
2. **Changes nest at most `nesting_limit` levels deep.** WPF has no limit, and its process ends when the stack is full.
   Programs on wasm cannot recover from that either.
3. **Values have types, and keys stand for them.** WPF stores `object`. Here a property is a `DependencyProperty[T]`, and a
   value of unknown type is an `AnyValue`. MoonBit has no overloads, so `SetValue` and `ClearValue` with a key are
   `set_with_key` and `clear_with_key`.
4. **Handlers are removed with a token.** WPF compares the handlers, and functions of MoonBit have no equality.
5. **A control has a dependency object.** In WPF it is one, and MoonBit has no inheritance between structs.
6. **`release_host`.** In WPF the control is the dependency object, and nothing has to be released.
7. **The default value is required.** WPF uses the default value of the .NET type when there is none.
8. **An element is an object of an element type.** In WPF it is an object of a class that derives from `FrameworkElement` or
   `FrameworkContentElement`.
9. **The logical children are a stored list.** In WPF a panel computes them from its collection, and so lists an element that was
   unlinked and still has its slot.

One difference is a decision. **Each element stores the values that it inherits**, and notifies whenever one changes. In WPF an
element without other values can read them from an ancestor. This shows in four cases:

- When a local value equal to the default is set above an element, the elements below that element get it too, and notify when
  their own default is another one. WPF stops at the first element whose value stays the same.
- The elements below one with `inherits=false` always have the value from above it, and notify it. In WPF they have it or not,
  depending on which other values were set on them and on the order of the steps, and a new parent is not notified.
- The elements that an evaluation did not reach because of an error keep their values. In WPF they can read the new value.
- A current value over an inherited value stays. WPF loses it at once on an element that reads its values from an ancestor.

These follow MAUI and Avalonia, which agree with each other and not with WPF:

- **A coerced value is not validated.** WPF validates it.
- **A coercion returns a value.** In WPF it can also return `UnsetValue`, which keeps the old value. Here it returns the old
  value for that.
- **A collection stores an element before it links it**, and **`replace` works for a slot that has an element.** In WPF such a
  replacement fails, after the old element has lost its parent.
