teksilo-widgets 0.9.0

Widget library for Teksilo — over a hundred widgets and layout primitives, from Button to TreeTableView.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
// SPDX-License-Identifier: MPL-2.0
// SPDX-FileCopyrightText: 2026 FernTech

//! `DropZone` — a "drop files here" target for external (OS) drag-and-drop.
//!
//! A bordered, tinted region that accepts files / text / URLs dragged in from
//! the operating system (Finder, Explorer, Nautilus) or another application.
//! It reacts to hover (accept / reject highlight) and fires typed callbacks on
//! drop. Because an OS drag cannot be initiated from the keyboard, the zone
//! also offers a keyboard-operable **Browse…** button (opening the native file
//! dialog) as the WCAG 2.1.1 equivalent.
//!
//! ```ignore
//! DropZone::new(tr!("drop_images_here"))
//!     .subtitle(tr!("png_or_jpeg"))
//!     .accept_extensions(["png", "jpg", "jpeg"])
//!     .allow_multiple(true)
//!     .on_files_dropped(|paths, _ctx| { /* import paths */ });
//! ```
//!
//! External drops are delivered through the framework's normal drag pipeline
//! (`on_drag_hover` / `on_drag_leave` / `on_drop`) once
//! [`install_external_dnd`](https://docs.rs/teksilo-app) is wired and a backend
//! is available; on platforms with no backend (e.g. X11) the Browse button
//! keeps the zone fully usable.
//!
//! # Styling
//!
//! The bordered, tinted chrome is a Tier-3 [`DropZoneStyle`]; the default
//! [`RecipeDropZoneStyle`](crate::styles::RecipeDropZoneStyle) tracks the
//! interaction state. Override per-call with [`DropZone::style`] or theme-wide
//! via `theme.style_slots.drop_zone`.
//!
//! # Accessibility
//!
//! The zone is a `Role::Group` labelled by its prompt, with a `Live::Polite`
//! status line that announces hover ("Drop to add 3 files"), success
//! ("3 files added"), and rejection. AccessKit models no drag/drop action and
//! ARIA's `aria-grabbed` / `aria-dropeffect` are deprecated, so live-region
//! announcements plus the Browse fallback are the supported pattern.

use std::cell::RefCell;
use std::path::PathBuf;
use std::rc::Rc;
use teksilo_i18n::{lit, tr_widget};

use teksilo_canvas::{Rect, SizeProposal};
use teksilo_core::accessibility::AccessNodeBuilder;
use teksilo_core::accesskit::{Live, Role};
use teksilo_core::build_context::BuildContext;
use teksilo_core::styles::{
    DropZoneStyle, DropZoneStyleConfig, DropZoneVisualState, SharedDropZoneStyle,
};
use teksilo_core::widget::{EventContext, LayoutContext, LayoutResponse, Widget, WidgetPlacement};
use teksilo_core::widget_builder::{HandlerSet, WidgetBuilder};
use teksilo_core::widget_id::WidgetId;
use teksilo_core::{DragPayload, DropFeedback};
use teksilo_platform::file_dialog::{
    EventContextFileDialogExt, FileDialogRequest, FileDialogResult,
};
use teksilo_tokens::{HAlignment, TextRole};

use crate::button::Button;
use crate::primitives::{TextWidget, VStack};
use teksilo_i18n::LocalizedString;

type FilesCallback = Box<dyn FnMut(Vec<PathBuf>, &mut EventContext)>;
type TextCallback = Box<dyn FnMut(String, &mut EventContext)>;
type UrlsCallback = Box<dyn FnMut(Vec<String>, &mut EventContext)>;

/// A drop target for external (OS) drag-and-drop. See the module docs.
pub struct DropZone {
    label: LocalizedString,
    subtitle: Option<LocalizedString>,
    browse_label: LocalizedString,
    starting_dir: Option<PathBuf>,
    extensions: Vec<String>,
    allow_multiple: bool,
    show_browse_button: bool,
    icon: Option<Box<dyn Widget>>,
    on_files: Option<FilesCallback>,
    on_text: Option<TextCallback>,
    on_urls: Option<UrlsCallback>,
    style_override: Option<SharedDropZoneStyle>,
    root_child_id: Option<WidgetId>,
}

impl DropZone {
    /// Build a drop zone with the given prompt (e.g. `tr!("drop_files_here")`).
    /// The label may come from `tr!(...)` (translated) or
    /// `lit!(...)`; it is resolved eagerly at construction
    /// and stored as a `String`. Locale changes rebuild the composite parent,
    /// which re-creates the `DropZone` with a fresh translation — the same
    /// model as [`Button::new`](crate::button::Button::new).
    pub fn new(label: impl Into<LocalizedString>) -> Self {
        Self {
            label: label.into(),
            subtitle: None,
            browse_label: lit!("Browse…"),
            starting_dir: None,
            extensions: Vec::new(),
            allow_multiple: true,
            show_browse_button: true,
            icon: None,
            on_files: None,
            on_text: None,
            on_urls: None,
            style_override: None,
            root_child_id: None,
        }
    }

    /// Secondary line under the prompt (e.g. `tr!("png_or_jpeg")`).
    pub fn subtitle(mut self, text: impl Into<LocalizedString>) -> Self {
        self.subtitle = Some(text.into());
        self
    }

    /// Restrict accepted files to these extensions (without leading dots,
    /// case-insensitive). Empty (the default) accepts any file. Text and URL
    /// drops are unaffected.
    pub fn accept_extensions<I, S>(mut self, extensions: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        self.extensions = extensions
            .into_iter()
            .map(|e| e.into().trim_start_matches('.').to_ascii_lowercase())
            .collect();
        self
    }

    /// Whether more than one file may be dropped at once. Default `true`.
    /// When `false`, a multi-file drop is rejected.
    pub fn allow_multiple(mut self, allow: bool) -> Self {
        self.allow_multiple = allow;
        self
    }

    /// Show or hide the keyboard-operable Browse button. Default `true`.
    /// Keeping it visible is strongly recommended — it is the only
    /// keyboard-accessible path to the zone's action.
    pub fn show_browse_button(mut self, show: bool) -> Self {
        self.show_browse_button = show;
        self
    }

    /// Override the Browse button's label (e.g. `tr!("browse")`).
    /// Directory the Browse button's dialog opens in. If unset, the OS default is
    /// used.
    ///
    /// The same builder [`FilePickerField::starting_dir`](crate::file_picker_field::FilePickerField::starting_dir)
    /// offers, and for the same reason: an app that remembers where its writer last
    /// picked files has no way to say so otherwise, because this widget builds its own
    /// `FileDialogRequest` internally rather than taking one.
    #[must_use]
    pub fn starting_dir(mut self, path: impl Into<PathBuf>) -> Self {
        self.starting_dir = Some(path.into());
        self
    }

    pub fn browse_label(mut self, label: impl Into<LocalizedString>) -> Self {
        self.browse_label = label.into();
        self
    }

    /// An icon widget shown above the prompt (any widget — typically an
    /// [`IconWidget`](crate::primitives::IconWidget)).
    pub fn icon(mut self, icon: impl Widget + 'static) -> Self {
        self.icon = Some(Box::new(icon));
        self
    }

    /// Override the Tier-3 [`DropZoneStyle`] for this instance only.
    pub fn style(mut self, style: impl DropZoneStyle) -> Self {
        self.style_override = Some(Rc::new(style));
        self
    }

    /// Called with the dropped (or browsed) file paths. Files are only
    /// accepted when this is set.
    pub fn on_files_dropped(
        mut self,
        f: impl FnMut(Vec<PathBuf>, &mut EventContext) + 'static,
    ) -> Self {
        self.on_files = Some(Box::new(f));
        self
    }

    /// Called with dropped plain text. Text drops are only accepted when set.
    pub fn on_text_dropped(mut self, f: impl FnMut(String, &mut EventContext) + 'static) -> Self {
        self.on_text = Some(Box::new(f));
        self
    }

    /// Called with dropped non-file URLs. URL drops are only accepted when set.
    pub fn on_urls_dropped(
        mut self,
        f: impl FnMut(Vec<String>, &mut EventContext) + 'static,
    ) -> Self {
        self.on_urls = Some(Box::new(f));
        self
    }
}

impl std::fmt::Debug for DropZone {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("DropZone")
            .field("label", &self.label)
            .field("extensions", &self.extensions)
            .field("allow_multiple", &self.allow_multiple)
            .finish_non_exhaustive()
    }
}

/// Decide whether `payload` is acceptable given the zone's policy. Free
/// function so the drag closures don't need to borrow `self`.
fn payload_accepted(
    payload: &DragPayload,
    extensions: &[String],
    allow_multiple: bool,
    has_files_cb: bool,
    has_text_cb: bool,
    has_urls_cb: bool,
) -> bool {
    let files = payload.files();
    if !files.is_empty() {
        if !has_files_cb {
            return false;
        }
        if !allow_multiple && files.len() > 1 {
            return false;
        }
        if extensions.is_empty() {
            return true;
        }
        return files.iter().all(|p| {
            p.extension()
                .and_then(|e| e.to_str())
                .map(|e| extensions.iter().any(|x| x.eq_ignore_ascii_case(e)))
                .unwrap_or(false)
        });
    }
    if payload.text().is_some() {
        return has_text_cb;
    }
    if !payload.uris().is_empty() {
        return has_urls_cb;
    }
    // No concrete data yet — on Wayland the bytes only arrive at drop, so the
    // hover decision is made from the advertised formats. Optimistic: accept if
    // the zone handles a kind the source offers; the real extension check runs
    // at drop once `files()` is populated.
    if payload.is_external() {
        let formats = payload.formats();
        let offers = |needles: &[&str]| {
            formats
                .iter()
                .any(|f| needles.iter().any(|n| f == n || f.starts_with(n)))
        };
        if has_files_cb && offers(&["text/uri-list"]) {
            return true;
        }
        if has_text_cb && offers(&["text/plain", "UTF8_STRING", "STRING", "TEXT"]) {
            return true;
        }
        if has_urls_cb && offers(&["text/x-moz-url", "text/uri-list", "_NETSCAPE_URL"]) {
            return true;
        }
    }
    false
}

/// Localized live-region announcement for a drag hovering over the zone.
/// Singular vs plural is chosen here (in Rust) rather than via a Fluent
/// select expression so the `tr_widget!` compile-time English fallback
/// works for apps that don't register the framework bundle. Drop counts
/// are always >= 1, so the `== 1` / `> 1` split is correct for both
/// English and French.
fn hover_announcement(payload: &DragPayload) -> String {
    let files = payload.files().len();
    if files == 1 {
        return tr_widget!(drop_zone_hover_file_one()).resolve_now();
    }
    if files > 1 {
        return tr_widget!(drop_zone_hover_file_many(count = files as i64)).resolve_now();
    }
    if payload.text().is_some() {
        return tr_widget!(drop_zone_hover_text()).resolve_now();
    }
    let links = payload.uris().len();
    if links == 1 {
        return tr_widget!(drop_zone_hover_link_one()).resolve_now();
    }
    if links > 1 {
        return tr_widget!(drop_zone_hover_link_many(count = links as i64)).resolve_now();
    }
    // Wayland hover before the bytes arrive (formats-only) — generic prompt.
    tr_widget!(drop_zone_hover_generic()).resolve_now()
}

/// Localized live-region announcement for a completed drop.
fn added_announcement(payload: &DragPayload) -> String {
    let files = payload.files().len();
    if files >= 1 {
        return added_files_announcement(files);
    }
    if payload.text().is_some() {
        return tr_widget!(drop_zone_added_text()).resolve_now();
    }
    let links = payload.uris().len();
    if links == 1 {
        return tr_widget!(drop_zone_added_link_one()).resolve_now();
    }
    if links > 1 {
        return tr_widget!(drop_zone_added_link_many(count = links as i64)).resolve_now();
    }
    added_files_announcement(files)
}

/// Localized "N file(s) added" — shared by drop success and Browse success.
fn added_files_announcement(count: usize) -> String {
    if count == 1 {
        tr_widget!(drop_zone_added_file_one()).resolve_now()
    } else {
        tr_widget!(drop_zone_added_file_many(count = count as i64)).resolve_now()
    }
}

impl Widget for DropZone {
    fn build(&mut self, ctx: &mut BuildContext) -> Vec<WidgetId> {
        let state = ctx.signal(DropZoneVisualState::Idle);
        let announce = ctx.signal(String::new());

        // Snapshots for the closures.
        let extensions = self.extensions.clone();
        let allow_multiple = self.allow_multiple;
        let has_files_cb = self.on_files.is_some();
        let has_text_cb = self.on_text.is_some();
        let has_urls_cb = self.on_urls.is_some();

        let on_files = self.on_files.take().map(|f| Rc::new(RefCell::new(f)));
        let on_text = self.on_text.take().map(|f| Rc::new(RefCell::new(f)));
        let on_urls = self.on_urls.take().map(|f| Rc::new(RefCell::new(f)));

        // --- Content column: [icon?] prompt [subtitle?] [status] [Browse?] ---
        let mut content = VStack::new().spacing(8.0).alignment(HAlignment::Center);

        if let Some(icon) = self.icon.take() {
            let icon_id = ctx.add_boxed(icon);
            content = content.add_child(icon_id);
        }

        content = content.child(TextWidget::new(self.label.clone()));

        if let Some(subtitle) = &self.subtitle {
            content = content.child(TextWidget::new(subtitle.clone()).color(TextRole::Secondary));
        }

        // Live-region status line: empty at rest, narrates hover / drop.
        content = content.child(
            TextWidget::new(lit!(String::new()))
                .text(announce.clone())
                .color(TextRole::Secondary)
                .access_live(Live::Polite),
        );

        if self.show_browse_button {
            let browse_extensions = self.extensions.clone();
            let allow_multiple_browse = self.allow_multiple;
            let on_files_browse = on_files.clone();
            let announce_browse = announce.clone();
            let browse_starting_dir = self.starting_dir.clone();
            let browse = Button::new(self.browse_label.clone()).on_activate_fn(
                move |ctx: &mut EventContext| {
                    let mut request = FileDialogRequest::pick_file();
                    if let Some(dir) = &browse_starting_dir {
                        request = request.starting_dir(dir.clone());
                    }
                    if !browse_extensions.is_empty() {
                        let exts: Vec<&str> =
                            browse_extensions.iter().map(String::as_str).collect();
                        request = request.add_filter("Allowed", &exts);
                    }
                    let on_files_cb = on_files_browse.clone();
                    let announce_cb = announce_browse.clone();
                    let result_cb = move |result: FileDialogResult, ctx: &mut EventContext| {
                        let paths = match result {
                            FileDialogResult::File(Some(p)) => vec![p],
                            FileDialogResult::Files(v) => v,
                            _ => Vec::new(),
                        };
                        if paths.is_empty() {
                            return;
                        }
                        let count = paths.len();
                        if let Some(cb) = &on_files_cb {
                            (cb.borrow_mut())(paths, ctx);
                        }
                        announce_cb.set(added_files_announcement(count));
                    };
                    // Multi vs single picker per policy. Errors (no dialog
                    // installed) are ignored — the zone stays usable.
                    let _ = if allow_multiple_browse {
                        ctx.pick_files(request, result_cb)
                    } else {
                        ctx.pick_file(request, result_cb)
                    };
                },
            );
            content = content.child(browse);
        }

        let content_id = ctx.add(content);

        // --- Tier-3 chrome: resolve style (per-call > theme slot > default) ---
        let style = self
            .style_override
            .clone()
            .or_else(|| ctx.theme().style_slots.drop_zone.clone())
            .unwrap_or_else(|| Rc::new(crate::styles::RecipeDropZoneStyle::default()));
        let body = style.make_body(
            &DropZoneStyleConfig {
                state: state.clone(),
                content: content_id,
            },
            ctx,
        );

        // --- Drag behaviour on the composite node (the drop target) ---
        let hover_state = state.clone();
        let hover_announce = announce.clone();
        let hover_exts = extensions.clone();
        let leave_state = state.clone();
        let leave_announce = announce.clone();
        let drop_exts = extensions;

        let handlers = HandlerSet::new()
            .on_drag_hover(move |payload, _pos, _ctx| {
                let ok = payload_accepted(
                    payload,
                    &hover_exts,
                    allow_multiple,
                    has_files_cb,
                    has_text_cb,
                    has_urls_cb,
                );
                if ok {
                    hover_state.set(DropZoneVisualState::HoverAccept);
                    hover_announce.set(hover_announcement(payload));
                } else {
                    hover_state.set(DropZoneVisualState::HoverReject);
                    hover_announce.set(tr_widget!(drop_zone_hover_reject()).resolve_now());
                }
                // Visuals are state-driven; engage with `Accept` (no framework
                // feedback) when accepting so the drop lands here, else
                // `NoFeedback` so the drag bubbles past to the next drop target.
                if ok {
                    DropFeedback::Accept
                } else {
                    DropFeedback::NoFeedback
                }
            })
            .on_drag_leave(move |_ctx| {
                leave_state.set(DropZoneVisualState::Idle);
                leave_announce.set(String::new());
            })
            .on_drop(move |payload, _pos, ctx| {
                let ok = payload_accepted(
                    &payload,
                    &drop_exts,
                    allow_multiple,
                    has_files_cb,
                    has_text_cb,
                    has_urls_cb,
                );
                state.set(DropZoneVisualState::Idle);
                if !ok {
                    announce.set(tr_widget!(drop_zone_rejected()).resolve_now());
                    return false;
                }
                if !payload.files().is_empty() {
                    if let Some(cb) = &on_files {
                        (cb.borrow_mut())(payload.files().to_vec(), ctx);
                    }
                } else if let Some(text) = payload.text() {
                    if let Some(cb) = &on_text {
                        (cb.borrow_mut())(text.to_string(), ctx);
                    }
                } else if !payload.uris().is_empty() {
                    if let Some(cb) = &on_urls {
                        (cb.borrow_mut())(payload.uris().to_vec(), ctx);
                    }
                }
                announce.set(added_announcement(&payload));
                true
            });
        ctx.apply_self_handlers(handlers);

        self.root_child_id = Some(body);
        self.children()
    }

    fn layout_response(&self, proposal: SizeProposal, ctx: &LayoutContext) -> LayoutResponse {
        self.root_child_id
            .and_then(|id| ctx.child_size(id, proposal))
            .unwrap_or_else(|| proposal.resolve(0.0, 0.0))
            .into()
    }

    fn place_children(
        &self,
        bounds: Rect,
        _proposal: SizeProposal,
        children: &mut [WidgetPlacement],
        _ctx: &LayoutContext,
    ) {
        for child in children.iter_mut() {
            child.origin = bounds.origin();
            child.size = bounds.size();
        }
    }

    fn accessibility(&self, builder: &mut AccessNodeBuilder) {
        // The composite node is the drop target and the labelled group; the
        // Live status line lives inside the content column.
        builder.set_role(Role::Group);
        builder.set_name(self.label.clone());
    }

    fn children(&self) -> Vec<WidgetId> {
        self.root_child_id.into_iter().collect()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::cell::RefCell;
    use std::rc::Rc;
    use teksilo_canvas::Point;
    use teksilo_core::ExternalDropData;
    use teksilo_core::widget_tree::WidgetTree;

    fn tree() -> WidgetTree {
        WidgetTree::new().with_theme(teksilo_core::presets::intui::light())
    }

    /// The builder must survive to the widget: a starting directory that is accepted
    /// and then dropped would look identical to one that works, right up until a writer
    /// noticed the dialog still opening in their home folder.
    #[test]
    fn a_starting_directory_reaches_the_built_zone() {
        let zone = DropZone::new(lit!("Drop files here")).starting_dir("/tmp/somewhere");
        assert_eq!(
            zone.starting_dir.as_deref(),
            Some(std::path::Path::new("/tmp/somewhere"))
        );

        let mut tree = tree();
        let id = tree.add(zone);
        tree.layout(SizeProposal::exact(400.0, 300.0));
        let b = tree.bounds(id);
        assert!(
            b.width > 0.0 && b.height > 0.0,
            "a zone carrying a starting directory still builds"
        );
    }

    #[test]
    fn builds_with_nonzero_size() {
        let mut tree = tree();
        let id = tree.add(DropZone::new(lit!("Drop files here")));
        tree.layout(SizeProposal::exact(400.0, 300.0));
        let b = tree.bounds(id);
        assert!(b.width > 0.0 && b.height > 0.0);
    }

    #[test]
    fn matching_file_drop_fires_callback() {
        let mut tree = tree();
        let got: Rc<RefCell<Vec<PathBuf>>> = Rc::new(RefCell::new(Vec::new()));
        let g = got.clone();
        tree.add(
            DropZone::new(lit!("Images"))
                .accept_extensions(["png", "jpg"])
                .on_files_dropped(move |paths, _ctx| *g.borrow_mut() = paths),
        );
        tree.layout(SizeProposal::exact(400.0, 300.0));

        let mut noop = teksilo_core::NoopWindowOps;
        let data = ExternalDropData {
            files: vec![PathBuf::from("/tmp/photo.png")],
            ..Default::default()
        };
        let p = Point::new(200.0, 150.0);
        tree.begin_external_drag(p, data.clone(), &mut noop);
        tree.end_external_drag(p, data, &mut noop);

        assert_eq!(*got.borrow(), vec![PathBuf::from("/tmp/photo.png")]);
    }

    #[test]
    fn wrong_extension_is_rejected() {
        let mut tree = tree();
        let got: Rc<RefCell<Vec<PathBuf>>> = Rc::new(RefCell::new(Vec::new()));
        let g = got.clone();
        tree.add(
            DropZone::new(lit!("Images"))
                .accept_extensions(["png"])
                .on_files_dropped(move |paths, _ctx| *g.borrow_mut() = paths),
        );
        tree.layout(SizeProposal::exact(400.0, 300.0));

        let mut noop = teksilo_core::NoopWindowOps;
        let data = ExternalDropData {
            files: vec![PathBuf::from("/tmp/notes.txt")],
            ..Default::default()
        };
        let p = Point::new(200.0, 150.0);
        tree.begin_external_drag(p, data.clone(), &mut noop);
        tree.end_external_drag(p, data, &mut noop);

        assert!(got.borrow().is_empty(), "non-png drop must be rejected");
    }

    #[test]
    fn multi_file_rejected_when_single_only() {
        let mut tree = tree();
        let got: Rc<RefCell<Vec<PathBuf>>> = Rc::new(RefCell::new(Vec::new()));
        let g = got.clone();
        tree.add(
            DropZone::new(lit!("One file"))
                .allow_multiple(false)
                .on_files_dropped(move |paths, _ctx| *g.borrow_mut() = paths),
        );
        tree.layout(SizeProposal::exact(400.0, 300.0));

        let mut noop = teksilo_core::NoopWindowOps;
        let data = ExternalDropData {
            files: vec![PathBuf::from("/a"), PathBuf::from("/b")],
            ..Default::default()
        };
        let p = Point::new(200.0, 150.0);
        tree.begin_external_drag(p, data.clone(), &mut noop);
        tree.end_external_drag(p, data, &mut noop);

        assert!(got.borrow().is_empty(), "multi-file drop must be rejected");
    }

    #[test]
    fn text_drop_fires_when_handler_set() {
        let mut tree = tree();
        let got: Rc<RefCell<Option<String>>> = Rc::new(RefCell::new(None));
        let g = got.clone();
        tree.add(
            DropZone::new(lit!("Notes")).on_text_dropped(move |t, _ctx| *g.borrow_mut() = Some(t)),
        );
        tree.layout(SizeProposal::exact(400.0, 300.0));

        let mut noop = teksilo_core::NoopWindowOps;
        let data = ExternalDropData {
            text: Some("hello".to_string()),
            ..Default::default()
        };
        let p = Point::new(200.0, 150.0);
        tree.begin_external_drag(p, data.clone(), &mut noop);
        tree.end_external_drag(p, data, &mut noop);

        assert_eq!(got.borrow().as_deref(), Some("hello"));
    }

    // --- Hover-time acceptance from advertised formats (Wayland) -------
    // On Wayland the dropped bytes only arrive at drop, so hover accept/reject
    // is decided from the advertised MIME formats alone.

    #[test]
    fn formats_only_hover_accepts_matching_kind() {
        // A file drag advertises text/uri-list (+ text/plain for the path).
        let file_drag = DragPayload::external(ExternalDropData {
            formats: vec!["text/uri-list".into(), "text/plain".into()],
            ..Default::default()
        });
        // Image-style zone: files handler, png filter — accept on hover even
        // though the extension can't be checked until drop.
        assert!(payload_accepted(
            &file_drag,
            &["png".into()],
            true,
            true,
            false,
            false
        ));

        // A pure text drag (no uri-list) onto a files-only zone → reject.
        let text_drag = DragPayload::external(ExternalDropData {
            formats: vec!["text/plain".into()],
            ..Default::default()
        });
        assert!(!payload_accepted(&text_drag, &[], true, true, false, false));
        // …but a text-handling zone accepts it.
        assert!(payload_accepted(&text_drag, &[], true, false, true, false));
    }

    #[test]
    fn formats_only_internal_drag_is_not_accepted() {
        // A non-external payload with no concrete data must not be accepted via
        // the formats path.
        let internal = DragPayload::typed(7_u32);
        assert!(!payload_accepted(&internal, &[], true, true, true, true));
    }
}