Rust样式管理库starbase_styles的使用,starbase_styles提供高效统一的UI组件样式解决方案

Rust样式管理库starbase_styles的使用,starbase_styles提供高效统一的UI组件样式解决方案

starbase_styles是一个用于终端样式、错误消息等的实用工具库。

Crates.io Crates.io

安装

在项目目录中运行以下Cargo命令:

cargo add starbase_styles

或者在Cargo.toml中添加以下行:

starbase_styles = "0.6.3"

使用示例

下面是一个使用starbase_styles的完整示例:

use starbase_styles::{color, style};

fn main() {
    // 创建带有颜色的文本
    let colored_text = color::red("这是红色文本");
    println!("{}", colored_text);

    // 创建带有背景色的文本
    let styled_text = style("这是带样式的文本")
        .fg(color::BLUE)
        .bg(color::YELLOW)
        .bold()
        .underline();
    println!("{}", styled_text);

    // 创建错误消息
    let error = style("错误: 文件未找到")
        .fg(color::RED)
        .bold();
    eprintln!("{}", error);

    // 创建成功消息
    let success = style("操作成功!")
        .fg(color::GREEN)
        .italic();
    println!("{}", success);
}

完整示例代码

use starbase_styles::{color, style};

fn main() {
    // 标题样式
    let title = style("===== 应用程序控制台 =====")
        .fg(color::CYAN)
        .bold()
        .underline();
    println!("\n{}\n", title);

    // 警告消息
    let warning = style("警告: 系统资源不足")
        .fg(color::YELLOW)
        .italic();
    println!("{}", warning);

    // 信息消息
    let info = style("信息: 正在处理数据...")
        .fg(color::BLUE);
    println!("{}", info);

    // 带背景色的强调文本
    let highlight = style("重要提示: 请保存您的工作")
        .fg(color::WHITE)
        .bg(color::MAGENTA)
        .bold();
    println!("\n{}\n", highlight);

    // 多级状态显示
    let status1 = style("[1/3] 初始化完成")
        .fg(color::GREEN);
    let status2 = style("[2/3] 处理中...")
        .fg(color::YELLOW);
    let status3 = style("[3/3] 未开始")
        .fg(color::GRAY);
    
    println!("{}", status1);
    println!("{}", status2);
    println!("{}\n", status3);

    // 自定义RGB颜色
    let custom_color = style("自定义颜色文本")
        .fg((255, 165, 0)); // 橙色
    println!("{}", custom_color);
}

功能说明

starbase_styles提供以下功能:

  1. 终端文本颜色和样式控制
  2. 统一的错误消息格式
  3. 预定义的颜色常量
  4. 链式样式调用方式

项目信息

这个库特别适合需要统一终端输出样式或创建美观CLI界面的Rust项目。


1 回复

Rust样式管理库starbase_styles使用指南

概述

starbase_styles是一个用于Rust应用程序的UI组件样式管理库,旨在提供高效统一的样式解决方案。它特别适合需要一致UI风格的大型项目或组件库。

主要特性

  • 集中式样式管理
  • 高性能样式计算
  • 类型安全的样式定义
  • 支持响应式设计
  • 与常见Rust UI框架兼容

安装

在Cargo.toml中添加依赖:

[dependencies]
starbase_styles = "0.5"

基本用法

1. 定义样式主题

use starbase_styles::{Theme, Style};

let theme = Theme::builder()
    .with_color("primary", "#4f46e5")
    .with_color("secondary", "#f43f5e")
    .with_spacing("sm", "0.5rem")
    .with_spacing("md", "1rem")
    .build();

2. 创建组件样式

use starbase_styles::{Style, style};

let button_style = style! {
    padding: theme.spacing("md"),
    background_color: theme.color("primary"),
    border_radius: "0.25rem",
    hover: {
        background_color: theme.color("secondary"),
    }
};

3. 应用样式到组件

use starbase_styles::Styled;

#[derive(Styled)]
struct Button {
    #[style]
    style: Style,
    // 其他字段...
}

let button = Button {
    style: button_style,
    // 其他字段...
};

高级功能

响应式样式

let responsive_style = style! {
    padding: ["0.5rem", "1rem", "1.5rem"], // 分别对应移动端、平板、桌面
    font_size: ["14px", "16px", "18px"],
};

样式继承

let base_button = style! {
    padding: "1rem",
    border_radius: "0.25rem",
};

let primary_button = style! {
    @inherit: base_button,
    background_color: theme.color("primary"),
};

动态样式计算

let dynamic_style = style! {
    background_color: |props: &ButtonProps| {
        if props.is_disabled {
            theme.color("disabled")
        } else {
            theme.color("primary")
        }
    },
};

最佳实践

  1. 主题集中管理:在应用顶层定义主题,通过上下文传递

  2. 组件样式分离:为每个组件创建单独的样式模块

  3. 样式组合:使用@inherit重用基础样式

  4. 性能优化:对于频繁更新的组件,使用memo_style!宏缓存样式计算结果

use starbase_styles::memo_style;

let memoized = memo_style! {
    // 复杂样式计算...
};

完整示例:主题化按钮组件

use starbase_styles::{style, Style, Styled, Theme};

// 定义按钮属性
#[derive(Debug, Clone)]
struct ButtonProps {
    is_disabled: bool,
    size: ButtonSize,
}

#[derive(Debug, Clone)]
enum ButtonSize {
    Small,
    Medium,
    Large,
}

// 定义可样式化的按钮组件
#[derive(Styled)]
struct Button {
    #[style]
    style: Style,
    props: ButtonProps,
    text: String,
}

impl Button {
    // 默认样式
    fn default_style(theme: &Theme) -> Style {
        style! {
            padding: theme.spacing("md"),
            border_radius: "0.25rem",
            cursor: "pointer",
            transition: "all 0.2s ease",
            hover: {
                opacity: 0.9,
            },
            disabled: {
                opacity: 0.6,
                cursor: "not-allowed",
            }
        }
    }
    
    // 主要按钮样式
    fn primary_style(theme: &Theme) -> Style {
        style! {
            @inherit: Self::default_style(theme),
            background_color: theme.color("primary"),
            color: "white",
            hover: {
                background_color: theme.color("secondary"),
            }
        }
    }
    
    // 根据尺寸获取样式
    fn size_style(size: &ButtonSize) -> Style {
        match size {
            ButtonSize::Small => style! { padding: "0.5rem", font_size: "0.875rem" },
            ButtonSize::Medium => style! { padding: "1rem", font_size: "1rem" },
            ButtonSize::Large => style! { padding: "1.5rem", font_size: "1.25rem" },
        }
    }
    
    // 创建新按钮
    fn new(text: &str, is_primary: bool, props: ButtonProps, theme: &Theme) -> Self {
        // 基础样式
        let base_style = if is_primary {
            Self::primary_style(theme)
        } else {
            Self::default_style(theme)
        };
        
        // 尺寸样式
        let size_style = Self::size_style(&props.size);
        
        // 合并样式
        let merged_style = style! {
            @inherit: base_style,
            @inherit: size_style,
        };
        
        Self {
            style: merged_style,
            props,
            text: text.to_string(),
        }
    }
    
    // 渲染按钮
    fn render(&self) -> String {
        format!(
            "<button style=\"{}\" {}>{}</button>",
            self.style.to_string(),
            if self.props.is_disabled { "disabled" } else { "" },
            self.text
        )
    }
}

fn main() {
    // 创建主题
    let theme = Theme::builder()
        .with_color("primary", "#4f46e5")
        .with_color("secondary", "#f43f5e")
        .with_spacing("md", "1rem")
        .build();
    
    // 创建不同状态的按钮
    let primary_button = Button::new(
        "主要按钮",
        true,
        ButtonProps {
            is_disabled: false,
            size: ButtonSize::Medium,
        },
        &theme,
    );
    
    let disabled_button = Button::new(
        "禁用按钮",
        false,
        ButtonProps {
            is_disabled: true,
            size: ButtonSize::Small,
        },
        &theme,
    );
    
    let large_button = Button::new(
        "大型按钮",
        true,
        ButtonProps {
            is_disabled: false,
            size: ButtonSize::Large,
        },
        &theme,
    );
    
    // 渲染按钮
    println!("{}", primary_button.render());
    println!("{}", disabled_button.render());
    println!("{}", large_button.render());
}

这个完整示例展示了如何使用starbase_styles创建一个功能完备的主题化按钮组件,包括:

  1. 主题定义和管理
  2. 基础样式和派生样式
  3. 响应不同状态(禁用状态)
  4. 支持多种尺寸
  5. 样式继承和合并
  6. 最终渲染输出

starbase_styles通过提供类型安全、高性能的样式管理方案,可以显著提高Rust UI开发效率和一致性。

回到顶部