> ## Documentation Index
> Fetch the complete documentation index at: https://docs.autype.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Document Styling

> Master pages, first/odd/even variants, reusable headers and footers, page decoration, validation, operations, and legacy migration

Document Styling extends the existing `defaults.styles` object. It does not
introduce a second preset type: typography, element styles, page styles, and
reusable header/footer regions stay in one style bundle.

Legacy documents remain valid and are not modified when opened or rendered.

## Root contract

```json theme={null}
{
  "defaults": {
    "styles": {
      "schemaVersion": 2,
      "layoutUnit": "mm",
      "tokens": {
        "colors": {
          "primary": "#17365D",
          "border": "#D7DEE8"
        }
      },
      "h1": {
        "fontSize": 26,
        "color": "$colors.primary"
      },
      "pages": [
        {
          "id": "default",
          "variant": "default",
          "format": "A4",
          "orientation": "portrait",
          "margins": {
            "mode": "fixed",
            "top": 20,
            "right": 20,
            "bottom": 20,
            "left": 20
          }
        }
      ],
      "regions": []
    }
  }
}
```

| Property        | Required | Description                                                     |
| --------------- | -------: | --------------------------------------------------------------- |
| `schemaVersion` |      yes | Must be `2` when any page-design field is present               |
| `layoutUnit`    |      yes | Must be `mm`; font sizes remain pt                              |
| `tokens`        |       no | Reusable colors, fonts, font sizes, spacing, borders, and radii |
| `pages`         |      yes | Flat page entries; at least `default/default` is required       |
| `regions`       |      yes | Reusable header and footer regions; may be empty                |

The current root fields are all-or-nothing. A partial object such as `{ "pages": [] }`
is rejected, which prevents ambiguous mixed versions.

## Page entries and master variants

Each page entry is identified by the pair `(id, variant)`. Dynamic object keys
and recursive inheritance are deliberately avoided.

```json theme={null}
{
  "id": "body",
  "variant": "default",
  "format": "A4",
  "orientation": "portrait",
  "margins": {
    "mode": "mirrored",
    "top": 20,
    "bottom": 20,
    "inside": 25,
    "outside": 18,
    "gutter": 3
  },
  "headerRegionId": "body-header",
  "footerRegionId": "body-footer"
}
```

Supported variants:

| Variant         | Purpose                             |
| --------------- | ----------------------------------- |
| `default`       | Required base for an ID             |
| `documentFirst` | First physical page of the document |
| `sectionFirst`  | First page of a section             |
| `odd`           | Odd physical pages                  |
| `even`          | Even physical pages                 |
| `blank`         | Inserted blank pages                |

The deterministic cascade is:

1. global `default/default`;
2. global odd/even or blank;
3. global section-first;
4. global document-first;
5. selected page ID `default`;
6. selected ID odd/even or blank;
7. selected ID section-first;
8. selected ID document-first;
9. local section overrides.

Arrays replace the inherited array. Objects merge recursively. `null`
explicitly clears a nullable value. A missing property inherits.

## Geometry

Page entries support:

* A3, A4, A5, Letter, Legal, and custom width/height;
* portrait and landscape;
* fixed or mirrored margins with an optional gutter;
* bleed;
* one to twelve columns, gap, divider, and balancing;
* top, center, or bottom content alignment;
* solid, image, linear-gradient, or radial-gradient backgrounds.

Custom dimensions are only legal with `format: "custom"`.

For Office exports, page size, orientation, margins, columns, bleed, and
vertical content alignment are section geometry. Therefore an odd/even/first
variant may change the master content (`headerRegionId`, `footerRegionId`,
background, and page objects), but it may not silently change section geometry.
Use mirrored margins for binding-aware odd/even pages. Use a named page style
assigned to a dedicated section for a cover, landscape appendix, or genuinely
different first-page margins. HTML can apply variant geometry directly.

Office export rejects PDF bleed boxes because DOCX/ODT cannot preserve them.
This is reported as an `unsupported` capability instead of producing a
misleading PDF.

## Repeating page objects

`objects` places reusable design elements behind or in front of document
content:

```json theme={null}
{
  "id": "brand-rail",
  "type": "shape",
  "shape": "rectangle",
  "layer": "background",
  "anchor": "page",
  "frame": { "top": 0, "right": 0, "bottom": 0, "width": 7 },
  "fill": { "type": "color", "color": "$colors.primary" },
  "mirrorOnEven": true,
  "locked": true,
  "zIndex": -10
}
```

Available object types are `shape`, `line`, `image`, `text`, and `field`.
A frame requires exactly two horizontal and two vertical constraints:

* `left + width`, `right + width`, or `left + right`;
* `top + height`, `bottom + height`, or `top + bottom`.

This supports rails, borders, corner marks, watermarks, full-page art, and
fixed metadata without storing arbitrary CSS.

Physical safety is explicit:

```json theme={null}
{
  "id": "intentional-crop",
  "type": "shape",
  "shape": "ellipse",
  "layer": "foreground",
  "anchor": "page",
  "frame": { "left": -4, "top": 30, "width": 16, "height": 16 },
  "fill": { "type": "color", "color": "#17365D" },
  "allowClip": true,
  "allowOverlap": true
}
```

By default, an object extending beyond the physical page is an error.
Foreground objects intersecting the content area are also errors. Set
`allowClip` or `allowOverlap` only when cropping or overlay is intentional.
Free text is wrapped inside its frame; insufficient height is rejected unless
intentional clipping is enabled.

## Reusable header and footer regions

A region uses a bounded grid. Cells can span tracks and contain multiple
blocks, so a header can contain several images, multiple text lines, fields,
rules, and a background without a recursive layout tree.

```json theme={null}
{
  "id": "body-header",
  "kind": "header",
  "box": {
    "width": "page",
    "edgeOffset": 6,
    "height": 18,
    "minHeight": 12,
    "maxHeight": 22
  },
  "fill": { "type": "color", "color": "#FFFFFF" },
  "borders": {
    "bottom": {
      "width": 0.5,
      "style": "solid",
      "color": "$colors.border"
    }
  },
  "grid": {
    "columns": ["28mm", "1fr", "25mm"],
    "rows": ["auto", "6mm"],
    "gapX": 3,
    "gapY": 1,
    "cells": [
      {
        "id": "brand",
        "row": 1,
        "column": 1,
        "rowSpan": 2,
        "flow": "column",
        "blocks": [
          {
            "id": "logo",
            "type": "image",
            "src": "/image/asset-id",
            "width": 24,
            "height": 10
          },
          {
            "id": "company",
            "type": "text",
            "text": "Example GmbH",
            "fontSize": 8
          }
        ]
      },
      {
        "id": "page-meta",
        "row": 1,
        "column": 2,
        "columnSpan": 2,
        "flow": "row",
        "align": "end",
        "blocks": [
          {
            "id": "label",
            "type": "text",
            "text": "Page"
          },
          {
            "id": "page",
            "type": "field",
            "field": "pageNumber"
          }
        ]
      }
    ]
  }
}
```

Region blocks:

| Type       | Typical use                                                   |
| ---------- | ------------------------------------------------------------- |
| `text`     | Plain or Markdown text, including multiple lines              |
| `image`    | Logos, seals, and icons; multiple images per cell are allowed |
| `field`    | Page number, page count, dates, and document/section metadata |
| `variable` | A named document variable                                     |
| `rule`     | Horizontal or vertical separator                              |
| `spacer`   | Explicit layout spacing                                       |
| `qrcode`   | QR code with error correction and colors                      |
| `shape`    | Editable badge or geometric decoration                        |

Regions and cells also support fills, padding, and per-edge borders. A
traditional Word-style separator is a bottom border on the region or a
horizontal `rule` block.

For Office output, column tracks may mix `mm`, `%`, `auto`, and `fr`. Their
fixed share must fit the available physical width. Row tracks are `auto` or
fixed `mm`; relative row heights are rejected because Word cannot preserve
them reliably. A fixed region height or `maxHeight` is checked against both
the configured blocks and the resolved runtime text/variables before the file
is written.

## Section assignment

Both page and flow sections can select a page style:

```json theme={null}
{
  "id": "appendix",
  "type": "flow",
  "pageStyleId": "appendix",
  "pageStart": "odd",
  "restartPageNumber": 1,
  "pageNumberFormat": "upperRoman",
  "content": []
}
```

`pageStart` accepts `auto`, `next`, `odd`, and `even`. Number formats are
`decimal`, `lowerRoman`, `upperRoman`, `lowerAlpha`, and `upperAlpha`.

## Validation layers

Autype validates a style in five layers:

1. structural Zod/JSON Schema validation;
2. semantic references, unique IDs, grids, constraints, gradients, and tokens;
3. asset authorization and copy-on-apply traversal;
4. renderer capabilities (`native`, `rasterized`, `approximated`,
   `unsupported`);
5. deterministic layout geometry and header/footer collision checks.

Potential header/footer-to-content collisions are warnings. The following are
hard errors:

* a non-positive content area;
* region content exceeding `height` or `maxHeight`;
* fixed grid tracks that do not fit or cannot resolve to 100%;
* a page object outside the physical page without `allowClip`;
* a foreground object over the content area without `allowOverlap`;
* free page text that cannot fit its frame.

Auto-height regions should define `minHeight` or `maxHeight` to make collision
checking deterministic. New atomic style operations run these layout checks
before committing. The renderer repeats capability and layout validation so a
direct JSON request cannot bypass them.

In compatible export mode, non-native decisions are returned as warnings. In
strict mode, any `unsupported` decision rejects the target export.

## Atomic style operations

Small edits do not require replacing the complete JSON:

```json theme={null}
{
  "schemaVersion": 2,
  "operations": [
    {
      "op": "setToken",
      "path": "colors.primary",
      "value": "#17365D"
    },
    {
      "op": "assignSection",
      "sectionId": "appendix",
      "pageStyleId": "appendix"
    }
  ]
}
```

Operations include `upsertPage`, `removePage`, `upsertRegion`,
`removeRegion`, `duplicatePage`, `duplicateRegion`, `addPageObject`,
`updatePageObject`, `removePageObject`, `duplicatePageObject`,
`movePageObject`, `moveRegionBlock`, `assignSection`, `setToken`, `removeToken`,
`setElementStyle`, and `resetElementStyle`. Passing `null` as
`assignSection.pageStyleId` removes the explicit page-style assignment.

The batch is atomic: structural, semantic, token-reference, capability, or
physical-layout failure leaves the stored style unchanged. Document writes can
provide `expectedSnapshotId`; preset writes can provide `expectedVersion`.
Document writes are additionally committed in a serializable database
transaction, so a concurrent snapshot created between validation and commit
also returns HTTP 409.

Clients that require a faithful target can request a strict renderer gate:

```json theme={null}
{
  "documentId": "document-id",
  "expectedSnapshotId": "snapshot-id",
  "requiredRenderers": ["docx"],
  "payload": {
    "schemaVersion": 2,
    "operations": [
      {
        "op": "duplicatePage",
        "sourceId": "business",
        "sourceVariant": "default",
        "targetId": "business",
        "targetVariant": "odd"
      }
    ]
  }
}
```

If the resulting style contains an unsupported DOCX capability, the complete
write is rejected with `UNSUPPORTED_STYLE_CAPABILITY`. Images referenced by
legacy header/footer fields or current pages, regions, fills, and blocks are copied
as one unit. A failed copy or a later transaction conflict rolls those copies
back before the request fails.

## Legacy migration

The read path normalizes legacy page settings and three-slot headers/footers in
memory. It does not mutate a document.

An explicit upgrade is copy-on-write:

1. preview the generated current bundle;
2. optionally persist it;
3. create a new immutable document snapshot;
4. keep legacy fields for rollback and compatibility.

The mapping preserves page geometry, left/center/right content, rich text
lines, header/footer images, and `excludeFirstPage`. Features that cannot be
downgraded losslessly return explicit warnings.

## Focused schemas for agents

Use the smallest applicable generated schema:

* [`style-bundle.schema.json`](https://autype.com/llm-resources/style-bundle.schema.json)
* [`page-style-entry.schema.json`](https://autype.com/llm-resources/page-style-entry.schema.json)
* [`page-region.schema.json`](https://autype.com/llm-resources/page-region.schema.json)
* [`region-block.schema.json`](https://autype.com/llm-resources/region-block.schema.json)
* [`style-operations.schema.json`](https://autype.com/llm-resources/style-operations.schema.json)

These files are generated from the canonical Zod source. Do not edit generated
JSON Schema files manually.
