[data-reveal]{opacity:1!important;transform:none!important}
AntelopeJS DMS
DocumentationData types

Data types

A data type is the single object that answers everything the DMS needs to know about one value: which input component edits it, which Zod schema validates it, which comparison modes its filter offers, and whether the…

Overview

A data type is the single object that answers everything the DMS needs to know about one value: which input component edits it, which Zod schema validates it, which comparison modes its filter offers, and whether the field it sits on needs extra decorators. FormField.type and ColumnOptions.type both take one, which is why a form field and a table column of the same type behave identically.

typescript
import {
  CreateDataType,
  DataType,
  DefaultDataCompareTypes,
  DefaultDataTypes,
  RegisterDataType,
  serializeType,
} from "@antelopejs/interface-dms/base/data-types";

The data-types subpath re-exports the built-in catalogues, so DefaultDataTypes, DefaultDataCompareTypes and StatusType are all reachable from it. They also have their own modules, data-types/default-types, data-types/compare-types and data-types/status-type, and much of the DMS imports them from there.

The base barrel does not re-export the data types. Import them from the data-types subpath.

Use a data type

Instantiate the type with its options and hand the instance to the field or the column.

typescript
import { Form } from "@antelopejs/interface-dms/base";
import { DefaultDataTypes } from "@antelopejs/interface-dms/base/data-types";

const form = Form({
  fields: [
    {
      id: "name",
      label: "Name",
      type: new DefaultDataTypes.StringType({ maxLength: 120 }),
      required: true,
    },
    {
      id: "status",
      label: "Status",
      type: new DefaultDataTypes.SelectType({
        items: [
          { label: "Draft", value: "draft" },
          { label: "Published", value: "published" },
        ],
      }),
    },
  ],
  submitUrl: "/api/articles/new",
});

An instance is reusable: the same object can back a form field and a table column, since it holds only its configuration.

The DataType contract

typescript
abstract class DataType {
  constructor(
    readonly compareModes: Class<DataCompareMode>[] = [],
    readonly defaultCompareMode?: Class<DataCompareMode>,
    readonly options?: Record<string, unknown>,
  );

  protected abstract defaultInputComponent(): ComponentInfoSerialized;
  abstract getValidation(): z.ZodType;

  filter(context, proxy, key, value, mode, row): ValueProxyOrValue<boolean>;
  filterComponents(): Record<string, ComponentInfoSerialized> & { default: ComponentInfoSerialized };
  inputComponent(): ComponentInfoSerialized;
  describedInputComponent(): ComponentInfoSerialized;
  decorateField?(target: unknown, key: PropertyKey, descriptor?: PropertyDescriptor): void;
}
MemberRole
compareModesCompare-mode classes this type offers in the filter dropdown.
defaultCompareModeThe mode selected when the viewer adds a filter on this field.
optionsThe type's own configuration, kept on the instance and readable by other code.
defaultInputComponent()Abstract. Returns the input component the type renders. Implemented by every concrete type.
getValidation()Abstract. Returns the Zod schema for one value of this type, before the field-level adaptation described in Forms.
inputComponent()The form input. Defaults to defaultInputComponent().
describedInputComponent()The input as it is described where nothing is entered through it: a table column's type (its cells, cards and quick filters read the options) and a read-only form field. Defaults to inputComponent(); a type leaves out what only an editable control uses, as a relation leaves out its add form.
filterComponents()The filter inputs, keyed by compare-mode id with a mandatory default. Defaults to { default: defaultInputComponent() }.
filter()Applies a filter for one compare mode. The base implementation looks the mode up in the compare-mode registry and delegates to it; a type overrides it when a mode needs different semantics.
decorateField()Optional. Called by the @Column decorator so the type can add further decorators to the field. The relation types install their join this way.

Write a custom type

StatusType is the smallest complete example: a boolean rendered as an online/offline indicator whose labels and colours are configurable.

typescript
import { z } from "zod";
import { FormComponents } from "@antelopejs/interface-dms/base/form";
import {
  DataType,
  DefaultDataCompareTypes,
  RegisterDataType,
} from "@antelopejs/interface-dms/base/data-types";

@RegisterDataType("status")
export class StatusType extends DataType {
  constructor(
    public readonly options: {
      onlineLabel?: string;
      offlineLabel?: string;
      onlineColor?: string;
      offlineColor?: string;
    } = {
      onlineLabel: "$common.status.online",
      offlineLabel: "$common.status.offline",
      onlineColor: "primary",
      offlineColor: "neutral",
    },
  ) {
    super(
      [DefaultDataCompareTypes.Is, DefaultDataCompareTypes.IsNot],
      DefaultDataCompareTypes.Is,
      options,
    );
  }

  protected defaultInputComponent() {
    const component = FormComponents.InputCheckbox();
    component.options = { label: this.options.onlineLabel };
    return component;
  }

  getValidation() {
    return z.boolean();
  }
}

Three pieces make it a type: the @RegisterDataType("status") decorator puts it in the registry under an id, the super() call declares the compare modes and stores the options, and the two abstract members supply the input and the schema. StatusType itself is exported by the data-types subpath and is one of the three column types a kanban board can group by. See Tables.

The registry

RegisterDataType

typescript
const RegisterDataType: (id: string) => ClassDecorator<Class<DataType>>;

Registers the decorated class under id, in both directions: CreateDataType looks up the class by id, and getDataTypeId recovers the id from an instance. An id must be unique. Registering twice under the same string replaces the earlier class.

RegisterDataCompareMode

typescript
const RegisterDataCompareMode: (
  id: string,
  noInput?: boolean,
) => ClassDecorator<Class<DataCompareMode>>;

Registers a compare mode. The decorator instantiates the class immediately and keeps that single instance, so a compare mode is stateless. noInput marks a mode that needs no value from the viewer. serializeType replaces its filter component with the literal "noInput".

DataCompareMode is the interface a mode implements:

typescript
interface DataCompareMode {
  filter(
    context: RequestContext,
    proxy: ValueProxy<unknown>,
    key: string,
    value: unknown,
    row: ValueProxy<Record<string, unknown>>,
  ): ValueProxyOrValue<boolean>;
}

proxy is the database value proxy for the field being filtered and row the proxy for the whole row, both from @antelopejs/interface-database, so a mode builds a database-side predicate rather than filtering in memory.

CreateDataType

typescript
function CreateDataType(id: string, options?: unknown): DataType;

Instantiates a registered type by id, forwarding options to its constructor. It asserts on an unknown id with the message Unknown type <id>. Use it when the type is chosen at runtime, from configuration or from a description another module produced, rather than written in the source.

getDataTypeId

typescript
function getDataTypeId(instance: DataType): string | undefined;

Returns the id an instance's class was registered under, or undefined when the class is not registered. It resolves the class from the instance's own prototype, so a subclass of a registered type returns its own id, not its parent's.

Serialization

typescript
function serializeType(instance?: DataType): DataTypeSerialized | undefined;

serializeType is what turns a type instance into the description shipped to the frontend. It returns undefined when there is no instance, and also when the instance's class is not registered.

DataTypeSerialized:

FieldTypeDescription
idstringThe registered id.
compareModesstring[]Ids of the type's compare modes; unregistered ones are dropped.
defaultCompareModestringId of the default mode.
filterComponentsRecord<string, FilterComponent>Filter inputs by mode id, from filterComponents(), with every noInput mode's entry replaced by the literal "noInput".
inputComponentComponentInfoSerializedThe input the column's cells and quick filters read the options of, from describedInputComponent().

FilterComponent is ComponentInfoSerialized | "noInput". The value-level counterpart, ComponentOrNoInput, is described in Shared types.

Compare modes

DefaultDataCompareTypes holds the built-in modes. Each entry is a class; you reference the class in a type's compareModes, and the string id is what appears in a serialized type and in a filter query.

ClassIdInput
Isisvalue
IsNotis_notvalue
GreaterThangreater_thanvalue
GreaterThanOrEqualTogreater_than_or_equal_tovalue
LessThanless_thanvalue
LessThanOrEqualToless_than_or_equal_tovalue
IsBetweenis_betweentwo values
IsEmptyis_emptynone
IsNotEmptyis_not_emptynone
Includeincludevalue
Excludeexcludevalue
Containscontainsvalue
NotContainsnot_containsvalue
ArrayContainsStringarray_contains_stringvalue

The ordering modes and is_between send a date value to the value proxy as epoch milliseconds. A type that stores Date values overrides filter, as DateType does.

IsEmpty and IsNotEmpty are the two registered with noInput. Include, Exclude and ArrayContainsString read a null or missing list as an empty one, so a row saved without a value never fails the query: it is left out by include and array_contains_string, and kept by exclude. The namespace also exports escapeRegex(str: string): string, the helper the substring modes use to make a viewer-supplied value safe inside a pattern.

The default types

DefaultDataTypes is the built-in catalogue. Every class takes its options object as its only constructor argument, and most of them accept a fallback string used in place of an empty value.

ClassIdCompare modes (default first)Input
StringTypestringcontains, is, is_not, not_contains, is_empty, is_not_emptytext or textarea
NumberTypenumberis, is_not, greater_than, greater_than_or_equal_to, less_than, less_than_or_equal_to, is_empty, is_not_emptynumber
PriceTypepriceas NumberTypenumber
PercentageTypepercentageas NumberTypepercentage
DateTypedateis, less_than, greater_than, is_between, is_empty, is_not_emptydate picker
BooleanTypebooleanis, is_not, is_empty, is_not_emptyswitch
SelectTypeselectinclude/exclude when multiple, otherwise is/is_not; plus is_empty, is_not_emptyselect
EmailTypeemailcontains, is, is_not, not_contains, is_empty, is_not_emptyemail
UrlTypeurlis, is_not, is_empty, is_not_emptytext
PhoneTypephonecontains, is, is_not, not_contains, is_empty, is_not_emptyphone
IbanTypeibancontains, is, is_not, not_contains, is_empty, is_not_emptyidentifier
BicTypebicas IbanTypeidentifier
VatNumberTypevat_numberas IbanTypeidentifier
CompanyNumberTypecompany_numberas IbanTypeidentifier
ColorTypecoloris, is_not, is_empty, is_not_emptycolour
PasswordTypepasswordnonepassword
RichTextTyperich_textnonerich text
StringTimeTypestring_timeas NumberTypetime
RelationTyperelationis, is_not, is_empty, is_not_emptyrelation picker
CascaderRelationTypecascader_relationis, is_not, is_empty, is_not_emptycascader
AddressTypeaddressis_empty, is_not_emptyaddress
FileTypefilenonefile upload
ImageTypeimagenoneimage upload

Scalar types

Options interfaceFields
StringTypeOptionsplaceholder?, maxLength?, minLength?, showCount?, textarea?, rows?, width?, fallback?
NumberTypeOptionsmin?, max?, step?, placeholder?, suffix?, width?, fallback?
DateTypeOptionsrange?, multiple?, minDate?, maxDate?, fallback?
BooleanTypeOptionsfallback?
SelectTypeOptionsitems: FormComponents.SelectOption[], placeholder?, multiple?, deselectable?, display?, columns? (cards per row of the cards display, 2 by default), fallback?
EmailTypeOptions, ColorTypeOptions, RichTextTypeOptionsplaceholder?, fallback?
UrlTypeOptionsplaceholder?, preview? ("avatar" | "image": shown read-only, the URL is drawn as the image it points to; the form still edits it as text), fallback?
PasswordTypeOptionsplaceholder?, minLength?, confirmPassword?, confirmPlaceholder?, fallback?
PhoneTypeOptionsplaceholder?, requiredPrefix?, defaultCountry?, fallback?
StringTimeTypeOptionsplaceholder?, min?, max?, fallback?

The options and the rules of IbanType, BicType, VatNumberType and CompanyNumberType are in Identifier data types.

Notes on the ones whose behaviour is not obvious from the options:

  • StringType renders a textarea instead of a single-line input when textarea is set, and passes rows to it.
  • StringType with showCount shows the characters typed, out of maxLength when set ("4 / 60"), in its input or under its textarea.
  • NumberType hands suffix (an i18n key with $, or a literal) to its input, which writes it after the field; the value stays a number. PriceType inherits it; PercentageType keeps its own %.
  • PriceType writes amounts in euros. new PriceType({ currency: "USD" }) (an ISO 4217 code) writes them in that currency in cells, cards, footer sums and read-only fields; a code that is not three letters falls back to euros.
  • NumberType (and the types extending it) and a single-line StringType hand width (FormComponents.InputWidth) to their input: "compact" sizes it for a short value from sm up, "full" fills the row, and left out the input is compact when min / max fit in 6 digits or maxLength is 16 or less.
  • DateType overrides filter so is, is_not and is_between compare whole UTC days rather than instants, and adds a range picker as the filter component for is_between. Its schema accepts a Date or an ISO-shaped string and transforms it to a Date; with multiple the value becomes an array, and with range it becomes { start, end }, end on or after start (a pair [start, end] is still read and validates to the same object).
  • BooleanType uses a two-option select as its filter component, so a viewer picks "checked"/"unchecked" rather than typing a value.
  • SelectType validates against the values of its items, as an enum or an array of that enum when multiple is set.
  • PriceType is a NumberType whose options default to min: 0 and step: 0.01.
  • PercentageType is a NumberType whose options default to min: 0, max: 1 and step: 0.01; the stored value is a fraction while the input works in whole percent.
  • PhoneType keeps any string when neither defaultCountry nor requiredPrefix is set. With defaultCountry (an ISO 3166-1 alpha-2 code such as "BE"), a value is valid only when it is a possible number of its country. A number without a + or 00 prefix is read in defaultCountry. The schema transforms the value to E.164 ("0494 66 94 43" becomes "+32494669443"), so it is stored in that form. requiredPrefix applies the same rule but refuses a national number. A refused value carries the issue message $dms.field_errors.invalid_phone. The DMS module reads the number, so parse a schema holding such a field with safeParseAsync.
  • ColorType validates a six-digit #RRGGBB string.
  • StringTimeType validates a number: a time of day expressed as a number, bounded by min and max.

Relations

RelationType<T> points a field at another data controller. Its input is a searchable picker whose searchUrl is the target controller's select endpoint. Unless filterOnly is set, its decorateField installs a data-api Foreign join so list rows carry the resolved related row instead of the raw foreign key.

typescript
import { DefaultDataTypes } from "@antelopejs/interface-dms/base/data-types";
import { Column } from "@antelopejs/interface-dms/base/table-view";

@Column({
  name: "Customer",
  type: new DefaultDataTypes.RelationType({
    dataApiController: customerDataAPI,
    keyMapping: { label: "name", value: "_id" },
  }),
  filterable: true,
})
declare customerId: string;
OptionTypeDescription
dataApiControllerT extends ControllerClassThe target data controller. Required.
keyMapping{ label?, value?, avatar?, disabled? }Which of the target's fields fill each role in the picker. Keys are checked against the target's own field names.
indexstringIndex the join reads, when it is not the primary key.
placeholderstringPicker placeholder.
multiplebooleanAllow more than one related row.
deselectablebooleanAllow clearing the selection.
filterOnlybooleanSkip the join entirely: the raw scalar id stays in the list output and the funnel filter runs equality on it. A table cell, a card or a kanban card of that column then shows the id: lists draw the joined row only, they never read the ids by ?ids=.
addForm{ displayName?: string; description?: string }Title and description of the drawer the picker's "add" entry opens ("New customer"). $-prefixed: i18n keys. Default to "New entry".
filterBy{ field, from }List only the target rows whose field equals the form's current value of the field from, e.g. { field: "customerId", from: "customerId" } for a site among its customer's sites. field must be filterable on the target (filterable: true or @Filter); decorateField throws otherwise.
filterTableViewTabFilter ({ accessorKey, mode, value? })List only the target rows meeting a fixed condition, written like a tab's filter, e.g. { accessorKey: "isArchived", mode: "ne", value: "true" } for the active rows of an @ArchiveField table. mode is one the target field's filter takes: eq or ne for an archive field, a compare mode (is, is_not, is_empty, …) for a filterable column. accessorKey must be filterable on the target, as for filterBy.
fallbackstringText used in place of an empty value.

With filterBy, the picker sends the table filter syntax to the select endpoint (filter_<field>=is:<value>), which honors only the filters the target controller declares. It searches again when from changes and clears a pick made for its previous value; the pair a record loaded with is kept, and while from is empty every row is offered. It narrows what is offered only: a rule that must hold on save belongs to the module's routes.

With filter, the picker of a form sends filter_<accessorKey>=<mode>:<value> on every search, as a tab does, next to filterBy's condition (both apply when they name the same field). The label read of the ids a record holds (?ids=) does not carry it, so a held row outside the condition keeps its label as long as the reader may see that row (an archived row stays hidden from a user without the viewArchived permission). A table filter's picker leaves it out and reaches every row.

When the target controller exposes a new endpoint and has form fields, the picker of an editable form field also carries an inline "add" form built from the target's new fields, plus the permission id of the target's add action. That form (the target's fields, its validation schema, its own relations' add forms) is the bulk of the component, so a table column's type, its filter and a read-only field leave it out: they read the related rows through the select route, and a filter only picks among them.

CascaderRelationType<T> is the same idea for a self-referencing table: the target's select endpoint returns a flat list, and the widget rebuilds the tree client-side. Its cell and its field name the picked row by its path, read by ?ids= for the picked rows and then each level of their ancestors. Its keyMapping is required and adds parent, the field pointing at the parent row, which must itself carry @Select(), alongside the required label and value. It adds maxDepth and leafOnly to the relation options, and supports the same filterOnly behaviour. In a table cell it shows the path of the picked node ("Electronics / Audio"); a multiple one shows a badge per picked node, named by its own label with its path on hover, and folds those past three into +N.

Address

AddressType<T> stores a structured postal address. Its Address shape follows ISO 19160-1 and maps directly onto the UBL cac:PostalAddress used by EN 16931 / Peppol BIS Billing 3.0.

FieldRequiredDescription
streetNameyesStreet or thoroughfare name.
postalCodeyesPostal or ZIP code.
cityyesCity or locality.
countryCodeyesISO 3166-1 alpha-2 country code.
houseNumbernoHouse or building number.
boxNumbernoBox, unit or apartment number.
addressLine2noSupplementary delivery information.
countrySubdivisionnoRegion, state or province.

The type's options are placeholder (one string per address component), autocomplete, defaultCountry (the ISO 3166-1 alpha-2 country shown while the address has none and whose places the street suggestions list first, written with the first part typed: an address left empty stays empty), an optional dataApiController with a keyMapping of label / value for picking an existing address, and fallback. AddressAutocomplete configures the geocoder:

OptionTypeDescription
enabledbooleanEnable suggestions on the street field. Defaults to false.
urlstringGeocoder endpoint. Defaults to "https://photon.komoot.io/api".
langstringPreferred result language, ISO 639-1. Falls back to the UI locale.
limitnumberMaximum number of suggestions. Defaults to 5.
placeholderstringSearch field placeholder.

Files and images

FileTypeOptions has multiple?, constraints?: UploadConstraints, path?, storage? and fallback?. ImageTypeOptions has multiple?, max?, constraints?, path?, storage? and resize?, the FormComponents.ImageResizeOptions the input applies client-side before uploading (Forms). Both accept attachmentField? for a stable native field identity and visibility?: "private" | "public", defaulting to private. constraints is the UploadConstraints type from @antelopejs/interface-file-storage; storage names the storage backend and path the prefix uploads land under.

A file value is the resource key as a string. Metadata-based validation checks configured constraints, matching allowedMimetypes patterns including the type/* form. A native field's save integration also validates upload provenance and canonical metadata before persistence. A key with no recorded upload is refused with HTTP 403, both in the submitted document and in the previously stored one, and the native metadata endpoint does not read it. A storage outage propagates as a server error rather than becoming a field validation error. An image value is an ImageValue, { key: string; alt?: string; principal?: boolean }, and ImageType defaults allowedMimetypes to ["image/*"], caps the array at max when multiple is set, and rejects a list with more than one principal image.

Both types enable the table view's native file handling: authorized saves promote staging keys, and successful edits or deletes clean removed native references. Failed saves retain promoted objects; cleanup is not reference-counted across records. See File storage for authorization, visibility, retries, and custom save routes, and Helpers for comparing references within records.

Next steps

  • Identifier data types: IBAN, BIC, VAT number and company number.
  • Helpers: Search, export jobs, file references and the archive-mode defaults.