===== moon.pkg =====
import {
  "example/demo/model",
  "KKKIIO/selene/app",
  "KKKIIO/selene/ecs",
  "KKKIIO/selene/entity",
  "KKKIIO/selene/event",
  "KKKIIO/selene/math",
  "KKKIIO/selene/system",
  "KKKIIO/selene/ui_view",
  "moonbitlang/core/string",
}

supported_targets = "native+js"

===== state.generated.mbt =====
// Generated by selene-xaml@0.37.3. DO NOT EDIT.
// lock-format: 1
// input user fixtures/demo.xaml sha256=86f5694c3227273b380ba70803408c8ec960489a6403dc9528bef1e96c98554a
// input moon-info fixtures/model.mbti sha256=fca30918d1c9571439e4c70a7cbb15bfc7bd82fc34baa6dc59011b54a5fc0278

///|
pub type DemoState = @model.DemoState

===== view.generated.mbt =====
// Generated by selene-xaml@0.37.3. DO NOT EDIT.
// lock-format: 1
// input user fixtures/demo.xaml sha256=86f5694c3227273b380ba70803408c8ec960489a6403dc9528bef1e96c98554a
// input moon-info fixtures/model.mbti sha256=fca30918d1c9571439e4c70a7cbb15bfc7bd82fc34baa6dc59011b54a5fc0278

///|
pub(all) enum DemoViewAction {} derive(Eq, Debug)

///|
pub(all) suberror DemoViewError {
  AlreadyMounted
  NotMounted
  DeadEntity
  DuplicateKey(String, String)
  InvalidPatch(String)
  Host(@ui_view.HostError)
} derive(Eq, Debug)

///|
pub impl Show for DemoViewError with fn output(self, logger) {
  match self {
    AlreadyMounted =>
      logger.write_string("view is already mounted on this entity")
    NotMounted => logger.write_string("view is not mounted on this entity")
    DeadEntity => logger.write_string("view entity is not alive")
    DuplicateKey(path, key) =>
      logger.write_string("duplicate or empty key in " + path + ": " + key)
    InvalidPatch(message) => logger.write_string(message)
    Host(error) => logger.write_string(error.to_string())
  }
}

///|
fn generated_compute_view_model(model : DemoState) -> DemoState {
  model
}

///|
#warnings("-unused_value")
fn generated_rect_component(
  value : String,
  index : Int,
  path : String,
  image_region : Bool,
) -> Double raise DemoViewError {
  let parts = value.split(" ").filter(part => part != "").collect()
  let selected = if image_region {
    if parts.length() != 4 {
      raise InvalidPatch(
        "image region requires x y width height for " + path + ": " + value,
      )
    }
    parts[index]
  } else {
    match parts.length() {
      1 => parts[0]
      2 => if index == 0 || index == 2 { parts[1] } else { parts[0] }
      4 =>
        match index {
          0 => parts[3]
          1 => parts[0]
          2 => parts[1]
          _ => parts[2]
        }
      _ => raise InvalidPatch("invalid rect value for " + path + ": " + value)
    }
  }
  let parsed = @string.parse_double(selected) catch {
    _ =>
      raise InvalidPatch(
        "invalid number for " + path + ": " + selected.to_owned(),
      )
  }
  if image_region &&
    ((index < 2 && parsed < 0.0) || (index >= 2 && parsed <= 0.0)) {
    raise InvalidPatch("invalid image region for " + path + ": " + value)
  }
  parsed
}

///|
#warnings("-struct_never_constructed")
pub struct DemoView {}

///|
#warnings("-unused_field")
priv struct GeneratedViewRecord {
  mut model : DemoState
  mut view_model : DemoState
  mut specs : Array[@ui_view.NodeSpec]
}

///|
let generated_records_by_world : Map[
  UInt,
  Map[@entity.Entity, GeneratedViewRecord],
] = Map([])

///|
fn generated_view_records() -> Map[@entity.Entity, GeneratedViewRecord] {
  let world_id = @ecs.require_current_world().id()
  generated_records_by_world.get_or_init(world_id, fn() { Map([]) })
}

///|
pub(all) struct DemoViewActionEvent {
  entity : @entity.Entity
  action : DemoViewAction
}

///|
/// World-isolated typed actions emitted by this view.
pub let action_event_bus : @event.Events[DemoViewActionEvent] = @event.Events()

///|
let generated_event_reader : @event.EventReader[@ui_view.UiViewEvent] = @event.EventReader()

///|
fn generated_specs(
  state : DemoState,
) -> Array[@ui_view.NodeSpec] raise DemoViewError {
  let nodes : Array[@ui_view.NodeSpec] = []
  nodes.push({
    key: "root",
    parent: None,
    kind: @ui_view.NodeKind::View,
    text: "",
    source: "",
    active: true,
    enabled: true,
    focusable: false,
    tab_index: 0,
    focus_scope: true,
    auto_focus: false,
    navigation_up: "",
    navigation_down: "",
    navigation_left: "",
    navigation_right: "",
    style: {
      absolute: false,
      left: 0.0,
      top: 0.0,
      width: @ui_view.LayoutValue::Auto,
      height: @ui_view.LayoutValue::Auto,
      margin_left: 0.0,
      margin_top: 0.0,
      margin_right: 0.0,
      margin_bottom: 0.0,
      padding_left: 0.0,
      padding_top: 0.0,
      padding_right: 0.0,
      padding_bottom: 0.0,
      background: "",
      border_color: "",
      border: 0.0,
      radius: 0.0,
      outline_color: "",
      outline_width: 0.0,
      outline_offset: 0.0,
      color: "",
      font_family: "",
      font_size: 0.0,
      bold: false,
      align: @ui_view.TextAlign::Left,
      wrap: false,
      z_index: 0,
      tint: "",
      source_region: None,
      fit: @ui_view.ImageFit::Fill,
      direction: @ui_view.FlexDirection::Column,
      flex_basis: @ui_view.LayoutValue::Auto,
      flex_grow: 0.0,
      flex_shrink: 1.0,
      row_gap: 0.0,
      column_gap: 0.0,
      grid_rows: [],
      grid_columns: [],
      grid_auto_flow: @ui_view.GridAutoFlow::Row,
      grid_row: None,
      grid_column: None,
      grid_row_span: 1,
      grid_column_span: 1,
      horizontal_scroll: false,
      vertical_scroll: false,
      scrollbar_width: 0.0,
    },
    visual_state_groups: [],
  })
  nodes.push({
    key: "node-root-0-text",
    parent: Some("root"),
    kind: @ui_view.NodeKind::Text,
    text: state.title,
    source: "",
    active: true,
    enabled: true,
    focusable: true,
    tab_index: 4,
    focus_scope: false,
    auto_focus: true,
    navigation_up: "",
    navigation_down: "",
    navigation_left: "",
    navigation_right: "Stop",
    style: {
      absolute: false,
      left: 0.0,
      top: 0.0,
      width: @ui_view.LayoutValue::Auto,
      height: @ui_view.LayoutValue::Auto,
      margin_left: 0.0,
      margin_top: 0.0,
      margin_right: 0.0,
      margin_bottom: 0.0,
      padding_left: 0.0,
      padding_top: 0.0,
      padding_right: 0.0,
      padding_bottom: 0.0,
      background: "",
      border_color: "",
      border: 0.0,
      radius: 0.0,
      outline_color: "",
      outline_width: 0.0,
      outline_offset: 0.0,
      color: "",
      font_family: "",
      font_size: 0.0,
      bold: false,
      align: @ui_view.TextAlign::Left,
      wrap: false,
      z_index: 0,
      tint: "",
      source_region: None,
      fit: @ui_view.ImageFit::Fill,
      direction: @ui_view.FlexDirection::Column,
      flex_basis: @ui_view.LayoutValue::Auto,
      flex_grow: 0.0,
      flex_shrink: 1.0,
      row_gap: 0.0,
      column_gap: 0.0,
      grid_rows: [],
      grid_columns: [],
      grid_auto_flow: @ui_view.GridAutoFlow::Row,
      grid_row: None,
      grid_column: None,
      grid_row_span: 1,
      grid_column_span: 1,
      horizontal_scroll: false,
      vertical_scroll: false,
      scrollbar_width: 0.0,
    },
    visual_state_groups: [],
  })
  nodes.push({
    key: "node-root-1-image",
    parent: Some("root"),
    kind: @ui_view.NodeKind::Image,
    text: "",
    source: "fixtures/icon.png",
    active: true,
    enabled: true,
    focusable: false,
    tab_index: 0,
    focus_scope: false,
    auto_focus: false,
    navigation_up: "",
    navigation_down: "",
    navigation_left: "",
    navigation_right: "",
    style: {
      absolute: false,
      left: 0.0,
      top: 0.0,
      width: @ui_view.LayoutValue::Auto,
      height: @ui_view.LayoutValue::Auto,
      margin_left: 0.0,
      margin_top: 0.0,
      margin_right: 0.0,
      margin_bottom: 0.0,
      padding_left: 0.0,
      padding_top: 0.0,
      padding_right: 0.0,
      padding_bottom: 0.0,
      background: "",
      border_color: "",
      border: 0.0,
      radius: 0.0,
      outline_color: "",
      outline_width: 0.0,
      outline_offset: 0.0,
      color: "",
      font_family: "",
      font_size: 0.0,
      bold: false,
      align: @ui_view.TextAlign::Left,
      wrap: false,
      z_index: 0,
      tint: state.icon_tint,
      source_region: if state.icon_region == "" {
        None
      } else {
        Some({
          position: @math.Vec2(
            generated_rect_component(state.icon_region, 0, "iconRegion", true),
            generated_rect_component(state.icon_region, 1, "iconRegion", true),
          ),
          size: @math.Vec2(
            generated_rect_component(state.icon_region, 2, "iconRegion", true),
            generated_rect_component(state.icon_region, 3, "iconRegion", true),
          ),
        })
      },
      fit: @ui_view.ImageFit::Fill,
      direction: @ui_view.FlexDirection::Column,
      flex_basis: @ui_view.LayoutValue::Auto,
      flex_grow: 0.0,
      flex_shrink: 1.0,
      row_gap: 0.0,
      column_gap: 0.0,
      grid_rows: [],
      grid_columns: [],
      grid_auto_flow: @ui_view.GridAutoFlow::Row,
      grid_row: None,
      grid_column: None,
      grid_row_span: 1,
      grid_column_span: 1,
      horizontal_scroll: false,
      vertical_scroll: false,
      scrollbar_width: 0.0,
    },
    visual_state_groups: [],
  })
  nodes
}

///|
/// Mounts this view on an alive root entity in the current world.
/// Destroying the root ends the view lifetime.
pub fn DemoView::mount(
  entity : @entity.Entity,
  model : DemoState,
) -> Unit raise DemoViewError {
  if !entity.is_alive() {
    raise DeadEntity
  }
  let records = generated_view_records()
  if records.contains(entity) {
    raise AlreadyMounted
  }
  let view_model = generated_compute_view_model(model)
  let desired = generated_specs(view_model)
  let host = @ui_view.ViewHost::new()
  host.mount(entity, desired) catch {
    error => raise Host(error)
  }
  records[entity] = { model, view_model, specs: desired }
}

///|
/// Atomically replaces the model of a mounted view in the current world.
pub fn DemoView::replace(
  entity : @entity.Entity,
  model : DemoState,
) -> Unit raise DemoViewError {
  let records = generated_view_records()
  let record = match records.get(entity) {
    Some(value) => value
    None => raise NotMounted
  }
  if !entity.is_alive() {
    records.remove(entity)
    raise DeadEntity
  }
  let view_model = generated_compute_view_model(model)
  let desired = generated_specs(view_model)
  let mutations = @ui_view.reconcile_specs(record.specs, desired)
  if mutations.length() > 0 {
    let host = @ui_view.ViewHost::new()
    host.apply(entity, mutations) catch {
      error => raise Host(error)
    }
  }
  record.model = model
  record.view_model = view_model
  record.specs = desired
}

///|
fn generated_handle_event(
  record : GeneratedViewRecord,
  event : @ui_view.UiEvent,
) -> DemoViewAction? {
  if !record.specs.any(spec => spec.key == event.key) {
    return None
  }
  None
}

///|
fn generated_route_events(_world : @ecs.World) -> Unit {
  let records = generated_view_records()
  let dead : Array[@entity.Entity] = []
  for entity, _ in records {
    if !entity.is_alive() {
      dead.push(entity)
    }
  }
  for entity in dead {
    records.remove(entity)
  }
  for raw in generated_event_reader.read(@ui_view.view_event_bus) {
    match records.get(raw.entity) {
      Some(record) =>
        match generated_handle_event(record, raw.event) {
          Some(action) => action_event_bus.send({ entity: raw.entity, action })
          None => ()
        }
      None => ()
    }
  }
}

///|
/// Installs the host, action bus, event routing, and lifetime cleanup.
pub fn plugin(app : @app.App) -> @app.App {
  app
  .add_plugin(@ui_view.plugin)
  .add_message(action_event_bus)
  .add_system(
    @system.PostUpdate,
    generated_route_events,
    system_name="selene_xaml_DemoView_events",
  )
}

===== view.generated.mbt.map.json =====
{
  "mappings": [
    {
      "source": "fixtures/demo.xaml",
      "original_offset": 231,
      "generated_offset": 5018,
      "length": 11
    },
    {
      "source": "fixtures/demo.xaml",
      "original_offset": 381,
      "generated_offset": 7590,
      "length": 15
    },
    {
      "source": "fixtures/demo.xaml",
      "original_offset": 417,
      "generated_offset": 7631,
      "length": 17
    },
    {
      "source": "fixtures/demo.xaml",
      "original_offset": 417,
      "generated_offset": 7769,
      "length": 17
    },
    {
      "source": "fixtures/demo.xaml",
      "original_offset": 417,
      "generated_offset": 7849,
      "length": 17
    },
    {
      "source": "fixtures/demo.xaml",
      "original_offset": 417,
      "generated_offset": 7970,
      "length": 17
    },
    {
      "source": "fixtures/demo.xaml",
      "original_offset": 417,
      "generated_offset": 8050,
      "length": 17
    }
  ]
}

===== selene-xaml.lock.json =====
{
  "format_version": 1,
  "generator": "selene-xaml@0.37.3",
  "runtime": "KKKIIO/selene",
  "inputs": [
    { "owner": "user", "path": "fixtures/demo.xaml", "sha256": "86f5694c3227273b380ba70803408c8ec960489a6403dc9528bef1e96c98554a" },
    { "owner": "moon-info", "path": "fixtures/model.mbti", "sha256": "fca30918d1c9571439e4c70a7cbb15bfc7bd82fc34baa6dc59011b54a5fc0278" }
  ],
  "resolved_contract": { "kind": "mbti", "path": "fixtures/model.mbti", "package": "example/demo/model", "sha256": "fca30918d1c9571439e4c70a7cbb15bfc7bd82fc34baa6dc59011b54a5fc0278" },
  "requested_outputs": ["moon.pkg", "state.generated.mbt", "view.generated.mbt", "view.generated.mbt.map.json", "selene-xaml.lock.json"],
  "output_naming": { "package_directory": ".", "state": "state.generated.mbt", "view": "view.generated.mbt", "source_map": "view.generated.mbt.map.json", "lock": "selene-xaml.lock.json" },
  "package_alias": { "alias": "model", "package": "example/demo/model" },
  "imported_sidecars": [],
  "host_capability": { "package": "KKKIIO/selene/ui_view", "contract": "ui-view", "version": "0.1.0", "operations": ["mount", "apply"] },
  "abi_fingerprint": "sha256:a5d852b04a64a46752e038d35139f01f5233379541746a0aa6a3c61ff4472f0e",
  "outputs": [    { "owner": "selene-xaml", "path": "moon.pkg", "sha256": "b8d8e9bc63579db7aa23cd64f484a6bac453b95ac52defc450ffbdbc87bce07b" },
    { "owner": "selene-xaml", "path": "state.generated.mbt", "sha256": "e87b5070d3483ecccbb30c011fe8737d36d1dc7a6719798c05ac42844758ec1f" },
    { "owner": "selene-xaml", "path": "view.generated.mbt", "sha256": "bfb73050f8797dd7739479f99eed961bc0869c3a9eb74bd74ad4b7317190d558" },
    { "owner": "selene-xaml", "path": "view.generated.mbt.map.json", "sha256": "7939e44683dd5ddf6b8e502911ccabe1c0e56e6f7af0a57f88c726b6abc84539" }
  ],
  "lock_path": "selene-xaml.lock.json"
}

