fix(web): same-named files open, sequences arrive whole, the editor's keys stay the editor's (M8)

In a real browser (headless Chrome): a picked file with the name of an open
document was refused as already open; a PNG or SVG sequence lost most of its
frames to the browser's limit on a run of downloads (now one ZIP); F5, Ctrl+R
and other editor shortcuts were acted on by the browser (F5 reloaded the page).
This commit is contained in:
Tanish Manku committed 2026-11-28 01:17:43 -07:00
1 parent b24cbcdd39
commit 167a090afe
7 files changed
+180 -14

No files matched your search

+1 -1
View File
@@ -184,7 +184,7 @@ js-sys = "0.3"
cpal = { version = "0.18", optional = true, features = ["wasm-bindgen"] }
# In the browser the page's language (navigator.languages) is the system's.
sys-locale = { version = "0.3", features = ["js"] }
web-sys = { version = "0.3", features = ["BeforeUnloadEvent", "Blob", "BlobPropertyBag", "CssStyleDeclaration", "DomRect", "DragEvent", "Document", "Element", "Event", "EventTarget", "File", "FileList", "HtmlAnchorElement", "HtmlCanvasElement", "HtmlElement", "HtmlInputElement", "MediaQueryList", "Navigator", "Storage", "Url", "Window", "console"] }
web-sys = { version = "0.3", features = ["BeforeUnloadEvent", "Blob", "BlobPropertyBag", "CssStyleDeclaration", "DomRect", "DragEvent", "Document", "Element", "Event", "EventTarget", "File", "FileList", "HtmlAnchorElement", "HtmlCanvasElement", "HtmlElement", "HtmlInputElement", "KeyboardEvent", "MediaQueryList", "Navigator", "Storage", "Url", "Window", "console"] }
[dev-dependencies]
# Plug-in fixtures for the shell's plug-in tests, in WebAssembly text (Apache-2.0 WITH
+25 -1
View File
@@ -1095,7 +1095,13 @@ impl App {
if platform::WEB && id.starts_with("file.") {
// In a browser, what a save or an export wrote is in memory: hand it to the
// browser as downloads (ADR 0036).
platform::deliver(anicraft_engine::vfs::take_written());
// Several files (a sequence) leave as one ZIP: a browser drops most of a run of
// downloads.
let (files, failed) = platform::as_one_download(anicraft_engine::vfs::take_written(), None);
platform::deliver(files);
if let Some(e) = failed {
self.status_err(tr!("Could not make the archive: {e}", e = e));
}
}
match result {
Ok(v) => {
@@ -1337,6 +1343,22 @@ impl App {
pub fn refresh_keymap(&mut self) {
self.keymap = keymap::Keymap::new(&self.prefs.shortcuts);
self.shortcuts = self.keymap.table();
#[cfg(target_arch = "wasm32")]
crate::web::claim_keys(self.browser_keys(), platform::menu_bar_keys());
}
/// Every chord the editor acts on that a browser would act on first (`platform::claims_key`
/// decides per key press): the shortcut table, the fixed ones `handle_shortcuts` takes, and
/// the menu bar's (ADR 0064).
#[cfg_attr(not(target_arch = "wasm32"), allow(dead_code))]
pub fn browser_keys(&self) -> Vec<(Modifiers, Key)> {
let mut keys: Vec<(Modifiers, Key)> = self.shortcuts.iter().map(|(m, k, _)| (*m, *k)).collect();
keys.extend([(Modifiers::NONE, Key::F1), (Modifiers::COMMAND, Key::K), (Modifiers::COMMAND | Modifiers::SHIFT, Key::P), (Modifiers::COMMAND, Key::U), (Modifiers::COMMAND, Key::Comma)]);
if platform::menu_bar_keys() {
keys.push((Modifiers::NONE, Key::F10));
keys.extend(crate::menus::top_access_keys().into_iter().map(|k| (Modifiers::ALT, k)));
}
keys
}
pub fn save_prefs(&mut self) {
@@ -3755,6 +3777,8 @@ impl App {
let done = trn!("Exported {path} ({n} frame, {layers} layers).", "Exported {path} ({n} frames, {layers} layers).", v["frames"].as_u64().unwrap_or(0), path = v["written"].as_str().unwrap_or(""), layers = v["layers"]);
self.status_ok(format!("{done}{report}"));
}
// In a browser a sequence's frames arrive as one archive named after the folder.
"file.export_png_sequence" | "file.export_svg_sequence" if platform::WEB => self.status_ok(tr!("Exported {path}.zip to your downloads", path = v.get("dir").and_then(Value::as_str).unwrap_or(""))),
"file.export_png" | "file.export_png_sequence" | "file.export_svg_sequence" | "file.export_gif" | "file.export_svg" | "file.export_video" => self.status_ok(tr!("Exported {path}", path = v.get("written").or_else(|| v.get("dir")).and_then(Value::as_str).unwrap_or(""))),
// Undo labels are the engine's English, translated when a catalog has them.
"edit.undo" => self.status_ok(tr!("Undid {action}", action = crate::i18n::t_dyn(v["undone"].as_str().unwrap_or("")))),
+6
View File
@@ -71,6 +71,12 @@ fn top_labels() -> Vec<String> {
TOP_MENUS.iter().map(|t| crate::i18n::t(t).to_string()).collect()
}
/// The keys that open the top menus with Alt, in the interface language.
pub fn top_access_keys() -> Vec<egui::Key> {
let labels = top_labels();
access_keys(&labels.iter().map(String::as_str).collect::<Vec<_>>()).into_iter().filter_map(|k| egui::Key::from_name(&k?.1.to_string())).collect()
}
/// Each top menu's access key: `(character index, letter)`, the first letter of its title that
/// no menu before it took (word starts first); ASCII letters only, so a title without one has
/// none.
+93 -1
View File
@@ -211,6 +211,34 @@ pub fn menu_bar_keys() -> bool {
keys_os() != Os::Mac
}
/// In a browser: whether the editor takes this key press from the browser, which would
/// otherwise act on it (F5 reloads the page, Ctrl+R too, Ctrl+D bookmarks it, Alt+F opens the
/// browser's menu). `bound` is every chord the editor acts on; `alt_menus` says Alt reaches the
/// menu bar (ADR 0064).
///
/// A key is taken only when the editor uses it, so the browser keeps the rest (F12, Ctrl+T,
/// Alt+D: the ways out of the page by keyboard). Plain typing keys are never taken (that would
/// stop text reaching a text field), nor are cut, copy and paste, which arrive as the
/// browser's clipboard events.
#[cfg_attr(not(target_arch = "wasm32"), allow(dead_code))]
pub fn claims_key(bound: &[(egui::Modifiers, egui::Key)], alt_menus: bool, pressed: egui::Modifiers, key: Option<egui::Key>) -> bool {
use egui::Key;
let Some(key) = key else {
// Alt by itself focuses the browser's own menu; here it focuses the editor's.
return alt_menus && pressed.alt && !pressed.ctrl && !pressed.command && !pressed.shift;
};
let chorded = pressed.ctrl || pressed.command || pressed.alt;
if chorded && !pressed.alt && matches!(key, Key::C | Key::X | Key::V) {
return false;
}
let function = matches!(key, Key::F1 | Key::F2 | Key::F3 | Key::F4 | Key::F5 | Key::F6 | Key::F7 | Key::F8 | Key::F9 | Key::F10 | Key::F11 | Key::F12);
if !chorded && !function {
return false;
}
// As egui matches a shortcut: extra Shift or Alt held still presses it.
bound.iter().any(|(m, k)| *k == key && pressed.matches_logically(*m))
}
pub fn set_mac_glyphs(available: bool) {
MAC_GLYPHS.store(available, Ordering::Relaxed);
}
@@ -1249,15 +1277,43 @@ pub fn picked_file() -> Option<Picked> {
None
}
/// Files a command wrote: each one's path and bytes.
pub type Written = Vec<(PathBuf, Vec<u8>)>;
/// In a browser: offers each file a command saved or exported as a download.
#[cfg_attr(not(target_arch = "wasm32"), allow(unused_variables))]
pub fn deliver(files: Vec<(PathBuf, Vec<u8>)>) {
pub fn deliver(files: Written) {
#[cfg(target_arch = "wasm32")]
for (path, data) in files {
crate::web::download(&path, &data);
}
}
/// In a browser: what one command wrote, as one download. A single file goes as it is; several
/// (a PNG or SVG sequence, a sprite sheet with its data, a publish) go in one ZIP, because a
/// browser lets a page start only a few downloads in a row and silently drops the rest (Chrome
/// kept 10 to 18 of a 48-frame sequence). The archive is named `name`, or after the folder the
/// files share, or after the first file. When they don't fit a ZIP the files come back as they
/// were, to send one by one after all, with why.
#[cfg_attr(not(target_arch = "wasm32"), allow(dead_code))]
pub fn as_one_download(files: Written, name: Option<&str>) -> (Written, Option<String>) {
use std::path::Component;
if files.len() < 2 {
return (files, None);
}
let folder = |p: &Path| match (p.components().next(), p.components().nth(1)) {
(Some(Component::Normal(f)), Some(_)) => Some(f.to_string_lossy().into_owned()),
_ => None,
};
let shared = files.first().and_then(|(p, _)| folder(p)).filter(|f| files.iter().all(|(p, _)| folder(p).as_ref() == Some(f)));
let first = files.first().and_then(|(p, _)| p.file_stem()).map(|s| s.to_string_lossy().into_owned());
let name = name.map(str::to_string).or(shared).or(first).filter(|n| !n.is_empty()).unwrap_or_else(|| "export".to_string()); // i18n-exempt: a file name
match anicraft_engine::publish::zip(&files) {
Ok(z) => (vec![(PathBuf::from(format!("{name}.zip")), z)], None),
Err(e) => (files, Some(e)),
}
}
/// In a browser: whether leaving the page asks first (there are unsaved changes).
#[cfg_attr(not(target_arch = "wasm32"), allow(unused_variables))]
pub fn set_unsaved(unsaved: bool) {
@@ -1412,6 +1468,42 @@ mod tests {
assert_eq!(split_suggestion(&gone.display().to_string()).0, None, "a folder that isn't there is not offered");
}
/// The web editor takes from the browser exactly the keys it acts on: F5 must insert a
/// frame, not reload the page, while typing, the clipboard and the browser's own keys stay.
#[test]
fn the_browser_keeps_every_key_the_editor_does_not_use() {
use egui::{Key, Modifiers};
let bound = [(Modifiers::NONE, Key::F5), (Modifiers::COMMAND, Key::R), (Modifiers::NONE, Key::V), (Modifiers::COMMAND | Modifiers::SHIFT, Key::V), (Modifiers::ALT, Key::F)];
let ctrl = Modifiers { ctrl: true, command: true, ..Modifiers::NONE };
let claims = |m: Modifiers, k: Key| claims_key(&bound, true, m, Some(k));
assert!(claims(Modifiers::NONE, Key::F5) && claims(ctrl, Key::R) && claims(Modifiers::ALT, Key::F));
assert!(claims(Modifiers::SHIFT, Key::F5), "as egui matches it: Shift held still presses F5");
assert!(!claims(Modifiers::NONE, Key::F12) && !claims(ctrl, Key::T) && !claims(Modifiers::ALT, Key::D), "unused keys are the browser's");
assert!(!claims(Modifiers::NONE, Key::V), "a tool letter is typing in a text field");
assert!(!claims(ctrl, Key::V) && !claims(ctrl | Modifiers::SHIFT, Key::V), "paste arrives as the browser's event");
assert!(claims_key(&bound, true, Modifiers::ALT, None), "Alt alone is the editor's menu bar");
assert!(!claims_key(&bound, false, Modifiers::ALT, None), "but not on a Mac, where Alt opens no menu");
}
/// One command's files leave the browser as one download: a browser drops most of a run
/// of downloads, so a sequence must be one archive holding every frame.
#[test]
fn several_exported_files_are_one_archive() {
let file = |p: &str| (PathBuf::from(p), p.as_bytes().to_vec());
let one = as_one_download(vec![file("movie.gif")], None).0;
assert_eq!(one, vec![file("movie.gif")], "a single file is not wrapped");
let frames: Vec<_> = (0..48).map(|i| file(&format!("frames/frame_{i:05}.png"))).collect();
let (zipped, failed) = as_one_download(frames.clone(), None);
assert_eq!(failed, None);
assert_eq!(zipped.len(), 1);
assert_eq!(zipped[0].0, PathBuf::from("frames.zip"), "named after the folder the frames share");
let listed = |name: &str| zipped[0].1.windows(name.len()).any(|w| w == name.as_bytes());
assert!(frames.iter().all(|(p, _)| listed(&p.display().to_string().replace('\\', "/"))), "every frame is in it");
let sheet = as_one_download(vec![file("sprites.png"), file("sprites.json")], None).0;
assert_eq!(sheet[0].0, PathBuf::from("sprites.zip"), "no shared folder: after the first file");
assert_eq!(as_one_download(frames, Some("walk")).0[0].0, PathBuf::from("walk.zip"));
}
#[test]
fn the_desktop_runs_every_command() {
assert!(anicraft_engine::commands().iter().all(|c| unavailable(c.id).is_none()));
+4 -11
View File
@@ -240,17 +240,10 @@ fn finish(app: &mut App, job: Job) {
if crate::platform::WEB {
// In a browser the files are in memory: they go to the downloads, in one ZIP when there
// are several (ADR 0060).
let written = anicraft_engine::vfs::take_written();
if written.len() > 1 {
match publish::zip(&written) {
Ok(z) => crate::platform::deliver(vec![(std::path::PathBuf::from(format!("{}.zip", job.name)), z)]),
Err(e) => {
app.status_err(tr!("Could not make the archive: {e}", e = e));
crate::platform::deliver(written);
}
}
} else {
crate::platform::deliver(written);
let (files, failed) = crate::platform::as_one_download(anicraft_engine::vfs::take_written(), Some(&job.name));
crate::platform::deliver(files);
if let Some(e) = failed {
app.status_err(tr!("Could not make the archive: {e}", e = e));
}
}
let (ok, failed, skipped) = (report.count(Status::Published), report.count(Status::Failed), report.count(Status::Skipped));
+4
View File
@@ -417,6 +417,10 @@ fn already_open(app: &App, id: &str, params: &Value) -> Option<usize> {
return None;
}
let path = match id {
// In a browser an opened file is one just picked or dropped, known only by its name:
// a second file may share it (a backup from another folder), and even the same file
// may have changed on disk since. It always opens, in a tab of its own.
"file.open" if platform::WEB => return None,
"file.open" => PathBuf::from(params.get("path")?.as_str()?),
"file.open_recent" => match (params.get("index").and_then(Value::as_u64), params.get("path").and_then(Value::as_str)) {
(Some(i), _) => app.s.recent.entries().get(usize::try_from(i).ok()?)?.path.clone(),
+47
View File
@@ -53,6 +53,9 @@ thread_local! {
/// Dropped files read so far, by ticket: each file's name and bytes.
static DROPPED: RefCell<Vec<(u64, ReadFiles)>> = const { RefCell::new(Vec::new()) };
static TICKET: Cell<u64> = const { Cell::new(0) };
/// The chords the editor acts on, and whether Alt reaches its menu bar: the key presses
/// taken from the browser (`platform::claims_key`).
static KEYS: RefCell<(Vec<(egui::Modifiers, egui::Key)>, bool)> = const { RefCell::new((Vec::new(), false)) };
}
/// Starts the editor on the page's canvas.
@@ -60,6 +63,7 @@ pub fn start() {
let mac = web_sys::window().and_then(|w| w.navigator().user_agent().ok()).is_some_and(|ua| ua.contains("Mac"));
crate::platform::set_web_on_mac(mac);
guard_leaving();
guard_keys();
wasm_bindgen_futures::spawn_local(async {
match run().await {
Ok(()) => {
@@ -299,6 +303,49 @@ fn guard_leaving() {
}
}
// ----- keys -------------------------------------------------------------------------------------
/// Tells the page which chords the editor acts on (its shortcut table changed).
pub fn claim_keys(bound: Vec<(egui::Modifiers, egui::Key)>, alt_menus: bool) {
KEYS.with(|k| *k.borrow_mut() = (bound, alt_menus));
}
/// Keeps the browser from acting on the editor's shortcuts: F5 inserts a frame instead of
/// reloading the page, Ctrl+R imports instead of reloading, Alt+F opens the editor's File menu.
/// eframe stops only a few (Ctrl+S, Ctrl+O, Ctrl+P, Tab, the arrows) and leaves F5 and Ctrl+R
/// to the browser on purpose. The key still reaches the editor: only the browser's own action
/// is called off, and only for keys the editor uses (`platform::claims_key`).
fn guard_keys() {
let Some(window) = web_sys::window() else { return };
let on_key = Closure::<dyn FnMut(web_sys::KeyboardEvent)>::new(|e: web_sys::KeyboardEvent| {
// The same reading of the event as eframe's, so both see one key.
// (Alt's own release no longer counts it as held.)
let pressed = egui::Modifiers { alt: e.alt_key() || e.key() == "Alt", ctrl: e.ctrl_key(), shift: e.shift_key(), mac_cmd: e.meta_key(), command: e.ctrl_key() || e.meta_key() };
let name = e.key();
let key = egui::Key::from_name(&name).or_else(|| egui::Key::from_name(&e.code()));
// AltGr types a character (€, @ on many layouts): never a shortcut to take.
if (key.is_none() && name != "Alt") || e.get_modifier_state("AltGraph") { // i18n-exempt: DOM key names
return;
}
if KEYS.with(|k| {
let k = k.borrow();
crate::platform::claims_key(&k.0, k.1, pressed, key)
}) {
e.prevent_default();
}
});
// In the capture phase, on the window: before eframe's listeners on the canvas, which stop
// the event from going further.
let mut held = false;
for kind in ["keydown", "keyup"] {
held |= window.add_event_listener_with_callback_and_bool(kind, on_key.as_ref().unchecked_ref(), true).is_ok();
}
if held {
// Lives as long as the page.
on_key.forget();
}
}
// ----- storage ----------------------------------------------------------------------------------
fn storage() -> Option<web_sys::Storage> {