import _ from "lodash" import React from "react" import ItemListComponent from "./ItemListComponent" import * as formUtils from "./formUtils" import { ResponseData } from "./response" import { InnerFormContext } from "./formContext" import { Schema } from "@mwater/expressions" import ResponseRow from "./ResponseRow" import { FormDesign, Section } from "./formDesign" import VisibilityCalculator from "./VisibilityCalculator" import ResponseDataValidator from "./ResponseDataValidator" export interface SectionsComponentProps { /** Complete design of the form */ formDesign: FormDesign contents: Section[] /** Current data of response. */ data: ResponseData /** Called when data changes */ onDataChange: (data: ResponseData) => void /** Schema to use, including form */ schema: Schema /** ResponseRow object (for roster entry if in roster) */ responseRow: ResponseRow /** (id) tells if an item is visible or not */ isVisible: (id: string) => boolean /** Called when submit is pressed */ onSubmit?: () => void /** Optional save for later */ onSaveLater?: () => void onDiscard?: () => void /** Form context */ formCtx: InnerFormContext /** Function to create a response row */ createResponseRow: (data: ResponseData) => ResponseRow } interface SectionsComponentState { sectionNum: number nextOrSubmitting: boolean } export default class SectionsComponent extends React.Component { itemListComponent: ItemListComponent | null = null sections: HTMLDivElement | null = null nextOrSubmit: HTMLButtonElement | null = null /** Time a section change was requested (see formUtils.now), to time its render */ sectionChangeStart: number | null constructor(props: SectionsComponentProps) { super(props) this.state = { sectionNum: 0, nextOrSubmitting: false } this.sectionChangeStart = null } componentDidUpdate(prevProps: SectionsComponentProps, prevState: SectionsComponentState) { if (prevState.sectionNum !== this.state.sectionNum && this.sectionChangeStart != null) { const elapsed = Math.round(formUtils.now() - this.sectionChangeStart) this.sectionChangeStart = null const section = this.props.contents[this.state.sectionNum] const items = formUtils.allItems(section).length - 1 console.log(`Section ${this.state.sectionNum + 1}/${this.props.contents.length} shown: ${items} items, rendered in ${elapsed}ms`) } } /** Switches to a section, timing the render (see componentDidUpdate) */ goToSection(sectionNum: number) { this.sectionChangeStart = formUtils.now() this.setState({ sectionNum }) } /** Handles next or submit button click */ handleNextOrSubmit = async () => { // Cannot submit or go to next 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 } try { this.setState({ nextOrSubmitting: true }) // The data may have just changed, which means that isVisible could return stale // visibility data. But submitting or going to the next section depend on having // the most up-to-date version to avoid skipping required sections that are slow // to display, so we recompute the visibility structure with the latest data const visibilityCalculator = new VisibilityCalculator(this.props.formDesign, this.props.schema) const visibilityStructure = await visibilityCalculator.createVisibilityStructure(this.props.data, this.props.createResponseRow(this.props.data)) // Validate the response for the entire form up to and including the current section // Do this by making a copy of the design, excluding all future sections const formDesignUpToCurrent: FormDesign = { ...this.props.formDesign, contents: this.props.contents.slice(0, this.state.sectionNum + 1) } const validationError = await new ResponseDataValidator().validate( formDesignUpToCurrent, visibilityStructure, this.props.data, this.props.schema, this.props.createResponseRow(this.props.data) ) if (validationError) { alert(validationError.message) return } // Determine if there is a next visible section let nextSectionNum = -1 for (let i = this.state.sectionNum + 1; i < this.props.contents.length; i++) { const section = this.props.contents[i] const isVisible = visibilityStructure[section._id] if (isVisible) { nextSectionNum = i break } } // If there is a next section, move to it if (nextSectionNum !== -1) { this.goToSection(nextSectionNum) // Scroll to top of section this.sections?.scrollIntoView() } else { // No next section, so submit this.props.onSubmit?.() } } finally { this.setState({ nextOrSubmitting: false }) } } hasPreviousSection() { // Returns true if a visible index exist with a higher value return this.nextVisibleSectionIndex(this.state.sectionNum - 1, -1) !== -1 } hasNextSection() { // Returns true if a visible index exist with a higher value return this.nextVisibleSectionIndex(this.state.sectionNum + 1, 1) !== -1 } nextVisibleSectionIndex(index: number, increment: number): number { if (index < 0) { return -1 } if (index >= this.props.contents.length) { return -1 } const section = this.props.contents[index] const isVisible = this.props.isVisible(section._id) if (isVisible) { return index } else { return this.nextVisibleSectionIndex(index + increment, increment) } } handleBackSection = () => { // Move to previous that is visible const previousVisibleIndex = this.nextVisibleSectionIndex(this.state.sectionNum - 1, -1) if (previousVisibleIndex !== -1) { this.goToSection(previousVisibleIndex) // Scroll to top of section return this.sections?.scrollIntoView() } } handleBreadcrumbClick = (index: number) => { this.goToSection(index) } handleItemListNext = () => { this.nextOrSubmit!.focus() } renderBreadcrumbs() { const breadcrumbs = [] let index = 0 while (index < this.state.sectionNum) { const section = this.props.contents[index] const visible = this.props.isVisible(section._id) breadcrumbs.push(
  • {visible ? ( {`${index + 1}.`} ) : ( `${index + 1}.` )}
  • ) index++ } const currentSectionName = formUtils.localizeString( this.props.contents[this.state.sectionNum].name, this.props.formCtx.locale ) breadcrumbs.push(
  • {`${this.state.sectionNum + 1}. ${currentSectionName}`}
  • ) return
      {breadcrumbs}
    } renderSection() { const section = this.props.contents[this.state.sectionNum] return (

    {formUtils.localizeString(section.name, this.props.formCtx.locale)}

    { this.itemListComponent = c }} contents={section.contents} data={this.props.data} onDataChange={this.props.onDataChange} isVisible={this.props.isVisible} responseRow={this.props.responseRow} onNext={this.handleItemListNext} schema={this.props.schema} formCtx={this.props.formCtx} />
    ) } renderSubmitOrNextButton() { const hasNextSection = this.hasNextSection() if (hasNextSection) { return } if (this.props.onSubmit) { return } return null } renderButtons() { return (
    {/* If can go back */} {this.hasPreviousSection() && ( <> {"\u00A0"} )} {/* Can go forward or submit */} {this.renderSubmitOrNextButton()} {"\u00A0"} {this.props.onSaveLater && ( <> {"\u00A0"} )} {this.props.onDiscard && ( )}
    ) } render() { return (
    { this.sections = c }} > {this.renderBreadcrumbs()}
    {this.renderSection()}
    {this.renderButtons()}
    ) } }