Detail forms
Both useTableEdit and useTableEditable can connect to a controlled array of detail rows. The parent form holds the committed source records, while row input stays in the table drafts; a full submission can collect drafts that have not been saved row by row yet, including virtualized off-screen rows.
Controlled source and drafts
const details = ref<Row[]>(initialRows)
const edit = useTableEditable<Row>({
rowKey: 'id',
mode: 'multiple',
columns,
controls,
dataSource: details,
onChange: (value) => {
details.value = value
},
})
const { records, errors, validating } = editrecords is a combined snapshot of the source records, row drafts and cached new rows; bind it directly to the table. onChange notifies once only after a successful row save or an add in source mode; keystroke input is not written back to the source data. Writes from the parent form or server refreshes do not overwrite local drafts that are already open. When a source record is deleted, its unfinished draft stays in records to avoid silently losing input; call cancel or reset once the application confirms discarding it.
When the controlled adapter is configured, onSave returns the canonical record from the server and onChange updates the parent source; avoid writing the same data back in both callbacks. Without the adapter, the original approach still applies: the application updates dataSource.
getDraft(key) / getDrafts() read the isolated editor values, and getOriginal(key) reads the source snapshot taken when editing started. getValues() combines the data currently held by the client and transforms drafts into submitted values, without triggering validation, saving or onChange. Use the result snapshot of validateAll() for the final submission, to avoid reading a changed copy of the data after validation.
Submitting details at once
async function submitMaster() {
await masterForm.value.validate()
const result = await edit.validateAll()
if (!result.valid) {
const key = result.errors.keys().next().value
if (key !== undefined) await table.value.scrollTo({ key })
return
}
await saveOrder({ ...masterValues, details: result.values })
details.value = result.values!
edit.reset()
}Mutual exclusion of external submissions, master form validation and network error messages are controlled by the application. validateAll() does not call onSave / onChange, nor does it close editing or change the source array; unedited source records are temporarily converted to editor values before validation, and the submission result still keeps their source values. When input, a source data change, a reset, a save or an unmount happens, the old validation returns { valid: false, obsolete: true } and does not overwrite new errors; identical validations in progress are merged.
Errors are stored in errors under the row key and field path, so they can still be located even after the corresponding virtual row has been unmounted. validating indicates full validation; the per-row savingKeys indicate saving, and looping over save is not a substitute for pure validation. User drafts are kept when validation fails or the API submission fails.
reset() aborts operations and clears drafts and errors while keeping the current external source array; when resetting the master form, replace details first, then call reset. It does not run cancel callbacks or send save requests.
Add strategies
const edit = useTableEditable<Row>({
rowKey: 'id',
mode: 'multiple',
columns,
controls,
dataSource: details,
onChange: (value) => {
details.value = value
},
createRecord: () => ({ id: nextLocalId--, name: '', amount: 1 }),
maxRows: 20,
})
edit.add(undefined, { position: 'top' })
edit.add(undefined, { position: 'bottom', mode: 'source' })The defaults are position: 'bottom' / mode: 'cache'. A row added in cache mode exists only in the draft before it is saved and is removed on cancel; source mode inserts the row into the source array immediately through onChange, after which it is edited as an existing source row, and cancelling only discards the edits and keeps that source record. source mode requires dataSource and onChange to be configured together.
The createRecord factory creates a stable, unique key on each attempt; maxRows counts the current client-side source rows and cached new rows. Adding returns false when the limit is reached, the key is a duplicate, or single mode already has a row being edited. Saving an existing row cannot change its key; a cached new row can have its final key assigned by the server, but it must not conflict with the existing source.
These capabilities cover only records held by the client: rows not loaded under remote pagination cannot be validated; inserting nested tree nodes is handled by the application; server-side batch atomicity, undo history and spreadsheet navigation are not part of this protocol.
A complete demo for both presets is in the playground at /#/pro-schema, covering the master form, locating validation errors, keeping drafts when saving fails, adding at the top or bottom and the virtual body.
API
The following lists the options and return values used by the detail scenarios on this page. All row editing APIs are collected in the complete useTableEdit API; for column controls and integration, see the useTableEditable API.
Options
| Option | Type | Default | Description |
|---|---|---|---|
dataSource | MaybeRefOrGetter<readonly TRecord[]> | - | Optional controlled source; pair with onChange to publish saves. When omitted, records contains only edit sessions and cached additions. |
onChange | (records: TRecord[]) => void | - | Pair with dataSource; called after a successful save or a source addition, not on each keystroke. |
createRecord | () => TRecord | - | Creates a record when add() is called without arguments. |
maxRows | number | - | Maximum number of records held on the client, including cached new rows. |
Return value
| Property or method | Type | Description |
|---|---|---|
records | ComputedRef<TRecord[]> | With dataSource, contains source rows, drafts and cached additions. Without it, contains only edit sessions and cached additions. |
validating | ComputedRef<boolean> | Whether a full validation is running. |
getOriginal | (key: Key) => TRecord | undefined | Reads the snapshot of the source record taken when editing started; returns undefined for cached new rows. |
getDrafts | () => ReadonlyMap<Key, TRecord> | Reads isolated draft snapshots keyed by row key. |
getValues | () => TRecord[] | Source records plus the converted drafts; the editing state is kept and save is not called. |
validateAll | () => Promise<TableEditValidationResult<TRecord>> | Validates all records held on the client and returns the submit snapshot of that same validation, without saving. |
reset | () => void | Aborts in-flight operations and clears drafts and errors; the external source records are kept. |
Type Declarations
View type declarations
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>>
}