移植新元件
PHP 專案是 HTML 與 CSS 的唯一來源。移植一個元件的意思是:寫一個 Rust builder,輸出跟 Blade view 一樣的元素樹,然後用測試證明。CSS 與 JS 不用動 —— 它們已經在 cg-component.css 與 resources/js/cg/ 裡。
步驟
1. 讀 PHP 版
app/Component/<Name>/<Name>.php:選項、預設值、驗證(哪些情況丟例外)。app/Component/<Name>/<Name>View.blade.php:HTML 結構、class、屬性、條件區塊。- 如果繼承別的元件(例如 Button 繼承
Action),父類別的選項與 view 也要讀。 tests/Snapshots/ComponentShowcase/裡有沒有這個元件的 snapshot;沒有的話,先在 PHP 專案把它加進 showcase 頁,產生 snapshot,再同步過來。
2. 寫 builder
crates/cg-component/src/<name>.rs:
rust
use crate::Component;
use crate::attributes::{AttributeValue, Attributes};
use crate::html::Content;
use crate::options::Color;
#[derive(Clone, Debug)]
pub struct Alert {
body: Content,
color: Color,
dismissible: bool,
attributes: Attributes,
}
impl Alert {
#[must_use]
pub fn new(body: impl Into<Content>) -> Self {
Self { body: body.into(), color: Color::Info, dismissible: false, attributes: Attributes::default() }
}
#[must_use]
pub const fn color(mut self, color: Color) -> Self {
self.color = color;
self
}
#[must_use]
pub const fn dismissible(mut self, dismissible: bool) -> Self {
self.dismissible = dismissible;
self
}
#[must_use]
pub fn attributes(mut self, attributes: Attributes) -> Self {
self.attributes.merge(attributes);
self
}
#[must_use]
pub fn attribute(mut self, name: &str, value: impl Into<AttributeValue>) -> Self {
self.attributes.set(name, value);
self
}
#[must_use]
pub fn class(mut self, classes: &str) -> Self {
self.attributes.add_classes(classes.split_whitespace());
self
}
}
impl Component for Alert {
fn write_html(&self, html: &mut String) {
let color = format!("cg-alert--{}", self.color);
html.push_str("<div");
html.push_str(&self.attributes.render(&["cg-alert", &color]));
html.push_str(" data-component=\"alert\" role=\"status\">");
html.push_str(&self.body.to_markup());
html.push_str("</div>");
}
}(Alert 只是示意結構,真正的 class 與屬性以 PHP 的 view 為準。)
規則:
- 根節點的 class 用
Attributes::render(&[...預設 class])輸出,順序跟 PHP 的attributesHtml()一樣:元件自己的在前、呼叫端的在後。 - 文字一律經過
escape或Content::to_markup()。Content讓呼叫端可以給純文字(跳脫)或Html(原樣)。 - 選項用 enum。 沿用
options.rs的Color、Size等;新的選項集合用同一個options!巨集,自動得到as_str、ALL、Display、FromStr。 - PHP 會丟例外的地方,Rust 也要擋。 寫一個
validate(&self) -> Result<(), String>,訊息照抄 PHP 的;write_html開頭if let Err(m) = self.validate() { panic!("{m}") }。 - 子元件(icon、按鈕)用既有的 builder,呼叫它們的
write_html(html)。 - 跟 PHP 一樣把屬性值轉成字串:布林
true/false怎麼輸出、數字有沒有小數點,都看 Blade 的寫法。
3. 匯出與樣板函式
crates/cg-component/src/lib.rs:
rust
mod alert;
pub use alert::Alert;crates/cg-component/src/jinja.rs:在 add_functions 加上 environment.add_function("cg_alert", alert);,照 badge() 的寫法讀 kwargs:
- 每個參數
kwargs.get::<Option<…>>("name")?。 - 選項字串用
parse(value)?(走FromStr,錯誤訊息會列出可用值)。 - 最後一定要
kwargs.assert_all_used()?,不認得的參數才會報錯。 - 需要
validate()的元件,在回傳前component.validate().map_err(invalid)?,讓樣板拿到錯誤而不是 panic。 - 回傳
safe(&component)。
4. Parity 測試
crates/cg-component/tests/php_parity.rs:
rust
#[test]
fn alerts_match_the_php_overview_snapshot() {
let php = php_component("overview.html", "alert", "已儲存");
let rust = Alert::new("已儲存").color(Color::Success).render();
assert_same_structure(&php, rust.as_str());
}php_component(page, component, label)從 snapshot 頁裡找出data-component="<component>"、文字含label的那個元素。assert_same_structure比對元素樹:忽略縮排空白與屬性順序,其他(標籤、屬性名與值、class、文字)都要一致。the_comparison_catches_differences這個測試確保比對真的會抓到差異,不要刪。
5. 樣板測試與文件
crates/cg-component/tests/templates.rs加一個測試,確認樣板函式的參數與錯誤訊息。- 在這份 wiki 的
components/加一頁,並更新元件總覽的表格。
移植時常見的差異
| 症狀 | 原因 |
|---|---|
| class 一樣但順序不同 → 測試失敗 | class 是一個字串,順序算在內;照 PHP 的順序傳給 render(&[...]) |
多了 class="" | 預設 class 是空字串的條件 class(例如 rounded 為否)要過濾,Attributes::render 已經會略過空字串 |
disabled="disabled" vs disabled | 看 Blade 怎麼寫;Button 輸出的是裸的 disabled |
文字裡的 ' 不一樣 | 用 escape:' 要變成 '(跟 PHP 的 ENT_QUOTES 一致) |
| snapshot 裡找不到元件 | snapshot 太舊;先在 PHP 專案更新 snapshot,再跑 scripts/sync-php-assets.py |
需要 JavaScript 的元件
Modal、Tabs、Table、Combobox 這類元件的行為由 resources/js/cg/ 的 binder 處理(bindComponents() 在 boot 時與每次 cg:rendered 時跑)。只要 Rust 輸出的 HTML 跟 PHP 一樣(尤其是 data-component 與 binder 讀的 data-* 屬性),行為就會跟 PHP 版一樣。
有些 PHP 元件的資料來自 Linker(例如 Chart 的 source('load')、Table 的伺服器端排序)。那部分的伺服器端協定要一起用 LinkerComponent 實作,請先讀 PHP 專案的對應文件。