Skip to content
Merged
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
3 changes: 2 additions & 1 deletion .github/workflows/check.yml
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ jobs:
node scripts/test-web-runtime.mjs
node scripts/test-offline.mjs
node scripts/test-file-processing.mjs
node scripts/test-file-drop.mjs

portable:
if: github.event_name != 'schedule'
Expand Down Expand Up @@ -118,7 +119,7 @@ jobs:
- os: windows-latest
updates: updates-velopack
runs-on: ${{ matrix.os }}
timeout-minutes: 60
timeout-minutes: ${{ matrix.os == 'windows-latest' && 90 || 60 }}
env:
RUST_BACKTRACE: "1"
steps:
Expand Down
2 changes: 1 addition & 1 deletion crates/rake-view-syntax/src/view.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1236,7 +1236,7 @@ impl Element {
}
}

builder.extend(variants.emit_variants(mapped));
builder.extend(variants.emit_variants(mapped, rake));

Ok(builder)
}
Expand Down
1 change: 1 addition & 0 deletions crates/rake-view-syntax/src/view/classes/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ pub fn unknown_variant(name: &str) -> String {
&name,
[
"hover:",
"drag-over:",
"active:",
"focus:",
"focus-visible:",
Expand Down
2 changes: 1 addition & 1 deletion crates/rake-view-syntax/src/view/preset.rs
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ pub fn expand(
let theme = theme::expression_use(&value).map(|span| theme::binding(span, rake));
let builder = format_ident!("__rake_style", span = Span::mixed_site());
let body = plan.emit_refinement(&builder);
let variants = plan.emit_variants(&builder);
let variants = plan.emit_variants(&builder, rake);
let name = &signature.ident;
let visibility = &item.vis;
let attributes = &item.attrs;
Expand Down
16 changes: 14 additions & 2 deletions crates/rake-view-syntax/src/view/style_plan.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ use quote::{format_ident, quote};
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord)]
pub(super) enum Variant {
Hover,
DragOver,
Active,
Focus,
FocusVisible,
Expand All @@ -20,6 +21,7 @@ impl Variant {
pub fn parse(name: &str, span: Span) -> syn::Result<Self> {
Ok(match name {
"hover" => Self::Hover,
"drag-over" => Self::DragOver,
"active" => Self::Active,
"focus" => Self::Focus,
"focus-visible" => Self::FocusVisible,
Expand Down Expand Up @@ -48,6 +50,7 @@ impl Variant {
pub fn method(&self) -> &'static str {
match self {
Self::Hover => "hover",
Self::DragOver => "drag_over",
Self::Active => "active",
Self::Focus => "focus",
Self::FocusVisible => "focus_visible",
Expand All @@ -59,6 +62,7 @@ impl Variant {

pub fn name(&self) -> &'static str {
match self {
Self::DragOver => "drag-over",
Self::FocusVisible => "focus-visible",
Self::InFocus => "in-focus",
Self::GroupHover(_) => "group-hover",
Expand Down Expand Up @@ -185,7 +189,7 @@ impl StylePlan {
emit_segments(&self.base, mapped)
}

pub fn emit_variants(&self, mapped: &Ident) -> TokenStream {
pub fn emit_variants(&self, mapped: &Ident, rake: &TokenStream) -> TokenStream {
let mut methods = TokenStream::new();

for (variant, segments) in &self.variants {
Expand All @@ -198,7 +202,15 @@ impl StylePlan {

let body = emit_segments(segments, mapped);

methods.extend(quote!(.#method(#group |#mapped| { #body #mapped })));
if matches!(variant, Variant::DragOver) {
methods.extend(quote!(.drag_over::<#rake::gpui::ExternalPaths>({
let #mapped = #rake::gpui::StyleRefinement::default();
#body
move |_, _, _, _| #mapped.clone()
})));
} else {
methods.extend(quote!(.#method(#group |#mapped| { #body #mapped })));
}
}

methods
Expand Down
14 changes: 14 additions & 0 deletions crates/rake-view-syntax/src/view/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -732,3 +732,17 @@ fn only_the_root_retains_layout_for_nested_elements_and_markup_properties() {
}
}
}

#[test]
fn file_drag_over_classes_merge_with_the_external_paths_payload() {
let expanded =
expand(r#"<div class="drag-over:opacity-50" class:drag-over:border-2={selected}/>"#)
.expect("file drag classes")
.to_string()
.replace(' ', "");

assert_eq!(expanded.matches(".drag_over::<").count(), 1);
assert!(expanded.contains("renamed::gpui::ExternalPaths>"));
assert!(expanded.contains(".opacity(0.5"));
assert!(expanded.contains(".border_2()"));
}
29 changes: 29 additions & 0 deletions crates/rake/src/platform/browser.js
Original file line number Diff line number Diff line change
Expand Up @@ -99,3 +99,32 @@ export function open_url(url) {
try { opened.opener = null; opened.location.href = url; }
catch (error) { opened.close(); throw error; }
}

// Canvas-wide listener; disposal removes every listener and releases the callback.
export function on_canvas_file_drop(callback) {
const canvasEvent = event => event.target?.tagName === 'CANVAS';
const fileEvent = event => canvasEvent(event) && Array.from(event.dataTransfer?.types ?? []).includes('Files');
const over = event => {
if (!fileEvent(event)) return;
event.preventDefault();
event.target.style.outline = '2px solid currentColor';
};
const leave = event => {
if (canvasEvent(event)) event.target.style.outline = '';
};
const drop = event => {
if (!fileEvent(event)) return;
event.preventDefault();
leave(event);
const files = event.dataTransfer?.files;
callback(files?.length === 1 ? files[0] : null);
};
document.addEventListener('dragover', over);
document.addEventListener('dragleave', leave);
document.addEventListener('drop', drop);
return () => {
document.removeEventListener('dragover', over);
document.removeEventListener('dragleave', leave);
document.removeEventListener('drop', drop);
};
}
40 changes: 40 additions & 0 deletions crates/rake/src/platform/browser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,9 @@ extern "C" {
#[wasm_bindgen(js_name = capabilities)]
fn detect() -> u32;
#[cfg(feature = "gpui")]
#[wasm_bindgen(js_name = on_canvas_file_drop)]
fn listen_canvas_drop(callback: &js_sys::Function) -> js_sys::Function;
#[cfg(feature = "gpui")]
#[wasm_bindgen(js_name = pick_file)]
fn select_file() -> js_sys::Promise;
#[cfg(feature = "gpui")]
Expand Down Expand Up @@ -172,3 +175,40 @@ pub(super) fn write_clipboard(text: &str) -> Request<()> {
pub(super) fn open_url(url: &str) -> Result<(), Error> {
launch_url(url).map_err(|value| error("open URL", value))
}

/// Owns canvas drop listeners. Retain it while the target view is mounted.
#[cfg(feature = "gpui")]
pub struct CanvasFileDrop {
dispose: js_sys::Function,
_callback: Closure<dyn FnMut(JsValue)>,
}

#[cfg(feature = "gpui")]
impl Drop for CanvasFileDrop {
fn drop(&mut self) {
let _ = self.dispose.call0(&JsValue::NULL);
}
}

/// Registers a canvas-wide single-file target without inventing filesystem paths.
/// Empty and multi-file drops report invalid input. Reading remains caller bounded.
#[cfg(feature = "gpui")]
pub fn on_canvas_file_drop(
mut callback: impl FnMut(Result<super::FileHandle, Error>) + 'static,
) -> CanvasFileDrop {
let closure = Closure::wrap(Box::new(move |file: JsValue| {
let name = js_sys::Reflect::get(&file, &JsValue::from_str("name"))
.ok()
.and_then(|name| name.as_string());
callback(match name {
Some(name) => Ok(super::FileHandle { name, file }),
None => Err(Error::InvalidInput("drop exactly one file".into())),
});
}) as Box<dyn FnMut(JsValue)>);
let dispose = listen_canvas_drop(closure.as_ref().unchecked_ref());

CanvasFileDrop {
dispose,
_callback: closure,
}
}
23 changes: 23 additions & 0 deletions crates/rake/src/platform/files.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,29 @@ impl FileHandle {
Self { name, path }
}

/// Accepts exactly one external file without reading it. Directories and read
/// limits are checked by [`Self::read`], off the UI thread.
///
/// # Errors
/// Rejects empty and multi-file drops.
pub fn from_drop(paths: &gpui::ExternalPaths) -> Result<Self, Error> {
#[cfg(target_family = "wasm")]
{
let _ = paths;

Err(Error::Unsupported("native path drop"))
}

#[cfg(not(target_family = "wasm"))]
{
if paths.paths().len() != 1 {
return Err(Error::InvalidInput("drop exactly one file".into()));
}

Ok(Self::from_path(paths.paths()[0].clone()))
}
}

/// Native extension for applications that need filesystem integration.
#[cfg(not(target_family = "wasm"))]
pub fn native_path(&self) -> &std::path::Path {
Expand Down
50 changes: 50 additions & 0 deletions crates/rake/tests/view_state/events.rs
Original file line number Diff line number Diff line change
Expand Up @@ -145,3 +145,53 @@ fn canonical_pointer_events_dispatch_and_disabled_buttons_suppress_them() {
})
.unwrap();
}

struct DropHost {
names: Vec<String>,
}

impl Render for DropHost {
fn render(&mut self, _: &mut gpui::Window, cx: &mut Context<Self>) -> impl IntoElement {
rake::view! {
<div
class="size-full"
aria-label="Drop one file"
on:drop={
cx.listener(|this, paths: &gpui::ExternalPaths, _, _| {
if let Ok(file) = rake::platform::FileHandle::from_drop(paths) {
this.names.push(file.name().to_owned());
}
})
}
/>
}
}
}

#[test]
fn external_file_drop_dispatches_and_rejects_multiple_files() {
let mut cx = gpui::TestAppContext::single();
let window = cx.add_window(|_, _| DropHost { names: Vec::new() });

draw(&mut cx, window);
for names in [vec!["hello.txt"], vec!["a.txt", "b.txt"], vec![]] {
cx.update_window(window.into(), |_, window, cx| {
let position = gpui::point(gpui::px(20.), gpui::px(20.));
let paths = gpui::ExternalPaths(names.iter().map(std::path::PathBuf::from).collect());
window.dispatch_event(
gpui::FileDropEvent::Entered { position, paths }.to_platform_input(),
cx,
);
window.dispatch_event(
gpui::FileDropEvent::Submit { position }.to_platform_input(),
cx,
);
})
.expect("dispatch external drop");
cx.run_until_parked();
}

window
.read_with(&cx, |host, _| assert_eq!(host.names, ["hello.txt"]))
.expect("read drop target");
}
86 changes: 86 additions & 0 deletions crates/rake/tests/view_state/theme.rs
Original file line number Diff line number Diff line change
Expand Up @@ -205,3 +205,89 @@ fn deep_components_read_replaced_themes_and_rebuild_hover_refinements() {
}
}
}

struct FileDropHost {
color: Rc<Cell<gpui::Hsla>>,
}

impl gpui::Render for FileDropHost {
fn render(
&mut self,
_: &mut gpui::Window,
_: &mut gpui::Context<Self>,
) -> impl gpui::IntoElement {
let color = self.color.clone();

rake::view! {
<div
class="w-20 h-20 text-surface drag-over:text-hover"
aria-label="Drop a file"
on:drop={|_: &gpui::ExternalPaths, _, _| {}}
>
{
// Drag-over styling uses hitboxes, which are available during paint.
gpui::canvas(
|_, _, _| {},
move |_, _, window, _| color.set(window.text_style().color)
)
.size_full()
}
</div>
}
}
}

#[test]
fn file_drag_over_classes_apply_theme_and_clear_on_exit_and_submit() {
let mut cx = gpui::TestAppContext::single();
let surface = gpui::rgb(0x18232b);
let hover = gpui::rgb(0x365849);
let color = Rc::new(Cell::new(gpui::Hsla::default()));

cx.update(|cx| theme::install(cx, Palette { surface, hover }));

let window = cx.add_window(|_, _| FileDropHost {
color: color.clone(),
});

super::draw(&mut cx, window);
assert_eq!(color.get(), gpui::Hsla::from(surface));

let dispatch = |cx: &mut gpui::TestAppContext, event: gpui::FileDropEvent| {
cx.update_window(window.into(), |_, window, cx| {
window.dispatch_event(event.to_platform_input(), cx);
})
.expect("dispatch file drag");
super::draw(cx, window);
};
let inside = gpui::point(gpui::px(10.), gpui::px(10.));
let outside = gpui::point(gpui::px(200.), gpui::px(200.));

for submit in [false, true] {
dispatch(
&mut cx,
gpui::FileDropEvent::Entered {
position: inside,
paths: gpui::ExternalPaths(
[std::path::PathBuf::from("hello.txt")]
.into_iter()
.collect(),
),
},
);
assert_eq!(color.get(), gpui::Hsla::from(hover), "entered target");
dispatch(&mut cx, gpui::FileDropEvent::Pending { position: outside });
assert_eq!(color.get(), gpui::Hsla::from(surface), "outside target");
dispatch(&mut cx, gpui::FileDropEvent::Pending { position: inside });
assert_eq!(color.get(), gpui::Hsla::from(hover), "pending over target");
dispatch(
&mut cx,
if submit {
gpui::FileDropEvent::Submit { position: inside }
} else {
gpui::FileDropEvent::Exited
},
);
assert_eq!(color.get(), gpui::Hsla::from(surface), "drag ended");
}
}
13 changes: 13 additions & 0 deletions docs/platform-services.md
Original file line number Diff line number Diff line change
Expand Up @@ -64,3 +64,16 @@ windows. This GUI capability is separate from portable notifications and launch
services. Browser/headless GUI calls are explicit errors. See [tray icons](tray.md).

See [OS notifications](notifications.md) for permission results, URL payloads, packaging requirements and the portable Foundation example.

File drops reuse `FileHandle::read(max_bytes)` and its size and regular-file
validation. `FileHandle::from_drop(&gpui::ExternalPaths)` accepts exactly one
native path without reading on the UI thread. Empty and multi-file drops fail.
The files example accepts one UTF-8 file up to 128 KiB and refuses replacement
while busy or while a transformation is unsaved.

On Web, `platform::browser::on_canvas_file_drop` registers a canvas-wide target
and returns an owned subscription. Its callback receives a real browser File
handle through `FileHandle`, with the same bounded read as `pick_file`; it never
exposes a synthetic path. Empty or multi-file drops report `InvalidInput`.
Dropping the subscription removes the DOM listeners. Drag-over outlines the
canvas; retain an accessible target label and the import button for keyboard use.
Loading
Loading