Skip to content

Porting a new component ​

The PHP project is the single source of HTML and CSS. Porting a component means writing a Rust builder that outputs the same element tree as the Blade view, and proving it with a test. The CSS and JS don't change; they're already in cg-component.css and resources/js/cg/.

Steps ​

1. Read the PHP version ​

  • app/Component/<Name>/<Name>.php: options, defaults, validation (when it throws).
  • app/Component/<Name>/<Name>View.blade.php: HTML structure, classes, attributes, conditional blocks.
  • If it extends another component (Button extends Action, say), read the parent's options and view too.
  • Is there a snapshot of this component in tests/Snapshots/ComponentShowcase/? If not, add it to a showcase page in the PHP project first, generate the snapshot, then sync it over.

2. Write the 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 only illustrates the structure; the real classes and attributes come from the PHP view.)

Rules:

  • Output the root's classes with Attributes::render(&[...default classes]), in the same order as PHP's attributesHtml(): the component's own first, the caller's after.
  • Always pass text through escape or Content::to_markup(). Content lets callers give plain text (escaped) or Html (as is).
  • Options are enums. Reuse Color, Size and the rest from options.rs; define new option sets with the same options! macro to get as_str, ALL, Display and FromStr.
  • Where PHP throws, Rust must block too. Write a validate(&self) -> Result<(), String> with the messages copied from PHP, and start write_html with if let Err(m) = self.validate() { panic!("{m}") }.
  • For child components (icons, buttons), use the existing builders and call their write_html(html).
  • Turn attribute values into strings the way PHP does: how booleans true / false are output and whether numbers have decimals depends on how the Blade view writes them.

3. Export it and add a template function ​

crates/cg-component/src/lib.rs:

rust
mod alert;
pub use alert::Alert;

crates/cg-component/src/jinja.rs: add environment.add_function("cg_alert", alert); to add_functions, and read kwargs the way badge() does:

  • Each parameter is kwargs.get::<Option<…>>("name")?.
  • Option strings go through parse(value)? (via FromStr, so the error lists the valid values).
  • Always finish with kwargs.assert_all_used()?, so unknown parameters are errors.
  • For components with validate(), call component.validate().map_err(invalid)? before returning, so the template gets an error instead of a panic.
  • Return safe(&component).

4. Parity test ​

crates/cg-component/tests/php_parity.rs:

rust
#[test]
fn alerts_match_the_php_overview_snapshot() {
    let php = php_component("overview.html", "alert", "Saved");
    let rust = Alert::new("Saved").color(Color::Success).render();

    assert_same_structure(&php, rust.as_str());
}
  • php_component(page, component, label) finds, in a snapshot page, the element with data-component="<component>" whose text contains label.
  • assert_same_structure compares element trees: indentation whitespace and attribute order are ignored; everything else (tags, attribute names and values, classes, text) must match.
  • The the_comparison_catches_differences test makes sure the comparison really catches differences; don't delete it.

5. Template test and docs ​

  • Add a test to crates/cg-component/tests/templates.rs covering the template function's parameters and error messages.
  • Add a page to components/ in this wiki and update the table on the Components overview.

Common differences when porting ​

SymptomCause
Same classes in a different order → the test failsclass is one string, so order counts; pass them to render(&[...]) in PHP's order
An extra class=""Conditional default classes that are empty strings (rounded off, say) must be filtered; Attributes::render already skips empty strings
disabled="disabled" vs disabledCheck how the Blade view writes it; Button outputs a bare disabled
A ' in text differsUse escape: ' must become &#039; (matching PHP's ENT_QUOTES)
The component isn't found in the snapshotThe snapshot is out of date; update it in the PHP project, then run scripts/sync-php-assets.py

Components that need JavaScript ​

The behavior of components such as Modal, Tabs, Table and Combobox comes from the binders in resources/js/cg/ (bindComponents() runs at boot and on every cg:rendered). As long as Rust outputs the same HTML as PHP (especially data-component and the data-* attributes the binders read), the behavior matches the PHP version.

Some PHP components get their data from Linker (Chart's source('load'), Table's server-side sorting). That server-side protocol has to be implemented with LinkerComponent as well; read the PHP project's documentation for it first.