OXYGENHUB
# 6907a989e82a oxygenhub / crates / backdrop / src / sky.rs
23.0 KiB · Rust · last changed feat(web): Your sky closer and fuller: 40% larger, tighter knots, the margins filled (refs #157) 22 days ago source blame history raw
1
//! Your sky (docs/backgrounds.md §5): the dashboard's scene, its layout
2
//! and its motion, with no browser in it so it is tested natively.
3
//!
4
//! Each repository is a cluster placed by a hash of its name, so a
5
//! viewer's sky is the same on every visit; its events of the last 30 days
6
//! orbit it as marks, brightest when newest, shaped by kind. The cursor
7
//! lights marks near it without moving them, and joins the lit marks of
8
//! one repository in the order they happened.
9
10
use std::f32::consts::TAU;
11
12
/// The scale of marks and orbits: the sky drawn 40% closer than first
13
/// built (Andy, 2026-10-13).
14
const ZOOM: f32 = 1.4;
15
/// How far the cursor lights marks, in CSS pixels (§4).
16
pub const LIGHT_RADIUS: f32 = 170.0;
17
/// Seconds a mark takes to light, and to fade.
18
const LIT_IN: f32 = 0.15;
19
const LIT_OUT: f32 = 0.6;
20
/// The fastest a mark drifts, in CSS pixels a second.
21
pub const MAX_SPEED: f32 = 12.0;
22
/// How far each depth layer shifts against the cursor, front to back.
23
const PARALLAX: [f32; 3] = [6.0, 3.0, 1.0];
24
/// The longest link: only marks that happened one after another and sit
25
/// near each other are joined, so a busy repository reads as a
26
/// constellation, not a scribble.
27
const LINK_MAX: f32 = 85.0;
28
/// Links fade when the cursor has rested this long, in seconds.
29
const LINK_REST: f32 = 2.0;
30
/// A resting cursor this near a cluster's core names it, after this long.
31
const LABEL_NEAR: f32 = 110.0;
32
const LABEL_REST: f32 = 0.4;
33
/// Events older than this many days are not drawn.
34
pub const DAYS: f32 = 30.0;
35
/// The most marks one push makes (one a change), and in all.
36
const PER_PUSH: u32 = 40;
37
const MAX_MARKS: usize = 3000;
38
/// A side margin narrower than this holds no clusters: the sky falls back
39
/// to a ring around the page.
40
const MIN_MARGIN: f32 = 180.0;
41
/// The width a cluster gets in a margin's grid.
42
const CELL: f32 = 260.0;
43
44
/// What a mark stands for, which decides its shape.
45
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
46
pub enum Kind {
47
    Push,
48
    Proposal,
49
    Issue,
50
    Release,
51
    /// A Flow run.
52
    Run,
53
    /// The repository itself, its cluster's core.
54
    Repo,
55
}
56
57
impl Kind {
58
    /// The code the page's data uses: 0 a push's change, 1 a proposal
59
    /// event, 2 an issue event, 3 a release, 4 a Flow run.
60
    pub fn from_code(code: u32) -> Kind {
61
        match code {
62
            1 => Kind::Proposal,
63
            2 => Kind::Issue,
64
            3 => Kind::Release,
65
            4 => Kind::Run,
66
            _ => Kind::Push,
67
        }
68
    }
69
70
    /// The shape the fragment shader draws: 0 dot, 1 diamond, 2 ring,
71
    /// 3 four-point star, 4 thin ring (a repository), 5 square.
72
    pub fn shape(self) -> f32 {
73
        match self {
74
            Kind::Push => 0.0,
75
            Kind::Proposal => 1.0,
76
            Kind::Issue => 2.0,
77
            Kind::Release => 3.0,
78
            Kind::Repo => 4.0,
79
            Kind::Run => 5.0,
80
        }
81
    }
82
83
    /// Its radius in CSS pixels.
84
    fn size(self) -> f32 {
85
        match self {
86
            Kind::Push => 2.0,
87
            Kind::Run => 2.2,
88
            Kind::Proposal => 3.2,
89
            Kind::Issue => 3.0,
90
            Kind::Release => 4.2,
91
            Kind::Repo => 6.0,
92
        }
93
    }
94
}
95
96
/// One repository, as the page gives it.
97
#[derive(Clone, Debug)]
98
pub struct Repo {
99
    pub name: String,
100
}
101
102
/// One event, as the page gives it: its repository (an index into the
103
/// repositories), its kind, how old it is, and how many marks it makes (a
104
/// push's changes; one otherwise).
105
#[derive(Clone, Copy, Debug)]
106
pub struct Event {
107
    pub repo: usize,
108
    pub kind: Kind,
109
    pub age_days: f32,
110
    pub n: u32,
111
}
112
113
/// A repository's place: a fraction of the view, and a depth layer.
114
#[derive(Clone, Debug)]
115
pub struct Cluster {
116
    pub name: String,
117
    pub fx: f32,
118
    pub fy: f32,
119
    pub layer: usize,
120
}
121
122
/// One drawn mark, orbiting its cluster.
123
#[derive(Clone, Debug)]
124
pub struct Mark {
125
    pub cluster: usize,
126
    pub kind: Kind,
127
    /// Its place in its cluster's history, 0 the newest; the core is 0
128
    /// too and has radius 0.
129
    pub order: u32,
130
    pub radius: f32,
131
    pub angle: f32,
132
    /// Radians a second, signed.
133
    pub speed: f32,
134
    /// 1 for today, fading to 0.3 for a month ago.
135
    pub bright: f32,
136
    /// How lit it is now, 0 to 1.
137
    pub lit: f32,
138
}
139
140
/// Straight RGBA, 0 to 1, as the page's tokens give them.
141
pub type Rgba = [f32; 4];
142
143
/// The three backdrop tokens (§3).
144
#[derive(Clone, Copy, Debug, PartialEq)]
145
pub struct Colours {
146
    pub mark: Rgba,
147
    pub lit: Rgba,
148
    pub link: Rgba,
149
}
150
151
/// The scene.
152
pub struct Sky {
153
    pub clusters: Vec<Cluster>,
154
    pub marks: Vec<Mark>,
155
    /// The view, in CSS pixels.
156
    pub w: f32,
157
    pub h: f32,
158
    /// Where the cursor is, if it is over the page.
159
    pub cursor: Option<(f32, f32)>,
160
    /// Seconds since the cursor last moved.
161
    pub rested: f32,
162
    /// Still (reduced motion, or the viewer's choice): no drift, no
163
    /// parallax, and marks light at once.
164
    pub still: bool,
165
    /// The page's content column, left and right, in CSS pixels: clusters
166
    /// go in the margins beside it, where they can be seen.
167
    avoid: Option<(f32, f32)>,
168
    parallax: [(f32, f32); 3],
169
    link_fade: f32,
170
}
171
172
/// FNV-1a: a small, stable hash, so a repository's place never changes.
173
pub fn hash(s: &str) -> u64 {
174
    let mut h: u64 = 0xcbf2_9ce4_8422_2325;
175
    for b in s.as_bytes() {
176
        h ^= *b as u64;
177
        h = h.wrapping_mul(0x0100_0000_01b3);
178
    }
179
    h
180
}
181
182
/// A number from 0 to 1 from bits of a hash.
183
fn unit(h: u64, shift: u32) -> f32 {
184
    ((h >> shift) & 0xffff) as f32 / 65536.0
185
}
186
187
impl Sky {
188
    /// The sky of `repos` and their `events` (newest first, as the page
189
    /// lists them), in a view of `w` by `h` CSS pixels.
190
    pub fn new(repos: &[Repo], events: &[Event], w: f32, h: f32, still: bool) -> Sky {
191
        // The most active repositories in front, the quiet ones behind.
192
        let mut activity = vec![0u32; repos.len()];
193
        for e in events {
194
            if e.repo < repos.len() && e.age_days <= DAYS {
195
                activity[e.repo] += 1;
196
            }
197
        }
198
        let mut rank: Vec<usize> = (0..repos.len()).collect();
199
        rank.sort_by_key(|&i| std::cmp::Reverse(activity[i]));
200
        let mut layer = vec![2usize; repos.len()];
201
        for (pos, &i) in rank.iter().enumerate() {
202
            layer[i] = (pos * 3 / repos.len().max(1)).min(2);
203
        }
204
        let clusters: Vec<Cluster> =
205
            repos.iter().enumerate().map(|(i, r)| Cluster { name: r.name.clone(), fx: 0.5, fy: 0.5, layer: layer[i] }).collect();
206
        let mut marks: Vec<Mark> = Vec::new();
207
        for i in 0..clusters.len() {
208
            marks.push(Mark { cluster: i, kind: Kind::Repo, order: 0, radius: 0.0, angle: 0.0, speed: 0.0, bright: 0.9, lit: 0.0 });
209
        }
210
        // Each event's marks: a push is a dot for each change it brought.
211
        let expanded: Vec<Event> = events
212
            .iter()
213
            .filter(|e| e.repo < repos.len() && e.age_days <= DAYS)
214
            .flat_map(|e| std::iter::repeat_n(*e, if e.kind == Kind::Push { e.n.clamp(1, PER_PUSH) as usize } else { 1 }))
215
            .take(MAX_MARKS)
216
            .collect();
217
        // A busy repository gets more lanes, so its marks spread out.
218
        let mut count = vec![0u32; repos.len()];
219
        for e in &expanded {
220
            count[e.repo] += 1;
221
        }
222
        let mut seen = vec![0u32; repos.len()];
223
        for e in &expanded {
224
            let k = seen[e.repo];
225
            seen[e.repo] += 1;
226
            let lanes = (6 + count[e.repo] / 30).min(14);
227
            let h = hash(&format!("{}#{k}", repos[e.repo].name));
228
            // Each repository turns one way; its marks keep their lanes, so
229
            // two clusters' streams cross without touching.
230
            let dir = if hash(&repos[e.repo].name) & 1 == 0 { 1.0 } else { -1.0 };
231
            // Lanes close together: each repository a tight knot.
232
            let radius = (16.0 + (k % lanes) as f32 * 6.5 + unit(h, 0) * 4.0) * ZOOM;
233
            let speed = dir * (MAX_SPEED / radius).min(0.25) * (0.5 + 0.5 * unit(h, 16));
234
            marks.push(Mark {
235
                cluster: e.repo,
236
                kind: e.kind,
237
                order: k,
238
                radius,
239
                angle: unit(h, 32) * TAU,
240
                speed,
241
                bright: 1.0 - 0.7 * (e.age_days / DAYS).clamp(0.0, 1.0),
242
                lit: 0.0,
243
            });
244
        }
245
        let mut sky =
246
            Sky { clusters, marks, w, h, cursor: None, rested: 0.0, still, avoid: None, parallax: [(0.0, 0.0); 3], link_fade: 0.0 };
247
        sky.layout();
248
        sky
249
    }
250
251
    /// The view is now `w` by `h`, its content column between `avoid`'s
252
    /// left and right.
253
    pub fn resize(&mut self, w: f32, h: f32, avoid: Option<(f32, f32)>) {
254
        self.w = w;
255
        self.h = h;
256
        self.avoid = avoid;
257
        self.layout();
258
    }
259
260
    /// Place the clusters. In the margins beside the content when both are
261
    /// wide enough: repositories in the order of their names' hashes, split
262
    /// between the sides by their widths, each side a staggered grid from
263
    /// top to bottom, so the sky fills the space the page leaves. Otherwise
264
    /// a ring around the middle. The same repositories in the same view
265
    /// always land in the same places.
266
    fn layout(&mut self) {
267
        let n = self.clusters.len();
268
        let mut order: Vec<usize> = (0..n).collect();
269
        order.sort_by_key(|&i| hash(&self.clusters[i].name));
270
        let margins = self.avoid.and_then(|(x0, x1)| {
271
            let (l, r) = (x0.max(0.0), (self.w - x1).max(0.0));
272
            (l >= MIN_MARGIN && r >= MIN_MARGIN).then_some((l, r, x1))
273
        });
274
        match margins {
275
            Some((l, r, x1)) => {
276
                let left = (((n as f32) * l / (l + r)).round() as usize).min(n);
277
                let (a, b) = order.split_at(left);
278
                self.grid(a, 0.0, l);
279
                self.grid(b, x1, self.w);
280
            }
281
            None => {
282
                for c in &mut self.clusters {
283
                    let h = hash(&c.name);
284
                    let a = unit(h, 0) * TAU;
285
                    let d = 0.25 + 0.3 * unit(h, 16).sqrt();
286
                    c.fx = (0.5 + d * a.cos()).clamp(0.03, 0.97);
287
                    c.fy = (0.5 + 0.9 * d * a.sin()).clamp(0.05, 0.95);
288
                }
289
            }
290
        }
291
    }
292
293
    /// Lay `ids` out in a staggered grid between `x0` and `x1`.
294
    fn grid(&mut self, ids: &[usize], x0: f32, x1: f32) {
295
        if ids.is_empty() || self.w <= 0.0 || self.h <= 0.0 {
296
            return;
297
        }
298
        let (top, bottom) = (self.h * 0.1, self.h * 0.97);
299
        let width = x1 - x0;
300
        let cols = ((width / CELL) as usize).clamp(1, 3);
301
        let rows = ids.len().div_ceil(cols);
302
        let (cw, ch) = (width / cols as f32, (bottom - top) / rows as f32);
303
        for (j, &i) in ids.iter().enumerate() {
304
            let (col, row) = (j % cols, j / cols);
305
            let h = hash(&self.clusters[i].name);
306
            let stagger = if cols > 1 && row % 2 == 1 { cw * 0.25 } else { 0.0 };
307
            let cx = x0 + (col as f32 + 0.5) * cw + stagger + (unit(h, 0) - 0.5) * 0.3 * cw;
308
            let cy = top + (row as f32 + 0.5) * ch + (unit(h, 16) - 0.5) * 0.3 * ch;
309
            self.clusters[i].fx = cx.clamp(x0 + 24.0, x1 - 24.0) / self.w;
310
            self.clusters[i].fy = cy / self.h;
311
        }
312
    }
313
314
    /// The cursor moved to `(x, y)`, or left the page.
315
    pub fn point(&mut self, at: Option<(f32, f32)>) {
316
        self.cursor = at;
317
        self.rested = 0.0;
318
    }
319
320
    /// Where cluster `c`'s core is now.
321
    pub fn core(&self, c: usize) -> (f32, f32) {
322
        let cl = &self.clusters[c];
323
        let (px, py) = self.parallax[cl.layer];
324
        (cl.fx * self.w + px, cl.fy * self.h + py)
325
    }
326
327
    /// Where mark `m` is now.
328
    pub fn position(&self, m: &Mark) -> (f32, f32) {
329
        let (cx, cy) = self.core(m.cluster);
330
        (cx + m.angle.cos() * m.radius, cy + m.angle.sin() * m.radius)
331
    }
332
333
    /// Move the scene on by `dt` seconds.
334
    pub fn step(&mut self, dt: f32) {
335
        let dt = dt.clamp(0.0, 0.1);
336
        self.rested += dt;
337
        if !self.still {
338
            for m in &mut self.marks {
339
                m.angle = (m.angle + m.speed * dt) % TAU;
340
            }
341
            let ease = 1.0 - (-dt * 4.0).exp();
342
            for (l, p) in self.parallax.iter_mut().enumerate() {
343
                let (tx, ty) = match self.cursor {
344
                    Some((x, y)) if self.w > 0.0 && self.h > 0.0 => {
345
                        (-(x - self.w / 2.0) / (self.w / 2.0) * PARALLAX[l], -(y - self.h / 2.0) / (self.h / 2.0) * PARALLAX[l])
346
                    }
347
                    _ => (0.0, 0.0),
348
                };
349
                p.0 += (tx - p.0) * ease;
350
                p.1 += (ty - p.1) * ease;
351
            }
352
        }
353
        let lit_targets: Vec<f32> = self
354
            .marks
355
            .iter()
356
            .map(|m| match self.cursor {
357
                Some((x, y)) => {
358
                    let (mx, my) = self.position(m);
359
                    if (mx - x).hypot(my - y) <= LIGHT_RADIUS {
360
                        1.0
361
                    } else {
362
                        0.0
363
                    }
364
                }
365
                None => 0.0,
366
            })
367
            .collect();
368
        for (m, target) in self.marks.iter_mut().zip(lit_targets) {
369
            m.lit = if self.still {
370
                target
371
            } else if target > m.lit {
372
                (m.lit + dt / LIT_IN).min(target)
373
            } else {
374
                (m.lit - dt / LIT_OUT).max(target)
375
            };
376
        }
377
        let fade_to = if self.cursor.is_some() && self.rested < LINK_REST { 1.0 } else { 0.0 };
378
        self.link_fade = if self.still {
379
            fade_to
380
        } else if fade_to > self.link_fade {
381
            (self.link_fade + dt / LIT_IN).min(1.0)
382
        } else {
383
            (self.link_fade - dt / LIT_OUT).max(0.0)
384
        };
385
    }
386
387
    /// Whether anything is still changing: a frame is worth drawing.
388
    pub fn busy(&self) -> bool {
389
        !self.still || self.marks.iter().any(|m| m.lit > 0.0 && m.lit < 1.0) || (self.link_fade > 0.0 && self.link_fade < 1.0)
390
    }
391
392
    /// One instance per mark: centre x, y and radius in CSS pixels, its
393
    /// shape, and its colour premultiplied, 8 floats each.
394
    pub fn instances(&self, c: &Colours, out: &mut Vec<f32>) {
395
        out.clear();
396
        for m in &self.marks {
397
            let (x, y) = self.position(m);
398
            let rest = [c.mark[0], c.mark[1], c.mark[2], c.mark[3] * m.bright];
399
            let col = mix(rest, c.lit, m.lit);
400
            let size = m.kind.size() * ZOOM * (1.0 + 0.35 * m.lit);
401
            out.extend_from_slice(&[x, y, size, m.kind.shape(), col[0] * col[3], col[1] * col[3], col[2] * col[3], col[3]]);
402
        }
403
    }
404
405
    /// The links among lit marks: each repository's lit marks in the order
406
    /// they happened, its core to its newest lit mark. Two vertices a
407
    /// link, x, y and a premultiplied colour each, 6 floats a vertex.
408
    pub fn links(&self, c: &Colours, out: &mut Vec<f32>) {
409
        out.clear();
410
        if self.link_fade <= 0.0 {
411
            return;
412
        }
413
        for ci in 0..self.clusters.len() {
414
            let mut lit: Vec<&Mark> = self.marks.iter().filter(|m| m.cluster == ci && m.lit > 0.05).collect();
415
            lit.sort_by_key(|m| (m.kind != Kind::Repo, m.order));
416
            for pair in lit.windows(2) {
417
                let (a, b) = (self.position(pair[0]), self.position(pair[1]));
418
                if (a.0 - b.0).hypot(a.1 - b.1) > LINK_MAX {
419
                    continue;
420
                }
421
                let alpha = c.link[3] * pair[0].lit.min(pair[1].lit) * self.link_fade;
422
                let col = [c.link[0] * alpha, c.link[1] * alpha, c.link[2] * alpha, alpha];
423
                out.extend_from_slice(&[a.0, a.1, col[0], col[1], col[2], col[3], b.0, b.1, col[0], col[1], col[2], col[3]]);
424
            }
425
        }
426
    }
427
428
    /// How far a cluster's marks reach from its core.
429
    fn reach(&self, c: usize) -> f32 {
430
        self.marks.iter().filter(|m| m.cluster == c).map(|m| m.radius).fold(0.0, f32::max)
431
    }
432
433
    /// The name to show for a resting cursor, and where: centred just
434
    /// above the nearest cluster within reach, clear of its marks.
435
    pub fn label(&self) -> Option<(&str, f32, f32)> {
436
        let (x, y) = self.cursor?;
437
        if self.rested < LABEL_REST {
438
            return None;
439
        }
440
        (0..self.clusters.len())
441
            .map(|i| (i, self.core(i)))
442
            .map(|(i, (cx, cy))| (i, cx, cy, (cx - x).hypot(cy - y)))
443
            .filter(|t| t.3 <= LABEL_NEAR)
444
            .min_by(|a, b| a.3.total_cmp(&b.3))
445
            .map(|(i, cx, cy, _)| (self.clusters[i].name.as_str(), cx, cy - self.reach(i) - 10.0))
446
    }
447
}
448
449
fn mix(a: Rgba, b: Rgba, t: f32) -> Rgba {
450
    let t = t.clamp(0.0, 1.0);
451
    [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t, a[2] + (b[2] - a[2]) * t, a[3] + (b[3] - a[3]) * t]
452
}
453
454
/// A computed CSS colour: `rgb(r, g, b)`, `rgba(r, g, b, a)` or
455
/// `color(srgb r g b / a)`, as browsers report them.
456
pub fn parse_colour(s: &str) -> Option<Rgba> {
457
    let s = s.trim();
458
    if let Some(inner) = s.strip_prefix("color(srgb").and_then(|r| r.strip_suffix(')')) {
459
        let (rgb, a) = match inner.split_once('/') {
460
            Some((rgb, a)) => (rgb, a.trim().parse().ok()?),
461
            None => (inner, 1.0),
462
        };
463
        let v: Vec<f32> = rgb.split_whitespace().map(|x| x.parse().ok()).collect::<Option<_>>()?;
464
        return (v.len() == 3).then(|| [v[0], v[1], v[2], a]);
465
    }
466
    let inner = s.strip_prefix("rgba(").or_else(|| s.strip_prefix("rgb("))?.strip_suffix(')')?;
467
    let v: Vec<f32> = inner.split([',', ' ', '/']).filter(|x| !x.is_empty()).map(|x| x.trim().parse().ok()).collect::<Option<_>>()?;
468
    match v.len() {
469
        3 => Some([v[0] / 255.0, v[1] / 255.0, v[2] / 255.0, 1.0]),
470
        4 => Some([v[0] / 255.0, v[1] / 255.0, v[2] / 255.0, v[3]]),
471
        _ => None,
472
    }
473
}
474
475
#[cfg(test)]
476
mod tests {
477
    use super::*;
478
479
    fn sky(still: bool) -> Sky {
480
        let repos = vec![Repo { name: "andy/hub".into() }, Repo { name: "andy/oxygen".into() }];
481
        let events = vec![
482
            Event { repo: 0, kind: Kind::Push, age_days: 0.0, n: 3 },
483
            Event { repo: 0, kind: Kind::Proposal, age_days: 2.0, n: 1 },
484
            Event { repo: 1, kind: Kind::Release, age_days: 29.0, n: 1 },
485
            Event { repo: 1, kind: Kind::Issue, age_days: 45.0, n: 1 },
486
        ];
487
        Sky::new(&repos, &events, 1600.0, 900.0, still)
488
    }
489
490
    #[test]
491
    fn a_sky_is_the_same_on_every_visit() {
492
        let (a, b) = (sky(false), sky(false));
493
        assert_eq!(a.clusters[0].fx, b.clusters[0].fx);
494
        assert_eq!(a.clusters[1].fy, b.clusters[1].fy);
495
        // A core per repository, a dot per change pushed, and one mark per
496
        // other event of the last 30 days.
497
        assert_eq!(a.marks.len(), 2 + 3 + 1 + 1);
498
        assert!(a.marks.iter().all(|m| m.kind != Kind::Issue), "older than 30 days: not drawn");
499
        let newest = a.marks.iter().find(|m| m.kind == Kind::Push).unwrap();
500
        let old = a.marks.iter().find(|m| m.kind == Kind::Release).unwrap();
501
        assert!(newest.bright > old.bright, "newer is brighter");
502
        assert_eq!(a.clusters[0].layer, 0, "the busiest in front");
503
    }
504
505
    #[test]
506
    fn marks_drift_slowly_and_the_cursor_lights_without_pulling() {
507
        let mut s = sky(false);
508
        for m in &s.marks {
509
            assert!(m.speed.abs() * m.radius <= MAX_SPEED + 0.01, "at most 12 px a second");
510
        }
511
        let target = s.position(&s.marks[2]);
512
        let radii: Vec<f32> = s.marks.iter().map(|m| m.radius).collect();
513
        s.point(Some(target));
514
        for _ in 0..30 {
515
            s.step(1.0 / 60.0);
516
        }
517
        assert!(s.marks[2].lit > 0.99, "lit near the cursor");
518
        assert_eq!(radii, s.marks.iter().map(|m| m.radius).collect::<Vec<_>>(), "nothing is pulled");
519
        let mut links = Vec::new();
520
        let colours = Colours { mark: [0.5, 0.5, 0.5, 0.2], lit: [0.0, 0.4, 0.9, 0.7], link: [0.0, 0.4, 0.9, 0.3] };
521
        s.links(&colours, &mut links);
522
        assert!(!links.is_empty() && links.len() % 12 == 0, "lit marks of one repository are joined");
523
        // Resting fades the links; leaving fades the light.
524
        for _ in 0..240 {
525
            s.step(1.0 / 60.0);
526
        }
527
        s.links(&colours, &mut links);
528
        assert!(links.is_empty(), "a resting cursor's links fade");
529
        s.point(None);
530
        for _ in 0..60 {
531
            s.step(1.0 / 60.0);
532
        }
533
        assert!(s.marks.iter().all(|m| m.lit == 0.0));
534
    }
535
536
    #[test]
537
    fn still_means_no_drift_and_instant_light() {
538
        let mut s = sky(true);
539
        let before: Vec<f32> = s.marks.iter().map(|m| m.angle).collect();
540
        let at = s.position(&s.marks[2]);
541
        s.point(Some(at));
542
        s.step(1.0 / 60.0);
543
        assert_eq!(before, s.marks.iter().map(|m| m.angle).collect::<Vec<_>>());
544
        assert_eq!(s.marks[2].lit, 1.0);
545
        assert!(!s.busy(), "nothing left to animate");
546
    }
547
548
    #[test]
549
    fn instances_are_premultiplied_and_a_resting_cursor_names_a_cluster() {
550
        let mut s = sky(false);
551
        let colours = Colours { mark: [1.0, 1.0, 1.0, 0.5], lit: [0.0, 0.0, 1.0, 1.0], link: [0.0, 0.0, 1.0, 0.3] };
552
        let mut inst = Vec::new();
553
        s.instances(&colours, &mut inst);
554
        assert_eq!(inst.len(), s.marks.len() * 8);
555
        let core = &inst[0..8];
556
        assert!((core[4] - core[7]).abs() < 1e-6 && core[7] < 0.5, "premultiplied, dimmed by brightness");
557
        let (cx, cy) = s.core(1);
558
        s.point(Some((cx + 10.0, cy)));
559
        assert!(s.label().is_none(), "not while moving");
560
        for _ in 0..10 {
561
            s.step(0.05);
562
        }
563
        assert_eq!(s.label().map(|l| l.0), Some("andy/oxygen"));
564
    }
565
566
    #[test]
567
    fn clusters_fill_the_margins_beside_the_content() {
568
        let repos: Vec<Repo> = (0..17).map(|i| Repo { name: format!("owner/repo{i}") }).collect();
569
        let mut s = Sky::new(&repos, &[], 2560.0, 1270.0, false);
570
        s.resize(2560.0, 1270.0, Some((707.0, 1838.0)));
571
        let xs: Vec<f32> = (0..17).map(|i| s.core(i).0).collect();
572
        assert!(xs.iter().all(|&x| x < 707.0 || x > 1838.0), "none behind the content: {xs:?}");
573
        let left = xs.iter().filter(|&&x| x < 707.0).count();
574
        assert!((7..=10).contains(&left), "both sides used: {left} on the left");
575
        let ys: Vec<f32> = (0..17).map(|i| s.core(i).1).collect();
576
        assert!(ys.iter().any(|&y| y < 400.0) && ys.iter().any(|&y| y > 900.0), "top to bottom: {ys:?}");
577
        // The same view lays the same sky out.
578
        let mut again = Sky::new(&repos, &[], 2560.0, 1270.0, false);
579
        again.resize(2560.0, 1270.0, Some((707.0, 1838.0)));
580
        assert_eq!(xs, (0..17).map(|i| again.core(i).0).collect::<Vec<_>>());
581
        // Narrow margins: back to the ring.
582
        s.resize(1200.0, 800.0, Some((100.0, 1100.0)));
583
        assert!((0..17).any(|i| (s.core(i).0 - 600.0).abs() < 400.0));
584
    }
585
586
    #[test]
587
    fn computed_colours_parse() {
588
        assert_eq!(parse_colour("rgb(9, 105, 218)"), Some([9.0 / 255.0, 105.0 / 255.0, 218.0 / 255.0, 1.0]));
589
        assert_eq!(parse_colour("rgba(0, 240, 255, 0.75)").map(|c| c[3]), Some(0.75));
590
        assert_eq!(parse_colour("color(srgb 0 0.5 1 / 0.2)"), Some([0.0, 0.5, 1.0, 0.2]));
591
        assert_eq!(parse_colour("rgb(1 2 3 / 0.5)").map(|c| c[3]), Some(0.5));
592
        assert!(parse_colour("transparent").is_none());
593
    }
594
}