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.

2 changes: 2 additions & 0 deletions examples/split-wasm/.cargo/config.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
[target.'cfg(target_arch = "wasm32")']
rustflags=["-Clink-args=--emit-relocs"]
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"
WASM_BINDGEN=~/.cache/trunk/"$(cargo tree --package wasm-bindgen --depth=0 --format="{p}" -e normal | sed -e 's/ v/-/g')/wasm-bindgen"
echo "$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

$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();
}
70 changes: 70 additions & 0 deletions examples/split-wasm/src/yew.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
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};

// ---------------------------------------------------------------------------
// A counter component — the one we'll load lazily.
// Uses use_state, which triggers re-renders via the scope it was created with.
// ---------------------------------------------------------------------------

#[derive(Clone, Debug, PartialEq, Properties)]
pub struct CounterProps {
pub label: AttrValue,
}

#[component]
fn Counter(props: &CounterProps) -> Html {
let count = use_state(|| 0_i32);
let onclick = {
let count = count.clone();
Callback::from(move |_| count.set(*count + 1))
};
let global_foo = GLOBAL_FOO.with(|f| *f);
let render_counter = COUNTER.with(|cnt| {
let c = cnt.get();
cnt.set(c + 1);
c
});

html! {
<div class="counter">
<p>{"This component is loaded from a separate bundle, render count: "}{render_counter}</p>
<p>{"Here is a number loaded from (shared) memory: "}{global_foo}</p>
<h3>{ &props.label }</h3>
<p class="count">{ *count }</p>
<button {onclick}>{ "+1" }</button>
</div>
}
}

declare_lazy_component!(Counter 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 label="A lazily loaded counter" /> } 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 = { workspace = true, features = ["derive"] }
tracing = "0.1.44"
tokise = "0.2.0"
rustversion.workspace = true
wasm_split_helpers = "0.2.0"
async-once-cell = "0.5.3"

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

/// The component's props as an Rc
#[inline]
pub(crate) fn rc_props(&self) -> &Rc<COMP::Properties> {
&self.props
}

#[cfg(feature = "hydration")]
pub(crate) fn creation_mode(&self) -> RenderMode {
self.creation_mode
Expand Down
12 changes: 11 additions & 1 deletion packages/yew/src/html/component/scope.rs
Original file line number Diff line number Diff line change
Expand Up @@ -390,7 +390,7 @@ mod feat_csr_ssr {
use std::sync::atomic::{AtomicUsize, Ordering};

use super::*;
use crate::html::component::lifecycle::UpdateRunner;
use crate::html::component::lifecycle::{RenderRunner, UpdateRunner};
use crate::scheduler::{self, Shared};

#[derive(Debug)]
Expand Down Expand Up @@ -473,6 +473,16 @@ mod feat_csr_ssr {
scheduler::start();
}

#[inline]
pub(crate) fn schedule_render(&self) {
scheduler::push_component_render(
self.id,
Box::new(RenderRunner {
state: self.state.clone(),
}),
);
}

#[inline]
pub(super) fn arch_send_message<T>(&self, msg: T)
where
Expand Down
Loading
Loading