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

Type-checking and IDE completions for HTML tags #354

Merged
merged 3 commits into from
Feb 9, 2022
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
14 changes: 10 additions & 4 deletions packages/sycamore-macro/src/view/codegen.rs
Original file line number Diff line number Diff line change
Expand Up @@ -72,9 +72,15 @@ impl Codegen {
children,
} = elem;

let tag = match tag {
ElementTag::Builtin(id) => id.to_string(),
ElementTag::Custom(s) => s.clone(),
let quote_tag = match tag {
ElementTag::Builtin(id) => quote! {
let __el = ::sycamore::generic_node::GenericNode::element(
<::sycamore::html::#id as ::sycamore::html::SycamoreElement>::TAG_NAME
);
},
ElementTag::Custom(tag_s) => quote! {
let __el = ::sycamore::generic_node::GenericNode::element(#tag_s);
},
};

let quote_attrs: TokenStream = attrs.iter().map(|attr| self.attribute(attr)).collect();
Expand Down Expand Up @@ -229,7 +235,7 @@ impl Codegen {
};

quote! {{
let __el = ::sycamore::generic_node::GenericNode::element(#tag);
#quote_tag
#quote_attrs
#quote_children
__el
Expand Down
1 change: 1 addition & 0 deletions packages/sycamore-macro/tests/view/element-fail.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ fn compile_fail<G: GenericNode>() {
let _: View<G> = view! { ctx, button(disabled) };
let _: View<G> = view! { ctx, button(on:click) };
let _: View<G> = view! { ctx, button(unknown:directive="123") };
let _: View<G> = view! { ctx, unknownelement };

let _: View<G> = view! { ctx, button(a.b.c="123") };

Expand Down
26 changes: 16 additions & 10 deletions packages/sycamore-macro/tests/view/element-fail.stderr
Original file line number Diff line number Diff line change
Expand Up @@ -17,20 +17,26 @@ error: unknown directive `unknown`
| ^^^^^^^

error: expected `=`
--> tests/view/element-fail.rs:9:47
|
9 | let _: View<G> = view! { ctx, button(a.b.c="123") };
| ^
--> tests/view/element-fail.rs:10:47
|
10 | let _: View<G> = view! { ctx, button(a.b.c="123") };
| ^

error: unexpected end of input, children and dangerously_set_inner_html cannot be both set
--> tests/view/element-fail.rs:11:26
--> tests/view/element-fail.rs:12:26
|
11 | let _: View<G> = view! { ctx,
12 | let _: View<G> = view! { ctx,
| __________________________^
12 | | p(dangerously_set_inner_html="<span>Test</span>") {
13 | | "Error"
14 | | }
15 | | };
13 | | p(dangerously_set_inner_html="<span>Test</span>") {
14 | | "Error"
15 | | }
16 | | };
| |_________^
|
= note: this error originates in the macro `view` (in Nightly builds, run with -Z macro-backtrace for more info)

error[E0412]: cannot find type `unknownelement` in module `sycamore::html`
--> tests/view/element-fail.rs:8:39
|
8 | let _: View<G> = view! { ctx, unknownelement };
| ^^^^^^^^^^^^^^ not found in `sycamore::html`
5 changes: 4 additions & 1 deletion packages/sycamore/src/component.rs
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,10 @@ impl<'a, G: GenericNode> Children<'a, G> {
}

/// Create a new [`Children`] from a closure.
pub fn new(_ctx: ScopeRef<'a>, f: impl FnOnce(BoundedScopeRef<'_, 'a>) -> View<G> + 'a) -> Self {
pub fn new(
_ctx: ScopeRef<'a>,
f: impl FnOnce(BoundedScopeRef<'_, 'a>) -> View<G> + 'a,
) -> Self {
Self { f: Box::new(f) }
}
}
196 changes: 196 additions & 0 deletions packages/sycamore/src/html/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,196 @@
//! HTML tag definitions.
//!
//! _Documentation sources: https://developer.mozilla.org/en-US/_

/// Represents an element.
pub trait SycamoreElement {
const TAG_NAME: &'static str;
const NAME_SPACE: Option<&'static str>;
}

/// MBE for generating elements.
macro_rules! define_elements {
(
$(
$(#[$attr:meta])*
$el:ident {
$(
$(#[$attr_method:meta])*
$at:ident: $ty:path,
)*
},
)*
) => {
$(
#[allow(non_camel_case_types)]
#[doc = concat!("Build a [`<", stringify!($el), ">`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/", stringify!($el), ") element.")]
$(#[$attr])*
pub struct $el;

impl SycamoreElement for $el {
const TAG_NAME: &'static str = stringify!($el);
const NAME_SPACE: Option<&'static str> = None;
}
)*
};
}

// A list of valid HTML5 elements (does not include removed or obsolete elements).
define_elements! {
/// The `<a>` HTML element (or anchor element), with its `href` attribute, creates a hyperlink to web pages, files, email addresses, locations in the same page, or anything else a URL can address.
///
/// Content within each `<a>` should indicate the link's destination. If the `href` attribute is present, pressing the enter key while focused on the `<a>` element will activate it.
a {},
abbr {},
address {},
area {},
article {},
aside {},
audio {},
b {},
base {},
bdi {},
bdo {},
blockquote {},
br {},
/// The `<button>` HTML element represents a clickable button, used to submit forms or anywhere in a document for accessible, standard button functionality.
///
/// By default, HTML buttons are presented in a style resembling the platform the user agent runs on, but you can change buttons’ appearance with CSS.
button {},
canvas {},
caption {},
cite {},
code {},
col {},
colgroup {},
data {},
datalist {},
dd {},
del {},
details {},
dfn {},
dialog {},
/// The `<div>` HTML element is the generic container for flow content. It has no effect on the content or layout until styled in some way using CSS (e.g. styling is directly applied to it, or some kind of layout model like Flexbox is applied to its parent element).
///
/// As a "pure" container, the `<div>` element does not inherently represent anything. Instead, it's used to group content so it can be easily styled using the class or id attributes, marking a section of a document as being written in a different language (using the lang attribute), and so on.
///
/// # Usage notes
/// The `<div>` element should be used only when no other semantic element (such as `<article>` or `<nav>`) is appropriate.
div {},
dl {},
dt {},
em {},
embed {},
fieldset {},
figcaption {},
figure {},
footer {},
form {},
head {},
header {},
hgorup {},
h1 {},
h2 {},
h3 {},
h4 {},
h5 {},
h6 {},
hr {},
html {},
i {},
iframe {},
img {},
/// The `<input>` HTML element is used to create interactive controls for web-based forms in order to accept data from the user; a wide variety of types of input data and control widgets are available, depending on the device and user agent. The <input> element is one of the most powerful and complex in all of HTML due to the sheer number of combinations of input types and attributes.
input {},
ins {},
kbd {},
keygen {},
/// The `<label>` HTML element represents a caption for an item in a user interface.
///
/// Associating a `<label>` with an `<input>` element offers some major advantages:
/// * The label text is not only visually associated with its corresponding text input; it is programmatically associated with it too. This means that, for example, a screen reader will read out the label when the user is focused on the form input, making it easier for an assistive technology user to understand what data should be entered.
/// * When a user clicks or touches/taps a label, the browser passes the focus to its associated input (the resulting event is also raised for the input). That increased hit area for focusing the input provides an advantage to anyone trying to activate it — including those using a touch-screen device.
///
/// To associate the `<label>` with an `<input>` element, you need to give the `<input>` an `id` attribute. The `<label>` then needs a for attribute whose value is the same as the input's `id`.
///
/// Alternatively, you can nest the `<input>` directly inside the `<label>`, in which case the `for` and `id` attributes are not needed because the association is implicit:
///
/// ```html
/// <label>Do you like peas?
/// <input type="checkbox" name="peas">
/// </label>
/// ```
/// The form control that a label is labeling is called the labeled control of the label element. Multiple labels can be associated with the same form control:
///
/// ```html
/// <label for="username">Enter your username:</label>
/// <input id="username">
/// <label for="username">Forgot your username?</label>
/// ```
/// Elements that can be associated with a `<label>` element include `<button>`, `<input>` (except for `type="hidden"`), `<meter>`, `<output>`, `<progress>`, `<select>` and `<textarea>`.
label {},
legend {},
/// The `<li>` HTML element is used to represent an item in a list. It must be contained in a parent element: an ordered list (`<ol>`), an unordered list (`<ul>`), or a menu (`<menu>`). In menus and unordered lists, list items are usually displayed using bullet points. In ordered lists, they are usually displayed with an ascending counter on the left, such as a number or letter.
li {},
link {},
main {},
map {},
mark {},
menu {},
menuitem {},
meta {},
meter {},
nav {},
noscript {},
object {},
/// The `<ol>` HTML element represents an ordered list of items — typically rendered as a numbered list.
ol {},
optgroup {},
option {},
output {},
/// The `<p>` HTML element represents a paragraph. Paragraphs are usually represented in visual media as blocks of text separated from adjacent blocks by blank lines and/or first-line indentation, but HTML paragraphs can be any structural grouping of related content, such as images or form fields.
///
/// Paragraphs are block-level elements, and notably will automatically close if another block-level element is parsed before the closing `</p>` tag.
p {},
param {},
picture {},
pre {},
progress {},
q {},
rp {},
rt {},
ruby {},
s {},
samp {},
script {},
section {},
select {},
small {},
source {},
/// The `<span>` HTML element is a generic inline container for phrasing content, which does not inherently represent anything. It can be used to group elements for styling purposes (using the class or id attributes), or because they share attribute values, such as lang. It should be used only when no other semantic element is appropriate. `<span>` is very much like a `<div>` element, but `<div>` is a block-level element whereas a `<span>` is an inline element.
span {},
strong {},
style {},
sub {},
summary {},
sup {},
svg {},
table {},
tbody {},
td {},
template {},
textarea {},
tfoot {},
th {},
thead {},
time {},
title {},
tr {},
track {},
u {},
/// The `<ul>` HTML element represents an unordered list of items, typically rendered as a bulleted list.
ul {},
var {},
video {},
wbr {},
}
1 change: 1 addition & 0 deletions packages/sycamore/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ pub mod flow;
#[cfg(feature = "suspense")]
pub mod futures;
pub mod generic_node;
pub mod html;
pub mod motion;
pub mod noderef;
pub mod portal;
Expand Down
5 changes: 3 additions & 2 deletions packages/sycamore/src/suspense.rs
Original file line number Diff line number Diff line change
Expand Up @@ -190,8 +190,8 @@ impl<'a> ScopeUseTransition<'a> for Scope<'a> {
mod tests {
use sycamore_futures::provide_executor_scope;

use crate::generic_node::render_to_string_await_suspense;
use super::*;
use crate::generic_node::render_to_string_await_suspense;

#[tokio::test]
async fn suspense() {
Expand Down Expand Up @@ -234,6 +234,7 @@ mod tests {
};
transition.start(|| trigger.set(()));
});
}).await;
})
.await;
}
}