use crate::container;
use crate::core::border::{self, Border};
use crate::core::clipboard::DndDestinationRectangles;
use iced_runtime::core::widget::Id;
#[cfg(feature = "a11y")]
use std::borrow::Cow;
use crate::core::event::{self, Event};
use crate::core::keyboard;
use crate::core::layout;
use crate::core::mouse;
use crate::core::overlay;
use crate::core::renderer;
use crate::core::time::{Duration, Instant};
use crate::core::touch;
use crate::core::widget::operation::{self, Operation};
use crate::core::widget::tree::{self, Tree};
use crate::core::window;
use crate::core::{
self, id::Internal, Background, Clipboard, Color, Element, Layout, Length,
Padding, Pixels, Point, Rectangle, Shell, Size, Theme, Vector, Widget,
};
use crate::runtime::task::{self, Task};
use crate::runtime::Action;
pub use operation::scrollable::{AbsoluteOffset, RelativeOffset};
#[allow(missing_debug_implementations)]
pub struct Scrollable<
'a,
Message,
Theme = crate::Theme,
Renderer = crate::Renderer,
> where
Theme: Catalog,
Renderer: core::Renderer,
{
id: Id,
scrollbar_id: Id,
#[cfg(feature = "a11y")]
name: Option<Cow<'a, str>>,
#[cfg(feature = "a11y")]
description: Option<iced_accessibility::Description<'a>>,
#[cfg(feature = "a11y")]
label: Option<Vec<iced_accessibility::accesskit::NodeId>>,
width: Length,
height: Length,
direction: Direction,
content: Element<'a, Message, Theme, Renderer>,
on_scroll: Option<Box<dyn Fn(Viewport) -> Message + 'a>>,
class: Theme::Class<'a>,
}
impl<'a, Message, Theme, Renderer> Scrollable<'a, Message, Theme, Renderer>
where
Theme: Catalog,
Renderer: core::Renderer,
{
pub fn new(
content: impl Into<Element<'a, Message, Theme, Renderer>>,
) -> Self {
Self::with_direction(content, Direction::default())
}
pub fn with_direction(
content: impl Into<Element<'a, Message, Theme, Renderer>>,
direction: impl Into<Direction>,
) -> Self {
Scrollable {
id: Id::unique(),
scrollbar_id: Id::unique(),
#[cfg(feature = "a11y")]
name: None,
#[cfg(feature = "a11y")]
description: None,
#[cfg(feature = "a11y")]
label: None,
width: Length::Shrink,
height: Length::Shrink,
direction: direction.into(),
content: content.into(),
on_scroll: None,
class: Theme::default(),
}
.validate()
}
fn validate(mut self) -> Self {
let size_hint = self.content.as_widget().size_hint();
debug_assert!(
self.direction.vertical().is_none() || !size_hint.height.is_fill(),
"scrollable content must not fill its vertical scrolling axis"
);
debug_assert!(
self.direction.horizontal().is_none() || !size_hint.width.is_fill(),
"scrollable content must not fill its horizontal scrolling axis"
);
if self.direction.horizontal().is_none() {
self.width = self.width.enclose(size_hint.width);
}
if self.direction.vertical().is_none() {
self.height = self.height.enclose(size_hint.height);
}
self
}
pub fn direction(mut self, direction: impl Into<Direction>) -> Self {
self.direction = direction.into();
self.validate()
}
pub fn id(mut self, id: Id) -> Self {
self.id = id;
self
}
pub fn width(mut self, width: impl Into<Length>) -> Self {
self.width = width.into();
self
}
pub fn height(mut self, height: impl Into<Length>) -> Self {
self.height = height.into();
self
}
pub fn on_scroll(mut self, f: impl Fn(Viewport) -> Message + 'a) -> Self {
self.on_scroll = Some(Box::new(f));
self
}
pub fn anchor_top(self) -> Self {
self.anchor_y(Anchor::Start)
}
pub fn anchor_bottom(self) -> Self {
self.anchor_y(Anchor::End)
}
pub fn anchor_left(self) -> Self {
self.anchor_x(Anchor::Start)
}
pub fn anchor_right(self) -> Self {
self.anchor_x(Anchor::End)
}
pub fn anchor_x(mut self, alignment: Anchor) -> Self {
match &mut self.direction {
Direction::Horizontal(horizontal)
| Direction::Both { horizontal, .. } => {
horizontal.alignment = alignment;
}
Direction::Vertical { .. } => {}
}
self
}
pub fn anchor_y(mut self, alignment: Anchor) -> Self {
match &mut self.direction {
Direction::Vertical(vertical)
| Direction::Both { vertical, .. } => {
vertical.alignment = alignment;
}
Direction::Horizontal { .. } => {}
}
self
}
pub fn spacing(mut self, new_spacing: impl Into<Pixels>) -> Self {
match &mut self.direction {
Direction::Horizontal(scrollbar)
| Direction::Vertical(scrollbar) => {
scrollbar.spacing = Some(new_spacing.into().0);
}
Direction::Both { .. } => {}
}
self
}
#[must_use]
pub fn style(mut self, style: impl Fn(&Theme, Status) -> Style + 'a) -> Self
where
Theme::Class<'a>: From<StyleFn<'a, Theme>>,
{
self.class = (Box::new(style) as StyleFn<'a, Theme>).into();
self
}
#[cfg(feature = "advanced")]
#[must_use]
pub fn class(mut self, class: impl Into<Theme::Class<'a>>) -> Self {
self.class = class.into();
self
}
#[cfg(feature = "a11y")]
pub fn name(mut self, name: impl Into<Cow<'a, str>>) -> Self {
self.name = Some(name.into());
self
}
#[cfg(feature = "a11y")]
pub fn description_widget(
mut self,
description: &impl iced_accessibility::Describes,
) -> Self {
self.description = Some(iced_accessibility::Description::Id(
description.description(),
));
self
}
#[cfg(feature = "a11y")]
pub fn description(mut self, description: impl Into<Cow<'a, str>>) -> Self {
self.description =
Some(iced_accessibility::Description::Text(description.into()));
self
}
#[cfg(feature = "a11y")]
pub fn label(mut self, label: &dyn iced_accessibility::Labels) -> Self {
self.label =
Some(label.label().into_iter().map(|l| l.into()).collect());
self
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Direction {
Vertical(Scrollbar),
Horizontal(Scrollbar),
Both {
vertical: Scrollbar,
horizontal: Scrollbar,
},
}
impl Direction {
pub fn horizontal(&self) -> Option<&Scrollbar> {
match self {
Self::Horizontal(scrollbar) => Some(scrollbar),
Self::Both { horizontal, .. } => Some(horizontal),
Self::Vertical(_) => None,
}
}
pub fn vertical(&self) -> Option<&Scrollbar> {
match self {
Self::Vertical(scrollbar) => Some(scrollbar),
Self::Both { vertical, .. } => Some(vertical),
Self::Horizontal(_) => None,
}
}
fn align(&self, delta: Vector) -> Vector {
let horizontal_alignment =
self.horizontal().map(|p| p.alignment).unwrap_or_default();
let vertical_alignment =
self.vertical().map(|p| p.alignment).unwrap_or_default();
let align = |alignment: Anchor, delta: f32| match alignment {
Anchor::Start => delta,
Anchor::End => -delta,
};
Vector::new(
align(horizontal_alignment, delta.x),
align(vertical_alignment, delta.y),
)
}
}
impl Default for Direction {
fn default() -> Self {
Self::Vertical(Scrollbar::default())
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Scrollbar {
width: f32,
margin: f32,
scroller_width: f32,
alignment: Anchor,
spacing: Option<f32>,
}
impl Default for Scrollbar {
fn default() -> Self {
Self {
width: 8.0,
margin: 0.0,
scroller_width: 8.0,
alignment: Anchor::Start,
spacing: None,
}
}
}
impl Scrollbar {
pub fn new() -> Self {
Self::default()
}
pub fn width(mut self, width: impl Into<Pixels>) -> Self {
self.width = width.into().0.max(0.0);
self
}
pub fn margin(mut self, margin: impl Into<Pixels>) -> Self {
self.margin = margin.into().0;
self
}
pub fn scroller_width(mut self, scroller_width: impl Into<Pixels>) -> Self {
self.scroller_width = scroller_width.into().0.max(0.0);
self
}
pub fn anchor(mut self, alignment: Anchor) -> Self {
self.alignment = alignment;
self
}
pub fn spacing(mut self, spacing: impl Into<Pixels>) -> Self {
self.spacing = Some(spacing.into().0);
self
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum Anchor {
#[default]
Start,
End,
}
impl<'a, Message, Theme, Renderer> Widget<Message, Theme, Renderer>
for Scrollable<'a, Message, Theme, Renderer>
where
Theme: Catalog,
Renderer: core::Renderer,
{
fn tag(&self) -> tree::Tag {
tree::Tag::of::<State>()
}
fn state(&self) -> tree::State {
tree::State::new(State::new())
}
fn children(&self) -> Vec<Tree> {
vec![Tree::new(&self.content)]
}
fn diff(&mut self, tree: &mut Tree) {
tree.diff_children(std::slice::from_mut(&mut self.content));
}
fn size(&self) -> Size<Length> {
Size {
width: self.width,
height: self.height,
}
}
fn layout(
&self,
tree: &mut Tree,
renderer: &Renderer,
limits: &layout::Limits,
) -> layout::Node {
let (right_padding, bottom_padding) = match self.direction {
Direction::Vertical(Scrollbar {
width,
margin,
spacing: Some(spacing),
..
}) => (width + margin * 2.0 + spacing, 0.0),
Direction::Horizontal(Scrollbar {
width,
margin,
spacing: Some(spacing),
..
}) => (0.0, width + margin * 2.0 + spacing),
_ => (0.0, 0.0),
};
layout::padded(
limits,
self.width,
self.height,
Padding {
right: right_padding,
bottom: bottom_padding,
..Padding::ZERO
},
|limits| {
let child_limits = layout::Limits::new(
Size::new(limits.min().width, limits.min().height),
Size::new(
if self.direction.horizontal().is_some() {
f32::INFINITY
} else {
limits.max().width
},
if self.direction.vertical().is_some() {
f32::MAX
} else {
limits.max().height
},
),
);
self.content.as_widget().layout(
&mut tree.children[0],
renderer,
&child_limits,
)
},
)
}
fn operate(
&self,
tree: &mut Tree,
layout: Layout<'_>,
renderer: &Renderer,
operation: &mut dyn Operation,
) {
let state = tree.state.downcast_mut::<State>();
let bounds = layout.bounds();
let content_layout = layout.children().next().unwrap();
let content_bounds = content_layout.bounds();
let translation =
state.translation(self.direction, bounds, content_bounds);
operation.scrollable(
state,
Some(&self.id),
bounds,
content_bounds,
translation,
);
operation.container(Some(&self.id), bounds, &mut |operation| {
self.content.as_widget().operate(
&mut tree.children[0],
layout.children().next().unwrap(),
renderer,
operation,
);
});
}
fn on_event(
&mut self,
tree: &mut Tree,
event: Event,
layout: Layout<'_>,
cursor: mouse::Cursor,
renderer: &Renderer,
clipboard: &mut dyn Clipboard,
shell: &mut Shell<'_, Message>,
_viewport: &Rectangle,
) -> event::Status {
let state = tree.state.downcast_mut::<State>();
let bounds = layout.bounds();
let cursor_over_scrollable = cursor.position_over(bounds);
let content = layout.children().next().unwrap();
let content_bounds = content.bounds();
let scrollbars =
Scrollbars::new(state, self.direction, bounds, content_bounds);
let (mouse_over_y_scrollbar, mouse_over_x_scrollbar) =
scrollbars.is_mouse_over(cursor);
if let Some(last_scrolled) = state.last_scrolled {
let clear_transaction = match event {
Event::Mouse(
mouse::Event::ButtonPressed(_)
| mouse::Event::ButtonReleased(_)
| mouse::Event::CursorLeft,
) => true,
Event::Mouse(mouse::Event::CursorMoved { .. }) => {
last_scrolled.elapsed() > Duration::from_millis(100)
}
_ => last_scrolled.elapsed() > Duration::from_millis(1500),
};
if clear_transaction {
state.last_scrolled = None;
}
}
if let Some(scroller_grabbed_at) = state.y_scroller_grabbed_at {
match event {
Event::Mouse(mouse::Event::CursorMoved { .. })
| Event::Touch(touch::Event::FingerMoved { .. }) => {
if let Some(scrollbar) = scrollbars.y {
let Some(cursor_position) = cursor.position() else {
return event::Status::Ignored;
};
state.scroll_y_to(
scrollbar.scroll_percentage_y(
scroller_grabbed_at,
cursor_position,
),
bounds,
content_bounds,
);
let _ = notify_scroll(
state,
&self.on_scroll,
bounds,
content_bounds,
shell,
);
return event::Status::Captured;
}
}
_ => {}
}
} else if mouse_over_y_scrollbar {
match event {
Event::Mouse(mouse::Event::ButtonPressed(
mouse::Button::Left,
))
| Event::Touch(touch::Event::FingerPressed { .. }) => {
let Some(cursor_position) = cursor.position() else {
return event::Status::Ignored;
};
if let (Some(scroller_grabbed_at), Some(scrollbar)) = (
scrollbars.grab_y_scroller(cursor_position),
scrollbars.y,
) {
state.scroll_y_to(
scrollbar.scroll_percentage_y(
scroller_grabbed_at,
cursor_position,
),
bounds,
content_bounds,
);
state.y_scroller_grabbed_at = Some(scroller_grabbed_at);
let _ = notify_scroll(
state,
&self.on_scroll,
bounds,
content_bounds,
shell,
);
}
return event::Status::Captured;
}
_ => {}
}
}
if let Some(scroller_grabbed_at) = state.x_scroller_grabbed_at {
match event {
Event::Mouse(mouse::Event::CursorMoved { .. })
| Event::Touch(touch::Event::FingerMoved { .. }) => {
let Some(cursor_position) = cursor.position() else {
return event::Status::Ignored;
};
if let Some(scrollbar) = scrollbars.x {
state.scroll_x_to(
scrollbar.scroll_percentage_x(
scroller_grabbed_at,
cursor_position,
),
bounds,
content_bounds,
);
let _ = notify_scroll(
state,
&self.on_scroll,
bounds,
content_bounds,
shell,
);
}
return event::Status::Captured;
}
_ => {}
}
} else if mouse_over_x_scrollbar {
match event {
Event::Mouse(mouse::Event::ButtonPressed(
mouse::Button::Left,
))
| Event::Touch(touch::Event::FingerPressed { .. }) => {
let Some(cursor_position) = cursor.position() else {
return event::Status::Ignored;
};
if let (Some(scroller_grabbed_at), Some(scrollbar)) = (
scrollbars.grab_x_scroller(cursor_position),
scrollbars.x,
) {
state.scroll_x_to(
scrollbar.scroll_percentage_x(
scroller_grabbed_at,
cursor_position,
),
bounds,
content_bounds,
);
state.x_scroller_grabbed_at = Some(scroller_grabbed_at);
let _ = notify_scroll(
state,
&self.on_scroll,
bounds,
content_bounds,
shell,
);
return event::Status::Captured;
}
}
_ => {}
}
}
let content_status = if state.last_scrolled.is_some()
&& matches!(event, Event::Mouse(mouse::Event::WheelScrolled { .. }))
{
event::Status::Ignored
} else {
let cursor = match cursor_over_scrollable {
Some(cursor_position)
if !(mouse_over_x_scrollbar || mouse_over_y_scrollbar) =>
{
mouse::Cursor::Available(
cursor_position
+ state.translation(
self.direction,
bounds,
content_bounds,
),
)
}
_ => mouse::Cursor::Unavailable,
};
let translation =
state.translation(self.direction, bounds, content_bounds);
let mut c_event = match event.clone() {
Event::Dnd(dnd::DndEvent::Offer(
id,
dnd::OfferEvent::Enter {
x,
y,
mime_types,
surface,
},
)) => Event::Dnd(dnd::DndEvent::Offer(
id.clone(),
dnd::OfferEvent::Enter {
x: x + translation.x as f64,
y: y + translation.y as f64,
mime_types: mime_types.clone(),
surface: surface.clone(),
},
)),
Event::Dnd(dnd::DndEvent::Offer(
id,
dnd::OfferEvent::Motion { x, y },
)) => Event::Dnd(dnd::DndEvent::Offer(
id.clone(),
dnd::OfferEvent::Motion {
x: x + translation.x as f64,
y: y + translation.y as f64,
},
)),
e => e,
};
self.content.as_widget_mut().on_event(
&mut tree.children[0],
c_event,
content,
cursor,
renderer,
clipboard,
shell,
&Rectangle {
y: bounds.y + translation.y,
x: bounds.x + translation.x,
..bounds
},
)
};
if matches!(
event,
Event::Mouse(mouse::Event::ButtonReleased(mouse::Button::Left))
| Event::Touch(
touch::Event::FingerLifted { .. }
| touch::Event::FingerLost { .. }
)
) {
state.scroll_area_touched_at = None;
state.x_scroller_grabbed_at = None;
state.y_scroller_grabbed_at = None;
return content_status;
}
if let event::Status::Captured = content_status {
return event::Status::Captured;
}
if let Event::Keyboard(keyboard::Event::ModifiersChanged(modifiers)) =
event
{
state.keyboard_modifiers = modifiers;
return event::Status::Ignored;
}
match event {
Event::Mouse(mouse::Event::WheelScrolled { delta }) => {
if cursor_over_scrollable.is_none() {
return event::Status::Ignored;
}
let Vector { x, y } = match delta {
mouse::ScrollDelta::Lines { x, y } => {
Vector::new(x, y) * 60.
}
mouse::ScrollDelta::Pixels { x, y } => Vector::new(x, y),
};
let is_shift_pressed = state.keyboard_modifiers.shift();
let (x, y) = if cfg!(target_os = "macos") && is_shift_pressed {
(y, x)
} else {
(x, y)
};
let is_vertical = match self.direction {
Direction::Vertical(_) => true,
Direction::Horizontal(_) => false,
Direction::Both { .. } => !is_shift_pressed,
};
let movement = if is_vertical {
Vector::new(x, y)
} else {
Vector::new(y, x)
};
let delta = movement * -1.;
state.scroll(
self.direction.align(delta),
bounds,
content_bounds,
);
let has_scrolled = notify_scroll(
state,
&self.on_scroll,
bounds,
content_bounds,
shell,
);
let in_transaction = state.last_scrolled.is_some();
if has_scrolled || in_transaction {
event::Status::Captured
} else {
event::Status::Ignored
}
}
Event::Touch(event)
if state.scroll_area_touched_at.is_some()
|| !mouse_over_y_scrollbar && !mouse_over_x_scrollbar =>
{
match event {
touch::Event::FingerPressed { .. } => {
let Some(cursor_position) = cursor.position() else {
return event::Status::Ignored;
};
state.scroll_area_touched_at = Some(cursor_position);
}
touch::Event::FingerMoved { .. } => {
if let Some(scroll_box_touched_at) =
state.scroll_area_touched_at
{
let Some(cursor_position) = cursor.position()
else {
return event::Status::Ignored;
};
let delta = Vector::new(
scroll_box_touched_at.x - cursor_position.x,
scroll_box_touched_at.y - cursor_position.y,
);
state.scroll(
self.direction.align(delta),
bounds,
content_bounds,
);
state.scroll_area_touched_at =
Some(cursor_position);
let _ = notify_scroll(
state,
&self.on_scroll,
bounds,
content_bounds,
shell,
);
}
}
_ => {}
}
event::Status::Captured
}
Event::Window(window::Event::RedrawRequested(_)) => {
let _ = notify_viewport(
state,
&self.on_scroll,
bounds,
content_bounds,
shell,
);
event::Status::Ignored
}
_ => event::Status::Ignored,
}
}
fn draw(
&self,
tree: &Tree,
renderer: &mut Renderer,
theme: &Theme,
defaults: &renderer::Style,
layout: Layout<'_>,
cursor: mouse::Cursor,
viewport: &Rectangle,
) {
let state = tree.state.downcast_ref::<State>();
let bounds = layout.bounds();
let content_layout = layout.children().next().unwrap();
let content_bounds = content_layout.bounds();
let Some(visible_bounds) = bounds.intersection(viewport) else {
return;
};
let scrollbars =
Scrollbars::new(state, self.direction, bounds, content_bounds);
let cursor_over_scrollable = cursor.position_over(bounds);
let (mouse_over_y_scrollbar, mouse_over_x_scrollbar) =
scrollbars.is_mouse_over(cursor);
let translation =
state.translation(self.direction, bounds, content_bounds);
let cursor = match cursor_over_scrollable {
Some(cursor_position)
if !(mouse_over_x_scrollbar || mouse_over_y_scrollbar) =>
{
mouse::Cursor::Available(cursor_position + translation)
}
_ => mouse::Cursor::Unavailable,
};
let status = if state.y_scroller_grabbed_at.is_some()
|| state.x_scroller_grabbed_at.is_some()
{
Status::Dragged {
is_horizontal_scrollbar_dragged: state
.x_scroller_grabbed_at
.is_some(),
is_vertical_scrollbar_dragged: state
.y_scroller_grabbed_at
.is_some(),
}
} else if cursor_over_scrollable.is_some() {
Status::Hovered {
is_horizontal_scrollbar_hovered: mouse_over_x_scrollbar,
is_vertical_scrollbar_hovered: mouse_over_y_scrollbar,
}
} else {
Status::Active
};
let style = theme.style(&self.class, status);
container::draw_background(renderer, &style.container, layout.bounds());
if scrollbars.active() {
renderer.with_layer(visible_bounds, |renderer| {
renderer.with_translation(
Vector::new(-translation.x, -translation.y),
|renderer| {
self.content.as_widget().draw(
&tree.children[0],
renderer,
theme,
defaults,
content_layout,
cursor,
&Rectangle {
y: bounds.y + translation.y,
x: bounds.x + translation.x,
..bounds
},
);
},
);
});
let draw_scrollbar =
|renderer: &mut Renderer,
style: Rail,
scrollbar: &internals::Scrollbar| {
if scrollbar.bounds.width > 0.0
&& scrollbar.bounds.height > 0.0
&& (style.background.is_some()
|| (style.border.color != Color::TRANSPARENT
&& style.border.width > 0.0))
{
renderer.fill_quad(
renderer::Quad {
bounds: scrollbar.bounds,
border: style.border,
..renderer::Quad::default()
},
style.background.unwrap_or(Background::Color(
Color::TRANSPARENT,
)),
);
}
if let Some(scroller) = scrollbar.scroller {
if scroller.bounds.width > 0.0
&& scroller.bounds.height > 0.0
&& (style.scroller.color != Color::TRANSPARENT
|| (style.scroller.border.color
!= Color::TRANSPARENT
&& style.scroller.border.width > 0.0))
{
renderer.fill_quad(
renderer::Quad {
bounds: scroller.bounds,
border: style.scroller.border,
..renderer::Quad::default()
},
style.scroller.color,
);
}
}
};
renderer.with_layer(
Rectangle {
width: (visible_bounds.width + 2.0).min(viewport.width),
height: (visible_bounds.height + 2.0).min(viewport.height),
..visible_bounds
},
|renderer| {
if let Some(scrollbar) = scrollbars.y {
draw_scrollbar(
renderer,
style.vertical_rail,
&scrollbar,
);
}
if let Some(scrollbar) = scrollbars.x {
draw_scrollbar(
renderer,
style.horizontal_rail,
&scrollbar,
);
}
if let (Some(x), Some(y)) = (scrollbars.x, scrollbars.y) {
let background =
style.gap.or(style.container.background);
if let Some(background) = background {
renderer.fill_quad(
renderer::Quad {
bounds: Rectangle {
x: y.bounds.x,
y: x.bounds.y,
width: y.bounds.width,
height: x.bounds.height,
},
..renderer::Quad::default()
},
background,
);
}
}
},
);
} else {
self.content.as_widget().draw(
&tree.children[0],
renderer,
theme,
defaults,
content_layout,
cursor,
&Rectangle {
x: bounds.x + translation.x,
y: bounds.y + translation.y,
..bounds
},
);
}
}
fn mouse_interaction(
&self,
tree: &Tree,
layout: Layout<'_>,
cursor: mouse::Cursor,
_viewport: &Rectangle,
renderer: &Renderer,
) -> mouse::Interaction {
let state = tree.state.downcast_ref::<State>();
let bounds = layout.bounds();
let cursor_over_scrollable = cursor.position_over(bounds);
let content_layout = layout.children().next().unwrap();
let content_bounds = content_layout.bounds();
let scrollbars =
Scrollbars::new(state, self.direction, bounds, content_bounds);
let (mouse_over_y_scrollbar, mouse_over_x_scrollbar) =
scrollbars.is_mouse_over(cursor);
if (mouse_over_x_scrollbar || mouse_over_y_scrollbar)
|| state.scrollers_grabbed()
{
mouse::Interaction::None
} else {
let translation =
state.translation(self.direction, bounds, content_bounds);
let cursor = match cursor_over_scrollable {
Some(cursor_position)
if !(mouse_over_x_scrollbar || mouse_over_y_scrollbar) =>
{
mouse::Cursor::Available(cursor_position + translation)
}
_ => mouse::Cursor::Unavailable,
};
self.content.as_widget().mouse_interaction(
&tree.children[0],
content_layout,
cursor,
&Rectangle {
y: bounds.y + translation.y,
x: bounds.x + translation.x,
..bounds
},
renderer,
)
}
}
fn overlay<'b>(
&'b mut self,
tree: &'b mut Tree,
layout: Layout<'_>,
renderer: &Renderer,
translation: Vector,
) -> Option<overlay::Element<'b, Message, Theme, Renderer>> {
let bounds = layout.bounds();
let content_layout = layout.children().next().unwrap();
let content_bounds = content_layout.bounds();
let offset = tree.state.downcast_ref::<State>().translation(
self.direction,
bounds,
content_bounds,
);
self.content.as_widget_mut().overlay(
&mut tree.children[0],
layout.children().next().unwrap(),
renderer,
translation - offset,
)
}
#[cfg(feature = "a11y")]
fn a11y_nodes(
&self,
layout: Layout<'_>,
state: &Tree,
cursor: mouse::Cursor,
) -> iced_accessibility::A11yTree {
use iced_accessibility::{
accesskit::{NodeBuilder, NodeId, Rect, Role},
A11yId, A11yNode, A11yTree,
};
let child_layout = layout.children().next().unwrap();
let child_tree = &state.children[0];
let child_tree = self.content.as_widget().a11y_nodes(
child_layout,
&child_tree,
cursor,
);
let window = layout.bounds();
let is_hovered = cursor.is_over(window);
let Rectangle {
x,
y,
width,
height,
} = window;
let bounds = Rect::new(
x as f64,
y as f64,
(x + width) as f64,
(y + height) as f64,
);
let mut node = NodeBuilder::new(Role::ScrollView);
node.set_bounds(bounds);
if let Some(name) = self.name.as_ref() {
node.set_name(name.clone());
}
match self.description.as_ref() {
Some(iced_accessibility::Description::Id(id)) => {
node.set_described_by(
id.iter()
.cloned()
.map(|id| NodeId::from(id))
.collect::<Vec<_>>(),
);
}
Some(iced_accessibility::Description::Text(text)) => {
node.set_description(text.clone());
}
None => {}
}
if is_hovered {
node.set_hovered();
}
if let Some(label) = self.label.as_ref() {
node.set_labelled_by(label.clone());
}
let content = layout.children().next().unwrap();
let content_bounds = content.bounds();
let mut scrollbar_node = NodeBuilder::new(Role::ScrollBar);
if matches!(state.state, tree::State::Some(_)) {
let state = state.state.downcast_ref::<State>();
let scrollbars = Scrollbars::new(
state,
self.direction,
content_bounds,
content_bounds,
);
for (window, content, offset, scrollbar) in scrollbars
.x
.iter()
.map(|s| {
(window.width, content_bounds.width, state.offset_x, s)
})
.chain(scrollbars.y.iter().map(|s| {
(window.height, content_bounds.height, state.offset_y, s)
}))
{
let scrollbar_bounds = scrollbar.total_bounds;
let is_hovered = cursor.is_over(scrollbar_bounds);
let Rectangle {
x,
y,
width,
height,
} = scrollbar_bounds;
let bounds = Rect::new(
x as f64,
y as f64,
(x + width) as f64,
(y + height) as f64,
);
scrollbar_node.set_bounds(bounds);
if is_hovered {
scrollbar_node.set_hovered();
}
scrollbar_node
.set_controls(vec![A11yId::Widget(self.id.clone()).into()]);
scrollbar_node.set_numeric_value(
100.0 * offset.absolute(window, content) as f64
/ scrollbar_bounds.height as f64,
);
}
}
let child_tree = A11yTree::join(
[
child_tree,
A11yTree::leaf(scrollbar_node, self.scrollbar_id.clone()),
]
.into_iter(),
);
A11yTree::node_with_child_tree(
A11yNode::new(node, self.id.clone()),
child_tree,
)
}
fn id(&self) -> Option<Id> {
Some(Id(Internal::Set(vec![
self.id.0.clone(),
self.scrollbar_id.0.clone(),
])))
}
fn set_id(&mut self, id: Id) {
if let Id(Internal::Set(list)) = id {
if list.len() == 2 {
self.id.0 = list[0].clone();
self.scrollbar_id.0 = list[1].clone();
}
}
}
fn drag_destinations(
&self,
tree: &Tree,
layout: Layout<'_>,
renderer: &Renderer,
dnd_rectangles: &mut crate::core::clipboard::DndDestinationRectangles,
) {
let my_state = tree.state.downcast_ref::<State>();
if let Some((c_layout, c_state)) =
layout.children().zip(tree.children.iter()).next()
{
let mut my_dnd_rectangles = DndDestinationRectangles::new();
self.content.as_widget().drag_destinations(
c_state,
c_layout,
renderer,
&mut my_dnd_rectangles,
);
let mut my_dnd_rectangles = my_dnd_rectangles.into_rectangles();
let bounds = layout.bounds();
let content_bounds = c_layout.bounds();
for r in &mut my_dnd_rectangles {
let translation = my_state.translation(
self.direction,
bounds,
content_bounds,
);
r.rectangle.x -= translation.x as f64;
r.rectangle.y -= translation.y as f64;
}
dnd_rectangles.append(&mut my_dnd_rectangles);
}
}
}
impl<'a, Message, Theme, Renderer>
From<Scrollable<'a, Message, Theme, Renderer>>
for Element<'a, Message, Theme, Renderer>
where
Message: 'a,
Theme: 'a + Catalog,
Renderer: 'a + core::Renderer,
{
fn from(
text_input: Scrollable<'a, Message, Theme, Renderer>,
) -> Element<'a, Message, Theme, Renderer> {
Element::new(text_input)
}
}
pub fn snap_to<T>(id: Id, offset: RelativeOffset) -> Task<T> {
task::effect(Action::widget(operation::scrollable::snap_to(id, offset)))
}
pub fn scroll_to<T>(id: Id, offset: AbsoluteOffset) -> Task<T> {
task::effect(Action::widget(operation::scrollable::scroll_to(id, offset)))
}
pub fn scroll_by<T>(id: Id, offset: AbsoluteOffset) -> Task<T> {
task::effect(Action::widget(operation::scrollable::scroll_by(id, offset)))
}
fn notify_scroll<Message>(
state: &mut State,
on_scroll: &Option<Box<dyn Fn(Viewport) -> Message + '_>>,
bounds: Rectangle,
content_bounds: Rectangle,
shell: &mut Shell<'_, Message>,
) -> bool {
if notify_viewport(state, on_scroll, bounds, content_bounds, shell) {
state.last_scrolled = Some(Instant::now());
true
} else {
false
}
}
fn notify_viewport<Message>(
state: &mut State,
on_scroll: &Option<Box<dyn Fn(Viewport) -> Message + '_>>,
bounds: Rectangle,
content_bounds: Rectangle,
shell: &mut Shell<'_, Message>,
) -> bool {
if content_bounds.width <= bounds.width
&& content_bounds.height <= bounds.height
{
return false;
}
let viewport = Viewport {
offset_x: state.offset_x,
offset_y: state.offset_y,
bounds,
content_bounds,
};
if let Some(last_notified) = state.last_notified {
let last_relative_offset = last_notified.relative_offset();
let current_relative_offset = viewport.relative_offset();
let last_absolute_offset = last_notified.absolute_offset();
let current_absolute_offset = viewport.absolute_offset();
let unchanged = |a: f32, b: f32| {
(a - b).abs() <= f32::EPSILON || (a.is_nan() && b.is_nan())
};
if last_notified.bounds == bounds
&& last_notified.content_bounds == content_bounds
&& unchanged(last_relative_offset.x, current_relative_offset.x)
&& unchanged(last_relative_offset.y, current_relative_offset.y)
&& unchanged(last_absolute_offset.x, current_absolute_offset.x)
&& unchanged(last_absolute_offset.y, current_absolute_offset.y)
{
return false;
}
}
state.last_notified = Some(viewport);
if let Some(on_scroll) = on_scroll {
shell.publish(on_scroll(viewport));
}
true
}
#[derive(Debug, Clone, Copy)]
struct State {
scroll_area_touched_at: Option<Point>,
offset_y: Offset,
y_scroller_grabbed_at: Option<f32>,
offset_x: Offset,
x_scroller_grabbed_at: Option<f32>,
keyboard_modifiers: keyboard::Modifiers,
last_notified: Option<Viewport>,
last_scrolled: Option<Instant>,
}
impl Default for State {
fn default() -> Self {
Self {
scroll_area_touched_at: None,
offset_y: Offset::Absolute(0.0),
y_scroller_grabbed_at: None,
offset_x: Offset::Absolute(0.0),
x_scroller_grabbed_at: None,
keyboard_modifiers: keyboard::Modifiers::default(),
last_notified: None,
last_scrolled: None,
}
}
}
impl operation::Scrollable for State {
fn snap_to(&mut self, offset: RelativeOffset) {
State::snap_to(self, offset);
}
fn scroll_to(&mut self, offset: AbsoluteOffset) {
State::scroll_to(self, offset);
}
fn scroll_by(
&mut self,
offset: AbsoluteOffset,
bounds: Rectangle,
content_bounds: Rectangle,
) {
State::scroll_by(self, offset, bounds, content_bounds);
}
}
#[derive(Debug, Clone, Copy)]
enum Offset {
Absolute(f32),
Relative(f32),
}
impl Offset {
fn absolute(self, viewport: f32, content: f32) -> f32 {
match self {
Offset::Absolute(absolute) => {
absolute.min((content - viewport).max(0.0))
}
Offset::Relative(percentage) => {
((content - viewport) * percentage).max(0.0)
}
}
}
fn translation(
self,
viewport: f32,
content: f32,
alignment: Anchor,
) -> f32 {
let offset = self.absolute(viewport, content);
match alignment {
Anchor::Start => offset,
Anchor::End => ((content - viewport).max(0.0) - offset).max(0.0),
}
}
}
#[derive(Debug, Clone, Copy)]
pub struct Viewport {
offset_x: Offset,
offset_y: Offset,
bounds: Rectangle,
content_bounds: Rectangle,
}
impl Viewport {
pub fn absolute_offset(&self) -> AbsoluteOffset {
let x = self
.offset_x
.absolute(self.bounds.width, self.content_bounds.width);
let y = self
.offset_y
.absolute(self.bounds.height, self.content_bounds.height);
AbsoluteOffset { x, y }
}
pub fn absolute_offset_reversed(&self) -> AbsoluteOffset {
let AbsoluteOffset { x, y } = self.absolute_offset();
AbsoluteOffset {
x: (self.content_bounds.width - self.bounds.width).max(0.0) - x,
y: (self.content_bounds.height - self.bounds.height).max(0.0) - y,
}
}
pub fn relative_offset(&self) -> RelativeOffset {
let AbsoluteOffset { x, y } = self.absolute_offset();
let x = x / (self.content_bounds.width - self.bounds.width);
let y = y / (self.content_bounds.height - self.bounds.height);
RelativeOffset { x, y }
}
pub fn bounds(&self) -> Rectangle {
self.bounds
}
pub fn content_bounds(&self) -> Rectangle {
self.content_bounds
}
}
impl State {
pub fn new() -> Self {
State::default()
}
pub fn scroll(
&mut self,
delta: Vector<f32>,
bounds: Rectangle,
content_bounds: Rectangle,
) {
if bounds.height < content_bounds.height {
self.offset_y = Offset::Absolute(
(self.offset_y.absolute(bounds.height, content_bounds.height)
+ delta.y)
.clamp(0.0, content_bounds.height - bounds.height),
);
}
if bounds.width < content_bounds.width {
self.offset_x = Offset::Absolute(
(self.offset_x.absolute(bounds.width, content_bounds.width)
+ delta.x)
.clamp(0.0, content_bounds.width - bounds.width),
);
}
}
pub fn scroll_y_to(
&mut self,
percentage: f32,
bounds: Rectangle,
content_bounds: Rectangle,
) {
self.offset_y = Offset::Relative(percentage.clamp(0.0, 1.0));
self.unsnap(bounds, content_bounds);
}
pub fn scroll_x_to(
&mut self,
percentage: f32,
bounds: Rectangle,
content_bounds: Rectangle,
) {
self.offset_x = Offset::Relative(percentage.clamp(0.0, 1.0));
self.unsnap(bounds, content_bounds);
}
pub fn snap_to(&mut self, offset: RelativeOffset) {
self.offset_x = Offset::Relative(offset.x.clamp(0.0, 1.0));
self.offset_y = Offset::Relative(offset.y.clamp(0.0, 1.0));
}
pub fn scroll_to(&mut self, offset: AbsoluteOffset) {
self.offset_x = Offset::Absolute(offset.x.max(0.0));
self.offset_y = Offset::Absolute(offset.y.max(0.0));
}
pub fn scroll_by(
&mut self,
offset: AbsoluteOffset,
bounds: Rectangle,
content_bounds: Rectangle,
) {
self.scroll(Vector::new(offset.x, offset.y), bounds, content_bounds);
}
pub fn unsnap(&mut self, bounds: Rectangle, content_bounds: Rectangle) {
self.offset_x = Offset::Absolute(
self.offset_x.absolute(bounds.width, content_bounds.width),
);
self.offset_y = Offset::Absolute(
self.offset_y.absolute(bounds.height, content_bounds.height),
);
}
fn translation(
&self,
direction: Direction,
bounds: Rectangle,
content_bounds: Rectangle,
) -> Vector {
Vector::new(
if let Some(horizontal) = direction.horizontal() {
self.offset_x.translation(
bounds.width,
content_bounds.width,
horizontal.alignment,
)
} else {
0.0
},
if let Some(vertical) = direction.vertical() {
self.offset_y.translation(
bounds.height,
content_bounds.height,
vertical.alignment,
)
} else {
0.0
},
)
}
pub fn scrollers_grabbed(&self) -> bool {
self.x_scroller_grabbed_at.is_some()
|| self.y_scroller_grabbed_at.is_some()
}
}
#[derive(Debug)]
struct Scrollbars {
y: Option<internals::Scrollbar>,
x: Option<internals::Scrollbar>,
}
impl Scrollbars {
fn new(
state: &State,
direction: Direction,
bounds: Rectangle,
content_bounds: Rectangle,
) -> Self {
let translation = state.translation(direction, bounds, content_bounds);
let show_scrollbar_x = direction.horizontal().filter(|scrollbar| {
scrollbar.spacing.is_some() || content_bounds.width > bounds.width
});
let show_scrollbar_y = direction.vertical().filter(|scrollbar| {
scrollbar.spacing.is_some() || content_bounds.height > bounds.height
});
let y_scrollbar = if let Some(vertical) = show_scrollbar_y {
let Scrollbar {
width,
margin,
scroller_width,
..
} = *vertical;
let x_scrollbar_height = show_scrollbar_x
.map_or(0.0, |h| h.width.max(h.scroller_width) + h.margin);
let total_scrollbar_width =
width.max(scroller_width) + 2.0 * margin;
let total_scrollbar_bounds = Rectangle {
x: bounds.x + bounds.width - total_scrollbar_width,
y: bounds.y,
width: total_scrollbar_width,
height: (bounds.height - x_scrollbar_height).max(0.0),
};
let scrollbar_bounds = Rectangle {
x: bounds.x + bounds.width
- total_scrollbar_width / 2.0
- width / 2.0,
y: bounds.y,
width,
height: (bounds.height - x_scrollbar_height).max(0.0),
};
let ratio = bounds.height / content_bounds.height;
let scroller = if ratio >= 1.0 {
None
} else {
let scroller_height =
(scrollbar_bounds.height * ratio).max(2.0);
let scroller_offset =
translation.y * ratio * scrollbar_bounds.height
/ bounds.height;
let scroller_bounds = Rectangle {
x: bounds.x + bounds.width
- total_scrollbar_width / 2.0
- scroller_width / 2.0,
y: (scrollbar_bounds.y + scroller_offset).max(0.0),
width: scroller_width,
height: scroller_height,
};
Some(internals::Scroller {
bounds: scroller_bounds,
})
};
Some(internals::Scrollbar {
total_bounds: total_scrollbar_bounds,
bounds: scrollbar_bounds,
scroller,
alignment: vertical.alignment,
})
} else {
None
};
let x_scrollbar = if let Some(horizontal) = show_scrollbar_x {
let Scrollbar {
width,
margin,
scroller_width,
..
} = *horizontal;
let scrollbar_y_width = y_scrollbar
.map_or(0.0, |scrollbar| scrollbar.total_bounds.width);
let total_scrollbar_height =
width.max(scroller_width) + 2.0 * margin;
let total_scrollbar_bounds = Rectangle {
x: bounds.x,
y: bounds.y + bounds.height - total_scrollbar_height,
width: (bounds.width - scrollbar_y_width).max(0.0),
height: total_scrollbar_height,
};
let scrollbar_bounds = Rectangle {
x: bounds.x,
y: bounds.y + bounds.height
- total_scrollbar_height / 2.0
- width / 2.0,
width: (bounds.width - scrollbar_y_width).max(0.0),
height: width,
};
let ratio = bounds.width / content_bounds.width;
let scroller = if ratio >= 1.0 {
None
} else {
let scroller_length = (scrollbar_bounds.width * ratio).max(2.0);
let scroller_offset =
translation.x * ratio * scrollbar_bounds.width
/ bounds.width;
let scroller_bounds = Rectangle {
x: (scrollbar_bounds.x + scroller_offset).max(0.0),
y: bounds.y + bounds.height
- total_scrollbar_height / 2.0
- scroller_width / 2.0,
width: scroller_length,
height: scroller_width,
};
Some(internals::Scroller {
bounds: scroller_bounds,
})
};
Some(internals::Scrollbar {
total_bounds: total_scrollbar_bounds,
bounds: scrollbar_bounds,
scroller,
alignment: horizontal.alignment,
})
} else {
None
};
Self {
y: y_scrollbar,
x: x_scrollbar,
}
}
fn is_mouse_over(&self, cursor: mouse::Cursor) -> (bool, bool) {
if let Some(cursor_position) = cursor.position() {
(
self.y
.as_ref()
.map(|scrollbar| scrollbar.is_mouse_over(cursor_position))
.unwrap_or(false),
self.x
.as_ref()
.map(|scrollbar| scrollbar.is_mouse_over(cursor_position))
.unwrap_or(false),
)
} else {
(false, false)
}
}
fn grab_y_scroller(&self, cursor_position: Point) -> Option<f32> {
let scrollbar = self.y?;
let scroller = scrollbar.scroller?;
if scrollbar.total_bounds.contains(cursor_position) {
Some(if scroller.bounds.contains(cursor_position) {
(cursor_position.y - scroller.bounds.y) / scroller.bounds.height
} else {
0.5
})
} else {
None
}
}
fn grab_x_scroller(&self, cursor_position: Point) -> Option<f32> {
let scrollbar = self.x?;
let scroller = scrollbar.scroller?;
if scrollbar.total_bounds.contains(cursor_position) {
Some(if scroller.bounds.contains(cursor_position) {
(cursor_position.x - scroller.bounds.x) / scroller.bounds.width
} else {
0.5
})
} else {
None
}
}
fn active(&self) -> bool {
self.y.is_some() || self.x.is_some()
}
}
pub(super) mod internals {
use crate::core::{Point, Rectangle};
use super::Anchor;
#[derive(Debug, Copy, Clone)]
pub struct Scrollbar {
pub total_bounds: Rectangle,
pub bounds: Rectangle,
pub scroller: Option<Scroller>,
pub alignment: Anchor,
}
impl Scrollbar {
pub fn is_mouse_over(&self, cursor_position: Point) -> bool {
self.total_bounds.contains(cursor_position)
}
pub fn scroll_percentage_y(
&self,
grabbed_at: f32,
cursor_position: Point,
) -> f32 {
if let Some(scroller) = self.scroller {
let percentage = (cursor_position.y
- self.bounds.y
- scroller.bounds.height * grabbed_at)
/ (self.bounds.height - scroller.bounds.height);
match self.alignment {
Anchor::Start => percentage,
Anchor::End => 1.0 - percentage,
}
} else {
0.0
}
}
pub fn scroll_percentage_x(
&self,
grabbed_at: f32,
cursor_position: Point,
) -> f32 {
if let Some(scroller) = self.scroller {
let percentage = (cursor_position.x
- self.bounds.x
- scroller.bounds.width * grabbed_at)
/ (self.bounds.width - scroller.bounds.width);
match self.alignment {
Anchor::Start => percentage,
Anchor::End => 1.0 - percentage,
}
} else {
0.0
}
}
}
#[derive(Debug, Clone, Copy)]
pub struct Scroller {
pub bounds: Rectangle,
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Status {
Active,
Hovered {
is_horizontal_scrollbar_hovered: bool,
is_vertical_scrollbar_hovered: bool,
},
Dragged {
is_horizontal_scrollbar_dragged: bool,
is_vertical_scrollbar_dragged: bool,
},
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Style {
pub container: container::Style,
pub vertical_rail: Rail,
pub horizontal_rail: Rail,
pub gap: Option<Background>,
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Rail {
pub background: Option<Background>,
pub border: Border,
pub scroller: Scroller,
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Scroller {
pub color: Color,
pub border: Border,
}
pub trait Catalog {
type Class<'a>;
fn default<'a>() -> Self::Class<'a>;
fn style(&self, class: &Self::Class<'_>, status: Status) -> Style;
}
pub type StyleFn<'a, Theme> = Box<dyn Fn(&Theme, Status) -> Style + 'a>;
impl Catalog for Theme {
type Class<'a> = StyleFn<'a, Self>;
fn default<'a>() -> Self::Class<'a> {
Box::new(default)
}
fn style(&self, class: &Self::Class<'_>, status: Status) -> Style {
class(self, status)
}
}
pub fn default(theme: &Theme, status: Status) -> Style {
let palette = theme.extended_palette();
let scrollbar = Rail {
background: Some(palette.background.weak.color.into()),
border: border::rounded(2),
scroller: Scroller {
color: palette.background.strong.color,
border: border::rounded(2),
},
};
match status {
Status::Active => Style {
container: container::Style::default(),
vertical_rail: scrollbar,
horizontal_rail: scrollbar,
gap: None,
},
Status::Hovered {
is_horizontal_scrollbar_hovered,
is_vertical_scrollbar_hovered,
} => {
let hovered_scrollbar = Rail {
scroller: Scroller {
color: palette.primary.strong.color,
..scrollbar.scroller
},
..scrollbar
};
Style {
container: container::Style::default(),
vertical_rail: if is_vertical_scrollbar_hovered {
hovered_scrollbar
} else {
scrollbar
},
horizontal_rail: if is_horizontal_scrollbar_hovered {
hovered_scrollbar
} else {
scrollbar
},
gap: None,
}
}
Status::Dragged {
is_horizontal_scrollbar_dragged,
is_vertical_scrollbar_dragged,
} => {
let dragged_scrollbar = Rail {
scroller: Scroller {
color: palette.primary.base.color,
..scrollbar.scroller
},
..scrollbar
};
Style {
container: container::Style::default(),
vertical_rail: if is_vertical_scrollbar_dragged {
dragged_scrollbar
} else {
scrollbar
},
horizontal_rail: if is_horizontal_scrollbar_dragged {
dragged_scrollbar
} else {
scrollbar
},
gap: None,
}
}
}
}