SuperAPI AI 工具集

directives

前端与建站

查看项目

更新于 10-16 08:31

技能介绍

用途

@json-render/directives 为 @json-render/core 提供预置的自定义指令(directives)。将这些指令放入 catalog 与渲染器后,即可在 JSON 规格中直接使用格式化、数学运算、字符串操作与国际化能力,无需自行实现这些常见逻辑。

主要能力

内置指令

  • $format:使用 Intl 格式化值,支持 date、currency、number、percent 四种类型。字段包括 $format(类型)、value(任意表达式)、locale?、currency?(默认 "USD")、notation?、style?(设为 "relative" 可输出相对日期)、options?(额外 Intl 选项)。
  • $math:算术运算,支持 add、subtract、multiply、divide、mod、min、max、round、floor、ceil、abs。一元运算(round、floor、ceil、abs)只使用 a。除零返回 0。字段为 $math(运算枚举)、a?(默认 0)、b?(默认 0)。
  • $concat:将数组中的值解析后拼接为字符串。字段为 $concat(待解析并拼接的值数组)。
  • $count:返回数组或字符串的 .length,其他类型返回 0。字段为 $count(待计数的值)。
  • $truncate:文本截断。字段为 $truncate(待截断值)、length?(最大字符数,默认 100)、suffix?(默认 "...")。
  • $pluralize:单复数形式输出,例如 "3 items"、"1 item" 或 "no items"。字段为 $pluralize(计数值)、one(单数标签)、other(复数标签)、zero?(零值标签)。
  • $join:连接数组元素。字段为 $join(待连接数组)、separator?(默认 ", ")。

国际化工厂

createI18nDirective 用于生成 $t 国际化指令。配置项包括 locale(当前语言)、messages(Record<locale, Record<key, string>>)、fallbackLocale?(键缺失时的回退语言)。在规格中使用 { "$t": "checkout.submit" } 或带插值参数的 { "$t": "greeting", "params": { "name": { "$state": "/user/name" } } }。

组合能力

指令可自然组合:每个解析器都会对输入调用 resolvePropValue,因此指令可以包裹其他指令或内置表达式,按由内而外的顺序求值。例如 $format 的 value 可以是 $math 表达式,$math 的操作数又可以是 $state。

自定义指令

使用 @json-render/core 的 defineDirective 定义自定义指令,配合 zod 定义 schema。规则:名称必须以 $ 开头;名称不得与内置键($state、$cond、$computed、$template、$item、$index、$bindState、$bindItem)冲突;解析器应对子值调用 resolvePropValue 以支持组合。

使用方式

接入 prompt 生成:

import { standardDirectives } from '@json-render/directives';
const prompt = catalog.prompt({ directives: standardDirectives });

接入渲染器(React 示例):

import { JSONUIProvider, Renderer } from '@json-render/react';
<JSONUIProvider registry={registry} directives={standardDirectives}>
  <Renderer spec={spec} registry={registry} />
</JSONUIProvider>

添加工厂指令时展开数组:

import { standardDirectives, createI18nDirective } from '@json-render/directives';
const directives = [...standardDirectives, createI18nDirective(config)];

四种渲染器(React、Vue、Svelte、Solid)均支持在 provider 与 createRenderer 输出上接收 directives:

// Provider 模式
<JSONUIProvider registry={registry} directives={directives}>
  <Renderer spec={spec} registry={registry} />
</JSONUIProvider>

// createRenderer 模式
const MyRenderer = createRenderer(catalog, components);
<MyRenderer spec={spec} directives={directives} />

prompt 生成时传入同一数组:

const prompt = catalog.prompt({ directives });

关键导出

  • formatDirective:$format 指令定义
  • mathDirective:$math 指令定义
  • concatDirective:$concat 指令定义
  • countDirective:$count 指令定义
  • truncateDirective:$truncate 指令定义
  • pluralizeDirective:$pluralize 指令定义
  • joinDirective:$join 指令定义
  • createI18nDirective:$t 国际化指令工厂
  • standardDirectives:包含全部 7 个非工厂指令的数组
  • I18nConfig:i18n 配置类型

适用场景

适用于使用 @json-render/core 构建 JSON 驱动界面的项目,需要在规格中直接完成数值格式化、货币与日期展示、简单计算、文本截断、单复数处理、数组连接以及多语言文案渲染的场景。

限制

自定义指令名称必须以 $ 开头,且不得与内置键冲突。除零返回 0。$count 对非数组、非字符串类型返回 0。其余限制暂未提供。