diff --git a/.github/workflows/check.yml b/.github/workflows/check.yml index 49746413..d991bac7 100644 --- a/.github/workflows/check.yml +++ b/.github/workflows/check.yml @@ -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' @@ -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: diff --git a/crates/rake-view-syntax/src/view.rs b/crates/rake-view-syntax/src/view.rs index 04028ed0..4cef0a3c 100644 --- a/crates/rake-view-syntax/src/view.rs +++ b/crates/rake-view-syntax/src/view.rs @@ -1236,7 +1236,7 @@ impl Element { } } - builder.extend(variants.emit_variants(mapped)); + builder.extend(variants.emit_variants(mapped, rake)); Ok(builder) } diff --git a/crates/rake-view-syntax/src/view/classes/error.rs b/crates/rake-view-syntax/src/view/classes/error.rs index a11f755f..8f4ac06e 100644 --- a/crates/rake-view-syntax/src/view/classes/error.rs +++ b/crates/rake-view-syntax/src/view/classes/error.rs @@ -58,6 +58,7 @@ pub fn unknown_variant(name: &str) -> String { &name, [ "hover:", + "drag-over:", "active:", "focus:", "focus-visible:", diff --git a/crates/rake-view-syntax/src/view/preset.rs b/crates/rake-view-syntax/src/view/preset.rs index 1eacf362..192d9445 100644 --- a/crates/rake-view-syntax/src/view/preset.rs +++ b/crates/rake-view-syntax/src/view/preset.rs @@ -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; diff --git a/crates/rake-view-syntax/src/view/style_plan.rs b/crates/rake-view-syntax/src/view/style_plan.rs index b664bf41..56b1f189 100644 --- a/crates/rake-view-syntax/src/view/style_plan.rs +++ b/crates/rake-view-syntax/src/view/style_plan.rs @@ -8,6 +8,7 @@ use quote::{format_ident, quote}; #[derive(Clone, PartialEq, Eq, PartialOrd, Ord)] pub(super) enum Variant { Hover, + DragOver, Active, Focus, FocusVisible, @@ -20,6 +21,7 @@ impl Variant { pub fn parse(name: &str, span: Span) -> syn::Result { Ok(match name { "hover" => Self::Hover, + "drag-over" => Self::DragOver, "active" => Self::Active, "focus" => Self::Focus, "focus-visible" => Self::FocusVisible, @@ -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", @@ -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", @@ -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 { @@ -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 diff --git a/crates/rake-view-syntax/src/view/tests.rs b/crates/rake-view-syntax/src/view/tests.rs index 3ebd677e..f4ab2199 100644 --- a/crates/rake-view-syntax/src/view/tests.rs +++ b/crates/rake-view-syntax/src/view/tests.rs @@ -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#"
"#) + .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()")); +} diff --git a/crates/rake/src/platform/browser.js b/crates/rake/src/platform/browser.js index aaa76549..0ae14749 100644 --- a/crates/rake/src/platform/browser.js +++ b/crates/rake/src/platform/browser.js @@ -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); + }; +} diff --git a/crates/rake/src/platform/browser.rs b/crates/rake/src/platform/browser.rs index 9bd6f9f9..d0777e16 100644 --- a/crates/rake/src/platform/browser.rs +++ b/crates/rake/src/platform/browser.rs @@ -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")] @@ -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, +} + +#[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) + '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); + let dispose = listen_canvas_drop(closure.as_ref().unchecked_ref()); + + CanvasFileDrop { + dispose, + _callback: closure, + } +} diff --git a/crates/rake/src/platform/files.rs b/crates/rake/src/platform/files.rs index 371ebe84..248777b6 100644 --- a/crates/rake/src/platform/files.rs +++ b/crates/rake/src/platform/files.rs @@ -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 { + #[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 { diff --git a/crates/rake/tests/view_state/events.rs b/crates/rake/tests/view_state/events.rs index 34683113..088a0d91 100644 --- a/crates/rake/tests/view_state/events.rs +++ b/crates/rake/tests/view_state/events.rs @@ -145,3 +145,53 @@ fn canonical_pointer_events_dispatch_and_disabled_buttons_suppress_them() { }) .unwrap(); } + +struct DropHost { + names: Vec, +} + +impl Render for DropHost { + fn render(&mut self, _: &mut gpui::Window, cx: &mut Context) -> impl IntoElement { + rake::view! { +
+ } + } +} + +#[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"); +} diff --git a/crates/rake/tests/view_state/theme.rs b/crates/rake/tests/view_state/theme.rs index 49c8a30b..79640fc4 100644 --- a/crates/rake/tests/view_state/theme.rs +++ b/crates/rake/tests/view_state/theme.rs @@ -205,3 +205,89 @@ fn deep_components_read_replaced_themes_and_rebuild_hover_refinements() { } } } + +struct FileDropHost { + color: Rc>, +} + +impl gpui::Render for FileDropHost { + fn render( + &mut self, + _: &mut gpui::Window, + _: &mut gpui::Context, + ) -> impl gpui::IntoElement { + let color = self.color.clone(); + + rake::view! { +
+ { + // Drag-over styling uses hitboxes, which are available during paint. + gpui::canvas( + |_, _, _| {}, + move |_, _, window, _| color.set(window.text_style().color) + ) + .size_full() + } +
+ } + } +} + +#[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"); + } +} diff --git a/docs/platform-services.md b/docs/platform-services.md index 20bf8f89..63d7f493 100644 --- a/docs/platform-services.md +++ b/docs/platform-services.md @@ -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. diff --git a/docs/view.md b/docs/view.md index 0c6cea3f..215013eb 100644 --- a/docs/view.md +++ b/docs/view.md @@ -190,7 +190,7 @@ named-value and reusable-function APIs. Existing scale values keep their GPUI convenience methods, and utilities map to the pinned GPUI builder methods. `truncate` and `whitespace-nowrap` are raw GPUI text styling. Composed paragraphs and headings also provide explicit `wrap`, `ellipsis` and `max-lines` controls. -Interaction variants use `hover:`, `active:`, `focus:`, `focus-visible:` and `in-focus:`. Named groups use `group/card`, `group-hover/card:` and `group-active/card:`. +Interaction variants use `drag-over:` (external file paths), `hover:`, `active:`, `focus:`, `focus-visible:` and `in-focus:`. Named groups use `group/card`, `group-hover/card:` and `group-active/card:`. - Each interaction kind merges into one GPUI style call, including from conditional class attributes. - A named group must use the same name across all literal class branches, even if the leaves are mutually exclusive. @@ -855,3 +855,21 @@ For custom GPUI windows, call `rake::theme::register(cx, mode, light, dark)` and palettes go through the same Base and optional Kit bridge as `theme::install`. The preference and active palette are application-wide; the latest observed window appearance supplies the system preference. + +## External file drops + +External file drops use the typed `on:drop` callback: + +```rust +on:drop={cx.listener(|this, paths: &gpui::ExternalPaths, _, cx| { + let file = rake::platform::FileHandle::from_drop(paths); + // Await file?.read(max_bytes) in retained asynchronous work. +})} +``` + +Give the target an `aria-label` and a keyboard-accessible import button. Use +`class="bg-surface drag-over:bg-hover"` (using your theme’s `surface` and `hover` colors) +for drag-over feedback. Native external paths are delivered by the platform on +macOS, Windows and Linux. Browser canvases use +`rake::platform::browser::on_canvas_file_drop` instead; retain its returned +subscription for the lifetime of the view. The files example shows both adapters. diff --git a/examples/files/src/lib.rs b/examples/files/src/lib.rs index b1ee6cab..3151ad47 100644 --- a/examples/files/src/lib.rs +++ b/examples/files/src/lib.rs @@ -12,6 +12,7 @@ use std::rc::Rc; struct Colors { surface: gpui::Rgba, ink: gpui::Rgba, + drop_surface: gpui::Rgba, } rake::theme!(Colors); @@ -63,6 +64,8 @@ async fn prepare( } struct Toolkit { + #[cfg(target_family = "wasm")] + _file_drop: rake::platform::browser::CanvasFileDrop, runtime: RuntimeContext, workspace: Rc, preferences: Preferences, @@ -82,6 +85,19 @@ impl Toolkit { } let selection = self.runtime.services().platform().pick_file(cx); + + self.import_selection(selection, cx); + } + + fn import_selection( + &mut self, + selection: rake::platform::Request>, + cx: &mut Context, + ) { + if self.busy(cx) || self.workspace.dirty() { + return; + } + let executor = cx.background_executor().clone(); let workspace = self.workspace.clone(); let expected = workspace.revision(); @@ -214,7 +230,14 @@ impl Render for Toolkit { rake::view! {

"Text Toolkit"

@@ -434,6 +457,7 @@ pub fn application() -> Result { .theme(Colors { surface: gpui::rgb(0x18232b), ink: gpui::rgb(0xf0f4e8), + drop_surface: gpui::rgb(0x365849), }) .control(rake::control::ControlConfig::FromEnvironment) .quit_guard(move |_| { @@ -485,7 +509,22 @@ pub fn application() -> Result { }) }); + #[cfg(target_family = "wasm")] + let file_drop = { + let entity: gpui::WeakEntity = cx.entity().downgrade(); + let mut app = cx.to_async(); + + rake::platform::browser::on_canvas_file_drop(move |file| { + let _ = entity.update(&mut app, |this, cx| { + this.import_selection(Box::pin(async move { file.map(Some) }), cx); + cx.notify(); + }); + }) + }; + Toolkit { + #[cfg(target_family = "wasm")] + _file_drop: file_drop, updates: runtime.bind_updates(cx), runtime, workspace: workspace.clone(), diff --git a/scripts/test-file-drop.mjs b/scripts/test-file-drop.mjs new file mode 100644 index 00000000..4e73f7f0 --- /dev/null +++ b/scripts/test-file-drop.mjs @@ -0,0 +1,35 @@ +import assert from 'node:assert/strict'; +import {on_canvas_file_drop, read_file} from '../crates/rake/src/platform/browser.js'; +globalThis.document = new EventTarget(); +const canvas = new EventTarget(); +canvas.tagName = 'CANVAS'; +canvas.style = {}; +const results = []; +const dispose = on_canvas_file_drop(file => results.push(file)); +const file = new File(['hello'], 'hello.txt'); +function drop(files) { + const event = new Event('drop', {cancelable: true}); + Object.defineProperties(event, {target: {value: canvas}, dataTransfer: {value: {files, types: ['Files']}}}); + document.dispatchEvent(event); + assert(event.defaultPrevented); +} +drop([file]); +assert.equal(results[0], file); +assert.equal(new TextDecoder().decode(await read_file(results[0], 5)), 'hello'); +await assert.rejects(read_file(file, 4), {name: 'RakeSizeLimit'}); +drop([file, file]); +assert.equal(results[1], null); +for (const type of ['dragover', 'drop']) { + const event = new Event(type, {cancelable: true}); + Object.defineProperties(event, {target: {value: canvas}, dataTransfer: {value: {types: ['text/plain'], files: []}}}); + document.dispatchEvent(event); + assert.equal(event.defaultPrevented, false, `${type} must ignore text drags`); + assert.equal(results.length, 2, 'non-file drag must not call the file handler'); + assert.equal(canvas.style.outline, '', 'non-file drag must not highlight the canvas'); +} +dispose(); +const event = new Event('drop'); +Object.defineProperties(event, {target: {value: canvas}, dataTransfer: {value: {files: [file], types: ['Files']}}}); +document.dispatchEvent(event); +assert.equal(results.length, 2); +console.log('Canvas drop identity, bounds, count and disposal passed'); diff --git a/scripts/test-web-platform.mjs b/scripts/test-web-platform.mjs index 85ca0ea9..dbbd3f06 100644 --- a/scripts/test-web-platform.mjs +++ b/scripts/test-web-platform.mjs @@ -110,6 +110,26 @@ try { await call('DOM.setFileInputFiles', {files: [textFile], backendNodeId: chooser.params.backendNodeId}, old); await eventually(() => evaluate(old, '!!window.picked || !!window.pickError')); assert.deepEqual(await evaluate(old, 'window.picked'), {name: 'hello.txt', text: 'Unicode 漢字'}); + assert.deepEqual(await evaluate(old, `(async () => { + const canvas = document.createElement('canvas'); + canvas.setAttribute('aria-label', 'Drop one text file'); + document.body.append(canvas); + let received; + const dispose = platform.on_canvas_file_drop(file => { received = file; }); + const file = new File(['dropped text'], 'drop.txt'); + const transfer = new DataTransfer(); + transfer.items.add(file); + canvas.dispatchEvent(new DragEvent('drop', {bubbles: true, cancelable: true, dataTransfer: transfer})); + const result = {same: received === file, name: received.name, + text: new TextDecoder().decode(await platform.read_file(received, 100))}; + transfer.items.add(new File(['second'], 'second.txt')); + canvas.dispatchEvent(new DragEvent('drop', {bubbles: true, cancelable: true, dataTransfer: transfer})); + result.multipleRejected = received === null; + dispose(); + canvas.remove(); + return result; + })()`), {same: true, name: 'drop.txt', text: 'dropped text', multipleRejected: true}); + await call('Browser.grantPermissions', {origin, permissions: ['clipboardReadWrite', 'clipboardSanitizedWrite']}); // Keep existing clipboard content inside this page and restore it without logging it. await evaluate(old, 'navigator.clipboard.readText().then(value => { window.previousClipboard = value; })', true);