1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
// SPDX-FileCopyrightText: Copyright (c) 2026 Mike Li/Mikewolfli/Wei Li(mikewolfli@163.com)
// SPDX-License-Identifier: MIT
//! SkeletonLoader widget — animated placeholder content while data loads.
//!
//! The SkeletonLoader renders a gray rounded-rect placeholder with a shimmer
//! pulse effect that oscillates the fill opacity between ~0.1 and ~0.3,
//! providing clear visual feedback that data is still loading.
//!
//! Supported shapes:
//! - `Rect(w, h)` — rectangular block
//! - `Circle(r)` — circular avatar/image placeholder
//! - `TextLine(w)` — three stacked text line placeholders
use crate::compat::{vec, RefCell, Vec};
use crate::core::{Color, Point, Rect, Size};
use crate::event::{Event, EventHandler};
use crate::render::{RenderCommand, RenderContext};
use crate::style::Gradient;
use crate::widget::capability::coercion::{expect_bool, expect_string, expect_u32};
use crate::widget::capability::properties_trait::{base_property_get, base_property_set};
use crate::widget::capability::types::{CapabilityAccessError, CapabilityValue};
use crate::widget::capability::WidgetProperties;
use crate::widget::metrics::{dimensions, ControlMetrics};
use crate::widget::{BaseWidget, Draw, Widget, WidgetKind};
use crate::{impl_widget_property_hooks, property_names_of};
/// Shape variants for the skeleton placeholder.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum SkeletonShape {
/// Rectangular placeholder (width, height).
Rect(u32, u32),
/// Circular placeholder (radius).
Circle(u32),
/// Single text line placeholder (width).
TextLine(u32),
}
/// The string spelling of a [`SkeletonShape`] discriminant, published by the
/// `shape` property.
///
/// The `Rect`/`Circle`/`TextLine` payloads are deliberately left out: the
/// property names the *kind* of placeholder, matching the token style the other
/// enum properties use.
pub fn skeleton_shape_to_str(shape: SkeletonShape) -> &'static str {
match shape {
SkeletonShape::Rect(..) => "rect",
SkeletonShape::Circle(..) => "circle",
SkeletonShape::TextLine(..) => "text_line",
}
}
/// Parses the [`skeleton_shape_to_str`] token back into a shape.
///
/// A `Rect` without dimensions is not representable, so the parse accepts only
/// the tokens that name a bare kind and rebuilds the default sizes for them.
fn expect_skeleton_shape(value: CapabilityValue) -> Result<SkeletonShape, CapabilityAccessError> {
match expect_string(value)?.as_str() {
"rect" => Ok(SkeletonShape::Rect(200, 20)),
"circle" => Ok(SkeletonShape::Circle(20)),
"text_line" => Ok(SkeletonShape::TextLine(200)),
_ => Err(CapabilityAccessError::TypeMismatch),
}
}
/// Timer ID used to drive the shimmer animation.
const SKELETON_ANIMATION_TIMER_ID: u32 = 0x534B;
/// How long one full shimmer pulse takes, in milliseconds.
///
/// The pulse is a loop, so it is priced from the theme's `slow` token scaled up by
/// [`PULSE_SLOW_MULTIPLE`] — the same rule `progress_circle`'s revolution follows, because
/// both are "an indefinite wait, animated" and a theme that slows everything down should
/// slow them together. The literal is the no-theme fallback.
const DEFAULT_PULSE_PERIOD_MS: u32 = 1200;
/// How many `slow` tokens one shimmer pulse is worth.
const PULSE_SLOW_MULTIPLE: u32 = 4;
/// The number of straight edges used to approximate one rounded corner of a
/// clip outline. Eight is enough for the 3–4 px radii a skeleton uses.
const SHIMMER_CORNER_STEPS: u32 = 8;
/// The number of straight edges used to approximate a circular clip outline.
const SHIMMER_CIRCLE_STEPS: u32 = 32;
/// The peak alpha of the shimmer band, out of 255.
const SHIMMER_PEAK_ALPHA: f32 = 140.0;
/// SkeletonLoader widget — renders a shimmering placeholder shape while data loads.
pub struct SkeletonLoader {
base: BaseWidget,
shape: SkeletonShape,
animated: bool,
/// Whether a highlight band sweeps across the placeholder shapes.
///
/// Off by default because the band is an extra visual treatment layered on
/// top of the pulse, and the historic picture must stay byte-identical for
/// callers that never asked for it.
shimmer: bool,
/// The shimmer's phase, in turns: `0.0` and `1.0` are the same point in the pulse.
///
/// # Why this is a phase and not a frame counter
///
/// The pulse used to advance one step per `Event::Timer`, which made its *rate* a
/// property of how often the host happened to send that event: the same placeholder
/// pulsed at one speed on a 60 Hz host and twice as fast on a 120 Hz one, and it sat
/// outside the animation bus entirely. A pulse is a duration, so it is driven by
/// [`SkeletonLoader::tick`] from `delta_ms` — the same contract every other animation in
/// the crate uses (BLUE23 \u00a73).
phase: f32,
/// How many stacked rows a [`SkeletonShape::TextLine`] placeholder draws.
///
/// Three is the historical picture; a caller laying out a longer paragraph can ask for
/// more. `Rect` and `Circle` ignore it.
text_line_rows: u32,
/// The fill boxes and clip outlines the shimmer lights up, keyed by the shape and rectangle
/// that produced them.
///
/// The geometry depends on the placeholder shape and the control's rectangle, not on the
/// pulse phase, so rebuilding it every frame was pure waste: `paint_shimmer` re-sampled every
/// rounded corner and circle outline per frame. A `RefCell` because the paint path reads it
/// through `&self`, exactly as the draw trait requires.
shimmer_geometry: RefCell<Option<ShimmerGeometryCache>>,
}
/// Cached shimmer geometry for one `(shape, rectangle, rows)` triple.
struct ShimmerGeometryCache {
shape: SkeletonShape,
rect: Rect,
text_line_rows: u32,
regions: Vec<(Rect, Vec<Point>)>,
}
impl SkeletonLoader {
/// Creates a new SkeletonLoader with the given geometry.
///
/// The default shape is a 200×20 `Rect` and the shimmer animation is enabled
/// by default.
pub fn new(geometry: Rect) -> Self {
Self {
base: BaseWidget::new(WidgetKind::SkeletonLoader, geometry, "SkeletonLoader"),
shape: SkeletonShape::Rect(200, 20),
animated: true,
shimmer: false,
phase: 0.0,
text_line_rows: 3,
shimmer_geometry: RefCell::new(None),
}
}
/// Sets the skeleton placeholder shape.
/// Sets the placeholder's shape, and repaints.
///
/// The shape drives the geometry the draw path emits (a line, a circle or a rectangle), so a
/// silent change would leave the previous shape on screen.
pub fn set_shape(&mut self, shape: SkeletonShape) {
if self.shape == shape {
return;
}
self.shape = shape;
*self.shimmer_geometry.borrow_mut() = None;
self.base.request_redraw();
}
/// Returns the current skeleton placeholder shape.
pub fn shape(&self) -> SkeletonShape {
self.shape
}
/// Enables or disables the shimmer animation.
///
/// When disabled the placeholder draws at a static mid-opacity of 0.2. A same-value write is
/// a no-op; a real change requests a repaint, so the still picture appears on the next frame
/// rather than whenever some unrelated event happens to repaint the control.
pub fn set_animated(&mut self, animated: bool) {
if self.animated == animated {
return;
}
self.animated = animated;
self.base.request_redraw();
}
/// Returns whether the shimmer animation is enabled.
pub fn is_animated(&self) -> bool {
self.animated
}
/// Returns whether the sweeping highlight band is enabled.
pub fn shimmer(&self) -> bool {
self.shimmer
}
/// How many stacked rows a `TextLine` placeholder draws. Defaults to three.
pub fn text_line_rows(&self) -> u32 {
self.text_line_rows
}
/// Sets how many stacked rows a `TextLine` placeholder draws.
///
/// The draw path and the shimmer geometry derive their row count from this one field, so the
/// two cannot disagree. One row is the minimum: a zero-row paragraph would be an invisible
/// placeholder. `Rect` and `Circle` are unaffected.
pub fn set_text_line_rows(&mut self, rows: u32) {
let rows = rows.max(1);
if self.text_line_rows == rows {
return;
}
self.text_line_rows = rows;
// The cached shimmer geometry contains one region per row; the next paint rebuilds it.
*self.shimmer_geometry.borrow_mut() = None;
self.base.request_redraw();
}
/// Enables or disables the sweeping highlight band.
///
/// The band is driven by the existing pulse phase, so enabling it does not
/// add a second clock: the highlight travels once per pulse period. The
/// default is `false`, which leaves the rendering untouched.
pub fn set_shimmer(&mut self, enabled: bool) {
if self.shimmer == enabled {
return;
}
self.shimmer = enabled;
self.base.request_redraw();
}
/// Computes the current shimmer opacity from the pulse phase.
///
/// A triangle wave over the phase: `0.0` and `1.0` are the dimmest point, `0.5` the
/// brightest. A disabled animation returns the static mid-point, which is also the wave's
/// own mean — so switching the animation off dims the shimmer to its average brightness
/// rather than jumping to one extreme.
fn current_opacity(&self) -> f32 {
if !self.animated {
return 0.2;
}
// `1 - |2p - 1|` is the triangle: 0 at both ends, 1 at the middle.
let triangle = 1.0 - (2.0 * self.phase - 1.0).abs();
0.1 + 0.2 * triangle
}
/// Advances the shimmer by `delta_ms` and reports whether another frame is owed.
///
/// Only the animated state owes frames: a static placeholder is drawn once, so it must
/// not keep the frame bus alive (\u00a73.2).
pub fn tick(&mut self, delta_ms: u32) -> bool {
if !self.animated {
return false;
}
// Wrapped rather than clamped, so a long-running app cannot drift into a large value
// and lose float precision on the phase.
self.phase = (self.phase + delta_ms as f32 / self.pulse_period_ms() as f32).fract();
self.request_frame_repaint(Some(self.damage_bounds()));
true
}
/// Submits one animated frame as damage bounded by the painted box plus the margin.
///
/// A control that is unmounted falls back to [`BaseWidget::request_redraw`], keeping the
/// redraw signal contract for host-owned controls. `bounds` is supplied by [`Self::tick`],
/// because the animation sweep calls `tick` while it holds the widget registry: passing the
/// rectangle keeps that path from asking the runtime to read the geometry back, which would
/// re-enter the held borrow. A tick frame therefore keeps the base signal in
/// [`crate::widget::runtime::RepaintMode::Full`], exactly as `arc` and `progress_circle` do.
fn request_frame_repaint(&self, bounds: Option<Rect>) {
let _ = bounds;
#[cfg(not(alloc_frugal))]
{
if let Some(id) = crate::widget::runtime::registry_id_of(self.id()) {
let narrow = crate::widget::runtime::repaint_mode(id)
!= crate::widget::runtime::RepaintMode::Full;
if narrow || bounds.is_none() {
let damage = bounds
.or_else(|| crate::widget::runtime::painted_box_with_damage_margin(id))
.unwrap_or_else(|| self.damage_bounds());
crate::widget::runtime::request_repaint_rect(id, damage);
// The replaced `request_redraw` emitted this signal; keep it.
self.base.redraw_requested.emit();
return;
}
}
}
self.base.request_redraw();
}
/// This control's own rectangle grown by the shared damage margin.
fn damage_bounds(&self) -> Rect {
let rect = self.geometry();
let margin = crate::widget::metrics::DAMAGE_MARGIN;
let offset = margin as i32;
Rect::new(
rect.x.saturating_sub(offset),
rect.y.saturating_sub(offset),
rect.width.saturating_add(margin).saturating_add(margin),
rect.height.saturating_add(margin).saturating_add(margin),
)
}
/// The duration of one full pulse, priced by the theme.
fn pulse_period_ms(&self) -> u32 {
let slow = crate::style::motion_tokens().2;
if slow == 0 {
DEFAULT_PULSE_PERIOD_MS
} else {
slow.saturating_mul(PULSE_SLOW_MULTIPLE).max(1)
}
}
}
impl Widget for SkeletonLoader {
fn base(&self) -> &BaseWidget {
&self.base
}
fn set_state_theme_hook(&mut self) {
crate::style::reapply_active_theme_state(self);
}
fn base_mut(&mut self) -> &mut BaseWidget {
&mut self.base
}
fn size_hint(&self) -> crate::core::Size {
crate::core::Size::new(
crate::widget::metrics::dimensions::SKELETON_DEFAULT_WIDTH,
crate::widget::metrics::dimensions::SKELETON_ROW_HEIGHT,
)
}
/// One frame of the shimmer. The frame bus calls this; nothing else does.
fn tick(&mut self, delta_ms: u32) -> bool {
SkeletonLoader::tick(self, delta_ms)
}
/// Only a shimmering placeholder owes frames; a static one is a still picture.
fn is_animating(&self) -> bool {
self.animated
}
impl_draw_bridge!();
impl_widget_property_hooks!();
}
/// `SkeletonLoader`'s property contract.
///
/// Read/write semantics are carried over unchanged from the centralised
/// `access_read_other.in.rs` / `access_write_other.in.rs` dispatch, so callers see
/// the same coercions and the same errors as before. The legacy table spelled the
/// animation flag `active`, which is kept as the published name and maps onto
/// [`SkeletonLoader::is_animated`]; `shape` is published alongside it so the
/// placeholder kind is describable too.
impl WidgetProperties for SkeletonLoader {
fn get(&self, name: &str) -> Result<CapabilityValue, CapabilityAccessError> {
match name {
"active" => Ok(CapabilityValue::Bool(self.is_animated())),
"shape" => Ok(CapabilityValue::String(skeleton_shape_to_str(self.shape()).to_string())),
"text_line_rows" => Ok(CapabilityValue::UInt(u64::from(self.text_line_rows()))),
_ => base_property_get(self, name),
}
}
fn set(&mut self, name: &str, value: CapabilityValue) -> Result<(), CapabilityAccessError> {
match name {
"active" => {
self.set_animated(expect_bool(value)?);
Ok(())
}
"shape" => {
self.set_shape(expect_skeleton_shape(value)?);
Ok(())
}
"text_line_rows" => {
self.set_text_line_rows(expect_u32(value)?);
Ok(())
}
_ => base_property_set(self, name, value),
}
}
fn property_names(&self) -> &'static [&'static str] {
property_names_of!["active", "shape", "text_line_rows", BASE_PROPERTY_NAMES]
}
/// Runs one of the commands `skeleton_loader` publishes.
///
/// `set_active` is the only published name and it assigns the animation flag,
/// which a command cannot carry, so it is refused as
/// [`CapabilityAccessError::OutOfRange`] — the name is right, the boolean belongs
/// on the property route `set("active", ..)` — rather than reported unknown.
fn command(&mut self, name: &str) -> Result<(), CapabilityAccessError> {
match name {
"set_active" => Err(CapabilityAccessError::OutOfRange),
_ => Err(CapabilityAccessError::UnknownCommand),
}
}
}
impl Draw for SkeletonLoader {
fn draw(&mut self, context: &mut RenderContext) {
let rect = self.geometry();
// Chrome colours resolve the explicit style first, then the theme's resolved style
// for this control, and only then the original literal. The literal stays as the
// fallback so an inactive theme still has a defined appearance. Previously the RGB
// was a literal grey, so the placeholder shimmered the same in light and dark and the
// rendering census reported the control as theme-blind.
//
// `resolved_theme_style` takes and releases the global manager's lock internally, so
// no guard is held across the draw (the mutex is not re-entrant).
let style = self.base.style();
let themed = crate::style::resolved_theme_style_shared("skeleton_loader");
let themed_bg = themed.as_ref().and_then(|r| r.background_color);
let themed_text = themed.as_ref().and_then(|r| r.text_color);
// The resolved surface, re-derived one visible step towards the theme's ink: the
// placeholder's whole job is to be *seen* against the surface it sits on, so painting
// it in that exact surface colour would defeat it.
let surface = style.background_color.or(themed_bg).unwrap_or(Color::WHITE);
let ink = style.text_color.or(themed_text).unwrap_or(Color::rgb(200, 200, 200));
let skeleton = surface.blend(&ink, 0.35);
let opacity = self.current_opacity();
// Only the RGB comes from the resolved colour: the alpha below is the shimmer
// animation's own modulation and is deliberately left exactly as it was.
let base_color =
Color::rgba(skeleton.r, skeleton.g, skeleton.b, (opacity * 255.0).round() as u8);
self.paint_shape(context, base_color);
if self.shimmer {
self.paint_shimmer(context, rect);
}
}
}
impl SkeletonLoader {
/// Paints the configured shape once in `color`.
///
/// Factored out of [`Draw::draw`] so the shimmer band can repaint the same
/// geometry inside a clip: an overlay that re-paints the shape rather than
/// a rectangle stays inside a disc or a rounded row, which a rectangular
/// gradient fill would not.
fn paint_shape(&self, context: &mut RenderContext, color: Color) {
let rect = self.geometry();
let cx = rect.x + rect.width as i32 / 2;
let cy = rect.y + rect.height as i32 / 2;
match self.shape {
SkeletonShape::Rect(w, h) => {
// The caller's own dimensions are the **datum** here: a skeleton stands in
// for a specific piece of content, so its width and height are the shape
// the caller asked for. They are still clamped to the rectangle, because
// an oversized placeholder would paint outside the area nothing clips it
// to — which is what `ControlMetrics::center_in` guarantees, and it is
// also what keeps a zero-size placeholder from being emitted.
let w = w.min(rect.width).max(1);
let h = h.min(rect.height).max(1);
let shape_rect = ControlMetrics::center_in(rect, crate::core::Size::new(w, h));
context.fill_rounded_rect(shape_rect, 4, color);
}
SkeletonShape::Circle(r) => {
// The radius is the caller's datum, clamped to the shortest side so the
// disc stays square and inside the control.
let r = r.min(rect.width.min(rect.height) / 2).max(1);
let center = Point::new(cx, cy);
context.fill_circle_aa(center, r, color);
}
SkeletonShape::TextLine(w) => {
// Draw stacked text-like lines to simulate paragraph text.
//
// The rows are a **fixed** height and gap, so the placeholder is
// `rows * row + (rows - 1) * gap` tall in any rectangle. Every term used to be a
// local literal, which is why the census cell drew a 12 px line in a
// 120 px box: the stack was the only fixed part of a control whose box
// was otherwise the caller's, so the same skeleton was a different
// object at every size. `SKELETON_ROW_HEIGHT` and `SKELETON_ROW_GAP`
// name the two values the caller can now predict from the shape.
let line_h = dimensions::SKELETON_ROW_HEIGHT;
let gap = dimensions::SKELETON_ROW_GAP;
let rows = self.text_line_rows.max(1);
let total_h = rows * line_h + rows.saturating_sub(1) * gap;
let start_y = cy - total_h as i32 / 2;
// A row is the caller's width clamped to the control, and never zero: an
// over-wide row would paint past the rectangle and a zero-width one would
// be an invisible element.
let row_w = w.clamp(1, rect.width.max(1));
for i in 0..rows {
let y = start_y + i as i32 * (line_h + gap) as i32;
let line_rect = Rect::new(cx - row_w as i32 / 2, y, row_w, line_h);
context.fill_rounded_rect(line_rect, 3, color);
}
}
}
}
/// Paints the moving highlight band over the placeholder shapes.
///
/// The band's position is read from the same [`SkeletonLoader::phase`] the
/// pulse uses, so enabling it adds no clock. One period moves the band from
/// just before the control's left edge to just past its right edge.
///
/// # One gradient pass, not one strip per shape
///
/// The band used to be six vertical strips, and every strip replayed the
/// whole [`Self::paint_shape`] geometry inside its own clip: the shape was
/// rasterised six times per frame and each strip had a hard step at its
/// boundary. It is now a single linear-gradient paint (transparent → peak →
/// transparent across the band) clipped to the shape's own outline once, so
/// a frame costs one gradient fill per painted shape part instead of six
/// shape replays. The outline clip is what keeps the highlight inside a disc
/// or a rounded row rather than lighting the bounding box.
fn paint_shimmer(&self, context: &mut RenderContext, rect: Rect) {
if rect.width == 0 || rect.height == 0 {
return;
}
let band_width = (rect.width / 3).max(1);
let travel = rect.width as f32 + band_width as f32;
let band_left = rect.x as f32 - band_width as f32 + self.phase * travel;
// The gradient is defined in the parent's pixel coordinates. A path clip
// executed directly on the context bypasses the translation offset, so the
// offset is applied to both the ramp and the outline here rather than
// letting one of the two drift inside a translated container.
let (dx, dy) = context.offset();
let gradient = Gradient::linear(
Point::new(band_left as i32 + dx, rect.y + dy),
Point::new((band_left + band_width as f32) as i32 + dx, rect.y + dy),
)
.add_stop(0.0, Color::rgba(255, 255, 255, 0))
.add_stop(0.5, Color::rgba(255, 255, 255, SHIMMER_PEAK_ALPHA.round() as u8))
.add_stop(1.0, Color::rgba(255, 255, 255, 0));
for (fill, outline) in self.ensure_shimmer_regions(rect).iter() {
if fill.x >= rect.x + rect.width as i32 || fill.x + fill.width as i32 <= rect.x {
continue;
}
let points: Vec<Point> =
outline.iter().map(|point| Point::new(point.x + dx, point.y + dy)).collect();
context.execute_command(RenderCommand::ClipPath { points: points.into() });
context.fill_gradient(*fill, &gradient);
context.pop_clip();
}
}
/// Returns the shimmer geometry, rebuilding it only when the shape or rectangle changed.
///
/// The outline point lists are the expensive part (a rounded corner is sampled in eight
/// steps per corner, a circle in thirty-two), and they do not depend on the pulse phase. The
/// cache therefore turns a per-frame re-sampling into a reference count bump.
fn ensure_shimmer_regions(&self, rect: Rect) -> core::cell::Ref<'_, [(Rect, Vec<Point>)]> {
let fresh = self.shimmer_geometry.borrow().as_ref().is_some_and(|cache| {
cache.shape == self.shape
&& cache.rect == rect
&& cache.text_line_rows == self.text_line_rows
});
if !fresh {
let regions = self.build_shimmer_regions(rect);
*self.shimmer_geometry.borrow_mut() = Some(ShimmerGeometryCache {
shape: self.shape,
rect,
text_line_rows: self.text_line_rows,
regions,
});
}
core::cell::Ref::map(self.shimmer_geometry.borrow(), |cache| {
cache.as_ref().map(|cache| cache.regions.as_slice()).unwrap_or(&[])
})
}
/// The geometry the highlight lights up, as `(fill box, outline)` pairs.
///
/// One pair for a rectangle or a disc and one per row for a text line, so the
/// gaps between stacked rows stay dark. The outline is in local coordinates;
/// [`Self::paint_shimmer`] translates it by the context offset before use.
fn build_shimmer_regions(&self, rect: Rect) -> Vec<(Rect, Vec<Point>)> {
let cx = rect.x + rect.width as i32 / 2;
let cy = rect.y + rect.height as i32 / 2;
match self.shape {
SkeletonShape::Rect(w, h) => {
let w = w.min(rect.width).max(1);
let h = h.min(rect.height).max(1);
let shape = ControlMetrics::center_in(rect, Size::new(w, h));
vec![(shape, rounded_rect_outline(shape, 4))]
}
SkeletonShape::Circle(r) => {
let r = r.min(rect.width.min(rect.height) / 2).max(1);
let box_rect = Rect::new(
cx - r as i32,
cy - r as i32,
r.saturating_mul(2),
r.saturating_mul(2),
);
vec![(box_rect, circle_outline(Point::new(cx, cy), r))]
}
SkeletonShape::TextLine(w) => {
let line_h = dimensions::SKELETON_ROW_HEIGHT;
let gap = dimensions::SKELETON_ROW_GAP;
let rows = self.text_line_rows.max(1);
let total_h = rows * line_h + rows.saturating_sub(1) * gap;
let start_y = cy - total_h as i32 / 2;
let row_w = w.clamp(1, rect.width.max(1));
(0..rows)
.map(|i| {
let y = start_y + i as i32 * (line_h + gap) as i32;
let row = Rect::new(cx - row_w as i32 / 2, y, row_w, line_h);
(row, rounded_rect_outline(row, 3))
})
.collect()
}
}
}
}
/// Builds a closed polygon approximating a rounded rectangle.
fn rounded_rect_outline(rect: Rect, radius: u32) -> Vec<Point> {
let r = radius.min(rect.width / 2).min(rect.height / 2) as f32;
let x0 = rect.x as f32;
let y0 = rect.y as f32;
let x1 = (rect.x + rect.width as i32) as f32;
let y1 = (rect.y + rect.height as i32) as f32;
let corners = [
(x1 - r, y0 + r, -core::f32::consts::FRAC_PI_2, 0.0),
(x1 - r, y1 - r, 0.0, core::f32::consts::FRAC_PI_2),
(x0 + r, y1 - r, core::f32::consts::FRAC_PI_2, core::f32::consts::PI),
(x0 + r, y0 + r, core::f32::consts::PI, 3.0 * core::f32::consts::FRAC_PI_2),
];
let mut points = Vec::with_capacity(corners.len() * (SHIMMER_CORNER_STEPS as usize + 1));
for (cx, cy, start, end) in corners {
for step in 0..=SHIMMER_CORNER_STEPS {
let angle = start + (end - start) * step as f32 / SHIMMER_CORNER_STEPS as f32;
points.push(Point::new((cx + r * angle.cos()) as i32, (cy + r * angle.sin()) as i32));
}
}
points
}
/// Builds a closed polygon approximating a circle.
fn circle_outline(center: Point, radius: u32) -> Vec<Point> {
let r = radius as f32;
(0..SHIMMER_CIRCLE_STEPS)
.map(|step| {
let angle = core::f32::consts::TAU * step as f32 / SHIMMER_CIRCLE_STEPS as f32;
Point::new(center.x + (r * angle.cos()) as i32, center.y + (r * angle.sin()) as i32)
})
.collect()
}
impl EventHandler for SkeletonLoader {
fn handle_event(&mut self, event: &Event) {
// A disabled control consumes nothing, so the base state stays authoritative.
if !self.base.is_enabled() {
return;
}
self.base.handle_event(event);
// The legacy timer still advances the pulse, at a nominal frame's worth of time, so a
// host that has not moved to the frame bus sees the shimmer it always did. It is a
// fallback, not the driver: the pulse's *rate* now comes from the theme rather than
// from how often this event arrives.
if let Event::Timer { id } = event {
if *id == SKELETON_ANIMATION_TIMER_ID && self.animated {
self.tick(16);
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::widget::svg::render_to_svg;
#[test]
fn skeleton_loader_default_creation() {
let sl = SkeletonLoader::new(Rect::new(0, 0, 200, 100));
assert_eq!(sl.kind(), WidgetKind::SkeletonLoader);
assert_eq!(sl.geometry(), Rect::new(0, 0, 200, 100));
assert_eq!(sl.shape(), SkeletonShape::Rect(200, 20));
assert!(sl.is_animated());
}
#[test]
fn skeleton_loader_rect_shape() {
let mut sl = SkeletonLoader::new(Rect::new(0, 0, 200, 100));
sl.set_shape(SkeletonShape::Rect(100, 50));
assert_eq!(sl.shape(), SkeletonShape::Rect(100, 50));
}
#[test]
fn skeleton_loader_circle_shape() {
let mut sl = SkeletonLoader::new(Rect::new(0, 0, 200, 100));
sl.set_shape(SkeletonShape::Circle(30));
assert_eq!(sl.shape(), SkeletonShape::Circle(30));
}
#[test]
fn skeleton_loader_text_line_shape() {
let mut sl = SkeletonLoader::new(Rect::new(0, 0, 200, 100));
sl.set_shape(SkeletonShape::TextLine(150));
assert_eq!(sl.shape(), SkeletonShape::TextLine(150));
}
/// The shimmer oscillates between its two ends, and its rate is a *duration* — not a frame
/// count.
///
/// Regression: the pulse advanced one step per `Event::Timer`, so its rate depended on how
/// often the host sent that event and it stood outside the frame bus. It is now driven by
/// `tick(delta_ms)` from the theme's `slow` token, so the same control pulses at the same
/// rate on any host. The legacy timer still nudges it, which is why the event path is
/// exercised here as well.
#[test]
fn skeleton_loader_pulses_over_time_and_holds_still_when_static() {
let mut sl = SkeletonLoader::new(Rect::new(0, 0, 200, 100));
assert!(sl.is_animated());
// Collect opacities across one full period, stepping in tenths of the period.
let period = sl.pulse_period_ms();
let at_rest = sl.current_opacity();
let opacities: Vec<f32> = (0..10)
.map(|_| {
assert!(sl.tick(period / 10), "an animated pulse owes another frame");
sl.current_opacity()
})
.collect();
// Both ends of the range are reached, so the pulse reads as a shimmer and not a wobble.
let min_op = opacities.iter().cloned().fold(f32::MAX, f32::min);
let max_op = opacities.iter().cloned().fold(f32::MIN, f32::max);
assert!(min_op < 0.15, "minimum opacity should be near 0.1, got {min_op}");
assert!(max_op > 0.25, "maximum opacity should be near 0.3, got {max_op}");
// Ten steps of a tenth of a period is exactly one turn, so the pulse is back where it
// started: the phase is a loop, not a counter that grows without bound.
assert!(
(sl.current_opacity() - at_rest).abs() < 0.02,
"one period returns to the start: {} vs {at_rest}",
sl.current_opacity()
);
// Disabling the animation freezes it at the wave's mean and stops it owing frames.
sl.set_animated(false);
assert!(!sl.is_animated());
let static_op = sl.current_opacity();
assert!((static_op - 0.2).abs() < 0.01, "static opacity should be 0.2, got {static_op}");
assert!(!sl.tick(period), "a static placeholder must not request another frame");
// The legacy timer path still advances the pulse for a host that has not migrated.
sl.set_animated(true);
let before = sl.current_opacity();
sl.handle_event(&Event::Timer { id: SKELETON_ANIMATION_TIMER_ID });
assert_ne!(sl.current_opacity(), before, "the legacy timer still nudges the pulse");
}
#[test]
fn skeleton_loader_svg_output() {
let mut sl = SkeletonLoader::new(Rect::new(0, 0, 200, 100));
let svg = render_to_svg(&mut sl);
assert!(svg.starts_with("<svg"));
assert!(svg.contains("width=\"200\""));
assert!(svg.contains("height=\"100\""));
}
#[test]
fn skeleton_loader_set_animated_flag() {
let mut sl = SkeletonLoader::new(Rect::new(0, 0, 200, 100));
assert!(sl.is_animated());
sl.set_animated(false);
assert!(!sl.is_animated());
sl.set_animated(true);
assert!(sl.is_animated());
}
/// Turning the animation off repaints the control and a same-value write is a no-op.
///
/// Regression: `set_animated` wrote the flag and returned, so switching a running shimmer
/// off left the last animated frame on screen instead of the documented static 0.2 picture.
#[test]
fn setting_animated_requests_a_redraw_and_ignores_a_same_value_write() {
let mut sl = SkeletonLoader::new(Rect::new(0, 0, 200, 100));
let fired = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
{
let f = std::sync::Arc::clone(&fired);
let scope = sl.connection_scope();
sl.redraw_requested_signal().connect_scoped(scope, move || {
f.store(true, std::sync::atomic::Ordering::SeqCst);
});
}
// Writing the value it already holds must not ask for a frame.
sl.set_animated(true);
assert!(!fired.load(std::sync::atomic::Ordering::SeqCst), "same value is a no-op");
sl.set_animated(false);
assert!(
fired.load(std::sync::atomic::Ordering::SeqCst),
"switching the animation off must repaint the static frame"
);
}
/// A `TextLine` placeholder draws the configured number of rows, and the shimmer geometry
/// follows the same field.
#[test]
fn the_text_line_row_count_is_configurable() {
let mut sl = SkeletonLoader::new(Rect::new(0, 0, 240, 200));
sl.set_shape(SkeletonShape::TextLine(180));
sl.set_animated(false);
assert_eq!(sl.text_line_rows(), 3, "three rows is the historical picture");
sl.set_text_line_rows(5);
assert_eq!(sl.text_line_rows(), 5);
let svg = render_to_svg(&mut sl);
assert_eq!(
svg.matches(&format!("height=\"{}\"", dimensions::SKELETON_ROW_HEIGHT)).count(),
5,
"five rows at SKELETON_ROW_HEIGHT: {svg}"
);
// The shimmer's region list is derived from the same field, one region per row.
let regions = sl.ensure_shimmer_regions(sl.geometry());
assert_eq!(regions.len(), 5);
}
/// The shimmer outline geometry is sampled once and reused until the shape or rectangle moves.
#[test]
fn shimmer_geometry_is_cached_until_the_shape_or_rectangle_changes() {
let mut sl = SkeletonLoader::new(Rect::new(0, 0, 200, 100));
sl.set_shape(SkeletonShape::TextLine(180));
{
let first = sl.ensure_shimmer_regions(sl.geometry());
assert_eq!(first.len(), 3);
}
let first_ptr = {
let regions = sl.ensure_shimmer_regions(sl.geometry());
regions.as_ptr()
};
let second_ptr = {
let regions = sl.ensure_shimmer_regions(sl.geometry());
regions.as_ptr()
};
assert_eq!(first_ptr, second_ptr, "an unchanged shape reuses the cached outlines");
sl.set_text_line_rows(2);
let regions = sl.ensure_shimmer_regions(sl.geometry());
assert_eq!(regions.len(), 2, "changing the row count invalidates the cache");
}
/// A `TextLine` skeleton is a fixed stack of rows, not a fraction of the control.
///
/// This pins the defect the fix removes: the row height and gap were local literals
/// and the rows were the only fixed part of a control whose box was otherwise the
/// caller's, so a skeleton in a 100 px slot and one in a census cell were laid out
/// against different arithmetic. The stack is now
/// `3 * SKELETON_ROW_HEIGHT + 2 * SKELETON_ROW_GAP` tall in any rectangle, which is
/// the one thing a caller can predict from the shape.
#[test]
fn a_text_line_skeleton_stacks_fixed_rows() {
// Holds the crate-wide theme guard: this test renders, and a concurrent
// test that switches the appearance would otherwise change a later frame.
let _theme_guard = crate::style::theme_test_guard();
let total = 3 * dimensions::SKELETON_ROW_HEIGHT + 2 * dimensions::SKELETON_ROW_GAP;
// The stack cannot outgrow the cell a control is measured in, or the census
// would be reporting a clipped placeholder rather than a drawn one.
assert!(total < 120, "the default stack is shorter than the census cell");
for rect in [Rect::new(0, 0, 240, 120), Rect::new(0, 0, 240, 300)] {
let mut sl = SkeletonLoader::new(rect);
sl.set_shape(SkeletonShape::TextLine(180));
sl.set_animated(false);
let svg = render_to_svg(&mut sl);
// Each of the three rows is emitted at the named height.
assert_eq!(
svg.matches(&format!("height=\"{}\"", dimensions::SKELETON_ROW_HEIGHT)).count(),
3,
"three rows at SKELETON_ROW_HEIGHT in {rect:?}: {svg}"
);
}
}
/// A `Rect` skeleton is the caller's size, clamped to the control rather than
/// painted outside it, and never zero-extent.
#[test]
fn a_rect_skeleton_is_clamped_to_its_control_and_never_empty() {
let mut oversized = SkeletonLoader::new(Rect::new(0, 0, 100, 40));
oversized.set_shape(SkeletonShape::Rect(500, 500));
oversized.set_animated(false);
let svg = render_to_svg(&mut oversized);
assert!(
svg.contains("height=\"40\""),
"an oversized placeholder clamps to the control: {svg}"
);
// A zero-size placeholder is still emitted at one pixel rather than not at all.
let mut empty = SkeletonLoader::new(Rect::new(0, 0, 100, 40));
empty.set_shape(SkeletonShape::Rect(0, 0));
empty.set_animated(false);
let svg = render_to_svg(&mut empty);
assert!(!svg.contains("width=\"0\""), "nothing is emitted zero-wide: {svg}");
assert!(!svg.contains("height=\"0\""), "nothing is emitted zero-tall: {svg}");
}
/// A `Circle` skeleton is a disc centred in the control, clamped to its short side.
#[test]
fn a_circle_skeleton_stays_square_and_inside() {
let mut sl = SkeletonLoader::new(Rect::new(0, 0, 60, 120));
sl.set_shape(SkeletonShape::Circle(200));
sl.set_animated(false);
// The disc is clamped to half the *shorter* side, so it cannot exceed the width.
let svg = render_to_svg(&mut sl);
assert!(!svg.contains("r=\"0\""), "a disc is never zero-radius: {svg}");
}
/// `set_shape` asks for a frame.
///
/// The shape decides the geometry the draw path emits (a line, a circle or a rectangle), so a
/// silent change left the previous placeholder on screen.
#[test]
fn setting_shape_requests_a_redraw() {
let mut s = SkeletonLoader::new(Rect::new(0, 0, 200, 20));
let fired = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
{
let f = std::sync::Arc::clone(&fired);
let scope = s.connection_scope();
s.redraw_requested_signal().connect_scoped(scope, move || {
f.store(true, std::sync::atomic::Ordering::SeqCst);
});
}
let other = if s.shape() == SkeletonShape::Rect(200, 20) {
SkeletonShape::Circle(12)
} else {
SkeletonShape::Rect(200, 20)
};
s.set_shape(other);
assert!(fired.load(std::sync::atomic::Ordering::SeqCst), "a new shape must be drawn");
}
/// The shimmer band is opt-in: the default picture is unchanged, and the
/// band moves with the existing pulse phase rather than a second clock.
#[test]
fn a_shimmer_band_is_opt_in_and_follows_the_pulse_phase() {
let mut plain = SkeletonLoader::new(Rect::new(0, 0, 200, 100));
plain.set_animated(false);
assert!(!plain.shimmer(), "the band is off by default");
let plain_svg = render_to_svg(&mut plain);
// The band starts just outside the left edge, so it is advanced to the
// quarter point before it is expected on screen.
let mut sl = SkeletonLoader::new(Rect::new(0, 0, 200, 100));
let period = sl.pulse_period_ms();
assert!(sl.tick(period / 4), "the pulse owes the frame that moves the band");
let without = render_to_svg(&mut sl);
sl.set_shimmer(true);
let with = render_to_svg(&mut sl);
assert_ne!(without, with, "enabling the band changes the picture");
assert_eq!(
with.matches("clip-path").count(),
1,
"the whole band is one gradient paint clipped to the shape"
);
// A further quarter turn moves the band, and the only clock involved
// is the pulse's own phase.
assert!(sl.tick(period / 4));
assert_ne!(with, render_to_svg(&mut sl), "the band advances with the pulse");
// Turning it back off leaves no band commands behind.
sl.set_shimmer(false);
let restored = render_to_svg(&mut sl);
assert!(!restored.contains("clip-path"), "a disabled band paints nothing: {restored}");
// A fresh, static placeholder is byte-identical to the old picture.
let mut fresh = SkeletonLoader::new(Rect::new(0, 0, 200, 100));
fresh.set_animated(false);
assert_eq!(render_to_svg(&mut fresh), plain_svg, "the default is unchanged");
}
/// Toggling the band asks for a frame, and toggling it to the same value
/// does not.
#[test]
fn setting_shimmer_requests_a_redraw() {
let mut sl = SkeletonLoader::new(Rect::new(0, 0, 200, 100));
let seen = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
sl.base.redraw_requested.connect({
let seen = std::sync::Arc::clone(&seen);
move || {
seen.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
}
});
sl.set_shimmer(true);
assert_eq!(seen.load(std::sync::atomic::Ordering::SeqCst), 1);
sl.set_shimmer(true);
assert_eq!(
seen.load(std::sync::atomic::Ordering::SeqCst),
1,
"the same value is not a change"
);
}
}