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
//! Spinner component for loading indicators
//!
//! A circular loading indicator: a faint track ring with a half-circle arc
//! turning on top. The arc's colour and its turn are `.cn-spinner__arc` rules
//! (`@keyframes cn-spinner-turn`); the track's colour is `.cn-spinner__track`.
//! A different speed is a rule of your own:
//!
//! ```css
//! .slow-spinner .cn-spinner__arc { animation-duration: 2000ms; }
//! ```
//!
//! # Example
//!
//! ```ignore
//! use blinc_cn::prelude::*;
//!
//! fn loading_view() -> impl ElementBuilder {
//! cn::spinner()
//! }
//!
//! // Customised
//! cn::spinner()
//! .size(SpinnerSize::Large)
//! .color(Color::BLUE)
//! .class("slow-spinner")
//! ```
use blinc_core::{ClipLength, ClipPath, Color};
use blinc_layout::InstanceKey;
use blinc_layout::div::{Div, ElementTypeId};
use blinc_layout::element::RenderProps;
use blinc_layout::prelude::*;
use blinc_layout::tree::{LayoutNodeId, LayoutTree};
use std::cell::{OnceCell, RefCell};
use std::sync::Arc;
use taffy::Style;
/// Spinner size variants
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum SpinnerSize {
/// Small spinner (16px)
Small,
/// Medium spinner (24px)
#[default]
Medium,
/// Large spinner (32px)
Large,
}
impl SpinnerSize {
fn diameter(&self) -> f32 {
match self {
SpinnerSize::Small => 16.0,
SpinnerSize::Medium => 24.0,
SpinnerSize::Large => 32.0,
}
}
fn border_width(&self) -> f32 {
match self {
SpinnerSize::Small => 2.0,
SpinnerSize::Medium => 2.5,
SpinnerSize::Large => 3.0,
}
}
}
/// Internal configuration accumulated by `SpinnerBuilder` before the
/// inner element is materialised on first `ElementBuilder` access.
#[derive(Clone, Default)]
struct SpinnerConfig {
size: SpinnerSize,
color: Option<blinc_layout::binding::Reactive<Color>>,
/// The faint full-circle ring behind the arc; `.cn-spinner__track`'s
/// colour when `None`.
track_color: Option<blinc_layout::binding::Reactive<Color>>,
classes: Vec<Arc<str>>,
user_id: Option<String>,
}
/// Built spinner — wraps the composed inner `Div`. Created by
/// `SpinnerBuilder::get_or_build` on first ElementBuilder access.
pub struct Spinner {
inner: Div,
}
impl Spinner {
/// Materialise the spinner tree from accumulated config.
fn with_config(_key: InstanceKey, config: SpinnerConfig) -> Self {
let diameter = config.size.diameter();
let border_width = config.size.border_width();
let half = diameter / 2.0;
// A rectangle over the left half, in the arc's own coordinates, so
// it turns with the arc and shows a half circle going round.
let polygon = ClipPath::Polygon {
points: vec![
(ClipLength::Px(0.0), ClipLength::Px(0.0)),
(ClipLength::Px(half), ClipLength::Px(0.0)),
(ClipLength::Px(half), ClipLength::Px(diameter)),
(ClipLength::Px(0.0), ClipLength::Px(diameter)),
],
};
// Colours are rules unless set on the builder; a bound colour patches
// the border in place.
let mut track = div()
.class("cn-spinner__track")
.absolute()
.inset(0.0)
.w(diameter)
.h(diameter)
.rounded(half)
.border_width(border_width);
if let Some(color) = config.track_color {
track = track.border_color(color);
}
let mut arc = div()
.class("cn-spinner__arc")
.absolute()
.inset(0.0)
.w(diameter)
.h(diameter)
.rounded(half)
.border_width(border_width)
.clip_path(polygon);
if let Some(color) = config.color {
arc = arc.border_color(color);
}
let arc_layer = div()
.absolute()
.inset(0.0)
.w(diameter)
.h(diameter)
.child(arc);
// Total container size includes border-stroke padding so the
// ring isn't clipped by the parent layout.
let total = diameter + border_width;
let mut spinner = div()
.class("cn-spinner")
.w(total)
.h(total)
.relative()
.child(track)
.child(arc_layer);
for c in &config.classes {
spinner = spinner.class(c.as_ref());
}
if let Some(ref id) = config.user_id {
spinner = spinner.id(id);
}
Self { inner: spinner }
}
}
impl ElementBuilder for Spinner {
fn build(&self, tree: &mut LayoutTree) -> LayoutNodeId {
self.inner.build(tree)
}
fn render_props(&self) -> RenderProps {
self.inner.render_props()
}
fn children_builders(&self) -> &[Box<dyn ElementBuilder>] {
self.inner.children_builders()
}
fn element_type_id(&self) -> ElementTypeId {
ElementTypeId::Div
}
fn layout_style(&self) -> Option<&Style> {
self.inner.layout_style()
}
fn element_classes(&self) -> &[Arc<str>] {
self.inner.element_classes()
}
fn element_id(&self) -> Option<&str> {
self.inner.element_id()
}
}
/// Fluent builder for `Spinner`. Implements `ElementBuilder` directly via
/// a lazy `OnceCell<Spinner>`, so the builder can be used inline as a
/// child — no terminal `build_final()` call needed. Same pattern as
/// `SliderBuilder` / `AvatarBuilder` / `CheckboxBuilder`.
pub struct SpinnerBuilder {
key: InstanceKey,
config: RefCell<SpinnerConfig>,
built: OnceCell<Spinner>,
}
impl SpinnerBuilder {
/// Create a new spinner builder. Uses `#[track_caller]` so each
/// distinct call-site gets a stable, unique `InstanceKey`.
#[track_caller]
pub fn new() -> Self {
Self {
key: InstanceKey::new("spinner"),
config: RefCell::new(SpinnerConfig::default()),
built: OnceCell::new(),
}
}
/// Set the spinner size.
pub fn size(self, size: SpinnerSize) -> Self {
self.config.borrow_mut().size = size;
self
}
/// Set the turning arc's colour; `.cn-spinner__arc`'s otherwise.
pub fn color(self, color: impl blinc_layout::binding::IntoReactive<Color>) -> Self {
self.config.borrow_mut().color = Some(color.into_reactive());
self
}
/// Set the track ring's colour; `.cn-spinner__track`'s otherwise. Pass
/// `Color::TRANSPARENT` to hide the track.
pub fn track_color(self, color: impl blinc_layout::binding::IntoReactive<Color>) -> Self {
self.config.borrow_mut().track_color = Some(color.into_reactive());
self
}
/// Add a CSS class for selector matching.
pub fn class(self, name: impl AsRef<str>) -> Self {
self.config
.borrow_mut()
.classes
.push(blinc_core::intern::intern(name.as_ref()));
self
}
/// Set the element ID for CSS selector matching.
pub fn id(self, id: &str) -> Self {
self.config.borrow_mut().user_id = Some(id.to_string());
self
}
fn get_or_build(&self) -> &Spinner {
::blinc_layout::build_once::build_once(&self.built, || {
let config = self.config.take();
Spinner::with_config(self.key.clone(), config)
})
}
}
impl Default for SpinnerBuilder {
fn default() -> Self {
Self::new()
}
}
impl ElementBuilder for SpinnerBuilder {
fn build(&self, tree: &mut LayoutTree) -> LayoutNodeId {
self.get_or_build().build(tree)
}
fn render_props(&self) -> RenderProps {
self.get_or_build().render_props()
}
fn children_builders(&self) -> &[Box<dyn ElementBuilder>] {
self.get_or_build().children_builders()
}
fn element_type_id(&self) -> ElementTypeId {
ElementTypeId::Div
}
fn layout_style(&self) -> Option<&Style> {
self.get_or_build().layout_style()
}
fn element_classes(&self) -> &[Arc<str>] {
self.get_or_build().element_classes()
}
fn element_id(&self) -> Option<&str> {
self.get_or_build().element_id()
}
}
/// A turning spinner for work in progress. Its turn and colours are rules.
///
/// # Example
///
/// ```ignore
/// use blinc_cn::prelude::*;
///
/// fn loading() -> impl ElementBuilder {
/// cn::spinner()
/// }
///
/// // With customisation
/// cn::spinner().size(SpinnerSize::Large)
/// ```
#[track_caller]
pub fn spinner() -> SpinnerBuilder {
SpinnerBuilder::new()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_spinner_size_values() {
assert_eq!(SpinnerSize::Small.diameter(), 16.0);
assert_eq!(SpinnerSize::Medium.diameter(), 24.0);
assert_eq!(SpinnerSize::Large.diameter(), 32.0);
}
#[test]
fn test_spinner_border_widths() {
assert_eq!(SpinnerSize::Small.border_width(), 2.0);
assert_eq!(SpinnerSize::Medium.border_width(), 2.5);
assert_eq!(SpinnerSize::Large.border_width(), 3.0);
}
}