Skip to main content

day_pieces/
dialogs.rs

1// Copyright © The Daybrite Project
2// SPDX-License-Identifier: MPL-2.0
3
4//! Imperative, awaitable presentations: the `alert` / `confirm` / `prompt` dialogs and the
5//! `open_file` / `open_files` / `open_folder` / `save_file` system file pickers (`FileUrl`).
6//! Each returns a future you await for the user's choice.
7
8use std::hash::Hash;
9
10use crate::*;
11
12// ---------------------------------------------------------------------------
13// Imperative presentation (docs/dialogs.md)
14// ---------------------------------------------------------------------------
15
16use std::future::{Future, IntoFuture};
17use std::pin::Pin;
18
19use day_spec::present::{ButtonRole, PresentButton, PresentResult, PresentSpec};
20
21/// Boxed future the awaitable presenters resolve to: one alloc per dialog, negligible.
22type Presenting<T> = Pin<Box<dyn Future<Output = T>>>;
23
24/// A dialog / confirmation / action sheet. Buttons carry a typed payload `T`; `.present()`
25/// awaits and returns the chosen button's payload, or `None` on cancel/dismiss.
26///
27/// ```ignore
28/// let choice = Alert::new(tr("delete-title"))
29///     .message(tr("delete-body"))
30///     .destructive(tr("delete"), Choice::Delete)
31///     .cancel(tr("cancel"))
32///     .present().await;   // Option<Choice>
33/// ```
34pub struct Alert<T> {
35    title: String,
36    message: Option<String>,
37    sheet: bool,
38    /// (label, role, payload) in presentation order; cancel buttons carry `None`.
39    buttons: Vec<(String, ButtonRole, Option<T>)>,
40}
41
42pub fn alert<M>(title: impl IntoText<M>) -> Alert<()> {
43    Alert {
44        title: title.into_text().initial(),
45        message: None,
46        sheet: false,
47        buttons: Vec::new(),
48    }
49}
50
51impl<T> Alert<T> {
52    pub fn new<M>(title: impl IntoText<M>) -> Alert<T> {
53        Alert {
54            title: title.into_text().initial(),
55            message: None,
56            sheet: false,
57            buttons: Vec::new(),
58        }
59    }
60    pub fn message<M>(mut self, m: impl IntoText<M>) -> Self {
61        self.message = Some(m.into_text().initial());
62        self
63    }
64    /// Present as a bottom action sheet on mobile (desktop falls back to an alert).
65    pub fn sheet(mut self) -> Self {
66        self.sheet = true;
67        self
68    }
69    /// A normal choice carrying `value`.
70    pub fn button<M>(mut self, label: impl IntoText<M>, value: T) -> Self {
71        self.buttons.push((
72            label.into_text().initial(),
73            ButtonRole::Default,
74            Some(value),
75        ));
76        self
77    }
78    /// A destructive choice (red on Apple) carrying `value`.
79    pub fn destructive<M>(mut self, label: impl IntoText<M>, value: T) -> Self {
80        self.buttons.push((
81            label.into_text().initial(),
82            ButtonRole::Destructive,
83            Some(value),
84        ));
85        self
86    }
87    /// The cancel affordance; choosing it (or dismissing) resolves to `None`.
88    pub fn cancel<M>(mut self, label: impl IntoText<M>) -> Self {
89        self.buttons
90            .push((label.into_text().initial(), ButtonRole::Cancel, None));
91        self
92    }
93
94    /// Present natively and await the chosen payload (`None` = cancel / dismissed).
95    pub async fn present(self) -> Option<T> {
96        let spec = PresentSpec::Dialog {
97            title: self.title,
98            message: self.message,
99            buttons: self
100                .buttons
101                .iter()
102                .map(|(label, role, _)| PresentButton {
103                    label: label.clone(),
104                    role: *role,
105                })
106                .collect(),
107            sheet: self.sheet,
108        };
109        let mut payloads: Vec<Option<T>> = self.buttons.into_iter().map(|(_, _, v)| v).collect();
110        match day_core::present(spec).await {
111            PresentResult::Button(i) => {
112                let i = i as usize;
113                if i < payloads.len() {
114                    payloads[i].take()
115                } else {
116                    None
117                }
118            }
119            _ => None,
120        }
121    }
122}
123
124impl<T: 'static> IntoFuture for Alert<T> {
125    type Output = Option<T>;
126    type IntoFuture = Presenting<Option<T>>;
127    fn into_future(self) -> Self::IntoFuture {
128        Box::pin(self.present())
129    }
130}
131
132/// A yes/no confirmation. Resolves to `true` only if the confirm button is chosen.
133pub struct Confirm {
134    title: String,
135    message: Option<String>,
136    confirm: String,
137    cancel: String,
138    destructive: bool,
139}
140
141pub fn confirm<M>(title: impl IntoText<M>) -> Confirm {
142    Confirm {
143        title: title.into_text().initial(),
144        message: None,
145        // Localized from the core catalog (docs/dialogs.md); `.confirm_label`/`.cancel_label`
146        // override. Resolved in the current locale at build time.
147        confirm: day_localization::t(day_localization::key::day_ok),
148        cancel: day_localization::t(day_localization::key::day_cancel),
149        destructive: false,
150    }
151}
152
153impl Confirm {
154    pub fn message<M>(mut self, m: impl IntoText<M>) -> Self {
155        self.message = Some(m.into_text().initial());
156        self
157    }
158    pub fn confirm_label<M>(mut self, label: impl IntoText<M>) -> Self {
159        self.confirm = label.into_text().initial();
160        self
161    }
162    pub fn cancel_label<M>(mut self, label: impl IntoText<M>) -> Self {
163        self.cancel = label.into_text().initial();
164        self
165    }
166    /// Style the confirm button as destructive.
167    pub fn destructive(mut self) -> Self {
168        self.destructive = true;
169        self
170    }
171    pub async fn present(self) -> bool {
172        let confirm_role = if self.destructive {
173            ButtonRole::Destructive
174        } else {
175            ButtonRole::Default
176        };
177        let spec = PresentSpec::Dialog {
178            title: self.title,
179            message: self.message,
180            buttons: vec![
181                PresentButton {
182                    label: self.cancel,
183                    role: ButtonRole::Cancel,
184                },
185                PresentButton {
186                    label: self.confirm,
187                    role: confirm_role,
188                },
189            ],
190            sheet: false,
191        };
192        // index 1 = the confirm button.
193        matches!(day_core::present(spec).await, PresentResult::Button(1))
194    }
195}
196
197impl IntoFuture for Confirm {
198    type Output = bool;
199    type IntoFuture = Presenting<bool>;
200    fn into_future(self) -> Self::IntoFuture {
201        Box::pin(self.present())
202    }
203}
204
205/// A single-line text prompt. Resolves to `Some(text)` on OK, `None` on cancel/dismiss.
206pub struct Prompt {
207    title: String,
208    message: Option<String>,
209    placeholder: String,
210    initial: String,
211    ok: String,
212    cancel: String,
213}
214
215pub fn prompt<M>(title: impl IntoText<M>) -> Prompt {
216    Prompt {
217        title: title.into_text().initial(),
218        message: None,
219        placeholder: String::new(),
220        initial: String::new(),
221        // Localized from the core catalog (docs/dialogs.md); `.ok_label`/`.cancel_label` override.
222        ok: day_localization::t(day_localization::key::day_ok),
223        cancel: day_localization::t(day_localization::key::day_cancel),
224    }
225}
226
227impl Prompt {
228    pub fn message<M>(mut self, m: impl IntoText<M>) -> Self {
229        self.message = Some(m.into_text().initial());
230        self
231    }
232    pub fn placeholder<M>(mut self, p: impl IntoText<M>) -> Self {
233        self.placeholder = p.into_text().initial();
234        self
235    }
236    pub fn initial<M>(mut self, v: impl IntoText<M>) -> Self {
237        self.initial = v.into_text().initial();
238        self
239    }
240    pub fn ok_label<M>(mut self, label: impl IntoText<M>) -> Self {
241        self.ok = label.into_text().initial();
242        self
243    }
244    pub fn cancel_label<M>(mut self, label: impl IntoText<M>) -> Self {
245        self.cancel = label.into_text().initial();
246        self
247    }
248    pub async fn present(self) -> Option<String> {
249        let spec = PresentSpec::Prompt {
250            title: self.title,
251            message: self.message,
252            placeholder: self.placeholder,
253            initial: self.initial,
254            ok: self.ok,
255            cancel: self.cancel,
256        };
257        match day_core::present(spec).await {
258            PresentResult::Text(t) => Some(t),
259            _ => None,
260        }
261    }
262}
263
264impl IntoFuture for Prompt {
265    type Output = Option<String>;
266    type IntoFuture = Presenting<Option<String>>;
267    fn into_future(self) -> Self::IntoFuture {
268        Box::pin(self.present())
269    }
270}
271
272// ---------------------------------------------------------------------------
273// File open / save (docs/files.md)
274// ---------------------------------------------------------------------------
275
276use day_spec::present::FileFilter;
277
278/// A cross-platform handle to a file the user chose in a native open/save picker.
279///
280/// Internally a single **locator string**. On desktop and iOS it is an absolute filesystem
281/// path; on Android it may be a `content://` URI, since the Storage Access Framework does not
282/// expose real filesystem paths. That is why Day uses a bespoke type rather than
283/// [`std::path::PathBuf`] (which cannot represent a `content://` URI) or a bare `String` (no
284/// type-safety / helpers): a `FileUrl` is the lossless union with ergonomic accessors.
285///
286/// Files returned from [`open_file`] are always readable via [`FileUrl::read_to_string`] /
287/// [`FileUrl::read`]: backends copy a picked file into app storage first where the platform
288/// requires it, so the local path works everywhere.
289#[derive(Clone, Debug, PartialEq, Eq, Hash)]
290pub struct FileUrl(String);
291
292impl FileUrl {
293    /// Wrap a locator string (a filesystem path or a URI). Usually produced by the pickers.
294    pub fn new(locator: impl Into<String>) -> Self {
295        FileUrl(locator.into())
296    }
297    /// The raw locator: a filesystem path, or a `content://`-style URI on Android.
298    pub fn as_str(&self) -> &str {
299        &self.0
300    }
301    /// The locator as a filesystem path: `Some` for local paths (and `file://` URLs), `None`
302    /// for opaque URIs such as Android's `content://`.
303    pub fn local_path(&self) -> Option<std::path::PathBuf> {
304        if self.0.starts_with("file://") {
305            return day_spec::transfer::file_paths(self.0.as_bytes())?
306                .into_iter()
307                .next();
308        }
309        if self.0.contains("://") {
310            return None;
311        }
312        Some(std::path::PathBuf::from(&self.0))
313    }
314    /// Persistable macOS security-scoped bookmark for a file the user has authorized.
315    /// Store the opaque bytes in app-private storage, not the path. Other platforms return
316    /// `Unsupported`. `read_only` prevents a bookmark from requesting write access.
317    pub fn bookmark(&self, read_only: bool) -> std::io::Result<Vec<u8>> {
318        crate::file_access::bookmark(self, read_only)
319    }
320    /// Resolve a saved macOS bookmark and hold its security scope until the returned guard
321    /// is dropped. Keep the guard alive across all I/O, including asynchronous operations.
322    pub fn resolve_bookmark(bytes: &[u8]) -> std::io::Result<crate::FileAccess> {
323        crate::file_access::resolve(bytes)
324    }
325    /// The last path component, for display (e.g. `notes.txt`). Best-effort for opaque URIs.
326    pub fn file_name(&self) -> Option<String> {
327        let s = self.0.trim_end_matches(['/', '\\']);
328        let tail = s.rsplit(['/', '\\']).next().unwrap_or(s);
329        if tail.is_empty() {
330            None
331        } else {
332            Some(tail.to_string())
333        }
334    }
335    /// Read the file's bytes. Local paths only; opaque URIs return an `Unsupported` error.
336    pub fn read(&self) -> std::io::Result<Vec<u8>> {
337        match self.local_path() {
338            Some(p) => fs_read(&p),
339            None => Err(std::io::Error::new(
340                std::io::ErrorKind::Unsupported,
341                "content:// URIs are not directly readable",
342            )),
343        }
344    }
345    /// Read at most `limit` bytes without blocking the UI. Native reads run on a worker;
346    /// browser-picked bytes are already in memory. Oversized input returns `InvalidData`.
347    /// Apple security-scoped access is held for the read and released on every exit path.
348    pub async fn read_limited(&self, limit: usize) -> std::io::Result<Vec<u8>> {
349        #[cfg(target_arch = "wasm32")]
350        {
351            let bytes = self.read()?;
352            if bytes.len() > limit {
353                return Err(std::io::ErrorKind::InvalidData.into());
354            }
355            Ok(bytes)
356        }
357        #[cfg(not(target_arch = "wasm32"))]
358        {
359            // A job on the blocking pool (docs/async.md): a panicking or never-run job is an
360            // I/O error here, like a worker that failed to start was.
361            let file = self.clone();
362            match day_core::spawn_blocking(move || file.read_bounded(limit)).await {
363                Ok(result) => result,
364                Err(e) => Err(std::io::Error::other(e)),
365            }
366        }
367    }
368    #[cfg(not(target_arch = "wasm32"))]
369    fn read_bounded(&self, limit: usize) -> std::io::Result<Vec<u8>> {
370        use std::io::Read;
371        let path = self.local_path().ok_or(std::io::ErrorKind::Unsupported)?;
372        #[cfg(any(target_os = "macos", target_os = "ios"))]
373        let _access = crate::file_access::scoped_read(&path)?;
374        let file = std::fs::File::open(path)?;
375        if file.metadata()?.len() > limit as u64 {
376            return Err(std::io::ErrorKind::InvalidData.into());
377        }
378        let mut bytes = Vec::new();
379        file.take((limit as u64).saturating_add(1))
380            .read_to_end(&mut bytes)?;
381        if bytes.len() > limit {
382            return Err(std::io::ErrorKind::InvalidData.into());
383        }
384        Ok(bytes)
385    }
386    /// Read the file as UTF-8 text.
387    pub fn read_to_string(&self) -> std::io::Result<String> {
388        match self.local_path() {
389            Some(p) => fs_read(&p).and_then(|b| {
390                String::from_utf8(b).map_err(|_| std::io::ErrorKind::InvalidData.into())
391            }),
392            None => Err(std::io::Error::new(
393                std::io::ErrorKind::Unsupported,
394                "content:// URIs are not directly readable",
395            )),
396        }
397    }
398}
399
400impl std::fmt::Display for FileUrl {
401    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
402        f.write_str(&self.0)
403    }
404}
405
406fn parse_filter(name: impl Into<String>, extensions: &[&str]) -> FileFilter {
407    FileFilter {
408        name: name.into(),
409        extensions: extensions
410            .iter()
411            .map(|e| e.trim_start_matches('.').to_string())
412            .collect(),
413    }
414}
415
416/// A native "open file" picker. `.await` (or `.present().await`) resolves to the chosen
417/// [`FileUrl`], or `None` if the user cancels.
418///
419/// ```ignore
420/// let file = open_file().filter("Text", &["txt", "md"]).await;
421/// if let Some(f) = file { let body = f.read_to_string()?; }
422/// ```
423pub struct OpenFile {
424    title: String,
425    filters: Vec<FileFilter>,
426}
427
428/// Start a native open-file picker (docs/files.md).
429pub fn open_file() -> OpenFile {
430    OpenFile {
431        title: day_localization::t(day_localization::key::day_open),
432        filters: Vec::new(),
433    }
434}
435
436impl OpenFile {
437    /// Override the picker's title (localizable via `tr()`).
438    pub fn title<M>(mut self, t: impl IntoText<M>) -> Self {
439        self.title = t.into_text().initial();
440        self
441    }
442    /// Add a named file-type filter, e.g. `.filter("Text", &["txt", "md"])`. No filter = all files.
443    pub fn filter(mut self, name: impl Into<String>, extensions: &[&str]) -> Self {
444        self.filters.push(parse_filter(name, extensions));
445        self
446    }
447    pub async fn present(self) -> Option<FileUrl> {
448        let spec = PresentSpec::OpenFile {
449            title: self.title,
450            filters: self.filters,
451            multiple: false,
452        };
453        match day_core::present(spec).await {
454            PresentResult::Files(mut v) if !v.is_empty() => Some(FileUrl(v.remove(0))),
455            _ => None,
456        }
457    }
458}
459
460impl IntoFuture for OpenFile {
461    type Output = Option<FileUrl>;
462    type IntoFuture = Presenting<Option<FileUrl>>;
463    fn into_future(self) -> Self::IntoFuture {
464        Box::pin(self.present())
465    }
466}
467
468/// A native "open files" picker that lets the user choose several files at once. `.await`
469/// (or `.present().await`) resolves to the chosen [`FileUrl`]s in the picker's order, or an
470/// empty `Vec` if the user cancels.
471///
472/// ```ignore
473/// let tracks = open_files().filter("Audio", &["mp3", "flac"]).await;
474/// for track in &tracks { library.add(track.read()?); }
475/// ```
476pub struct OpenFiles {
477    title: String,
478    filters: Vec<FileFilter>,
479}
480
481/// Start a native multi-file open picker (docs/files.md).
482pub fn open_files() -> OpenFiles {
483    OpenFiles {
484        title: day_localization::t(day_localization::key::day_open),
485        filters: Vec::new(),
486    }
487}
488
489impl OpenFiles {
490    /// Override the picker's title (localizable via `tr()`).
491    pub fn title<M>(mut self, t: impl IntoText<M>) -> Self {
492        self.title = t.into_text().initial();
493        self
494    }
495    /// Add a named file-type filter, e.g. `.filter("Audio", &["mp3", "flac"])`. No filter = all files.
496    pub fn filter(mut self, name: impl Into<String>, extensions: &[&str]) -> Self {
497        self.filters.push(parse_filter(name, extensions));
498        self
499    }
500    pub async fn present(self) -> Vec<FileUrl> {
501        let spec = PresentSpec::OpenFile {
502            title: self.title,
503            filters: self.filters,
504            multiple: true,
505        };
506        match day_core::present(spec).await {
507            PresentResult::Files(v) => v.into_iter().map(FileUrl).collect(),
508            _ => Vec::new(),
509        }
510    }
511}
512
513impl IntoFuture for OpenFiles {
514    type Output = Vec<FileUrl>;
515    type IntoFuture = Presenting<Vec<FileUrl>>;
516    fn into_future(self) -> Self::IntoFuture {
517        Box::pin(self.present())
518    }
519}
520
521/// A native "choose folder" picker. `.await` (or `.present().await`) resolves to the chosen
522/// directory as a [`FileUrl`], or `None` if the user cancels — and `None` at once on a toolkit
523/// without a folder chooser, so ask [`Cap::FolderDialog`](day_spec::Cap::FolderDialog) before
524/// offering the command (phones answer `Unsupported`).
525///
526/// ```ignore
527/// if let Some(dir) = open_folder().title(res::str::add_folder()).await {
528///     scan(dir.local_path()?);
529/// }
530/// ```
531pub struct OpenFolder {
532    title: String,
533}
534
535/// Start a native folder chooser (docs/files.md).
536pub fn open_folder() -> OpenFolder {
537    OpenFolder {
538        title: day_localization::t(day_localization::key::day_open_folder),
539    }
540}
541
542impl OpenFolder {
543    /// Override the picker's title (localizable via `tr()`).
544    pub fn title<M>(mut self, t: impl IntoText<M>) -> Self {
545        self.title = t.into_text().initial();
546        self
547    }
548    pub async fn present(self) -> Option<FileUrl> {
549        let spec = PresentSpec::OpenFolder { title: self.title };
550        match day_core::present(spec).await {
551            PresentResult::Files(mut v) if !v.is_empty() => Some(FileUrl(v.remove(0))),
552            _ => None,
553        }
554    }
555}
556
557impl IntoFuture for OpenFolder {
558    type Output = Option<FileUrl>;
559    type IntoFuture = Presenting<Option<FileUrl>>;
560    fn into_future(self) -> Self::IntoFuture {
561        Box::pin(self.present())
562    }
563}
564
565/// A native "save file" picker carrying the bytes to write. `.await` resolves to the chosen
566/// destination [`FileUrl`], or `None` on cancel.
567///
568/// ```ignore
569/// let saved = save_file(text.into_bytes())
570///     .suggested_name("notes.txt")
571///     .filter("Text", &["txt"])
572///     .await;
573/// ```
574pub struct SaveFile {
575    title: String,
576    suggested_name: String,
577    filters: Vec<FileFilter>,
578    data: Vec<u8>,
579}
580
581/// Start a native save-file picker for `data` (docs/files.md).
582pub fn save_file(data: impl Into<Vec<u8>>) -> SaveFile {
583    SaveFile {
584        title: day_localization::t(day_localization::key::day_save),
585        suggested_name: "untitled.txt".to_string(),
586        filters: Vec::new(),
587        data: data.into(),
588    }
589}
590
591impl SaveFile {
592    /// Override the picker's title (localizable via `tr()`).
593    pub fn title<M>(mut self, t: impl IntoText<M>) -> Self {
594        self.title = t.into_text().initial();
595        self
596    }
597    /// The default file name shown in the picker.
598    pub fn suggested_name(mut self, name: impl Into<String>) -> Self {
599        self.suggested_name = name.into();
600        self
601    }
602    /// Add a named file-type filter, e.g. `.filter("Text", &["txt"])`.
603    pub fn filter(mut self, name: impl Into<String>, extensions: &[&str]) -> Self {
604        self.filters.push(parse_filter(name, extensions));
605        self
606    }
607    pub async fn present(self) -> Option<FileUrl> {
608        // Stage the bytes in an app-writable temp file the backend hands to the native picker.
609        let mut src = day_core::app_temp_dir();
610        src.push(format!(
611            "day-save-{}-{}",
612            stage_tag(),
613            sanitize_name(&self.suggested_name)
614        ));
615        if !fs_write(&src, &self.data) {
616            return None;
617        }
618        let spec = PresentSpec::SaveFile {
619            title: self.title,
620            suggested_name: self.suggested_name,
621            src_path: src.to_string_lossy().into_owned(),
622            filters: self.filters,
623        };
624        let dest = match day_core::present(spec).await {
625            PresentResult::Files(mut v) if !v.is_empty() => FileUrl(v.remove(0)),
626            _ => {
627                fs_remove(&src);
628                return None;
629            }
630        };
631        // Best-effort deliver the bytes to a local destination (desktop, and headless dayscript).
632        // On Android the destination is a `content://` URI the backend already wrote (no
633        // `local_path`, so the copy is skipped); iOS delivers via the document exporter.
634        if let Some(p) = dest.local_path()
635            && p != src
636        {
637            fs_copy(&src, &p);
638        }
639        fs_remove(&src);
640        Some(dest)
641    }
642}
643
644impl IntoFuture for SaveFile {
645    type Output = Option<FileUrl>;
646    type IntoFuture = Presenting<Option<FileUrl>>;
647    fn into_future(self) -> Self::IntoFuture {
648        Box::pin(self.present())
649    }
650}
651
652// The file flows' filesystem, behind four verbs: a browser has no `std::fs`, so the wasm arms
653// go through day-spec's `web_files` byte store instead (day-toolkit-dom's picker fills it and the
654// shim's download drains it), while every other platform reads and writes files on disk.
655#[cfg(not(all(target_family = "wasm", target_os = "unknown")))]
656mod files {
657    use std::path::Path;
658    pub(super) fn fs_read(p: &Path) -> std::io::Result<Vec<u8>> {
659        std::fs::read(p)
660    }
661    pub(super) fn fs_write(p: &Path, bytes: &[u8]) -> bool {
662        std::fs::write(p, bytes).is_ok()
663    }
664    pub(super) fn fs_copy(src: &Path, dest: &Path) {
665        let _ = std::fs::copy(src, dest);
666    }
667    pub(super) fn fs_remove(p: &Path) {
668        let _ = std::fs::remove_file(p);
669    }
670    pub(super) fn stage_tag() -> u32 {
671        std::process::id()
672    }
673}
674#[cfg(all(target_family = "wasm", target_os = "unknown"))]
675mod files {
676    use day_spec::present::web_files;
677    use std::path::Path;
678    pub(super) fn fs_read(p: &Path) -> std::io::Result<Vec<u8>> {
679        web_files::read(&p.to_string_lossy())
680            .ok_or_else(|| std::io::Error::new(std::io::ErrorKind::NotFound, "no such web file"))
681    }
682    pub(super) fn fs_write(p: &Path, bytes: &[u8]) -> bool {
683        web_files::write(&p.to_string_lossy(), bytes.to_vec());
684        true
685    }
686    pub(super) fn fs_copy(src: &Path, dest: &Path) {
687        if let Some(b) = web_files::read(&src.to_string_lossy()) {
688            web_files::write(&dest.to_string_lossy(), b);
689        }
690    }
691    pub(super) fn fs_remove(p: &Path) {
692        web_files::remove(&p.to_string_lossy());
693    }
694    /// `std::process::id()` aborts on wasm; one page is one "process".
695    pub(super) fn stage_tag() -> u32 {
696        0
697    }
698}
699use files::{fs_copy, fs_read, fs_remove, fs_write, stage_tag};
700
701/// Keep a suggested file name safe as a temp-file component (path-separator / control-char free).
702fn sanitize_name(name: &str) -> String {
703    let s: String = name
704        .chars()
705        .map(|c| {
706            if c.is_alphanumeric() || matches!(c, '.' | '-' | '_') {
707                c
708            } else {
709                '_'
710            }
711        })
712        .collect();
713    if s.is_empty() {
714        "untitled".to_string()
715    } else {
716        s
717    }
718}
719
720#[cfg(all(test, not(target_arch = "wasm32")))]
721mod document_read_tests {
722    use super::*;
723    #[test]
724    fn bounded_read_accepts_exact_limit_rejects_oversize_and_opaque_uris() {
725        let path = std::env::temp_dir().join(format!("day-document-test-{}", std::process::id()));
726        std::fs::write(&path, b"12345").unwrap();
727        let file = FileUrl::new(path.to_str().unwrap());
728        assert_eq!(file.read_bounded(5).unwrap(), b"12345");
729        assert_eq!(
730            file.read_bounded(4).unwrap_err().kind(),
731            std::io::ErrorKind::InvalidData
732        );
733        assert_eq!(
734            FileUrl::new("content://fixture/test")
735                .read_bounded(5)
736                .unwrap_err()
737                .kind(),
738            std::io::ErrorKind::Unsupported
739        );
740        std::fs::remove_file(path).unwrap();
741    }
742}
743
744#[cfg(feature = "conformance")]
745pub(crate) mod conformance {
746    use day_core::conformance::{Case, Drive};
747    use day_reactive::Signal;
748    use day_spec::Cap;
749
750    use crate::*;
751
752    /// A page whose button asks `confirm` and shows the answer.
753    fn asker() -> impl day_core::Piece {
754        let answer = Signal::new(String::from("none"));
755        column((
756            label(move || format!("answer {}", answer.get())).id(day_core::id!(answer)),
757            button("Ask")
758                .action(move || {
759                    let set = answer.setter();
760                    day_core::task(async move {
761                        let yes = confirm("Delete it?").present().await;
762                        set.set(if yes { "yes" } else { "no" }.into());
763                    });
764                })
765                .id(day_core::id!(ask)),
766            // A focus target without an IME: opening the keyboard here would change the
767            // viewport inherited by the next test on mobile toolkits.
768            rectangle()
769                .frame(40.0, 40.0)
770                .focusable()
771                .id(day_core::id!(after_dialog)),
772        ))
773    }
774
775    /// A native confirmation presents with its title, and the button chosen comes back; the
776    /// toolkit dismisses the dialog it showed.
777    #[day_macros::test(day_core)]
778    fn confirm_native_answer() -> Case {
779        Case::new()
780            .proves_cap(Cap::Dialogs)
781            .proves_duty("present")
782            .proves_duty("dismiss")
783            .requires(Cap::Dialogs)
784            .page(asker)
785            .drive(|d: Drive| async move {
786                d.dialogs_scripted(false).await?;
787                d.tap("ask").await?;
788                d.assert_presented(Some("Delete it?")).await?;
789                d.respond(Some(1)).await?;
790                d.assert_text("answer", "answer yes").await?;
791                // A completed modal must release native focus to the underlying page,
792                // including when a scripted answer arrives before its first frame.
793                d.focus("after_dialog").await?;
794                d.assert_focused("after_dialog", true).await
795            })
796    }
797
798    /// Dismissing a native confirmation answers it as cancelled.
799    #[day_macros::test(day_core)]
800    fn confirm_native_dismiss() -> Case {
801        Case::new()
802            .proves_cap(Cap::Dialogs)
803            .requires(Cap::Dialogs)
804            .page(asker)
805            .drive(|d: Drive| async move {
806                d.dialogs_scripted(false).await?;
807                d.tap("ask").await?;
808                d.assert_presented(None).await?;
809                d.respond(None).await?;
810                d.assert_text("answer", "answer no").await?;
811                d.focus("after_dialog").await?;
812                d.assert_focused("after_dialog", true).await
813            })
814    }
815
816    fn prompt_asker() -> impl day_core::Piece {
817        let answer = Signal::new(String::from("pending"));
818        column((
819            label(move || answer.get()).id(day_core::id!(answer)),
820            button("Ask").id(day_core::id!(ask)).action(move || {
821                let set = answer.setter();
822                day_core::task(async move {
823                    let value = prompt("Your name")
824                        .message("Enter a name")
825                        .placeholder("Name")
826                        .initial("Ada")
827                        .present()
828                        .await;
829                    set.set(format!("{value:?}"));
830                });
831            }),
832        ))
833    }
834
835    #[day_macros::test(day_core)]
836    fn prompt_native_answer() -> Case {
837        Case::new()
838            .requires(Cap::Dialogs)
839            .proves_cap(Cap::Dialogs)
840            .proves_duty("present")
841            .proves_duty("dismiss")
842            .page(prompt_asker)
843            .drive(|d: Drive| async move {
844                d.dialogs_scripted(false).await?;
845                d.tap("ask").await?;
846                d.assert_presented(Some("Your name")).await?;
847                d.respond_text("Zoë 東京\n\"quoted\"").await?;
848                d.assert_text("answer", "Some(\"Zoë 東京\\n\\\"quoted\\\"\")")
849                    .await?;
850                d.tap("ask").await?;
851                d.respond_text("").await?;
852                d.assert_text("answer", "Some(\"\")").await
853            })
854    }
855
856    #[day_macros::test(day_core)]
857    fn prompt_native_dismiss() -> Case {
858        Case::new()
859            .requires(Cap::Dialogs)
860            .proves_cap(Cap::Dialogs)
861            .page(prompt_asker)
862            .drive(|d: Drive| async move {
863                d.dialogs_scripted(false).await?;
864                d.tap("ask").await?;
865                d.assert_presented(Some("Your name")).await?;
866                d.respond(None).await?;
867                d.assert_text("answer", "None").await
868            })
869    }
870
871    #[day_macros::test(day_core)]
872    fn alert_sheet_preserves_button_indices() -> Case {
873        Case::new()
874            .requires(Cap::Dialogs)
875            .proves_cap(Cap::Dialogs)
876            .page(|| {
877                let answer = Signal::new(String::from("pending"));
878                column((
879                    label(move || answer.get()).id(day_core::id!(answer)),
880                    button("Ask").id(day_core::id!(ask)).action(move || {
881                        let set = answer.setter();
882                        day_core::task(async move {
883                            let value = Alert::new("Choose an action")
884                                .sheet()
885                                .button("First", 10)
886                                .cancel("Cancel")
887                                .destructive("Delete", 30)
888                                .button("Last", 40)
889                                .present()
890                                .await;
891                            set.set(format!("{value:?}"));
892                        });
893                    }),
894                ))
895            })
896            .drive(|d: Drive| async move {
897                d.dialogs_scripted(false).await?;
898                d.tap("ask").await?;
899                d.assert_presented(Some("Choose an action")).await?;
900                d.respond(Some(2)).await?;
901                d.assert_text("answer", "Some(30)").await?;
902                d.tap("ask").await?;
903                d.respond(Some(1)).await?;
904                d.assert_text("answer", "None").await
905            })
906    }
907}