Skip to content

Commit

Permalink
Add data-type attribute to rust links
Browse files Browse the repository at this point in the history
This allows web workers to be included in `index.html`. Since this makes the
rust-worker attribute unnecessary it has been removed.

Also adds an example showing basic usage and updates the documentation.
  • Loading branch information
kristoff3r committed Jan 19, 2022
1 parent d46ba85 commit f911eda
Show file tree
Hide file tree
Showing 11 changed files with 345 additions and 83 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ Subheadings to categorize changes are `added, changed, deprecated, removed, fixe
### added
- Added the `--address` option for `trunk serve`.
- Open autoreload websocket using wss when assets are served over a secure connection.
- Added the `data-type` attribute to Rust assets. Can be set to either `main` (previous behaviour and default) or `worker`, which builds the asset and includes it as a web worker.

### changed
- Bump notify to 5.0.0-pre.13, which fixes [notify-rs/notify#356](https://github.com/notify-rs/notify/issues/356)
Expand Down
210 changes: 210 additions & 0 deletions examples/webworker/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

13 changes: 13 additions & 0 deletions examples/webworker/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
[package]
name = "webworker-example"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
console_error_panic_hook = "0.1"
web-sys = { version = "0.3", features = ["Window", "Location", "Document", "HtmlElement", "Node", "Text", "Worker", "DedicatedWorkerGlobalScope"] }
wasm-bindgen = "=0.2.74"
wee_alloc = "0.4"
js-sys = "0.3.55"
17 changes: 17 additions & 0 deletions examples/webworker/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
<!DOCTYPE html>
<html>

<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Trunk | Web worker</title>

<base data-trunk-public-url />
</head>

<body>
<link data-trunk rel="rust" href="Cargo.toml" data-wasm-opt="z" data-bin="app" data-type="main" />
<link data-trunk rel="rust" href="Cargo.toml" data-wasm-opt="z" data-bin="worker" data-type="worker" />
</body>

</html>
24 changes: 24 additions & 0 deletions examples/webworker/src/bin/app.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
#![recursion_limit = "1024"]

#[global_allocator]
static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT;

use console_error_panic_hook::set_once as set_panic_hook;
use web_sys::{window, Worker};

fn worker_new(file_name: &str) -> Worker {
let origin = window().unwrap().location().origin().unwrap();
let url = format!("{}/{}", origin, file_name);

Worker::new(&url).expect("failed to spawn worker")
}

fn main() {
set_panic_hook();
let document = window().and_then(|win| win.document()).expect("Could not access document");
let body = document.body().expect("Could not access document.body");
let text_node = document.create_text_node("Hello, world from Rust!");
body.append_child(text_node.as_ref()).expect("Failed to append text");

let worker = worker_new("worker.js");
}
1 change: 1 addition & 0 deletions examples/webworker/src/bin/worker.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
fn main() {}
10 changes: 3 additions & 7 deletions site/content/assets.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,10 @@ This will typically look like: `<link data-trunk rel="{type}" href="{path}" ..ot

# Asset Types
## rust
`rel="rust"`: Trunk will compile the specified Cargo project as the main WASM application. This is optional. If not specified, Trunk will look for a `Cargo.toml` in the parent directory of the source HTML file.
`rel="rust"`: Trunk will compile the specified Cargo project as WASM and load it. This is optional. If not specified, Trunk will look for a `Cargo.toml` in the parent directory of the source HTML file.
- `href`: (optional) the path to the `Cargo.toml` of the Rust project. If a directory is specified, then Trunk will look for the `Cargo.toml` in the given directory. If no value is specified, then Trunk will look for a `Cargo.toml` in the parent directory of the source HTML file.
- `data-bin`: (optional) the name of the binary to compile and use as the main WASM application. If the Cargo project has multiple binaries, this value will be required for proper functionality.
- `data-bin`: (optional) the name of the binary to compile and load. If the Cargo project has multiple binaries, this value will be required for proper functionality.
- `data-type`: (optional) specifies how the binary should be loaded into the project. Can be set to `main` or `worker`. `main` is the default. There can only be one `main` link. For workers a javascript wrapper is created named after the binary name (if provided) or project name, which can be used to load it.
- `data-cargo-features`: (optional) Space or comma separated list of cargo features to activate.
- `data-wasm-opt`: (optional) run wasm-opt with the set optimization level. The possible values are `0`, `1`, `2`, `3`, `4`, `s`, `z` or an _empty value_ for wasm-opt's default. Set this option to `0` to disable wasm-opt explicitly. The values `1-4` are increasingly stronger optimization levels for speed. `s` and `z` (z means more optimization) optimize for binary size instead. Only used in `--release` mode.
- `data-keep-debug`: (optional) instruct `wasm-bindgen` to preserve debug info in the final WASM output, even for `--release` mode. This may conflict with the use of wasm-opt, so to be sure, it is recommended to set `data-wasm-opt="0"` when using this option.
Expand Down Expand Up @@ -43,11 +44,6 @@ This will typically look like: `<link data-trunk rel="{type}" href="{path}" ..ot
## copy-dir
`rel="copy-dir"`: Trunk will recursively copy the directory specified in the `href` attribute to the `dist` dir. This content is copied exactly, no hashing is performed.

## rust-worker
`rel="rust-worker"`: (in-progress) Trunk will compile the specified Rust project as a WASM web worker. The following attributes are required:
- `href`: (optional) the path to the `Cargo.toml` of the Rust project. If a directory is specified, then Trunk will look for the `Cargo.toml` in the given directory. If no value is specified, then Trunk will look for a `Cargo.toml` in the parent directory of the source HTML file.
- `data-bin`: (optional) the name of the binary to compile and use as the web worker. If the Cargo project has multiple binaries, this value will be required for proper functionality.

Trunk is still a young project, and new asset types will be added as we move forward. Keep an eye on [trunk#3](https://github.com/thedodd/trunk/issues/3) for more information on planned asset types, implementation status, and please contribute to the discussion if you think something is missing.

# JS Snippets
Expand Down
11 changes: 8 additions & 3 deletions src/pipelines/html.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ use tokio::task::JoinHandle;

use crate::config::RtcBuild;
use crate::hooks::{spawn_hooks, wait_hooks};
use crate::pipelines::rust_app::RustApp;
use crate::pipelines::rust::RustApp;
use crate::pipelines::{LinkAttrs, PipelineStage, TrunkLink, TrunkLinkPipelineOutput, TRUNK_ID};

const PUBLIC_URL_MARKER_ATTR: &str = "data-trunk-public-url";
Expand Down Expand Up @@ -96,8 +96,13 @@ impl HtmlPipeline {
}

// Ensure we have a Rust app pipeline to spawn.
let rust_app_nodes = target_html.select(r#"link[data-trunk][rel="rust"]"#).length();
ensure!(rust_app_nodes <= 1, r#"only one <link data-trunk rel="rust" .../> may be specified"#);
let rust_app_nodes = target_html
.select(r#"link[data-trunk][rel="rust"][data-type="main"], link[data-trunk][rel="rust"]:not([data-type])"#)
.length();
ensure!(
rust_app_nodes <= 1,
r#"only one <link data-trunk rel="rust" data-type="main" .../> may be specified"#
);
if rust_app_nodes == 0 {
let app = RustApp::new_default(self.cfg.clone(), self.target_html_dir.clone(), self.ignore_chan.clone()).await?;
assets.push(TrunkLink::RustApp(app));
Expand Down
12 changes: 2 additions & 10 deletions src/pipelines/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,7 @@ mod css;
mod html;
mod icon;
mod inline;
mod rust_app;
mod rust_worker;
mod rust;
mod sass;

use std::collections::HashMap;
Expand All @@ -27,8 +26,7 @@ use crate::pipelines::copy_file::{CopyFile, CopyFileOutput};
use crate::pipelines::css::{Css, CssOutput};
use crate::pipelines::icon::{Icon, IconOutput};
use crate::pipelines::inline::{Inline, InlineOutput};
use crate::pipelines::rust_app::{RustApp, RustAppOutput};
use crate::pipelines::rust_worker::{RustWorker, RustWorkerOutput};
use crate::pipelines::rust::{RustApp, RustAppOutput};
use crate::pipelines::sass::{Sass, SassOutput};

pub use html::HtmlPipeline;
Expand Down Expand Up @@ -58,7 +56,6 @@ pub enum TrunkLink {
CopyFile(CopyFile),
CopyDir(CopyDir),
RustApp(RustApp),
RustWorker(RustWorker),
}

impl TrunkLink {
Expand All @@ -77,7 +74,6 @@ impl TrunkLink {
CopyFile::TYPE_COPY_FILE => Self::CopyFile(CopyFile::new(cfg, html_dir, attrs, id).await?),
CopyDir::TYPE_COPY_DIR => Self::CopyDir(CopyDir::new(cfg, html_dir, attrs, id).await?),
RustApp::TYPE_RUST_APP => Self::RustApp(RustApp::new(cfg, html_dir, ignore_chan, attrs, id).await?),
RustWorker::TYPE_RUST_WORKER => Self::RustWorker(RustWorker::new(cfg, html_dir, ignore_chan, attrs, id).await?),
_ => bail!(
r#"unknown <link data-trunk .../> attr value `rel="{}"`; please ensure the value is lowercase and is a supported asset type"#,
rel
Expand All @@ -95,7 +91,6 @@ impl TrunkLink {
TrunkLink::CopyFile(inner) => inner.spawn(),
TrunkLink::CopyDir(inner) => inner.spawn(),
TrunkLink::RustApp(inner) => inner.spawn(),
TrunkLink::RustWorker(inner) => inner.spawn(),
}
}
}
Expand All @@ -109,8 +104,6 @@ pub enum TrunkLinkPipelineOutput {
CopyFile(CopyFileOutput),
CopyDir(CopyDirOutput),
RustApp(RustAppOutput),
#[allow(dead_code)] // TODO: remove this when this pipeline type is implemented.
RustWorker(RustWorkerOutput),
}

impl TrunkLinkPipelineOutput {
Expand All @@ -123,7 +116,6 @@ impl TrunkLinkPipelineOutput {
TrunkLinkPipelineOutput::CopyFile(out) => out.finalize(dom).await,
TrunkLinkPipelineOutput::CopyDir(out) => out.finalize(dom).await,
TrunkLinkPipelineOutput::RustApp(out) => out.finalize(dom).await,
TrunkLinkPipelineOutput::RustWorker(out) => out.finalize(dom).await,
}
}
}
Expand Down
Loading

0 comments on commit f911eda

Please sign in to comment.