import _ from "lodash" import React from "react" import { useEffect, useState } from "react" import * as formUtils from "./formUtils" import { Expr, PromiseExprEvaluator, Schema } from "@mwater/expressions" import { ExprUtils } from "@mwater/expressions" import { format } from "d3-format" import { LocalizedString } from "ez-localize" import ResponseRow from "./ResponseRow" import { convertMarkdownToHtml } from "./formUtils" export interface TextExprsComponentProps { /** String to render (localized) */ localizedStr?: LocalizedString /** Array of mwater-expressions to insert at {0}, {1}, etc. */ exprs?: Expr[] /** Schema that includes the current form */ schema: Schema /** response row to use */ responseRow: ResponseRow /** locale (e.g. "en") to use */ locale?: string /** True to render as markdown text */ markdown?: boolean /** Formats to be used by d3 formatter for numbers. Should match exprs */ exprFormats?: (string | undefined)[] } /** Displays a text string with optional expressions embedded in it that are computed */ const TextExprsComponent: React.FC = (props) => { const [exprValueStrs, setExprValueStrs] = useState([]) const evaluateExprs = async () => { if (!props.exprs || props.exprs.length === 0) { return } // Evaluate expressions const exprEvaluator = new PromiseExprEvaluator({ schema: props.schema }) const exprValues = await Promise.all(props.exprs.map(expr => exprEvaluator.evaluate(expr, { row: props.responseRow }).catch(() => ""))) // Format values const formattedValues = exprValues.map((value, index) => { if ((props.exprFormats && props.exprFormats[index]) && _.isNumber(value)) { return format(props.exprFormats[index] || "")(value) } return new ExprUtils(props.schema).stringifyExprLiteral(props.exprs![index], value, props.locale) }) // Only update state if changed if (!_.isEqual(formattedValues, exprValueStrs)) { setExprValueStrs(formattedValues) } } useEffect(() => { evaluateExprs().catch(() => setExprValueStrs(props.exprs!.map(() => ""))) }, [props.exprs, props.responseRow, props.schema, props.locale]) // Localize string let str = formUtils.localizeString(props.localizedStr, props.locale) || "" // Perform substitutions ({0}, {1}, etc.) str = str.replace(/\{(\d+)\}/g, (match: any, index: any) => { index = parseInt(index) if (exprValueStrs[index] != null) { return exprValueStrs[index] } return "..." }) if (props.markdown) { let html = str ? convertMarkdownToHtml(str) : "" // Make sure links are external html = html.replace(/