import React, { forwardRef, useEffect, useImperativeHandle, useRef, useState } from "react" import _ from "lodash" import ReactSelect from "react-select" import { Select } from "@mwater/react-library/lib/bootstrap" import { AdminRegionQuestion } from "../formDesign" import { AdminRegionAnswerValue } from "../response" import { AdminRegionRow } from "../formContext" import { localizeString } from "../formUtils" /** Threshold above which we switch from native select to a searchable react-select */ const SEARCHABLE_THRESHOLD = 20 /** Option used by admin region dropdowns */ interface DropdownOption { /** Option label */ label: string /** Admin region id */ value: number } /** Localizes strings. Must be called as T("some string") or someThing.T("some string") */ type LocalizeString = (str: string, ...args: any[]) => string /** Props for admin region answer component */ export interface AdminRegionAnswerComponentProps { /** Question design */ question: AdminRegionQuestion /** Current answer value */ value?: AdminRegionAnswerValue /** Called when the committed answer value changes */ onValueChange: (value?: AdminRegionAnswerValue) => void /** Get a specific administrative region */ getAdminRegion: (id: number) => Promise /** Get child administrative regions */ getAdminRegionChildren: (parentId: number | null, level: number) => Promise /** Localizer to use */ T: LocalizeString /** Locale to use */ locale?: string /** True if an alternate is selected. Resets editing mode. */ alternateSelected?: boolean } /** Ref exposed by admin region answer component */ export interface AdminRegionAnswerComponentRef { /** Validate incomplete in-progress selections */ validate: () => string | boolean | null } /** Administrative region cascading dropdown answer component */ export const AdminRegionAnswerComponent = forwardRef((props, ref) => { const [countries, setCountries] = useState() const [optionsByLevel, setOptionsByLevel] = useState<{ [level: number]: AdminRegionRow[] }>({}) const [selectedIds, setSelectedIds] = useState>([]) const [editing, setEditing] = useState(false) const [loading, setLoading] = useState(false) const [error, setError] = useState() /** Last value emitted by this component via onValueChange. Used to ignore the round-trip * of our own commit so we don't refetch and stomp on options we just loaded. */ const lastEmittedValueRef = useRef<{ value: number | undefined } | undefined>(undefined) /** Monotonically increasing id for in-flight loadNextOptions calls so a stale response * cannot overwrite state that a newer selection has already populated. */ const nextOptionsRequestIdRef = useRef(0) const allowedLevels = props.question.allowedLevels || [] const countryIds = Array.from( new Set(allowedLevels.map(level => level.countryId).filter((id): id is number => id != null)) ) const allowAnyCountry = allowedLevels.some(level => level.countryId == null && level.level === 0) useImperativeHandle(ref, () => ({ validate: () => editing ? props.T("Incomplete selection") : null })) useEffect(() => { setCountries(undefined) setOptionsByLevel({}) setSelectedIds([]) setError(undefined) if (countryIds.length === 0 && !allowAnyCountry) { setCountries([]) return } setLoading(true) const countryPromise: Promise = allowAnyCountry ? props.getAdminRegionChildren(null, 0) : Promise.all(countryIds.map(countryId => props.getAdminRegion(countryId))) .then(rows => rows.filter((row): row is AdminRegionRow => row != null)) countryPromise .then(rows => { setCountries(_.sortBy(rows, row => row.name)) setLoading(false) }) .catch(err => { setError(err.message) setCountries([]) setLoading(false) }) }, [JSON.stringify(countryIds), allowAnyCountry]) useEffect(() => { if (!countries) { return } // If this value change is the echo of our own commit or clear, our local state // already represents it. Skipping avoids re-fetching the path or wiping out an // in-progress selection (e.g. the user just switched country at a level where // level 0 isn't a valid answer, so we cleared the value but kept the new country). const isOwnValueEcho = lastEmittedValueRef.current && props.value === lastEmittedValueRef.current.value && (props.value == null || selectedIds.includes(props.value)) if (isOwnValueEcho) { return } if (!props.value) { setSelectedIds([]) setOptionsByLevel({}) setEditing(false) return } loadPathForValue(props.value).catch(err => { setError(err.message) }) }, [countries, props.value]) useEffect(() => { if (props.alternateSelected && (editing || selectedIds.some(id => id != null))) { handleReset() } }, [props.alternateSelected, editing, selectedIds]) // Auto-select the country when there's exactly one and the country level itself is // not a valid answer (so picking it would be pointless). The country dropdown is // hidden in render below in the same conditions. useEffect(() => { if (!countries || countries.length !== 1 || allowAnyCountry) { return } if (props.value != null) { return } const onlyCountry = countries[0] if (isAllowedLevel(onlyCountry._id, 0)) { return } if (selectedIds[0] === onlyCountry._id) { return } setSelectedIds([onlyCountry._id]) const maxLevel = getMaxLevelForCountry(onlyCountry._id) if (maxLevel >= 1) { loadNextOptions(onlyCountry._id, 1).catch(err => { setError(err.message) }) } }, [countries, allowAnyCountry, props.value]) const getMaxLevelForCountry = (countryId: number) => { const levels = allowedLevels.filter(level => level.countryId === countryId).map(level => level.level) return levels.length > 0 ? Math.max(...levels) : 0 } const isAllowedLevel = (countryId: number, level: number) => { return allowedLevels.some(allowedLevel => (allowedLevel.countryId === countryId || allowedLevel.countryId == null) && allowedLevel.level === level ) } const getLevelLabel = (countryId: number, level: number, options?: AdminRegionRow[]) => { if (level === 0) { return props.T("Country") } const allowedLevel = allowedLevels.find(allowedLevel => allowedLevel.countryId === countryId && allowedLevel.level === level) if (allowedLevel) { return localizeString(allowedLevel.levelName, props.locale) } const optionType = options?.find(option => option.type)?.type return optionType || props.T("Level {0}", level) } const loadPathForValue = async (value: number) => { // Invalidate any in-flight loadNextOptions: their state is about to be replaced. nextOptionsRequestIdRef.current++ const region = await props.getAdminRegion(value) if (!region) { setSelectedIds([]) setOptionsByLevel({}) setEditing(false) return } const newSelectedIds: Array = [] newSelectedIds[0] = region.level0 for (let level = 1; level < region.level; level++) { newSelectedIds[level] = region[`level${level}`] as number } newSelectedIds[region.level] = region._id const newOptionsByLevel: { [level: number]: AdminRegionRow[] } = {} for (let level = 1; level <= region.level; level++) { const parentId = newSelectedIds[level - 1] if (parentId != null) { newOptionsByLevel[level] = await props.getAdminRegionChildren(parentId, level) } } setSelectedIds(newSelectedIds) setOptionsByLevel(newOptionsByLevel) setEditing(false) } const loadNextOptions = async (parentId: number, nextLevel: number) => { const requestId = ++nextOptionsRequestIdRef.current const options = await props.getAdminRegionChildren(parentId, nextLevel) if (requestId !== nextOptionsRequestIdRef.current) { return } setOptionsByLevel(current => ({ ...current, [nextLevel]: options })) } const commitSelection = (newSelectedIds: Array, selectedLevel: number) => { const countryId = newSelectedIds[0] const selectedId = newSelectedIds[selectedLevel] if (countryId != null && selectedId != null && isAllowedLevel(countryId, selectedLevel)) { setEditing(false) lastEmittedValueRef.current = { value: selectedId } props.onValueChange(selectedId) return } setEditing(selectedId != null) if (props.value != null) { lastEmittedValueRef.current = { value: undefined } props.onValueChange() } } const handleChange = (level: number, value: number | null) => { if (level === 0 && value == null) { handleReset() return } const newSelectedIds = selectedIds.slice(0, level + 1) newSelectedIds[level] = value setSelectedIds(newSelectedIds) const newOptionsByLevel: { [level: number]: AdminRegionRow[] } = {} for (const optionsLevelText of Object.keys(optionsByLevel)) { const optionsLevel = parseInt(optionsLevelText) if (optionsLevel <= level) { newOptionsByLevel[optionsLevel] = optionsByLevel[optionsLevel] } } setOptionsByLevel(newOptionsByLevel) if (value != null) { const countryId = newSelectedIds[0]! const maxLevel = getMaxLevelForCountry(countryId) if (level < maxLevel) { loadNextOptions(value, level + 1).catch(err => { setError(err.message) }) } commitSelection(newSelectedIds, level) return } if (level > 0) { commitSelection(newSelectedIds, level - 1) } } const handleReset = () => { setSelectedIds([]) setOptionsByLevel({}) setEditing(false) lastEmittedValueRef.current = { value: undefined } props.onValueChange() } const renderSelect = (level: number, label: string, options: AdminRegionRow[]) => { const dropdownOptions = options.map(option => ({ value: option._id, label: option.name })) const value = dropdownOptions.find(option => option.value === selectedIds[level]) ?? null const selectControl = dropdownOptions.length > SEARCHABLE_THRESHOLD ? ( value={value} options={dropdownOptions} onChange={opt => handleChange(level, opt ? opt.value : null)} getOptionValue={opt => opt.value.toString()} isClearable placeholder={props.T("Select...")} menuPortalTarget={document.body} styles={{ menu: (style) => ({ ...style, zIndex: 2000 }), menuPortal: (style) => ({ ...style, zIndex: 2000 }) }} /> ) : (