layout/flow/inline/
construct.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
5use std::borrow::Cow;
6use std::char::{ToLowercase, ToUppercase};
7
8use icu_segmenter::WordSegmenter;
9use itertools::izip;
10use style::computed_values::white_space_collapse::T as WhiteSpaceCollapse;
11use style::values::specified::text::TextTransformCase;
12use unicode_bidi::Level;
13
14use super::text_run::TextRun;
15use super::{
16    InlineBox, InlineBoxIdentifier, InlineBoxes, InlineFormattingContext, InlineItem,
17    SharedInlineStyles,
18};
19use crate::cell::ArcRefCell;
20use crate::context::LayoutContext;
21use crate::dom::LayoutBox;
22use crate::dom_traversal::NodeAndStyleInfo;
23use crate::flow::float::FloatBox;
24use crate::formatting_contexts::IndependentFormattingContext;
25use crate::positioned::AbsolutelyPositionedBox;
26use crate::style_ext::ComputedValuesExt;
27
28#[derive(Default)]
29pub(crate) struct InlineFormattingContextBuilder {
30    /// A stack of [`SharedInlineStyles`] including one for the root, one for each inline box on the
31    /// inline box stack, and importantly, one for every `display: contents` element that we are
32    /// currently processing. Normally `display: contents` elements don't affect the structure of
33    /// the [`InlineFormattingContext`], but the styles they provide do style their children.
34    pub shared_inline_styles_stack: Vec<SharedInlineStyles>,
35
36    /// The collection of text strings that make up this [`InlineFormattingContext`] under
37    /// construction.
38    pub text_segments: Vec<String>,
39
40    /// The current offset in the final text string of this [`InlineFormattingContext`],
41    /// used to properly set the text range of new [`InlineItem::TextRun`]s.
42    current_text_offset: usize,
43
44    /// Whether the last processed node ended with whitespace. This is used to
45    /// implement rule 4 of <https://www.w3.org/TR/css-text-3/#collapse>:
46    ///
47    /// > Any collapsible space immediately following another collapsible space—even one
48    /// > outside the boundary of the inline containing that space, provided both spaces are
49    /// > within the same inline formatting context—is collapsed to have zero advance width.
50    /// > (It is invisible, but retains its soft wrap opportunity, if any.)
51    last_inline_box_ended_with_collapsible_white_space: bool,
52
53    /// Whether or not the current state of the inline formatting context is on a word boundary
54    /// for the purposes of `text-transform: capitalize`.
55    on_word_boundary: bool,
56
57    /// Whether or not this inline formatting context will contain floats.
58    pub contains_floats: bool,
59
60    /// The current list of [`InlineItem`]s in this [`InlineFormattingContext`] under
61    /// construction. This is stored in a flat list to make it easy to access the last
62    /// item.
63    pub inline_items: Vec<ArcRefCell<InlineItem>>,
64
65    /// The current [`InlineBox`] tree of this [`InlineFormattingContext`] under construction.
66    pub inline_boxes: InlineBoxes,
67
68    /// The ongoing stack of inline boxes stack of the builder.
69    ///
70    /// Contains all the currently ongoing inline boxes we entered so far.
71    /// The traversal is at all times as deep in the tree as this stack is,
72    /// which is why the code doesn't need to keep track of the actual
73    /// container root (see `handle_inline_level_element`).
74    ///
75    /// When an inline box ends, it's removed from this stack.
76    inline_box_stack: Vec<InlineBoxIdentifier>,
77
78    /// Normally, an inline box produces a single box tree [`InlineItem`]. When a block
79    /// element causes an inline box [to be split], it can produce multiple
80    /// [`InlineItem`]s, all inserted into different [`InlineFormattingContext`]s.
81    /// [`Self::block_in_inline_splits`] is responsible for tracking all of these split
82    /// inline box results, so that they can be inserted into the [`crate::dom::BoxSlot`]
83    /// for the DOM element once it has been processed for BoxTree construction.
84    ///
85    /// [to be split]: https://www.w3.org/TR/CSS2/visuren.html#anonymous-block-level
86    block_in_inline_splits: Vec<Vec<ArcRefCell<InlineItem>>>,
87
88    /// If the [`InlineBox`] of an inline-level element is not damaged, it can be reused
89    /// to support incremental layout. An [`InlineBox`] can be split by block elements
90    /// into multiple [`InlineBox`]es, all inserted into different
91    /// [`InlineFormattingContext`]s. Therefore, [`Self::old_block_in_inline_splits`] is
92    /// used to hold all these split inline boxes from the previous box tree construction
93    /// that are about to be reused, ensuring they can be sequentially inserted into each
94    /// newly built [`InlineFormattingContext`].
95    old_block_in_inline_splits: Vec<Vec<ArcRefCell<InlineBox>>>,
96
97    /// Whether this [`InlineFormattingContextBuilder`] is empty for the purposes of ignoring
98    /// during box tree construction. An IFC is empty if it only contains TextRuns with
99    /// completely collapsible whitespace. When that happens it can be ignored completely.
100    pub is_empty: bool,
101}
102
103impl InlineFormattingContextBuilder {
104    pub(crate) fn new(info: &NodeAndStyleInfo) -> Self {
105        Self::new_for_shared_styles(vec![info.into()])
106    }
107
108    pub(crate) fn new_for_shared_styles(
109        shared_inline_styles_stack: Vec<SharedInlineStyles>,
110    ) -> Self {
111        Self {
112            // For the purposes of `text-transform: capitalize` the start of the IFC is a word boundary.
113            on_word_boundary: true,
114            is_empty: true,
115            shared_inline_styles_stack,
116            ..Default::default()
117        }
118    }
119
120    pub(crate) fn currently_processing_inline_box(&self) -> bool {
121        !self.inline_box_stack.is_empty()
122    }
123
124    fn push_control_character_string(&mut self, string_to_push: &str) {
125        self.text_segments.push(string_to_push.to_owned());
126        self.current_text_offset += string_to_push.len();
127    }
128
129    fn shared_inline_styles(&self) -> SharedInlineStyles {
130        self.shared_inline_styles_stack
131            .last()
132            .expect("Should always have at least one SharedInlineStyles")
133            .clone()
134    }
135
136    pub(crate) fn push_atomic(
137        &mut self,
138        independent_formatting_context_creator: impl FnOnce()
139            -> ArcRefCell<IndependentFormattingContext>,
140        old_layout_box: Option<LayoutBox>,
141    ) -> ArcRefCell<InlineItem> {
142        // If there is an existing undamaged layout box that's compatible, use that.
143        let independent_formatting_context = old_layout_box
144            .and_then(LayoutBox::unsplit_inline_level_layout_box)
145            .and_then(|inline_item| match &*inline_item.borrow() {
146                InlineItem::Atomic(atomic, ..) => Some(atomic.clone()),
147                _ => None,
148            })
149            .unwrap_or_else(independent_formatting_context_creator);
150
151        let inline_level_box = ArcRefCell::new(InlineItem::Atomic(
152            independent_formatting_context,
153            self.current_text_offset,
154            Level::ltr(), /* This will be assigned later if necessary. */
155        ));
156        self.inline_items.push(inline_level_box.clone());
157        self.is_empty = false;
158
159        // Push an object replacement character for this atomic, which will ensure that the line breaker
160        // inserts a line breaking opportunity here.
161        self.push_control_character_string("\u{fffc}");
162
163        self.last_inline_box_ended_with_collapsible_white_space = false;
164        self.on_word_boundary = true;
165
166        inline_level_box
167    }
168
169    pub(crate) fn push_absolutely_positioned_box(
170        &mut self,
171        absolutely_positioned_box_creator: impl FnOnce() -> ArcRefCell<AbsolutelyPositionedBox>,
172        old_layout_box: Option<LayoutBox>,
173    ) -> ArcRefCell<InlineItem> {
174        let absolutely_positioned_box = old_layout_box
175            .and_then(LayoutBox::unsplit_inline_level_layout_box)
176            .and_then(|inline_item| match &*inline_item.borrow() {
177                InlineItem::OutOfFlowAbsolutelyPositionedBox(positioned_box, ..) => {
178                    Some(positioned_box.clone())
179                },
180                _ => None,
181            })
182            .unwrap_or_else(absolutely_positioned_box_creator);
183
184        // We cannot just reuse the old inline item, because the `current_text_offset` may have changed.
185        let inline_level_box = ArcRefCell::new(InlineItem::OutOfFlowAbsolutelyPositionedBox(
186            absolutely_positioned_box,
187            self.current_text_offset,
188        ));
189
190        self.inline_items.push(inline_level_box.clone());
191        self.is_empty = false;
192        inline_level_box
193    }
194
195    pub(crate) fn push_float_box(
196        &mut self,
197        float_box_creator: impl FnOnce() -> ArcRefCell<FloatBox>,
198        old_layout_box: Option<LayoutBox>,
199    ) -> ArcRefCell<InlineItem> {
200        let inline_level_box = old_layout_box
201            .and_then(LayoutBox::unsplit_inline_level_layout_box)
202            .unwrap_or_else(|| ArcRefCell::new(InlineItem::OutOfFlowFloatBox(float_box_creator())));
203
204        debug_assert!(
205            matches!(
206                &*inline_level_box.borrow(),
207                InlineItem::OutOfFlowFloatBox(..),
208            ),
209            "Created float box with incompatible `old_layout_box`"
210        );
211
212        self.inline_items.push(inline_level_box.clone());
213        self.is_empty = false;
214        self.contains_floats = true;
215        inline_level_box
216    }
217
218    pub(crate) fn start_inline_box(
219        &mut self,
220        inline_box_creator: impl FnOnce() -> ArcRefCell<InlineBox>,
221        old_layout_box: Option<LayoutBox>,
222    ) {
223        // If there is an existing undamaged layout box that's compatible, use the `InlineBox` within it.
224        if let Some(LayoutBox::InlineLevel(inline_level_box)) = old_layout_box {
225            let old_block_in_inline_splits: Vec<ArcRefCell<InlineBox>> = inline_level_box
226                .iter()
227                .rev() // reverse to facilitate the `Vec::pop` operation
228                .filter_map(|inline_item| match &*inline_item.borrow() {
229                    InlineItem::StartInlineBox(inline_box) => Some(inline_box.clone()),
230                    _ => None,
231                })
232                .collect();
233
234            debug_assert!(
235                old_block_in_inline_splits.is_empty() ||
236                    old_block_in_inline_splits.len() == inline_level_box.len(),
237                "Create inline box with incompatible `old_layout_box`"
238            );
239
240            self.start_inline_box_internal(inline_box_creator, None, old_block_in_inline_splits);
241        } else {
242            self.start_inline_box_internal(inline_box_creator, None, vec![]);
243        }
244    }
245
246    fn start_inline_box_internal(
247        &mut self,
248        inline_box_creator: impl FnOnce() -> ArcRefCell<InlineBox>,
249        block_in_inline_splits: Option<Vec<ArcRefCell<InlineItem>>>,
250        mut old_block_in_inline_splits: Vec<ArcRefCell<InlineBox>>,
251    ) {
252        let inline_box = old_block_in_inline_splits
253            .pop()
254            .unwrap_or_else(inline_box_creator);
255
256        let borrowed_inline_box = inline_box.borrow();
257        self.push_control_character_string(borrowed_inline_box.base.style.bidi_control_chars().0);
258
259        // Don't push a `SharedInlineStyles` if we are pushing this box when splitting
260        // an IFC for a block-in-inline split. Shared styles are pushed as part of setting
261        // up the second split of the IFC.
262        if borrowed_inline_box.is_first_split {
263            self.shared_inline_styles_stack
264                .push(borrowed_inline_box.shared_inline_styles.clone());
265        }
266        std::mem::drop(borrowed_inline_box);
267
268        let identifier = self.inline_boxes.start_inline_box(inline_box.clone());
269        let inline_level_box = ArcRefCell::new(InlineItem::StartInlineBox(inline_box));
270        self.inline_items.push(inline_level_box.clone());
271        self.inline_box_stack.push(identifier);
272        self.is_empty = false;
273
274        let mut block_in_inline_splits = block_in_inline_splits.unwrap_or_default();
275        block_in_inline_splits.push(inline_level_box);
276        self.block_in_inline_splits.push(block_in_inline_splits);
277
278        self.old_block_in_inline_splits
279            .push(old_block_in_inline_splits);
280    }
281
282    /// End the ongoing inline box in this [`InlineFormattingContextBuilder`], returning
283    /// shared references to all of the box tree items that were created for it. More than
284    /// a single box tree items may be produced for a single inline box when that inline
285    /// box is split around a block-level element.
286    pub(crate) fn end_inline_box(&mut self) -> Vec<ArcRefCell<InlineItem>> {
287        self.shared_inline_styles_stack.pop();
288
289        let (identifier, block_in_inline_splits) = self.end_inline_box_internal();
290        let inline_level_box = self.inline_boxes.get(&identifier);
291        {
292            let mut inline_level_box = inline_level_box.borrow_mut();
293            inline_level_box.is_last_split = true;
294            self.push_control_character_string(inline_level_box.base.style.bidi_control_chars().1);
295        }
296
297        debug_assert!(
298            self.old_block_in_inline_splits
299                .last()
300                .is_some_and(|inline_boxes| inline_boxes.is_empty()),
301            "Reuse incompatible `old_block_in_inline_splits` for inline boxes",
302        );
303        let _ = self.old_block_in_inline_splits.pop();
304
305        block_in_inline_splits.unwrap_or_default()
306    }
307
308    fn end_inline_box_internal(
309        &mut self,
310    ) -> (InlineBoxIdentifier, Option<Vec<ArcRefCell<InlineItem>>>) {
311        let identifier = self
312            .inline_box_stack
313            .pop()
314            .expect("Ended non-existent inline box");
315        self.inline_items
316            .push(ArcRefCell::new(InlineItem::EndInlineBox));
317        self.is_empty = false;
318
319        self.inline_boxes.end_inline_box(identifier);
320
321        // This might be `None` if this builder has already drained its block-in-inline-splits
322        // into the new builder on the other side of a new block-in-inline split.
323        let block_in_inline_splits = self.block_in_inline_splits.pop();
324
325        (identifier, block_in_inline_splits)
326    }
327
328    pub(crate) fn push_text<'dom>(&mut self, text: Cow<'dom, str>, info: &NodeAndStyleInfo<'dom>) {
329        let white_space_collapse = info.style.clone_white_space_collapse();
330        let collapsed = WhitespaceCollapse::new(
331            text.chars(),
332            white_space_collapse,
333            self.last_inline_box_ended_with_collapsible_white_space,
334        );
335
336        // TODO: Not all text transforms are about case, this logic should stop ignoring
337        // TextTransform::FULL_WIDTH and TextTransform::FULL_SIZE_KANA.
338        let text_transform = info.style.clone_text_transform().case();
339        let capitalized_text: String;
340        let char_iterator: Box<dyn Iterator<Item = char>> = match text_transform {
341            TextTransformCase::None => Box::new(collapsed),
342            TextTransformCase::Capitalize => {
343                // `TextTransformation` doesn't support capitalization, so we must capitalize the whole
344                // string at once and make a copy. Here `on_word_boundary` indicates whether or not the
345                // inline formatting context as a whole is on a word boundary. This is different from
346                // `last_inline_box_ended_with_collapsible_white_space` because the word boundaries are
347                // between atomic inlines and at the start of the IFC, and because preserved spaces
348                // are a word boundary.
349                let collapsed_string: String = collapsed.collect();
350                capitalized_text = capitalize_string(&collapsed_string, self.on_word_boundary);
351                Box::new(capitalized_text.chars())
352            },
353            _ => {
354                // If `text-transform` is active, wrap the `WhitespaceCollapse` iterator in
355                // a `TextTransformation` iterator.
356                Box::new(TextTransformation::new(collapsed, text_transform))
357            },
358        };
359
360        let white_space_collapse = info.style.clone_white_space_collapse();
361        let new_text: String = char_iterator
362            .inspect(|&character| {
363                self.is_empty = self.is_empty &&
364                    match white_space_collapse {
365                        WhiteSpaceCollapse::Collapse => character.is_ascii_whitespace(),
366                        WhiteSpaceCollapse::PreserveBreaks => {
367                            character.is_ascii_whitespace() && character != '\n'
368                        },
369                        WhiteSpaceCollapse::Preserve | WhiteSpaceCollapse::BreakSpaces => false,
370                    };
371            })
372            .collect();
373
374        if new_text.is_empty() {
375            return;
376        }
377
378        let selection_range = info.get_selection_range();
379        if let Some(last_character) = new_text.chars().next_back() {
380            self.on_word_boundary = last_character.is_whitespace();
381            self.last_inline_box_ended_with_collapsible_white_space =
382                self.on_word_boundary && white_space_collapse != WhiteSpaceCollapse::Preserve;
383        }
384
385        let new_range = self.current_text_offset..self.current_text_offset + new_text.len();
386        self.current_text_offset = new_range.end;
387        self.text_segments.push(new_text);
388
389        if let Some(inline_item) = self.inline_items.last() {
390            if let InlineItem::TextRun(text_run) = &mut *inline_item.borrow_mut() {
391                text_run.borrow_mut().text_range.end = new_range.end;
392                return;
393            }
394        }
395
396        self.inline_items
397            .push(ArcRefCell::new(InlineItem::TextRun(ArcRefCell::new(
398                TextRun::new(
399                    info.into(),
400                    self.shared_inline_styles(),
401                    new_range,
402                    selection_range,
403                ),
404            ))));
405    }
406
407    pub(crate) fn enter_display_contents(&mut self, shared_inline_styles: SharedInlineStyles) {
408        self.shared_inline_styles_stack.push(shared_inline_styles);
409    }
410
411    pub(crate) fn leave_display_contents(&mut self) {
412        self.shared_inline_styles_stack.pop();
413    }
414
415    pub(crate) fn split_around_block_and_finish(
416        &mut self,
417        layout_context: &LayoutContext,
418        has_first_formatted_line: bool,
419        default_bidi_level: Level,
420    ) -> Option<InlineFormattingContext> {
421        if self.is_empty {
422            return None;
423        }
424
425        // Create a new inline builder which will be active after the block splits this inline formatting
426        // context. It has the same inline box structure as this builder, except the boxes are
427        // marked as not being the first fragment. No inline content is carried over to this new
428        // builder.
429        let mut new_builder = Self::new_for_shared_styles(self.shared_inline_styles_stack.clone());
430
431        let block_in_inline_splits = std::mem::take(&mut self.block_in_inline_splits);
432        let old_block_in_inline_splits = std::mem::take(&mut self.old_block_in_inline_splits);
433        for (identifier, already_collected_inline_boxes, being_recollected_inline_boxes) in izip!(
434            self.inline_box_stack.iter(),
435            block_in_inline_splits,
436            old_block_in_inline_splits
437        ) {
438            // Start a new inline box for every ongoing inline box in this
439            // InlineFormattingContext once we are done processing this block element,
440            // being sure to give the block-in-inline-split to the new
441            // InlineFormattingContext. These will finally be inserted into the DOM's
442            // BoxSlot once the inline box has been fully processed. Meanwhile, being
443            // sure to give the old-block-in-inline-split to new InlineFormattingContext,
444            // so that them will be inserted into each following InlineFormattingContext.
445            let split_inline_box_callback = || {
446                ArcRefCell::new(
447                    self.inline_boxes
448                        .get(identifier)
449                        .borrow()
450                        .split_around_block(),
451                )
452            };
453            new_builder.start_inline_box_internal(
454                split_inline_box_callback,
455                Some(already_collected_inline_boxes),
456                being_recollected_inline_boxes,
457            );
458        }
459        let mut inline_builder_from_before_split = std::mem::replace(self, new_builder);
460
461        // End all ongoing inline boxes in the first builder, but ensure that they are not
462        // marked as the final fragments, so that they do not get inline end margin, borders,
463        // and padding.
464        while !inline_builder_from_before_split.inline_box_stack.is_empty() {
465            inline_builder_from_before_split.end_inline_box_internal();
466        }
467
468        inline_builder_from_before_split.finish(
469            layout_context,
470            has_first_formatted_line,
471            /* is_single_line_text_input = */ false,
472            default_bidi_level,
473        )
474    }
475
476    /// Finish the current inline formatting context, returning [`None`] if the context was empty.
477    pub(crate) fn finish(
478        self,
479        layout_context: &LayoutContext,
480        has_first_formatted_line: bool,
481        is_single_line_text_input: bool,
482        default_bidi_level: Level,
483    ) -> Option<InlineFormattingContext> {
484        if self.is_empty {
485            return None;
486        }
487
488        assert!(self.inline_box_stack.is_empty());
489        debug_assert!(self.old_block_in_inline_splits.is_empty());
490        Some(InlineFormattingContext::new_with_builder(
491            self,
492            layout_context,
493            has_first_formatted_line,
494            is_single_line_text_input,
495            default_bidi_level,
496        ))
497    }
498}
499
500fn preserve_segment_break() -> bool {
501    true
502}
503
504pub struct WhitespaceCollapse<InputIterator> {
505    char_iterator: InputIterator,
506    white_space_collapse: WhiteSpaceCollapse,
507
508    /// Whether or not we should collapse white space completely at the start of the string.
509    /// This is true when the last character handled in our owning [`super::InlineFormattingContext`]
510    /// was collapsible white space.
511    remove_collapsible_white_space_at_start: bool,
512
513    /// Whether or not the last character produced was newline. There is special behavior
514    /// we do after each newline.
515    following_newline: bool,
516
517    /// Whether or not we have seen any non-white space characters, indicating that we are not
518    /// in a collapsible white space section at the beginning of the string.
519    have_seen_non_white_space_characters: bool,
520
521    /// Whether the last character that we processed was a non-newline white space character. When
522    /// collapsing white space we need to wait until the next non-white space character or the end
523    /// of the string to push a single white space.
524    inside_white_space: bool,
525
526    /// When we enter a collapsible white space region, we may need to wait to produce a single
527    /// white space character as soon as we encounter a non-white space character. When that
528    /// happens we queue up the non-white space character for the next iterator call.
529    character_pending_to_return: Option<char>,
530}
531
532impl<InputIterator> WhitespaceCollapse<InputIterator> {
533    pub fn new(
534        char_iterator: InputIterator,
535        white_space_collapse: WhiteSpaceCollapse,
536        trim_beginning_white_space: bool,
537    ) -> Self {
538        Self {
539            char_iterator,
540            white_space_collapse,
541            remove_collapsible_white_space_at_start: trim_beginning_white_space,
542            inside_white_space: false,
543            following_newline: false,
544            have_seen_non_white_space_characters: false,
545            character_pending_to_return: None,
546        }
547    }
548
549    fn is_leading_trimmed_white_space(&self) -> bool {
550        !self.have_seen_non_white_space_characters && self.remove_collapsible_white_space_at_start
551    }
552
553    /// Whether or not we need to produce a space character if the next character is not a newline
554    /// and not white space. This happens when we are exiting a section of white space and we
555    /// waited to produce a single space character for the entire section of white space (but
556    /// not following or preceding a newline).
557    fn need_to_produce_space_character_after_white_space(&self) -> bool {
558        self.inside_white_space && !self.following_newline && !self.is_leading_trimmed_white_space()
559    }
560}
561
562impl<InputIterator> Iterator for WhitespaceCollapse<InputIterator>
563where
564    InputIterator: Iterator<Item = char>,
565{
566    type Item = char;
567
568    fn next(&mut self) -> Option<Self::Item> {
569        // Point 4.1.1 first bullet:
570        // > If white-space is set to normal, nowrap, or pre-line, whitespace
571        // > characters are considered collapsible
572        // If whitespace is not considered collapsible, it is preserved entirely, which
573        // means that we can simply return the input string exactly.
574        if self.white_space_collapse == WhiteSpaceCollapse::Preserve ||
575            self.white_space_collapse == WhiteSpaceCollapse::BreakSpaces
576        {
577            // From <https://drafts.csswg.org/css-text-3/#white-space-processing>:
578            // > Carriage returns (U+000D) are treated identically to spaces (U+0020) in all respects.
579            //
580            // In the non-preserved case these are converted to space below.
581            return match self.char_iterator.next() {
582                Some('\r') => Some(' '),
583                next => next,
584            };
585        }
586
587        if let Some(character) = self.character_pending_to_return.take() {
588            self.inside_white_space = false;
589            self.have_seen_non_white_space_characters = true;
590            self.following_newline = false;
591            return Some(character);
592        }
593
594        while let Some(character) = self.char_iterator.next() {
595            // Don't push non-newline whitespace immediately. Instead wait to push it until we
596            // know that it isn't followed by a newline. See `push_pending_whitespace_if_needed`
597            // above.
598            if character.is_ascii_whitespace() && character != '\n' {
599                self.inside_white_space = true;
600                continue;
601            }
602
603            // Point 4.1.1:
604            // > 2. Collapsible segment breaks are transformed for rendering according to the
605            // >    segment break transformation rules.
606            if character == '\n' {
607                // From <https://drafts.csswg.org/css-text-3/#line-break-transform>
608                // (4.1.3 -- the segment break transformation rules):
609                //
610                // > When white-space is pre, pre-wrap, or pre-line, segment breaks are not
611                // > collapsible and are instead transformed into a preserved line feed"
612                if self.white_space_collapse != WhiteSpaceCollapse::Collapse {
613                    self.inside_white_space = false;
614                    self.following_newline = true;
615                    return Some(character);
616
617                // Point 4.1.3:
618                // > 1. First, any collapsible segment break immediately following another
619                // >    collapsible segment break is removed.
620                // > 2. Then any remaining segment break is either transformed into a space (U+0020)
621                // >    or removed depending on the context before and after the break.
622                } else if !self.following_newline &&
623                    preserve_segment_break() &&
624                    !self.is_leading_trimmed_white_space()
625                {
626                    self.inside_white_space = false;
627                    self.following_newline = true;
628                    return Some(' ');
629                } else {
630                    self.following_newline = true;
631                    continue;
632                }
633            }
634
635            // Point 4.1.1:
636            // > 2. Any sequence of collapsible spaces and tabs immediately preceding or
637            // >    following a segment break is removed.
638            // > 3. Every collapsible tab is converted to a collapsible space (U+0020).
639            // > 4. Any collapsible space immediately following another collapsible space—even
640            // >    one outside the boundary of the inline containing that space, provided both
641            // >    spaces are within the same inline formatting context—is collapsed to have zero
642            // >    advance width.
643            if self.need_to_produce_space_character_after_white_space() {
644                self.inside_white_space = false;
645                self.character_pending_to_return = Some(character);
646                return Some(' ');
647            }
648
649            self.inside_white_space = false;
650            self.have_seen_non_white_space_characters = true;
651            self.following_newline = false;
652            return Some(character);
653        }
654
655        if self.need_to_produce_space_character_after_white_space() {
656            self.inside_white_space = false;
657            return Some(' ');
658        }
659
660        None
661    }
662
663    fn size_hint(&self) -> (usize, Option<usize>) {
664        self.char_iterator.size_hint()
665    }
666
667    fn count(self) -> usize
668    where
669        Self: Sized,
670    {
671        self.char_iterator.count()
672    }
673}
674
675enum PendingCaseConversionResult {
676    Uppercase(ToUppercase),
677    Lowercase(ToLowercase),
678}
679
680impl PendingCaseConversionResult {
681    fn next(&mut self) -> Option<char> {
682        match self {
683            PendingCaseConversionResult::Uppercase(to_uppercase) => to_uppercase.next(),
684            PendingCaseConversionResult::Lowercase(to_lowercase) => to_lowercase.next(),
685        }
686    }
687}
688
689/// This is an iterator that consumes a char iterator and produces character transformed
690/// by the given CSS `text-transform` value. It currently does not support
691/// `text-transform: capitalize` because Unicode segmentation libraries do not support
692/// streaming input one character at a time.
693pub struct TextTransformation<InputIterator> {
694    /// The input character iterator.
695    char_iterator: InputIterator,
696    /// The `text-transform` value to use.
697    text_transform: TextTransformCase,
698    /// If an uppercasing or lowercasing produces more than one character, this
699    /// caches them so that they can be returned in subsequent iterator calls.
700    pending_case_conversion_result: Option<PendingCaseConversionResult>,
701}
702
703impl<InputIterator> TextTransformation<InputIterator> {
704    pub fn new(char_iterator: InputIterator, text_transform: TextTransformCase) -> Self {
705        Self {
706            char_iterator,
707            text_transform,
708            pending_case_conversion_result: None,
709        }
710    }
711}
712
713impl<InputIterator> Iterator for TextTransformation<InputIterator>
714where
715    InputIterator: Iterator<Item = char>,
716{
717    type Item = char;
718
719    fn next(&mut self) -> Option<Self::Item> {
720        if let Some(character) = self
721            .pending_case_conversion_result
722            .as_mut()
723            .and_then(|result| result.next())
724        {
725            return Some(character);
726        }
727        self.pending_case_conversion_result = None;
728
729        for character in self.char_iterator.by_ref() {
730            match self.text_transform {
731                TextTransformCase::None => return Some(character),
732                TextTransformCase::Uppercase => {
733                    let mut pending_result =
734                        PendingCaseConversionResult::Uppercase(character.to_uppercase());
735                    if let Some(character) = pending_result.next() {
736                        self.pending_case_conversion_result = Some(pending_result);
737                        return Some(character);
738                    }
739                },
740                TextTransformCase::Lowercase => {
741                    let mut pending_result =
742                        PendingCaseConversionResult::Lowercase(character.to_lowercase());
743                    if let Some(character) = pending_result.next() {
744                        self.pending_case_conversion_result = Some(pending_result);
745                        return Some(character);
746                    }
747                },
748                // `text-transform: capitalize` currently cannot work on a per-character basis,
749                // so must be handled outside of this iterator.
750                TextTransformCase::Capitalize => return Some(character),
751            }
752        }
753        None
754    }
755}
756
757/// Given a string and whether the start of the string represents a word boundary, create a copy of
758/// the string with letters after word boundaries capitalized.
759pub(crate) fn capitalize_string(string: &str, allow_word_at_start: bool) -> String {
760    let mut output_string = String::new();
761    output_string.reserve(string.len());
762
763    let word_segmenter = WordSegmenter::new_auto();
764    let mut bounds = word_segmenter.segment_str(string).peekable();
765    let mut byte_index = 0;
766    for character in string.chars() {
767        let current_byte_index = byte_index;
768        byte_index += character.len_utf8();
769
770        if let Some(next_index) = bounds.peek() {
771            if *next_index == current_byte_index {
772                bounds.next();
773
774                if current_byte_index != 0 || allow_word_at_start {
775                    output_string.extend(character.to_uppercase());
776                    continue;
777                }
778            }
779        }
780
781        output_string.push(character);
782    }
783
784    output_string
785}