mirror of
https://github.com/storytold/gridcraft.git
synced 2026-12-03 02:57:01 -06:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0bcc39e0ba | ||
|
|
71ec2b9aa0 |
Generated
+1
@@ -3078,6 +3078,7 @@ dependencies = [
|
||||
name = "gridcraft-web"
|
||||
version = "0.20.0"
|
||||
dependencies = [
|
||||
"craft-print",
|
||||
"craft-web-api",
|
||||
"craft-web-host",
|
||||
"eframe",
|
||||
|
||||
@@ -25,9 +25,10 @@ log = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
|
||||
[target.'cfg(target_arch = "wasm32")'.dependencies]
|
||||
craft-print = { workspace = true }
|
||||
eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit"] }
|
||||
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", "Event", "EventTarget", "HtmlElement", "HtmlCanvasElement", "HtmlAnchorElement", "HtmlIFrameElement", "Blob", "BlobPropertyBag", "Url", "Location", "CssStyleDeclaration", "Clipboard", "ClipboardItem", "Navigator", "MessageEvent", "UrlSearchParams", "AddEventListenerOptions", "Storage", "CustomEvent", "CustomEventInit"] }
|
||||
web-sys = { version = "0.3", features = ["Window", "Document", "Element", "Event", "EventTarget", "HtmlElement", "HtmlCanvasElement", "HtmlAnchorElement", "Blob", "BlobPropertyBag", "Url", "Location", "CssStyleDeclaration", "Clipboard", "ClipboardItem", "Navigator", "MessageEvent", "UrlSearchParams", "Storage", "CustomEvent", "CustomEventInit"] }
|
||||
|
||||
@@ -227,11 +227,7 @@ fn services(inbox: Inbox, ctx: egui::Context) -> Services {
|
||||
log::error!("download of {name} failed: {e}");
|
||||
}
|
||||
})),
|
||||
print: Some(Box::new(|bytes: &[u8]| {
|
||||
if let Err(e) = print_pdf(bytes) {
|
||||
log::error!("print failed: {e}");
|
||||
}
|
||||
})),
|
||||
print: Some(Box::new(craft_print::browser::print_pdf)),
|
||||
open_url: Some(Box::new(|url: &str| {
|
||||
if let Some(w) = web_sys::window()
|
||||
&& let gridcraft_engine::links::LinkKind::External(url) = gridcraft_engine::links::classify(url)
|
||||
@@ -280,75 +276,6 @@ fn copy_html(html: &str, text: &str) -> Result<(), String> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Opens `bytes` (a PDF) as an object URL in a hidden iframe and calls the iframe's own
|
||||
/// `print()` once it has finished loading — the standard way to drive the browser's native print
|
||||
/// dialog on a PDF without a download or a popup window the browser might block. The blob URL and
|
||||
/// the iframe are both cleaned up once the print dialog closes, so repeated prints don't leak
|
||||
/// them.
|
||||
fn print_pdf(bytes: &[u8]) -> Result<(), String> {
|
||||
let js = |e: wasm_bindgen::JsValue| format!("{e:?}");
|
||||
let window = web_sys::window().ok_or("no window")?;
|
||||
let document = window.document().ok_or("no document")?;
|
||||
|
||||
let iframe: web_sys::HtmlIFrameElement = document.create_element("iframe").map_err(js)?.dyn_into().map_err(|_| "not an iframe")?;
|
||||
iframe.style().set_property("display", "none").map_err(js)?;
|
||||
let body = document.body().ok_or("no body")?;
|
||||
|
||||
let parts = js_sys::Array::of1(&js_sys::Uint8Array::from(bytes));
|
||||
let opts = web_sys::BlobPropertyBag::new();
|
||||
opts.set_type("application/pdf");
|
||||
let blob = web_sys::Blob::new_with_u8_array_sequence_and_options(&parts, &opts).map_err(js)?;
|
||||
let url = web_sys::Url::create_object_url_with_blob(&blob).map_err(js)?;
|
||||
|
||||
if let Err(e) = body.append_child(&iframe) {
|
||||
cleanup_print(&iframe, &url);
|
||||
return Err(js(e));
|
||||
}
|
||||
|
||||
// `onload` fires once the PDF has actually rendered inside the iframe;
|
||||
// printing before that would show a blank page. Set the handler BEFORE
|
||||
// `src` so a fast/cached load can't fire before we're listening.
|
||||
let iframe_for_load = iframe.clone();
|
||||
let url_for_cleanup = url.clone();
|
||||
let on_load = wasm_bindgen::closure::Closure::once_into_js(move || {
|
||||
iframe_for_load.set_onload(None);
|
||||
if let Err(e) = print_loaded_pdf(&iframe_for_load, &url_for_cleanup) {
|
||||
cleanup_print(&iframe_for_load, &url_for_cleanup);
|
||||
log::error!("print failed: {e:?}");
|
||||
}
|
||||
});
|
||||
iframe.set_onload(Some(on_load.unchecked_ref()));
|
||||
iframe.set_src(&url);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn cleanup_print(iframe: &web_sys::HtmlIFrameElement, url: &str) {
|
||||
// Both operations are idempotent: print can fail after dispatching `afterprint`.
|
||||
web_sys::Url::revoke_object_url(url).ok();
|
||||
iframe.remove();
|
||||
}
|
||||
|
||||
fn print_loaded_pdf(iframe: &web_sys::HtmlIFrameElement, url: &str) -> Result<(), JsValue> {
|
||||
let content_window = iframe.content_window().ok_or_else(|| JsValue::from_str("no print content window"))?;
|
||||
let iframe_for_cleanup = iframe.clone();
|
||||
let url_for_cleanup = url.to_owned();
|
||||
let on_after_print = wasm_bindgen::closure::Closure::once(move || {
|
||||
cleanup_print(&iframe_for_cleanup, &url_for_cleanup);
|
||||
});
|
||||
// Listen before `print()`, which can dispatch `afterprint` before it returns.
|
||||
// A one-shot listener also releases the callback when the dialog closes or is cancelled.
|
||||
let options = web_sys::AddEventListenerOptions::new();
|
||||
options.set_once(true);
|
||||
let callback = on_after_print.as_ref().unchecked_ref();
|
||||
content_window.add_event_listener_with_callback_and_add_event_listener_options("afterprint", callback, &options)?;
|
||||
if let Err(e) = content_window.print() {
|
||||
let _ = content_window.remove_event_listener_with_callback("afterprint", callback);
|
||||
return Err(e);
|
||||
}
|
||||
let _ = on_after_print.into_js_value();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn mime_for(name: &str) -> &'static str {
|
||||
match name.rsplit('.').next().map(str::to_ascii_lowercase).as_deref() {
|
||||
Some("xlsx") => "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||
|
||||
@@ -58,7 +58,7 @@ impl SheetApp {
|
||||
self.printing.begin(submit(bytes, self.printing.settings.clone())).map_err(|_| "A print job is already being submitted.".to_owned())?;
|
||||
self.print_feedback_seen = None;
|
||||
} else if let Some(print) = &self.services.print {
|
||||
print(&bytes);
|
||||
print(&bytes)?;
|
||||
} else {
|
||||
return Err("Printing is unavailable here; export a PDF instead.".into());
|
||||
}
|
||||
|
||||
@@ -39,8 +39,10 @@ pub(super) fn print(app: &mut SheetApp, ui: &mut Ui, bs: &mut Backstage, out: &m
|
||||
if ui.add_enabled_ui(can_print, |ui| square_button(ui, Icon::Print, lang.tr("Print"))).inner.clicked()
|
||||
&& app.commit_edit(0, 0, false, false)
|
||||
{
|
||||
app.print_now(params.clone());
|
||||
out.close = app.services.print_native.is_none();
|
||||
match app.run("ui.printSubmit", params.clone()) {
|
||||
Ok(_) => out.close = app.services.print_native.is_none(),
|
||||
Err(error) => app.alert(error),
|
||||
}
|
||||
}
|
||||
ui.add_space(16.0);
|
||||
egui::ComboBox::from_id_salt("backstage_print_scope")
|
||||
|
||||
@@ -4,7 +4,7 @@ type PickSave = Box<dyn Fn(&str) -> Option<String>>;
|
||||
type OpenUrl = Box<dyn Fn(&str)>;
|
||||
type CopyHtml = Box<dyn FnMut(&str, &str) -> Result<(), String>>;
|
||||
type Download = Box<dyn Fn(&str, &[u8])>;
|
||||
type PrintPdf = Box<dyn Fn(&[u8])>;
|
||||
type PrintPdf = Box<dyn Fn(&[u8]) -> Result<(), String>>;
|
||||
|
||||
/// Host services the platform shell provides (file pickers, opening URLs).
|
||||
#[derive(Default)]
|
||||
|
||||
@@ -21,7 +21,10 @@ fn harness(jobs: Rc<RefCell<Vec<Vec<u8>>>>) -> egui_kittest::Harness<'static, Sh
|
||||
app.run("cell.set", json!({"cell": "H20", "input": "Outside"})).unwrap();
|
||||
app.run("pageLayout.pageSetup", json!({"printArea": "F10:H20"})).unwrap();
|
||||
app.run("selection.set", json!({"range": "A1:B2"})).unwrap();
|
||||
app.services.print = Some(Box::new(move |bytes| jobs.borrow_mut().push(bytes.to_vec())));
|
||||
app.services.print = Some(Box::new(move |bytes| {
|
||||
jobs.borrow_mut().push(bytes.to_vec());
|
||||
Ok(())
|
||||
}));
|
||||
app.run("ui.backstage", json!({"page": "print"})).unwrap();
|
||||
let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1000.0, 800.0)).build_ui_state(
|
||||
|ui, app: &mut SheetApp| {
|
||||
@@ -76,3 +79,30 @@ fn the_preview_follows_the_selection_and_each_area_gets_its_own_page() {
|
||||
h.run_steps(4);
|
||||
assert!(h.query_by_label("Page 1 of 2").is_some(), "two areas, two pages");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refused_browser_handoff_keeps_the_print_selection_available_for_retry() {
|
||||
let jobs = Rc::new(RefCell::new(Vec::new()));
|
||||
let mut h = harness(jobs.clone());
|
||||
choose_selection(&mut h);
|
||||
let accepted = h.state_mut().services.print.take();
|
||||
h.state_mut().services.print = Some(Box::new(|_| Err("The browser blocked the print window".into())));
|
||||
let error = h.state_mut().run("ui.printSubmit", json!({})).unwrap_err();
|
||||
assert!(error.contains("blocked the print window"));
|
||||
h.get_all_by_role_and_label(egui::accesskit::Role::Button, "Print").last().expect("Print button").click();
|
||||
h.run_steps(3);
|
||||
assert!(h.state().backstage.is_some());
|
||||
assert!(h.state().message.as_ref().unwrap().1.contains("blocked the print window"));
|
||||
assert!(jobs.borrow().is_empty());
|
||||
|
||||
h.state_mut().message = None;
|
||||
h.state_mut().services.print = accepted;
|
||||
h.run_steps(3);
|
||||
h.get_all_by_role_and_label(egui::accesskit::Role::Button, "Print").last().expect("Print button").click();
|
||||
h.run_steps(3);
|
||||
assert!(h.state().backstage.is_none());
|
||||
let jobs = jobs.borrow();
|
||||
assert_eq!(jobs.len(), 1);
|
||||
assert!(contains(&jobs[0], "(Inside) Tj"));
|
||||
assert!(!contains(&jobs[0], "(Outside) Tj"));
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user