use std::{any::Any, cell::RefCell, rc::Rc, sync::Arc};
use gpui_kit::component::Size as ComponentSize;
use gpui_kit::{
App, Context, InteractiveElement, MouseButton, MouseDownEvent, ParentElement as _, Pixels,
Role, SharedString, Size, StatefulInteractiveElement as _, Styled, WeakEntity, Window, div,
prelude::FluentBuilder as _, px, size,
};
use super::{
CELL_PADDING, CellChange, ColumnAlign, LiveGridDelegate, LiveGridState,
a11y::column_index,
columns::CellContent,
edit::EditState,
editors::{CellCommit, CellEditHandle, GridCommit},
frame::{HostCell, RowPlanner},
selection::FocusedCell,
};
use crate::{
actions::ActivateCell,
element::{CellHost, HostLayer},
model::{CellValue, GridColumns as _, GridRow, display_text_in},
store::PinnedEdge,
};
pub(crate) type CellActivation = Rc<dyn Fn(&mut Window, &mut App)>;
pub(super) struct ActiveCell<K, C> {
key: K,
column: C,
handler: CellActivation,
}
pub(super) struct CellPress<K, C> {
key: K,
column: C,
pinned: Option<PinnedEdge>,
button: MouseButton,
accepted: bool,
}
pub(super) struct WidgetSlot<K, C> {
press: Option<CellPress<K, C>>,
activation: RefCell<Option<ActiveCell<K, C>>>,
commit: RefCell<Option<Rc<dyn CellCommit>>>,
}
impl<K, C> Default for WidgetSlot<K, C> {
fn default() -> Self {
Self {
press: None,
activation: RefCell::new(None),
commit: RefCell::new(None),
}
}
}
impl<K, C> WidgetSlot<K, C> {
pub(super) fn begin_frame(&self) {
self.activation.borrow_mut().take();
}
fn commit<D: LiveGridDelegate>(
&self,
grid: &WeakEntity<LiveGridState<D>>,
) -> Rc<dyn CellCommit> {
let mut commit = self.commit.borrow_mut();
Rc::clone(commit.get_or_insert_with(|| {
Rc::new(GridCommit { grid: grid.clone() }) as Rc<dyn CellCommit>
}))
}
}
pub struct CellElementContext<'a, R: GridRow> {
row: &'a Arc<R>,
column: R::Column,
value: CellValue<'a>,
text: &'a str,
change: Option<CellChange>,
size: ComponentSize,
cell_size: Size<Pixels>,
selected: bool,
focused: bool,
edit_state: Option<&'a EditState>,
activation: Option<&'a RefCell<Option<ActiveCell<R::Key, R::Column>>>>,
commit: Option<Rc<dyn CellCommit>>,
}
impl<'a, R: GridRow> CellElementContext<'a, R> {
pub fn row(&self) -> &'a R {
self.row
}
pub fn shared_row(&self) -> &'a Arc<R> {
self.row
}
pub fn key(&self) -> &'a R::Key {
self.row.key()
}
pub fn column(&self) -> R::Column {
self.column
}
pub fn value(&self) -> CellValue<'a> {
self.value
}
pub fn text(&self) -> &'a str {
self.text
}
pub fn change(&self) -> Option<CellChange> {
self.change
}
pub fn size(&self) -> ComponentSize {
self.size
}
pub fn cell_size(&self) -> Size<Pixels> {
self.cell_size
}
pub fn is_selected(&self) -> bool {
self.selected
}
pub fn is_focused(&self) -> bool {
self.focused
}
pub fn edit_state(&self) -> Option<&'a EditState> {
self.edit_state
}
pub fn edit(&self) -> Option<CellEditHandle> {
let commit = self.commit.as_ref()?;
let row: Arc<dyn Any> = Arc::clone(self.row) as Arc<dyn Any>;
Some(CellEditHandle::new(
Rc::clone(commit),
row,
self.column.ix(),
))
}
pub fn on_activate(&self, handler: impl Fn(&mut Window, &mut App) + 'static) {
if let Some(activation) = self.activation {
*activation.borrow_mut() = Some(ActiveCell {
key: self.row.key().clone(),
column: self.column,
handler: Rc::new(handler),
});
}
}
}
fn component_size(row_height: Pixels) -> ComponentSize {
[
ComponentSize::XSmall,
ComponentSize::Small,
ComponentSize::Medium,
ComponentSize::Large,
]
.into_iter()
.find(|size| size.table_row_height() == row_height)
.unwrap_or(ComponentSize::Size(row_height))
}
struct HostA11y {
label: Option<SharedString>,
description: SharedString,
column_index: usize,
selected: Option<bool>,
}
impl<D: LiveGridDelegate> RowPlanner<'_, D> {
pub(super) fn plan_cell_host(
&mut self,
cell: &HostCell<'_, D::Row>,
window: &mut Window,
) -> bool {
let row = cell.row;
let live = row.is_live();
let bounds = cell.host_bounds();
let control = cell.content == CellContent::Control;
let widgets = self.widgets;
let activation = (live && control && cell.focused && row.pinned.is_none())
.then_some(&widgets.activation);
let delegate = self.delegate;
self.host_text.clear();
let text = display_text_in(cell.value, cell.number_format, &mut self.host_text);
let context = CellElementContext {
row: row.row,
column: cell.column,
value: cell.value,
text,
change: cell.change,
size: component_size(self.row_height),
cell_size: size(
(bounds.size.width - CELL_PADDING * 2.).max(px(0.)),
bounds.size.height,
),
selected: cell.selected,
focused: cell.focused,
edit_state: cell.edit_state,
activation,
commit: (live && self.edit.has_editor(cell.column.ix()) && row.pinned.is_none())
.then(|| widgets.commit(&self.grid)),
};
let Some(element) = delegate.render_cell(&context, window, self.app) else {
return false;
};
let a11y = self.a11y.as_ref().map(|input| HostA11y {
label: (!control).then(|| SharedString::from(text.to_owned())),
description: cell.title.clone(),
column_index: column_index(cell.view),
selected: input.cell_selected(cell.selected),
});
let column = cell.column;
if !live {
let grid = self.grid.clone();
self.hosts.push(CellHost {
layer: HostLayer::Widget,
column: column.ix(),
zone: cell.zone,
bounds,
element: CellHost::host_div(HostLayer::Widget, column.id())
.relative()
.flex()
.items_center()
.px(CELL_PADDING)
.map(|this| align_host(this, cell.align))
.child(element)
.child(
div()
.absolute()
.inset_0()
.block_mouse_except_scroll()
.on_any_mouse_down(move |event, window, cx| {
let _ = grid.update(cx, |state, cx| {
state.on_body_mouse_down(event, window, cx);
});
}),
),
});
return true;
}
let press = HostPress {
grid: self.grid.clone(),
row: Arc::clone(row.row),
column,
pinned: row.pinned,
};
let element = CellHost::host_div(HostLayer::Widget, column.id())
.flex()
.items_center()
.px(CELL_PADDING)
.map(|this| align_host(this, cell.align))
.block_mouse_except_scroll()
.capture_any_mouse_down({
let press = press.clone();
move |event, window, cx| press.record(event, window, cx)
})
.on_any_mouse_down(move |event, window, cx| press.accept(event, window, cx))
.when_some(a11y, |this, a11y| {
this.role(Role::GridCell)
.aria_column_index(a11y.column_index)
.aria_description(a11y.description)
.when_some(a11y.label, |this, label| this.aria_label(label))
.when_some(a11y.selected, |this, selected| this.aria_selected(selected))
})
.child(element);
self.hosts.push(CellHost {
layer: HostLayer::Widget,
column: column.ix(),
zone: cell.zone,
bounds,
element,
});
true
}
}
fn align_host<E: Styled>(host: E, align: ColumnAlign) -> E {
match align {
ColumnAlign::Start => host.justify_start(),
ColumnAlign::End => host.justify_end(),
ColumnAlign::Auto => host.justify_center(),
}
}
struct HostPress<D: LiveGridDelegate> {
grid: WeakEntity<LiveGridState<D>>,
row: Arc<D::Row>,
column: <D::Row as GridRow>::Column,
pinned: Option<PinnedEdge>,
}
impl<D: LiveGridDelegate> Clone for HostPress<D> {
fn clone(&self) -> Self {
Self {
grid: self.grid.clone(),
row: Arc::clone(&self.row),
column: self.column,
pinned: self.pinned,
}
}
}
impl<D: LiveGridDelegate> HostPress<D> {
fn record(&self, event: &MouseDownEvent, window: &mut Window, cx: &mut App) {
let press = CellPress {
key: self.row.key().clone(),
column: self.column,
pinned: self.pinned,
button: event.button,
accepted: false,
};
if self
.grid
.update(cx, |state, _| state.widgets.press = Some(press))
.is_err()
{
return;
}
let grid = self.grid.clone();
window.defer(cx, move |window, cx| {
let _ = grid.update(cx, |state, cx| state.settle_cell_press(window, cx));
});
}
fn accept(&self, event: &MouseDownEvent, window: &mut Window, cx: &mut App) {
let _ = self.grid.update(cx, |state, cx| {
if let Some(press) = &mut state.widgets.press {
press.accepted = true;
}
state.on_body_mouse_down(event, window, cx);
});
}
}
impl<D: LiveGridDelegate> LiveGridState<D> {
pub(super) fn bind_cell_actions<E: InteractiveElement>(root: E, cx: &Context<Self>) -> E {
root.on_action(cx.listener(Self::on_activate_cell))
}
fn on_activate_cell(&mut self, _: &ActivateCell, window: &mut Window, cx: &mut Context<Self>) {
let handler = self.selection.focus().and_then(|focus| {
let key = focus.row()?;
let column = focus.column();
if self.columns.column(column.ix()).content != CellContent::Control {
return None;
}
let activation = self.widgets.activation.borrow();
activation
.as_ref()
.filter(|active| active.key == *key && active.column == column)
.map(|active| Rc::clone(&active.handler))
});
match handler {
Some(handler) => window.defer(cx, move |window, cx| handler(window, cx)),
None => cx.propagate(),
}
}
fn settle_cell_press(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let Some(press) = self.widgets.press.take() else {
return;
};
if !press.accepted && press.pinned.is_none() {
self.focus_press(FocusedCell::new(press.key, press.column), cx);
if press.button != MouseButton::Left {
self.on_body_mouse_up(cx);
}
}
if !self.is_body_focused(window, cx) {
#[cfg(debug_assertions)]
self.warn_tab_stop_in_cell(window, cx);
window.focus(&self.focus_handle, cx);
}
}
#[cfg(debug_assertions)]
fn warn_tab_stop_in_cell(&self, window: &Window, cx: &App) {
use std::sync::atomic::{AtomicBool, Ordering};
static WARNED: AtomicBool = AtomicBool::new(false);
let in_cell = window.focused(cx).is_some_and(|focused| {
focused.tab_stop && self.focus_handle.contains(&focused, window)
});
if in_cell && !WARNED.swap(true, Ordering::Relaxed) {
log::warn!(
"an element in a grid cell took the keyboard focus as a Tab stop; \
give it `tab_stop(false)`: the grid is one Tab stop"
);
}
}
}