use iced::widget::{
button as iced_button, column, container, mouse_area, rich_text, row, span, text, Column, Row,
Space, Stack,
};
use iced::{Alignment, Element, Length, Padding, Point, Size};
use crate::a11y::{self, A11y, Role};
use crate::action::{Action, ActionTable};
use crate::collection::Tabs;
use crate::i18n::{align_start, order, Catalog, Direction};
use crate::icon::{Icon, Icons};
use crate::layout;
use crate::nav::NavStack;
use crate::style;
use crate::theme::Tokens;
use crate::typo;
use crate::variant::Variant;
use crate::widget::{
button, dismiss_button, group_box, icon_svg, label, meta, scroll, search_input, tab_bar,
text_input, ButtonOpts, CardFace, FieldOpts, LabelFace,
};
pub fn menu_groups<M: Clone>(table: &ActionTable<M>) -> Vec<(&str, Vec<&Action<M>>)> {
let mut groups: Vec<(&str, Vec<&Action<M>>)> = Vec::new();
for a in table.iter() {
let prefix = a.id.as_str().split('.').next().unwrap_or("app");
if let Some((_, list)) = groups.iter_mut().find(|(p, _)| *p == prefix) {
list.push(a);
} else {
groups.push((prefix, vec![a]));
}
}
groups
}
pub fn menu_heading(cat: &Catalog, prefix: &str) -> String {
let t = cat.t(prefix);
if t != prefix {
return t.to_string();
}
let mut chars = prefix.chars();
match chars.next() {
None => String::new(),
Some(first) => first.to_uppercase().chain(chars).collect(),
}
}
pub fn menu_item_label<M>(a: &Action<M>) -> String {
match &a.shortcut {
Some(sc) => format!("{} {sc}", a.title),
None => a.title.clone(),
}
}
pub fn pick_menu_message<M: Clone>(entries: &[(String, M)], chosen: &str) -> M {
entries
.iter()
.find(|(l, _)| l == chosen)
.map(|(_, m)| m.clone())
.expect("menu item")
}
fn bind_menu_pick<M: Clone>(entries: Vec<(String, M)>) -> impl Fn(String) -> M {
move |chosen| pick_menu_message(&entries, &chosen)
}
pub fn menu_bar<'a, M: Clone + 'a>(
table: &'a ActionTable<M>,
tok: Tokens,
dir: Direction,
cat: &Catalog,
on_open: impl Fn(bool) -> M + Clone + 'a,
) -> Element<'a, M> {
let groups = order(dir, menu_groups(table));
let mut titles = Row::new()
.spacing(0)
.padding([2.0, tok.density.gap() / 2.0]);
for (prefix, acts) in groups {
let heading = menu_heading(cat, prefix);
let entries: Vec<(String, M)> = acts
.into_iter()
.filter_map(|a| a.invoke().map(|m| (menu_item_label(a), m)))
.collect();
if entries.is_empty() {
titles = titles.push(meta(heading, tok, A11y::new(prefix, Role::Menu)));
continue;
}
let labels: Vec<String> = entries.iter().map(|(l, _)| l.clone()).collect();
titles = titles.push(crate::menubar::drop_menu(
heading,
labels,
bind_menu_pick(entries),
on_open.clone(),
tok,
));
}
crate::a11y::attach(
container(titles)
.width(Length::Fill)
.align_x(crate::i18n::align_start(dir))
.style(move |_| style::app_bar(tok))
.into(),
&A11y::new("menubar", Role::Menu),
)
}
pub fn toolbar<'a, M: Clone + 'a>(
actions: impl IntoIterator<Item = &'a Action<M>>,
tok: Tokens,
dir: Direction,
) -> Element<'a, M> {
let actions: Vec<_> = order(dir, actions);
let mut r = Row::new()
.spacing(crate::density::GRID as f32)
.padding(tok.density.gap());
for a in actions {
r = r.push(button(
a.title.clone(),
a.invoke(),
tok,
Variant::Quiet,
Icons::NONE,
ButtonOpts::SHRINK,
A11y::button(a.title.clone()).with_disabled(!a.enabled),
));
}
crate::a11y::attach(
container(r)
.width(Length::Fill)
.align_x(crate::i18n::align_start(dir))
.style(move |_| style::toolbar(tok))
.into(),
&A11y::new("toolbar", Role::Group),
)
}
pub fn command_bar<'a, M: Clone + 'a>(
actions: impl IntoIterator<Item = impl std::borrow::Borrow<Action<M>>>,
tok: Tokens,
dir: Direction,
) -> Element<'a, M> {
let owned: Vec<Action<M>> = actions.into_iter().map(|a| a.borrow().clone()).collect();
if owned.is_empty() {
return Space::new().width(0).height(0).into();
}
let actions = order(dir, owned);
let rail = container(Space::new().width(1).height(12)).style(move |_| style::hairline(tok));
let mut r = Row::new()
.spacing(2)
.align_y(Alignment::Center)
.push(container(rail).padding(Padding {
top: 1.0,
right: 6.0,
bottom: 1.0,
left: 2.0,
}));
for a in actions {
let face = text(a.title.clone())
.size(tok.body())
.color(tok.scheme().on_surface);
let mut b = iced_button(face)
.padding([2.0, tok.density.gap()])
.style(style::joined_button_style(tok, Variant::Ghost));
if let Some(m) = a.invoke() {
b = b.on_press(m);
}
r = r.push(crate::a11y::attach(
b.into(),
&A11y::button(a.title.clone()).with_disabled(!a.enabled),
));
}
let bar = crate::a11y::attach(r.into(), &A11y::new("commands", Role::Group));
container(bar)
.width(Length::Fill)
.align_x(crate::i18n::align_start(dir))
.into()
}
pub fn status_bar<'a, M: Clone + 'a>(
status: impl Into<String>,
tone: Option<crate::toast::ToastKind>,
caption: Option<&str>,
table: &ActionTable<M>,
tok: Tokens,
dir: Direction,
) -> Element<'a, M> {
let status = status.into();
let left: Element<'a, M> = if let Some(kind) = tone {
crate::widget::banner(
status.clone(),
None,
Some(kind),
tok,
A11y::new(status, Role::Status),
)
} else {
meta(status.clone(), tok, A11y::new(status, Role::Status))
};
let right = match caption {
Some(s) => Some(meta(s.to_string(), tok, A11y::new(s, Role::Status))),
None => status_hint_rail(table, tok),
};
let fill: Element<'a, M> = iced::widget::Space::new().width(Length::Fill).into();
let line = match right {
Some(r) => {
let ends = order(dir, [left, r]);
let mut ends = ends.into_iter();
row![ends.next().unwrap(), fill, ends.next().unwrap()]
}
None => {
let ends = order(dir, [left, fill]);
let mut ends = ends.into_iter();
row![ends.next().unwrap(), ends.next().unwrap()]
}
};
crate::a11y::attach(
container(line.padding([tok.density.gap(), tok.density.inset()]))
.width(Length::Fill)
.style(move |_| style::footer(tok))
.into(),
&A11y::new("statusbar", Role::Status),
)
}
fn status_hint_rail<'a, M: Clone + 'a>(
table: &ActionTable<M>,
tok: Tokens,
) -> Option<Element<'a, M>> {
let actions: Vec<_> = table
.iter()
.filter(|a| a.enabled && a.shortcut.is_some())
.cloned()
.collect();
if actions.is_empty() {
return None;
}
let name = actions
.iter()
.filter_map(|a| {
a.shortcut
.as_ref()
.map(|s| format!("{} {}", s, a.title.to_ascii_lowercase()))
})
.collect::<Vec<_>>()
.join(" · ");
let mut row = Row::new()
.spacing(tok.density.gap())
.align_y(Alignment::Center);
for (i, a) in actions.into_iter().enumerate() {
if i > 0 {
row = row.push(meta("·", tok, A11y::new("sep", Role::Status)));
}
let chord = a
.shortcut
.as_ref()
.map(|s| s.to_string())
.unwrap_or_default();
let title = a.title.to_ascii_lowercase();
let face = row![
text(chord).size(tok.meta()).color(tok.text).font(typo::UI),
text(format!(" {title}")).size(tok.meta()).color(tok.muted),
];
let mut b = iced_button(face)
.padding(0)
.style(style::joined_button_style(tok, Variant::Ghost));
if let Some(m) = a.invoke() {
b = b.on_press(m);
}
row = row.push(b);
}
Some(a11y::attach(row.into(), &A11y::new(name, Role::Status)))
}
#[allow(clippy::too_many_arguments)]
pub fn command_palette_view<'a, M: Clone + 'a>(
query: &str,
placeholder: &str,
results: &[&Action<M>],
selected: usize,
on_query: impl Fn(String) -> M + 'a,
on_pick: impl Fn(usize) -> M + Copy + 'a,
prompt: Option<&crate::palette::Prompt>,
on_prompt: impl Fn(String) -> M + 'a,
on_done: Option<M>,
progress: f32,
opts: crate::palette::PaletteOpts<'a, M>,
tok: Tokens,
a11y: A11y,
) -> Element<'a, M> {
let t = crate::motion::visual(progress, tok.reduced_motion);
let paint = tok.fade(t);
let dir = paint.direction;
let idle = query.trim().is_empty();
let mut list = Column::new().spacing(2);
let mut last_heading: Option<String> = None;
for (i, a) in results.iter().enumerate() {
if let Some(heading) = palette_heading(a, i, idle, &opts) {
if last_heading.as_deref() != Some(heading.as_str()) {
list = list.push(palette_group_heading(heading.clone(), paint, dir));
last_heading = Some(heading);
}
}
list = list.push(palette_hit(
a,
i == selected,
a.enabled.then(|| on_pick(i)),
query,
&opts,
paint,
dir,
));
}
let n = results.len();
let submit = (!results.is_empty() && selected < results.len()).then(|| on_pick(selected));
let query_field = search_input(
query,
on_query,
None,
submit,
paint,
A11y::new(placeholder, Role::TextBox),
Some(iced::widget::Id::new("palette-query")),
&[],
);
let mut fields = Column::new().spacing(6).align_x(align_start(dir));
fields = fields.push(query_field);
if let Some(page) = opts.page {
fields = fields.push(meta(
page.title.clone(),
paint,
A11y::new(page.title.clone(), Role::Header),
));
}
if let Some(p) = prompt {
fields = fields.push(
column![
meta(
p.label.clone(),
paint,
A11y::new(p.label.clone(), Role::Status)
),
text_input(
p.label.as_str(),
&p.value,
on_prompt,
on_done,
FieldOpts::NONE,
paint,
A11y::new("palette-arg", Role::TextBox),
Some(iced::widget::Id::new("palette-arg")),
),
]
.spacing(6),
);
}
let empty_kind = if idle {
opts.empty_idle
} else {
opts.empty_miss
};
let hits: Option<Element<'a, M>> = if n == 0 {
empty_kind.text(!idle).map(|copy| {
meta(
copy.to_string(),
paint,
A11y::new("palette-empty", Role::Status),
)
})
} else if n > opts.scroll_after {
Some(
container(scroll(
list.into(),
paint,
A11y::new("palette-list", Role::List),
false,
None,
None::<fn(_) -> M>,
))
.height(Length::Fixed(opts.scroll_height))
.into(),
)
} else {
Some(list.into())
};
let mut body = column![fields]
.spacing(tok.density.gap())
.align_x(align_start(dir));
if let Some(hits) = hits {
body = body.push(hits);
}
let panel = container(body)
.padding(tok.density.inset())
.width(opts.width)
.max_height(opts.max_height)
.align_x(align_start(dir))
.style(move |_| style::fade_face(style::menu_sheet(tok), t));
crate::a11y::attach(
crate::motion::overlay(
panel.into(),
t,
crate::motion::Slide::Down,
tok,
a11y.clone(),
),
&a11y,
)
}
fn palette_heading<M>(
action: &Action<M>,
index: usize,
idle: bool,
opts: &crate::palette::PaletteOpts<'_, M>,
) -> Option<String> {
if idle && opts.favorite_count > 0 && opts.group != crate::palette::PaletteGroup::None {
return Some(if index < opts.favorite_count {
opts.favorites_label.to_string()
} else {
opts.recent_label.to_string()
});
}
match opts.group {
crate::palette::PaletteGroup::None => None,
crate::palette::PaletteGroup::Section => action.section.clone(),
crate::palette::PaletteGroup::Prefix => Some(
action
.id
.as_str()
.split('.')
.next()
.unwrap_or("app")
.to_string(),
),
}
}
fn palette_group_heading<'a, M: Clone + 'a>(
label: String,
tok: Tokens,
dir: Direction,
) -> Element<'a, M> {
let s = tok.scheme();
a11y::attach(
container(
text(label.clone())
.size(tok.meta())
.color(s.on_surface_variant),
)
.padding(tok.density.inset())
.width(Length::Fill)
.align_x(align_start(dir))
.into(),
&A11y::new(label, Role::Header),
)
}
fn palette_hit<'a, M: Clone + 'a>(
action: &Action<M>,
selected: bool,
on_pick: Option<M>,
query: &str,
opts: &crate::palette::PaletteOpts<'a, M>,
tok: Tokens,
dir: Direction,
) -> Element<'a, M> {
use crate::palette::PaletteFace;
let s = tok.scheme();
let title: Element<'a, M> = if opts.highlight && !query.trim().is_empty() {
palette_title_highlight(action.title.as_str(), query, tok)
} else {
text(action.title.clone()).size(tok.body()).into()
};
let mut lead: Vec<Element<'a, M>> = Vec::new();
if let Some(slot) = opts.leading {
lead.push(slot(action, tok));
} else if let Some(ic) = action.icon {
lead.push(icon_svg(
ic,
tok,
A11y::new(action.title.clone(), Role::Image),
));
}
let mut col = Column::new().spacing(2);
col = col.push(title);
let show_tip = match opts.face {
PaletteFace::Compact => false,
PaletteFace::Default | PaletteFace::Detail => true,
};
if show_tip {
if let Some(tip) = &action.tooltip {
col = col.push(
text(tip.clone())
.size(tok.meta())
.color(s.on_surface_variant),
);
}
}
if opts.face == PaletteFace::Detail {
if let Some(section) = &action.section {
col = col.push(
text(section.clone())
.size(tok.meta())
.color(s.on_surface_variant),
);
}
match action.checked {
Some(true) => {
col = col.push(text("✓").size(tok.meta()).color(s.on_surface_variant));
}
Some(false) => {
col = col.push(text("â—‹").size(tok.meta()).color(s.on_surface_variant));
}
None => {}
}
}
lead.push(col.into());
let mut trail: Vec<Element<'a, M>> = Vec::new();
if let Some(slot) = opts.trailing {
trail.push(slot(action, tok));
} else if let Some(sc) = &action.shortcut {
trail.push(
text(sc.to_string())
.size(tok.meta())
.color(s.on_surface_variant)
.into(),
);
}
let mut line = Row::new()
.spacing(tok.density.gap())
.align_y(Alignment::Center);
let mut parts = lead;
parts.push(Space::new().width(Length::Fill).into());
parts.extend(trail);
for el in order(dir, parts) {
line = line.push(el);
}
let pad = match opts.face {
PaletteFace::Compact => (tok.density.inset() - 2.0).max(4.0),
PaletteFace::Default | PaletteFace::Detail => tok.density.inset(),
};
let mut b = iced_button(line)
.padding(pad)
.width(Length::Fill)
.style(style::palette_hit(tok, selected));
if let Some(msg) = on_pick {
b = b.on_press(msg);
}
a11y::attach(
b.into(),
&A11y::new(action.title.clone(), Role::MenuItem)
.with_checked(selected)
.with_disabled(!action.enabled),
)
}
fn palette_title_highlight<'a, M: Clone + 'a>(
title: &str,
query: &str,
tok: Tokens,
) -> Element<'a, M> {
let s = tok.scheme();
let ranges = match_ranges(query, title);
if ranges.is_empty() {
return text(title.to_string()).size(tok.body()).into();
}
let chars: Vec<char> = title.chars().collect();
let mut spans: Vec<iced::advanced::text::Span<'static, (), iced::Font>> = Vec::new();
let mut at = 0usize;
for (start, end) in ranges {
if start > at {
let chunk: String = chars[at..start].iter().collect();
spans.push(span(chunk).size(tok.body()).color(s.on_surface));
}
let chunk: String = chars[start..end].iter().collect();
spans.push(span(chunk).size(tok.body()).color(s.primary));
at = end;
}
if at < chars.len() {
let chunk: String = chars[at..].iter().collect();
spans.push(span(chunk).size(tok.body()).color(s.on_surface));
}
rich_text(spans).into()
}
pub(crate) fn match_ranges(query: &str, title: &str) -> Vec<(usize, usize)> {
let q = query.trim();
if q.is_empty() {
return Vec::new();
}
let title_l: String = title.to_ascii_lowercase();
let q_l = q.to_ascii_lowercase();
if let Some(byte) = title_l.find(&q_l) {
let start = title_l[..byte].chars().count();
return vec![(start, start + q.chars().count())];
}
let tchars: Vec<char> = title_l.chars().collect();
let qchars: Vec<char> = q_l.chars().collect();
let mut qi = 0;
let mut ranges = Vec::new();
let mut run: Option<(usize, usize)> = None;
for (i, ch) in tchars.iter().enumerate() {
if qi < qchars.len() && *ch == qchars[qi] {
match run {
Some((start, end)) if end == i => run = Some((start, i + 1)),
_ => {
if let Some(r) = run.take() {
ranges.push(r);
}
run = Some((i, i + 1));
}
}
qi += 1;
}
}
if let Some(r) = run {
ranges.push(r);
}
if qi == qchars.len() {
ranges
} else {
Vec::new()
}
}
pub fn status_page<'a, M: Clone + 'a>(
title: impl Into<String>,
body: impl Into<String>,
action: Option<(String, M)>,
tok: Tokens,
a11y: A11y,
) -> Element<'a, M> {
let title = title.into();
let body = body.into();
let mut col = column![
label(
title.clone(),
LabelFace::Body,
tok,
A11y::new(title, Role::Header)
),
meta(body.clone(), tok, A11y::new(body, Role::Status)),
]
.spacing(tok.density.gap())
.align_x(align_start(tok.direction));
if let Some((t, m)) = action {
col = col.push(button(
t.clone(),
Some(m),
tok,
Variant::Primary,
Icons::NONE,
ButtonOpts::SHRINK,
A11y::button(t),
));
}
crate::a11y::attach(
container(col)
.padding(tok.density.inset() * 2.0)
.center_x(Length::Fill)
.center_y(Length::Fill)
.width(Length::Fill)
.height(Length::Fill)
.into(),
&a11y,
)
}
pub fn about_page<'a, M: Clone + 'a>(
name: &'a str,
version: &'a str,
license: &'a str,
credits: &'a str,
tok: Tokens,
cat: &'a Catalog,
a11y: A11y,
) -> Element<'a, M> {
const ABOUT_WIDTH: f32 = 420.0;
let inner = (ABOUT_WIDTH - 2.0 * tok.density.sheet()).max(120.0);
let page = container(group_box(
cat.t("about"),
column![
text(name).size(tok.page()).color(tok.scheme().on_surface),
meta(version, tok, A11y::new(version, Role::Status)),
meta(license, tok, A11y::new(license, Role::Status)),
text(credits)
.size(tok.meta())
.color(tok.scheme().on_surface_variant)
.wrapping(iced::widget::text::Wrapping::Glyph)
.width(Length::Fixed(inner))
.align_x(align_start(tok.direction)),
]
.spacing(6.0)
.width(Length::Fill)
.align_x(align_start(tok.direction))
.into(),
tok,
CardFace::Elevated,
A11y::new(cat.t("about"), Role::Dialog),
None,
))
.width(Length::Fixed(ABOUT_WIDTH))
.into();
crate::a11y::attach(page, &a11y)
}
#[derive(Debug, Clone)]
pub struct PrefGroup {
pub title: String,
pub keys: Vec<(String, String)>,
}
pub fn filter_prefs<'a>(groups: &'a [PrefGroup], query: &str) -> Vec<&'a PrefGroup> {
let q = query.trim().to_ascii_lowercase();
if q.is_empty() {
return groups.iter().collect();
}
groups
.iter()
.filter(|g| {
g.title.to_ascii_lowercase().contains(&q)
|| g.keys.iter().any(|(k, v)| {
k.to_ascii_lowercase().contains(&q) || v.to_ascii_lowercase().contains(&q)
})
})
.collect()
}
pub fn preferences_page<'a, M: Clone + 'a>(
groups: &'a [PrefGroup],
query: &str,
on_query: impl Fn(String) -> M + 'a,
tok: Tokens,
cat: &Catalog,
a11y: A11y,
) -> Element<'a, M> {
let filtered = filter_prefs(groups, query);
let mut body = Column::new().spacing(tok.density.inset());
if filtered.is_empty() {
body = body.push(meta(
cat.t("empty"),
tok,
A11y::new(cat.t("empty"), Role::Status),
));
}
for g in filtered {
let mut lines = Column::new().spacing(4).align_x(align_start(tok.direction));
for (k, v) in &g.keys {
let line = format!("{k}: {v}");
lines = lines.push(meta(line.clone(), tok, A11y::new(line, Role::Status)));
}
body = body.push(group_box(
g.title.clone(),
lines.into(),
tok,
CardFace::Elevated,
A11y::new(g.title.clone(), Role::Group),
None,
));
}
let page = column![
text_input(
cat.t("search"),
query,
on_query,
None,
FieldOpts::NONE,
tok,
A11y::new(cat.t("search"), Role::TextBox),
None,
),
scroll(
body.into(),
tok,
A11y::new("prefs", Role::Group),
false,
None,
None::<fn(_) -> M>,
),
]
.spacing(tok.density.inset())
.into();
crate::a11y::attach(page, &a11y)
}
pub fn list_detail<'a, M: 'a>(
list: Element<'a, M>,
detail: Element<'a, M>,
sidebar: Length,
tok: Tokens,
dir: Direction,
a11y: A11y,
) -> Element<'a, M> {
let g = tok.density.gap();
let list_pad = match dir {
Direction::Ltr => iced::Padding {
top: g,
right: crate::density::GRID as f32,
bottom: g,
left: g,
},
Direction::Rtl => iced::Padding {
top: g,
right: g,
bottom: g,
left: crate::density::GRID as f32,
},
};
let list_pane: Element<'a, M> = container(list)
.width(sidebar)
.height(Length::Fill)
.padding(list_pad)
.clip(true)
.style(move |_| style::panel(tok))
.into();
let rule: Element<'a, M> = container(Space::new().width(1).height(Length::Fill))
.width(1)
.height(Length::Fill)
.style(move |_| style::hairline(tok))
.into();
let detail_pane: Element<'a, M> = container(detail)
.width(Length::Fill)
.height(Length::Fill)
.padding(iced::Padding::from(tok.density.inset()))
.into();
let mut row = Row::new();
for child in order(dir, [list_pane, rule, detail_pane]) {
row = row.push(child);
}
crate::a11y::attach(row.width(Length::Fill).height(Length::Fill).into(), &a11y)
}
#[allow(clippy::too_many_arguments)]
pub fn navigation_view<'a, M: Clone + 'a>(
sidebar: Element<'a, M>,
content: Element<'a, M>,
nav: &NavStack,
width: f32,
on_back: M,
tok: Tokens,
cat: &Catalog,
dir: Direction,
a11y: A11y,
) -> Element<'a, M> {
if crate::layout::Breakpoint::from_width(width).sidebar_beside() {
list_detail(
sidebar,
content,
crate::layout::fixed(260.0),
tok,
dir,
a11y,
)
} else {
let top = if nav.can_back() {
button(
cat.t("back"),
Some(on_back),
tok,
Variant::Quiet,
Icons::NONE,
ButtonOpts::SHRINK,
A11y::button(cat.t("back")),
)
} else {
crate::widget::icon_svg(Icon::Menu, tok, A11y::new("menu", Role::Image))
};
crate::a11y::attach(
column![top, content].spacing(tok.density.gap()).into(),
&a11y,
)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RailDest {
pub title: String,
pub icon: Option<Icon>,
pub badge: Option<String>,
}
impl RailDest {
pub fn new(title: impl Into<String>) -> Self {
Self {
title: title.into(),
icon: None,
badge: None,
}
}
pub fn with_icon(mut self, icon: Icon) -> Self {
self.icon = Some(icon);
self
}
pub fn with_badge(mut self, badge: impl Into<String>) -> Self {
self.badge = Some(badge.into());
self
}
}
impl From<&str> for RailDest {
fn from(title: &str) -> Self {
Self::new(title)
}
}
impl From<String> for RailDest {
fn from(title: String) -> Self {
Self::new(title)
}
}
pub fn nav_rail<'a, M: Clone + 'a>(
items: impl IntoIterator<Item = impl Into<RailDest>>,
selected: usize,
on_select: impl Fn(usize) -> M + Copy + 'a,
expanded: bool,
tok: Tokens,
a11y: A11y,
) -> Element<'a, M> {
let items: Vec<RailDest> = items.into_iter().map(Into::into).collect();
let mut col = Column::new().spacing(4).width(Length::Fill);
for (i, dest) in items.iter().enumerate() {
let on = i == selected;
let face_title = if expanded {
dest.title.clone()
} else {
dest.title
.chars()
.next()
.map(|c| c.to_string())
.unwrap_or_default()
};
let icons = dest.icon.map(Icons::leading).unwrap_or(Icons::NONE);
let mut face: Element<'a, M> = crate::widget::button(
face_title,
if a11y.disabled {
None
} else {
Some(on_select(i))
},
tok,
if on { Variant::Quiet } else { Variant::Ghost },
icons,
ButtonOpts::SHRINK,
A11y::button(dest.title.clone())
.with_checked(on)
.with_disabled(a11y.disabled),
);
if let Some(b) = dest.badge.as_ref().filter(|s| !s.is_empty()) {
face = crate::widget::badge(
b.clone(),
Some(face),
tok,
Variant::Primary,
crate::widget::BadgeSize::Small,
A11y::new(b.clone(), Role::Status),
);
}
let face = container(face)
.width(Length::Fill)
.style(move |_| style::nav_rail(tok, on));
col = col.push(face);
}
let n = items.len();
crate::a11y::attach(
crate::focus::group_keys(
container(col)
.width(if expanded { 220 } else { 72 })
.padding(tok.density.gap())
.style(move |_| style::panel(tok))
.into(),
tok,
!a11y.disabled && n > 0,
move |press| {
use crate::key::Press;
match press {
Press::ArrowDown | Press::ArrowRight => {
Some(on_select(crate::focus::rove(selected, 1, n)))
}
Press::ArrowUp | Press::ArrowLeft => {
Some(on_select(crate::focus::rove(selected, -1, n)))
}
Press::Home => Some(on_select(0)),
Press::End => Some(on_select(n.saturating_sub(1))),
_ => None,
}
},
),
&a11y,
)
}
pub fn tab_view<'a, M: Clone + 'a>(
tabs: &Tabs,
body: Element<'a, M>,
on_select: impl Fn(usize) -> M + Copy + 'a,
on_close: impl Fn(usize) -> M + Copy + 'a,
tok: Tokens,
a11y: A11y,
) -> Element<'a, M> {
crate::a11y::attach(
column![
tab_bar(
tabs,
on_select,
on_close,
0.0,
false,
tok,
A11y::new("tabs", Role::Tab)
),
body
]
.spacing(0)
.width(Length::Fill)
.height(Length::Fill)
.into(),
&a11y,
)
}
pub fn main_window<'a, M: Clone + 'a>(
menu: Element<'a, M>,
toolbar: Element<'a, M>,
center: Element<'a, M>,
status: Element<'a, M>,
tok: Tokens,
a11y: A11y,
) -> Element<'a, M> {
crate::a11y::attach(
container(layout::dock(
Some(column![menu, toolbar].into()),
Some(status),
None,
None,
center,
))
.width(Length::Fill)
.height(Length::Fill)
.style(move |_| style::shell(tok))
.into(),
&a11y,
)
}
fn modal_card<'a, M: 'a>(
backdrop: Element<'a, M>,
card: Element<'a, M>,
progress: f32,
tok: Tokens,
) -> Element<'a, M> {
let t = crate::motion::visual(progress, tok.reduced_motion);
let sheet = crate::motion::overlay(
card,
t,
crate::motion::Slide::Up,
tok,
A11y::new("modal-card", Role::Dialog),
);
Stack::new()
.push(backdrop)
.push(
container(Space::new().width(Length::Fill).height(Length::Fill))
.width(Length::Fill)
.height(Length::Fill)
.style(move |_| style::dim_backdrop_at(tok, t)),
)
.push(
container(sheet)
.width(Length::Fill)
.height(Length::Fill)
.center_x(Length::Fill)
.center_y(Length::Fill),
)
.into()
}
pub struct DialogOpts<'a, M> {
pub cancel: Option<(String, M)>,
pub extra: Vec<(String, M)>,
pub icon: Option<Icon>,
pub backdrop: Option<Element<'a, M>>,
pub progress: f32,
}
impl<M> Default for DialogOpts<'_, M> {
fn default() -> Self {
Self {
cancel: None,
extra: Vec::new(),
icon: None,
backdrop: None,
progress: 1.0,
}
}
}
pub fn dialog_sheet<'a, M: Clone + 'a>(
title: impl Into<String>,
body: impl Into<String>,
accept: (String, M),
tok: Tokens,
a11y: A11y,
opts: DialogOpts<'a, M>,
) -> Element<'a, M> {
let title = title.into();
let body = body.into();
let escape = opts.cancel.as_ref().map(|(_, m)| m.clone());
let DialogOpts {
cancel,
extra,
icon,
backdrop,
progress,
} = opts;
let mut acts: Vec<Element<'a, M>> = Vec::new();
for (t, m) in extra {
acts.push(button(
t.clone(),
Some(m),
tok,
Variant::Quiet,
Icons::NONE,
ButtonOpts::SHRINK,
A11y::button(t),
));
}
if let Some((t, m)) = cancel {
acts.push(button(
t.clone(),
Some(m),
tok,
Variant::Ghost,
Icons::NONE,
ButtonOpts::SHRINK,
A11y::button(t),
));
}
acts.push(button(
accept.0.clone(),
Some(accept.1),
tok,
Variant::Primary,
Icons::NONE,
ButtonOpts::SHRINK,
A11y::button(accept.0),
));
let mut actions = Row::new().spacing(tok.density.gap());
for el in order(tok.direction, acts) {
actions = actions.push(el);
}
let actions = container(actions)
.width(Length::Fill)
.align_x(crate::i18n::align_end(tok.direction));
let mut head_parts: Vec<Element<'a, M>> = Vec::new();
if let Some(ic) = icon {
head_parts.push(crate::widget::icon_svg(
ic,
tok,
A11y::new(title.clone(), Role::Image),
));
}
head_parts.push(crate::a11y::attach(
text(title.clone())
.size(tok.title())
.font(typo::UI_BOLD)
.color(tok.scheme().on_surface)
.into(),
&A11y::new(title.clone(), Role::Header),
));
let mut head = Row::new()
.spacing(tok.density.gap())
.align_y(Alignment::Center);
for el in order(tok.direction, head_parts) {
head = head.push(el);
}
let sheet = crate::a11y::attach(
container(
column![
head,
label(
body.clone(),
LabelFace::Body,
tok,
A11y::new(body, Role::Status)
),
actions,
]
.spacing(tok.density.sheet())
.width(Length::Fill),
)
.padding(tok.density.inset() * 2.0)
.width(Length::Fill)
.style(move |_| style::dialog_sheet_face(tok))
.into(),
&a11y,
);
let sheet = match escape {
Some(m) => crate::focus::dismiss_on_escape(sheet, m),
None => sheet,
};
match backdrop {
Some(scene) => modal_card(scene, sheet, progress, tok),
None => sheet,
}
}
#[derive(Debug, Clone)]
pub struct MenuSection<M> {
pub title: Option<String>,
pub actions: Vec<Action<M>>,
}
impl<M> MenuSection<M> {
pub fn new(title: impl Into<String>, actions: impl IntoIterator<Item = Action<M>>) -> Self {
Self {
title: {
let t = title.into();
if t.is_empty() {
None
} else {
Some(t)
}
},
actions: actions.into_iter().collect(),
}
}
pub fn untitled(actions: impl IntoIterator<Item = Action<M>>) -> Self {
Self {
title: None,
actions: actions.into_iter().collect(),
}
}
}
fn menu_section_divider<'a, M: 'a>(tok: Tokens) -> Element<'a, M> {
container(Space::new().width(Length::Fill).height(1))
.width(Length::Fill)
.padding([4, 0])
.style(move |_| style::hairline(tok))
.into()
}
pub fn sectioned_menu<'a, M: Clone + 'a>(
sections: impl IntoIterator<Item = MenuSection<M>>,
tok: Tokens,
a11y: A11y,
) -> Element<'a, M> {
let sections: Vec<_> = sections.into_iter().collect();
let start = crate::i18n::align_start(tok.direction);
let mut col = Column::new()
.spacing(2)
.padding(tok.density.gap())
.width(Length::Fill);
for (si, sec) in sections.into_iter().enumerate() {
if si > 0 {
col = col.push(menu_section_divider(tok));
}
if let Some(title) = sec.title {
col = col.push(
container(meta(title.clone(), tok, A11y::new(title, Role::Header)))
.width(Length::Fill)
.align_x(start)
.padding([crate::density::GRID as f32, tok.density.gap()]),
);
}
for a in sec.actions {
col = col.push(
container(button(
a.title.clone(),
a.invoke(),
tok,
Variant::Ghost,
Icons::NONE,
ButtonOpts::SHRINK,
A11y::new(a.title.clone(), Role::MenuItem).with_disabled(!a.enabled),
))
.width(Length::Fill)
.align_x(start),
);
}
}
crate::a11y::attach(
container(col).style(move |_| style::menu_sheet(tok)).into(),
&a11y,
)
}
pub fn cascade_menu<'a, M: Clone + 'a>(
entries: impl IntoIterator<Item = (Action<M>, Option<Vec<Action<M>>>)>,
open_sub: Option<usize>,
sub_progress: f32,
on_open_sub: impl Fn(Option<usize>) -> M + Copy + 'a,
tok: Tokens,
a11y: A11y,
) -> Element<'a, M> {
let entries: Vec<_> = entries.into_iter().collect();
let mut primary = Column::new().spacing(2).padding(tok.density.gap());
for (i, (act, kids)) in entries.iter().enumerate() {
let has_sub = kids.as_ref().map(|k| !k.is_empty()).unwrap_or(false);
let title = if has_sub {
match tok.direction {
Direction::Ltr => format!("{} â–¸", act.title),
Direction::Rtl => format!("â—‚ {}", act.title),
}
} else {
act.title.clone()
};
let press = if has_sub {
Some(on_open_sub(if open_sub == Some(i) {
None
} else {
Some(i)
}))
} else {
act.invoke()
};
primary = primary.push(button(
title.clone(),
press,
tok,
if open_sub == Some(i) {
Variant::Quiet
} else {
Variant::Ghost
},
Icons::NONE,
ButtonOpts::SHRINK,
A11y::new(title, Role::MenuItem).with_disabled(!act.enabled),
));
}
let left = container(primary)
.style(move |_| style::menu_sheet(tok))
.width(Length::Fixed(200.0));
let mut row = Row::new().spacing(4).align_y(Alignment::Start).push(left);
if let Some(i) = open_sub {
if let Some((_, Some(kids))) = entries.get(i) {
if !kids.is_empty() {
let t = crate::motion::visual(sub_progress, tok.reduced_motion);
let paint = tok.fade(t);
let sub = sectioned_menu(
vec![MenuSection::untitled(kids.clone())],
paint,
A11y::new("submenu", Role::Menu),
);
row = row.push(crate::motion::overlay(
sub,
t,
crate::motion::Slide::End,
tok,
A11y::new("submenu-motion", Role::Group),
));
}
}
}
crate::a11y::attach(row.into(), &a11y)
}
#[allow(clippy::too_many_arguments)]
pub fn side_sheet<'a, M: Clone + 'a>(
backdrop: Element<'a, M>,
title: impl Into<String>,
body: Element<'a, M>,
on_dismiss: Option<M>,
end: bool,
width: f32,
progress: f32,
tok: Tokens,
a11y: A11y,
) -> Element<'a, M> {
let title = title.into();
let t = crate::motion::visual(progress, tok.reduced_motion);
let paint = tok.fade(t);
let mut head_kids: Vec<Element<'a, M>> = vec![
label(
title.clone(),
LabelFace::Body,
paint,
A11y::new(title.clone(), Role::Header),
),
Space::new().width(Length::Fill).into(),
];
if let Some(m) = on_dismiss {
head_kids.push(dismiss_button(
m,
paint,
A11y::button(format!("close {title}")),
));
}
let mut head = Row::new()
.spacing(paint.density.gap())
.align_y(Alignment::Center);
for kid in crate::i18n::order(tok.direction, head_kids) {
head = head.push(kid);
}
let sheet = container(
column![head, body]
.spacing(paint.density.inset())
.width(Length::Fill)
.height(Length::Fill),
)
.padding(paint.density.sheet())
.width(Length::Fixed(width.max(200.0)))
.height(Length::Fill)
.style(move |_| style::fade_face(style::side_sheet_face(tok), t));
let from_physical_end = match tok.direction {
crate::i18n::Direction::Ltr => end,
crate::i18n::Direction::Rtl => !end,
};
let slide = if from_physical_end {
crate::motion::Slide::End
} else {
crate::motion::Slide::Start
};
let sheet = crate::motion::overlay(
sheet.into(),
t,
slide,
tok,
A11y::new(title.clone(), Role::Group),
);
let fill: Element<'a, M> = Space::new().width(Length::Fill).into();
let dock_kids = if end {
vec![fill, sheet]
} else {
vec![sheet, fill]
};
let mut dock_row = Row::new().height(Length::Fill).width(Length::Fill);
for kid in crate::i18n::order(tok.direction, dock_kids) {
dock_row = dock_row.push(kid);
}
let docked = container(dock_row).width(Length::Fill).height(Length::Fill);
let sheet_stack = Stack::new()
.push(backdrop)
.push(
container(Space::new().width(Length::Fill).height(Length::Fill))
.width(Length::Fill)
.height(Length::Fill)
.style(move |_| style::dim_backdrop_at(tok, t)),
)
.push(docked)
.width(Length::Fill)
.height(Length::Fill)
.into();
crate::a11y::attach(sheet_stack, &a11y)
}
fn context_row_h(density: crate::density::Density) -> f32 {
density.gap() * 3.0 + 10.0
}
pub fn context_card_size(n: usize, viewport: Size, density: crate::density::Density) -> Size {
const MENU_W: f32 = 220.0;
let row = context_row_h(density);
let pad = density.gap();
let natural = pad + (n.max(1) as f32) * row;
let max_h = (viewport.height * 0.5).max(row + pad);
Size::new(MENU_W.min(viewport.width.max(1.0)), natural.min(max_h))
}
pub fn context_origin(origin: Point, size: Size, viewport: Size) -> Point {
Point::new(
origin
.x
.min((viewport.width - size.width).max(0.0))
.max(0.0),
origin
.y
.min((viewport.height - size.height).max(0.0))
.max(0.0),
)
}
pub fn context_menu<'a, M: Clone + 'a>(
actions: impl IntoIterator<Item = Action<M>>,
origin: Point,
viewport: Size,
on_dismiss: M,
progress: f32,
tok: Tokens,
a11y: A11y,
) -> Element<'a, M> {
let t = crate::motion::visual(progress, tok.reduced_motion);
let paint = tok.fade(t);
let actions: Vec<Action<M>> = actions.into_iter().collect();
let n = actions.len();
let size = context_card_size(n, viewport, tok.density);
let at = context_origin(origin, size, viewport);
let mut col = Column::new()
.spacing(2)
.padding(paint.density.gap())
.width(Length::Fill);
for a in actions {
let a11y = A11y::new(a.title.clone(), Role::MenuItem).with_disabled(!a.enabled);
let face = container(
text(a.title.clone())
.size(tok.body())
.color(paint.scheme().on_surface),
)
.width(Length::Fill)
.align_x(crate::i18n::align_start(tok.direction));
let mut row = iced_button(face)
.padding(Padding::from([
paint.density.gap() / 2.0 + 2.0,
paint.density.gap() + 2.0,
]))
.width(Length::Fill)
.height(Length::Fixed(context_row_h(paint.density)))
.style(style::menu_item_style(paint));
if let Some(m) = a11y.apply_message(a.invoke()) {
row = row.on_press(m);
}
col = col.push(crate::a11y::attach(row.into(), &a11y));
}
let list: Element<'a, M> = col.into();
let inner = if size.height + 1.0
< paint.density.gap() + (n.max(1) as f32) * context_row_h(paint.density)
{
container(scroll(
list,
paint,
A11y::new("context-scroll", Role::Group),
false,
None,
None::<fn(_) -> M>,
))
.width(Length::Fixed(size.width))
.height(Length::Fixed(size.height))
} else {
container(list)
.width(Length::Fixed(size.width))
.height(Length::Fixed(size.height))
};
let card = crate::widget::capture_press(
container(inner)
.style(move |_| style::fade_face(style::menu_sheet(tok), t))
.into(),
);
let placed = column![
Space::new().height(Length::Fixed(at.y)),
row![Space::new().width(Length::Fixed(at.x)), card],
];
let stack = Stack::new()
.push(crate::widget::capture_press(
mouse_area(Space::new().width(Length::Fill).height(Length::Fill))
.on_press(on_dismiss.clone())
.into(),
))
.push(crate::motion::overlay(
placed.into(),
t,
crate::motion::Slide::Up,
tok,
A11y::new("context-motion", Role::Group),
))
.width(Length::Fill)
.height(Length::Fill)
.into();
crate::a11y::attach(crate::focus::dismiss_on_escape(stack, on_dismiss), &a11y)
}
pub fn inspector<'a, M: 'a>(
list: Element<'a, M>,
detail: Element<'a, M>,
props: Element<'a, M>,
tok: Tokens,
a11y: A11y,
) -> Element<'a, M> {
let list_pane: Element<'a, M> = container(list)
.width(layout::fixed(200.0))
.height(Length::Fill)
.style(move |_| style::panel(tok))
.into();
let detail_pane: Element<'a, M> = container(detail)
.width(Length::Fill)
.height(Length::Fill)
.into();
let props_pane: Element<'a, M> = container(props)
.width(layout::fixed(280.0))
.height(Length::Fill)
.padding(tok.density.inset())
.align_x(crate::i18n::align_start(tok.direction))
.style(move |_| style::panel(tok))
.into();
let mut row = Row::new().width(Length::Fill).height(Length::Fill);
for child in order(tok.direction, [list_pane, detail_pane, props_pane]) {
row = row.push(child);
}
crate::a11y::attach(row.into(), &a11y)
}
#[allow(clippy::too_many_arguments)]
pub fn workspace<'a, M: Clone + 'a>(
root: &crate::workspace::DockNode,
pane: impl Fn(&str) -> Element<'a, M> + Copy + 'a,
header: impl Fn(&str) -> Option<Element<'a, M>> + Copy + 'a,
viewport: Size,
on_sash: impl Fn(usize, layout::SashEvent) -> M + Copy + 'a,
on_tab: impl Fn(usize, usize) -> M + Copy + 'a,
tok: Tokens,
a11y: A11y,
) -> Element<'a, M> {
let mut paint = DockPaint {
pane,
header,
split_i: 0,
tab_i: 0,
on_sash,
on_tab,
tok,
};
crate::a11y::attach(
paint_dock(
root,
viewport.width.max(1.0),
viewport.height.max(1.0),
&mut paint,
),
&a11y,
)
}
struct DockPaint<'a, M, Pane, Header, Sash, Tab>
where
Pane: Fn(&str) -> Element<'a, M> + Copy + 'a,
Header: Fn(&str) -> Option<Element<'a, M>> + Copy + 'a,
Sash: Fn(usize, layout::SashEvent) -> M + Copy + 'a,
Tab: Fn(usize, usize) -> M + Copy + 'a,
{
pane: Pane,
header: Header,
split_i: usize,
tab_i: usize,
on_sash: Sash,
on_tab: Tab,
tok: Tokens,
}
fn paint_dock<'a, M, Pane, Header, Sash, Tab>(
node: &crate::workspace::DockNode,
width: f32,
height: f32,
paint: &mut DockPaint<'a, M, Pane, Header, Sash, Tab>,
) -> Element<'a, M>
where
M: Clone + 'a,
Pane: Fn(&str) -> Element<'a, M> + Copy + 'a,
Header: Fn(&str) -> Option<Element<'a, M>> + Copy + 'a,
Sash: Fn(usize, layout::SashEvent) -> M + Copy + 'a,
Tab: Fn(usize, usize) -> M + Copy + 'a,
{
let tok = paint.tok;
match node {
crate::workspace::DockNode::Leaf(p) => {
let body = (paint.pane)(&p.id);
let trailing = (paint.header)(&p.id);
group_box(
p.title.clone(),
body,
tok,
CardFace::Elevated,
A11y::new(p.id.clone(), Role::Group),
trailing,
)
}
crate::workspace::DockNode::Tabs { panes, active } => {
let gi = paint.tab_i;
paint.tab_i += 1;
let titles: Vec<String> = panes.iter().map(|p| p.title.clone()).collect();
let mut tabs = Tabs::new(titles);
tabs.active = (*active).min(panes.len().saturating_sub(1));
let id = panes.get(tabs.active).map(|p| p.id.as_str()).unwrap_or("");
let body = (paint.pane)(id);
let on_tab = paint.on_tab;
let pick = move |i| on_tab(gi, i);
tab_view(&tabs, body, pick, pick, tok, A11y::new("pat", Role::Group))
}
crate::workspace::DockNode::Split {
axis,
ratio,
first,
second,
} => {
let i = paint.split_i;
paint.split_i += 1;
let st = layout::SplitState::new(*axis, *ratio);
let total = match axis {
layout::Axis::Horizontal => width,
layout::Axis::Vertical => height,
};
let (fw, fh, sw, sh) = match axis {
layout::Axis::Horizontal => {
let a = st.first_size(width);
let b = st.second_size(width);
(a, height, b, height)
}
layout::Axis::Vertical => {
let a = st.first_size(height);
let b = st.second_size(height);
(width, a, width, b)
}
};
let left = paint_dock(first, fw, fh, paint);
let right = paint_dock(second, sw, sh, paint);
let on_sash = paint.on_sash;
layout::split_view(
left,
right,
st,
total,
move |ev| on_sash(i, ev),
paint.tok.direction,
paint.tok,
)
}
}
}
pub fn tool_panel<'a, M: Clone + 'a>(
title: impl Into<String>,
body: Element<'a, M>,
on_dock: Option<M>,
dock: impl Into<String>,
tok: Tokens,
a11y: A11y,
) -> Element<'a, M> {
let title = title.into();
let dock = dock.into();
let head = row![
iced::widget::Space::new().width(Length::Fill),
button(
dock.clone(),
a11y.apply_message(on_dock),
tok,
Variant::Ghost,
Icons::NONE,
ButtonOpts::SHRINK,
A11y::button(dock).with_disabled(a11y.disabled)
),
]
.spacing(tok.density.gap())
.padding([crate::density::GRID as f32, tok.density.gap()]);
crate::a11y::attach(
group_box(
title,
column![head, body].into(),
tok,
CardFace::Elevated,
a11y.clone(),
None,
),
&a11y,
)
}
pub fn drawer<'a, M: Clone + 'a>(
open: bool,
pane: Element<'a, M>,
content: Element<'a, M>,
progress: f32,
on_close: M,
tok: Tokens,
a11y: A11y,
) -> Element<'a, M> {
let t = crate::motion::visual(progress, tok.reduced_motion);
if !open && t <= 0.0 {
let _ = on_close;
crate::a11y::attach(content, &a11y)
} else {
let pane = crate::motion::expand(
container(pane).width(220.0).into(),
t,
0.0,
crate::motion::Axis::Inline,
tok,
A11y::new("drawer-pane", Role::Group),
);
crate::a11y::attach(
crate::focus::dismiss_on_escape(
list_detail(
pane,
content,
Length::Shrink,
tok,
tok.direction,
a11y.clone(),
),
on_close,
),
&a11y,
)
}
}
pub fn cheatsheet<'a, M: Clone + 'a>(
table: &ActionTable<M>,
query: &str,
tok: Tokens,
a11y: A11y,
) -> Element<'a, M> {
let q = query.trim().to_ascii_lowercase();
let rail = crate::chrome::SCROLL_RAIL_WIDTH;
let g = tok.density.gap();
let (left, right) = crate::i18n::inline_pad(tok.direction, g, g + rail);
let mut col = Column::new()
.spacing(crate::density::GRID as f32)
.padding(Padding {
top: g,
right,
bottom: g,
left,
});
for a in table.iter() {
if !a.enabled {
continue;
}
let blob = a.search_blob().to_ascii_lowercase();
if !q.is_empty() && !blob.contains(&q) {
continue;
}
let keys = a
.shortcut
.as_ref()
.map(|s| s.to_string())
.unwrap_or_else(|| "—".into());
let mut line = Row::new().align_y(Alignment::Center);
let title: Element<'a, M> = label(
a.title.clone(),
LabelFace::Body,
tok,
A11y::new(a.title.clone(), Role::Status),
);
let fill: Element<'a, M> = iced::widget::Space::new().width(Length::Fill).into();
let shortcut: Element<'a, M> = meta(keys.clone(), tok, A11y::new(keys, Role::Status));
for kid in order(tok.direction, [title, fill, shortcut]) {
line = line.push(kid);
}
col = col.push(line);
}
crate::a11y::attach(
scroll(
col.into(),
tok,
a11y.clone(),
false,
None,
None::<fn(_) -> M>,
),
&a11y,
)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::action::Action;
use crate::shortcut::Shortcut;
use crate::theme::named;
fn focusable_after_click<M: Clone>(
el: &mut Element<'_, M>,
size: iced::Size,
click: iced::Point,
) -> (usize, usize) {
use iced::advanced::layout::{Layout, Limits};
use iced::advanced::widget::operation::{focusable::Focusable, Operation};
use iced::advanced::widget::Tree;
use iced::{Event, Font, Pixels, Point, Rectangle};
struct Count {
n: usize,
focused: usize,
}
impl Operation<()> for Count {
fn focusable(
&mut self,
_id: Option<&iced::widget::Id>,
_bounds: Rectangle,
state: &mut dyn Focusable,
) {
self.n += 1;
if state.is_focused() {
self.focused += 1;
}
}
fn traverse(&mut self, operate: &mut dyn FnMut(&mut dyn Operation<()>)) {
operate(self);
}
}
let mut tree = Tree::new(el.as_widget());
let renderer = iced::Renderer::Secondary(iced_tiny_skia::Renderer::new(
Font::DEFAULT,
Pixels::from(16u32),
));
let limits = Limits::new(iced::Size::ZERO, size);
let node = el.as_widget_mut().layout(&mut tree, &renderer, &limits);
let layout = Layout::new(&node);
let mut messages = Vec::<M>::new();
{
let mut shell = iced::advanced::Shell::new(&mut messages);
let mut clipboard = iced::advanced::clipboard::Null;
el.as_widget_mut().update(
&mut tree,
&Event::Mouse(iced::mouse::Event::ButtonPressed(iced::mouse::Button::Left)),
layout,
iced::mouse::Cursor::Available(click),
&renderer,
&mut clipboard,
&mut shell,
&Rectangle::new(Point::ORIGIN, size),
);
}
let mut op = Count { n: 0, focused: 0 };
el.as_widget_mut()
.operate(&mut tree, layout, &renderer, &mut op);
(op.n, op.focused)
}
fn draw_once<M: Clone>(el: &mut Element<'_, M>) {
use iced::advanced::layout::{Layout, Limits};
use iced::advanced::renderer::Style;
use iced::advanced::widget::Tree;
use iced::mouse;
use iced::{Font, Pixels, Point, Rectangle, Size, Theme};
let mut tree = Tree::new(el.as_widget());
let mut renderer = iced::Renderer::Secondary(iced_tiny_skia::Renderer::new(
Font::DEFAULT,
Pixels::from(16u32),
));
let limits = Limits::new(Size::ZERO, Size::new(200.0, 400.0));
let node = el.as_widget_mut().layout(&mut tree, &renderer, &limits);
let layout = Layout::new(&node);
let viewport = Rectangle::new(Point::ORIGIN, Size::new(200.0, 400.0));
el.as_widget().draw(
&tree,
&mut renderer,
&Theme::Dark,
&Style::default(),
layout,
mouse::Cursor::Unavailable,
&viewport,
);
}
#[test]
fn nav_rail_click_focuses_when_it_has_items() {
let tok = crate::theme::named("dark").tokens;
let mut rail: Element<'_, usize> = nav_rail(
["Inbox", "Sent"],
0,
|i| i,
true,
tok,
A11y::new("rail", Role::List),
);
let (n, focused) = focusable_after_click(
&mut rail,
iced::Size::new(220.0, 200.0),
iced::Point::new(20.0, 20.0),
);
assert!(n >= 1);
assert!(focused >= 1);
let got = {
use iced::advanced::clipboard;
use iced::advanced::layout::{Layout, Limits};
use iced::advanced::widget::Tree;
use iced::{Event, Font, Pixels, Rectangle, Size};
let mut el: Element<'_, usize> = nav_rail(
["Inbox", "Sent", "Drafts"],
0,
|i| i,
true,
tok,
A11y::new("rail-keys", Role::List),
);
let mut tree = Tree::new(el.as_widget());
let renderer = iced::Renderer::Secondary(iced_tiny_skia::Renderer::new(
Font::DEFAULT,
Pixels::from(16u32),
));
let size = Size::new(220.0, 200.0);
let node =
el.as_widget_mut()
.layout(&mut tree, &renderer, &Limits::new(Size::ZERO, size));
let layout = Layout::new(&node);
let vp = Rectangle::new(iced::Point::ORIGIN, size);
let mut clipboard = clipboard::Null;
{
let mut messages = Vec::new();
let mut shell = iced::advanced::Shell::new(&mut messages);
el.as_widget_mut().update(
&mut tree,
&Event::Mouse(iced::mouse::Event::ButtonPressed(iced::mouse::Button::Left)),
layout,
iced::mouse::Cursor::Available(iced::Point::new(20.0, 20.0)),
&renderer,
&mut clipboard,
&mut shell,
&vp,
);
}
let mut messages = Vec::new();
for named in [
iced::keyboard::key::Named::ArrowDown,
iced::keyboard::key::Named::ArrowUp,
iced::keyboard::key::Named::Home,
iced::keyboard::key::Named::End,
iced::keyboard::key::Named::Escape,
] {
let mut shell = iced::advanced::Shell::new(&mut messages);
el.as_widget_mut().update(
&mut tree,
&Event::Keyboard(iced::keyboard::Event::KeyPressed {
key: iced::keyboard::Key::Named(named),
modified_key: iced::keyboard::Key::Named(named),
physical_key: iced::keyboard::key::Physical::Unidentified(
iced::keyboard::key::NativeCode::Unidentified,
),
location: iced::keyboard::Location::Standard,
modifiers: iced::keyboard::Modifiers::empty(),
text: None,
repeat: false,
}),
layout,
iced::mouse::Cursor::Unavailable,
&renderer,
&mut clipboard,
&mut shell,
&vp,
);
}
messages
};
assert_eq!(got, vec![1, 2, 0, 2]);
let mut empty: Element<'_, usize> = nav_rail(
Vec::<String>::new(),
0,
|i| i,
true,
tok,
A11y::new("rail-empty", Role::List),
);
let (n, focused) = focusable_after_click(
&mut empty,
iced::Size::new(220.0, 200.0),
iced::Point::new(20.0, 20.0),
);
assert_eq!(n, 0);
assert_eq!(focused, 0);
}
#[test]
fn drawer_escape_closes_when_open() {
let tok = crate::theme::named("dark").tokens;
let mut el: Element<'_, u8> = drawer(
true,
crate::widget::label(
"n",
crate::widget::LabelFace::Body,
tok,
A11y::new("n", Role::Group),
),
crate::widget::label(
"c",
crate::widget::LabelFace::Body,
tok,
A11y::new("c", Role::Status),
),
1.0,
1,
tok,
A11y::new("drawer", Role::Group),
);
use iced::advanced::clipboard;
use iced::advanced::layout::{Layout, Limits};
use iced::advanced::widget::Tree;
use iced::{Event, Font, Pixels, Rectangle, Size};
let mut tree = Tree::new(el.as_widget());
let renderer = iced::Renderer::Secondary(iced_tiny_skia::Renderer::new(
Font::DEFAULT,
Pixels::from(16u32),
));
let size = Size::new(400.0, 200.0);
let node = el
.as_widget_mut()
.layout(&mut tree, &renderer, &Limits::new(Size::ZERO, size));
let layout = Layout::new(&node);
let vp = Rectangle::new(iced::Point::ORIGIN, size);
let mut messages = Vec::new();
{
let mut shell = iced::advanced::Shell::new(&mut messages);
let mut clipboard = clipboard::Null;
el.as_widget_mut().update(
&mut tree,
&Event::Keyboard(iced::keyboard::Event::KeyPressed {
key: iced::keyboard::Key::Named(iced::keyboard::key::Named::Escape),
modified_key: iced::keyboard::Key::Named(iced::keyboard::key::Named::Escape),
physical_key: iced::keyboard::key::Physical::Unidentified(
iced::keyboard::key::NativeCode::Unidentified,
),
location: iced::keyboard::Location::Standard,
modifiers: iced::keyboard::Modifiers::empty(),
text: None,
repeat: false,
}),
layout,
iced::mouse::Cursor::Unavailable,
&renderer,
&mut clipboard,
&mut shell,
&vp,
);
}
assert_eq!(messages, vec![1]);
}
#[test]
fn nav_rail_builds_selected_and_empty() {
let tok = crate::theme::named("dark").tokens;
let mut rail: Element<'_, usize> = nav_rail(
["Inbox", "Sent"],
0,
|i| i,
true,
tok,
A11y::new("rail", Role::List),
);
draw_once(&mut rail);
let mut compact: Element<'_, usize> = nav_rail(
["Inbox", "Sent"],
0,
|i| i,
false,
tok,
A11y::new("rail-compact", Role::List),
);
draw_once(&mut compact);
let mut off: Element<'_, usize> = nav_rail(
["Inbox"],
1,
|i| i,
true,
tok,
A11y::new("rail-off", Role::List).with_disabled(true),
);
draw_once(&mut off);
let mut empty: Element<'_, usize> = nav_rail(
Vec::<String>::new(),
0,
|i| i,
false,
tok,
A11y::new("rail-empty", Role::List).with_disabled(true),
);
draw_once(&mut empty);
let _ = RailDest::from(String::from("Other"));
let dest = RailDest::new(String::from("Mail"))
.with_icon(Icon::Menu)
.with_badge("2");
let mut badged: Element<'_, usize> = nav_rail(
[dest],
0,
|i| i,
true,
tok,
A11y::new("rail-badge", Role::List),
);
draw_once(&mut badged);
let mut dlg: Element<'_, ()> = dialog_sheet(
"Save",
"Overwrite?",
("Save".into(), ()),
tok,
A11y::new("Save", Role::Dialog),
DialogOpts {
cancel: Some(("Cancel".into(), ())),
extra: vec![("Keep".into(), ())],
icon: Some(Icon::Warning),
..DialogOpts::default()
},
);
draw_once(&mut dlg);
let scene = crate::widget::label(
" ",
crate::widget::LabelFace::Body,
tok,
A11y::new("dim", Role::Status),
);
let mut dimmed: Element<'_, ()> = dialog_sheet(
"Save",
"Overwrite?",
("Save".into(), ()),
tok,
A11y::new("Save", Role::Dialog),
DialogOpts {
backdrop: Some(scene),
progress: 1.0,
..DialogOpts::default()
},
);
draw_once(&mut dimmed);
}
#[test]
fn dialog_sheet_puts_confirm_on_the_end() {
use iced::advanced::layout::{Layout, Limits};
use iced::advanced::widget::Tree;
use iced::{Font, Pixels, Size};
fn action_widths(el: &mut Element<'_, ()>) -> Vec<f32> {
let mut tree = Tree::new(el.as_widget());
let renderer = iced::Renderer::Secondary(iced_tiny_skia::Renderer::new(
Font::DEFAULT,
Pixels::from(16u32),
));
let limits = Limits::new(Size::ZERO, Size::new(480.0, 240.0));
let node = el.as_widget_mut().layout(&mut tree, &renderer, &limits);
let layout = Layout::new(&node);
let mut boxes = Vec::new();
fn walk(layout: Layout<'_>, boxes: &mut Vec<iced::Rectangle>) {
boxes.push(layout.bounds());
for child in layout.children() {
walk(child, boxes);
}
}
walk(layout, &mut boxes);
let mut row: Vec<_> = boxes
.into_iter()
.filter(|b| b.height > 24.0 && b.height < 48.0 && b.width > 36.0 && b.width < 180.0)
.collect();
row.sort_by(|a, b| a.x.partial_cmp(&b.x).unwrap());
row.into_iter().map(|b| b.width).collect()
}
let ltr = crate::theme::named("dark").tokens;
let rtl = ltr.with_direction(crate::i18n::Direction::Rtl);
let mk = |tok| {
dialog_sheet(
"Save",
"Overwrite?",
("Save".into(), ()),
tok,
A11y::new("Save", Role::Dialog),
DialogOpts {
cancel: Some(("Cancel".into(), ())),
extra: vec![("Don't save".into(), ())],
..DialogOpts::default()
},
)
};
let ltr_w = action_widths(&mut mk(ltr));
let rtl_w = action_widths(&mut mk(rtl));
assert!(ltr_w.len() >= 3 && rtl_w.len() >= 3);
assert!(ltr_w[0] > ltr_w[ltr_w.len() - 1]);
assert!(rtl_w[0] < rtl_w[rtl_w.len() - 1]);
}
#[test]
fn sectioned_cascade_and_side_sheet_build() {
let tok = crate::theme::named("dark").tokens;
let save = Action::new("file.save", "Save", ());
let open = Action::new("file.open", "Open", ());
let _: Element<'_, ()> = sectioned_menu(
vec![
MenuSection::new("File", [save.clone(), open.clone()]),
MenuSection::new("", [Action::new("app.about", "About", ())]),
MenuSection::untitled([Action::new("app.quit", "Quit", ())]),
],
tok,
A11y::new("m", Role::Menu),
);
let mut open_sub = cascade_menu(
vec![
(
Action::new("file.recent", "Recent", None),
Some(vec![Action::new("file.r1", "a", Some(0))]),
),
(
Action::new("file.more", "More", None),
Some(vec![Action::new("file.m1", "b", Some(1))]),
),
(Action::new("file.open", "Open", Some(9)), None),
(Action::new("file.none", "Empty", None), Some(vec![])),
],
Some(0),
1.0,
|i| i,
tok,
A11y::new("c", Role::Menu),
);
draw_once(&mut open_sub);
let mut mid_sub = cascade_menu(
vec![(
Action::new("file.recent", "Recent", None),
Some(vec![Action::new("file.r1", "a", Some(0))]),
)],
Some(0),
0.4,
|i| i,
tok,
A11y::new("c-mid", Role::Menu),
);
draw_once(&mut mid_sub);
let _: Element<'_, Option<usize>> = cascade_menu(
vec![(
Action::new("file.recent", "Recent", None),
Some(vec![Action::new("file.r1", "a", Some(0))]),
)],
Some(99),
0.4,
|i| i,
tok,
A11y::new("c-miss", Role::Menu),
);
let _: Element<'_, Option<usize>> = cascade_menu(
vec![(Action::new("x", "X", Some(1)), None)],
None,
0.0,
|i| i,
tok,
A11y::new("c2", Role::Menu),
);
let body = label(
"x",
crate::widget::LabelFace::Body,
tok,
A11y::new("x", Role::Status),
);
let scene = label(
"s",
crate::widget::LabelFace::Body,
tok,
A11y::new("s", Role::Status),
);
let mut sheet: Element<'_, ()> = side_sheet(
scene,
"I",
body,
Some(()),
true,
240.0,
1.0,
tok,
A11y::new("pat", Role::Group),
);
draw_once(&mut sheet);
let body = label(
"x",
crate::widget::LabelFace::Body,
tok,
A11y::new("x", Role::Status),
);
let scene = label(
"s",
crate::widget::LabelFace::Body,
tok,
A11y::new("s", Role::Status),
);
let _: Element<'_, ()> = side_sheet(
scene,
"L",
body,
None,
false,
100.0,
1.0,
tok,
A11y::new("pat", Role::Group),
);
let rtl = tok.with_direction(crate::i18n::Direction::Rtl);
let body = label("x", LabelFace::Body, rtl, A11y::new("x", Role::Status));
let scene = label("s", LabelFace::Body, rtl, A11y::new("s", Role::Status));
let mut rtl_end: Element<'_, ()> = side_sheet(
scene,
"I",
body,
Some(()),
true,
240.0,
1.0,
rtl,
A11y::new("pat", Role::Group),
);
draw_once(&mut rtl_end);
let body = label("x", LabelFace::Body, rtl, A11y::new("x", Role::Status));
let scene = label("s", LabelFace::Body, rtl, A11y::new("s", Role::Status));
let mut rtl_start: Element<'_, ()> = side_sheet(
scene,
"L",
body,
None,
false,
100.0,
1.0,
rtl,
A11y::new("pat", Role::Group),
);
draw_once(&mut rtl_start);
assert!(MenuSection::<()>::untitled([]).title.is_none());
assert!(MenuSection::<()>::new("", []).title.is_none());
assert_eq!(MenuSection::<()>::new("T", []).title.as_deref(), Some("T"));
let _: Element<'_, ()> = menu_section_divider(tok);
assert!(style::hairline(tok).background.is_some());
assert!(style::dialog_sheet_face(tok).background.is_some());
assert!(style::dim_backdrop(tok).background.is_some());
assert!(style::raised_card(tok).background.is_some());
assert!(style::app_bar(tok).background.is_some());
assert!(style::panel(tok).background.is_some());
assert!(style::footer(tok).background.is_some());
assert!(style::shell(tok).background.is_some());
assert!(style::card(tok, true).background.is_some());
assert!(style::card(tok, false).background.is_some());
assert!(style::list_row(tok, true).background.is_some());
assert!(style::list_row(tok, false).background.is_some());
assert!(style::nav_rail(tok, true).background.is_some());
assert!(style::nav_rail(tok, false).background.is_some());
assert!(style::tab_indicator(tok).background.is_some());
let theme = crate::theme::iced_theme("dark", tok);
let _ = style::button_style(tok, Variant::Primary)(
&theme,
iced::widget::button::Status::Active,
);
let _ =
style::button_style(tok, Variant::Quiet)(&theme, iced::widget::button::Status::Hovered);
let _ =
style::button_style(tok, Variant::Ghost)(&theme, iced::widget::button::Status::Pressed);
let _ = style::button_style(tok, Variant::Danger)(
&theme,
iced::widget::button::Status::Disabled,
);
let _ = style::tab_style(tok, true)(&theme, iced::widget::button::Status::Active);
let _ = style::tab_style(tok, false)(&theme, iced::widget::button::Status::Hovered);
let _ = style::palette_hit(tok, true)(&theme, iced::widget::button::Status::Active);
let _ = style::palette_hit(tok, false)(&theme, iced::widget::button::Status::Hovered);
let _ = style::search_style(tok)(
&theme,
iced::widget::text_input::Status::Focused { is_hovered: false },
);
let _ = style::slider_style(tok)(&theme, iced::widget::slider::Status::Dragged);
let _ = style::progress_style(tok)(&theme);
let _ = style::rule_style(tok)(&theme);
let _ = style::scroll_style(tok)(
&theme,
iced::widget::scrollable::Status::Active {
is_horizontal_scrollbar_disabled: false,
is_vertical_scrollbar_disabled: false,
},
);
let _ = style::scroll_style(tok)(
&theme,
iced::widget::scrollable::Status::Hovered {
is_horizontal_scrollbar_hovered: true,
is_vertical_scrollbar_hovered: false,
is_horizontal_scrollbar_disabled: false,
is_vertical_scrollbar_disabled: false,
},
);
let _ = style::checkbox_style(tok)(
&theme,
iced::widget::checkbox::Status::Hovered { is_checked: true },
);
let _ = style::radio_style(tok)(
&theme,
iced::widget::radio::Status::Hovered { is_selected: true },
);
let _ = style::switch_style(tok)(
&theme,
iced::widget::toggler::Status::Disabled { is_toggled: false },
);
let _ = style::overlay_menu_style(tok)(&theme);
let _ = style::picker_style(tok)(
&theme,
iced::widget::pick_list::Status::Opened { is_hovered: true },
);
}
#[test]
fn pref_filter_and_patterns_build() {
let prefs = [
PrefGroup {
title: "Appearance".into(),
keys: vec![("theme".into(), "dark".into())],
},
PrefGroup {
title: "Editor".into(),
keys: vec![("tab".into(), "4".into())],
},
];
assert_eq!(filter_prefs(&prefs, "").len(), 2);
assert_eq!(filter_prefs(&prefs, "theme").len(), 1);
assert_eq!(filter_prefs(&prefs, "nope").len(), 0);
let tok = named("dark").tokens;
let cat = Catalog::builtin();
let mut table = ActionTable::new();
table.insert(
Action::new("file.save", "Save", ()).with_shortcut(Shortcut::parse("ctrl+s").unwrap()),
);
table.insert(Action::new("edit.undo", "Undo", ()));
table.insert(Action::new("file.open", "Open", ()));
let ltr = Direction::Ltr;
let rtl = Direction::Rtl;
let menus = menu_groups(&table);
assert_eq!(menus.len(), 2);
assert_eq!(menus[0].0, "file");
assert_eq!(menu_heading(&cat, "file"), "File");
assert_eq!(menu_heading(&cat, "custom"), "Custom");
assert_eq!(menu_heading(&cat, ""), "");
let save = table.iter().find(|a| a.id.as_str() == "file.save").unwrap();
let cmd = "cmd+s";
let ctrl = "ctrl+s";
let host = if cfg!(target_os = "macos") { cmd } else { ctrl };
assert!(menu_item_label(save).contains(host));
let undo = table.iter().find(|a| a.id.as_str() == "edit.undo").unwrap();
assert_eq!(menu_item_label(undo), "Undo");
assert_eq!(
pick_menu_message(&[("Open".into(), 1u8), ("Save".into(), 2)], "Save"),
2
);
assert_eq!(
bind_menu_pick(vec![("Open".into(), 1u8), ("Save".into(), 2)])("Open".into()),
1
);
let _: Element<'_, ()> = menu_bar(&table, tok, ltr, &cat, |_| ());
let _: Element<'_, ()> = menu_bar(&table, tok, rtl, &cat, |_| ());
let src = include_str!("pattern.rs");
let bar_src = src
.split("pub fn menu_bar")
.nth(1)
.unwrap()
.split("pub fn toolbar")
.next()
.unwrap();
assert!(bar_src.contains("align_start(dir)"));
let tool_src = src
.split("pub fn toolbar")
.nth(1)
.unwrap()
.split("pub fn command_bar")
.next()
.unwrap();
assert!(tool_src.contains("align_start(dir)"));
let sec_src = src
.split("pub fn sectioned_menu")
.nth(1)
.unwrap()
.split("pub fn cascade_menu")
.next()
.unwrap();
assert!(sec_src.contains("align_start(tok.direction)"));
let empty = ActionTable::new();
let _: Element<'_, ()> = menu_bar(&empty, tok, ltr, &cat, |_| ());
let mut disabled = ActionTable::new();
let mut dead = Action::new("file.dead", "Dead", ());
dead.enabled = false;
disabled.insert(dead);
let _: Element<'_, ()> = menu_bar(&disabled, tok, ltr, &cat, |_| ());
let _: Element<'_, ()> = dialog_sheet(
"Save",
"Overwrite notes.txt?",
("Save".into(), ()),
tok,
A11y::new("Save", Role::Dialog),
DialogOpts {
cancel: Some(("Cancel".into(), ())),
..DialogOpts::default()
},
);
let _: Element<'_, ()> = dialog_sheet(
"Note",
"Hello",
("OK".into(), ()),
tok,
A11y::new("Note", Role::Dialog),
DialogOpts::default(),
);
let acts: Vec<_> = table.iter().collect();
let src = include_str!("pattern.rs");
let palette_src = src
.split("pub fn command_palette_view")
.nth(1)
.unwrap()
.split("pub fn status_page")
.next()
.unwrap();
assert!(!palette_src.contains("A11y::new(query"));
assert!(palette_src.contains("Id::new(\"palette-query\""));
let pref_src = src
.split("pub fn preferences_page")
.nth(1)
.unwrap()
.split("pub fn list_detail")
.next()
.unwrap();
assert!(!pref_src.contains("A11y::new(query"));
let ld_src = src
.split("pub fn list_detail")
.nth(1)
.unwrap()
.split("pub fn navigation_view")
.next()
.unwrap();
assert!(ld_src.contains("order(dir"));
let insp_src = src
.split("pub fn inspector")
.nth(1)
.unwrap()
.split("pub fn workspace")
.next()
.unwrap();
assert!(insp_src.contains("order(tok.direction"));
let drawer_src = src
.split("pub fn drawer")
.nth(1)
.unwrap()
.split("pub fn cheatsheet")
.next()
.unwrap();
assert!(drawer_src.contains("tok.direction"));
assert!(!drawer_src.contains("Direction::Ltr"));
let tool_src = src
.split("pub fn tool_panel")
.nth(1)
.unwrap()
.split("pub fn drawer")
.next()
.unwrap();
assert!(!tool_src.contains("label(title.clone()"));
assert!(!tool_src.contains("\"Dock\""));
assert!(tool_src.contains("dock.clone()"));
let pal_src = src
.split("pub fn command_palette_view")
.nth(1)
.unwrap()
.split("pub fn status_page")
.next()
.unwrap();
assert!(!pal_src.contains("\"Type a command\""));
assert!(pal_src.contains("placeholder,"));
let _: Element<'_, ()> = toolbar(acts.iter().copied(), tok, ltr);
let _: Element<'_, ()> = toolbar(acts.iter().copied(), tok, rtl);
let _: Element<'_, ()> = command_bar(table.iter(), tok, rtl);
let _: Element<'_, ()> = command_bar(std::iter::empty::<Action<()>>(), tok, ltr);
let bar_src = src
.split("pub fn command_bar")
.nth(1)
.unwrap()
.split("pub fn status_bar")
.next()
.unwrap();
assert!(bar_src.contains("tok.body()"));
assert!(bar_src.contains("on_surface)"));
assert!(!bar_src.contains("on_surface_variant"));
assert!(bar_src.contains("align_start(dir)"));
let _: Element<'_, ()> = status_bar("ready", None, None, &table, tok, ltr);
let _: Element<'_, ()> = status_bar("ready", None, None, &table, tok, rtl);
let _: Element<'_, ()> = status_bar("ready", None, None, &empty, tok, ltr);
let _: Element<'_, ()> = status_bar("ready", None, None, &empty, tok, rtl);
let _: Element<'_, ()> = status_bar(
"socket down",
Some(crate::toast::ToastKind::Danger),
Some("Tab fields · Esc"),
&table,
tok,
ltr,
);
let ltr_ids: Vec<_> = order(ltr, table.iter().map(|a| a.id.as_str()));
let rtl_ids: Vec<_> = order(rtl, table.iter().map(|a| a.id.as_str()));
assert_eq!(ltr_ids.first(), Some(&"file.save"));
assert_eq!(rtl_ids.first(), Some(&"file.open"));
let loc = crate::i18n::Locale::new("ar");
assert_eq!(loc.direction, Direction::Rtl);
let res: Vec<&Action<()>> = table.iter().collect();
let _: Element<'_, ()> = command_palette_view(
"",
"Command",
&res,
0,
|_| (),
|_| (),
None,
|_| (),
None,
1.0,
crate::palette::PaletteOpts::new(),
tok,
A11y::new("pat", Role::Group),
);
let dead_res: Vec<&Action<()>> = disabled.iter().collect();
let _: Element<'_, ()> = command_palette_view(
"q",
"Command",
&dead_res,
0,
|_| (),
|_| (),
None,
|_| (),
None,
1.0,
crate::palette::PaletteOpts::new(),
tok,
A11y::new("pat", Role::Group),
);
let mut many = ActionTable::new();
for i in 0..20 {
many.insert(Action::new(format!("cmd.{i}"), format!("Command {i}"), ()));
}
let many_res: Vec<&Action<()>> = many.iter().collect();
let _: Element<'_, ()> = status_page(
"Empty",
"Nothing",
Some(("New".into(), ())),
tok,
A11y::new("pat", Role::Group),
);
let _: Element<'_, ()> =
status_page("Empty", "Nothing", None, tok, A11y::new("pat", Role::Group));
let _: Element<'_, ()> = about_page(
"App",
"0.1.0",
"MIT",
"us",
tok,
&cat,
A11y::new("about", Role::Dialog),
);
let _: Element<'_, ()> =
preferences_page(&prefs, "", |_| (), tok, &cat, A11y::new("pat", Role::Group));
let _: Element<'_, ()> = preferences_page(
&prefs,
"nope",
|_| (),
tok,
&cat,
A11y::new("pat", Role::Group),
);
let lab = |s: &str| {
crate::widget::label::<()>(s, LabelFace::Body, tok, A11y::new(s, Role::Header))
};
let _: Element<'_, ()> = list_detail(
lab("l"),
lab("d"),
crate::layout::fixed(260.0),
tok,
ltr,
A11y::new("pat", Role::Group),
);
let _: Element<'_, ()> = list_detail(
lab("l"),
lab("d"),
crate::layout::FILL,
tok,
rtl,
A11y::new("pat", Role::Group),
);
let nav = NavStack::new("home");
let mut deep = nav.clone();
deep.push("x");
let _: Element<'_, ()> = navigation_view(
lab("s"),
lab("c"),
&nav,
900.0,
(),
tok,
&cat,
ltr,
A11y::new("pat", Role::Group),
);
let _: Element<'_, ()> = navigation_view(
lab("s"),
lab("c"),
&deep,
400.0,
(),
tok,
&cat,
rtl,
A11y::new("pat", Role::Group),
);
let _: Element<'_, ()> = navigation_view(
lab("s"),
lab("c"),
&nav,
400.0,
(),
tok,
&cat,
ltr,
A11y::new("pat", Role::Group),
);
let tabs = Tabs::new(["A"]);
let _: Element<'_, ()> = tab_view(
&tabs,
lab("b"),
|_| (),
|_| (),
tok,
A11y::new("pat", Role::Group),
);
let _: Element<'_, ()> = main_window(
lab("m"),
lab("t"),
lab("c"),
lab("s"),
tok,
A11y::new("pat", Role::Group),
);
let _: Element<'_, ()> = modal_card(lab("b"), lab("c"), 1.0, tok);
let _: Element<'_, ()> = context_menu(
table.iter().cloned(),
iced::Point::ORIGIN,
iced::Size::new(640.0, 400.0),
(),
1.0,
tok,
A11y::new("pat", Role::Group),
);
fn paint(el: &mut Element<'_, ()>) {
use iced::advanced::layout::{Layout, Limits};
use iced::advanced::renderer::Style;
use iced::advanced::widget::Tree;
use iced::mouse;
use iced::{Font, Pixels, Point, Rectangle, Size, Theme};
let mut tree = Tree::new(el.as_widget());
let mut renderer = iced::Renderer::Secondary(iced_tiny_skia::Renderer::new(
Font::DEFAULT,
Pixels::from(16u32),
));
let limits = Limits::new(Size::ZERO, Size::new(640.0, 400.0));
let node = el.as_widget_mut().layout(&mut tree, &renderer, &limits);
let layout = Layout::new(&node);
let viewport = Rectangle::new(Point::ORIGIN, Size::new(640.0, 400.0));
el.as_widget().draw(
&tree,
&mut renderer,
&Theme::Dark,
&Style::default(),
layout,
mouse::Cursor::Unavailable,
&viewport,
);
}
fn menu_row_width(el: &mut Element<'_, ()>) -> f32 {
use iced::advanced::layout::{Layout, Limits};
use iced::advanced::widget::Tree;
use iced::{Font, Pixels, Size};
let mut tree = Tree::new(el.as_widget());
let renderer = iced::Renderer::Secondary(iced_tiny_skia::Renderer::new(
Font::DEFAULT,
Pixels::from(16u32),
));
let limits = Limits::new(Size::ZERO, Size::new(640.0, 400.0));
let node = el.as_widget_mut().layout(&mut tree, &renderer, &limits);
let layout = Layout::new(&node);
fn walk(layout: Layout<'_>, best: &mut f32) {
let b = layout.bounds();
if (b.height - 34.0).abs() < 2.0 && b.width > 80.0 {
*best = best.max(b.width);
}
for child in layout.children() {
walk(child, best);
}
}
let mut best = 0.0;
walk(layout, &mut best);
best
}
let mut bar = menu_bar(&table, tok, ltr, &cat, |_| ());
paint(&mut bar);
let mut tb = toolbar(acts.iter().copied(), tok, ltr);
paint(&mut tb);
let mut sb = status_bar("ready", None, None, &table, tok, ltr);
paint(&mut sb);
let mut empty_sb = status_bar("ready", None, None, &empty, tok, rtl);
paint(&mut empty_sb);
let mut two = ActionTable::new();
two.insert(
Action::new("nav.down", "Down", ()).with_shortcut(Shortcut::parse("j").unwrap()),
);
two.insert(Action::new("nav.up", "Up", ()).with_shortcut(Shortcut::parse("k").unwrap()));
let mut two_sb = status_bar("ready", None, None, &two, tok, ltr);
paint(&mut two_sb);
let mut pal = command_palette_view(
"",
"Command",
&res,
0,
|_| (),
|_| (),
None,
|_| (),
None,
1.0,
crate::palette::PaletteOpts::new(),
tok,
A11y::new("pat", Role::Group),
);
paint(&mut pal);
let mut many_pal = command_palette_view(
"c",
"Command",
&many_res,
0,
|_| (),
|_| (),
None,
|_| (),
None,
1.0,
crate::palette::PaletteOpts::new(),
tok,
A11y::new("pat", Role::Group),
);
paint(&mut many_pal);
let ask = crate::palette::Prompt {
action: "go.line".into(),
label: "Line".into(),
value: "12".into(),
};
let mut asked = command_palette_view(
"",
"Command",
&res,
0,
|_| (),
|_| (),
Some(&ask),
|_| (),
Some(()),
1.0,
crate::palette::PaletteOpts::new(),
tok,
A11y::new("pat", Role::Group),
);
paint(&mut asked);
let mut page = status_page(
"Empty",
"Nothing",
Some(("New".into(), ())),
tok,
A11y::new("pat", Role::Group),
);
paint(&mut page);
let mut about = about_page(
"App",
"0.1.0",
"MIT",
"us",
tok,
&cat,
A11y::new("about", Role::Dialog),
);
paint(&mut about);
let rtl = tok.with_direction(Direction::Rtl);
let mut about_rtl = about_page(
"icedtea",
"0.2.0",
"MIT",
"iced 0.14 ڈیسک ٹاپ اطلاقیوں کے ویجٹ اور چوکھٹا۔",
rtl,
&cat,
A11y::new("about", Role::Dialog),
);
paint(&mut about_rtl);
let mut prefs_el =
preferences_page(&prefs, "", |_| (), tok, &cat, A11y::new("pat", Role::Group));
paint(&mut prefs_el);
let mut mw = main_window(
lab("m"),
lab("t"),
lab("c"),
lab("s"),
tok,
A11y::new("pat", Role::Group),
);
paint(&mut mw);
let vp = iced::Size::new(640.0, 400.0);
let two = context_card_size(2, vp, tok.density);
assert!(two.height < 120.0);
assert!(two.height > 40.0);
let tall = context_card_size(40, vp, tok.density);
assert!(tall.height <= vp.height * 0.5 + 0.1);
let pinned = context_origin(iced::Point::new(10.0, 390.0), two, vp);
assert!(pinned.y + two.height <= vp.height + 0.1);
let mut cm = context_menu(
table.iter().cloned(),
iced::Point::new(12.0, 20.0),
vp,
(),
1.0,
tok,
A11y::new("pat", Role::Group),
);
paint(&mut cm);
let cm_src = src
.split("pub fn context_menu")
.nth(1)
.unwrap()
.split("pub fn inspector")
.next()
.unwrap();
assert!(cm_src.contains("align_start(tok.direction)"));
assert!(cm_src.contains("tok.body()"));
assert!(cm_src.contains("menu_item_style"));
assert!(!cm_src.contains("button_style"));
let pill = tok.with_shape(crate::m3::ShapePolicy::Pill);
let mut cm_pill = context_menu(
table.iter().cloned(),
iced::Point::new(12.0, 20.0),
vp,
(),
1.0,
pill,
A11y::new("pat", Role::Group),
);
paint(&mut cm_pill);
let theme = crate::theme::iced_theme("dark", pill);
let row = style::menu_item_style(pill)(&theme, iced::widget::button::Status::Hovered);
assert_ne!(row.border.radius.top_left, crate::m3::Shape::Full.dp());
assert_eq!(
row.border.radius.top_left,
crate::m3::shape::Component::Menu
.shape_for(crate::m3::ShapePolicy::Pill)
.dp()
);
let card = context_card_size(table.iter().count(), vp, tok.density);
let row_w = menu_row_width(&mut cm);
let row_msg = format!("menu row {row_w} should fill the {card:?} card");
assert!(row_w + 1.0 >= card.width - 16.0, "{row_msg}");
let mut edge = context_menu(
table.iter().cloned(),
iced::Point::new(800.0, 500.0),
vp,
(),
0.5,
tok,
A11y::new("pat", Role::Group),
);
paint(&mut edge);
let none: [Action<()>; 0] = [];
let mut empty = context_menu(
none,
iced::Point::new(-8.0, -4.0),
iced::Size::new(10.0, 10.0),
(),
0.0,
tok,
A11y::new("pat", Role::Group),
);
paint(&mut empty);
let many: Vec<Action<()>> = (0..30)
.map(|i| Action::new(format!("a.{i}"), format!("A{i}"), ()))
.collect();
let mut long = context_menu(
many,
iced::Point::new(8.0, 8.0),
vp,
(),
1.0,
tok,
A11y::new("pat", Role::Group),
);
paint(&mut long);
let mut ld = list_detail(
lab("l"),
lab("d"),
crate::layout::fixed(260.0),
tok,
ltr,
A11y::new("pat", Role::Group),
);
paint(&mut ld);
let mut nv = navigation_view(
lab("s"),
lab("c"),
&nav,
900.0,
(),
tok,
&cat,
ltr,
A11y::new("pat", Role::Group),
);
paint(&mut nv);
let mut tv = tab_view(
&tabs,
lab("b"),
|_| (),
|_| (),
tok,
A11y::new("pat", Role::Group),
);
paint(&mut tv);
let mut mc = modal_card(lab("b"), lab("c"), 1.0, tok);
paint(&mut mc);
let mut mc_mid = modal_card(lab("b"), lab("c"), 0.4, tok);
paint(&mut mc_mid);
let mut pal_mid = command_palette_view(
"",
"Command",
&res,
0,
|_| (),
|_| (),
None,
|_| (),
None,
0.4,
crate::palette::PaletteOpts::new(),
tok,
A11y::new("pat", Role::Group),
);
paint(&mut pal_mid);
let mut notes = ActionTable::new();
notes.insert(Action::new("app.notes", "Notes", ()).with_icon(Icon::Document));
let notes_res: Vec<&Action<()>> = notes.iter().collect();
let mut el: Element<'_, ()> = command_palette_view(
"no",
"Search",
¬es_res,
0,
|_| (),
|_| (),
None,
|_| (),
None,
1.0,
crate::palette::PaletteOpts::new(),
tok,
A11y::new("pat", Role::Group),
);
paint(&mut el);
let none: Vec<&Action<()>> = Vec::new();
let mut miss: Element<'_, ()> = command_palette_view(
"zzz",
"Search",
&none,
0,
|_| (),
|_| (),
None,
|_| (),
None,
1.0,
crate::palette::PaletteOpts::new(),
tok,
A11y::new("pat", Role::Group),
);
paint(&mut miss);
let body = lab("x");
let scene = lab("s");
let mut sheet_mid: Element<'_, ()> = side_sheet(
scene,
"I",
body,
Some(()),
true,
240.0,
0.4,
tok,
A11y::new("pat", Role::Group),
);
paint(&mut sheet_mid);
let mut cb = command_bar(table.iter(), tok, ltr);
paint(&mut cb);
let mut dlg = dialog_sheet(
"Note",
"Hello",
("OK".into(), ()),
tok,
A11y::new("Note", Role::Dialog),
DialogOpts::default(),
);
paint(&mut dlg);
let mut dlg2 = dialog_sheet(
"Save",
"Overwrite?",
("Save".into(), ()),
tok,
A11y::new("Save", Role::Dialog),
DialogOpts {
cancel: Some(("Cancel".into(), ())),
..DialogOpts::default()
},
);
paint(&mut dlg2);
let mut insp = inspector(
lab("l"),
lab("d"),
lab("p"),
tok,
A11y::new("pat", Role::Group),
);
paint(&mut insp);
let root = crate::workspace::DockNode::leaf("edit", "Edit");
let mut ws = workspace(
&root,
|_| lab("c"),
|_id| None,
Size::new(400.0, 240.0),
|_, _| (),
|_, _| (),
tok,
A11y::new("ws", Role::Group),
);
paint(&mut ws);
let mut tp = tool_panel(
"Outline",
lab("b"),
Some(()),
"Dock",
tok,
A11y::new("tp", Role::Group),
);
paint(&mut tp);
let mut dr = drawer(
true,
lab("n"),
lab("c"),
1.0,
(),
tok,
A11y::new("pat", Role::Group),
);
paint(&mut dr);
let mut mid = drawer(
true,
lab("n"),
lab("c"),
0.4,
(),
tok,
A11y::new("pat", Role::Group),
);
paint(&mut mid);
let mut shut = drawer(
false,
lab("n"),
lab("c"),
0.0,
(),
tok,
A11y::new("pat", Role::Group),
);
paint(&mut shut);
let mut closing = drawer(
false,
lab("n"),
lab("c"),
0.5,
(),
tok,
A11y::new("pat", Role::Group),
);
paint(&mut closing);
let mut sheet = cheatsheet(&table, "sa", tok, A11y::new("pat", Role::Group));
paint(&mut sheet);
let mut extra = ActionTable::new();
extra.insert(Action::new("file.save", "Save", ()));
let mut dead = Action::new("edit.redo", "Redo", ());
dead.enabled = false;
extra.insert(dead);
let mut miss = cheatsheet(&extra, "zzzz", tok, A11y::new("pat", Role::Group));
paint(&mut miss);
let root = crate::workspace::DockNode::tabs(
vec![
crate::workspace::Panel::new("a", "A"),
crate::workspace::Panel::new("b", "B"),
],
0,
);
let mut ws = workspace(
&root,
|_| lab("c"),
|_id| None,
Size::new(400.0, 240.0),
|_, _| (),
|_, _| (),
tok,
A11y::new("ws", Role::Group),
);
paint(&mut ws);
let split_root = crate::workspace::DockNode::split(
crate::layout::Axis::Horizontal,
0.35,
crate::workspace::DockNode::leaf("ex", "Ex"),
crate::workspace::DockNode::tabs(
vec![
crate::workspace::Panel::new("ed", "Ed"),
crate::workspace::Panel::new("tm", "Tm"),
],
0,
),
);
let mut split_ws = workspace(
&split_root,
|id| {
lab(if id == "ex" {
"explorer-body"
} else {
"edit-body"
})
},
|_id| None,
Size::new(400.0, 240.0),
|_, _| (),
|_, _| (),
tok,
A11y::new("ws-split", Role::Group),
);
paint(&mut split_ws);
let vertical = crate::workspace::DockNode::split(
crate::layout::Axis::Vertical,
0.4,
crate::workspace::DockNode::leaf("top", "Top"),
crate::workspace::DockNode::leaf("bot", "Bot"),
);
let mut vws = workspace(
&vertical,
|_| lab("c"),
|_id| None,
Size::new(400.0, 240.0),
|_, _| (),
|_, _| (),
tok,
A11y::new("ws-v", Role::Group),
);
paint(&mut vws);
let twins = crate::workspace::DockNode::split(
crate::layout::Axis::Horizontal,
0.5,
crate::workspace::DockNode::leaf("same", "One"),
crate::workspace::DockNode::leaf("same", "Two"),
);
let mut tws = workspace(
&twins,
|_| lab("c"),
|_id| None,
Size::new(200.0, 120.0),
|_, _| (),
|_, _| (),
tok,
A11y::new("ws-twins", Role::Group),
);
paint(&mut tws);
let empty_tabs = crate::workspace::DockNode::tabs(vec![], 0);
let mut ews = workspace(
&empty_tabs,
|_| lab("c"),
|_id| None,
Size::new(200.0, 120.0),
|_, _| (),
|_, _| (),
tok,
A11y::new("ws-empty", Role::Group),
);
paint(&mut ews);
}
#[test]
fn context_menu_outside_press_dismisses() {
use iced::advanced::clipboard;
use iced::advanced::layout::{Layout, Limits};
use iced::advanced::widget::Tree;
use iced::mouse;
use iced::{Event, Font, Pixels, Point, Rectangle, Size};
#[derive(Clone, Debug, PartialEq)]
enum Msg {
Dismiss,
Save,
}
let tok = crate::theme::named("dark").tokens;
let mut table = ActionTable::new();
table.insert(Action::new("file.save", "Save", Msg::Save));
let vp = Size::new(640.0, 400.0);
let mut el = context_menu(
table.iter().cloned(),
Point::new(24.0, 48.0),
vp,
Msg::Dismiss,
1.0,
tok,
A11y::new("pat", Role::Group),
);
let mut tree = Tree::new(el.as_widget());
let renderer = iced::Renderer::Secondary(iced_tiny_skia::Renderer::new(
Font::DEFAULT,
Pixels::from(16u32),
));
let limits = Limits::new(Size::ZERO, vp);
let node = el.as_widget_mut().layout(&mut tree, &renderer, &limits);
let layout = Layout::new(&node);
let viewport = Rectangle::new(Point::ORIGIN, vp);
let mut clipboard = clipboard::Null;
let miss = Point::new(500.0, 300.0);
let mut messages = Vec::new();
{
let mut shell = iced::advanced::Shell::new(&mut messages);
el.as_widget_mut().update(
&mut tree,
&Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Left)),
layout,
mouse::Cursor::Available(miss),
&renderer,
&mut clipboard,
&mut shell,
&viewport,
);
}
assert_eq!(messages, vec![Msg::Dismiss]);
let hit = Point::new(40.0, 64.0);
let mut on_row = Vec::new();
{
let mut shell = iced::advanced::Shell::new(&mut on_row);
el.as_widget_mut().update(
&mut tree,
&Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Left)),
layout,
mouse::Cursor::Available(hit),
&renderer,
&mut clipboard,
&mut shell,
&viewport,
);
}
{
let mut shell = iced::advanced::Shell::new(&mut on_row);
el.as_widget_mut().update(
&mut tree,
&Event::Mouse(mouse::Event::ButtonReleased(mouse::Button::Left)),
layout,
mouse::Cursor::Available(hit),
&renderer,
&mut clipboard,
&mut shell,
&viewport,
);
}
let save_msg = format!("row press should run the action, got {on_row:?}");
assert!(on_row.contains(&Msg::Save), "{save_msg}");
let dismiss_msg = format!("row press must not be dismiss-only, got {on_row:?}");
assert!(!on_row.iter().all(|m| *m == Msg::Dismiss), "{dismiss_msg}");
}
#[test]
fn context_menu_escape_dismisses() {
use iced::advanced::clipboard;
use iced::advanced::layout::{Layout, Limits};
use iced::advanced::widget::Tree;
use iced::{Event, Font, Pixels, Point, Rectangle, Size};
let tok = crate::theme::named("dark").tokens;
let mut el = context_menu(
std::iter::empty::<Action<()>>(),
Point::new(24.0, 48.0),
Size::new(640.0, 400.0),
(),
1.0,
tok,
A11y::new("pat", Role::Group),
);
let mut tree = Tree::new(el.as_widget());
let renderer = iced::Renderer::Secondary(iced_tiny_skia::Renderer::new(
Font::DEFAULT,
Pixels::from(16u32),
));
let limits = Limits::new(Size::ZERO, Size::new(640.0, 400.0));
let node = el.as_widget_mut().layout(&mut tree, &renderer, &limits);
let layout = Layout::new(&node);
let mut messages = Vec::new();
{
let mut shell = iced::advanced::Shell::new(&mut messages);
let mut clipboard = clipboard::Null;
el.as_widget_mut().update(
&mut tree,
&Event::Keyboard(iced::keyboard::Event::KeyPressed {
key: iced::keyboard::Key::Named(iced::keyboard::key::Named::Escape),
modified_key: iced::keyboard::Key::Named(iced::keyboard::key::Named::Escape),
physical_key: iced::keyboard::key::Physical::Unidentified(
iced::keyboard::key::NativeCode::Unidentified,
),
location: iced::keyboard::Location::Standard,
modifiers: iced::keyboard::Modifiers::empty(),
text: None,
repeat: false,
}),
layout,
iced::mouse::Cursor::Unavailable,
&renderer,
&mut clipboard,
&mut shell,
&Rectangle::new(Point::ORIGIN, Size::new(640.0, 400.0)),
);
}
assert_eq!(messages, vec![()]);
}
fn layout_palette(
query: &str,
results: &[&Action<()>],
prompt: Option<&crate::palette::Prompt>,
opts: crate::palette::PaletteOpts<'_, ()>,
tok: crate::theme::Tokens,
) -> iced::advanced::layout::Node {
use iced::advanced::layout::Limits;
use iced::advanced::widget::Tree;
use iced::{Font, Pixels, Size};
let mut el: Element<'_, ()> = command_palette_view(
query,
"Search",
results,
0,
|_| (),
|_| (),
prompt,
|_| (),
prompt.and(Some(())),
1.0,
opts,
tok,
A11y::new("pat", Role::Group),
);
let mut tree = Tree::new(el.as_widget());
let renderer = iced::Renderer::Secondary(iced_tiny_skia::Renderer::new(
Font::DEFAULT,
Pixels::from(16u32),
));
el.as_widget_mut().layout(
&mut tree,
&renderer,
&Limits::new(Size::ZERO, Size::new(800.0, 800.0)),
)
}
fn tree_max_height(node: &iced::advanced::layout::Node) -> f32 {
node.children()
.iter()
.map(tree_max_height)
.fold(node.bounds().height, f32::max)
}
#[test]
fn command_palette_view_keeps_query_with_page_and_ask() {
let src = include_str!("pattern.rs");
let pal = src
.split("pub fn command_palette_view")
.nth(1)
.unwrap()
.split("fn palette_heading")
.next()
.unwrap();
assert!(pal.contains("search_input("), "{pal}");
assert!(pal.contains("if let Some(p) = prompt"), "{pal}");
assert!(pal.contains("opts.page"), "{pal}");
assert!(pal.find("search_input(").unwrap() < pal.find("if let Some(p) = prompt").unwrap());
let tok = crate::theme::named("dark").tokens;
let mut table = ActionTable::new();
table.insert(Action::new("file.save", "Save", ()));
let hits: Vec<&Action<()>> = table.iter().collect();
let page = crate::palette::PalettePage {
action: "theme".into(),
title: "Theme".into(),
};
let ask = crate::palette::Prompt {
action: "go.line".into(),
label: "Line".into(),
value: "12".into(),
};
let mut opts = crate::palette::PaletteOpts::new();
opts.page = Some(&page);
let node = layout_palette("", &hits, Some(&ask), opts, tok);
assert!(tree_max_height(&node) > 40.0);
let src_fn = include_str!("pattern.rs");
let body = src_fn
.split("pub fn command_palette_view")
.nth(1)
.unwrap()
.split("fn palette_heading")
.next()
.unwrap();
assert!(body.contains("Id::new(\"palette-query\""));
assert!(body.contains("Id::new(\"palette-arg\""));
}
#[test]
fn command_palette_view_groups_and_omit_idle() {
let tok = crate::theme::named("dark").tokens;
let mut table = ActionTable::new();
table.insert(Action::new("file.save", "Save", ()).with_section("File"));
table.insert(Action::new("view.zoom", "Zoom", ()).with_section("View"));
let hits: Vec<&Action<()>> = table.iter().collect();
let mut opts = crate::palette::PaletteOpts::new();
opts.favorite_count = 1;
opts.group = crate::palette::PaletteGroup::Section;
let grouped = layout_palette("", &hits, None, opts, tok);
assert!(tree_max_height(&grouped) > 40.0);
let mut prefix = crate::palette::PaletteOpts::new();
prefix.group = crate::palette::PaletteGroup::Prefix;
let _ = layout_palette("z", &hits, None, prefix, tok);
let mut flat = crate::palette::PaletteOpts::new();
flat.group = crate::palette::PaletteGroup::None;
let _ = layout_palette("", &hits, None, flat, tok);
let mut scrolled = crate::palette::PaletteOpts::new();
scrolled.scroll_after = 0;
scrolled.scroll_height = 280.0;
let scrolled_node = layout_palette("", &hits, None, scrolled, tok);
fn node_has_height(node: &iced::advanced::layout::Node, h: f32) -> bool {
if (node.bounds().height - h).abs() < 0.5 {
return true;
}
node.children().iter().any(|c| node_has_height(c, h))
}
assert!(node_has_height(&scrolled_node, 280.0));
let none: Vec<&Action<()>> = Vec::new();
let mut blank = crate::palette::PaletteOpts::new();
blank.empty_idle = crate::palette::EmptyHits::Copy("");
let _ = layout_palette("", &none, None, blank, tok);
let mut copy = crate::palette::PaletteOpts::new();
copy.empty_idle = crate::palette::EmptyHits::Copy("Idle list");
let _ = layout_palette("", &none, None, copy, tok);
let mut omit = crate::palette::PaletteOpts::new();
omit.empty_idle = crate::palette::EmptyHits::Omit;
let idle = layout_palette("", &none, None, omit, tok);
let miss_opts = crate::palette::PaletteOpts::new();
let miss = layout_palette("zzz", &none, None, miss_opts, tok);
assert!(tree_max_height(&idle) < tree_max_height(&miss));
let src = include_str!("pattern.rs");
assert!(src.contains("palette_group_heading"));
assert!(super::match_ranges("sa", "Save").contains(&(0, 2)));
assert_eq!(super::match_ranges("sv", "Save").len(), 2);
assert!(super::match_ranges("", "Save").is_empty());
assert_eq!(super::match_ranges("ave", "Save"), vec![(1, 4)]);
assert!(super::match_ranges("qq", "Save").is_empty());
}
#[test]
fn command_palette_view_hit_row_follows_direction() {
use crate::shortcut::Shortcut;
let ltr = crate::theme::named("dark").tokens;
let rtl = ltr.with_direction(crate::i18n::Direction::Rtl);
let mut table = ActionTable::new();
table.insert(
Action::new("file.save", "Save", ())
.with_icon(Icon::Save)
.with_shortcut(Shortcut::parse("ctrl+s").unwrap()),
);
let hits: Vec<&Action<()>> = table.iter().collect();
let ltr_n = layout_palette("", &hits, None, crate::palette::PaletteOpts::new(), ltr);
let rtl_n = layout_palette("", &hits, None, crate::palette::PaletteOpts::new(), rtl);
fn first_wide_row(
node: &iced::advanced::layout::Node,
) -> Option<&iced::advanced::layout::Node> {
let kids = node.children();
let mixed = kids.len() >= 3 && node.bounds().width >= 200.0 && {
let widths: Vec<f32> = kids.iter().map(|c| c.bounds().width).collect();
widths.iter().any(|w| *w < 40.0) && widths.iter().any(|w| *w > 80.0)
};
if mixed {
Some(node)
} else {
kids.iter().find_map(first_wide_row)
}
}
let ltr_row = first_wide_row(<r_n).expect("ltr hit row");
let rtl_row = first_wide_row(&rtl_n).expect("rtl hit row");
let ltr_kids: Vec<_> = ltr_row.children().iter().map(|c| c.bounds().x).collect();
let rtl_kids: Vec<_> = rtl_row.children().iter().map(|c| c.bounds().x).collect();
assert!(ltr_kids.first() < ltr_kids.last());
assert!(rtl_kids.first() < rtl_kids.last());
let src = include_str!("pattern.rs");
let hit = src
.split("fn palette_hit")
.nth(1)
.unwrap()
.split("fn palette_title_highlight")
.next()
.unwrap();
assert!(hit.contains("parts.extend(trail)"));
assert!(hit.contains("order(dir, parts)"));
let head = src
.split("fn palette_group_heading")
.nth(1)
.unwrap()
.split("fn palette_hit")
.next()
.unwrap();
assert!(head.contains("align_start(dir)"));
}
#[test]
fn cheatsheet_row_title_sits_on_start() {
use crate::shortcut::Shortcut;
let ltr = crate::theme::named("dark").tokens;
let rtl = ltr.with_direction(crate::i18n::Direction::Rtl);
let mut table = ActionTable::new();
table.insert(
Action::new("file.save", "Save the document now", ())
.with_shortcut(Shortcut::parse("s").unwrap()),
);
fn layout_sheet(
tok: crate::theme::Tokens,
table: &ActionTable<()>,
) -> iced::advanced::layout::Node {
use iced::advanced::layout::Limits;
use iced::advanced::widget::Tree;
use iced::{Font, Pixels, Size};
let mut el: Element<'_, ()> = cheatsheet(table, "", tok, A11y::new("pat", Role::Group));
let mut tree = Tree::new(el.as_widget());
let renderer = iced::Renderer::Secondary(iced_tiny_skia::Renderer::new(
Font::DEFAULT,
Pixels::from(16u32),
));
el.as_widget_mut().layout(
&mut tree,
&renderer,
&Limits::new(Size::ZERO, Size::new(480.0, 240.0)),
)
}
fn first_cheat_row(
node: &iced::advanced::layout::Node,
) -> Option<&iced::advanced::layout::Node> {
let kids = node.children();
let hit = kids.len() == 3 && {
let w: Vec<f32> = kids.iter().map(|c| c.bounds().width).collect();
w[1] > w[0] && w[1] > w[2] && w[1] > 80.0
};
if hit {
Some(node)
} else {
kids.iter().find_map(first_cheat_row)
}
}
let ltr_n = layout_sheet(ltr, &table);
let rtl_n = layout_sheet(rtl, &table);
let ltr_row = first_cheat_row(<r_n).expect("ltr cheat row");
let rtl_row = first_cheat_row(&rtl_n).expect("rtl cheat row");
let ltr_w: Vec<f32> = ltr_row
.children()
.iter()
.map(|c| c.bounds().width)
.collect();
let rtl_w: Vec<f32> = rtl_row
.children()
.iter()
.map(|c| c.bounds().width)
.collect();
assert!(ltr_w[0] > ltr_w[2]);
assert!(rtl_w[2] > rtl_w[0]);
}
#[test]
fn command_palette_view_face_and_slots_change_row() {
let tok = crate::theme::named("dark").tokens;
let mut table = ActionTable::new();
table.insert(
Action::new("file.save", "Save", ())
.with_icon(Icon::Save)
.with_tooltip("Write")
.with_section("File")
.with_checked(true),
);
table.insert(
Action::new("file.open", "Open", ())
.with_section("File")
.with_checked(false),
);
table.insert(Action::new("file.close", "Close", ()).with_section("File"));
let hits: Vec<&Action<()>> = table.iter().collect();
let mut compact = crate::palette::PaletteOpts::new();
compact.face = crate::palette::PaletteFace::Compact;
let mut detail = crate::palette::PaletteOpts::new();
detail.face = crate::palette::PaletteFace::Detail;
fn extra(a: &Action<()>, tok: crate::theme::Tokens) -> Element<'static, ()> {
crate::widget::meta(
a.section.clone().unwrap_or_default(),
tok,
A11y::new("slot", Role::Status),
)
}
detail.trailing = Some(extra);
detail.leading = Some(extra);
let c = layout_palette("sa", &hits, None, compact, tok);
let d = layout_palette("zz", &hits, None, detail, tok);
let mut mid = crate::palette::PaletteOpts::new();
mid.highlight = true;
let _ = layout_palette("ave", &hits, None, mid.clone(), tok);
let _ = layout_palette("sv", &hits, None, mid, tok);
assert!(tree_max_height(&d) > tree_max_height(&c));
let src = include_str!("pattern.rs");
let hit = src
.split("fn palette_hit")
.nth(1)
.unwrap()
.split("fn palette_title_highlight")
.next()
.unwrap();
assert!(hit.contains("PaletteFace::Compact"), "{hit}");
assert!(hit.contains("opts.leading"), "{hit}");
assert!(hit.contains("opts.trailing"), "{hit}");
assert!(hit.contains("action.checked"), "{hit}");
}
}