More small tweaks to support config

This commit is contained in:
Ben Wishovich 2022-12-20 17:56:38 -08:00
parent ee379bb405
commit f2e9d6f4c3
5 changed files with 41 additions and 38 deletions

View file

@ -228,18 +228,18 @@ pub fn render_app_to_stream(
// Because wasm-pack adds _bg to the end of the WASM filename, and we want to mantain compatibility with it's default options
// we add _bg to the wasm files if cargo-leptos doesn't set the env var PACKAGE_NAME
// Otherwise we need to add _bg because wasm_pack always does. This is not the same as options.pkg_name, which is set regardless
let wasm_pkg_name;
// Otherwise we need to add _bg because wasm_pack always does. This is not the same as options.package_name, which is set regardless
let wasm_package_name;
if std::env::var("PACKAGE_NAME").is_ok() {
wasm_pkg_name = pkg_name
wasm_package_name = package_name
} else {
wasm_pkg_name = pkg_name.push_str("_bg");
wasm_package_name = package_name.push_str("_bg");
}
let site_ip = &options.site_address.ip().to_string();
let reload_port = options.reload_port;
let leptos_autoreload = match options.leptos_watch {
let leptos_autoreload = match options.watch {
true => format!(
r#"
<script crossorigin="">(function () {{
@ -262,9 +262,9 @@ pub fn render_app_to_stream(
<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<link rel="modulepreload" href="{pkg_path}]{pkg_name}.js">
<link rel="preload" href="{pkg_path}/{wasm_pkg_name}.wasm" as="fetch" type="application/wasm" crossorigin="">
<script type="module">import init, {{ hydrate }} from '{pkg_path}/{pkg_name}.js'; init('{pkg_path}]{wasm_pkg_name}.wasm').then(hydrate);</script>
<link rel="modulepreload" href="{pkg_path}]{package_name}.js">
<link rel="preload" href="{pkg_path}/{wasm_package_name}.wasm" as="fetch" type="application/wasm" crossorigin="">
<script type="module">import init, {{ hydrate }} from '{pkg_path}/{package_name}.js'; init('{pkg_path}]{wasm_package_name}.wasm').then(hydrate);</script>
{leptos_autoreload}
"#
);

View file

@ -236,8 +236,8 @@ pub type PinnedHtmlStream = Pin<Box<dyn Stream<Item = io::Result<Bytes>> + Send>
/// async fn main() {
/// let addr = SocketAddr::from(([127, 0, 0, 1], 8082));
/// let render_options: LeptosOptions = LeptosOptions::builder()
/// .pkg_path("/pkg")
/// .pkg_name("leptos_example")
/// .site_root("/pkg")
/// .package_name("leptos_example")
/// .site_address(addr)
/// .reload_port(3001)
/// .environment(&env::var("LEPTOS_ENV")).build();
@ -285,23 +285,21 @@ pub fn render_app_to_stream(
full_path = "http://leptos".to_string() + &path.to_string()
}
let pkg_path = &options.pkg_path;
let pkg_name = &options.pkg_name;
let site_root = &options.site_root;
let package_name = &options.package_name;
// Because wasm-pack adds _bg to the end of the WASM filename, and we want to mantain compatibility with it's default options
// we add _bg to the wasm files if cargo-leptos doesn't set the env var PACKAGE_NAME
// Otherwise we need to add _bg because wasm_pack always does. This is not the same as options.pkg_name, which is set regardless
let wasm_pkg_name;
if std::env::var("PACKAGE_NAME").is_ok() {
wasm_pkg_name = pkg_name
} else {
wasm_pkg_name = pkg_name.push_str("_bg");
// Otherwise we need to add _bg because wasm_pack always does. This is not the same as options.package_name, which is set regardless
let mut wasm_package_name = package_name.clone();
if std::env::var("LEPTOS__PKG_NAME").is_err() {
wasm_package_name.push_str("_bg");
}
let site_ip = &options.site_address.ip().to_string();
let reload_port = options.reload_port;
let leptos_autoreload = match options.leptos_watch {
let leptos_autoreload = match options.watch {
true => format!(
r#"
<script crossorigin="">(function () {{
@ -324,9 +322,9 @@ pub fn render_app_to_stream(
<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<link rel="modulepreload" href="{pkg_path}]{pkg_name}.js">
<link rel="preload" href="{pkg_path}/{wasm_pkg_name}.wasm" as="fetch" type="application/wasm" crossorigin="">
<script type="module">import init, {{ hydrate }} from '{pkg_path}/{pkg_name}.js'; init('{pkg_path}]{wasm_pkg_name}.wasm').then(hydrate);</script>
<link rel="modulepreload" href="{site_root}]{package_name}.js">
<link rel="preload" href="{site_root}/{wasm_package_name}.wasm" as="fetch" type="application/wasm" crossorigin="">
<script type="module">import init, {{ hydrate }} from '{site_root}/{package_name}.js'; init('{site_root}]{wasm_package_name}.wasm').then(hydrate);</script>
{leptos_autoreload}
"#
);

View file

@ -7,23 +7,31 @@ use std::convert::{TryFrom, TryInto};
use std::fs;
use std::{env::VarError, net::SocketAddr, str::FromStr};
use typed_builder::TypedBuilder;
#[derive(Clone, serde::Deserialize)]
pub struct ConfFile {
pub leptos_options: LeptosOptions,
}
/// This struct serves as a convenient place to store details used for configuring Leptos.
/// It's used in our actix and axum integrations to generate the
/// correct path for WASM, JS, and Websockets, as well as other configuration tasks.
/// It shares keys with cargo-leptos, to allow for easy interoperability
#[derive(TypedBuilder, Clone, serde::Deserialize)]
pub struct LeptosOptions {
/// The name of the WASM and JS files generated by wasm-bindgen.
#[builder(setter(into))]
pub package_name: String,
/// The path of the all the files generated by cargo-leptos
#[builder(setter(into))]
pub site_root: String,
/// The path of the WASM and JS files generated by wasm-bindgen from the root of your app
/// By default, wasm-bindgen puts them in `/pkg`.
#[builder(setter(into))]
pub pkg_path: String,
/// The name of the WASM and JS files generated by wasm-bindgen.
#[builder(setter(into))]
pub pkg_name: String,
pub site_pkg_dir: String,
/// Used to configure the running environment of Leptos. Can be used to load dev constants and keys v prod, or change
/// things based on the deployment environment
/// I recommend passing in the result of `env::var("LEPTOS__ENV")`
#[builder(setter(into), default)]
#[builder(setter(into), default=Env::DEV)]
pub env: Env,
/// Provides a way to control the address leptos is served from.
/// Using an env variable here would allow you to run the same code in dev and prod
@ -37,7 +45,7 @@ pub struct LeptosOptions {
/// This controls whether the Leptos Websocket Autoreload JS is included for each page
/// Defaults to false
#[builder(default = false)]
pub leptos_watch: bool,
pub watch: bool,
}
/// An enum that can be used to define the environment Leptos is running in. Can be passed to RenderOptions.
@ -120,21 +128,21 @@ impl TryFrom<String> for Env {
}
}
pub async fn get_configuration() -> Result<LeptosOptions, LeptosConfigError> {
pub async fn get_configuration() -> Result<ConfFile, LeptosConfigError> {
let text = fs::read_to_string("Cargo.toml").map_err(|_| LeptosConfigError::ConfigNotFound)?;
let re: Regex = Regex::new(r#"(?m)^\[package.metadata.leptos\]"#).unwrap();
let start = match re.find(&text) {
Some(found) => found.start(),
None => return Err(LeptosConfigError::ConfigSectionNotFound),
};
println!("Config file content:\n{text}");
// so that serde error messages have right line number
let newlines = text[..start].matches('\n').count();
let toml = "\n".repeat(newlines) + &text[start..];
let input = "\n".repeat(newlines) + &text[start..];
let toml = input.replace("[package.metadata.leptos]", "[leptos_options]");
// Detect the running environment.
// Default to `local` if unspecified.
// Default to `dev` if unspecified.
let environment: Env = std::env::var("LEPTOS_ENV")
.unwrap_or_else(|_| "dev".into())
.try_into()

View file

@ -359,7 +359,6 @@ where
Binary(Vec<u8>),
Url(String),
}
// log!("ARGS TO ENCODE: {:#}", &args);
let args_encoded = match &enc {
Encoding::Url => Payload::Url(
serde_urlencoded::to_string(&args)
@ -373,8 +372,6 @@ where
}
};
//log!("ENCODED DATA: {:#?}", args_encoded);
let content_type_header = match &enc {
Encoding::Url => "application/x-www-form-urlencoded",
Encoding::Cbor => "application/cbor",

View file

@ -28,8 +28,8 @@ pub struct StylesheetProps {
#[builder(setter(into))]
pub href: String,
/// The URL at which the stylesheet can be located.
#[builder(setter(into, strip_option))]
pub id: Option<String>,
#[builder(setter(into), default = "".to_string())]
pub id: String,
}
/// Injects an [HTMLLinkElement](https://developer.mozilla.org/en-US/docs/Web/API/HTMLLinkElement) into the document
@ -69,7 +69,7 @@ pub fn Stylesheet(cx: Scope, props: StylesheetProps) {
} else {
let el = document().create_element("link").unwrap_throw();
el.set_attribute("rel", "stylesheet").unwrap_throw();
if let Some(id) = id{
if id != ""{
el.set_attribute("id", &id).unwrap_throw();
}
el.set_attribute("href", &href).unwrap_throw();