// Type keys: MoonBit's replacement for GPUI's `TypeId`-keyed maps of // `Box` (globals, events). // // A key is created once per type, usually as a top-level `let`: // // let theme_key : @app.GlobalKey[Theme] = @app.GlobalKey::new("Theme") // // The app stores values under the key's id without knowing their type. A // stored value is a closure that writes the value into its key's typed slot, // so reading it back through the same key is type-safe without downcasts. ///| let next_key_id : Ref[Int32] = { val: 0, } ///| fn fresh_key_id() -> Int32 { let id = next_key_id.val next_key_id.val = id + 1 id } ///| /// Identifies one kind of global state (GPUI: `TypeId::of::()` for a /// `G: Global`). pub struct GlobalKey[G] { id : Int32 name : String priv slot : Ref[G?] } ///| pub fn[G] GlobalKey::new(name : String) -> GlobalKey[G] { { id: fresh_key_id(), name, slot: { val: None, }, } } ///| /// A type-erased value that can only be read back through `key`. fn[G] GlobalKey::erase(self : GlobalKey[G], value : G) -> () -> Unit { fn() { self.slot.val = Some(value) } } ///| fn[G] GlobalKey::unerase(self : GlobalKey[G], erased : () -> Unit) -> G { self.slot.val = None erased() guard self.slot.val is Some(value) else { abort("global \{self.name}: stored value has the wrong key") } self.slot.val = None value } ///| /// Identifies one kind of event (GPUI: `TypeId::of::()` for events /// declared with `impl EventEmitter for T`). pub struct EventKey[E] { id : Int32 name : String priv slot : Ref[E?] } ///| pub fn[E] EventKey::new(name : String) -> EventKey[E] { { id: fresh_key_id(), name, slot: { val: None, }, } } ///| fn[E] EventKey::erase(self : EventKey[E], event : E) -> () -> Unit { fn() { self.slot.val = Some(event) } } ///| fn[E] EventKey::unerase(self : EventKey[E], erased : () -> Unit) -> E { self.slot.val = None erased() guard self.slot.val is Some(event) else { abort("event \{self.name}: payload has the wrong key") } self.slot.val = None event }