directives

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

@json-render/directives

@json-render/directives

Pre-built custom directives for
@json-render/core
. Drop them into your catalog and renderer to add formatting, math, string manipulation, and i18n.
@json-render/core
提供的预构建自定义指令。将它们集成到你的目录和渲染器中,即可添加格式化、数学运算、字符串处理及国际化功能。

Quick 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
createI18nDirective
, spread the array:
typescript
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>
要添加
createI18nDirective
这类工厂指令,请展开数组:
typescript
import { standardDirectives, createI18nDirective } from '@json-render/directives';

const directives = [...standardDirectives, createI18nDirective(config)];

Defining Custom Directives

定义自定义指令

Use
defineDirective
from
@json-render/core
:
typescript
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
    resolvePropValue
    on sub-values to support composition
使用
@json-render/core
中的
defineDirective
typescript
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
— 支持本地化的值格式化

Formats values using
Intl
formatters. Supports
date
,
currency
,
number
, and
percent
.
json
{ "$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:
$format
(date | currency | number | percent),
value
(any expression),
locale?
(string),
currency?
(string, default "USD"),
notation?
(string),
style?
("relative" for relative dates),
options?
(extra Intl options).
使用
Intl
格式化工具格式化值。支持
date
currency
number
percent
类型。
json
{ "$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" }
字段:
$format
(date | currency | number | percent)、
value
(任意表达式)、
locale?
(字符串)、
currency?
(字符串,默认值"USD")、
notation?
(字符串)、
style?
(相对日期使用"relative")、
options?
(额外的Intl配置项)。

$math
— Arithmetic operations

$math
— 算术运算

json
{ "$math": "add", "a": { "$state": "/subtotal" }, "b": { "$state": "/tax" } }
{ "$math": "round", "a": 3.7 }
Operations:
add
,
subtract
,
multiply
,
divide
,
mod
,
min
,
max
,
round
,
floor
,
ceil
,
abs
. Unary ops (
round
,
floor
,
ceil
,
abs
) only use
a
. Division by zero returns
0
.
Fields:
$math
(operation enum),
a?
(first operand, default 0),
b?
(second operand, default 0).
json
{ "$math": "add", "a": { "$state": "/subtotal" }, "b": { "$state": "/tax" } }
{ "$math": "round", "a": 3.7 }
支持的运算:
add
subtract
multiply
divide
mod
min
max
round
floor
ceil
abs
。一元运算(
round
floor
ceil
abs
)仅使用
a
参数。除以零返回
0
字段:
$math
(运算枚举值)、
a?
(第一个操作数,默认值0)、
b?
(第二个操作数,默认值0)。

$concat
— String concatenation

$concat
— 字符串拼接

json
{ "$concat": [{ "$state": "/user/firstName" }, " ", { "$state": "/user/lastName" }] }
Fields:
$concat
(array of values to resolve and join into a string).
json
{ "$concat": [{ "$state": "/user/firstName" }, " ", { "$state": "/user/lastName" }] }
字段:
$concat
(需解析并拼接成字符串的值数组)。

$count
— Array/string length

$count
— 数组/字符串长度

json
{ "$count": { "$state": "/cart/items" } }
Returns
.length
of arrays or strings,
0
for other types.
Fields:
$count
(value to count).
json
{ "$count": { "$state": "/cart/items" } }
返回数组或字符串的
.length
属性值,其他类型返回
0
字段:
$count
(需统计长度的值)。

$truncate
— Text truncation

$truncate
— 文本截断

json
{ "$truncate": { "$state": "/post/body" }, "length": 140, "suffix": "..." }
Fields:
$truncate
(value to truncate),
length?
(max chars, default 100),
suffix?
(string, default "...").
json
{ "$truncate": { "$state": "/post/body" }, "length": 140, "suffix": "..." }
字段:
$truncate
(需截断的文本)、
length?
(最大字符数,默认值100)、
suffix?
(后缀字符串,默认值"...")。

$pluralize
— Singular/plural forms

$pluralize
— 单复数形式转换

json
{ "$pluralize": { "$state": "/cart/itemCount" }, "one": "item", "other": "items", "zero": "no items" }
Output:
"3 items"
,
"1 item"
, or
"no items"
.
Fields:
$pluralize
(count value),
one
(singular label),
other
(plural label),
zero?
(zero label).
json
{ "$pluralize": { "$state": "/cart/itemCount" }, "one": "item", "other": "items", "zero": "no items" }
输出示例:
"3 items"
"1 item"
"no items"
字段:
$pluralize
(数量值)、
one
(单数标签)、
other
(复数标签)、
zero?
(零值标签)。

$join
— Join array elements

$join
— 数组元素拼接

json
{ "$join": { "$state": "/tags" }, "separator": ", " }
Fields:
$join
(array to join),
separator?
(string, default ", ").
json
{ "$join": { "$state": "/tags" }, "separator": ", " }
字段:
$join
(需拼接的数组)、
separator?
(分隔符字符串,默认值", ")。

createI18nDirective
— Internationalization factory

createI18nDirective
— 国际化工厂函数

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',
});
Usage in specs:
json
{ "$t": "checkout.submit" }
{ "$t": "greeting", "params": { "name": { "$state": "/user/name" } } }
Fields:
$t
(translation key),
params?
(interpolation parameters, values accept expressions).
Config:
locale
(current locale),
messages
(Record<locale, Record<key, string>>),
fallbackLocale?
(fallback when key missing).
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" } } }
字段:
$t
(翻译键)、
params?
(插值参数,值支持表达式)。
配置项:
locale
(当前语言)、
messages
(语言包对象,格式为Record<locale, Record<key, string>>)、
fallbackLocale?
(当翻译键不存在时的 fallback 语言)。

Composition

组合使用

Directives compose naturally — each resolver calls
resolvePropValue
on its inputs, so directives can wrap other directives or built-in expressions:
json
{
  "$format": "currency",
  "value": { "$math": "multiply", "a": { "$state": "/price" }, "b": { "$state": "/qty" } },
  "currency": "USD"
}
Resolves inside-out:
$state
reads from state,
$math
multiplies,
$format
formats as currency.
指令支持自然组合——每个解析器都会调用
resolvePropValue
处理输入值,因此指令可以嵌套其他指令或内置表达式:
json
{
  "$format": "currency",
  "value": { "$math": "multiply", "a": { "$state": "/price" }, "b": { "$state": "/qty" } },
  "currency": "USD"
}
解析顺序为从内到外:
$state
读取状态值,
$math
执行乘法运算,
$format
格式化为货币。

Wiring into Renderers

集成到渲染器

All four renderers (React, Vue, Svelte, Solid) accept
directives
on their provider and
createRenderer
output:
tsx
// 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和
createRenderer
输出均支持传入
directives
tsx
// 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

核心导出

ExportPurpose
formatDirective
$format
directive definition
mathDirective
$math
directive definition
concatDirective
$concat
directive definition
countDirective
$count
directive definition
truncateDirective
$truncate
directive definition
pluralizeDirective
$pluralize
directive definition
joinDirective
$join
directive definition
createI18nDirective
Factory for
$t
i18n directive
standardDirectives
Array of all 7 non-factory directives
I18nConfig
Type for i18n configuration
导出项用途
formatDirective
$format
指令定义
mathDirective
$math
指令定义
concatDirective
$concat
指令定义
countDirective
$count
指令定义
truncateDirective
$truncate
指令定义
pluralizeDirective
$pluralize
指令定义
joinDirective
$join
指令定义
createI18nDirective
$t
国际化指令的工厂函数
standardDirectives
所有7个非工厂指令的数组
I18nConfig
国际化配置的类型定义