标记语言

模型写的是什么:Markdown、标签、状态、表达式、组件和绘图。

一条回复就是带标签的 Markdown。下面的例子可以直接拿去用,每个都是渲染器根据下方的源码画出来的。语言参考是交给模型的完整文本。

Markdown 和标签

Markdown 在哪里都能用,标签里面也可以。小写标签是布局和文本的基础元素,还包括普通的 HTML 和内联 SVG。PascalCase 标签是组件。

实时渲染

正在加载渲染器…

**Two plans fit a team of five.** Both include SSO.

<grid columns={2} gap={3}>
  <card padding={4}>
    <row><title level={3}>Team</title><spacer /><badge color="success">Fits</badge></row>
    <text color="muted">Up to 10 seats, shared inbox, 30-day history.</text>
  </card>
  <card padding={4}>
    <row><title level={3}>Business</title><spacer /><badge>More than you need</badge></row>
    <text color="muted">Unlimited seats, audit log, priority support.</text>
  </card>
</grid>

属性的值可以是文本(name="Team")、带值的文本(name="Hi {user}")、表达式(columns={2}),不写值就表示 true(wrap)。文本里的 {expression} 会输出一个值。

状态

<state> 声明界面要记住什么,<derive> 声明界面由此算出什么。两者在任何地方都能按名字读取。

实时渲染

正在加载渲染器…

<state nights={3} guests={2} />
<derive total={nights * 120 + guests * 15 * nights} />

<card padding={4} gap={3}>
  <row gap={2} wrap>
    <Button on:click={nights = max(nights - 1, 1)} aria-label="One night fewer"><icon name="minus" /></Button>
    <text weight="medium">{nights} {plural(nights, "night", "nights")}</text>
    <Button on:click={nights += 1} aria-label="One night more"><icon name="plus" /></Button>
    <spacer />
    <text size="xl" weight="semibold" tabular>{currency(total)}</text>
  </row>
  <text size="sm" color="muted">{currency(120)} a night, plus {currency(15)} per guest per night for {guests} guests.</text>
</card>

状态只属于这条回复。回复的其余部分还在到达时,它保持用户留下的样子。给 <state> 加上 persist,它的值就能在多次访问之间保留。

连接控件

bind: 把控件和状态双向连接起来。它可以用在原生输入控件上,也可以用在任何带有对应变更回调的组件 prop 上。

实时渲染

正在加载渲染器…

<state name="" plan="team" yearly={false} />
<derive price={(plan == "team" ? 12 : 29) * (yearly ? 10 : 1)} />

<box gap={3} maxWidth={420}>
  <Field>
    <FieldLabel>Workspace name</FieldLabel>
    <Input bind:value={name} placeholder="Acme" />
  </Field>
  <SegmentedControl bind:value={plan} aria-label="Plan">
    <SegmentedControlIndicator />
    <SegmentedControlItem value="team">Team</SegmentedControlItem>
    <SegmentedControlItem value="business">Business</SegmentedControlItem>
  </SegmentedControl>
  <label>
    <row gap={2}><Switch bind:checked={yearly}><SwitchThumb /></Switch><text>Pay yearly, two months free</text></row>
  </label>
  <text>{name || "Your workspace"} on {capitalize(plan)}: **{currency(price)}** per seat, per {yearly ? "year" : "month"}.</text>
</box>

动作

on: 在事件触发时执行一个动作:一条或多条语句,用 ; 分隔。动作可以赋值、写入对象和列表、使用 if 和 else,还可以调用内置动作:send、call、refetch、reset、toast、copy、open。

实时渲染

正在加载渲染器…

<state todos={[{ title: "Book the venue", done: true }, { title: "Send invitations", done: false }]} draft="" />
<derive left={todos.filter(t => !t.done).length} />

<box gap={3} maxWidth={440}>
  <row gap={2}>
    <Input bind:value={draft} placeholder="Add a task" aria-label="New task" on:keydown={if ($event.key == "Enter" && draft != "") { todos.push({ title: draft, done: false }); draft = "" }} />
    <Button variant="solid" disabled={draft == ""} on:click={todos.push({ title: draft, done: false }); draft = ""}>Add</Button>
  </row>
  {#each todos as todo, i (todo.title)}
    <row gap={2}>
      <Checkbox bind:checked={todo.done} aria-label={todo.title}><CheckboxIndicator /></Checkbox>
      <text strike={todo.done} color={todo.done ? "muted" : "foreground"}>{todo.title}</text>
      <spacer />
      <Button variant="ghost" size="sm" aria-label="Remove {todo.title}" on:click={todos.splice(i, 1)}><icon name="x" /></Button>
    </row>
  {/each}
  <text size="sm" color="muted">{left} {plural(left, "task", "tasks")} left</text>
</box>

在 HTML 上用 DOM 事件名(on:click、on:keydown),在组件上用去掉 on 的回调名(on:valueChange)。在事件处理里,$event 是事件数据,$value 是新值。

逻辑

{#if} 在条件成立时显示内容。{#each} 遍历列表重复渲染;括号里的 key 让每一行在增、删、重排时保持自己的身份。写入循环变量就是写入列表。

实时渲染

正在加载渲染器…

<state budget={900} items={[{ name: "Flights", cost: 420 }, { name: "Hotel", cost: 380 }, { name: "Food", cost: 150 }]} />
<derive total={sumBy(items, "cost")} />

<box gap={2} maxWidth={420}>
  {#each items as item (item.name)}
    <row gap={2}>
      <text>{item.name}</text>
      <spacer />
      <Button size="sm" variant="ghost" aria-label="Less for {item.name}" on:click={item.cost = max(item.cost - 50, 0)}><icon name="minus" /></Button>
      <text tabular weight="medium">{currency(item.cost)}</text>
      <Button size="sm" variant="ghost" aria-label="More for {item.name}" on:click={item.cost += 50}><icon name="plus" /></Button>
    </row>
  {/each}
  <divider />
  <row>
    <text weight="semibold">{currency(total)}</text>
    <spacer />
    {#if total > budget}
      <badge color="danger">{currency(total - budget)} over</badge>
    {:else}
      <badge color="success">{currency(budget - total)} to spare</badge>
    {/if}
  </row>
</box>

标签不能写在花括号里。{open && <card>…</card>} 和 {items.map(i => <row>…</row>)} 是 JSX 的写法,在这里对应的是 {#if} 和 {#each}。检查器会报告这种写法。

表达式

表达式是访问不到页面的 JavaScript 表达式:字面量、运算符、可选链、模板字符串、箭头函数,以及一组固定的方法和辅助函数。

类别辅助函数
数字min max sum avg round floor ceil abs clamp range,以及 Math.*
格式化num currency percent compact signed unit date time datetime relative duration plural ordinal capitalize truncate initials
列表len sortBy groupBy countBy sumBy maxBy minBy unique toggle without chunk first last keys values entries
其他now today addDays uid json

没有 window、document、fetch、定时器和 eval,也没有 new Date()。数据来自工具。

UI SDK 组件

每个 UI SDK 组件都可以按名字使用,连同它的部件:<Tabs>、<Dialog>、<Select>、<Popover>、<Accordion>、<Slider>、<Combobox> 等等。它们自带焦点处理、键盘支持和无障碍,外观由设计决定。

实时渲染

正在加载渲染器…

<state tab="specs" open={false} />

<Tabs bind:value={tab}>
  <TabsList aria-label="Laptop">
    <TabsTab value="specs">Specs</TabsTab>
    <TabsTab value="reviews">Reviews</TabsTab>
  </TabsList>
  <TabsPanel value="specs">
    <list marker="check">
      <list-item>14-inch display, 120 Hz</list-item>
      <list-item>18 hours of battery</list-item>
      <list-item>1.2 kg</list-item>
    </list>
  </TabsPanel>
  <TabsPanel value="reviews">
    <text>4.6 out of 5 across 1,284 reviews.</text>
  </TabsPanel>
</Tabs>

<row>
  <Dialog bind:open={open}>
    <DialogTrigger>Compare with last year's model</DialogTrigger>
    <DialogBackdrop />
    <DialogContent>
      <DialogTitle>What changed</DialogTitle>
      <DialogDescription>Two more hours of battery and 200 g lighter. The ports are the same.</DialogDescription>
      <row justify="end"><DialogClose>Close</DialogClose></row>
    </DialogContent>
  </Dialog>
</row>

部件必须放在它所属的组件里面,其他库里的名字(<TabsTrigger>、<TabsContent>)并不存在。提示词列出了每个组件,并各附一个例子;@open-intelligent-ui/core/prompt 里的 describeComponent(name) 返回单个组件的完整说明。

预设组件

六个预设组件覆盖 UI SDK 没有的内容:<Chart>、<Stat>、<Number>、<DataTable>、<CodeBlock> 和 <Skeleton>。

实时渲染

正在加载渲染器…

<state rows={[
  { month: "Jan", plan: 40, actual: 38 },
  { month: "Feb", plan: 44, actual: 47 },
  { month: "Mar", plan: 48, actual: 53 },
  { month: "Apr", plan: 52, actual: 50 }
]} />
<derive actual={sumBy(rows, "actual")} plan={sumBy(rows, "plan")} />

<grid columns={2} gap={3} stagger>
  <Stat label="Revenue" value={actual * 1000} format="currency" delta={actual / plan - 1} caption="against plan" />
  <Stat label="Best month" value={maxBy(rows, "actual").month} caption="{currency(maxBy(rows, "actual").actual * 1000)}" />
</grid>

<Chart type="bar" data={rows} x="month" y={["plan", "actual"]} names={{ plan: "Plan", actual: "Actual" }} height={200} legend aria-label="Plan and actual revenue by month" />

<DataTable data={rows} columns={["month", { key: "plan", label: "Plan", align: "right" }, { key: "actual", label: "Actual", align: "right" }]} sortable />

定义组件

<define> 给一段标记起个名字,这样它可以用不止一次。它能读到自己的 props 和这块界面的状态;<slot /> 是调用方的子内容放进去的位置。

实时渲染

正在加载渲染器…

<state choice="b" plans={[
  { id: "a", name: "Basic", price: 9, blurb: "One project, community support." },
  { id: "b", name: "Pro", price: 24, blurb: "Unlimited projects, priority support." }
]} />

<define name="PlanCard" props="plan, selected">
  <card padding={4} interactive border={selected ? "accent" : true} on:click={choice = plan.id}>
    <row><title level={3}>{plan.name}</title><spacer /><text weight="semibold">{currency(plan.price)}</text></row>
    <slot />
  </card>
</define>

<grid columns={2} gap={3}>
  {#each plans as plan (plan.id)}
    <PlanCard {plan} selected={choice == plan.id}><text color="muted">{plan.blurb}</text></PlanCard>
  {/each}
</grid>

这是模型为一条回复定义的组件。你的产品为每条回复注册的组件是另一回事。

CSS 和 SVG

基础元素表达不了的时候,模型会写 CSS 和内联 SVG:CSS 只作用于它自己这块界面,SVG 由状态驱动。两者都用设计的变量,不用固定值。

实时渲染

正在加载渲染器…

<state level={62} />

<row gap={4} wrap>
  <svg viewBox="0 0 120 70" width="180" role="img" aria-label="Tank at {level} percent">
    <path d="M10 60 A50 50 0 0 1 110 60" fill="none" stroke="var(--iui-color-muted)" stroke-width="10" stroke-linecap="round" />
    <path class="gauge" d="M10 60 A50 50 0 0 1 110 60" fill="none" stroke="var(--iui-color-accent)" stroke-width="10" stroke-linecap="round" stroke-dasharray="{level * 1.571} 157.1" />
    <text x="60" y="58" text-anchor="middle" font-size="16" font-weight="600" fill="var(--iui-color-foreground)">{level}%</text>
  </svg>
  <box flex={1} minWidth={200}>
    <Slider min={0} max={100} bind:value={level}>
      <SliderControl><SliderTrack><SliderIndicator /><SliderThumb aria-label="Level" /></SliderTrack></SliderControl>
    </Slider>
  </box>
</row>

<style>
  .gauge { transition: stroke-dasharray var(--iui-motion-layout-duration) var(--iui-motion-layout-easing); }
</style>

<script>、<iframe>、字符串形式的事件属性、@import、指向其他站点的 url() 和 position: fixed 都会被移除。完整列表见安全。