OXYGENHUB
# 946fe7a09faa oxygenhub / crates / backdrop / src / sky.rs
30.1 KiB · Rust · last changed UI polish: keys, backups, wiki, editor, bookmarks, summaries, backdrops 21 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
/// An arrival's ring (§4): seconds it lasts, and its radius from first to
44
/// last, in CSS pixels before the zoom.
45
const RING_S: f32 = 1.2;
46
const RING_FROM: f32 = 6.0;
47
const RING_TO: f32 = 46.0;
48
49
/// What a mark stands for, which decides its shape.
50
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
51
pub enum Kind {
52
    Push,
53
    Proposal,
54
    Issue,
55
    Release,
56
    /// A Flow run.
57
    Run,
58
    /// The repository itself, its cluster's core.
59
    Repo,
60
}
61
62
impl Kind {
63
    /// The code the page's data uses: 0 a push's change, 1 a proposal
64
    /// event, 2 an issue event, 3 a release, 4 a Flow run.
65
    pub fn from_code(code: u32) -> Kind {
66
        match code {
67
            1 => Kind::Proposal,
68
            2 => Kind::Issue,
69
            3 => Kind::Release,
70
            4 => Kind::Run,
71
            _ => Kind::Push,
72
        }
73
    }
74
75
    /// The shape the fragment shader draws: 0 dot, 1 diamond, 2 ring,
76
    /// 3 four-point star, 4 thin ring (a repository), 5 square.
77
    pub fn shape(self) -> f32 {
78
        match self {
79
            Kind::Push => 0.0,
80
            Kind::Proposal => 1.0,
81
            Kind::Issue => 2.0,
82
            Kind::Release => 3.0,
83
            Kind::Repo => 4.0,
84
            Kind::Run => 5.0,
85
        }
86
    }
87
88
    /// Its radius in CSS pixels.
89
    fn size(self) -> f32 {
90
        match self {
91
            Kind::Push => 2.0,
92
            Kind::Run => 2.2,
93
            Kind::Proposal => 3.2,
94
            Kind::Issue => 3.0,
95
            Kind::Release => 4.2,
96
            Kind::Repo => 6.0,
97
        }
98
    }
99
}
100
101
/// One repository, as the page gives it.
102
#[derive(Clone, Debug)]
103
pub struct Repo {
104
    pub name: String,
105
}
106
107
/// One event, as the page gives it: its repository (an index into the
108
/// repositories), its kind, how old it is, and how many marks it makes (a
109
/// push's changes; one otherwise).
110
#[derive(Clone, Copy, Debug)]
111
pub struct Event {
112
    pub repo: usize,
113
    pub kind: Kind,
114
    pub age_days: f32,
115
    pub n: u32,
116
}
117
118
/// A repository's place: a fraction of the view, and a depth layer.
119
#[derive(Clone, Debug)]
120
pub struct Cluster {
121
    pub name: String,
122
    pub fx: f32,
123
    pub fy: f32,
124
    pub layer: usize,
125
}
126
127
/// One drawn mark, orbiting its cluster.
128
#[derive(Clone, Debug)]
129
pub struct Mark {
130
    pub cluster: usize,
131
    pub kind: Kind,
132
    /// Its place in its cluster's history, 0 the newest; the core is 0
133
    /// too and has radius 0.
134
    pub order: u32,
135
    pub radius: f32,
136
    pub angle: f32,
137
    /// Radians a second, signed.
138
    pub speed: f32,
139
    /// 1 for today, fading to 0.3 for a month ago.
140
    pub bright: f32,
141
    /// How lit it is now, 0 to 1.
142
    pub lit: f32,
143
}
144
145
/// Straight RGBA, 0 to 1, as the page's tokens give them.
146
pub type Rgba = [f32; 4];
147
148
/// The three backdrop tokens (§3), and the page's status colours for the
149
/// scenes whose data has a status (Diffusion's pills).
150
#[derive(Clone, Copy, Debug, Default, PartialEq)]
151
pub struct Colours {
152
    pub mark: Rgba,
153
    pub lit: Rgba,
154
    pub link: Rgba,
155
    pub ok: Rgba,
156
    pub warn: Rgba,
157
    pub bad: Rgba,
158
}
159
160
/// A widening ring at a cluster's core: something just arrived there.
161
#[derive(Clone, Copy, Debug)]
162
pub struct Ring {
163
    pub cluster: usize,
164
    /// Seconds since it began.
165
    pub age: f32,
166
}
167
168
/// The scene.
169
pub struct Sky {
170
    pub clusters: Vec<Cluster>,
171
    pub marks: Vec<Mark>,
172
    /// The view, in CSS pixels.
173
    pub w: f32,
174
    pub h: f32,
175
    /// Where the cursor is, if it is over the page.
176
    pub cursor: Option<(f32, f32)>,
177
    /// Seconds since the cursor last moved.
178
    pub rested: f32,
179
    /// Still (reduced motion, or the viewer's choice): no drift, no
180
    /// parallax, and marks light at once.
181
    pub still: bool,
182
    /// The page's content column, left and right, in CSS pixels: clusters
183
    /// go in the margins beside it, where they can be seen.
184
    avoid: Option<(f32, f32)>,
185
    parallax: [(f32, f32); 3],
186
    link_fade: f32,
187
    /// Arrivals' rings, while they widen.
188
    pub rings: Vec<Ring>,
189
    /// Marks added since the page loaded, for their places in the lanes.
190
    arrived: u32,
191
}
192
193
/// FNV-1a, then splitmix64's finaliser: a small, stable hash, so a
194
/// repository's place never changes. The finaliser spreads every bit:
195
/// FNV alone gives names that differ only at the end (`repo#1`, `repo#2`)
196
/// alike high bits, which drew a cluster's marks as fans at a few angles.
197
pub fn hash(s: &str) -> u64 {
198
    let mut h: u64 = 0xcbf2_9ce4_8422_2325;
199
    for b in s.as_bytes() {
200
        h ^= *b as u64;
201
        h = h.wrapping_mul(0x0100_0000_01b3);
202
    }
203
    h = (h ^ (h >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9);
204
    h = (h ^ (h >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb);
205
    h ^ (h >> 31)
206
}
207
208
/// A number from 0 to 1 from bits of a hash.
209
fn unit(h: u64, shift: u32) -> f32 {
210
    ((h >> shift) & 0xffff) as f32 / 65536.0
211
}
212
213
impl Sky {
214
    /// The sky of `repos` and their `events` (newest first, as the page
215
    /// lists them), in a view of `w` by `h` CSS pixels.
216
    pub fn new(repos: &[Repo], events: &[Event], w: f32, h: f32, still: bool) -> Sky {
217
        // The most active repositories in front, the quiet ones behind.
218
        let mut activity = vec![0u32; repos.len()];
219
        for e in events {
220
            if e.repo < repos.len() && e.age_days <= DAYS {
221
                activity[e.repo] += 1;
222
            }
223
        }
224
        let mut rank: Vec<usize> = (0..repos.len()).collect();
225
        rank.sort_by_key(|&i| std::cmp::Reverse(activity[i]));
226
        let mut layer = vec![2usize; repos.len()];
227
        for (pos, &i) in rank.iter().enumerate() {
228
            layer[i] = (pos * 3 / repos.len().max(1)).min(2);
229
        }
230
        let clusters: Vec<Cluster> =
231
            repos.iter().enumerate().map(|(i, r)| Cluster { name: r.name.clone(), fx: 0.5, fy: 0.5, layer: layer[i] }).collect();
232
        let mut marks: Vec<Mark> = Vec::new();
233
        for i in 0..clusters.len() {
234
            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 });
235
        }
236
        // Each event's marks: a push is a dot for each change it brought.
237
        let expanded: Vec<Event> = events
238
            .iter()
239
            .filter(|e| e.repo < repos.len() && e.age_days <= DAYS)
240
            .flat_map(|e| std::iter::repeat_n(*e, if e.kind == Kind::Push { e.n.clamp(1, PER_PUSH) as usize } else { 1 }))
241
            .take(MAX_MARKS)
242
            .collect();
243
        // A busy repository gets more lanes, so its marks spread out.
244
        let mut count = vec![0u32; repos.len()];
245
        for e in &expanded {
246
            count[e.repo] += 1;
247
        }
248
        let mut seen = vec![0u32; repos.len()];
249
        for e in &expanded {
250
            let k = seen[e.repo];
251
            seen[e.repo] += 1;
252
            let lanes = (6 + count[e.repo] / 30).min(14);
253
            let h = hash(&format!("{}#{k}", repos[e.repo].name));
254
            // Each repository turns one way; its marks keep their lanes, so
255
            // two clusters' streams cross without touching.
256
            let dir = if hash(&repos[e.repo].name) & 1 == 0 { 1.0 } else { -1.0 };
257
            // Lanes close together: each repository a tight knot.
258
            let radius = (16.0 + (k % lanes) as f32 * 6.5 + unit(h, 0) * 4.0) * ZOOM;
259
            let speed = dir * (MAX_SPEED / radius).min(0.25) * (0.5 + 0.5 * unit(h, 16));
260
            marks.push(Mark {
261
                cluster: e.repo,
262
                kind: e.kind,
263
                order: k,
264
                radius,
265
                angle: unit(h, 32) * TAU,
266
                speed,
267
                bright: 1.0 - 0.7 * (e.age_days / DAYS).clamp(0.0, 1.0),
268
                lit: 0.0,
269
            });
270
        }
271
        let mut sky = Sky {
272
            clusters,
273
            marks,
274
            w,
275
            h,
276
            cursor: None,
277
            rested: 0.0,
278
            still,
279
            avoid: None,
280
            parallax: [(0.0, 0.0); 3],
281
            link_fade: 0.0,
282
            rings: Vec::new(),
283
            arrived: 0,
284
        };
285
        sky.layout();
286
        sky
287
    }
288
289
    /// The view is now `w` by `h`, its content column between `avoid`'s
290
    /// left and right.
291
    pub fn resize(&mut self, w: f32, h: f32, avoid: Option<(f32, f32)>) {
292
        self.w = w;
293
        self.h = h;
294
        self.avoid = avoid;
295
        self.layout();
296
    }
297
298
    /// Place the clusters. In the margins beside the content when both are
299
    /// wide enough: repositories in the order of their names' hashes, split
300
    /// between the sides by their widths, each side a staggered grid from
301
    /// top to bottom, so the sky fills the space the page leaves. Otherwise
302
    /// a ring around the middle. The same repositories in the same view
303
    /// always land in the same places.
304
    fn layout(&mut self) {
305
        let n = self.clusters.len();
306
        let mut order: Vec<usize> = (0..n).collect();
307
        order.sort_by_key(|&i| hash(&self.clusters[i].name));
308
        let margins = self.avoid.and_then(|(x0, x1)| {
309
            let (l, r) = (x0.max(0.0), (self.w - x1).max(0.0));
310
            (l >= MIN_MARGIN && r >= MIN_MARGIN).then_some((l, r, x1))
311
        });
312
        // One repository's own sky (oxygenhub#196): its cluster sits in the
313
        // wider margin, a little below the middle, even a narrow one, so
314
        // it never lands on the page's heading or tabs.
315
        if n == 1 {
316
            if let Some((x0, x1)) = self.avoid {
317
                let (l, r) = (x0.max(0.0), (self.w - x1).max(0.0));
318
                if l.max(r) >= 40.0 && self.w > 0.0 {
319
                    let cx = if r >= l { x1 + r / 2.0 } else { l / 2.0 };
320
                    self.clusters[0].fx = cx / self.w;
321
                    self.clusters[0].fy = 0.6;
322
                    return;
323
                }
324
            }
325
        }
326
        match margins {
327
            Some((l, r, x1)) => {
328
                let left = (((n as f32) * l / (l + r)).round() as usize).min(n);
329
                let (a, b) = order.split_at(left);
330
                self.grid(a, 0.0, l);
331
                self.grid(b, x1, self.w);
332
            }
333
            None => {
334
                for c in &mut self.clusters {
335
                    let h = hash(&c.name);
336
                    let a = unit(h, 0) * TAU;
337
                    let d = 0.25 + 0.3 * unit(h, 16).sqrt();
338
                    c.fx = (0.5 + d * a.cos()).clamp(0.03, 0.97);
339
                    c.fy = (0.5 + 0.9 * d * a.sin()).clamp(0.05, 0.95);
340
                }
341
            }
342
        }
343
    }
344
345
    /// Lay `ids` out in a staggered grid between `x0` and `x1`.
346
    fn grid(&mut self, ids: &[usize], x0: f32, x1: f32) {
347
        if ids.is_empty() || self.w <= 0.0 || self.h <= 0.0 {
348
            return;
349
        }
350
        let (top, bottom) = (self.h * 0.1, self.h * 0.97);
351
        let width = x1 - x0;
352
        let cols = ((width / CELL) as usize).clamp(1, 3);
353
        let rows = ids.len().div_ceil(cols);
354
        let (cw, ch) = (width / cols as f32, (bottom - top) / rows as f32);
355
        for (j, &i) in ids.iter().enumerate() {
356
            let (col, row) = (j % cols, j / cols);
357
            let h = hash(&self.clusters[i].name);
358
            let stagger = if cols > 1 && row % 2 == 1 { cw * 0.25 } else { 0.0 };
359
            let cx = x0 + (col as f32 + 0.5) * cw + stagger + (unit(h, 0) - 0.5) * 0.3 * cw;
360
            let cy = top + (row as f32 + 0.5) * ch + (unit(h, 16) - 0.5) * 0.3 * ch;
361
            self.clusters[i].fx = cx.clamp(x0 + 24.0, x1 - 24.0) / self.w;
362
            self.clusters[i].fy = cy / self.h;
363
        }
364
    }
365
366
    /// The cursor moved to `(x, y)`, or left the page.
367
    pub fn point(&mut self, at: Option<(f32, f32)>) {
368
        self.cursor = at;
369
        self.rested = 0.0;
370
    }
371
372
    /// New activity in the repository `name` (§5, "Live"): its marks join
373
    /// its cluster as the newest, and one ring widens from its core. A
374
    /// repository the sky does not draw is ignored; a still sky adds the
375
    /// marks without the ring.
376
    pub fn arrive(&mut self, name: &str, kind: Kind, n: u32) {
377
        let Some(c) = self.clusters.iter().position(|cl| cl.name == name) else {
378
            return;
379
        };
380
        let add = if kind == Kind::Push { n.clamp(1, PER_PUSH) } else { 1 };
381
        for m in self.marks.iter_mut().filter(|m| m.cluster == c && m.kind != Kind::Repo) {
382
            m.order += add;
383
        }
384
        let have = self.marks.iter().filter(|m| m.cluster == c && m.kind != Kind::Repo).count() as u32;
385
        let lanes = (6 + (have + add) / 30).min(14);
386
        let dir = if hash(name) & 1 == 0 { 1.0 } else { -1.0 };
387
        for i in 0..add {
388
            let h = hash(&format!("{name}+{}", self.arrived));
389
            self.arrived += 1;
390
            let radius = (16.0 + ((have + i) % lanes) as f32 * 6.5 + unit(h, 0) * 4.0) * ZOOM;
391
            let speed = dir * (MAX_SPEED / radius).min(0.25) * (0.5 + 0.5 * unit(h, 16));
392
            self.marks.push(Mark { cluster: c, kind, order: add - 1 - i, radius, angle: unit(h, 32) * TAU, speed, bright: 1.0, lit: 0.0 });
393
        }
394
        // Over the limit, the cluster's oldest marks make room.
395
        while self.marks.len() > MAX_MARKS {
396
            let Some(oldest) = self
397
                .marks
398
                .iter()
399
                .enumerate()
400
                .filter(|(_, m)| m.cluster == c && m.kind != Kind::Repo)
401
                .max_by_key(|(_, m)| m.order)
402
                .map(|(i, _)| i)
403
            else {
404
                break;
405
            };
406
            self.marks.swap_remove(oldest);
407
        }
408
        if !self.still {
409
            self.rings.retain(|r| r.cluster != c);
410
            self.rings.push(Ring { cluster: c, age: 0.0 });
411
        }
412
    }
413
414
    /// Where cluster `c`'s core is now.
415
    pub fn core(&self, c: usize) -> (f32, f32) {
416
        let cl = &self.clusters[c];
417
        let (px, py) = self.parallax[cl.layer];
418
        (cl.fx * self.w + px, cl.fy * self.h + py)
419
    }
420
421
    /// Where mark `m` is now.
422
    pub fn position(&self, m: &Mark) -> (f32, f32) {
423
        let (cx, cy) = self.core(m.cluster);
424
        (cx + m.angle.cos() * m.radius, cy + m.angle.sin() * m.radius)
425
    }
426
427
    /// Move the scene on by `dt` seconds.
428
    pub fn step(&mut self, dt: f32) {
429
        let dt = dt.clamp(0.0, 0.1);
430
        self.rested += dt;
431
        for r in &mut self.rings {
432
            r.age += dt;
433
        }
434
        self.rings.retain(|r| r.age < RING_S);
435
        if !self.still {
436
            for m in &mut self.marks {
437
                m.angle = (m.angle + m.speed * dt) % TAU;
438
            }
439
            let ease = 1.0 - (-dt * 4.0).exp();
440
            for (l, p) in self.parallax.iter_mut().enumerate() {
441
                let (tx, ty) = match self.cursor {
442
                    Some((x, y)) if self.w > 0.0 && self.h > 0.0 => {
443
                        (-(x - self.w / 2.0) / (self.w / 2.0) * PARALLAX[l], -(y - self.h / 2.0) / (self.h / 2.0) * PARALLAX[l])
444
                    }
445
                    _ => (0.0, 0.0),
446
                };
447
                p.0 += (tx - p.0) * ease;
448
                p.1 += (ty - p.1) * ease;
449
            }
450
        }
451
        let lit_targets: Vec<f32> = self
452
            .marks
453
            .iter()
454
            .map(|m| match self.cursor {
455
                Some((x, y)) => {
456
                    let (mx, my) = self.position(m);
457
                    if (mx - x).hypot(my - y) <= LIGHT_RADIUS {
458
                        1.0
459
                    } else {
460
                        0.0
461
                    }
462
                }
463
                None => 0.0,
464
            })
465
            .collect();
466
        for (m, target) in self.marks.iter_mut().zip(lit_targets) {
467
            m.lit = if self.still {
468
                target
469
            } else if target > m.lit {
470
                (m.lit + dt / LIT_IN).min(target)
471
            } else {
472
                (m.lit - dt / LIT_OUT).max(target)
473
            };
474
        }
475
        let fade_to = if self.cursor.is_some() && self.rested < LINK_REST { 1.0 } else { 0.0 };
476
        self.link_fade = if self.still {
477
            fade_to
478
        } else if fade_to > self.link_fade {
479
            (self.link_fade + dt / LIT_IN).min(1.0)
480
        } else {
481
            (self.link_fade - dt / LIT_OUT).max(0.0)
482
        };
483
    }
484
485
    /// Whether anything besides the drift is still changing: lighting,
486
    /// links or a ring. The engine keeps drawing a moving sky for a while
487
    /// after the last input anyway (§6), then stops until something is.
488
    pub fn busy(&self) -> bool {
489
        !self.rings.is_empty() || self.marks.iter().any(|m| m.lit > 0.0 && m.lit < 1.0) || (self.link_fade > 0.0 && self.link_fade < 1.0)
490
    }
491
492
    /// One instance per mark: centre x, y and radius in CSS pixels, its
493
    /// shape, and its colour premultiplied, 8 floats each.
494
    pub fn instances(&self, c: &Colours, out: &mut Vec<f32>) {
495
        out.clear();
496
        for m in &self.marks {
497
            let (x, y) = self.position(m);
498
            let rest = [c.mark[0], c.mark[1], c.mark[2], c.mark[3] * m.bright];
499
            let col = mix(rest, c.lit, m.lit);
500
            let size = m.kind.size() * ZOOM * (1.0 + 0.35 * m.lit);
501
            out.extend_from_slice(&[x, y, size, m.kind.shape(), col[0] * col[3], col[1] * col[3], col[2] * col[3], col[3]]);
502
        }
503
        // Arrivals: a thin ring in the lit colour, widening as it fades.
504
        for r in &self.rings {
505
            let t = (r.age / RING_S).clamp(0.0, 1.0);
506
            let (x, y) = self.core(r.cluster);
507
            let size = (RING_FROM + (RING_TO - RING_FROM) * (1.0 - (1.0 - t) * (1.0 - t))) * ZOOM;
508
            let a = c.lit[3] * (1.0 - t) * 0.8;
509
            out.extend_from_slice(&[x, y, size, Kind::Repo.shape(), c.lit[0] * a, c.lit[1] * a, c.lit[2] * a, a]);
510
        }
511
    }
512
513
    /// The links among lit marks: each repository's lit marks in the order
514
    /// they happened, its core to its newest lit mark. Two vertices a
515
    /// link, x, y and a premultiplied colour each, 6 floats a vertex.
516
    pub fn links(&self, c: &Colours, out: &mut Vec<f32>) {
517
        out.clear();
518
        if self.link_fade <= 0.0 {
519
            return;
520
        }
521
        for ci in 0..self.clusters.len() {
522
            let mut lit: Vec<&Mark> = self.marks.iter().filter(|m| m.cluster == ci && m.lit > 0.05).collect();
523
            lit.sort_by_key(|m| (m.kind != Kind::Repo, m.order));
524
            for pair in lit.windows(2) {
525
                let (a, b) = (self.position(pair[0]), self.position(pair[1]));
526
                if (a.0 - b.0).hypot(a.1 - b.1) > LINK_MAX {
527
                    continue;
528
                }
529
                let alpha = c.link[3] * pair[0].lit.min(pair[1].lit) * self.link_fade;
530
                let col = [c.link[0] * alpha, c.link[1] * alpha, c.link[2] * alpha, alpha];
531
                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]]);
532
            }
533
        }
534
    }
535
536
    /// How far a cluster's marks reach from its core.
537
    fn reach(&self, c: usize) -> f32 {
538
        self.marks.iter().filter(|m| m.cluster == c).map(|m| m.radius).fold(0.0, f32::max)
539
    }
540
541
    /// The name to show for a resting cursor, and where: centred just
542
    /// above the nearest cluster within reach, clear of its marks.
543
    pub fn label(&self) -> Option<(&str, f32, f32)> {
544
        let (x, y) = self.cursor?;
545
        if self.rested < LABEL_REST {
546
            return None;
547
        }
548
        (0..self.clusters.len())
549
            .map(|i| (i, self.core(i)))
550
            .map(|(i, (cx, cy))| (i, cx, cy, (cx - x).hypot(cy - y)))
551
            .filter(|t| t.3 <= LABEL_NEAR)
552
            .min_by(|a, b| a.3.total_cmp(&b.3))
553
            .map(|(i, cx, cy, _)| (self.clusters[i].name.as_str(), cx, cy - self.reach(i) - 10.0))
554
    }
555
}
556
557
fn mix(a: Rgba, b: Rgba, t: f32) -> Rgba {
558
    let t = t.clamp(0.0, 1.0);
559
    [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]
560
}
561
562
/// A computed CSS colour: `rgb(r, g, b)`, `rgba(r, g, b, a)` or
563
/// `color(srgb r g b / a)`, as browsers report them.
564
pub fn parse_colour(s: &str) -> Option<Rgba> {
565
    let s = s.trim();
566
    if let Some(inner) = s.strip_prefix("color(srgb").and_then(|r| r.strip_suffix(')')) {
567
        let (rgb, a) = match inner.split_once('/') {
568
            Some((rgb, a)) => (rgb, a.trim().parse().ok()?),
569
            None => (inner, 1.0),
570
        };
571
        let v: Vec<f32> = rgb.split_whitespace().map(|x| x.parse().ok()).collect::<Option<_>>()?;
572
        return (v.len() == 3).then(|| [v[0], v[1], v[2], a]);
573
    }
574
    let inner = s.strip_prefix("rgba(").or_else(|| s.strip_prefix("rgb("))?.strip_suffix(')')?;
575
    let v: Vec<f32> = inner.split([',', ' ', '/']).filter(|x| !x.is_empty()).map(|x| x.trim().parse().ok()).collect::<Option<_>>()?;
576
    match v.len() {
577
        3 => Some([v[0] / 255.0, v[1] / 255.0, v[2] / 255.0, 1.0]),
578
        4 => Some([v[0] / 255.0, v[1] / 255.0, v[2] / 255.0, v[3]]),
579
        _ => None,
580
    }
581
}
582
583
#[cfg(test)]
584
mod tests {
585
    use super::*;
586
587
    fn sky(still: bool) -> Sky {
588
        let repos = vec![Repo { name: "andy/hub".into() }, Repo { name: "andy/oxygen".into() }];
589
        let events = vec![
590
            Event { repo: 0, kind: Kind::Push, age_days: 0.0, n: 3 },
591
            Event { repo: 0, kind: Kind::Proposal, age_days: 2.0, n: 1 },
592
            Event { repo: 1, kind: Kind::Release, age_days: 29.0, n: 1 },
593
            Event { repo: 1, kind: Kind::Issue, age_days: 45.0, n: 1 },
594
        ];
595
        Sky::new(&repos, &events, 1600.0, 900.0, still)
596
    }
597
598
    #[test]
599
    fn a_sky_is_the_same_on_every_visit() {
600
        let (a, b) = (sky(false), sky(false));
601
        assert_eq!(a.clusters[0].fx, b.clusters[0].fx);
602
        assert_eq!(a.clusters[1].fy, b.clusters[1].fy);
603
        // A core per repository, a dot per change pushed, and one mark per
604
        // other event of the last 30 days.
605
        assert_eq!(a.marks.len(), 2 + 3 + 1 + 1);
606
        assert!(a.marks.iter().all(|m| m.kind != Kind::Issue), "older than 30 days: not drawn");
607
        let newest = a.marks.iter().find(|m| m.kind == Kind::Push).unwrap();
608
        let old = a.marks.iter().find(|m| m.kind == Kind::Release).unwrap();
609
        assert!(newest.bright > old.bright, "newer is brighter");
610
        assert_eq!(a.clusters[0].layer, 0, "the busiest in front");
611
    }
612
613
    #[test]
614
    fn marks_drift_slowly_and_the_cursor_lights_without_pulling() {
615
        let mut s = sky(false);
616
        for m in &s.marks {
617
            assert!(m.speed.abs() * m.radius <= MAX_SPEED + 0.01, "at most 12 px a second");
618
        }
619
        let target = s.position(&s.marks[2]);
620
        let radii: Vec<f32> = s.marks.iter().map(|m| m.radius).collect();
621
        s.point(Some(target));
622
        for _ in 0..30 {
623
            s.step(1.0 / 60.0);
624
        }
625
        assert!(s.marks[2].lit > 0.99, "lit near the cursor");
626
        assert_eq!(radii, s.marks.iter().map(|m| m.radius).collect::<Vec<_>>(), "nothing is pulled");
627
        let mut links = Vec::new();
628
        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], ..Default::default() };
629
        s.links(&colours, &mut links);
630
        assert!(!links.is_empty() && links.len() % 12 == 0, "lit marks of one repository are joined");
631
        // Resting fades the links; leaving fades the light.
632
        for _ in 0..240 {
633
            s.step(1.0 / 60.0);
634
        }
635
        s.links(&colours, &mut links);
636
        assert!(links.is_empty(), "a resting cursor's links fade");
637
        s.point(None);
638
        for _ in 0..60 {
639
            s.step(1.0 / 60.0);
640
        }
641
        assert!(s.marks.iter().all(|m| m.lit == 0.0));
642
    }
643
644
    #[test]
645
    fn still_means_no_drift_and_instant_light() {
646
        let mut s = sky(true);
647
        let before: Vec<f32> = s.marks.iter().map(|m| m.angle).collect();
648
        let at = s.position(&s.marks[2]);
649
        s.point(Some(at));
650
        s.step(1.0 / 60.0);
651
        assert_eq!(before, s.marks.iter().map(|m| m.angle).collect::<Vec<_>>());
652
        assert_eq!(s.marks[2].lit, 1.0);
653
        assert!(!s.busy(), "nothing left to animate");
654
    }
655
656
    #[test]
657
    fn instances_are_premultiplied_and_a_resting_cursor_names_a_cluster() {
658
        let mut s = sky(false);
659
        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], ..Default::default() };
660
        let mut inst = Vec::new();
661
        s.instances(&colours, &mut inst);
662
        assert_eq!(inst.len(), s.marks.len() * 8);
663
        let core = &inst[0..8];
664
        assert!((core[4] - core[7]).abs() < 1e-6 && core[7] < 0.5, "premultiplied, dimmed by brightness");
665
        let (cx, cy) = s.core(1);
666
        s.point(Some((cx + 10.0, cy)));
667
        assert!(s.label().is_none(), "not while moving");
668
        for _ in 0..10 {
669
            s.step(0.05);
670
        }
671
        assert_eq!(s.label().map(|l| l.0), Some("andy/oxygen"));
672
    }
673
674
    #[test]
675
    fn clusters_fill_the_margins_beside_the_content() {
676
        let repos: Vec<Repo> = (0..17).map(|i| Repo { name: format!("owner/repo{i}") }).collect();
677
        let mut s = Sky::new(&repos, &[], 2560.0, 1270.0, false);
678
        s.resize(2560.0, 1270.0, Some((707.0, 1838.0)));
679
        let xs: Vec<f32> = (0..17).map(|i| s.core(i).0).collect();
680
        assert!(xs.iter().all(|&x| x < 707.0 || x > 1838.0), "none behind the content: {xs:?}");
681
        let left = xs.iter().filter(|&&x| x < 707.0).count();
682
        assert!((7..=10).contains(&left), "both sides used: {left} on the left");
683
        let ys: Vec<f32> = (0..17).map(|i| s.core(i).1).collect();
684
        assert!(ys.iter().any(|&y| y < 400.0) && ys.iter().any(|&y| y > 900.0), "top to bottom: {ys:?}");
685
        // The same view lays the same sky out.
686
        let mut again = Sky::new(&repos, &[], 2560.0, 1270.0, false);
687
        again.resize(2560.0, 1270.0, Some((707.0, 1838.0)));
688
        assert_eq!(xs, (0..17).map(|i| again.core(i).0).collect::<Vec<_>>());
689
        // Narrow margins: back to the ring.
690
        s.resize(1200.0, 800.0, Some((100.0, 1100.0)));
691
        assert!((0..17).any(|i| (s.core(i).0 - 600.0).abs() < 400.0));
692
    }
693
694
    #[test]
695
    fn a_clusters_marks_spread_all_the_way_round() {
696
        let repos = vec![Repo { name: "doomsdayone/rstar-api".into() }];
697
        let events: Vec<Event> = (0..200).map(|_| Event { repo: 0, kind: Kind::Issue, age_days: 1.0, n: 1 }).collect();
698
        let s = Sky::new(&repos, &events, 1600.0, 900.0, true);
699
        // Every eighth of the circle holds a fair share of the marks.
700
        let mut octants = [0u32; 8];
701
        for m in s.marks.iter().filter(|m| m.kind == Kind::Issue) {
702
            octants[((m.angle / TAU * 8.0) as usize).min(7)] += 1;
703
        }
704
        assert!(octants.iter().all(|&n| (12..=40).contains(&n)), "{octants:?}");
705
    }
706
707
    #[test]
708
    fn one_repository_sits_in_the_wider_margin() {
709
        let repos = vec![Repo { name: "andy/demo".into() }];
710
        let mut s = Sky::new(&repos, &[], 1400.0, 900.0, false);
711
        s.resize(1400.0, 900.0, Some((127.0, 1259.0)));
712
        let (x, y) = s.core(0);
713
        assert!((x - (1259.0 + 141.0 / 2.0)).abs() < 8.0 && (y - 540.0).abs() < 8.0, "{x} {y}");
714
    }
715
716
    #[test]
717
    fn an_arrival_joins_its_cluster_with_one_ring() {
718
        let mut s = sky(false);
719
        let before = s.marks.iter().filter(|m| m.cluster == 1).count();
720
        s.arrive("andy/oxygen", Kind::Push, 2);
721
        s.arrive("someone/else", Kind::Issue, 1);
722
        let marks: Vec<&Mark> = s.marks.iter().filter(|m| m.cluster == 1).collect();
723
        assert_eq!(marks.len(), before + 2, "a dot for each change pushed; an unknown repository adds nothing");
724
        let newest: Vec<&&Mark> = marks.iter().filter(|m| m.kind == Kind::Push).collect();
725
        assert!(newest.iter().all(|m| m.order < 2 && m.bright == 1.0), "the newest, at full brightness");
726
        assert!(marks.iter().any(|m| m.kind == Kind::Release && m.order == 2), "older marks move back");
727
        assert_eq!(s.rings.len(), 1);
728
        assert!(s.busy(), "a ring is drawn while it widens");
729
        let colours = Colours { lit: [0.0, 0.4, 0.9, 0.7], ..Default::default() };
730
        let mut inst = Vec::new();
731
        s.instances(&colours, &mut inst);
732
        assert_eq!(inst.len(), (s.marks.len() + 1) * 8, "the ring is one more instance");
733
        for _ in 0..80 {
734
            s.step(1.0 / 60.0);
735
        }
736
        assert!(s.rings.is_empty() && !s.busy(), "gone after 1.2 s, and nothing left to draw but the drift");
737
        // A still sky takes the marks without the ring.
738
        let mut still = sky(true);
739
        still.arrive("andy/hub", Kind::Release, 1);
740
        assert!(still.rings.is_empty());
741
        assert_eq!(still.marks.iter().filter(|m| m.kind == Kind::Release).count(), 2);
742
    }
743
744
    #[test]
745
    fn computed_colours_parse() {
746
        assert_eq!(parse_colour("rgb(9, 105, 218)"), Some([9.0 / 255.0, 105.0 / 255.0, 218.0 / 255.0, 1.0]));
747
        assert_eq!(parse_colour("rgba(0, 240, 255, 0.75)").map(|c| c[3]), Some(0.75));
748
        assert_eq!(parse_colour("color(srgb 0 0.5 1 / 0.2)"), Some([0.0, 0.5, 1.0, 0.2]));
749
        assert_eq!(parse_colour("rgb(1 2 3 / 0.5)").map(|c| c[3]), Some(0.5));
750
        assert!(parse_colour("transparent").is_none());
751
    }
752
}