import _, { isEqual } from "lodash" import React, { CSSProperties } from "react" import * as formUtils from "./formUtils" import TextExprsComponent from "./TextExprsComponent" import ItemListComponent from "./ItemListComponent" import cx from "classnames" import { ResponseData, RosterData } from "./response" import ResponseRow from "./ResponseRow" import { Schema } from "@mwater/expressions" import { RosterGroup } from "./formDesign" import { InnerFormContext } from "./formContext" export interface RosterGroupComponentProps { /** Design of roster group. See schema */ rosterGroup: RosterGroup /** Current data of response. */ data: ResponseData /** Called when data changes */ onDataChange: (data: ResponseData) => void /** (id) tells if an item is visible or not */ isVisible: (id: string) => boolean /** ResponseRow object (for roster entry if in roster) */ responseRow: ResponseRow schema: Schema /** Form context */ formCtx: InnerFormContext } interface RosterGroupComponentState { /** The indices that are collapsed */ collapsedEntries: number[] /** Whether the roster group is valid */ valid: boolean } // TODO Add focus() // Rosters are repeated information, such as asking questions about household members N times. // A roster group is a group of questions that is asked once for each roster entry export default class RosterGroupComponent extends React.Component< RosterGroupComponentProps, RosterGroupComponentState > { constructor(props: RosterGroupComponentProps) { super(props) this.state = { collapsedEntries: JSON.parse( window.localStorage.getItem( `roster_group_collapse_state:${props.rosterGroup.rosterId ?? props.rosterGroup._id}` ) ?? "[]" ), valid: true } } componentDidUpdate( prevProps: Readonly, prevState: Readonly, snapshot?: any ): void { if (!isEqual(prevState.collapsedEntries, this.state.collapsedEntries)) { window.localStorage.setItem( `roster_group_collapse_state:${this.props.rosterGroup.rosterId ?? this.props.rosterGroup._id}`, JSON.stringify(this.state.collapsedEntries) ) } } // Gets the id that the answer is stored under getAnswerId() { // Prefer rosterId if specified, otherwise use id. return this.props.rosterGroup.rosterId || this.props.rosterGroup._id } // Get the current answer value getAnswer() { return (this.props.data[this.getAnswerId()] || []) as RosterData } // 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() 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) } async validate(scrollToFirstInvalid: boolean) { // For each entry let foundInvalid = false const iterable = this.getAnswer() if (iterable.length == 0 && this.props.rosterGroup.required) { this.setState({ valid: false }) return true } for (let index = 0; index < iterable.length; index++) { const entry = iterable[index] const result = await (this as any)[`itemlist_${index}`].validate(scrollToFirstInvalid && !foundInvalid) if (result) { foundInvalid = true } } this.setState({ valid: !foundInvalid }) return foundInvalid } isChildVisible = (index: any, id: any) => { return this.props.isVisible(`${this.getAnswerId()}.${index}.${id}`) } handleToggle = (index: number) => { this.setState({ collapsedEntries: _.xor(this.state.collapsedEntries, [index]) }) } renderName() { return (

{formUtils.localizeString(this.props.rosterGroup.name, this.props.formCtx.locale)} {this.props.rosterGroup.required ? * : undefined}

) } renderEntryTitle(entry: any, index: any) { return ( ) } renderEntry(entry: any, index: any) { const isCollapsed = this.state.collapsedEntries.includes(index) const bodyStyle = { height: isCollapsed ? 0 : "auto", transition: "height 0.25s ease-in", padding: isCollapsed ? 0 : 15, overflow: "hidden" } return (
{`${index + 1}. `} {this.renderEntryTitle(entry, index)}
{this.props.rosterGroup.allowRemove && ( )} { ;(this as any)[`itemlist_${index}`] = c }} contents={this.props.rosterGroup.contents} data={this.getAnswer()[index].data} responseRow={this.props.responseRow.getRosterResponseRow(this.getAnswerId(), index)} onDataChange={(data) => this.handleEntryDataChange(index, data)} isVisible={(id) => this.isChildVisible(index, id)} schema={this.props.schema} formCtx={this.props.formCtx} />
) } renderAdd() { if (this.props.rosterGroup.allowAdd) { return (
) } return null } renderEmptyPrompt() { return (
{formUtils.localizeString(this.props.rosterGroup.emptyPrompt, this.props.formCtx.locale) || this.props.formCtx.T("Click +Add to add an item")}
) } render() { const style: CSSProperties = { padding: 5, marginBottom: 20, overflowX: "auto", border: "transparent 2px solid ", borderColor: "transparent", borderRadius: 5 } if (!this.state.valid) { style.borderColor = "#c43b1d" } return (
{this.renderName()} {this.getAnswer().map((entry, index) => this.renderEntry(entry, index))} {this.getAnswer().length === 0 && this.props.rosterGroup.allowAdd && this.renderEmptyPrompt()} {this.renderAdd()}
) } }