Skip to content

Column editors ​

useTableEditable adds column configuration wiring on top of useTableEdit. It uses the same draft, error and saving state and renders the registered host controls through bodyCell; the base table does not enter editing mode automatically.

Registering controls ​

If your project already has Ant Design Vue installed, pass in the components you need:

ts
import { Input, Select, InputNumber, DatePicker, TimePicker } from 'ant-design-vue'
import { createAntdvTableControls } from '@vtable-guild/vtable-guild'

const controls = createAntdvTableControls({
  Input,
  Select,
  InputNumber,
  DatePicker,
  RangePicker: DatePicker.RangePicker,
  TimePicker,
})

Element Plus uses the same registry protocol:

ts
import {
  ElInput,
  ElSelect,
  ElOption,
  ElInputNumber,
  ElDatePicker,
  ElTimePicker,
} from 'element-plus'
import { createElementPlusTableControls } from '@vtable-guild/vtable-guild'

const controls = createElementPlusTableControls({
  Input: ElInput,
  Select: ElSelect,
  Option: ElOption,
  InputNumber: ElInputNumber,
  DatePicker: ElDatePicker,
  TimePicker: ElTimePicker,
})

These two factories only receive the components you pass in and do not import the UI library. The application imports the host component styles. The built-in wired types are text / textarea / select / enum / digit / money / date / dateRange / dateTime / dateTimeRange / time; queries and editing can share the same registry.

editor.valueType uses the extensible TableControlValueType. See Schema query control types for the complete built-in type table, common configuration, custom registration and differences from display types.

Date controls use formatted strings by default: YYYY-MM-DD for date, YYYY-MM-DD HH:mm:ss for dateTime and HH:mm:ss for time. Range types return an array of the two ends. Override this through fieldProps.valueFormat; set it explicitly to undefined to use the host's native date objects. Converting between the date object protocols of different UI libraries is up to the application.

The control value of Select uses an internal encoding, and the string, number or boolean identity is restored on update, so false, 'false', 1 and '1' are never confused. Clearing a single select normalizes the host's empty value to undefined. Multiple-select arrays are decoded item by item, so clearing to [] preserves the empty array. If the host instead returns a non-array empty value, it is normalized to undefined. Other value protocols such as labelInValue need a custom renderer.

Configuration and wiring ​

ts
import { ref } from 'vue'
import { useTableEditable, VTableEditCell, type TableColumnsType } from '@vtable-guild/vtable-guild'

interface Row {
  id: number
  name: string
  amount: number
  team: number
}
const rows = ref<Row[]>([{ id: 1, name: 'Item A', amount: 2, team: 1 }])
const columns: TableColumnsType<Row> = [
  {
    dataIndex: 'name',
    title: 'Name',
    editor: {
      validate: (value) =>
        typeof value === 'string' && value.trim() ? undefined : 'Please enter a name',
    },
  },
  {
    dataIndex: 'amount',
    title: 'Quantity',
    valueType: 'digit',
    editor: {
      valueType: 'digit',
      fieldProps: { min: 1 },
      disabled: ({ draft }) => draft.team === 2,
    },
  },
  {
    dataIndex: 'team',
    title: 'Team',
    valueEnum: { 1: 'Platform', 2: 'Trading' },
    editor: {
      valueType: 'select',
      options: [
        { value: 1, label: 'Platform' },
        { value: 2, label: 'Trading' },
      ],
    },
  },
]
const edit = useTableEditable({
  rowKey: 'id',
  mode: 'multiple',
  columns,
  controls,
  dataSource: rows,
  onChange: (value) => {
    rows.value = value
  },
  onSave: async (value) => value,
})
const { records } = edit
vue
<VTable :columns="columns" :data-source="records" row-key="id">
  <template #bodyCell="cell">
    <VTableEditCell v-if="edit.getCell(cell)" :edit="edit" :cell="cell" />
  </template>
</VTable>

In the template, VTableEditCell supplies the editor context and keeps the host control mounted while you type. A TSX bodyCell slot receives text and index. Pass those values as value and renderIndex as well when calling renderEditor. With Row, columns, edit and records from the example above, return the following renderTable function from the component's setup.

tsx
import { VTable, type TableBodyCellSlotProps } from '@vtable-guild/vtable-guild'

const bodyCell = (cell: TableBodyCellSlotProps<Row>) =>
  edit.renderEditor({ ...cell, value: cell.text, renderIndex: cell.index })

const renderTable = () => (
  <VTable<Row> rowKey="id" columns={columns} dataSource={records.value} v-slots={{ bodyCell }} />
)

When a cell has no editor, renderEditor returns undefined and the table renders its usual read-only content. The template's v-if="edit.getCell(cell)" preserves the same fallback. The application can handle its action column in bodyCell and use host buttons and confirmation dialogs to call start(record), save(key) and cancel(key). A column's customRender takes precedence over bodyCell.

A column with editor: false or no editor configuration keeps its read-only display. editor.editable / readonly / disabled accept booleans and callbacks that receive the row context. In the row editing example above, readonly or editable: false shows the read-only value, and disabled keeps the control and blocks updates. Conversion and validation still run for every field with an editor.

Click a cell to edit ​

Reuse rows, columns and controls from the example above. Replace the editing setup and template with the following.

ts
const edit = useTableEditable<Row>({
  trigger: 'click',
  rowKey: 'id',
  columns,
  controls,
  dataSource: rows,
  onChange: (value) => {
    rows.value = value
  },
})
const { records } = edit
vue
<VTable :columns="columns" :data-source="records" row-key="id">
  <template #bodyCell="cell">
    <VTableEditCell v-if="edit.getCell(cell) || edit.canEditCell(cell)" :edit="edit" :cell="cell" />
  </template>
</VTable>

canEditCell(cell) shows the edit button for eligible cells. getCell(cell) keeps the active control and its validation message visible. If editable becomes false or readonly / disabled becomes true during editing, the control blocks further input and shows a Cancel editing button. If the condition allows editing again, you can correct the current draft. If clearing the field itself triggered the restriction, cancel to restore the previous value and reopen the cell.

Layout stability ​

Entering edit mode keeps column widths and row heights unchanged by default. The editing cell keeps an invisible copy of the display content, which alone sizes the cell; the control is stacked over it and fills the column. A table with table-layout: auto therefore does not redistribute its columns when inputs appear, and rows are not stretched by the controls.

ts
const edit = useTableEditable<Row>({
  rowKey: 'id',
  columns,
  controls,
  layout: 'stable', // default; 'flow' lets the control size the cell
  errorPlacement: 'tooltip', // defaults to 'inline'
})
  • layout and errorPlacement are also props of VTableEditCell. They apply to that one cell and take precedence over the composable options.
  • With errorPlacement: 'inline' the error takes a line below the control, so a failing row grows taller while column widths stay the same. With 'tooltip' the error is shown in a tooltip while the cell is hovered or focused and the row height stays the same too; the message is still exposed to screen readers through role="alert".
  • The invisible copy renders the record as it was before editing, so the cell does not resize while the user types. The default slot of VTableEditCell is used for both the display state and the copy, so custom display content such as a tag belongs in the default slot rather than in a v-else branch:
vue
<VTableEditCell v-if="edit.getCell(cell)" :edit="edit" :cell="cell">
  <template #default="{ record }">
    <StatusTag :value="record.status" />
  </template>
</VTableEditCell>

Things to know before relying on it:

  • The display content is rendered a second time. The copy is aria-hidden, invisible and not interactive, but its components mount as usual. If the display content has side effects (requests, tracking), replace the copy with plain content through the sizer option in the third argument of renderEditor, or through the default slot.
  • The control is as wide as the display content, that is the column minus the inline padding of the cell. When that is less than --vtg-editor-min-inline-size (64px by default), the control grows into the inline padding, up to --vtg-editor-inset-inline (2px by default) from the cell edges. A column narrower than the padding and buttons of the control itself still cannot show the value after that: set width / minWidth on the column, or use layout="flow" for that cell. Columns that display one or two digits in auto layout are the usual case; the Element Plus number input reserves 84px for its two buttons, which fieldProps: { controls: false } removes.
  • The control cannot be taller than the row minus --vtg-editor-inset-block (2px by default) on each side. The default row heights of both presets fit the default host controls. Element Plus rows with size="small" are shorter and need small controls as well (fieldProps: { size: 'small' }). For multi-line input use the built-in textarea, see Multi-line text; use layout="flow" for other taller controls.
  • When you change the cell padding, override --vtg-table-cell-padding-block (vertical) and --vtg-table-cell-padding-inline (horizontal) to match, so the control can extend towards the cell edges correctly.
  • It relies on CSS contain: inline-size: Chrome / Edge 105, Safari 16 and Firefox 121 or later.

Multi-line text ​

When the text of a cell wraps, set its editor to the built-in textarea. The box fills the cell: it is as many lines tall as the displayed text, the text stays where it was and wraps at the same width, and neither the column width nor the row height changes.

ts
const columns = [
  {
    dataIndex: 'remark',
    title: 'Remark',
    width: 240,
    editor: { valueType: 'textarea' },
    // Keep the line breaks of the text when it is displayed
    customCell: () => ({ style: { whiteSpace: 'pre-line' } }),
  },
]
  • Enter breaks the line, Ctrl + Enter (⌘ + Enter on macOS) commits and Esc cancels. When cells are edited on click, leaving the box commits as well.
  • Text that outgrows the cell scrolls inside the box; after saving, the row height follows the new content.
  • Browsers collapse line breaks into spaces when displaying text. To show saved line breaks as typed, set white-space: pre-line on the column through customCell, as in the example.
  • While editing, the box defaults to rows: 1, so in an empty cell it is as tall as a single-line input. A larger rows or autoSize in fieldProps can make the box taller than its cell, and the row then grows when editing starts.
  • Ant Design Vue uses Input.TextArea and Element Plus uses ElInput with type="textarea". Pass TextArea to the control factory to use another component.

A multi-line control you register yourself fills its cell too when it carries fill: true:

ts
const controls = {
  ...createAntdvTableControls({ Input, Select, InputNumber, DatePicker }),
  markdown: Object.assign(
    (field: TableControlContext) => h(MarkdownInput, { ...field.fieldProps }),
    {
      fill: true,
    },
  ),
}

fill lays the layer that holds the control over the whole cell, leaving the editor inset on each side; direct children of that layer and textarea elements follow. Controls with another structure have to set height: 100% themselves.

Conversion, linkage and validation ​

convertValue(value, context) converts a source value into a control value when editing starts. In click mode, function-based editable, readonly, and disabled conditions also receive the converted field and row. Open rows reuse their current drafts. Each validateAll() run creates temporary drafts for the remaining source rows. transform(value, context) produces the submitted value from a draft snapshot and preserves the value the user is typing.

dataIndex: ['profile', 'name'] supports nested fields. A string dataIndex is read as the complete field name, consistent with the read-only table. Updates run on an isolated draft with a stable row key. When records contain mutable class instances, use clone(record) to define the snapshot behavior. For classes with private fields, isDraftEqual(draft, baseline) can compare the entire row, including linked fields. Return true when the draft matches the row as it was when the cell opened.

onValueChange(value, context) can return a Partial<Row> to update other linked fields; one input updates the draft only once. The context contains key / column / name / value / draft / original / isNew, where draft and original are isolated copies.

Saving first runs the column validate; once the field rules pass, it runs the row-level validate you passed in once, then performs the submission transform and onSave. A string returned by field validation is shown below the control; row-level validation can return { message, fields }, where fields uses dot-separated field paths. When wiring a host form, put the form's validate in the row-level validate to avoid validating again in onSave. On failure the draft is kept, and savingKeys / cancellingKeys disable the controls of the current row.

In click mode, commitCell(key) validates the active column and save(key) validates the whole row. If a blur commit is still validating, a concurrent save(key) checks the remaining columns before calling onSave. If the cell has already called onSave, the table accepts the confirmed record and its key. A failed whole-row check returns undefined to the row caller and exposes the validation error in errors.

If you replace the reactive column configuration while editing, commitCell(key) looks up the latest validation rule by column key and field path. Removing the column or its editor, or binding the column to a different field, makes the commit cancel the cell edit. A row that was already being edited returns to the draft it had when the cell opened.

getCell(context) returns the complete control context and supports custom controls and slots. To register an application type, just return a VNode:

ts
import { h } from 'vue'
import type { TableControls } from '@vtable-guild/vtable-guild'

const extendedControls: TableControls = {
  ...controls,
  project: (field) =>
    h(ProjectSelect, {
      modelValue: field.value,
      'onUpdate:modelValue': field.onChange,
      disabled: field.disabled,
    }),
}

editor.dictionary can connect to Remote dictionaries, which automatically provides loading, options and remote search and keeps the selected labels. Dependency parameters are defined when the dictionary subscription is created; whether an application value is cleared or kept is decided by the application's linkage rules. An explicit editor.options takes precedence over the dictionary's candidates, including an empty array; when neither options nor dictionary is specified, options are generated only from the string labels of the same column's valueEnum. Numeric, boolean-text and VNode labels need explicit options or a custom control.

Controls, errors and spacing are configured through the table's editCell / editControl / editError slots and the --vtg-editor-* variables, and work with both presets. A regular table only gains the column type declarations; it creates no editors, forms or watchers.

For submitting once from an external master form, validating all drafts without saving, adding rows at the top or bottom and row count limits, see Detail forms.

API ​

Column fields ​

FieldTypeDefaultDescription
valueTypestring-Specifies a built-in field render type or a registered custom type.
fieldPropsTableFieldProps | ((context: CustomRenderContext<TRecord>) => TableFieldProps)-Configures the field renderer. Accepts an object or a function that returns the configuration from the cell context.
editorfalse | TableColumnEditor<TRecord>-Configures the column editor. Read by useTableEditable to connect host controls and row drafts.

useTableEditable configuration ​

useTableEditable<TRecord>(options) inherits every UseTableEditOptions<TRecord> option except toDraft / toValue, including rowKey, mode, dataSource, onChange, validation and save callbacks. See useTableEdit API for all row-level options; use column editor.convertValue / transform for value conversion. The additional options are listed below.

OptionTypeDefaultDescription
columnsMaybeRefOrGetter<ColumnsType<TRecord>>RequiredColumns with an editor config.
controlsMaybeRefOrGetter<TableControls>RequiredMap of host editing controls.
trigger'manual' | 'click''manual'Editing trigger mode: manual for row editing, click for hover-hinted cell editing.
showRowErrorbooleantrueWhether to fall back to row-level save/cancel errors inside the active cell in cell-trigger mode.
layout'stable' | 'flow''stable'How an editing cell takes part in layout: stable stacks the control over the display content so column widths and row heights stay unchanged, flow lets the control size the cell.
errorPlacement'inline' | 'tooltip''inline'Where a field error is shown: inline takes a line below the control and makes the row taller, tooltip shows it while the cell is hovered or focused and keeps the row height.
isDraftEqual(draft: TRecord, baseline: TRecord) => boolean-Compare the full draft with the row snapshot taken when the cell opened. Return true to skip saving. Use this for domain types with private state.
uiPartial<Record<TableEditCellUiSlots, string>>-Overrides the classes of the edit cell, control container, error message and click trigger.

useTableEditable return value ​

The return value includes all useTableEdit state and methods, such as isEditing(key), start(record), save(key), getValues() and validateAll(), plus the cell editing APIs below.

MethodTypeDescription
trigger'manual' | 'click'Active editing trigger mode.
layout'stable' | 'flow'Resolved edit layout.
errorPlacement'inline' | 'tooltip'Resolved field error placement.
activeCellsComputedRef<ReadonlyMap<Key, TableEditableActiveCell>>Active cell sessions per row in click-to-edit mode.
canEditCell(context: Pick<CustomRenderContext<TRecord>, 'record' | 'column'>) => booleanWhether a cell can enter click-to-edit mode (evaluates editor, editable, readonly and disabled).
startCell(record: TRecord, column: ColumnType<TRecord>) => Promise<boolean>Activate editing for a specific cell after committing any competing active cell.
commitCell(key: Key, column?: ColumnType<TRecord>) => Promise<boolean>Commit an active cell; unchanged row drafts exit cleanly without calling onSave.
cancelCell(key: Key, column?: ColumnType<TRecord>) => Promise<boolean>Cancel an active cell while preserving borrowed drafts or cached additions.
uiPartial<Record<TableEditCellUiSlots, string>> | undefinedSlot class overrides forwarded to edit cells and triggers.
getCell(context: Pick<CustomRenderContext<TRecord>, 'record' | 'column'>) => TableEditableCellContext<TRecord> | undefinedRead an editor control context. Returns undefined when there is no draft, editor or dataIndex, or editable=false or readonly=true, preserving the readonly display.
renderEditor(context: CustomRenderContext<TRecord>, ui?: Partial<Record<TableEditCellUiSlots, string>>, options?: TableEditRenderOptions<TRecord>) => VNodeChildRender the registered host editor. The third argument overrides layout and errorPlacement for one cell and customizes the hidden layer through sizer. In a TSX bodyCell slot, pass { ...cell, value: cell.text, renderIndex: cell.index }. Returns undefined without an editor context so the table can render the read-only cell.

TableEditableCellContext ​

getCell(context) returns a control context with the following fields. Custom controls read value / fieldProps / options and call onChange to update the draft.

FieldTypeDescription
keyKeyThe stable key of the editing row.
columnTableColumnType<TRecord>The current column definition.
draftTRecordAn isolated row draft copy; apply edits through onChange or setDraft.
valueTypeTableControlValueTypeThe control key derived from editor, enum or display type metadata.
valueunknownThe current field draft value.
onChange(value: unknown) => voidUpdate the field and run editor.onValueChange; disabled controls ignore updates.
onSearch((keyword: string) => void) | undefinedRemote search when a dictionary is connected.
fieldPropsRecord<string, unknown>Resolved host control props.
optionsreadonly TableDictionaryOption[]Explicit options, dictionary candidates or enum-derived options, including known selected labels.
disabledbooleanTrue when the column is disabled or the row is being saved or cancelled.
readonlybooleanShared control protocol field; editing contexts returned by getCell use false, while readonly fields retain display rendering.
loadingbooleanDictionary loading state; false without a dictionary.
errorstring | undefinedValidation error for the current field, or row-level fallback error in cell-trigger mode.
idstring | undefinedOptional ID in the shared control protocol; current column editor wiring does not populate it.
namestring | undefinedThe field path; array dataIndex values use dot-separated paths.
mode'query' | 'edit'Shared control protocol field; column editing uses edit.
lightFilter{ grouped: boolean; getPopupContainer: () => HTMLElement } | undefinedShared filter popup context; current column editor wiring does not populate it.
cellEditTableControlCellEditBridge | undefinedCommit, cancel and popup-state bridge injected in click-to-edit mode.
autoFocusTokennumber | undefinedSingle-shot focus token for freshly activated cells so remounts never steal focus.
consumeAutoFocus((token: number) => boolean) | undefinedConsumes the single-shot focus token, returning true only once.

VTableEditCell Props ​

Pass the complete bodyCell context in templates. Row editing uses v-if="edit.getCell(cell)". Click editing uses v-if="edit.getCell(cell) || edit.canEditCell(cell)" to mount both the active editor and the edit buttons.

PropTypeDefaultDescription
editPick<UseTableEditableReturn<TRecord>, 'renderEditor'> & Partial<Pick<UseTableEditableReturn<TRecord>, 'trigger' | 'layout' | 'errorPlacement' | 'getCell' | 'canEditCell' | 'startCell' | 'ui'>>RequiredThe useTableEditable return value, or an object implementing the same renderEditor protocol.
cellTableBodyCellSlotProps<TRecord>RequiredThe complete VTable bodyCell slot context. The bridge maps text/index to the editor renderer value/renderIndex.
emptyTextstring-Fallback text for empty cells in click-to-edit trigger display.
editIconbooleantrueWhether to display the edit icon on hover or focus.
layout'stable' | 'flow'-Overrides the layout of useTableEditable for this cell.
errorPlacement'inline' | 'tooltip'-Overrides the errorPlacement of useTableEditable for this cell.
uiPartial<Record<TableEditCellUiSlots, string>>-Overrides the edit cell or trigger slot classes for this cell.

TableColumnEditor ​

FieldTypeDefaultDescription
valueTypeTableControlValueTypeinferred from columnSelects a registered editing control. When unset, it is 'select' if the column has valueEnum, otherwise the column's valueType, and 'text' when neither exists.
editableboolean | ((context: TableEditableFieldContext<TRecord>) => boolean)trueKeeps the read-only cell when it returns false.
readonlyboolean | ((context: TableEditableFieldContext<TRecord>) => boolean)falseKeeps the read-only cell when true.
disabledboolean | ((context: TableEditableFieldContext<TRecord>) => boolean)falseKeeps the editing control and blocks updates.
fieldPropsTableColumnEditor<TRecord>['fieldProps']{}Props passed to the host control, or a function computing them from the row context.
optionsMaybeRefOrGetter<readonly TableDictionaryOption[]>dictionary or column enumExplicit options. When unset, the dictionary options are used, then the column's valueEnum.
dictionaryTableDictionaryBinding-Provides dictionary options, loading state and search.
convertValueTableColumnEditor<TRecord>['convertValue']-Converts source values when editing starts. Rows without drafts also use this conversion for function-based edit conditions and validateAll().
transformTableColumnEditor<TRecord>['transform']-Produces the submit value from the draft snapshot; the current control value is kept.
validateTableColumnEditor<TRecord>['validate']-Validates the field synchronously or asynchronously. The draft is kept when an error message is returned.
onValueChangeTableColumnEditor<TRecord>['onValueChange']-May return a patch updating other fields.

Theming ​

Use the per-instance ui or the global theme.table.slots to adjust the editing area. The appearance of host controls follows their UI library.

ui slots ​

SlotDescription
editCellContent container of a cell that has entered editing.
editSizerHidden copy of the display content that sizes an editing cell in stable layout.
editControlWidth and error outline of the host control.
editErrorValidation error located by field.
editTriggerInteractive trigger button for click-to-edit cells.
editTriggerValueDisplay text wrapper inside the click-to-edit cell trigger.
editTriggerIconEdit icon wrapper revealed on cell hover or focus.

Preset defaults ​

ts
createVTableGuild({
  theme: {
    table: {
      slots: {
        editCell: 'min-w-0 data-[vtg-edit-layout=stable]:relative data-[vtg-edit-layout=stable]:flex data-[vtg-edit-layout=stable]:flex-1 data-[vtg-edit-layout=stable]:flex-wrap data-[vtg-edit-layout=stable]:items-center',
        editSizer: 'basis-full shrink-0 min-w-0 invisible pointer-events-none data-[vtg-edit-strut=true]:basis-0',
        editControl: 'min-w-0 [&>*]:w-full [&[data-vtg-edit-error=tooltip]>span>*]:w-full data-[vtg-edit-layout=stable]:basis-full data-[vtg-edit-layout=stable]:shrink-0 data-[vtg-edit-layout=stable]:[margin-inline-start:-100%] data-[vtg-edit-layout=stable]:[contain:inline-size] [&[data-vtg-edit-layout=stable]:not([data-vtg-edit-fill])]:[--vtg-edit-bleed-inline:clamp(0px,calc((var(--vtg-editor-min-inline-size)_-_100%)_/_2),max(0px,var(--vtg-table-cell-padding-inline)_-_var(--vtg-editor-inset-inline)))] [&[data-vtg-edit-fill=true]:not([data-vtg-edit-bleed])]:[--vtg-edit-bleed-inline:max(0px,var(--vtg-table-cell-padding-inline)_-_var(--vtg-editor-inset-inline))] [&[data-vtg-edit-layout=stable]>*]:mx-[calc(-1_*_var(--vtg-edit-bleed-inline,0px))] [&[data-vtg-edit-layout=stable]>*]:w-[calc(100%_+_2_*_var(--vtg-edit-bleed-inline,0px))] [&[data-vtg-edit-fill=true]:not([data-vtg-edit-bleed])>*]:!mx-[calc(-1_*_var(--vtg-edit-bleed-inline,0px))] [&[data-vtg-edit-fill=true]:not([data-vtg-edit-bleed])>*]:!w-[calc(100%_+_2_*_var(--vtg-edit-bleed-inline,0px))] data-[vtg-edit-bleed=true]:my-[calc(var(--vtg-editor-inset-block)_-_var(--vtg-table-cell-padding-block))] data-[vtg-edit-fill=true]:self-stretch [&[data-vtg-edit-fill=true]_textarea]:!max-w-none [&[data-vtg-edit-fill=true][data-vtg-edit-bleed=true]]:absolute [&[data-vtg-edit-fill=true][data-vtg-edit-bleed=true]]:!m-0 [&[data-vtg-edit-fill=true][data-vtg-edit-bleed=true]]:[inset-inline:calc(-1_*_max(0px,var(--vtg-table-cell-padding-inline)_-_var(--vtg-editor-inset-inline)))] [&[data-vtg-edit-fill=true][data-vtg-edit-bleed=true]]:[inset-block:calc(var(--vtg-editor-inset-block)_-_var(--vtg-table-cell-padding-block))] [&[data-vtg-edit-fill=true]>*]:h-full [&[data-vtg-edit-fill=true][data-vtg-edit-error=tooltip]>span>*]:h-full [&[data-vtg-edit-fill=true]_textarea]:!h-full [&[data-vtg-edit-fill=true]_textarea]:!resize-none [&[data-vtg-edit-fill=true]_textarea]:![line-height:inherit] [&[data-vtg-edit-fill=true][data-vtg-edit-bleed=true]_textarea]:!py-[calc(var(--vtg-table-cell-padding-block)_-_var(--vtg-editor-inset-block)_-_1px)] [&[data-vtg-edit-fill=true]_textarea]:!px-[calc(var(--vtg-table-cell-padding-inline)_-_var(--vtg-editor-inset-inline)_-_1px)]',
        editError: 'block mt-[var(--vtg-editor-error-gap)] text-[length:var(--vtg-editor-error-font-size)] text-[color:var(--vtg-cell-error)] data-[vtg-edit-layout=stable]:basis-full data-[vtg-edit-layout=stable]:min-w-0 data-[vtg-edit-layout=stable]:whitespace-normal data-[vtg-edit-layout=stable]:[contain:inline-size] data-[vtg-edit-error=tooltip]:sr-only',
        editTrigger: 'group/edit-trigger flex w-full min-w-0 items-center gap-1.5 border-0 bg-transparent p-0 [text-align:inherit] [font:inherit] text-inherit cursor-pointer focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-[color:var(--color-primary)]',
        editTriggerValue: 'block min-w-0 flex-1',
        editTriggerIcon: 'shrink-0 text-[color:var(--color-primary)] opacity-0 transition-opacity group-hover/cell:opacity-100 group-hover/edit-trigger:opacity-100 group-focus-visible/edit-trigger:opacity-100',
      },
    },
  },
})
ts
createVTableGuild({
  themePreset: 'element-plus',
  theme: {
    table: {
      slots: {
        editCell: 'min-w-0 data-[vtg-edit-layout=stable]:relative data-[vtg-edit-layout=stable]:flex data-[vtg-edit-layout=stable]:flex-1 data-[vtg-edit-layout=stable]:flex-wrap data-[vtg-edit-layout=stable]:items-center',
        editSizer: 'basis-full shrink-0 min-w-0 invisible pointer-events-none data-[vtg-edit-strut=true]:basis-0',
        editControl: 'min-w-0 [&>*]:w-full [&[data-vtg-edit-error=tooltip]>span>*]:w-full [&[data-invalid=true]>*]:outline [&[data-invalid=true]>*]:outline-1 [&[data-invalid=true]>*]:outline-[color:var(--vtg-cell-error)] [&[data-invalid=true]>*]:rounded-[var(--vtg-editor-radius)] data-[vtg-edit-layout=stable]:basis-full data-[vtg-edit-layout=stable]:shrink-0 data-[vtg-edit-layout=stable]:[margin-inline-start:-100%] data-[vtg-edit-layout=stable]:[contain:inline-size] [&[data-vtg-edit-layout=stable]:not([data-vtg-edit-fill])]:[--vtg-edit-bleed-inline:clamp(0px,calc((var(--vtg-editor-min-inline-size)_-_100%)_/_2),max(0px,var(--vtg-table-cell-padding-inline)_-_var(--vtg-editor-inset-inline)))] [&[data-vtg-edit-fill=true]:not([data-vtg-edit-bleed])]:[--vtg-edit-bleed-inline:max(0px,var(--vtg-table-cell-padding-inline)_-_var(--vtg-editor-inset-inline))] [&[data-vtg-edit-layout=stable]>*]:mx-[calc(-1_*_var(--vtg-edit-bleed-inline,0px))] [&[data-vtg-edit-layout=stable]>*]:w-[calc(100%_+_2_*_var(--vtg-edit-bleed-inline,0px))] [&[data-vtg-edit-fill=true]:not([data-vtg-edit-bleed])>*]:!mx-[calc(-1_*_var(--vtg-edit-bleed-inline,0px))] [&[data-vtg-edit-fill=true]:not([data-vtg-edit-bleed])>*]:!w-[calc(100%_+_2_*_var(--vtg-edit-bleed-inline,0px))] data-[vtg-edit-bleed=true]:my-[calc(var(--vtg-editor-inset-block)_-_var(--vtg-table-cell-padding-block))] data-[vtg-edit-fill=true]:self-stretch [&[data-vtg-edit-fill=true]_textarea]:!max-w-none [&[data-vtg-edit-fill=true][data-vtg-edit-bleed=true]]:absolute [&[data-vtg-edit-fill=true][data-vtg-edit-bleed=true]]:!m-0 [&[data-vtg-edit-fill=true][data-vtg-edit-bleed=true]]:[inset-inline:calc(-1_*_max(0px,var(--vtg-table-cell-padding-inline)_-_var(--vtg-editor-inset-inline)))] [&[data-vtg-edit-fill=true][data-vtg-edit-bleed=true]]:[inset-block:calc(var(--vtg-editor-inset-block)_-_var(--vtg-table-cell-padding-block))] [&[data-vtg-edit-fill=true]>*]:h-full [&[data-vtg-edit-fill=true][data-vtg-edit-error=tooltip]>span>*]:h-full [&[data-vtg-edit-fill=true]_textarea]:!h-full [&[data-vtg-edit-fill=true]_textarea]:!resize-none [&[data-vtg-edit-fill=true]_textarea]:![line-height:inherit] [&[data-vtg-edit-fill=true][data-vtg-edit-bleed=true]_textarea]:!py-[calc(var(--vtg-table-cell-padding-block)_-_var(--vtg-editor-inset-block))] [&[data-vtg-edit-fill=true]_textarea]:!px-[calc(var(--vtg-table-cell-padding-inline)_-_var(--vtg-editor-inset-inline))]',
        editError: 'block mt-[var(--vtg-editor-error-gap)] text-[length:var(--vtg-editor-error-font-size)] text-[color:var(--vtg-cell-error)] data-[vtg-edit-layout=stable]:basis-full data-[vtg-edit-layout=stable]:min-w-0 data-[vtg-edit-layout=stable]:whitespace-normal data-[vtg-edit-layout=stable]:[contain:inline-size] data-[vtg-edit-error=tooltip]:sr-only',
        editTrigger: 'group/edit-trigger flex w-full min-w-0 items-center gap-1.5 border-0 bg-transparent p-0 [text-align:inherit] [font:inherit] text-inherit cursor-pointer focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-[color:var(--color-primary)]',
        editTriggerValue: 'block min-w-0 flex-1',
        editTriggerIcon: 'shrink-0 text-[color:var(--color-primary)] opacity-0 transition-opacity group-hover/cell:opacity-100 group-hover/edit-trigger:opacity-100 group-focus-visible/edit-trigger:opacity-100',
      },
    },
  },
})

CSS variables ​

VariablePurposeantdvelement-plus
--vtg-cell-errorField error status color; also used for query and editing validation text#ff4d4f#f56c6c
--vtg-editor-inset-blockMinimum gap between the control and the row edges in stable layout2px2px
--vtg-editor-inset-inlineMinimum gap between a control that grows into the cell padding and the cell edges in stable layout2px2px
--vtg-editor-min-inline-sizePreferred minimum control width in stable layout; a narrower control grows into the inline cell padding64px64px
--vtg-editor-error-gapGap between the control and the error text2px2px
--vtg-editor-error-font-sizeError font size14px12px
--vtg-editor-radiusOutline radius of the editing controlnot read4px

Type Declarations ​

View type declarations
ts
export {
  VTableEditCell,
  createAntdvTableControls,
  createElementPlusTableControls,
} from '@vtable-guild/vtable-guild'

export declare function useTableEdit<TRecord extends object>(
  options: UseTableEditOptions<TRecord>,
): UseTableEditReturn<TRecord>

export interface TableEditContext<TRecord extends object> {
  key: Key
  /** Snapshot from start(); undefined for a cached addition until it is saved. */
  original: TRecord | undefined
  isNew: boolean
  signal: AbortSignal
}

export type TableEditDraftContext<TRecord extends object> = Omit<
  TableEditContext<TRecord>,
  'signal'
>

export interface TableEditAddConfig {
  position?: 'top' | 'bottom'
  /** Cache until saved (default), or immediately insert into the controlled source. */
  mode?: 'cache' | 'source'
}

export interface TableEditValidationErrors {
  message?: string
  /** Field names or business-defined nested field paths. */
  fields?: Record<string, string>
}

export interface TableEditError extends TableEditValidationErrors {
  type: 'validation' | 'save' | 'cancel'
  message: string
  cause?: unknown
}

export interface TableEditValidationResult<TRecord extends object> {
  valid: boolean
  /** Submitted snapshots from this validation; absent for failures or obsolete work. */
  values?: TRecord[]
  errors: ReadonlyMap<Key, TableEditError>
  obsolete?: boolean
}

export interface UseTableEditOptions<TRecord extends object> {
  /** A stable key is required; row indexes are intentionally unsupported. */
  rowKey: keyof TRecord | ((record: TRecord) => Key)
  /** Defaults to single. Starting another row in single mode returns false. */
  mode?: 'single' | 'multiple'
  /** Override when records contain mutable class instances. */
  clone?: (record: TRecord) => TRecord
  /** Optional controlled source. Parent updates never replace an open local draft. */
  dataSource?: MaybeRefOrGetter<readonly TRecord[]>
  /** Commit notifications only; draft keystrokes never write back into the source. */
  onChange?: (records: TRecord[]) => void
  /** Convert a record when editing starts and when validateAll() validates a row without a draft. */
  toDraft?: (record: TRecord, context: TableEditDraftContext<TRecord>) => TRecord
  /** Convert an editor snapshot when saving or obtaining submitted values. */
  toValue?: (draft: TRecord, context: TableEditContext<TRecord>) => TRecord
  /** Used by add() when no explicit record is supplied. */
  createRecord?: () => TRecord
  /** Maximum client-held rows, including cached additions. Finite limits round down to an integer. */
  maxRows?: number
  /** Return errors to keep the draft open, or void to continue saving. */
  validate?: (
    draft: TRecord,
    context: TableEditContext<TRecord>,
  ) => TableEditValidationErrors | void | Promise<TableEditValidationErrors | void>
  /**
   * Return a canonical record, true/void to accept the submitted value, or false to keep editing.
   * With dataSource and onChange, return the saved record here and update the source in onChange.
   */
  onSave?: (
    draft: TRecord,
    context: TableEditContext<TRecord>,
  ) => TRecord | void | boolean | Promise<TRecord | void | boolean>
  /** Returning false or rejecting keeps the draft open. Cancellation aborts a pending save first. */
  onCancel?: (
    draft: TRecord,
    context: TableEditContext<TRecord>,
  ) => void | boolean | Promise<void | boolean>
  onError?: (error: TableEditError, key: Key) => void
}

export interface UseTableEditReturn<TRecord extends object> {
  /** Controlled source overlaid with local drafts and positioned cached additions. */
  records: ComputedRef<TRecord[]>
  validating: ComputedRef<boolean>
  editableKeys: ComputedRef<readonly Key[]>
  savingKeys: ComputedRef<ReadonlySet<Key>>
  cancellingKeys: ComputedRef<ReadonlySet<Key>>
  errors: ComputedRef<ReadonlyMap<Key, TableEditError>>
  /** Unsaved cache-mode additions. Source-mode additions are committed through onChange. */
  newRecords: ComputedRef<TRecord[]>
  isEditing: (key: Key) => boolean
  /** Returns an isolated copy. Use setDraft() to apply changes. */
  getDraft: (key: Key) => TRecord | undefined
  /** Source snapshot captured when editing began; undefined for cached additions or missing sessions. */
  getOriginal: (key: Key) => TRecord | undefined
  getDrafts: () => ReadonlyMap<Key, TRecord>
  /** Source records plus converted draft snapshots; never calls onSave or onChange. */
  getValues: () => TRecord[]
  /** Validate all client-held rows, including unmounted virtual rows, without saving. */
  validateAll: () => Promise<TableEditValidationResult<TRecord>>
  /** Abort operations and discard drafts/errors, retaining the current controlled source. */
  reset: () => void
  start: (record: TRecord) => boolean
  add: (record?: TRecord, config?: TableEditAddConfig) => boolean
  setDraft: (key: Key, patch: Partial<TRecord> | ((draft: TRecord) => TRecord)) => boolean
  /** Resolves undefined on validation/save failure, cancellation, or disposal. */
  save: (key: Key) => Promise<TRecord | undefined>
  cancel: (key: Key) => Promise<boolean>
  cancelAll: () => Promise<boolean[]>
}


export declare function useTableEditable<T extends object>(
  options: UseTableEditableOptions<T>,
): UseTableEditableReturn<T>

export interface TableEditableFieldContext<TRecord extends object> {
  key: Key
  name: string
  column: ColumnType<TRecord>
  draft: TRecord
  original?: TRecord
  value: unknown
  isNew: boolean
}
export interface TableColumnEditor<TRecord extends object> {
  /** Select a built-in or custom host control; omission uses the column's inferred control. */
  valueType?: TableControlValueType
  editable?: boolean | ((context: TableEditableFieldContext<TRecord>) => boolean)
  readonly?: boolean | ((context: TableEditableFieldContext<TRecord>) => boolean)
  disabled?: boolean | ((context: TableEditableFieldContext<TRecord>) => boolean)
  fieldProps?:
    | Record<string, unknown>
    | ((context: TableEditableFieldContext<TRecord>) => Record<string, unknown>)
  options?: MaybeRefOrGetter<readonly TableDictionaryOption[]>
  dictionary?: TableDictionaryBinding
  /** Convert source values for editing, dynamic entry conditions, and validation of undrafted rows. */
  convertValue?: (value: unknown, context: TableEditableFieldContext<TRecord>) => unknown
  /** Applied to a draft snapshot for saving/getValues, without rewriting the editor value. */
  transform?: (value: unknown, context: TableEditableFieldContext<TRecord>) => unknown
  validate?: (
    value: unknown,
    context: TableEditableFieldContext<TRecord> & { signal: AbortSignal },
  ) => string | void | Promise<string | void>
  /** A linked-field patch after the current field changes. */
  onValueChange?: (
    value: unknown,
    context: TableEditableFieldContext<TRecord>,
  ) => Partial<TRecord> | void
}
export type TableEditTrigger = 'manual' | 'click'

/**
 * - 'stable': the control is stacked over the display content, so entering edit mode
 *   changes neither the column width nor the row height.
 * - 'flow': the control takes part in layout with its own size.
 */
export type TableEditLayout = 'stable' | 'flow'

/**
 * - 'inline': the error takes a line below the control and makes the row taller.
 * - 'tooltip': the error is shown in a tooltip while the cell is hovered or focused.
 */
export type TableEditErrorPlacement = 'inline' | 'tooltip'

export interface TableEditRenderOptions<TRecord extends object> {
  /** Overrides the layout configured on useTableEditable for this cell. */
  layout?: TableEditLayout
  /** Overrides the error placement configured on useTableEditable for this cell. */
  errorPlacement?: TableEditErrorPlacement
  /**
   * Content of the hidden layer that keeps the cell at its display size in 'stable' layout.
   * Receives the cell as it was displayed before editing; defaults to the column's display rendering.
   */
  sizer?: (cell: TableBodyCellSlotProps<TRecord>) => VNodeChild
}

export interface TableEditableActiveCell {
  key: Key
  /** Stable column key (explicit column.key or normalized dataIndex key). */
  columnKey: Key
  /** Normalized field name matching TableEditableFieldContext.name and errors.fields keys. */
  name: string
}

export type TableEditCellUiSlots =
  | 'editCell'
  | 'editSizer'
  | 'editControl'
  | 'editError'
  | 'editTrigger'
  | 'editTriggerValue'
  | 'editTriggerIcon'

export interface TableEditableCellContext<TRecord extends object> extends TableControlContext {
  key: Key
  column: ColumnType<TRecord>
  draft: TRecord
  valueType: TableControlValueType
  /** Present for freshly activated cells so the editor focuses once without stealing focus on remounts. */
  autoFocusToken?: number
  consumeAutoFocus?: (token: number) => boolean
}
export interface UseTableEditableOptions<TRecord extends object> extends Omit<
  UseTableEditOptions<TRecord>,
  'toDraft' | 'toValue'
> {
  columns: MaybeRefOrGetter<ColumnsType<TRecord>>
  controls: MaybeRefOrGetter<TableControls>
  /**
   * Editing trigger mode:
   * - 'manual' (default): row-level editing via start() / save() / cancel().
   * - 'click': cell-level hover hint and click-to-edit managed through VTableEditCell.
   */
  trigger?: TableEditTrigger
  /** Show row-level save/cancel/validation message inside the active cell in cell-trigger mode. Defaults to true. */
  showRowError?: boolean
  /**
   * How an editing cell takes part in table layout:
   * - 'stable' (default): keeps the display size of the cell while editing.
   * - 'flow': sizes the cell by its control.
   */
  layout?: TableEditLayout
  /**
   * Where a field error is shown:
   * - 'inline' (default): below the control, which makes the row taller.
   * - 'tooltip': in a tooltip, leaving the row height unchanged.
   */
  errorPlacement?: TableEditErrorPlacement
  /** Compare the full edited row with its baseline, including domain-specific private state. */
  isDraftEqual?: (draft: TRecord, baseline: TRecord) => boolean
  ui?: Partial<Record<TableEditCellUiSlots, string>>
}
export interface UseTableEditableReturn<
  TRecord extends object,
> extends UseTableEditReturn<TRecord> {
  trigger: TableEditTrigger
  /** Resolved edit layout. */
  layout: TableEditLayout
  /** Resolved error placement. */
  errorPlacement: TableEditErrorPlacement
  /** Active cell sessions keyed by row key (empty in 'manual' mode). */
  activeCells: ComputedRef<ReadonlyMap<Key, TableEditableActiveCell>>
  /** Whether a cell can enter click-to-edit mode (checks editor, editable, readonly and disabled). */
  canEditCell: (context: Pick<CustomRenderContext<TRecord>, 'record' | 'column'>) => boolean
  /** Activate a specific cell for editing, committing any competing active cell first. */
  startCell: (record: TRecord, column: ColumnType<TRecord>) => Promise<boolean>
  /** Commit an active cell; unchanged drafts exit cleanly without calling onSave. */
  commitCell: (key: Key, column?: ColumnType<TRecord>) => Promise<boolean>
  /** Cancel an active cell, preserving borrowed drafts or cached additions. */
  cancelCell: (key: Key, column?: ColumnType<TRecord>) => Promise<boolean>
  /** Optional ui overrides configured on useTableEditable. */
  ui?: Partial<Record<TableEditCellUiSlots, string>>
  getCell: (
    context: Pick<CustomRenderContext<TRecord>, 'record' | 'column'>,
  ) => TableEditableCellContext<TRecord> | undefined
  /** Return from bodyCell; undefined retains VTable's normal readonly rendering. */
  renderEditor: (
    context: CustomRenderContext<TRecord>,
    ui?: Partial<Record<TableEditCellUiSlots, string>>,
    options?: TableEditRenderOptions<TRecord>,
  ) => VNodeChild
}

/** Documentation helper for VTableEditCell props; this interface is not a package export. */
export interface VTableEditCellProps<TRecord extends object = Record<string, unknown>> {
  edit: Pick<UseTableEditableReturn<TRecord>, 'renderEditor'> &
    Partial<
      Pick<
        UseTableEditableReturn<TRecord>,
        'trigger' | 'layout' | 'errorPlacement' | 'getCell' | 'canEditCell' | 'startCell' | 'ui'
      >
    >
  cell: TableBodyCellSlotProps<TRecord>
  emptyText?: string
  editIcon?: boolean
  /** Overrides the layout configured on useTableEditable for this cell. */
  layout?: TableEditLayout
  /** Overrides the error placement configured on useTableEditable for this cell. */
  errorPlacement?: TableEditErrorPlacement
  ui?: Partial<Record<TableEditCellUiSlots, string>>
}

/** Documentation helper for VTableEditShell props; this interface is not a package export. */
export interface VTableEditShellProps<TRecord extends object = Record<string, unknown>> {
  /** The bodyCell slot context of the cell being edited. */
  cell: TableBodyCellSlotProps<TRecord>
  /** The record as it was before editing, e.g. edit.getOriginal(key). Defaults to cell.record. */
  original?: TRecord
  layout?: TableEditLayout
  /** Stretch the control to the height of the cell; for a multi-line control such as a textarea. */
  fill?: boolean
  error?: string
  errorPlacement?: TableEditErrorPlacement
  ui?: Partial<Record<TableEditCellUiSlots, string>>
}