元件總覽
cg-component 原本是 PHP(Laravel + Blade)的元件框架:伺服器端渲染 HTML、狀態放在 GET 查詢字串、沒有 JavaScript 也能用。Laravel for Rust 的樣板是 MiniJinja,不能跑 Blade,所以這裡的元件是 Rust struct 自己輸出 HTML,輸出結構跟 PHP 版一致,因此 resources/css/cg-component.css 與 JS 原封不動共用。
已移植的元件
| 元件 | Rust | 樣板函式 | PHP 原始檔 |
|---|---|---|---|
| Badge | Badge | cg_badge(label, …) | app/Component/Badge/ |
| Button | Button | cg_button(label, …) | app/Component/Button/(繼承 Action) |
| Icon | Icon、IconDefinition | cg_icon(name, …) | app/Component/Icon/ |
tests/php_parity.rs 從 PHP 的視覺 snapshot 取出同一個元件,跟 Rust 的輸出比對標籤、屬性、class 與文字:Badge(overview 與 catalog 兩頁)、帶 icon 的 Button、state_set 的 Button、icon-only Button。Icon 包在這些 Badge / Button 裡一起比對。
PHP 版有 61 個元件。其他元件的前端行為(modal.js、tabs.js、table.js、chart/、datePicker.js…)已經在 resources/js/cg/ 裡,CSS 也在 cg-component.css 裡,只差 Rust builder。要用就照移植新元件做一個。
兩種用法
在 Rust 裡建構
use cg_component::{Badge, Button, ButtonType, Color, Component};
use laravel::prelude::*;
use laravel::view::View;
pub async fn show() -> View {
let status = Badge::new("已付款").color(Color::Success).icon("check").render();
let save = Button::new("儲存").icon("check").button_type(ButtonType::Submit).render();
view("orders.show", ()).with_html("status", status).with_html("save", save)
}render()回傳 Laravel 的Html。用View::with_html傳進樣板才不會被跳脫,也可以直接當成回應回傳,或放進另一段 HTML(html.as_str())。- 顏色、尺寸、樣式是 enum,打錯在編譯期就會發現。
- PHP 版會丟例外的規則(例如 icon-only 按鈕沒有 icon、不存在的 icon 名稱),Rust 版會 panic。用
Button::validate()可以先檢查。
在樣板裡呼叫
{{ cg_badge("Draft", color="warning", icon="warning") }}
{{ cg_button("下一步", variant="outline", icon="chevron-right", icon_position="after") }}
{{ cg_button("關閉", variant="ghost", color="neutral", size="sm", icon="x", icon_only=true) }}
{{ cg_icon("info", size="lg", label="說明") }}文字一律跳脫,只有標成 safe 的值(|safe、caller())會當成 HTML。不認得的參數、不合法的選項值直接回樣板錯誤,不會被默默忽略。完整參數見樣板函式與屬性。
共用的選項
| 型別 | 值 | 用在 |
|---|---|---|
Color | Neutral Primary Success Warning Danger Info | Badge(預設 Neutral)、Button(預設 Primary) |
Size | Sm Md Lg | Badge、Button(預設 Md) |
Variant | Solid Outline Ghost | Button(預設 Solid) |
IconSize | Xs Sm Md Lg Xl | Icon(預設 Md;當成 Badge / Button 的 icon 時是 Sm) |
IconPosition | Before After | Button |
ButtonType | Button Submit Reset | Button(預設 Button) |
每個 enum 都有 as_str()、ALL、Display 與 FromStr(樣板用小寫字串,例如 "warning")。FromStr 失敗的訊息會列出可用值。
共用的屬性 API
每個元件都有:
Badge::new("x")
.class("ml-2 shrink-0") // 追加 class
.attribute("data-state-text", "matchCount") // 單一屬性
.attributes(runtime::render_object(...)); // 合併一組 Attributes規則跟 PHP 的 HasAttributes 一樣:元件自己的 class 在前、你的 class 在後;其他屬性依設定順序;同名屬性後設的蓋掉先設的;true 輸出 name=""、false 不輸出。屬性名稱要符合 ^[A-Za-z_:][A-Za-z0-9:._-]*$,不合法時 panic。見樣板函式與屬性。
沒有 JavaScript 也能用
元件輸出的是純 HTML:Badge、Icon 沒有行為;Button 是真的 <button>,type="submit" 在沒有 JS 時照常送出表單。互動(片段渲染、Linker)是在這之上的漸進增強。頁面狀態放在 GET 查詢字串,例如篩選表單用 method="GET",重新整理與分享網址都能保留狀態。