use std::{
collections::HashMap,
sync::{
Arc, Mutex,
atomic::{AtomicBool, Ordering},
},
};
use super::{
context_menu::ContextMenu,
icons,
menu::{Menu, MenuItem},
names,
part_style::Length,
recipe::{Case, Interaction, Name, Recipe, ResolvedPart, ResolvedRecipe, Selector},
shared::{fading, glyph, one_line, pressable},
theme::{Themed, current_theme},
};
use crate::{
app::{
component::Component,
ctx::{Ctx, Placement},
events::{DragEvent, KeyboardEvent, MouseButton, MouseButtonMask, MouseEvent},
theme::{BorderSize, OpacityLevel, PaletteColor, RadiusSize, Theme, TypographyStyle},
},
components::{self, Row, Stack},
core::{ElementRef, Signal, SignalValue},
layout::{
Alignment,
layout_kind::{Justify, ShrinkLimit},
text_style::{FontStyle, FontWeight},
},
node::{CursorIcon, Element, FocusGroup, border::Border, dimension::Dimension, outline::Outline},
};
const DRAG_START: f32 = 4.0;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum DocumentTabsPart {
Root,
Bar,
List,
Tab,
Icon,
Label,
Close,
CloseIcon,
Dirty,
Add,
AddIcon,
More,
MoreLabel,
MoreIcon,
}
names!(DocumentTabsPart {
Root => "root",
Bar => "bar",
List => "list",
Tab => "tab",
Icon => "icon",
Label => "label",
Close => "close",
CloseIcon => "close_icon",
Dirty => "dirty",
Add => "add",
AddIcon => "add_icon",
More => "more",
MoreLabel => "more_label",
MoreIcon => "more_icon",
});
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum DocumentTabsState {
Selected,
Dirty,
Pinned,
Preview,
Disabled,
Dragged,
DropBefore,
DropAfter,
Overflowing,
}
names!(DocumentTabsState {
Selected => "selected",
Dirty => "dirty",
Pinned => "pinned",
Preview => "preview",
Disabled => "disabled",
Dragged => "dragged",
DropBefore => "drop_before",
DropAfter => "drop_after",
Overflowing => "overflowing",
});
pub type DocumentTabsRenderer = Arc<dyn Fn(DocumentTabsView) -> Element + Send + Sync>;
type Handler<V> = Arc<dyn Fn(&V) + Send + Sync>;
type Told<T> = Arc<dyn Fn(&T) + Send + Sync>;
type Reorder = Arc<dyn Fn(usize, usize) + Send + Sync>;
type Call = Arc<dyn Fn() + Send + Sync>;
type Items = Arc<dyn Fn() -> Vec<MenuItem> + Send + Sync>;
pub struct DocumentTab<T> {
value: T,
label: Arc<str>,
icon: Option<Name>,
dirty: bool,
pinned: bool,
preview: bool,
disabled: bool,
on_close: Vec<Call>,
id: Option<Arc<str>>,
key: Option<Arc<str>>,
}
impl<T> DocumentTab<T> {
pub fn new(value: T, label: &str) -> Self {
Self {
value,
label: Arc::from(label),
icon: None,
dirty: false,
pinned: false,
preview: false,
disabled: false,
on_close: Vec::new(),
id: None,
key: None,
}
}
pub fn icon(mut self, name: impl Into<Name>) -> Self {
self.icon = Some(name.into());
self
}
pub fn dirty(mut self, dirty: bool) -> Self {
self.dirty = dirty;
self
}
pub fn pinned(mut self, pinned: bool) -> Self {
self.pinned = pinned;
self
}
pub fn preview(mut self, preview: bool) -> Self {
self.preview = preview;
self
}
pub fn disabled(mut self, disabled: bool) -> Self {
self.disabled = disabled;
self
}
pub fn on_close(mut self, handler: impl Fn() + Send + Sync + 'static) -> Self {
self.on_close.push(Arc::new(handler));
self
}
pub fn id(mut self, id: impl Into<Arc<str>>) -> Self {
self.id = Some(id.into());
self
}
pub fn key(mut self, key: impl Into<Arc<str>>) -> Self {
self.key = Some(key.into());
self
}
}
impl<T> From<(T, &str)> for DocumentTab<T> {
fn from((value, label): (T, &str)) -> Self {
Self::new(value, label)
}
}
#[derive(Clone)]
struct Words {
close: Arc<str>,
add: Arc<str>,
more: Arc<str>,
}
pub struct DocumentTabs<T = (), V: ?Sized = T> {
tabs: Vec<DocumentTab<T>>,
selected: Option<T>,
write: Option<Arc<dyn Fn(&T) + Send + Sync>>,
tell: fn(&T, &[Handler<V>]),
on_change: Vec<Handler<V>>,
on_close: Vec<Told<T>>,
on_keep: Vec<Told<T>>,
on_reorder: Vec<Reorder>,
on_drag_away: Vec<Arc<dyn Fn(&T, &DragEvent) + Send + Sync>>,
on_add: Vec<Call>,
context_menu: Option<Arc<dyn Fn(&T) -> Vec<MenuItem> + Send + Sync>>,
label: Option<Arc<str>>,
words: Words,
disabled: bool,
shortcuts: bool,
states: Vec<Name>,
rules: Recipe,
forced: Option<Interaction>,
id: Option<Arc<str>>,
key: Option<Arc<str>>,
}
impl<T: Clone + PartialEq + Send + Sync + 'static> DocumentTabs<T, T> {
pub fn new(value: Signal<T>, tabs: impl IntoIterator<Item = impl Into<DocumentTab<T>>>) -> Self
where
T: SignalValue,
{
let selected = Some(value.get());
Self::of(
tabs,
selected,
Some(Arc::new(move |next: &T| value.set(next.clone()))),
Self::tell_one,
)
}
pub fn controlled(
value: T,
tabs: impl IntoIterator<Item = impl Into<DocumentTab<T>>>,
on_change: impl Fn(&T) + Send + Sync + 'static,
) -> Self {
Self::of(tabs, Some(value), None, Self::tell_one).on_change(on_change)
}
fn tell_one(value: &T, handlers: &[Handler<T>]) {
for handler in handlers {
handler(value);
}
}
}
impl<T: Clone + PartialEq + Send + Sync + 'static> DocumentTabs<T, Option<T>> {
pub fn optional(value: Signal<Option<T>>, tabs: impl IntoIterator<Item = impl Into<DocumentTab<T>>>) -> Self
where
Option<T>: SignalValue,
{
let selected = value.get();
Self::of(
tabs,
selected,
Some(Arc::new(move |next: &T| value.set(Some(next.clone())))),
Self::tell_optional,
)
}
pub fn controlled_optional(
value: Option<T>,
tabs: impl IntoIterator<Item = impl Into<DocumentTab<T>>>,
on_change: impl Fn(&Option<T>) + Send + Sync + 'static,
) -> Self {
Self::of(tabs, value, None, Self::tell_optional).on_change(on_change)
}
fn tell_optional(value: &T, handlers: &[Handler<Option<T>>]) {
let value = Some(value.clone());
for handler in handlers {
handler(&value);
}
}
}
impl<T: Clone + PartialEq + Send + Sync + 'static, V: ?Sized + 'static> DocumentTabs<T, V> {
fn of(
tabs: impl IntoIterator<Item = impl Into<DocumentTab<T>>>,
selected: Option<T>,
write: Option<Arc<dyn Fn(&T) + Send + Sync>>,
tell: fn(&T, &[Handler<V>]),
) -> Self {
Self {
tabs: tabs.into_iter().map(Into::into).collect(),
selected,
write,
tell,
on_change: Vec::new(),
on_close: Vec::new(),
on_keep: Vec::new(),
on_reorder: Vec::new(),
on_drag_away: Vec::new(),
on_add: Vec::new(),
context_menu: None,
label: None,
words: Words {
close: super::current_locale().common.close.clone(),
add: super::current_locale().navigation.new_tab.clone(),
more: super::current_locale().navigation.show_hidden_tabs.clone(),
},
disabled: false,
shortcuts: true,
states: Vec::new(),
rules: Recipe::new(),
forced: None,
id: None,
key: None,
}
}
pub fn tab(mut self, tab: impl Into<DocumentTab<T>>) -> Self {
self.tabs.push(tab.into());
self
}
pub fn tabs(mut self, tabs: impl IntoIterator<Item = impl Into<DocumentTab<T>>>) -> Self {
self.tabs.extend(tabs.into_iter().map(Into::into));
self
}
pub fn on_change(mut self, handler: impl Fn(&V) + Send + Sync + 'static) -> Self {
self.on_change.push(Arc::new(handler));
self
}
pub fn on_close(mut self, handler: impl Fn(&T) + Send + Sync + 'static) -> Self {
self.on_close.push(Arc::new(handler));
self
}
pub fn on_keep(mut self, handler: impl Fn(&T) + Send + Sync + 'static) -> Self {
self.on_keep.push(Arc::new(handler));
self
}
pub fn on_reorder(mut self, handler: impl Fn(usize, usize) + Send + Sync + 'static) -> Self {
self.on_reorder.push(Arc::new(handler));
self
}
pub fn on_drag_away(mut self, handler: impl Fn(&T, &DragEvent) + Send + Sync + 'static) -> Self {
self.on_drag_away.push(Arc::new(handler));
self
}
pub fn on_add(mut self, handler: impl Fn() + Send + Sync + 'static) -> Self {
self.on_add.push(Arc::new(handler));
self
}
pub fn context_menu(mut self, items: impl Fn(&T) -> Vec<MenuItem> + Send + Sync + 'static) -> Self {
self.context_menu = Some(Arc::new(items));
self
}
pub fn label(mut self, label: &str) -> Self {
self.label = Some(Arc::from(label));
self
}
pub fn close_label(mut self, label: &str) -> Self {
self.words.close = Arc::from(label);
self
}
pub fn add_label(mut self, label: &str) -> Self {
self.words.add = Arc::from(label);
self
}
pub fn more_label(mut self, label: &str) -> Self {
self.words.more = Arc::from(label);
self
}
pub fn disabled(mut self, disabled: bool) -> Self {
self.disabled = disabled;
self
}
pub fn shortcuts(mut self, on: bool) -> Self {
self.shortcuts = on;
self
}
pub fn state(mut self, state: impl Into<Name>, on: bool) -> Self {
let state = state.into();
self.states.retain(|held| *held != state);
if on {
self.states.push(state);
}
self
}
pub fn style(mut self, part: impl Into<Name>, style: impl FnOnce(super::PartStyle) -> super::PartStyle) -> Self {
self.rules = self.rules.base(part, style);
self
}
pub fn rules(mut self, rules: &Recipe) -> Self {
self.rules = self.rules.extend(rules);
self
}
pub fn force(mut self, interaction: Option<Interaction>) -> Self {
self.forced = interaction;
self
}
pub fn id(mut self, id: impl Into<Arc<str>>) -> Self {
self.id = Some(id.into());
self
}
pub fn key(mut self, key: impl Into<Arc<str>>) -> Self {
self.key = Some(key.into());
self
}
fn prepare(self) -> Prepared {
let handlers: Arc<[Handler<V>]> = self.on_change.into();
let on_close: Arc<[Told<T>]> = self.on_close.into();
let on_keep: Arc<[Told<T>]> = self.on_keep.into();
let on_drag_away: Arc<[Arc<dyn Fn(&T, &DragEvent) + Send + Sync>]> = self.on_drag_away.into();
let (write, tell) = (self.write, self.tell);
let mut seen: HashMap<Arc<str>, usize> = HashMap::new();
let tabs = self
.tabs
.into_iter()
.map(|tab| {
let selected = self.selected.as_ref() == Some(&tab.value);
let key = tab.key.unwrap_or_else(|| {
let count = seen.entry(tab.label.clone()).or_insert(0);
*count += 1;
Arc::from(format!("document-tab-{}-{count}", tab.label))
});
let select: Call = {
let (value, write, handlers) = (tab.value.clone(), write.clone(), handlers.clone());
Arc::new(move || {
if selected {
return;
}
if let Some(write) = &write {
write(&value);
}
tell(&value, &handlers);
})
};
let close: Call = {
let (value, own, told) = (tab.value.clone(), tab.on_close, on_close.clone());
Arc::new(move || {
for handler in &own {
handler();
}
for handler in told.iter() {
handler(&value);
}
})
};
let keep: Call = {
let (value, told) = (tab.value.clone(), on_keep.clone());
Arc::new(move || {
for handler in told.iter() {
handler(&value);
}
})
};
let away: Option<Away> = (!on_drag_away.is_empty()).then(|| {
let (value, told) = (tab.value.clone(), on_drag_away.clone());
Arc::new(move |event: &DragEvent| {
for handler in told.iter() {
handler(&value, event);
}
}) as Away
});
let context: Option<Items> = self.context_menu.clone().map(|items| {
let value = tab.value.clone();
Arc::new(move || items(&value)) as Items
});
DocumentTabEntry {
label: tab.label,
icon: tab.icon,
dirty: tab.dirty,
pinned: tab.pinned,
preview: tab.preview,
disabled: tab.disabled,
selected,
select,
close,
keep,
away,
context,
id: tab.id,
key,
}
})
.collect();
Prepared {
tabs,
on_reorder: self.on_reorder.into(),
on_add: self.on_add.into(),
label: self.label,
words: self.words,
disabled: self.disabled,
shortcuts: self.shortcuts,
states: self.states,
rules: self.rules,
forced: self.forced,
id: self.id,
key: self.key,
}
}
pub fn mount(self, ctx: &mut Ctx) -> Element {
let mut tabs = self.prepare();
let key = tabs.key.take();
let mut element = ctx.mount::<DocumentTabsHost>(DocumentTabsProps { tabs });
if let Some(key) = key {
element = element.key(key);
}
element
}
pub fn build(self, theme: &Theme) -> Element {
self.prepare().build(theme, None)
}
}
impl<T: Clone + PartialEq + Send + Sync + 'static, V: ?Sized + 'static> From<DocumentTabs<T, V>> for Element {
fn from(tabs: DocumentTabs<T, V>) -> Self {
tabs.build(¤t_theme())
}
}
#[derive(Clone)]
pub struct DocumentTabEntry {
pub label: Arc<str>,
pub icon: Option<Name>,
pub dirty: bool,
pub pinned: bool,
pub preview: bool,
pub disabled: bool,
pub selected: bool,
select: Call,
close: Call,
keep: Call,
away: Option<Away>,
context: Option<Items>,
pub id: Option<Arc<str>>,
pub key: Arc<str>,
}
#[derive(Clone)]
struct Prepared {
tabs: Vec<DocumentTabEntry>,
on_reorder: Arc<[Reorder]>,
on_add: Arc<[Call]>,
label: Option<Arc<str>>,
words: Words,
disabled: bool,
shortcuts: bool,
states: Vec<Name>,
rules: Recipe,
forced: Option<Interaction>,
id: Option<Arc<str>>,
key: Option<Arc<str>>,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, crate::DevtoolsInspectable)]
struct Drag {
from: usize,
to: usize,
moved: bool,
away: bool,
}
type Away = Arc<dyn Fn(&DragEvent) + Send + Sync>;
#[derive(Clone)]
struct Kept {
dropped: Signal<Vec<bool>>,
open: Signal<bool>,
anchor: ElementRef,
refs: Arc<Mutex<Vec<ElementRef>>>,
drag: Signal<Option<Drag>>,
menus: Arc<Mutex<HashMap<Arc<str>, Signal<bool>>>>,
focus: Signal<Option<Arc<str>>>,
}
impl Kept {
fn refs(&self, count: usize) -> Vec<ElementRef> {
let mut refs = self.refs.lock().unwrap();
while refs.len() < count {
refs.push(ElementRef::new());
}
refs[..count].to_vec()
}
fn menu(&self, key: &Arc<str>) -> Signal<bool> {
self
.menus
.lock()
.unwrap()
.entry(key.clone())
.or_insert_with(|| Signal::new(false))
.clone()
}
}
impl Prepared {
fn build(self, theme: &Theme, kept: Option<Kept>) -> Element {
let breakpoint = super::current_breakpoint();
let count = self.tabs.len();
let dropped: Vec<bool> = match &kept {
Some(kept) => {
let read = kept.dropped.get();
(0..count)
.map(|index| read.get(index).copied().unwrap_or(false) && droppable(&self.tabs[index]))
.collect()
}
None => vec![false; count],
};
let drag = kept.as_ref().and_then(|kept| kept.drag.get()).filter(|drag| drag.moved);
let overflowing = dropped.contains(&true);
let case = Case {
breakpoint,
states: self.states.clone(),
..Case::new()
}
.state(DocumentTabsState::Overflowing, overflowing);
let recipe = theme
.resolve::<DocumentTabs>(&case, Some(&self.rules))
.owned_by(self.id.as_ref());
let recipe_of_bar = &recipe;
let tab_recipes = self
.tabs
.iter()
.enumerate()
.map(|(index, tab)| {
let (before, after) = match drag {
Some(drag) => drop_place(&self.tabs, drag, index),
None => (false, false),
};
let recipe = theme.resolve::<DocumentTabs>(
&case
.clone()
.state(DocumentTabsState::Selected, tab.selected)
.state(DocumentTabsState::Dirty, tab.dirty)
.state(DocumentTabsState::Pinned, tab.pinned)
.state(DocumentTabsState::Preview, tab.preview)
.state(DocumentTabsState::Disabled, self.disabled || tab.disabled)
.state(DocumentTabsState::Dragged, drag.is_some_and(|drag| drag.from == index))
.state(DocumentTabsState::DropBefore, before)
.state(DocumentTabsState::DropAfter, after),
Some(&self.rules),
);
let recipe = recipe.owned_like(recipe_of_bar);
match &tab.id {
Some(id) => recipe.item(Some(id), DocumentTabsPart::Tab),
None => recipe.keyed_item(&tab.key, DocumentTabsPart::Tab),
}
})
.collect();
let refs = kept.as_ref().map(|kept| kept.refs(count)).unwrap_or_default();
let view = DocumentTabsView {
tabs: self.tabs,
dropped,
label: self.label,
disabled: self.disabled,
shortcuts: self.shortcuts,
recipe,
tab_recipes,
words: self.words,
on_reorder: self.on_reorder,
on_add: self.on_add,
kept,
refs,
forced: self.forced,
id: self.id,
key: self.key,
};
match theme.renderer::<DocumentTabs>() {
Some(renderer) => renderer(view),
None => view.render(),
}
}
}
fn droppable(tab: &DocumentTabEntry) -> bool {
!tab.selected && !tab.pinned
}
fn kind_range(tabs: &[DocumentTabEntry], from: usize) -> (usize, usize) {
let pinned = tabs[from].pinned;
let first = tabs.iter().position(|tab| tab.pinned == pinned).unwrap_or(0);
let last = tabs.iter().rposition(|tab| tab.pinned == pinned).unwrap_or(from);
(first, last)
}
fn drop_place(tabs: &[DocumentTabEntry], drag: Drag, index: usize) -> (bool, bool) {
if drag.away || drag.to == drag.from || index == drag.from {
return (false, false);
}
let others: Vec<usize> = (0..tabs.len()).filter(|other| *other != drag.from).collect();
match others.get(drag.to) {
Some(next) => (*next == index, false),
None => (false, others.last() == Some(&index)),
}
}
#[derive(Clone)]
struct DocumentTabsProps {
tabs: Prepared,
}
impl PartialEq for DocumentTabsProps {
fn eq(&self, _: &Self) -> bool {
false
}
}
impl crate::app::component::DevtoolsInspectable for DocumentTabsProps {}
struct DocumentTabsHost {
kept: Kept,
}
impl Component for DocumentTabsHost {
type Props = DocumentTabsProps;
fn create(ctx: &mut Ctx) -> Self {
Self {
kept: Kept {
dropped: ctx.signal(Vec::new()),
open: ctx.signal(false),
anchor: ElementRef::new(),
refs: Arc::new(Mutex::new(Vec::new())),
drag: ctx.signal(None),
menus: Arc::new(Mutex::new(HashMap::new())),
focus: ctx.signal(None),
},
}
}
fn render(&self, ctx: &mut Ctx) -> impl Into<Element> {
let DocumentTabsProps { tabs } = ctx.props::<DocumentTabsProps>().clone();
if let Some(key) = self.kept.focus.get() {
match tabs.tabs.iter().position(|tab| tab.key == key) {
Some(index) if self.kept.dropped.get().get(index).copied().unwrap_or(false) => {}
Some(index) => {
self.kept.focus.set(None);
ctx.focus(&self.kept.refs(tabs.tabs.len())[index]);
}
None => self.kept.focus.set(None),
}
}
tabs.build(¤t_theme(), Some(self.kept.clone()))
}
}
pub struct DocumentTabsView {
pub tabs: Vec<DocumentTabEntry>,
pub dropped: Vec<bool>,
pub label: Option<Arc<str>>,
pub disabled: bool,
pub shortcuts: bool,
recipe: ResolvedRecipe,
tab_recipes: Vec<ResolvedRecipe>,
words: Words,
on_reorder: Arc<[Reorder]>,
on_add: Arc<[Call]>,
kept: Option<Kept>,
refs: Vec<ElementRef>,
forced: Option<Interaction>,
id: Option<Arc<str>>,
key: Option<Arc<str>>,
}
impl DocumentTabsView {
pub fn part(&self, part: impl Into<Name>) -> ResolvedPart {
self.recipe.part(part)
}
pub fn tab_part(&self, index: usize, part: impl Into<Name>) -> ResolvedPart {
let forced = self.forced.filter(|_| self.entry() == Some(index));
self.tab_recipes[index].part(part).forced(forced)
}
pub fn entry(&self) -> Option<usize> {
if self.disabled {
return None;
}
let open = |tab: &DocumentTabEntry| !tab.disabled;
self
.tabs
.iter()
.position(|tab| tab.selected && open(tab))
.or_else(|| self.tabs.iter().position(open))
}
pub fn theme(&self) -> &Theme {
self.recipe.theme()
}
fn reorder_call(&self) -> impl Fn(usize, usize) + Send + Sync + 'static {
let handlers = self.on_reorder.clone();
move |from, to| {
if from != to {
for handler in handlers.iter() {
handler(from, to);
}
}
}
}
fn close(&self, index: usize) -> components::Button {
let entry = &self.tabs[index];
let close = entry.close.clone();
let icon = glyph(
&self.tab_part(index, DocumentTabsPart::CloseIcon),
Name::new(icons::CLOSE),
false,
);
let mut button = components::Button::empty()
.focusable(false)
.part(&self.tab_part(index, DocumentTabsPart::Close))
.describe("a11y_name", format!("{} {}", self.words.close, entry.label))
.disabled(self.disabled || entry.disabled)
.on_click(move |event: MouseEvent| {
event.stop_propagation();
close();
});
if entry.dirty {
let fill = Dimension::Pct(100.0);
let middle = |child: Element| {
Row::new()
.size(fill, fill)
.align_items(Alignment::Center)
.justify(Justify::Center)
.child(child)
};
let dot = Row::new().part(&self.tab_part(index, DocumentTabsPart::Dirty));
button = button.child(
Stack::new()
.size(fill, fill)
.child(middle(icon))
.child(middle(dot.into())),
);
} else {
button = button.child(icon);
}
if let Some(id) = &entry.id {
button = button.id(format!("{id}-close"));
}
button
}
pub fn tab(&self, index: usize) -> Element {
let entry = &self.tabs[index];
let part = |part: DocumentTabsPart| self.tab_part(index, part);
let disabled = self.disabled || entry.disabled;
let (select, close, keep) = (entry.select.clone(), entry.close.clone(), entry.keep.clone());
let mut tab = pressable(&part(DocumentTabsPart::Tab), disabled)
.interaction_group(true)
.focus_entry(entry.selected)
.key(entry.key.clone())
.describe("a11y_role", "tab")
.describe("a11y_name", entry.label.clone())
.describe("a11y_selected", if entry.selected { "true" } else { "false" })
.on_click(move |event: MouseEvent| {
if event.button == MouseButton::Left {
select();
}
});
if !disabled {
let middle = close.clone();
tab = tab.on_mouse_up(move |event: MouseEvent| {
if event.button == MouseButton::Middle {
middle();
}
});
if entry.preview {
let tapped = keep.clone();
tab = tab
.on_dblclick(move |_: MouseEvent| keep())
.on_double_tap(move |event: crate::app::events::TapEvent| {
if event.fingers == 1 {
tapped();
}
});
}
tab = tab.on_key_down(self.keys(index));
}
if entry.pinned {
tab = tab.child(glyph(&part(DocumentTabsPart::Icon), Name::new(icons::PIN), false));
} else {
if let Some(name) = entry.icon {
tab = tab.child(glyph(&part(DocumentTabsPart::Icon), name, false));
}
tab = tab.child(one_line(&part(DocumentTabsPart::Label), &entry.label));
tab = tab.child(self.close(index));
}
if let Some(id) = &entry.id {
tab = tab.id(id.clone());
}
if let Some(at) = self.refs.get(index) {
tab = tab.ref_element(at.clone());
}
if let Some(kept) = &self.kept
&& !disabled
{
tab = self.draggable(tab, kept, index);
}
let mut element: Element = match (&self.kept, &entry.context) {
(Some(kept), Some(items)) if !disabled => ContextMenu::new(kept.menu(&entry.key), tab)
.label(&entry.label)
.items(items())
.into(),
_ => tab.into(),
};
if let Some(kept) = &self.kept
&& let Some(at) = self.refs.get(index)
{
element = self.place(element, kept, at.clone(), index, droppable(entry));
}
element
}
fn keys(&self, index: usize) -> impl Fn(KeyboardEvent) + Send + Sync + 'static {
let entry = &self.tabs[index];
let close = entry.close.clone();
let own = entry.key.clone();
let beside = self
.tabs
.get(index + 1)
.or_else(|| index.checked_sub(1).and_then(|before| self.tabs.get(before)))
.map(|tab| tab.key.clone());
let (first, last) = kind_range(&self.tabs, index);
let reorder = self.reorder_call();
let pinned = entry.pinned;
move |event: KeyboardEvent| {
if !event.focus_within || event.default_prevented() {
return;
}
let command = event.ctrl || event.meta;
if command && !event.shift && !event.alt && event.key.eq_ignore_ascii_case("w") {
if pinned {
return;
}
event.prevent_default();
close();
if let Some(beside) = &beside {
event.focus_key(beside.clone());
}
return;
}
if event.ctrl && event.shift && !event.alt {
let to = match event.key.as_str() {
"PageUp" if index > first => index - 1,
"PageDown" if index < last => index + 1,
"PageUp" | "PageDown" => {
event.prevent_default();
return;
}
_ => return,
};
reorder(index, to);
event.focus_key(own.clone());
}
}
}
fn draggable(&self, tab: components::Button, kept: &Kept, index: usize) -> components::Button {
let (first, last) = kind_range(&self.tabs, index);
let refs = self.refs.clone();
let (start, moving, ending) = (kept.drag.clone(), kept.drag.clone(), kept.drag.clone());
let reorder = self.reorder_call();
let away = self.tabs[index].away.clone();
let (away_moving, away_ending) = (away.clone(), away);
let (bar, bar_end) = (refs.clone(), refs.clone());
let far = move |refs: &[ElementRef], event: &DragEvent| {
let Some(at) = refs.get(index) else {
return false;
};
let (top, height) = (at.y(), at.height());
event.outside_window || event.y < top - height || event.y > top + 2.0 * height
};
tab
.start_drag_buttons(MouseButtonMask::LEFT)
.on_drag_start(move |_: DragEvent| {
start.set(Some(Drag {
from: index,
to: index,
moved: false,
away: false,
}))
})
.on_drag_move(move |event: DragEvent| {
let Some(mut drag) = moving.get_untracked() else {
return;
};
drag.moved |= event.total_delta_x.abs() >= DRAG_START || event.total_delta_y.abs() >= DRAG_START;
drag.away = away_moving.is_some() && far(&bar, &event);
if drag.away {
if let Some(away) = &away_moving {
away(&event);
}
if moving.get_untracked() != Some(drag) {
moving.set(Some(drag));
}
return;
}
let mut to = 0;
for (other, at) in refs.iter().enumerate() {
if other != index && at.x() + at.width() / 2.0 < event.x {
to += 1;
}
}
drag.to = to.clamp(first, last);
if moving.get_untracked() != Some(drag) {
moving.set(Some(drag));
}
})
.on_drag_end(move |event: DragEvent| {
let drag = ending.get_untracked();
ending.set(None);
if let Some(away) = &away_ending
&& (drag.is_some_and(|drag| drag.away) || far(&bar_end, &event))
{
away(&event);
return;
}
if let Some(drag) = drag
&& drag.moved
{
reorder(drag.from, drag.to);
}
})
}
fn place(&self, element: Element, kept: &Kept, at: ElementRef, index: usize, drops: bool) -> Element {
let (dropped, open, count) = (kept.dropped.clone(), kept.open.clone(), self.tabs.len());
at.observe_rect(move |rect| {
let now = rect.width <= 0.0 && rect.height <= 0.0;
if dropped.get_untracked().get(index).copied() != Some(now) {
dropped.update(|dropped| {
dropped.resize(count.max(dropped.len()), false);
dropped[index] = now;
});
if !dropped.get_untracked().contains(&true) && open.get_untracked() {
open.set(false);
}
}
});
let place = Row::new().align_items(Alignment::Stretch).overflow_visible();
let place = if drops {
place.flex_shrink(1.0).shrink_limit(ShrinkLimit::Drop)
} else {
place
};
place.child(element).into()
}
pub fn add(&self) -> Option<components::Button> {
if self.on_add.is_empty() {
return None;
}
let handlers = self.on_add.clone();
let mut button = pressable(&self.part(DocumentTabsPart::Add), self.disabled)
.describe("a11y_name", self.words.add.clone())
.child(glyph(
&self.part(DocumentTabsPart::AddIcon),
Name::new(icons::PLUS),
false,
))
.on_click(move |_| {
for handler in handlers.iter() {
handler();
}
});
if let Some(id) = &self.id {
button = button.id(format!("{id}-add"));
}
Some(button)
}
pub fn more(&self) -> Option<(components::Button, Menu)> {
let kept = self.kept.as_ref()?;
let hidden = self.dropped.iter().filter(|dropped| **dropped).count();
if hidden == 0 {
return None;
}
let open = kept.open.clone();
let label = self.part(DocumentTabsPart::MoreLabel);
let mut button = pressable(&self.part(DocumentTabsPart::More), self.disabled)
.ref_element(kept.anchor.clone())
.describe("a11y_name", self.words.more.clone())
.describe("a11y_haspopup", "menu")
.describe("a11y_expanded", if open.get() { "true" } else { "false" })
.child(label.text(&hidden.to_string()).nowrap().part(&label))
.child(glyph(
&self.part(DocumentTabsPart::MoreIcon),
Name::new(icons::CHEVRON_DOWN),
false,
))
.on_click(move |_| open.set(!open.get_untracked()));
if let Some(id) = &self.id {
button = button.id(format!("{id}-more"));
}
let mut menu = Menu::new(kept.open.clone(), kept.anchor.clone())
.placement(Placement::BottomEnd)
.label(&self.words.more);
for (index, entry) in self.tabs.iter().enumerate() {
if !self.dropped[index] {
continue;
}
let (select, focus, key) = (entry.select.clone(), kept.focus.clone(), entry.key.clone());
let mut item = MenuItem::new(&entry.label)
.disabled(self.disabled || entry.disabled)
.on_select(move || {
select();
focus.set(Some(key.clone()));
});
if let Some(icon) = entry.icon {
item = item.icon(icon);
}
if let Some(id) = &entry.id {
item = item.id(format!("{id}-item"));
}
menu = menu.item(item);
}
Some((button, menu))
}
pub fn list(&self) -> Element {
let mut list = Row::new()
.part(&self.part(DocumentTabsPart::List))
.flex(1.0)
.align_items(Alignment::Stretch)
.focus_group(FocusGroup::horizontal().activate(false).one_stop(true))
.describe("a11y_role", "tablist")
.describe("a11y_name", self.label.clone().unwrap_or_default())
.describe("a11y_orientation", "horizontal");
for index in 0..self.tabs.len() {
list = list.child(self.tab(index));
}
if let Some(add) = self.add() {
list = list.child(
Row::new()
.focus_group(FocusGroup::none())
.align_items(Alignment::Stretch)
.child(add),
);
}
list.into()
}
fn shortcut(&self, in_bar: Arc<AtomicBool>) -> impl Fn(KeyboardEvent) + Send + Sync + 'static {
let tabs: Vec<(bool, bool, bool, Call, Call, Arc<str>)> = self
.tabs
.iter()
.map(|tab| {
(
tab.selected,
!tab.disabled,
tab.pinned,
tab.select.clone(),
tab.close.clone(),
tab.key.clone(),
)
})
.collect();
let ranges: Vec<(usize, usize)> = (0..self.tabs.len())
.map(|index| kind_range(&self.tabs, index))
.collect();
let reorder = self.reorder_call();
move |event: KeyboardEvent| {
if event.default_prevented() || event.composing || event.alt || tabs.is_empty() {
return;
}
let mac = cfg!(target_os = "macos");
let at = tabs.iter().position(|tab| tab.0);
let key = event.key.as_str();
let (select, close, moves) = match key {
"Tab" if event.ctrl && !event.meta => (Some(if event.shift { -1 } else { 1 }), false, None),
"PageDown" | "PageUp" if event.ctrl && !event.meta => {
let by: isize = if key == "PageDown" { 1 } else { -1 };
if event.shift {
(None, false, Some(by))
} else if mac {
return;
} else {
(Some(by), false, None)
}
}
_ if key.eq_ignore_ascii_case("w")
&& !event.shift
&& if mac {
event.meta && !event.ctrl
} else {
event.ctrl && !event.meta
} =>
{
(None, true, None)
}
_ => return,
};
event.prevent_default();
let follow = in_bar.load(Ordering::Relaxed);
if let Some(by) = select {
let count = tabs.len() as isize;
let from = at.map(|at| at as isize).unwrap_or(if by > 0 { -1 } else { count });
let next = (1..=count)
.map(|n| (from + by * n).rem_euclid(count) as usize)
.find(|index| tabs[*index].1 && Some(*index) != at);
if let Some(next) = next {
(tabs[next].3)();
if follow {
event.focus_key(tabs[next].5.clone());
}
}
} else if close {
if let Some(at) = at.filter(|at| tabs[*at].1 && !tabs[*at].2) {
(tabs[at].4)();
let beside = tabs
.get(at + 1)
.or_else(|| at.checked_sub(1).and_then(|before| tabs.get(before)));
if let (true, Some(beside)) = (follow, beside) {
event.focus_key(beside.5.clone());
}
}
} else if let (Some(by), Some(from)) = (moves, at) {
let (first, last) = ranges[from];
let to = from as isize + by;
if to >= first as isize && to <= last as isize {
reorder(from, to as usize);
if follow {
event.focus_key(tabs[from].5.clone());
}
}
}
}
}
pub fn render(self) -> Element {
let fill = Dimension::Pct(100.0);
let mut row = Row::new()
.size(fill, fill)
.align_items(Alignment::Stretch)
.child(self.list());
if let Some((more, menu)) = self.more() {
row = row.child(more).child(menu);
}
let mut root = Stack::new()
.part(&self.part(DocumentTabsPart::Root))
.child(Row::new().size(fill, fill).part(&self.part(DocumentTabsPart::Bar)))
.child(row);
if self.shortcuts && !self.disabled {
let in_bar = Arc::new(AtomicBool::new(false));
let heard = in_bar.clone();
root = root
.on_key_down(move |event: KeyboardEvent| heard.store(event.focus_within, Ordering::Relaxed))
.child(Row::new().on_key_down(self.shortcut(in_bar)));
}
if let Some(id) = &self.id {
root = root.id(id.clone());
}
if let Some(key) = &self.key {
root = root.key(key.clone());
}
root.into()
}
}
impl<T: Clone + PartialEq + Send + Sync + 'static, V: ?Sized + 'static> crate::ui::Styled for DocumentTabs<T, V> {
type Component = Self;
fn rules(self, rules: &crate::ui::Recipe) -> Self {
Self::rules(self, rules)
}
fn state(self, state: impl Into<crate::ui::Name>, on: bool) -> Self {
Self::state(self, state, on)
}
}
impl<T: Send + Sync + 'static, V: ?Sized + 'static> Themed for DocumentTabs<T, V> {
const NAME: &'static str = "document_tabs";
type Renderer = DocumentTabsRenderer;
fn parts() -> crate::ui::Declared {
DocumentTabsPart::declared()
}
fn states() -> crate::ui::Declared {
DocumentTabsState::declared()
}
fn recipe() -> Recipe {
use DocumentTabsPart::{
Add, AddIcon, Bar, Close, CloseIcon, Dirty, Icon, Label, List, More, MoreIcon, MoreLabel, Root, Tab,
};
use DocumentTabsState::{Disabled, Dragged, DropAfter, DropBefore, Pinned, Preview, Selected};
use PaletteColor::{Background, Foreground, MutedForeground, Primary, Ring, SecondaryHover, StateHover};
let line = |width: BorderSize, color: PaletteColor| Border::inside(width, color);
let inner_ring = || Outline::new(BorderSize::Md, Ring).offset(-2.0);
let dirty = Selector::new().state(DocumentTabsState::Dirty);
Recipe::new()
.base(Root, |s| s.height(38.0).width(Length::Fill))
.base(Bar, |s| {
s.background(PaletteColor::Bar)
.underline(line(BorderSize::Sm, PaletteColor::Border))
})
.base(List, |s| s.width(Length::Fill))
.base(Tab, |s| {
fading(
s.padding_start(12.0)
.padding_end(8.0)
.gap(8.0)
.max_width(240.0)
.end_line(line(BorderSize::Sm, PaletteColor::Border))
.foreground(MutedForeground)
.cursor(CursorIcon::Pointer),
)
})
.base(Icon, |s| s.square(14.0).foreground(MutedForeground))
.base(Label, |s| {
s.typography(TypographyStyle::Body)
.font_size(13.0)
.weight(FontWeight::Normal)
.foreground(MutedForeground)
})
.base(Close, |s| {
fading(
s.square(20.0)
.radius(RadiusSize::Sm)
.cursor(CursorIcon::Pointer),
)
})
.base(CloseIcon, |s| s.square(13.0).foreground(MutedForeground).opacity(0.5))
.base(Dirty, |s| s.square(8.0).radius(RadiusSize::Full).background(Foreground))
.base(Add, |s| {
fading(s.width(38.0).foreground(Foreground).cursor(CursorIcon::Pointer))
})
.base(AddIcon, |s| s.square(16.0))
.base(More, |s| {
fading(
s.padding_x(10.0)
.gap(4.0)
.start_line(line(BorderSize::Sm, PaletteColor::Border))
.cursor(CursorIcon::Pointer),
)
})
.base(MoreLabel, |s| s.typography(TypographyStyle::Caption).foreground(MutedForeground))
.base(MoreIcon, |s| s.square(14.0).foreground(MutedForeground))
.state(Pinned, Tab, |s| s.width(38.0).padding_x(0.0).gap(0.0))
.row_density(Selector::new(), Root, 38.0)
.by_density(Selector::new(), Add, |s, step| s.width(38.0 + step))
.by_density(Selector::new().state(Pinned), Tab, |s, step| s.width(38.0 + step))
.within(CloseIcon, |s| s.foreground(Foreground).opacity(1.0))
.hovered(Close, |s| s.background(SecondaryHover))
.hovered(Add, |s| s.background(StateHover))
.hovered(More, |s| s.background(StateHover))
.focus_visible(Tab, |s| s.outline(inner_ring()))
.focus_visible(Add, |s| s.outline(inner_ring()))
.focus_visible(More, |s| s.outline(inner_ring()))
.state(Selected, Tab, |s| {
s.background(Background)
.foreground(Foreground)
.top_line(line(BorderSize::Md, Primary))
.end_line(line(BorderSize::Sm, Background))
})
.state(Selected, Icon, |s| s.foreground(Foreground))
.state(Selected, Label, |s| s.foreground(Foreground))
.state(Selected, CloseIcon, |s| s.foreground(Foreground).opacity(1.0))
.state(DocumentTabsState::Dirty, CloseIcon, |s| s.opacity(0.0))
.when(dirty.clone().within(), CloseIcon, |s| s.foreground(Foreground).opacity(1.0))
.when(dirty.within(), Dirty, |s| s.opacity(0.0))
.state(Preview, Label, |s| s.font_style(FontStyle::Italic))
.state(Disabled, Tab, |s| {
s.opacity(OpacityLevel::Disabled).cursor(CursorIcon::Default)
})
.state(Dragged, Tab, |s| s.opacity(OpacityLevel::Muted))
.state(DropBefore, Tab, |s| s.start_line(line(BorderSize::Md, Primary)))
.state(DropAfter, Tab, |s| s.end_line(line(BorderSize::Md, Primary)))
}
}