import _ from "lodash" import { Schema } from "@mwater/expressions" import React, { ReactElement } from "react" import { Item, Question } from "./formDesign" import * as formRenderUtils from "./formRenderUtils" import { ResponseData } from "./response" import ResponseRow from "./ResponseRow" import { InnerFormContext } from "./formContext" export interface ItemListComponentProps { contents: Item[] /** Current data of response (for roster entry if in roster) */ data: ResponseData /** ResponseRow object (for roster entry if in roster) */ responseRow: ResponseRow onDataChange: (data: ResponseData) => void onNext?: () => void /** (id) tells if an item is visible or not */ isVisible: (id: string) => boolean schema: Schema /** Form context */ formCtx: InnerFormContext } // Display a list of items export default class ItemListComponent extends React.Component { itemRefs: { [itemId: string]: any } constructor(props: ItemListComponentProps) { super(props) // Refs of all items this.itemRefs = {} } async validate(scrollToFirstInvalid: boolean) { let foundInvalid = false for (let item of this.props.contents) { // Only if validation is possible if (this.itemRefs[item._id]?.validate) { const result = await this.itemRefs[item._id]?.validate(scrollToFirstInvalid && !foundInvalid) // Do not break here, as it's important to call validate on each item so that all errors are shown if (result) { foundInvalid = true } } } return foundInvalid } handleNext(index: number) { index++ if (index >= this.props.contents.length) { return this.props.onNext?.() } else { return this.itemRefs[this.props.contents[index]._id]?.focus?.() } } isItemVisible(item: Item) { return this.props.isVisible(item._id) && !(item as Question).disabled } renderItem = (item: Item, index: number) => { if (this.isItemVisible(item)) { return formRenderUtils.renderItem({ item, data: this.props.data, responseRow: this.props.responseRow, schema: this.props.schema, onDataChange: this.props.onDataChange, isVisible: this.props.isVisible, onNext: this.props.onNext, ref: (c: ReactElement | null) => { return (this.itemRefs[item._id] = c) }, formCtx: this.props.formCtx }) } return null } render() { return
{_.map(this.props.contents, this.renderItem)}
} }