import _ from "lodash" import React from "react" import { FormContext } from "./formContext" import { FormDesign, Section } from "./formDesign" import { ResponseData } from "./response" import { Schema } from "@mwater/expressions" import SectionsComponent from "./SectionsComponent" import ItemListComponent from "./ItemListComponent" import { Localizer, LocalizeString } from "ez-localize" import ResponseCleaner from "./ResponseCleaner" import { default as ResponseRow } from "./ResponseRow" import DefaultValueApplier from "./DefaultValueApplier" import VisibilityCalculator, { VisibilityStructure } from "./VisibilityCalculator" import RandomAskedCalculator from "./RandomAskedCalculator" import ResponseDataValidator from "./ResponseDataValidator" import { isRtlLocale, allItems, now } from "./formUtils" export interface FormComponentProps { /** Context to use for form. See docs/FormsContext.md */ formCtx: FormContext /** Form design. See schema.coffee */ design: FormDesign /** Form response data. See docs/Answer Formats.md */ data: ResponseData /** Called when response data changes */ onDataChange: (data: ResponseData) => void /** Called once when the data passed at mount has been cleaned (defaults, sticky values and * visibility applied), with the cleaned data. Earlier onDataChange calls come from this * cleaning, not from user edits */ onDataInitialized?: (data: ResponseData) => void /** Schema to use, including form and any dependent extra tables like assets or custom tablesets */ schema: Schema /** Optional factory for custom row contexts such as workflow events */ createResponseRow?: (data: ResponseData) => ResponseRow /** The current deployment */ deployment?: string /** e.g. "fr" */ locale?: string /** Called when submit is pressed */ onSubmit?: () => void /** Optional save for later */ onSaveLater?: () => void /** Called when discard is pressed */ onDiscard?: () => void /** To override submit label */ submitLabel?: string /** To override Save For Later label */ saveLaterLabel?: string /** To override Discard label */ discardLabel?: string /** Form-level entity to load */ entity?: any /** Type of form-level entity to load */ entityType?: string /** Form-level asset to load */ assetSystemId?: number /** Type of form-level asset to load */ assetType?: string /** Id of form-level asset to load */ assetId?: string /** True to render as a single page, not divided into sections */ singlePageMode?: boolean /** True to disable the confidential fields, used during editing responses with confidential data */ disableConfidentialFields?: boolean /** Force all questions to be visible */ forceAllVisible?: boolean } interface FormComponentState { T: LocalizeString visibilityStructure: VisibilityStructure submitting: boolean } /** Displays a form that can be filled out */ export default class FormComponent extends React.Component { currentData: ResponseData | null cleanInProgress: ResponseData | null = null /** Data passed at mount, until its cleaning has been reported by onDataInitialized */ mountData: ResponseData | null = null itemListComponent: ItemListComponent | null = null submit: HTMLButtonElement | null = null /** Time constructed (see formUtils.now), to time the first render */ createdAt: number constructor(props: FormComponentProps) { super(props) this.createdAt = now() this.state = { visibilityStructure: {}, T: this.createLocalizer(this.props.design, this.props.locale), submitting: false } // Save which data visibility structure applies to this.currentData = null } componentDidMount() { const sections = this.props.design.contents.filter((item) => item._type === "Section").length const items = allItems(this.props.design).length - 1 console.log(`Form opened: ${items} items, ${sections} sections, rendered in ${Math.round(now() - this.createdAt)}ms`) // This will clean the data that has been passed at creation // It will also initialize the visibilityStructure // And set the sticky data this.mountData = this.props.data this.handleDataChange(this.props.data) } componentDidUpdate(prevProps: FormComponentProps) { // Update localizer if design or locale changed if (this.props.design !== prevProps.design || this.props.locale !== prevProps.locale) { this.setState({ T: this.createLocalizer(this.props.design, this.props.locale || "en") }) } // When data change is external, process it to set visibility, etc. if (prevProps.data !== this.props.data && !_.isEqual(this.props.data, this.currentData)) { this.handleDataChange(this.props.data) } } // Creates a localizer for the form design createLocalizer(design: FormDesign, locale?: string) { // Create localizer const localizedStrings = design.localizedStrings || [] const localizerData = { locales: design.locales, strings: localizedStrings } const { T } = new Localizer(localizerData, locale) return T } /** Handle submit button click in the case of a page-less form */ handleSubmit = async () => { this.setState({ submitting: true }) try { // Cannot submit if at least one item is invalid const result = await this.itemListComponent!.validate(true) if (result) { // If an invalid item is found, do not submit (message is shown by validate) return } // Perform a complete validation of the response, recomputing the visibility structure const visibilityCalculator = new VisibilityCalculator(this.props.design, this.props.schema) const visibilityStructure = await visibilityCalculator.createVisibilityStructure(this.props.data, this.createResponseRow(this.props.data)) const validationError = await new ResponseDataValidator().validate(this.props.design, visibilityStructure, this.props.data, this.props.schema, this.createResponseRow(this.props.data)) if (validationError) { alert(validationError.message) return } this.props.onSubmit!() } finally { this.setState({ submitting: false }) } } isVisible = (itemId: string) => { return this.props.forceAllVisible || this.state.visibilityStructure[itemId] } /** Creates a response row */ createResponseRow = (data: ResponseData) => { if (this.props.createResponseRow) { return this.props.createResponseRow(data) } return new ResponseRow({ responseData: data, formDesign: this.props.design, schema: this.props.schema, getEntityById: this.props.formCtx.getEntityById, getEntityByCode: this.props.formCtx.getEntityByCode, getCustomTableRow: this.props.formCtx.getCustomTableRow, getAssetById: this.props.formCtx.getAssetById, getAdminRegion: this.props.formCtx.getAdminRegion, deployment: this.props.deployment }) } handleDataChange = (data: ResponseData) => { const visibilityCalculator = new VisibilityCalculator(this.props.design, this.props.schema) const defaultValueApplier = this.props.formCtx.stickyStorage ? new DefaultValueApplier( this.props.design, this.props.formCtx.stickyStorage, { entityType: this.props.entityType, entity: this.props.entity, assetSystemId: this.props.assetSystemId, assetType: this.props.assetType, assetId: this.props.assetId, } ) : null const randomAskedCalculator = new RandomAskedCalculator(this.props.design) const responseCleaner = new ResponseCleaner() // Immediately update data, as another answer might be clicked on (e.g. blur from a number input and clicking on a radio answer) this.currentData = data this.props.onDataChange(data) // Clean response data, remembering which data object is being cleaned this.cleanInProgress = data return responseCleaner.cleanData( this.props.design, visibilityCalculator, defaultValueApplier, randomAskedCalculator, data, this.createResponseRow, this.state.visibilityStructure, (error: any, results: any) => { // Report the cleaned mount-time data, even if a later change has superseded it if (data === this.mountData) { this.mountData = null this.props.onDataInitialized?.(error ? data : results.data) } if (error) { alert(this.state.T("Error saving data") + `: ${error.message}`) return } // Ignore if from a previous clean if (data !== this.cleanInProgress) { console.log("Ignoring stale handleDataChange data") return } this.setState({ visibilityStructure: results.visibilityStructure }) // Ignore if unchanged if (!_.isEqual(data, results.data)) { this.currentData = results.data return this.props.onDataChange(results.data) } } ) } handleNext = () => { return this.submit!.focus() } render() { const dir = this.props.locale && isRtlLocale(this.props.locale) ? "rtl" : undefined if ( this.props.design.contents[0] && this.props.design.contents[0]._type === "Section" && !this.props.singlePageMode ) { return
} else { return (
{ this.itemListComponent = c }} contents={this.props.design.contents} data={this.props.data} onDataChange={this.handleDataChange} responseRow={this.createResponseRow(this.props.data)} schema={this.props.schema} isVisible={this.isVisible} onNext={this.handleNext} formCtx={{ ...this.props.formCtx, locale: this.props.locale, T: this.state.T, disableConfidentialFields: this.props.disableConfidentialFields, }} /> {this.props.onSubmit && ( )} {"\u00A0"} {this.props.onSaveLater && ( <> {"\u00A0"} )} {this.props.onDiscard && ( )}
) } } }