### Registering and Using DivKit Extensions and Custom Components Source: https://context7.com/divkit/divkit.git/llms.txt This example shows how to import necessary DivKit modules, define custom extensions (like Lottie and a highlight extension), create a custom web component (MapComponent), and then render a DivKit UI that utilizes these custom elements. It includes setup for Lottie animations, custom highlighting, and a map widget. ```javascript import { render } from '@divkitframework/divkit/client'; import { lottieExtensionBuilder } from '@divkitframework/divkit/extensions/lottie'; import lottie from 'lottie-web'; // Built-in Lottie extension const lottieExtension = lottieExtensionBuilder(lottie); // Custom extension class HighlightExtension { constructor() { this.id = 'highlight'; } mountView(node, context) { const color = context.getExtensionParam('highlight_color') || 'yellow'; node.style.backgroundColor = color; } unmountView(node, context) { node.style.backgroundColor = ''; } } // Custom web component for maps class MapComponent extends HTMLElement { connectedCallback() { this.innerHTML = '
'; } setProps(props, variables) { const lat = props.latitude || 0; const lng = props.longitude || 0; // Initialize map with coordinates this.initMap(lat, lng); } } customElements.define('divkit-map', MapComponent); // Render with extensions and custom components render({ id: 'extended-divkit', target: document.getElementById('root'), extensions: new Map([ ['lottie', lottieExtension], ['highlight', new HighlightExtension()] ]), customComponents: new Map([ ['map_widget', { element: 'divkit-map' }] ]), json: { card: { log_id: 'extensions_demo', states: [{ state_id: 0, div: { type: 'container', items: [ { type: 'image', image_url: 'empty://', // Placeholder for lottie width: { type: 'fixed', value: 200 }, height: { type: 'fixed', value: 200 }, extensions: [{ id: 'lottie', params: { lottie_url: 'https://example.com/animation.json' } }] }, { type: 'text', text: 'Highlighted text!', extensions: [{ id: 'highlight', params: { highlight_color: '#ffeb3b' } }] }, { type: 'custom', custom_type: 'map_widget', custom_props: { latitude: 37.7749, longitude: -122.4194 }, width: { type: 'match_parent' }, height: { type: 'fixed', value: 300 } } ] } }] } } }); ``` -------------------------------- ### Install Dependencies Source: https://github.com/divkit/divkit.git/blob/main/client/web/divkit-examples/custom-container/README.md Run this command to install the necessary packages for your project. ```bash npm ci ``` -------------------------------- ### Start Development Server Source: https://github.com/divkit/divkit.git/blob/main/figma-plugin/README.md Run this command to start the development server for the Figma plugin. ```bash npm run dev ``` -------------------------------- ### Get Test Data Script Source: https://github.com/divkit/divkit.git/blob/main/client/flutter/divkit/README.md Run this command from `client/flutter/divkit` to create a soft link to layout examples. ```shell ./tool/get_test_data.sh ``` -------------------------------- ### DivKit Installation Source: https://github.com/divkit/divkit.git/blob/main/client/web/divkit/README.md Instructions for installing the DivKit package using npm. ```APIDOC ## Installation ``` npm i @divkitframework/divkit --save ``` ``` -------------------------------- ### Setup Environment for DivKit API Generator Source: https://github.com/divkit/divkit.git/blob/main/api_generator/README.md Installs the necessary development dependencies for the DivKit API Generator using pip. Ensure you have Python and pip installed. ```shell pip install -r dev_requirements.txt ``` -------------------------------- ### Installation Rules for Application Bundle Source: https://github.com/divkit/divkit.git/blob/main/client/flutter/divkit/example/windows/CMakeLists.txt Configures the installation process to copy the executable, support files, and assets next to the executable, ensuring the application can run in place. It also sets up the installation prefix and defines destinations for data and libraries. ```cmake # === Installation === # Support files are copied into place next to the executable, so that it can # run in place. This is done instead of making a separate bundle (as on Linux) # so that building and running from within Visual Studio will work. set(BUILD_BUNDLE_DIR "$") # Make the "install" step default, as it's required to run. set(CMAKE_VS_INCLUDE_INSTALL_TO_DEFAULT_BUILD 1) if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE) endif() set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data") set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}") install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}" COMPONENT Runtime) install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" COMPONENT Runtime) if(PLUGIN_BUNDLED_LIBRARIES) install(FILES "${PLUGIN_BUNDLED_LIBRARIES}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" COMPONENT Runtime) endif() # Fully re-copy the assets directory on each build to avoid having stale files # from a previous install. set(FLUTTER_ASSET_DIR_NAME "flutter_assets") install(CODE " file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\") " COMPONENT Runtime) install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) # Install the AOT library on non-Debug builds only. install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" CONFIGURATIONS Profile;Release COMPONENT Runtime) ``` -------------------------------- ### Run Sample Application Source: https://github.com/divkit/divkit.git/blob/main/client/web/divkit-examples/custom-extended-api/README.md Execute this command to start the sample application. ```shell npm start ``` -------------------------------- ### Install Application Bundle Source: https://github.com/divkit/divkit.git/blob/main/client/flutter/divkit/example/linux/CMakeLists.txt Configures the installation process to create a relocatable bundle. It ensures a clean build bundle directory, installs the executable, ICU data, Flutter library, bundled plugin libraries, and assets. ```cmake install(CODE " file(REMOVE_RECURSE \"${BUILD_BUNDLE_DIR}/\") " COMPONENT Runtime) ``` ```cmake install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}" COMPONENT Runtime) ``` ```cmake install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) ``` ```cmake install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" COMPONENT Runtime) ``` ```cmake foreach(bundled_library ${PLUGIN_BUNDLED_LIBRARIES}) install(FILES "${bundled_library}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" COMPONENT Runtime) endforeach(bundled_library) ``` ```cmake install(CODE " file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\") " COMPONENT Runtime) ``` ```cmake install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) ``` -------------------------------- ### Install DivKit Packages Source: https://github.com/divkit/divkit.git/blob/main/client/web/divkit-examples/globals/README.md Run this command to install the necessary DivKit packages via npm. ```bash npm сi ``` -------------------------------- ### Naive DRY Example (Not Recommended) Source: https://github.com/divkit/divkit.git/blob/main/json-builder/python/README.md This example demonstrates a non-recommended approach to defining reusable components using functions, which does not scale well and is less efficient than using DivKit templates. ```python import pydivkit as dk def get_size(value: int = 32) -> dk.DivFixedSize: return dk.DivFixedSize(value=value) def get_shape() -> dk.DivShape: return dk.DivShape( item_width=get_size(), item_height=get_size(), corner_radius=get_size(100) ) slider_shape = get_shape() slider = dk.DivData( log_id="sample_card", states=[ dk.DivDataState( # other arguments div=dk.DivSlider( thumb_style=dk.DivShapeDrawable( shape=slider_shape, # other arguments ), # other arguments ) ) ] ) ``` -------------------------------- ### Initialize Divan with DSL Source: https://github.com/divkit/divkit.git/blob/main/json-builder/kotlin/README.md Use the `divan` method to access the `DivScope` and start building your layout data within the DSL. ```kotlin val divan = divan { // Your layout data here } ``` -------------------------------- ### Install DivKit React Component Source: https://github.com/divkit/divkit.git/blob/main/client/web/divkit-react/README.md Install the React component for DivKit using npm. ```bash npm i @divkitframework/react --save ``` -------------------------------- ### Start Server with Existing Layout Source: https://github.com/divkit/divkit.git/blob/main/tools/hot_reload/README.md Start the DivKit hot reload server to serve an existing div-json file. This is useful for updating built-in div-json files without rebuilding the application, as it does not accept updates from clients. ```bash ./run.sh path/to/your/layout.json ``` -------------------------------- ### Install DivKit Package Source: https://github.com/divkit/divkit.git/blob/main/client/web/divkit-examples/node-esm/README.md Install the DivKit package using npm before using it in your Node.js project. ```bash npm i @divkitframework/divkit ``` -------------------------------- ### Start Hot Reload Server Source: https://github.com/divkit/divkit.git/blob/main/tools/hot_reload/README.md Start the DivKit hot reload server using the provided script. By default, it uses 10.0.2.2 as the host machine address for emulators. This command creates a temporary div-json file, starts the server, and opens the file in your default editor, allowing the client to send layout data. ```sh ./run.sh ``` -------------------------------- ### Build DivKit Project Source: https://github.com/divkit/divkit.git/blob/main/client/web/divkit-examples/extensions-handmade/README.md Execute this script to build your DivKit project after installing dependencies. ```bash npm run build ``` -------------------------------- ### Install DivKit Visual Editor Source: https://github.com/divkit/divkit.git/blob/main/visual-editor/README.md Install the DivKit Visual Editor package using npm. This command should be run in your project's root directory. ```sh npm i @divkitframework/visual-editor ``` -------------------------------- ### Install DivKit via npm Source: https://github.com/divkit/divkit.git/blob/main/client/web/divkit/README.md Use this command to add the DivKit framework to your project dependencies. ```bash npm i @divkitframework/divkit --save ``` -------------------------------- ### Build Lottie Extension Source: https://github.com/divkit/divkit.git/blob/main/client/web/divkit-examples/extensions-builtin/README.md Construct a Lottie extension using the provided builder and a Lottie player. This requires installing the 'lottie-web' package separately. ```javascript import { lottieExtensionBuilder } from '@divkitframework/divkit/client'; import Lottie from 'lottie-web/build/player/lottie'; map.set('lottie', lottieExtensionBuilder(Lottie.loadAnimation)); ``` -------------------------------- ### Install DivKit with CocoaPods Source: https://github.com/divkit/divkit.git/blob/main/client/ios/README.md Add the DivKit pod to your application's Podfile for installation using CocoaPods. Ensure you are sourcing from the correct repository. ```ruby source 'https://github.com/divkit/divkit-ios.git' target 'MyApp' do pod 'DivKit' end ``` -------------------------------- ### Client-Only Rendering Source: https://github.com/divkit/divkit.git/blob/main/client/web/divkit/README.md Example of using DivKit for client-side rendering only. ```APIDOC ## Client-only rendering For the client-only usage there is `/client` module. The size of this module is slightly smaller than `/client-hydratable`. ```js import {render} from '@divkitframework/divkit/client'; render({ id: 'smth', target: document.querySelector('#root'), json: { card: {}, templates: {} }, onError(details) { console.error(details.error); } }); ``` ``` -------------------------------- ### Use Column Container with Nested Rows and Stacks Source: https://github.com/divkit/divkit.git/blob/main/json-builder/kotlin/README.md Demonstrates the use of the `column` container shortcut, which simplifies the declaration of child items. Nested `row` and `stack` containers are shown as examples of children. ```kotlin val divan = divan { data( logId = "my-layout-id", states = singleRoot( div = column( // Container items = listOf( row(...), // Container stack(...) // Container ) ) ) ) } ``` -------------------------------- ### Server-Side Rendering (SSR) + Hydration Source: https://github.com/divkit/divkit.git/blob/main/client/web/divkit/README.md Example of using DivKit with server-side rendering and client-side hydration. ```APIDOC ## SSR + hydration On the server side there is `/server` module: ```js import {render} from '@divkitframework/divkit/server'; const html = render({ id: 'smth', json: { card: {}, templates: {} }, onError(details) { console.error(details.error); } }); ``` Then use `/client-hydratable` on client to hydrate server-side html:: ```js import {render} from '@divkitframework/divkit/client-hydratable'; render({ id: 'smth', target: document.querySelector('#root'), hydrate: true, json: { card: {}, templates: {} }, onError(details) { console.error(details.error); } }); ``` ``` -------------------------------- ### DivJson with Palette Support Example Source: https://github.com/divkit/divkit.git/blob/main/client/web/divkit/README.md This JSON structure demonstrates how to define colors for light and dark themes using the 'palette' property, which can be referenced within the 'card' and 'templates'. ```json { "card": { "states": [ { "div": { "type": "text", "text": "Hello palette", "text_color": "@{text}", "background": [{ "type": "solid", "color": "@{bg}" }] }, "state_id": 0 } ], "log_id": "test" }, "templates": {}, "palette": { "dark": [ { "name": "bg", "color": "#000" }, { "name": "text", "color": "#fff" } ], "light": [ { "name": "bg", "color": "#fff" }, { "name": "text", "color": "#000" } ] } } ``` -------------------------------- ### Build DivKit JSON with Kotlin DSL Source: https://context7.com/divkit/divkit.git/llms.txt Use the `divan` function for scoped, type-safe construction of DivKit layouts. This example shows basic layout elements like columns, text, images, and buttons. ```kotlin import com.yandex.div.dsl.* import com.yandex.div.dsl.context.* import com.yandex.div.dsl.type.* // Basic layout construction val divJson = divan { data( logId = "kotlin_builder_demo", states = singleRoot( div = column( width = matchParentSize(), height = wrapContentSize(), paddings = edgeInsets(all = 16), items = listOf( header("Welcome to DivKit"), text( text = "Built with Kotlin DSL", fontSize = 16, textColor = color("#666666"), margins = edgeInsets(top = 8) ), image( imageUrl = "https://example.com/banner.jpg", width = matchParentSize(), height = fixedSize(200), scale = fit, margins = edgeInsets(top = 16) ), row( button("Cancel") + textProps( width = wrapContentSize(), actions = action("cancel_click", "app://cancel").asList() ), button("Submit") + textProps( width = wrapContentSize(), actions = action("submit_click", "app://submit").asList(), margins = edgeInsets(left = 8) ), contentAlignmentHorizontal = end, margins = edgeInsets(top = 24) ) ) ) ) ) } // Reusable components via DivScope extensions fun DivScope.header(title: String) = text( text = title, fontSize = 24, fontWeight = bold, textColor = color("#333333") ) fun DivScope.button(label: String) = text( text = label, fontSize = 16, textColor = color("#FFFFFF"), background = solidBackground(color("#2196F3")).asList(), paddings = edgeInsets(left = 16, right = 16, top = 12, bottom = 12), borderRadius = 8 ) fun DivScope.action(logId: String, url: String) = divAction( logId = logId, url = url ) // Serialize to JSON val jsonString = divJson.toJson() println(jsonString) ``` -------------------------------- ### Changing DivKit Theme Example Source: https://github.com/divkit/divkit.git/blob/main/client/web/divkit/README.md This JavaScript snippet shows how to dynamically change the theme of a DivKit instance to 'dark'. ```javascript instance.setTheme('dark'); ``` -------------------------------- ### Setup DivKit Environment on Android Source: https://github.com/divkit/divkit.git/blob/main/client/multiplatform/README.md Configure platform-specific dependencies for DivKit on Android, such as setting an image loader factory and a lifecycle owner. This code should be placed within your Android-specific code. ```kotlin val environment = DivKitEnvironment.Builder(baseContext = this) .imageLoaderFactory { ctx -> PicassoDivImageLoader(ctx) } .lifecycleOwner(this) .build() setContent { inject(environment) { MainScreen() } } ``` -------------------------------- ### Render DivKit Card with Custom Component Source: https://github.com/divkit/divkit.git/blob/main/client/web/divkit-examples/custom-simple/index.html Use the `render` function to display a DivKit card. This example shows how to register and use a custom component named 'custom_card'. Ensure the custom element is imported and defined. ```javascript import { render } from './node_modules/@divkitframework/divkit/dist/esm/client.mjs'; import './customElement.js'; render({ id: 'test', target: document.querySelector('#root'), customComponents: new Map([ ['custom_card', { element: 'custom-card' }] ]), json: { "templates": { }, "card": { "log_id": "snapshot_test_card", "states": [ { "state_id": 0, "div": { "type": "custom", "custom_type": "custom_card", "custom_props": { "start": 15 } } } ] } } }); ``` -------------------------------- ### Basic Client-Side Rendering with DivKit Source: https://context7.com/divkit/divkit.git/llms.txt Renders DivKit JSON directly in the browser. Includes setup for rendering, error handling, statistics tracking, and custom action handling. Use this for standard client-side applications. ```javascript import { render } from '@divkitframework/divkit/client'; import '@divkitframework/divkit/dist/client.css'; // Basic client-side rendering const divkitInstance = render({ id: 'my-divkit-card', target: document.getElementById('root'), json: { templates: { // Reusable templates card_header: { type: 'text', font_size: 24, font_weight: 'bold', text_color: '#333333', $text: 'title' } }, card: { log_id: 'web_sample', states: [{ state_id: 0, div: { type: 'container', orientation: 'vertical', paddings: { left: 16, right: 16, top: 16, bottom: 16 }, items: [ { type: 'card_header', title: 'Welcome to DivKit Web' }, { type: 'text', text: 'This is rendered on the web!', font_size: 16, margins: { top: 8 } }, { type: 'image', image_url: 'https://example.com/banner.jpg', width: { type: 'match_parent' }, height: { type: 'fixed', value: 200 }, scale: 'fill', margins: { top: 16 } } ] } }] } }, onError(details) { console.error('DivKit error:', details.error.level, details.error.message); }, onStat(details) { console.log('DivKit stat:', details.type, details.action); // Track clicks and visibility if (details.type === 'click') { analytics.track('divkit_click', details.action); } }, onCustomAction(action) { // Handle custom URL schemes const url = new URL(action.url); if (url.protocol === 'app-action:') { handleAppAction(url); } } }); // Update data without full re-render (experimental) divkitInstance.setData({ card: { log_id: 'updated_card', states: [{ state_id: 0, div: { /* new content */ } }] } }); // Cleanup when done // divkitInstance.destroy(); ``` -------------------------------- ### Initialize Div2View with Configuration Source: https://context7.com/divkit/divkit.git/llms.txt Creates a DivKit view by configuring DivConfiguration, parsing JSON data with templates, and setting the data on Div2View. Ensure a valid DivImageLoader and Div2Context are provided. ```kotlin import com.yandex.div.core.Div2Context import com.yandex.div.core.DivConfiguration import com.yandex.div.core.view2.Div2View import com.yandex.div.data.DivParsingEnvironment import com.yandex.div.json.ParsingErrorLogger import com.yandex.div2.DivData import org.json.JSONObject // 1. Create DivConfiguration with required image loader val configuration = DivConfiguration.Builder(GlideDivImageLoader(context)) .actionHandler(customActionHandler) .div2Logger(DemoDiv2Logger()) .supportHyphenation(true) .build() // 2. Parse JSON with templates and card data fun JSONObject.asDiv2DataWithTemplates(): DivData { val templates = getJSONObject("templates") val card = getJSONObject("card") val environment = DivParsingEnvironment(ParsingErrorLogger.LOG) environment.parseTemplates(templates) return DivData(environment, card) } // 3. Create and configure Div2View val div2Context = Div2Context(baseContext = baseContext, configuration = configuration) val div2View = Div2View(div2Context) // 4. Set data with unique tag for tracking val jsonData = JSONObject(""" { "templates": {}, "card": { "log_id": "sample_card", "states": [{ "state_id": 0, "div": { "type": "text", "text": "Hello DivKit!", "font_size": 24 } }] } } """) val divData = jsonData.asDiv2DataWithTemplates() div2View.setData(divData, DivDataTag("unique_card_id")) // 5. Add to view hierarchy yourViewGroup.addView(div2View) ``` -------------------------------- ### Set up Body and Root Styles Source: https://github.com/divkit/divkit.git/blob/main/client/web/divkit/tests/hermione/static/index.html Configures the default font family for the body, applies font features for 'liga' and 'kern', and sets up the root element for flexible layout. ```css body { font-family: 'YS Text', 'Helvetica Neue', Arial, sans-serif; -webkit-font-feature-settings: 'liga', 'kern'; -moz-font-feature-settings: 'liga', 'kern'; font-feature-settings: 'liga', 'kern'; margin: 0; background: repeat 0 0; background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAgAAAAICAYAAADED76LAAAAH0lEQVQY02NkYGAwZkAFZ5E5TAwEAOUKGLGIGdPZDQAWUwFC/UpibwAAAABJRU5ErkJggg==); } ``` ```css html, body { height: 100%; } ``` ```css #root { display: flex; flex-direction: column; /* So it would take at least some place */ min-height: 100%; height: max-content; } ``` ```css #root > div { width: 100%; flex: 1 0 auto; } ``` ```css .log-item { font-family: monospace; margin: 0; } ``` -------------------------------- ### Install AOT Library on Non-Debug Builds Source: https://github.com/divkit/divkit.git/blob/main/client/flutter/divkit/example/linux/CMakeLists.txt Installs the AOT library to the runtime destination only when the build type is not Debug. Ensure the AOT_LIBRARY variable is defined. ```cmake if(NOT CMAKE_BUILD_TYPE MATCHES "Debug") install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" COMPONENT Runtime) endif() ``` -------------------------------- ### Create a Basic Layout Tree in Kotlin Source: https://github.com/divkit/divkit.git/blob/main/json-builder/kotlin/README.md Demonstrates the creation of a simple layout tree using DivKit's DSL in Kotlin. This includes defining basic elements like columns, text, and images with specified dimensions and margins. ```kotlin val divan = divan { data( logId = "my-layout-id", states = singleRoot( div = column( width = wrapContentSize(), height = wrapContentSize(), margins = edgeInsets(left = 10, right = 10, top = 5, bottom = 5), items = listOf( text("Hello, world!", fontSize = 18), image("https://my-image-link") ) ) ) ) } ``` -------------------------------- ### fetchInit Function for Fetch Requests Source: https://github.com/divkit/divkit.git/blob/main/client/web/divkit/README.md Used as the second parameter for fetch requests in download and submit actions. It can be a function returning an options object or a direct options object. ```typescript function fetchInit(url: string) { return { credentials: 'include' }; } ``` ```typescript fetchInit: { credentials: 'include' } ``` -------------------------------- ### Template Name Conflicts Example Source: https://github.com/divkit/divkit.git/blob/main/json-builder/python/README.md This example illustrates a potential issue with template name conflicts when multiple classes with the same name are defined, which can lead to unexpected behavior. It's a warning for scenarios where class names might clash. ```python import pydivkit as dk class MyTemplate(dk.DivContainer): width = dk.DivWrapContentSize() class MyTemplate(dk.DivContainer): pass ``` -------------------------------- ### Project and Build Configuration Source: https://github.com/divkit/divkit.git/blob/main/client/flutter/divkit/example/windows/CMakeLists.txt Sets up the minimum CMake version, project name, executable name, and manages build configuration types based on whether the generator is multi-config. ```cmake cmake_minimum_required(VERSION 3.14) project(example LANGUAGES CXX) set(BINARY_NAME "example") cmake_policy(SET CMP0063 NEW) get_property(IS_MULTICONFIG GLOBAL PROPERTY GENERATOR_IS_MULTI_CONFIG) if(IS_MULTICONFIG) set(CMAKE_CONFIGURATION_TYPES "Debug;Profile;Release" CACHE STRING "" FORCE) else() if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) set(CMAKE_BUILD_TYPE "Debug" CACHE STRING "Flutter build mode" FORCE) set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS "Debug" "Profile" "Release") endif() endif() ``` -------------------------------- ### Initialize DivHostingView in SwiftUI Source: https://github.com/divkit/divkit.git/blob/main/client/ios/Samples/README.md This snippet demonstrates initializing a DivHostingView for SwiftUI. It requires DivKitComponents, a DivViewSource, and optional debug parameters. ```swift DivHostingView( divkitComponents: DivKitComponents( divCustomBlockFactory: SampleDivCustomBlockFactory(), urlHandler: SampleDivActionHandler( isPresented: $isPresented, text: $text ) ), source: DivViewSource(kind: .data(sampleData), cardId: "Sample"), debugParams: DebugParams(isDebugInfoEnabled: true) ) ``` -------------------------------- ### Initialize and Manage DivKit Variables in Swift Source: https://context7.com/divkit/divkit.git/llms.txt Demonstrates how to set up and manage global variables using DivKit's `DivVariableStorage`. Ensure `DivKitComponents` is initialized before use. ```swift import DivKit class VariableManager { private let divKitComponents: DivKitComponents private var variableStorage: DivVariableStorage init(divKitComponents: DivKitComponents) { self.divKitComponents = divKitComponents self.variableStorage = divKitComponents.variablesStorage } func setupVariables() { // Define initial variables let variables: [DivVariableValue] = [ .string(name: "username", value: "Guest"), .integer(name: "score", value: 0), .bool(name: "darkMode", value: false), .color(name: "accentColor", value: .systemBlue), .url(name: "profileUrl", value: URL(string: "https://example.com")!) ] // Set variables in storage for variable in variables { variableStorage.set(cardId: nil, variables: [variable]) } } func updateVariable(name: String, value: String) { variableStorage.update( cardId: nil, name: name, value: value ) } func updateIntegerVariable(name: String, value: Int) { variableStorage.update( cardId: nil, name: name, value: String(value) ) } func subscribeToChanges() { // Observe variable changes variableStorage.changeEvents.addObserver { event in print("Variables changed: \(event.changedVariables)") } } func getVariableValue(name: String) -> T? { return variableStorage.getVariableValue(cardId: nil, name: name) } } ``` -------------------------------- ### Initialize DivKit and Render Layout in iOS Source: https://context7.com/divkit/divkit.git/llms.txt Set up DivKitComponents with a URL handler and initialize DivView. Load and render DivKit JSON data by parsing it and setting the source for DivView. Handles custom URL schemes and opens external URLs. ```swift import DivKit import UIKit class DivKitViewController: UIViewController { private var divKitComponents: DivKitComponents! private var divView: DivView! override func viewDidLoad() { super.viewDidLoad() setupDivKit() } private func setupDivKit() { // 1. Initialize DivKitComponents with optional customizations divKitComponents = DivKitComponents( urlHandler: { [weak self] url, info in self?.handleAction(url: url, info: info) } ) // 2. Create DivView divView = DivView(divKitComponents: divKitComponents) divView.translatesAutoresizingMaskIntoConstraints = false view.addSubview(divView) NSLayoutConstraint.activate([ divView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor), divView.leadingAnchor.constraint(equalTo: view.leadingAnchor), divView.trailingAnchor.constraint(equalTo: view.trailingAnchor), divView.bottomAnchor.constraint(equalTo: view.bottomAnchor) ]) // 3. Load and render JSON loadDivData() } private func loadDivData() { let jsonString = """ { "templates": {}, "card": { "log_id": "ios_sample", "states": [{ "state_id": 0, "div": { "type": "container", "orientation": "vertical", "items": [ { "type": "text", "text": "Hello from iOS!", "font_size": 24, "font_weight": "bold", "text_alignment_horizontal": "center" }, { "type": "image", "image_url": "https://example.com/image.png", "width": {"type": "match_parent"}, "height": {"type": "fixed", "value": 200}, "scale": "fit" } ] } }] } } """ guard let data = jsonString.data(using: .utf8), let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any], let divData = divKitComponents.parseDivData(json) else { return } divView.setSource(.init( kind: .divData(divData), cardId: "sample_card" )) } private func handleAction(url: URL, info: DivActionInfo) { switch url.scheme { case "custom": print("Custom action: \(url)") default: UIApplication.shared.open(url) } } } ``` -------------------------------- ### entity_with_string_enum_property JSON Example Source: https://github.com/divkit/divkit.git/blob/main/api_generator/tests/references/documentation/en/entity_with_string_enum_property.md This JSON object represents an instance of the entity_with_string_enum_property. The 'type' must be 'entity_with_string_enum_property', and 'property' can be any string. ```json { type*: "entity_with_string_enum_property", property*: "string" } ``` -------------------------------- ### Build with Ya Make Source: https://github.com/divkit/divkit.git/blob/main/api_generator/README.md Builds the project using the 'ya make' build system. This is a common command for projects within certain development environments. ```shell ya make ``` -------------------------------- ### Create a basic DivContainer with DivGallery and DivText Source: https://github.com/divkit/divkit.git/blob/main/json-builder/python/README.md Demonstrates the basic object-oriented API for creating nested DivKit blocks. Use this for simple UI structures. ```python import json import pydivkit as dk container = dk.DivContainer( items=[ dk.DivGallery( items=[ dk.DivText(text="Hello from pydivkit") ] ) ] ) print(json.dumps(container.dict(), indent=1)) ``` -------------------------------- ### Export Flutter Library Path Source: https://github.com/divkit/divkit.git/blob/main/client/flutter/divkit/example/windows/flutter/CMakeLists.txt Makes the FLUTTER_LIBRARY variable available in the parent CMake scope for use in installation steps. ```cmake set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE) ``` -------------------------------- ### Styling and Platform Settings Source: https://github.com/divkit/divkit.git/blob/main/client/web/divkit/README.md Options to control the appearance and platform-specific behavior. ```APIDOC ## platform ### Description Tweaks for mouse or touch events. ### Type `desktop` | `touch` | `auto` ### Default Value `auto` ## direction ### Description Sets the direction of the text and layout inside the markup (the html `dir` attribute). This property changes the behaviour of `start` / `end` and other properties and values. ### Type `ltr` | `rtl` ### Default Value `ltr` ## mix ### Description An additional class added to the root element. ### Type String, optional ``` -------------------------------- ### entity_with_raw_array JSON Example Source: https://github.com/divkit/divkit.git/blob/main/api_generator/tests/references/documentation/en/entity_with_raw_array.md This JSON object represents an entity with a raw array. Ensure the 'type' field is set to 'entity_with_raw_array'. ```json { type*: "entity_with_raw_array", array*: "raw_array" } ``` -------------------------------- ### Set Minimum CMake Version Source: https://github.com/divkit/divkit.git/blob/main/client/flutter/divkit/example/windows/flutter/CMakeLists.txt Specifies the minimum required version of CMake for this project. Ensure your CMake installation meets this requirement. ```cmake cmake_minimum_required(VERSION 3.14) ``` -------------------------------- ### JSON with DivKit Variables Source: https://context7.com/divkit/divkit.git/llms.txt Example of a DivKit JSON structure that defines and utilizes variables for dynamic content rendering and conditional logic. ```json { "card": { "log_id": "variable_card", "variables": [ {"name": "counter", "type": "integer", "value": 0} ], "variable_triggers": [{ "condition": "@{counter > 10}", "actions": [{ "log_id": "threshold_reached", "url": "custom://show_alert?message=Threshold reached!" }] }], "states": [{ "state_id": 0, "div": { "type": "text", "text": "Welcome, @{username}! Score: @{score}" } }] } } ``` -------------------------------- ### Example JSON for Custom Container Source: https://github.com/divkit/divkit.git/blob/main/client/android/README.md This JSON structure defines a custom container with text items. It specifies the custom type for the container. ```json { "type": "custom", "id": "new_custom_container_1", "items": [ { "type": "text", "news_item_text": "This is div-text item 1" }, { "type": "text", "news_item_text": "This is div-text item 2" } ], "custom_type": "new_custom_container_1" } ``` -------------------------------- ### API: render Function Source: https://github.com/divkit/divkit.git/blob/main/client/web/divkit/README.md Detailed documentation for the `render` function, including its parameters and usage across different modules. ```APIDOC ## API: render All 3 exported modules have an exported function `render`. This function works in a similar way on client and server. `/client` and `/client-hydratable` requires option `target` - an HTML-element that is used to render json. Instead, `/server` module will return an HTML string. ### id String, required. Means the unique block identifier. Used to generate ids and classes. There should not be 2 blocks with the same `id` on the page. ### json Object, required. Divjson itself. ### target `/client` and `/client-hydratable` HTML-element, required. ### hydrate `/client-hydratable` Boolean, optional. It must be `true`, if the current render must hydrate html in `target`. ### onError Function, optional. Callback for errors and warnings for manual processing. ```ts function onError(detauls: { error: Error & { level: 'error' | 'warn'; additional: Record; }; }) { console.log(error.level, error.additional, error.message); } ``` ``` -------------------------------- ### Build Catalog Layout with Product Cards in Kotlin Source: https://context7.com/divkit/divkit.git/llms.txt Constructs a DivKit layout for a product catalog using the 'productCard' component. It demonstrates how to use the 'gallery' and 'column' composables to arrange multiple product cards. ```kotlin // Use templates in layout val catalogLayout = divan { data( logId = "product_catalog", states = singleRoot( div = column( header("Featured Products"), gallery( items = listOf( productCard( title = "Wireless Headphones", subtitle = "$99.99", imageUrl = "https://example.com/headphones.jpg", productId = "prod_001" ), productCard( title = "Smart Watch", subtitle = "$249.99", imageUrl = "https://example.com/watch.jpg", productId = "prod_002" ), productCard( title = "Bluetooth Speaker", subtitle = "$79.99", imageUrl = "https://example.com/speaker.jpg", productId = "prod_003" ) ), itemSpacing = 16, paddings = edgeInsets(left = 16, right = 16), margins = edgeInsets(top = 16) ) ) ) ) } ``` -------------------------------- ### Entity with Required Property JSON Example Source: https://github.com/divkit/divkit.git/blob/main/api_generator/tests/references/documentation/en/entity_with_required_property.md This JSON structure represents an entity that requires specific string properties. Ensure 'property' is a non-empty string and 'type' is exactly 'entity_with_required_property'. ```json { "type": "entity_with_required_property", "property": "string" } ``` -------------------------------- ### Add Dependencies and Include Directories Source: https://github.com/divkit/divkit.git/blob/main/client/flutter/divkit/example/windows/runner/CMakeLists.txt Links the application target against the 'flutter' and 'flutter_wrapper_app' libraries and adds the source directory to the include path. Add any other application-specific dependencies here. ```cmake # Add dependency libraries and include directories. Add any application-specific # dependencies here. target_link_libraries(${BINARY_NAME} PRIVATE flutter flutter_wrapper_app) target_include_directories(${BINARY_NAME} PRIVATE "${CMAKE_SOURCE_DIR}") ``` -------------------------------- ### Define App Wrapper Source Files Source: https://github.com/divkit/divkit.git/blob/main/client/flutter/divkit/example/windows/flutter/CMakeLists.txt Lists the C++ source files specific to the application runner wrapper implementation. These are prepended with the wrapper root directory. ```cmake list(APPEND CPP_WRAPPER_SOURCES_APP "flutter_engine.cc" "flutter_view_controller.cc" ) list(TRANSFORM CPP_WRAPPER_SOURCES_APP PREPEND "${WRAPPER_ROOT}/") ``` -------------------------------- ### Create Evaluated Expression with Variables Source: https://github.com/divkit/divkit.git/blob/main/json-builder/kotlin/README.md Use `expression` to create evaluable properties, often in conjunction with variables declared in the `data` object. This example shows how to use a variable `alpha_var` in an expression. ```kotlin val divan = divan { data( logId = "my-layout-id", states = singleState( div = column( items = listOf( text("Hello, world!").evaluate(alpha = "@{toNumber(alpha_var) / 255.0}"), slider( minValue = 0, maxValue = 255, thumbValueVariable = "alpha_var", ... ) ) ) ), variables = listOf( integerVariable(name = "alpha_var", value = 0) ) ) } ``` -------------------------------- ### Implement DivDownloader for Patch Loading Source: https://github.com/divkit/divkit.git/blob/main/client/android/sample/README.md Implement the DivDownloader interface to handle the download of patches. This method is called when a `div-action://download` action is triggered. Ensure you handle success and failure callbacks appropriately. ```kotlin override fun downloadPatch( divView: Div2View, downloadUrl: String, callback: DivPatchDownloadCallback) ``` -------------------------------- ### Client-Side DivKit API Callback Source: https://github.com/divkit/divkit.git/blob/main/client/web/divkit-examples/custom-extended-api/README.md Implement `divKitApiCallback` in your Custom Elements class to receive DivKit API access after construction and connection. Use this to get variable instances and subscribe to their changes. ```typescript divKitApiCallback({ variables }) { const instance = variables.get('name'); if (instance) { instance.subscribe(newValue => console.log); } } ``` -------------------------------- ### Define Plugin Wrapper Source Files Source: https://github.com/divkit/divkit.git/blob/main/client/flutter/divkit/example/windows/flutter/CMakeLists.txt Lists the C++ source files specific to the plugin wrapper implementation. These are prepended with the wrapper root directory. ```cmake list(APPEND CPP_WRAPPER_SOURCES_PLUGIN "plugin_registrar.cc" ) list(TRANSFORM CPP_WRAPPER_SOURCES_PLUGIN PREPEND "${WRAPPER_ROOT}/") ``` -------------------------------- ### Using DivKit ES Module in Browser Source: https://github.com/divkit/divkit.git/blob/main/client/web/divkit/README.md Include DivKit as an ES module directly in your HTML using a script tag with `type="module"`. This example demonstrates client-only rendering. ```html ``` -------------------------------- ### Apply Standard Build Settings Source: https://github.com/divkit/divkit.git/blob/main/client/flutter/divkit/example/windows/runner/CMakeLists.txt Applies a standard set of build settings to the defined executable target. This can be removed if custom build settings are required. ```cmake # Apply the standard set of build settings. This can be removed for applications # that need different build settings. apply_standard_settings(${BINARY_NAME}) ``` -------------------------------- ### Define and Print Template Name Source: https://github.com/divkit/divkit.git/blob/main/json-builder/python/README.md Demonstrates how to define a DivKit template and print its default template name. ```python import pydivkit as dk class MyTemplate(dk.DivContainer): width = dk.DivWrapContentSize() print(MyTemplate.template_name) ``` -------------------------------- ### Define Core Wrapper Source Files Source: https://github.com/divkit/divkit.git/blob/main/client/flutter/divkit/example/windows/flutter/CMakeLists.txt Lists the core C++ source files for the wrapper implementation. These are prepended with the wrapper root directory. ```cmake list(APPEND CPP_WRAPPER_SOURCES_CORE "core_implementations.cc" "standard_codec.cc" ) list(TRANSFORM CPP_WRAPPER_SOURCES_CORE PREPEND "${WRAPPER_ROOT}/") ``` -------------------------------- ### Create Feature Branch Source: https://github.com/divkit/divkit.git/blob/main/client/flutter/divkit/CONTRIBUTING.md Create a new branch for your feature development. Replace my-feature-branch with a descriptive name for your branch. ```bash git checkout -b my-feature-branch ``` -------------------------------- ### Entity with String Enum Property Example Source: https://github.com/divkit/divkit.git/blob/main/api_generator/tests/references/documentation/en/entity_with_string_enum_property_with_default_value.md This JSON structure represents an entity with a required type and an optional string enum value. The 'value' parameter accepts 'first', 'second', or 'third', defaulting to 'second' if not specified. ```json { type*: "entity_with_string_enum_property_with_default_value", value: "string" } ```