# Complete Data Binding Guide

## What is Data Binding?

Data binding in Wallboard connects widgets to live data sources, making content dynamic and automatically updating. Instead of static text or images, widgets display real-time information from RSS feeds, spreadsheets, databases, APIs, and other data sources.

**Key Benefits:**
- **Automatic Updates**: Content refreshes when data changes
- **Template Reusability**: Same design works with different data sets
- **Real-time Content**: Live feeds directly to displays
- **Reduced Maintenance**: No manual content updates needed

## Accessing Data Binding

### Primary Access Methods

**1. Binding Buttons (Hand/Cursor Icons)**
Available next to bindable properties in widget settings:
- **"Bind to data"** - Main content binding
- **"Hide based on"** - Conditional visibility
- **"Font color"** - Dynamic text coloring
- **"BG color"** - Dynamic background coloring

**2. Quick Binding Shortcut**
- **SHIFT + Double Click** on any widget opens data binding for main property

**3. Universal Property Binding**
- **"BIND ANYTHING"** button on all widgets
- Access to any bindable widget property

## The Data Picker Modal

### Interface Layout

The Data Picker Modal opens when clicking any binding button, showing:

**Left Panel: Data Navigation**
- Datasource selection dropdown
- Connected path navigation dropdowns
- Data vs Meta data toggle
- Pivot point controls

**Right Panel: Preview & Configuration**
- **Data Tab**: Raw JSON from selected path
- **Preview Tab**: Formatted display preview
- Fallback value configuration
- Advanced features (Special Formatting, Change Binded Value)

### Data Navigation System

#### Step 1: Datasource Selection
The dropdown shows all available data sources:
- **Regular datasources**: RSS feeds, APIs, databases
- **Mock datasources**: Prefixed with "!" for testing
- **System datasources**: Device info, file system, screenshots

#### Step 2: Path Navigation
Connected dropdown menus navigate through data structure:

1. **First dropdown**: Top-level properties (channel, items, data)
2. **Second dropdown**: Next level (array indices, object properties)
3. **Additional dropdowns**: Continue until reaching target field

**Example Paths:**
- RSS Feed: `channel → description`
- Product Data: `items → 0 → name`
- Weather: `current → temperature → value`

#### Step 3: Pivot Points
**Definition**: Split data path into fixed (above) and variable (at/below) portions

**Visual Indicators:**
- **Connected circles** between dropdowns
- **Blue filled circle** indicates current pivot location
- **Click circles** to move pivot point

**Strategic Placement:**
- **Collection Level**: Set pivot at array/list level for multi-widget binding
- **Higher Pivots**: More reusable for shared contexts
- **Lower Pivots**: More specific, potentially faster

### Data vs Meta Data
- **Data** (default): Actual datasource content
- **Meta data**: Datasource information (refresh time, status, errors)

### Advanced Configuration Options

#### Fallback Values
Default content when data is unavailable:
- Applied when data is null/undefined
- Used during loading or offline states
- Prevents empty widget display

#### Special Formatting
Transform how data appears to users:

**Format Types:**
- **text**: Plain text display
- **number**: Locale-based number formatting
- **date and time**: Timestamp to readable format conversion
- **regular expression**: Pattern-based transformation
- **with fields**: Multi-field combination

**Additional Options:**
- **Before bound value**: Prepend text
- **After bound value**: Append text
- **Trim if too long**: Text truncation

#### Change Binded Value
Data transformation before display:

**Change Types:**
- **Lookup table**: Map specific values to outputs
- **Call function**: JavaScript transformation

**Function Template:**
```javascript
(value) => {return value}
```

**Use Cases:**
- Status code to readable text conversion
- Mathematical calculations
- Complex data structure formatting

## Base Data Binding

### Concept
Content-wide shared data context enabling multiple widgets to use the same datasource with simplified individual bindings.

### Configuration Methods

#### Method 1: Content Tab (Recommended)
1. **Select content** (click outside widgets)
2. **Navigate to Content tab** in properties panel
3. **Find "Data binding" section**
4. **Click binding button** next to "Base data path"
5. **Configure datasource** and set pivot at collection level

#### Method 2: Widget Modal Access
1. **Open any widget's data picker**
2. **Click cog icon** (⚙️) next to "Independent binding"
3. **Configure in "Base binding for content" modal**

### Base Data Configuration

**Key Settings:**
- **Change data row based on data**: Dynamic row selection
- **Hide dependent elements**: Control widget visibility on base data failure
- **Pivot point placement**: Must be at collection level for sharing

**Example Setup:**
- Datasource: Product Catalog
- Path: `products` (array of product objects)
- Pivot: Set at `products` level
- Result: All widgets can bind to `{Base} → field_name`

### Widget Behavior with Base Data

**When Base Data Active:**
- **Simplified paths**: Widgets show relative navigation from pivot
- **Synchronized updates**: All widgets update with base data changes
- **Empty datasource dropdowns**: Inherit from base configuration
- **{Base} indicators**: Show base data dependency

**Template Benefits:**
- **Reusable designs**: Same layout works with different datasets
- **Centralized control**: Single point for data source management
- **Efficient binding**: Reduced configuration per widget

## Independent Binding

### Purpose
Allow individual widgets to use different data sources than content base binding.

### When to Use
- Widget needs unrelated data
- Different refresh requirements
- Cross-datasource comparisons
- Special authentication needs

### Configuration
Enable "Independent binding" toggle in any data picker modal.

## Conditional Features

### Hide Based On (Dynamic Visibility)

**Purpose**: Show/hide widgets based on data conditions
**Logic**: Widget **hides** when condition evaluates to **TRUE**

#### Rule Categories

**Existence Rules:**
- **is anything**: Always hide (testing)
- **is empty**: Hide when null, undefined, "", 0, false, [], {}
- **is not empty**: Hide when data has value
- **is true/false**: Hide when data === true/false

**Equality Rules:**
- **equals**: Hide when data == value (type coercion)
- **does not equal**: Hide when data != value

**Arithmetic Rules:**
- **is less than**: Numeric comparison with Number() conversion
- **is less than or equal**: Inclusive numeric comparison
- **is greater than**: Numeric comparison
- **is greater than or equal**: Inclusive numeric comparison

**Text Rules:**
- **contains**: Case-insensitive substring check
- **does not contain**: Negated substring check
- **regular expression (match)**: Pattern matching
- **regular expression (no match)**: Negated pattern matching

#### Configuration Process
1. **Select data path** to evaluate
2. **Choose rule category** and specific rule
3. **Enter comparison value** (if required)
4. **Set fallback value** for data unavailable
5. **Test in preview** with sample data

#### Example Use Cases
- Hide "Out of Stock" when inventory > 0: `inventory → is greater than → 0`
- Show error message when status = "error": `status → equals → error`
- Hide weekend content on weekdays: `day_of_week → contains → Saturday|Sunday`

### Dynamic Color Binding

**Purpose**: Change text or background colors based on data values
**Types**: Font Color and Background Color (identical interface)

**Configuration**: Uses same comparison rules as Hide Based On (equals, contains, greater than, etc.)

**Evaluation Origins:**
- **Static**: Compare against fixed value (Status = "online" → Green)
- **Interactive Widget**: Compare against another widget's current value
- **Data Field**: Compare against another field from same datasource

**Rule Processing**: Top-to-bottom priority, first match wins, supports presets for reuse

**Independent Binding**: Enable when color data comes from different datasource than widget content

## Universal Property Binding ("Bind Anything")

### Access and Scope
**Availability**: All widget types via "BIND ANYTHING" button
**Purpose**: Bind any widget property to data, beyond standard bindings

### Bindable Properties

**Visual Properties:**
- **Top/Left Position**: Dynamic widget positioning
- **Width/Height**: Data-driven sizing
- **Background Image**: Dynamic image sources
- **Background Color**: Same as BG Color binding
- **Opacity**: Transparency control

**Behavioral Properties:**
- **Hide Based On**: Same as conditional visibility
- **Animate Changes**: Control transition smoothness

### Use Cases

**Dynamic Layouts:**
- Position widgets based on data values
- Create responsive designs adapting to content
- Build dashboards with data-driven positioning

**Visual Feedback:**
- Resize elements to show relative values
- Adjust opacity for highlighting/de-emphasis
- Change backgrounds for status indication

**Data Visualization:**
- Use width/height for simple bar charts
- Position elements for scatter plot creation
- Combine properties for complex visual representations

### Configuration Process
1. **Click "BIND ANYTHING"** on target widget
2. **Select property** from modal list
3. **Click "Add binding"** for chosen property
4. **Configure using standard data picker**
5. **Apply advanced rules** if needed (colors, conditions)

## Data Transformation and Processing

### Datasource Mappers (Custom Field Calculator)

**Purpose**: Calculate fields from content base data or one or more datasources and publish changed results to bound widgets
**Access**: Content tab > **Edit datasource mappers**

**Built-in Templates**: Calendar processing, Emergency alert filtering, Custom JavaScript
**Configuration**: Choose Base data path, Single Datasource, or Multiple Datasources (at least two, referenced as datasource1, datasource2, etc.); output to a property path, mock datasource, or internal datasource using SET (replace) or MERGE

**Custom JavaScript Template (single-input example):**
```javascript
(originalDatasource) => {
    // Transformation logic - always return object
    return { calculatedField: result };
}
```

### External Resource Caching

**Purpose**: Automatically download and cache media files referenced in datasource data

**Benefits for Data Binding**: Improves widget performance, ensures reliable media display during outages, works transparently with all external data sources

## Team-Based Permissions

### Permission Model
- **View**: Use datasource in widgets
- **Edit**: Modify datasource content globally across all screens using it

**Key Principle**: Edit rights enable data modification on any screen displaying that datasource, regardless of content access permissions.

### Role Separation
- **Data Managers**: Edit business data (prices, schedules) with domain expertise
- **Content Creators**: Design layouts and configure data binding with technical skills

## Troubleshooting Common Issues

**Binding Not Updating:**
- Verify data source is active and refreshing
- Check path navigation is complete (no empty dropdowns)
- Ensure fallback value isn't overriding real data

**No Data in Preview:**
- Confirm data source is online and populated
- Validate path exists in current data structure
- Check pivot point placement

**Performance Issues:**
- Optimize display settings (filters, sorts, limits)
- Set pivot points efficiently (higher = more reusable)
- Monitor data volumes

**Empty Widget Display:**
- Configure fallback values for all bindings
- Verify data types match widget expectations
- Test with mock data

## Best Practices

- **Use Base Data Binding** for shared contexts across multiple widgets
- **Test with Mock Data** before connecting live sources
- **Set Meaningful Fallbacks** for all bindings to prevent empty displays
- **Optimize Pivot Points** at collection levels for reusability
- **Enable Resource Caching** for media-heavy external sources

This comprehensive guide covers all aspects of Wallboard's data binding system, providing complete knowledge for effective dynamic content creation and management.
