import { Components } from '@formio/js'; import _ from 'lodash'; import { isCommentOnlyConditional } from './commentOnlyConditional'; import { isSafeKey } from './safeKey'; interface ComponentSchema { key?: string; calculateValue?: string; calculateValueVariable?: string; redrawOn?: string | string[]; refreshOn?: string | string[]; customConditional?: string; clearOnHide?: boolean; type?: string; } interface ComponentInstance { component: ComponentSchema; redraw: () => unknown; __gdsVisibilityChanging?: boolean; parent?: { data?: unknown }; key?: string; rootValue?: unknown; evaluate?: (expr: string, ctx: Record, variable?: string) => unknown; _conditionallyClear?: boolean; options?: { readOnly?: boolean; showHiddenFields?: boolean }; shouldAddDefaultValue?: boolean; defaultValue?: unknown; setValue?: (value: unknown, flags?: { noUpdateEvent?: boolean }) => unknown; visible?: boolean; allowData?: boolean; builderMode?: boolean; previewMode?: boolean; _data?: unknown; data?: unknown; getComponents?: () => ComponentInstance[]; hasValue?: (data?: unknown) => boolean; } interface ComponentPrototype { __gdsCalculatedValueRedrawGuardInstalled?: boolean; __gdsClearOnHideGuardInstalled?: boolean; __gdsHiddenDefaultGuardInstalled?: boolean; checkRefreshOn: ( this: ComponentInstance, changes: unknown[], flags?: unknown, ) => void; redraw: (this: ComponentInstance) => unknown; clearComponentOnHide?: (this: ComponentInstance) => void; checkCondition?: (this: ComponentInstance, row?: unknown, data?: unknown) => boolean; } interface ComponentConstructor { prototype: ComponentPrototype; } interface NestedInstance { data: unknown; getComponents: () => Array<{ checkData: (data: unknown, flags: unknown, row: unknown) => void; data: unknown }>; checkData: (data: unknown, flags: unknown, row: unknown, components?: unknown[]) => void; } interface NestedPrototype { __gdsNestedCheckDataGuardInstalled?: boolean; __gdsHiddenNestedDefaultGuardInstalled?: boolean; checkData: (this: NestedInstance, data: unknown, flags: unknown, row: unknown, components?: unknown[]) => void; setNestedValue?: ( this: NestedInstance, component: ComponentInstance, value: unknown, flags?: Record, changed?: boolean, ) => unknown; } interface NestedConstructor { prototype: NestedPrototype; } interface DataGridInstance { dataValue: unknown[]; rows: Record[]; component: { components?: ComponentSchema[] }; } interface DataGridSetValueFlags { triggeredComponentId?: string; [key: string]: unknown; } interface DataGridPrototype { __gdsDataGridRedrawGuardInstalled?: boolean; setValue: ( this: DataGridInstance, value: unknown, flags?: DataGridSetValueFlags, ) => boolean; } interface DataGridConstructor { prototype: DataGridPrototype; } interface VisiblePrototype { visible?: boolean; } // Both `Component` and `NestedComponent` define `visible`; wrap each. function wrapVisibleSetter(prototype: object): void { const descriptor = Object.getOwnPropertyDescriptor(prototype, 'visible'); if (!descriptor?.set) return; const originalSet = descriptor.set; Object.defineProperty(prototype, 'visible', { ...descriptor, set(this: ComponentInstance & VisiblePrototype, value: boolean) { const previous = this.__gdsVisibilityChanging; this.__gdsVisibilityChanging = true; try { originalSet.call(this, value); } finally { this.__gdsVisibilityChanging = previous; } }, }); } function getCalculatedIds(datagrid: DataGridInstance): Set { const ids = new Set(); for (const row of datagrid.rows) { for (const comp of Object.values(row)) { const schema = comp?.component; if (schema && (schema.calculateValue || schema.calculateValueVariable)) { const id = (comp as unknown as { id?: string }).id; if (id) ids.add(id); } } } return ids; } const OBJECT_DATA_TYPES = new Set(['container']); function isMissingFromRow(instance: ComponentInstance): boolean { const row = instance._data; if (!instance.key || !_.isObjectLike(row) || _.get(row, instance.key) !== undefined) return false; // A tree container's `_data` may be its own value; that is not a missing key. return row !== _.get(instance.parent?.data, instance.key); } function addDefaultWhenShown(instance: ComponentInstance): void { if ( OBJECT_DATA_TYPES.has(instance.component?.type ?? '') || instance.options?.readOnly || instance.options?.showHiddenFields || typeof instance.setValue !== 'function' || !isMissingFromRow(instance) || !instance.shouldAddDefaultValue ) { return; } instance.setValue(instance.defaultValue, { noUpdateEvent: true }); } function attachIfDetached(instance: ComponentInstance): void { if ( !OBJECT_DATA_TYPES.has(instance.component?.type ?? '') || !instance.allowData || instance.visible !== true || instance.builderMode || instance.previewMode || instance.options?.readOnly || typeof instance.getComponents !== 'function' || !isSafeKey(instance.key ?? '') || !isMissingFromRow(instance) ) { return; } const value: Record = {}; collectChildValues(instance, value); _.set(instance._data as object, instance.key as string, value); instance.data = instance._data; } function collectChildValues(parent: ComponentInstance, target: Record): void { for (const child of parent.getComponents?.() ?? []) { if (child.allowData && child.key) { const childValue = _.isObjectLike(child._data) ? _.get(child._data, child.key) : undefined; if (childValue !== undefined && isSafeKey(child.key)) { _.set(target, child.key, childValue); } } else if (typeof child.getComponents === 'function') { collectChildValues(child, target); } } } function isHiddenAndCleared(instance: ComponentInstance): boolean { return ( instance.component?.clearOnHide !== false && instance.visible === false && !instance.options?.showHiddenFields && !OBJECT_DATA_TYPES.has(instance.component?.type ?? '') ); } // `setNestedValue` seeds defaults via `resetValue`, which skips `shouldAddDefaultValue`. function installHiddenNestedDefaultGuard(nestedPrototype: NestedPrototype): void { const originalSetNestedValue = nestedPrototype.setNestedValue; if ( typeof originalSetNestedValue !== 'function' || Object.prototype.hasOwnProperty.call(nestedPrototype, '__gdsHiddenNestedDefaultGuardInstalled') ) { return; } nestedPrototype.__gdsHiddenNestedDefaultGuardInstalled = true; nestedPrototype.setNestedValue = function ( this: NestedInstance, component: ComponentInstance, value: unknown, flags: Record = {}, changed?: boolean, ): unknown { const incomingHasValue = Boolean(value) && typeof component?.hasValue === 'function' && component.hasValue(value); if ( component?.allowData && component.component?.type !== 'components' && !incomingHasValue && !flags.noDefault && isHiddenAndCleared(component) ) { const componentContext = (this as unknown as { componentContext?: (c: unknown) => unknown }).componentContext; if (typeof componentContext === 'function') { component._data = componentContext.call(this, component); } return false; } return originalSetNestedValue.call(this, component, value, flags, changed); }; } // v4 did not seed hidden clear-on-hide fields and treated comment-only conditions as hidden. function installHiddenDefaultGuard(prototype: ComponentPrototype): void { if (Object.prototype.hasOwnProperty.call(prototype, '__gdsHiddenDefaultGuardInstalled')) return; const defaultDescriptor = Object.getOwnPropertyDescriptor(prototype, 'shouldAddDefaultValue'); const originalCheckCondition = prototype.checkCondition; if (!defaultDescriptor?.get || typeof originalCheckCondition !== 'function') return; prototype.__gdsHiddenDefaultGuardInstalled = true; prototype.checkCondition = function (this: ComponentInstance, row?: unknown, data?: unknown): boolean { if (isCommentOnlyConditional(this.component?.customConditional)) { return false; } return originalCheckCondition.call(this, row, data); }; const originalShouldAddDefault = defaultDescriptor.get; Object.defineProperty(prototype, 'shouldAddDefaultValue', { ...defaultDescriptor, get(this: ComponentInstance) { if (isHiddenAndCleared(this)) { return false; } return originalShouldAddDefault.call(this); }, }); } /** * Patches Form.io v5 prototypes to: * - stop calculated fields flickering from redundant redraws; * - stop `customConditional` containers losing data on tab switches; * - keep hidden fields out of the data, as v4 did; * - avoid the double iteration in `NestedComponent.checkData` (input lag). * * UMD consumers must call this explicitly after Formio is ready: * * installCalculatedValueRedrawGuard( * Formio.Components.components.component, * Formio.Components.components.datagrid * ); */ export const installCalculatedValueRedrawGuard = ( ComponentClass?: ComponentConstructor, DataGridClass?: DataGridConstructor, ): void => { const resolvedClass: ComponentConstructor = ComponentClass ?? (Components.components.component as unknown as ComponentConstructor); const prototype = resolvedClass.prototype; if (!Object.prototype.hasOwnProperty.call(prototype, '__gdsCalculatedValueRedrawGuardInstalled')) { prototype.__gdsCalculatedValueRedrawGuardInstalled = true; const originalCheckRefreshOn = prototype.checkRefreshOn; const originalRedraw = prototype.redraw; prototype.checkRefreshOn = function ( this: ComponentInstance, changes: unknown[], flags?: unknown, ): void { const component = this.component; const hasCalculation = Boolean( component.calculateValue || component.calculateValueVariable, ); if (hasCalculation && !component.refreshOn) { return; } originalCheckRefreshOn.call(this, changes, flags); }; wrapVisibleSetter(prototype); prototype.redraw = function (this: ComponentInstance): unknown { const component = this.component; const hasCalculation = Boolean( component.calculateValue || component.calculateValueVariable, ); // Blocking this redraw on show would leave the field unrendered. if (hasCalculation && !component.refreshOn && !this.__gdsVisibilityChanging) { return Promise.resolve(); } return originalRedraw.call(this); }; // Form.io evaluates `customConditional` against the component's own data // rather than the parent row, so containers get wrongly cleared. Re-evaluate // with the parent row and abort the clear if the component is visible. // A shown container missing from its row is reattached, or a tab switch resets it. if ( prototype.clearComponentOnHide && !Object.prototype.hasOwnProperty.call(prototype, '__gdsClearOnHideGuardInstalled') ) { prototype.__gdsClearOnHideGuardInstalled = true; const originalClearComponentOnHide = prototype.clearComponentOnHide; prototype.clearComponentOnHide = function (this: ComponentInstance): void { const customConditional = this.component?.customConditional; if ( customConditional && this.component?.clearOnHide !== false && typeof this.evaluate === 'function' && this.parent?.data !== undefined ) { const show = this.evaluate( customConditional, { row: this.parent.data, data: this.rootValue ?? {} }, 'show', ); if (show) { this._conditionallyClear = false; addDefaultWhenShown(this); attachIfDetached(this); return; } } originalClearComponentOnHide.call(this); attachIfDetached(this); }; } installHiddenDefaultGuard(prototype); } const resolvedDataGridClass: DataGridConstructor | undefined = DataGridClass ?? (Components.components.datagrid as unknown as DataGridConstructor | undefined); if (!resolvedDataGridClass) return; const dgPrototype = resolvedDataGridClass.prototype; if (Object.prototype.hasOwnProperty.call(dgPrototype, '__gdsDataGridRedrawGuardInstalled')) return; dgPrototype.__gdsDataGridRedrawGuardInstalled = true; const originalDataGridSetValue = dgPrototype.setValue; dgPrototype.setValue = function ( this: DataGridInstance, value: unknown, flags: DataGridSetValueFlags = {}, ): boolean { const triggeredId = flags.triggeredComponentId; if (triggeredId) { const calculatedIds = getCalculatedIds(this); if (calculatedIds.has(triggeredId)) { const self = this as unknown as { redraw: () => Promise }; const savedRedraw = self.redraw; self.redraw = () => Promise.resolve(); try { return originalDataGridSetValue.call(this, value, flags); } finally { self.redraw = savedRedraw; } } } return originalDataGridSetValue.call(this, value, flags); }; const NestedClass = Components.components.nested as unknown as NestedConstructor | undefined; if (!NestedClass) return; const nestedPrototype = NestedClass.prototype; installHiddenNestedDefaultGuard(nestedPrototype); if (Object.prototype.hasOwnProperty.call(nestedPrototype, '__gdsNestedCheckDataGuardInstalled')) return; nestedPrototype.__gdsNestedCheckDataGuardInstalled = true; wrapVisibleSetter(nestedPrototype); // Children are iterated below with their own data, so skip the original's pass. const originalNestedCheckData = nestedPrototype.checkData; nestedPrototype.checkData = function ( this: NestedInstance, data: unknown, flags: unknown, row: unknown, components?: unknown[], ): void { if ((this as unknown as { builderMode?: boolean }).builderMode) { return; } const effectiveRow = row ?? this.data; originalNestedCheckData.call(this, data, flags, effectiveRow, []); const children = Array.isArray(components) && components.length ? (components as Array<{ checkData: (d: unknown, f: unknown, r: unknown) => void; data: unknown }>) : this.getComponents(); children.forEach((comp) => comp.checkData(data, Object.assign({}, flags as object), comp.data ?? effectiveRow), ); }; };