Skip to content

物件與允許清單 ​

render 物件宣告「這一塊 DOM 被允許做什麼」,名稱同時是狀態的命名空間。PHP 的 @renderObject,在 Rust 是 runtime::render_object。

語法 ​

rust
use cg_component::runtime::{self, Allow};

let attrs = runtime::render_object("customerPanel", &[Allow::Render, Allow::StateRead, Allow::StateWrite]);

回傳 Attributes,輸出:

html
data-render-blade-object="customerPanel" data-render-allow="render state:read state:write"
Allow屬性值允許什麼
Renderrenderdata-cg-event="renderBlade"、data-render-auto
StateReadstate:readdata-state-text / -show / -class / -is / -is-class
StateWritestate:writedata-state-bind / -set / -toggle / -init,以及 Linker 把 data 寫進 state

PHP 版名稱為空或動作打錯字會丟例外;Rust 版動作是 enum,打錯字編譯不過。名稱請自己給有意義的非空字串。

放到頁面上 ​

三種方式,看你在哪裡組 HTML:

rust
// 1. 給樣板:轉成字串,用 with_html 傳進去
view("page", data! {}).with_html("panel_attrs", Html::raw(attrs.render(&[])));
html
<section{{ panel_attrs }}>…</section>
rust
// 2. 加到元件的根節點上
Badge::new("草稿").attributes(runtime::render_object("summary", &[Allow::StateRead]));

// 3. 跟 Linker 掛載點串在同一個元素上
let attrs = mount.html() + &runtime::render_object("counter", &[Allow::StateRead, Allow::StateWrite]).render(&[]);

Attributes::render(&[]) 回傳開頭帶空白的字串( data-…="…"),所以樣板裡寫成 <section{{ panel_attrs }}>,不要多一個空白。

判定規則 ​

permit(element, action)
  → 往上找最近的 [data-render-blade-object]
      ├─ 碰到 ShadowRoot → 跳到 host 繼續找
      ├─ 到 document 都沒有 → 拒絕 + console.warn
      └─ 找到 → action 在 data-render-allow 裡?
                 ├─ 否 → 拒絕 + console.warn(印出實際清單)
                 └─ 是 → 通過,回傳命名空間
  • 最近的祖先說了算,不繼承。 內層物件沒寫 state:write,外層有也一樣拒絕。
  • 跨 shadow root。 isolated 模式的片段在 shadow DOM 裡,碰到邊界會跳到 host 繼續找。
  • 拒絕不丟例外。 一律 console.warn + 該動作不執行,漏一個屬性不會讓整頁掛掉。

它不是資安機制 ​

使用者當然可以自己在 DevTools 加屬性。render 物件的價值是:

  1. handler 就是真相 —— 看 Rust 的 render_object(...) 就知道這塊能做什麼,不用追 JS。
  2. 擋掉手滑 —— 唯讀區塊不給 StateWrite,誤綁會在 console 看到。

真正的把關永遠在伺服器:片段函式驗 params、Linker 元件驗參數與權限。

最小權限 ​

rust
// 唯讀的摘要卡片:只要 StateRead
runtime::render_object("summary", &[Allow::StateRead]);

// 篩選面板:要寫入,也要觸發重畫
runtime::render_object("filters", &[Allow::Render, Allow::StateRead, Allow::StateWrite]);

同一份模板放兩次 ​

html
<section{{ calc_a }}>{% include "partials/calculator.html" %}</section>
<section{{ calc_b }}>{% include "partials/calculator.html" %}</section>
rust
let all = [Allow::Render, Allow::StateRead, Allow::StateWrite];
view("calc", data! {})
    .with_html("calc_a", Html::raw(runtime::render_object("calcA", &all).render(&[])))
    .with_html("calc_b", Html::raw(runtime::render_object("calcB", &all).render(&[])));

模板裡的 key 一個字都不用改,calcA:display 與 calcB:display 是兩個獨立的值。