/** * The parts of a calculation card for calculator funnels (Funnelforms Pro): the functions clamp, * lookup, days and age with a table that writes lookup() for price tiers, texts by range of the * result ({{calc::text}}), the lead value and test dates for days() and age(). */ import React, { useState } from 'react'; import type { Calculation, CalcFunction, ExpressionNode, Field, FormDocument } from '@funnelforms/form-schema'; import { parseFormula, printFormula, rangeText } from '../calculations'; import type { Recipe } from '../store'; import { useEnv } from './context'; import { __, sprintf } from './i18n'; import { put, TextProp } from './texts'; import { Badge, Button, Field as FieldRow, IconButton, icons, Notice, Toggle } from './ui'; /** Most texts by range a calculation can have (form.v1.schema.json). */ const MAX_TEXTS = 20; function useChange(): ( recipe: Recipe, key?: string ) => void { return useEnv().store.getState().change; } /** Changes one calculation of the document. */ function useCalc( id: string ): ( recipe: ( c: Calculation ) => void, key: string ) => void { const change = useChange(); return ( recipe, key ) => change( ( d ) => { const c = d.calculations.find( ( x ) => x.id === id ); if ( c ) { recipe( c ); } }, `calc:${ id }:${ key }` ); } /** The new functions as the editor offers them, next to round(), if() and the others. */ export function moreFunctionHelp(): Array<{ fn: CalcFunction; insert: string; text: string }> { return [ { fn: 'clamp', insert: 'clamp(; ; )', text: __( 'Keeps a value between a minimum and a maximum: clamp([m2] * 12; 99; 2500).', 'funnelforms-pro' ) }, { fn: 'lookup', insert: 'lookup(; ; ; )', text: __( 'Price tiers: the value of the first limit the number is up to, else the last value. lookup([quantity]; 10; 25; 50; 20; 15).', 'funnelforms-pro' ) }, { fn: 'days', insert: 'days()', text: __( 'Days from today until a date field: days([move_date]). Days between two dates: days([arrival]; [departure]).', 'funnelforms-pro' ) }, { fn: 'age', insert: 'age()', text: __( 'Full years since a date field until today: age([birthday]).', 'funnelforms-pro' ) }, ]; } interface Tier { limit: string; value: string; } /** The parts of a lookup() whose limits are plain numbers, to edit it as a table; null for anything else. */ function tableOf( node: ExpressionNode ): { input: string; tiers: Tier[]; otherwise: string } | null { if ( ! ( 'fn' in node ) || 'lookup' !== node.fn || node.args.length < 4 || node.args.length % 2 ) { return null; } const [ input, ...rest ] = node.args; const otherwise = rest.pop(); const tiers: Tier[] = []; for ( let i = 0; i < rest.length; i += 2 ) { const limit = rest[ i ]; const value = rest[ i + 1 ]; if ( ! limit || ! value || ! ( 'num' in limit || ( 'neg' in limit && 'num' in limit.neg ) ) ) { return null; } tiers.push( { limit: printFormula( limit ), value: printFormula( value ) } ); } return input && otherwise ? { input: printFormula( input ), tiers, otherwise: printFormula( otherwise ) } : null; } /** The formula of a table: tiers by their limits, the smallest first; empty values count 0. */ export function lookupFormula( input: string, tiers: Tier[], otherwise: string ): string { const rows = tiers .map( ( t ) => ( { limit: Number( t.limit.replace( ',', '.' ) ), value: t.value.trim() || '0' } ) ) .filter( ( t ) => Number.isFinite( t.limit ) ) .sort( ( a, b ) => a.limit - b.limit ); return `lookup(${ [ input.trim() || '0', ...rows.flatMap( ( t ) => [ String( t.limit ), t.value ] ), otherwise.trim() || '0' ].join( '; ' ) })`; } /** * "Price table": tiers of a number, e.g. a price per piece by quantity or a price per zone, as * rows of "up to" and result. Writes lookup(); a formula that is such a lookup is edited in place. */ export function LookupTable( props: { expression: ExpressionNode; fields: Field[]; readOnly: boolean; insert: ( text: string ) => void; replace: ( text: string ) => void } ) { const { expression, fields, readOnly } = props; const [ open, setOpen ] = useState( false ); const [ input, setInput ] = useState( '' ); const [ tiers, setTiers ] = useState( [] ); const [ otherwise, setOtherwise ] = useState( '' ); const [ editing, setEditing ] = useState( false ); const start = (): void => { const table = tableOf( expression ); const first = fields.find( ( f ) => [ 'slider', 'number', 'choice', 'dropdown' ].includes( f.type ) ) ?? fields[ 0 ]; setEditing( null !== table ); setInput( table?.input ?? ( first ? `[${ first.key }]` : '' ) ); setTiers( table?.tiers ?? [ { limit: '10', value: '' }, { limit: '50', value: '' }, ] ); setOtherwise( table?.otherwise ?? '' ); setOpen( true ); }; if ( ! open ) { return (
{ __( 'Tiers without nested if(): a price per quantity, zone or size.', 'funnelforms-pro' ) }
); } const formula = lookupFormula( input, tiers, otherwise ); const parsed = parseFormula( formula ); const setTier = ( i: number, patch: Partial ): void => setTiers( ( list ) => list.map( ( t, j ) => ( i === j ? { ...t, ...patch } : t ) ) ); return (
{ ( id ) => (
setInput( e.target.value ) } />
) }
{ tiers.map( ( t, i ) => ( ) ) }
{ __( 'Up to', 'funnelforms-pro' ) } { __( 'Result', 'funnelforms-pro' ) }
setTier( i, { limit: e.target.value } ) } /> setTier( i, { value: e.target.value } ) } /> setTiers( ( list ) => list.filter( ( _, j ) => j !== i ) ) } />
{ __( 'Above that', 'funnelforms-pro' ) } setOtherwise( e.target.value ) } />
{ formula } { parsed.ok ? null : { __( 'A value of the table cannot be read. Use numbers, fields in [brackets] and the operators of formulas.', 'funnelforms-pro' ) } }
); } /** Texts by range of the result: "0 to 40: Beginner", "from 5,000: We recommend a visit". */ export function ResultTexts( { calc, result, readOnly }: { calc: Calculation; result: number | undefined; readOnly: boolean } ) { const { ctx, lang } = useEnv(); const set = useCalc( calc.id ); const texts = calc.texts ?? []; const token = `{{calc:${ calc.id }:text}}`; const current = rangeText( calc, result ); const number = ( value: string ): number | undefined => ( '' === value.trim() || ! Number.isFinite( Number( value ) ) ? undefined : Number( value ) ); const bound = ( i: number, key: 'from' | 'to', value: string ): void => set( ( c ) => { const range = c.texts?.[ i ]; if ( range ) { const n = number( value ); if ( undefined !== n ) { range[ key ] = n; } else if ( 'from' === key ) { delete range.from; } else { delete range.to; } } }, `texts.${ i }.${ key }` ); return (

{ __( 'Text by result', 'funnelforms-pro' ) }

{ __( 'A text for each range of the result, e.g. a level for a score or a recommendation for a high price. The first range the result lies in counts; an empty limit leaves the range open.', 'funnelforms-pro' ) }

{ texts.map( ( range, i ) => (
bound( i, 'from', e.target.value ) } /> bound( i, 'to', e.target.value ) } /> { current && current === range.text ? { __( 'Applies to the test', 'funnelforms-pro' ) } : null } set( ( c ) => void c.texts?.splice( i, 1 ), 'texts' ) } />
set( ( c ) => c.texts?.[ i ] && put( c.texts[ i ], 'text', lang, v, ctx.locale ), `texts.${ i }.text` ) } />
) ) }
{ texts.length ? ( { ( id ) => (
e.target.select() } />
) }
) : null }
); } /** "This is the order value of the lead": settings.valueCalculation. */ export function LeadValueToggle( { doc, calc, readOnly }: { doc: FormDocument; calc: Calculation; readOnly: boolean } ) { const change = useChange(); const on = doc.settings.valueCalculation === calc.id; const other = doc.calculations.find( ( c ) => c.id === doc.settings.valueCalculation && c.id !== calc.id ); return ( change( ( d ) => { if ( v ) { d.settings.valueCalculation = calc.id; } else if ( d.settings.valueCalculation === calc.id ) { delete d.settings.valueCalculation; } } ) } /> ); } /** A date for the test, in the format of the field: YYYY-MM-DD of the date input written as dd.mm.yy and so on. */ function formatted( iso: string, format: string ): string { const [ y = '', m = '', d = '' ] = iso.split( '-' ); return iso ? format.replace( 'dd', d ).replace( 'mm', m ).replace( 'yy', y ) : ''; } /** The YYYY-MM-DD of a date written in the format of the field, for the date input. */ function isoOf( text: string, format: string ): string { const order: string[] = format.match( /dd|mm|yy/g ) ?? []; const digits = text.match( /\d+/g ) ?? []; const part = ( key: string, size: number ): string => ( digits[ order.indexOf( key ) ] ?? '' ).padStart( size, '0' ); return 3 === digits.length ? `${ part( 'yy', 4 ) }-${ part( 'mm', 2 ) }-${ part( 'dd', 2 ) }` : ''; } /** Test answer of a date field: one date, or two for a period. */ export function DateTestAnswer( { field, value, onChange }: { field: Extract; value: unknown; onChange: ( v: unknown ) => void } ) { const format = field.props.format || 'dd.mm.yy'; const [ from = '', to = '' ] = ( 'string' === typeof value ? value : '' ).split( ' – ' ); const write = ( a: string, b: string ): void => onChange( field.props.range ? ( a && b ? `${ a } – ${ b }` : a ) : a ); return (
write( formatted( e.target.value, format ), to ) } /> { field.props.range ? write( from, formatted( e.target.value, format ) ) } /> : null }
); }