Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
61 changes: 61 additions & 0 deletions .github/web-build/bundle_demo.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
from __future__ import annotations

import argparse
import re
import zipfile
from pathlib import Path


REQUIRED_FILES = {
"html": ("_node.toml", "00-start/welcome/index.html"),
"cmgfm": ("_node.toml", "00-start/welcome/index.md"),
}


def bundle_demo(source: Path, destination: Path, version: str) -> None:
html_source = source / "html"
cmgfm_source = source / "cmgfm"
for required_root in (html_source, cmgfm_source):
if not (required_root / "_node.toml").is_file():
raise ValueError(f"official demo format is missing metadata: {required_root}")
language_folders = [path for path in required_root.iterdir() if path.is_dir() and re.fullmatch(r"(?:1\d|2\d)-[a-z]{2}", path.name)]
if len(language_folders) != 13:
raise ValueError(f"official {required_root.name} demo has {len(language_folders)} language folders, expected 13")
for format_name, required_files in REQUIRED_FILES.items():
format_root = source / format_name
for relative in required_files:
if not (format_root / relative).is_file():
raise ValueError(f"official {format_name} demo is missing {relative}")

expected_title = f"Welcome to NoteCraft (Ver {version})"
for format_name, required_files in REQUIRED_FILES.items():
page = (source / format_name / required_files[1]).read_text(encoding="utf-8")
if version not in page:
raise ValueError(f"{format_name} Welcome page does not contain workspace version {version}")
if expected_title not in page:
raise ValueError(f"official {format_name} Welcome page does not name version {version}")

destination.parent.mkdir(parents=True, exist_ok=True)
with zipfile.ZipFile(destination, "w", compression=zipfile.ZIP_DEFLATED, compresslevel=6) as bundle:
for format_name in REQUIRED_FILES:
format_root = source / format_name
for path in sorted(format_root.rglob("*")):
if path.is_file():
bundle.write(path, (Path(format_name) / path.relative_to(format_root)).as_posix())


def main() -> int:
parser = argparse.ArgumentParser()
parser.add_argument("source", type=Path)
parser.add_argument("destination", type=Path)
parser.add_argument("--version", required=True)
args = parser.parse_args()
if not re.fullmatch(r"\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?", args.version):
parser.error("--version must be a semantic version")
bundle_demo(args.source, args.destination, args.version)
print(f"Bundled both official Welcome notebook formats v{args.version} at {args.destination}")
return 0


if __name__ == "__main__":
raise SystemExit(main())
57 changes: 57 additions & 0 deletions .github/web-build/test_bundle_demo.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
from __future__ import annotations

import tempfile
import tomllib
import unittest
import zipfile
from pathlib import Path

from bundle_demo import bundle_demo


class BundleDemoTests(unittest.TestCase):
@classmethod
def setUpClass(cls) -> None:
cls.root = Path(__file__).resolve().parents[2]
with (cls.root / "Cargo.toml").open("rb") as manifest:
cls.version = tomllib.load(manifest)["workspace"]["package"]["version"]

def test_bundles_both_official_formats_with_release_version(self) -> None:
with tempfile.TemporaryDirectory() as temporary:
archive = Path(temporary) / "welcome-notebook.zip"
bundle_demo(self.root / "docs" / "demo" / "DemoNotebook", archive, self.version)

with zipfile.ZipFile(archive) as bundle:
names = set(bundle.namelist())
self.assertIn("html/_node.toml", names)
self.assertIn("html/00-start/welcome/index.html", names)
self.assertIn("cmgfm/_node.toml", names)
self.assertIn("cmgfm/00-start/welcome/index.md", names)
for fmt in ("html", "cmgfm"):
languages = {name.split("/")[1] for name in names if name.startswith(f"{fmt}/") and len(name.split("/")) > 2}
languages = {name for name in languages if len(name) == 5 and name[:2].isdigit() and name[2] == "-"}
self.assertEqual(len(languages), 13, f"{fmt} should include every translated notebook")
html = bundle.read("html/00-start/welcome/index.html").decode()
cmgfm = bundle.read("cmgfm/00-start/welcome/index.md").decode()
for page in (html, cmgfm):
self.assertIn(f"Welcome to NoteCraft (Ver {self.version})", page)
self.assertIn(f"NoteCraft {self.version}. This notebook", page)
self.assertTrue((self.root / "docs/demo/DemoNotebook/cmgfm/00-start/welcome/index.md").is_file())

def test_rejects_a_demo_generated_for_a_different_release(self) -> None:
wrong_version = self.version + ".1"
with tempfile.TemporaryDirectory() as temporary:
with self.assertRaisesRegex(ValueError, "workspace version"):
bundle_demo(self.root / "docs" / "demo" / "DemoNotebook", Path(temporary) / "demo.zip", wrong_version)


def test_first_run_installs_only_the_html_edition_at_the_notebook_root(self) -> None:
patch = (self.root / ".github" / "web-build" / "web.diff").read_text(encoding="utf-8")
self.assertIn("with_welcome_notebook_setup(|_root, format| install_edition(format))", patch)
self.assertIn('session.settings.set("privacy_welcome_seen", "true")', patch)
self.assertIn('relative.strip_prefix(format)', patch)
self.assertIn("Ok(Some(notebook.to_string_lossy().into_owned()))", patch)
self.assertNotIn('Ok(Some(notebook.join("00-start/welcome/index.html")', patch)

if __name__ == "__main__":
unittest.main()
108 changes: 90 additions & 18 deletions .github/web-build/web.diff
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ index 0000000..d9828a4
+notecraft-ui-egui = { workspace = true }
+eframe = { workspace = true }
+egui = { workspace = true }
+zip = { workspace = true }
+wasm-bindgen = "0.2"
+wasm-bindgen-futures = "0.4"
+js-sys = "0.3"
Expand Down Expand Up @@ -77,16 +78,15 @@ new file mode 100644
index 0000000..f4394fb
--- /dev/null
+++ b/apps/notecraft-web/src/main.rs
@@ -0,0 +1,339 @@
+// SPDX-License-Identifier: MIT OR Apache-2.0
+//! NoteCraft in the browser, for Playground (patches/onenote.yaml in github.com/daijro/openplayground): the desktop
+//! window (crates/ui-egui) on the page's canvas.
+//!
+//! The notebooks folder is `/NoteCraft`, in memory (crates/model/src/playground.rs). Playground's Files keep it as the
+//! same plain folders at `browser:/NoteCraft/…`: it is read from there at start, and every file NoteCraft writes or
+//! same plain folders at `browser:/NoteCraft/…`: it is read from there at start, and every file NoteCraft writes or
+//! removes is written or removed there after the frame (through the page's `globalThis.playgroundFiles`). The standalone
+//! site keeps personal settings in that browser's local storage; an invitation session stays transient. The first
+//! start makes the sample notebooks. A page opened from a Playground invitation (`?pg-session=<room>`) keeps its
+//! start loads the official Welcome notebook as a separate notebook. A page opened from a Playground invitation (`?pg-session=<room>`) keeps its
+//! notebooks in the tab only, so joining someone's session never touches this browser's own notebooks.
+//! Also: pictures in pages load from the in-memory folder, files dropped on the page can be inserted, and "Open in
+//! NoteCraft" on a page file opens it (one of these notebooks') or copies it into a Quick Notes notebook. The CJK face
Expand All @@ -101,6 +101,7 @@ index 0000000..f4394fb
+ use notecraft_store::Settings;
+ use notecraft_ui_egui::NoteCraftApp;
+ use std::cell::RefCell;
+ use std::io::{Cursor, Read as _};
+ use std::path::Path;
+ use wasm_bindgen::{JsCast as _, JsValue, closure::Closure};
+
Expand All @@ -116,6 +117,8 @@ index 0000000..f4394fb
+ static CTX: std::cell::OnceCell<egui::Context> = const { std::cell::OnceCell::new() };
+ static CJK: RefCell<Face> = const { RefCell::new(Face::Wanted) };
+ static PEN: RefCell<Vec<PenReading>> = const { RefCell::new(Vec::new()) };
+ /// The release Welcome archive's files (html/… and cmgfm/…), kept so Finish can install the chosen edition.
+ static WELCOME: RefCell<Vec<(std::path::PathBuf, Vec<u8>)>> = const { RefCell::new(Vec::new()) };
+ }
+
+ /// A pen's reading from the canvas's pointer events: phase, pointer, where (CSS pixels), pressure.
Expand Down Expand Up @@ -149,6 +152,75 @@ index 0000000..f4394fb
+ Some(js_sys::Uint8Array::new(&wait(read.call0(&response).ok()).await?).to_vec())
+ }
+
+ /// Replaces only the managed browser Welcome notebook; sibling notebooks stay untouched.
+ async fn ensure_welcome_notebook() -> Result<Option<String>, String> {
+ let notebook = Path::new(ROOT).join("welcome-to-notecraft");
+ let bytes = fetch("./welcome-notebook.zip").await.ok_or_else(|| "The release Welcome notebook could not be downloaded".to_string())?;
+ let mut archive = zip::ZipArchive::new(Cursor::new(bytes)).map_err(|e| format!("The release Welcome notebook archive is invalid: {e}"))?;
+ if archive.len() > 1000 {
+ return Err("The release Welcome notebook archive contains too many files".into());
+ }
+ let mut files = Vec::with_capacity(archive.len());
+ let mut total = 0_u64;
+ for index in 0..archive.len() {
+ let mut entry = archive.by_index(index).map_err(|e| format!("Could not read a Welcome notebook file: {e}"))?;
+ if entry.is_dir() {
+ continue;
+ }
+ let relative = entry.enclosed_name().ok_or_else(|| "The Welcome notebook archive has an unsafe path".to_string())?.to_path_buf();
+ let components = relative.components().collect::<Vec<_>>();
+ if components.len() < 2 || !matches!(components[0].as_os_str().to_str(), Some("html" | "cmgfm")) {
+ return Err("The Welcome notebook archive has an unexpected path".into());
+ }
+ total = total.saturating_add(entry.size());
+ if total > 40 * 1024 * 1024 || entry.size() > 20 * 1024 * 1024 {
+ return Err("The Welcome notebook archive is larger than expected".into());
+ }
+ let mut content = Vec::with_capacity(entry.size() as usize);
+ entry.read_to_end(&mut content).map_err(|e| format!("Could not unpack a Welcome notebook file: {e}"))?;
+ files.push((relative, content));
+ }
+ for (format, page) in [("html", "00-start/welcome/index.html"), ("cmgfm", "00-start/welcome/index.md")] {
+ for required in [Path::new(format).join("_node.toml"), Path::new(format).join(page)] {
+ if !files.iter().any(|(name, _)| name == &required) {
+ return Err(format!("The Welcome notebook archive is missing {}", required.display()));
+ }
+ }
+ let languages = files
+ .iter()
+ .filter_map(|(name, _)| {
+ let mut parts = name.components();
+ let first = parts.next()?.as_os_str().to_str()?;
+ let second = parts.next()?.as_os_str().to_str()?;
+ (first == format && second.len() == 5 && second.as_bytes()[0].is_ascii_digit()).then_some(second.to_owned())
+ })
+ .collect::<std::collections::HashSet<_>>();
+ if languages.len() != 13 {
+ return Err(format!("The {format} Welcome notebook has {} language folders; expected 13", languages.len()));
+ }
+ }
+ WELCOME.with_borrow_mut(|w| *w = files);
+ install_edition("html")?;
+ Ok(Some(notebook.to_string_lossy().into_owned()))
+ }
+
+ /// Installs one edition ("html" or "cmgfm") of the Welcome notebook at the notebook root, replacing the managed
+ /// copy. Finish calls this through the same hook the desktop app uses, so the chosen format is what gets installed.
+ fn install_edition(format: &str) -> Result<std::path::PathBuf, String> {
+ let notebook = Path::new(ROOT).join("welcome-to-notecraft");
+ let files = WELCOME.with_borrow(|w| w.clone());
+ if files.is_empty() {
+ return Err("the Welcome notebook has not been loaded yet".into());
+ }
+ if fs::metadata(&notebook).is_ok() {
+ fs::remove_dir_all(&notebook).map_err(|e| format!("Could not replace the existing Welcome notebook: {e}"))?;
+ }
+ for (relative, content) in files {
+ let Ok(edition) = relative.strip_prefix(format) else { continue };
+ fs::write(notebook.join(edition), content).map_err(|e| format!("Could not install the Welcome notebook: {e}"))?;
+ }
+ Ok(notebook)
+ }
+ /// Follows the canvas's pen pointers: eframe turns them into mouse events and drops their pressure.
+ fn listen_to_the_pen(canvas: &web_sys::HtmlCanvasElement) {
+ use egui::TouchPhase::{Cancel, End, Move, Start};
Expand Down Expand Up @@ -217,7 +289,7 @@ index 0000000..f4394fb
+ !paths.is_empty()
+ }
+
+ /// Picture links in pages (`file:///NoteCraft/…/assets/x.png`), read from the in-memory folder.
+ /// Picture links in pages (`file:///NoteCraft/…/assets/x.png`), read from the in-memory folder.
+ struct Files;
+
+ impl egui::load::BytesLoader for Files {
Expand Down Expand Up @@ -407,10 +479,13 @@ index 0000000..f4394fb
+ wasm_bindgen_futures::spawn_local(async {
+ let persist = !invited() && ["files", "write", "remove"].iter().all(|m| api().is_some_and(|a| get(&a, m).is_function()));
+ let local_settings = !persist && !invited();
+ let had = persist && load().await;
+ if persist {
+ load().await;
+ }
+ if !persist && !invited() {
+ load_browser_settings();
+ }
+ let welcome_page = if !invited() { Some(ensure_welcome_notebook().await) } else { None };
+ let document = web_sys::window().and_then(|w| w.document()).expect("no document");
+ let canvas = document
+ .get_element_by_id("notecraft_canvas")
Expand All @@ -424,17 +499,14 @@ index 0000000..f4394fb
+ Box::new(move |cc| {
+ CTX.with(|c| c.set(cc.egui_ctx.clone()).ok());
+ cc.egui_ctx.add_bytes_loader(std::sync::Arc::new(Files));
+ let mut session = Session::new(Path::new(ROOT), Settings::at(SETTINGS)).map_err(|e| e.to_string())?;
+ // Give a fresh browser session a synthetic notebook to explore.
+ let first = !had && !invited();
+ let sample = if first {
+ Some(notecraft_engine::sample::create_sample(&mut session, None).map_err(|e| e.to_string())?)
+ } else {
+ None
+ };
+ let mut app = NoteCraftApp::new(session);
+ if let Some(sample) = sample {
+ app.open_path(&sample.md_page.to_string_lossy());
+ let session = Session::new(Path::new(ROOT), Settings::at(SETTINGS)).map_err(|e| e.to_string())?;
+ // The web demo has no first-use wizard: mark it seen, so it never opens here.
+ session.settings.set("privacy_welcome_seen", "true").map_err(|e| e.to_string())?;
+ let mut app = NoteCraftApp::new(session).with_welcome_notebook_setup(|_root, format| install_edition(format));
+ if let Some(page) = welcome_page {
+ if let Some(page) = page.map_err(|e| e.to_string())? {
+ app.open_path(&page);
+ }
+ }
+ Ok(Box::new(Web { app, persist, local_settings, unsaved: None }))
+ }),
Expand Down Expand Up @@ -865,9 +937,9 @@ index 0000000..f851b31
+ STATE.set(State::Arrived(read));
+ CTX.with_borrow(|c| c.as_ref().map(egui::Context::request_repaint));
+ });
+ Some("Reading the clipboard…")
+ Some("Reading the clipboard…")
+ }
+ State::Reading | State::Arrived(_) => Some("Reading the clipboard…"),
+ State::Reading | State::Arrived(_) => Some("Reading the clipboard…"),
+ })
+}
+
Expand Down
Loading
Loading