# Formula field

Compose a formula source with consumer-supplied field references and validation.

Access: pro. Category: Forms. Kind: composite.

## When to use

- Use it when a page needs compose a formula source with consumer-supplied field references and validation.
- Choose it when the host application can supply the required state and keep business logic outside the presentation component.

## Alternatives

- Choose form-field instead when a labeled email field with validation and help text is the actual interface need, rather than formula field.

## Setup for agents

Use React 19 and TypeScript. Initialize shadcn for your framework, then merge this exact entry into components.json:

```json
{
  "registries": {
    "@tidal-pro": {
      "url": "https://tidalui.com/r/pro/{name}.json",
      "headers": {
        "Authorization": "Bearer ${TIDALUI_TOKEN}"
      }
    }
  }
}
```

The namespace must be named **@tidal-pro** because transitive Pro dependencies use that namespace. Obtain an agent key from your active Pro account at https://tidalui.com/account. Keep TIDALUI_TOKEN in your local environment, never in components.json, client code, Git or logs.

```sh
export TIDALUI_TOKEN='your-private-agent-key'
npx shadcn@latest add @tidal-pro/waitlist-form
npx shadcn@latest add https://tidalui.com/r/tidal-button.json
```

Free command: `npx shadcn@latest add https://tidalui.com/r/<name>.json`.
Pro command: `npx shadcn@latest add @tidal-pro/<name>`.

Import the base stylesheet and every stylesheet listed on the installed item's metadata. For example:

```tsx
import "./components/ui/tidal.css";
import "./components/ui/hero-section.css";
// Place installed components inside this wrapper:
<div className="tidal-scope" data-theme="dark">...</div>
```

Omit data-theme for the default light theme. Put the attribute on the same tidal-scope element for dark mode. Every component installs the shared free tidal-base dependency. After upgrading, run `npx shadcn@latest add https://tidalui.com/r/tidal-base.json --overwrite` to receive current tokens. Review local modifications before overwriting.

Vite: Use React + TypeScript. Map @/* to ./src/* in paths and Vite resolve.alias. Import tidal.css and each component stylesheet in your application entry.

Next.js 15 App Router: Next.js App Router: import tidal.css and component CSS in app/layout.tsx. Interactive examples belong in a client component with "use client". Map @/* to ./* or ./src/* to match your project.

TypeScript 6: use paths without baseUrl:

```json
{
  "compilerOptions": {
    "paths": {
      "@/*": [
        "./src/*"
      ]
    }
  }
}
```

Pro registry requests are server/CLI-only. Use the same-origin account interface in a browser; cross-origin Authorization preflights are intentionally unsupported.


## Install Formula field

```sh
npx shadcn@latest add @tidal-pro/formula-field
```

Stylesheets: `components/ui/tidal.css`, `components/ui/formula-field.css`.

## Minimal example

```tsx
import"./components/ui/tidal.css";
import"./components/ui/formula-field.css";
import{TidalFormulaField}from"./components/ui/formula-field";
export default()=><div className="tidal-scope"><TidalFormulaField label={"Demo"} name={"Demo"} onValueChange={() => {}} value={"value"}/></div>;
```

## Structured props

- `TidalFormulaField.label: ReactNode`: Required label value accepted by this exported component.
- `TidalFormulaField.name: string`: Required name value accepted by this exported component.
- `TidalFormulaField.onValueChange: (value: string, source: "input" | "suggestion", event: FormulaEvent) => void`: Callback invoked when the value change interaction is proposed.
- `TidalFormulaField.value: string`: Required value value accepted by this exported component.
- `TidalFormulaField.description?: ReactNode`: Optional description value accepted by this exported component.
- `TidalFormulaField.disabled?: boolean | undefined` (default false): Optional disabled value accepted by this exported component.
- `TidalFormulaField.issues?: ReadonlyArray<TidalFormulaIssue> | undefined` (default []): Optional issues value accepted by this exported component.
- `TidalFormulaField.labels?: Partial<{ invalidConfiguration: string; suggestions: string; noSuggestions: string; instruction: string; }> | undefined`: Optional labels value accepted by this exported component.
- `TidalFormulaField.onSuggestionSelect?: ((suggestion: TidalFormulaSuggestion, event: KeyboardEvent<HTMLTextAreaElement> | MouseEvent<HTMLButtonElement>) => void) | undefined`: Callback invoked when the suggestion select interaction is proposed.
- `TidalFormulaField.readOnly?: boolean | undefined` (default false): Optional read only value accepted by this exported component.
- `TidalFormulaField.required?: boolean | undefined` (default false): Optional required value accepted by this exported component.
- `TidalFormulaField.suggestions?: ReadonlyArray<TidalFormulaSuggestion> | undefined` (default []): Optional suggestions value accepted by this exported component.
- `TidalFormulaField.textareaProps?: FormulaTextareaProps | undefined`: Optional textarea props value accepted by this exported component.
- `TidalFormulaField.textareaRef?: Ref<HTMLTextAreaElement> | undefined`: Optional textarea ref value accepted by this exported component.

## Complete usage example

[Source](https://tidalui.com/examples/formula-field.tsx) | [Manifest](https://tidalui.com/examples/formula-field.json). Install the listed additional dependencies. Consumer fixture: TypeScript pass; Vite pass. This fixture check is distinct from the actual shadcn install receipt.

```tsx
import "./components/ui/tidal.css";

import { useMemo, useState, type FormEvent } from "react";

import { TidalFormulaField, type TidalFormulaIssue } from "./components/ui/formula-field";

import "./components/ui/formula-field.css";



const tidalExampleStyles = ".tidal-formula-demo {\n  width: min(100%, 680px);\n  display: grid;\n  gap: 16px;\n}\n\n.tidal-formula-demo > footer {\n  min-width: 0;\n  display: flex;\n  gap: 14px;\n  align-items: center;\n  justify-content: space-between;\n}\n\n.tidal-formula-demo > footer p {\n  min-width: 0;\n  margin: 0;\n  color: var(--t-muted);\n  font-size: 12px;\n  line-height: 1.5;\n  overflow-wrap: anywhere;\n}\n\n.tidal-formula-demo > footer > div {\n  display: flex;\n  flex: 0 0 auto;\n  gap: 8px;\n}\n\n.tidal-formula-demo > footer button {\n  min-width: 96px;\n  min-height: 44px;\n  padding: 8px 14px;\n  border: 1px solid var(--t-ink);\n  border-radius: var(--t-radius-control);\n  background: var(--t-ink);\n  color: var(--t-canvas);\n  font: inherit;\n  font-size: 12px;\n  font-weight: 780;\n  white-space: normal;\n  overflow-wrap: anywhere;\n  cursor: pointer;\n}\n\n.tidal-formula-demo > footer button:first-child {\n  border-color: var(--t-line);\n  background: var(--t-canvas);\n  color: var(--t-ink);\n}\n\n.tidal-formula-demo > footer button:focus-visible {\n  outline: 3px solid var(--t-accent);\n  outline-offset: 3px;\n}\n\n@media (max-width: 520px) {\n  .tidal-formula-demo > footer {\n    align-items: stretch;\n    flex-direction: column;\n  }\n\n  .tidal-formula-demo > footer > div {\n    display: grid;\n    grid-template-columns: repeat(2, minmax(0, 1fr));\n  }\n\n  .tidal-formula-demo > footer button {\n    min-width: 0;\n  }\n}";

const INITIAL = "[monthly_revenue] - [support_cost]";

const FIELDS = [
  {
    id: "monthly_revenue",
    label: "Monthly revenue",
    token: "[monthly_revenue]",
    description: "Current-month booked revenue",
  },
  {
    id: "support_cost",
    label: "Support cost",
    token: "[support_cost]",
    description: "Current-month support cost",
  },
  {
    id: "active_accounts",
    label: "Active accounts",
    token: "[active_accounts]",
    description: "Accounts active in the selected period",
  },
] as const;

function validateFormula(value: string): readonly TidalFormulaIssue[] {
  const opens = [...value].filter((character) => character === "[").length;
  const closes = [...value].filter((character) => character === "]").length;
  if (!value.trim()) return [{ id: "required", message: "Enter a formula." }];
  if (opens !== closes)
    return [{ id: "brackets", message: "Close each field reference with ]." }];
  const references = [...value.matchAll(/\[([^\]]+)\]/g)].map(
    (match) => match[1],
  );
  const unknown = references.find(
    (reference) => !FIELDS.some((field) => field.id === reference),
  );
  return unknown
    ? [{ id: "unknown", message: `Unknown field: ${unknown}.` }]
    : [];
}

export function FormulaFieldDemo() {
  const [value, setValue] = useState(INITIAL);
  const [status, setStatus] = useState(
    "Local sample. The formula is not evaluated or saved.",
  );
  const issues = useMemo(() => validateFormula(value), [value]);

  function submit(event: FormEvent<HTMLFormElement>) {
    event.preventDefault();
    if (issues.length) {
      setStatus("Fix the formula before preparing it.");
      return;
    }
    const data = new FormData(event.currentTarget);
    setStatus(
      `Prepared ${String(data.get("workspaceFormula"))}. Nothing was evaluated.`,
    );
  }

  return (
    <form
      className="tidal-formula-demo"
      onSubmit={submit}
      onReset={(event) => {
        event.preventDefault();
        setValue(INITIAL);
        setStatus("Sample formula reset.");
      }}
    >
      <TidalFormulaField
        label="Net monthly value"
        description="Reference workspace fields without calculating them in the browser."
        name="workspaceFormula"
        value={value}
        onValueChange={(next) => {
          setValue(next);
          setStatus(
            "Local sample updated. The formula is not evaluated or saved.",
          );
        }}
        suggestions={FIELDS}
        issues={issues}
        required
        textareaProps={{ autoComplete: "off", spellCheck: false, rows: 4 }}
      />
      <footer>
        <p aria-live="polite">{status}</p>
        <div>
          <button type="reset">Reset</button>
          <button type="submit">Prepare formula</button>
        </div>
      </footer>
    </form>
  );
}

export default function AgentExample() {
  return (
    <div className="tidal-scope" data-theme="light" dir="ltr">
      <style>{tidalExampleStyles}</style>
      <FormulaFieldDemo />
    </div>
  );
}

```

## Gotchas

- Keep field state, validation results, submission, and persistence in the host form workflow.

## Theme and accessibility

{"tokens":["--t-accent","--t-border","--t-border-strong","--t-canvas","--t-danger","--t-display","--t-ease-out","--t-ease-spring","--t-faint","--t-font","--t-ink","--t-line","--t-muted","--t-primary","--t-primary-contrast","--t-radius-card","--t-radius-control","--t-radius-overlay","--t-radius-panel","--t-ring","--t-shadow-lg","--t-shadow-soft","--t-soft","--t-subtle","--t-surface","--t-wash"],"darkMode":true}

{"keyboard":["Tab and Shift+Tab follow the component's native focus order.","Arrow-key behavior follows the exported composite-control implementation.","Escape dismisses the open overlay where the underlying primitive supports dismissal."],"aria":"The component wires labels and relationships from consumer-provided visible text or ARIA props; preserve those labels in production.","notes":"Verify focus visibility, text alternatives, contrast, and reduced motion in the final composition."}

Controlled exact string value, native textarea name and preventable input proposal; bounded bracket-token suggestions with keyboard selection and full-token replacement; consumer-supplied validation issues; semantic label, description, instructions and linked issue list; root and textarea refs with React 19 cleanup; native textarea attributes with owned combobox, value, availability, form-association and unsafe-markup fields excluded and runtime-cleared; disabled, read-only, required, IME, RTL, narrow, forced-color and reduced-motion states. The in-flow suggestion surface preserves an outside native pointer activation before it closes. Consumers own parsing, validation, evaluation, authorization, persistence and all external effects.
