import _ from "lodash" import React from "react" import { Image } from "@mwater/expressions" import * as formUtils from "./formUtils" import TextExprsComponent from "./TextExprsComponent" import LocationFinder from "./LocationFinder" import { default as CurrentPositionFinder } from "./CurrentPositionFinder" import AnswerValidator from "./answers/AnswerValidator" import AquagenxCBTAnswerComponent from "./answers/AquagenxCBTAnswerComponent" import BarcodeAnswerComponent from "./answers/BarcodeAnswerComponent" import CheckAnswerComponent from "./answers/CheckAnswerComponent" import DateAnswerComponent from "./answers/DateAnswerComponent" import DropdownAnswerComponent from "./answers/DropdownAnswerComponent" import EntityAnswerComponent from "./answers/EntityAnswerComponent" import ImageAnswerComponent from "./answers/ImageAnswerComponent" import ImagesAnswerComponent from "./answers/ImagesAnswerComponent" import SignatureAnswerComponent from "./answers/SignatureAnswerComponent" import LikertAnswerComponent from "./answers/LikertAnswerComponent" import LocationAnswerComponent from "./answers/LocationAnswerComponent" import MatrixAnswerComponent from "./answers/MatrixAnswerComponent" import MulticheckAnswerComponent from "./answers/MulticheckAnswerComponent" import NumberAnswerComponent from "./answers/NumberAnswerComponent" import RadioAnswerComponent from "./answers/RadioAnswerComponent" import SiteAnswerComponent from "./answers/SiteAnswerComponent" import StopwatchAnswerComponent from "./answers/StopwatchAnswerComponent" import TextAnswerComponent from "./answers/TextAnswerComponent" import TextListAnswerComponent from "./answers/TextListAnswerComponent" import UnitsAnswerComponent from "./answers/UnitsAnswerComponent" import { CascadingListAnswerComponent } from "./answers/CascadingListAnswerComponent" import { CascadingRefAnswerComponent, CascadingRefAnswerComponentRef } from "./answers/CascadingRefAnswerComponent" import { AdminRegionAnswerComponent, AdminRegionAnswerComponentRef } from "./answers/AdminRegionAnswerComponent" import RankedQuestion from "./answers/RankedQuestion" import ResponseRow from "./ResponseRow" import { Schema } from "@mwater/expressions" import { Choice, Question } from "./formDesign" import { AdminRegionAnswerValue, Answer, AssetAnswerValue, CascadingListAnswerValue, RankedAnswerValue, ResponseData } from "./response" import { FileValue } from "@mwater/expressions" import { AssetAnswerComponent } from "./answers/AssetAnswerComponent" import FileAnswerComponent from "./answers/FileAnswerComponent" import FilesAnswerComponent from "./answers/FilesAnswerComponent" import { InnerFormContext } from "./formContext" import { convertMarkdownToHtml } from "./formUtils" import LargeCheckbox from "./LargeCheckbox" export interface QuestionComponentProps { /** Design of question. See schema */ question: Question /** Current data of response (for roster entry if in roster) */ data: ResponseData /** ResponseRow object (for roster entry if in roster) */ responseRow: ResponseRow onAnswerChange: (answer: Answer) => void displayMissingRequired?: boolean onNext?: any schema: Schema formCtx: InnerFormContext } interface QuestionComponentState { helpVisible: any savedValue: any savedSpecify: any validationError: any } // Question component that displays a question of any type. // Displays question text and hint // Displays toggleable help // Displays required (*) // Displays comments field // Does NOT fill in when sticky and visible for first time. This is done by data cleaning // Does NOT remove answer when invisible. This is done by data cleaning // Does NOT check conditions and make self invisible. This is done by parent (ItemListComponent) // Displays alternates and makes exclusive with answer export default class QuestionComponent extends React.Component { comments: HTMLTextAreaElement | null = null answer: any unmounted!: boolean prompt: HTMLElement | null = null currentPositionFinder!: CurrentPositionFinder constructor(props: QuestionComponentProps) { super(props) this.state = { helpVisible: false, // True to display help validationError: null, // savedValue and savedSpecify are used to save the value when selecting an alternate answer savedValue: null, savedSpecify: null } } componentWillUnmount() { this.unmounted = true // Stop position finder if (this.currentPositionFinder) { return this.currentPositionFinder.stop() } } /** Speed up reloading by not updating questions that are simple. */ shouldComponentUpdate(nextProps: QuestionComponentProps, nextState: QuestionComponentState) { if (this.props.formCtx.locale !== nextProps.formCtx.locale) { return true } if (nextProps.question.textExprs != null && nextProps.question.textExprs.length > 0) { return true } if ((nextProps.question as any).choices != null) { for (let choice of (nextProps.question as any).choices as Choice[]) { if (choice.conditions != null && choice.conditions.length > 0) { return true } if (choice.conditionExpr != null) { return true } } } // Matrix questions are complicated as they can have calculations in cells // See https://github.com/mWater/monorepo/issues/248 if (nextProps.question._type === "MatrixQuestion") { return true } if (nextProps.question !== this.props.question) { return true } const oldAnswer = this.props.data[this.props.question._id] const newAnswer = nextProps.data[this.props.question._id] if (newAnswer !== oldAnswer) { return true } if (!_.isEqual(this.state, nextState)) { return true } return false } focus() { const { answer } = this if (answer != null && answer.focus != null) { return answer.focus() } } getAnswer(): Answer { // The answer to this question const answer = this.props.data[this.props.question._id] if (answer != null) { return answer as Answer } return {} as Answer } // Returns true if validation error async validate(scrollToFirstInvalid: boolean) { // If we are disabling confidential data return false if (this.props.formCtx.disableConfidentialFields && this.props.question.confidential) { return false } // If answer has custom validation, use that if (this.answer?.validate) { const answerInvalid = this.answer?.validate() if (answerInvalid && scrollToFirstInvalid) { this.prompt?.scrollIntoView() } if (answerInvalid) { this.setState({ validationError: answerInvalid }) return answerInvalid } } let validationError = await new AnswerValidator( this.props.schema, this.props.responseRow, this.props.formCtx.locale ).validate(this.props.question, this.getAnswer()) if (validationError != null) { if (scrollToFirstInvalid) { this.prompt?.scrollIntoView() } this.setState({ validationError }) return true } else { this.setState({ validationError: null }) return false } } handleToggleHelp = () => { return this.setState({ helpVisible: !this.state.helpVisible }) } handleValueChange = (value: any) => { return this.handleAnswerChange(_.extend({}, this.getAnswer(), { value }, { alternate: null })) } // Record a position found handleCurrentPositionFound = (loc: GeolocationPosition) => { if (!this.unmounted) { const newAnswer = _.clone(this.getAnswer()) newAnswer.location = _.pick(loc.coords, "latitude", "longitude", "accuracy", "altitude", "altitudeAccuracy") as any this.props.onAnswerChange(newAnswer) } } handleCurrentPositionStatus = (status: any) => { // Always record useable positions if (status.useable) { return this.handleCurrentPositionFound(status.pos) } } handleAnswerChange = (newAnswer: any) => { const readonly = this.props.formCtx.disableConfidentialFields && this.props.question.confidential if (readonly) { return } const oldAnswer = this.getAnswer() if (this.props.question.sticky && this.props.formCtx.stickyStorage != null && newAnswer.value != null) { // TODO: SurveyorPro: What should happen if value is set to null? // TODO: SurveyorPro: What should happen if alternate is set? (or anything else that didn't change the value field) this.props.formCtx.stickyStorage.set(this.props.question._id, newAnswer.value) } if (this.props.question.recordTimestamp) { newAnswer.timestamp = oldAnswer.timestamp ?? new Date().toISOString() } // Record location if no answer and not already getting location if (this.props.question.recordLocation && oldAnswer.location == null && !this.currentPositionFinder) { // Create location finder const locationFinder = this.props.formCtx.locationFinder || new LocationFinder() // Create position finder this.currentPositionFinder = new CurrentPositionFinder({ locationFinder }) // Listen to current position events (for setting location) this.currentPositionFinder.on("found", this.handleCurrentPositionFound) this.currentPositionFinder.on("status", this.handleCurrentPositionStatus) this.currentPositionFinder.start() } return this.props.onAnswerChange(newAnswer) } handleAlternate = (alternate: any) => { const answer = this.getAnswer() // If we are selecting a new alternate if (answer.alternate !== alternate) { // If old alternate was null (important not to do this when changing from an alternate value to another) if (answer.alternate == null) { // It saves value and specify this.setState({ savedValue: answer.value, savedSpecify: answer.specify }) } // Then clear value, specify and set alternate return this.handleAnswerChange( _.extend({}, answer, { value: null, specify: null, alternate }) ) } else { // Clear alternate and put back saved value and specify this.handleAnswerChange( _.extend({}, answer, { value: this.state.savedValue, specify: this.state.savedSpecify, alternate: null }) ) return this.setState({ savedValue: null, savedSpecify: null }) } } handleCommentsChange = (ev: any) => { return this.handleAnswerChange(_.extend({}, this.getAnswer(), { comments: ev.target.value })) } // Either jump to next question or select the comments box handleNextOrComments = (ev?: any) => { // If it has a comment box, set the focus on it if (this.props.question.commentsField) { // For some reason, comments can be null here sometimes this.comments?.focus() this.comments?.select() // Else we lose the focus and go to the next question } else { // Blur the input (remove the focus) if (ev) { ev.target.blur() } return this.props.onNext?.() } } renderPrompt() { const promptDiv = (
{ this.prompt = c }}> {this.props.question.code ? {this.props.question.code + ": "} : undefined} {/* Required star */} {this.props.question.required && !(this.props.formCtx.disableConfidentialFields && this.props.question.confidential) ? * : undefined} {this.props.question.help ? : undefined}
) // Special case! if (this.props.question._type === "CheckQuestion") { return ( { this.answer = c }} value={this.getAnswer().value as boolean | undefined} onValueChange={this.handleValueChange} > {promptDiv} ) } else { return promptDiv } } renderHint() { return (
{this.props.question.hint ?
{formUtils.localizeString(this.props.question.hint, this.props.formCtx.locale)}
: undefined} {this.props.formCtx.disableConfidentialFields && this.props.question.confidential ?
{this.props.formCtx.T("Confidential answers may not be edited.")}
: undefined}
) } renderHelp() { if (this.state.helpVisible && this.props.question.help) { const help = formUtils.localizeString(this.props.question.help, this.props.formCtx.locale) // Use the new utility function to convert Markdown to HTML const safeHtml = convertMarkdownToHtml(help) return (
) } return null } renderValidationError() { if (this.state.validationError != null && typeof this.state.validationError === "string") { return
{this.state.validationError}
} return null } renderAlternates() { if ( this.props.question.alternates && (this.props.question.alternates.na || this.props.question.alternates.dontknow) ) { return (
{this.props.question.alternates.dontknow ? this.handleAlternate("dontknow")} > {this.props.formCtx.T("Don't Know")} : undefined} {this.props.question.alternates.na ? this.handleAlternate("na")} > {this.props.formCtx.T("Not Applicable")} : undefined}
) } return null } renderCommentsField() { if (this.props.question.commentsField) { return (