{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "$id": "https://formspec.org/schemas/theme/1.0",
  "title": "Formspec Theme Document",
  "description": "A Formspec Theme document — a sidecar JSON file that controls the visual presentation of a Formspec Definition without modifying it. A Theme binds to a Definition by URL, overrides inline Tier 1 presentation hints through a three-level cascade (defaults → selectors → item overrides), assigns widgets with typed configuration and fallback chains, defines page layout on a 12-column grid, and provides design tokens for visual consistency. Multiple Theme documents MAY target the same Definition, enabling platform-specific rendering (web, mobile, PDF, kiosk). A Theme MUST NOT affect data collection, validation, or behavioral semantics — it controls only how items are displayed.",
  "type": "object",
  "required": [
    "$formspecTheme",
    "version",
    "targetDefinition"
  ],
  "additionalProperties": false,
  "properties": {
    "$formspecTheme": {
      "type": "string",
      "const": "1.0",
      "description": "Theme specification version. MUST be '1.0'.",
      "examples": [
        "1.0"
      ],
      "x-lm": {
        "critical": true,
        "intent": "Version pin for theme document compatibility. Processors MUST reject themes with an unrecognized version."
      }
    },
    "url": {
      "type": "string",
      "format": "uri",
      "description": "Canonical identifier for this theme. Stable across theme versions — the pair (url, version) SHOULD be globally unique.",
      "examples": [
        "https://agency.gov/forms/budget/themes/web",
        "https://example.org/themes/intake-mobile"
      ]
    },
    "version": {
      "type": "string",
      "minLength": 1,
      "description": "Version of this theme document. SemVer is RECOMMENDED. The pair (url, version) SHOULD be unique across all published theme versions.",
      "examples": [
        "1.0.0",
        "2.1.0-beta.1"
      ],
      "x-lm": {
        "critical": true,
        "intent": "Theme revision identifier. Enables cache-busting and auditing which theme version was applied."
      }
    },
    "name": {
      "type": "string",
      "description": "Machine-friendly short identifier for programmatic use.",
      "examples": [
        "budget-web",
        "intake-mobile"
      ]
    },
    "title": {
      "type": "string",
      "description": "Human-readable display name for the theme.",
      "examples": [
        "Budget Form — Web Theme",
        "Patient Intake — Mobile Theme"
      ]
    },
    "description": {
      "type": "string",
      "description": "Human-readable description of the theme's purpose and target audience.",
      "examples": [
        "Web-optimized theme for the annual budget form with USWDS styling.",
        "Compact mobile theme for clinic check-in kiosks."
      ]
    },
    "targetDefinition": {
      "$ref": "#/$defs/TargetDefinition",
      "description": "Binding to the target Formspec Definition and compatible version range. The theme will only be applied to Definitions matching this target. If compatibleVersions is present and the Definition version falls outside the range, the processor SHOULD warn and MAY fall back to Tier 1 hints only (null theme). The processor MUST NOT fail on a version mismatch.",
      "examples": [
        {
          "url": "https://agency.gov/forms/budget",
          "compatibleVersions": ">=1.0.0 <2.0.0"
        },
        {
          "url": "https://example.org/forms/intake"
        }
      ],
      "x-lm": {
        "critical": true,
        "intent": "Declares which form definition this theme can be applied to. Prevents accidental application to unrelated definitions."
      }
    },
    "platform": {
      "type": "string",
      "description": "Target rendering platform. Informational — processors that do not recognize a platform value SHOULD apply the theme regardless. Well-known values: 'web' (desktop/mobile browsers), 'mobile' (native apps), 'pdf' (PDF rendering), 'print' (print-optimized), 'kiosk' (public terminals), 'universal' (no platform assumptions, implicit default).",
      "examples": [
        "web",
        "mobile",
        "pdf",
        "kiosk"
      ]
    },
    "tokens": {
      "$ref": "#/$defs/Tokens",
      "description": "Design tokens — named values (colors, spacing, typography, borders) that promote visual consistency. Defined once here, referenced throughout the theme via '$token.<key>' syntax in style and widgetConfig string values. Token keys use dot-delimited category prefixes (e.g., 'color.primary', 'spacing.md'). Values MUST be strings or numbers. Token references MUST NOT be recursive.",
      "examples": [
        {
          "color.primary": "#0057B7",
          "color.error": "#D32F2F",
          "color.surface": "#FFFFFF",
          "spacing.sm": "8px",
          "spacing.md": "16px",
          "spacing.lg": "24px",
          "border.radius": "6px",
          "border.width": 1,
          "typography.body.family": "Inter, system-ui, sans-serif",
          "typography.body.size": "1rem",
          "elevation.low": "0 1px 3px rgba(0,0,0,0.12)"
        }
      ],
      "x-lm": {
        "critical": true,
        "intent": "Central design vocabulary referenced via $token.<key> in style and widgetConfig. Enables consistent theming and easy rebrand. RECOMMENDED category prefixes: color.*, spacing.*, typography.*, border.*, elevation.*, x-* (custom)."
      }
    },
    "defaults": {
      "$ref": "#/$defs/PresentationBlock",
      "description": "Cascade level 1 (lowest theme specificity): baseline PresentationBlock applied to every item before selectors or per-item overrides. Sets the form-wide visual baseline. Overrides Tier 1 inline presentation hints (level 0) and formPresentation globals (level -1). Overridden by selectors (level 2) and items (level 3). Merge is shallow per-property — nested objects (widgetConfig, style, accessibility) are replaced as a whole, not deep-merged. Exception: cssClass uses union semantics across all levels.",
      "examples": [
        {
          "labelPosition": "top",
          "style": {
            "borderRadius": "$token.border.radius",
            "fontFamily": "$token.typography.body.family"
          },
          "cssClass": "formspec-field"
        }
      ],
      "x-lm": {
        "critical": true,
        "intent": "Cascade level 1. Form-wide presentation baseline. Establishes consistent defaults before type-specific or per-item overrides."
      }
    },
    "selectors": {
      "type": "array",
      "items": {
        "$ref": "#/$defs/Selector"
      },
      "description": "Cascade level 2: type/dataType-based presentation overrides. Each selector has a 'match' (criteria) and 'apply' (PresentationBlock). Selectors are evaluated in document order — all matching selectors apply, with later matches overriding earlier ones per-property. Overrides defaults (level 1); overridden by items (level 3).",
      "examples": [
        [
          {
            "match": { "dataType": "money" },
            "apply": {
              "widget": "moneyInput",
              "widgetConfig": { "showCurrencySymbol": true, "locale": "en-US" }
            }
          },
          {
            "match": { "dataType": "boolean" },
            "apply": {
              "widget": "toggle",
              "widgetConfig": { "onLabel": "Yes", "offLabel": "No" }
            }
          },
          {
            "match": { "type": "display" },
            "apply": { "widget": "paragraph" }
          }
        ]
      ],
      "x-lm": {
        "critical": true,
        "intent": "Cascade level 2. Pattern-based overrides by item type or dataType. All matching selectors apply in order, enabling layered type-specific styling."
      }
    },
    "items": {
      "type": "object",
      "additionalProperties": {
        "$ref": "#/$defs/PresentationBlock"
      },
      "description": "Cascade level 3 (highest theme specificity): per-item overrides keyed by the item's 'key' from the Definition. Overrides all lower cascade levels. Item keys that do not correspond to any item in the target Definition SHOULD produce a warning but MUST NOT cause failure.",
      "examples": [
        {
          "totalBudget": {
            "widget": "moneyInput",
            "style": {
              "background": "#F0F6FF",
              "borderColor": "$token.color.primary",
              "borderWidth": "2px"
            },
            "accessibility": {
              "liveRegion": "polite",
              "description": "Calculated total of all budget line items"
            }
          },
          "priorityLevel": {
            "widget": "slider",
            "widgetConfig": { "min": 1, "max": 5, "step": 1, "showTicks": true },
            "fallback": ["dropdown"]
          }
        }
      ],
      "x-lm": {
        "critical": true,
        "intent": "Cascade level 3. Highest specificity — surgical per-item presentation control. Overrides defaults, selectors, and Tier 1 hints."
      }
    },
    "pages": {
      "type": "array",
      "items": {
        "$ref": "#/$defs/PageLayout"
      },
      "description": "Page layout — ordered list of pages grouping items into logical sections with a 12-column grid. When absent, the renderer walks the Definition's item tree top-to-bottom without page grouping. Items not referenced by any region on any page SHOULD be rendered after all pages in default order. The cascade (defaults/selectors/items) still applies regardless of page layout.",
      "examples": [
        [
          {
            "id": "info",
            "title": "Project Information",
            "regions": [
              { "key": "projectName", "span": 8 },
              { "key": "projectCode", "span": 4 },
              { "key": "email", "span": 12 }
            ]
          },
          {
            "id": "review",
            "title": "Review & Submit",
            "description": "Review your submission before signing.",
            "regions": [
              { "key": "certify", "span": 12 },
              { "key": "approverSignature", "span": 12 }
            ]
          }
        ]
      ]
    },
    "breakpoints": {
      "$ref": "#/$defs/Breakpoints",
      "description": "Named responsive breakpoints as min-width pixel values. Referenced by regions' 'responsive' objects to override span, start, or visibility at different viewport sizes. Processors that do not support responsive layouts SHOULD use the base span and start values.",
      "examples": [
        {
          "sm": 576,
          "md": 768,
          "lg": 1024
        }
      ]
    },
    "extensions": {
      "type": "object",
      "propertyNames": {
        "pattern": "^x-"
      },
      "description": "Extension namespace for platform-specific or vendor-specific metadata. All keys MUST be x- prefixed. Processors MUST ignore unrecognized extensions. Extensions MUST NOT alter core presentation semantics.",
      "examples": [
        {
          "x-analytics": { "trackFields": true, "provider": "formspec-analytics" },
          "x-pdf": { "paperSize": "A4", "orientation": "portrait" }
        }
      ]
    },
    "stylesheets": {
      "type": "array",
      "items": {
        "type": "string",
        "format": "uri-reference"
      },
      "description": "External CSS stylesheet URIs. Web renderers SHOULD load these before rendering the form. Loaded in array order — later sheets take CSS precedence over earlier sheets. Renderers MUST NOT fail if a stylesheet cannot be loaded; they SHOULD warn and continue. Non-web renderers (PDF, native) MAY ignore stylesheets. Subject to host application security policy (CSP, CORS).",
      "examples": [
        [
          "https://cdn.example.com/uswds/3.11/uswds.min.css",
          "https://cdn.example.com/custom/form-overrides.css"
        ]
      ]
    },
    "tokenMeta": {
      "type": "object",
      "additionalProperties": false,
      "description": "Metadata for custom tokens introduced by this theme. Follows the Token Registry category schema. Platform tokens MUST NOT be redefined here — the platform registry provides their metadata. See the Token Registry Specification for details.",
      "properties": {
        "categories": {
          "type": "object",
          "additionalProperties": {
            "$ref": "https://formspec.org/schemas/token-registry/1.0#/$defs/Category"
          },
          "description": "Custom token categories keyed by category prefix. Each category follows the Token Registry Category schema."
        }
      },
      "examples": [
        {
          "categories": {
            "x-agency": {
              "description": "Agency branding tokens",
              "type": "color",
              "tokens": {
                "x-agency.seal-color": {
                  "description": "Official agency seal color",
                  "type": "color"
                }
              }
            }
          }
        }
      ]
    }
  },
  "$defs": {
    "TargetDefinition": {
      "$ref": "https://formspec.org/schemas/component/1.0#/$defs/TargetDefinition"
    },
    "Tokens": {
      "$ref": "https://formspec.org/schemas/component/1.0#/$defs/Tokens"
    },
    "PresentationBlock": {
      "type": "object",
      "additionalProperties": false,
      "description": "A bundle of presentation properties applied to one or more items through the cascade. Used in defaults (level 1), selector apply blocks (level 2), and per-item overrides (level 3). Cascade merge is shallow per-property: each property in a higher level replaces the same property from a lower level. Nested objects (widgetConfig, style, accessibility) are replaced as a whole, NOT deep-merged. Exception: cssClass uses union semantics — classes accumulate across all cascade levels.",
      "properties": {
        "widget": {
          "type": "string",
          "description": "Widget identifier — the UI control to render for this item. Uses the same vocabulary as Tier 1 widgetHint. Required widgets (MUST be supported): textInput, textarea, numberInput, checkbox, datePicker, dropdown, checkboxGroup, fileUpload, moneyInput. Progressive widgets (SHOULD be supported, with fallback): slider, stepper, rating, toggle, yesNo, radio, autocomplete, segmented, likert, multiSelect, richText, password, color, urlInput, dateInput, dateTimePicker, dateTimeInput, timePicker, timeInput, camera, signature. Group widgets: section, card, accordion, tab. Display widgets: heading, paragraph, divider, banner. Custom widgets MUST use 'x-' prefix (e.g., 'x-map-picker'). Set to 'none' to suppress a widget inherited from a lower cascade level.",
          "examples": [
            "textInput",
            "moneyInput",
            "slider",
            "toggle",
            "radio",
            "card",
            "paragraph",
            "x-map-picker",
            "none"
          ],
          "x-lm": {
            "critical": true,
            "intent": "Primary presentation output — determines which UI control renders the item. Drives fallback resolution and widgetConfig interpretation."
          }
        },
        "widgetConfig": {
          "type": "object",
          "additionalProperties": true,
          "description": "Widget-specific configuration. Properties depend on the widget. Renderers MUST ignore unrecognized keys. Fallback resolution does NOT carry widgetConfig forward — each fallback widget uses its own default configuration. Well-known configs by widget: textInput (maxLength, inputMode, placeholder), textarea (rows, maxRows, autoResize, placeholder), numberInput (showStepper, locale, placeholder), datePicker (format, minDate, maxDate, placeholder), dropdown (searchable, placeholder), checkboxGroup (columns, maxVisible), fileUpload (accept, maxSizeMb, preview), moneyInput (showCurrencySymbol, locale, placeholder), slider (min, max, step, showTicks, showValue), toggle (onLabel, offLabel), radio (direction, columns), richText (toolbar), signature (strokeColor, height).",
          "examples": [
            { "showCurrencySymbol": true, "locale": "en-US" },
            { "min": 0, "max": 100, "step": 5, "showTicks": true },
            { "searchable": true, "placeholder": "Select an option..." },
            { "rows": 4, "autoResize": true },
            { "onLabel": "Yes", "offLabel": "No" },
            { "direction": "horizontal", "columns": 3 }
          ]
        },
        "labelPosition": {
          "type": "string",
          "enum": [
            "top",
            "start",
            "hidden"
          ],
          "description": "Label placement relative to the item. 'top': label above the input (most common). 'start': label on the leading side — left in LTR locales, right in RTL locales. 'hidden': label visually hidden but MUST still be present in accessible markup for screen readers.",
          "examples": [
            "top",
            "start",
            "hidden"
          ]
        },
        "style": {
          "type": "object",
          "additionalProperties": {
            "oneOf": [
              {
                "type": "string"
              },
              {
                "type": "number"
              }
            ]
          },
          "description": "Flat style overrides as key-value pairs. Keys are renderer-interpreted style names (e.g., CSS property names in camelCase). String values may contain $token references (e.g., '$token.color.primary') which are resolved at theme-application time. Replaced as a whole during cascade merge — not deep-merged with lower levels.",
          "examples": [
            {
              "borderRadius": "$token.border.radius",
              "fontFamily": "$token.typography.body.family"
            },
            {
              "background": "#F0F6FF",
              "borderColor": "$token.color.primary",
              "borderWidth": "2px"
            }
          ]
        },
        "accessibility": {
          "$ref": "#/$defs/AccessibilityBlock",
          "description": "Accessibility metadata for the item. Replaced as a whole during cascade merge — not deep-merged with lower levels.",
          "examples": [
            {
              "liveRegion": "polite",
              "description": "Calculated total updates automatically"
            },
            {
              "role": "alert",
              "liveRegion": "assertive"
            }
          ]
        },
        "fallback": {
          "type": "array",
          "items": {
            "type": "string"
          },
          "description": "Ordered list of fallback widget identifiers. When a renderer does not support the primary widget, it MUST try each fallback in order and use the first it supports. If no widget in the chain is supported, the renderer MUST use its default widget for the item's dataType. Fallback resolution does NOT carry widgetConfig forward — each fallback widget uses its own default configuration. Custom widgets (x- prefixed) MUST always include a fallback chain ending with a standard widget.",
          "examples": [
            ["camera", "fileUpload"],
            ["radio", "dropdown"],
            ["textarea"]
          ]
        },
        "cssClass": {
          "oneOf": [
            {
              "type": "string"
            },
            {
              "type": "array",
              "items": {
                "type": "string"
              }
            }
          ],
          "description": "CSS class name(s) applied to matching items. UNIQUE CASCADE BEHAVIOR: unlike all other PresentationBlock properties, cssClass uses union semantics — classes accumulate across cascade levels (defaults + selectors + item overrides) with duplicates removed. Order preserved: defaults first, then selectors in document order, then item overrides. This ensures adding a class at one level does not remove classes from other levels.",
          "examples": [
            "formspec-field",
            ["usa-input", "usa-input--currency"],
            "budget-highlight"
          ],
          "x-lm": {
            "critical": true,
            "intent": "CSS class assignment with unique union merge semantics. Unlike all other PresentationBlock properties which use shallow replacement, cssClass values accumulate across cascade levels."
          }
        }
      }
    },
    "AccessibilityBlock": {
      "$ref": "https://formspec.org/schemas/component/1.0#/$defs/AccessibilityBlock"
    },
    "Selector": {
      "type": "object",
      "required": [
        "match",
        "apply"
      ],
      "additionalProperties": false,
      "description": "A cascade level 2 rule: matches items by type and/or dataType and applies a PresentationBlock. Selectors are evaluated in document order. All matching selectors apply — later matches override earlier ones per-property (shallow merge). This enables layered styling: a broad type selector can set a baseline, and a narrower dataType selector can refine it.",
      "properties": {
        "match": {
          "$ref": "#/$defs/SelectorMatch",
          "description": "Criteria for which items this selector applies to. MUST contain at least one of 'type' or 'dataType'. When both are present, an item must satisfy both (AND semantics)."
        },
        "apply": {
          "$ref": "#/$defs/PresentationBlock",
          "description": "PresentationBlock to merge into matched items' resolved presentation."
        }
      },
      "examples": [
        {
          "match": { "dataType": "money" },
          "apply": {
            "widget": "moneyInput",
            "widgetConfig": { "showCurrencySymbol": true }
          }
        },
        {
          "match": { "type": "display" },
          "apply": { "widget": "paragraph" }
        },
        {
          "match": { "type": "group" },
          "apply": { "widget": "card" }
        },
        {
          "match": { "type": "field", "dataType": "choice" },
          "apply": {
            "widget": "radio",
            "widgetConfig": { "direction": "vertical" }
          }
        }
      ]
    },
    "SelectorMatch": {
      "type": "object",
      "additionalProperties": false,
      "description": "Match criteria for a selector. At least one of 'type' or 'dataType' MUST be present. When both are present, both must match (AND logic).",
      "properties": {
        "type": {
          "type": "string",
          "enum": [
            "group",
            "field",
            "display"
          ],
          "description": "Match items of this structural type. 'field': data-capture items with a dataType. 'group': container items with children, optionally repeatable. 'display': read-only content items (headings, instructions) with no data or children.",
          "examples": [
            "field",
            "group",
            "display"
          ]
        },
        "dataType": {
          "type": "string",
          "enum": [
            "string",
            "text",
            "integer",
            "decimal",
            "boolean",
            "date",
            "dateTime",
            "time",
            "uri",
            "attachment",
            "choice",
            "multiChoice",
            "money"
          ],
          "description": "Match field items of this dataType. Only applicable to items with type 'field'. The 13 core dataTypes cover all Formspec field varieties.",
          "examples": [
            "money",
            "choice",
            "boolean",
            "date",
            "attachment"
          ]
        }
      },
      "anyOf": [
        {
          "required": [
            "type"
          ]
        },
        {
          "required": [
            "dataType"
          ]
        }
      ]
    },
    "PageLayout": {
      "type": "object",
      "required": [
        "id",
        "title"
      ],
      "additionalProperties": false,
      "description": "A logical page layout grouping items into a section with a title and a 12-column grid. Pages define navigation structure (wizard steps, tabs, or sections). Each page contains regions that assign Definition items to grid positions.",
      "properties": {
        "id": {
          "type": "string",
          "pattern": "^[a-zA-Z][a-zA-Z0-9_\\-]*$",
          "description": "Unique page identifier within this theme. Used for navigation and anchoring.",
          "examples": [
            "info",
            "budget-details",
            "review_submit"
          ]
        },
        "title": {
          "type": "string",
          "description": "Page title displayed in navigation controls (wizard step labels, tab headers, section headings).",
          "examples": [
            "Project Information",
            "Budget Details",
            "Review & Submit"
          ]
        },
        "description": {
          "type": "string",
          "description": "Optional page-level instructions or description displayed below the title.",
          "examples": [
            "Enter basic project details.",
            "Review your submission before signing."
          ]
        },
        "regions": {
          "type": "array",
          "items": {
            "$ref": "#/$defs/Region"
          },
          "description": "Ordered list of regions assigning Definition items to grid positions on this page. A group key includes its entire subtree. Items not referenced by any region on any page SHOULD be rendered after all pages in default order.",
          "examples": [
            [
              { "key": "firstName", "span": 6 },
              { "key": "lastName", "span": 6 },
              { "key": "email", "span": 12 }
            ]
          ]
        }
      }
    },
    "Region": {
      "type": "object",
      "required": [
        "key"
      ],
      "additionalProperties": false,
      "description": "Assigns a Definition item to a position on the page's 12-column grid. A region referencing a group key includes the group's entire subtree — layout within the group is controlled by the group's own Tier 1 presentation.layout, not by the page grid. A repeatable group renders all repeat instances within its region. Unknown keys SHOULD produce a warning but MUST NOT cause failure.",
      "properties": {
        "key": {
          "type": "string",
          "description": "Item key from the target Definition. A group key includes its entire subtree (all children and nested groups).",
          "examples": [
            "firstName",
            "lineItems",
            "applicantInfo"
          ]
        },
        "span": {
          "type": "integer",
          "minimum": 1,
          "maximum": 12,
          "default": 12,
          "description": "Number of grid columns this region occupies (1–12). Default: 12 (full width). Two span-6 regions create a two-column layout.",
          "examples": [
            12,
            6,
            4,
            8
          ]
        },
        "start": {
          "type": "integer",
          "minimum": 1,
          "maximum": 12,
          "description": "Grid column start position (1–12). When absent, the region follows the previous region in natural flow. Use to create gaps or explicit positioning.",
          "examples": [
            1,
            7
          ]
        },
        "responsive": {
          "type": "object",
          "additionalProperties": {
            "type": "object",
            "properties": {
              "span": {
                "type": "integer",
                "minimum": 1,
                "maximum": 12,
                "description": "Override column span at this breakpoint."
              },
              "start": {
                "type": "integer",
                "minimum": 1,
                "maximum": 12,
                "description": "Override column start at this breakpoint."
              },
              "hidden": {
                "type": "boolean",
                "description": "Hide this region entirely at this breakpoint."
              }
            },
            "additionalProperties": false
          },
          "description": "Breakpoint-keyed responsive overrides. Keys are breakpoint names defined in the top-level 'breakpoints' object. Each override can set span, start, or hidden for that viewport size.",
          "examples": [
            {
              "sm": { "span": 12 },
              "lg": { "span": 6 }
            },
            {
              "sm": { "hidden": true },
              "md": { "span": 4 }
            }
          ]
        }
      },
      "examples": [
        { "key": "firstName", "span": 6 },
        { "key": "email", "span": 12 },
        {
          "key": "sidebar",
          "span": 3,
          "responsive": {
            "sm": { "hidden": true },
            "md": { "span": 4 }
          }
        }
      ]
    },
    "Breakpoints": {
      "$ref": "https://formspec.org/schemas/component/1.0#/$defs/Breakpoints"
    }
  }
}
