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