1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
/*! Render queue and batching.

*/

use std::{
    cell::RefCell,
    collections::{HashSet, VecDeque},
    hash::Hash,
    sync::atomic::{AtomicBool, Ordering},
};

use wasm_bindgen::{prelude::Closure, JsCast};
use web_sys::{console, window};

use crate::{construction::component::ComponentStore, locking::UnmountedLock};

#[derive(Clone)]
pub(crate) struct RerenderTask {
    pub(crate) comp: &'static dyn ComponentStore,
    pub(crate) lock: UnmountedLock,
}

impl Hash for RerenderTask {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        (self.comp as *const dyn ComponentStore, self.lock.as_ptr()).hash(state)
    }
}

impl PartialEq for RerenderTask {
    fn eq(&self, other: &RerenderTask) -> bool {
        (self.comp as *const _ as *const () == other.comp as *const _ as *const ())
            && (self.lock == other.lock)
    }
}

impl Eq for RerenderTask {}

impl RerenderTask {
    pub(crate) fn new(comp: &'static dyn ComponentStore, lock: UnmountedLock) -> Self {
        Self { comp, lock }
    }
    pub(crate) fn enqueue(self) {
        PENDING_RERENDERS.with(|p| {
            if p.borrow_mut().insert(self.clone()) {
                EXECUTOR.with(|l| l.enqueue(ExecutorTask::Rerender(self)))
            }
        });
    }
    fn execute(&self) {
        PENDING_RERENDERS.with(|p| {
            p.borrow_mut().remove(&self);
        });
        if self.lock.is_mounted() {
            self.comp.render();
        } else {
            console::warn_1(
                &"Trying to render a component whose tree had been unmounted. This is a no-op."
                    .into(),
            );
        }
    }
}

thread_local! {
    static PENDING_RERENDERS: RefCell<HashSet<RerenderTask>> = RefCell::new(HashSet::new());
}

pub struct RunTask {
    run: Box<dyn FnOnce()>,
}

impl RunTask {
    pub fn new<F: FnOnce() + 'static>(func: F) -> Self {
        Self {
            run: Box::new(func),
        }
    }
    pub fn enqueue(self) {
        EXECUTOR.with(|l| l.enqueue(ExecutorTask::Run(self)))
    }
    fn execute(self) {
        (self.run)();
    }
}

enum ExecutorTask {
    Rerender(RerenderTask),
    Run(RunTask),
}

impl ExecutorTask {
    fn execute(self) {
        match self {
            ExecutorTask::Rerender(rerender) => rerender.execute(),
            ExecutorTask::Run(run) => run.execute(),
        }
    }
}

struct Executor {
    queue: RefCell<VecDeque<ExecutorTask>>,
    active: AtomicBool,
    timeout_closure: Closure<dyn Fn()>,
}

impl Executor {
    fn enqueue(&self, task: ExecutorTask) {
        self.queue.borrow_mut().push_back(task);
        self.maybe_batch_updates_with_timeout();
    }
    fn execute_loop(&self) {
        loop {
            let task_opt = { self.queue.borrow_mut().pop_front() };
            if let Some(task) = task_opt {
                task.execute();
            } else {
                break;
            }
        }
    }
    fn execute(&self) {
        if !self.active.swap(true, Ordering::Acquire) {
            self.execute_loop();
            self.active.store(false, Ordering::Release);
        }
    }
    fn batch_updates(&self, f: impl FnOnce()) {
        let already_running = self.active.swap(true, Ordering::Acquire);
        f();
        if !already_running {
            self.active.store(false, Ordering::Release);
            self.execute();
        }
    }
    fn maybe_batch_updates_with_timeout(&self) {
        if !self.active.swap(true, Ordering::Acquire) {
            window()
                .unwrap()
                .set_timeout_with_callback(self.timeout_closure.as_ref().unchecked_ref())
                .unwrap();
        }
    }
}

thread_local! {
    static EXECUTOR: Executor = Executor {
        active: AtomicBool::new(false),
        queue: RefCell::new(VecDeque::new()),
        timeout_closure: Closure::wrap(Box::new(|| {
            EXECUTOR.with(|l| {
                l.active.store(false, Ordering::Release);
                l.execute();
            });
        }))
    };
}

/** Batch the state updates started inside the given closure. **READ BEFORE USE**

Consecuit batch updates using setTimeout anyway, even if you are not using this.

Using this will avoid the setTimeout.

**Updates from inside [crate::hooks::use_effect()], consecuit_html's Callback, and [run_later] are already batched.**

*/
pub fn batch_updates(f: impl FnOnce()) {
    EXECUTOR.with(|l| l.batch_updates(f))
}

/** Schedule the given closure to run after the current component finishes rendering.

Example use to focus a consecuit_html's input field:

```
use consecuit_html::prelude::*;
let (cc, input_ref) = cc.hook(use_ref, ());
let (cc, _) = cc.hook(use_effect, (|input_ref: Reference<Option<web_sys::HtmlInputElement>>| {
    run_later(move || {
        input_ref.visit_with(|opt| opt.as_ref().unwrap().focus().unwrap()).unwrap();
    })
}, input_ref.clone()))
cc_tree!(
    <input html_props().reference(input_ref) />
)

```
*/
pub fn run_later(f: impl FnOnce() + 'static) {
    RunTask::new(f).enqueue();
}