├── .gitignore ├── Cargo.toml ├── LICENSE.md ├── README.md ├── examples ├── README.md ├── counters.rs ├── dom.rs ├── extension.rs └── interop.rs └── src ├── compat.rs ├── events.rs ├── lib.rs ├── listener.rs ├── system.rs └── variable.rs /.gitignore: -------------------------------------------------------------------------------- 1 | .devcontainer 2 | .vscode 3 | tmp 4 | target 5 | 6 | Cargo.lock 7 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "korhah" 3 | version = "0.1.3" 4 | rust-version = "1.63.0" 5 | edition = "2021" 6 | license = "MPL-2.0" 7 | description = "A minimal & extensible reactive event system" 8 | repository = "https://github.com/konall/korhah" 9 | categories = ["gui", "no-std", "rust-patterns"] 10 | 11 | [dependencies] 12 | ahash = { version = "0.8.11", default-features = false } 13 | educe = { version = "0.6.0", default-features = false, features = [ 14 | "Clone", "Copy", "Debug", "Eq", "Hash", "PartialEq", "PartialOrd", "Ord" 15 | ] } 16 | indexmap = { version = "2.2.6", default-features = false } 17 | spin = { version = "0.9.8", default-features = false, features = ["spin_mutex", "mutex"] } 18 | 19 | [features] 20 | default = ["std"] 21 | std = ["ahash/std", "indexmap/std", "spin/std"] 22 | unsync = [] 23 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | Mozilla Public License Version 2.0 2 | ================================== 3 | 4 | 1. Definitions 5 | -------------- 6 | 7 | 1.1. "Contributor" 8 | means each individual or legal entity that creates, contributes to 9 | the creation of, or owns Covered Software. 10 | 11 | 1.2. "Contributor Version" 12 | means the combination of the Contributions of others (if any) used 13 | by a Contributor and that particular Contributor's Contribution. 14 | 15 | 1.3. "Contribution" 16 | means Covered Software of a particular Contributor. 17 | 18 | 1.4. "Covered Software" 19 | means Source Code Form to which the initial Contributor has attached 20 | the notice in Exhibit A, the Executable Form of such Source Code 21 | Form, and Modifications of such Source Code Form, in each case 22 | including portions thereof. 23 | 24 | 1.5. "Incompatible With Secondary Licenses" 25 | means 26 | 27 | (a) that the initial Contributor has attached the notice described 28 | in Exhibit B to the Covered Software; or 29 | 30 | (b) that the Covered Software was made available under the terms of 31 | version 1.1 or earlier of the License, but not also under the 32 | terms of a Secondary License. 33 | 34 | 1.6. "Executable Form" 35 | means any form of the work other than Source Code Form. 36 | 37 | 1.7. "Larger Work" 38 | means a work that combines Covered Software with other material, in 39 | a separate file or files, that is not Covered Software. 40 | 41 | 1.8. "License" 42 | means this document. 43 | 44 | 1.9. "Licensable" 45 | means having the right to grant, to the maximum extent possible, 46 | whether at the time of the initial grant or subsequently, any and 47 | all of the rights conveyed by this License. 48 | 49 | 1.10. "Modifications" 50 | means any of the following: 51 | 52 | (a) any file in Source Code Form that results from an addition to, 53 | deletion from, or modification of the contents of Covered 54 | Software; or 55 | 56 | (b) any new file in Source Code Form that contains any Covered 57 | Software. 58 | 59 | 1.11. "Patent Claims" of a Contributor 60 | means any patent claim(s), including without limitation, method, 61 | process, and apparatus claims, in any patent Licensable by such 62 | Contributor that would be infringed, but for the grant of the 63 | License, by the making, using, selling, offering for sale, having 64 | made, import, or transfer of either its Contributions or its 65 | Contributor Version. 66 | 67 | 1.12. "Secondary License" 68 | means either the GNU General Public License, Version 2.0, the GNU 69 | Lesser General Public License, Version 2.1, the GNU Affero General 70 | Public License, Version 3.0, or any later versions of those 71 | licenses. 72 | 73 | 1.13. "Source Code Form" 74 | means the form of the work preferred for making modifications. 75 | 76 | 1.14. "You" (or "Your") 77 | means an individual or a legal entity exercising rights under this 78 | License. For legal entities, "You" includes any entity that 79 | controls, is controlled by, or is under common control with You. For 80 | purposes of this definition, "control" means (a) the power, direct 81 | or indirect, to cause the direction or management of such entity, 82 | whether by contract or otherwise, or (b) ownership of more than 83 | fifty percent (50%) of the outstanding shares or beneficial 84 | ownership of such entity. 85 | 86 | 2. License Grants and Conditions 87 | -------------------------------- 88 | 89 | 2.1. Grants 90 | 91 | Each Contributor hereby grants You a world-wide, royalty-free, 92 | non-exclusive license: 93 | 94 | (a) under intellectual property rights (other than patent or trademark) 95 | Licensable by such Contributor to use, reproduce, make available, 96 | modify, display, perform, distribute, and otherwise exploit its 97 | Contributions, either on an unmodified basis, with Modifications, or 98 | as part of a Larger Work; and 99 | 100 | (b) under Patent Claims of such Contributor to make, use, sell, offer 101 | for sale, have made, import, and otherwise transfer either its 102 | Contributions or its Contributor Version. 103 | 104 | 2.2. Effective Date 105 | 106 | The licenses granted in Section 2.1 with respect to any Contribution 107 | become effective for each Contribution on the date the Contributor first 108 | distributes such Contribution. 109 | 110 | 2.3. Limitations on Grant Scope 111 | 112 | The licenses granted in this Section 2 are the only rights granted under 113 | this License. No additional rights or licenses will be implied from the 114 | distribution or licensing of Covered Software under this License. 115 | Notwithstanding Section 2.1(b) above, no patent license is granted by a 116 | Contributor: 117 | 118 | (a) for any code that a Contributor has deleted from Covered Software; 119 | or 120 | 121 | (b) for infringements caused by: (i) Your and any other third party's 122 | modifications of Covered Software, or (ii) the combination of its 123 | Contributions with other software (except as part of its Contributor 124 | Version); or 125 | 126 | (c) under Patent Claims infringed by Covered Software in the absence of 127 | its Contributions. 128 | 129 | This License does not grant any rights in the trademarks, service marks, 130 | or logos of any Contributor (except as may be necessary to comply with 131 | the notice requirements in Section 3.4). 132 | 133 | 2.4. Subsequent Licenses 134 | 135 | No Contributor makes additional grants as a result of Your choice to 136 | distribute the Covered Software under a subsequent version of this 137 | License (see Section 10.2) or under the terms of a Secondary License (if 138 | permitted under the terms of Section 3.3). 139 | 140 | 2.5. Representation 141 | 142 | Each Contributor represents that the Contributor believes its 143 | Contributions are its original creation(s) or it has sufficient rights 144 | to grant the rights to its Contributions conveyed by this License. 145 | 146 | 2.6. Fair Use 147 | 148 | This License is not intended to limit any rights You have under 149 | applicable copyright doctrines of fair use, fair dealing, or other 150 | equivalents. 151 | 152 | 2.7. Conditions 153 | 154 | Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted 155 | in Section 2.1. 156 | 157 | 3. Responsibilities 158 | ------------------- 159 | 160 | 3.1. Distribution of Source Form 161 | 162 | All distribution of Covered Software in Source Code Form, including any 163 | Modifications that You create or to which You contribute, must be under 164 | the terms of this License. You must inform recipients that the Source 165 | Code Form of the Covered Software is governed by the terms of this 166 | License, and how they can obtain a copy of this License. You may not 167 | attempt to alter or restrict the recipients' rights in the Source Code 168 | Form. 169 | 170 | 3.2. Distribution of Executable Form 171 | 172 | If You distribute Covered Software in Executable Form then: 173 | 174 | (a) such Covered Software must also be made available in Source Code 175 | Form, as described in Section 3.1, and You must inform recipients of 176 | the Executable Form how they can obtain a copy of such Source Code 177 | Form by reasonable means in a timely manner, at a charge no more 178 | than the cost of distribution to the recipient; and 179 | 180 | (b) You may distribute such Executable Form under the terms of this 181 | License, or sublicense it under different terms, provided that the 182 | license for the Executable Form does not attempt to limit or alter 183 | the recipients' rights in the Source Code Form under this License. 184 | 185 | 3.3. Distribution of a Larger Work 186 | 187 | You may create and distribute a Larger Work under terms of Your choice, 188 | provided that You also comply with the requirements of this License for 189 | the Covered Software. If the Larger Work is a combination of Covered 190 | Software with a work governed by one or more Secondary Licenses, and the 191 | Covered Software is not Incompatible With Secondary Licenses, this 192 | License permits You to additionally distribute such Covered Software 193 | under the terms of such Secondary License(s), so that the recipient of 194 | the Larger Work may, at their option, further distribute the Covered 195 | Software under the terms of either this License or such Secondary 196 | License(s). 197 | 198 | 3.4. Notices 199 | 200 | You may not delete or alter the substance of any license notices 201 | (including copyright notices, patent notices, disclaimers of warranty, 202 | or limitations of liability) contained within the Source Code Form of 203 | the Covered Software, except that You may alter any license notices to 204 | the extent required to remedy known factual inaccuracies. 205 | 206 | 3.5. Application of Additional Terms 207 | 208 | You may choose to offer, and to charge a fee for, warranty, support, 209 | indemnity or liability obligations to one or more recipients of Covered 210 | Software. However, You may do so only on Your own behalf, and not on 211 | behalf of any Contributor. You must make it absolutely clear that any 212 | such warranty, support, indemnity, or liability obligation is offered by 213 | You alone, and You hereby agree to indemnify every Contributor for any 214 | liability incurred by such Contributor as a result of warranty, support, 215 | indemnity or liability terms You offer. You may include additional 216 | disclaimers of warranty and limitations of liability specific to any 217 | jurisdiction. 218 | 219 | 4. Inability to Comply Due to Statute or Regulation 220 | --------------------------------------------------- 221 | 222 | If it is impossible for You to comply with any of the terms of this 223 | License with respect to some or all of the Covered Software due to 224 | statute, judicial order, or regulation then You must: (a) comply with 225 | the terms of this License to the maximum extent possible; and (b) 226 | describe the limitations and the code they affect. Such description must 227 | be placed in a text file included with all distributions of the Covered 228 | Software under this License. Except to the extent prohibited by statute 229 | or regulation, such description must be sufficiently detailed for a 230 | recipient of ordinary skill to be able to understand it. 231 | 232 | 5. Termination 233 | -------------- 234 | 235 | 5.1. The rights granted under this License will terminate automatically 236 | if You fail to comply with any of its terms. However, if You become 237 | compliant, then the rights granted under this License from a particular 238 | Contributor are reinstated (a) provisionally, unless and until such 239 | Contributor explicitly and finally terminates Your grants, and (b) on an 240 | ongoing basis, if such Contributor fails to notify You of the 241 | non-compliance by some reasonable means prior to 60 days after You have 242 | come back into compliance. Moreover, Your grants from a particular 243 | Contributor are reinstated on an ongoing basis if such Contributor 244 | notifies You of the non-compliance by some reasonable means, this is the 245 | first time You have received notice of non-compliance with this License 246 | from such Contributor, and You become compliant prior to 30 days after 247 | Your receipt of the notice. 248 | 249 | 5.2. If You initiate litigation against any entity by asserting a patent 250 | infringement claim (excluding declaratory judgment actions, 251 | counter-claims, and cross-claims) alleging that a Contributor Version 252 | directly or indirectly infringes any patent, then the rights granted to 253 | You by any and all Contributors for the Covered Software under Section 254 | 2.1 of this License shall terminate. 255 | 256 | 5.3. In the event of termination under Sections 5.1 or 5.2 above, all 257 | end user license agreements (excluding distributors and resellers) which 258 | have been validly granted by You or Your distributors under this License 259 | prior to termination shall survive termination. 260 | 261 | ************************************************************************ 262 | * * 263 | * 6. Disclaimer of Warranty * 264 | * ------------------------- * 265 | * * 266 | * Covered Software is provided under this License on an "as is" * 267 | * basis, without warranty of any kind, either expressed, implied, or * 268 | * statutory, including, without limitation, warranties that the * 269 | * Covered Software is free of defects, merchantable, fit for a * 270 | * particular purpose or non-infringing. The entire risk as to the * 271 | * quality and performance of the Covered Software is with You. * 272 | * Should any Covered Software prove defective in any respect, You * 273 | * (not any Contributor) assume the cost of any necessary servicing, * 274 | * repair, or correction. This disclaimer of warranty constitutes an * 275 | * essential part of this License. No use of any Covered Software is * 276 | * authorized under this License except under this disclaimer. * 277 | * * 278 | ************************************************************************ 279 | 280 | ************************************************************************ 281 | * * 282 | * 7. Limitation of Liability * 283 | * -------------------------- * 284 | * * 285 | * Under no circumstances and under no legal theory, whether tort * 286 | * (including negligence), contract, or otherwise, shall any * 287 | * Contributor, or anyone who distributes Covered Software as * 288 | * permitted above, be liable to You for any direct, indirect, * 289 | * special, incidental, or consequential damages of any character * 290 | * including, without limitation, damages for lost profits, loss of * 291 | * goodwill, work stoppage, computer failure or malfunction, or any * 292 | * and all other commercial damages or losses, even if such party * 293 | * shall have been informed of the possibility of such damages. This * 294 | * limitation of liability shall not apply to liability for death or * 295 | * personal injury resulting from such party's negligence to the * 296 | * extent applicable law prohibits such limitation. Some * 297 | * jurisdictions do not allow the exclusion or limitation of * 298 | * incidental or consequential damages, so this exclusion and * 299 | * limitation may not apply to You. * 300 | * * 301 | ************************************************************************ 302 | 303 | 8. Litigation 304 | ------------- 305 | 306 | Any litigation relating to this License may be brought only in the 307 | courts of a jurisdiction where the defendant maintains its principal 308 | place of business and such litigation shall be governed by laws of that 309 | jurisdiction, without reference to its conflict-of-law provisions. 310 | Nothing in this Section shall prevent a party's ability to bring 311 | cross-claims or counter-claims. 312 | 313 | 9. Miscellaneous 314 | ---------------- 315 | 316 | This License represents the complete agreement concerning the subject 317 | matter hereof. If any provision of this License is held to be 318 | unenforceable, such provision shall be reformed only to the extent 319 | necessary to make it enforceable. Any law or regulation which provides 320 | that the language of a contract shall be construed against the drafter 321 | shall not be used to construe this License against a Contributor. 322 | 323 | 10. Versions of the License 324 | --------------------------- 325 | 326 | 10.1. New Versions 327 | 328 | Mozilla Foundation is the license steward. Except as provided in Section 329 | 10.3, no one other than the license steward has the right to modify or 330 | publish new versions of this License. Each version will be given a 331 | distinguishing version number. 332 | 333 | 10.2. Effect of New Versions 334 | 335 | You may distribute the Covered Software under the terms of the version 336 | of the License under which You originally received the Covered Software, 337 | or under the terms of any subsequent version published by the license 338 | steward. 339 | 340 | 10.3. Modified Versions 341 | 342 | If you create software not governed by this License, and you want to 343 | create a new license for such software, you may create and use a 344 | modified version of this License if you rename the license and delete 345 | any references to the name of the license steward (except to note that 346 | such modified license differs from this License). 347 | 348 | 10.4. Distributing Source Code Form that is Incompatible With Secondary 349 | Licenses 350 | 351 | If You choose to distribute Source Code Form that is Incompatible With 352 | Secondary Licenses under the terms of this version of the License, the 353 | notice described in Exhibit B of this License must be attached. 354 | 355 | Exhibit A - Source Code Form License Notice 356 | ------------------------------------------- 357 | 358 | This Source Code Form is subject to the terms of the Mozilla Public 359 | License, v. 2.0. If a copy of the MPL was not distributed with this 360 | file, You can obtain one at http://mozilla.org/MPL/2.0/. 361 | 362 | If it is not possible or desirable to put the notice in a particular 363 | file, then You may include the notice in a location (such as a LICENSE 364 | file in a relevant directory) where a recipient would be likely to look 365 | for such a notice. 366 | 367 | You may add additional accurate notices of copyright ownership. 368 | 369 | Exhibit B - "Incompatible With Secondary Licenses" Notice 370 | --------------------------------------------------------- 371 | 372 | This Source Code Form is "Incompatible With Secondary Licenses", as 373 | defined by the Mozilla Public License, v. 2.0. 374 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # korhah [![crates.io](https://img.shields.io/crates/v/korhah.svg)](https://crates.io/crates/korhah) [![docs.rs](https://img.shields.io/docsrs/korhah)](https://docs.rs/korhah) 2 | 3 | `korhah` is a minimal & extensible reactive event system. 4 | 5 | At its most basic, it allows users to register callback functions and emit _arbitrary_ custom events which will trigger those functions. 6 | 7 | It can also act as an object store, whose contents are accessible from within registered callback functions as well as from outside the system. 8 | 9 | To keep it minimal, only basic CRUD operations are provided along with signal-y behaviour via automatic dependency-tracking. 10 | 11 | To make it extensible, the built-in CRUD operations emit events that can be hooked into. 12 | 13 | ### Example Usage 14 | 15 | ```rust 16 | let mut system = korhah::System::default(); 17 | 18 | // create a simple variable in the reactive system 19 | let a = system.create(|_, _| 0).expect("no cancelling listeners registered"); 20 | // create a signal-y variable that depends on `a` 21 | let b = system.create(move |s, _| { 22 | // the dependency on `a` is automatically tracked here 23 | let a = s.read(a, |v| *v) 24 | .expect("no cancelling listeners registered") 25 | .expect("`a` exists"); 26 | // subsequent updates to `a` will recompute `b` according to this formula 27 | a + 1 28 | }).expect("no cancelling listeners registered"); 29 | 30 | // we can emit *any* 'static type we like as an event 31 | struct CustomEvent { 32 | n: i32, 33 | } 34 | 35 | // listen for our custom event being emitted in a "global" scope 36 | // (the "global" scope being due to specifying a `None` target) 37 | system.listen(None, move |s, e: &CustomEvent, _, _| { 38 | // we'll update `a` to the associated event info 39 | // (note that this should automatically update `b` too) 40 | _ = s.update(a, |v| *v = e.n); 41 | }); 42 | 43 | assert_eq!(Ok(Some(0)), system.read(a, |v| *v)); 44 | assert_eq!(Ok(Some(1)), system.read(b, |v| *v)); 45 | 46 | // emit our custom event 47 | _ = system.emit(None, &CustomEvent { n: 42 }); 48 | 49 | assert_eq!(Ok(Some(42)), system.read(a, |v| *v)); 50 | assert_eq!(Ok(Some(43)), system.read(b, |v| *v)); 51 | ``` 52 | 53 | #### `no_std` 54 | This crate is compatible with `no_std` environments, requiring only the `alloc` crate. 55 | 56 | #### (Un)Sync 57 | This crate can be used in both single-threaded and multi-threaded environments.\ 58 | In the spirit of [cargo features being additive](https://doc.rust-lang.org/cargo/reference/features.html#feature-unification), the stricter [`Send`](https://doc.rust-lang.org/core/marker/trait.Send.html) + [`Sync`](https://doc.rust-lang.org/core/marker/trait.Sync.html) bounds of a multi-threaded environment are assumed by default for variable types and callback types, and these bounds can be relaxed for single-threaded environments via the `unsync` feature. 59 | 60 | #### MSRV 61 | The minimum supported Rust version is **1.63.0**. 62 | 63 | --- 64 | -------------------------------------------------------------------------------- /examples/README.md: -------------------------------------------------------------------------------- 1 | # Examples 2 | 3 | - **counters**: a basic example demonstrating signal-y usage 4 | 5 | - **extension**: an example of extending the built-in CRUD functionality with your own behaviour 6 | 7 | - **dom**: a "practical" example of GUI-type usage 8 | 9 | - **interop**: an example showing patterns enabling interoperability with downstream resources -------------------------------------------------------------------------------- /examples/counters.rs: -------------------------------------------------------------------------------- 1 | use std::io::BufRead; 2 | 3 | struct InputEvent { 4 | line: String, 5 | } 6 | 7 | fn main() { 8 | let mut system = korhah::System::default(); 9 | 10 | // # lines 11 | let lines = system 12 | .create(|_, _| 0) 13 | .expect("no cancelling listeners registered"); 14 | 15 | system.listen(None, move |s, _: &InputEvent, _, _| { 16 | _ = s.update(lines, |v| *v += 1); 17 | }); 18 | 19 | // # characters 20 | let chars = system 21 | .create(move |_, _| 0) 22 | .expect("no cancelling listeners registered"); 23 | 24 | system.listen(None, move |s, e: &InputEvent, _, _| { 25 | _ = s.update(chars, |v| *v += e.line.chars().count()); 26 | }); 27 | 28 | // average # characters per line 29 | let average = system 30 | .create(move |s, _| { 31 | let lines = s 32 | .read(lines, |v| *v) 33 | .expect("no cancelling listeners registered") 34 | .expect("`lines` exists"); 35 | let chars = s 36 | .read(chars, |v| *v) 37 | .expect("no cancelling listeners registered") 38 | .expect("`chars` exists"); 39 | chars as f32 / lines as f32 40 | }) 41 | .expect("no cancelling listeners registered"); 42 | 43 | for line in std::io::stdin().lock().lines().flatten() { 44 | match line.as_str() { 45 | "@exit" => { 46 | println!("Exiting..."); 47 | break; 48 | } 49 | "@lines" => { 50 | println!( 51 | "-> {} lines read", 52 | system 53 | .read(lines, |v| *v) 54 | .expect("no cancelling listeners registered") 55 | .expect("`lines` exists") 56 | ); 57 | } 58 | "@chars" => { 59 | println!( 60 | "-> {} characters read", 61 | system 62 | .read(chars, |v| *v) 63 | .expect("no cancelling listeners registered") 64 | .expect("`chars` exists") 65 | ); 66 | } 67 | "@avg" => { 68 | println!( 69 | "-> average of {} characters read per line", 70 | system 71 | .read(average, |v| *v) 72 | .expect("no cancelling listeners registered") 73 | .expect("`average` exists") 74 | ); 75 | } 76 | _ => { 77 | _ = system.emit(None, &InputEvent { line }); 78 | } 79 | } 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /examples/dom.rs: -------------------------------------------------------------------------------- 1 | use korhah::{events::Created, System, Variable}; 2 | 3 | use std::io::BufRead; 4 | 5 | #[derive(Debug)] 6 | struct InputEvent(String); 7 | 8 | #[derive(Debug, Clone, Default)] 9 | struct State { 10 | focused: Option>, 11 | } 12 | 13 | #[derive(Debug, Clone, Default)] 14 | struct Element { 15 | parent: Option>, 16 | children: Vec>, 17 | text: Option, 18 | } 19 | 20 | fn main() { 21 | let mut dom = System::default(); 22 | 23 | // the DOM state is stored alongside the elements 24 | let state = dom 25 | .create(|_, _| State::default()) 26 | .expect("no cancelling listeners registered"); 27 | 28 | // automatically establish parent-child relationships when a new element is added to the DOM 29 | dom.listen(None, move |dom, e: &Created, _, _| { 30 | // should only be done if the new element has a parent element of course 31 | if let Ok(Some(Some(parent))) = dom.read(e.source, |el| el.parent) { 32 | _ = dom.update(parent, |el| el.children.push(e.source)); 33 | } 34 | }); 35 | 36 | // the `body` element will be the parent of the other elements 37 | let body = dom 38 | .create(|_, _| Element::default()) 39 | .expect("no cancelling listeners registered"); 40 | 41 | // the `input` element will receive `InputEvent`s and update its text to match 42 | let input = dom 43 | .create(move |_, _| Element { 44 | parent: Some(body), 45 | text: Some("".into()), 46 | children: vec![], 47 | }) 48 | .expect("no cancelling listeners registered"); 49 | 50 | // receive `InputEvent`s on the `input` element 51 | dom.listen(input, move |dom, e: &InputEvent, _, _| { 52 | _ = dom.update(input, |el| { 53 | if let Some(text) = el.text.as_mut() { 54 | text.push_str(&e.0); 55 | } else { 56 | el.text = Some(e.0.to_owned()); 57 | } 58 | }); 59 | }); 60 | 61 | // the `p` element will automatically update its text to match the text "entered" in the `input` element 62 | let p = dom 63 | .create(move |dom, _| Element { 64 | parent: Some(body), 65 | text: dom 66 | .read(input, |el| el.text.clone()) 67 | .expect("no cancelling listeners registered") 68 | .expect("`input` exists"), 69 | children: vec![], 70 | }) 71 | .expect("no cancelling listeners registered"); 72 | 73 | for line in std::io::stdin().lock().lines().flatten() { 74 | match line.as_str() { 75 | "exit" => { 76 | println!("Exiting..."); 77 | break; 78 | } 79 | // focus different elements 80 | "@" => { 81 | println!("-> removing focus"); 82 | _ = dom.update(state, |state| state.focused = None); 83 | } 84 | "@body" => { 85 | println!("-> focus `body`"); 86 | _ = dom.update(state, |state| state.focused = Some(body)); 87 | } 88 | "@input" => { 89 | println!("-> focus `input`"); 90 | _ = dom.update(state, |state| state.focused = Some(input)); 91 | } 92 | "@p" => { 93 | println!("-> focus `p`"); 94 | _ = dom.update(state, |state| state.focused = Some(p)); 95 | } 96 | // retrieve info 97 | "#state" => { 98 | _ = dom.read(state, |state| println!("STATE: {state:?}")); 99 | } 100 | "#dom" => { 101 | _ = dom.read(body, |el| println!("BODY: {el:?}")); 102 | _ = dom.read(input, |el| println!("INPUT: {el:?}")); 103 | _ = dom.read(p, |el| println!("P: {el:?}")); 104 | } 105 | "#body" => { 106 | _ = dom.read(body, |el| println!("BODY: {el:?}")); 107 | } 108 | "#input" => { 109 | _ = dom.read(input, |el| println!("INPUT: {el:?}")); 110 | } 111 | "#p" => { 112 | _ = dom.read(p, |el| println!("P: {el:?}")); 113 | } 114 | // clear the `input` element 115 | "$clear" => { 116 | println!("-> clearing `input`"); 117 | _ = dom.update(input, |el| el.text = None); 118 | } 119 | _ => { 120 | if let Ok(Some(Some(focused))) = dom.read(state, |state| state.focused) { 121 | let event = InputEvent(line); 122 | println!("-> emitting {event:?}"); 123 | _ = dom.emit(focused, &event); 124 | } else { 125 | println!("-> no element has focus"); 126 | } 127 | } 128 | } 129 | } 130 | } 131 | -------------------------------------------------------------------------------- /examples/extension.rs: -------------------------------------------------------------------------------- 1 | use std::{collections::HashMap, io::BufRead}; 2 | 3 | use korhah::{ 4 | events::{Created, Updated, Updating}, 5 | System, Variable, Vote, 6 | }; 7 | 8 | #[derive(Debug, Default, Clone, Copy)] 9 | struct Item(usize); 10 | 11 | // our custom `Update` event which combines the built-in `Updating` & `Updated` events to 12 | // provide a `prev` and `next` value to better inform possible cancellation of the update 13 | struct Update { 14 | prev: Item, 15 | next: Item, 16 | } 17 | 18 | fn main() { 19 | let mut system = System::default(); 20 | 21 | // track the previous values of variables for which our custom updates are underway 22 | let prev_values = system 23 | .create(|_, _| HashMap::, Item>::new()) 24 | .expect("no cancelling listeners registered"); 25 | 26 | // a flag that is used to circumvent our custom `Update` logic to allow "normal" variable updates to occur whenever 27 | // our custom `Update` needs undoing 28 | let undoing = system 29 | .create(|_, _| false) 30 | .expect("no cancelling listeners registered"); 31 | 32 | // a test flag that cancels all of our custom `Update` events when set 33 | let should_cancel = system 34 | .create(|_, _| false) 35 | .expect("no cancelling listeners registered"); 36 | 37 | // hook into the creation of all `Item` variables in order to define global behaviours 38 | system.listen(None, move |s, e: &Created, _, _| { 39 | let target = e.source; 40 | 41 | s.listen(target, move |s, _: &Updating, _, _| { 42 | // if we're undoing our custom `Update` event, we need to skip over our custom logic in order to prevent an infinite cycle 43 | if !s 44 | .read(undoing, |v| *v) 45 | .expect("no `Read`-cancelling listeners registered") 46 | .expect("`undoing` exists") 47 | { 48 | // store the previous value of the target, to be retrieved by the `Updated` event later 49 | let prev = s 50 | .read(target, |v| *v) 51 | .expect("no `Read`-cancelling listeners registered") 52 | .expect("`e.source` exists"); 53 | _ = s.update(prev_values, |v| { 54 | v.insert(target, prev); 55 | }); 56 | } 57 | }); 58 | 59 | s.listen(target, move |s, _: &Updated, _, _| { 60 | // as above, we prevent an infinite cycle while undoing 61 | if !s 62 | .read(undoing, |v| *v) 63 | .expect("no `Read`-cancelling listeners registered") 64 | .expect("`undoing` exists") 65 | { 66 | // retrieve the information for our custom `Update` event 67 | let prev = s 68 | .update(prev_values, |v| v.remove(&target)) // we no longer need the previous value 69 | .expect("`Update` wasn't cancelled") 70 | .flatten() 71 | .expect("`prev_values` exists and contained `e.source`"); 72 | let next = s 73 | .read(target, |v| *v) 74 | .expect("no `Read`-cancelling listeners registered") 75 | .expect("`e.source` exists"); 76 | 77 | // let's abandon our custom `Update` event if it is aborted, or if the votes to cancel >= the votes to proceed 78 | let undo = match s.emit(target, &Update { prev, next }) { 79 | Ok(votes) => votes.cancel > votes.proceed, 80 | Err(_) => true, 81 | }; 82 | if undo { 83 | // set the undo flag so we can revert our changes without entering an infinite cycle 84 | _ = s.update(undoing, |v| *v = true); 85 | // restore the target to its previous value 86 | _ = s.update(target, |v| *v = prev); 87 | } 88 | } else { 89 | // the undoing is complete, we can reset the flag for the next time 90 | _ = s.update(undoing, |v| *v = false); 91 | } 92 | }); 93 | 94 | s.listen(target, move |s, e: &Update, vote, _| { 95 | // while `should_cancel` is set, our `Update` event will always be cancelled, so no updates should happen 96 | let should_cancel = s 97 | .read(should_cancel, |v| *v) 98 | .expect("no `Read`-cancelling listeners registered") 99 | .expect("`should_cancel` exists"); 100 | if should_cancel { 101 | *vote = Vote::Cancel; 102 | println!("-> prevented change: {} => {}", e.prev.0, e.next.0); 103 | } else { 104 | println!("-> made change: {} => {}", e.prev.0, e.next.0); 105 | } 106 | }); 107 | }); 108 | 109 | // our testing variable 110 | let x = system 111 | .create(|_, _| Item::default()) 112 | .expect("no cancelling listeners registered"); 113 | 114 | for line in std::io::stdin().lock().lines().flatten() { 115 | match line.as_str() { 116 | "@exit" => { 117 | println!("Exiting..."); 118 | break; 119 | } 120 | "@toggle" => { 121 | // toggle whether or not subsequent `Update` events should be cancelled 122 | _ = system.update(should_cancel, |v| *v = !*v); 123 | } 124 | "@val" => { 125 | // print the current value of our testing variable `x` 126 | _ = system.read(x, |v| println!("-> x = {}", v.0)); 127 | } 128 | _ => { 129 | // otherwise we show of our `Update` event by setting our test variable to the # chars read 130 | _ = system.update(x, |v| *v = Item(line.chars().count())); 131 | } 132 | } 133 | } 134 | } 135 | -------------------------------------------------------------------------------- /examples/interop.rs: -------------------------------------------------------------------------------- 1 | use std::{ 2 | error::Error, 3 | io::BufRead, 4 | sync::{Arc, Mutex}, 5 | }; 6 | 7 | // a demo resource that needs to interact with `korhah` downstream 8 | struct Resource { 9 | counter: usize, 10 | } 11 | 12 | impl Resource { 13 | fn new(options: Options) -> Self { 14 | Self { 15 | counter: options.initial, 16 | } 17 | } 18 | 19 | // an example operation on the resource that requires mutable access 20 | fn modify(&mut self) { 21 | self.counter += 1; 22 | } 23 | } 24 | 25 | // our troublesome demo resource options that can't be easily moved into closures as 26 | // they don't implement `Clone` / `Copy` 27 | struct Options { 28 | initial: usize, 29 | } 30 | 31 | struct InputEvent; 32 | 33 | fn main() -> Result<(), Box> { 34 | let mut system = korhah::System::default(); 35 | 36 | // approach #1 - Arc + Mutex 37 | 38 | // the options are defined out here to simulate a downstream user passing their own options 39 | let options = Options { initial: 1 }; 40 | let resource1 = Arc::new(Mutex::new(Resource::new(options))); 41 | 42 | let resource = resource1.clone(); 43 | system.listen(None, move |_, _: &InputEvent, _, _| { 44 | let mut resource = resource.lock().expect("mutex lock acquired"); 45 | resource.modify(); 46 | println!("-> approach #1 - {}", resource.counter); 47 | }); 48 | 49 | // approach #2 - within `korhah` 50 | 51 | // the options are defined out here to simulate a downstream user passing their own options 52 | let options = Options { initial: 10 }; 53 | let resource2 = { 54 | // this commented-out attempt fails, as the `Create` needs to be able to be run an arbitrary 55 | // number on times (ie: is an `Fn`) in case it reads other variables and thus needs 56 | // its recipe recomputed whenever one of them changes 57 | // let resource = system 58 | // .create(move |_, _| Resource::new(options)) 59 | // .expect("no cancelling listeners registered"); 60 | 61 | // this attempt succeeds, since we instantiate an "empty" variable in the `Create` recipe, 62 | // and only initialise it in an `Update` callback into which the options can be safely 63 | // moved, as it's only run once (ie: is an `FnOnce`) 64 | let resource = system 65 | .create(|_, _| Option::::None) 66 | .expect("no cancelling listeners registered"); 67 | _ = system.update(resource, move |v| { 68 | let resource = Resource::new(options); 69 | *v = Some(resource); 70 | }); 71 | resource 72 | }; 73 | 74 | system.listen(None, move |s, _: &InputEvent, _, _| { 75 | _ = s.update(resource2, |v| v.as_mut().map(|v| v.modify())); 76 | _ = s.read(resource2, |v| { 77 | v.as_ref() 78 | .map(|v| println!("-> approach #2 - {}", v.counter)) 79 | }); 80 | }); 81 | 82 | for line in std::io::stdin().lock().lines().flatten() { 83 | match line.as_str() { 84 | "@exit" => { 85 | println!("Exiting..."); 86 | break; 87 | } 88 | _ => { 89 | _ = system.emit(None, &InputEvent); 90 | } 91 | } 92 | } 93 | 94 | Ok(()) 95 | } 96 | -------------------------------------------------------------------------------- /src/compat.rs: -------------------------------------------------------------------------------- 1 | pub use compat::*; 2 | 3 | #[cfg(not(feature = "unsync"))] 4 | mod compat { 5 | use alloc::boxed::Box; 6 | use core::any::Any; 7 | 8 | pub(crate) use ::spin::{Mutex as Cell, MutexGuard as Guard}; 9 | pub(crate) use alloc::sync::Arc as Rc; 10 | 11 | use crate::{listener::Vote, system::System}; 12 | 13 | pub trait VariableBounds: Any + Send + Sync {} 14 | impl VariableBounds for T {} 15 | 16 | pub trait FnBounds: Send + Sync {} 17 | impl FnBounds for F {} 18 | 19 | pub(crate) type Value = Box; 20 | 21 | pub(crate) type Handler<'a> = 22 | Rc, &dyn Any, &mut Vote, &mut bool) + Send + Sync + 'a>; 23 | pub(crate) type Recipe<'a> = Rc) -> Value + Send + Sync + 'a>; 24 | } 25 | 26 | #[cfg(feature = "unsync")] 27 | mod compat { 28 | use alloc::boxed::Box; 29 | use core::any::Any; 30 | 31 | pub(crate) use alloc::rc::Rc; 32 | pub(crate) use core::cell::{RefCell as Cell, RefMut as Guard}; 33 | 34 | use crate::{listener::Vote, system::System}; 35 | 36 | pub trait VariableBounds: Any {} 37 | impl VariableBounds for T {} 38 | 39 | pub trait FnBounds {} 40 | impl FnBounds for F {} 41 | 42 | pub(crate) type Value = Box; 43 | 44 | pub(crate) type Handler<'a> = Rc, &dyn Any, &mut Vote, &mut bool) + 'a>; 45 | pub(crate) type Recipe<'a> = Rc) -> Value + 'a>; 46 | } 47 | -------------------------------------------------------------------------------- /src/events.rs: -------------------------------------------------------------------------------- 1 | use crate::{compat::VariableBounds, variable::Variable}; 2 | 3 | /// A variable is about to be created.\ 4 | /// If this event is cancelled, the variable will not be created.\ 5 | /// Since it's impossible to listen for this event prior to the variable existing, it's emitted in the global scope. 6 | #[derive(educe::Educe)] 7 | #[educe(Clone, Copy)] 8 | pub struct Creating { 9 | /// The value that will be given to the newly-created variable 10 | pub value: T, 11 | } 12 | 13 | /// A variable has just been created.\ 14 | /// Cancelling this event has no effect.\ 15 | /// Since it's impossible to listen for this event prior to the variable existing, it's emitted in the global scope. 16 | #[derive(educe::Educe)] 17 | #[educe(Clone, Copy)] 18 | pub struct Created { 19 | /// The variable that was just created 20 | pub source: Variable, 21 | } 22 | 23 | /// The targeted variable is about to be read.\ 24 | /// If this event is cancelled, the variable will not be read. 25 | #[derive(Clone, Copy)] 26 | pub struct Reading; 27 | 28 | /// The targeted variable has just been read.\ 29 | /// Cancelling this event has no effect. 30 | #[derive(Clone, Copy)] 31 | pub struct Read; 32 | 33 | /// The targeted variable is about to be updated.\ 34 | /// If this event is cancelled, the variable will not be updated. 35 | #[derive(Clone, Copy)] 36 | pub struct Updating; 37 | 38 | /// The targeted variable has just been updated.\ 39 | /// Cancelling this event has no effect. 40 | #[derive(Clone, Copy)] 41 | pub struct Updated; 42 | 43 | /// The targeted variable is about to be deleted.\ 44 | /// If this event is cancelled, the variable will not be deleted. 45 | #[derive(Clone, Copy)] 46 | pub struct Deleting; 47 | 48 | /// A variable has just been deleted.\ 49 | /// Cancelling this event has no effect.\ 50 | /// Since the targeted variable no longer exists in the system, this event is emitted in the global scope.\ 51 | /// The deleted variable is provided in case any cleanup is required external to the system- it should not be used in any system operations. 52 | #[derive(educe::Educe)] 53 | #[educe(Clone, Copy)] 54 | pub struct Deleted { 55 | /// The variable that was just deleted- it should not be used for any interactions with the system 56 | pub _source: Variable, 57 | } 58 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | #![no_std] 2 | #![doc = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/README.md"))] 3 | 4 | extern crate alloc; 5 | 6 | mod compat; 7 | /// Events that are emitted as a result of built-in CRUD actions 8 | pub mod events; 9 | mod listener; 10 | mod system; 11 | mod variable; 12 | 13 | pub(crate) type Id = u128; 14 | 15 | pub use listener::{Listener, Vote, Votes}; 16 | pub use system::System; 17 | pub use variable::Variable; 18 | -------------------------------------------------------------------------------- /src/listener.rs: -------------------------------------------------------------------------------- 1 | use crate::Id; 2 | 3 | use core::marker::PhantomData; 4 | 5 | /// A typed handle to a listener in the reactive system 6 | #[derive(educe::Educe)] 7 | #[educe(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] 8 | pub struct Listener { 9 | pub(crate) id: Id, 10 | pub(crate) target: Option, 11 | pub(crate) _e: PhantomData, 12 | } 13 | 14 | /// Represents a certain event handler's preference as to whether or not the effects from its corresponding event should be followed through 15 | #[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash)] 16 | pub enum Vote { 17 | /// Choose to abstain from voting 18 | #[default] 19 | Abstain, 20 | /// Vote to cancel the effects of an event 21 | Cancel, 22 | /// Vote to proceed with the effects of an event 23 | Proceed, 24 | } 25 | 26 | /// Represents the consensus among event handlers as to whether or not the effects from their corresponding event should be followed through.\ 27 | /// Effects of built-in events are followed through if the number of votes to proceed >= the number of votes to cancel.\ 28 | /// Custom events decide their own criteria for acting on these results, if at all. 29 | #[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash)] 30 | pub struct Votes { 31 | /// The number of event handlers who chose to abstain from voting 32 | pub abstain: usize, 33 | /// The number of event handlers who voted to cancel the event 34 | pub cancel: usize, 35 | /// The number of event handlers who voted to proceed with the event 36 | pub proceed: usize, 37 | } 38 | -------------------------------------------------------------------------------- /src/system.rs: -------------------------------------------------------------------------------- 1 | use crate::{ 2 | compat::{Cell, FnBounds, Guard, Handler, Rc, Recipe, Value, VariableBounds}, 3 | events::{Created, Creating, Deleted, Deleting, Read, Reading, Updated, Updating}, 4 | listener::{Listener, Vote, Votes}, 5 | variable::{Variable, VariableId}, 6 | Id, 7 | }; 8 | 9 | use alloc::{ 10 | boxed::Box, 11 | collections::{BTreeMap, BTreeSet}, 12 | vec::Vec, 13 | }; 14 | use core::{ 15 | any::{Any, TypeId}, 16 | marker::PhantomData, 17 | }; 18 | 19 | use ahash::RandomState; 20 | use indexmap::IndexMap; 21 | 22 | /// The reactive system 23 | #[derive(Clone, Default)] 24 | pub struct System<'x>(pub(crate) Rc>>); 25 | 26 | #[derive(Default)] 27 | pub(crate) struct SystemInner<'x> { 28 | next_id: Id, 29 | id_pool: Vec, 30 | /// while a tracking ID is set, system reads establish a dependency between the tracked variable and the variable being read 31 | tracking_id: Option, 32 | dependencies: BTreeMap>, 33 | values: BTreeMap, 34 | recipes: BTreeMap>, 35 | listeners: BTreeMap, IndexMap, RandomState>>>, 36 | } 37 | 38 | impl<'x> System<'x> { 39 | fn hold(&self) -> Guard<'_, SystemInner<'x>> { 40 | #[cfg(not(feature = "unsync"))] 41 | { 42 | self.0.lock() 43 | } 44 | #[cfg(feature = "unsync")] 45 | { 46 | self.0.borrow_mut() 47 | } 48 | } 49 | 50 | /// Create a new variable in the reactive system.\ 51 | /// The `recipe` parameter computes the value of the variable- it receives a read-only handle to the system, and the 52 | /// previous value of the variable ([`None`] on creation, [`Some`] for subsequent updates).\ 53 | /// Variables that are read within the recipe are automatically tracked- whenever any of them are updated, a re-run of 54 | /// the recipe is triggered to update this new variable's value.\ 55 | /// The creation of this variable (and any subsequent updates to it) can only be cancelled _after_ the recipe has already 56 | /// been run, so care should be taken to avoid unwanted side-effects- however, since the recipe is read-only, it should be 57 | /// difficult to accidentally go wrong, as it will by default be idempotent. 58 | /// 59 | /// Returns: 60 | /// - [`Err`], if the action was cancelled 61 | /// - an [`Ok`] value containing the new variable, otherwise 62 | /// 63 | /// # Example 64 | /// ``` 65 | /// let mut system = korhah::System::default(); 66 | /// 67 | /// let a = system.create(|_, _| 0).expect("no cancelling listeners registered"); 68 | /// let b = system.create(move |s, _| { 69 | /// // `b`'s dependency on `a` is automatically tracked here 70 | /// s 71 | /// .read(a, |v| *v + 1) 72 | /// .expect("no cancelling listeners registered") 73 | /// .expect("`a` was not deleted") 74 | /// }).expect("no cancelling listeners registered"); 75 | /// assert_eq!(Ok(Some(1)), system.read(b, |v| *v)); 76 | /// 77 | /// _ = system.update(a, |v| *v += 1); 78 | /// assert_eq!(Ok(Some(2)), system.read(b, |v| *v)); 79 | /// ``` 80 | pub fn create(&mut self, recipe: F) -> Result, ()> 81 | where 82 | T: VariableBounds, 83 | F: Fn(&System<'x>, Option) -> T + FnBounds + 'x, 84 | { 85 | SystemInner::create(self.clone(), recipe) 86 | } 87 | 88 | /// Read the value of a variable in the reactive system.\ 89 | /// The `callback` parameter computes the value to be returned from this function- it receives a read-only reference to the target variable's current value. 90 | /// 91 | /// Returns: 92 | /// - [`Err`], if the action was cancelled 93 | /// - an [`Ok`] value containing [`None`], if the target variable doesn't exist 94 | /// - an [`Ok`] value containing a [`Some`] value containing the result of the passed callback, otherwise 95 | /// 96 | /// # Example 97 | /// ``` 98 | /// let mut system = korhah::System::default(); 99 | /// 100 | /// let a = system.create(|_, _| 0).expect("no cancelling listeners registered"); 101 | /// 102 | /// assert_eq!(Ok(Some(true)), system.read(a, |v| *v < 5)); 103 | /// 104 | /// _ = system.delete(a); 105 | /// assert_eq!(Ok(None), system.read(a, |v| *v + 1)); 106 | /// ``` 107 | pub fn read(&self, variable: Variable, callback: F) -> Result, ()> 108 | where 109 | T: VariableBounds, 110 | F: FnOnce(&T) -> S, 111 | { 112 | SystemInner::read(self.clone(), variable, callback) 113 | } 114 | 115 | /// Update the value of a variable in the reactive system.\ 116 | /// The `callback` parameter performs the update, and optionally returns a value to the caller- it receives 117 | /// a mutable reference to the target variable's current value. 118 | /// 119 | /// Returns: 120 | /// - [`Err`], if the action was cancelled 121 | /// - an [`Ok`] value containing [`None`], if the target variable doesn't exist 122 | /// - an [`Ok`] value containing a [`Some`] value containing the result of the passed callback, otherwise 123 | /// 124 | /// # Example 125 | /// ``` 126 | /// let mut system = korhah::System::default(); 127 | /// 128 | /// let a = system.create(|_, _| 0).expect("no cancelling listeners registered"); 129 | /// 130 | /// assert_eq!(Ok(Some(())), system.update(a, |v| *v += 1)); 131 | /// assert_eq!(Ok(Some(1)), system.read(a, |v| *v)); 132 | /// 133 | /// _ = system.delete(a); 134 | /// assert_eq!(Ok(None), system.update(a, |v| *v += 2)); 135 | /// ``` 136 | pub fn update(&mut self, variable: Variable, callback: F) -> Result, ()> 137 | where 138 | T: VariableBounds, 139 | F: FnOnce(&mut T) -> S, 140 | { 141 | SystemInner::update(self.clone(), variable, callback) 142 | } 143 | 144 | /// Remove a variable from the reactive system. 145 | /// 146 | /// Returns: 147 | /// - [`Err`], if the action was cancelled (including if deleting the target variable would leave dangling references) 148 | /// - an [`Ok`] value containing [`None`], if the target variable doesn't exist 149 | /// - an [`Ok`] value containing the most recent value of the deleted variable, otherwise 150 | /// 151 | /// # Example 152 | /// ``` 153 | /// let mut system = korhah::System::default(); 154 | /// 155 | /// let a = system.create(|_, _| 0).expect("no cancelling listeners registered"); 156 | /// let b = system.create(move |s, _| { 157 | /// s 158 | /// .read(a, |v| *v + 1) 159 | /// .expect("no cancelling listeners registered") 160 | /// .expect("`a` was not deleted") 161 | /// }).expect("no cancelling listeners registered"); 162 | /// 163 | /// // can't delete `a` as `b` depends on it 164 | /// assert_eq!(Err(()), system.delete(a)); 165 | /// 166 | /// // if we delete `b` first, we can then delete `a` as it has no dependents 167 | /// assert_eq!(Ok(Some(1)), system.delete(b)); 168 | /// assert_eq!(Ok(Some(0)), system.delete(a)); 169 | /// 170 | /// // now `a` doesn't exist 171 | /// assert_eq!(Ok(None), system.delete(a)); 172 | /// ``` 173 | pub fn delete(&mut self, variable: Variable) -> Result, ()> 174 | where 175 | T: VariableBounds, 176 | { 177 | SystemInner::delete(self.clone(), variable) 178 | } 179 | 180 | /// Register a handler that will be called when a certain event is triggered in the reactive system.\ 181 | /// A [`None`] target listens for an event in the global scope, whereas a [`Some`] target listens for an event on that specific variable.\ 182 | /// The `handler` parameter receives a read-write handle to the system, as well as: 183 | /// - a reference to the triggered event 184 | /// - a mutable reference that can be used to cast the handler's vote on the triggered event (see [`Vote`], [`Votes`]) 185 | /// - a mutable reference that can be used to abort the triggered event 186 | /// 187 | /// Events are uniquely identified by their type, so type annotations are always required for the event argument of the handler. 188 | /// 189 | /// Returns: 190 | /// - [`None`], if the target variable doesn't exist 191 | /// - a [`Some`] value containing the new listener, otherwise 192 | /// 193 | /// # Example 194 | /// ``` 195 | /// struct CustomEvent { 196 | /// n: usize, 197 | /// } 198 | /// 199 | /// let mut system = korhah::System::default(); 200 | /// 201 | /// let listener = system.listen(None, move |_, e: &CustomEvent, vote, abort| { 202 | /// if e.n == 1 { 203 | /// *vote = korhah::Vote::Cancel; 204 | /// } else if e.n == 2 { 205 | /// *abort = true; 206 | /// } 207 | /// }).expect("can always listen in the global scope"); 208 | /// 209 | /// let votes = system.emit(None, &CustomEvent { n: 0 }).expect("not aborted if n == 0"); 210 | /// assert!(votes.cancel <= votes.proceed); 211 | /// 212 | /// let votes = system.emit(None, &CustomEvent { n: 1 }).expect("not aborted if n == 1"); 213 | /// assert!(votes.cancel >= votes.proceed); 214 | /// 215 | /// assert!(system.emit(None, &CustomEvent { n: 2 }).is_err()); 216 | /// ``` 217 | pub fn listen( 218 | &self, 219 | target: impl Into>, 220 | handler: F, 221 | ) -> Option> 222 | where 223 | E: 'static, 224 | F: Fn(&mut System<'x>, &E, &mut Vote, &mut bool) + FnBounds + 'x, 225 | { 226 | SystemInner::listen(self.clone(), target, handler) 227 | } 228 | 229 | /// Trigger the given event in the reactive system.\ 230 | /// A [`None`] target triggers an event in the global scope, whereas a [`Some`] target triggers an event on that specific variable. 231 | /// 232 | /// Returns: 233 | /// - [`Err`], if any of the triggered handlers aborted the event 234 | /// - an [`Ok`] value containing the consensus among the triggered handlers on the event's effects, otherwise (see [`Votes`]) 235 | /// 236 | /// # Example 237 | /// ``` 238 | /// struct CustomEvent; 239 | /// 240 | /// let mut system = korhah::System::default(); 241 | /// 242 | /// let triggered = system.create(|_, _| false).expect("no cancelling listeners registered"); 243 | /// system.listen(None, move |s, _: &CustomEvent, _, abort| { 244 | /// if s.read(triggered, |v| *v) 245 | /// .expect("no cancelling listeners registered") 246 | /// .expect("`a` exists") 247 | /// { 248 | /// *abort = true; 249 | /// } else { 250 | /// _ = s.update(triggered, |v| *v = true); 251 | /// } 252 | /// }); 253 | /// 254 | /// assert!(system.emit(None, &CustomEvent).is_ok()); 255 | /// assert!(system.emit(None, &CustomEvent).is_err()); 256 | /// ``` 257 | pub fn emit(&mut self, target: impl Into>, event: &E) -> Result 258 | where 259 | E: 'static, 260 | { 261 | SystemInner::emit(self.clone(), target, event) 262 | } 263 | 264 | /// Remove the given event listener from the reactive system. 265 | /// 266 | /// Returns: 267 | /// - [`None`], if the target event listener doesn't exist 268 | /// - [`Some`], otherwise 269 | /// 270 | /// # Example 271 | /// ``` 272 | /// struct CustomEvent; 273 | /// 274 | /// let mut system = korhah::System::default(); 275 | /// 276 | /// let x = system.create(|_, _| 0).expect("no cancelling listeners registered"); 277 | /// let listener = system.listen(None, move |s, _: &CustomEvent, _, _| { 278 | /// _ = s.update(x, |v| *v += 1); 279 | /// }).expect("can always listen in the global scope"); 280 | /// 281 | /// _ = system.emit(None, &CustomEvent); 282 | /// assert_eq!(Ok(Some(1)), system.read(x, |v| *v)); 283 | /// _ = system.emit(None, &CustomEvent); 284 | /// assert_eq!(Ok(Some(2)), system.read(x, |v| *v)); 285 | /// 286 | /// assert!(system.silence(listener).is_some()); 287 | /// 288 | /// _ = system.emit(None, &CustomEvent); 289 | /// assert_eq!(Ok(Some(2)), system.read(x, |v| *v)); 290 | /// 291 | /// assert!(system.silence(listener).is_none()); 292 | /// ``` 293 | pub fn silence(&mut self, listener: Listener) -> Option<()> 294 | where 295 | E: 'static, 296 | { 297 | SystemInner::silence(self.clone(), listener) 298 | } 299 | } 300 | 301 | impl<'x> SystemInner<'x> { 302 | /// add a new variable to the reactive system 303 | fn create(mut this: System<'x>, recipe: F) -> Result, ()> 304 | where 305 | T: VariableBounds, 306 | F: Fn(&System<'x>, Option) -> T + FnBounds + 'x, 307 | { 308 | // previously-deleted IDs are reused if possible, otherwise new IDs are allocated by incrementing a global counter 309 | let id = { 310 | // use an intermediate variable to avoid deadlock 311 | let reusable_id = this.hold().id_pool.pop(); 312 | reusable_id.unwrap_or_else(|| { 313 | let id = this.hold().next_id; 314 | this.hold().next_id += 1; 315 | id 316 | }) 317 | }; 318 | 319 | // ensure the new variable's dependencies, if any, are tracked 320 | this.hold().tracking_id = Some(id); 321 | let value = recipe(&this, None); 322 | this.hold().tracking_id = None; 323 | 324 | let event = Creating { value }; 325 | // since the variable is not yet created, it's impossible to listen for its local events at this point, so 326 | // the `Creating` event is only emitted in the global scope 327 | if this 328 | .emit(None, &event) 329 | .map(|votes| votes.cancel > votes.proceed) 330 | .unwrap_or(true) 331 | { 332 | // since the `Creating` event has been cancelled, the ID we selected hasn't ended up being used, so we free it 333 | this.hold().id_pool.push(id); 334 | return Err(()); 335 | } 336 | 337 | // reclaim the newly-created value after having temporarily loaned it to the `Creating` event 338 | let value = event.value; 339 | // store the type-erased initial value 340 | this.hold().values.insert(id, Box::new(value)); 341 | // we have to wrap the recipe somewhat, in order to supply the previous value of the variable as an argument to it 342 | // and to type-erase its return value 343 | this.hold().recipes.insert( 344 | id, 345 | Rc::new(move |s| { 346 | let prev = s 347 | .hold() 348 | .values 349 | .remove(&id) 350 | .and_then(|v| v.downcast().ok()) 351 | .map(|v| *v); 352 | Box::new(recipe(s, prev)) 353 | }), 354 | ); 355 | 356 | let variable = Variable { 357 | id, 358 | _t: PhantomData, 359 | }; 360 | 361 | // same as the `Creating` event, the `Created` event is emitted only in the global scope as it's impossible to 362 | // listen for it locally ahead of time 363 | // we don't care if the `Created` event is cancelled, as it doesn't prevent any subsequent actions 364 | _ = this.emit(None, &Created { source: variable }); 365 | 366 | Ok(variable) 367 | } 368 | 369 | /// read the value of a variable in the reactive system 370 | fn read( 371 | mut this: System<'x>, 372 | variable: Variable, 373 | callback: F, 374 | ) -> Result, ()> 375 | where 376 | T: VariableBounds, 377 | F: FnOnce(&T) -> S, 378 | { 379 | if !this.hold().values.contains_key(&variable.id) { 380 | // the target variable doesn't exist so we ignore this request 381 | return Ok(None); 382 | } 383 | 384 | // the `Reading` event is cancellable 385 | if this 386 | .emit(variable, &Reading) 387 | .map(|votes| votes.cancel > votes.proceed) 388 | .unwrap_or(true) 389 | { 390 | return Err(()); 391 | } 392 | 393 | // store the tracking ID serparately to avoid deadlock 394 | let dependent = this.hold().tracking_id; 395 | if let Some(dependent) = dependent { 396 | // this variable is being read as part of a new variable's recipe, so we track the dependency 397 | // in order to trigger updates when the new variable is changed, and to prevent dangling references 398 | this.hold() 399 | .dependencies 400 | .entry(variable.id) 401 | .or_default() 402 | .insert(dependent); 403 | } 404 | 405 | // compute the result of the passed callback 406 | let ret = callback( 407 | // this type system should prevent downcasting errors here, so `unwrap` is used here to preserve the semantic meaning of 408 | // an `Ok(Some)`, `Ok(None)`, or `Err` return value from this function 409 | this.hold() 410 | .values 411 | .get(&variable.id) 412 | .unwrap() 413 | .downcast_ref() 414 | .unwrap(), 415 | ); 416 | 417 | // we don't care if `Read` events are cancelled as there are no subsequent actions to take 418 | _ = this.emit(variable, &Read); 419 | 420 | Ok(Some(ret)) 421 | } 422 | 423 | /// update the value of a variable in the reactive system 424 | fn update( 425 | mut this: System<'x>, 426 | variable: Variable, 427 | callback: F, 428 | ) -> Result, ()> 429 | where 430 | T: VariableBounds, 431 | F: FnOnce(&mut T) -> S, 432 | { 433 | if !this.hold().values.contains_key(&variable.id) { 434 | // the target variable doesn't exist so we ignore this request 435 | return Ok(None); 436 | } 437 | 438 | // the `Updating` event is cancellable 439 | if this 440 | .emit(variable, &Updating) 441 | .map(|votes| votes.cancel > votes.proceed) 442 | .unwrap_or(true) 443 | { 444 | return Err(()); 445 | } 446 | 447 | // invoke the callback that will update the variable 448 | let ret = callback( 449 | // this type system should prevent downcasting errors here, so `unwrap` is used here to preserve the semantic meaning of 450 | // an `Ok(Some)`, `Ok(None)`, or `Err` return value from this function 451 | this.hold() 452 | .values 453 | .get_mut(&variable.id) 454 | .unwrap() 455 | .downcast_mut() 456 | .unwrap(), 457 | ); 458 | 459 | // store this variable's dependents (if any) separately to avoid deadlock 460 | let dependents = this 461 | .hold() 462 | .dependencies 463 | .get(&variable.id) 464 | .cloned() 465 | .unwrap_or_default(); 466 | // we must recompute the values of any variables that depend on the just-changed variable 467 | // since we don't have access to the type of the dependent variables, we have to manually recompute them instead of 468 | // being able to use the `update` function 469 | for dependent in dependents { 470 | // the `Updating` event for the dependent variables can be cancelled as usual 471 | if this 472 | .emit(VariableId(dependent), &Updating) 473 | .map(|votes| votes.cancel > votes.proceed) 474 | .unwrap_or(true) 475 | { 476 | continue; 477 | } 478 | 479 | // update the value of the dependent variable 480 | let recipe = this 481 | .hold() 482 | .recipes 483 | .get(&dependent) 484 | .cloned() 485 | .expect("all variables have a recipe"); 486 | let value = recipe(&this); 487 | this.hold().values.insert(dependent, value); 488 | 489 | // we don't care if this `Updated` event is cancelled as there are no subsequent actions to take for this dependent variable 490 | _ = this.emit(VariableId(dependent), &Updated); 491 | } 492 | 493 | // we don't care if this `Updated` event is cancelled as there are no subsequent actions to take 494 | _ = this.emit(variable, &Updated); 495 | 496 | Ok(Some(ret)) 497 | } 498 | 499 | /// remove a variable from the reactive system 500 | fn delete(mut this: System<'x>, variable: Variable) -> Result, ()> 501 | where 502 | T: VariableBounds, 503 | { 504 | if !this.hold().values.contains_key(&variable.id) { 505 | // the target variable doesn't exist so we ignore this request 506 | return Ok(None); 507 | } 508 | 509 | // cancel the deletion if the value of any other variables depends on this one, as 510 | // that would otherwise leave a dangling reference 511 | if this 512 | .hold() 513 | .dependencies 514 | .get(&variable.id) 515 | .map(|deps| !deps.is_empty()) 516 | .unwrap_or_default() 517 | { 518 | return Err(()); 519 | } 520 | 521 | // the `Deleting` event is cancellable 522 | if this 523 | .emit(variable, &Deleting) 524 | .map(|votes| votes.cancel > votes.proceed) 525 | .unwrap_or(true) 526 | { 527 | return Err(()); 528 | } 529 | 530 | // wipe the resources associated with the deleted variable 531 | this.hold().dependencies.remove(&variable.id); 532 | this.hold().dependencies.values_mut().for_each(|deps| { 533 | deps.remove(&variable.id); 534 | }); 535 | this.hold().recipes.remove(&variable.id); 536 | this.hold().listeners.values_mut().for_each(|listeners| { 537 | listeners.remove(&Some(variable.id)); 538 | }); 539 | this.hold().id_pool.push(variable.id); 540 | 541 | // this type system should prevent downcasting errors here, so `unwrap` is used here to preserve the semantic meaning of 542 | // an `Ok(Some)`, `Ok(None)`, or `Err` return value from this function 543 | let value = *this 544 | .hold() 545 | .values 546 | .remove(&variable.id) 547 | .unwrap() 548 | .downcast() 549 | .unwrap(); 550 | 551 | // we don't care if `Read` events are cancelled as there are no subsequent actions to take 552 | _ = this.emit(None, &Deleted { _source: variable }); 553 | 554 | Ok(Some(value)) 555 | } 556 | 557 | /// register a function to be called 558 | fn listen( 559 | this: System<'x>, 560 | target: impl Into>, 561 | handler: F, 562 | ) -> Option> 563 | where 564 | E: 'static, 565 | F: Fn(&mut System<'x>, &E, &mut Vote, &mut bool) + FnBounds + 'x, 566 | { 567 | // extract the ID of the passed target, if any 568 | let target_id = target.into().map(|VariableId(id)| id); 569 | 570 | if target_id 571 | .map(|id| !this.hold().values.contains_key(&id)) 572 | .unwrap_or_default() 573 | { 574 | // the target variable doesn't exist so we ignore this request 575 | return None; 576 | } 577 | 578 | // we have to wrap the passed handler in order to upcast the event type, so that handlers for different 579 | // event types can be treated the same in the system 580 | let handler = Rc::new( 581 | move |system: &mut System<'x>, event: &dyn Any, vote: &mut Vote, abort: &mut bool| { 582 | if let Some(event) = event.downcast_ref() { 583 | handler(system, event, vote, abort); 584 | } 585 | }, 586 | ); 587 | 588 | // listener IDs are allocated from the same pool as variables 589 | let id = { 590 | let reusable_id = this.hold().id_pool.pop(); 591 | reusable_id.unwrap_or_else(|| { 592 | let id = this.hold().next_id; 593 | this.hold().next_id += 1; 594 | id 595 | }) 596 | }; 597 | 598 | // store the event handler 599 | this.hold() 600 | .listeners 601 | .entry(TypeId::of::()) 602 | .or_default() 603 | .entry(target_id) 604 | .or_insert(IndexMap::with_hasher(RandomState::new())) 605 | .insert(id, handler); 606 | 607 | Some(Listener { 608 | id, 609 | target: target_id, 610 | _e: PhantomData, 611 | }) 612 | } 613 | 614 | /// trigger an event, optionally on a given target 615 | fn emit( 616 | mut this: System<'x>, 617 | target: impl Into>, 618 | event: &E, 619 | ) -> Result 620 | where 621 | E: 'static, 622 | { 623 | // extract the ID of the passed target, if any 624 | let target_id = target.into().map(|VariableId(id)| id); 625 | 626 | // gather the relevant handlers for this event & target 627 | let handlers = this 628 | .hold() 629 | .listeners 630 | .get(&event.type_id()) 631 | .and_then(|targets| targets.get(&target_id)) 632 | .into_iter() 633 | .flatten() 634 | .map(|(_, handler)| handler) 635 | .cloned() 636 | .collect::>(); 637 | 638 | let mut votes = Votes::default(); 639 | for handler in handlers { 640 | // by default this handler will proceed without affecting subsequent ones 641 | let mut vote = Vote::Abstain; 642 | let mut abort = false; 643 | handler(&mut this, event, &mut vote, &mut abort); 644 | 645 | // if aborted, subsqeuent handlers are skipped 646 | if abort { 647 | return Err(()); 648 | } 649 | 650 | // votes are tallied following the execution of alll handlers, so we continue on 651 | match vote { 652 | Vote::Abstain => votes.abstain += 1, 653 | Vote::Cancel => votes.cancel += 1, 654 | Vote::Proceed => votes.proceed += 1, 655 | } 656 | } 657 | 658 | Ok(votes) 659 | } 660 | 661 | /// removes an event listener 662 | fn silence(this: System<'x>, listener: Listener) -> Option<()> 663 | where 664 | E: 'static, 665 | { 666 | this.hold() 667 | .listeners 668 | .get_mut(&TypeId::of::()) 669 | .and_then(|targets| targets.get_mut(&listener.target)) 670 | .and_then(|handlers| handlers.shift_remove(&listener.id)) 671 | .map(|_| ()) 672 | } 673 | } 674 | -------------------------------------------------------------------------------- /src/variable.rs: -------------------------------------------------------------------------------- 1 | use crate::{compat::VariableBounds, Id}; 2 | 3 | use core::marker::PhantomData; 4 | 5 | /// A typed handle to a variable belonging to the reactive system 6 | #[derive(educe::Educe)] 7 | #[educe(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] 8 | pub struct Variable { 9 | pub(crate) id: Id, 10 | pub(crate) _t: PhantomData, 11 | } 12 | 13 | impl Into> for Variable { 14 | fn into(self) -> Option { 15 | Some(VariableId(self.id)) 16 | } 17 | } 18 | 19 | /// An untyped handle to a variable belonging to the reactive system 20 | #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] 21 | pub struct VariableId(pub(crate) Id); 22 | --------------------------------------------------------------------------------