pretty_text 0.1.0

Core implementation for Bevy Pretty Text
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
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
//! # Parser Syntax
//!
//! **Spans** are ranges of text, denoted with backticks: ``"`...`"``.
//!
//! **Modifiers** are a comma separated collection of effects and styles
//! applied to a **span**. They directly follow a **span** and are contained
//! in square brackets: `"[mod1, ...]"`.
//!
//! ## Effects
//!
//! **Effects** are a modifier that optionally take arguments.
//!
//! ``"`Simple effect`[my_effect]"``
//!
//! ``"`Effect with supplied arguments`[my_effect(10, 4.3)]"``
//!
//! ``"`Multiple effects`[my_effect, another_effect]"``
//!
//! ## Styles
//!
//! **Styles** are a modifier, prefixed with `!`.
//!
//! ``"`Simple style`[!my_style]"``
//!
//! ``"`Multiple styles`[!my_style, !another_style]"``
//!
//! # Type Writer Syntax
//!
//! The [`TypeWriter`](crate::type_writer::TypeWriter) has built-in syntax for
//! sequencing:
//! - Pause: `[seconds]`
//!     - ex: `"Pause[1] between"`
//! - Set relative speed: `<mult>`
//!     - ex: `"<2.0>Fast <0.2>Slow"`
//! - Emit [`TypeWriterEvent`]s: `{my_event}`
//!     - ex: `"Emit an {my_event}event"`
//!
//! And in the special case of the `pretty` macro:
//! - Trigger [`TypeWriterCallback`]s: `{}`
//!     - ex: `pretty!("Trigger a {}callback", |mut commands: Commands| { ... })`
//!
//! # Usage
//!
//! ```
//! # use bevy::prelude::*;
//! # use pretty_text::parser::*;
#![doc = include_str!("../docs/pretty.txt")]
//! # fn parser() -> Result {
//! # let mut world = World::new();
//! #
//! // Basic usage.
//! world.spawn(PrettyTextParser::bundle("my pretty text")?);
//!
//! // Static parsing.
//! world.spawn(pretty!("my pretty text"));
//!
//! // Or, save the text for later...
//! let spans = PrettyTextParser::spans("my pretty text")?;
//!
//! // Which you can be inserted as a component
//! world.spawn(spans);
//! // Or turned into a bundle
//! // world.spawn(spans.into_bundle());
//! # Ok(())
//! # }
//! # parser().unwrap();
//! ```
//!
//! The [`PrettyTextParser`] returns a result that indicates whether or not the
//! syntax is valid. However, the effects and styles are dynamically constructed
//! at run time, so the parser *will not* fail to parse unregistered modifiers.
//!
//! The static parser, similarly, will produce a compiler error if the syntax is
//! invalid, but fails to warn about unregistered modifiers.
//!
//! # ECS Structure
//!
//! The parser produces [`PrettyTextSpans`], which is a collection of
//! [`TextSpanBundle`]s that represent either raw text spans or special type
//! writer sequencing components.
//!
//! [`PrettyTextSpans`] is a component that, when inserted, populates its entity
//! with a [`Text2d`] hierarchy. In many cases you will want to turn it into a
//! bundle directly with [`PrettyTextSpans::into_bundle`].
//!
//! ```
//! # use bevy::prelude::*;
//! # use pretty_text::type_writer::*;
//! # use pretty_text::type_writer::hierarchy::*;
#![doc = include_str!("../docs/pretty.txt")]
//! #
//! # let mut world = World::new();
//! // A simple type writer sequence that speeds up in the middle.
//! world.spawn((
//!     TypeWriter::new(30.0),
//!     pretty!("normal speed <2>doubled speed"),
//! ));
//! ```
//!
//! Internally, this is parsed as two spans with a [`TypeWriterCommand`]
//! in between.
//!
//! ```toml
//!               Speed command
//!               ↓↓↓
//! "normal speed <2>doubled speed"
//!  ^^^^^^^^^^^^^
//!  First span      ^^^^^^^^^^^^^
//!                  Second span
//! ```
//!
//! Which can easily be represented with children:
//!
//! ```
//! # use bevy::prelude::*;
//! # use pretty_text::type_writer::*;
//! # use pretty_text::type_writer::hierarchy::*;
//! #
//! # let mut world = World::new();
//! world.spawn((
//!     TypeWriter::new(30.0),
//!     Text2d::default(),
//!     children![
//!         TextSpan::new("normal speed "), // First span
//!         TypeWriterCommand::Speed(2.0),  // Speed command
//!         TextSpan::new("doubled speed"), // Second span
//!     ]
//! ));
//! ```
//!
//! Note that the spans from [`PrettyTextSpans`] will always be represented
//! as [`TextSpan`] entities, and no text will be placed into the root [`Text2d`]
//! component.
//!
//! This means that inserting materials or effects directly into the component
//! will have unstable results (i.e. usually won't work).
//!
//! ```
//! # use bevy::prelude::*;
//! # use pretty_text::type_writer::*;
//! # use pretty_text::type_writer::hierarchy::*;
#![doc = include_str!("../docs/pretty.txt")]
//! # #[derive(Component, Default)]
//! # struct Shake;
//! #
//! # let mut world = World::new();
//! // This should be avoided!
//! world.spawn((
//!     TypeWriter::new(30.0),
//!     pretty!("normal speed <2>doubled speed"),
//!     Shake::default(),
//! //  ^^^^^ Shake will not apply to any text spans!
//! ));
//! ```

use std::borrow::Cow;

use bevy::prelude::*;

use crate::PrettyText;
use crate::dynamic_effects::PrettyTextEffect;
use crate::style::SpanStyle;
use crate::type_writer::hierarchy::{TypeWriterCallback, TypeWriterCommand, TypeWriterEvent};

/// Dynamically parses pretty text.
///
/// See [`parser`](bevy_pretty_text::parser) for syntax documentation.
///
/// ```
/// # use bevy::prelude::*;
/// # use pretty_text::parser::*;
/// #
/// # fn parser() -> Result {
/// # let mut world = World::new();
/// #
/// // Basic usage.
/// world.spawn(PrettyTextParser::bundle("my pretty text")?);
///
/// // Or, save the text for later...
/// let spans = PrettyTextParser::spans("my pretty text")?;
///
/// // Which you can be inserted as a component
/// world.spawn(spans);
/// // Or turned into a bundle
/// // world.spawn(spans.into_bundle());
/// # Ok(())
/// # }
/// # parser().unwrap();
/// ```
#[derive(Debug)]
pub struct PrettyTextParser;

impl PrettyTextParser {
    /// Parse `pretty_text` into a bundle.
    pub fn bundle(pretty_text: &str) -> Result<impl Bundle, String> {
        Self::spans(pretty_text).map(PrettyTextSpans::into_bundle)
    }

    /// Parse `pretty_text` into a collection of spans.
    pub fn spans(pretty_text: &str) -> Result<PrettyTextSpans, String> {
        sealed::parse_bundles(pretty_text).map(PrettyTextSpans)
    }
}

/// Collection of [text spans](TextSpanBundle).
///
/// Inserting `PrettyTextSpans` into an entity will insert [`Text2d`] and spawn
/// the text spans as children.
///
/// Use [`PrettyTextSpans::into_bundle`] to convert directly into a bundle.
///
/// You can serialize [`PrettyTextSpans`] with the `serialize` feature. Any
/// [`TypeWriterCallback`]s will be skipped. You can emulate callback behaviour
/// with a [`TypeWriterEvent`] and an [`Observer`] or [`EventReader`].
#[derive(Debug, Clone, Component, Reflect)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serialize", reflect(Serialize, Deserialize))]
pub struct PrettyTextSpans(pub Vec<TextSpanBundle>);

impl PrettyTextSpans {
    /// Produce a valid text hierarchy bundle.
    pub fn into_bundle(self) -> impl Bundle {
        (
            PrettyText,
            Text2d::default(),
            Children::spawn(sealed::TextSpanSpawner::from_vec(self.0)),
        )
    }
}

pub(crate) fn pretty_text_spans(
    trigger: Trigger<OnInsert, PrettyTextSpans>,
    mut commands: Commands,
    spans: Query<&PrettyTextSpans>,
) {
    let spans = spans.get(trigger.target()).unwrap();
    commands
        .entity(trigger.target())
        .insert(spans.clone().into_bundle());
}

/// An enumeration of valid bundles in a
/// [type writer sequence](crate::type_writer::hierarchy).
///
/// Useful for storing the entire sequence in a single
/// [collection](PrettyTextSpans).
#[derive(Debug, Clone, Reflect)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serialize", reflect(Serialize, Deserialize))]
pub enum TextSpanBundle {
    /// Span of text with optional modifiers.
    Span {
        /// Range of text.
        span: Span,
        /// One or more [`Modifier`]s applied to `span`.
        mods: Modifiers,
    },
    /// Type writer command.
    Effect(TypeWriterCommand),
    /// Type writer event.
    Event(TypeWriterEvent),
    /// Type writer callback.
    Callback(
        #[cfg_attr(feature = "serialize", serde(skip))]
        #[cfg_attr(feature = "serialize", reflect(skip_serializing))]
        TypeWriterCallback,
    ),
}

impl TextSpanBundle {
    /// Spawn this bundle as a child of `entity`.
    pub fn with_parent(self, entity: &mut EntityCommands) {
        spawn_bundle_with_parent(self, entity);
    }
}

/// Contains a range of text, denoted with backticks: ``"`...`"``.
///
/// This range can contain either raw text or a collection of spans, allowing
/// for recursive parsing.
#[derive(Debug, Clone, Reflect)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serialize", reflect(Serialize, Deserialize))]
#[reflect(no_field_bounds)]
pub enum Span {
    /// Raw text data.
    Text(Cow<'static, str>),
    /// Recursive collection of spans.
    Bundles(Vec<TextSpanBundle>),
}

/// A comma separated collection of [effects](crate::dynamic_effects) and [styles](crate::style)
/// directly following a [`Span`], contained within square brackets: `"[mod1, ...]"`.
#[derive(Debug, Default, Clone, Component, Reflect)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serialize", reflect(Serialize, Deserialize))]
pub struct Modifiers(pub Vec<Modifier>);

/// A [style](crate::style) or [effect](crate::dynamic_effects), contained by
/// [`Modifiers`]:
/// - Effect -> `"name[(arg1, ...)]"`
/// - Style  -> `"!name"`
#[derive(Debug, Clone, Reflect)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serialize", reflect(Serialize, Deserialize))]
pub enum Modifier {
    /// A dynamic effect, e.g. `shake`.
    Effect(PrettyTextEffect),
    /// A [pretty style](crate::style).
    Style(SpanStyle),
}

#[cfg(feature = "proc-macro")]
impl quote::ToTokens for Modifier {
    fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
        use quote::TokenStreamExt;

        tokens.append_all(match self {
            Self::Effect(effect) => {
                quote::quote! {
                    bevy_pretty_text::parser::Modifier::Effect(#effect)
                }
            }
            Self::Style(style) => {
                quote::quote! {
                    bevy_pretty_text::parser::Modifier::Style(#style)
                }
            }
        });
    }
}

fn spawn_bundle_with_parent(bundle: TextSpanBundle, entity: &mut EntityCommands) {
    match bundle {
        TextSpanBundle::Span { span, mods } => match span {
            Span::Text(text) => {
                entity.with_child((PrettyText, TextSpan::new(text), mods));
            }
            Span::Bundles(bundles) => {
                let mut mods = mods.0;
                for bundle in bundles.into_iter() {
                    spawn_bundle_with_parent_recur(bundle, entity, &mut mods);
                }
            }
        },
        TextSpanBundle::Effect(effect) => {
            entity.with_child(effect);
        }
        TextSpanBundle::Event(tag) => {
            entity.with_child(tag);
        }
        TextSpanBundle::Callback(callback) => {
            entity.with_child(callback);
        }
    }
}

fn spawn_bundle_with_parent_recur(
    bundle: TextSpanBundle,
    entity: &mut EntityCommands,
    parent_mods: &mut Vec<Modifier>,
) {
    match bundle {
        TextSpanBundle::Span { span, mods } => match span {
            Span::Text(text) => {
                let mut new_effects = mods.0;
                if !parent_mods.is_empty() {
                    for effect in parent_mods.iter() {
                        new_effects.push(effect.clone());
                    }
                }

                entity.with_child((
                    PrettyText,
                    TextSpan::new(text.as_ref()),
                    Modifiers(new_effects),
                ));
            }
            Span::Bundles(bundles) => {
                let len = mods.0.len();
                parent_mods.extend(mods.0);

                for bundle in bundles.into_iter() {
                    spawn_bundle_with_parent_recur(bundle, entity, parent_mods);
                }

                for _ in 0..len {
                    parent_mods.pop();
                }
            }
        },
        TextSpanBundle::Effect(effect) => {
            entity.with_child(effect);
        }
        TextSpanBundle::Event(tag) => {
            entity.with_child(tag);
        }
        TextSpanBundle::Callback(callback) => {
            entity.with_child(callback);
        }
    }
}

// private parsing module
mod sealed {
    use std::borrow::Cow;

    use bevy::ecs::spawn::SpawnableList;
    use bevy::prelude::*;
    use winnow::combinator::{alt, delimited, fail, opt, preceded, repeat, separated};
    use winnow::error::{ContextError, ErrMode, ParserError, StrContext, StrContextValue};
    use winnow::stream::Stream;
    use winnow::token::take_while;
    use winnow::{Parser, prelude::*};

    use crate::dynamic_effects::PrettyTextEffect;
    use crate::parser::{Modifier, Modifiers};
    use crate::style::SpanStyle;
    use crate::type_writer::hierarchy::{TypeWriterCallback, TypeWriterCommand, TypeWriterEvent};

    use super::{Span, TextSpanBundle};

    pub(super) struct TextSpanSpawner(std::vec::IntoIter<TextSpanBundle>);

    impl TextSpanSpawner {
        pub fn from_vec(spans: Vec<TextSpanBundle>) -> Self {
            Self(spans.into_iter())
        }
    }

    impl SpawnableList<ChildOf> for TextSpanSpawner {
        fn spawn(self, world: &mut World, entity: Entity) {
            let mut commands = world.commands();
            let mut parent = commands.entity(entity);
            for span in self.0 {
                span.with_parent(&mut parent);
            }
        }

        fn size_hint(&self) -> usize {
            self.0.len()
        }
    }

    pub(super) fn parse_bundles(pretty_text: &str) -> Result<Vec<TextSpanBundle>, String> {
        tokenize
            .parse(pretty_text)
            .map_err(|err| err.to_string())
            .and_then(|tokens| {
                parse_tokens.parse(&tokens).map_err(|err| {
                    pretty_print_token_err(pretty_text, err.input(), err.offset(), err.inner())
                })
            })
    }

    fn parse_tokens(input: &mut &[Token]) -> ModalResult<Vec<TextSpanBundle>> {
        repeat::<_, _, Vec<_>, _, _>(1.., text_components).parse_next(input)
    }

    fn text_components(input: &mut &[Token]) -> ModalResult<TextSpanBundle> {
        alt((
            speed,
            pause,
            normal_text,
            styled_effect_text,
            event,
            fail.context(StrContext::Label("item")),
        ))
        .parse_next(input)
    }

    fn speed(input: &mut &[Token]) -> ModalResult<TextSpanBundle> {
        delimited(
            Token::OpenAngle,
            token_str.verify_map(|value| value.parse::<f32>().ok()),
            Token::CloseAngle,
        )
        .map(|speed| TextSpanBundle::Effect(TypeWriterCommand::Speed(speed)))
        .parse_next(input)
    }

    fn pause(input: &mut &[Token]) -> ModalResult<TextSpanBundle> {
        delimited(
            Token::OpenBracket,
            token_str.verify_map(|value| value.parse::<f32>().ok()),
            Token::CloseBracket,
        )
        .map(|dur| TextSpanBundle::Effect(TypeWriterCommand::Pause(dur)))
        .parse_next(input)
    }

    #[derive(Default)]
    struct RawTextAccumulator<'a>(smallvec::SmallVec<[&'a str; 3]>);

    impl<'a> winnow::stream::Accumulate<&'a str> for RawTextAccumulator<'a> {
        fn initial(capacity: Option<usize>) -> Self {
            capacity
                .map(|cap| Self(smallvec::SmallVec::with_capacity(cap)))
                .unwrap_or_default()
        }

        fn accumulate(&mut self, acc: &'a str) {
            self.0.push(acc);
        }
    }

    fn raw_text(input: &mut &[Token]) -> ModalResult<Span> {
        repeat(
            1..,
            alt((
                token_str,
                Token::Bang.map(|_| "!"),
                Token::Comma.map(|_| ","),
                Token::OpenParen.map(|_| "("),
                Token::CloseParen.map(|_| ")"),
                (Token::BackSlash, Token::BackTick).map(|_| "`"),
                (Token::BackSlash, Token::OpenBracket).map(|_| "["),
                (Token::BackSlash, Token::CloseBracket).map(|_| "]"),
                (Token::BackSlash, Token::OpenCurly).map(|_| "{"),
                (Token::BackSlash, Token::CloseCurly).map(|_| "}"),
                (Token::BackSlash, Token::OpenAngle).map(|_| "<"),
                (Token::BackSlash, Token::CloseAngle).map(|_| ">"),
            )),
        )
        .map(|text: RawTextAccumulator| Span::Text(Cow::Owned(text.0.join(""))))
        .parse_next(input)
    }

    fn normal_text(input: &mut &[Token]) -> ModalResult<TextSpanBundle> {
        raw_text
            .map(|span| TextSpanBundle::Span {
                span,
                mods: Modifiers::default(),
            })
            .parse_next(input)
    }

    fn styled_effect_text(input: &mut &[Token]) -> ModalResult<TextSpanBundle> {
        (
            preceded(Token::BackTick, repeat(1.., text_components)),
            Token::BackTick,
            delimited(Token::OpenBracket, mods, Token::CloseBracket),
        )
            .map(|(bundles, _, mods)| TextSpanBundle::Span {
                span: Span::Bundles(bundles),
                mods,
            })
            .parse_next(input)
    }

    fn mods(input: &mut &[Token]) -> ModalResult<Modifiers> {
        let mods = separated(
            1..,
            alt((
                preceded(
                    Token::Bang,
                    token_str
                        .verify(|str: &str| !str.trim().contains(char::is_whitespace))
                        .map(|str| String::from(str.trim()))
                        .context(StrContext::Label("modifier"))
                        .context(StrContext::Expected(StrContextValue::Description(
                            "a single modifier, e.g. `shake`",
                        ))),
                )
                .map(|str| Modifier::Style(SpanStyle::Style(Cow::Owned(str)))),
                (
                    token_str
                        .verify(|str: &str| !str.trim().contains(char::is_whitespace))
                        .map(|str| Cow::Owned(String::from(str.trim())))
                        .context(StrContext::Label("modifier"))
                        .context(StrContext::Expected(StrContextValue::Description(
                            "a single modifier, e.g. `shake`",
                        ))),
                    opt(delimited(
                        Token::OpenParen,
                        separated(
                            1..,
                            token_str
                                .verify(|str: &str| !str.trim().contains(char::is_whitespace))
                                .map(|str| Cow::Owned(String::from(str.trim())))
                                .context(StrContext::Label("effect argument"))
                                .context(StrContext::Expected(StrContextValue::Description(
                                    "comma separated list",
                                ))),
                            Token::Comma,
                        )
                        .map_err(ErrMode::cut),
                        Token::CloseParen
                            .map_err(ErrMode::cut)
                            .context(StrContext::Label("closing delimiter")),
                    ))
                    .map(|args: Option<Vec<Cow<'static, str>>>| args.unwrap_or_default()),
                )
                    .map(|(tag, args)| Modifier::Effect(PrettyTextEffect { tag, args })),
            )),
            (
                Token::Comma,
                opt(token_str.verify(|str: &str| str.chars().all(char::is_whitespace))),
            ),
        )
        .parse_next(input)?;

        if input
            .peek_token()
            .is_none_or(|token| !matches!(token, Token::CloseBracket))
        {
            fail.map_err(ErrMode::cut)
                .context(StrContext::Label("text modifiers"))
                .context(StrContext::Expected(StrContextValue::Description(
                    "comma separated list",
                )))
                .parse_next(input)?;
        }

        Ok(Modifiers(mods))
    }

    fn event(input: &mut &[Token]) -> ModalResult<TextSpanBundle> {
        delimited(Token::OpenCurly, opt(token_str), Token::CloseCurly)
            .map(|tag| {
                tag.map(|tag| TextSpanBundle::Event(TypeWriterEvent(tag.to_string())))
                    .unwrap_or_else(|| TextSpanBundle::Callback(TypeWriterCallback::default()))
            })
            .parse_next(input)
    }

    fn token_str<'a>(input: &mut &'a [Token]) -> ModalResult<&'a str> {
        match input.next_token() {
            Some(Token::Text(str)) => Ok(str),
            _ => fail.parse_next(input),
        }
    }

    impl<'a> Parser<&[Token<'a>], Token<'a>, ErrMode<ContextError>> for Token<'a> {
        fn parse_next(
            &mut self,
            input: &mut &[Token<'a>],
        ) -> winnow::Result<Token<'a>, ErrMode<ContextError>> {
            (input.next_token() == Some(*self))
                .then_some(*self)
                .ok_or_else(|| ParserError::from_input(input))
        }
    }

    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
    enum Token<'a> {
        Text(&'a str),
        BackTick,
        Bang,
        Comma,
        OpenBracket,
        CloseBracket,
        OpenAngle,
        CloseAngle,
        OpenCurly,
        CloseCurly,
        OpenParen,
        CloseParen,
        BackSlash,
    }

    impl Token<'_> {
        fn as_str(&self) -> &str {
            match self {
                Self::Text(str) => str,
                _ => self.as_static_str(),
            }
        }

        fn as_static_str(&self) -> &'static str {
            match self {
                Self::Text(_) => "",
                Self::BackTick => "`",
                Self::Bang => "!",
                Self::Comma => ",",
                Self::OpenBracket => "[",
                Self::CloseBracket => "]",
                Self::OpenAngle => "<",
                Self::CloseAngle => ">",
                Self::OpenCurly => "{",
                Self::CloseCurly => "}",
                Self::OpenParen => "(",
                Self::CloseParen => ")",
                Self::BackSlash => "\\",
            }
        }
    }

    fn tokenize<'a>(input: &mut &'a str) -> ModalResult<Vec<Token<'a>>> {
        repeat(0.., token).parse_next(input)
    }

    fn token<'a>(input: &mut &'a str) -> ModalResult<Token<'a>> {
        let special_tokens = ['`', '!', '[', ']', '<', '>', '{', '}', '(', ')', ',', '\\'];

        alt((
            "`".map(|_| Token::BackTick),
            "!".map(|_| Token::Bang),
            "[".map(|_| Token::OpenBracket),
            "]".map(|_| Token::CloseBracket),
            "<".map(|_| Token::OpenAngle),
            ">".map(|_| Token::CloseAngle),
            "{".map(|_| Token::OpenCurly),
            "}".map(|_| Token::CloseCurly),
            "(".map(|_| Token::OpenParen),
            ")".map(|_| Token::CloseParen),
            ",".map(|_| Token::Comma),
            "\\".map(|_| Token::BackSlash),
            take_while(1.., |c| !special_tokens.contains(&c)).map(Token::Text),
        ))
        .parse_next(input)
    }

    fn pretty_print_token_err(
        str_input: &str,
        input: &[Token],
        offset: usize,
        ctx: &ContextError,
    ) -> String {
        let mut arrow_str = String::new();
        if offset >= input.len() {
            for _ in 0..str_input.len() {
                arrow_str.push(' ');
            }
            arrow_str.push('^');
        } else {
            let location = input[offset];
            let offset = input
                .iter()
                .map(|token| token.as_str().chars().count())
                .take(offset)
                .sum();

            for _ in 0..offset {
                arrow_str.push(' ');
            }
            for _ in offset..offset + location.as_str().chars().count() {
                arrow_str.push('^');
            }
        }

        format!("failed to parse input\n{str_input}\n{arrow_str}\n{ctx}")
    }
}

#[cfg(test)]
mod test {
    use super::*;

    #[track_caller]
    fn assert_ok(str: &str) {
        assert!(PrettyTextParser::bundle(str).is_ok());
    }

    #[track_caller]
    fn assert_err(str: &str) {
        assert!(PrettyTextParser::bundle(str).is_err());
    }

    #[test]
    fn valid_parser_syntax() {
        assert_ok("hello, world!");

        assert_ok("`simple style`[!red]");
        assert_ok("`simple style and effect`[!red, shake]");

        assert_ok("simple{tag} tag");
        assert_ok("`simple{tag} tag and effect`[shake]");

        assert_ok("`effect args`[shake(1, \"str\", 9.232)]");

        assert_ok("`recursive `effect`[wave]`[shake]");
        assert_ok("`recursive `effect`[wave] and `style`[!red]`[shake]");

        assert_ok("escaped \\`\\` ticks");
    }

    #[test]
    fn invalid_parser_syntax() {
        assert_err("`unclosed");
        assert_err("unclosed`");

        assert_err("`unclosed`[wave");
        assert_err("`unclosed`wave]");
        assert_err("`unclosed`[wave(]");
        assert_err("`unclosed`[wave)]");
        assert_err("`no comma`[wave(1 2)]");
        assert_err("`many commas`[wave(1,, 2)]");
        assert_err("`empty mods`[]");

        assert_err("`wave and scramble`[wave(1, 20) scramble][2]");

        assert_err("``unclosed`");
        assert_err("`unclosed``");

        assert_err("unclosed{");
        assert_err("unclosed}");

        assert_err("{`styled`[!red]}");
    }
}