11 个版本 (5 个重大更改)
0.5.0 | 2020年7月11日 |
---|---|
0.4.1 | 2020年6月6日 |
0.3.0 | 2020年6月2日 |
0.2.2 | 2020年4月12日 |
0.0.1 | 2020年3月12日 |
#2299 in 网页开发
每月下载量:91
用于 3 crates
40KB
824 行
CSSinRust
CSSinRust 通过在 web-sys 应用程序中实现 CSS 样式的新方式,提供了一种组件级别的 CSS 样式体验。其目的是通过提供一种在组件级别进行样式的途径,使 Rust 编写的网页前端更具吸引力。该库的设计可以理论上与任何框架一起工作。然而,目前只有 yew 的实现。欢迎 Pull requests,无论是为了提高代码质量、集成解决方案还是功能。
请注意,此项目仍在积极开发中,未来的更改可能会破坏您的代码。我仍然不确定整体设计,但我需要这样的东西,我相信其他人也需要。
如果您想保持最新状态或想支持我的工作,请访问以下平台
语法
目前仅支持一个非常基本的语法集合。尽管语法与 CSS 非常相似,但 CSSinRust 中有一些受 SASS 和 JS 中的 styled-components 启发的特定性。
以下是基本样式定义的示例。
let style = match css_in_rust::Style::create(
"Component", // The class prefix
// The actual css
r#"
background-color: red;
.nested {
background-color: blue;
width: 100px
}"#,
) {
Ok(style) => style,
Err(error) => {
panic!("An error occured while creating the style: {}", error);
}
};
所以,所有不在条件块中的内容都将应用于应用此样式类的组件。具体如何应用取决于所使用的框架。下面有支持框架的示例。
您放入的样式将被解析并转换为实际的 CSS,并自动附加到您的 HTML 文档的头部。
您还可以使用 &
标识符来在样式化元素上使用 CSS 选择器或伪类
&:hover {
background-color: #d0d0d9;
}
您还可以使用其他 CSS 规则,例如关键帧
@keyframes mymove {
from {
top: 0px;
}
to {
top: 200px;
}
}
请注意,目前,CSSinRust 不会解析动画名称以使其唯一。如果您需要此功能,请对该问题进行投票或如果尚未创建,请创建一个新问题。
现在也支持媒体查询!
@media only screen and (max-width: 600px) {
background-color: #303040;
.nested {
background-color: lightblue;
}
&:hover {
background-color: #606072;
}
}
集成
Seed
为了启用所有 yew 集成,请在您的 Cargo.toml
中使用 CSSinRust 的 seed_integration
功能。然后创建一个样式并像这样与 yew 一起使用
pub(crate) struct Model {
pub style: css_in_rust::Style,
}
impl Default for Model {
fn default() -> Self {
let style = match css_in_rust::Style::create(
String::from("Component"),
String::from(
r#"
background-color: #303040;
color: #DDDDDD;
padding: 5px;
&:hover {
background-color: #606072;
}
"#,
),
) {
Ok(style) => style,
Err(error) => {
panic!("An error occured while creating the style: {}", error);
}
};
Self {
style: style,
}
}
}
#[derive(Clone)]
pub(crate) enum Msg {
}
pub(crate) fn update(msg: Msg, model: &mut Model, _: &mut impl Orders<Msg>) {
}
pub(crate) fn view(model: &Model) -> impl View<Msg> {
div![
model.style.clone(),
"Hello, World"
]
}
Yew
为了启用所有 Yew 集成,在您的 Cargo.toml
中使用 CSSinRust 的功能 yew_integration
。然后创建一个样式,并像这样与 Yew 一起使用
impl Component for HelloComponent {
type Message = ();
type Properties = ();
fn create(_: Self::Properties, _: ComponentLink<Self>) -> Self {
let style = match css_in_rust::Style::create(
"Component",
"background-color: #505050;",
) {
Ok(style) => style,
Err(error) => {
panic!("An error occured while creating the style: {}", error);
}
};
HelloComponent {
style,
}
}
fn update(&mut self, _: Self::Message) -> ShouldRender {
true
}
fn view(&self) -> Html {
html! {<div class=self.style.clone()>{"Hello World!"}</div>}
}
}
CSSinRust 版本和对应的 Yew 版本
Yew 版本 | CSSinRust 版本 |
---|---|
0.14.x | 0.2.2 |
0.15.x | 0.3.x |
0.16.x | 0.4.x |
0.17.x | 0.5.x |
依赖项
~0.8–4.5MB
~88K SLoC