fw sync: apply the areas' owed lines (platform/web-host files, clipboard cfg, tooltip, canvas, stories gating, balloons selection, recent list, specimen, preferences re-export)

This commit is contained in:
Dylan M. Taylor
2026-11-22 23:13:52 -05:00
parent 1cae51b2cb
commit a48cd842f4
17 changed files with 62 additions and 161 deletions
@@ -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,
}
}
+2 -2
View File
@@ -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;
-15
View File
@@ -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<bool> {
match ::windows::UI::ViewManagement::UISettings::new().and_then(|settings| settings.AnimationsEnabled()) {
Ok(enabled) => Some(!enabled),
Err(e) => {
log::debug!("system animation effects: {e}");
None
}
}
}
+2 -2
View File
@@ -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<bool, FileError> {
Err(FileError::Unsupported)
}
+1 -1
View File
@@ -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())
}
+4 -3
View File
@@ -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))
}
+2 -1
View File
@@ -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)];
+3 -3
View File
@@ -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");
}
+2 -2
View File
@@ -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;
@@ -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.
+1 -1
View File
@@ -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)
+1 -1
View File
@@ -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<String> {
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))
}
}
@@ -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};
+6 -5
View File
@@ -85,7 +85,7 @@ impl<'a> RecentList<'a> {
let env = Env::of(ui);
let words = env.words::<ShellWords>();
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<RecentFile> = 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<PathBuf> = 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,
};
+2 -2
View File
@@ -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 _,
+1 -1
View File
@@ -6,7 +6,7 @@ The crate has three parts:
- **The contract** (all targets): the message kinds and their `<app>:<kind>` 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
+30 -120
View File
@@ -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<Mutex<HashMap<PickId, Option<Picked>>>>;
/// 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<Picked> {
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<Vec<u8>, FileError> {
Err(FileError::Unsupported)
fn read(&self, path: &Path) -> Result<Vec<u8>, FileError> {
self.inner.read(path)
}
fn write(&self, path: &Path, bytes: &[u8], intent: WriteIntent) -> Result<bool, FileError> {
@@ -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<PathBuf> {
None
fn last_folder(&self, purpose: &str) -> Option<PathBuf> {
self.inner.last_folder(purpose)
}
}
fn lock(answers: &Mutex<HashMap<PickId, Option<Picked>>>) -> MutexGuard<'_, HashMap<PickId, Option<Picked>>> {
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<HashMap<PickId, Option<Picked>>>, 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<u8>) -> 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<String> = 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 {