import { CascadingRefAnswerValue, CascadingRefsAnswerValue } from "../response" import { CascadingRefQuestion } from "../formDesign" import React, { useState, useEffect } from "react" import { localizeString, normalizeCascadingRefsValue } from "../formUtils" import { Expr, ExprUtils, PromiseExprEvaluator, Row, Schema } from "@mwater/expressions" import { CustomRow } from "../CustomRow" /** Evaluated dropdown values of one selected row */ interface RowDropdownValues { /** Row _id */ id: string /** Stringified value of each dropdown in question order */ values: string[] } /** Displays a cascading reference question answer. Handles both a single row _id and, * for multiSelectLast questions, an array of row _ids */ export const CascadingRefDisplayComponent = (props: { question: CascadingRefQuestion value: CascadingRefAnswerValue | CascadingRefsAnswerValue locale?: string schema: Schema /** Get a specific row of a custom table */ getCustomTableRow: (tableId: string, rowId: string) => Promise /** * entityType: e.g. "water_point" * entityId: _id of entity * callback: called with an entity e.g. { _id: some id, a: "abc", b: 123 } or callback null if entity not found */ getEntityById: (entityType: string, entityId: string, callback: (entity: any) => void) => void }) => { const [rows, setRows] = useState() const [notFoundCount, setNotFoundCount] = useState(0) const [loading, setLoading] = useState(false) const multi = props.question.multiSelectLast === true // Ids to display. Single mode tolerates an array by taking the first id const ids: string[] = multi ? normalizeCascadingRefsValue(props.value) || [] : props.value ? [Array.isArray(props.value) ? props.value[0] : props.value] : [] const idsKey = ids.join("\n") useEffect(() => { let cancelled = false if (ids.length === 0) { setRows([]) setNotFoundCount(0) setLoading(false) return } setLoading(true) async function load() { const exprEvaluator = new PromiseExprEvaluator({ schema: props.schema, locale: props.locale }) const exprUtils = new ExprUtils(props.schema) // Get dropdown expressions, handling legacy case where expr is not specified const dropdownExprs: Expr[] = props.question.dropdowns.map( (dropdown) => dropdown.expr ?? { type: "field", table: props.question.tableId, column: dropdown.columnId! } ) const loaded = await Promise.all( ids.map(async (id): Promise => { const row = await props.getCustomTableRow(props.question.tableId, id) if (!row) { return null } const customRow = new CustomRow({ tableId: props.question.tableId, row, schema: props.schema, getEntityById: props.getEntityById, getCustomTableRow: props.getCustomTableRow }) const values: string[] = [] for (const dropdownExpr of dropdownExprs) { const value = await exprEvaluator.evaluate(dropdownExpr, { row: customRow }) values.push(value ? exprUtils.stringifyExprLiteral(dropdownExpr, value, props.locale) : "") } return { id, values } }) ) if (cancelled) { return } const found = loaded.filter((r): r is RowDropdownValues => r != null) setRows(found) setNotFoundCount(loaded.length - found.length) setLoading(false) } load().catch((err) => { throw err }) return () => { cancelled = true } }, [idsKey, props.question]) if (loading || !rows) { if (ids.length === 0) { return null } return (
) } const exprUtils = new ExprUtils(props.schema) /** Label of a dropdown, falling back to a summary of its expression */ const getDropdownName = (index: number) => { const dropdown = props.question.dropdowns[index] const dropdownExpr = dropdown.expr ?? { type: "field", table: props.question.tableId, column: dropdown.columnId! } return localizeString(dropdown.name, props.locale) || exprUtils.summarizeExpr(dropdownExpr, props.locale) } const notFound = notFoundCount > 0 ?
???
: null if (rows.length === 0) { return notFound } if (!multi) { return (
{rows[0].values.map((value, index) => (
{getDropdownName(index)}:  {value}
))} {notFound}
) } // Multi: show the upper levels once (from the first row) and then list the last level of each row const lastIndex = props.question.dropdowns.length - 1 return (
{rows[0].values.slice(0, lastIndex).map((value, index) => (
{getDropdownName(index)}:  {value}
))}
{getDropdownName(lastIndex)}:
    {rows.map((row) => (
  • {row.values[lastIndex]}
  • ))}
{notFound}
) }