spanda 0.9.2

A general-purpose animation library for Rust — tweening, keyframes, timelines, and physics.
Documentation
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
//! Text splitting for staggered character/word animation.
//!
//! `SplitText` splits a string into characters and words with index metadata,
//! and can generate pre-staggered [`Timeline`]s for each. The DOM injection
//! methods (`inject_chars`, `inject_words`, `detect_lines`) require the
//! `wasm-dom` feature.
//!
//! # Example
//!
//! ```rust
//! use spanda::integrations::split_text::SplitText;
//!
//! let split = SplitText::from_str("Hello world");
//! assert_eq!(split.char_count(), 11);
//! assert_eq!(split.word_count(), 2);
//! ```

use crate::easing::Easing;
use crate::timeline::{Timeline, stagger};
use crate::traits::Animatable;
use crate::tween::Tween;

#[cfg(not(feature = "std"))]
use alloc::{
    string::{String, ToString},
    vec::Vec,
};

/// Configuration options for [`SplitText`].
///
/// GSAP equivalent: SplitText options like `wordDelimiter`, `charsClass`, etc.
#[derive(Debug, Clone)]
pub struct SplitTextOptions {
    /// Custom word delimiter pattern. Default is whitespace.
    ///
    /// GSAP equivalent: `wordDelimiter`.
    pub word_delimiter: Option<String>,

    /// CSS class to apply to character spans.
    ///
    /// GSAP equivalent: `charsClass`.
    pub chars_class: Option<String>,

    /// CSS class to apply to word spans.
    ///
    /// GSAP equivalent: `wordsClass`.
    pub words_class: Option<String>,

    /// CSS class to apply to line spans.
    ///
    /// GSAP equivalent: `linesClass`.
    pub lines_class: Option<String>,

    /// Whether to include whitespace as separate elements.
    ///
    /// If true, spaces become their own spans. Default is false.
    pub split_whitespace: bool,

    /// Whether to preserve original element content for later rebuilding.
    ///
    /// GSAP equivalent: used by `revert()`.
    pub preserve_original: bool,
}

impl Default for SplitTextOptions {
    fn default() -> Self {
        Self {
            word_delimiter: None,
            chars_class: None,
            words_class: None,
            lines_class: None,
            split_whitespace: false,
            preserve_original: true,
        }
    }
}

impl SplitTextOptions {
    /// Create new options with default values.
    pub fn new() -> Self {
        Self::default()
    }

    /// Set a custom word delimiter.
    pub fn word_delimiter(mut self, delimiter: impl Into<String>) -> Self {
        self.word_delimiter = Some(delimiter.into());
        self
    }

    /// Set CSS class for character spans.
    pub fn chars_class(mut self, class: impl Into<String>) -> Self {
        self.chars_class = Some(class.into());
        self
    }

    /// Set CSS class for word spans.
    pub fn words_class(mut self, class: impl Into<String>) -> Self {
        self.words_class = Some(class.into());
        self
    }

    /// Set CSS class for line spans.
    pub fn lines_class(mut self, class: impl Into<String>) -> Self {
        self.lines_class = Some(class.into());
        self
    }

    /// Set whether to split whitespace into separate elements.
    pub fn split_whitespace(mut self, split: bool) -> Self {
        self.split_whitespace = split;
        self
    }

    /// Set whether to preserve original content.
    pub fn preserve_original(mut self, preserve: bool) -> Self {
        self.preserve_original = preserve;
        self
    }
}

/// A single character with index metadata.
#[derive(Debug, Clone)]
pub struct SplitChar {
    /// The character.
    pub ch: char,
    /// Index within the full text (character position).
    pub index: usize,
    /// Which word this character belongs to.
    pub word_index: usize,
}

/// A single word.
#[derive(Debug, Clone)]
pub struct SplitWord {
    /// The word text.
    pub text: String,
    /// Word index (0-based).
    pub index: usize,
    /// First character index in the full text.
    pub char_start: usize,
    /// Exclusive end character index.
    pub char_end: usize,
}

/// Split text into characters and words for staggered animation.
#[derive(Debug, Clone)]
pub struct SplitText {
    chars: Vec<SplitChar>,
    words: Vec<SplitWord>,
    original: String,
    options: SplitTextOptions,
}

impl SplitText {
    /// Split a string into characters and words. Works everywhere (no DOM).
    #[allow(clippy::should_implement_trait)]
    pub fn from_str(text: &str) -> Self {
        Self::from_str_with_options(text, SplitTextOptions::default())
    }

    /// Split a string with custom options.
    ///
    /// GSAP equivalent: `new SplitText(element, { wordDelimiter, ... })`
    pub fn from_str_with_options(text: &str, options: SplitTextOptions) -> Self {
        let mut chars = Vec::new();
        let mut words = Vec::new();
        let mut word_index = 0;
        let mut char_index = 0;

        // Use custom delimiter or default whitespace splitting
        let word_strs: Vec<&str> = if let Some(ref delim) = options.word_delimiter {
            text.split(delim.as_str()).collect()
        } else {
            text.split_whitespace().collect()
        };

        for word_str in word_strs {
            if word_str.is_empty() {
                continue;
            }

            let char_start = text[char_index..]
                .find(word_str)
                .map(|i| i + char_index)
                .unwrap_or(char_index);

            // Add space/delimiter characters between words (if any)
            while char_index < char_start {
                if let Some(ch) = text.chars().nth(char_index) {
                    chars.push(SplitChar {
                        ch,
                        index: char_index,
                        word_index: if word_index > 0 { word_index - 1 } else { 0 },
                    });
                }
                char_index += 1;
            }

            let word_char_start = char_index;
            for ch in word_str.chars() {
                chars.push(SplitChar {
                    ch,
                    index: char_index,
                    word_index,
                });
                char_index += 1;
            }

            words.push(SplitWord {
                text: word_str.to_string(),
                index: word_index,
                char_start: word_char_start,
                char_end: char_index,
            });
            word_index += 1;
        }

        // Remaining characters (trailing spaces)
        while char_index < text.len() {
            if let Some(ch) = text.chars().nth(char_index) {
                chars.push(SplitChar {
                    ch,
                    index: char_index,
                    word_index: if word_index > 0 { word_index - 1 } else { 0 },
                });
            }
            char_index += 1;
        }

        Self {
            chars,
            words,
            original: text.to_string(),
            options,
        }
    }

    /// All split characters.
    pub fn chars(&self) -> &[SplitChar] {
        &self.chars
    }

    /// All split words.
    pub fn words(&self) -> &[SplitWord] {
        &self.words
    }

    /// Total character count (including spaces).
    pub fn char_count(&self) -> usize {
        self.chars.len()
    }

    /// Word count.
    pub fn word_count(&self) -> usize {
        self.words.len()
    }

    /// The original text.
    pub fn original(&self) -> &str {
        &self.original
    }

    /// Get the options used for splitting.
    pub fn options(&self) -> &SplitTextOptions {
        &self.options
    }

    /// Rebuild the split with new options.
    ///
    /// GSAP equivalent: `split.revert()` followed by `new SplitText()`
    pub fn rebuild(&self, options: SplitTextOptions) -> Self {
        Self::from_str_with_options(&self.original, options)
    }

    /// Create a staggered [`Timeline`] for each character.
    ///
    /// Each character gets a `Tween<T>` from `from` to `to` with the given
    /// duration and easing, staggered by `delay` seconds.
    pub fn stagger_chars<T: Animatable + Clone>(
        &self,
        from: T,
        to: T,
        duration: f32,
        delay: f32,
        easing: Easing,
    ) -> Timeline {
        let tweens: Vec<_> = (0..self.chars.len())
            .map(|_| {
                let t = Tween::new(from.clone(), to.clone())
                    .duration(duration)
                    .easing(easing.clone())
                    .build();
                (t, duration)
            })
            .collect();
        stagger(tweens, delay)
    }

    /// Create a staggered [`Timeline`] for each word.
    pub fn stagger_words<T: Animatable + Clone>(
        &self,
        from: T,
        to: T,
        duration: f32,
        delay: f32,
        easing: Easing,
    ) -> Timeline {
        let tweens: Vec<_> = (0..self.words.len())
            .map(|_| {
                let t = Tween::new(from.clone(), to.clone())
                    .duration(duration)
                    .easing(easing.clone())
                    .build();
                (t, duration)
            })
            .collect();
        stagger(tweens, delay)
    }

    /// Wrap each character in a `<span>` inside the parent element.
    ///
    /// Clears the parent's content first, then creates one `<span>` per
    /// character with `display: inline-block` for individual animation.
    /// Space characters become `&nbsp;`.
    ///
    /// If `chars_class` is set in options, applies that CSS class to each span.
    #[cfg(feature = "wasm-dom")]
    pub fn inject_chars(&self, parent: &web_sys::Element) {
        parent.set_inner_html("");
        let doc = web_sys::window().unwrap().document().unwrap();

        for sc in &self.chars {
            let span = doc.create_element("span").unwrap();
            let _ = span.set_attribute("style", "display:inline-block");
            let _ = span.set_attribute("data-char-index", &sc.index.to_string());

            // Apply custom CSS class if set
            if let Some(ref class) = self.options.chars_class {
                let _ = span.set_attribute("class", class);
            }

            if sc.ch == ' ' {
                span.set_inner_html("&nbsp;");
            } else {
                span.set_text_content(Some(&sc.ch.to_string()));
            }
            let _ = parent.append_child(&span);
        }
    }

    /// Wrap each word in a `<span>` inside the parent element.
    ///
    /// Words are separated by spaces. Each `<span>` has `display: inline-block`.
    ///
    /// If `words_class` is set in options, applies that CSS class to each span.
    #[cfg(feature = "wasm-dom")]
    pub fn inject_words(&self, parent: &web_sys::Element) {
        parent.set_inner_html("");
        let doc = web_sys::window().unwrap().document().unwrap();

        for (i, sw) in self.words.iter().enumerate() {
            if i > 0 {
                // Add a space text node between words
                let space = doc.create_text_node(" ");
                let _ = parent.append_child(&space);
            }
            let span = doc.create_element("span").unwrap();
            let _ = span.set_attribute("style", "display:inline-block");
            let _ = span.set_attribute("data-word-index", &sw.index.to_string());

            // Apply custom CSS class if set
            if let Some(ref class) = self.options.words_class {
                let _ = span.set_attribute("class", class);
            }

            span.set_text_content(Some(&sw.text));
            let _ = parent.append_child(&span);
        }
    }

    /// Detect visual lines by comparing `getBoundingClientRect().top` of
    /// injected char spans.
    ///
    /// **Call `inject_chars` first**, then call this on the same container.
    /// Returns groups of character indices, one group per visual line.
    ///
    /// This is expensive — call once, not every frame.
    #[cfg(feature = "wasm-dom")]
    pub fn detect_lines(container: &web_sys::Element) -> Vec<Vec<usize>> {
        let spans = container.children();
        let mut lines: Vec<Vec<usize>> = Vec::new();
        let mut current_top: Option<f32> = None;

        for i in 0..spans.length() {
            if let Some(span) = spans.item(i) {
                let rect = span.get_bounding_client_rect();
                let top = rect.top() as f32;

                match current_top {
                    Some(ct) if (top - ct).abs() < 2.0 => {
                        // Same line
                        if let Some(line) = lines.last_mut() {
                            line.push(i as usize);
                        }
                    }
                    _ => {
                        // New line
                        current_top = Some(top);
                        lines.push(vec![i as usize]);
                    }
                }
            }
        }

        lines
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::traits::Update;

    #[test]
    fn split_basic() {
        let split = SplitText::from_str("Hello world");
        assert_eq!(split.word_count(), 2);
        assert_eq!(split.words()[0].text, "Hello");
        assert_eq!(split.words()[1].text, "world");
    }

    #[test]
    fn split_chars_count() {
        let split = SplitText::from_str("Hi");
        assert_eq!(split.char_count(), 2);
        assert_eq!(split.chars()[0].ch, 'H');
        assert_eq!(split.chars()[1].ch, 'i');
    }

    #[test]
    fn split_empty_string() {
        let split = SplitText::from_str("");
        assert_eq!(split.char_count(), 0);
        assert_eq!(split.word_count(), 0);
    }

    #[test]
    fn split_single_word() {
        let split = SplitText::from_str("Rust");
        assert_eq!(split.word_count(), 1);
        assert_eq!(split.chars()[0].word_index, 0);
    }

    #[test]
    fn stagger_chars_creates_timeline() {
        let split = SplitText::from_str("ABC");
        let mut timeline = split.stagger_chars(0.0_f32, 1.0, 0.5, 0.1, Easing::Linear);
        timeline.play();
        // Should not panic, and should be playable
        timeline.update(0.1);
    }

    #[test]
    fn stagger_words_creates_timeline() {
        let split = SplitText::from_str("One Two Three");
        let mut timeline = split.stagger_words(0.0_f32, 1.0, 0.5, 0.2, Easing::Linear);
        timeline.play();
        timeline.update(0.3);
    }
}