1use std::cell::RefCell;
7use std::future::Future;
8use std::pin::Pin;
9use std::rc::Rc;
10
11use hyve::state::{Owner, on_cleanup};
12use hyve::{Ctx, Scope};
13
14#[derive(Clone, Debug)]
16pub struct View {
17 scope: Scope,
18 owner: Owner,
19}
20
21thread_local! {
22 static CURRENT: RefCell<Vec<View>> = const { RefCell::new(Vec::new()) };
23 static EXECUTOR: RefCell<Option<Rc<dyn Executor>>> = const { RefCell::new(None) };
24}
25
26impl View {
27 pub fn root(scope: Scope) -> View {
29 let owner = Owner::new();
30 let s = scope.clone();
31 owner.with(|| on_cleanup(move || s.dispose()));
32 View { scope, owner }
33 }
34
35 pub fn child(&self) -> View {
39 self.child_in(&self.scope)
40 }
41
42 pub fn child_in(&self, parent: &Scope) -> View {
45 let scope = parent.child();
46 let owner = Owner::new();
47 let s = scope.clone();
48 owner.with(|| on_cleanup(move || s.dispose()));
49 View { scope, owner }
50 }
51
52 pub fn run<R>(&self, f: impl FnOnce() -> R) -> R {
55 let _g = Push::new(self.clone());
56 self.scope.enter(|| self.owner.with(f))
57 }
58
59 pub fn enter<R>(&self, f: impl FnOnce() -> R) -> R {
62 let _g = Push::new(self.clone());
63 self.scope.enter(f)
64 }
65
66 pub fn current() -> Option<View> {
68 CURRENT.with(|c| c.borrow().last().cloned())
69 }
70
71 pub fn scope(&self) -> &Scope {
73 &self.scope
74 }
75
76 pub fn owner(&self) -> Owner {
78 self.owner
79 }
80
81 pub fn dispose(&self) {
84 self.owner.dispose();
85 }
86
87 pub fn is_alive(&self) -> bool {
89 self.owner.is_alive() && !self.scope.is_disposed()
90 }
91}
92
93struct Push;
94
95impl Push {
96 fn new(v: View) -> Push {
97 CURRENT.with(|c| c.borrow_mut().push(v));
98 Push
99 }
100}
101
102impl Drop for Push {
103 fn drop(&mut self) {
104 CURRENT.with(|c| {
105 c.borrow_mut().pop();
106 });
107 }
108}
109
110pub fn inject<T: Send + Sync + 'static>() -> Ctx<T> {
118 let scope = Scope::current().expect("serge: components run inside a view scope");
119 scope.get::<T>().unwrap_or_else(|| {
120 panic!(
121 "serge: no `{}` is provided here; provide it with `.provide(..)` on the app or a feature that encloses this view",
122 std::any::type_name::<T>()
123 )
124 })
125}
126
127pub type LocalFuture = Pin<Box<dyn Future<Output = ()>>>;
130
131pub trait Executor {
134 fn spawn(&self, task: LocalFuture) -> TaskHandle;
136}
137
138pub struct TaskHandle(Box<dyn FnOnce()>);
140
141impl TaskHandle {
142 pub fn new(abort: impl FnOnce() + 'static) -> Self {
144 TaskHandle(Box::new(abort))
145 }
146
147 pub fn abort(self) {
149 (self.0)()
150 }
151}
152
153pub fn install_executor(executor: Rc<dyn Executor>) {
155 EXECUTOR.with(|e| *e.borrow_mut() = Some(executor));
156}
157
158pub fn with_executor<R>(executor: Rc<dyn Executor>, f: impl FnOnce() -> R) -> R {
160 struct Restore(Option<Rc<dyn Executor>>);
161 impl Drop for Restore {
162 fn drop(&mut self) {
163 EXECUTOR.with(|slot| {
164 slot.replace(self.0.take());
165 });
166 }
167 }
168 let _restore = Restore(EXECUTOR.with(|slot| slot.replace(Some(executor))));
169 f()
170}
171
172pub fn spawn(future: impl Future<Output = ()> + 'static) {
182 let view = View::current();
183 let task: LocalFuture = match &view {
184 Some(v) => Box::pin(v.scope().clone().scoped(future)),
185 None => Box::pin(future),
186 };
187 let handle = EXECUTOR.with(|e| {
188 e.borrow()
189 .clone()
190 .expect("serge: no executor is installed; run the app (or a test harness) first")
191 .spawn(task)
192 });
193 if let Some(v) = view {
194 let handle = RefCell::new(Some(handle));
195 v.owner().with(|| {
196 on_cleanup(move || {
197 if let Some(h) = handle.borrow_mut().take() {
198 h.abort();
199 }
200 })
201 });
202 }
203}
204
205#[cfg(not(target_arch = "wasm32"))]
209pub fn runtime() -> &'static tokio::runtime::Runtime {
210 static RT: std::sync::OnceLock<tokio::runtime::Runtime> = std::sync::OnceLock::new();
211 RT.get_or_init(|| {
212 tokio::runtime::Builder::new_multi_thread()
213 .worker_threads(2)
214 .thread_name("serge-io")
215 .enable_all()
216 .build()
217 .expect("serge: failed to start the tokio runtime")
218 })
219}
220
221pub async fn sleep(duration: std::time::Duration) {
225 #[cfg(not(target_arch = "wasm32"))]
226 {
227 let timer = {
228 let _rt = runtime().enter();
229 tokio::time::sleep(duration)
230 };
231 timer.await;
232 }
233 #[cfg(target_arch = "wasm32")]
234 {
235 let ms = i32::try_from(duration.as_millis()).unwrap_or(i32::MAX);
236 let p = js_sys::Promise::new(&mut |resolve, _| {
237 if let Some(w) = web_sys::window() {
238 let _ = w.set_timeout_with_callback_and_timeout_and_arguments_0(&resolve, ms);
239 }
240 });
241 let _ = wasm_bindgen_futures::JsFuture::from(p).await;
242 }
243}