Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
use cap_project::{TextAlign, TextAnimation, TextBackgroundStyle, TextSegment, XY};
/// Text font sizes are authored against a 1080p-tall reference frame and
/// scaled to the output height, so a project renders identically at every
/// export resolution. `size` only positions and wraps the text — it never
/// affects glyph size (that coupling is baked away by the config migration
/// in cap_project).
pub(crate) const REFERENCE_HEIGHT: f32 = 1080.0;
pub const MIN_FONT_SIZE: f32 = 8.0;
pub const MAX_FONT_SIZE: f32 = 480.0;
#[derive(Debug, Clone)]
pub struct PreparedText {
pub track: u32,
pub content: String,
pub bounds: [f32; 4],
pub color: [f32; 4],
pub background_color: Option<[f32; 4]>,
pub font_family: String,
pub font_size: f32,
pub font_weight: f32,
pub italic: bool,
pub opacity: f32,
pub align: TextAlign,
/// Output px, already scaled from the 1080p reference.
pub letter_spacing: f32,
/// Multiplier of `font_size`.
pub line_height: f32,
/// 0..1 drop-shadow strength; 0 disables the shadow pass.
pub shadow: f32,
/// Animation translation in output px, applied to the whole block.
pub offset: [f32; 2],
/// Animation scale about the box center.
pub scale: f32,
/// Outline (output px, colour); `None` when the width is 0.
pub stroke: Option<(f32, [f32; 4])>,
/// 0..1 halo strength in the text colour; 0 disables the glow passes.
pub glow: f32,
/// Right-hand colour of a horizontal gradient that starts at `color`.
pub gradient_color: Option<[f32; 4]>,
pub background_style: TextBackgroundStyle,
/// Fraction of the wrap width left visible by a wipe; 1 = unclipped.
pub wipe: f32,
pub stagger_in: Option<StaggerEdge>,
pub stagger_out: Option<StaggerEdge>,
}
/// One edge of a per-word / per-letter reveal: `progress` runs 0 → 1 toward
/// fully visible, and [`stagger_alpha`] turns it into a unit's alpha.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct StaggerEdge {
pub by_word: bool,
pub progress: f32,
}
/// Every unit gets the same-length window; unit `i` of `n` opens its window
/// at `i / n` of the remaining span so the last unit finishes exactly at 1.
pub fn stagger_alpha(edge: StaggerEdge, unit: usize, units: usize) -> f32 {
if edge.progress >= 1.0 || units == 0 {
return 1.0;
}
const WINDOW: f32 = 0.55;
let start = (unit as f32 / units as f32) * (1.0 - WINDOW);
ease_out_cubic(((edge.progress - start) / WINDOW).clamp(0.0, 1.0))
}
fn parse_color(hex: &str) -> [f32; 4] {
parse_rgb_color(hex).unwrap_or([1.0, 1.0, 1.0, 1.0])
}
fn parse_rgb_color(hex: &str) -> Option<[f32; 4]> {
let color = hex.trim_start_matches('#');
if color.len() == 6
&& color.is_ascii()
&& let (Ok(r), Ok(g), Ok(b)) = (
u8::from_str_radix(&color[0..2], 16),
u8::from_str_radix(&color[2..4], 16),
u8::from_str_radix(&color[4..6], 16),
)
{
return Some([r as f32 / 255.0, g as f32 / 255.0, b as f32 / 255.0, 1.0]);
}
None
}
/// The block-level background behind a text box. A pill widens the side
/// padding and rounds to half its height.
pub(crate) fn background_rect(
bounds: [f32; 4],
laid_out_height: f32,
font_size: f32,
center: [f32; 2],
scale: f32,
offset: [f32; 2],
pill: bool,
) -> ([f32; 4], f32) {
let padding = font_size * 0.2;
let padding_x = if pill { font_size * 0.5 } else { padding };
let left = bounds[0] - padding_x;
let top = bounds[1] - padding;
let right = bounds[2] + padding_x;
let bottom = bounds[1] + (bounds[3] - bounds[1]).max(laid_out_height) + padding;
let [cx, cy] = center;
let transform = |x: f32, y: f32| {
[
cx + (x - cx) * scale + offset[0],
cy + (y - cy) * scale + offset[1],
]
};
let [transformed_left, transformed_top] = transform(left, top);
let [transformed_right, transformed_bottom] = transform(right, bottom);
let width = (transformed_right - transformed_left).max(0.0);
let height = (transformed_bottom - transformed_top).max(0.0);
let radius = if pill {
height * 0.5
} else {
font_size * 0.15 * scale
};
(
[transformed_left, transformed_top, width, height],
radius.min(width * 0.5).min(height * 0.5),
)
}
/// One marker stroke behind a laid-out line: `ink` is the line's glyph extent
/// (left, right) and `line` its top and height, all in unscaled buffer space.
pub(crate) fn highlight_rect(
ink: (f32, f32),
line: (f32, f32),
font_size: f32,
box_center: [f32; 2],
scale: f32,
offset: [f32; 2],
) -> ([f32; 4], f32) {
let padding_x = font_size * 0.12;
let padding_y = font_size * 0.06;
let transform = |x: f32, y: f32| {
[
box_center[0] + (x - box_center[0]) * scale + offset[0],
box_center[1] + (y - box_center[1]) * scale + offset[1],
]
};
let [left, top] = transform(ink.0 - padding_x, line.0 - padding_y);
let [right, bottom] = transform(ink.1 + padding_x, line.0 + line.1 + padding_y);
let width = (right - left).max(0.0);
let height = (bottom - top).max(0.0);
(
[left, top, width, height],
(font_size * 0.12 * scale)
.min(width * 0.5)
.min(height * 0.5),
)
}
fn ease_out_cubic(t: f32) -> f32 {
let t = t.clamp(0.0, 1.0);
1.0 - (1.0 - t).powi(3)
}
fn ease_out_back(t: f32) -> f32 {
let t = t.clamp(0.0, 1.0);
let c1 = 1.70158;
let c3 = c1 + 1.0;
let p = t - 1.0;
1.0 + c3 * p * p * p + c1 * p * p
}
const POP_MIN_SCALE: f32 = 0.8;
const ZOOM_MAX_SCALE: f32 = 1.35;
const BOUNCE_TRAVEL: f32 = 1.25;
/// Extra tracking at the start of a `Tracking` reveal, in em.
const TRACKING_TRAVEL_EM: f32 = 0.35;
#[derive(Debug, Clone, Copy)]
struct AnimSample {
alpha: f32,
offset: [f32; 2],
scale: f32,
/// Fraction of characters visible (typewriter); 1 for other styles.
reveal: f32,
/// Fraction of the width visible (wipe); 1 for other styles.
wipe: f32,
/// Extra letter spacing in em (tracking); 0 for other styles.
tracking: f32,
stagger: Option<StaggerEdge>,
}
const ANIM_REST: AnimSample = AnimSample {
alpha: 1.0,
offset: [0.0, 0.0],
scale: 1.0,
reveal: 1.0,
wipe: 1.0,
tracking: 0.0,
stagger: None,
};
/// `progress` runs 0 → 1 toward fully visible for both edges: time since
/// start over the enter duration, time until end over the exit duration.
/// `direction` is +1 entering and -1 exiting so slides continue through the
/// text's resting position (enter from below, exit above) instead of
/// retracing themselves.
fn sample_animation(
style: TextAnimation,
progress: f32,
direction: f32,
slide_px: f32,
) -> AnimSample {
if progress >= 1.0 {
return ANIM_REST;
}
let eased = ease_out_cubic(progress);
match style {
TextAnimation::None => ANIM_REST,
TextAnimation::Fade => AnimSample {
alpha: eased,
..ANIM_REST
},
TextAnimation::SlideUp => AnimSample {
alpha: eased,
offset: [0.0, direction * (1.0 - eased) * slide_px],
..ANIM_REST
},
TextAnimation::SlideDown => AnimSample {
alpha: eased,
offset: [0.0, -direction * (1.0 - eased) * slide_px],
..ANIM_REST
},
TextAnimation::SlideLeft => AnimSample {
alpha: eased,
offset: [direction * (1.0 - eased) * slide_px, 0.0],
..ANIM_REST
},
TextAnimation::SlideRight => AnimSample {
alpha: eased,
offset: [-direction * (1.0 - eased) * slide_px, 0.0],
..ANIM_REST
},
TextAnimation::Pop => AnimSample {
alpha: eased,
scale: POP_MIN_SCALE + (1.0 - POP_MIN_SCALE) * ease_out_back(progress),
..ANIM_REST
},
TextAnimation::Zoom => AnimSample {
alpha: eased,
scale: ZOOM_MAX_SCALE - (ZOOM_MAX_SCALE - 1.0) * eased,
..ANIM_REST
},
TextAnimation::Bounce => AnimSample {
alpha: eased,
offset: [
0.0,
direction * (1.0 - ease_out_back(progress)) * slide_px * BOUNCE_TRAVEL,
],
..ANIM_REST
},
TextAnimation::Wipe => AnimSample {
wipe: eased,
..ANIM_REST
},
TextAnimation::Words => AnimSample {
stagger: Some(StaggerEdge {
by_word: true,
progress,
}),
..ANIM_REST
},
TextAnimation::Letters => AnimSample {
stagger: Some(StaggerEdge {
by_word: false,
progress,
}),
..ANIM_REST
},
TextAnimation::Tracking => AnimSample {
alpha: eased,
tracking: (1.0 - eased) * TRACKING_TRAVEL_EM,
..ANIM_REST
},
TextAnimation::Typewriter => AnimSample {
reveal: progress,
..ANIM_REST
},
}
}
fn edge_progress(elapsed: f64, duration: f64) -> f32 {
if duration <= 0.0 {
1.0
} else {
(elapsed / duration).clamp(0.0, 1.0) as f32
}
}
/// Truncates to the first `ceil(reveal * chars)` characters on a char
/// boundary, so the typewriter reveal never splits a code point.
fn reveal_content(content: &str, reveal: f32) -> String {
if reveal >= 1.0 {
return content.to_string();
}
let total = content.chars().count();
let visible = ((total as f32) * reveal.max(0.0)).ceil() as usize;
content.chars().take(visible).collect()
}
pub fn prepare_texts(
output_size: XY<u32>,
frame_time: f64,
segments: &[TextSegment],
hidden_indices: &[usize],
) -> Vec<PreparedText> {
let mut prepared = Vec::new();
let height_scale = if output_size.y == 0 {
1.0
} else {
output_size.y as f32 / REFERENCE_HEIGHT
};
let mut ordered = segments
.iter()
.enumerate()
.filter(|(index, segment)| {
segment.enabled
&& !hidden_indices.contains(index)
&& !(frame_time < segment.start || frame_time > segment.end)
})
.collect::<Vec<_>>();
ordered.sort_by_key(|(index, segment)| (segment.track, *index));
for (_, segment) in ordered {
let center = XY::new(
segment.center.x.clamp(0.0, 1.0),
segment.center.y.clamp(0.0, 1.0),
);
let size = XY::new(
segment.size.x.clamp(0.01, 2.0),
segment.size.y.clamp(0.01, 2.0),
);
let width = (size.x * output_size.x as f64).max(1.0) as f32;
let height = (size.y * output_size.y as f64).max(1.0) as f32;
// The box may overhang frame edges (the editor allows dragging up to
// half the box outside); glyphon culls anything past the viewport.
let left = center.x as f32 * output_size.x as f32 - width / 2.0;
let top = center.y as f32 * output_size.y as f32 - height / 2.0;
let right = left + width;
let bottom = top + height;
let font_size = segment.font_size.clamp(MIN_FONT_SIZE, MAX_FONT_SIZE) * height_scale;
let slide_px = font_size * 0.5;
let enter = sample_animation(
segment.animation_in,
edge_progress(frame_time - segment.start, segment.animation_in_duration),
1.0,
slide_px,
);
let exit = sample_animation(
segment.animation_out,
edge_progress(segment.end - frame_time, segment.animation_out_duration),
-1.0,
slide_px,
);
let opacity = segment.opacity.clamp(0.0, 1.0) * enter.alpha * exit.alpha;
if opacity <= 0.0 {
continue;
}
let reveal = enter.reveal.min(exit.reveal);
let cased = if segment.uppercase {
segment.content.to_uppercase()
} else {
segment.content.clone()
};
let content = reveal_content(&cased, reveal);
if content.is_empty() {
continue;
}
let wipe = enter.wipe * exit.wipe;
if wipe <= 0.0 {
continue;
}
let tracking_px = (enter.tracking + exit.tracking) * font_size;
let stroke_px = segment.stroke_width.clamp(0.0, 40.0) * height_scale;
prepared.push(PreparedText {
track: segment.track,
content,
bounds: [left, top, right, bottom],
color: parse_color(&segment.color),
background_color: segment
.background_color
.as_deref()
.and_then(parse_rgb_color),
font_family: segment.font_family.clone(),
font_size,
font_weight: segment.font_weight,
italic: segment.italic,
opacity,
align: segment.align,
letter_spacing: segment.letter_spacing.clamp(-24.0, 240.0) * height_scale + tracking_px,
line_height: segment.line_height.clamp(0.5, 3.0),
shadow: segment.shadow.clamp(0.0, 1.0),
offset: [
enter.offset[0] + exit.offset[0],
enter.offset[1] + exit.offset[1],
],
scale: (enter.scale * exit.scale).max(0.01),
stroke: (stroke_px > 0.0).then(|| (stroke_px, parse_color(&segment.stroke_color))),
glow: segment.glow.clamp(0.0, 1.0),
gradient_color: segment.gradient_color.as_deref().and_then(parse_rgb_color),
background_style: segment.background_style,
wipe,
stagger_in: enter.stagger,
stagger_out: exit.stagger,
});
}
prepared
}
#[cfg(test)]
mod tests {
use super::*;
use cap_project::{TextAnimation, TextLayout};
fn segment(animation_in: TextAnimation, animation_out: TextAnimation) -> TextSegment {
TextSegment {
start: 0.0,
end: 10.0,
track: 0,
enabled: true,
content: "Hello".to_string(),
center: XY::new(0.5, 0.5),
size: XY::new(0.35, 0.2),
font_family: "sans-serif".to_string(),
font_size: 48.0,
font_weight: 700.0,
italic: false,
color: "#ffffff".to_string(),
background_color: None,
background_style: Default::default(),
uppercase: false,
stroke_width: 0.0,
stroke_color: "#000000".to_string(),
gradient_color: None,
glow: 0.0,
fade_duration: 0.15,
align: TextAlign::Center,
letter_spacing: 0.0,
line_height: 1.2,
opacity: 1.0,
shadow: 0.0,
animation_in,
animation_out,
animation_in_duration: 1.0,
animation_out_duration: 1.0,
layout: TextLayout::Overlay,
layout_transition: 0.5,
}
}
#[test]
#[ignore]
fn benchmark_text_preparation() {
use std::{
hash::{DefaultHasher, Hash, Hasher},
hint::black_box,
time::Instant,
};
for (name, total, active, tracks) in [
("empty", 0, 0, 1),
("eight_all_active", 8, 8, 4),
("64_one_active", 64, 1, 4),
("256_four_active", 256, 4, 4),
("1024_four_active", 1024, 4, 4),
("256_all_active", 256, 256, 4),
("256_four_active_single_track", 256, 4, 1),
] {
let segments = (0..total)
.map(|index| {
let mut seg = segment(TextAnimation::None, TextAnimation::None);
seg.track = ((index * 97) % tracks) as u32;
seg.content = format!("Overlay {index}: café 字");
if (index * 97) % total >= active {
seg.start = 20.0 + index as f64;
seg.end = seg.start + 4.0;
}
seg
})
.collect::<Vec<_>>();
let prepare = || {
prepare_texts(
black_box(XY::new(1920, 1080)),
black_box(5.0),
black_box(&segments),
black_box(&[]),
)
};
let output = prepare();
assert_eq!(output.len(), active);
let mut hasher = DefaultHasher::new();
format!("{output:?}").hash(&mut hasher);
let fingerprint = hasher.finish();
let start = Instant::now();
for _ in 0..1000 {
black_box(prepare());
}
let ns_per_call = start.elapsed().as_nanos() as f64 / 1000.0;
let iterations = (20_000_000.0 / ns_per_call).clamp(100.0, 1_000_000.0) as usize;
for sample in 0..15 {
let start = Instant::now();
for _ in 0..iterations {
black_box(prepare());
}
println!(
"TEXT_BENCH {}",
serde_json::json!({
"case": name, "sample": sample, "iterations": iterations,
"ns_per_call": start.elapsed().as_nanos() as f64 / iterations as f64,
"fingerprint": fingerprint,
})
);
}
}
}
fn prepare_one(seg: TextSegment, time: f64) -> Option<PreparedText> {
prepare_texts(XY::new(1920, 1080), time, &[seg], &[])
.into_iter()
.next()
}
#[test]
fn text_layer_order_preserves_hidden_segment_identity() {
let mut front = segment(TextAnimation::None, TextAnimation::None);
front.track = 2;
front.content = "Front".into();
let mut back = front.clone();
back.track = 0;
back.content = "Back".into();
let mut middle = front.clone();
middle.track = 1;
middle.content = "Middle".into();
let segments = [front, back, middle];
let prepared = prepare_texts(XY::new(1920, 1080), 5.0, &segments, &[]);
assert_eq!(
prepared
.iter()
.map(|text| text.content.as_str())
.collect::<Vec<_>>(),
["Back", "Middle", "Front"]
);
assert_eq!(
prepared.iter().map(|text| text.track).collect::<Vec<_>>(),
[0, 1, 2]
);
let hidden = prepare_texts(XY::new(1920, 1080), 5.0, &segments, &[0]);
assert_eq!(
hidden
.iter()
.map(|text| text.content.as_str())
.collect::<Vec<_>>(),
["Back", "Middle"]
);
}
#[test]
fn filtering_preserves_original_indices_order_and_time_comparisons() {
let mut segments = (0..64)
.map(|index| {
let mut seg = segment(TextAnimation::None, TextAnimation::None);
seg.track = ((index * 11) % 7) as u32;
seg.content = format!("Text {index}: café 字");
seg.start = (index % 9) as f64 - 4.0;
seg.end = seg.start + 2.0;
seg.enabled = index % 5 != 0;
seg.uppercase = index % 3 == 0;
seg.center.x = index as f64 / 63.0;
seg.stroke_width = (index % 4) as f32;
seg
})
.collect::<Vec<_>>();
segments[7].start = f64::NAN;
segments[13].end = f64::NAN;
segments[19].end = segments[19].start - 1.0;
segments[31].end = f64::INFINITY;
segments[41].start = f64::NEG_INFINITY;
let hidden = [0, 1, 15, 60, 15, usize::MAX];
for time in [
f64::NEG_INFINITY,
-4.0,
-2.0,
0.0,
2.0,
4.0,
6.0,
f64::INFINITY,
f64::NAN,
] {
for size in [XY::new(1920, 1080), XY::new(0, 0)] {
let mut ordered = segments.iter().enumerate().collect::<Vec<_>>();
ordered.sort_by_key(|(index, seg)| (seg.track, *index));
let mut expected = Vec::new();
for (index, seg) in ordered {
if !seg.enabled || hidden.contains(&index) || time < seg.start || time > seg.end
{
continue;
}
let mut single = prepare_texts(size, time, std::slice::from_ref(seg), &[]);
assert_eq!(single.len(), 1, "segment {index}, time {time}");
expected.append(&mut single);
}
let actual = prepare_texts(size, time, &segments, &hidden);
assert_eq!(
format!("{actual:?}"),
format!("{expected:?}"),
"time {time}"
);
}
}
}
#[test]
fn resting_text_has_identity_animation_state() {
let text = prepare_one(segment(TextAnimation::Fade, TextAnimation::Fade), 5.0).unwrap();
assert_eq!(text.opacity, 1.0);
assert_eq!(text.offset, [0.0, 0.0]);
assert_eq!(text.scale, 1.0);
assert_eq!(text.content, "Hello");
assert_eq!(text.background_color, None);
}
#[test]
fn background_color_is_prepared_and_invalid_colors_are_ignored() {
let mut with_background = segment(TextAnimation::None, TextAnimation::None);
with_background.background_color = Some("#102030".to_string());
let prepared = prepare_one(with_background, 5.0).unwrap();
assert_eq!(
prepared.background_color,
Some([16.0 / 255.0, 32.0 / 255.0, 48.0 / 255.0, 1.0])
);
let mut malformed = segment(TextAnimation::None, TextAnimation::None);
malformed.color = "#ééé".to_string();
malformed.background_color = Some("#ééé".to_string());
let prepared = prepare_one(malformed, 5.0).unwrap();
assert_eq!(prepared.color, [1.0, 1.0, 1.0, 1.0]);
assert_eq!(prepared.background_color, None);
}
#[test]
fn background_rect_expands_authored_bounds_then_transforms_about_center() {
let (rect, radius) = background_rect(
[100.0, 200.0, 300.0, 400.0],
100.0,
50.0,
[200.0, 300.0],
0.5,
[10.0, -20.0],
false,
);
assert_eq!(rect, [155.0, 225.0, 110.0, 110.0]);
assert!((radius - 3.75).abs() < 0.000_001);
}
#[test]
fn pill_background_widens_and_rounds_to_half_height() {
let (rect, radius) = background_rect(
[100.0, 200.0, 300.0, 260.0],
60.0,
50.0,
[200.0, 230.0],
1.0,
[0.0, 0.0],
true,
);
assert_eq!(rect, [75.0, 190.0, 250.0, 80.0]);
assert_eq!(radius, 40.0);
}
#[test]
fn highlight_rect_hugs_one_line_of_ink() {
let (rect, radius) = highlight_rect(
(100.0, 200.0),
(50.0, 60.0),
50.0,
[150.0, 80.0],
1.0,
[0.0, 0.0],
);
assert_eq!(rect, [94.0, 47.0, 112.0, 66.0]);
assert_eq!(radius, 6.0);
}
#[test]
fn slides_enter_from_opposite_sides_and_exit_through() {
let seg = |anim| segment(anim, anim);
let left = prepare_one(seg(TextAnimation::SlideLeft), 0.1).unwrap();
assert!(left.offset[0] > 0.0 && left.offset[1] == 0.0);
let left_exit = prepare_one(seg(TextAnimation::SlideLeft), 9.9).unwrap();
assert!(left_exit.offset[0] < 0.0);
let right = prepare_one(seg(TextAnimation::SlideRight), 0.1).unwrap();
assert!(right.offset[0] < 0.0);
assert!(
prepare_one(seg(TextAnimation::SlideRight), 5.0)
.unwrap()
.offset
== [0.0, 0.0]
);
}
#[test]
fn zoom_starts_large_and_bounce_overshoots_the_rest_position() {
let zoom = prepare_one(segment(TextAnimation::Zoom, TextAnimation::None), 0.05).unwrap();
assert!(zoom.scale > 1.25 && zoom.scale < ZOOM_MAX_SCALE);
assert_eq!(
prepare_one(segment(TextAnimation::Zoom, TextAnimation::None), 5.0)
.unwrap()
.scale,
1.0
);
let early = prepare_one(segment(TextAnimation::Bounce, TextAnimation::None), 0.05).unwrap();
assert!(early.offset[1] > 0.0, "starts below its rest position");
let late = prepare_one(segment(TextAnimation::Bounce, TextAnimation::None), 0.8).unwrap();
assert!(late.offset[1] < 0.0, "overshoots above before settling");
}
#[test]
fn wipe_reveals_width_without_fading() {
let seg = segment(TextAnimation::Wipe, TextAnimation::Wipe);
let half = prepare_one(seg.clone(), 0.5).unwrap();
assert_eq!(half.opacity, 1.0);
assert!(half.wipe > 0.5 && half.wipe < 1.0);
assert_eq!(prepare_one(seg.clone(), 5.0).unwrap().wipe, 1.0);
assert!(prepare_one(seg.clone(), 9.8).unwrap().wipe < 1.0);
assert!(
prepare_one(seg, 0.0).is_none(),
"nothing visible at width 0"
);
}
#[test]
fn words_and_letters_carry_their_edge_progress() {
let seg = segment(TextAnimation::Words, TextAnimation::Letters);
let entering = prepare_one(seg.clone(), 0.25).unwrap();
assert_eq!(
entering.stagger_in,
Some(StaggerEdge {
by_word: true,
progress: 0.25
})
);
assert_eq!(entering.stagger_out, None);
assert_eq!(entering.opacity, 1.0);
assert_eq!(
stagger_alpha(entering.stagger_in.unwrap(), 0, 2),
ease_out_cubic(0.25 / 0.55)
);
assert!(stagger_alpha(entering.stagger_in.unwrap(), 1, 2) < 0.2);
let resting = prepare_one(seg.clone(), 5.0).unwrap();
assert_eq!(resting.stagger_in, None);
let exiting = prepare_one(seg, 9.5).unwrap();
assert_eq!(
exiting.stagger_out,
Some(StaggerEdge {
by_word: false,
progress: 0.5
})
);
}
#[test]
fn tracking_widens_letter_spacing_while_entering() {
let seg = segment(TextAnimation::Tracking, TextAnimation::None);
let entering = prepare_one(seg.clone(), 0.05).unwrap();
let eased = ease_out_cubic(0.05);
let expected = (1.0 - eased) * TRACKING_TRAVEL_EM * 48.0;
assert!((entering.letter_spacing - expected).abs() < 1e-3);
assert_eq!(prepare_one(seg, 5.0).unwrap().letter_spacing, 0.0);
}
#[test]
fn look_fields_are_prepared_and_scaled() {
let mut seg = segment(TextAnimation::None, TextAnimation::None);
seg.uppercase = true;
seg.stroke_width = 4.0;
seg.stroke_color = "#ff0000".to_string();
seg.gradient_color = Some("#0000ff".to_string());
seg.glow = 0.5;
seg.background_style = TextBackgroundStyle::Pill;
let text = prepare_texts(XY::new(3840, 2160), 5.0, &[seg], &[])
.into_iter()
.next()
.unwrap();
assert_eq!(text.content, "HELLO");
assert_eq!(text.stroke, Some((8.0, [1.0, 0.0, 0.0, 1.0])));
assert_eq!(text.gradient_color, Some([0.0, 0.0, 1.0, 1.0]));
assert_eq!(text.glow, 0.5);
assert_eq!(text.background_style, TextBackgroundStyle::Pill);
}
#[test]
fn multiline_background_keeps_the_authored_transform_origin() {
let (rect, _) = background_rect(
[100.0, 200.0, 300.0, 400.0],
300.0,
50.0,
[200.0, 300.0],
0.5,
[10.0, -20.0],
false,
);
assert_eq!(rect, [155.0, 225.0, 110.0, 160.0]);
}
#[test]
fn fade_ramps_in_and_out() {
let early = prepare_one(segment(TextAnimation::Fade, TextAnimation::Fade), 0.25).unwrap();
assert!(early.opacity > 0.0 && early.opacity < 1.0);
let late = prepare_one(segment(TextAnimation::Fade, TextAnimation::Fade), 9.75).unwrap();
assert!(late.opacity > 0.0 && late.opacity < 1.0);
}
#[test]
fn slide_up_enters_from_below_and_exits_above() {
let entering = prepare_one(
segment(TextAnimation::SlideUp, TextAnimation::SlideUp),
0.25,
)
.unwrap();
assert!(entering.offset[1] > 0.0);
let exiting = prepare_one(
segment(TextAnimation::SlideUp, TextAnimation::SlideUp),
9.75,
)
.unwrap();
assert!(exiting.offset[1] < 0.0);
}
#[test]
fn pop_scales_up_from_min() {
let entering = prepare_one(segment(TextAnimation::Pop, TextAnimation::None), 0.05).unwrap();
assert!(entering.scale < 1.0);
assert!(entering.scale >= POP_MIN_SCALE);
}
#[test]
fn typewriter_reveals_characters_over_time() {
let seg = segment(TextAnimation::Typewriter, TextAnimation::None);
let mid = prepare_one(seg.clone(), 0.5).unwrap();
assert!(mid.content.len() < "Hello".len());
assert!(mid.content.starts_with(&seg.content[..1]));
assert_eq!(mid.opacity, 1.0);
let done = prepare_one(seg, 2.0).unwrap();
assert_eq!(done.content, "Hello");
}
#[test]
fn typewriter_start_renders_nothing() {
assert!(
prepare_one(segment(TextAnimation::Typewriter, TextAnimation::None), 0.0).is_none()
);
}
#[test]
fn none_animation_shows_instantly() {
let text = prepare_one(segment(TextAnimation::None, TextAnimation::None), 0.0).unwrap();
assert_eq!(text.opacity, 1.0);
assert_eq!(text.scale, 1.0);
}
#[test]
fn segment_opacity_multiplies_animation_alpha() {
let mut seg = segment(TextAnimation::None, TextAnimation::None);
seg.opacity = 0.5;
let text = prepare_one(seg, 5.0).unwrap();
assert_eq!(text.opacity, 0.5);
}
}