mirror of
https://github.com/storytold/gridcraft.git
synced 2026-11-07 12:13:13 +00:00
gridcraft-web: speak the host messages through craft-web-host
The transports, the message types and the origin checks come from the shared crate (storytold/craft-libs#420); GridCraft keeps the download hook, the open size limit, the workbook-saved rule and the author.
This commit is contained in:
Generated
+10
@@ -995,6 +995,15 @@ dependencies = [
|
||||
"zip 9.1.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-web-host"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=2e2312ddaf21bc3d85cd3395d0955c7d239306f6#2e2312ddaf21bc3d85cd3395d0955c7d239306f6"
|
||||
dependencies = [
|
||||
"wasm-bindgen",
|
||||
"web-sys",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-window"
|
||||
version = "0.1.0"
|
||||
@@ -2186,6 +2195,7 @@ dependencies = [
|
||||
name = "gridcraft-web"
|
||||
version = "0.16.0"
|
||||
dependencies = [
|
||||
"craft-web-host",
|
||||
"eframe",
|
||||
"egui",
|
||||
"gridcraft-engine",
|
||||
|
||||
@@ -16,6 +16,8 @@ path = "src/main.rs"
|
||||
[dependencies]
|
||||
gridcraft-engine = { workspace = true }
|
||||
gridcraft-ui-egui = { workspace = true }
|
||||
# The host messages (storytold/craft-libs): one contract and one bridge for the web builds.
|
||||
craft-web-host = { git = "https://github.com/storytold/craft-libs", rev = "2e2312ddaf21bc3d85cd3395d0955c7d239306f6", version = "0.1.0" }
|
||||
egui = { workspace = true }
|
||||
log = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
|
||||
+54
-187
@@ -1,127 +1,61 @@
|
||||
//! Host modes: a page that runs GridCraft (as an iframe, or in its own document) opens workbooks
|
||||
//! in it and stores what it saves instead of the browser downloading.
|
||||
//! in it and stores what it saves instead of the browser downloading. The messages and the two
|
||||
//! transports are `craft-web-host`'s (storytold/craft-libs), the same contract as the other Craft
|
||||
//! apps' bridges, with the `gridcraft:` prefix. This module is GridCraft's part of it.
|
||||
//!
|
||||
//! ## `?host=parent` — an `<iframe>` (such as a Nextcloud app)
|
||||
//!
|
||||
//! The framing page and GridCraft talk over `postMessage` between same-origin windows. Messages
|
||||
//! are plain objects with a `type`:
|
||||
//!
|
||||
//! - `gridcraft:ready` (to the parent): `{ version }`, the app is listening; send a file now.
|
||||
//! - `gridcraft:open` (from the parent): `{ name, bytes }`, bytes an `ArrayBuffer` or
|
||||
//! `Uint8Array`. It opens like a workbook picked with File › Open or dropped on the window.
|
||||
//! - `gridcraft:save` (to the parent): `{ name, bytes }` (a transferred `ArrayBuffer`) for every
|
||||
//! file GridCraft would otherwise download: Save and Save As (an .xlsx workbook) and Export
|
||||
//! as PDF. The parent stores it and reports failures itself.
|
||||
//! - `gridcraft:dirty` (to the parent): `{ dirty }` whenever unsaved changes appear or go away.
|
||||
//! - `gridcraft:failed` (to the parent): `{ error }` when the app couldn't start.
|
||||
//!
|
||||
//! Only the parent window on the page's own origin is heard or answered.
|
||||
//!
|
||||
//! ## `data-host="page"` — the page's own document
|
||||
//!
|
||||
//! A page that loads the module into its own document (its own `<canvas id="gridcraft_canvas">`
|
||||
//! with `data-host="page"`, no iframe) gets the same behaviour over DOM `CustomEvent`s on the
|
||||
//! canvas instead of `postMessage`: the same four events outward (`ready`, `save`, `dirty`,
|
||||
//! `failed`, with the message fields as the event's `detail`), and the page dispatches
|
||||
//! `gridcraft:open` on the canvas with `detail: { name, bytes }` to open a workbook. Events don't
|
||||
//! bubble, so two editors on one page can't hear each other, and the canvas is the only target
|
||||
//! GridCraft listens on.
|
||||
//! - `?host=parent` (an `<iframe>`, such as a Nextcloud app) talks to the same-origin parent over
|
||||
//! `postMessage`; `data-host="page"` on the canvas (the page's own document, no iframe) uses
|
||||
//! DOM `CustomEvent`s on the canvas instead. `?host=parent` wins when both are present. With no
|
||||
//! parent, or a parent on another origin, there is no bridge: the normal app with downloads.
|
||||
//! - `gridcraft:ready` once the app is listening; send a file now. GridCraft reads bytes, so it
|
||||
//! says `file: false` and a host sends `bytes`.
|
||||
//! - `gridcraft:open` (from the host): `{ name, bytes }`. It opens like a workbook picked with
|
||||
//! File › Open or dropped on the window; a file over [`MAX_OPEN_BYTES`] is refused before it is
|
||||
//! copied.
|
||||
//! - `gridcraft:save` (to the host): `{ name, saveAs, bytes }` for every file GridCraft would
|
||||
//! otherwise download: Save and Save As (an .xlsx workbook) and Export as PDF. The host stores
|
||||
//! it and reports failures itself. GridCraft doesn't tell the host which saves make a file the
|
||||
//! document, so `saveAs` is always `false`.
|
||||
//! - `gridcraft:dirty` whenever unsaved changes appear or go away, `gridcraft:failed` when the
|
||||
//! app couldn't start.
|
||||
//!
|
||||
//! In both host modes the page starts with an empty workbook instead of a sample, saves and PDF
|
||||
//! exports are handed to the page rather than downloaded, and `?author=` names the user for new
|
||||
//! notes and comments.
|
||||
|
||||
use std::cell::{Cell, RefCell};
|
||||
use std::cell::RefCell;
|
||||
use std::rc::Rc;
|
||||
|
||||
use craft_web_host::web::{FileData, Host, Message};
|
||||
use gridcraft_ui_egui::{Inbox, Services, SheetApp};
|
||||
use wasm_bindgen::JsCast as _;
|
||||
use wasm_bindgen::JsValue;
|
||||
use wasm_bindgen::closure::Closure;
|
||||
|
||||
use crate::hostmode::open_name;
|
||||
|
||||
/// Saving one of these hands the whole workbook to the host, which stores it: the workbook
|
||||
/// counts as saved under that name, as it would after Save on the desktop.
|
||||
/// The app id in the host messages (`gridcraft:ready`).
|
||||
const APP: &str = "gridcraft";
|
||||
|
||||
/// Saved files that count as a workbook: the document is then clean under the name it was saved as.
|
||||
const WORKBOOK_EXTS: &[&str] = &["xlsx"];
|
||||
|
||||
/// The largest file the host may hand over to open, checked before it is copied (the app's own readers have their own limits).
|
||||
/// The largest workbook taken from the host page, refused before it is copied.
|
||||
const MAX_OPEN_BYTES: u64 = 512 << 20;
|
||||
|
||||
/// The longest file name taken from the host.
|
||||
const MAX_NAME_CHARS: usize = 255;
|
||||
|
||||
/// The longest user name taken from `?author=`.
|
||||
const MAX_AUTHOR_CHARS: usize = 200;
|
||||
|
||||
/// How a host page is reached. The modes behave the same; they differ only in how an event goes
|
||||
/// out ([`Transport::send`]) and how an open request comes in ([`Bridge::listen`]).
|
||||
#[derive(Clone)]
|
||||
enum Transport {
|
||||
/// `?host=parent`: `postMessage` between same-origin windows.
|
||||
Parent { window: web_sys::Window, parent: web_sys::Window, origin: String },
|
||||
/// `data-host="page"`: DOM `CustomEvent`s on the editor's own canvas.
|
||||
Page { canvas: web_sys::HtmlCanvasElement },
|
||||
}
|
||||
|
||||
impl Transport {
|
||||
/// Hand an event to the host. In parent mode this is a `postMessage` with a `type` field; in
|
||||
/// page mode a `CustomEvent` of that name on the canvas, whose `detail` holds the fields and
|
||||
/// which never bubbles (two editors on one page must not hear each other).
|
||||
fn send(&self, event: &str, fields: &[(&str, JsValue)], transfer: Option<&js_sys::ArrayBuffer>) -> Result<(), String> {
|
||||
match self {
|
||||
Transport::Parent { parent, origin, .. } => {
|
||||
let mut message_fields = Vec::with_capacity(fields.len() + 1);
|
||||
message_fields.push(("type", JsValue::from_str(event)));
|
||||
message_fields.extend_from_slice(fields);
|
||||
let message = message(&message_fields).ok_or_else(|| "couldn't build the message".to_string())?;
|
||||
let sent = match transfer {
|
||||
Some(buffer) => parent.post_message_with_transfer(&message, origin, &js_sys::Array::of1(buffer)),
|
||||
// `None` is only ever passed for the parent mode's small events; the page mode
|
||||
// can't transfer anyway (below).
|
||||
None => parent.post_message(&message, origin),
|
||||
};
|
||||
sent.map_err(|e| js_error(&e, "couldn't post the message"))
|
||||
}
|
||||
Transport::Page { canvas } => {
|
||||
let detail = message(fields).ok_or_else(|| "couldn't build the event detail".to_string())?;
|
||||
let init = web_sys::CustomEventInit::new();
|
||||
init.set_bubbles(false);
|
||||
init.set_detail(&detail);
|
||||
let custom = web_sys::CustomEvent::new_with_event_init_dict(event, &init).map_err(|e| js_error(&e, "couldn't create the event"))?;
|
||||
canvas.dispatch_event(&custom).map_err(|e| js_error(&e, "couldn't dispatch the event"))?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct Bridge {
|
||||
transport: Transport,
|
||||
host: Rc<Host>,
|
||||
/// Names of the files handed to the host since the last frame.
|
||||
saved: Rc<RefCell<Vec<String>>>,
|
||||
/// The unsaved-changes state last reported to the host.
|
||||
reported: Rc<Cell<Option<bool>>>,
|
||||
}
|
||||
|
||||
impl Bridge {
|
||||
/// The parent bridge for `?host=parent`; `None` when the page isn't framed (there is no
|
||||
/// parent to talk to), so opening that URL directly stays the normal app with downloads.
|
||||
pub fn new() -> Option<Self> {
|
||||
let window = web_sys::window()?;
|
||||
let parent = window.parent().ok().flatten()?;
|
||||
if js_sys::Object::is(&parent, &window) {
|
||||
return None;
|
||||
}
|
||||
let origin = window.location().origin().ok()?;
|
||||
Some(Self { transport: Transport::Parent { window, parent, origin }, saved: Rc::default(), reported: Rc::default() })
|
||||
}
|
||||
|
||||
/// The page bridge for `data-host="page"`: the host page runs GridCraft in its own document
|
||||
/// and hears the editor's DOM `CustomEvent`s on this canvas.
|
||||
pub fn for_page(canvas: &web_sys::HtmlCanvasElement) -> Self {
|
||||
Self { transport: Transport::Page { canvas: canvas.clone() }, saved: Rc::default(), reported: Rc::default() }
|
||||
/// The bridge for this page, or `None` when GridCraft isn't hosted: no `?host=parent` and no
|
||||
/// `data-host="page"` on the canvas, an unframed `?host=parent` page (it stays the normal app
|
||||
/// with downloads), or a parent on another origin.
|
||||
pub fn detect(canvas: &web_sys::HtmlCanvasElement) -> Option<Self> {
|
||||
Some(Self { host: Rc::new(Host::connect(APP, canvas)?), saved: Rc::default() })
|
||||
}
|
||||
|
||||
/// Send saved and exported files to the host instead of downloading them, and hear files
|
||||
@@ -145,15 +79,16 @@ impl Bridge {
|
||||
}
|
||||
|
||||
pub fn post_ready(&self) {
|
||||
let _ = self.transport.send("gridcraft:ready", &[("version", env!("CARGO_PKG_VERSION").into())], None);
|
||||
let _ = self.host.post_ready(env!("CARGO_PKG_VERSION"), false);
|
||||
}
|
||||
|
||||
pub fn post_failed(&self, error: &str) {
|
||||
let _ = self.transport.send("gridcraft:failed", &[("error", error.into())], None);
|
||||
let _ = self.host.post_failed(error, None);
|
||||
}
|
||||
|
||||
/// After each frame: a workbook handed to the host this frame counts as saved under the
|
||||
/// name it was saved as, and the host hears when unsaved changes appear or go away.
|
||||
/// name it was saved as, and the host hears when unsaved changes appear or go away (the
|
||||
/// crate does not repeat a state it already reported).
|
||||
pub fn sync(&self, app: &mut SheetApp) {
|
||||
let saved = std::mem::take(&mut *self.saved.borrow_mut());
|
||||
if let Some(name) = saved.iter().rev().find(|name| is_workbook(name))
|
||||
@@ -164,70 +99,39 @@ impl Bridge {
|
||||
doc.title = name.clone();
|
||||
}
|
||||
}
|
||||
let dirty = app.session.documents().iter().any(|d| d.is_dirty());
|
||||
if self.reported.get() != Some(dirty) && self.transport.send("gridcraft:dirty", &[("dirty", dirty.into())], None).is_ok() {
|
||||
self.reported.set(Some(dirty));
|
||||
}
|
||||
self.host.post_dirty(app.session.documents().iter().any(|d| d.is_dirty()));
|
||||
}
|
||||
|
||||
fn post_save(&self, path: &str, bytes: &[u8]) -> Result<(), String> {
|
||||
let name = file_name(path);
|
||||
// `gridcraft:save` carries the bytes as an `ArrayBuffer`; the parent bridge transfers it.
|
||||
let buffer = js_sys::Uint8Array::from(bytes).buffer();
|
||||
self.transport.send("gridcraft:save", &[("name", name.as_str().into()), ("bytes", buffer.clone().into())], Some(&buffer))?;
|
||||
self.host.post_save(&name, bytes, None, false)?;
|
||||
self.saved.borrow_mut().push(name);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn listen(&self, inbox: Inbox, ctx: egui::Context) {
|
||||
match &self.transport {
|
||||
Transport::Parent { window, parent, origin } => {
|
||||
let parent = parent.clone();
|
||||
let origin = origin.clone();
|
||||
let on_message = Closure::<dyn FnMut(web_sys::MessageEvent)>::new(move |event: web_sys::MessageEvent| {
|
||||
if event.origin() != origin || !event.source().is_some_and(|s| js_sys::Object::is(&s, &parent)) {
|
||||
return;
|
||||
}
|
||||
let data = event.data();
|
||||
if string(&data, "type").as_deref() != Some("gridcraft:open") {
|
||||
return;
|
||||
}
|
||||
deliver_open(&inbox, &ctx, &data);
|
||||
});
|
||||
if window.add_event_listener_with_callback("message", on_message.as_ref().unchecked_ref()).is_ok() {
|
||||
// The listener lives as long as the page.
|
||||
on_message.forget();
|
||||
}
|
||||
self.host.listen(move |message| {
|
||||
if let Message::Open { name, data } = message {
|
||||
deliver_open(&inbox, &ctx, &name, &data);
|
||||
}
|
||||
Transport::Page { canvas } => {
|
||||
let on_open = Closure::<dyn FnMut(web_sys::Event)>::new(move |event: web_sys::Event| {
|
||||
let Some(open) = event.dyn_ref::<web_sys::CustomEvent>() else { return };
|
||||
let detail = open.detail();
|
||||
deliver_open(&inbox, &ctx, &detail);
|
||||
});
|
||||
if canvas.add_event_listener_with_callback("gridcraft:open", on_open.as_ref().unchecked_ref()).is_ok() {
|
||||
// The listener lives as long as the page.
|
||||
on_open.forget();
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// The file an open message or event carries, pushed onto the inbox for the next frame, like a
|
||||
/// dropped file.
|
||||
fn deliver_open(inbox: &Inbox, ctx: &egui::Context, data: &JsValue) {
|
||||
if let Some((name, bytes)) = open_payload(data) {
|
||||
inbox.lock().unwrap_or_else(|e| e.into_inner()).push((name, bytes));
|
||||
ctx.request_repaint();
|
||||
/// The file an open message carries, pushed onto the inbox for the next frame, like a dropped
|
||||
/// file. A host's file is untrusted input: an oversized one is refused before it is copied into
|
||||
/// the app's memory (the data's own length, not the host's claim).
|
||||
fn deliver_open(inbox: &Inbox, ctx: &egui::Context, name: &str, data: &FileData) {
|
||||
let FileData::Bytes(array) = data else {
|
||||
log::warn!("host file {name} came as a File; GridCraft reads bytes only; not opened");
|
||||
return;
|
||||
};
|
||||
if data.size() > MAX_OPEN_BYTES as f64 {
|
||||
log::warn!("host file is {} bytes, over the {} MiB host open limit; not opened", data.size(), MAX_OPEN_BYTES >> 20);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
/// The file an open message or event carries: a usable name and the bytes.
|
||||
fn open_payload(data: &JsValue) -> Option<(String, Vec<u8>)> {
|
||||
let name: String = open_name(string(data, "name").as_deref()).chars().take(MAX_NAME_CHARS).collect();
|
||||
let bytes = bytes(data)?;
|
||||
Some((name, bytes))
|
||||
inbox.lock().unwrap_or_else(|e| e.into_inner()).push((open_name(name), array.to_vec()));
|
||||
ctx.request_repaint();
|
||||
}
|
||||
|
||||
fn is_workbook(name: &str) -> bool {
|
||||
@@ -237,40 +141,3 @@ fn is_workbook(name: &str) -> bool {
|
||||
fn file_name(path: &str) -> String {
|
||||
std::path::Path::new(path).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| path.to_string())
|
||||
}
|
||||
|
||||
/// A message object or `CustomEvent` detail with the given fields, or `None` if one couldn't be
|
||||
/// set.
|
||||
fn message(fields: &[(&str, JsValue)]) -> Option<js_sys::Object> {
|
||||
let m = js_sys::Object::new();
|
||||
for (key, value) in fields {
|
||||
js_sys::Reflect::set(&m, &JsValue::from_str(key), value).ok()?;
|
||||
}
|
||||
Some(m)
|
||||
}
|
||||
|
||||
fn string(data: &JsValue, key: &str) -> Option<String> {
|
||||
js_sys::Reflect::get(data, &JsValue::from_str(key)).ok()?.as_string()
|
||||
}
|
||||
|
||||
/// `bytes` as an `ArrayBuffer` or `Uint8Array`.
|
||||
fn bytes(data: &JsValue) -> Option<Vec<u8>> {
|
||||
let bytes = js_sys::Reflect::get(data, &JsValue::from_str("bytes")).ok()?;
|
||||
let view = if let Some(array) = bytes.dyn_ref::<js_sys::Uint8Array>() {
|
||||
array.clone()
|
||||
} else if bytes.is_instance_of::<js_sys::ArrayBuffer>() {
|
||||
js_sys::Uint8Array::new(&bytes)
|
||||
} else {
|
||||
return None;
|
||||
};
|
||||
// A file from the host is untrusted input: refuse an oversized one before copying it into the app's memory.
|
||||
if u64::from(view.length()) > MAX_OPEN_BYTES {
|
||||
log::warn!("host file is {} bytes, over the {} MiB host open limit; not opened", view.length(), MAX_OPEN_BYTES >> 20);
|
||||
return None;
|
||||
}
|
||||
Some(view.to_vec())
|
||||
}
|
||||
|
||||
/// A `JsValue` error as a string, after `what` went wrong.
|
||||
fn js_error(e: &JsValue, what: &str) -> String {
|
||||
format!("{what}: {}", e.as_string().unwrap_or_else(|| format!("{e:?}")))
|
||||
}
|
||||
|
||||
@@ -1,23 +1,18 @@
|
||||
//! Pure host-mode rules, shared by the bridge ([`crate::host`]) and testable without a browser
|
||||
//! (like [`crate::prefs`]): what opts a page into hosting GridCraft in its own document, and the
|
||||
//! name the bridge fills in when a host's open request has none.
|
||||
|
||||
/// The one `data-host` value that opts a page in: the exact string `"page"`.
|
||||
pub const PAGE_HOST: &str = "page";
|
||||
//! (like [`crate::prefs`]): the name the bridge fills in when a host's open request has none.
|
||||
//! Which pages host the app is `craft-web-host`'s.
|
||||
|
||||
/// The file name used when an open request carries no usable one.
|
||||
pub const DEFAULT_OPEN_NAME: &str = "Book.xlsx";
|
||||
|
||||
/// Does this `data-host` value ask for page host mode? Only the exact value [`PAGE_HOST`] counts;
|
||||
/// anything else is ignored, so the page host mode stays opt-in.
|
||||
pub fn page_host_requested(data_host: Option<&str>) -> bool {
|
||||
data_host == Some(PAGE_HOST)
|
||||
}
|
||||
/// The name `craft-web-host` gives an open request that carries no usable one (it cleans a host's
|
||||
/// name and falls back to this).
|
||||
const NAMELESS: &str = "document";
|
||||
|
||||
/// A usable file name for an open request: the host's name when it isn't blank, else the
|
||||
/// [`DEFAULT_OPEN_NAME`].
|
||||
pub fn open_name(name: Option<&str>) -> String {
|
||||
name.filter(|n| !n.trim().is_empty()).unwrap_or(DEFAULT_OPEN_NAME).to_string()
|
||||
/// A usable file name for an open request: the cleaned name the crate hands over, or
|
||||
/// [`DEFAULT_OPEN_NAME`] when the host sent none.
|
||||
pub fn open_name(name: &str) -> String {
|
||||
if name == NAMELESS { DEFAULT_OPEN_NAME.to_string() } else { name.to_string() }
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -25,21 +20,9 @@ mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn only_the_exact_page_value_opts_in() {
|
||||
assert!(page_host_requested(Some("page")));
|
||||
assert!(!page_host_requested(Some("Page")));
|
||||
assert!(!page_host_requested(Some(" page")));
|
||||
assert!(!page_host_requested(Some("parent")));
|
||||
assert!(!page_host_requested(Some("")));
|
||||
assert!(!page_host_requested(None));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn open_names_fall_back_to_the_default_when_blank() {
|
||||
assert_eq!(open_name(Some("Budget.xlsx")), "Budget.xlsx");
|
||||
assert_eq!(open_name(Some(" Sheet2!Book.xlsx ")), " Sheet2!Book.xlsx ");
|
||||
assert_eq!(open_name(Some("")), DEFAULT_OPEN_NAME);
|
||||
assert_eq!(open_name(Some(" ")), DEFAULT_OPEN_NAME);
|
||||
assert_eq!(open_name(None), DEFAULT_OPEN_NAME);
|
||||
fn open_names_fall_back_to_the_default_when_the_host_sent_none() {
|
||||
assert_eq!(open_name("Budget.xlsx"), "Budget.xlsx");
|
||||
assert_eq!(open_name("Sheet2!Book.xlsx"), "Sheet2!Book.xlsx");
|
||||
assert_eq!(open_name("document"), DEFAULT_OPEN_NAME, "what the crate says for a missing or blank name");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -37,18 +37,12 @@ pub fn start() {
|
||||
{
|
||||
create.instance_descriptor.backends = eframe::wgpu::Backends::GL;
|
||||
}
|
||||
// `?host=parent`: a same-origin page framing GridCraft (such as a Nextcloud app) opens
|
||||
// workbooks in it and stores what it saves (`host`). Unframed there is no parent, so that
|
||||
// URL on its own stays the normal app with downloads. `data-host="page"` on the canvas
|
||||
// opts a page in instead: it runs GridCraft in its own document and talks over DOM
|
||||
// `CustomEvent`s on the canvas (`host`).
|
||||
let bridge = if query_param("host").as_deref() == Some("parent") {
|
||||
crate::host::Bridge::new()
|
||||
} else if crate::hostmode::page_host_requested(canvas.get_attribute("data-host").as_deref()) {
|
||||
Some(crate::host::Bridge::for_page(&canvas))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
// Host modes (`craft-web-host`): `?host=parent`, a same-origin page framing GridCraft (such
|
||||
// as a Nextcloud app), opens workbooks in it and stores what it saves (`host`). Unframed
|
||||
// there is no parent, so that URL on its own stays the normal app with downloads.
|
||||
// `data-host="page"` on the canvas opts a page in instead: it runs GridCraft in its own
|
||||
// document and talks over DOM `CustomEvent`s on the canvas.
|
||||
let bridge = crate::host::Bridge::detect(&canvas);
|
||||
let app_bridge = bridge.clone();
|
||||
let result = eframe::WebRunner::new()
|
||||
.start(
|
||||
|
||||
@@ -87,7 +87,7 @@ downloading them. The two sides talk `postMessage` with plain window messages th
|
||||
|
||||
| Message | Direction | Fields |
|
||||
|---|---|---|
|
||||
| `gridcraft:ready` | app → page | `version`: the app is listening; send a file now |
|
||||
| `gridcraft:ready` | app → page | `version`, `appVersion`: the app is listening; send a file now |
|
||||
| `gridcraft:open` | page → app | `name`, `bytes` (an `ArrayBuffer` or `Uint8Array`): open like File › Open |
|
||||
| `gridcraft:save` | app → page | `name`, `bytes` (a transferred `ArrayBuffer`): every file the app would otherwise download (Save, Save As, Export as PDF). The page stores it and reports failures itself. |
|
||||
| `gridcraft:dirty` | app → page | `dirty`: unsaved changes appeared or went away |
|
||||
@@ -149,6 +149,8 @@ As with the parent bridge, the app starts with an empty workbook instead of a sa
|
||||
must be exactly `page`; anything else is ignored, and the app runs as a standalone page with
|
||||
downloads.
|
||||
|
||||
The messages and both transports are the shared contract of [`craft-web-host`](https://github.com/storytold/craft-libs/tree/main/crates/web-host) (storytold/craft-libs#420), the same for every Craft app: its README lists every message, including `saved`, with the compatibility notes. In `gridcraft:ready`, `version` is the contract's (`"1"`) and `appVersion` is this app's release. GridCraft reads bytes, so a host sends `bytes`, not a `File`.
|
||||
|
||||
### Trust and limits
|
||||
|
||||
- **Who is trusted.** In page host mode the page and GridCraft share one document, so any script on the page can drive the app: open files in it and receive what it saves. Use this mode only for a page you control. The iframe mode (`?host=parent`) answers only the parent window, on the page's own origin.
|
||||
|
||||
Reference in New Issue
Block a user