OXYGENHUB
# 417184c73f4e oxygenhub / crates / backdrop / src / lib.rs
10.7 KiB · Rust · last changed feat(web): Backdrops, the engine in Rust and WASM, and the dashboard's Your sky (refs #157) 22 days ago source blame history raw
17ca6cdd Andy McCall ↶ 1
//! Backdrops (docs/backgrounds.md): the quiet, moving pictures behind
2
//! some of OxygenHub's pages, in Rust compiled to WebAssembly and drawn
3
//! with WebGL2. `sky` is the scene and its motion, with no browser in it;
4
//! `gl` draws it; this module is the browser around them: the frame loop,
5
//! the cursor, the window's size, the page's colours and when to stop.
6
7
pub mod gl;
8
pub mod sky;
9
10
use sky::{Colours, Event, Kind, Repo, Sky};
11
use std::cell::RefCell;
12
use std::rc::Rc;
13
use wasm_bindgen::prelude::*;
14
use wasm_bindgen::JsCast;
15
use web_sys::{HtmlCanvasElement, HtmlElement, WebGl2RenderingContext, Window};
16
17
/// The highest device pixel ratio drawn at: sharp enough, and cheap.
18
const MAX_DPR: f64 = 1.5;
19
/// After this long without input a moving backdrop draws its last frame
20
/// and stops until the next movement (§6).
21
const STOP_AFTER_S: f64 = 120.0;
22
/// A still cursor drops the frame rate to half after this long.
23
const HALF_RATE_AFTER_S: f64 = 3.0;
24
25
struct Engine {
26
    window: Window,
27
    canvas: HtmlCanvasElement,
28
    renderer: gl::Renderer,
29
    sky: Sky,
30
    colours: Colours,
31
    colours_at: f64,
32
    probe: HtmlElement,
33
    label: HtmlElement,
34
    label_text: String,
35
    inst: Vec<f32>,
36
    lines: Vec<f32>,
37
    last: Option<f64>,
38
    frame: u64,
39
    running: bool,
40
    input_at: f64,
41
    pw: i32,
42
    ph: i32,
43
}
44
45
type Frame = Rc<RefCell<Option<Closure<dyn FnMut(f64)>>>>;
46
47
impl Engine {
48
    fn now(&self) -> f64 {
49
        self.window.performance().map(|p| p.now()).unwrap_or(0.0)
50
    }
51
52
    /// Fit the canvas to the window.
53
    fn fit(&mut self) {
54
        let w = self.window.inner_width().ok().and_then(|v| v.as_f64()).unwrap_or(0.0);
55
        let h = self.window.inner_height().ok().and_then(|v| v.as_f64()).unwrap_or(0.0);
56
        let dpr = self.window.device_pixel_ratio().clamp(1.0, MAX_DPR);
57
        self.pw = (w * dpr).round() as i32;
58
        self.ph = (h * dpr).round() as i32;
59
        self.canvas.set_width(self.pw.max(1) as u32);
60
        self.canvas.set_height(self.ph.max(1) as u32);
61
        self.sky.resize(w as f32, h as f32);
62
    }
63
64
    /// The page's backdrop tokens, as the browser computes them, so a
65
    /// theme switch shows within a second.
66
    fn read_colours(&mut self) {
67
        let read = |token: &str, fallback: sky::Rgba| -> sky::Rgba {
68
            let _ = self.probe.style().set_property("color", &format!("var({token})"));
69
            self.window
70
                .get_computed_style(&self.probe)
71
                .ok()
72
                .flatten()
73
                .and_then(|s| s.get_property_value("color").ok())
74
                .and_then(|c| sky::parse_colour(&c))
75
                .unwrap_or(fallback)
76
        };
77
        self.colours = Colours {
78
            mark: read("--bd-mark", [0.5, 0.5, 0.55, 0.16]),
79
            lit: read("--bd-lit", [0.04, 0.41, 0.85, 0.7]),
80
            link: read("--bd-link", [0.04, 0.41, 0.85, 0.22]),
81
        };
82
    }
83
84
    /// One animation frame at time `t`; whether another is wanted.
85
    fn tick(&mut self, t: f64) -> bool {
86
        if self.window.document().is_some_and(|d| d.hidden()) {
87
            self.last = None;
88
            return false;
89
        }
90
        let idle = (t - self.input_at) / 1000.0;
91
        self.frame += 1;
92
        if !self.sky.still && idle > HALF_RATE_AFTER_S && self.frame % 2 == 1 {
93
            return true;
94
        }
95
        let dt = self.last.map(|l| ((t - l) / 1000.0) as f32).unwrap_or(0.0);
96
        self.last = Some(t);
97
        if t - self.colours_at > 1000.0 {
98
            self.read_colours();
99
            self.colours_at = t;
100
        }
101
        self.sky.step(dt);
102
        self.sky.instances(&self.colours, &mut self.inst);
103
        self.sky.links(&self.colours, &mut self.lines);
104
        self.renderer.draw(self.sky.w, self.sky.h, self.pw, self.ph, &self.inst, &self.lines);
105
        self.show_label();
106
        if self.sky.still {
107
            self.sky.busy()
108
        } else {
109
            idle < STOP_AFTER_S || self.sky.busy()
110
        }
111
    }
112
113
    /// The name beside a resting cursor (§4): faded in and out by CSS.
114
    fn show_label(&mut self) {
115
        let next = self.sky.label().map(|(name, x, y)| (name.to_string(), x, y));
116
        let style = self.label.style();
117
        match next {
118
            Some((name, x, y)) => {
119
                if name != self.label_text {
120
                    self.label.set_text_content(Some(&name));
121
                    self.label_text = name;
122
                }
123
                let _ = style.set_property("left", &format!("{}px", (x + 12.0) as i32));
124
                let _ = style.set_property("top", &format!("{}px", (y - 8.0) as i32));
125
                let _ = style.set_property("opacity", "1");
126
            }
127
            None => {
128
                let _ = style.set_property("opacity", "0");
129
            }
130
        }
131
    }
132
}
133
134
/// Ask for a frame unless the loop is already running.
135
fn wake(engine: &Rc<RefCell<Engine>>, frame: &Frame) {
136
    let mut e = engine.borrow_mut();
137
    if e.running {
138
        return;
139
    }
140
    e.running = true;
141
    if let Some(f) = frame.borrow().as_ref() {
142
        let _ = e.window.request_animation_frame(f.as_ref().unchecked_ref());
143
    }
144
}
145
146
fn get(v: &JsValue, key: &str) -> JsValue {
147
    js_sys::Reflect::get(v, &JsValue::from_str(key)).unwrap_or(JsValue::UNDEFINED)
148
}
149
150
/// The page's data (§5): `{now, repos: [name], events: [[repo, kind, at_ms]]}`.
151
fn read_data(data: &JsValue) -> (Vec<Repo>, Vec<Event>) {
152
    let now = get(data, "now").as_f64().unwrap_or(0.0);
153
    let repos: Vec<Repo> =
154
        js_sys::Array::from(&get(data, "repos")).iter().filter_map(|v| v.as_string()).map(|name| Repo { name }).collect();
155
    let events: Vec<Event> = js_sys::Array::from(&get(data, "events"))
156
        .iter()
157
        .filter_map(|v| {
158
            let e = js_sys::Array::from(&v);
159
            let repo = e.get(0).as_f64()? as usize;
160
            let kind = Kind::from_code(e.get(1).as_f64()? as u32);
161
            let at = e.get(2).as_f64()?;
162
            Some(Event { repo, kind, age_days: ((now - at) / 86_400_000.0).max(0.0) as f32 })
163
        })
164
        .collect();
165
    (repos, events)
166
}
167
168
/// Start the dashboard's sky on `canvas` with the page's `data`. `still`
169
/// is the viewer's choice of a still backdrop; reduced motion asks for
170
/// one too. Without WebGL2 there is no backdrop, and nothing breaks.
171
#[wasm_bindgen]
172
pub fn start(canvas: HtmlCanvasElement, data: JsValue, still: bool) -> Result<(), JsValue> {
173
    let window = web_sys::window().ok_or("no window")?;
174
    let document = window.document().ok_or("no document")?;
175
    let reduced = window.match_media("(prefers-reduced-motion: reduce)").ok().flatten().is_some_and(|m| m.matches());
176
    let still = still || reduced;
177
178
    let options = js_sys::Object::new();
179
    js_sys::Reflect::set(&options, &"alpha".into(), &true.into())?;
180
    js_sys::Reflect::set(&options, &"premultipliedAlpha".into(), &true.into())?;
181
    js_sys::Reflect::set(&options, &"antialias".into(), &false.into())?;
182
    js_sys::Reflect::set(&options, &"powerPreference".into(), &"low-power".into())?;
183
    let gl: WebGl2RenderingContext = canvas.get_context_with_context_options("webgl2", &options)?.ok_or("no WebGL2")?.dyn_into()?;
184
    let renderer = gl::Renderer::new(gl)?;
185
186
    let body = document.body().ok_or("no body")?;
187
    let probe: HtmlElement = document.create_element("span")?.dyn_into()?;
188
    probe.set_attribute("style", "position:fixed;visibility:hidden;pointer-events:none")?;
189
    probe.set_attribute("aria-hidden", "true")?;
190
    body.append_child(&probe)?;
191
    let label: HtmlElement = document.create_element("div")?.dyn_into()?;
192
    label.set_class_name("bd-label");
193
    label.set_attribute("aria-hidden", "true")?;
194
    body.append_child(&label)?;
195
196
    let (repos, events) = read_data(&data);
197
    let sky = Sky::new(&repos, &events, 0.0, 0.0, still);
198
    let colours = Colours { mark: [0.0; 4], lit: [0.0; 4], link: [0.0; 4] };
199
    let engine = Rc::new(RefCell::new(Engine {
200
        window: window.clone(),
201
        canvas,
202
        renderer,
203
        sky,
204
        colours,
205
        colours_at: f64::NEG_INFINITY,
206
        probe,
207
        label,
208
        label_text: String::new(),
209
        inst: Vec::new(),
210
        lines: Vec::new(),
211
        last: None,
212
        frame: 0,
213
        running: false,
214
        input_at: 0.0,
215
        pw: 0,
216
        ph: 0,
217
    }));
218
    {
219
        let mut e = engine.borrow_mut();
220
        e.fit();
221
        e.input_at = e.now();
222
    }
223
224
    // The frame loop: each frame asks for the next while it is wanted.
225
    let frame: Frame = Rc::new(RefCell::new(None));
226
    {
227
        let (engine, again) = (engine.clone(), frame.clone());
228
        *frame.borrow_mut() = Some(Closure::new(move |t: f64| {
229
            let more = engine.borrow_mut().tick(t);
230
            let mut e = engine.borrow_mut();
231
            if more {
232
                if let Some(f) = again.borrow().as_ref() {
233
                    let _ = e.window.request_animation_frame(f.as_ref().unchecked_ref());
234
                }
235
            } else {
236
                e.running = false;
237
            }
238
        }));
239
    }
240
241
    // The cursor lights marks; it never moves them.
242
    {
243
        let (engine, frame) = (engine.clone(), frame.clone());
244
        let moved = Closure::<dyn FnMut(web_sys::MouseEvent)>::new(move |ev: web_sys::MouseEvent| {
245
            {
246
                let mut e = engine.borrow_mut();
247
                e.sky.point(Some((ev.client_x() as f32, ev.client_y() as f32)));
248
                e.input_at = e.now();
249
            }
250
            wake(&engine, &frame);
251
        });
252
        window.add_event_listener_with_callback("mousemove", moved.as_ref().unchecked_ref())?;
253
        moved.forget();
254
    }
255
    {
256
        let (engine, frame) = (engine.clone(), frame.clone());
257
        let left = Closure::<dyn FnMut(web_sys::MouseEvent)>::new(move |ev: web_sys::MouseEvent| {
258
            if ev.related_target().is_none() {
259
                engine.borrow_mut().sky.point(None);
260
                wake(&engine, &frame);
261
            }
262
        });
263
        document.add_event_listener_with_callback("mouseout", left.as_ref().unchecked_ref())?;
264
        left.forget();
265
    }
266
    {
267
        let (engine, frame) = (engine.clone(), frame.clone());
268
        let resized = Closure::<dyn FnMut()>::new(move || {
269
            engine.borrow_mut().fit();
270
            wake(&engine, &frame);
271
        });
272
        window.add_event_listener_with_callback("resize", resized.as_ref().unchecked_ref())?;
273
        resized.forget();
274
    }
275
    {
276
        let (engine, frame) = (engine.clone(), frame.clone());
277
        let shown = Closure::<dyn FnMut()>::new(move || {
278
            let visible = engine.borrow().window.document().is_some_and(|d| !d.hidden());
279
            if visible {
280
                engine.borrow_mut().last = None;
281
                wake(&engine, &frame);
282
            }
283
        });
284
        document.add_event_listener_with_callback("visibilitychange", shown.as_ref().unchecked_ref())?;
285
        shown.forget();
286
    }
287
288
    wake(&engine, &frame);
289
    Ok(())
290
}