import React, { useState, useEffect, useRef, forwardRef, useImperativeHandle, ReactNode } from "react" import _ from "lodash" import ReactSelect from "react-select" import { CascadingRefAnswerValue, CascadingRefsAnswerValue } from "../response" import { CascadingRefQuestion, CascadingRefDropdown } from "../formDesign" import { Select } from "@mwater/react-library/lib/bootstrap" import { localizeString, normalizeCascadingRefsValue } from "../formUtils" import { Expr, ExprUtils, PromiseExprEvaluator, Row, Schema } from "@mwater/expressions" import { CustomRow } from "../CustomRow" import LargeCheckbox from "../LargeCheckbox" import { useStableCallback } from "@mwater/react-library/lib/useStableCallback" /** Threshold above which we switch from native select to a searchable react-select, and above which the multi-select checklist becomes a searchable multi-select */ const SEARCHABLE_THRESHOLD = 20 /** Number of rows above which "Select All" is not offered on the multi-select last level, as selecting that many is almost certainly a mistake */ const SELECT_ALL_LIMIT = 100 /** Option type used by the cascading ref dropdowns */ interface DropdownOption { label: string value: string | string[] } /** Localizes strings. Must be called as T("some string") or someThing.T("some string") */ type LocalizeString = (str: string, ...args: any[]) => string export interface Props { question: CascadingRefQuestion /** Row _id, or array of row _ids if question.multiSelectLast */ value?: CascadingRefAnswerValue | CascadingRefsAnswerValue onValueChange: (value?: CascadingRefAnswerValue | CascadingRefsAnswerValue) => void /** Schema which includes the custom tableset */ schema: Schema /** Localizer to use */ T: LocalizeString /** Locale to use */ locale?: string /** Get all rows of a custom table * @param tableId table id e.g. custom.abc.xyz */ getCustomTableRows: (tableId: string, filter: Expr, locale?: string) => Promise /** 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 /** True if an alternate is selected. Resets editing mode */ alternateSelected?: boolean } /** Row of a table with evaluated dropdown values */ interface RefRow { id: string /** Evaluated dropdown values */ dropdownValues: any[] } /** Entry of the multi-select checklist */ interface ChecklistItem { /** Row _id */ id: string /** Display label (value of the last dropdown) */ label: string } export interface CascadingRefAnswerComponentRef { validate: () => string | boolean | null } export const CascadingRefAnswerComponent = forwardRef((props, ref) => { const [refRows, setRefRows] = useState() const [dropdownValues, setDropdownValues] = useState() const [editing, setEditing] = useState(false) const [error, setError] = useState() /** Value most recently sent by this component in multi-select mode that differs from the incoming value. * Used to skip re-hydrating dropdowns from our own change, which would otherwise wipe a partially edited cascade */ const pendingEmit = useRef<{ value: CascadingRefsAnswerValue | undefined } | null>(null) const multi = props.question.multiSelectLast === true const lastIndex = props.question.dropdowns.length - 1 const createRefRows = useStableCallback(async (rows: Row[]) => { // Create ref rows and then fill them dropdown by dropdown const refRows = rows.map(row => { return { id: row._id, dropdownValues: props.question.dropdowns.map(c => null) } }) const exprEvaluator = new PromiseExprEvaluator({ schema: props.schema, locale: props.locale }) const tableId = props.question.tableId const schema = props.schema const customRows = rows.map((row) => { return new CustomRow({ tableId: props.question.tableId, row: row, schema: props.schema, getEntityById: props.getEntityById, getCustomTableRow: props.getCustomTableRow, }) }) async function fillDropdown(dropdown: CascadingRefDropdown, dropdownIndex: number) { const dropdownExpr = dropdown.expr ?? (dropdown.columnId ? { type: "field", table: tableId, column: dropdown.columnId! } : null) // Handle simple case of a field that can be easily evaluated (and is not an expression) if (dropdownExpr && dropdownExpr.type == "field" && schema.getColumn(dropdownExpr.table, dropdownExpr.column) && !schema.getColumn(dropdownExpr.table, dropdownExpr.column)!.expr) { for (let rowIndex = 0; rowIndex < refRows.length; rowIndex++) { refRows[rowIndex].dropdownValues[dropdownIndex] = rows[rowIndex][dropdownExpr.column] } } else { // Otherwise, need to evaluate expression await Promise.all(rows.map(async (row, rowIndex) => { refRows[rowIndex].dropdownValues[dropdownIndex] = await exprEvaluator.evaluate(dropdownExpr, { row: customRows[rowIndex] }) })) } } await Promise.all(props.question.dropdowns.map((dropdown, index) => fillDropdown(dropdown, index))) return refRows }) // Load rows useEffect(() => { setRefRows(undefined) setDropdownValues(undefined) // Load rows props.getCustomTableRows(props.question.tableId, props.question.filterExpr || null, props.locale) .then(async rows => { const newRefRows = await createRefRows(rows) setRefRows(newRefRows) }) .catch(err => { setRefRows([]) setError(err.message) }) }, [props.question.tableId, props.question.filterExpr, props.question.dropdowns]) // Set dropdown values if value changes useEffect(() => { if (!refRows) { return } if (multi) { // Skip if this is the echo of our own change. Local state is already consistent if (pendingEmit.current && _.isEqual(pendingEmit.current.value, props.value)) { pendingEmit.current = null return } pendingEmit.current = null // Hydrate the upper dropdowns from the first selected row that still exists const ids = normalizeCascadingRefsValue(props.value) const currentRefRow = ids ? refRows.find(row => ids.includes(row.id)) : undefined if (currentRefRow) { setDropdownValues(currentRefRow.dropdownValues.map((dv, index) => (index < lastIndex ? dv ?? "" : null))) } else { setDropdownValues(props.question.dropdowns.map(c => null)) } setEditing(false) return } if (props.value) { const currentRefRow = refRows.find(row => row.id == props.value) if (currentRefRow) { setDropdownValues(currentRefRow.dropdownValues.map(dv => dv ?? "")) } else { setDropdownValues(props.question.dropdowns.map(c => null)) } } else { setDropdownValues(props.question.dropdowns.map(c => null)) } setEditing(false) }, [refRows, props.value]) useEffect(() => { // Reset if alternate selected if ( props.alternateSelected && (editing || (dropdownValues && dropdownValues.some(dv => dv != null))) ) { setDropdownValues(props.question.dropdowns.map(c => null)) setEditing(false) } }, [props.alternateSelected, editing, dropdownValues, props.question.dropdowns]) useImperativeHandle(ref, () => ({ validate: () => { return editing ? props.T("Incomplete selection") : null } })) /** Sends a new multi-select value, remembering it so the hydration effect does not undo local state */ const emitMulti = (ids: string[]) => { const newValue = ids.length > 0 ? ids : undefined if (!_.isEqual(newValue, props.value)) { pendingEmit.current = { value: newValue } props.onValueChange(newValue) } } const handleChange = (index: number, value: string | string[] | null) => { const dropdowns = props.question.dropdowns // If first one reset, then reset entire control if (index === 0 && !value) { handleReset() return } const newDropdownValues = dropdownValues!.slice() newDropdownValues[index] = value // In multi-select mode the last dropdown is a checklist and is never auto-filled const autoFillEnd = multi ? lastIndex : dropdowns.length // For each afterwards, set to null let pos = index + 1 for (; pos < dropdowns.length; pos++) { newDropdownValues[pos] = null } // For each afterwards, set if has single value, or otherwise set to null pos = index + 1 for (; pos < autoFillEnd; pos++) { const values = findValues(pos, newDropdownValues) if (values.length == 1) { newDropdownValues[pos] = values[0] ?? "" } else { break } } // Set rest to null for (; pos < props.question.dropdowns.length; pos++) { newDropdownValues[pos] = null } if (multi) { // Changing an upper level invalidates the current selection setDropdownValues(newDropdownValues) const upperComplete = _.range(0, lastIndex).every(i => newDropdownValues[i] != null) setEditing(!upperComplete) emitMulti([]) return } // If all set, change value if (newDropdownValues[dropdowns.length - 1] != null) { // Find row for (const row of refRows!) { let exclude = false for (let pos = 0; pos < dropdowns.length; pos++) { if (!isMatch(row.dropdownValues[pos], newDropdownValues[pos])) { exclude = true } } if (!exclude) { // No longer editing setDropdownValues(newDropdownValues) setEditing(false) props.onValueChange(row.id) return } } } setDropdownValues(newDropdownValues) setEditing(true) } const handleReset = () => { setDropdownValues(props.question.dropdowns.map(c => null)) setEditing(false) if (multi) { emitMulti([]) } else { props.onValueChange() } } /** Rows that match all dropdown selections before index */ const findMatchingRows = (index: number, currentDropdownValues: Array) => { return refRows!.filter(row => { for (let prev = 0; prev < index; prev++) { if (!isMatch(row.dropdownValues[prev], currentDropdownValues[prev])) { return false } } return true }) } const findValues = (index: number, currentDropdownValues: Array) => { let values: string[] = findMatchingRows(index, currentDropdownValues).map(row => row.dropdownValues[index] ?? "") // Keep unique values values = _.uniq(values) return values } /** Gets the expression of a dropdown, handling the legacy columnId case */ const getDropdownExpr = (dropdown: CascadingRefDropdown): Expr => { return dropdown.expr ?? { type: "field", table: props.question.tableId, column: dropdown.columnId! } } const renderDropdown = (index: number) => { const dropdown = props.question.dropdowns[index] // Determine available options const options: { label: string; value: string | string[] }[] = [] // Find all possible values, filtering by all previous selections const values = findValues(index, dropdownValues!) // Get expression type const dropdownExpr = getDropdownExpr(dropdown) const exprUtils = new ExprUtils(props.schema) const exprType = exprUtils.getExprType(dropdownExpr) const exprEnumValues = exprUtils.getExprEnumValues(dropdownExpr) if (!exprType) { // Not localized because should not happen return
Missing column
} // If enum if (exprType == "enum" && exprEnumValues) { for (const enumValue of _.sortBy(exprEnumValues, e => e.name[e.name._base])) { // Add if in values if (values.includes(enumValue.id)) { options.push({ value: enumValue.id, label: localizeString(enumValue.name, props.locale) }) } } } else if (exprType == "enumset" && exprEnumValues) { for (const enumValue of _.sortBy(exprEnumValues, e => e.name[e.name._base])) { // Add if in values if (values.some(v => v.includes(enumValue.id))) { options.push({ value: [enumValue.id], label: localizeString(enumValue.name, props.locale) }) } } // If current value is a multi-value array, then add as is if (Array.isArray(dropdownValues![index]) && dropdownValues![index].length > 1) { options.push({ value: dropdownValues![index], label: exprUtils.stringifyExprLiteral(dropdownExpr, dropdownValues![index], props.locale) }) } } else if (exprType == "text") { // Text are added as is, converting null value to "" and label to emdash for (const value of values.sort()) { options.push({ value: value ?? "", label: value || "—" }) } } const selectControl = options.length > SEARCHABLE_THRESHOLD ? ( value={options.find(o => JSON.stringify(o.value) === JSON.stringify(dropdownValues![index])) ?? null} options={options} onChange={(opt) => handleChange(index, opt ? opt.value as any : null)} getOptionValue={(opt) => JSON.stringify(opt.value)} isClearable placeholder={props.T("Select...")} menuPortalTarget={document.body} styles={{ menu: (style) => ({ ...style, zIndex: 2000 }), menuPortal: (style) => ({ ...style, zIndex: 2000 }) }} /> ) : ( value={dropdownValues![index]} options={options} nullLabel={props.T("Select...")} onChange={handleChange.bind(null, index)} /> ) return (
{selectControl} {dropdown.hint ?
{localizeString(dropdown.hint, props.locale)}
: null}
) } /** Creates the checklist items for the last level: one per row matching the upper dropdowns, sorted by label. * Rows with a blank last-level value are left out: they cannot be told apart, nor written to or read back * from the one-value-per-line export */ const createChecklistItems = (): ChecklistItem[] | null => { const dropdown = props.question.dropdowns[lastIndex] const dropdownExpr = getDropdownExpr(dropdown) const exprUtils = new ExprUtils(props.schema) const exprType = exprUtils.getExprType(dropdownExpr) if (!exprType) { return null } const items: ChecklistItem[] = [] for (const row of findMatchingRows(lastIndex, dropdownValues!)) { const value = row.dropdownValues[lastIndex] if (value == null || (Array.isArray(value) && value.length === 0)) { continue } const label = exprType == "text" ? String(value) : exprUtils.stringifyExprLiteral(dropdownExpr, value, props.locale) || "" if (label.trim() === "") { continue } items.push({ id: row.id, label }) } return _.sortBy(items, item => item.label.toLowerCase()) } const renderChecklist = () => { const dropdown = props.question.dropdowns[lastIndex] const items = createChecklistItems() if (!items) { // Not localized because should not happen return
Missing column
} const selectedIds = normalizeCascadingRefsValue(props.value) || [] const selectedSet = new Set(selectedIds) // Number of selected ids that are no longer in the table or no longer match the upper levels const availableSet = new Set(items.map(item => item.id)) const unavailableCount = selectedIds.filter(id => !availableSet.has(id)).length // Large lists use a searchable multi-select instead of a long column of checkboxes const useSelect = items.length > SEARCHABLE_THRESHOLD /** Rebuilds the value from the available rows, so stale ids are dropped on any change */ const setSelected = (isSelected: (item: ChecklistItem) => boolean) => { emitMulti(items.filter(isSelected).map(item => item.id)) } const handleToggle = (id: string) => { setSelected(item => (item.id === id ? !selectedSet.has(id) : selectedSet.has(item.id))) } const handleSelectAll = () => { setSelected(() => true) } const handleClear = () => { setSelected(() => false) } const selectedCount = items.filter(item => selectedSet.has(item.id)).length return (
{items.length <= SELECT_ALL_LIMIT ? ( ) : null} {props.T("{0} of {1} selected", selectedCount, items.length)}
{items.length === 0 ?
{props.T("No options available")}
: null} {useSelect ? ( isMulti value={items.filter(item => selectedSet.has(item.id))} options={items} getOptionValue={item => item.id} getOptionLabel={item => item.label} onChange={opts => { const chosen = new Set(opts.map(opt => opt.id)) setSelected(item => chosen.has(item.id)) }} closeMenuOnSelect={false} placeholder={props.T("Select...")} menuPortalTarget={document.body} styles={{ menu: (style) => ({ ...style, zIndex: 2000 }), menuPortal: (style) => ({ ...style, zIndex: 2000 }) }} /> ) : ( items.map(item => ( handleToggle(item.id)} > {item.label} )) )} {unavailableCount > 0 ? (
{props.T("{0} previously selected option(s) are no longer available and will be removed when the selection is changed", unavailableCount)}
) : null} {dropdown.hint ?
{localizeString(dropdown.hint, props.locale)}
: null}
) } // If error accessing rows if (error) { return (
{error}
) } if (!refRows || !dropdownValues) { return (
{props.T("Loading question data. This may take several minutes...")}
) } const dropdowns: ReactNode[] = [] let checklistRendered = false for (let i = 0; i < props.question.dropdowns.length; i++) { if (multi && i === lastIndex) { dropdowns.push(renderChecklist()) checklistRendered = true break } dropdowns.push(renderDropdown(i)) // Skip rest if not selected if (!dropdownValues[i]) { break } } // If no data, probably internet issue or not set up if (refRows.length == 0) { return (
{props.T( "No data found for question. Please ensure that you are connected to internet for the first use of this form." )}
) } // In multi-select mode, selected rows that no longer exist would otherwise be invisible when the checklist is not shown. // The checklist itself reports unavailable selections when it is shown. const multiSelectedIds = multi && !checklistRendered ? normalizeCascadingRefsValue(props.value) : null const multiOrphaned = multiSelectedIds != null && !refRows.some(row => multiSelectedIds.includes(row.id)) return (
{multiOrphaned ? (
{props.T("{0} previously selected option(s) are no longer available and will be removed when the selection is changed", multiSelectedIds!.length)}
) : null} {dropdowns}
) }) /** Match values, coercing null to "" and allowing arrays to match * if they have any value in common */ function isMatch(value: any, expectedValue: any) { // Exact match works if ((value ?? "") == (expectedValue ?? "")) { return true } if (Array.isArray(value) && Array.isArray(expectedValue)) { return _.intersection(value, expectedValue).length > 0 } return false }