Icon
從註冊表輸出的 SVG icon。對應 PHP 的 app/Component/Icon/IconView.blade.php 與 IconRegistry。
Rust
rust
use cg_component::{Component, Icon, IconSize};
Icon::new("info").size(IconSize::Lg).label("說明").render(); // 有意義的圖:role="img"
Icon::new("search").render(); // 裝飾性:aria-hidden="true"| 方法 | 預設 | 說明 |
|---|---|---|
Icon::new(name) | — | 名稱要已註冊,否則 panic |
.size(IconSize) | Md | cg-icon--{size} |
.label(text) | 無 | 有 label 就是有意義的圖(role="img" aria-label),沒有就是裝飾(aria-hidden) |
.class(...) / .attribute(...) / .attributes(...) | — | 見樣板函式與屬性 |
.name() | — | 取回名稱 |
當成 Badge / Button 的 icon 時,字串名稱會自動變成 Sm。想要別的大小,就傳一個設定好的 Icon:
rust
Button::new("下載").icon(Icon::new("download").size(IconSize::Md))樣板
jinja
{{ cg_icon("info", size="lg", label="說明") }}
{{ cg_icon("x", attrs={"class": "text-slate-400"}) }}| 參數 | 值 |
|---|---|
name(第一個) | 已註冊的名稱 |
size | xs sm md lg xl |
label | 無障礙標籤 |
attrs | map |
輸出
html
<svg class="cg-icon cg-icon--lg" data-component="icon" data-icon="info" viewBox="0 0 24 24"
fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"
focusable="false" role="img" aria-label="說明">
<path d="M12 16v-4" /><path d="M12 8h.01" /><path d="M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0Z" />
</svg>線條 icon:stroke="currentColor",顏色跟著文字。
內建 icon
跟 PHP 的 IconRegistry::BUILT_INS 同步,全部 viewBox="0 0 24 24":
check chevron-down chevron-right copy grip search menu info warning x user image file download audio
IconDefinition::names() 回傳目前可用的全部名稱(內建 + 自己註冊的)。
註冊自己的 icon
rust
use cg_component::IconDefinition;
// 啟動時(例如 src/cg/mod.rs 的 register())
IconDefinition::register("calendar", &["M8 2v4", "M16 2v4", "M3 10h18", "M5 4h14v18H5z"], "0 0 24 24")
.expect("calendar icon");- 名稱要 kebab-case(
^[a-z][a-z0-9-]*$)。 - 至少一條 path;
viewBox要是四個數字。 - 同名會蓋掉內建的。
- 只接受 path 的
d,不接受任意 SVG markup —— icon 用名稱白名單,業務資料永遠插不進任意 SVG。
register 回 Result<(), String>,啟動時用 expect 讓錯誤馬上浮出來。
錯誤
| 情況 | Rust | 樣板 |
|---|---|---|
| 名稱沒註冊 | panic:沒有註冊的 Icon [x];可用:… | 樣板錯誤,同樣的訊息 |
| 名稱不是 kebab-case | panic:Icon 名稱要用 kebab-case:[x] | 樣板錯誤 |