Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions crates/gpui/nsh-platform-gpui/src/app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -404,6 +404,7 @@ impl AppView {
cx.observe_window_activation(window, |view: &mut AppView, window, cx| {
if !window.is_window_active() {
crate::keymap::forget_held(&view.surface);
crate::selectable_view::cancel_drag_in(&view.surface, nsh_core::ROOT_ID);
}
cx.notify();
})
Expand Down
77 changes: 57 additions & 20 deletions crates/gpui/nsh-platform-gpui/src/selectable_view.rs
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,8 @@ struct Active {
reported: String,
/// The ends last reported with it (`SelectionModel::ends`).
reported_ends: Option<[(u64, u32); 2]>,
/// Whether the last report was emitted during an active drag.
reported_dragging: bool,
/// The ends' texts, whose virtual list rows stay rendered while
/// scrolled away: recycled, they would show other items.
kept: KeptRows,
Expand Down Expand Up @@ -302,6 +304,7 @@ fn with_area<R>(surface: u64, area: &NshView, f: impl FnOnce(&mut Active) -> R)
gesture: None,
reported: String::new(),
reported_ends: None,
reported_dragging: false,
kept: KeptRows::default(),
});
(old, f(a))
Expand Down Expand Up @@ -333,20 +336,26 @@ fn report(surface: u64) {
if !listens {
return None;
}
let (text, start, ends) = if a.model.is_empty() {
(String::new(), 0, None)
let (text, start, ends, dragging) = if a.model.is_empty() {
(String::new(), 0, None, false)
} else {
let active_drag = a.gesture.as_ref().is_some_and(|g| g.dragging);
AreaTexts::of(&a.area).map_or_else(
|| (String::new(), 0, None),
|t| (a.model.text(&t), a.model.start_offset(&t), a.model.ends(&t)),
|| (String::new(), 0, None, false),
|t| {
let text = a.model.text(&t);
let dragging = !text.is_empty() && active_drag;
(text, a.model.start_offset(&t), a.model.ends(&t), dragging)
},
)
};
if text == a.reported && ends == a.reported_ends {
if text == a.reported && ends == a.reported_ends && dragging == a.reported_dragging {
return None;
}
a.reported.clone_from(&text);
a.reported_ends = ends;
Some((id, text, start, ends))
a.reported_dragging = dragging;
Some((id, text, start, ends, dragging))
});
if let Some(change) = change {
send(surface, change);
Expand All @@ -361,14 +370,13 @@ fn cleared(old: &mut Active) {
}
if !old.reported.is_empty() && old.area.attached() {
let id = old.area.state().id;
send(old.surface, (id, String::new(), 0, None));
send(old.surface, (id, String::new(), 0, None, false));
}
}

/// An `onSelectionChange` due: the area, the selected text, where it
/// starts and its ends (`SelectionModel::ends`), which the core places in
/// list items.
type Change = (NodeId, String, u32, Option<[(u64, u32); 2]>);
/// starts, its ends (`SelectionModel::ends`), and whether a drag is active.
type Change = (NodeId, String, u32, Option<[(u64, u32); 2]>, bool);

/// Keeps the virtual list rows holding `nodes` of `surface` rendered
/// (none: releases them).
Expand All @@ -380,11 +388,12 @@ fn keep_rendered(surface: u64, nodes: Vec<u64>) {
}

/// Sends `onSelectionChange` with `change` to its view of `surface`.
fn send(surface: u64, (id, text, start, ends): Change) {
fn send(surface: u64, (id, text, start, ends, dragging): Change) {
if let Some(surface) = Surface::by_key(surface) {
let mut fields = vec![
("text", PayloadValue::Str(text)),
("start", PayloadValue::Number(f64::from(start))),
("dragging", PayloadValue::Bool(dragging)),
];
if let Some(ends) = ends {
fields.extend(nsh_core::selection::end_fields(ends));
Expand Down Expand Up @@ -488,6 +497,25 @@ pub(crate) fn down(
});
}

/// Ends any active selection drag owned by window `root` (`ROOT_ID` for the
/// main window, or a secondary `<Window>`'s root node id), e.g. when that
/// window deactivates before the pointer release reaches it.
pub(crate) fn cancel_drag_in(surface: &Rc<Surface>, root: NodeId) {
let key = surface.key();
let ended = ACTIVE.with_borrow_mut(|active| {
let Some(a) = active.as_mut().filter(|a| a.surface == key) else {
return false;
};
if crate::window::root_of(surface, &a.area) != root {
return false;
}
a.gesture.take().is_some_and(|g| g.dragging)
});
if ended {
report(key);
}
}

/// The mouse moved or its button went up (`kind`) at `(x, y)` (root
/// coordinates) after [`down`]; true when the area took it (a drag that
/// selects).
Expand Down Expand Up @@ -531,21 +559,30 @@ pub(crate) fn pointer(surface: &Rc<Surface>, kind: PointerKind, x: f32, y: f32)
taken
}
PointerKind::Up | PointerKind::Cancel => {
let text = ACTIVE.with_borrow_mut(|active| {
let a = active.as_mut().filter(|a| a.surface == key)?;
let g = a.gesture.take()?;
if !g.dragging || a.model.is_empty() {
return Some(None);
let (ended_drag, text) = ACTIVE.with_borrow_mut(|active| {
let Some(a) = active.as_mut().filter(|a| a.surface == key) else {
return (false, None);
};
let Some(g) = a.gesture.take() else {
return (false, None);
};
if !g.dragging {
return (false, None);
}
let texts = AreaTexts::of(&a.area)?;
Some(Some(a.model.text(&texts)))
let text = (!a.model.is_empty())
.then(|| AreaTexts::of(&a.area).map(|texts| a.model.text(&texts)))
.flatten();
(true, text)
});
if ended_drag {
report(key);
}
match text {
Some(Some(text)) => {
Some(text) => {
set_primary(text);
true
}
_ => false,
None => false,
}
}
PointerKind::Down | PointerKind::Leave => false,
Expand Down
1 change: 1 addition & 0 deletions crates/gpui/nsh-platform-gpui/src/window.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2010,6 +2010,7 @@ impl WindowView {
&& !is_active(gw, cx)
{
crate::keymap::forget_held(&surface);
crate::selectable_view::cancel_drag_in(&surface, self.window.id);
// Losing the focus closes a window that says so.
let w = &self.window;
if w.flag(|a| a.close_on_blur, false) && w.shown.get() && !w.hidden.get() {
Expand Down
4 changes: 4 additions & 0 deletions crates/nsh-base/src/text_view/view.rs
Original file line number Diff line number Diff line change
Expand Up @@ -319,6 +319,9 @@ pub struct TextViewSelectionEvent {
/// The same box in the root view the view is in, as of the event (an
/// `Overlay`'s `anchor`).
pub page_bounds: Option<Bounds<Points>>,
/// True while a pointer or selection-handle drag is still extending the
/// selection; flips to `false` once the drag ends.
pub dragging: bool,
}

/// An action of the code blocks of a [`TextView`] (`codeBlockActions`).
Expand Down Expand Up @@ -492,6 +495,7 @@ pub fn TextView(props: TextViewProps, cx: Scope<TextViewEvent>) -> impl IntoElem
start: e.start,
bounds: e.bounds,
page_bounds: e.page_bounds,
dragging: e.dragging,
}));
})
.map(|mut el| {
Expand Down
63 changes: 63 additions & 0 deletions crates/nsh-base/tests/base/text_view.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2496,3 +2496,66 @@ fn images_line_up_as_their_block_aligns() {
"{end:?}"
);
}

#[component]
fn TextViewDragging() -> impl IntoElement {
let log = signal(String::new());
view()
.flex_1()
.items_start()
.child(
text_view()
.selectable(true)
.markdown("Hello dragging world")
.on_selection_change(move |e: &nsh_base::TextViewSelectionEvent| {
log.update(|s| {
if !s.is_empty() {
s.push(';');
}
s.push_str(&format!("{}:{}", e.text, e.dragging));
});
}),
)
.child(text(move || format!("Log {}", log.get())))
}

#[test]
fn text_view_selection_change_forwards_dragging_state() {
let mut config = EngineConfig::new(nsh_testing::windowed_root::<TextViewDragging>());
config.environment.os = Os::MacOs;
config.environment.idiom = Idiom::Desktop;
let mut app = Headless::start(config).unwrap();
app.wait_for("Hello dragging world").unwrap();
app.drag(
"Hello dragging world",
point(px(50.0), px(0.0)),
DragOptions::default(),
)
.unwrap();
let line = app
.screen()
.texts()
.into_iter()
.find(|t| t.starts_with("Log "))
.expect("log text")
.trim_start_matches("Log ")
.to_string();
let events: Vec<(&str, bool)> = line
.split(';')
.filter(|s| !s.is_empty())
.map(|item| {
let (t, d) = item.rsplit_once(':').unwrap();
(t, d == "true")
})
.collect();
assert!(
events.iter().any(|(t, d)| !t.is_empty() && *d),
"expected TextView dragging=true mid-drag, got {events:?}"
);
let &(final_text, final_dragging) = events.last().expect("final event");
assert!(!final_text.is_empty(), "got {events:?}");
assert!(
!final_dragging,
"expected dragging=false after release, got {events:?}"
);
}
7 changes: 4 additions & 3 deletions crates/nsh-core/src/element/builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2096,9 +2096,10 @@ pub trait Interactive: Element {
/// ([`Self::selectable`]) changed: the selected text, as a copy gives
/// it, empty once nothing is selected, where it starts in the view's
/// whole text, the box around it in the view and in its root view, and
/// the list items its ends are in (TSX `onSelectionChange` of a
/// `<View selectable>`, `{ text, start, bounds, pageBounds, anchor,
/// focus }`). Only the outermost selectable view of an area
/// the list items its ends are in, and whether a drag is still active
/// (TSX `onSelectionChange` of a `<View selectable>`, `{ text, start,
/// bounds, pageBounds, anchor, focus, dragging }`). Only the outermost
/// selectable view of an area
/// reports it; an [`Input`](super::Input)'s own selection is its
/// `on_selection_change`.
fn on_text_selection_change<M>(
Expand Down
29 changes: 29 additions & 0 deletions crates/nsh-core/src/element/events.rs
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,10 @@ pub struct TextSelectionEvent {
/// is in a list item, as of the event. Before [`Self::anchor`] in the
/// list when the user selected backward.
pub focus: Option<TextSelectionEndpoint>,
/// True while a pointer or selection-handle drag is still extending the
/// selection; flips to `false` once the drag ends so overlays anchored at
/// [`Self::page_bounds`] can appear without flickering mid-drag.
pub dragging: bool,
}

/// One end of a selection across a list's items
Expand Down Expand Up @@ -602,6 +606,7 @@ pub(crate) fn selected_text(p: &EventPayload) -> Option<Cow<'_, TextSelectionEve
page_bounds: optional_bounds("pageBounds"),
anchor: endpoint(anchor),
focus: endpoint(focus),
dragging: matches!(field(p, "dragging"), Some(PayloadValue::Bool(true))),
}))
}

Expand Down Expand Up @@ -956,4 +961,28 @@ mod tests {
super::Composition::default()
);
}

#[test]
fn selected_text_reads_dragging_state() {
use crate::{EventPayload, PayloadValue};
let active = EventPayload::Map(vec![
("text", PayloadValue::Str("hello".into())),
("start", PayloadValue::Number(2.0)),
("dragging", PayloadValue::Bool(true)),
]);
let ev = super::selected_text(&active).unwrap();
assert_eq!(ev.text, "hello");
assert_eq!(ev.start, Some(2));
assert!(ev.dragging);

let settled = EventPayload::Map(vec![
("text", PayloadValue::Str("hello".into())),
("start", PayloadValue::Number(2.0)),
("dragging", PayloadValue::Bool(false)),
]);
assert!(!super::selected_text(&settled).unwrap().dragging);

let omitted = EventPayload::Map(vec![("text", PayloadValue::Str("hello".into()))]);
assert!(!super::selected_text(&omitted).unwrap().dragging);
}
}
4 changes: 2 additions & 2 deletions crates/nsh-core/src/js/host.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1040,8 +1040,8 @@ pub const EVENTS: &[(EventKind, u32, &str, &str)] = &[
(
EventKind::SelectionChange,
on::VIEW,
"(e: { text: string; start?: number; bounds?: Bounds; pageBounds?: Bounds; anchor?: TextSelectionEndpoint; focus?: TextSelectionEndpoint }) => void",
"The selection across the texts of a `selectable` view changed: `text` is what a copy would give, empty once nothing is selected; `start` is where it starts in the view's whole text (UTF-16 units) when the platform knows it; `bounds` is the box around the selected text in the view and `pageBounds` in the root view it is in, as of the event (an `Overlay`'s `anchor`: a bar of actions on the selection), while something is selected and the platform knows them. `anchor` (where the selection started) and `focus` (where it goes now, before `anchor` when the user selected backward) name the `List` item each end is in by its key, with the offset in that item's text, while something is selected and the end is in a list item. Only the outermost selectable view of an area reports it.",
"(e: { text: string; start?: number; bounds?: Bounds; pageBounds?: Bounds; anchor?: TextSelectionEndpoint; focus?: TextSelectionEndpoint; dragging: boolean }) => void",
"The selection across the texts of a `selectable` view changed: `text` is what a copy would give, empty once nothing is selected; `start` is where it starts in the view's whole text (UTF-16 units) when the platform knows it; `bounds` is the box around the selected text in the view and `pageBounds` in the root view it is in, as of the event (an `Overlay`'s `anchor`: a bar of actions on the selection), while something is selected and the platform knows them. `anchor` (where the selection started) and `focus` (where it goes now, before `anchor` when the user selected backward) name the `List` item each end is in by its key, with the offset in that item's text, while something is selected and the end is in a list item. `dragging` is `true` while a pointer or selection-handle drag is still extending the selection, then flips to `false` once the drag ends. Only the outermost selectable view of an area reports it.",
),
(
EventKind::Paste,
Expand Down
7 changes: 7 additions & 0 deletions crates/nsh-js/src/host.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1386,11 +1386,18 @@ fn text_selection<'js>(
) -> rquickjs::Result<Value<'js>> {
let ends = nsh_core::selection::ITEM_FIELDS;
let obj = rquickjs::Object::new(cx.clone())?;
let mut has_dragging = false;
for (key, value) in fields {
if !ends.iter().any(|(k, o)| key == k || key == o) {
if *key == "dragging" {
has_dragging = true;
}
obj.set(*key, payload_value(cx, value)?)?;
}
}
if !has_dragging {
obj.set("dragging", false)?;
}
let field = |name: &str| fields.iter().find(|(k, _)| *k == name).map(|(_, v)| v);
for ((key, offset), name) in ends.into_iter().zip(["anchor", "focus"]) {
if let (Some(key), Some(offset)) = (field(key), field(offset)) {
Expand Down
Loading
Loading