Skip to content

PhotoCraft: An open-source, photo editor written by scratch in pure Rust

Fix #1380: the web build asks before leaving the page with unsaved work (#1424)

BFlat4477cf6bdfc2
diff --git a/apps/photocraft-web/Cargo.toml b/apps/photocraft-web/Cargo.toml
index be1f764fa..e633c753b 100644
--- a/apps/photocraft-web/Cargo.toml
+++ b/apps/photocraft-web/Cargo.toml
@@ -34,4 +34,4 @@ rfd = { workspace = true }
wasm-bindgen = "0.2"
wasm-bindgen-futures = "0.4"
js-sys = "0.3"
-web-sys = { version = "0.3", features = ["Window", "Document", "Element", "HtmlElement", "HtmlCanvasElement", "HtmlAnchorElement", "Blob", "BlobPropertyBag", "Url", "Location", "CssStyleDeclaration", "Storage", "Event", "EventTarget", "MouseEvent", "PointerEvent"] }
+web-sys = { version = "0.3", features = ["Window", "Document", "Element", "HtmlElement", "HtmlCanvasElement", "HtmlAnchorElement", "Blob", "BlobPropertyBag", "Url", "Location", "CssStyleDeclaration", "Storage", "Event", "EventTarget", "MouseEvent", "PointerEvent", "BeforeUnloadEvent"] }
diff --git a/apps/photocraft-web/src/web.rs b/apps/photocraft-web/src/web.rs
index fa543d099..c422a00b1 100644
--- a/apps/photocraft-web/src/web.rs
+++ b/apps/photocraft-web/src/web.rs
@@ -1,5 +1,6 @@
//! The browser shell: web `Services`, drag-and-drop, and the eframe web runner.
+use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use photocraft_codecs::{ChannelLayout, EncodeOptions, Image};
@@ -56,7 +57,9 @@ pub fn start() {
log::info!("photocraft-web: wgpu backend {:?}", rs.adapter.get_info().backend);
app.set_wgpu(rs);
}
- Ok(Box::new(WebShell { app, inbox }))
+ let unsaved = Arc::new(AtomicBool::new(false));
+ guard_unload(unsaved.clone());
+ Ok(Box::new(WebShell { app, inbox, unsaved }))
}),
)
.await;
@@ -99,6 +102,24 @@ fn listen_pen(target: &web_sys::HtmlCanvasElement, feed: photocraft_ui_egui::sty
}
}
+/// Closing or reloading the tab while a document has unsaved changes asks first, as closing the
+/// desktop window does: the browser shows its own "Leave site?" prompt (#1380). `unsaved` is
+/// refreshed every frame by [`WebShell`].
+fn guard_unload(unsaved: Arc<AtomicBool>) {
+ use wasm_bindgen::closure::Closure;
+ let Some(window) = web_sys::window() else { return };
+ let cb = Closure::<dyn FnMut(web_sys::BeforeUnloadEvent)>::new(move |e: web_sys::BeforeUnloadEvent| {
+ if unsaved.load(Ordering::Relaxed) {
+ e.prevent_default();
+ // Older browsers show the prompt only when a return value is set.
+ e.set_return_value("");
+ }
+ });
+ if window.add_event_listener_with_callback("beforeunload", cb.as_ref().unchecked_ref()).is_ok() {
+ cb.forget();
+ }
+}
+
fn query() -> String {
web_sys::window().and_then(|w| w.location().search().ok()).unwrap_or_default()
}
@@ -108,6 +129,8 @@ fn query() -> String {
struct WebShell {
app: PhotocraftApp,
inbox: Inbox,
+ /// Read by the `beforeunload` listener ([`guard_unload`]).
+ unsaved: Arc<AtomicBool>,
}
impl eframe::App for WebShell {
@@ -128,6 +151,7 @@ impl eframe::App for WebShell {
});
}
self.app.logic(ctx, frame);
+ self.unsaved.store(self.app.has_unsaved_work(), Ordering::Relaxed);
}
fn ui(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) {
diff --git a/crates/ui-egui/src/discard_ui.rs b/crates/ui-egui/src/discard_ui.rs
index 41b1776a7..e8d9ad397 100644
--- a/crates/ui-egui/src/discard_ui.rs
+++ b/crates/ui-egui/src/discard_ui.rs
@@ -80,6 +80,14 @@ pub fn intercept(app: &mut PhotocraftApp, id: &str, params: &Value) -> bool {
true
}
+impl PhotocraftApp {
+ /// Whether closing now would lose work: a document has unsaved changes and closing wasn't
+ /// confirmed. The web build has the browser ask before leaving the page while this holds (#1380).
+ pub fn has_unsaved_work(&self) -> bool {
+ !self.allow_close && self.session.documents().iter().any(|d| d.is_dirty())
+ }
+}
+
/// Called once per frame: holds back a window close request while there is unsaved work.
pub fn guard_window_close(app: &mut PhotocraftApp, ctx: &egui::Context) {
if app.allow_close || !ctx.input(|i| i.viewport().close_requested()) {
@@ -461,6 +469,16 @@ mod tests {
assert!(app.discard.is_some());
}
+ #[test]
+ fn unsaved_work_is_any_dirty_document_until_closing_is_confirmed() {
+ let mut app = app_with_docs(2);
+ assert!(!app.has_unsaved_work());
+ make_dirty(&mut app, 1);
+ assert!(app.has_unsaved_work(), "a dirty document that isn't the active one counts");
+ app.allow_close = true;
+ assert!(!app.has_unsaved_work());
+ }
+
#[test]
fn window_close_goes_through_when_nothing_is_unsaved_or_it_was_confirmed() {
let mut app = app_with_docs(1);