feat: allow including a view from an external file (closes #2182) (#2862)

This commit is contained in:
Greg Johnston 2024-08-20 09:00:40 -04:00 committed by GitHub
parent b932bd5e04
commit d5096ff2e6
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
1 changed files with 26 additions and 0 deletions

View File

@ -13,6 +13,7 @@ use component::DummyModel;
use proc_macro::TokenStream;
use proc_macro2::{Span, TokenTree};
use quote::{quote, ToTokens};
use std::str::FromStr;
use syn::{parse_macro_input, spanned::Spanned, token::Pub, Visibility};
mod params;
@ -331,6 +332,31 @@ fn normalized_call_site(site: proc_macro::Span) -> Option<String> {
}
}
/// This behaves like the [`view`] macro, but loads the view from an external file instead of
/// parsing it inline.
///
/// This is designed to allow editing views in a separate file, if this improves a user's workflow.
///
/// The file is loaded and parsed during proc-macro execution, and its path is resolved relative to
/// the crate root rather than relative to the file from which it is called.
#[proc_macro_error::proc_macro_error]
#[proc_macro]
pub fn include_view(tokens: TokenStream) -> TokenStream {
let file_name = syn::parse::<syn::LitStr>(tokens).unwrap_or_else(|_| {
abort!(
Span::call_site(),
"the only supported argument is a string literal"
);
});
let file =
std::fs::read_to_string(file_name.value()).unwrap_or_else(|_| {
abort!(Span::call_site(), "could not open file");
});
let tokens = proc_macro2::TokenStream::from_str(&file)
.unwrap_or_else(|e| abort!(Span::call_site(), e));
view(tokens.into())
}
/// Annotates a function so that it can be used with your template as a Leptos `<Component/>`.
///
/// The `#[component]` macro allows you to annotate plain Rust functions as components