mirror of
https://github.com/storytold/wordcraft.git
synced 2026-11-08 03:32:19 +00:00
wordcraft-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); WordCraft keeps the host save and dirty hooks, the saveAs rule, the open size limit and the author.
This commit is contained in:
1 parent
22989a77da
commit
5a8e6e4894
7 files changed
+74
-231
No files matched your search
Generated
+10
@@ -1157,6 +1157,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"
|
||||
@@ -7085,6 +7094,7 @@ dependencies = [
|
||||
name = "wordcraft-web"
|
||||
version = "0.15.1"
|
||||
dependencies = [
|
||||
"craft-web-host",
|
||||
"eframe",
|
||||
"egui",
|
||||
"js-sys",
|
||||
|
||||
@@ -16,6 +16,8 @@ path = "src/main.rs"
|
||||
[dependencies]
|
||||
wordcraft-engine = { workspace = true }
|
||||
wordcraft-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 }
|
||||
|
||||
+57
-198
@@ -1,19 +1,20 @@
|
||||
//! Host modes: a page that runs WordCraft (as an `<iframe>`, or in its own document) opens
|
||||
//! documents in it and stores what it saves instead of the browser downloading. The same
|
||||
//! messages as GridCraft's and PdfCraft's bridges.
|
||||
//! documents 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 `wordcraft:` prefix. This module is WordCraft's part of it.
|
||||
//!
|
||||
//! ## `?host=parent` — an `<iframe>` (such as a Nextcloud app)
|
||||
//!
|
||||
//! The framing page and WordCraft talk over `postMessage` between same-origin windows. Messages
|
||||
//! are plain objects with a `type`:
|
||||
//!
|
||||
//! - `wordcraft:ready` (to the parent): `{ version }`, sent once the app is running and
|
||||
//! listening; send a file now.
|
||||
//! - `wordcraft:open` (from the parent): `{ name, bytes }`, bytes an `ArrayBuffer` or
|
||||
//! `Uint8Array`. It opens like a document picked with File › Open or dropped on the window.
|
||||
//! - `wordcraft:save` (to the parent): `{ name, saveAs, bytes }` (a transferred `ArrayBuffer`) for
|
||||
//! every file WordCraft would otherwise download. The parent stores it and reports failures
|
||||
//! itself. `saveAs` says whether the file becomes the document's file:
|
||||
//! - `?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.
|
||||
//! - `wordcraft:ready` once the app is running and listening; send a file now. WordCraft reads
|
||||
//! bytes, so it says `file: false` and a host sends `bytes`.
|
||||
//! - `wordcraft:open` (from the host): `{ name, bytes }`. It opens like a document picked with
|
||||
//! File › Open or dropped on the window; a file over [`MAX_OPEN_BYTES`] is refused before it is
|
||||
//! copied.
|
||||
//! - `wordcraft:save` (to the host): `{ name, saveAs, bytes }` for every file WordCraft would
|
||||
//! otherwise download. The host stores it and reports failures itself. `saveAs` says whether
|
||||
//! the file becomes the document's file:
|
||||
//! - Save: `false`. It writes the opened file under its own name and format, as the desktop
|
||||
//! app does. A name the parent never sent (an untitled document, an imported .doc saved as
|
||||
//! .docx) is a new file: `true`, as for Save As.
|
||||
@@ -22,119 +23,41 @@
|
||||
//! is now that file; the next Save sends its name with `false`.
|
||||
//! - Save As or Export to a format that doesn't (PDF, Markdown, plain text), Export as PDF and
|
||||
//! Export Page as PNG: `false`. They are copies; the document's file stays the same.
|
||||
//! - `wordcraft:dirty` (to the parent): `{ dirty }` whenever unsaved changes appear or go away.
|
||||
//! - `wordcraft: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="wordcraft_canvas"
|
||||
//! 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 `wordcraft:open` on
|
||||
//! the canvas with `detail: { name, bytes }` to open a document. Events don't bubble, so two
|
||||
//! editors on one page can't hear each other, and the canvas is the only target WordCraft
|
||||
//! listens on.
|
||||
//! - `wordcraft:dirty` whenever unsaved changes appear or go away, `wordcraft:failed` when the
|
||||
//! app couldn't start.
|
||||
//!
|
||||
//! In both host modes the host sends the document to edit, so no sample opens, saves are handed
|
||||
//! to the host rather than downloaded, the host guards leaving the page, and `?author=` names the
|
||||
//! user for comments and tracked changes.
|
||||
|
||||
use std::cell::Cell;
|
||||
use std::rc::Rc;
|
||||
|
||||
use wasm_bindgen::JsCast as _;
|
||||
use wasm_bindgen::JsValue;
|
||||
use wasm_bindgen::closure::Closure;
|
||||
use craft_web_host::web::{FileData, Host, Message};
|
||||
use wordcraft_ui_egui::{Inbox, Services, WordApp};
|
||||
|
||||
/// The largest file the host may hand over to open, checked before it is copied (the app's own readers have their own limits).
|
||||
const MAX_OPEN_BYTES: u64 = 512 << 20;
|
||||
/// The app id in the host messages (`wordcraft:ready`).
|
||||
const APP: &str = "wordcraft";
|
||||
|
||||
/// The longest file name taken from the host.
|
||||
const MAX_NAME_CHARS: usize = 255;
|
||||
/// The name a document gets when the host sent none (the crate says `document` for a blank name).
|
||||
const DEFAULT_NAME: &str = "Document.docx";
|
||||
|
||||
/// The largest document taken from the host page, refused before it is copied.
|
||||
const MAX_OPEN_BYTES: u64 = 512 << 20;
|
||||
|
||||
/// 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` whose object carries 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). `transfer` hands an `ArrayBuffer` to the parent instead of copying it (parent
|
||||
/// mode only; the page's document already shares the buffer's bytes).
|
||||
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 => 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();
|
||||
// The builder methods (`bubbles(..)`, `detail(..)`) are deprecated in web-sys
|
||||
// 0.3.106 and fail clippy -D warnings; use the setters.
|
||||
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"))?;
|
||||
// A listener calling `preventDefault` would be the bool; not a send failure.
|
||||
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>,
|
||||
}
|
||||
|
||||
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, or
|
||||
/// when the parent is on another origin: messages only go to this origin, so the browser
|
||||
/// would drop every save without an error while the document showed as saved.
|
||||
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()?;
|
||||
// An opaque origin (a `file://` page in some browsers) can't be a `postMessage` target.
|
||||
if origin == "null" {
|
||||
return None;
|
||||
}
|
||||
// Reading another origin's location throws, which is `None` too.
|
||||
if parent.location().origin().ok()? != origin {
|
||||
return None;
|
||||
}
|
||||
Some(Self { transport: Transport::Parent { window, parent, origin } })
|
||||
}
|
||||
|
||||
/// The page bridge for `data-host="page"`: the host page runs WordCraft 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() } }
|
||||
/// The bridge for this page, or `None` when WordCraft 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)?) })
|
||||
}
|
||||
|
||||
/// Hand saved and exported files to the host instead of downloading them, report unsaved
|
||||
@@ -148,13 +71,9 @@ impl Bridge {
|
||||
services.download = Some(Box::new(move |name: &str, bytes: &[u8]| bridge.post_save(name, bytes, false)));
|
||||
// The browser's save picker is never used, so no save finishes later.
|
||||
services.async_saves = None;
|
||||
let bridge = self.clone();
|
||||
let reported: Rc<Cell<Option<bool>>> = Rc::default();
|
||||
services.on_dirty = Some(Box::new(move |dirty: bool| {
|
||||
if reported.get() != Some(dirty) && bridge.transport.send("wordcraft:dirty", &[("dirty", dirty.into())], None).is_ok() {
|
||||
reported.set(Some(dirty));
|
||||
}
|
||||
}));
|
||||
// The crate does not repeat a state it already reported.
|
||||
let host = self.host.clone();
|
||||
services.on_dirty = Some(Box::new(move |dirty: bool| host.post_dirty(dirty)));
|
||||
}
|
||||
|
||||
/// `?author=`: the host's name for the user signs comments and tracked changes.
|
||||
@@ -166,103 +85,43 @@ impl Bridge {
|
||||
}
|
||||
|
||||
pub fn post_ready(&self) {
|
||||
let _ = self.transport.send("wordcraft:ready", &[("version", env!("CARGO_PKG_VERSION").into())], None);
|
||||
let _ = self.host.post_ready(env!("CARGO_PKG_VERSION"), false);
|
||||
}
|
||||
|
||||
/// The app couldn't start (no WebGPU or WebGL2, for example): let the host say so.
|
||||
pub fn post_failed(&self, error: &str) {
|
||||
let _ = self.transport.send("wordcraft:failed", &[("error", error.into())], None);
|
||||
let _ = self.host.post_failed(error, None);
|
||||
}
|
||||
|
||||
fn post_save(&self, path: &str, bytes: &[u8], save_as: bool) -> Result<(), String> {
|
||||
let name = std::path::Path::new(path).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| path.to_string());
|
||||
// `wordcraft:save` carries the bytes as an `ArrayBuffer`; the parent bridge transfers it.
|
||||
let buffer = js_sys::Uint8Array::from(bytes).buffer();
|
||||
let fields: [(&str, JsValue); 3] = [("name", name.as_str().into()), ("saveAs", save_as.into()), ("bytes", buffer.clone().into())];
|
||||
self.transport.send("wordcraft:save", &fields, Some(&buffer))
|
||||
self.host.post_save(&name, bytes, None, save_as)
|
||||
}
|
||||
|
||||
/// Hear `wordcraft:open` — from the same-origin parent (a `message` on the window) or from
|
||||
/// the host document (a `wordcraft:open` event on the canvas) — and queue the file like a
|
||||
/// dropped one.
|
||||
/// Hear `wordcraft:open` and queue the file like a dropped one.
|
||||
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("wordcraft: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| {
|
||||
// A plain `Event` of the same name carries no detail; only a `CustomEvent`.
|
||||
let Some(open) = event.dyn_ref::<web_sys::CustomEvent>() else { return };
|
||||
deliver_open(&inbox, &ctx, &open.detail());
|
||||
});
|
||||
if canvas.add_event_listener_with_callback("wordcraft: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) {
|
||||
let name: String =
|
||||
string(data, "name").filter(|n| !n.trim().is_empty()).unwrap_or_else(|| "Document.docx".to_string()).chars().take(MAX_NAME_CHARS).collect();
|
||||
let Some(bytes) = bytes(data) else { return };
|
||||
inbox.lock().unwrap_or_else(|e| e.into_inner()).push((name, bytes));
|
||||
/// 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). The crate has cleaned the name
|
||||
/// (and cut it to 255 characters); a blank one comes as `document` and becomes `Document.docx`.
|
||||
fn deliver_open(inbox: &Inbox, ctx: &egui::Context, name: &str, data: &FileData) {
|
||||
let name = if name == "document" { DEFAULT_NAME } else { name }.to_string();
|
||||
let FileData::Bytes(array) = data else {
|
||||
log::warn!("host file {name} came as a File; WordCraft 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;
|
||||
}
|
||||
inbox.lock().unwrap_or_else(|e| e.into_inner()).push((name, array.to_vec()));
|
||||
ctx.request_repaint();
|
||||
}
|
||||
|
||||
/// A message object or `CustomEvent` detail with the given fields, or `None` if one couldn't be
|
||||
/// built (a field that isn't a valid property name, say).
|
||||
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,22 +0,0 @@
|
||||
//! Pure host-mode rules, shared by the bridge ([`crate::host`]) and testable without a browser
|
||||
//! (like [`crate::prefs`]): what opts a page into hosting WordCraft in its own document.
|
||||
|
||||
/// Does this `data-host` value ask for page host mode? Only the exact value `page` counts;
|
||||
/// anything else is ignored, so the page host mode stays opt-in. `?host=parent`, the parent
|
||||
/// bridge's URL opt-in, is answered before this is asked.
|
||||
pub fn page_host_requested(data_host: Option<&str>) -> bool {
|
||||
data_host == Some("page")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn only_the_exact_page_value_opts_in() {
|
||||
assert!(page_host_requested(Some("page")));
|
||||
for off in [None, Some(""), Some("Page"), Some("PAGE"), Some(" page"), Some("page "), Some("parent")] {
|
||||
assert!(!page_host_requested(off), "{off:?} must keep the page host mode off");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -15,8 +15,6 @@
|
||||
//! either host mode.
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
|
||||
#[cfg(any(target_arch = "wasm32", test))]
|
||||
mod hostmode;
|
||||
#[cfg(any(target_arch = "wasm32", test))]
|
||||
mod prefs;
|
||||
#[cfg(any(target_arch = "wasm32", test))]
|
||||
|
||||
@@ -28,18 +28,12 @@ pub fn start() {
|
||||
log::error!("missing <canvas id=\"{CANVAS_ID}\">");
|
||||
return;
|
||||
};
|
||||
// Host modes: `?host=parent`, a same-origin page framing WordCraft, opens documents in
|
||||
// Host modes (`craft-web-host`): `?host=parent`, a same-origin page framing WordCraft, opens documents 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 WordCraft in its own document and talks over DOM `CustomEvent`s
|
||||
// on the canvas (`host`). The host guards leaving the page, so this one doesn't.
|
||||
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
|
||||
};
|
||||
let bridge = crate::host::Bridge::detect(&canvas);
|
||||
let app_bridge = bridge.clone();
|
||||
let dirty = Rc::new(Cell::new(false));
|
||||
let saves = AsyncSaves::default();
|
||||
|
||||
@@ -81,7 +81,7 @@ downloading them. The two sides talk `postMessage` with plain window messages th
|
||||
|
||||
| Message | Direction | Fields |
|
||||
|---|---|---|
|
||||
| `wordcraft:ready` | app → page | `version`: the app is running and listening; send a file now |
|
||||
| `wordcraft:ready` | app → page | `version`, `appVersion`: the app is running and listening; send a file now |
|
||||
| `wordcraft:open` | page → app | `name`, `bytes` (an `ArrayBuffer` or `Uint8Array`): open like File › Open |
|
||||
| `wordcraft:save` | app → page | `name`, `saveAs`, `bytes` (a transferred `ArrayBuffer`): every file the app would otherwise download (Save, Save As, Export as PDF, Export Page as PNG). The page stores it and reports failures itself. `saveAs` says whether the file becomes the document's file: `false` after Save (the page's own file, written under its name) and for exports that are only copies (PDF, Markdown, plain text); `true` after Save As and for exports to a format that keeps everything (.docx, .odt, .rtf), after which the next Save carries that name with `false` |
|
||||
| `wordcraft:dirty` | app → page | `dirty`: unsaved changes appeared or went away |
|
||||
@@ -151,6 +151,8 @@ await init({ module_or_path: "./wordcraft-web-<hash>_bg.wasm" });
|
||||
present it takes precedence, so a same-origin framed page uses the parent bridge, while an
|
||||
unframed or cross-origin page gets no bridge and keeps normal 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 `wordcraft:ready`, `version` is the contract's (`"1"`) and `appVersion` is this app's release. WordCraft reads bytes, so a host sends `bytes`, not a `File`.
|
||||
|
||||
### Trust and limits
|
||||
|
||||
- **Who is trusted.** In page host mode the page and WordCraft 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