Skip to main content

iced_code_editor/canvas_editor/render/
view.rs

1//! Iced UI view and rendering logic.
2
3use iced::Size;
4use iced::advanced::input_method;
5use iced::alignment;
6use iced::mouse;
7use iced::widget::canvas::Canvas;
8use iced::widget::{
9    Column, MouseArea, Row, Scrollable, Space, container, scrollable, text,
10};
11use iced::{Background, Border, Color, Element, Length, Rectangle, Shadow};
12use iced_aw::ContextMenu;
13
14use super::text::{expand_tabs, expand_tabs_visible};
15use super::wrapping::{self, WrappingCalculator};
16use crate::canvas_editor::features::command_palette::dialog as command_palette_dialog;
17use crate::canvas_editor::features::context_menu;
18use crate::canvas_editor::features::goto_line::dialog as goto_line_dialog;
19use crate::canvas_editor::features::search::dialog as search_dialog;
20use crate::canvas_editor::features::sticky_scroll;
21use crate::canvas_editor::input::ime_requester::ImeRequester;
22use crate::canvas_editor::{CodeEditor, GUTTER_WIDTH, Message, TAB_WIDTH};
23use std::rc::Rc;
24
25/// Horizontal gap in pixels between the gutter and the code text, matching the
26/// offset the canvas text layer uses so pinned headers line up with the code.
27const CODE_TEXT_LEFT_PADDING: f32 = 5.0;
28
29/// Thickness in pixels of the separator drawn under the sticky-scroll headers.
30const STICKY_SEPARATOR_WIDTH: f32 = 1.0;
31
32/// Builds the transparent-container scrollable style shared by the canvas
33/// editor's vertical and horizontal scrollbars.
34fn canvas_scrollbar_style(
35    scrollbar_bg: Color,
36    scroller_color: Color,
37) -> scrollable::Style {
38    scrollable::Style {
39        container: container::Style {
40            background: Some(Background::Color(Color::TRANSPARENT)),
41            ..container::Style::default()
42        },
43        vertical_rail: scrollable_rail(scrollbar_bg, scroller_color, 4.0),
44        horizontal_rail: scrollable_rail(scrollbar_bg, scroller_color, 4.0),
45        gap: None,
46        auto_scroll: scrollable::AutoScroll {
47            background: Color::TRANSPARENT.into(),
48            border: Border::default(),
49            shadow: Shadow::default(),
50            icon: Color::TRANSPARENT,
51        },
52    }
53}
54
55impl CodeEditor {
56    /// Calculates visual lines and canvas height for the editor.
57    ///
58    /// Returns a tuple of (visual_lines, canvas_height) where:
59    /// - visual_lines: The visual line mapping with wrapping applied
60    /// - canvas_height: The total height needed for the canvas
61    fn calculate_canvas_height(&self) -> (Rc<Vec<wrapping::VisualLine>>, f32) {
62        // Reuse memoized visual lines so view layout (canvas height + IME cursor rect)
63        // does not trigger repeated wrapping computation.
64        let visual_lines = self.visual_lines_cached(self.viewport_width);
65        let total_visual_lines = visual_lines.len();
66        let content_height = total_visual_lines as f32 * self.line_height;
67
68        // Use max of content height and viewport height to ensure the canvas
69        // always covers the visible area (prevents visual artifacts when
70        // content is shorter than viewport after reset/file change)
71        let canvas_height = content_height.max(self.viewport_height);
72
73        (visual_lines, canvas_height)
74    }
75
76    /// Creates the scrollable style function with custom colors.
77    ///
78    /// Returns a style function that configures the scrollbar appearance.
79    fn create_scrollable_style(
80        &self,
81    ) -> impl Fn(&iced::Theme, scrollable::Status) -> scrollable::Style {
82        let scrollbar_bg = self.style.scrollbar_background;
83        let scroller_color = self.style.scroller_color;
84
85        move |_theme, _status| {
86            canvas_scrollbar_style(scrollbar_bg, scroller_color)
87        }
88    }
89
90    /// Creates the canvas widget wrapped in a scrollable container.
91    ///
92    /// # Arguments
93    ///
94    /// * `canvas_height` - The total height of the canvas
95    ///
96    /// # Returns
97    ///
98    /// A configured scrollable widget containing the canvas
99    fn create_canvas_with_scrollable(
100        &self,
101        canvas_height: f32,
102    ) -> Scrollable<'_, Message> {
103        let canvas = Canvas::new(self)
104            .width(Length::Fill)
105            .height(Length::Fixed(canvas_height));
106
107        Scrollable::new(canvas)
108            .id(self.scrollable_id.clone())
109            .width(Length::Fill)
110            .height(Length::Fill)
111            .on_scroll(Message::Scrolled)
112            .style(self.create_scrollable_style())
113    }
114
115    /// Creates the horizontal scrollbar element when wrap is disabled and content overflows.
116    ///
117    /// # Arguments
118    ///
119    /// * `max_content_width` - The total pixel width of the widest line
120    ///
121    /// # Returns
122    ///
123    /// `Some(element)` if a horizontal scrollbar is needed, `None` otherwise
124    fn create_horizontal_scrollbar(
125        &self,
126        max_content_width: f32,
127    ) -> Option<Element<'_, Message>> {
128        if self.wrap_enabled || max_content_width <= self.viewport_width {
129            return None;
130        }
131
132        let scrollbar_bg = self.style.scrollbar_background;
133        let scroller_color = self.style.scroller_color;
134
135        let h_scrollable = Scrollable::new(
136            Space::new().width(Length::Fixed(max_content_width)).height(0.0),
137        )
138        .id(self.horizontal_scrollable_id.clone())
139        .width(Length::Fill)
140        .height(Length::Fixed(12.0))
141        .direction(scrollable::Direction::Horizontal(
142            scrollable::Scrollbar::new(),
143        ))
144        .on_scroll(Message::HorizontalScrolled)
145        .style(move |_theme, _status| {
146            canvas_scrollbar_style(scrollbar_bg, scroller_color)
147        });
148
149        Some(h_scrollable.into())
150    }
151
152    /// Creates the gutter background container if line numbers are enabled.
153    ///
154    /// # Returns
155    ///
156    /// Some(container) if line numbers are enabled, None otherwise
157    fn create_gutter_container(
158        &self,
159    ) -> Option<container::Container<'_, Message>> {
160        if self.line_numbers_enabled {
161            let gutter_background = self.style.gutter_background;
162            Some(
163                container(
164                    Space::new().width(Length::Fill).height(Length::Fill),
165                )
166                .width(Length::Fixed(GUTTER_WIDTH))
167                .height(Length::Fill)
168                .style(move |_| container::Style {
169                    background: Some(Background::Color(gutter_background)),
170                    ..container::Style::default()
171                }),
172            )
173        } else {
174            None
175        }
176    }
177
178    /// Creates the code area background container.
179    ///
180    /// # Returns
181    ///
182    /// The code background container widget
183    fn create_code_background_container(
184        &self,
185    ) -> container::Container<'_, Message> {
186        let background_color = self.style.background;
187        container(Space::new().width(Length::Fill).height(Length::Fill))
188            .width(Length::Fill)
189            .height(Length::Fill)
190            .style(move |_| container::Style {
191                background: Some(Background::Color(background_color)),
192                ..container::Style::default()
193            })
194    }
195
196    /// Creates the fixed Vim status and command line shown below the editor.
197    fn create_vim_status_bar(&self) -> Element<'_, Message> {
198        let (left_text, right_text) = self.vim_state.status_line_text();
199        let background = self.style.gutter_background;
200        let text_color = self.style.text_color;
201
202        container(
203            Row::new()
204                .push(
205                    text(left_text).size(self.font_size).style(move |_| {
206                        text::Style { color: Some(text_color) }
207                    }),
208                )
209                .push(Space::new().width(Length::Fill))
210                .push(
211                    text(right_text).size(self.font_size).style(move |_| {
212                        text::Style { color: Some(text_color) }
213                    }),
214                ),
215        )
216        .padding([2, 8])
217        .width(Length::Fill)
218        .height(Length::Fixed(self.line_height.max(20.0)))
219        .style(move |_| container::Style {
220            background: Some(Background::Color(background)),
221            ..container::Style::default()
222        })
223        .into()
224    }
225
226    /// Creates the background layer combining gutter and code backgrounds.
227    ///
228    /// # Returns
229    ///
230    /// A row containing the background elements
231    fn create_background_layer(&self) -> Row<'_, Message> {
232        let gutter_container = self.create_gutter_container();
233        let code_background_container = self.create_code_background_container();
234
235        if let Some(gutter) = gutter_container {
236            Row::new().push(gutter).push(code_background_container)
237        } else {
238            Row::new().push(code_background_container)
239        }
240    }
241
242    /// Calculates the IME cursor rectangle for the current cursor position.
243    ///
244    /// # Arguments
245    ///
246    /// * `visual_lines` - The visual line mapping
247    ///
248    /// # Returns
249    ///
250    /// A rectangle representing the cursor position for IME
251    fn calculate_ime_cursor_rect(
252        &self,
253        visual_lines: &[wrapping::VisualLine],
254    ) -> Rectangle {
255        let ime_enabled = self.is_focused() && self.has_canvas_focus;
256
257        if !ime_enabled {
258            return Rectangle::new(
259                iced::Point::new(0.0, 0.0),
260                Size::new(0.0, 0.0),
261            );
262        }
263
264        if let Some(cursor_visual) = WrappingCalculator::logical_to_visual(
265            visual_lines,
266            self.cursors.primary_position().0,
267            self.cursors.primary_position().1,
268        ) {
269            let vl = &visual_lines[cursor_visual];
270            let line_content = self.buffer.line(vl.logical_line);
271            let prefix_len =
272                self.cursors.primary_position().1.saturating_sub(vl.start_col);
273            let prefix_text: String = line_content
274                .chars()
275                .skip(vl.start_col)
276                .take(prefix_len)
277                .collect();
278            let cursor_x = self.gutter_width()
279                + 5.0
280                + crate::canvas_editor::measure_text_width(
281                    &prefix_text,
282                    self.full_char_width,
283                    self.char_width,
284                )
285                - self.horizontal_scroll_offset;
286
287            // Calculate visual Y position relative to the viewport
288            // We subtract viewport_scroll because the content is scrolled up/down
289            // but the cursor position sent to IME must be relative to the visible area
290            let cursor_y = (cursor_visual as f32 * self.line_height)
291                - self.viewport_scroll;
292
293            Rectangle::new(
294                iced::Point::new(cursor_x, cursor_y + 2.0),
295                Size::new(2.0, self.line_height - 4.0),
296            )
297        } else {
298            Rectangle::new(iced::Point::new(0.0, 0.0), Size::new(0.0, 0.0))
299        }
300    }
301
302    /// Builds one pinned header row: its line number, then its colored text.
303    ///
304    /// The row reuses the memoized per-line highlight spans, so pinning a header
305    /// costs no extra syntect work. Unlike the canvas text layer, it ignores
306    /// `horizontal_scroll_offset`: a pinned header exists to be read, and would
307    /// be useless if it scrolled out of view sideways.
308    ///
309    /// # Arguments
310    ///
311    /// * `line` - Index of the logical header line to render
312    /// * `syntax_set` - The syntax set `syntax` belongs to
313    /// * `syntax` - The syntect syntax definition to tokenize with
314    /// * `theme` - The syntect theme providing token colors
315    fn create_sticky_header_row(
316        &self,
317        line: usize,
318        syntax_set: &syntect::parsing::SyntaxSet,
319        syntax: &syntect::parsing::SyntaxReference,
320        theme: &syntect::highlighting::Theme,
321    ) -> Element<'_, Message> {
322        let font = self.font;
323        let font_size = self.font_size;
324        let line_number_color = self.style.line_number_color;
325
326        let mut row = Row::new();
327
328        if self.line_numbers_enabled {
329            row = row.push(
330                container(
331                    text(format!("{}", line + 1))
332                        .size(font_size)
333                        .font(font)
334                        .style(move |_| text::Style {
335                            color: Some(line_number_color),
336                        }),
337                )
338                .width(Length::Fixed(self.line_number_gutter_width()))
339                .align_x(alignment::Horizontal::Center),
340            );
341        }
342
343        // Keep the fold margin empty: a pinned header is not where the user
344        // folds, and a chevron there would invite a click that does nothing.
345        row = row
346            .push(Space::new().width(Length::Fixed(self.fold_margin_width())));
347        row =
348            row.push(Space::new().width(Length::Fixed(CODE_TEXT_LEFT_PADDING)));
349
350        let spans =
351            self.highlighted_line_cached(line, syntax, theme, syntax_set);
352        let mut code = Row::new();
353        for (color, content) in spans.iter() {
354            let color = *color;
355            // Match the canvas text layer, so a pinned header shows the same
356            // whitespace glyphs as the line it mirrors.
357            let content = if self.show_whitespace {
358                expand_tabs_visible(content, TAB_WIDTH)
359            } else {
360                expand_tabs(content, TAB_WIDTH).into_owned()
361            };
362            code = code.push(
363                text(content)
364                    .size(font_size)
365                    .font(font)
366                    .wrapping(text::Wrapping::None)
367                    .style(move |_| text::Style { color: Some(color) }),
368            );
369        }
370        row = row.push(code);
371
372        MouseArea::new(
373            container(row)
374                .width(Length::Fill)
375                .height(Length::Fixed(self.line_height))
376                .clip(true),
377        )
378        .interaction(mouse::Interaction::Pointer)
379        .on_press(Message::StickyScrollJump(line))
380        .into()
381    }
382
383    /// Creates the sticky-scroll layer: the headers of the blocks enclosing the
384    /// topmost visible line, pinned above the viewport.
385    ///
386    /// # Arguments
387    ///
388    /// * `visual_lines` - The visual line mapping, used to resolve the topmost
389    ///   visible visual line back to its logical line
390    ///
391    /// # Returns
392    ///
393    /// `Some(layer)` when at least one header must be pinned, `None` when the
394    /// feature is disabled or the topmost visible line sits at the top level
395    fn create_sticky_scroll_layer(
396        &self,
397        visual_lines: &[wrapping::VisualLine],
398    ) -> Option<Element<'_, Message>> {
399        if !self.sticky_scroll_enabled || self.line_height <= 0.0 {
400            return None;
401        }
402
403        // Same first-visible-line formula the canvas layer uses. The topmost
404        // entry is a *visual* line, so it must be mapped back to a logical one:
405        // wrapping and collapsed folds make the two indices diverge.
406        let first_visible =
407            (self.viewport_scroll / self.line_height).floor() as usize;
408        let top_line = visual_lines.get(first_visible)?.logical_line;
409
410        // `block_regions`, not `foldable_regions`: the blocks a line sits in
411        // are a property of the buffer, not of whether the user may collapse
412        // them. Sticky scroll keeps working with code folding turned off.
413        let regions = self.block_regions();
414        let headers = sticky_scroll::sticky_headers(
415            &regions,
416            top_line,
417            sticky_scroll::DEFAULT_MAX_STICKY_LINES,
418        );
419        if headers.is_empty() {
420            return None;
421        }
422
423        let (syntax_set, syntax, theme) = self.resolve_syntax();
424        let (Some(syntax), Some(theme)) = (syntax, theme) else {
425            return None;
426        };
427
428        let mut column = Column::new();
429        for line in headers {
430            column = column.push(
431                self.create_sticky_header_row(line, syntax_set, syntax, theme),
432            );
433        }
434
435        let background = self.style.gutter_background;
436        let border_color = self.style.gutter_border;
437
438        // An explicit rule rather than a container shadow: it must sit exactly
439        // one pixel under the last header, on top of the code scrolling beneath.
440        let column = column.push(
441            container(Space::new().width(Length::Fill).height(Length::Fill))
442                .width(Length::Fill)
443                .height(Length::Fixed(STICKY_SEPARATOR_WIDTH))
444                .style(move |_| container::Style {
445                    background: Some(Background::Color(border_color)),
446                    ..container::Style::default()
447                }),
448        );
449
450        Some(
451            container(column)
452                .width(Length::Fill)
453                .height(Length::Shrink)
454                .style(move |_| container::Style {
455                    background: Some(Background::Color(background)),
456                    ..container::Style::default()
457                })
458                .into(),
459        )
460    }
461
462    /// Creates the IME (Input Method Editor) layer widget.
463    ///
464    /// # Arguments
465    ///
466    /// * `cursor_rect` - The rectangle representing the cursor position
467    ///
468    /// # Returns
469    ///
470    /// An element containing the IME requester widget
471    fn create_ime_layer(&self, cursor_rect: Rectangle) -> Element<'_, Message> {
472        let ime_enabled = self.is_focused() && self.has_canvas_focus;
473
474        let preedit =
475            self.ime_preedit.as_ref().map(|p| input_method::Preedit {
476                content: p.content.clone(),
477                selection: p.selection.clone(),
478                text_size: None,
479            });
480
481        let ime_layer = ImeRequester::new(ime_enabled, cursor_rect, preedit);
482        iced::Element::new(ime_layer)
483    }
484
485    /// Creates the view element with scrollable wrapper.
486    ///
487    /// The backgrounds (editor and gutter) are handled by container styles
488    /// to ensure proper clipping when the pane is resized.
489    ///
490    /// Call this from the host application's `view`, mapping the editor's
491    /// [`Message`] into the host's own message type.
492    ///
493    /// # Returns
494    ///
495    /// An `Element` rendering the editor, its gutter, and any open overlay
496    ///
497    /// # Example
498    ///
499    /// ```
500    /// use iced::Element;
501    /// use iced_code_editor::{CodeEditor, Message};
502    ///
503    /// /// The host application's own message type.
504    /// #[derive(Debug, Clone)]
505    /// enum AppMessage {
506    ///     Editor(Message),
507    /// }
508    ///
509    /// fn view(editor: &CodeEditor) -> Element<'_, AppMessage> {
510    ///     editor.view().map(AppMessage::Editor)
511    /// }
512    /// ```
513    pub fn view(&self) -> Element<'_, Message> {
514        // Calculate canvas height and visual lines
515        let (visual_lines, canvas_height) = self.calculate_canvas_height();
516
517        // Create scrollable containing the canvas
518        let scrollable = self.create_canvas_with_scrollable(canvas_height);
519
520        // Create background layer with gutter and code backgrounds
521        let background_row = self.create_background_layer();
522
523        // Build editor stack: backgrounds + scrollable
524        let mut editor_stack =
525            iced::widget::Stack::new().push(background_row).push(scrollable);
526
527        // Pin the enclosing block headers above the viewport. This goes right
528        // above the scrollable so the dialogs pushed below stay on top of it.
529        if let Some(sticky_layer) =
530            self.create_sticky_scroll_layer(visual_lines.as_ref())
531        {
532            editor_stack = editor_stack.push(sticky_layer);
533        }
534
535        // Add IME layer for input method support.
536        // The IME requester needs the cursor rect in viewport coordinates, which
537        // depends on the current logical↔visual mapping.
538        let cursor_rect = self.calculate_ime_cursor_rect(visual_lines.as_ref());
539        let ime_layer = self.create_ime_layer(cursor_rect);
540        editor_stack = editor_stack.push(ime_layer);
541
542        // Add search dialog overlay if open
543        if self.search_state.is_open {
544            let search_dialog =
545                search_dialog::view(&self.search_state, &self.translations);
546
547            // Position the dialog in top-right corner with 20px margin
548            let positioned_dialog = container(
549                Row::new()
550                    .push(Space::new().width(Length::Fill))
551                    .push(search_dialog),
552            )
553            .padding(20)
554            .width(Length::Fill)
555            .height(Length::Shrink);
556
557            editor_stack = editor_stack.push(positioned_dialog);
558        }
559
560        // Add the compact go-to-line dialog in the top center.
561        if self.goto_line_state.is_open {
562            let goto_line_dialog = goto_line_dialog::view(
563                &self.goto_line_state,
564                self.buffer.line_count(),
565            );
566            let positioned_dialog = container(
567                Row::new()
568                    .push(Space::new().width(Length::Fill))
569                    .push(goto_line_dialog)
570                    .push(Space::new().width(Length::Fill)),
571            )
572            .padding(20)
573            .width(Length::Fill)
574            .height(Length::Shrink);
575
576            editor_stack = editor_stack.push(positioned_dialog);
577        }
578
579        // Add the command palette in the top center, above every other
580        // dialog: opening it closes the others, so it is always innermost.
581        if self.command_palette_state.is_open {
582            let entries = self.command_palette_entries();
583            let palette = command_palette_dialog::view(
584                &self.command_palette_state,
585                &entries,
586                &self.translations,
587            );
588            let positioned_palette = container(
589                Row::new()
590                    .push(Space::new().width(Length::Fill))
591                    .push(palette)
592                    .push(Space::new().width(Length::Fill)),
593            )
594            .padding(20)
595            .width(Length::Fill)
596            .height(Length::Shrink);
597
598            editor_stack = editor_stack.push(positioned_palette);
599        }
600
601        // Wrap the editor stack in a container with clip
602        let editor_container = container(editor_stack)
603            .width(Length::Fill)
604            .height(Length::Fill)
605            .clip(true);
606
607        // The context menu owns its transient open/close state and positions
608        // itself at the right-click location. The canvas still receives the
609        // right-click event so it can preserve or reposition the selection.
610        let action_context = self.action_context();
611        let custom_context_menu_entries =
612            self.custom_context_menu_entries().to_vec();
613        let default_context_menu_enabled = self.default_context_menu_enabled();
614        let translations = self.translations;
615        let editor_container = ContextMenu::new(editor_container, move || {
616            context_menu::view(
617                &custom_context_menu_entries,
618                default_context_menu_enabled,
619                action_context,
620                translations,
621            )
622        });
623
624        // When wrap is disabled, add a horizontal scrollbar below the editor.
625        let editor_body: Element<'_, Message> = if self.wrap_enabled {
626            editor_container.into()
627        } else {
628            // Measuring the widest line scans the entire buffer. It is only
629            // needed for the horizontal scrollbar, so never do that work while
630            // wrapping is enabled (the default), especially after every edit in
631            // a large file.
632            let max_content_width = self.max_content_width();
633            if let Some(h_scrollbar) =
634                self.create_horizontal_scrollbar(max_content_width)
635            {
636                Column::new().push(editor_container).push(h_scrollbar).into()
637            } else {
638                editor_container.into()
639            }
640        };
641
642        if self.vim_enabled {
643            Column::new()
644                .push(editor_body)
645                .push(self.create_vim_status_bar())
646                .width(Length::Fill)
647                .height(Length::Fill)
648                .into()
649        } else {
650            editor_body
651        }
652    }
653}
654
655/// Builds a plain-color scrollable rail: a solid background track with a
656/// solid-color scroller, square corners of `radius`, and no border.
657///
658/// Shared by the canvas editor's own scrollbars ([`view`]) and the LSP
659/// overlay panels ([`lsp::process::overlay`]), which derive their colors from
660/// a theme palette instead of plain [`Color`]s.
661///
662/// # Examples
663///
664/// ```text
665/// let rail = scrollable_rail(Color::BLACK, Color::WHITE, 4.0);
666/// ```
667pub(crate) fn scrollable_rail(
668    background: Color,
669    scroller: Color,
670    radius: f32,
671) -> iced::widget::scrollable::Rail {
672    iced::widget::scrollable::Rail {
673        background: Some(background.into()),
674        border: iced::Border {
675            radius: radius.into(),
676            width: 0.0,
677            color: Color::TRANSPARENT,
678        },
679        scroller: iced::widget::scrollable::Scroller {
680            background: scroller.into(),
681            border: iced::Border {
682                radius: radius.into(),
683                width: 0.0,
684                color: Color::TRANSPARENT,
685            },
686        },
687    }
688}
689
690#[cfg(test)]
691mod tests {
692    use super::*;
693
694    #[test]
695    fn test_scrollable_rail_sets_background_scroller_and_radius() {
696        let bg = Color::from_rgb(0.1, 0.2, 0.3);
697        let scroller = Color::from_rgb(0.4, 0.5, 0.6);
698        let rail = scrollable_rail(bg, scroller, 4.0);
699
700        assert_eq!(rail.background, Some(iced::Background::Color(bg)));
701        assert_eq!(rail.scroller.background, iced::Background::Color(scroller));
702        assert_eq!(rail.border.radius, iced::border::Radius::from(4.0));
703        assert!(rail.border.width.abs() < f32::EPSILON);
704        assert_eq!(
705            rail.scroller.border.radius,
706            iced::border::Radius::from(4.0)
707        );
708    }
709
710    #[test]
711    fn test_sticky_layer_absent_when_disabled() {
712        let mut editor =
713            CodeEditor::new("fn main() {\n    let x = 1;\n}", "rs");
714        editor.set_sticky_scroll_enabled(false);
715        let visual_lines = editor.visual_lines_cached(editor.viewport_width);
716
717        assert!(
718            editor.create_sticky_scroll_layer(visual_lines.as_ref()).is_none()
719        );
720    }
721
722    #[test]
723    fn test_sticky_layer_absent_without_enclosing_block() {
724        // A flat buffer has no fold region, so nothing can be pinned.
725        let editor = CodeEditor::new("a\nb\nc", "rs");
726        let visual_lines = editor.visual_lines_cached(editor.viewport_width);
727
728        assert!(
729            editor.create_sticky_scroll_layer(visual_lines.as_ref()).is_none()
730        );
731    }
732
733    #[test]
734    fn test_sticky_layer_absent_at_top_of_file() {
735        // Scrolled to the top, the header is on screen and must not be pinned.
736        let editor = CodeEditor::new(
737            "fn main() {\n    let x = 1;\n    let y = 2;\n}",
738            "rs",
739        );
740        let visual_lines = editor.visual_lines_cached(editor.viewport_width);
741
742        assert!(
743            editor.create_sticky_scroll_layer(visual_lines.as_ref()).is_none()
744        );
745    }
746
747    #[test]
748    fn test_sticky_layer_survives_code_folding_being_disabled() {
749        // End-to-end counterpart of
750        // `sticky_scroll::tests::test_headroom_survives_code_folding_being_disabled`:
751        // the layer is built from `block_regions`, so turning folding off
752        // removes the chevrons and leaves the pinned headers alone.
753        let mut editor = CodeEditor::new(
754            "fn main() {\n    let x = 1;\n    let y = 2;\n}",
755            "rs",
756        );
757        editor.set_folding_enabled(false);
758        editor.viewport_scroll = editor.line_height();
759        let visual_lines = editor.visual_lines_cached(editor.viewport_width);
760
761        assert!(
762            editor.create_sticky_scroll_layer(visual_lines.as_ref()).is_some()
763        );
764    }
765
766    #[test]
767    fn test_sticky_layer_maps_a_wrapped_segment_back_to_its_logical_line() {
768        // The subtlest line in the feature: the topmost entry of the viewport
769        // is a *visual* line, and soft wrapping makes visual and logical
770        // indices diverge. Here the body of the `if` wraps into several
771        // segments, so scrolling onto one of its continuations puts the
772        // topmost visual index well past any logical line index.
773        //
774        // The fixture discriminates: reading the visual index as a logical one
775        // would land on `}` or past the end of the buffer, where nothing
776        // encloses anything and the layer would be `None`.
777        let mut editor = CodeEditor::new(
778            "fn main() {\n    if a {\n        let x = 1; let y = 2; let z = 3; let w = 4;\n    }\n}",
779            "rs",
780        )
781        .with_wrap_column(Some(20));
782
783        let visual_lines = editor.visual_lines_cached(editor.viewport_width);
784        let continuation = visual_lines
785            .iter()
786            .position(|line| line.logical_line == 2 && line.segment_index == 1)
787            .unwrap_or_default();
788        assert!(
789            continuation > 2,
790            "the fixture must wrap far enough for the two indices to diverge"
791        );
792
793        editor.viewport_scroll = continuation as f32 * editor.line_height();
794        let visual_lines = editor.visual_lines_cached(editor.viewport_width);
795
796        assert!(
797            editor.create_sticky_scroll_layer(visual_lines.as_ref()).is_some(),
798            "a continuation segment is still inside both enclosing blocks"
799        );
800        // Both headers, so the layer really resolved logical line 2 and not
801        // whatever line the raw visual index points at.
802        assert_eq!(editor.sticky_headroom(2), 2);
803    }
804
805    #[test]
806    fn test_sticky_layer_present_when_scrolled_into_block() {
807        let mut editor = CodeEditor::new(
808            "fn main() {\n    let x = 1;\n    let y = 2;\n}",
809            "rs",
810        );
811        // Scroll so the second line is the topmost visible one, putting the
812        // viewport inside the `fn` block.
813        editor.viewport_scroll = editor.line_height();
814        let visual_lines = editor.visual_lines_cached(editor.viewport_width);
815
816        assert!(
817            editor.create_sticky_scroll_layer(visual_lines.as_ref()).is_some()
818        );
819    }
820
821    #[test]
822    fn test_canvas_scrollbar_style_uses_transparent_container() {
823        let bg = Color::from_rgb(0.1, 0.2, 0.3);
824        let scroller = Color::from_rgb(0.4, 0.5, 0.6);
825        let style = canvas_scrollbar_style(bg, scroller);
826
827        assert_eq!(
828            style.container.background,
829            Some(Background::Color(Color::TRANSPARENT))
830        );
831        let expected_rail = scrollable_rail(bg, scroller, 4.0);
832        assert_eq!(style.vertical_rail.background, expected_rail.background);
833        assert_eq!(style.horizontal_rail.background, expected_rail.background);
834    }
835}