> For the complete documentation index, see [llms.txt](https://docs.scaleflex.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.scaleflex.com/developers-headless/studio/template-builder/api-reference.md).

# API reference

Everything `<sfx-template-builder>` exposes, at version 0.7.2. Entries marked **Next release** are merged but need a widget release newer than 0.7.2.

### Attributes and properties

Attributes are kebab-case; the matching property is camelCase. Where both are listed, either works.

| Attribute / property                            | Required     | Description                                                                                                                                                                                                                                                                                                   |
| ----------------------------------------------- | ------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `base-url` / `baseUrl`                          | Yes          | Origin of the Template Builder deployment                                                                                                                                                                                                                                                                     |
| `token`                                         | Yes          | Scaleflex project token                                                                                                                                                                                                                                                                                       |
| `sass-key` / `sassKey`                          | Session auth | Project sass key                                                                                                                                                                                                                                                                                              |
| `session-uuid` / `sessionUuid`                  | Session auth | Hub session uuid                                                                                                                                                                                                                                                                                              |
| `sec-template` / `secTemplate`                  | Guest auth   | Security-template key, *instead of* `sass-key` and `session-uuid`. Stateless only                                                                                                                                                                                                                             |
| `company-uuid`, `project-uuid`                  | No           | Company and project scoping. Session auth only                                                                                                                                                                                                                                                                |
| `template-id` / `templateId`                    | No           | DAM-backed: the file uuid to edit; empty opens the new-template flow. Stateless: an opaque id echoed back on `save`                                                                                                                                                                                           |
| `mode`                                          | No           | `inline` (default - size the element) or `modal` (fullscreen overlay, starts closed; call `open()`)                                                                                                                                                                                                           |
| `stateless`                                     | No           | Pass the template in and take it back out instead of using the DAM. Requires `content` or `new-template`                                                                                                                                                                                                      |
| `content`                                       | Stateless    | **Property only.** The template to edit, as `.fdt` XML. Assigning a new value loads it into a running editor                                                                                                                                                                                                  |
| `new-template` / `newTemplate`                  | No           | Stateless: open on a new, empty template instead of supplying `content`. Ignored when `content` is set                                                                                                                                                                                                        |
| `template-name` / `templateName`                | No           | Stateless: the header title                                                                                                                                                                                                                                                                                   |
| `template-query` / `templateQuery`              | No           | Stateless: the render to open on. Empty uses the XML's `default=` values                                                                                                                                                                                                                                      |
| `custom-metadata` / `customMetadata`            | No           | Metadata model offered as a third **Source type**: `[{ key, title?, group?, type? }]`, as an array (property) or JSON (attribute). Image variables bind only to fields with `type: 'image'`. See [Custom metadata](https://docs.scaleflex.com/developers-headless/studio/template-builder/custom-metadata.md) |
| `custom-metadata-label` / `customMetadataLabel` | No           | Renames that source type in the editor. Wording only; empty uses the default                                                                                                                                                                                                                                  |
| `labels`                                        | No           | Renames the editor's vocabulary: the `layout`, `layer` and `variable` terms and a few labels, as an object (property) or JSON (attribute). Wording only. See [Editor labels](https://docs.scaleflex.com/developers-headless/studio/template-builder/editor-labels.md)                                         |
| `dam-store` / `damStore`                        | No           | Stateless only: store each save in Filerobot too. `save` then carries `stored` or `storeError`                                                                                                                                                                                                                |
| `store-folder` / `storeFolder`                  | No           | `dam-store`: folder for templates whose id names no existing DAM file (default `/`). An existing file's own folder always wins. With a security template it must sit inside the upload scope; unset, it defaults to the scope's folder when there is exactly one                                              |
| `stored-uuid` / `storedUuid`                    | No           | `dam-store`: the `stored.uuid` you persisted, passed back so re-saves after a reload version the existing copy. Per-document - `load()` clears it when omitted                                                                                                                                                |
| `brand-color` / `brandColor`                    | No           | Accent color for the editor chrome, `#rgb` or `#rrggbb`                                                                                                                                                                                                                                                       |
| `theme`                                         | No           | `light`, `dark` or `auto`                                                                                                                                                                                                                                                                                     |
| `ready-timeout` / `readyTimeout`                | No           | Milliseconds to wait for the handshake before `error`. Default `20000`; `0` disables                                                                                                                                                                                                                          |

### Methods

| Method                                                               | Description                                                                                                                                                                                                                                                                                                                                                                                                            |
| -------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `open(templateId?)`                                                  | Open the editor, loading it if it is not loaded. Optionally switch template first                                                                                                                                                                                                                                                                                                                                      |
| `close()`                                                            | Close the editor and unload it. Does **not** emit `close`                                                                                                                                                                                                                                                                                                                                                              |
| `load({ content, templateId?, name?, templateQuery?, storedUuid? })` | Stateless: load a template, opening the editor if needed                                                                                                                                                                                                                                                                                                                                                               |
| `createNew({ templateId?, name? })`                                  | Stateless: open on a new, empty template. No XML needed                                                                                                                                                                                                                                                                                                                                                                |
| `confirmSave(ok, message?)`                                          | Stateless: report whether you persisted the content                                                                                                                                                                                                                                                                                                                                                                    |
| `whenSaved({ timeout? })`                                            | **Next release.** `dam-store`: resolves once every save the editor handed over has reached your `save` listeners, whatever its outcome. Never rejects. With `timeout` (ms), saves still uploading are delivered with `storeError` and it resolves. See [Storing a rendering copy](https://docs.scaleflex.com/developers-headless/studio/template-builder/storing-a-rendering-copy.md#closing-the-editor-during-a-save) |
| `flushPendingSaves(reason?)`                                         | Emit any `dam-store` saves still awaiting upload, with `storeError` in place of the links. Only for wrappers that unsubscribe listeners before removing the element - the React wrapper calls it for you                                                                                                                                                                                                               |

### Read-only properties

| Property          | Value                                                                                                                                                   |
| ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `status`          | `idle`, `loading`, `ready` or `error`                                                                                                                   |
| `isDirty`         | Stateless: whether the editor holds edits not yet handed back                                                                                           |
| `hasPendingSaves` | **Next release.** `dam-store`: whether a save is still uploading its rendering copy, so its `save` has not fired yet. Always `false` in DAM-backed mode |

In React these are reached through a ref.

### Events

All are `CustomEvent`s, with the payload in `detail`.

| Event                | `detail`                                                                                                                                                | Fired when                                                                                                                                    |
| -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- |
| `ready`              | -                                                                                                                                                       | The editor mounted and the credential validated. Clears the handshake timeout                                                                 |
| `open`               | -                                                                                                                                                       | The editor UI opened                                                                                                                          |
| `save`               | DAM-backed: `{ uuid, name }`. Stateless: `{ templateId, content, name, templateQuery }`, plus `stored: { uuid, url }` or `storeError` under `dam-store` | The author saved                                                                                                                              |
| `dirtychange`        | `{ isDirty }`                                                                                                                                           | Stateless: the unsaved-changes flag flipped                                                                                                   |
| `pendingsaveschange` | `{ hasPendingSaves }`                                                                                                                                   | **Next release.** `dam-store`: a save started uploading with none pending (`true`), or the last pending one was delivered as `save` (`false`) |
| `close`              | `{ reason }`                                                                                                                                            | The author left the editor, or it unmounted                                                                                                   |
| `error`              | `{ code, message? }`                                                                                                                                    | See below                                                                                                                                     |

`close` fires when the author leaves the editor as well as when it unmounts. In `modal` mode the element tears its own overlay down. In `inline` mode it is yours to act on - the editor never navigates itself anywhere.

`detail.reason` is `dismiss` when the author left the editor, and `navigation` when the deployment moved to one of its own non-editor screens instead. A widget frames a single editor route, so what you get here is `dismiss`; the reason is forwarded for hosts that frame more of the app, which must not send the frame back to its entry route on a `navigation` close. Deployments older than protocol `4` send no reason and the widget reports `dismiss` - the reading that keeps a host behaving as it did before the reason existed, not a faithful report of what happened, since those deployments send the same bare close when they navigate themselves.

### Error codes

| Code                | Means                                                                                                                         |
| ------------------- | ----------------------------------------------------------------------------------------------------------------------------- |
| `auth`              | The deployment could not authenticate - blocked cookies, an expired session, or a security template the Filerobot API refused |
| `invalid-content`   | Stateless: the `content` you sent is not a parseable `.fdt` document                                                          |
| `invalid-config`    | Attributes that contradict each other, such as `sec-template` without `stateless`. The editor never mounts                    |
| `handshake-timeout` | No ready signal in time. Usually a missing entry in the deployment's embedding allowlist, or blocked third-party cookies      |
| `invalid-base-url`  | `base-url` is not a URL                                                                                                       |
| `unknown`           | Something the deployment reported that this widget version does not name                                                      |

[Troubleshooting](https://docs.scaleflex.com/developers-headless/studio/template-builder/troubleshooting.md) maps these to what you will actually see.

### React API

Props mirror the attributes in camelCase, plus `className` and `style`. Callbacks are `onReady`, `onOpen`, `onSave`, `onDirtyChange`, `onClose`, `onError` and `onPendingSavesChange` (**next release**).

The credential props are a **discriminated union**, so the two authentication modes are enforced at compile time. `sassKey` with `sessionUuid`, or `secTemplate` with `stateless` - mixing them, or passing `secTemplate` without `stateless`, is a type error rather than a runtime one.

`onSave` may return `false` or a promise. Returning or resolving to `false`, or throwing, reports the failure to the editor.

`customMetadata` is an array prop compared by identity. Hoist it to module scope or memoize it, or every render counts as a change - harmless, because the element de-duplicates by value, but wasted work.

The component forwards a ref to the underlying element, which is how you reach the imperative methods. That is required for `mode="modal"`, which renders nothing until `open()` is called:

```tsx
import { useRef } from 'react'
import { TemplateBuilder } from '@scaleflex/template-builder/react'
import type { SfxTemplateBuilder } from '@scaleflex/template-builder'

const builder = useRef<SfxTemplateBuilder>(null)

<TemplateBuilder ref={builder} mode="modal" baseUrl={...} {...auth} />
<button onClick={() => builder.current?.open('tpl-1')}>Edit template</button>
```

`react` and `react-dom` 18 or later are optional peer dependencies.

### Exports

| Entry                                | Contents                                                                                                 |
| ------------------------------------ | -------------------------------------------------------------------------------------------------------- |
| `@scaleflex/template-builder`        | The element class, every protocol constant and type, and `BLANK_TEMPLATE_XML`. Does not register the tag |
| `@scaleflex/template-builder/define` | Registers `<sfx-template-builder>`                                                                       |
| `@scaleflex/template-builder/react`  | The `<TemplateBuilder>` wrapper, which also registers the tag                                            |

Each entry ships ESM and CommonJS builds, each with its own type declarations. All three are client-only - see [Getting started](https://docs.scaleflex.com/developers-headless/studio/template-builder/getting-started.md).
