1use schemars::JsonSchema;
2use serde::{Deserialize, Serialize};
3use skia_safe::Canvas;
4
5use rustmotion_core::css::CssStyle;
6use rustmotion_core::engine::animator::AnimatedProperties;
7use rustmotion_core::engine::layout_pass::BoxLayout;
8use rustmotion_core::engine::renderer::{
9 draw_text_with_fallback, emoji_typeface, measure_text_with_fallback, paint_from_hex,
10 parse_hex_color, subpixel_font, typeface_with_fallback,
11};
12use rustmotion_core::schema::TimelineStep;
13use rustmotion_core::traits::{PaintCtx, Painter, TimingConfig};
14
15const DEFAULT_PALETTE: &[&str] = &[
16 "#3B82F6", "#EF4444", "#22C55E", "#F59E0B", "#8B5CF6", "#EC4899", "#06B6D4", "#F97316",
17];
18
19fn default_min_font_size() -> f32 {
20 14.0
21}
22
23fn default_max_font_size() -> f32 {
24 64.0
25}
26
27fn default_animated() -> bool {
28 true
29}
30
31fn default_animation_duration() -> f64 {
32 1.5
33}
34
35#[derive(Debug, Serialize, Deserialize, JsonSchema)]
36pub struct TagItem {
37 pub text: String,
38 #[serde(default)]
39 pub weight: f64,
40 #[serde(default)]
41 pub color: Option<String>,
42}
43
44#[derive(Debug, Serialize, Deserialize, JsonSchema)]
45#[deprecated(
46 since = "0.7.1",
47 note = "`tag_cloud` is a frozen composition (issue #333). Compose weighted tags from a \
48 `for-each` over `text` nodes with `font-size` scaled by weight instead — see \
49 crates/rustmotion/skills/rules/composition-recipes.md. Kept for compatibility; \
50 scheduled for removal in a future major version via `rustmotion migrate` \
51 (#335)."
52)]
53pub struct TagCloud {
54 pub tags: Vec<TagItem>,
55 #[serde(default = "default_min_font_size")]
56 pub min_font_size: f32,
57 #[serde(default = "default_max_font_size")]
58 pub max_font_size: f32,
59 #[serde(default)]
60 pub colors: Option<Vec<String>>,
61 #[serde(default = "default_animated")]
62 pub animated: bool,
63 #[serde(default = "default_animation_duration")]
64 pub animation_duration: f64,
65 #[serde(flatten)]
66 pub timing: TimingConfig,
67 #[serde(default)]
68 pub style: CssStyle,
69 #[serde(default)]
70 pub timeline: Vec<TimelineStep>,
71 #[serde(default)]
72 pub stagger: Option<f32>,
73}
74
75rustmotion_core::impl_traits!(TagCloud {
76 Animatable => animation,
77 Timed => timing,
78 Styled => style,
79});
80
81impl TagCloud {
82 fn progress_at(&self, time: f64) -> f32 {
83 if !self.animated {
84 return 1.0;
85 }
86 let p = (time / self.animation_duration).clamp(0.0, 1.0) as f32;
87 1.0 - (1.0 - p).powi(3)
88 }
89
90 fn palette(&self) -> Vec<&str> {
91 match &self.colors {
92 Some(colors) if !colors.is_empty() => colors.iter().map(|s| s.as_str()).collect(),
93 _ => DEFAULT_PALETTE.to_vec(),
94 }
95 }
96
97 fn font_size_for_weight(&self, weight: f64, min_weight: f64, max_weight: f64) -> f32 {
98 let range = (max_weight - min_weight).max(0.001);
99 let normalized = ((weight - min_weight) / range) as f32;
100 self.min_font_size + normalized * (self.max_font_size - self.min_font_size)
101 }
102}
103
104impl TagCloud {
105 fn paint(&self, canvas: &Canvas, layout_w: f32, layout_h: f32, time: f64) {
106 let w = layout_w;
107 let h = layout_h;
108
109 if self.tags.is_empty() {
110 return;
111 }
112
113 let progress = self.progress_at(time);
114 let palette = self.palette();
115
116 let min_weight = self.tags.iter().map(|t| t.weight).fold(f64::MAX, f64::min);
117 let max_weight = self.tags.iter().map(|t| t.weight).fold(f64::MIN, f64::max);
118
119 let mut sorted_indices: Vec<usize> = (0..self.tags.len()).collect();
120 sorted_indices.sort_by(|&a, &b| {
121 self.tags[b]
122 .weight
123 .partial_cmp(&self.tags[a].weight)
124 .unwrap_or(std::cmp::Ordering::Equal)
125 });
126
127 let tag_count = self.tags.len();
128 let h_gap = 12.0_f32;
129 let v_gap = 8.0_f32;
130
131 struct TagMetrics {
132 index: usize,
133 font_size: f32,
134 text_width: f32,
135 ascent: f32,
136 height: f32,
137 }
138
139 let mut metrics_list: Vec<TagMetrics> = Vec::with_capacity(tag_count);
140 for &idx in &sorted_indices {
141 let tag = &self.tags[idx];
142 let font_size = self.font_size_for_weight(tag.weight, min_weight, max_weight);
143 let font_style = skia_safe::FontStyle::bold();
144 let Ok(typeface) = typeface_with_fallback("Inter", font_style) else {
145 continue;
146 };
147 let font = subpixel_font(typeface, font_size);
148 let emoji_font = emoji_typeface().map(|tf| subpixel_font(tf, font_size));
149
150 let text_width = measure_text_with_fallback(&tag.text, &font, &emoji_font, 0.0);
151 let (_, fm_metrics) = font.metrics();
152 let ascent = -fm_metrics.ascent;
153 let height = ascent + fm_metrics.descent;
154
155 metrics_list.push(TagMetrics {
156 index: idx,
157 font_size,
158 text_width,
159 ascent,
160 height,
161 });
162 }
163
164 struct PlacedTag {
165 index: usize,
166 x: f32,
167 y: f32,
168 font_size: f32,
169 ascent: f32,
170 line_height: f32,
171 }
172
173 let mut placed: Vec<PlacedTag> = Vec::with_capacity(tag_count);
174 let mut cursor_x = 0.0_f32;
175 let mut cursor_y = 0.0_f32;
176 let mut line_max_height = 0.0_f32;
177
178 for m in &metrics_list {
179 let item_width = m.text_width + h_gap;
180
181 if cursor_x + m.text_width > w && cursor_x > 0.0 {
182 cursor_y += line_max_height + v_gap;
183 cursor_x = 0.0;
184 line_max_height = 0.0;
185 }
186
187 placed.push(PlacedTag {
188 index: m.index,
189 x: cursor_x,
190 y: cursor_y,
191 font_size: m.font_size,
192 ascent: m.ascent,
193 line_height: m.height,
194 });
195
196 if m.height > line_max_height {
197 line_max_height = m.height;
198 }
199
200 cursor_x += item_width;
201 }
202
203 let total_height = if let Some(last) = placed.last() {
204 last.y
205 + placed.iter().fold(0.0_f32, |max_h, p| {
206 if (p.y - last.y).abs() < 0.01 {
207 max_h.max(p.line_height)
208 } else {
209 max_h
210 }
211 })
212 } else {
213 0.0
214 };
215 let y_offset = ((h - total_height) / 2.0).max(0.0);
216
217 for (draw_order, pt) in placed.iter().enumerate() {
218 let tag = &self.tags[pt.index];
219
220 let tag_alpha = if self.animated {
221 let stagger_delay = (draw_order as f64 / tag_count as f64) * 0.6;
222 let tag_progress = ((time - stagger_delay) / (self.animation_duration * 0.4))
223 .clamp(0.0, 1.0) as f32;
224 tag_progress * progress
225 } else {
226 1.0
227 };
228
229 if tag_alpha <= 0.0 {
230 continue;
231 }
232
233 let color_str = tag
234 .color
235 .as_deref()
236 .unwrap_or(palette[pt.index % palette.len()]);
237
238 let (_r, _g, _b, _) = parse_hex_color(color_str);
239 let mut text_paint = paint_from_hex(color_str);
240 text_paint.set_anti_alias(true);
241 text_paint.set_alpha((tag_alpha * 255.0) as u8);
242
243 let font_style = skia_safe::FontStyle::bold();
244 let Ok(typeface) = typeface_with_fallback("Inter", font_style) else {
245 continue;
246 };
247 let font = subpixel_font(typeface, pt.font_size);
248 let emoji_font = emoji_typeface().map(|tf| subpixel_font(tf, pt.font_size));
249
250 let text_x = pt.x;
251 let text_y = y_offset + pt.y + pt.ascent;
252
253 draw_text_with_fallback(
254 canvas,
255 &tag.text,
256 &font,
257 &emoji_font,
258 0.0,
259 text_x,
260 text_y,
261 &text_paint,
262 );
263 }
264 }
265}
266
267impl Painter for TagCloud {
268 fn paint_content(
269 &self,
270 canvas: &Canvas,
271 layout: &BoxLayout,
272 _props: &AnimatedProperties,
273 ctx: &PaintCtx,
274 ) {
275 self.paint(canvas, layout.width, layout.height, ctx.time);
276 }
277}