directives
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
Chinese@json-render/directives
@json-render/directives
Pre-built custom directives for . Drop them into your catalog and renderer to add formatting, math, string manipulation, and i18n.
@json-render/core为提供的预构建自定义指令。将它们集成到你的目录和渲染器中,即可添加格式化、数学运算、字符串处理及国际化功能。
@json-render/coreQuick Start
快速开始
typescript
import { standardDirectives } from '@json-render/directives';
// Wire into prompt generation
const prompt = catalog.prompt({ directives: standardDirectives });
// Wire into the renderer (React example)
import { JSONUIProvider, Renderer } from '@json-render/react';
<JSONUIProvider registry={registry} directives={standardDirectives}>
<Renderer spec={spec} registry={registry} />
</JSONUIProvider>To add factory directives like , spread the array:
createI18nDirectivetypescript
import { standardDirectives, createI18nDirective } from '@json-render/directives';
const directives = [...standardDirectives, createI18nDirective(config)];typescript
import { standardDirectives } from '@json-render/directives';
// Wire into prompt generation
const prompt = catalog.prompt({ directives: standardDirectives });
// Wire into the renderer (React example)
import { JSONUIProvider, Renderer } from '@json-render/react';
<JSONUIProvider registry={registry} directives={standardDirectives}>
<Renderer spec={spec} registry={registry} />
</JSONUIProvider>要添加这类工厂指令,请展开数组:
createI18nDirectivetypescript
import { standardDirectives, createI18nDirective } from '@json-render/directives';
const directives = [...standardDirectives, createI18nDirective(config)];Defining Custom Directives
定义自定义指令
Use from :
defineDirective@json-render/coretypescript
import { defineDirective, resolvePropValue } from '@json-render/core';
import { z } from 'zod';
const doubleDirective = defineDirective({
name: '$double',
description: 'Double a numeric value.',
schema: z.object({
$double: z.unknown(),
}),
resolve(value, ctx) {
const resolved = resolvePropValue(value.$double, ctx);
return (resolved as number) * 2;
},
});Rules:
- Name must start with
$ - Name must not conflict with built-in keys (,
$state,$cond,$computed,$template,$item,$index,$bindState)$bindItem - Resolvers should call on sub-values to support composition
resolvePropValue
使用中的:
@json-render/coredefineDirectivetypescript
import { defineDirective, resolvePropValue } from '@json-render/core';
import { z } from 'zod';
const doubleDirective = defineDirective({
name: '$double',
description: 'Double a numeric value.',
schema: z.object({
$double: z.unknown(),
}),
resolve(value, ctx) {
const resolved = resolvePropValue(value.$double, ctx);
return (resolved as number) * 2;
},
});规则:
- 名称必须以开头
$ - 名称不得与内置关键字冲突(、
$state、$cond、$computed、$template、$item、$index、$bindState)$bindItem - 解析器应调用处理子值,以支持组合使用
resolvePropValue
Built-in Directives
内置指令
$format
— Locale-aware value formatting
$format$format
— 支持本地化的值格式化
$formatFormats values using formatters. Supports , , , and .
Intldatecurrencynumberpercentjson
{ "$format": "currency", "value": { "$state": "/cart/total" }, "currency": "USD" }
{ "$format": "date", "value": { "$state": "/user/createdAt" } }
{ "$format": "number", "value": 1234567, "notation": "compact" }
{ "$format": "percent", "value": 0.75 }
{ "$format": "date", "value": { "$state": "/post/createdAt" }, "style": "relative" }Fields: (date | currency | number | percent), (any expression), (string), (string, default "USD"), (string), ("relative" for relative dates), (extra Intl options).
$formatvaluelocale?currency?notation?style?options?使用格式化工具格式化值。支持、、和类型。
Intldatecurrencynumberpercentjson
{ "$format": "currency", "value": { "$state": "/cart/total" }, "currency": "USD" }
{ "$format": "date", "value": { "$state": "/user/createdAt" } }
{ "$format": "number", "value": 1234567, "notation": "compact" }
{ "$format": "percent", "value": 0.75 }
{ "$format": "date", "value": { "$state": "/post/createdAt" }, "style": "relative" }字段:(date | currency | number | percent)、(任意表达式)、(字符串)、(字符串,默认值"USD")、(字符串)、(相对日期使用"relative")、(额外的Intl配置项)。
$formatvaluelocale?currency?notation?style?options?$math
— Arithmetic operations
$math$math
— 算术运算
$mathjson
{ "$math": "add", "a": { "$state": "/subtotal" }, "b": { "$state": "/tax" } }
{ "$math": "round", "a": 3.7 }Operations: , , , , , , , , , , . Unary ops (, , , ) only use . Division by zero returns .
addsubtractmultiplydividemodminmaxroundfloorceilabsroundfloorceilabsa0Fields: (operation enum), (first operand, default 0), (second operand, default 0).
$matha?b?json
{ "$math": "add", "a": { "$state": "/subtotal" }, "b": { "$state": "/tax" } }
{ "$math": "round", "a": 3.7 }支持的运算:、、、、、、、、、、。一元运算(、、、)仅使用参数。除以零返回。
addsubtractmultiplydividemodminmaxroundfloorceilabsroundfloorceilabsa0字段:(运算枚举值)、(第一个操作数,默认值0)、(第二个操作数,默认值0)。
$matha?b?$concat
— String concatenation
$concat$concat
— 字符串拼接
$concatjson
{ "$concat": [{ "$state": "/user/firstName" }, " ", { "$state": "/user/lastName" }] }Fields: (array of values to resolve and join into a string).
$concatjson
{ "$concat": [{ "$state": "/user/firstName" }, " ", { "$state": "/user/lastName" }] }字段:(需解析并拼接成字符串的值数组)。
$concat$count
— Array/string length
$count$count
— 数组/字符串长度
$countjson
{ "$count": { "$state": "/cart/items" } }Returns of arrays or strings, for other types.
.length0Fields: (value to count).
$countjson
{ "$count": { "$state": "/cart/items" } }返回数组或字符串的属性值,其他类型返回。
.length0字段:(需统计长度的值)。
$count$truncate
— Text truncation
$truncate$truncate
— 文本截断
$truncatejson
{ "$truncate": { "$state": "/post/body" }, "length": 140, "suffix": "..." }Fields: (value to truncate), (max chars, default 100), (string, default "...").
$truncatelength?suffix?json
{ "$truncate": { "$state": "/post/body" }, "length": 140, "suffix": "..." }字段:(需截断的文本)、(最大字符数,默认值100)、(后缀字符串,默认值"...")。
$truncatelength?suffix?$pluralize
— Singular/plural forms
$pluralize$pluralize
— 单复数形式转换
$pluralizejson
{ "$pluralize": { "$state": "/cart/itemCount" }, "one": "item", "other": "items", "zero": "no items" }Output: , , or .
"3 items""1 item""no items"Fields: (count value), (singular label), (plural label), (zero label).
$pluralizeoneotherzero?json
{ "$pluralize": { "$state": "/cart/itemCount" }, "one": "item", "other": "items", "zero": "no items" }输出示例:、或。
"3 items""1 item""no items"字段:(数量值)、(单数标签)、(复数标签)、(零值标签)。
$pluralizeoneotherzero?$join
— Join array elements
$join$join
— 数组元素拼接
$joinjson
{ "$join": { "$state": "/tags" }, "separator": ", " }Fields: (array to join), (string, default ", ").
$joinseparator?json
{ "$join": { "$state": "/tags" }, "separator": ", " }字段:(需拼接的数组)、(分隔符字符串,默认值", ")。
$joinseparator?createI18nDirective
— Internationalization factory
createI18nDirectivecreateI18nDirective
— 国际化工厂函数
createI18nDirectivetypescript
import { createI18nDirective } from '@json-render/directives';
const tDirective = createI18nDirective({
locale: 'en',
messages: {
en: { "greeting": "Hello, {{name}}!", "checkout.submit": "Place Order" },
es: { "greeting": "Hola, {{name}}!", "checkout.submit": "Realizar Pedido" },
},
fallbackLocale: 'en',
});Usage in specs:
json
{ "$t": "checkout.submit" }
{ "$t": "greeting", "params": { "name": { "$state": "/user/name" } } }Fields: (translation key), (interpolation parameters, values accept expressions).
$tparams?Config: (current locale), (Record<locale, Record<key, string>>), (fallback when key missing).
localemessagesfallbackLocale?typescript
import { createI18nDirective } from '@json-render/directives';
const tDirective = createI18nDirective({
locale: 'en',
messages: {
en: { "greeting": "Hello, {{name}}!", "checkout.submit": "Place Order" },
es: { "greeting": "Hola, {{name}}!", "checkout.submit": "Realizar Pedido" },
},
fallbackLocale: 'en',
});在specs中的使用方式:
json
{ "$t": "checkout.submit" }
{ "$t": "greeting", "params": { "name": { "$state": "/user/name" } } }字段:(翻译键)、(插值参数,值支持表达式)。
$tparams?配置项:(当前语言)、(语言包对象,格式为Record<locale, Record<key, string>>)、(当翻译键不存在时的 fallback 语言)。
localemessagesfallbackLocale?Composition
组合使用
Directives compose naturally — each resolver calls on its inputs, so directives can wrap other directives or built-in expressions:
resolvePropValuejson
{
"$format": "currency",
"value": { "$math": "multiply", "a": { "$state": "/price" }, "b": { "$state": "/qty" } },
"currency": "USD"
}Resolves inside-out: reads from state, multiplies, formats as currency.
$state$math$format指令支持自然组合——每个解析器都会调用处理输入值,因此指令可以嵌套其他指令或内置表达式:
resolvePropValuejson
{
"$format": "currency",
"value": { "$math": "multiply", "a": { "$state": "/price" }, "b": { "$state": "/qty" } },
"currency": "USD"
}解析顺序为从内到外:读取状态值,执行乘法运算,格式化为货币。
$state$math$formatWiring into Renderers
集成到渲染器
All four renderers (React, Vue, Svelte, Solid) accept on their provider and output:
directivescreateRenderertsx
// Provider pattern
<JSONUIProvider registry={registry} directives={directives}>
<Renderer spec={spec} registry={registry} />
</JSONUIProvider>
// createRenderer pattern
const MyRenderer = createRenderer(catalog, components);
<MyRenderer spec={spec} directives={directives} />For prompt generation, pass the same array:
typescript
const prompt = catalog.prompt({ directives });所有四个渲染器(React、Vue、Svelte、Solid)的Provider和输出均支持传入:
createRendererdirectivestsx
// Provider 模式
<JSONUIProvider registry={registry} directives={directives}>
<Renderer spec={spec} registry={registry} />
</JSONUIProvider>
// createRenderer 模式
const MyRenderer = createRenderer(catalog, components);
<MyRenderer spec={spec} directives={directives} />对于提示生成,传入相同的指令数组即可:
typescript
const prompt = catalog.prompt({ directives });Key Exports
核心导出
| Export | Purpose |
|---|---|
| |
| |
| |
| |
| |
| |
| |
| Factory for |
| Array of all 7 non-factory directives |
| Type for i18n configuration |
| 导出项 | 用途 |
|---|---|
| |
| |
| |
| |
| |
| |
| |
| |
| 所有7个非工厂指令的数组 |
| 国际化配置的类型定义 |