/** * The logic of the form in the properties panel: where visitors go after a step (by answer, by * rules, otherwise), the rules of one path, and when a field of a step is shown. Rules read as a * sentence: "Go to … when all of these apply: Budget is at least 5000 and …". */ import React, { useState } from 'react'; import type { Condition, Edge, FormDocument, FormNode } from '@funnelforms/form-schema'; import { calcRule, fieldsBefore, fromGroup, isGroup, opsFor, ruleKind, ruleOp, setAnswerRoute, starterRule, toGroup, withOp, type Between, type ConditionField, type Group, type Leaf, type Rule, type RuleKind, type RuleOp, } from '../conditions'; import { coverage } from '../coverage'; import { addEnd, connect, findNode, nodeName, removeEdge, setCondition, text } from '../document'; import { addRulePath, answerField, applyShownOrder, canAddRule, canMoveRule, moveRule, orderDiffers, outputsOf, settlePath, type RuleOutput } from '../ports'; import { isQuizEdge } from '../quiz'; import type { Recipe } from '../store'; import { useBuilder, useEnv } from './context'; import { describeCondition, fieldIndex, fieldTitle, opName, partName, ruleText } from './describe'; import { HintList, restText, useHints } from './Hints'; import { covered } from '../logic'; import { __, sprintf } from './i18n'; import { Button, IconButton, icons, Notice, Section } from './ui'; function useChange(): ( recipe: Recipe, key?: string ) => void { return useEnv().store.getState().change; } /** A node's name for lists, with what it is in front: "End: Thank you!". */ export function nodeLabel( node: FormNode, locale: string ): string { const name = nodeName( node, locale ) || __( 'Without a title', 'funnelforms-pro' ); const kind = 'step' === node.type ? __( 'Step', 'funnelforms-pro' ) : 'contact' === node.type ? __( 'Contact step', 'funnelforms-pro' ) : __( 'End', 'funnelforms-pro' ); return sprintf( '%1$s: %2$s', kind, name.length > 48 ? name.slice( 0, 47 ) + '…' : name ); } /* ------------------------------------------------------------------ targets */ const NEW_END = '#new-end'; /** * Where a path leads: any other node of the form, or a new end. `none` names the choice of no * node (empty value), when there is one. */ export function TargetSelect( { doc, from, value, label: name, none, onChange }: { doc: FormDocument; from: string; value: string; label: string; none?: string; onChange: ( to: string ) => void } ) { const { store, ctx, readOnly } = useEnv(); // Steps with the same title get their number in the form, so they can be told apart. const names = new Map(); doc.nodes.forEach( ( n ) => names.set( nodeName( n, ctx.locale ), ( names.get( nodeName( n, ctx.locale ) ) ?? 0 ) + 1 ) ); const label = ( n: FormNode ): string => { const name = nodeName( n, ctx.locale ) || __( 'Without a title', 'funnelforms-pro' ); return ( names.get( nodeName( n, ctx.locale ) ) ?? 0 ) > 1 ? sprintf( __( '%1$s (no. %2$d)', 'funnelforms-pro' ), name, doc.nodes.indexOf( n ) + 1 ) : name; }; const current = findNode( doc, value ); const groups: Array<[ string, FormNode[] ]> = [ [ __( 'Steps', 'funnelforms-pro' ), doc.nodes.filter( ( n ) => 'step' === n.type && n.id !== from ) ], [ __( 'Contact steps', 'funnelforms-pro' ), doc.nodes.filter( ( n ) => 'contact' === n.type && n.id !== from ) ], [ __( 'Ends', 'funnelforms-pro' ), doc.nodes.filter( ( n ) => 'end' === n.type ) ], ]; const choose = ( to: string ): void => { if ( NEW_END !== to ) { onChange( to ); return; } let id = ''; store.getState().change( ( d ) => { const at = d.layout?.nodes[ from ]; id = addEnd( d, ctx, { position: at ? { x: at.x + 320, y: at.y + 200 } : undefined } ); } ); onChange( id ); }; return ( ); } /* ------------------------------------------------------------------ rules */ /** A first rule: on the first field of the list, else on the first calculation. */ function firstLeaf( doc: FormDocument, fields: ConditionField[], prefer?: string, calcs = true ): Leaf | null { const ordered = prefer ? [ ...fields.filter( ( f ) => f.nodeId === prefer ), ...fields ] : fields; // Paths and shown fields of Funnelforms Free ask for a chosen answer only. for ( const f of 'free' === process.env.FUNNELFORMS_EDITION ? ordered.filter( ( x ) => 'option' === x.kind ) : ordered ) { const rule = starterRule( f.field ); if ( rule ) { return rule; } } const calc = calcs ? doc.calculations[ 0 ] : undefined; return calc ? calcRule( calc.id ) : null; } interface EditorProps { doc: FormDocument; /** Fields the rules may ask for. */ fields: ConditionField[]; /** Rules on calculations (not for fields, which the browser shows). */ calcs: boolean; /** Node whose fields come first in new rules. */ prefer?: string; } /** * Rules of a condition: a group whose rules must all or any hold, with groups of the other kind * inside for "A and (B or C)". Changes give the new condition, null without rules; typing in a * value passes a key, so a run of keystrokes is one step to undo. */ export function ConditionEditor( { value, lead, onChange, ...props }: EditorProps & { value: Condition | undefined; lead: string; onChange: ( condition: Condition | null, key?: string ) => void } ) { const group = toGroup( value ); return onChange( fromGroup( g ), key ) } />; } function GroupEditor( { group, depth, lead, onChange, onRemove, ...props }: EditorProps & { group: Group; depth: number; lead: string; onChange: ( group: Group, key?: string ) => void; onRemove?: () => void } ) { const { readOnly } = useEnv(); const set = ( i: number, item: Leaf | Between | Group, key?: string ): void => onChange( { ...group, items: group.items.map( ( x, j ) => ( j === i ? item : x ) ) }, key ); const remove = ( i: number ): void => onChange( { ...group, items: group.items.filter( ( _x, j ) => j !== i ) } ); const add = ( item: Leaf | Group | null ): void => { if ( item ) { onChange( { ...group, items: [ ...group.items, item ] } ); } }; const joiner = 'all' === group.mode ? __( 'and', 'funnelforms-pro' ) : __( 'or', 'funnelforms-pro' ); const first = (): Leaf | null => firstLeaf( props.doc, props.fields, props.prefer, props.calcs ); return (
{ lead } { group.items.length > 1 || depth ? ( ) : null } { onRemove ? : null }
{ group.items.map( ( item, i ) => ( { i > 0 ?
{ joiner }
: null } { isGroup( item ) ? ( set( i, g, key ) } onRemove={ () => remove( i ) } /> ) : ( set( i, l, key ) } onRemove={ () => remove( i ) } /> ) }
) ) }
{ 0 === depth && group.items.length > 0 ? ( ) : null }
); } const CALC_OPS: Array<'gte' | 'gt' | 'lte' | 'lt' | 'eq' | 'neq'> = [ 'gte', 'gt', 'lte', 'lt', 'eq', 'neq' ]; function LeafEditor( { doc, fields, calcs, leaf, onChange, onRemove }: EditorProps & { leaf: Leaf | Between; onChange: ( leaf: Leaf | Between, key?: string ) => void; onRemove: () => void } ) { const { ctx, readOnly } = useEnv(); if ( 'experiment' in leaf ) { const experiment = doc.experiments?.find( ( x ) => x.id === leaf.experiment ); return (
{ describeCondition( leaf, doc, ctx.locale ) + ( experiment?.name ? ` (${ experiment.name })` : '' ) }
); } // The subject: a field (its id) or a calculation ("calc:" and its id). const subject = 'calc' in leaf ? 'calc:' + leaf.calc : leaf.field; const known = fields.some( ( f ) => f.field.id === subject ) || ( 'calc' in leaf && doc.calculations.some( ( c ) => c.id === leaf.calc ) ); const all = fieldIndex( doc ); const steps: Array<[ string, ConditionField[] ]> = []; for ( const f of fields ) { const node = findNode( doc, f.nodeId ); const name = node ? nodeName( node, ctx.locale ) || __( 'Without a title', 'funnelforms-pro' ) : ''; const last = steps[ steps.length - 1 ]; if ( last && last[ 1 ][ 0 ]?.nodeId === f.nodeId ) { last[ 1 ].push( f ); } else { steps.push( [ name.length > 40 ? name.slice( 0, 39 ) + '…' : name, [ f ] ] ); } } const chooseSubject = ( value: string ): void => { if ( value.startsWith( 'calc:' ) ) { onChange( calcRule( value.slice( 5 ) ) ); return; } const next = fields.find( ( f ) => f.field.id === value ); const start = next ? starterRule( next.field ) : null; if ( start ) { onChange( start ); } }; const subjectSelect = ( ); const remove = ; if ( 'calc' in leaf ) { return (
{ subjectSelect } { remove }
onChange( { ...leaf, value: Number( e.target.value ) || 0 }, 'value' ) } />
); } return (
{ subjectSelect } { remove }
f.field.id === leaf.field ) ?? ( all.has( leaf.field ) ? { nodeId: '', field: all.get( leaf.field ) as NonNullable>, kind: ruleKind( all.get( leaf.field ) as NonNullable> ) ?? 'text' } : undefined ) } onChange={ onChange } />
); } type CalcRuleOp = ( typeof CALC_OPS )[ number ]; /** Comparison and value of a rule on an answer. */ function RuleInputs( { rule, field, onChange }: { rule: Rule | Between; field: ConditionField | undefined; onChange: ( rule: Rule | Between, key?: string ) => void } ) { const { ctx, readOnly } = useEnv(); const value = 'value' in rule ? rule.value : undefined; const kind: RuleKind = field?.kind ?? ( 'string' === typeof value ? 'text' : 'number' ); const op = ruleOp( rule ); const ops = opsFor( kind, field?.field ); const set = ( change: Partial>, key?: string ): void => { // Unset settings are left out, as the schema has no empty values for them. const next = Object.fromEntries( Object.entries( { ...rule, ...change } ).filter( ( [ , v ] ) => undefined !== v ) ); onChange( next as Rule | Between, key ); }; let input: React.ReactNode = null; if ( 'filled' === rule.op || 'empty' === rule.op ) { input = null; } else if ( 'between' === rule.op ) { input = ( <> set( { min: Number( e.target.value ) || 0 }, 'min' ) } /> { __( 'and', 'funnelforms-pro' ) } set( { max: Number( e.target.value ) || 0 }, 'max' ) } /> ); } else if ( ( 'selected' === rule.op || 'selectedOnly' === rule.op ) && field && 'options' in field.field ) { input = ( ); } else if ( 'dateBefore' === rule.op || 'dateAfter' === rule.op || 'dateOn' === rule.op ) { const today = 'today' === rule.value; input = ( <> { today ? null : ( e.target.value && set( { value: e.target.value } ) } /> ) } { const days = Math.trunc( Number( e.target.value ) || 0 ); set( { days: 0 === days ? undefined : Math.max( -36500, Math.min( 36500, days ) ) }, 'days' ); } } /> ); } else { const numeric = 'number' === typeof value; input = ( set( { value: numeric ? Number( e.target.value ) || 0 : e.target.value }, 'value' ) } /> ); } return (
{ 'address' === kind ? ( ) : null } { input }
); } /** * The condition of a path in Funnelforms Free: one chosen answer. Rules with "and" and "or", * numbers, texts or dates are Pro; a path that has one can get a rule of Free instead. */ function FreeCondition( { candidates, value, onChange, subject = 'path' }: { candidates: ConditionField[]; value: Condition | undefined; onChange: ( when: Condition ) => void; subject?: 'path' | 'field' } ) { const { ctx, readOnly } = useEnv(); const fields = candidates.filter( ( f ) => 'option' === f.kind && 'options' in f.field && f.field.options.length > 0 ); const rule = value && 'field' in value && 'selected' === value.op ? value : undefined; const current = rule ? fields.find( ( f ) => f.field.id === rule.field ) : undefined; const choose = ( id: string ): void => { const next = fields.find( ( f ) => f.field.id === id ); const start = next ? starterRule( next.field ) : null; if ( start ) { onChange( start ); } }; if ( ! fields.length ) { return

{ 'field' === subject ? __( 'A field can depend on the answer to a choice or dropdown question before it.', 'funnelforms-pro' ) : __( 'A path can ask for the answer to a choice or dropdown question before it.', 'funnelforms-pro' ) }

; } return (
{ value && ! rule ? ( { 'field' === subject ? __( 'This field has a condition of Funnelforms Pro. Choose a question and an answer to replace it, or show the field always.', 'funnelforms-pro' ) : __( 'This path has a condition of Funnelforms Pro. Choose a question and an answer to replace it.', 'funnelforms-pro' ) } ) : null }
{ __( 'when', 'funnelforms-pro' ) }
{ current && rule && 'options' in current.field ? (
{ __( 'is answered with', 'funnelforms-pro' ) }
) : null }
); } /* ------------------------------------------------------------------ one path */ /** * The rules, the target and the order of a path with a condition. `order` shows the buttons that * move a rule among the rules of its step (not where its row has them). */ /** Sets the condition of a path and keeps its place among the paths true to what is shown (ports.ts, settlePath). */ function setPath( doc: FormDocument, edgeId: string, when: Condition ): void { setCondition( doc, edgeId, when ); settlePath( doc, edgeId ); } export function PathEditor( { doc, edge, order = true, deletable = true }: { doc: FormDocument; edge: Edge; order?: boolean; deletable?: boolean } ) { const { readOnly } = useEnv(); const change = useChange(); const from = findNode( doc, edge.from ); const outputs = order && from ? outputsOf( doc, from ) : null; const up = !! outputs && canMoveRule( outputs, edge.id, -1 ); const down = !! outputs && canMoveRule( outputs, edge.id, 1 ); return (
{ __( 'Go to', 'funnelforms-pro' ) } change( ( d ) => void ( ( d.edges.find( ( e ) => e.id === edge.id ) ?? { to } ).to = to ) ) } />
{ 'free' === process.env.FUNNELFORMS_EDITION ? ( change( ( d ) => setPath( d, edge.id, when ) ) } /> ) : ( { if ( when ) { change( ( d ) => setPath( d, edge.id, when ), key ? `when:${ edge.id }:${ key }` : undefined ); } else if ( deletable ) { // Without rules the path would always be taken: it goes, as with "Delete rule". change( ( d ) => removeEdge( d, edge.id ) ); } else { change( ( d ) => setCondition( d, edge.id, null ) ); } } } /> ) }
{ up || down ? ( <> ) : null } { deletable ? ( ) : null }
); } /* ------------------------------------------------------------------ a node's way on */ /** * Where visitors go after a step or contact step, in the order the form checks it: rules * checked first, the answers of a choice, rules checked after them, and otherwise. Rules open in * place; the arrows move them. */ export function NodeLogic( { doc, node, title }: { doc: FormDocument; node: Extract; title?: string } ) { const { ctx, readOnly } = useEnv(); const change = useChange(); const hints = useHints().filter( ( h ) => h.node === node.id && 'unreachable' !== h.code ); const choices = 'step' === node.type ? node.fields.filter( ( f ) => 'options' in f && f.options.length > 0 ) : []; const [ by, setBy ] = useState( '' ); const [ open, setOpen ] = useState( null ); // As on the canvas: the field whose answers already have paths, unless another is chosen. const first = answerField( doc, node )?.id; const choice = choices.find( ( f ) => f.id === by ) ?? choices.find( ( f ) => f.id === first ) ?? choices[ 0 ]; const outputs = outputsOf( doc, node, choice?.id ); const routes = outputs.answers; const conditional = doc.edges.filter( ( e ) => e.from === node.id && ! e.default ); const fallback = outputs.otherwise; const quiz = conditional.some( ( e ) => isQuizEdge( doc, e ) ); const complete = ! fallback && conditional.length > 0 && covered( doc, node, conditional ); const cover = conditional.length ? coverage( doc, node ) : null; const rest = cover && ! cover.complete ? restText( cover.rest, ctx.locale ) : ''; const fields = fieldIndex( doc ); const before = outputs.rules.filter( ( r ) => r.first ); const after = outputs.rules.filter( ( r ) => ! r.first ); const answered = routes.some( ( r ) => r.edge ); const addRule = (): void => { let id: string | null = null; change( ( d ) => { id = addRulePath( d, node.id ); } ); setOpen( id ); }; // Nothing to ask for yet (a first step without a question): no rule to add. const addButton = ! canAddRule( doc, node.id ) ? null : ( ); if ( quiz ) { return (
{ __( 'The quiz sets the paths after the contact steps: visitors see the result their points reach. Change the results under Quiz in the settings.', 'funnelforms-pro' ) }
); } const ruleList = ( rules: RuleOutput[], lead: string | null ): React.ReactNode => rules.length ? ( <> { lead ?

{ lead }

: null }
    { rules.map( ( r ) => { const e = r.edge; const target = findNode( doc, e.to ); const expanded = open === e.id; const up = canMoveRule( outputs, e.id, -1 ); const down = canMoveRule( outputs, e.id, 1 ); return (
  1. h.edge === e.id ) ? ' has-hint' : '' ) }>
    { up || down ? ( change( ( d ) => moveRule( d, e.id, -1, choice?.id ) ) } /> change( ( d ) => moveRule( d, e.id, 1, choice?.id ) ) } /> ) : null }
    { expanded ? : null } { expanded ? h.edge === e.id ) } compact /> : null }
  2. ); } ) }
) : null; return (
{ orderDiffers( doc, node, choice?.id ) ? ( change( ( d ) => applyShownOrder( d, node.id, choice?.id ) ) }> { __( 'Use the order shown', 'funnelforms-pro' ) } } > { __( 'The form checks the paths of this step in another order than this list shows them (from an import). Where several apply, another path can win than you expect.', 'funnelforms-pro' ) } ) : null } { ruleList( before, answered || after.length ? __( 'Checked first', 'funnelforms-pro' ) : null ) } { choice ? (
{ choices.length > 1 ? ( ) : ( { choice && 'step' === node.type && node.fields.length > 1 ? sprintf( __( 'By answer to “%s”', 'funnelforms-pro' ), fieldTitle( choice, ctx.locale ) ) : __( 'By answer', 'funnelforms-pro' ) } ) }
    { routes.map( ( r, i ) => { const answer = text( r.option.label, ctx.locale ).replace( /<[^>]*>/g, '' ) || r.option.value; // A path for several answers is edited at the first of them. const edge = r.edge && routes.findIndex( ( x ) => x.edge?.id === r.edge?.id ) === i ? r.edge : undefined; const expanded = !! edge && open === edge.id; return (
  • { answer } change( ( d ) => setAnswerRoute( d, node.id, choice.id, r.option.id, to || null ) ) } /> { 'free' === process.env.FUNNELFORMS_EDITION ? null : edge ? ( setOpen( expanded ? null : edge.id ) } /> ) : ( ) }
    { expanded && edge ? (
    ) : null }
  • ); } ) }
{ 'choice' === choice.type && choice.props.multiple ?

{ __( 'With several answers chosen, the first answer in this list with its own step decides.', 'funnelforms-pro' ) }

: null }
) : null } { ruleList( after, __( 'Checked after the answers', 'funnelforms-pro' ) ) } { outputs.rules.length || choice ? addButton : null }
{ conditional.length ? __( 'Otherwise go to', 'funnelforms-pro' ) : __( 'Go to', 'funnelforms-pro' ) } change( ( d ) => { if ( to ) { connect( d, node.id, to ); } else { d.edges = d.edges.filter( ( e ) => ! ( e.from === node.id && e.default ) ); } } ) } />
{ complete ?

{ __( 'Every answer has its own next step.', 'funnelforms-pro' ) }

: null } { fallback && rest ?

{ sprintf( /* translators: %s: the answers that take the path without condition, e.g. "Other, 20 – 30" */ __( 'Applies to: %s', 'funnelforms-pro' ), rest ) }

: null } { outputs.rules.length || choice ? null : addButton }

{ __( 'Rules are checked from the top; the first that applies decides. You can also draw paths on the canvas.', 'funnelforms-pro' ) }

); } /* ------------------------------------------------------------------ a path selected on the canvas */ export function EdgeInspector( { doc, edgeId }: { doc: FormDocument; edgeId: string } ) { const { store, ctx, readOnly } = useEnv(); const change = useChange(); const select = store.getState().select; const hints = useHints().filter( ( h ) => h.edge === edgeId ); const edge = doc.edges.find( ( e ) => e.id === edgeId ); if ( ! edge ) { return null; } const from = findNode( doc, edge.from ); const to = findNode( doc, edge.to ); const route = (

{ from ? nodeName( from, ctx.locale ) || __( 'Without a title', 'funnelforms-pro' ) : '?' } { to ? nodeName( to, ctx.locale ) || __( 'Without a title', 'funnelforms-pro' ) : '?' }

); if ( isQuizEdge( doc, edge ) ) { return (
{ route } { edge.when ? describeCondition( edge.when, doc, ctx.locale ) + '. ' : '' } { __( 'The quiz sets the paths after the contact steps: visitors see the result their points reach. Change the results under Quiz, with nothing selected.', 'funnelforms-pro' ) }
); } const firstRule = (): Leaf | null => firstLeaf( doc, fieldsBefore( doc, edge.from ), edge.from ); const actions = ( { change( ( d ) => removeEdge( d, edge.id ) ); select( {} ); } } /> ); return ( <>
{ route } { edge.when ? ( <> ) : ( <>

{ __( 'Visitors take this path when no path with a condition applies.', 'funnelforms-pro' ) }

) }
{ from && 'end' !== from.type ? (
) : null } ); } /* ------------------------------------------------------------------ fields shown on answers */ /** When a field of a step with several fields is shown. */ export function FieldVisibility( { node, fieldId }: { node: Extract; fieldId: string } ) { const doc = useBuilder( ( s ) => s.doc ); const { readOnly } = useEnv(); const change = useChange(); const field = node.fields.find( ( f ) => f.id === fieldId ); const hints = useHints().filter( ( h ) => h.field === fieldId ); if ( ! doc || ! field || ( node.fields.length < 2 && ! field.showWhen ) ) { return null; } const fields = fieldsBefore( doc, node.id, field.id ); const write = ( when: Condition | null, key?: string ): void => change( ( d ) => { const n = findNode( d, node.id ); const f = n && 'step' === n.type ? n.fields.find( ( x ) => x.id === fieldId ) : undefined; if ( f ) { if ( when ) { f.showWhen = when; } else { delete f.showWhen; } } }, key ? `show:${ fieldId }:${ key }` : undefined ); const first = firstLeaf( doc, fields, node.id, false ); return (

{ __( 'Show this field', 'funnelforms-pro' ) }

{ ! field.showWhen && ! first ?

{ __( 'Fields can be shown on answers given above them or on earlier steps. Put the question it depends on first.', 'funnelforms-pro' ) }

: null } { field.showWhen ? ( <> { 'free' === process.env.FUNNELFORMS_EDITION ? ( write( when ) } /> ) : ( ) }

{ __( 'While hidden, the field is not required and its answer is not sent.', 'funnelforms-pro' ) }

) : null }
); }