Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Don't store JsValue in ListenerProduct #75

Merged
merged 4 commits into from
Apr 15, 2023
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
6 changes: 3 additions & 3 deletions Cargo.lock

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

4 changes: 2 additions & 2 deletions crates/kobold/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "kobold"
version = "0.7.0"
version = "0.8.0"
authors = ["Maciej Hirsz <[email protected]>"]
edition = "2021"
license = "MPL-2.0"
Expand All @@ -19,7 +19,7 @@ stateful = []
wasm-bindgen = "0.2.84"
wasm-bindgen-futures = "0.4.34"
itoa = "1.0.6"
kobold_macros = { version = "0.7.0", path = "../kobold_macros" }
kobold_macros = { version = "0.8.0", path = "../kobold_macros" }
console_error_panic_hook = "0.1.7"

[dependencies.web-sys]
Expand Down
55 changes: 35 additions & 20 deletions crates/kobold/src/event.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

use std::marker::PhantomData;
use std::ops::Deref;
use std::ptr::NonNull;

use wasm_bindgen::closure::Closure;
use wasm_bindgen::prelude::wasm_bindgen;
Expand Down Expand Up @@ -87,43 +88,57 @@ where
E: EventCast,
Self: Sized + 'static,
{
fn build(self) -> ListenerProduct<Self>;
type Product: ListenerHandle;

fn update(self, p: &mut ListenerProduct<Self>);
fn build(self) -> Self::Product;

fn update(self, p: &mut Self::Product);
}

impl<E, F> Listener<E> for F
where
F: FnMut(E) + 'static,
E: EventCast,
{
fn build(self) -> ListenerProduct<Self> {
let raw = Box::leak(Box::new(self));

let js = Closure::wrap(unsafe {
Box::from_raw(raw as *mut dyn FnMut(E) as *mut dyn FnMut(web_sys::Event))
})
.into_js_value();
type Product = ListenerProduct<Self, E>;

// `into_js_value` will _forget_ the previous Box, so we can safely reconstruct it
let boxed = unsafe { Box::from_raw(raw) };
fn build(self) -> ListenerProduct<Self, E> {
ListenerProduct {
raw: Box::leak(Box::new(self)).into(),
_event: PhantomData,
}
}

ListenerProduct { js, boxed }
fn update(self, p: &mut ListenerProduct<Self, E>) {
unsafe { *p.raw.as_ptr() = self };
}
}

pub struct ListenerProduct<F, E> {
raw: NonNull<F>,
_event: PhantomData<E>,
}

fn update(self, p: &mut ListenerProduct<Self>) {
*p.boxed = self;
impl<F, E> Drop for ListenerProduct<F, E> {
fn drop(&mut self) {
unsafe { drop(Box::from_raw(self.raw.as_ptr())) }
}
}

pub struct ListenerProduct<F> {
js: JsValue,
boxed: Box<F>,
pub trait ListenerHandle {
fn js(&self) -> JsValue;
}

impl<F> ListenerProduct<F> {
pub fn js(&self) -> &JsValue {
&self.js
impl<F, E> ListenerHandle for ListenerProduct<F, E>
where
F: FnMut(E) + 'static,
E: EventCast,
{
fn js(&self) -> JsValue {
Closure::wrap(unsafe {
Box::from_raw(self.raw.as_ptr() as *mut dyn FnMut(E) as *mut dyn FnMut(web_sys::Event))
})
.into_js_value()
}
}

Expand Down
35 changes: 34 additions & 1 deletion crates/kobold/src/stateful/hook.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
// file, You can obtain one at https://mozilla.org/MPL/2.0/.

use std::future::Future;
use std::marker::PhantomData;
use std::mem::ManuallyDrop;
use std::ops::Deref;
use std::rc::{Rc, Weak};
Expand Down Expand Up @@ -102,7 +103,7 @@ impl<S> Hook<S> {
{
let inner = &self.inner as *const Inner<S>;

move |e| {
let bound = move |e| {
// ⚠️ Safety:
// ==========
//
Expand All @@ -115,6 +116,11 @@ impl<S> Hook<S> {
if callback(state, e).should_render() {
inner.update();
}
};

Bound {
bound,
_unbound: PhantomData::<F>,
}
}

Expand Down Expand Up @@ -157,6 +163,33 @@ impl<S> Hook<S> {
}
}

struct Bound<B, U> {
bound: B,
_unbound: PhantomData<U>,
}

impl<B, U, E> Listener<E> for Bound<B, U>
where
B: Listener<E>,
E: EventCast,
Self: 'static,
{
type Product = B::Product;

fn build(self) -> Self::Product {
self.bound.build()
}

fn update(self, p: &mut Self::Product) {
// No need to update zero-sized closures.
//
// This is a const branch that should be optimized away.
if std::mem::size_of::<U>() != 0 {
self.bound.update(p);
}
}
}

impl<S> Deref for Hook<S> {
type Target = S;

Expand Down
2 changes: 1 addition & 1 deletion crates/kobold_macros/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "kobold_macros"
version = "0.7.0"
version = "0.8.0"
authors = ["Maciej Hirsz <[email protected]>"]
edition = "2021"
license = "MPL-2.0"
Expand Down
12 changes: 8 additions & 4 deletions crates/kobold_macros/src/gen/element.rs
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,7 @@ impl IntoGenerator for HtmlElement {
writeln!(el, "{var}.addEventListener(\"{}\",{value});", &name[2..])
});

el.args.push(JsArgument::new(value))
el.args.push(JsArgument::with_abi(value, InlineAbi::Event))
}
AttributeType::Provided(attr) => {
el.hoisted = true;
Expand Down Expand Up @@ -206,27 +206,31 @@ impl IntoGenerator for HtmlElement {
pub enum InlineAbi {
Bool,
Str,
Event,
}

impl InlineAbi {
pub fn abi(self) -> &'static str {
match self {
InlineAbi::Bool => "bool",
InlineAbi::Str => "&str",
InlineAbi::Event => "wasm_bindgen::JsValue",
}
}

pub fn method(self) -> &'static str {
pub fn method(self) -> Option<&'static str> {
match self {
InlineAbi::Bool => ".into()",
InlineAbi::Str => ".as_ref()",
InlineAbi::Bool => Some(".into()"),
InlineAbi::Str => Some(".as_ref()"),
InlineAbi::Event => None,
}
}

pub fn bound(self) -> &'static str {
match self {
InlineAbi::Bool => "+ Into<bool> + Copy",
InlineAbi::Str => "+ AsRef<str>",
InlineAbi::Event => "",
}
}
}
Expand Down
15 changes: 4 additions & 11 deletions crates/kobold_macros/src/gen/transient.rs
Original file line number Diff line number Diff line change
Expand Up @@ -140,19 +140,11 @@ impl Tokenize for Transient {

match field.kind {
FieldKind::StaticView => (),
FieldKind::View | FieldKind::Attribute { .. } => {
_ => {
let _ = write!(product_generics, "{typ},");
let _ = write!(product_generics_binds, "{typ}::Product,");
field.declare(&mut product_declare);
}
FieldKind::Event { .. } => {
let _ = write!(product_generics, "{typ},");
let _ = write!(
product_generics_binds,
"::kobold::event::ListenerProduct<{typ}>,"
);
field.declare(&mut product_declare);
}
}
}

Expand All @@ -170,7 +162,7 @@ impl Tokenize for Transient {
.map(|a| {
let mut temp = ArrayString::<24>::new();
let name = a.name;
let _ = match a.abi.map(InlineAbi::method) {
let _ = match a.abi.and_then(|abi| abi.method()) {
Some(method) => write!(temp, "self.{name}{method}"),
None => write!(temp, "{name}.js()"),
};
Expand All @@ -189,7 +181,8 @@ impl Tokenize for Transient {
block((
(
"\
use ::kobold::dom::{Mountable as _};\
use ::kobold::dom::Mountable as _;\
use ::kobold::event::ListenerHandle as _;\
use ::kobold::reexport::wasm_bindgen;\
",
self.js,
Expand Down
4 changes: 2 additions & 2 deletions crates/kobold_qr/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "kobold_qr"
version = "0.7.0"
version = "0.8.0"
authors = ["Maciej Hirsz <[email protected]>"]
edition = "2021"
license = "MPL-2.0"
Expand All @@ -10,7 +10,7 @@ description = "QR code component for Kobold"

[dependencies]
fast_qr = "0.8.5"
kobold = { version = "0.7.0", path = "../kobold" }
kobold = { version = "0.8.0", path = "../kobold" }
wasm-bindgen = "0.2.84"

[dependencies.web-sys]
Expand Down