1use std::fmt::Write as _;
10
11use super::host::{HostCx, HostInput, HostList, HostValue, field};
12use crate::{
13 LayoutAnimation, LayoutCurve, LayoutProperty, LayoutTransition,
14 animation::{
15 Composite, Curve, EaseMode, Easing, Keyframe, KeyframeTiming, MotionChannel, MotionPreset,
16 MotionSpec, NodeId, PRESETS as MOTIONS, PlaybackDirection, StaggerFrom, StepPosition,
17 keyframes,
18 },
19 element::{Spring, TsTypes},
20};
21
22struct CurveSpec {
25 name: &'static str,
26 param: Option<(&'static str, f32)>,
27 make: fn(f32) -> Curve,
28 doc: &'static str,
29}
30
31const CURVES: &[CurveSpec] = &[
32 CurveSpec {
33 name: "quad",
34 param: None,
35 make: |_| Curve::Quad,
36 doc: "`t²`.",
37 },
38 CurveSpec {
39 name: "cubic",
40 param: None,
41 make: |_| Curve::Cubic,
42 doc: "`t³`.",
43 },
44 CurveSpec {
45 name: "poly",
46 param: Some(("n", 2.0)),
47 make: Curve::Poly,
48 doc: "`tⁿ`.",
49 },
50 CurveSpec {
51 name: "sin",
52 param: None,
53 make: |_| Curve::Sin,
54 doc: "Sinusoidal.",
55 },
56 CurveSpec {
57 name: "circle",
58 param: None,
59 make: |_| Curve::Circle,
60 doc: "Circular.",
61 },
62 CurveSpec {
63 name: "exp",
64 param: None,
65 make: |_| Curve::Exp,
66 doc: "Exponential.",
67 },
68 CurveSpec {
69 name: "elastic",
70 param: Some(("bounciness", 1.0)),
71 make: Curve::Elastic,
72 doc: "Springy overshoot.",
73 },
74 CurveSpec {
75 name: "back",
76 param: Some(("s", 1.70158)),
77 make: Curve::Back,
78 doc: "Pulls back before going; `s` is the overshoot.",
79 },
80 CurveSpec {
81 name: "bounce",
82 param: None,
83 make: |_| Curve::Bounce,
84 doc: "Bounces at the end.",
85 },
86];
87
88const NAMED: &[(&str, Easing)] = &[
90 ("linear", Easing::Linear),
91 ("ease", Easing::Bezier(0.25, 0.1, 0.25, 1.0)),
93 ("easeIn", Easing::EaseIn),
94 ("easeOut", Easing::EaseOut),
95 ("easeInOut", Easing::EaseInOut),
96];
97
98pub fn easing<I: HostInput>(input: &I) -> Option<Easing> {
102 if let Some(list) = input.as_list() {
103 let p = |i| list.item(i).and_then(|v| v.as_number()).unwrap_or(0.0) as f32;
104 return Some(Easing::Bezier(p(0), p(1), p(2), p(3)));
105 }
106 if let Some(steps) = input.field("steps").and_then(|n| n.as_number()) {
107 let position = input
108 .field("position")
109 .and_then(|p| p.as_string())
110 .and_then(|p| StepPosition::parse(&p))
111 .unwrap_or_default();
112 return Some(Easing::Steps(steps.clamp(1.0, 10_000.0) as u32, position));
113 }
114 if input.is_object() {
115 let name = input.field("curve").and_then(|c| c.as_string())?;
116 let spec = CURVES.iter().find(|c| c.name == name)?;
117 let param = input.field("param").and_then(|p| p.as_number());
118 let curve = (spec.make)(param.map_or_else(
119 || spec.param.map_or(0.0, |(_, default)| default),
120 |p| p as f32,
121 ));
122 let mode = match input.field("mode").and_then(|m| m.as_string()).as_deref() {
123 Some("out") => EaseMode::Out,
124 Some("inOut") => EaseMode::InOut,
125 _ => EaseMode::In,
126 };
127 return Some(Easing::Curve(curve, mode));
128 }
129 let name = input.as_string()?;
130 NAMED.iter().find(|(n, _)| *n == name).map(|&(_, e)| e)
131}
132
133fn keyframe_value<I: HostInput>(input: &I) -> Option<f32> {
136 match input.as_number() {
137 Some(n) => Some(n as f32).filter(|n| n.is_finite()),
138 None => crate::css::angle(&input.as_string()?),
139 }
140}
141
142pub fn keyframe_list<I: HostInput>(input: &I) -> Vec<Keyframe> {
145 input
146 .items()
147 .iter()
148 .filter_map(|item| {
149 if let Some(value) = keyframe_value(item) {
150 return Some(Keyframe::new(value));
151 }
152 let mut frame = Keyframe::new(keyframe_value(&item.field("value")?)?);
153 frame.offset = item
154 .field("offset")
155 .and_then(|o| o.as_number())
156 .map(|o| o as f32);
157 frame.easing = item.field("easing").and_then(|e| easing(&e));
158 Some(frame)
159 })
160 .collect()
161}
162
163pub fn keyframe_timing<I: HostInput>(input: &I) -> KeyframeTiming {
167 let number = |key| {
168 input
169 .field(key)
170 .and_then(|v| v.as_number())
171 .filter(|n| n.is_finite())
172 .map(|n| n as f32)
173 };
174 let defaults = KeyframeTiming::default();
175 let iterations = match input.field("iterations") {
176 Some(v) if v.as_string().as_deref() == Some("infinite") => None,
177 Some(v) => match v.as_number() {
178 Some(n) if n.is_infinite() && n > 0.0 => None,
179 Some(n) if n.is_finite() => Some(n.max(0.0).round().min(u32::MAX as f64) as u32),
180 _ => defaults.iterations,
181 },
182 None => defaults.iterations,
183 };
184 KeyframeTiming {
185 duration_ms: number("duration").map_or(defaults.duration_ms, |d| d.max(0.0)),
186 delay_ms: number("delay").map_or(0.0, |d| d.max(0.0)),
187 easing: input
188 .field("easing")
189 .and_then(|e| easing(&e))
190 .unwrap_or(defaults.easing),
191 iterations,
192 direction: input
193 .field("direction")
194 .and_then(|d| d.as_string())
195 .and_then(|d| PlaybackDirection::parse(&d))
196 .unwrap_or_default(),
197 frame_rate: crate::style::frame_rate(number("frameRate")),
198 }
199}
200
201pub fn keyframes_composite<I: HostInput>(input: &I, node: NodeId) -> Composite {
204 let frames = input
205 .field("keyframes")
206 .map(|k| keyframe_list(&k))
207 .unwrap_or_default();
208 keyframes(node, &frames, &keyframe_timing(input))
209}
210
211pub fn motion_spec<I: HostInput>(input: &I) -> Option<MotionSpec> {
218 if let Some(name) = input.as_string() {
219 return MotionPreset::parse(&name).map(MotionPreset::spec);
220 }
221 if !input.is_object() {
222 return None;
223 }
224 let mut spec = MotionSpec::new(keyframe_timing(input));
225 spec.spring = input
226 .field("spring")
227 .filter(|s| s.is_object())
228 .map(|s| motion_spring(&s));
229 let frames = input.field("keyframes")?;
230 if let Some(list) = frames.as_list() {
231 let items: Vec<_> = (0..list.len()).filter_map(|i| list.item(i)).collect();
236 let count = items.len();
237 for channel in MotionChannel::ALL {
238 let mut track = Vec::new();
239 for (i, item) in items.iter().enumerate() {
240 let Some(value) = item.field(channel.name()).and_then(|v| keyframe_value(&v))
241 else {
242 continue;
243 };
244 let offset = item
245 .field("offset")
246 .and_then(|o| o.as_number())
247 .map(|o| o as f32);
248 let offset = offset.or_else(|| match count {
251 1 => Some(1.0),
252 n => Some(i as f32 / (n - 1) as f32),
253 });
254 track.push(Keyframe {
255 offset,
256 easing: item.field("easing").and_then(|e| easing(&e)),
257 ..Keyframe::new(value)
258 });
259 }
260 if !track.is_empty() {
261 spec = spec.track(channel, track);
262 }
263 }
264 } else {
265 for (name, value) in frames.entries() {
266 if let Some(channel) = MotionChannel::parse(&name) {
267 let track = keyframe_list(&value);
268 if !track.is_empty() {
269 spec = spec.track(channel, track);
270 }
271 }
272 }
273 }
274 Some(spec)
275}
276
277fn motion_spring<I: HostInput>(input: &I) -> Spring {
280 let defaults = Spring::default();
281 let number = |key, default| {
282 input
283 .field(key)
284 .and_then(|v| v.as_number())
285 .filter(|n| n.is_finite())
286 .map_or(default, |n| n as f32)
287 };
288 Spring {
289 stiffness: number("stiffness", defaults.stiffness),
290 damping: number("damping", defaults.damping),
291 mass: number("mass", defaults.mass),
292 ..defaults
293 }
294}
295
296pub fn stagger_from<I: HostInput>(input: &I) -> StaggerFrom {
299 if let Some(index) = input.as_number() {
300 return StaggerFrom::Index(index.max(0.0) as usize);
301 }
302 match input.as_string().as_deref() {
303 Some("last") => StaggerFrom::Last,
304 Some("center") => StaggerFrom::Center,
305 _ => StaggerFrom::First,
306 }
307}
308
309type MakeLayoutCurve = fn(f32) -> LayoutCurve;
311
312const LAYOUT_TYPES: &[(&str, MakeLayoutCurve)] = &[
315 ("easeInEaseOut", |_| LayoutCurve::EaseInEaseOut),
316 ("spring", |damping_ratio| LayoutCurve::FittedSpring {
317 damping_ratio,
318 }),
319 ("linear", |_| LayoutCurve::Linear),
320 ("easeIn", |_| LayoutCurve::EaseIn),
321 ("easeOut", |_| LayoutCurve::EaseOut),
322 ("keyboard", |_| LayoutCurve::Keyboard),
323 ("bezier", |_| LayoutCurve::EaseInEaseOut),
326];
327
328const LAYOUT_PROPERTIES: &[(&str, LayoutProperty, bool)] = &[
331 ("opacity", LayoutProperty::Opacity, true),
332 ("scaleXY", LayoutProperty::Scale, true),
333 ("scale", LayoutProperty::Scale, false),
334];
335
336const SPRING_DAMPING: f32 = 0.7;
338
339fn physical_spring<I: HostInput>(part: &I, cx: &mut HostCx) -> Option<Spring> {
342 let [stiffness, damping, mass] =
343 ["stiffness", "damping", "mass"].map(|key| field::<f32, _>(part, key, cx));
344 if stiffness.is_none() && damping.is_none() && mass.is_none() {
345 return None;
346 }
347 let default = Spring::default();
348 Some(Spring {
349 stiffness: stiffness.unwrap_or(default.stiffness),
350 damping: damping.unwrap_or(default.damping),
351 mass: mass.unwrap_or(default.mass),
352 ..default
353 })
354}
355
356fn transition<I: HostInput>(part: &I, duration: f32, cx: &mut HostCx) -> LayoutTransition {
358 let named = |key, names: &mut dyn Iterator<Item = &'static str>| {
360 let name = part.field(key).and_then(|v| v.as_string());
361 let mut at = 0;
362 for (i, n) in names.enumerate() {
363 if Some(n) == name.as_deref() {
364 at = i;
365 break;
366 }
367 }
368 at
369 };
370 let damping = field::<f32, _>(part, "springDamping", cx)
371 .unwrap_or(SPRING_DAMPING)
372 .clamp(0.01, 1.0);
373 let kind = LAYOUT_TYPES[named("type", &mut LAYOUT_TYPES.iter().map(|t| t.0))].0;
374 let spring = if kind == "spring" {
375 physical_spring(part, cx)
376 } else {
377 None
378 };
379 let curve = match (spring, part.field("bezier").and_then(|b| b.as_list())) {
380 (Some(spring), _) => LayoutCurve::Spring(spring),
381 (None, Some(list)) if kind == "bezier" && list.len() == 4 => {
382 let p = |i| list.item(i).and_then(|v| v.as_number()).unwrap_or(0.0) as f32;
383 LayoutCurve::bezier(p(0), p(1), p(2), p(3))
384 }
385 _ => LAYOUT_TYPES
386 .iter()
387 .find(|t| t.0 == kind)
388 .map_or(LayoutCurve::EaseInEaseOut, |t| t.1(damping)),
389 };
390 let property =
391 LAYOUT_PROPERTIES[named("property", &mut LAYOUT_PROPERTIES.iter().map(|p| p.0))].1;
392 let duration_ms = match spring {
394 Some(spring) => spring.settle_ms(),
395 None => field(part, "duration", cx).unwrap_or(duration),
396 };
397 LayoutTransition {
398 curve,
399 property,
400 duration_ms,
401 delay_ms: field(part, "delay", cx).unwrap_or(0.0),
402 }
403}
404
405impl HostValue for LayoutAnimation {
410 fn decode<I: HostInput>(input: &I, cx: &mut HostCx) -> Option<Self> {
411 let duration = field(input, "duration", cx).unwrap_or(300.0);
412 let mut phase = |key| {
413 input
414 .field(key)
415 .filter(|p| p.is_object())
416 .map(|p| transition(&p, duration, cx))
417 };
418 Some(LayoutAnimation {
419 create: phase("create"),
420 update: phase("update"),
421 delete: phase("delete"),
422 })
423 }
424
425 fn ts_type(types: &mut TsTypes) -> String {
426 let union = |names: &mut dyn Iterator<Item = &str>| {
427 names
428 .map(|n| format!("{n:?}"))
429 .collect::<Vec<_>>()
430 .join(" | ")
431 };
432 let curve = types.declare("LayoutAnimationType", |_| {
433 format!(
434 "/** The curve of a layout animation phase (`type`). */\nexport type LayoutAnimationType = {};",
435 union(&mut LAYOUT_TYPES.iter().map(|t| t.0))
436 )
437 });
438 let property = types.declare("LayoutAnimationProperty", |_| {
439 format!(
440 "/** What appearing and disappearing views animate (`property`). */\n\
441 export type LayoutAnimationProperty = {};",
442 union(&mut LAYOUT_PROPERTIES.iter().map(|p| p.0))
443 )
444 });
445 types.declare("LayoutAnimationAnimation", |_| {
446 format!(
447 "/** How one kind of change animates. */\nexport interface LayoutAnimationAnimation {{\n \
448 type?: {curve};\n /** What appearing and disappearing views animate. */\n \
449 property?: {property};\n /** Milliseconds (the config's by default). */\n \
450 duration?: number;\n delay?: number;\n /** The `spring`'s damping ratio, 0..1 \
451 ({SPRING_DAMPING} by default; 1 does not overshoot), the spring fitted into `duration`. */\n \
452 springDamping?: number;\n /** A physical `spring`'s stiffness `k` (170 by default). With \
453 `stiffness`, `damping` or `mass` the `spring` moves on its physics and lasts until it \
454 settles: `duration` and `springDamping` are not used. */\n stiffness?: number;\n \
455 /** A physical `spring`'s damping coefficient `c` (26 by default; the ratio is \
456 `c / (2 √(k m))`). */\n damping?: number;\n /** A physical `spring`'s mass `m` \
457 (1 by default). */\n mass?: number;\n \
458 /** The `bezier`'s control points `[x1, y1, x2, y2]`, as CSS `cubic-bezier()` \
459 (each `x` clamped to 0..1); without them it eases in and out. */\n \
460 bezier?: [number, number, number, number];\n}}"
461 )
462 });
463 types.declare("LayoutAnimationConfig", |_| {
464 "/** What the next commit's changes animate: views inserted (`create`), moved or \
465 resized (`update`) and removed (`delete`). */\nexport interface LayoutAnimationConfig {\n \
466 /** Milliseconds. */\n duration: number;\n create?: LayoutAnimationAnimation;\n \
467 update?: LayoutAnimationAnimation;\n delete?: LayoutAnimationAnimation;\n}"
468 .into()
469 })
470 }
471}
472
473const PRESETS: &[(&str, LayoutAnimation)] = &[
475 ("easeInEaseOut", LayoutAnimation::EASE_IN_EASE_OUT),
476 ("linear", LayoutAnimation::LINEAR),
477 ("spring", LayoutAnimation::SPRING),
478];
479
480pub fn declarations() -> String {
483 let mut types = TsTypes::default();
484 let layout = <LayoutAnimation as HostValue>::ts_type(&mut types);
485 let names = |list: &mut dyn Iterator<Item = &str>| {
486 list.map(|n| format!("{n:?}"))
487 .collect::<Vec<_>>()
488 .join(" | ")
489 };
490 let mut out = String::new();
491 let _ = write!(
492 out,
493 "/** The curves of `Easing` (their \"in\" form; `Easing.out` / `inOut` turn them around). */\n\
494 export type EasingCurveName = {};\n\n\
495 /** A curve of the `Easing` module. */\n\
496 export interface EasingCurve {{\n curve: EasingCurveName;\n param?: number;\n mode: \"in\" | \"out\" | \"inOut\";\n}}\n\n\
497 /** CSS `steps()`: jumps between `steps` levels instead of moving. */\n\
498 export interface EasingSteps {{\n steps: number;\n position?: StepPosition;\n}}\n\n\
499 /** Where a `steps()` curve jumps (CSS's `<step-position>`; `\"jump-end\"` by default). */\n\
500 export type StepPosition = \"jump-start\" | \"jump-end\" | \"jump-none\" | \"jump-both\" | \"start\" | \"end\";\n\n\
501 /** How a timing animation (or an interpolation segment) progresses: a name, a cubic\n \
502 * Bézier `[x1, y1, x2, y2]`, a curve from `Easing` or `Easing.steps(…)`. */\n\
503 export type Easing = {} | [number, number, number, number] | EasingCurve | EasingSteps;\n",
504 names(&mut CURVES.iter().map(|c| c.name)),
505 names(&mut NAMED.iter().map(|(n, _)| *n)),
506 );
507 out.push_str("\n/** `Easing`'s curves. */\nexport interface EasingCurves {\n");
508 for c in CURVES {
509 match c.param {
510 Some((p, default)) => {
511 let _ = writeln!(
512 out,
513 " /** {} `{p}`: {default} by default. */\n {}({p}?: number): EasingCurve;",
514 c.doc, c.name
515 );
516 }
517 None => {
518 let _ = writeln!(out, " /** {} */\n {}: EasingCurve;", c.doc, c.name);
519 }
520 }
521 }
522 out.push_str("}\n");
523 for declaration in types.declarations() {
524 let _ = write!(out, "\n{declaration}\n");
525 }
526 let _ = write!(
527 out,
528 "\n/** Ready-made layout animations. */\nexport interface LayoutAnimationPresets {{\n{}}}\n",
529 PRESETS
530 .iter()
531 .map(|(name, _)| format!(" {name}: {layout};\n"))
532 .collect::<String>()
533 );
534 out.push_str(&motion_declarations());
535 let object = |iface: &str, doc: &str, names: &mut dyn Iterator<Item = &str>| {
537 let fields: String = names.map(|n| format!(" readonly {n}: {n:?};\n")).collect();
538 format!("\n/** {doc} */\nexport interface {iface} {{\n{fields}}}\n")
539 };
540 out.push_str(&object(
541 "LayoutAnimationTypes",
542 "The curves, by name.",
543 &mut LAYOUT_TYPES.iter().map(|t| t.0),
544 ));
545 out.push_str(&object(
546 "LayoutAnimationProperties",
547 "The properties, by name.",
548 &mut LAYOUT_PROPERTIES.iter().filter(|p| p.2).map(|p| p.0),
549 ));
550 out
551}
552
553fn motion_declarations() -> String {
555 let mut out = String::new();
556 let channels = MotionChannel::ALL
557 .iter()
558 .map(|c| format!("{:?}", c.name()))
559 .collect::<Vec<_>>()
560 .join(" | ");
561 let _ = write!(
562 out,
563 "\n/** What a motion moves: the opacity and the parts of the transform (translations in points,\n \
564 * rotations in degrees), applied translations first, then rotations, then scales. */\n\
565 export type MotionChannel = {channels};\n"
566 );
567 out.push_str("\n/** The ready-made motions:\n");
568 for preset in MOTIONS {
569 let _ = writeln!(
570 out,
571 " * - `{}` ({}):{}",
572 preset.name,
573 preset.kind.name(),
574 preset.doc
575 );
576 }
577 out.push_str(" */\nexport type MotionName =\n");
578 for preset in MOTIONS {
579 let _ = writeln!(out, " | {:?}", preset.name);
580 }
581 out.push_str(" ;\n");
582 out
583}
584
585fn motion_json(preset: &crate::animation::PresetDef) -> crate::JsonValue {
589 use serde_json::{Map, Value, json};
590 let spec = preset.spec();
591 let mut keyframes = Map::new();
592 for (channel, frames) in &spec.tracks {
593 keyframes.insert(
594 channel.name().into(),
595 Value::Array(
596 frames
597 .iter()
598 .map(|f| json!({ "offset": f.offset, "value": f.value }))
599 .collect(),
600 ),
601 );
602 }
603 let t = spec.timing;
604 json!({
605 "kind": preset.kind.name(),
606 "keyframes": keyframes,
607 "duration": t.duration_ms,
608 "easing": easing_json(t.easing),
609 "iterations": match t.iterations {
610 Some(n) => json!(n),
611 None => json!("infinite"),
612 },
613 "direction": t.direction.name(),
614 })
615}
616
617fn easing_json(e: Easing) -> crate::JsonValue {
619 use serde_json::json;
620 match e {
621 Easing::Linear => json!("linear"),
622 Easing::EaseIn => json!("easeIn"),
623 Easing::EaseOut => json!("easeOut"),
624 Easing::EaseInOut => json!("easeInOut"),
625 Easing::Bezier(a, b, c, d) => json!([a, b, c, d]),
626 Easing::Curve(curve, mode) => {
627 let (name, param) = match curve {
628 Curve::Quad => ("quad", None),
629 Curve::Cubic => ("cubic", None),
630 Curve::Poly(n) => ("poly", Some(n)),
631 Curve::Sin => ("sin", None),
632 Curve::Circle => ("circle", None),
633 Curve::Exp => ("exp", None),
634 Curve::Elastic(b) => ("elastic", Some(b)),
635 Curve::Back(s) => ("back", Some(s)),
636 Curve::Bounce => ("bounce", None),
637 };
638 let mode = match mode {
639 EaseMode::In => "in",
640 EaseMode::Out => "out",
641 EaseMode::InOut => "inOut",
642 };
643 json!({ "curve": name, "param": param, "mode": mode })
644 }
645 Easing::Steps(steps, position) => json!({ "steps": steps, "position": position.name() }),
646 }
647}
648
649pub fn tables() -> crate::JsonValue {
656 use serde_json::{Map, Value, json};
657 let transition = |t: &LayoutTransition| {
658 let (mut bezier, mut physics) = (None, None);
659 let (kind, damping) = match t.curve {
660 LayoutCurve::Linear => ("linear", None),
661 LayoutCurve::EaseIn => ("easeIn", None),
662 LayoutCurve::EaseOut => ("easeOut", None),
663 LayoutCurve::EaseInEaseOut => ("easeInEaseOut", None),
664 LayoutCurve::FittedSpring { damping_ratio } => ("spring", Some(damping_ratio)),
665 LayoutCurve::Keyboard => ("keyboard", None),
666 LayoutCurve::Spring(spring) => {
667 physics = Some(spring);
668 ("spring", None)
669 }
670 LayoutCurve::Bezier(points) => {
671 bezier = Some(points);
672 ("bezier", None)
673 }
674 };
675 let property = match t.property {
676 LayoutProperty::Opacity => "opacity",
677 LayoutProperty::Scale => "scaleXY",
678 };
679 let mut o = json!({
680 "type": kind,
681 "property": property,
682 "duration": t.duration_ms,
683 "delay": t.delay_ms,
684 });
685 if let Some(d) = damping {
686 o["springDamping"] = json!(d);
687 }
688 if let Some(points) = bezier {
689 o["bezier"] = json!(points);
690 }
691 if let Some(spring) = physics {
692 o["stiffness"] = json!(spring.stiffness);
693 o["damping"] = json!(spring.damping);
694 o["mass"] = json!(spring.mass);
695 }
696 o
697 };
698 let mut presets = Map::new();
699 for (name, preset) in PRESETS {
700 let duration = [preset.create, preset.update, preset.delete]
701 .iter()
702 .flatten()
703 .map(|t| t.duration_ms + t.delay_ms)
704 .fold(0.0, f32::max);
705 let mut o = Map::new();
706 o.insert("duration".into(), json!(duration));
707 for (key, phase) in [
708 ("create", &preset.create),
709 ("update", &preset.update),
710 ("delete", &preset.delete),
711 ] {
712 if let Some(t) = phase {
713 o.insert(key.into(), transition(t));
714 }
715 }
716 presets.insert((*name).into(), Value::Object(o));
717 }
718 json!({
719 "curves": CURVES
720 .iter()
721 .map(|c| match c.param {
722 Some((p, default)) => json!([c.name, p, default]),
723 None => json!([c.name, null, null]),
724 })
725 .collect::<Vec<_>>(),
726 "presets": presets,
727 "types": LAYOUT_TYPES.iter().map(|t| t.0).collect::<Vec<_>>(),
728 "properties": LAYOUT_PROPERTIES.iter().filter(|p| p.2).map(|p| p.0).collect::<Vec<_>>(),
729 "motions": MOTIONS
730 .iter()
731 .map(|p| (p.name.to_string(), motion_json(p)))
732 .collect::<Map<String, Value>>(),
733 })
734}
735
736#[cfg(test)]
737mod tests {
738 use super::*;
739 use crate::element::animated::JsonInput;
740
741 #[test]
742 fn a_motion_reads_its_spring() {
743 let motion = serde_json::json!({
744 "keyframes": { "opacity": [0, 1] },
745 "spring": { "stiffness": 620, "damping": 36 },
746 });
747 let spec = motion_spec(&JsonInput(Some(&motion))).unwrap();
748 let spring = spec.spring.unwrap();
749 assert_eq!(
750 (spring.stiffness, spring.damping, spring.mass),
751 (620.0, 36.0, 1.0)
752 );
753 let keyframes = serde_json::json!({ "keyframes": { "opacity": [0, 1] }, "spring": 1 });
754 assert_eq!(
755 motion_spec(&JsonInput(Some(&keyframes))).unwrap().spring,
756 None
757 );
758 assert_eq!(motion_spec(&JsonInput(None)), None);
759 }
760}