Skip to content
Open
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
58 changes: 58 additions & 0 deletions Cargo.lock

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

16 changes: 16 additions & 0 deletions examples/split-wasm/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
[package]
name = "split-wasm"
version = "0.1.0"
authors = []
edition = "2021"
license = "MIT OR Apache-2.0"

[dependencies]
async-once-cell = "0.5.3"
yew = { path = "../../packages/yew", features = ["csr"] }
wasm-bindgen = "*"
wasm-bindgen-futures = "*"

[dependencies.web-sys]
version = "0.3"
features = ["HtmlInputElement"]
42 changes: 42 additions & 0 deletions examples/split-wasm/build.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
#!/usr/bin/env bash
set -e
shopt -s extglob

CARGO="cargo +nightly"
WASM_BINDGEN=~/.cache/trunk/"$(cargo tree --package wasm-bindgen --depth=0 --format="{p}" | sed -e 's/ v/-/g')/wasm-bindgen"
WASM_OPT="$(ls -dv1 ~/.cache/trunk/wasm-opt-version_* | tail -n 1)"/bin/wasm-opt # will select most recently installed :)

PROFILE="release"
THIS_DIR=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" &> /dev/null && pwd)
TARGET_DIR=$(cd -- "$THIS_DIR"/../../target/ &> /dev/null && pwd)
OPT=1

RUSTFLAGS="-Clink-args=--emit-relocs$(case "$CARGO" in *nightly*) echo " -Zunstable-options -Cpanic=immediate-abort" ;; esac)" \
$CARGO build --target wasm32-unknown-unknown \
$(case $PROFILE in "debug") ;; "release") echo "--release" ;; *) echo '--profile "${PROFILE}"' ;; esac)

mkdir -p dist/
GLOBIGNORE=".:.."
rm -rf dist/*
mkdir dist/.stage
(
wasm_split_cli --verbose "$TARGET_DIR/wasm32-unknown-unknown/${PROFILE}/split-wasm.wasm" "$THIS_DIR"/dist/.stage/ \
> "$THIS_DIR"/dist/.stage/split.log
)
echo "running wasm-bindgen"
$WASM_BINDGEN dist/.stage/main.wasm --out-dir dist/.stage --no-demangle --target web --keep-lld-exports --no-typescript
if [ "$OPT" == 1 ] ; then
echo "running wasm-opt"
for wasm in dist/.stage/!(main).wasm ; do
$WASM_OPT -Os "$wasm" -o dist/"$(basename -- "$wasm")"
done
else
for wasm in dist/.stage/!(main).wasm ; do
mv "$wasm" dist/"$(basename -- "$wasm")"
done
fi
echo "moving to dist dir"
mv dist/.stage/*.!(wasm) dist
#rmdir dist/.stage
cp index.html dist/

28 changes: 28 additions & 0 deletions examples/split-wasm/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />

<title>Yew • Split WASM</title>
<base href="/" />

<script type="module">
import init, * as bindings from '/main.js';
const wasm = await init({ module_or_path: '/main_bg.wasm' });

window.globalFoo = 42;
window.wasmBindings = bindings;


dispatchEvent(new CustomEvent("TrunkApplicationStarted", {detail: {wasm}}));

</script>
<link rel="modulepreload" href="/main.js" crossorigin="anonymous">
<link rel="preload" href="/main_bg.wasm" crossorigin="anonymous" as="fetch" type="application/wasm">
<link rel="modulepreload" href="/__wasm_split.js" crossorigin="anonymous">
<!--link rel="preload" href="/lazy_addon.wasm" crossorigin="anonymous" as="fetch" type="application/wasm"-->
</head>

<body></body>
</html>
20 changes: 20 additions & 0 deletions examples/split-wasm/src/main.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
use std::cell::Cell;

use wasm_bindgen::prelude::wasm_bindgen;

// You can use a global variable from javascript, or a static
// and even thread local variable without any changes.
#[wasm_bindgen]
extern "C" {
#[wasm_bindgen(thread_local_v2, js_name = "globalFoo")]
static GLOBAL_FOO: u32;
}
thread_local! {
static COUNTER: Cell<usize> = const { Cell::new(0) };
}

mod yew;

pub fn main() {
yew::main();
}
48 changes: 48 additions & 0 deletions examples/split-wasm/src/yew.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
use std::future::{pending, Future};

use web_sys::HtmlInputElement;
use yew::lazy::declare_lazy_component;
use yew::prelude::*;
use yew::suspense::Suspension;
use yew::Renderer;

use super::{COUNTER, GLOBAL_FOO};

#[component]
fn Addition() -> Html {
let global_foo = GLOBAL_FOO.with(|f| *f);
let counter = COUNTER.with(|cnt| {
let c = cnt.get();
cnt.set(c + 1);
c
});
html! {
<p>{"This component is loaded from a separate bundle and displays: "}{global_foo}{", render count: "}{counter}</p>
}
}

declare_lazy_component!(Addition as LazyAddition in lazy_addition);

#[component]
fn Pending() -> HtmlResult {
Err(Suspension::from_future(pending()).into())
}

#[component]
fn App() -> Html {
let toggle = use_state(|| false);
let show = *toggle;
html! {
<>
<input id="additional" type="checkbox" checked={*toggle} oninput={move |ev: InputEvent| toggle.set(ev.target_unchecked_into::<HtmlInputElement>().checked())} />
<label for="additional">{"Display additional content"}</label>
<Suspense fallback={html! { <p>{"not yet loaded"}</p> }}>
if show { <LazyAddition /> } else { <Pending /> }
</Suspense>
</>
}
}

pub fn main() {
let _ = Renderer::<App>::new().render();
}
2 changes: 2 additions & 0 deletions packages/yew/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,8 @@ serde = { version = "1", features = ["derive"] }
tracing = "0.1.40"
tokise = "0.2.0"
rustversion = "1"
wasm_split_helpers = "0.2.0"
async-once-cell = "0.5.3"

[target.'cfg(target_arch = "wasm32")'.dependencies]
wasm-bindgen-futures = "0.4"
Expand Down
20 changes: 20 additions & 0 deletions packages/yew/src/html/component/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,26 @@ impl<COMP: BaseComponent> Context<COMP> {

state
}

pub(crate) fn narrow_scope<D: BaseComponent<Properties = COMP::Properties>>(
&self,
inner: &Scope<D>,
) -> Context<D> {
let mut ctx = Context {
scope: inner.clone(),
props: self.props.clone(),
#[cfg(feature = "hydration")]
creation_mode: self.creation_mode,
#[cfg(feature = "hydration")]
prepared_state: None,
};
let _ = &mut ctx; // silence warning due to feature conditional branch below
#[cfg(feature = "hydration")]
{
ctx.prepared_state = self.prepared_state.clone();
}
ctx
}
}

/// The common base of both function components and struct components.
Expand Down
Loading
Loading