TypeScript JSON Builder
TypeScript JSON Builder is the @divkitframework/jsonbuilder npm package for describing DivKit layout in TypeScript. It is intended for a Node.js backend: a card is described with objects in code, and the library turns them into JSON for the client. The library classes and types are generated from the DivKit schema, so the compiler catches mistakes in property names and types.
The library source code is available on GitHub. A similar tool for Kotlin is described on the Kotlin DSL page.
Installation
Install the package from npm:
npm install @divkitframework/jsonbuilder
The package includes CommonJS and ES module builds and TypeScript type declarations.
Building a card
The divCard function assembles a card. The first argument is the templates (an empty object if there are none), and the second one is an object with the div-data structure. Layout elements are created with the constructors of the DivText, DivContainer, DivImage, and other classes. Property names are the same as in JSON.
import { divCard, DivText } from '@divkitframework/jsonbuilder';
const card = divCard({}, {
// Card ID, a required property.
log_id: 'hello_card',
states: [
{
state_id: 0,
// The card consists of a single text element.
div: new DivText({
font_size: 18,
text: 'Hello, world!',
}),
},
],
});
// Serializing the card into JSON.
const json = JSON.stringify(card);
The serialization result (formatted for readability):
{
"templates": {},
"card": {
"log_id": "hello_card",
"states": [
{
"state_id": 0,
"div": {
"type": "text",
"font_size": 18,
"text": "Hello, world!"
}
}
]
}
}
All that remains is to send the resulting string to the client. An example of a backend that returns layout and a way to view the result in the demo app are described in the guide to deploying a simple backend.
Templates
Templates are described by an object where a key is a template name and a value is an element or another template. A template parameter is declared with the reference function: its call is put in place of a property value. An element is created from a template with the template function, which takes the template name and the values of its parameters and properties.
import {
divCard,
DivContainer,
DivText,
reference,
rewriteRefs,
template,
templateHelper,
wrapContent,
} from '@divkitframework/jsonbuilder';
const templates = {
// The title template based on a text element.
title: new DivText({
font_size: 18,
width: wrapContent(),
// The value of the text property is set by the title_text parameter.
text: reference('title_text'),
}),
// The greeting template uses the title template.
greeting: new DivContainer({
items: [
template('title', {
// The title_text parameter gets the value of the greeting_text parameter.
title_text: reference('greeting_text'),
}),
template('title', {
title_text: 'Hello, DivKit!',
// Overriding a template property.
font_size: 14,
}),
],
}),
};
Before templates are passed to divCard, they must be processed with the rewriteRefs function. It returns a copy of the templates in which reference calls are replaced with properties that have the $ prefix. Without it, template parameters get into JSON in an incorrect form.
The templateHelper function returns an object with a function for each template. Calling tHelper.greeting({...}) is equivalent to calling template('greeting', {...}), but the template name is checked by the compiler.
const tHelper = templateHelper(templates);
const card = divCard(rewriteRefs(templates), {
log_id: 'template_card',
states: [
{
state_id: 0,
// Creating an element from the greeting template.
div: tHelper.greeting({
// The value of the template parameter.
greeting_text: 'Hello, world!',
}),
},
],
});
The templates get into the templates section, and the card gets into the card section:
{
"templates": {
"title": {
"type": "text",
"font_size": 18,
"width": {
"type": "wrap_content"
},
"$text": "title_text"
},
"greeting": {
"type": "container",
"items": [
{
"type": "title",
"$title_text": "greeting_text"
},
{
"type": "title",
"title_text": "Hello, DivKit!",
"font_size": 14
}
]
}
},
"card": {
"log_id": "template_card",
"states": [
{
"state_id": 0,
"div": {
"type": "greeting",
"greeting_text": "Hello, world!"
}
}
]
}
}
Note
If the parameter name in reference is the same as the property name, no property with the $ prefix is added to the template. The value of such a property is set directly by the property name when the template is used.
Selecting the templates in use
If a set of templates is shared by many cards, the JSON can include only the templates that a particular card needs. There are two functions for this:
thelperWithMemoreturns thethelperobject, which is used in the same way as the result oftemplateHelper, and theusedset with the names of the templates that were called. Usethelperonly when building a card:templatesDepsMapdoes not see its calls inside template definitions.templatesDepsMapreturns, for each template, the list of templates it depends on, including the template itself. If a template uses an undeclared template or the dependencies form a cycle, the function throws an exception.
The example continues the previous one:
import { templatesDepsMap, thelperWithMemo } from '@divkitframework/jsonbuilder';
const { thelper, used } = thelperWithMemo<typeof templates>();
const cardData = {
log_id: 'title_card',
states: [
{
state_id: 0,
div: thelper.title({ title_text: 'Hello, world!' }),
},
],
};
// The templates called while building the card, and their dependencies.
const deps = templatesDepsMap(templates);
const names = new Set([...used].flatMap((name) => deps[name]));
const usedTemplates = Object.fromEntries(
Object.entries(templates).filter(([name]) => names.has(name)),
);
// Only the title template gets into the templates section.
const titleCard = divCard(rewriteRefs(usedTemplates), cardData);
Variables and expressions
Variables are declared in the variables property with the StringVariable, IntegerVariable, BooleanVariable, and other classes. To set a calculated expression as a property value, pass the expression string through the expression function. Its result is accepted only by the properties that support expressions.
import { divCard, DivText, expression, StringVariable } from '@divkitframework/jsonbuilder';
const card = divCard({}, {
log_id: 'variables_card',
// Declaring variables.
variables: [
new StringVariable({ name: 'user_name', value: 'DivKit' }),
],
states: [
{
state_id: 0,
div: new DivText({
// A constant property.
font_size: 18,
// A calculated property.
text: expression('Hello, @{user_name}!'),
}),
},
],
});
String escaping
When the result of divCard is serialized, plain strings are escaped: @{ is replaced with \@{, and \ is replaced with \\. As a result, text from external sources is not evaluated on the client as an expression and is displayed as is. For the same reason, an expression passed as a plain string without expression is not evaluated.
Strings created with the expression function get into JSON unchanged. To insert arbitrary text into an expression, escape it with the escapeExpression function.
import { DivText, escapeExpression, expression } from '@divkitframework/jsonbuilder';
const comment = 'Type @{name} here';
const items = [
// A plain string. In JSON: "Type \\@{name} here", on the screen: Type @{name} here
new DivText({ text: comment }),
// An expression with arbitrary text. In JSON: "Type \\@{name} here: @{user_name}"
new DivText({ text: expression(`${escapeExpression(comment)}: @{user_name}`) }),
];
Type and value checks
The TypeScript compiler checks:
- the names of the properties of elements and other layout objects;
- value types, allowed enumeration values, and the presence of required properties;
- that the result of
expressionis passed to a property that supports expressions; - template names when the
templateHelperfunctions are called. Template parameters are not checked in this case.
Schema entities that have the type property are represented by classes: DivText, DivFixedSize, StringVariable. The rest are described by plain objects, and their types are interfaces with the I prefix, such as IDivData and IDivAction. For sizes, there are short functions: fixed, matchParent, wrapContent, and weighted.
When the result of divCard is serialized, the true and false values are replaced with 1 and 0.
Warning
The library does not check the values themselves. When developing cards, make sure that text strings and arrays are not empty and that the URLs of images, actions, and other properties are valid.
Learn more
You can discuss topics of interest in the DivKit user community in Telegram: https://t.me/divkit_community_en.