15k

@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.

Install#

npm install @json-render/directives

Quick Start#

import { standardDirectives } from '@json-render/directives';

// Wire into prompt generation
const prompt = catalog.prompt({ directives: standardDirectives });

// Wire into the renderer
<JSONUIProvider spec={spec} directives={standardDirectives}>
  ...
</JSONUIProvider>

To add factory directives like createI18nDirective, spread the array:

import { standardDirectives, createI18nDirective } from '@json-render/directives';

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

Directives#

$format — Locale-aware value formatting#

Formats values using Intl formatters. Supports date, currency, number, and percent.

{ "$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 }

Relative dates are also supported:

{ "$format": "date", "value": { "$state": "/post/createdAt" }, "style": "relative" }

This returns strings like "3h ago", "2d from now", or "just now".

FieldTypeDescription
$format"date" | "currency" | "number" | "percent"Format type.
valueunknownValue to format. Accepts any dynamic expression.
localestringOptional. Locale for formatting (e.g. "en-US").
currencystringOptional. Currency code for "currency" format. Default: "USD".
notationstringOptional. Notation for "number" format (e.g. "compact").
stylestringOptional. Set to "relative" for relative date formatting.
optionsRecord<string, unknown>Optional. Extra Intl formatter options.

$math — Arithmetic operations#

Performs arithmetic on one or two operands. Operands accept any dynamic expression.

{ "$math": "add", "a": { "$state": "/subtotal" }, "b": { "$state": "/tax" } }
{ "$math": "round", "a": 3.7 }
FieldTypeDescription
$math"add" | "subtract" | "multiply" | "divide" | "mod" | "min" | "max" | "round" | "floor" | "ceil" | "abs"Operation to perform.
aunknownFirst operand. Defaults to 0 if missing.
bunknownSecond operand (binary ops only). Defaults to 0 if missing.

Unary operations (round, floor, ceil, abs) only use a. Division by zero returns 0.

$concat — String concatenation#

Concatenates multiple values into a single string. Each element is resolved then joined.

{ "$concat": [{ "$state": "/user/firstName" }, " ", { "$state": "/user/lastName" }] }
FieldTypeDescription
$concatunknown[]Array of values to concatenate. Each is resolved, converted to string, and joined.

$count — Array/string length#

Returns the length of an array or string. Returns 0 for other types.

{ "$count": { "$state": "/cart/items" } }
FieldTypeDescription
$countunknownValue to count. Accepts arrays and strings.

$truncate — Text truncation#

Truncates text to a maximum length with a configurable suffix.

{ "$truncate": { "$state": "/post/body" }, "length": 140, "suffix": "..." }
FieldTypeDescription
$truncateunknownValue to truncate.
lengthnumberOptional. Max character length. Default: 100.
suffixstringOptional. Suffix to append when truncated. Default: "...".

$pluralize — Singular/plural forms#

Selects a singular, plural, or zero form based on a count.

{ "$pluralize": { "$state": "/cart/itemCount" }, "one": "item", "other": "items", "zero": "no items" }

Output: "3 items", "1 item", or "no items".

FieldTypeDescription
$pluralizeunknownCount value. Accepts dynamic expressions.
onestringSingular form label.
otherstringPlural form label.
zerostringOptional. Label for count of zero. If omitted, uses "0 <other>".

$join — Join array elements#

Joins array elements with a separator string.

{ "$join": { "$state": "/tags" }, "separator": ", " }
FieldTypeDescription
$joinunknownArray to join. Non-array values are converted to string.
separatorstringOptional. Separator between elements. Default: ", ".

createI18nDirective — Internationalization#

Factory function that creates a $t directive for translations with {'{{param}}'} interpolation.

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:

{ "$t": "checkout.submit" }
{ "$t": "greeting", "params": { "name": { "$state": "/user/name" } } }
FieldTypeDescription
$tstringTranslation key.
paramsRecord<string, unknown>Optional. Interpolation parameters. Values accept dynamic expressions.

I18nConfig

FieldTypeDescription
localestringCurrent locale (e.g. "en").
messagesRecord<string, Record<string, string>>Map of locale to key-value translation pairs.
fallbackLocalestringOptional. Fallback locale when a key is missing in the current locale.

Composition#

Directives compose naturally. Each resolver calls resolvePropValue on its inputs, so you can nest directives:

{
  "$format": "currency",
  "value": { "$math": "multiply", "a": { "$state": "/price" }, "b": { "$state": "/qty" } },
  "currency": "USD"
}
{
  "$pluralize": { "$count": { "$state": "/items" } },
  "one": "item",
  "other": "items"
}