# Digia Architecture & Runtime

This guide details how Digia transforms a visual definition into a native mobile experience at runtime.

**Core Philosophy**: Just as a **Web Browser** reads HTML to render a webpage, the **Digia SDK** reads a JSON configuration to render Native Widgets. The Server sends the blueprint; the Device builds the house.

## 1. High-Level Architecture

Digia operates on a decoupled architecture where the UI definition is separated from the rendering logic.

* **Digia Studio (The IDE)**: A specialized environment for building server-driven apps. It handles static analysis, data binding, visual layout, and state management to produce a robust UI definition.
* **Digia Cloud (The CDN)**: Hosts the compiled JSON configuration, ensuring global low-latency availability.
* **Digia SDK (The Runtime)**: A lightweight engine inside your app that fetches the configuration and renders native components.

{% @mermaid/diagram content="graph LR
%% Styles
classDef studio fill:#e1f5fe,stroke:#01579b,stroke-width:2px,color:#01579b;
classDef api fill:#fff3e0,stroke:#e65100,stroke-width:2px,color:#e65100;
classDef client fill:#e8f5e9,stroke:#1b5e20,stroke-width:2px,color:#1b5e20;

```
subgraph Design [Design Time]
    Studio[Digia Studio]:::studio
    Compiler[Compiler Service]:::studio
end

subgraph Runtime [Runtime]
    CDN[Edge CDN]:::api
    SDK[Digia SDK]:::client
end

Studio -->|Save & Compile| Compiler
Compiler -->|Publish JSON| CDN
CDN -->|Fetch Config| SDK" %}
```

## 2. The Protocol (JSON Schema)

The core communication language between Digia Cloud and your app is the **SDUI JSON Protocol**.

Unlike traditional APIs that just fetch *data* (e.g., a list of users), the Digia configuration contains **everything** needed to run the module:

* **Pages & Navigation**: The structure of every screen.
* **Components & Styling**: Layouts, colors, fonts, and themes.
* **Logic & Actions**: What happens when a user taps a button or submits a form.
* **API Calls**: Definitions of network requests to your own backend.

```json
{
  "appSettings": {
    "initialRoute": "home"
  },
  "pages": {
    "home": {
      "layout": {
        "root": {
          "type": "scaffold",
          "props": { "backgroundColor": "#FFFFFF" },
          "children": {
            "body": [
              {
                "type": "text",
                "props": {
                  "text": "Hello, Server-Driven World!",
                  "style": { "fontSize": 24, "color": "#000000" }
                }
              },
              {
                "type": "button",
                "props": { "label": "Click Me" },
                "actions": { "onTap": "navigateToSettings" }
              }
            ]
          }
        }
      }
    }
  }
}
```

## 3. The Runtime (Digia UI SDK)

The Digia SDK (available for Flutter, React Native, iOS, Android) is the engine that interprets the protocol. It is not just a UI mapper; it is a full-fledged runtime environment composed of some key layers:

{% @mermaid/diagram content="graph TD
%% Styles
classDef layer fill:#e3f2fd,stroke:#1565c0,stroke-width:2px;
classDef core fill:#fff3e0,stroke:#e65100,stroke-width:2px;

```
subgraph SDK [Digia SDK Runtime]
    direction TB
    Config[Config Manager]:::layer
    Renderer[Recursive Renderer]:::core
    State[State Manager]:::layer
    Logic[Actions & Expressions]:::layer

    Config --> Renderer
    Renderer <--> State
    Renderer <--> Logic
end" %}
```

### 3.1 Core Engine (Recursive Renderer)

At its core, the SDK is a **Recursive Renderer**. It loops through the JSON tree and instantiates the native widgets.

* **Direct Mapping**: Each JSON node translates directly to a native widget. There is no "Virtual DOM" layer.
* **Reactive Updates**: When state changes, the SDK simply rebuilds the affected part of the tree. It relies on the native platform (Flutter, SwiftUI, Compose) to render the changes efficiently.

{% hint style="info" %}
**Performance**: Since the SDK maps JSON directly to **Native Widgets** (e.g., `UIButton`, `RecyclerView`), you get 60fps scrolling and native gesture handling. There are no WebViews involved.
{% endhint %}

### 3.2 State Management System

Digia manages data at multiple levels, ensuring that complex apps can be built without fighting the framework:

1. **Global Store**: App-wide data (e.g., User Profile, Auth Token) accessible from any page.
2. **Page State**: Data scoped to a single screen (e.g., Form data).
3. **Local State**: Ephemeral state for individual components (e.g., Is this dropdown open?).

### 3.3 Logic & Interactivity

The SDK handles dynamic behavior without needing a server round-trip for every action:

* **Expression Library**: Supports dynamic bindings like `${user.name}` or conditional visibility `${gt(cart.total, 0)}`.
* **Actions Manager**: Orchestrates events such as navigation, API calls, or state updates (e.g., `onTap: navigateToPage`).

### 3.4 Config Manager (Network & Caching)

This layer handles the synchronization of your UI definition. It is responsible for fetching, caching, and validating the JSON/Protobuf payload.

{% @mermaid/diagram content="sequenceDiagram
%%{init: {'theme': 'base', 'themeVariables': { 'mainBkg': '#ffffff', 'textColor': '#000000', 'background': '#fff3e0' }}}%%
participant App as Client App
participant SDK as Digia SDK
participant Cloud as Digia Cloud

```
App->>SDK: Initialize SDK
SDK->>Cloud: Check for Updates (Current Version)
Cloud->>Cloud: Compare with Published Version
alt New Version Available
    Cloud-->>SDK: Return New JSON Config
    SDK->>SDK: Update Cache & Render
else Version Match
    Cloud-->>SDK: 304 Not Modified
    SDK->>SDK: Load from Local Cache
end" %}
```

You can configure the update strategy based on your app's needs:

1. **Sync Fetch (Instant Updates)**:
   * On startup, the SDK checks for a new version.
   * If available, it downloads and applies it **immediately** for the current session.
   * *Best for:* Critical fixes or apps that must always show the latest content.
2. **Async Fetch (Background Updates)**:
   * On startup, the SDK immediately requires the **cached** config (zero latency).
   * It checks for updates in the **background**. If a new version is found, it is downloaded silently and saved.
   * The *next* app session will use the new configuration.
   * *Best for:* Optimizing startup time and non-critical updates.

{% hint style="info" %}
**Resilience & Offline Mode**: Our global CDN is backed by industry-standard cloud infrastructure, ensuring 99.99% uptime. However, in the unlikely event of a service disruption or network failure, the app remains fully functional by seamlessly falling back to its **local cache**.
{% endhint %}

## 4. Adoption Strategy: Start Small

You do not need to rebuild your entire app to use Digia. The architecture supports **Incremental Adoption**.

* **Widget Integration**: Use Digia for a single dynamic section, like a "Holiday Sale" banner or a "Feedback Form".
* **Screen Integration**: Embed a Digia view inside an existing native screen.
* **Flow Integration**: Build an entire "Explore" tab or "Onboarding" flow in Digia while keeping the rest of the app as-is.

## 5. Extending the Runtime

Sometimes you need a specialized UI element that isn't in the standard library (e.g., a 3D Model Viewer or a specialized Camera view).

**Custom Widgets** allow you to register your own native components with the SDK. Once registered, you can drop them into the Digia Studio visual builder just like any other component. For implementation details, see [Building Custom Widgets](https://docs.digia.tech/extend-and-ship/custom-widgets).

```dart
void registerCustomButton() {
  DUIFactory().registerWidget<CustomButtonProps>(
    'custom/button-v1', // Unique ID used in Digia Studio
    CustomButtonProps.fromJson,
    (props, childGroups) => CustomButton(
      props: props,
      commonProps: null,
      parent: null,
      refName: 'custom_button',
    ),
  );
}
```
