Inline void fields that one role fills, each with a kind, settings, an optional condition on another field and an id unique in the document.
A field is a typed blank in a document that one role fills, such as a tenant's name, a start date, a checkbox or a signature. Each field is an inline void field element with a kind, a role, a label and a fieldId that no other field in the document holds. A field's condition names another field by that id. Plate checks roles, never users. Your app decides which person fills which role.
The demo is a lease template for a landlord, a tenant and an app role that holds the address and the rent. Insert a field from the toolbar's menu, click a field to change its settings, and read the HTML, Markdown and Word panels under the editor. Pick Fill as landlord or Fill as tenant above the editor to fill the lease as that role. In the Author view, Fill from sample data submits the app's answers from a sample record and opens the tenant's view with the tenant's name from the same record. Submit checks that role's answers after the answers of the roles that submitted before it. The Submission panel then shows each refusal, or the filled document as static output with the roles it still waits on, and the Answers panel lists each role's answers by name.
field element of six kinds: text, number, date, checkbox, choice and signature.fieldId and tests that field's value. A field whose condition fails is skipped, so it needs no answer.name that gives the fields of one role one answer, so a question the document asks twice is answered once.insert and update commands that refuse a setting or condition that does not fit, and reads that report what is wrong with each field and whether it applies.applyFieldValues, which checks each role's answers against the template on a server and builds the filled document.fieldSubmission, startFieldValues and readFieldAnswers, which build a submission from app data by name, start a role from app values and read a saved document's answers by name.The fastest way to add fields is FieldKit, which installs FieldPlugin with the registry FieldElement. Installing field also installs field-toolbar-button.
'use client';
import { cn } from 'cn';
import { CheckIcon, PlusIcon, TriangleAlertIcon, XIcon } from 'lucide-react';
import { EditorSchemaValidationError } from 'platejs';
import { AuthoredPlugin } from 'platejs/authored';
import {
FIELD_TESTS,
fitsField,
type FieldKind,
type FieldOption,
type FieldPatch,
type FieldProblem,
type FieldSettings,
type FieldTest,
type FieldValue,
} from 'platejs/field';
import { FieldPlugin, useFieldRead } from 'platejs/field/react';
import {
type EditorElementProps,
EditorElement,
useEditor,
useEditorReadOnly,
useEditorSelector,
usePluginStore,
} from 'platejs/react';
import * as React from 'react';
import { Button } from '@/components/ui/button';
import { Checkbox } from '@/components/ui/checkbox';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import {
NativeSelect,
NativeSelectOption,
} from '@/components/ui/native-select';
import {
Popover,
PopoverContent,
PopoverTrigger,
} from '@/components/ui/popover';
import { inlineSuggestionVariants } from '@/lib/inline-suggestion';
const KINDS: Record<FieldKind, string> = {
checkbox: 'Checkbox',
choice: 'Choice',
date: 'Date',
number: 'Number',
signature: 'Signature',
text: 'Text',
};
const TEST_LABELS: Record<FieldTest, string> = {
above: 'is above',
below: 'is below',
blank: 'is blank',
equals: 'is',
filled: 'is filled',
'not-equals': 'is not',
};
const PROBLEMS: Record<FieldProblem, string> = {
'answer-conflict': 'The fields of its name hold different answers.',
'condition-loop': 'Its condition leads back to this field.',
'invalid-value': 'A value does not fit this kind of field.',
'missing-target': 'The field its condition names is gone.',
'name-conflict':
'The fields of its name differ in kind, options or condition.',
'unsupported-test': 'Its condition does not fit the field it names.',
};
const isKind = (value: string): value is FieldKind => value in KINDS;
const isTest = (value: string): value is FieldTest => value in TEST_LABELS;
const needsValue = (test: FieldTest) => test !== 'filled' && test !== 'blank';
const firstValue = ({ kind, options }: FieldSettings) =>
({
checkbox: true,
choice: options?.[0]?.value,
date: new Date().toISOString().slice(0, 10),
number: 0,
signature: undefined,
text: '',
})[kind];
const fillableTests = (target: FieldSettings) =>
FIELD_TESTS[target.kind].filter(
(test) => !needsValue(test) || firstValue(target) !== undefined
);
const conditionOn = (
ref: string,
target: FieldSettings,
test: FieldTest,
value?: FieldValue
) => ({
ref,
test,
...(needsValue(test) ? { value: value ?? firstValue(target) } : {}),
});
type FieldNode = EditorElementProps<typeof FieldPlugin>['element'];
const saveAnswer = (
editor: ReturnType<typeof useEditor>,
fieldId: string,
value?: FieldValue
) =>
editor.update((tx) => {
tx.plugin(FieldPlugin).update(fieldId, { value });
return true;
}) === true &&
Object.is(editor.plugin(FieldPlugin).read.field(fieldId)?.node.value, value);
const useWaitsForReview = (element: FieldNode, watches: boolean) => {
const editor = useEditor();
const subscribe = React.useCallback(
(wake: () => void) => (watches ? editor.subscribeCommit(wake) : () => {}),
[editor, watches]
);
const waits = () =>
watches &&
editor
.plugin(AuthoredPlugin)
.read.reviewOf(element)
.marks.some((mark) => mark.kind === 'format' && mark.key === 'value');
return React.useSyncExternalStore(subscribe, waits, waits);
};
export function FieldElement(props: EditorElementProps<typeof FieldPlugin>) {
const { element } = props;
const editor = useEditor();
const readOnly = useEditorReadOnly();
const fillRole = usePluginStore(FieldPlugin, 'fillRole') ?? null;
const field = useFieldRead(element.fieldId);
const problems = field?.problems ?? [];
const skipped = field?.applies === false;
const warning = problems.map((problem) => PROBLEMS[problem]).join(' ');
const filling = fillRole !== null;
const ownField = element.role === fillRole;
const waitsForReview = useWaitsForReview(
element,
ownField && editor.plugin(AuthoredPlugin).installed
);
const fills = ownField && !readOnly && !waitsForReview;
const toggles = fills && element.kind === 'checkbox';
const ticked = element.value === true;
const [refusedToggle, setRefusedToggle] = React.useState<{
role: string | null;
stored?: FieldValue;
} | null>(null);
if (
refusedToggle &&
(refusedToggle.role !== fillRole ||
!Object.is(refusedToggle.stored, element.value))
) {
setRefusedToggle(null);
}
const answer = String(
element.options?.find((option) => option.value === element.value)?.label ??
element.value ??
''
);
const writeName = React.useRef<() => 'refused' | 'written'>(null);
let form: React.ReactNode = null;
if (!filling && !readOnly) {
form = <FieldSettingsForm element={element} writeName={writeName} />;
}
if (fills && !toggles) form = <FieldAnswerForm element={element} />;
const openAtPointerDownRef = React.useRef(false);
const [openAs, setOpenAs] = React.useState<{ role: string | null } | null>(
null
);
const open = form !== null && openAs?.role === fillRole;
if (openAs && !open) setOpenAs(null);
const chip = {
className: cn(
'inline-flex w-fit items-baseline gap-1 rounded-sm bg-muted px-1 text-muted-foreground',
(form || toggles) && 'cursor-pointer',
skipped && 'opacity-50',
inlineSuggestionVariants({ on: 'parent' })
),
contentEditable: false,
draggable: !filling,
onClick: (event: React.MouseEvent) => {
if (toggles) {
setRefusedToggle(
saveAnswer(editor, element.fieldId, !ticked)
? null
: { role: fillRole, stored: element.value }
);
return;
}
const beganOpen =
event.detail === 0 ? open : openAtPointerDownRef.current;
if (!form || beganOpen) return;
event.preventDefault();
setOpenAs({ role: fillRole });
},
onPointerDown: () => {
openAtPointerDownRef.current = open;
},
};
const chipContent = (
<>
{filling && element.kind === 'checkbox' && (
<span
aria-label={ticked ? 'Ticked' : 'Not ticked'}
className="flex size-3 items-center justify-center self-center rounded-[3px] border border-current"
role="img"
>
{ticked && <CheckIcon className="size-2.5" />}
</span>
)}
{filling && element.kind !== 'checkbox'
? answer || element.label
: element.label}
{element.required && <span className="text-destructive">*</span>}
<span className="text-xs opacity-70">{element.role}</span>
{skipped && <span className="text-xs opacity-70">skipped</span>}
{waitsForReview && (
<span className="text-xs opacity-70">waits for review</span>
)}
{warning && (
<span
aria-label={warning}
className="self-center text-destructive"
data-slot="field-warning"
role="img"
title={warning}
>
<TriangleAlertIcon className="size-3" />
</span>
)}
</>
);
return (
<EditorElement
{...props}
className="inline-block"
attributes={{
...props.attributes,
contentEditable: false,
}}
>
{form ? (
<Popover
open={open}
onOpenChange={(nextOpen) => {
if (!nextOpen && writeName.current?.() === 'refused') return;
setOpenAs(nextOpen ? { role: fillRole } : null);
}}
>
<PopoverTrigger asChild>
<button {...chip} type="button">
{chipContent}
</button>
</PopoverTrigger>
<PopoverContent className={filling ? 'w-64' : 'w-80'}>
{form}
</PopoverContent>
</Popover>
) : (
<button {...chip} type="button">
{chipContent}
</button>
)}
{ownField && element.kind === 'checkbox' && (
<span className="text-xs text-muted-foreground" role="status">
{refusedToggle && ' Not saved.'}
</span>
)}
{props.children}
</EditorElement>
);
}
function FieldAnswerForm({ element }: { element: FieldNode }) {
const editor = useEditor();
const { fieldId, kind, label, options, value } = element;
const [refusal, setRefusal] = React.useState<{
stored?: FieldValue;
} | null>(null);
if (refusal && !Object.is(refusal.stored, value)) setRefusal(null);
const setValue = (next?: FieldValue) =>
setRefusal(saveAnswer(editor, fieldId, next) ? null : { stored: value });
return (
<div className="flex flex-col gap-1">
<div className="flex items-center gap-2">
<FieldValueInput
kind={kind}
label={label}
options={options}
value={value}
onChange={setValue}
/>
<Button size="sm" variant="ghost" onClick={() => setValue()}>
Clear
</Button>
</div>
<p className="text-xs text-muted-foreground" role="status">
{refusal && 'Not saved.'}
</p>
</div>
);
}
function FieldSettingsForm({
element,
writeName,
}: {
element: FieldNode;
writeName: React.Ref<() => 'refused' | 'written'>;
}) {
const editor = useEditor();
const { condition, fieldId, kind, options = [] } = element;
const update = (patch: FieldPatch) =>
editor.update((tx) => tx.plugin(FieldPlugin).update(fieldId, patch));
const fields = useEditorSelector(
(innerEditor) => innerEditor.plugin(FieldPlugin).read.fields(),
{
shouldUpdate: (commit) =>
!commit ||
commit.changed.hasAny('properties') ||
commit.changed.hasAny('structure'),
}
);
const targets = fields.filter((entry) => entry.fieldId !== fieldId);
const target = fields.find((entry) => entry.fieldId === condition?.ref)?.node;
const namers = new Map<string, string[]>();
for (const { fieldId: namer, node } of fields) {
if (!node.condition) continue;
const named = namers.get(node.condition.ref) ?? [];
named.push(namer);
namers.set(node.condition.ref, named);
}
const leadsHere = new Set([fieldId]);
for (const id of leadsHere) {
for (const namer of namers.get(id) ?? []) leadsHere.add(namer);
}
const choices = fields.filter(
(entry) => entry.fieldId === condition?.ref || !leadsHere.has(entry.fieldId)
);
const tests = target ? fillableTests(target) : [];
return (
<div className="grid grid-cols-[5rem_1fr] items-center gap-2 text-sm">
<Label htmlFor={`${fieldId}-label`}>Label</Label>
<Input
id={`${fieldId}-label`}
className="h-8"
value={element.label}
onChange={(event) => update({ label: event.target.value })}
/>
<FieldNameInput element={element} writeName={writeName} />
<Label htmlFor={`${fieldId}-kind`}>Kind</Label>
<NativeSelect
id={`${fieldId}-kind`}
size="sm"
value={kind}
onChange={(event) => {
if (isKind(event.target.value)) update({ kind: event.target.value });
}}
>
{Object.entries(KINDS).map(([value, label]) => (
<NativeSelectOption key={value} value={value}>
{label}
</NativeSelectOption>
))}
</NativeSelect>
<Label htmlFor={`${fieldId}-role`}>Role</Label>
<Input
id={`${fieldId}-role`}
className="h-8"
list={`${fieldId}-roles`}
value={element.role}
onChange={(event) => update({ role: event.target.value })}
/>
<datalist id={`${fieldId}-roles`}>
{[...new Set(targets.map((entry) => entry.node.role))].map((role) => (
<option key={role}>{role}</option>
))}
</datalist>
<Label htmlFor={`${fieldId}-required`}>Required</Label>
<Checkbox
id={`${fieldId}-required`}
checked={element.required === true}
onCheckedChange={(checked) =>
update({ required: checked === true || undefined })
}
/>
{kind === 'choice' && (
<>
<Label className="self-start pt-2">Options</Label>
<div className="flex flex-col gap-1">
{options.map((option, index) => (
<div key={option.value} className="flex gap-1">
<Input
aria-label={`Option ${index + 1}`}
className="h-8"
value={option.label}
onChange={(event) =>
update({
options: options.map((entry) =>
entry === option
? { ...entry, label: event.target.value }
: entry
),
})
}
/>
<Button
aria-label={`Remove option ${index + 1}`}
size="icon-sm"
variant="ghost"
onClick={() =>
update({
options: options.filter((entry) => entry !== option),
})
}
>
<XIcon />
</Button>
</div>
))}
<Button
className="w-fit"
size="sm"
variant="ghost"
onClick={() =>
update({
options: [
...options,
{
label: `Option ${options.length + 1}`,
value: crypto.randomUUID().slice(0, 8),
},
],
})
}
>
<PlusIcon />
Add option
</Button>
</div>
</>
)}
{kind !== 'signature' && (
<>
<Label>Default</Label>
<FieldValueInput
kind={kind}
label="Default"
options={options}
value={element.defaultValue}
onChange={(defaultValue) => update({ defaultValue })}
/>
</>
)}
<Label htmlFor={`${fieldId}-condition`}>Show when</Label>
<NativeSelect
id={`${fieldId}-condition`}
size="sm"
value={condition ? `#${condition.ref}` : ''}
onChange={(event) => {
const next = choices.find(
(entry) => `#${entry.fieldId}` === event.target.value
);
update({
condition:
next &&
conditionOn(next.fieldId, next.node, fillableTests(next.node)[0]),
});
}}
>
<NativeSelectOption value="">Always</NativeSelectOption>
{condition && !target && (
<NativeSelectOption value={`#${condition.ref}`}>
Missing field
</NativeSelectOption>
)}
{choices.map((entry) => (
<NativeSelectOption key={entry.fieldId} value={`#${entry.fieldId}`}>
{entry.node.name === undefined
? entry.node.label
: `${entry.node.label} (${entry.node.name})`}
</NativeSelectOption>
))}
</NativeSelect>
{condition && target && (
<div className="col-start-2 flex gap-1">
<NativeSelect
aria-label="Test"
size="sm"
value={condition.test}
onChange={(event) => {
if (!isTest(event.target.value)) return;
update({
condition: conditionOn(
condition.ref,
target,
event.target.value,
fitsField(target, condition.value)
? condition.value
: undefined
),
});
}}
>
{[...new Set([...tests, condition.test])].map((test) => (
<NativeSelectOption key={test} value={test}>
{TEST_LABELS[test]}
</NativeSelectOption>
))}
</NativeSelect>
{needsValue(condition.test) && tests.includes(condition.test) && (
<FieldValueInput
clearable={false}
kind={target.kind}
label="Compared value"
options={target.options}
value={condition.value}
onChange={(value) =>
update({
condition: conditionOn(
condition.ref,
target,
condition.test,
value
),
})
}
/>
)}
</div>
)}
</div>
);
}
function FieldNameInput({
element,
writeName,
}: {
element: FieldNode;
writeName: React.Ref<() => 'refused' | 'written'>;
}) {
const editor = useEditor();
const { fieldId, name } = element;
const [draft, setDraft] = React.useState<{
refused: boolean;
text: string;
} | null>(null);
const write = () => {
if (!draft) return 'written';
const next = draft.text === '' ? undefined : draft.text;
if (next === name) {
setDraft(null);
return 'written';
}
try {
editor.update((tx) =>
tx.plugin(FieldPlugin).update(fieldId, { name: next })
);
setDraft(null);
return 'written';
} catch (error) {
if (!(error instanceof EditorSchemaValidationError)) throw error;
setDraft({ ...draft, refused: true });
return 'refused';
}
};
React.useImperativeHandle(writeName, () => write);
return (
<>
<Label htmlFor={`${fieldId}-name`}>Name</Label>
<Input
id={`${fieldId}-name`}
className="h-8"
aria-describedby={draft?.refused ? `${fieldId}-name-error` : undefined}
aria-invalid={draft?.refused || undefined}
value={draft?.text ?? name ?? ''}
onBlur={write}
onChange={(event) =>
setDraft({ refused: false, text: event.target.value })
}
onKeyDown={(event) => {
if (event.key === 'Enter' && !event.nativeEvent.isComposing) write();
}}
/>
{draft?.refused && (
<p
id={`${fieldId}-name-error`}
className="col-start-2 text-xs text-destructive"
role="alert"
>
A name cannot start or end with a space or hold a tab, a line break or
another control character.
</p>
)}
</>
);
}
const NO_OPTION = '';
const optionToken = (option: FieldOption) => `option:${option.value}`;
const entryOf = (
kind: FieldKind,
input: HTMLInputElement,
clearable: boolean
): { value?: FieldValue } | null => {
// The browser reports a number or date typed in part as bad input.
if (input.validity.badInput) return null;
if (input.value === '') {
if (clearable) return { value: undefined };
return kind === 'text' ? { value: '' } : null;
}
const value = kind === 'number' ? input.valueAsNumber : input.value;
return fitsField({ kind }, value) ? { value } : null;
};
function FieldValueInput({
clearable = true,
kind,
label,
onChange,
options,
value,
}: {
clearable?: boolean;
kind: FieldKind;
label: string;
onChange: (value: FieldValue | undefined) => void;
options?: readonly FieldOption[];
value?: FieldValue;
}) {
const [draft, setDraft] = React.useState<{
kind: FieldKind;
stored?: FieldValue;
text: string;
} | null>(null);
const [resets, setResets] = React.useState(0);
if (draft && (draft.kind !== kind || !Object.is(draft.stored, value))) {
setDraft(null);
}
if (kind === 'checkbox') {
return (
<Checkbox
aria-label={label}
checked={value === true}
onCheckedChange={(checked) => onChange(checked === true)}
/>
);
}
if (kind === 'choice') {
const picked = options?.find((option) => option.value === value);
return (
<NativeSelect
aria-label={label}
size="sm"
value={picked ? optionToken(picked) : NO_OPTION}
onChange={(event) => {
const option = options?.find(
(entry) => optionToken(entry) === event.target.value
);
if (option) onChange(option.value);
else if (event.target.value === NO_OPTION && clearable) {
onChange(undefined);
}
}}
>
{(clearable || !picked) && (
<NativeSelectOption value={NO_OPTION}>None</NativeSelectOption>
)}
{options?.map((option) => (
<NativeSelectOption key={option.value} value={optionToken(option)}>
{option.label}
</NativeSelectOption>
))}
</NativeSelect>
);
}
return (
<Input
key={resets}
aria-label={label}
className="h-8"
type={kind === 'number' || kind === 'date' ? kind : 'text'}
value={draft?.text ?? (value === undefined ? '' : String(value))}
onBlur={(event) => {
// A partial number or date reads as an empty value, so React never
// clears it from an input whose stored answer is empty, and WebKit
// keeps a partial date through an empty value write.
if (event.currentTarget.validity.badInput) {
setResets((count) => count + 1);
}
setDraft(null);
}}
onInput={(event) => {
const entry = entryOf(kind, event.currentTarget, clearable);
if (entry) onChange(entry.value);
setDraft({
kind,
stored: entry ? entry.value : value,
text: event.currentTarget.value,
});
}}
/>
);
}
export const FieldKit = [FieldPlugin.configure({ component: FieldElement })];'use client';
import { cn } from 'cn';
import { CheckIcon, PlusIcon, TriangleAlertIcon, XIcon } from 'lucide-react';
import { EditorSchemaValidationError } from 'platejs';
import { AuthoredPlugin } from 'platejs/authored';
import {
FIELD_TESTS,
fitsField,
type FieldKind,
type FieldOption,
type FieldPatch,
type FieldProblem,
type FieldSettings,
type FieldTest,
type FieldValue,
} from 'platejs/field';
import { FieldPlugin, useFieldRead } from 'platejs/field/react'
FieldElement: renders the field chip and its settings popover.import { useCreateEditor } from 'platejs/react';
import { FieldKit } from '@/components/editor/field';
const editor = useCreateEditor({
plugins: [
// ...otherPlugins,
...FieldKit,
],
});import { useCreateEditor } from 'platejs/react';
import { FieldKit } from '@/components/editor/field';
const editor
FieldToolbarButton inserts a field of each kind. A new field takes the role of the document's first field, or signer in a document with no field. The main insert and slash menus have no Field item, so add this menu to a toolbar.
'use client';
import { BracesIcon } from 'lucide-react';
import { BaseFieldPlugin } from 'platejs/field';
import { useEditor, useEditorReadOnly, usePluginStore } from 'platejs/react';
import * as React from 'react';
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from '@/components/editor/dropdown-menu';
import { ToolbarButton } from '@/components/editor/toolbar';
const KINDS = [
{ kind: 'text', label: 'Text' },
import { FieldToolbarButton } from '@/components/editor/field-toolbar-button';
import { Toolbar } from '@/components/editor/toolbar';
export function FieldToolbar() {
return (
<Toolbar>
<FieldToolbarButton />
</Toolbar>
);
}import { FieldToolbarButton } from '@/components/editor/field-toolbar-button';
import { Toolbar }
BaseFieldKit renders each field for read-only output with platejs/static. A field shows its answer in place: a choice as its option's label, a checkbox as a ticked or empty box, and a number as written, 0 included. A field other than a checkbox shows a blank line when it has no filled answer. An app makes the PDF of a filled document from this output, as Print the filled document shows.
import { CheckIcon } from 'lucide-react';
import { BaseFieldPlugin, fillsField } from 'platejs/field';
import { type EditorElementProps, EditorElement } from 'platejs/static';
import * as React from 'react';
export function FieldElementStatic(
props: EditorElementProps<typeof BaseFieldPlugin>
) {
const { element } = props;
const { kind, options, value } = element;
let shown: React.ReactNode
import { FieldPlugin } from 'platejs/field/react';
import { useCreateEditor } from 'platejs/react';
import { FieldElement } from '@/components/editor/field';
const editor = useCreateEditor({
plugins: [FieldPlugin.configure({ component: FieldElement })],
});import { FieldPlugin } from 'platejs/field/react';
import { useCreateEditor } from 'platejs/react';
import { FieldElement } from '@/components/editor/field';
const editor = useCreateEditor({
plugins: [FieldPlugin.configure({ component: FieldElement })],
});BaseFieldPlugin from platejs/field runs without React, such as on a server that reads a submitted document:
import { createEditor, type Value } from 'platejs';
import { BaseFieldPlugin } from 'platejs/field';
export const readFields = (value: Value) =>
createEditor({ initialValue: value, plugins: [BaseFieldPlugin] })
.plugin(BaseFieldPlugin)
.read.fields();import { createEditor, type Value } from 'platejs';
import
A field sits inside a paragraph, like a date or a mention.
{
"type": "paragraph",
"children": [
{ "text": "Tenant name: " },
{
"type": "field",
"fieldId": "f_k2x9",
"kind": "text",
"role": "tenant",
"label": "Tenant name",
"name": "tenant_name",
"required": true,
"children": [{ "text": "" }]
},
{ "text": "" }
]
}{
"type": "paragraph",
"children": [
{ "text": "Tenant name: " },
{
"type": "field",
"fieldId": "f_k2x9",
"kind": "text",
"role": "tenant",
"label": "Tenant name",
"name": "tenant_name",
"required": true,
"children": [{ "text": "" }]
},
{ "text": "" }
]
| Property | Type | Notes |
|---|---|---|
type | 'field' | Inline void element owned by BaseFieldPlugin. |
fieldId | string | Unique in the document. A new field gets a random nanoid. |
kind | FieldKind | 'text', 'number', 'date', 'checkbox', 'choice' or 'signature'. Required. |
role | string | The role that fills the field, such as 'tenant'. Required. |
label | string | Required. The chip shows it, and HTML, Word and plain text show it in brackets when the field has no answer. |
name | string | Fields of one role that share a name hold one answer, see Names. |
required | boolean | Marks a field that needs a filled answer while it applies. applyFieldValues refuses a submission that leaves it unfilled. |
defaultValue | FieldValue | A value of the field's kind. |
options | FieldOption[] | Choice fields only. Each option is { value, label }, and no two share a value. |
value | FieldValue | The answer. A field is unfilled without one, or when fillsField says its answer does not fill it. |
condition | FieldCondition | { ref, test, value? }, see Conditions. |
children | [{ text: '' }] | Required child of an inline void element. |
Each kind fixes the shape of its value and the tests a condition on it may use. fitsField(field, value) from platejs/field says whether a value fits a field's kind, and FIELD_TESTS lists each kind's tests.
| Kind | Value | Tests |
|---|---|---|
text | a string | filled, blank, equals, not-equals |
number | a finite number | filled, blank, equals, not-equals, above, below |
date | an ISO date, YYYY-MM-DD | filled, blank, equals, not-equals, above, below |
checkbox | true or false | equals, not-equals |
choice | one option's value | filled, blank, equals, not-equals |
signature | a string your app owns, such as a stored image's id | filled, blank |
A choice stores the option's value, so renaming an option's label keeps every answer and condition that names it.
fillsField(field, value) from platejs/field says whether a value is a filled answer for a field. required and the filled and blank tests read the same rule. A filled answer is a ticked checkbox, or a value that fits the field's kind. A text or signature answer also needs a character that JavaScript's \s does not match. So false, an empty text and a text of spaces fit a field but do not fill it, and 0 fills a number field.
import { fillsField } from 'platejs/field';
fillsField({ kind: 'text' }, ' '); // false
fillsField({ kind: 'number' }, 0); // true
fillsField({ kind: 'checkbox' }, false); // falseimport { fillsField } from 'platejs/field';
fillsField({ kind: 'text' }, ' '); // false
fillsField({ kind: 'number' }, 0); // true
fillsField({ kind: 'checkbox' }, false); // falseEach field names the role that fills it, such as landlord or tenant. A role is any string. Plate stores it and never checks who a user is. Your app maps each person to a role, as it maps each comment to its author.
A fill-only view stops one role from changing another role's field, or the text around it, in that editor. An app that collects answers from several people still checks each role's answers on its server, with applyFieldValues.
The settings popover offers the roles the document's fields already use, and takes a new one.
A name says that fields of one role ask for the same answer, such as a lease that asks for the tenant's name at the top and again by the signature. Fields of one role that share a name hold one answer. The same name in two roles is two answers. A field with no name works by its fieldId alone.
A name is a text that is not empty, has no whitespace at either end, and holds no control character, line or paragraph separator or lone surrogate. Loading, insert, update and a plain tx.nodes.set refuse any other name. In the registry UI, the settings popover's Name input sets a field's name and shows an error for a name the rule refuses.
update writes a value, a cleared one included, to every field of the role that shares the field's name, in the same commit and the same undo step. No other setting reaches the other fields. In the demo, the lease asks for the tenant's name twice under one name, so typing it in one place fills the other, and undo takes it back in both.
Fields of one role that share a name must share their kind, the values of their options and their condition. A default takes no part. Two conditions match when they name the same field, or fields of one role and name, with the same test and value. Each field of a name whose fields differ reads name-conflict, and update then writes a value to its own field alone. insert and update never refuse a name conflict, so an author can change the fields of a name one at a time.
Each field of a name whose fields hold different values reads answer-conflict. An empty text and no value differ, and so do false and no value. insert and a paste write no other field. So a field that joins a name with another value, or with none, reads answer-conflict until an update writes a value to a field of that name, which writes every field of it.
insert takes a field's settings and returns its new fieldId. Its second argument takes node insert options, such as at and select.
import { BaseFieldPlugin } from 'platejs/field';
const fieldId = editor.plugin(BaseFieldPlugin).update.insert({
kind: 'text',
label: 'Tenant name',
name: 'tenant_name',
required: true,
role: 'tenant',
});import { BaseFieldPlugin } from 'platejs/field';
const fieldId = editor.plugin(BaseFieldPlugin).update.insert({
kind: 'text',
label: 'Tenant name',
name: 'tenant_name',
required: true,
role: 'tenant',
});insert throws when a value, default or options do not fit the kind, when the settings name a fieldId or a name the name rule refuses, or when the condition names no field, or a test or value that the named field's kind does not take.
update changes the settings or value of the field that holds a fieldId. A setting given as undefined is removed. A value also goes to every other field of the role and name.
editor.update((tx) => {
tx.plugin(BaseFieldPlugin).update(fieldId, { value: 'Ada Lovelace' });
});editor.update((tx) => {
tx.plugin(BaseFieldPlugin).update(fieldId, { value: 'Ada Lovelace' });
});update throws, and changes nothing, when:
fieldId;name the name rule refuses;kind, role or label, or names fieldId;A patch that changes kind or options also drops each value, default and options that the field no longer fits. Turning a number field with a default into a date field drops the default. The field keeps its fieldId.
A condition says when a field applies. It applies when the field whose fieldId is ref passes test. Every test but filled and blank compares against value, which takes the shape of the named field's value. The demo's Pet name field, which the tenant fills, applies when the landlord's Pets allowed choice is yes:
editor.update((tx) => {
tx.plugin(BaseFieldPlugin).update(petNameId, {
condition: { ref: petsId, test: 'equals', value: 'yes' },
});
});editor.update((tx) => {
tx.plugin(BaseFieldPlugin).update(petNameId, {
condition: { ref: petsId, test: 'equals', value: 'yes' },
});
});The popover's Show when list offers the field the condition names and every other field whose conditions do not lead back to this one. Its test list offers only the tests that field's kind takes.
The editor never hides a field. A field whose condition fails is skipped. It needs no answer even when it is required, and applyFieldValues refuses a filled answer for it. A condition tests the answer of the field it names:
equals holds when the answer is value, and not-equals when it is not, no answer included.above and below compare numbers, and ISO dates as dates. Neither holds without an answer.false once its role is done answering. In the editor, that holds for a checkbox of the role that fills the field being read. In applyFieldValues, it holds once the checkbox's role has submitted.update refuses a condition that would close a loop, such as A naming B while B names A, or a field naming itself. A new test or value on a field of a loop passes. A loop can still come from a loaded document, a plain node write or two peers' updates made at the same time, and each of its fields then reports condition-loop.
read.field(fieldId) returns the field that holds an id, in any root, or null. It looks up that field, then one field for each condition it follows along the chain. read.fields() returns every field of the document in reading order. Each read is a FieldRead: { applies, fieldId, node, problems }.
import { BaseFieldPlugin } from 'platejs/field';
const fields = editor.plugin(BaseFieldPlugin).read;
const tenant = fields.field(tenantId);
const broken = fields.fields().filter((field) => field.problems.length > 0);
const skipped = fields.fields().filter((field) => field.applies === false);import { BaseFieldPlugin } from 'platejs/field';
const fields = editor.plugin(BaseFieldPlugin).read;
const tenant = fields.field(tenantId);
const broken = fields.fields().filter((field) => field.problems.length > 0);
const skipped = fields.fields().filter((field) => field.applies === false);| Problem | When |
|---|---|
missing-target | No field holds the id its condition names, such as after that field is deleted. |
unsupported-test | The kind of the field its condition names does not take the condition's test. |
invalid-value | Its value, default or options do not fit its kind, or its condition's value does not fit the test or the named field's kind. |
condition-loop | Its condition names a field whose chain of conditions leads back to it, such as A naming B while B names A. |
name-conflict | A field of its role and name has another kind, other option values or another condition. |
answer-conflict | A field of its role and name holds another value, or none. |
insert and update refuse a write that would cause one of the first four problems. They never refuse a name or answer conflict, which the read reports. A problem comes from a later edit, such as deleting or changing the field a condition names, or from a write that skipped the commands, such as a plain tx.nodes.set or a loaded document.
applies says whether the field applies under its condition. It reads the answers the document holds now, along the whole chain of conditions, as the field's own role reads them:
true for a field with no condition, a condition that has a problem or one in a loop, and a condition that holds.false for a skipped field, whose condition fails.null while it depends on an answer another role has not given, such as the tenant's Pet name before the landlord picks Pets allowed. Only applyFieldValues knows which roles have submitted, so the editor reads such a field as waiting.A field whose condition names a skipped field is decided, even when another role owns that field.
In React, useFieldRead(fieldId) from platejs/field/react reads one field, its problems and whether it applies. A commit that changes an element reads it again, and the component renders again only when the field, its problems or applies changed. The registry chip uses it to show a warning when the field its condition names is deleted, and an undo clears the warning. The chip also mutes a field whose applies is false and marks it skipped. The chip of a field that waits is not muted.
import { useFieldRead } from 'platejs/field/react';
const field = useFieldRead(element.fieldId);
const problems = field?.problems ?? [];
const skipped = field?.applies === false;import { useFieldRead } from 'platejs/field/react';
const field = useFieldRead(element.fieldId);
const problems = field?.problems ?? [];
const skipped = field?.applies === false;Set fillRole to open a fill-only view of one role. The editor then takes answers for that role's fields and refuses every other local change, so a tenant fills the tenant's fields and changes nothing else.
import { FieldPlugin } from 'platejs/field/react';
import { useCreateEditor } from 'platejs/react';
import { FieldElement } from '@/components/editor/field';
const editor = useCreateEditor({
initialValue: template,
plugins: [
// ...otherPlugins,
FieldPlugin.configure({
component: FieldElement,
initialState: { fillRole: 'tenant' },
}),
],
});import { FieldPlugin } from 'platejs/field/react';
import { useCreateEditor } from 'platejs/react';
import { FieldElement } from '@/components/editor/field';
const editor = useCreateEditor({
initialValue: template,
plugins: [
// ...otherPlugins,
FieldPlugin.configure({
component: FieldElement,
initialState: { fillRole: 'tenant' },
}),
],
});The demo switches one editor between authoring and each role through the plugin store, and null returns to authoring:
editor.plugin(FieldPlugin).store.set({ fillRole: 'landlord' });
editor.plugin(FieldPlugin).store.set({ fillRole: null });editor.plugin(FieldPlugin).store.set({ fillRole: 'landlord' });
editor.plugin(FieldPlugin).store.set({ fillRole: null });usePluginStore(FieldPlugin, 'fillRole') from platejs/react reads the role in a component. The role is editor state, so every view of one editor fills as the same role. Switch it between updates. A switch writes nothing to the document and leaves undo and redo as they are.
While a role is set:
persist and effects that neither persist nor sync to peers pass, so a person can still select and copy.{ reason, status: 'blocked' }. The first answer after a switch is its own undo step, so an answer typed right after a switch takes two undos.tx.value.replace or loading another template, is refused, and so is a plugin reconfiguration. Load the template and configure plugins before you set the role, or clear the role first.A peer's change passes whole. Every commit tagged collaboration passes, so collaborators keep one document. Apply a peer's Yjs update from your provider's events, never from inside an editor update. A local write made inside a peer's change takes its collaboration tag, passes and never reaches peers. For the same reason, a Yjs UndoManager that your app drives itself, or a local update that your app tags collaboration, passes the fill check.
The fill check runs in the field plugin's activate, and the undo step boundary in its corrections. A plugin that extends the field plugin with its own activate or corrections replaces them, so put that work in a companion plugin.
The fill check runs in the person's browser, where anyone can run their own code. Your server assigns each person's role and checks each submission with applyFieldValues.
A client reads one role's answers from the editor and posts them. The server checks every role's answers against the template it saved, and keeps the filled document.
read.submission(role) returns a FieldSubmission, { role, values }. values holds the value of each field of the role that has one, keyed by fieldId.
import { FieldPlugin } from 'platejs/field/react';
const submission = editor.plugin(FieldPlugin).read.submission('tenant');
// { role: 'tenant', values: { tenant: 'Grace Hopper', 'pet-name': 'Milo', rules: true } }import { FieldPlugin } from 'platejs/field/react';
const submission = editor.plugin(FieldPlugin).read.submission('tenant');
// { role: 'tenant', values: { tenant: 'Grace Hopper', 'pet-name': 'Milo', rules: true } }Fields of one name keep their own keys, so the submission holds the answer once for each of them. The submission keeps false, 0, an empty text, a text of spaces and a value that no longer fits its field's kind, so the server judges each of them. It leaves out a field with no value, so a checkbox never touched and one ticked and then unticked stay apart.
applyFieldValues(template, submissions, options?) from platejs/field checks each role's answers and builds the filled document. It imports no React and checks each submission's shape itself, so a server passes parsed JSON straight in. In this route, frozenTemplate is the template your app saved, accepted holds the submissions it accepted before, and saveFilled stores the result.
import { applyFieldValues } from 'platejs/field';
const result = applyFieldValues(frozenTemplate, [...accepted, submission]);
if (!result.ok) {
return Response.json({ refusals: result.refusals }, { status: 400 });
}
await saveFilled(result.document);import { applyFieldValues } from 'platejs/field';
const result = applyFieldValues(frozenTemplate, [...accepted, submission]);
if (!result.ok) {
return Response.json({ refusals: result.refusals }, { status: 400 });
}
await saveFilled(result.document);template is the authored document as your app saved it, with its fieldIds and no answers, so the fill view and applyFieldValues start from the same ids. It takes a Value or a document with named roots, and result.document has the same shape. applyFieldValues reads fields in the main root and each named root, never in meta or records.submissions lists each role's submission in the order the roles submitted. Each one is checked against the roles before it plus its own answers.options.type names the field element's type when your app renamed it with schema.override. It defaults to field.The filled document is the template with each accepted answer set as its field's value. A default stays a setting and never becomes an answer.
On success, pending lists each role that has not submitted and holds a required field that applies or waits. It also lists the role whose answer each such waiting field needs next. An optional field never puts a role in pending. The demo shows pending as Waiting on.
On a refusal, result is { ok: false, refusals } with at least one refusal. When the template has refusals, the result lists all of them and checks no submission. Otherwise it lists the refusals of the first submission that has any.
| Code | When |
|---|---|
invalid-template | A template field holds an answer (answered), lacks a fieldId, holds anything but one text or has a kind, role, label, setting or condition of the wrong shape (malformed), repeats a fieldId (duplicate-id), or has a problem a read reports, condition-loop and name-conflict included. The refusal names the problem, the field's path, its root in a named root, and its fieldId and name when it has them. |
invalid-submission | A submission is not an object with a role string and a values object. The refusal names its index. |
duplicate-role | A role already in the list submits again. |
unknown-role | The role owns no field. |
unknown-field | An answer names no field of the template. |
wrong-role | An answer is for another role's field. |
invalid-value | An answer does not fit its field. |
waiting | A field of the role waits on a role that has not submitted, which waitsOn names. It is reported even when the field's answer is refused too. |
skipped | A field of the role is skipped and holds a filled answer. An unfilled answer stays as written, so clearing the answer or unticking the box ends the refusal. |
missing-required | A required field of the role applies and has no filled answer. |
answer-conflict | Once the role's answers apply, the fields of one of its names hold different values. The refusal names the name and lists every field of the name in document order as fieldIds. A name gets none when the submission already refused one of its fields as invalid-value, waiting or skipped. A required field left out does not stop it, so it can come beside missing-required. |
invalid-submission, duplicate-role and unknown-role come alone. The other submission refusals name the role, and the fieldId of their field and its name when it has one. An answer-conflict names fieldIds instead of a fieldId. The result lists every refusal of that submission.
In a template whose landlord's Rent field is named rent, and whose tenant's two name fields share tenant_name:
applyFieldValues(template, [{ role: 'landlord', values: {} }]);
// { ok: false, refusals: [{ code: 'missing-required', fieldId: 'rent', name: 'rent', role: 'landlord' }] }
applyFieldValues(template, [
{ role: 'tenant', values: { tenant: 'Ada Lovelace', 'tenant-again': 'Ada' } },
]);
// { ok: false, refusals: [{ code: 'answer-conflict', fieldIds: ['tenant', 'tenant-again'], name: 'tenant_name', role: 'tenant' }] }applyFieldValues(template, [{ role: 'landlord', values: {} }]);
// { ok: false, refusals: [{ code: 'missing-required', fieldId: 'rent', name: 'rent', role: 'landlord' }] }
applyFieldValues(template, [
{ role: 'tenant', values: { tenant: 'Ada Lovelace', 'tenant-again': 'Ada' } },
]);
// { ok: false, refusals: [{ code: 'answer-conflict', fieldIds: ['tenant', 'tenant-again'], name: 'tenant_name', role: 'tenant' }] }In the demo, the tenant's Submit before the landlord's gets a waiting refusal, because Pet name waits on the landlord's Pets allowed. When the landlord submits No, a pet name the tenant types anyway is refused as skipped until it is cleared.
A template where two roles each wait on the other passes, because a third role's answer can end the wait by making a field along the chain skip. While both fields still wait, the role that submits first is refused as waiting on the other.
Render the filled document with BaseFieldKit through platejs/static, and make its PDF from that output. Static output shows a field other than a checkbox as a blank line when it has no filled answer, while editor.api.html.serialize() writes the label in brackets for a field with no answer.
import { createEditor } from 'platejs';
import { renderStaticHtml } from 'platejs/static';
import { BaseFieldKit } from '@/components/editor/field-static';
const filled = createEditor({
initialValue: result.document,
plugins: [
// ...otherPlugins,
...BaseFieldKit,
],
});
const { data } = await renderStaticHtml(filled);import { createEditor } from 'platejs';
import { renderStaticHtml } from 'platejs/static';
import { BaseFieldKit } from '@/components/editor/field-static';
const filled = createEditor({
initialValue: result.document,
plugins: [
// ...otherPlugins,
...BaseFieldKit,
],
});
const { data } = await renderStaticHtml(filled);Static Rendering covers EditorStatic and renderStaticHtml.
Give the fields your app fills itself a role of their own, such as app, and submit that role's answers before anyone signs. Every other role's fill view refuses a write to those fields, and applyFieldValues refuses another role's answer for one as wrong-role, so the app's values stay locked. Your server keeps the app's submission and sends it first in every list.
In a lease whose app role holds fields named address and rent, and whose tenant's two name fields share tenant_name, the app fills its own fields and starts the tenant's name from the same record:
import {
applyFieldValues,
BaseFieldPlugin,
fieldSubmission,
readFieldAnswers,
startFieldValues,
} from 'platejs/field';
const record = {
address: '1 Main St',
rent: 1200,
tenant_name: 'Ada Lovelace',
};
// The app's own role fills locked values before anyone signs.
const app = fieldSubmission(template, 'app', record);
// The tenant's fill view opens on the app's answers, with the record's values as a start.
const start = startFieldValues(
template,
[app],
fieldSubmission(template, 'tenant', record)
);
if (!start.ok) throw new Error(start.refusals[0].code);
// The tenant fills start.document in an editor whose fillRole is 'tenant'.
const tenant = editor.plugin(BaseFieldPlugin).read.submission('tenant');
// The server applies every role.
const result = applyFieldValues(template, [app, tenant]);
if (!result.ok) throw new Error(result.refusals[0].code);
// The saved document reads back by name.
readFieldAnswers(result.document).tenant?.tenant_name;
// { kind: 'text', value: 'Ada Lovelace' } when the tenant kept the starting nameimport {
applyFieldValues,
BaseFieldPlugin,
fieldSubmission,
readFieldAnswers,
startFieldValues,
} from 'platejs/field';
const record = {
address: '1 Main St',
rent: 1200,
tenant_name: 'Ada Lovelace',
};
// The app's own role fills locked values before anyone signs.
const app = fieldSubmission(template, 'app', record);
// The tenant's fill view opens on the app's answers, with the record's values as a start.
const start = startFieldValues(
template,
[app],
fieldSubmission(template,
fieldSubmission(template, role, values, options?) turns a record keyed by field name into one role's FieldSubmission, keyed by fieldId. Each field of role whose name is an own key of values gets that key's value, so a name the role asks twice gets it on both fields.
null and undefined leave the field out.constructor, never counts.applyFieldValues judges each one, and refuses an app submission that misses a required field as missing-required with the field's name.options.type names a renamed field type, as it does for applyFieldValues.startFieldValues(template, submissions, start, options?) checks submissions as applyFieldValues does, then writes the values of start, a FieldSubmission of a role that has not submitted, on that role's fields. It returns applyFieldValues's result shape. On success, document is the filled document the role starts from, to open in that role's fill view.
update writes it.start gives no value starts blank, even one with a defaultValue.start's own values, as if the role had submitted. A value on a field that skips, or that waits on a role that has not submitted, is left out with no refusal, and the field starts blank. So an app can start from a wide record before every role has answered.pending comes from submissions alone, so start never takes its role off it.The person who fills keeps, changes or clears each starting value. Their submission is their own answer, and applyFieldValues judges it like any other. It refuses a cleared required value as missing-required, and a kept value on a field that another answer then skips as skipped until it is cleared.
startFieldValues first refuses what applyFieldValues refuses for submissions. Then it refuses start alone as invalid-submission when it is malformed, with index equal to submissions.length, as duplicate-role when its role already submitted, and as unknown-role when the role owns no field. Otherwise it lists together unknown-field, wrong-role or invalid-value for each value that names no field, another role's field or a value that does not fit, and answer-conflict for each name that start gives two different values. It never refuses start as missing-required, skipped or waiting, because a start may leave any field blank.
readFieldAnswers(document, options?) reads a saved document and returns each role's answers keyed by name, as answers[role][name]. Each role that has a named field gets a record, and unnamed fields are left out. Both levels are records with no prototype, so a role or name such as constructor reads as its own key. It reads fields as applyFieldValues reads them, so a node that is not a valid field is skipped, and a duplicated fieldId reads from its first holder. options.type names a renamed field type.
Each answer is a FieldAnswer:
| Answer | When |
|---|---|
{ kind, value } | The fields of the name hold one value that fits kind. value is a boolean for a checkbox, a number for a number and a string for every other kind. |
{ kind } | The fields hold no value, or one value that does not fit kind. |
{ kind, problem: 'answer-conflict' } | The fields hold different values. |
{ problem: 'name-conflict' } | The fields differ in kind, option values or condition, so the name has no one kind. |
Check 'problem' in answer first, then narrow on kind to read value:
const rent = readFieldAnswers(result.document).app?.rent;
if (rent && !('problem' in rent) && rent.kind === 'number') {
rent.value; // number | undefined
}const rent = readFieldAnswers(result.document).app?.rent;
if (rent && !('problem' in rent) && rent.kind === 'number') {
rent.value; // number | undefined
}The read keeps no record of submissions, so it says nothing of which fields apply. A role that submitted nothing and one that left every field blank read the same. An app that needs to know which fields apply takes that from the result of applyFieldValues.
A field keeps its fieldId through a move, a drag move included, through an undo that brings it back and when a saved document loads. A copy gets new ids:
tx.blocks.duplicate and a table fill give each field they copy a new id and keep its name. A copied condition that names a field in the same copy names that field's copy.name-conflict. Give the condition's field and its copy one name, and the conflict ends.missing-target until an undo.tx.schema.copy and inserts the result gets a new id, and the copy's condition keeps naming the original.In Suggesting mode, a change from a field to a mention shows the field as deleted beside the inserted mention, so rejecting it keeps the field and its fieldId.
editor.api.html.serialize() writes each field as a span with one data-field-* attribute per property. The span's text is the answer, a choice as its option's label, or the label in brackets when the field has no answer. The id, kind, label, name and role attributes hold plain text, and the others hold JSON:
<p>Pets allowed? <span data-field-id="pets" data-field-kind="choice" data-field-label="Pets allowed" data-field-name="pets_allowed" data-field-options="[{"label":"Yes","value":"yes"},{"label":"No","value":"no"}]" data-field-required="true" data-field-role="landlord" data-field-value=""yes"">Yes</span> Pet name: <span data-field-condition="{"ref":"pets","test":"equals","value":"yes"}" data-field-id="pet-name" data-field-kind="text" data-field-label="Pet name" data-field-name="pet_name" data-field-required="true" data-field-role="tenant">[Pet name]</span></p><p>Pets allowed? <span data-field-id="pets" data-field-kind="choice" data-field-label="Pets allowed" data-field-name="pets_allowed" data-field-options="[{"label":"Yes","value":"yes"},{"label":"No","value":"no"}]" data-field-required="true" data-field-role="landlord" data-field-value=""yes"">Yes</span> Pet name: <span data-field-conditionParsing that HTML reads every property back. A span needs data-field-kind, data-field-label and data-field-role to read as a field. A pasted HTML template gets new ids, and its conditions name the copies.
The demo's HTML panel serializes with lossPolicy: 'allow', because the date element has no HTML encoder. The panel lists one html-unsupported-content line for the date it drops.
Markdown writes each field as a <field> tag with every property, the fieldId and the condition included:
Pets allowed? <field kind="choice" label="Pets allowed" name="pets_allowed" options="[{"label":"Yes","value":"yes"},{"label":"No","value":"no"}]" required role="landlord" value="yes" fieldId="pets" /> Pet name: <field kind="text" label="Pet name" name="pet_name" required role="tenant" condition="{"ref":"pets","test":"equals","value":"yes"}" fieldId="pet-name" />Pets allowed? <field kind="choice" label="Pets allowed" name="pets_allowed" options="[{"label":"Yes","value":"yes"},{"label":"No","value":"no"}]" required role="landlord" value="yes" fieldId="pets" /> Pet name: <field kind="text" label="Pet name" name="pet_name" required role="tenant"The reader needs kind, label and role. A tag without them stays as text, with a markdown-unsupported-node diagnostic. A pasted Markdown template gets new ids, and its conditions name the copies.
Word has no field element. Word export writes each field's answer as text, a choice as its option's label, or the label in brackets when the field has no answer. It needs no static field component, so a headless export keeps the answers.
import { exportDocx } from 'platejs/docx/export';
const result = await exportDocx(editor);
const dropped = result.diagnostics.filter(
(diagnostic) => diagnostic.code === 'property-dropped'
);import { exportDocx } from 'platejs/docx/export';
const result = await exportDocx(editor);
const dropped = result.diagnostics.filter(
(diagnostic) => diagnostic.code === 'property-dropped'
);The export drops each field's id, kind, role, name, settings and condition. It reports them with one property-dropped warning whose message is "Word keeps each field answer and drops its name and settings.", whose feature is field and whose count is the number of fields. The warning never refuses an export, under lossPolicy: 'allow' or 'reject'. The demo's Word panel shows that warning, and its count goes up as you insert fields.
Plain text, through serializePlainText from platejs, writes the same text as Word.
| API | Package | Use |
|---|---|---|
BaseFieldPlugin | platejs/field | Headless inline void field plugin. |
FieldPlugin | platejs/field/react | React field plugin. |
tx.plugin(BaseFieldPlugin).insert(settings, options?) | BaseFieldPlugin update | Inserts a field and returns its fieldId. |
tx.plugin(BaseFieldPlugin).update(fieldId, patch) | BaseFieldPlugin update | Changes a field's settings or value, and writes a value to every field of its role and name. |
editor.plugin(BaseFieldPlugin).read.field(fieldId) | BaseFieldPlugin read | The field that holds an id, with its problems and whether it applies, or null. |
editor.plugin(BaseFieldPlugin).read.fields() | BaseFieldPlugin read | Every field in reading order, with its problems and whether it applies. |
editor.plugin(BaseFieldPlugin).read.submission(role) | BaseFieldPlugin read | The values of one role's fields, keyed by fieldId, to pass to applyFieldValues. |
fillRole | BaseFieldPlugin state | The role this editor fills as, or null while authoring. Set it through initialState or editor.plugin(FieldPlugin).store.set. |
useFieldRead(fieldId) | platejs/field/react | Reads one field, its problems and whether it applies, and renders again when any of them changes. |
applyFieldValues(template, submissions, options?) | platejs/field | Checks each role's answers against the template, and returns the filled document with pending or the refusals. |
fieldSubmission(template, role, values, options?) | platejs/field | Builds one role's submission, keyed by fieldId, from a record keyed by field name. |
startFieldValues(template, submissions, start, options?) | platejs/field | Checks the submissions, and returns the document a role starts filling from with pending, or the refusals. |
readFieldAnswers(document, options?) | platejs/field | Reads a saved document's answers by role and name, each as a FieldAnswer. |
fitsField(field, value) | platejs/field | Whether a value fits a field's kind and options. |
fillsField(field, value) | platejs/field | Whether a value is a filled answer for a field. |
FIELD_TESTS | platejs/field | The tests a condition may use on each kind. |
FieldElement, FieldSettings, FieldPatch, FieldRead, FieldCondition, FieldProblem, FieldKind, FieldTest, FieldValue, FieldOption, FieldSubmission, FieldRefusal, FieldApplyResult, FieldAnswer | platejs/field | Field types. |
'use client';
import { BracesIcon } from 'lucide-react';
import { BaseFieldPlugin } from 'platejs/field';
import { useEditor, useEditorReadOnly, usePluginStore } from 'platejs/react';
import * as React from 'react';
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from '@/components/editor/dropdown-menu';
import { ToolbarButton } from '@/components/editor/toolbar';
const KINDS = [
{ kind: 'text', label: 'Text' },
{ kind: 'number', label: 'Number' },
{ kind: 'date', label: 'Date' },
{ kind: 'checkbox', label: 'Checkbox' },
{ kind: 'choice', label: 'Choice' },
{ kind: 'signature', label: 'Signature' },
] as const;
export function FieldToolbarButton() {
const editor = useEditor();
const readOnly = useEditorReadOnly();
const filling = usePluginStore(
BaseFieldPlugin,
(state) => state.fillRole != null
);
const [open, setOpen] = React.useState(false);
if (open && (readOnly || filling)) setOpen(false);
return (
<DropdownMenu open={open} onOpenChange={setOpen} modal={false}>
<DropdownMenuTrigger disabled={readOnly || filling}>
<ToolbarButton pressed={open} tooltip="Insert field" isDropdown>
<BracesIcon />
</ToolbarButton>
</DropdownMenuTrigger>
<DropdownMenuContent className="min-w-0" align="start">
{KINDS.map(({ kind, label }) => (
<DropdownMenuItem
key={kind}
className="min-w-[180px]"
finalFocus={() => editor.api.dom.focus()}
onSelect={() => {
const fields = editor.plugin(BaseFieldPlugin);
const role = fields.read.fields()[0]?.node.role ?? 'signer';
editor.update((tx) => {
tx.plugin(BaseFieldPlugin).insert(
{ kind, label, role },
{ select: true }
);
});
}}
>
{label}
</DropdownMenuItem>
))}
</DropdownMenuContent>
</DropdownMenu>
);
}import { CheckIcon } from 'lucide-react';
import { BaseFieldPlugin, fillsField } from 'platejs/field';
import { type EditorElementProps, EditorElement } from 'platejs/static';
import * as React from 'react';
export function FieldElementStatic(
props: EditorElementProps<typeof BaseFieldPlugin>
) {
const { element } = props;
const { kind, options, value } = element;
let shown: React.ReactNode = (
<span
aria-label="Blank"
className="inline-block h-4 w-24 border-b border-current"
role="img"
/>
);
if (kind === 'checkbox') {
shown = (
<span
aria-label={value === true ? 'Ticked' : 'Not ticked'}
className="inline-flex size-3.5 items-center justify-center rounded-[3px] border border-current align-middle"
role="img"
>
{value === true && <CheckIcon className="size-3" />}
</span>
);
} else if (fillsField(element, value)) {
shown =
kind === 'choice'
? options?.find((option) => option.value === value)?.label
: String(value);
}
return (
<EditorElement as="span" className="inline-block" {...props}>
{shown}
{props.children}
</EditorElement>
);
}
export const BaseFieldKit = [
BaseFieldPlugin.configure({ component: FieldElementStatic }),
];