diff --git a/crates/font-manager/src/panel/specimen.rs b/crates/font-manager/src/panel/specimen.rs index 64e4a50a4..824f8ac90 100644 --- a/crates/font-manager/src/panel/specimen.rs +++ b/crates/font-manager/src/panel/specimen.rs @@ -37,6 +37,8 @@ pub(crate) struct FontSampleStyle { pub(crate) enum SampleFace<'a> { /// A face of `catalog`, which the document-face registry loads when the sample is measured or painted. Face { catalog: &'a Catalog, owner: Owner, face: &'a FaceInfo }, + /// A face the host gives, ready as it is (a host row of the picker). + Font(&'a FontRef), /// No face is here to draw with: the sample keeps its band and shows nothing. Missing, } @@ -51,6 +53,7 @@ impl SampleFace<'_> { Shown::Ready(font) => Some(font), _ => None, }, + SampleFace::Font(font) => Some((*font).clone()), SampleFace::Missing => None, } } diff --git a/crates/pages/src/ui/sync_views.rs b/crates/pages/src/ui/sync_views.rs index b61223b6e..7528c8a30 100644 --- a/crates/pages/src/ui/sync_views.rs +++ b/crates/pages/src/ui/sync_views.rs @@ -4,8 +4,8 @@ //! and scroll before it is drawn, in the same pass. The halves and the divider are craft-ui's [`SplitViews`] with //! [`SplitLayout::TwoUpVertical`]: pane 0 is the left half, pane 1 the right half and main view. -#[cfg(feature = "screen-testing")] -mod stories; +#[cfg(feature = "suite")] +pub(crate) mod stories; use super::view::{PageViewOutput, PageViewState}; use craft_behavior::Proposal; diff --git a/crates/platform/src/appearance/windows.rs b/crates/platform/src/appearance/windows.rs deleted file mode 100644 index 3435f5db3..000000000 --- a/crates/platform/src/appearance/windows.rs +++ /dev/null @@ -1,15 +0,0 @@ -//! The Windows source of the appearance watcher: Settings ▸ Accessibility ▸ Visual effects ▸ -//! Animation effects ("Show animations in Windows" in the Control Panel), read through WinRT's -//! `UISettings::AnimationsEnabled`, which needs no `unsafe`. The user changes it in Settings, outside -//! the app, so the watcher reads it when it starts and again each time the app becomes active. - -/// Whether the system asks for no animations; `None` when WinRT can't be asked. -pub(super) fn reduced_motion() -> Option { - match ::windows::UI::ViewManagement::UISettings::new().and_then(|settings| settings.AnimationsEnabled()) { - Ok(enabled) => Some(!enabled), - Err(e) => { - log::debug!("system animation effects: {e}"); - None - } - } -} diff --git a/crates/platform/src/browser_files.rs b/crates/platform/src/browser_files.rs index 12c15615c..b9e72c5f7 100644 --- a/crates/platform/src/browser_files.rs +++ b/crates/platform/src/browser_files.rs @@ -3,7 +3,7 @@ use std::path::{Path, PathBuf}; use std::sync::{Arc, Mutex, MutexGuard}; -use craft_host::{FileError, Files, PickId, PickKind, PickRequest, Picked, Wake}; +use craft_host::{FileError, Files, PickId, PickKind, PickRequest, Picked, Wake, WriteIntent}; use js_sys::{Array, Function, Object, Promise, Reflect}; use wasm_bindgen::{JsCast, JsValue}; use wasm_bindgen_futures::{JsFuture, spawn_local}; @@ -300,7 +300,7 @@ impl Files for BrowserFiles { Err(FileError::Unsupported) } - fn write(&self, _path: &Path, _bytes: &[u8]) -> Result<(), FileError> { + fn write(&self, _path: &Path, _bytes: &[u8], _intent: WriteIntent) -> Result { Err(FileError::Unsupported) } diff --git a/crates/platform/src/clipboard/types.rs b/crates/platform/src/clipboard/types.rs index d16bf14f4..d5b665126 100644 --- a/crates/platform/src/clipboard/types.rs +++ b/crates/platform/src/clipboard/types.rs @@ -40,7 +40,7 @@ pub struct Flavor { impl Flavor { /// A [`URI_LIST`] flavor (RFC 2483) of the files `paths`, which a write puts on the system /// clipboard as copied files, the way a file manager's Copy does. - #[cfg(all(feature = "clipboard", not(target_arch = "wasm32")))] + #[cfg(all(feature = "clipboard-system", not(target_arch = "wasm32")))] pub fn files(paths: &[std::path::PathBuf]) -> Flavor { Self::new(URI_LIST, super::convert::uri_list(paths, cfg!(windows)).into_bytes()) } diff --git a/crates/review/src/ui/balloons.rs b/crates/review/src/ui/balloons.rs index a8c1d75fb..95dbfd9d7 100644 --- a/crates/review/src/ui/balloons.rs +++ b/crates/review/src/ui/balloons.rs @@ -239,9 +239,9 @@ impl<'a> CommentBalloons<'a> { apply(event, state, &mut edits); } for thread in pressed { - if state.selected != Some(thread.id) { + if state.selected.lead != Some(thread.id) { state.reveal(thread); - edits.push(CommentEdit::Select(thread.id)); + edits.push(CommentEdit::Select(vec![thread.id])); } } CommentBalloonsOutput { response, edits, cards } @@ -264,12 +264,13 @@ fn card<'r, 't: 'r>( BalloonItem::Thread { thread, .. } => { let name = thread.messages.first().map_or_else(String::new, |first| words.card_name.fill(&[("author", &first.author), ("text", &first.text)])); - let selected = state.selected == Some(thread.id); + let selected = state.selected.lead == Some(thread.id); let editing = state.editing.as_ref().filter(|(id, ..)| *id == thread.id).map(|(_, index, text)| (*index, text.as_str())); let row = CommentRow::card(thread, name) .actions(CardActions::Buttons) .body_rows(BODY_ROWS) .state(selected, !read_only && !thread.locked, now) + .lead(selected) .drafts(editing, if selected { state.reply.as_str() } else { "" }); (row, Some(thread)) } diff --git a/crates/review/src/ui/balloons/stories.rs b/crates/review/src/ui/balloons/stories.rs index 8e1b8a89d..e343ea980 100644 --- a/crates/review/src/ui/balloons/stories.rs +++ b/crates/review/src/ui/balloons/stories.rs @@ -1,5 +1,6 @@ //! Stories of `CommentBalloons`: cards beside a page. +use craft_behavior::Selection; use craft_behavior::kurbo::{Point, Rect as DocRect}; use craft_pages::ui::PlacedPage; use craft_ui::testing::canvas_story::{OUTLINE, StoryPicture, StoryShape, accent, on_picture, paint_shapes}; @@ -48,7 +49,7 @@ fn beside_page( place: BalloonPlace, read_only: bool, ) -> StoryOutput { - let state = data.value("state", CommentsPanelState { selected: selected.map(ThreadId), ..CommentsPanelState::default() }); + let state = data.value("state", CommentsPanelState { selected: selected.map_or_else(Selection::default, |id| Selection::single(ThreadId(id))), ..CommentsPanelState::default() }); // design: allow[raw-colour/const](the demo page is white paper, document data and not a theme colour) let (fill, line) = (Color32::WHITE, accent(ui, 1.0)); let shapes = [StoryShape::filled(&DocRect::new(0.0, 0.0, PAGE.0, PAGE.1), fill).outlined(OUTLINE, line)]; diff --git a/crates/review/tests/it/balloons.rs b/crates/review/tests/it/balloons.rs index eab04d54d..71a6979ba 100644 --- a/crates/review/tests/it/balloons.rs +++ b/crates/review/tests/it/balloons.rs @@ -119,7 +119,7 @@ fn selecting_a_card_and_posting_a_reply_report_the_matching_edits() { "a click on a card reports its selection: {:?}", shown.edits.borrow() ); - assert_eq!(shown.state.borrow().selected, Some(ThreadId(1))); + assert_eq!(shown.state.borrow().selected.lead, Some(ThreadId(1))); let reply = shown.fixture.by_label(words.reply.as_str()).expect("the selected card's reply field"); shown.fixture.click(&reply).settle(); shown.fixture.type_text("Thanks").settle(); @@ -145,12 +145,12 @@ fn reselecting_a_card_keeps_its_edit_draft() { // A click on the card's heading, above the open edit's field. let card = shown.card(1); shown.fixture.click_at(card.left_top() + vec2(30.0, 8.0)).settle(); - assert_eq!(shown.state.borrow().selected, Some(ThreadId(1)), "the click selects the card"); + assert_eq!(shown.state.borrow().selected.lead, Some(ThreadId(1)), "the click selects the card"); assert_eq!(shown.state.borrow().editing, Some((ThreadId(1), 0, "Edited".into())), "the card's own draft survives its selection"); let other = shown.card(2); shown.fixture.click_at(other.center()).settle(); - assert_eq!(shown.state.borrow().selected, Some(ThreadId(2))); + assert_eq!(shown.state.borrow().selected.lead, Some(ThreadId(2))); assert_eq!(shown.state.borrow().editing, None, "selecting another card drops the draft, as before"); } diff --git a/crates/text/src/ui/character/format_text.rs b/crates/text/src/ui/character/format_text.rs index ba81d05d7..be4e2a431 100644 --- a/crates/text/src/ui/character/format_text.rs +++ b/crates/text/src/ui/character/format_text.rs @@ -466,5 +466,5 @@ fn line_label(spacing: LineSpacing, dialog: &ParagraphDialogWords, units: &Units } } -#[cfg(feature = "screen-testing")] -mod stories; +#[cfg(feature = "suite")] +pub(crate) mod stories; diff --git a/crates/ui-canvas/src/canvas/navigate/wheel.rs b/crates/ui-canvas/src/canvas/navigate/wheel.rs index 201462df3..d2e8c3bb6 100644 --- a/crates/ui-canvas/src/canvas/navigate/wheel.rs +++ b/crates/ui-canvas/src/canvas/navigate/wheel.rs @@ -84,7 +84,7 @@ impl WheelInput { /// Shift + wheel scrolls sideways; there is no ladder step. /// - A trackpad pinch zooms about the pointer (Zoom with Trackpad Pinch). /// -/// That is [`WheelScheme::Photoshop`]. Under [`WheelScheme::Document`], a document editor's scheme: +/// That is [`WheelScheme::Scroll`]. Under [`WheelScheme::Document`], a document editor's scheme: /// /// - The wheel scrolls up and down; Shift + wheel scrolls sideways. /// - Ctrl or Cmd + wheel (without Alt) steps the zoom ladder one rung a notch about the pointer. diff --git a/crates/ui-canvas/src/canvas/stories.rs b/crates/ui-canvas/src/canvas/stories.rs index b74e93529..8ffc6283c 100644 --- a/crates/ui-canvas/src/canvas/stories.rs +++ b/crates/ui-canvas/src/canvas/stories.rs @@ -142,7 +142,7 @@ fn scrolled_view(room: Rect, pixels_per_point: f32) -> craft_behavior::CanvasVie #[story(Canvas, covers = [], drive = Drive::Custom(middle_click_centre))] fn middle_autoscroll(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let room = stage(ui); - let navigation = NavigationOptions { middle_button: MiddleButton::Autoscroll, ..NavigationOptions::default() }; + let navigation = NavigationOptions { middle_button: MiddleButton::AutoScroll, ..NavigationOptions::default() }; let (view, view_at) = data.value_at("view", scrolled_view(room, ui.pixels_per_point())); let shown = Canvas::new("Document") .navigation(navigation) diff --git a/crates/ui-contract/src/contract/props.rs b/crates/ui-contract/src/contract/props.rs index d946877bd..5130623b1 100644 --- a/crates/ui-contract/src/contract/props.rs +++ b/crates/ui-contract/src/contract/props.rs @@ -271,7 +271,7 @@ impl Resolved<'_> { /// The text of the component's own tooltip as the tooltip shows it: its disabled text while the component is /// disabled. `None` when the component has no tooltip. pub fn tooltip_text(&self, env: &crate::runtime::env::EnvView<'_>) -> Option { - self.tooltip.map(|tooltip| super::tooltip::spec_text(env, tooltip.spec(), self.enabled)) + self.tooltip.map(|tooltip| super::tooltip::resolve_spec(env, tooltip.spec(), self.enabled)) } } diff --git a/crates/ui-patterns/src/patterns/preferences/mod.rs b/crates/ui-patterns/src/patterns/preferences/mod.rs index 51aad461a..b217f22f8 100644 --- a/crates/ui-patterns/src/patterns/preferences/mod.rs +++ b/crates/ui-patterns/src/patterns/preferences/mod.rs @@ -32,7 +32,7 @@ pub(crate) mod path_setting; mod rows; pub(crate) mod window; -pub use page::{PreferencesPage, PreferencesPageOutput}; +pub use page::{PreferencesLayout, PreferencesPage, PreferencesPageOutput}; pub use path_setting::{PathSetting, PathSettingOutput}; diff --git a/crates/ui-shell/src/shell/recent_list.rs b/crates/ui-shell/src/shell/recent_list.rs index d78248463..2557d49b4 100644 --- a/crates/ui-shell/src/shell/recent_list.rs +++ b/crates/ui-shell/src/shell/recent_list.rs @@ -85,7 +85,7 @@ impl<'a> RecentList<'a> { let env = Env::of(ui); let words = env.words::(); let actions = RefCell::new(Vec::new()); - let page = Page { env: &env, words: &words, thumbnails, picture, card_zoom: None, paper: None, drop_hint: None, now, actions: &actions }; + let page = Page { env: &env, words: &words, thumbnails, picture, card_zoom: None, paper: None, drop_hint: None, now, actions: &actions, offers_new: true, offers_open: true, pinned_title: None }; let files: Vec = recent.iter().take(max_recent).cloned().collect(); let empty = empty.unwrap_or_else(|| words.no_recent.clone()); let shown = Section::fixed(words.recent.clone()).header_gap(Gap::Section).command_scope(StartRecentCommands::SCOPE).show(ui, |ui, cx| { @@ -156,8 +156,8 @@ pub(super) fn recent_body( }; let out = grid.show_items(ui, &source, &mut |path, _| { let Some(file) = file_of(path) else { return Tile::new(Label::Empty) }; - page.tile(&file.name, page.age(file.opened), ThumbKey::Recent(file.path.clone())) - .corner_action(IconId::new("close"), StartRecentCommands::Remove) + page.tile(&file.name, page.recent_detail(file), ThumbKey::Recent(file.path.clone())) + .action(IconId::new("close"), StartRecentCommands::Remove) .tooltip(file.path.display().to_string()) }); let corner: Vec = out @@ -165,7 +165,8 @@ pub(super) fn recent_body( .events .iter() .filter_map(|event| match event { - CollectionEvent::Item(key, TilePartEvent::CornerAction) => Some(key.clone()), + // The card's one action, its remove button, is action 0. + CollectionEvent::Item(key, TilePartEvent::Action(0)) => Some(key.clone()), _ => None, }) .collect(); @@ -182,7 +183,7 @@ pub(super) fn recent_body( .show_items(ui, &source, &mut |path, _| { let Some(file) = file_of(path) else { return ListRow::new(Label::Empty) }; let row = ListRow::new(Label::from(file.name.clone())).detail(folder_of(&file.path)).tooltip(file.path.display().to_string()); - let row = match page.age(file.opened) { + let row = match page.recent_detail(file) { Some(age) => row.trailing(age), None => row, }; diff --git a/crates/ui-widgets/src/text/word_run.rs b/crates/ui-widgets/src/text/word_run.rs index 3d9e66df0..5e28f5880 100644 --- a/crates/ui-widgets/src/text/word_run.rs +++ b/crates/ui-widgets/src/text/word_run.rs @@ -1,7 +1,7 @@ //! `WordRun`: a wrapping run of pickable words in one Tab stop. -#[cfg(feature = "testing")] -mod stories; +#[cfg(feature = "suite")] +pub(crate) mod stories; use crate::contract::{ Access, Bind, BindMut, Common, Component, Cx, Edit as _, EditResponse, MeasureCx, Name, Outcome, PaintUi, PartsCx, Pointer as _, Props as _, diff --git a/crates/web-host/README.md b/crates/web-host/README.md index f3ee51023..4da95b7e7 100644 --- a/crates/web-host/README.md +++ b/crates/web-host/README.md @@ -6,7 +6,7 @@ The crate has three parts: - **The contract** (all targets): the message kinds and their `:` types, the contract version, how the hosting mode is read from the URL and the canvas, and the clean-up of file names a host passes in. Pure, tested natively. - **The bridge** (`web`, wasm32 only): `Host::connect(app, canvas)` finds the host, `listen` hears its messages, and `post_ready`, `post_save`, `post_dirty`, `post_failed` and `post_handoff` answer it. Only the same-origin parent window is heard and answered; with a parent on another origin the app runs as if unframed. -- **The file service** (`files`, wasm32 only): `BrowserFiles::new(wake, max_read)` is the app's `craft_host::Files`. Open picks go through a file input and answer the files' contents (a file over `max_read` bytes is not copied in), and a finished read wakes the app; a Save pick answers the suggested name at once; Folder picks are unavailable. `write` posts the bytes to the page through the connection `Host::connect` made, or downloads them when no page hosts the app. +- **The file service** (`files`, wasm32 only, deprecated): `BrowserFiles::new(wake, max_read)` wraps `craft_platform::browser_files::BrowserFiles`, which holds its picks and saves (`Files::save`). Only `write` is its own: it posts the bytes to the page through the connection `Host::connect` made, or downloads them when no page hosts the app. New code uses the platform service directly. ## Messages diff --git a/crates/web-host/src/files.rs b/crates/web-host/src/files.rs index ddffafd7e..118e1548a 100644 --- a/crates/web-host/src/files.rs +++ b/crates/web-host/src/files.rs @@ -1,76 +1,51 @@ -//! The file service of a web build: pickers through a file input, saves through the host page or a download. +//! The file service of a web build: a deprecated wrapper over the platform browser service whose writes go to the host page or a download. -use std::collections::HashMap; use std::path::{Path, PathBuf}; -use std::sync::atomic::{AtomicU64, Ordering}; -use std::sync::{Arc, Mutex, MutexGuard, PoisonError}; -use craft_host::{FileError, Files, PickId, PickKind, PickRequest, Picked, Wake, WriteIntent}; +use craft_host::{FileError, Files, PickId, PickRequest, Picked, Wake, WriteIntent}; use craft_platform::browser::{DownloadOptions, download_bytes}; -use wasm_bindgen::{JsCast as _, JsValue}; -use wasm_bindgen_futures::JsFuture; -use web_sys::js_sys; +use craft_platform::browser_files::{BrowserFiles as PlatformFiles, PickLimits}; +use wasm_bindgen::JsValue; -/// Answers by ticket: `None` while the browser's picker is open or its files are being read. -type Answers = Arc>>>; - -/// The [`Files`] service of a web build. Open and OpenMany go through a file input to -/// [`Picked::Contents`] and a finished read wakes the app; Save answers the name at once and -/// `write` posts to the host page or downloads; Folder is unavailable. +/// The [`Files`] service of a web build, kept for apps written against it: a thin wrapper over +/// [`craft_platform::browser_files::BrowserFiles`], which holds the picks and saves (one store). +/// Only `write` differs: it posts to the hosting page when one is connected, and downloads +/// otherwise. +#[deprecated(note = "use craft_platform::browser_files::BrowserFiles; host-page saves go through Files::save")] pub struct BrowserFiles { - wake: Wake, - max_read: u64, - next: AtomicU64, - answers: Answers, + inner: PlatformFiles, } +#[allow(deprecated, reason = "the deprecated type's own impl")] impl BrowserFiles { - /// A service that wakes the app through `wake` when a picked file has been read. A picked file - /// longer than `max_read` bytes is not copied in: its pick answers [`Picked::Unavailable`]. + /// A service that wakes the app through `wake` when a pick has been answered. Picked files + /// waiting to be taken stay under `max_read` bytes. pub fn new(wake: Wake, max_read: u64) -> Self { - Self { wake, max_read, next: AtomicU64::new(0), answers: Arc::default() } + let limits = PickLimits { pending_bytes: usize::try_from(max_read).unwrap_or(usize::MAX), ..PickLimits::DEFAULT }; + Self { inner: PlatformFiles::new(move || wake.wake()).limits(limits) } } } +#[allow(deprecated, reason = "the deprecated type's own impl")] impl Files for BrowserFiles { fn pick(&self, request: PickRequest) -> PickId { - let id = PickId(self.next.fetch_add(1, Ordering::Relaxed) + 1); - lock(&self.answers).insert(id, None); - let now = match request.kind { - PickKind::Save => Some(Picked::Paths(vec![PathBuf::from(save_name(&request))])), - PickKind::Folder => Some(Picked::Unavailable("a browser has no folder picker".into())), - PickKind::Open | PickKind::OpenMany => match open_input(&request) { - Ok((input, settled)) => { - wasm_bindgen_futures::spawn_local(read_picked(input, settled, self.max_read, self.answers.clone(), self.wake.clone(), id)); - None - } - Err(error) => Some(Picked::Unavailable(error)), - }, - }; - if let Some(picked) = now { - answer(&self.answers, &self.wake, id, picked); - } - id + self.inner.pick(request) } fn take_answer(&self, id: PickId) -> Option { - let mut answers = lock(&self.answers); - if !matches!(answers.get(&id), Some(Some(_))) { - return None; - } - answers.remove(&id).flatten() + self.inner.take_answer(id) } fn forget(&self, id: PickId) { - lock(&self.answers).remove(&id); + self.inner.forget(id); } fn pick_pending(&self) -> bool { - lock(&self.answers).values().any(Option::is_none) + self.inner.pick_pending() } - fn read(&self, _path: &Path) -> Result, FileError> { - Err(FileError::Unsupported) + fn read(&self, path: &Path) -> Result, FileError> { + self.inner.read(path) } fn write(&self, path: &Path, bytes: &[u8], intent: WriteIntent) -> Result { @@ -81,86 +56,21 @@ impl Files for BrowserFiles { download_bytes(&name, mime_type(&name), bytes, DownloadOptions::default()).map(|()| false).map_err(|e| FileError::Other(js_error(e))) } - fn last_folder(&self, _purpose: &str) -> Option { - None + fn last_folder(&self, purpose: &str) -> Option { + self.inner.last_folder(purpose) } -} -fn lock(answers: &Mutex>>) -> MutexGuard<'_, HashMap>> { - answers.lock().unwrap_or_else(PoisonError::into_inner) -} - -/// Stores `picked` for `id` and wakes the app to take it; a ticket forgotten meanwhile gets nothing. -fn answer(answers: &Mutex>>, wake: &Wake, id: PickId, picked: Picked) { - { - let mut answers = lock(answers); - let Some(slot) = answers.get_mut(&id) else { return }; - *slot = Some(picked); + fn save(&self, request: PickRequest, bytes: Vec) -> PickId { + self.inner.save(request, bytes) } - wake.wake(); -} -/// The name a Save pick answers: the suggested name, cleaned, with the suggested extension when it has none. -fn save_name(request: &PickRequest) -> String { - let name = crate::file_name(request.file_name.as_deref(), "document"); - match &request.suggested_extension { - Some(extension) if !extension.is_empty() && Path::new(&name).extension().is_none() => format!("{name}.{extension}"), - _ => name, + fn can_pick(&self) -> bool { + self.inner.can_pick() } -} -/// A hidden file input for `request`, already clicked, and the promise its `change` or `cancel` -/// event settles: the browser fires `cancel` at a file input when the user closes its picker -/// without choosing (HTML, "show the picker"), so a cancelled pick ends too. -fn open_input(request: &PickRequest) -> Result<(web_sys::HtmlInputElement, js_sys::Promise), String> { - let document = web_sys::window().and_then(|w| w.document()).ok_or("the page has no document")?; - let input: web_sys::HtmlInputElement = - document.create_element("input").map_err(js_error)?.dyn_into().map_err(|_| "the element is not an input".to_string())?; - input.set_type("file"); - input.set_multiple(request.kind == PickKind::OpenMany); - let accept: Vec = request.filters.iter().flat_map(|f| &f.extensions).map(|e| format!(".{e}")).collect(); - if !accept.is_empty() { - input.set_accept(&accept.join(",")); + fn browser_saves(&self) -> bool { + self.inner.browser_saves() } - input.set_hidden(true); - // Some browsers show no picker for an input outside the document. - let body = document.body().ok_or("the page has no body")?; - body.append_child(&input).map_err(js_error)?; - let settled = js_sys::Promise::new(&mut |resolve, _reject| { - input.set_onchange(Some(&resolve)); - input.set_oncancel(Some(&resolve)); - }); - input.click(); - Ok((input, settled)) -} - -/// Waits for the picker to close, reads what was chosen, and answers ticket `id`. -async fn read_picked(input: web_sys::HtmlInputElement, settled: js_sys::Promise, max_read: u64, answers: Answers, wake: Wake, id: PickId) { - let picked = match JsFuture::from(settled).await { - Ok(_) => read_files(&input, max_read).await, - Err(error) => Picked::Unavailable(js_error(error)), - }; - input.remove(); - answer(&answers, &wake, id, picked); -} - -/// The chosen files' names and contents; nothing chosen is `Cancelled`. -async fn read_files(input: &web_sys::HtmlInputElement, max_read: u64) -> Picked { - let Some(list) = input.files() else { return Picked::Cancelled }; - let mut files = Vec::new(); - for at in 0..list.length() { - let Some(file) = list.get(at) else { continue }; - let name = crate::file_name(Some(&file.name()), "document"); - // Checked before the copy: the file is untrusted and its bytes would come into memory whole. - if file.size() > max_read as f64 { - return Picked::Unavailable(format!("{name} is larger than {max_read} bytes")); - } - match JsFuture::from(file.array_buffer()).await { - Ok(buffer) => files.push((name, js_sys::Uint8Array::new(&buffer).to_vec())), - Err(error) => return Picked::Unavailable(js_error(error)), - } - } - if files.is_empty() { Picked::Cancelled } else { Picked::Contents(files) } } fn js_error(error: JsValue) -> String {