use crate::CodeEditor;
use iced::widget::{
Id, Space, button, column, container, markdown, mouse_area, rich_text, row, rule, scrollable,
stack, text,
};
use iced::{
Background, Border, Color, Element, Font, Length, Point, Shadow, Theme, Vector, padding,
};
const MAX_COMPLETION_ITEMS: usize = 8;
const COMPLETION_ITEM_HEIGHT: f32 = 20.0;
const COMPLETION_HEADER_HEIGHT: f32 = 24.0;
const COMPLETION_PADDING: f32 = 4.0;
const COMPLETION_MENU_WIDTH: f32 = 250.0;
const SCROLLABLE_BORDER_RADIUS: f32 = 4.0;
const HOVER_PADDING: f32 = 8.0;
const HOVER_GAP: f32 = 4.0;
const HOVER_MAX_VISIBLE_LINES: f32 = 12.0;
const HOVER_VIEWPORT_INSET: f32 = 24.0;
const HOVER_EDGE_MARGIN: f32 = 4.0;
const HOVER_WIDTH_SLACK: f32 = 2.0;
const HOVER_RADIUS: f32 = 6.0;
const HOVER_HAIRLINE: Color = Color {
r: 1.0,
g: 1.0,
b: 1.0,
a: 0.08,
};
const HOVER_SHADOW_COLOR: Color = Color {
r: 0.0,
g: 0.0,
b: 0.0,
a: 0.35,
};
const HOVER_SHADOW_OFFSET_Y: f32 = 4.0;
const HOVER_SHADOW_BLUR: f32 = 14.0;
const HOVER_ITEM_SPACING_RATIO: f32 = 0.5;
pub struct LspOverlayState {
pub hover_text: Option<String>,
pub hover_items: Vec<iced::widget::markdown::Item>,
pub hover_visible: bool,
pub hover_position: Option<Point>,
pub hover_interactive: bool,
pub all_completions: Vec<String>,
pub completion_filter: String,
pub completion_items: Vec<String>,
pub completion_visible: bool,
pub completion_selected: usize,
pub completion_suppressed: bool,
pub completion_position: Option<Point>,
}
impl LspOverlayState {
pub fn new() -> Self {
Self {
hover_text: None,
hover_items: Vec::new(),
hover_visible: false,
hover_position: None,
hover_interactive: false,
all_completions: Vec::new(),
completion_filter: String::new(),
completion_items: Vec::new(),
completion_visible: false,
completion_selected: 0,
completion_suppressed: false,
completion_position: None,
}
}
pub fn set_hover_position(&mut self, point: Point) {
self.hover_position = Some(point);
}
pub fn show_hover(&mut self, text: String) {
self.hover_items = iced::widget::markdown::parse(&text).collect();
self.hover_text = Some(text);
self.hover_visible = true;
}
pub fn clear_hover(&mut self) {
self.hover_text = None;
self.hover_items.clear();
self.hover_visible = false;
self.hover_position = None;
self.hover_interactive = false;
}
pub fn set_completions(&mut self, items: Vec<String>, position: Point) {
self.all_completions = items;
self.completion_selected = 0;
self.completion_position = Some(position);
self.filter_completions();
}
pub fn clear_completions(&mut self) {
self.all_completions.clear();
self.completion_items.clear();
self.completion_filter.clear();
self.completion_visible = false;
self.completion_suppressed = false;
}
pub fn filter_completions(&mut self) {
let filter = self.completion_filter.to_lowercase();
if filter.is_empty() {
self.completion_items = self.all_completions.clone();
} else {
self.completion_items = self
.all_completions
.iter()
.filter(|item| item.to_lowercase().contains(&filter))
.cloned()
.collect();
}
self.completion_visible = !self.completion_items.is_empty();
if self.completion_selected >= self.completion_items.len() {
self.completion_selected = self.completion_items.len().saturating_sub(1);
}
}
pub fn navigate(&mut self, delta: i32) {
if self.completion_items.is_empty() {
return;
}
let len = self.completion_items.len();
let current = self.completion_selected as i32;
self.completion_selected = ((current + delta).rem_euclid(len as i32)) as usize;
}
pub fn selected_item(&self) -> Option<&str> {
self.completion_items.get(self.completion_selected).map(String::as_str)
}
pub fn scroll_offset_for_selected(&self) -> f32 {
self.completion_selected as f32 * COMPLETION_ITEM_HEIGHT
}
}
impl Default for LspOverlayState {
fn default() -> Self {
Self::new()
}
}
#[derive(Debug, Clone)]
pub enum LspOverlayMessage {
HoverEntered,
HoverExited,
CompletionSelected(usize),
CompletionClosed,
CompletionNavigateUp,
CompletionNavigateDown,
CompletionConfirm,
}
pub fn view_lsp_overlay<'a, M: Clone + 'a>(
state: &'a LspOverlayState,
editor: &'a CodeEditor,
theme: &'a Theme,
font_size: f32,
line_height: f32,
f: impl Fn(LspOverlayMessage) -> M + 'a,
) -> Element<'a, M> {
let msg_hover_entered = f(LspOverlayMessage::HoverEntered);
let msg_hover_exited = f(LspOverlayMessage::HoverExited);
let msg_completion_closed = f(LspOverlayMessage::CompletionClosed);
let msg_completion_selected: Vec<M> = (0..state.completion_items.len())
.map(|i| f(LspOverlayMessage::CompletionSelected(i)))
.collect();
let mut has_overlay = false;
let hover_layer: Element<'a, M> = build_hover_layer(
state,
editor,
theme,
(font_size, line_height),
msg_hover_entered,
msg_hover_exited,
&mut has_overlay,
);
let completion_layer: Element<'a, M> = build_completion_layer(
state,
editor,
line_height,
msg_completion_closed,
msg_completion_selected,
&mut has_overlay,
);
if !has_overlay {
return container(Space::new().width(Length::Shrink).height(Length::Shrink)).into();
}
let base = container(Space::new().width(Length::Fill).height(Length::Fill))
.width(Length::Fill)
.height(Length::Fill);
stack![base, completion_layer, hover_layer].into()
}
fn build_hover_layer<'a, M: Clone + 'a>(
state: &'a LspOverlayState,
editor: &'a CodeEditor,
theme: &'a Theme,
text_metrics: (f32, f32),
msg_entered: M,
msg_exited: M,
has_overlay: &mut bool,
) -> Element<'a, M> {
let (font_size, line_height) = text_metrics;
if !state.hover_visible {
return empty_overlay();
}
let Some(hover) = state.hover_text.as_ref().filter(|t| !t.trim().is_empty()) else {
return empty_overlay();
};
let mut markdown_style = markdown::Style::from_palette(theme.palette());
markdown_style.code_block_font = editor.font;
markdown_style.inline_code_font = editor.font;
let mut markdown_settings = markdown::Settings::with_text_size(font_size, markdown_style);
markdown_settings.spacing = (font_size * HOVER_ITEM_SPACING_RATIO).into();
let measure = |line: &str| editor.measure_text_width(line);
let viewport_width = editor.viewport_width();
let natural_width =
hover_content_width(hover, &state.hover_items, &measure).ceil() + HOVER_WIDTH_SLACK;
let content_max_width = (viewport_width - HOVER_VIEWPORT_INSET - 2.0 * HOVER_PADDING).max(0.0);
let content_width = if content_max_width > 0.0 {
natural_width.min(content_max_width)
} else {
natural_width
};
let hover_width = content_width + 2.0 * HOVER_PADDING;
let max_box_height = HOVER_MAX_VISIBLE_LINES * line_height + 2.0 * HOVER_PADDING;
let estimated_height = HeightEstimator {
settings: markdown_settings,
line_height,
measure: &measure,
}
.hover_height(&state.hover_items, content_width)
.min(max_box_height)
+ HOVER_GAP;
let (anchor_x, anchor_top) = match state.hover_position {
Some(anchor) => (
anchor.x - editor.horizontal_scroll_offset,
anchor.y - editor.viewport_scroll(),
),
None => (HOVER_EDGE_MARGIN, HOVER_EDGE_MARGIN),
};
let placement = hover_vertical_placement(
anchor_top,
line_height,
estimated_height,
editor.viewport_height(),
);
let offset_x = hover_offset_x(anchor_x, hover_width, viewport_width);
let (side_space, gap) = match placement {
HoverPlacement::Below { max_height, .. } => (max_height, padding::top(HOVER_GAP)),
HoverPlacement::Above { max_height, .. } => (max_height, padding::bottom(HOVER_GAP)),
};
let box_max_height = max_box_height.min(side_space - HOVER_GAP).max(0.0);
let viewer = HoverViewer {
font: editor.font,
font_size: editor.font_size(),
line_height,
};
let entered_for_map = msg_entered.clone();
let entered_for_enter = msg_entered.clone();
let entered_for_move = msg_entered;
let hover_content = scrollable(
container(
markdown::view_with(&state.hover_items, markdown_settings, &viewer)
.map(move |_| entered_for_map.clone()),
)
.width(Length::Fixed(hover_width))
.padding(HOVER_PADDING),
)
.width(Length::Fixed(hover_width))
.height(Length::Shrink)
.style(|theme: &Theme, _status| {
let palette = theme.extended_palette();
scrollable::Style {
container: container::Style {
background: Some(Background::Color(Color::TRANSPARENT)),
..container::Style::default()
},
vertical_rail: lsp_scrollable_rail(palette),
horizontal_rail: lsp_scrollable_rail(palette),
gap: None,
auto_scroll: scrollable::AutoScroll {
background: Color::TRANSPARENT.into(),
border: Border::default(),
shadow: Shadow::default(),
icon: Color::TRANSPARENT,
},
}
});
let hover_box = container(hover_content).max_height(box_max_height).style(hover_box_style);
let hit_area = mouse_area(container(hover_box).padding(gap))
.interaction(iced::mouse::Interaction::Idle)
.on_enter(entered_for_enter)
.on_move(move |_| entered_for_move.clone())
.on_exit(msg_exited);
let positioned = row![Space::new().width(Length::Fixed(offset_x)), hit_area];
let layer: Element<'a, M> = match placement {
HoverPlacement::Below { top, .. } => {
column![Space::new().height(Length::Fixed(top)), positioned].into()
},
HoverPlacement::Above { bottom, .. } => container(positioned)
.width(Length::Fill)
.align_bottom(Length::Fixed(bottom))
.into(),
};
*has_overlay = true;
container(layer).width(Length::Fill).height(Length::Fill).into()
}
fn hover_box_style(theme: &Theme) -> container::Style {
container::Style {
background: Some(Background::Color(
theme.extended_palette().background.weak.color,
)),
border: Border {
color: HOVER_HAIRLINE,
width: 1.0,
radius: HOVER_RADIUS.into(),
},
shadow: Shadow {
color: HOVER_SHADOW_COLOR,
offset: Vector::new(0.0, HOVER_SHADOW_OFFSET_Y),
blur_radius: HOVER_SHADOW_BLUR,
},
..container::Style::default()
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
enum HoverPlacement {
Below {
top: f32,
max_height: f32,
},
Above {
bottom: f32,
max_height: f32,
},
}
fn hover_vertical_placement(
anchor_top: f32,
line_height: f32,
estimated_height: f32,
viewport_height: f32,
) -> HoverPlacement {
let viewport_height = viewport_height.max(0.0);
let line_bottom = (anchor_top + line_height).max(0.0).min(viewport_height);
let space_below = viewport_height - line_bottom;
let space_above = anchor_top.max(0.0).min(viewport_height);
if estimated_height > space_below && space_above > space_below {
HoverPlacement::Above {
bottom: space_above,
max_height: space_above,
}
} else {
HoverPlacement::Below {
top: line_bottom,
max_height: space_below,
}
}
}
fn hover_offset_x(anchor_x: f32, hover_width: f32, viewport_width: f32) -> f32 {
let max_x = (viewport_width - hover_width - HOVER_EDGE_MARGIN).max(0.0);
anchor_x.min(max_x).max(0.0)
}
fn hover_content_width(
markdown: &str,
items: &[markdown::Item],
measure: &dyn Fn(&str) -> f32,
) -> f32 {
let mut code_blocks = Vec::new();
collect_code_blocks(items, &mut code_blocks);
let code_width = code_blocks
.iter()
.flat_map(|code| code.lines())
.map(measure)
.fold(0.0, f32::max);
let prose_width = prose_lines(markdown).map(measure).fold(0.0, f32::max);
code_width.max(prose_width)
}
fn collect_code_blocks<'a>(items: &'a [markdown::Item], out: &mut Vec<&'a str>) {
for item in items {
match item {
markdown::Item::CodeBlock { code, .. } => out.push(code),
markdown::Item::Quote(items) => collect_code_blocks(items, out),
markdown::Item::List { bullets, .. } => {
for bullet in bullets {
collect_code_blocks(bullet_items(bullet), out);
}
},
_ => {},
}
}
}
fn bullet_items(bullet: &markdown::Bullet) -> &[markdown::Item] {
match bullet {
markdown::Bullet::Point { items } | markdown::Bullet::Task { items, .. } => items,
}
}
fn prose_lines(markdown: &str) -> impl Iterator<Item = &str> {
let mut fence: Option<&str> = None;
markdown.lines().filter(move |line| {
let line = line.trim_start();
match fence {
Some(marker) => {
if line.starts_with(marker) {
fence = None;
}
false
},
None => match ["```", "~~~"].into_iter().find(|marker| line.starts_with(marker)) {
Some(marker) => {
fence = Some(marker);
false
},
None => true,
},
}
})
}
struct HeightEstimator<'m> {
settings: markdown::Settings,
line_height: f32,
measure: &'m dyn Fn(&str) -> f32,
}
impl HeightEstimator<'_> {
fn hover_height(&self, items: &[markdown::Item], content_width: f32) -> f32 {
self.blocks(items, content_width, self.settings.spacing.0) + 2.0 * HOVER_PADDING
}
fn blocks(&self, items: &[markdown::Item], width: f32, spacing: f32) -> f32 {
let gaps = items.len().saturating_sub(1) as f32 * spacing;
items.iter().map(|item| self.block(item, width, spacing)).sum::<f32>() + gaps
}
fn block(&self, item: &markdown::Item, width: f32, spacing: f32) -> f32 {
let text_size = self.settings.text_size.0;
match item {
markdown::Item::CodeBlock { code, .. } => {
self.wrapped_lines(code, width) * self.line_height
},
markdown::Item::Rule => 1.0,
markdown::Item::Paragraph(text) => {
self.wrapped_lines(&self.plain_text(text), width) * self.line_height
},
markdown::Item::Heading(level, text) => {
let scale = if text_size > 0.0 {
self.heading_size(*level) / text_size
} else {
1.0
};
let lines = self.wrapped_lines(&self.plain_text(text), width / scale);
lines * self.line_height * scale + text_size / 2.0
},
markdown::Item::List { bullets, .. } => {
let width = (width - 2.0 * spacing).max(0.0);
let gaps = bullets.len().saturating_sub(1) as f32 * spacing;
bullets
.iter()
.map(|bullet| self.blocks(bullet_items(bullet), width, spacing))
.sum::<f32>()
+ gaps
},
markdown::Item::Quote(items) => self.blocks(items, width, spacing),
markdown::Item::Table { rows, .. } => {
(rows.len() + 1) as f32 * (self.line_height + spacing)
},
markdown::Item::Image { .. } => self.line_height,
}
}
fn wrapped_lines(&self, text: &str, width: f32) -> f32 {
let lines: f32 = text
.lines()
.map(|line| {
if width > 0.0 {
((self.measure)(line) / width).ceil().max(1.0)
} else {
1.0
}
})
.sum();
lines.max(1.0)
}
fn heading_size(&self, level: markdown::HeadingLevel) -> f32 {
let settings = &self.settings;
match level {
markdown::HeadingLevel::H1 => settings.h1_size.0,
markdown::HeadingLevel::H2 => settings.h2_size.0,
markdown::HeadingLevel::H3 => settings.h3_size.0,
markdown::HeadingLevel::H4 => settings.h4_size.0,
markdown::HeadingLevel::H5 => settings.h5_size.0,
markdown::HeadingLevel::H6 => settings.h6_size.0,
}
}
fn plain_text(&self, text: &markdown::Text) -> String {
text.spans(self.settings.style).iter().map(|span| &*span.text).collect()
}
}
#[derive(Debug, Clone, Copy)]
struct HoverViewer {
font: Font,
font_size: f32,
line_height: f32,
}
impl<'a> markdown::Viewer<'a, markdown::Uri> for HoverViewer {
fn on_link_click(url: markdown::Uri) -> markdown::Uri {
url
}
fn code_block(
&self,
settings: markdown::Settings,
_language: Option<&'a str>,
_code: &'a str,
lines: &'a [markdown::Text],
) -> Element<'a, markdown::Uri> {
let HoverViewer {
font,
font_size,
line_height,
} = *self;
column(lines.iter().map(|line| {
rich_text(spans_in_font_family(&line.spans(settings.style), font))
.font(font)
.size(font_size)
.line_height(text::LineHeight::Absolute(line_height.into()))
.into()
}))
.into()
}
fn rule(&self, _settings: markdown::Settings) -> Element<'a, markdown::Uri> {
rule::horizontal(1)
.style(|_theme: &Theme| rule::Style {
color: HOVER_HAIRLINE,
radius: 0.0.into(),
fill_mode: rule::FillMode::Full,
snap: true,
})
.into()
}
}
fn spans_in_font_family(
spans: &[text::Span<'static, markdown::Uri>],
font: Font,
) -> Vec<text::Span<'static, markdown::Uri>> {
spans
.iter()
.map(|span| {
let mut span = span.clone();
span.font = span.font.map(|token_font| Font {
family: font.family,
..token_font
});
span
})
.collect()
}
fn build_completion_layer<'a, M: Clone + 'a>(
state: &'a LspOverlayState,
editor: &'a CodeEditor,
line_height: f32,
msg_closed: M,
msg_selected: Vec<M>,
has_overlay: &mut bool,
) -> Element<'a, M> {
if !state.completion_visible || state.completion_items.is_empty() || state.completion_suppressed
{
return empty_overlay();
}
let visible_count = state.completion_items.len().min(MAX_COMPLETION_ITEMS);
let menu_height = COMPLETION_HEADER_HEIGHT
+ (visible_count as f32 * COMPLETION_ITEM_HEIGHT)
+ (COMPLETION_PADDING * 2.0);
let cursor_pos = state.completion_position.unwrap_or(Point::new(4.0, 4.0));
let viewport_width = editor.viewport_width();
let viewport_height = editor.viewport_height();
let viewport_scroll = editor.viewport_scroll();
let menu_width = COMPLETION_MENU_WIDTH.min(viewport_width - 8.0);
let adjusted_y = (cursor_pos.y - viewport_scroll).max(0.0);
let space_below = viewport_height - adjusted_y - line_height;
let show_above = space_below < menu_height + 4.0 && adjusted_y >= menu_height + 4.0;
let offset_x = cursor_pos.x.min(viewport_width - menu_width - 4.0).max(4.0);
let offset_y = if show_above {
(adjusted_y - menu_height - 4.0).max(0.0)
} else {
adjusted_y + line_height + 4.0
};
let completion_elements: Vec<Element<'_, M>> = state
.completion_items
.iter()
.enumerate()
.zip(msg_selected)
.map(|((index, item), msg)| {
let is_selected = index == state.completion_selected;
button(
text(item.clone())
.size(12)
.line_height(iced::widget::text::LineHeight::Relative(1.5)),
)
.padding([2, 8])
.width(Length::Fill)
.on_press(msg)
.style(move |theme: &Theme, _status| {
let palette = theme.extended_palette();
if is_selected {
button::Style {
background: Some(iced::Background::Color(palette.primary.weak.color)),
text_color: Color::WHITE,
..Default::default()
}
} else {
button::Style {
background: Some(iced::Background::Color(palette.background.weak.color)),
text_color: Color::WHITE,
..Default::default()
}
}
})
.into()
})
.collect();
let completion_box = scrollable(column(completion_elements).spacing(0))
.height(Length::Fixed(menu_height))
.width(Length::Fixed(menu_width))
.id(Id::new("completion_scrollable"))
.style(|theme: &Theme, _status| {
let palette = theme.extended_palette();
scrollable::Style {
container: container::Style {
background: Some(iced::Background::Color(palette.background.weak.color)),
border: iced::Border {
color: palette.primary.weak.color,
width: 1.0,
radius: SCROLLABLE_BORDER_RADIUS.into(),
},
..Default::default()
},
vertical_rail: lsp_scrollable_rail(palette),
horizontal_rail: lsp_scrollable_rail(palette),
gap: None,
auto_scroll: scrollable::AutoScroll {
background: Color::TRANSPARENT.into(),
border: Border::default(),
shadow: Shadow::default(),
icon: Color::TRANSPARENT,
},
}
});
*has_overlay = true;
let click_outside = button(Space::new().width(Length::Fill).height(Length::Fill))
.width(Length::Fill)
.height(Length::Fill)
.on_press(msg_closed)
.style(|_theme: &Theme, _status| button::Style {
background: Some(Background::Color(Color::TRANSPARENT)),
..Default::default()
});
let completion_content = container(
column![
Space::new().height(Length::Fixed(offset_y)),
row![Space::new().width(Length::Fixed(offset_x)), completion_box]
]
.spacing(0)
.width(Length::Fill)
.height(Length::Fill),
)
.width(Length::Fill)
.height(Length::Fill);
stack![click_outside, completion_content].into()
}
fn lsp_scrollable_rail(palette: &iced::theme::palette::Extended) -> scrollable::Rail {
crate::canvas_editor::render::view::scrollable_rail(
palette.background.weak.color,
palette.primary.weak.color,
SCROLLABLE_BORDER_RADIUS,
)
}
fn empty_overlay<'a, M: 'a>() -> Element<'a, M> {
container(Space::new().width(Length::Shrink).height(Length::Shrink)).into()
}
#[cfg(test)]
mod tests {
use super::*;
use iced::Point;
#[test]
fn test_lsp_overlay_state_new() {
let state = LspOverlayState::new();
assert!(!state.hover_visible);
assert!(!state.completion_visible);
assert!(state.hover_text.is_none());
assert!(state.completion_items.is_empty());
}
#[test]
fn test_show_hover() {
let mut state = LspOverlayState::new();
state.show_hover("hello".to_string());
assert!(state.hover_visible);
assert_eq!(state.hover_text, Some("hello".to_string()));
}
#[test]
fn test_clear_hover() {
let mut state = LspOverlayState::new();
state.show_hover("hello".to_string());
state.hover_interactive = true;
state.hover_position = Some(Point::ORIGIN);
state.clear_hover();
assert!(!state.hover_visible);
assert!(state.hover_text.is_none());
assert!(!state.hover_interactive);
assert!(state.hover_position.is_none());
}
#[test]
fn test_set_hover_position() {
let mut state = LspOverlayState::new();
state.set_hover_position(Point::new(10.0, 20.0));
assert_eq!(state.hover_position, Some(Point::new(10.0, 20.0)));
}
#[test]
fn test_set_completions() {
let mut state = LspOverlayState::new();
state.set_completions(vec!["foo".to_string(), "bar".to_string()], Point::ORIGIN);
assert_eq!(state.completion_items.len(), 2);
assert!(state.completion_visible);
assert_eq!(state.completion_selected, 0);
}
#[test]
fn test_clear_completions() {
let mut state = LspOverlayState::new();
state.set_completions(vec!["foo".to_string()], Point::ORIGIN);
state.clear_completions();
assert!(!state.completion_visible);
assert!(state.all_completions.is_empty());
assert!(state.completion_items.is_empty());
}
#[test]
fn test_filter_completions() {
let mut state = LspOverlayState::new();
state.set_completions(
vec!["foo".to_string(), "bar".to_string(), "baz".to_string()],
Point::ORIGIN,
);
state.completion_filter = "ba".to_string();
state.filter_completions();
assert_eq!(state.completion_items.len(), 2);
assert!(state.completion_items.contains(&"bar".to_string()));
assert!(state.completion_items.contains(&"baz".to_string()));
}
#[test]
fn test_navigate() {
let mut state = LspOverlayState::new();
state.set_completions(
vec!["a".to_string(), "b".to_string(), "c".to_string()],
Point::ORIGIN,
);
state.navigate(1);
assert_eq!(state.completion_selected, 1);
state.navigate(-1);
assert_eq!(state.completion_selected, 0);
state.navigate(-1);
assert_eq!(state.completion_selected, 2);
state.navigate(1);
assert_eq!(state.completion_selected, 0);
}
#[test]
#[allow(clippy::float_cmp)]
fn test_scroll_offset_for_selected() {
let mut state = LspOverlayState::new();
assert_eq!(state.scroll_offset_for_selected(), 0.0);
state.set_completions(
vec!["a".to_string(), "b".to_string(), "c".to_string()],
Point::ORIGIN,
);
assert_eq!(state.scroll_offset_for_selected(), 0.0);
state.navigate(1);
assert_eq!(state.scroll_offset_for_selected(), COMPLETION_ITEM_HEIGHT);
state.navigate(1);
assert_eq!(
state.scroll_offset_for_selected(),
2.0 * COMPLETION_ITEM_HEIGHT
);
}
#[test]
fn test_selected_item() {
let mut state = LspOverlayState::new();
assert_eq!(state.selected_item(), None);
state.set_completions(
vec!["first".to_string(), "second".to_string()],
Point::ORIGIN,
);
assert_eq!(state.selected_item(), Some("first"));
state.navigate(1);
assert_eq!(state.selected_item(), Some("second"));
}
const EPSILON: f32 = 1e-3;
fn approx_eq(a: f32, b: f32) -> bool {
(a - b).abs() < EPSILON
}
fn measure_8px(text: &str) -> f32 {
text.chars().count() as f32 * 8.0
}
fn settings_14px() -> markdown::Settings {
let mut settings = markdown::Settings::with_text_size(
14.0,
markdown::Style::from_palette(Theme::Dark.palette()),
);
settings.spacing = 7.0.into();
settings
}
#[test]
fn test_hover_vertical_placement_defaults_below() {
let placement = hover_vertical_placement(100.0, 20.0, 120.0, 600.0);
assert!(
matches!(
placement,
HoverPlacement::Below { top, max_height }
if approx_eq(top, 120.0) && approx_eq(max_height, 480.0)
),
"got {placement:?}"
);
}
#[test]
fn test_hover_vertical_placement_flips_above_when_no_room() {
let placement = hover_vertical_placement(500.0, 20.0, 120.0, 600.0);
assert!(
matches!(
placement,
HoverPlacement::Above { bottom, max_height }
if approx_eq(bottom, 500.0) && approx_eq(max_height, 500.0)
),
"got {placement:?}"
);
}
#[test]
fn test_hover_vertical_placement_stays_below_when_above_is_smaller() {
let placement = hover_vertical_placement(40.0, 20.0, 300.0, 200.0);
assert!(
matches!(
placement,
HoverPlacement::Below { top, max_height }
if approx_eq(top, 60.0) && approx_eq(max_height, 140.0)
),
"got {placement:?}"
);
}
#[test]
fn test_hover_vertical_placement_max_height_never_negative() {
let cases = [
(590.0, 20.0, 0.0, 600.0),
(-10.0, 20.0, 500.0, 100.0),
(10.0, 20.0, 50.0, 0.0),
(10.0, 20.0, 50.0, -5.0),
];
for (anchor_top, line_height, estimated_height, viewport_height) in cases {
let placement = hover_vertical_placement(
anchor_top,
line_height,
estimated_height,
viewport_height,
);
let (edge, max_height) = match placement {
HoverPlacement::Below { top, max_height } => (top, max_height),
HoverPlacement::Above { bottom, max_height } => (bottom, max_height),
};
assert!(max_height >= 0.0, "negative max_height in {placement:?}");
assert!(edge >= 0.0, "edge outside the viewport in {placement:?}");
}
}
#[test]
fn test_hover_offset_x_starts_at_anchor() {
assert!(approx_eq(hover_offset_x(100.0, 200.0, 800.0), 100.0));
}
#[test]
fn test_hover_offset_x_clamps_to_viewport() {
let max_x = 800.0 - 200.0 - HOVER_EDGE_MARGIN;
assert!(approx_eq(hover_offset_x(700.0, 200.0, 800.0), max_x));
assert!(approx_eq(hover_offset_x(-50.0, 200.0, 800.0), 0.0));
}
#[test]
fn test_hover_offset_x_narrow_viewport_is_zero() {
assert!(approx_eq(hover_offset_x(100.0, 300.0, 200.0), 0.0));
}
#[test]
fn test_prose_lines_skips_fenced_code() {
let markdown = "```rust\nfn main()\n```\nprose\n~~~\ncode\n~~~\n---\nmore";
let lines: Vec<&str> = prose_lines(markdown).collect();
assert_eq!(lines, vec!["prose", "---", "more"]);
}
#[test]
fn test_hover_content_width_uses_widest_line() {
let markdown = "```rust\nfn long_signature()\n```\n\nshort docs";
let items: Vec<markdown::Item> = markdown::parse(markdown).collect();
let width = hover_content_width(markdown, &items, &measure_8px);
assert!(
approx_eq(width, measure_8px("fn long_signature()")),
"got {width}"
);
let markdown = "```rust\nfn f()\n```\n\nthese docs are the widest";
let items: Vec<markdown::Item> = markdown::parse(markdown).collect();
let width = hover_content_width(markdown, &items, &measure_8px);
assert!(
approx_eq(width, measure_8px("these docs are the widest")),
"got {width}"
);
}
#[test]
fn test_hover_height_estimate_counts_code_rule_and_prose() {
let items: Vec<markdown::Item> =
markdown::parse("```rust\nfn foo()\n```\n\n---\n\nSome docs.").collect();
let estimator = HeightEstimator {
settings: settings_14px(),
line_height: 20.0,
measure: &measure_8px,
};
let expected = 20.0 + 7.0 + 1.0 + 7.0 + 20.0 + 2.0 * HOVER_PADDING;
assert!(approx_eq(estimator.hover_height(&items, 400.0), expected));
}
#[test]
fn test_hover_height_estimate_wraps_prose() {
let paragraph = "word ".repeat(20);
let items: Vec<markdown::Item> = markdown::parse(paragraph.trim_end()).collect();
let estimator = HeightEstimator {
settings: settings_14px(),
line_height: 20.0,
measure: &measure_8px,
};
let height = estimator.hover_height(&items, 400.0);
assert!(
approx_eq(height, 2.0 * 20.0 + 2.0 * HOVER_PADDING),
"got {height}"
);
}
}