跳到主要内容

CSX 编译器

UltimateUI.Components.SourceGen 是一个 Roslyn Source Generator。它读取项目中的 *.uui.csx AdditionalFiles,把 C# 方法里的 CSX return 表达式生成成普通 C# element 构造代码。

项目配置

<ProjectReference Include="..\..\src\UltimateUI.Components.SourceGen\UltimateUI.Components.SourceGen.csproj"
OutputItemType="Analyzer"
ReferenceOutputAssembly="false" />
<AdditionalFiles Include="WelcomeCard.uui.csx" />

语法

using System;
using UltimateUI;
using UltimateUI.Components;
using UltimateUI.Events;

namespace MyApp.Views;

public static partial class WelcomeCard
{
public static Element Render(ComponentContext context, string title, int count, EventHandler<ClickEventArgs>? onClick)
{
var caption = $"Clicked {count}";
return (
<div className="card">
<h1>{title}</h1>
<p>Compiled from .uui.csx.</p>
<button onClick={onClick}>{caption}</button>
</div>
);
}
}

生成的 API:

var element = WelcomeCard.Render(context, "CSX", 3, OnClick);

支持范围

  • 一个 .uui.csx 文件可包含 using、file-scoped namespacepartial class 和返回 Element 的 C# 方法。
  • 函数组件方法的第一个参数必须是 ComponentContext context,hook 只能通过这个 context 使用。
  • 方法签名和 return 前的普通语句使用 C# 格式;CSX 只扩展 return (<.../>); 这一处表达式语法。
  • XML-like 元素会映射到 UltimateUI.DivUltimateUI.ButtonUltimateUI.H1 等类型。
  • PascalCase 标签会映射为函数组件调用,例如 <CounterView /> 生成 CounterView.Render(context)
  • 所有 attribute 名必须使用 camelCase,不能包含 -。例如使用 ariaLabelhtmlForonClick,不要写 aria-labelhtml-foron-click
  • classNameidariaLabel 等属性会映射为 C# 属性。
  • 文本和属性值支持 {expression} 插值。
  • 事件属性使用 React 风格的 onClick={handler}onInput={handler},生成 OnClick += handler / OnInput += handler
  • 子节点中的 {rows} 可插入 IEnumerable<Element>

旧的顶层 component / function 声明、class=、所有带 - 的 attribute (例如 on-click="handler"aria-label="...")和 <slot name="rows" /> 语法已经移除。

当前 CSX 编译器目标是开发体验优先的实用子集;不执行 JavaScript,也不引入浏览器端 JSX runtime。