migrate wasm example to trunk (#844)

## Description

This PR migrates the wasm example from an npm/webpack based approach to [trunk](https://trunkrs.dev/). Fixes #834.

Of note:
the `console_error_panic_hook` dependency was gated in `Cargo.toml` via `[target."cfg(debug_assertions)".dependencies]`. This is documented as nonfunctional and will throw a warning on build:
```
warning: Found `debug_assertions` in `target.'cfg(...)'.dependencies`. 
This value is not supported for selecting dependencies and will not work as expected. 
To learn more visit https://doc.rust-lang.org/cargo/reference/specifying-dependencies.html#platform-specific-dependencies
```

Since the actual usage of `console_error_panic_hook` is *also* gated in `lib.rs` behind `#[cfg(debug_assertions)]` it didn't make sense to have the cargo gate in place, hence I have removed it.

## Next steps

If this PR is merged, the [wiki page](https://github.com/RustAudio/cpal/wiki/Setting-up-a-new-CPAL-WASM-project) linked in the root README should be updated as well.
This commit is contained in:
Anatol Ulrich 2024-02-25 01:49:53 +01:00 • committed by GitHub
parent bdbbf75d82
commit db04f57be4
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
8 changed files with 52 additions and 6994 deletions

View file

@ -1,6 +1,3 @@
Cargo.lock
node_modules
/dist
/target
/pkg
/wasm-pack.log

View file

@ -18,6 +18,8 @@ lto = true
[dependencies]
cpal = { path = "../..", features = ["wasm-bindgen"] }
# `gloo` is a utility crate which improves ergonomics over direct `web-sys` usage.
gloo = "0.11.0"
# The `wasm-bindgen` crate provides the bare minimum functionality needed
# to interact with JavaScript.
wasm-bindgen = "0.2.45"
@ -27,15 +29,12 @@ wasm-bindgen = "0.2.45"
# allocator, so it's not enabled by default.
wee_alloc = { version = "0.4.2", optional = true }
# The `console_error_panic_hook` crate provides better debugging of panics by
# logging them with `console.error`.
console_error_panic_hook = "0.1.5"
# The `web-sys` crate allows you to interact with the various browser APIs,
# like the DOM.
[dependencies.web-sys]
version = "0.3.22"
features = ["console"]
# The `console_error_panic_hook` crate provides better debugging of panics by
# logging them with `console.error`. This is great for development, but requires
# all the `std::fmt` and `std::panicking` infrastructure, so it's only enabled
# in debug mode.
[target."cfg(debug_assertions)".dependencies]
console_error_panic_hook = "0.1.5"
features = ["console", "MouseEvent"]

View file

@ -1,29 +1,28 @@
## How to install
[trunk](https://trunkrs.dev/) is used to build and serve the example.
```sh
npm install
cargo install --locked trunk
# -- or --
cargo binstall trunk
```
## How to run in debug mode
```sh
# Builds the project and opens it in a new browser tab. Auto-reloads when the project changes.
npm start
trunk serve --open
```
## How to build in release mode
```sh
# Builds the project and places it into the `dist` folder.
npm run build
# Builds the project in release mode and places it into the `dist` folder.
trunk build --release
```
## What does each file do?
* `Cargo.toml` contains the standard Rust metadata. You put your Rust dependencies in here. You must change this file with your details (name, description, version, authors, categories)
* `package.json` contains the standard npm metadata. You put your JavaScript dependencies in here. You must change this file with your details (author, name, version)
* `webpack.config.js` contains the Webpack configuration. You shouldn't need to change this, unless you have very special needs.
* The `src` folder contains your Rust code.

View file

@ -1,14 +0,0 @@
import("./pkg").catch(console.error).then(rust_module=>{
let handle = null;
const play_button = document.getElementById("play");
play_button.addEventListener("click", event => {
handle = rust_module.beep();
});
const stop_button = document.getElementById("stop");
stop_button.addEventListener("click", event => {
if (handle != null) {
handle.free();
handle = null;
}
});
});

File diff suppressed because it is too large Load diff

View file

@ -1,21 +0,0 @@
{
"author": "You <you@example.com>",
"name": "rust-webpack-template",
"version": "0.1.0",
"scripts": {
"build": "rimraf dist pkg && webpack",
"start": "rimraf dist pkg && webpack-dev-server --open",
"test": "cargo test && wasm-pack test --headless"
},
"devDependencies": {
"@wasm-tool/wasm-pack-plugin": "^1.6.0",
"copy-webpack-plugin": "^11.0.0",
"webpack": "^5.73.0",
"webpack-cli": "^4.10.0",
"webpack-dev-server": "^4.9.3",
"rimraf": "^3.0.2"
},
"dependencies": {
"html-webpack-plugin": "^5.5.0"
}
}

View file

@ -1,3 +1,9 @@
use std::{cell::Cell, rc::Rc};
use cpal::{
traits::{DeviceTrait, HostTrait, StreamTrait},
Stream,
};
use wasm_bindgen::prelude::*;
use web_sys::console;
@ -17,29 +23,51 @@ pub fn main_js() -> Result<(), JsValue> {
#[cfg(debug_assertions)]
console_error_panic_hook::set_once();
let document = gloo::utils::document();
let play_button = document.get_element_by_id("play").unwrap();
let stop_button = document.get_element_by_id("stop").unwrap();
// stream needs to be referenced from the "play" and "stop" closures
let stream = Rc::new(Cell::new(None));
// set up play button
{
let stream = stream.clone();
let closure = Closure::<dyn FnMut(_)>::new(move |_event: web_sys::MouseEvent| {
stream.set(Some(beep()));
});
play_button
.add_event_listener_with_callback("mousedown", closure.as_ref().unchecked_ref())?;
closure.forget();
}
// set up stop button
{
let closure = Closure::<dyn FnMut(_)>::new(move |_event: web_sys::MouseEvent| {
// stop the stream by dropping it
stream.take();
});
stop_button
.add_event_listener_with_callback("mousedown", closure.as_ref().unchecked_ref())?;
closure.forget();
}
Ok(())
}
use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};
use cpal::Stream;
#[wasm_bindgen]
pub struct Handle(Stream);
#[wasm_bindgen]
pub fn beep() -> Handle {
fn beep() -> Stream {
let host = cpal::default_host();
let device = host
.default_output_device()
.expect("failed to find a default output device");
let config = device.default_output_config().unwrap();
Handle(match config.sample_format() {
match config.sample_format() {
cpal::SampleFormat::F32 => run::<f32>(&device, &config.into()),
cpal::SampleFormat::I16 => run::<i16>(&device, &config.into()),
cpal::SampleFormat::U16 => run::<u16>(&device, &config.into()),
_ => panic!("unsupported sample format"),
})
}
}
fn run<T>(device: &cpal::Device, config: &cpal::StreamConfig) -> Stream

View file

@ -1,34 +0,0 @@
const path = require("path");
const CopyPlugin = require("copy-webpack-plugin");
const WasmPackPlugin = require("@wasm-tool/wasm-pack-plugin");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const dist = path.resolve(__dirname, "dist");
module.exports = {
mode: "production",
entry: {
index: "./index.js"
},
output: {
path: dist,
filename: "[name].js"
},
experiments: {
syncWebAssembly: true
},
devServer: {
static: {
directory: dist
},
},
plugins: [
new HtmlWebpackPlugin({
template: 'index.html'
}),
new WasmPackPlugin({
crateDirectory: __dirname,
outName: "index"
}),
]
};