kirei 25.11.10

Askama formatter
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
use std::collections::{BTreeMap, HashMap, HashSet};
use std::ops::{Range, RangeInclusive};

use crate::{
    askama::{self, AskamaNode, ControlTag},
    config::Config,
    html::{self, HtmlNode},
};

#[derive(Debug, Clone)]
pub struct SakuraTree {
    pub config: Config,
    pub leaves: Vec<Leaf>,
    pub rings: Vec<Ring>,
    pub branches: Vec<Branch>,
    twigs: Vec<Twig>,
}

#[derive(Debug, Clone)]
pub enum Leaf {
    AskamaControl {
        content: String,
        tag: ControlTag,
    },
    AskamaExpr {
        content: String,
        space_before: bool,
        space_after: bool,
    },
    AskamaComment(String),

    HtmlStartTag {
        content: String,
        is_inline: bool,
    },
    HtmlVoidTag {
        content: String,
        is_inline: bool,
    },
    HtmlEndTag(String),

    HtmlText(String),
    HtmlEntity(String),
    HtmlRawText(String),
    HtmlComment(String),
    HtmlDoctype(String),
}

#[derive(Debug, Clone)]
pub enum Ring {
    // Compound
    Element(Twig, Option<Vec<Ring>>),
    ControlBlock(Twig, Option<Vec<Ring>>),
    MatchArm(Twig, Option<Vec<Ring>>),
    TextSequence(Twig, Vec<Ring>),

    // Atomic
    RawText(Twig),
    Comment(Twig),
    Other(Twig),
}

// Maps start_leaf index to end_leaf index
#[derive(Debug, Clone, Copy)]
pub struct Twig(usize, usize);

impl Twig {
    #[inline]
    pub fn start(self) -> usize {
        self.0
    }
    #[inline]
    pub fn end(self) -> usize {
        self.1
    }
    #[inline]
    pub fn has_same_idx(self) -> bool {
        self.0 == self.1
    }
    #[inline]
    pub fn indices(self) -> RangeInclusive<usize> {
        self.0..=self.1
    }
}

impl From<usize> for Twig {
    fn from(idx: usize) -> Self {
        Self(idx, idx)
    }
}

impl From<(usize, usize)> for Twig {
    fn from((start, end): (usize, usize)) -> Self {
        Self(start, end)
    }
}

#[derive(Debug, Clone)]
pub struct Branch {
    pub twig: Twig,
    pub style: BranchStyle,
    pub indent: i32,
}

#[derive(Debug, Clone)]
pub enum BranchStyle {
    Inline,
    OpenClose,
    WrappedText,
    MultilineComment,
    Raw,
}

// Askama and HTML nodes relationship map
struct PruneMap {
    askama_in_attrs: HashSet<usize>,                   // Askama indices
    tags_with_askama: HashSet<usize>,                  // Html tag indices
    askama_in_text: HashMap<Range<usize>, Vec<usize>>, // Askama indices
}

impl PruneMap {
    fn new(askama_nodes: &[AskamaNode], html_nodes: &[HtmlNode]) -> Self {
        let askama_in_attrs = Self::find_askama_in_attrs(askama_nodes, html_nodes);
        let tags_with_askama = Self::find_tags_with_askama(askama_nodes, html_nodes);
        let askama_in_text = Self::find_askama_in_text(askama_nodes, html_nodes);

        Self {
            askama_in_attrs,
            tags_with_askama,
            askama_in_text,
        }
    }

    fn find_askama_in_attrs(
        askama_nodes: &[AskamaNode],
        html_nodes: &[HtmlNode],
    ) -> HashSet<usize> {
        html_nodes
            .iter()
            .filter_map(|node| match node {
                HtmlNode::StartTag { range, .. }
                | HtmlNode::Void { range, .. }
                | HtmlNode::SelfClosingTag { range, .. } => Some(range.clone()),
                _ => None,
            })
            .flat_map(|tag| {
                askama_nodes
                    .iter()
                    .enumerate()
                    .filter(move |(_, a)| {
                        a.is_expr() && a.start() >= tag.start && a.end() <= tag.end
                    })
                    .map(|(idx, _)| idx)
            })
            .collect()
    }

    fn find_tags_with_askama(
        askama_nodes: &[AskamaNode],
        html_nodes: &[HtmlNode],
    ) -> HashSet<usize> {
        html_nodes
            .iter()
            .enumerate()
            .filter_map(|(html_idx, node)| match node {
                HtmlNode::StartTag { range, .. }
                | HtmlNode::Void { range, .. }
                | HtmlNode::SelfClosingTag { range, .. } => {
                    let has_askama = askama_nodes
                        .iter()
                        .any(|a| a.start() >= range.start && a.end() <= range.end);
                    has_askama.then_some(html_idx)
                }
                _ => None,
            })
            .collect()
    }

    fn find_askama_in_text(
        askama_nodes: &[AskamaNode],
        html_nodes: &[HtmlNode],
    ) -> HashMap<Range<usize>, Vec<usize>> {
        html_nodes
            .iter()
            .filter_map(|node| match node {
                HtmlNode::Text { range, .. } | HtmlNode::RawText { range, .. } => {
                    Some(range.clone())
                }
                _ => None,
            })
            .filter_map(|range| {
                let indices: Vec<usize> = askama_nodes
                    .iter()
                    .enumerate()
                    .filter(|(_, a)| a.start() >= range.start && a.end() <= range.end)
                    .map(|(idx, _)| idx)
                    .collect();

                (!indices.is_empty()).then_some((range, indices))
            })
            .collect()
    }
}

impl Leaf {
    fn from_askama(config: &Config, askama_node: &AskamaNode, source: &str) -> Self {
        let content = askama::format_askama_node(config, askama_node);

        match askama_node {
            AskamaNode::Control { ctrl_tag, .. } => Self::AskamaControl {
                content,
                tag: *ctrl_tag,
            },
            AskamaNode::Expression { .. } => {
                let start = askama_node.start();
                let end = askama_node.end();

                let space_before = start > 0
                    && source[..start]
                        .chars()
                        .last()
                        .is_some_and(char::is_whitespace);

                let space_after = end < source.len()
                    && source[end..]
                        .chars()
                        .next()
                        .is_some_and(char::is_whitespace);

                Self::AskamaExpr {
                    content,
                    space_before,
                    space_after,
                }
            }
            AskamaNode::Comment { .. } => Self::AskamaComment(content),
        }
    }

    fn from_html(html_node: &HtmlNode) -> Self {
        let source = html_node.to_string();
        match html_node {
            HtmlNode::StartTag { name, .. } => Self::HtmlStartTag {
                content: source,
                is_inline: html::is_inline_tag_name(name),
            },
            HtmlNode::Void { name, .. } | HtmlNode::SelfClosingTag { name, .. } => {
                Self::HtmlVoidTag {
                    content: source,
                    is_inline: html::is_inline_tag_name(name),
                }
            }
            HtmlNode::EndTag { .. } | HtmlNode::ErroneousEndTag { .. } => Self::HtmlEndTag(source),
            HtmlNode::Text { .. } => Self::HtmlText(source),
            HtmlNode::Entity { .. } => Self::HtmlEntity(source),
            HtmlNode::RawText { .. } => Self::HtmlRawText(source),
            HtmlNode::Comment { .. } => Self::HtmlComment(source),
            HtmlNode::Doctype { .. } => Self::HtmlDoctype(source),
        }
    }

    fn is_inline_level(&self) -> bool {
        match self {
            Self::HtmlStartTag { is_inline, .. } | Self::HtmlVoidTag { is_inline, .. } => {
                *is_inline
            }
            Self::HtmlText(_) | Self::HtmlEntity(_) => true,
            _ => false,
        }
    }

    pub fn content(&self) -> &str {
        match self {
            Self::AskamaControl { content, .. }
            | Self::AskamaExpr { content, .. }
            | Self::AskamaComment(content)
            | Self::HtmlStartTag { content, .. }
            | Self::HtmlVoidTag { content, .. }
            | Self::HtmlEndTag(content)
            | Self::HtmlText(content)
            | Self::HtmlEntity(content)
            | Self::HtmlRawText(content)
            | Self::HtmlComment(content)
            | Self::HtmlDoctype(content) => content,
        }
    }

    pub fn is_ctrl(&self) -> bool {
        matches!(self, Self::AskamaControl { .. })
    }

    pub fn is_expr(&self) -> bool {
        matches!(self, Self::AskamaExpr { .. })
    }

    fn is_text_or_expr(&self) -> bool {
        matches!(self, Self::HtmlText(_) | Self::AskamaExpr { .. })
    }

    pub fn chars_count(&self) -> usize {
        self.content().chars().count()
    }

    fn from_text_fragment(fragment: &str, is_raw: bool) -> Self {
        if is_raw {
            // Normalize raw text by trimming newlines and normalizing line-by-line
            // Preserves blank lines (empty after trimming) to maintain user formatting
            Self::HtmlRawText(
                fragment
                    .trim_matches('\n')
                    .lines()
                    .map(str::trim)
                    .collect::<Vec<_>>()
                    .join("\n"),
            )
        } else {
            Self::HtmlText(crate::normalize_whitespace(fragment))
        }
    }
}

impl Branch {
    pub fn grow(twig: Twig, style: BranchStyle, indent: i32) -> Self {
        Self {
            twig,
            style,
            indent,
        }
    }
}

impl SakuraTree {
    pub fn grow(
        askama_nodes: &[AskamaNode],
        html_nodes: &[HtmlNode],
        source: &str,
        config: &Config,
    ) -> Self {
        let mut tree = Self {
            config: config.clone(),
            leaves: Vec::new(),
            rings: Vec::new(),
            branches: Vec::new(),
            twigs: Vec::new(),
        };

        let prune_map = PruneMap::new(askama_nodes, html_nodes);

        let mut leaves: BTreeMap<usize, Leaf> = BTreeMap::new();
        Self::leaves_from_askama(&mut leaves, askama_nodes, &prune_map, source, config);
        Self::leaves_from_html(
            &mut leaves,
            html_nodes,
            askama_nodes,
            &prune_map,
            source,
            config,
        );

        // Build byte-to-leaf map for HTML tags
        let byte_to_leaf_map: HashMap<usize, usize> = leaves
            .iter()
            .enumerate()
            .filter_map(|(leaf_idx, (start, leaf))| {
                matches!(
                    leaf,
                    Leaf::HtmlStartTag { .. } | Leaf::HtmlVoidTag { .. } | Leaf::HtmlEndTag(_)
                )
                .then_some((*start, leaf_idx))
            })
            .collect();

        tree.leaves = leaves.into_values().collect();

        // Initialize twigs with same index for each leaf
        tree.twigs = (0..tree.leaves.len()).map(Twig::from).collect();

        // Update twigs for paired start/end tags
        for html_node in html_nodes {
            if let HtmlNode::StartTag {
                range,
                end_tag_idx: Some(end_html_idx),
                ..
            } = html_node
                && let Some(end_node) = html_nodes.get(*end_html_idx)
            {
                let end_start = end_node.start();

                if let (Some(&start_leaf_idx), Some(&end_leaf_idx)) = (
                    byte_to_leaf_map.get(&range.start),
                    byte_to_leaf_map.get(&end_start),
                ) {
                    tree.twigs[start_leaf_idx] = Twig(start_leaf_idx, end_leaf_idx);
                }
            }
        }

        if let Some(rings) = tree.grow_rings(0, tree.leaves.len()) {
            tree.rings.extend(rings);
        }

        tree
    }

    fn leaves_from_askama(
        leaves: &mut BTreeMap<usize, Leaf>,
        askama_nodes: &[AskamaNode],
        prune_map: &PruneMap,
        source: &str,
        config: &Config,
    ) {
        for (idx, node) in askama_nodes.iter().enumerate() {
            if !prune_map.askama_in_attrs.contains(&idx) {
                leaves.insert(node.start(), Leaf::from_askama(config, node, source));
            }
        }
    }

    fn leaves_from_html(
        leaves: &mut BTreeMap<usize, Leaf>,
        html_nodes: &[HtmlNode],
        askama_nodes: &[AskamaNode],
        prune_map: &PruneMap,
        source: &str,
        config: &Config,
    ) {
        for (idx, node) in html_nodes.iter().enumerate() {
            match node {
                HtmlNode::StartTag { range, name, .. }
                | HtmlNode::Void { range, name, .. }
                | HtmlNode::SelfClosingTag { range, name, .. } => {
                    let leaf = if prune_map.tags_with_askama.contains(&idx) {
                        let content = html::reconstruct_tag(range, source, askama_nodes, config);
                        let is_inline = html::is_inline_tag_name(name);
                        match node {
                            HtmlNode::StartTag { .. } => Leaf::HtmlStartTag { content, is_inline },
                            _ => Leaf::HtmlVoidTag { content, is_inline },
                        }
                    } else {
                        Leaf::from_html(node)
                    };
                    leaves.insert(range.start, leaf);
                }
                HtmlNode::Text { range, text, .. } => {
                    Self::split_text(leaves, range, text, askama_nodes, prune_map, source, false);
                }
                HtmlNode::RawText { range, text, .. } => {
                    Self::split_text(leaves, range, text, askama_nodes, prune_map, source, true);
                }
                _ => {
                    leaves.insert(node.start(), Leaf::from_html(node));
                }
            }
        }
    }

    fn split_text(
        leaves: &mut BTreeMap<usize, Leaf>,
        range: &Range<usize>,
        content: &str,
        askama_nodes: &[AskamaNode],
        prune_map: &PruneMap,
        source: &str,
        is_raw: bool,
    ) {
        let Some(askama_indices) = prune_map.askama_in_text.get(range) else {
            leaves.insert(range.start, Leaf::from_text_fragment(content, is_raw));
            return;
        };

        let mut current_pos = range.start;
        for &idx in askama_indices {
            let askama = &askama_nodes[idx];
            if askama.start() > current_pos {
                let fragment = &source[current_pos..askama.start()];
                leaves.insert(current_pos, Leaf::from_text_fragment(fragment, is_raw));
            }
            current_pos = askama.end();
        }

        if current_pos < range.end {
            let fragment = &source[current_pos..range.end];
            leaves.insert(current_pos, Leaf::from_text_fragment(fragment, is_raw));
        }
    }

    // Grow concentric rings
    fn grow_rings(&self, start_idx: usize, end_idx: usize) -> Option<Vec<Ring>> {
        if start_idx >= end_idx {
            return None;
        }

        let mut rings = Vec::new();
        let mut idx = start_idx;

        while idx < end_idx {
            let leaf = &self.leaves[idx];

            let (ring, next_idx) = match leaf {
                Leaf::AskamaControl { tag, .. } if tag.is_match_arm() => {
                    self.match_arm_with_content(idx, end_idx)
                }
                Leaf::AskamaControl { .. } => self
                    .try_askama_block(idx, end_idx)
                    .unwrap_or_else(|| (self.with_single_leaf(idx), idx + 1)),
                Leaf::HtmlStartTag { .. } => self.handle_start_tag(idx, end_idx),
                Leaf::HtmlRawText(_) => {
                    // Collect consecutive RawText and Askama leaves into one ring
                    let mut last_idx = idx;
                    let mut curr_idx = idx + 1;

                    while curr_idx < end_idx {
                        match &self.leaves[curr_idx] {
                            Leaf::HtmlRawText(_)
                            | Leaf::AskamaExpr { .. }
                            | Leaf::AskamaComment(_) => {
                                last_idx = curr_idx;
                                curr_idx += 1;
                            }
                            _ => break,
                        }
                    }

                    (Ring::RawText((idx, last_idx).into()), curr_idx)
                }
                leaf if leaf.is_text_or_expr() => self
                    .try_text_sequence(idx, end_idx)
                    .unwrap_or_else(|| (self.with_single_leaf(idx), idx + 1)),
                _ => (self.with_single_leaf(idx), idx + 1),
            };

            rings.push(ring);
            idx = next_idx;
        }

        Some(rings)
    }

    fn with_single_leaf(&self, idx: usize) -> Ring {
        let leaf = &self.leaves[idx];
        let twig = idx.into();

        match leaf {
            Leaf::HtmlRawText(_) => Ring::RawText(twig),
            Leaf::HtmlComment(_) | Leaf::AskamaComment(_) => Ring::Comment(twig),
            _ => Ring::Other(twig),
        }
    }

    fn handle_start_tag(&self, idx: usize, end_idx: usize) -> (Ring, usize) {
        let leaf = &self.leaves[idx];

        // Try text sequence for inline elements followed by text/expr
        if leaf.is_inline_level()
            && !self.twigs[idx].has_same_idx()
            && self
                .leaves
                .get(self.twigs[idx].end() + 1)
                .is_some_and(Leaf::is_text_or_expr)
            && let Some(result) = self.try_text_sequence(idx, end_idx)
        {
            return result;
        }

        // Try complete element, or fall back to single leaf
        self.try_complete_element(idx)
            .unwrap_or_else(|| (self.with_single_leaf(idx), idx + 1))
    }

    fn try_complete_element(&self, start_leaf: usize) -> Option<(Ring, usize)> {
        // Get the end_leaf for this element from twigs
        let twig = self.twigs[start_leaf];
        if twig.has_same_idx() {
            return None;
        }
        let end_leaf = twig.end();

        // Recursively grow inner rings
        let inner = self.grow_rings(start_leaf + 1, end_leaf);

        let ring = Ring::Element(twig, inner);

        // Next index for parent is after the end tag
        Some((ring, end_leaf + 1))
    }

    fn try_askama_block(&self, start_idx: usize, end_idx: usize) -> Option<(Ring, usize)> {
        let Leaf::AskamaControl { tag: ctrl_tag, .. } = &self.leaves[start_idx] else {
            return None;
        };

        if !ctrl_tag.is_opening() {
            return None;
        }

        let expected_close = ctrl_tag.matching_close()?;

        // Look for matching close block, tracking nesting depth
        let mut curr_idx = start_idx + 1;
        let mut depth: u32 = 0;

        while curr_idx < end_idx && depth < 200 {
            let leaf = self.leaves.get(curr_idx)?;

            // Check if this is another opening of the same type (nested block)
            if let Leaf::AskamaControl { tag, .. } = leaf
                && ctrl_tag.same_kind(*tag)
                && tag.is_opening()
            {
                depth += 1;
            } else if let Leaf::AskamaControl { tag, .. } = leaf
                && *tag == expected_close
            {
                if depth == 0 {
                    // Found our matching close at depth 0
                    let end_leaf = curr_idx;

                    // Recursively grow inner rings for leaves between open and close indices
                    let inner = self.grow_rings(start_idx + 1, end_leaf);

                    let twig = (start_idx, end_leaf).into();
                    let ring = Ring::ControlBlock(twig, inner);
                    return Some((ring, end_leaf + 1));
                }
                // This closes a nested block, decrement depth
                depth = depth.saturating_sub(1);
            }
            curr_idx += 1;
        }
        // Didn't find a matching close tag
        None
    }

    // Build a when block with its inline content as inner rings
    fn match_arm_with_content(&self, start_idx: usize, end_idx: usize) -> (Ring, usize) {
        let mut curr_idx = start_idx + 1;

        // Find where the content ends
        while curr_idx < end_idx {
            let Some(leaf) = self.leaves.get(curr_idx) else {
                break;
            };

            // Stop at any control block
            if leaf.is_ctrl() {
                break;
            }

            // If start tag, skip to after the end tag
            if let Leaf::HtmlStartTag { .. } = leaf
                && !self.twigs[curr_idx].has_same_idx()
            {
                curr_idx = self.twigs[curr_idx].end() + 1;
                continue;
            }

            curr_idx += 1;
        }

        let content_end_idx = curr_idx;

        // All or nothing
        let twig = (start_idx, content_end_idx - 1).into();
        let temp_ring = Ring::TextSequence(twig, Vec::new());
        let fits = temp_ring.total_chars(self) <= self.config.max_width;

        if fits {
            let inner = self.grow_rings(start_idx + 1, content_end_idx);
            (Ring::MatchArm(start_idx.into(), inner), content_end_idx)
        } else {
            (Ring::MatchArm(start_idx.into(), None), start_idx + 1)
        }
    }

    fn try_text_sequence(&self, start_idx: usize, end_idx: usize) -> Option<(Ring, usize)> {
        let mut last_idx = start_idx;
        let mut curr_idx = start_idx + 1;
        let mut inner_rings = Vec::new();

        // Process first element
        if let Some(leaf) = self.leaves.get(start_idx) {
            if let Leaf::HtmlStartTag { .. } = leaf
                && !self.twigs[start_idx].has_same_idx()
            {
                // Check if complete element fits inline
                let elem_twig = self.twigs[start_idx];
                let elem_width: usize = elem_twig
                    .indices()
                    .filter_map(|i| self.leaves.get(i))
                    .map(Leaf::chars_count)
                    .sum();

                if elem_width > self.config.max_width {
                    return None;
                }

                let elem_inner = self.grow_rings(start_idx + 1, elem_twig.end());
                inner_rings.push(Ring::Element(elem_twig, elem_inner));
                last_idx = elem_twig.end();
                curr_idx = elem_twig.end() + 1;
            } else {
                inner_rings.push(self.with_single_leaf(start_idx));
            }
        }

        // Collect following inline content
        while curr_idx < end_idx {
            let leaf = &self.leaves[curr_idx];

            if let Leaf::HtmlStartTag { .. } = leaf
                && !self.twigs[curr_idx].has_same_idx()
                && leaf.is_inline_level()
            {
                // Check if complete element fits inline
                let elem_twig = self.twigs[curr_idx];
                let elem_width: usize = elem_twig
                    .indices()
                    .filter_map(|i| self.leaves.get(i))
                    .map(Leaf::chars_count)
                    .sum();

                if elem_width > self.config.max_width {
                    break;
                }

                let elem_inner = self.grow_rings(curr_idx + 1, elem_twig.end());
                inner_rings.push(Ring::Element(elem_twig, elem_inner));
                last_idx = elem_twig.end();
                curr_idx = elem_twig.end() + 1;
                continue;
            }

            let can_include = leaf.is_expr() || leaf.is_inline_level();

            if can_include {
                inner_rings.push(self.with_single_leaf(curr_idx));
                last_idx = curr_idx;
                curr_idx += 1;
            } else {
                break;
            }
        }

        (last_idx >= start_idx).then(|| {
            let ring = Ring::TextSequence((start_idx, last_idx).into(), inner_rings);
            (ring, curr_idx)
        })
    }
}

impl Ring {
    pub fn total_chars(&self, tree: &SakuraTree) -> usize {
        self.twig()
            .indices()
            .filter_map(|i| tree.leaves.get(i))
            .map(Leaf::chars_count)
            .sum()
    }

    // Check if any inner rings contain block-level structure
    pub fn has_block(&self, tree: &SakuraTree) -> bool {
        match self {
            Self::Element(_, Some(inner)) => {
                // Check if any inner ring is a block-level element
                inner.iter().any(|node| match node {
                    Self::Element(twig, _) => {
                        let start = twig.start();
                        !tree.leaves[start].is_inline_level()
                    }
                    Self::ControlBlock(_, _) | Self::RawText(_) => true,
                    _ => node.has_block(tree),
                })
            }
            Self::ControlBlock(_, Some(inner)) => inner.iter().any(|node| node.has_block(tree)),
            Self::MatchArm(_, Some(inner)) => inner.iter().any(|node| node.has_block(tree)),
            Self::TextSequence(_, inner) => inner.iter().any(|node| node.has_block(tree)),
            Self::RawText(_) => true,
            _ => false,
        }
    }

    pub fn twig(&self) -> Twig {
        match self {
            Self::Element(twig, _)
            | Self::TextSequence(twig, _)
            | Self::ControlBlock(twig, _)
            | Self::RawText(twig)
            | Self::Comment(twig)
            | Self::Other(twig)
            | Self::MatchArm(twig, None) => *twig,
            Self::MatchArm(twig, Some(inner)) => {
                // Get the last leaf from the last inner ring
                let first = twig.start();
                let last = inner.last().map_or(first, |ring| ring.twig().end());

                (first, last).into()
            }
        }
    }
}