import _, { isEmpty } from "lodash" import React from "react" import * as formUtils from "./formUtils" import ValidationCompiler from "./answers/ValidationCompiler" import ReorderableListComponent from "@mwater/react-library/lib/reorderable/ReorderableListComponent" import MatrixColumnCellComponent from "./MatrixColumnCellComponent" import { RosterMatrix } from "./formDesign" import { ResponseData, RosterData, RosterEntry, RosterEntryData } from "./response" import { Schema } from "@mwater/expressions" import ResponseRow from "./ResponseRow" import { InnerFormContext } from "./formContext" export interface RosterMatrixComponentProps { rosterMatrix: RosterMatrix /** Current data of response */ data: ResponseData onDataChange: (data: ResponseData) => void /** (id) tells if an item is visible or not */ isVisible: (id: string) => boolean schema: Schema responseRow: ResponseRow /** Form context */ formCtx: InnerFormContext } interface RosterMatrixComponentState { /** Map of "_" to validation error */ validationErrors: { [id: string]: string | true } } // Rosters are repeated information, such as asking questions about household members N times. // A roster matrix is a list of column-type questions with one row for each entry in the roster export default class RosterMatrixComponent extends React.Component< RosterMatrixComponentProps, RosterMatrixComponentState > { prompt: HTMLHeadingElement | null = null constructor(props: RosterMatrixComponentProps) { super(props) this.state = { validationErrors: {} } } // Gets the id that the answer is stored under getAnswerId() { // Prefer rosterId if specified, otherwise use id. return this.props.rosterMatrix.rosterId || this.props.rosterMatrix._id } // Get the current answer value getAnswer(): RosterData { return (this.props.data[this.getAnswerId()] || []) as RosterData } async validate(scrollToFirstInvalid: any) { const validationErrors: { [id: string]: string | true } = {} // For each entry let foundInvalid = false const iterable = this.getAnswer() if (iterable.length == 0 && this.props.rosterMatrix.required) { validationErrors["root"] = true foundInvalid = true } else { for (let rowIndex = 0; rowIndex < iterable.length; rowIndex++) { // For each column const entry = iterable[rowIndex] for (let columnIndex = 0; columnIndex < this.props.rosterMatrix.contents.length; columnIndex++) { const column = this.props.rosterMatrix.contents[columnIndex] if (!formUtils.isQuestionOrMatrixColumnQuestion(column)) { continue } const key = `${rowIndex}_${column._id}` if (column.required && !entry.data[column._id]?.alternate && (entry.data[column._id]?.value == null || entry.data[column._id]?.value === "")) { foundInvalid = true validationErrors[key] = true } if (column.validations && column.validations.length > 0) { const validationError = new ValidationCompiler(this.props.formCtx.locale).compileValidations(column.validations)( entry.data[column._id] ) if (validationError) { foundInvalid = true validationErrors[key] = validationError } } } } } // Save state this.setState({ validationErrors }) // Scroll into view if (foundInvalid && scrollToFirstInvalid) { this.prompt!.scrollIntoView() } return foundInvalid } // Propagate an answer change to the onDataChange handleAnswerChange = (answer: any) => { const change: any = {} change[this.getAnswerId()] = answer return this.props.onDataChange(_.extend({}, this.props.data, change)) } // Handles a change in data of a specific entry of the roster handleEntryDataChange = (index: any, data: any) => { const answer = this.getAnswer().slice() answer[index] = _.extend({}, answer[index], { data }) return this.handleAnswerChange(answer) } handleAdd = () => { const answer = this.getAnswer().slice() const lastEntry = answer.length > 0 ? answer[answer.length - 1] : null const data: RosterEntryData = {} if (lastEntry) { for (const column of this.props.rosterMatrix.contents) { if (formUtils.isQuestionOrMatrixColumnQuestion(column) && column.sticky) { const prevAnswer = lastEntry.data[column._id] if (prevAnswer && prevAnswer.value != null) { data[column._id] = { ...prevAnswer } } } } } answer.push({ _id: formUtils.createUid(), data }) return this.handleAnswerChange(answer) } handleRemove = (index: any) => { const answer = this.getAnswer().slice() answer.splice(index, 1) return this.handleAnswerChange(answer) } handleCellChange = (entryIndex: any, columnId: any, answer: any) => { let { data } = this.getAnswer()[entryIndex] const change: any = {} change[columnId] = answer data = _.extend({}, data, change) return this.handleEntryDataChange(entryIndex, data) } handleSort = (column: any, order: any) => { let answer = this.getAnswer() as RosterData answer = _.sortByOrder(answer, [(item: RosterEntry) => item.data[column._id]?.value], [order]) return this.handleAnswerChange(answer) } renderName() { return (

{ this.prompt = c }} > {formUtils.localizeString(this.props.rosterMatrix.name, this.props.formCtx.locale)} {this.props.rosterMatrix.required ? * : undefined}

) } renderColumnHeader(column: any, index: any) { return ( {formUtils.localizeString(column.text, this.props.formCtx.locale)} {/* Required star */} {column.required ? * : undefined} {/* Allow sorting */} {["TextColumnQuestion", "NumberColumnQuestion", "DateColumnQuestion"].includes(column._type) ? (
) : undefined} ) } renderHeader() { return ( {_.map(this.props.rosterMatrix.contents, (column, index) => this.renderColumnHeader(column, index))} {/* Extra for remove button */} {this.props.rosterMatrix.allowRemove ? : undefined} ) } renderCell(entry: any, entryIndex: any, column: any, columnIndex: any) { // Get data of the entry const entryData = this.getAnswer()[entryIndex].data // Determine if invalid const key = `${entryIndex}_${column._id}` const invalid = this.state.validationErrors[key] // Render cell return ( ) } renderEntry = (entry: any, index: any, connectDragSource: any, connectDragPreview: any, connectDropTarget: any) => { const elem = ( {_.map(this.props.rosterMatrix.contents, (column, columnIndex) => this.renderCell(entry, index, column, columnIndex) )} {this.props.rosterMatrix.allowRemove ? ( ) : undefined} ) return connectDropTarget(connectDragPreview(connectDragSource(elem))) } renderAdd() { if (this.props.rosterMatrix.allowAdd) { return (
) } return null } renderBody() { return ( entry._id} element={} /> ) } renderEmptyPrompt() { return (
{formUtils.localizeString(this.props.rosterMatrix.emptyPrompt, this.props.formCtx.locale) || this.props.formCtx.T("Click +Add to add an item")}
) } render() { let style: React.CSSProperties = { padding: 5, marginBottom: 20, overflowX: "auto", border: "transparent 2px solid ", borderColor: "transparent", borderRadius: 5 } if (!isEmpty(this.state.validationErrors)) { style = { ...style, borderColor: "#c43b1d" } } return (
{this.renderName()} {this.renderHeader()}{this.renderBody()}
{/* Display message if none and can add */} {this.getAnswer().length === 0 && this.props.rosterMatrix.allowAdd ? this.renderEmptyPrompt() : undefined} {this.renderAdd()}
) } }