Skip to content

Rust API 字典 ​

cg_component crate 的公開 API。產生的 rustdoc 是最終依據:

bash
cargo doc -p cg-component --no-deps --open

cg_component ​

元件 ​

型別建構方法
BadgeBadge::new(impl Into<Content>)color(Color) size(Size) icon(impl Into<IconInput>) rounded(bool) class(&str) attribute(&str, impl Into<AttributeValue>) attributes(Attributes)
ButtonButton::new(impl Into<Content>)color size variant(Variant) icon icon_position(IconPosition) icon_only(Option<&str>) disabled(bool) button_type(ButtonType) name(impl Into<String>) value(impl Into<ButtonValue>) state_set(&str, impl Into<Value>) state_toggle(&str) opens_modal(&str) closes_modal(&str) class attribute attributes validate() -> Result<(), String>
IconIcon::new(impl Into<String>)size(IconSize) label(impl Into<String>) class attribute attributes name() -> &str

全部實作 Component。builder 方法都是 #[must_use]、吃掉 self 回傳 Self。

trait方法
Componentwrite_html(&self, &mut String)(必須實作);render(&self) -> Html(預設實作)

選項 enum ​

型別值(as_str())預設
Colorneutral primary success warning danger infoBadge Neutral、Button Primary
Sizesm md lgMd
Variantsolid outline ghostSolid
IconSizexs sm md lg xlMd(當 Badge / Button 的 icon 時 Sm)
IconPositionbefore afterBefore
ButtonTypebutton submit resetButton

每個 enum 都有 ALL: &[Self]、as_str()、Display、FromStr(錯誤訊息列出可用值)。

屬性與 HTML ​

項目說明
Attributesset(&mut self, &str, impl Into<AttributeValue>)、add_classes(iter)、merge(Self)、get(&str) -> Option<&AttributeValue>、render(&[&str]) -> String。見樣板函式與屬性
AttributeValue屬性值;From<&str>、String、bool、整數、f64
Content元件內容:純文字(跳脫)或 Html(原樣)。to_markup()、as_text()
escape(&str) -> Cow<str>跟 PHP e() 一樣跳脫 & < > " '
ButtonValueButton::value 的參數;From 字串、數字、bool(true → 1)
IconInputicon(..) 的參數;From<&str>、String(變成 Sm 的 Icon)、Icon。into_icon()

Icon 註冊表 ​

函式說明
IconDefinition::register(name, paths, view_box) -> Result<(), String>註冊或覆蓋 icon
IconDefinition::find(name) -> Result<IconDefinition, String>查詢
IconDefinition::names() -> Vec<String>全部名稱

樣板 ​

函式說明
cg_component::register(&mut ViewConfig)在 .with_views 裡呼叫,加入全部樣板函式
cg_component::jinja::add_functions(&mut Environment)對裸的 MiniJinja Environment 加入(測試用)

樣板函式:cg_badge cg_button cg_icon cg_head cg_html_attrs。見樣板函式與屬性。

cg_component::runtime ​

項目說明
routes::<U>(&mut Router)註冊四條端點:POST /{prefix}/render、/render/token(60/分)、/linker(120/分)、/linker/stateless/{alias}/call(120/分)。U 是使用者 model
share_headweb middleware:為頁面請求發 render token、把 head 標籤分享給樣板
HEAD_VARIABLE / HTML_ATTRIBUTE_VARIABLEshare_head 分享的樣板變數名稱(cg_head_tags、cg_html_attribute)
AllowRender / StateRead / StateWrite
render_object(name, &[Allow]) -> Attributesrender 物件(授權邊界 + 命名空間)
render_trigger(name, RenderMethod, Option<&str>, &[(&str, &str)]) -> Attributes點擊觸發渲染;第三個參數是 target
render_auto(name, RenderMethod, &[(&str, &str)]) -> Attributes載入後自動渲染
kebab(&str) -> StringcustomerId → customer-id(data-param-* 用)

runtime::render ​

項目說明
register(name, Fn(RenderInput) -> Future<Output = laravel::Result<Html>>)註冊片段
has(name) -> bool是否註冊
RenderInputmethod: RenderMethod、params: BTreeMap<String, String>、target: Option<String>、url: Option<String>;param(&str) -> Option<&str>
RenderMethodComponents / Toast / Page / Isolated;as_str()
POOL每個 session 保留的 token 數(16)
SESSION_KEYtoken 存放的 session key(cg_render_before)
issue(&Session) -> String / consume(&Session, &str) -> bool發 / 用 token(測試或自訂端點用)
fingerprint(&str) -> String片段指紋(SHA-256 前 16 bytes 的 hex)
render / token端點 handler(由 routes 註冊)

runtime::endpoints ​

項目說明
prefix()目前的端點前綴
meta_name()端點 meta 的名稱(m-…)
render_url() / render_token_url() / linker_url()帶前綴的路徑
meta_payload()meta 內容 {"r":…,"t":…,"l":…}
html_attribute()<html> 用的 data-cg-endpoints="…"
head_tags(csrf, render_token)<head> 用的 meta 標籤
derive(purpose, key) / app_key()底層:HMAC-SHA256 衍生
PURPOSE_PREFIX / PURPOSE_META衍生用的 purpose 字串

runtime::linker ​

項目說明
LinkerComponenttrait,需要 Serialize + DeserializeOwned + Default + Send + Sync + 'static。常數 ALIAS、MODE(預設 Stateful)、METHODS、ALLOWS_REFERER_URLS(預設空 = 不限);方法 mount(預設什麼都不做)、booted、call
LinkerContextuser: String、alias: &'static str、instance: Option<String>、referer: Option<String>
LinkerModeStateful / Stateless
Argsserde_json::Map<String, Value>
register::<C>()註冊元件(啟動時)
mount::<C, U>(&user, Args) -> laravel::Result<LinkerMount>建立實例或簽 URL
LinkerMountattributes: Attributes;html() -> String
bind(&Value) -> Result<(String, String), String>data-linker-bind
MIN_DELAY_MS800
LinkerResponseok() fail(FailureKind) validation(iter) policy(&str) not_found();message(&str) data(&str, impl Serialize) then(Action) catch(Action) always(Action);is_ok() kind() to_json() status()
FailureKindValidation Policy Expired Conflict Service Fatal;default_message()、status()(Expired / Conflict 為 409,其他 200)
Actionnew(&str, Value) -> Result<Self, String>;捷徑 scroll_to class focus reset state_set state_clear render_fragment render_page toast confirm;name()
OnThen / Catch / Always
BUILTIN_ACTIONS內建動作規格表
messages固定文字:VALIDATION POLICY EXPIRED CONFLICT BUSY NOT_FOUND FATAL UNKNOWN_METHOD REFERER UNAUTHENTICATED UNVERIFIED
stateful / stateless端點 handler(由 routes 註冊)

runtime::linker::store ​

Stateful 實例的儲存。通常不需要直接用;測試或管理工具可能會用到。

項目說明
IDLE / RENEW_INTERVAL / MAX_LIFETIME1800 / 90 / 28800 秒
Recordalias state rev created_at renewed_at expires_at absolute_expires_at
key(user, instance)linker:{user}:{instance}
create / find / update / renew非同步存取

JavaScript(resources/js/cg/runtime.js) ​

匯出說明
boot(root?)(default)綁定 state、元件、Linker,跑自動渲染
registerLinkerAction(name, fn)註冊自訂動作,fn(args, context)
within(context, selector)在掛載點內 querySelector
callLinker(element, method, args)從 JS 呼叫 Linker 方法
renderBlade(options) / renderBladeAuto(root)直接要求片段
bindState / bindLinker / bindComponents個別綁定(通常由 boot 處理)
CGEventPHP 版的事件基底類別

同步自 PHP 專案;行為以 PHP 專案的文件與原始碼為準。