Skip to content

Files

Latest commit

author
robot-divkit
Dec 20, 2023
16c9cbb · Dec 20, 2023

History

History
This branch is 1761 commits behind divkit/divkit:main.

typescript

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
Sep 4, 2023
Jul 6, 2023
Nov 30, 2023
Aug 25, 2022
Aug 26, 2022
Aug 25, 2022
Aug 25, 2022
Aug 26, 2022
Aug 26, 2022
Sep 5, 2022
Sep 29, 2022
Aug 25, 2022
Oct 18, 2023
Dec 20, 2023
Aug 25, 2022
Oct 14, 2022
Aug 25, 2022
Aug 25, 2022

DivKit TypeScript JSON Buidler

DivKit Documentation

What is this and what for

@divkitframework/jsonbuilder library provides type safe tools to generate DivKit JSON

Example

import { divCard, DivContainer, DivText, reference, rewritRefs, template, templateHelper } from '@divkitframework/jsonbuilder';

const templates = {
  sampleBlock: new DivContainer({
    items: [
      template('header', {
        text: reference('title')
      }),
      template('header', {
        text: reference('subtitle')
      }),
    ],
  }),
  header: new DivText({
    font_size: 24,
  }),
};

const tHelper = templateHelper(templates);

console.log(JSON.stringify(
  divCard(rewriteRefs(templates), {
    log_id: 'sample_card',
    states: [
      {
        state_id: 0,
        div: tHelper.sampleBlock({
          title: "Some Title",
          subtitle: "Some Subtitle",
        }),
      },
    ],
  }
)));

In the result JSON.stringify(divCard(...)) will return JSON below:

{
  "templates": {
    "sampleBlock": {
      "type": "container",
      "items": [
        {
          "type": "header",
          "$text": "title"
        },
        {
          "type": "header",
          "$text": "subtitle"
        },
      ]
    },
    "header": {
      "type": "text",
      "font_size": 24
    }
  },
  "card": {
    "log_id": "sample_card",
    "states": [
      {
        "state_id": 0,
        "div": {
          "type": "sampleBlock",
          "title": "Some Title",
          "subtitle": "Some Subtitle",
        }
      }
    ]
  }
}

Typesafe templates with compile-time validation

You can use templateHelper helper function to achieve compile time template parameters validation. Type safety works only when you enable strictNullChecks in tsconfig.json

const block = template('header', {
    title: 'Some Title'
});

// using templateHelper for checking template parameters at compile-time
const safeBlock = tHelper.header({
    title: 'Some Title'
});

Validity guarantees

While developing cards you need to make sure that:

  • Textual string are not empty;
  • Urls of images, actions, etc are valid;
  • Arrays are non-empty.

Documentation. Medium tutorial. Habr tutorial.

Telegram: News | English-speaking chat | Чат на русском.

Twitter