OXYGENHUB
# 0a3b244b748f oxygenhub / crates / backdrop / src / lib.rs
10.8 KiB · Rust · last changed feat(web): a denser sky, every change and run a mark; short links; the name above (refs #157) 23 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
df5c69cb Andy McCall ↶ 113
    /// The name above the cluster a cursor rests by (§4): faded in and out
114
    /// by CSS, which centres it on `left` and sets its foot on `top`.
17ca6cdd Andy McCall ↶ 115
    fn show_label(&mut self) {
116
        let next = self.sky.label().map(|(name, x, y)| (name.to_string(), x, y));
117
        let style = self.label.style();
118
        match next {
119
            Some((name, x, y)) => {
120
                if name != self.label_text {
121
                    self.label.set_text_content(Some(&name));
122
                    self.label_text = name;
123
                }
df5c69cb Andy McCall ↶ 124
                let _ = style.set_property("left", &format!("{}px", x as i32));
125
                let _ = style.set_property("top", &format!("{}px", y as i32));
17ca6cdd Andy McCall ↶ 126
                let _ = style.set_property("opacity", "1");
127
            }
128
            None => {
129
                let _ = style.set_property("opacity", "0");
130
            }
131
        }
132
    }
133
}
134
135
/// Ask for a frame unless the loop is already running.
136
fn wake(engine: &Rc<RefCell<Engine>>, frame: &Frame) {
137
    let mut e = engine.borrow_mut();
138
    if e.running {
139
        return;
140
    }
141
    e.running = true;
142
    if let Some(f) = frame.borrow().as_ref() {
143
        let _ = e.window.request_animation_frame(f.as_ref().unchecked_ref());
144
    }
145
}
146
147
fn get(v: &JsValue, key: &str) -> JsValue {
148
    js_sys::Reflect::get(v, &JsValue::from_str(key)).unwrap_or(JsValue::UNDEFINED)
149
}
150
df5c69cb Andy McCall ↶ 151
/// The page's data (§5): `{now, repos: [name], events: [[repo, kind, at_ms, n]]}`.
17ca6cdd Andy McCall ↶ 152
fn read_data(data: &JsValue) -> (Vec<Repo>, Vec<Event>) {
153
    let now = get(data, "now").as_f64().unwrap_or(0.0);
154
    let repos: Vec<Repo> =
155
        js_sys::Array::from(&get(data, "repos")).iter().filter_map(|v| v.as_string()).map(|name| Repo { name }).collect();
156
    let events: Vec<Event> = js_sys::Array::from(&get(data, "events"))
157
        .iter()
158
        .filter_map(|v| {
159
            let e = js_sys::Array::from(&v);
160
            let repo = e.get(0).as_f64()? as usize;
161
            let kind = Kind::from_code(e.get(1).as_f64()? as u32);
162
            let at = e.get(2).as_f64()?;
df5c69cb Andy McCall ↶ 163
            let n = e.get(3).as_f64().unwrap_or(1.0).max(1.0) as u32;
164
            Some(Event { repo, kind, age_days: ((now - at) / 86_400_000.0).max(0.0) as f32, n })
17ca6cdd Andy McCall ↶ 165
        })
166
        .collect();
167
    (repos, events)
168
}
169
170
/// Start the dashboard's sky on `canvas` with the page's `data`. `still`
171
/// is the viewer's choice of a still backdrop; reduced motion asks for
172
/// one too. Without WebGL2 there is no backdrop, and nothing breaks.
173
#[wasm_bindgen]
174
pub fn start(canvas: HtmlCanvasElement, data: JsValue, still: bool) -> Result<(), JsValue> {
175
    let window = web_sys::window().ok_or("no window")?;
176
    let document = window.document().ok_or("no document")?;
177
    let reduced = window.match_media("(prefers-reduced-motion: reduce)").ok().flatten().is_some_and(|m| m.matches());
178
    let still = still || reduced;
179
180
    let options = js_sys::Object::new();
181
    js_sys::Reflect::set(&options, &"alpha".into(), &true.into())?;
182
    js_sys::Reflect::set(&options, &"premultipliedAlpha".into(), &true.into())?;
183
    js_sys::Reflect::set(&options, &"antialias".into(), &false.into())?;
184
    js_sys::Reflect::set(&options, &"powerPreference".into(), &"low-power".into())?;
185
    let gl: WebGl2RenderingContext = canvas.get_context_with_context_options("webgl2", &options)?.ok_or("no WebGL2")?.dyn_into()?;
186
    let renderer = gl::Renderer::new(gl)?;
187
188
    let body = document.body().ok_or("no body")?;
189
    let probe: HtmlElement = document.create_element("span")?.dyn_into()?;
190
    probe.set_attribute("style", "position:fixed;visibility:hidden;pointer-events:none")?;
191
    probe.set_attribute("aria-hidden", "true")?;
192
    body.append_child(&probe)?;
193
    let label: HtmlElement = document.create_element("div")?.dyn_into()?;
194
    label.set_class_name("bd-label");
195
    label.set_attribute("aria-hidden", "true")?;
196
    body.append_child(&label)?;
197
198
    let (repos, events) = read_data(&data);
199
    let sky = Sky::new(&repos, &events, 0.0, 0.0, still);
200
    let colours = Colours { mark: [0.0; 4], lit: [0.0; 4], link: [0.0; 4] };
201
    let engine = Rc::new(RefCell::new(Engine {
202
        window: window.clone(),
203
        canvas,
204
        renderer,
205
        sky,
206
        colours,
207
        colours_at: f64::NEG_INFINITY,
208
        probe,
209
        label,
210
        label_text: String::new(),
211
        inst: Vec::new(),
212
        lines: Vec::new(),
213
        last: None,
214
        frame: 0,
215
        running: false,
216
        input_at: 0.0,
217
        pw: 0,
218
        ph: 0,
219
    }));
220
    {
221
        let mut e = engine.borrow_mut();
222
        e.fit();
223
        e.input_at = e.now();
224
    }
225
226
    // The frame loop: each frame asks for the next while it is wanted.
227
    let frame: Frame = Rc::new(RefCell::new(None));
228
    {
229
        let (engine, again) = (engine.clone(), frame.clone());
230
        *frame.borrow_mut() = Some(Closure::new(move |t: f64| {
231
            let more = engine.borrow_mut().tick(t);
232
            let mut e = engine.borrow_mut();
233
            if more {
234
                if let Some(f) = again.borrow().as_ref() {
235
                    let _ = e.window.request_animation_frame(f.as_ref().unchecked_ref());
236
                }
237
            } else {
238
                e.running = false;
239
            }
240
        }));
241
    }
242
243
    // The cursor lights marks; it never moves them.
244
    {
245
        let (engine, frame) = (engine.clone(), frame.clone());
246
        let moved = Closure::<dyn FnMut(web_sys::MouseEvent)>::new(move |ev: web_sys::MouseEvent| {
247
            {
248
                let mut e = engine.borrow_mut();
249
                e.sky.point(Some((ev.client_x() as f32, ev.client_y() as f32)));
250
                e.input_at = e.now();
251
            }
252
            wake(&engine, &frame);
253
        });
254
        window.add_event_listener_with_callback("mousemove", moved.as_ref().unchecked_ref())?;
255
        moved.forget();
256
    }
257
    {
258
        let (engine, frame) = (engine.clone(), frame.clone());
259
        let left = Closure::<dyn FnMut(web_sys::MouseEvent)>::new(move |ev: web_sys::MouseEvent| {
260
            if ev.related_target().is_none() {
261
                engine.borrow_mut().sky.point(None);
262
                wake(&engine, &frame);
263
            }
264
        });
265
        document.add_event_listener_with_callback("mouseout", left.as_ref().unchecked_ref())?;
266
        left.forget();
267
    }
268
    {
269
        let (engine, frame) = (engine.clone(), frame.clone());
270
        let resized = Closure::<dyn FnMut()>::new(move || {
271
            engine.borrow_mut().fit();
272
            wake(&engine, &frame);
273
        });
274
        window.add_event_listener_with_callback("resize", resized.as_ref().unchecked_ref())?;
275
        resized.forget();
276
    }
277
    {
278
        let (engine, frame) = (engine.clone(), frame.clone());
279
        let shown = Closure::<dyn FnMut()>::new(move || {
280
            let visible = engine.borrow().window.document().is_some_and(|d| !d.hidden());
281
            if visible {
282
                engine.borrow_mut().last = None;
283
                wake(&engine, &frame);
284
            }
285
        });
286
        document.add_event_listener_with_callback("visibilitychange", shown.as_ref().unchecked_ref())?;
287
        shown.forget();
288
    }
289
290
    wake(&engine, &frame);
291
    Ok(())
292
}