LeanUI Docs
← Open LeanUI Studio GitHub

08 · Control Templates, Multi-Root Composition & Visual Verification#

LeanUI Studio treats Control Templates (❖) and Built-In Verified / Custom Component Templates as first-class citizens of the main Studio Graph Canvas — giving both scopes 100% parity with main app editing (infinite pan/zoom, obstacle-avoiding wire routing, minimizable minimap, groups, reroute waypoints, wireless portals, undo/redo, 5 auto-layouts, Live Preview, and real Lean 4 proving) while adding specialized tooling for reusable templated controls.


1. How Control Template Verification Works Visually#

Every time you edit a template or its parent screen, LeanUI runs a two-tier verification pipeline whose results are painted directly onto the Graph Canvas, Live Preview, Verification Console, and ✓ Proofs panel:

Mermaid Diagram
flowchart LR
  subgraph S1["Parent App Canvas (e.g. VerifiedTemplatesStudio)"]
    RES["resource: VerifiedTokens<br/>(EN/DE + Light/Dark Tokens)"]
    STY["style: VerifiedSurface<br/>(WCAG AAA 15.8:1)"]
    TPL["control_template: MetricGridTile<br/>(root: grid 2× + nested ViewNodes)"]
    TC["templated_control: ChecksGridTile<br/>(propValues + ContentPresenter children)"]
    RES -->|"res"| TPL
    RES -->|"res"| TC
    TPL -->|"template"| TC
  end

  subgraph S2["Drilled-In ControlTemplate Canvas (❖ Scope)"]
    P["tpl_prop: {tpl:label}, {tpl:tag}"]
    R["tpl_resource: {res:surfaceBg}, {res:surfaceFg}"]
    ROOT["tpl_root: MetricGridTile<br/>(root: grid 2×, bg/fg/border)"]
    STAT["view: stat (AuditStat)"]
    BADGE["view: badge (RootBadge)"]
    R -->|"bg / fg"| ROOT
    ROOT -->|"children → parent"| STAT
    ROOT -->|"children → parent"| BADGE
    P -->|"text"| BADGE
  end

  subgraph S3["Tier 1: Instant Static Gate (<15 ms)"]
    CHK["TPL001 ≥1 part/view<br/>TPL002 {tpl:...} declared<br/>TPL003 {res:...} exists<br/>TPL004 wired template<br/>TPL005 grid/scroll bounds"]
  end

  subgraph S4["Tier 2: Real Lean 4 Kernel (λ Prove)"]
    LEAN["theorem control_templates_valid : by decide<br/>theorem styles_wcag_aa : by decide<br/>theorem resources_resolved : by decide<br/>theorem step_preserves_inv : by omega<br/>theorem rule_* (Hoare & View rules)"]
  end

  TPL -. "Double-click / ❖" .-> S2
  S1 --> S3
  S2 --> S3
  S3 -->|"0 errors"| S4
  S3 -. "Red node border + Console pin" .-> S2
LIVE GENERATED SVG · AUTO-UPDATED ON BUILD
Open SVG ↗
Live Annotated TemplatedDesignStudio Graph — Resource Dictionary ({res:...}), ControlTemplate Blueprint & TemplatedControl Live Annotated TemplatedDesignStudio Graph — Resource Dictionary ({res:...}), ControlTemplate Blueprint & TemplatedControl
Live Annotated TemplatedDesignStudio Graph — Resource Dictionary ({res:...}), ControlTemplate Blueprint & TemplatedControl

Visual Feedback Loop on the Canvas#

Verification StateWhat You See on the Graph CanvasWhat You See in Console & ✓ Proofs
Valid Binding ({tpl:...} / {res:...})Clean green/teal/magenta port wires; tpl_resource Inspector displays a resolved color swatch + ✓ Resolved badge; topbar shows ● Verified (0 err).control_templates_valid, resources_resolved, and styles_wcag_aa appear as ✓ Verified in ✓ Proofs → Matrix, Blueprint, and Proof Tree.
Broken Wire / Missing Prop (TPL002)The exact offending tpl_part, nested ViewNode, or control_template card highlights with a crimson error outline.Diagnostic TPL002 pins straight to that nodeId — clicking the diagnostic pans & focuses the exact node on the canvas.
Missing Resource Token (TPL003)The offending tpl_resource node (even before it is wired!) or consuming tpl_part/ViewNode lights up red; Inspector shows ⚠ TPL002/TPL003 missing key badge.resources_resolved / control_templates_valid marks ✗ Failed until the key is fixed or added to the bound ResourceBundle.
Invalid Root Bounds (TPL005)Setting rootContainer = grid with rootColumns < 1 or rootContainer = scroll with rootMaxHeightPx < 80 highlights tpl_root (or control_template) in red immediately.TPL005 diagnostic pins to tpl_root with the exact required bound.
Real Lean 4 Kernel Proof (λ Prove)Topbar hero pill turns ✓ Proved (Lean 4) (or opens Console on any kernel error).✓ Proofs → Infoview lets you step through theorem control_templates_valid : ControlTemplatesValid controlTemplates := by decide and all invariant/Hoare/View theorems line by line.

2. Walkthrough of the Showcase Samples#

Sample A — VerifiedTemplatesStudio (verified_templates)#

Open Topbar Preset → Verified Control Templates (Proofs + Multi-Root) (or Solution Explorer → CoreDesignSystem/DesignSystem/VerifiedTemplatesStudio):

  1. Resource Dictionary & WCAG AAA Surface:
    • VerifiedTokens (resource) defines EN/DE localized strings (panelTitle, statusSub, boostCta, resetCta) and Light/Dark design tokens (surfaceBg, surfaceFg, brandAccent, okAccent, cardRadius).
    • VerifiedSurface (style) enforces WCAG AAA contrast (minContrastX10: 70, actual 15.8:1).
  2. Three Multi-Root control_template Blueprints:
    • StatusCardTemplate (rootContainer: 'card'): Elevated card surface hosting title, badge, subtitle, and a ContentPresenter slot that projects live HealthSlider + HealthBar child controls inside SafetyStatusCard.
    • MetricGridTemplate (rootContainer: 'grid', 2 columns): Uses a nested main-scene templateSpecGraph! Double-click MetricGridTemplate to drill into the main canvas and inspect mgt_root.children → AuditStat (stat) + RootBadge (badge) with mgt_r_bg/mgt_r_fg wired straight into tpl_root's bg/fg ports and mgt_p_tag wired into RootBadge.text.
    • ActionButtonTemplate (rootContainer: 'button'): Emits a semantic <button type="button"> root with :hover and :disabled visual triggers wired to BoostHealth and gated by atMaxHealth.
  3. Formal Theorems Proved Together:
    • control_templates_valid, styles_wcag_aa, resources_resolved
    • healthAndChecksBounded (health <= 100 && checks <= 10) → init_preserves_inv, step_preserves_inv, reachable_preserves_inv
    • User Hoare Triple boostPreservesBounds ({health <= 100 ∧ checks <= 10} BoostHealth {health <= 100 ∧ checks <= 10})
    • User View Constraint maxDisablesBoost (health >= 100 → atMaxHealth)
    • User Lean 4 Theorem boostHealth_bounded : ∀ h, min 100 (h + 10) ≤ 100 := by omega

Sample B — TemplatedDesignStudio (templated_kit)#

Demonstrates two-pass {tpl:title} → {res:brandTitle} interpolation, live Light/Dark and EN/DE locale switching in Preview, ContentPresenter projecting an interactive QualityRating star control, and expanded widgets (grid, chip_group, color_picker, date_picker, chart, tree_view).

Sample C — CustomLogicEngine (custom_logic)#

Open Topbar Preset → Custom Logic, Rules & FSM Engine (or Solution Explorer → CoreDesignSystem/Proofs/CustomLogicEngine):

  • Custom Lean 4 Functions Bridged into Live App UI: discountPct (qty : Nat) (vip : Bool) : Nat (20% VIP / 10% bulk >= 5 / 0%) and applyDiscount (gross pct : Nat) : Nat execute live inside appliedPct and netTotal computed nodes.
  • Algebraic Lean 4 Theorems: discountPct_le_twenty and applyDiscount_le_gross are proved directly in Lean 4 tactics.
  • Multi-Rule Validator & Workflow FSM: orderValidator evaluates 3 business rules (Quantity 1..20, Unit Price <= 100, VIP or Coupon) while orderFsm drives a 4-stage draft → reviewed → approved → dispatched stepper via Advance Workflow →, guarded by orderBoundsSafe and Hoare triple addPreservesQty.

3. First-Class ControlTemplate Node Kinds (category: 'template')#

KindPurposePorts
tpl_propDeclares a typed {tpl:propName} input (String, Nat, Bool, Color) with mode: 'oneWay' | 'twoWay', defaultValue, and WYSIWYG sampleValue. When mode = 'twoWay', nested interactive controls (input, textarea, select, toggle, slider, date_picker, color_picker, chip_group, rating) write mutations back into the parent screen's bound state node and record Timeline Debugger steps.Out: val : TemplateBinding
tpl_resourceReferences a {res:resourceKey} token or i18n entry from the parent's wired ResourceBundle (live swatch preview & TPL003 check).Out: val : TemplateBinding
tpl_partVisual part (text, badge, button, progress, icon, content_presenter, divider, border, row, stack). Button parts accept a custom eventName (e.g. onConfirm, onDismiss) surfaced as a dynamic Event output port on templated_control. Can wire either into tpl_root.parts OR nest inside any View container via parent : VNode.In: parent, text, bg, fg, border, visible · Out: part : TemplatePart
tpl_triggerVisual state override (:hover, :active, :disabled, :checked) setting bg, fg, border, and opacity.In: bg, fg, border · Out: trigger : TemplateTrigger
tpl_rootControlTemplate root hosting templateName, targetKind, configurable Root Container, custom events[] ports (onConfirm, onDismiss), wireable root brushes, parts[], triggers[], and children : VNode for nested View controls (including live interactive tabs).In: parts, triggers, bg, fg, border · Out: children : VNode

Full Routing Parity: reroute waypoints (Shift+Click / double-click on any wire) and wireless portal_out/portal_in pairs work transparently on every TemplateBinding, TemplatePart, TemplateTrigger, and VNode edge — specGraphToControlTemplate follows them cleanly!


4. All 8 Configurable Root Containers#

Switch the root container directly in the Breadcrumb Bar (root: ...), the tpl_root Inspector, or the parent control_template Inspector:

ContainerHTML / TSX ElementLayout & Special Options
border (default)<section>Bordered vertical surface box (rootGapPx, rootAlign, rootBg, rootFg, rootBorder, rootRadius, rootPadding)
stack<div>Clean borderless vertical StackPanel
row<div>Horizontal wrapping RowPanel (flex-direction: row)
grid<div>Responsive CSS Grid (rootColumns 1–6, verified >= 1 by TPL005)
scroll<div>Bounded scrollable ScrollView (rootMaxHeightPx, verified >= 80px by TPL005)
card<section>Elevated card chrome with shadow and structured padding
panel<div>Plain chrome-free container (background: transparent, border: none, padding: 0)
button<button type="button">Semantic interactive <button> root with native click dispatch & disabled state

5. Composing All 36 Main-Scene Controls Inside a ControlTemplate#

Inside a ControlTemplate canvas scope, every one of the 36 main-scene View controls stays at full contrast in the Node Palette and works identically to the main app scene:

  1. Auto-Wiring on Add/Drop:
    • Click or drag any View control (grid, split_view, scroll, card, accordion, tabs, conditional, stat, chart, slider, rating, toggle, button, code_block, tree_view, etc.) — if a container View node is selected, it wires selectedContainer.children → newNode.parent; otherwise it wires tpl_root.children → newNode.parent.
  2. Nesting ContentPresenter Anywhere:
    • Drag or click Part: ContentSlot while any container (card, grid, scroll, accordion, tabs) is selected (or wire container.children → content_presenter.parent) to project caller child controls deep inside your template hierarchy.
  3. Binding {tpl:...} & {res:...} to Any Control:
    • Either wire tpl_prop.val / tpl_resource.val directly into any compatible View input port (text, value, checked, visible, when, disabled, code, res), OR write {tpl:propName} / {res:tokenKey} in any control's text, label, title, or brush field.
    • All nested View references are scanned automatically by @leanui/verifier (TPL002 / TPL003) and proved by Lean 4's theorem control_templates_valid.

6. Editing Built-In Verified & Custom Component Templates#

Open Templates (topbar or Palette) and click ◈ Edit Visually on any Built-In Verified Template or My Custom Template:

  • Opens the template's full node-and-wire graph directly on the main Studio Canvas with a dedicated banner providing:
    • Inline Name, Category, and Description editing
    • λ Prove — verify the template directly in Lean 4 before saving
    • ✓ Save Template — persists overrides cleanly in localStorage (used by all future insertions)
    • ⧉ Save Copy — forks into a new custom template in My Custom Templates
    • ↺ Reset Default — restores any customized Built-In Verified Template to its original verified graph
    • ✕ Exit — returns seamlessly to your app canvas
  • Nested Drill-Down: Editing a Built-In Template that contains a control_template (e.g., Resource + Templated Control Kit) lets you double-click its control_template node to drill into ❖ ControlTemplate mode (❖ Template: ... › ❖ ControlTemplate: ...), and clicking ✓ Apply & Back writes your changes right back into the Built-In Template!

7. ControlTemplate Diagnostic Codes Reference#

CodeSeverityMeaningHow to Fix
TPL001ErrorMissing templateName, missing tpl_root, or 0 visual parts & 0 nested View controls.Name the template and wire at least one tpl_part or View control into tpl_root.
TPL002ErrorReference to {tpl:foo} where no tpl_prop named foo is declared (checked across root, parts, and all nested View controls).Add a tpl_prop named foo or fix the binding spelling.
TPL003ErrorReference to {res:key} (or a tpl_resource node) whose key does not exist in the bound ResourceBundle.Pick an existing token/i18n key in the Inspector dropdown or add the token to the parent resource node.
TPL004Errortemplated_control has no wired control_template and no matching templateName.Wire a control_template.template port into templated_control.template.
TPL005ErrorInvalid root container bounds (grid with rootColumns < 1, or scroll with rootMaxHeightPx < 80).Set rootColumns to 1..6 or rootMaxHeightPx >= 80.
Diagram Preview
Enlarged diagram