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