/** * The editor of one form: top bar (name, save state, workspaces, undo, revisions, publish) and * the open workspace: the palette, the canvas and the properties of what is selected, or the * design, the settings, the actions or the ways to embed the form. The figures of a form are on * the statistics page; from there the editor can open with them on the canvas (figures). */ import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'; import { useStore } from 'zustand'; import type { AiConfig, FormsApi, Revision } from '../api'; import { AiBar } from './AiForm'; import { deliveryWarnings } from '../actions'; import { asksFor, duplicateField, duplicateNode, isClip, pasteField, pasteNode, removeEdge, removeField, removeNode, type Clip } from '../document'; import { ChangeNotice, fieldsOf, removeWithNotice } from './Removal'; import { createBuilderStore, type BuilderStore } from '../store'; import { Canvas } from './Canvas'; import { problemTexts, rightName } from './catalog'; import { BuilderContext, DEFAULT_RIGHTS, SHORTCUTS_EVENT, useBuilder, useEnv, ViewContext, type BuilderEnv, type Rights, type View } from './context'; import { __, sprintf } from './i18n'; import { Inspector } from './Inspector'; import { LanguagePicker } from './Languages'; import { Palette } from './Palette'; import { EmbedWorkspace } from './Embed'; import type { EmbedConfig } from '../embed'; import { DraftPreview } from './Preview'; import { AnalyticsContext, useAnalyticsState, type Analytics } from './Analytics'; import { PredictionContext, predictionBadge, usePredictionState, type PredictionMode } from './Prediction'; import { PredictionWorkspace } from './PredictionWorkspace'; import { canvasFigures, FiguresContext } from './Stats'; import type { StepFigures } from '../stats'; import { StatusBadge } from './FormsList'; import { Tour, TourIcon, tourSeen } from './Tour'; import { Button, Dialog, icons, Notice, Spinner, TextInput } from './ui'; import { ActionsWorkspace, DesignWorkspace, SettingsWorkspace } from './Workspaces'; import type { Labels } from '../document'; import type { ContactField, Field, FormDocument } from '@funnelforms/form-schema'; export interface BuilderProps { api: FormsApi; formId: number; onBack: () => void; /** Default texts of new fields for a form language; English for languages without. */ labelsFor?: ( locale: string ) => Labels | undefined; /** Store to use (tests); by default one is made for the form. */ store?: BuilderStore; rights?: Rights; /** Offers the tour through the builder, by itself the first time in this browser. */ tour?: boolean; /** Workspace to open first; the canvas by default. */ view?: View; /** Opens with the figures on the canvas ("Show on the canvas" on the statistics page). */ figures?: boolean; /** The embed code for other websites (Funnelforms Pro); without it that way is not offered. */ embed?: EmbedConfig | null; /** The AI form builder (Funnelforms Pro); without it "Edit with AI" is not offered. */ ai?: AiConfig | null; } export function Builder( { api, formId, onBack, labelsFor, store: given, rights = DEFAULT_RIGHTS, tour = false, view: first = 'build', figures: withFigures = false, embed, ai }: BuilderProps ) { const store = useMemo( () => given ?? createBuilderStore( api, formId ), [ api, formId, given ] ); useEffect( () => { void store.getState().load(); return () => store.getState().dispose(); }, [ store ] ); const status = useStore( store, ( s ) => s.status ); const loadError = useStore( store, ( s ) => s.loadError ); const locale = useStore( store, ( s ) => s.doc?.locales.default ?? 'en_US' ); // A language removed meanwhile (or by undo) falls back to the default language. const lang = useStore( store, ( s ) => ( s.lang && s.doc?.locales.available.includes( s.lang ) ? s.lang : locale ) ); const locked = useStore( store, ( s ) => 'locked' === s.save.state ); // Funnelforms Free shows the figures per step on the canvas; Pro has the analytics mode instead. const [ figures, setFigures ] = useState<{ figures: StepFigures; label: string } | null>( null ); // The edition is a constant of the build, so the order of the hooks stays the same. const analyticsState = 'free' === process.env.FUNNELFORMS_EDITION ? null : useAnalyticsState( api, formId, store ); // The figures need the right to see entries, so the mode is off without it. const analyticsMode = rights.entries ? analyticsState : null; const [ chosen, showView ] = useState( first ); // The prediction (Predictive AI) needs the AI form builder; one of the two modes at a time. // Its tab and the canvas mode share it, so a new analysis in the tab shows on the canvas. const predictionState = 'free' === process.env.FUNNELFORMS_EDITION ? null : usePredictionState( api, formId, store, ai, 'predict' === chosen, locked ); const prediction = useMemo( () => predictionState && { ...predictionState, setOn: ( on: boolean ) => { if ( on ) { analyticsMode?.setOn( false ); } predictionState.setOn( on ); }, }, [ predictionState, analyticsMode ] ); const analytics = useMemo( () => analyticsMode && { ...analyticsMode, setOn: ( on: boolean ) => { if ( on ) { predictionState?.setOn( false ); } analyticsMode.setOn( on ); }, }, [ analyticsMode, predictionState ] ); const [ touring, setTouring ] = useState( false ); // Publishing, with the note it starts with (e.g. from the Predictive AI); null: closed. const [ publishNote, setPublishNote ] = useState( null ); // Without the prediction (Funnelforms Free, no AI) its tab is not there: the canvas instead. const view: View = 'predict' === chosen && ! prediction ? 'build' : chosen; const doc = useStore( store, ( s ) => s.doc ); /** * What happens after sending is edited at the contact step whose entries it handles; the * former workspace of its own stays only for forms without a contact step. */ const setView = useCallback( ( next: View ): void => { const contact = 'actions' === next ? store.getState().doc?.nodes.find( ( n ) => 'contact' === n.type ) : undefined; if ( contact ) { store.getState().select( { node: contact.id }, 'logic' ); showView( 'build' ); return; } showView( next ); }, [ store ] ); useEffect( () => { if ( 'ready' === status && 'actions' === view ) { setView( 'actions' ); } }, [ status, view, setView ] ); useFoldedMenu(); // From the statistics page: the figures on the steps, once the form is loaded. Only once: the // switch of the mode changes with every state of both modes, and turning the figures on again // then would keep them from being turned off and the prediction from being turned on. const setAnalyticsOn = analytics?.setOn; const figuresOpened = useRef( false ); useEffect( () => { if ( ! withFigures || ! rights.entries || 'ready' !== status || figuresOpened.current ) { return; } if ( setAnalyticsOn ) { figuresOpened.current = true; setAnalyticsOn( true ); return; } let cancelled = false; canvasFigures( api, formId ).then( ( shown ) => { if ( ! cancelled ) { setFigures( shown ); } }, // Without figures the canvas simply shows the form. () => undefined ); return () => { cancelled = true; }; }, [ withFigures, rights.entries, status, setAnalyticsOn, api, formId ] ); useEffect( () => { // Not over a workspace the address asked for, or the figures from the statistics page. if ( tour && 'ready' === status && ! tourSeen() && 'build' === first && ! withFigures ) { setTouring( true ); } }, [ tour, status, first, withFigures ] ); const env = useMemo( () => ( { api, rights, store, ctx: { locale, labels: labelsFor?.( locale ) }, lang, readOnly: locked } ), [ api, rights, store, locale, lang, labelsFor, locked ] ); // The tour shows the parts of the canvas workspace. const startTour = (): void => { setView( 'build' ); setTouring( true ); }; if ( 'loading' === status ) { return ; } if ( 'failed' === status ) { return (
} > { loadError }
); } return (
{ figures && 'build' === view ? (
{ sprintf( __( 'The steps show the figures of %s: page views that reached them and left there.', 'funnelforms-pro' ), figures.label ) }
) : null } { 'build' === view ? (
) : null } { 'design' === view ? : null } { 'settings' === view && doc ? : null } { 'actions' === view && doc ? : null } { 'predict' === view && prediction ? ( { prediction.setOn( true ); if ( node ) { store.getState().select( { node } ); } setView( 'build' ); } } onPublish={ locked ? undefined : setPublishNote } /> ) : null } { 'embed' === view ? : null }
{ touring ? setTouring( false ) } /> : null }
); } function SaveState() { const save = useBuilder( ( s ) => s.save ); const saveNow = useEnv().store.getState().saveNow; const texts: Record = { saved: __( 'All changes saved', 'funnelforms-pro' ), dirty: __( 'Unsaved changes', 'funnelforms-pro' ), saving: __( 'Saving…', 'funnelforms-pro' ), error: __( 'Not saved. Trying again…', 'funnelforms-pro' ), offline: __( 'Offline. Saving when you are back online.', 'funnelforms-pro' ), locked: __( 'Read only', 'funnelforms-pro' ), }; return ( ); } /** * The workspaces in the top bar. The figures of a form are no workspace of the editor: they live * under Funnelforms → Statistics, in both editions. */ function Views( { view, onView, prediction }: { view: View; onView: ( view: View ) => void; prediction: PredictionMode | null } ) { const views: Array<[ View, string ]> = [ [ 'build', __( 'Structure', 'funnelforms-pro' ) ], [ 'design', __( 'Design', 'funnelforms-pro' ) ], [ 'settings', __( 'Settings', 'funnelforms-pro' ) ], ...( prediction ? [ [ 'predict', __( 'Predictive AI', 'funnelforms-pro' ) ] as [ View, string ] ] : [] ), [ 'embed', __( 'Embed', 'funnelforms-pro' ) ], ]; const badge = predictionBadge( prediction ); return ( ); } function TopBar( { api, formId, onBack, view, onView, onTour, prediction, publishNote, onPublish }: { api: FormsApi; formId: number; onBack: () => void; view: View; onView: ( view: View ) => void; onTour?: () => void; prediction: PredictionMode | null; publishNote: string | null; onPublish: ( note: string | null ) => void } ) { const { store, readOnly } = useEnv(); const form = useBuilder( ( s ) => s.form ); const title = useBuilder( ( s ) => s.doc?.title ?? '' ); const canUndo = useBuilder( ( s ) => s.canUndo ); const canRedo = useBuilder( ( s ) => s.canRedo ); const problems = useBuilder( ( s ) => problemTexts( s.problems ).length + s.missingRights.length ); const { undo, redo } = store.getState(); const [ revisions, setRevisions ] = useState( false ); const [ previewing, setPreviewing ] = useState( false ); return (
{ onTour ?
{ null !== publishNote ? ( onPublish( null ) } onEmbed={ () => { onPublish( null ); onView( 'embed' ); } } /> ) : null } { previewing ? setPreviewing( false ) } /> : null } { revisions ? setRevisions( false ) } /> : null }
); } /** The workspaces under the AI bar (Funnelforms Pro with the AI form builder); without it the workspaces alone. */ function AiWorkspaces( { api, ai, formId, show, children }: { api: FormsApi; ai?: AiConfig | null; formId: number; show: boolean; children: React.ReactNode } ) { if ( 'free' === process.env.FUNNELFORMS_EDITION || ! ai ) { return <>{ children }; } return ( { children } ); } /** Folds the admin menu of WordPress while the editor is open, for room on the canvas. */ function useFoldedMenu(): void { useEffect( () => { const body = document.body; if ( body.classList.contains( 'folded' ) ) { return undefined; } body.classList.add( 'folded' ); return () => body.classList.remove( 'folded' ); }, [] ); } function LockedBanner() { const { store } = useEnv(); const save = useBuilder( ( s ) => s.save ); const [ error, setError ] = useState( null ); if ( 'locked' !== save.state ) { return null; } const name = save.lockedBy?.name ?? __( 'Someone else', 'funnelforms-pro' ); return (
{ setError( null ); store .getState() .takeOver() .catch( ( e: unknown ) => setError( e instanceof Error ? e.message : String( e ) ) ); } } > { __( 'Take over', 'funnelforms-pro' ) } } > { __( 'You can look at it, but your changes are not saved. If you take over, changes the other person has not saved yet are lost.', 'funnelforms-pro' ) } { error ?

{ error }

: null }
); } function PublishDialog( { note: initialNote = '', onClose, onEmbed }: { note?: string; onClose: () => void; onEmbed: () => void } ) { const { store } = useEnv(); const publishing = useBuilder( ( s ) => s.publishing ); const problems = useBuilder( ( s ) => s.problems ); const missingRights = useBuilder( ( s ) => s.missingRights ); const form = useBuilder( ( s ) => s.form ); const doc = useBuilder( ( s ) => s.doc ); const delivery = useMemo( () => ( doc ? deliveryWarnings( doc ) : [] ), [ doc ] ); const [ note, setNote ] = useState( initialNote ); const busy = 'publishing' === publishing.state; const done = 'published' === publishing.state; const blocked = problems.length > 0 || missingRights.length > 0; const stays = publishing.stays ?? []; const onLegacy = 'legacy' === form?.renderer && stays.length > 0; useEffect( () => { // Show the state of the current draft, not of an earlier attempt. void store.getState().saveNow(); }, [ store ] ); return ( ) : ( <> ) } > { done && onLegacy ? ( <> { /* A form from 3.x that could not move: the pages keep showing the 3.x form, only the preview shows this version. */ }

{ __( 'The new version is published and the preview shows it. Visitors see it once the form runs on Funnelforms 5, and for that this is missing:', 'funnelforms-pro' ) }

    { stays.map( ( stay ) => (
  • { stay.title } { stay.fix } { stay.url && stay.link ? { stay.link } : null }
  • ) ) }
{ form ? { form.shortcode } : null } ) : done ? ( <>

{ __( 'Visitors now see this version. Embed it with the shortcode, the block or the Elementor widget:', 'funnelforms-pro' ) }

{ form ? { form.shortcode } : null } { publishing.warnings.length ? (
    { problemTexts( publishing.warnings ).map( ( w ) => (
  • { w }
  • ) ) }
) : null } ) : ( <> { problems.length ? (
    { problemTexts( problems ).map( ( p ) => (
  • { p }
  • ) ) }
) : null } { missingRights.length ? (
    { missingRights.map( ( r ) => (
  • { rightName( r ) }
  • ) ) }
) : null } { delivery.length ? (
    { delivery.includes( 'nobody' ) ?
  • { __( 'Nobody is told about new entries. Add an "E-mail to you" under "After sending".', 'funnelforms-pro' ) }
  • : null } { delivery.includes( 'recipient' ) ?
  • { __( 'A mail has no recipient and is not sent. Add one under "After sending".', 'funnelforms-pro' ) }
  • : null }
) : null } { 'failed' === publishing.state && publishing.error && ! blocked ? { publishing.error } : null } { ! blocked ?

{ __( 'Visitors see the new version right away. The previous version stays in the version history.', 'funnelforms-pro' ) }

: null } ) }
); } function RevisionsDialog( { api, formId, onClose }: { api: FormsApi; formId: number; onClose: () => void } ) { const { store, readOnly } = useEnv(); const form = useBuilder( ( s ) => s.form ); const [ list, setList ] = useState( null ); const [ error, setError ] = useState( null ); const [ busy, setBusy ] = useState( false ); useEffect( () => { api.revisions( formId ).then( setList, ( e: unknown ) => setError( e instanceof Error ? e.message : String( e ) ) ); }, [ api, formId ] ); const run = async ( work: () => Promise ): Promise => { setBusy( true ); setError( null ); try { await work(); onClose(); } catch ( e ) { setError( e instanceof Error ? e.message : String( e ) ); } finally { setBusy( false ); } }; const restore = ( revision: Revision ): Promise => run( async () => { await store.getState().saveNow(); const detail = await api.restore( formId, revision.id ); if ( detail.document ) { store.getState().replace( detail.document, detail ); } } ); const discard = (): Promise => run( async () => store.getState().reset( await api.dropDraft( formId ) ) ); const date = ( value: string | null ): string => ( value ? new Date( value.replace( ' ', 'T' ) + ( /[zZ+]/.test( value ) ? '' : 'Z' ) ).toLocaleString() : '' ); return ( { __( 'Close', 'funnelforms-pro' ) } }> { error ? { error } : null } { form?.hasDraft && null !== form.currentRevision ? ( void discard() }> { __( 'Discard changes', 'funnelforms-pro' ) } } > { __( 'Back to the published version. This cannot be undone.', 'funnelforms-pro' ) } ) : null } { null === list && ! error ? : null } { list && 0 === list.length ?

{ __( 'Nothing published yet. Each time you publish, a version is kept here.', 'funnelforms-pro' ) }

: null } { list && list.length > 0 ? (
    { list.map( ( r ) => (
  1. { date( r.createdAt ) } { r.current ? { __( 'Live', 'funnelforms-pro' ) } : null }
    { r.author ? r.author.name : '' } { r.note && 'migration' !== r.note ? ' · ' + r.note : '' } { 'migration' === r.note ? ' · ' + __( 'Imported from Funnelforms 3', 'funnelforms-pro' ) : '' }
  2. ) ) }
) : null }
); } /** Where Ctrl+C keeps a step or field, so it can be pasted in this form or another one. */ const CLIPBOARD = 'ffxb-clipboard'; /** The selected node, or the selected field of it, as a clip. */ function clipOf( doc: FormDocument | null, nodeId: string, fieldId?: string ): Clip | null { const node = doc?.nodes.find( ( n ) => n.id === nodeId ); if ( ! node ) { return null; } if ( ! fieldId ) { return { kind: 'node', node }; } const field = 'end' === node.type ? undefined : ( node.fields as Array ).find( ( f ) => f.id === fieldId ); return field ? { kind: 'field', field, contact: 'contact' === node.type } : null; } function writeClip( clip: Clip ): boolean { try { window.localStorage.setItem( CLIPBOARD, JSON.stringify( { v: 1, ...clip } ) ); return true; } catch { return false; } } function readClip(): Clip | null { try { const value: unknown = JSON.parse( window.localStorage.getItem( CLIPBOARD ) ?? 'null' ); return isClip( value ) ? value : null; } catch { return null; } } /** Pastes a clip after the selection and selects the copy; tells why when it does not fit there. */ function paste( state: ReturnType, clip: Clip ): void { const { node, field } = state.selection; if ( 'node' === clip.kind ) { let id = ''; state.change( ( d ) => { id = pasteNode( d, clip.node, node ); } ); state.select( { node: id } ); state.notify( __( 'Step pasted.', 'funnelforms-pro' ) ); return; } const target = node ? state.doc?.nodes.find( ( n ) => n.id === node ) : undefined; if ( ! target || target.type !== ( clip.contact ? 'contact' : 'step' ) ) { state.notify( clip.contact ? __( 'Select a contact step to paste this field into.', 'funnelforms-pro' ) : __( 'Select a step to paste this field into.', 'funnelforms-pro' ), false ); return; } let id: string | null = null; state.change( ( d ) => { id = pasteField( d, target.id, clip.field, clip.contact, field ); } ); if ( id ) { state.select( { node: target.id, field: id } ); state.notify( __( 'Field pasted.', 'funnelforms-pro' ) ); } } /** Keyboard shortcuts while no input has the focus (undo and save also inside inputs). */ function Shortcuts( { analytics, prediction }: { analytics: Analytics | null; prediction: PredictionMode | null } ) { const { store, readOnly, rights } = useEnv(); const [ help, setHelp ] = useState( false ); useEffect( () => { const open = (): void => setHelp( true ); window.addEventListener( SHORTCUTS_EVENT, open ); return () => window.removeEventListener( SHORTCUTS_EVENT, open ); }, [] ); useEffect( () => { const onKey = ( event: KeyboardEvent ): void => { const state = store.getState(); const mod = event.ctrlKey || event.metaKey; const target = event.target as HTMLElement | null; const typing = !! target && ( /^(INPUT|TEXTAREA|SELECT)$/.test( target.tagName ) || target.isContentEditable ); const key = event.key.toLowerCase(); if ( mod && 's' === key ) { event.preventDefault(); void state.saveNow(); return; } if ( typing ) { return; } if ( '?' === event.key && ! mod ) { event.preventDefault(); setHelp( true ); return; } if ( 'a' === key && ! mod && ! event.altKey && analytics ) { event.preventDefault(); analytics.setOn( ! analytics.on ); return; } if ( 'p' === key && ! mod && ! event.altKey && prediction ) { event.preventDefault(); prediction.setOn( ! prediction.on ); return; } const { node: selected } = state.selection; if ( 'l' === key && ! mod && ! event.altKey && selected && 'end' !== state.doc?.nodes.find( ( n ) => n.id === selected )?.type ) { event.preventDefault(); state.select( { node: selected }, 'logic' === state.panel && ! state.selection.field ? 'content' : 'logic' ); return; } if ( mod && 'c' === key && selected && ! event.altKey && ! window.getSelection()?.toString() ) { const clip = clipOf( state.doc, selected, state.selection.field ); if ( clip && writeClip( clip ) ) { event.preventDefault(); state.notify( 'node' === clip.kind ? __( 'Step copied. Paste it into this form or another one.', 'funnelforms-pro' ) : __( 'Field copied. Paste it into this form or another one.', 'funnelforms-pro' ), false ); } return; } if ( readOnly ) { return; } if ( mod && 'v' === key && ! event.altKey ) { const clip = readClip(); if ( ! clip ) { return; } event.preventDefault(); paste( state, clip ); return; } if ( mod && 'z' === key ) { event.preventDefault(); if ( event.shiftKey ) { state.redo(); } else { state.undo(); } return; } if ( mod && 'y' === key ) { event.preventDefault(); state.redo(); return; } const { node, field, edge } = state.selection; if ( mod && 'd' === key && node ) { event.preventDefault(); let id: string | null = null; state.change( ( d ) => { id = field ? duplicateField( d, node, field ) : duplicateNode( d, node ); } ); if ( id ) { state.select( field ? { node, field: id } : { node: id } ); } return; } if ( 'delete' === key || 'backspace' === key ) { if ( edge ) { state.change( ( d ) => removeEdge( d, edge ) ); state.select( {} ); } else if ( node && field ) { removeWithNotice( store, ( d ) => void removeField( d, node, field ), asksFor( field ) ); state.select( { node } ); } else if ( node && ( state.doc?.nodes.length ?? 0 ) > 1 ) { removeWithNotice( store, ( d ) => removeNode( d, node ), fieldsOf( state.doc, node ) ); state.select( {} ); } else { return; } event.preventDefault(); return; } if ( 'escape' === key ) { state.select( {} ); } }; window.addEventListener( 'keydown', onKey ); return () => window.removeEventListener( 'keydown', onKey ); }, [ store, readOnly, analytics, prediction ] ); if ( ! help ) { return null; } const mod = /Mac|iPhone|iPad/.test( globalThis.navigator?.platform ?? '' ) ? '⌘' : 'Ctrl'; const keys: Array<[ string[], string ]> = [ [ [ mod, 'Z' ], __( 'Undo', 'funnelforms-pro' ) ], [ [ mod, 'Shift', 'Z' ], __( 'Redo', 'funnelforms-pro' ) ], [ [ mod, 'S' ], __( 'Save now', 'funnelforms-pro' ) ], [ [ mod, 'D' ], __( 'Duplicate the selected step or field', 'funnelforms-pro' ) ], [ [ mod, 'C' ], __( 'Copy the selected step or field', 'funnelforms-pro' ) ], [ [ mod, 'V' ], __( 'Paste it after the selected step or field, also in another form', 'funnelforms-pro' ) ], [ [ __( 'Delete', 'funnelforms-pro' ) ], __( 'Delete the selected step, field or path', 'funnelforms-pro' ) ], [ [ 'L' ], __( 'Switch between the content and the logic of the selected step', 'funnelforms-pro' ) ], ...( 'free' === process.env.FUNNELFORMS_EDITION || ! rights.entries ? [] : [ [ [ 'A' ], __( 'Turn the analytics on the canvas on or off', 'funnelforms-pro' ) ] as [ string[], string ] ] ), ...( prediction ? [ [ [ 'P' ], __( 'Turn the prediction on the canvas on or off', 'funnelforms-pro' ) ] as [ string[], string ] ] : [] ), [ [ 'Esc' ], __( 'Deselect', 'funnelforms-pro' ) ], [ [ '?' ], __( 'Show these shortcuts', 'funnelforms-pro' ) ], ]; return ( setHelp( false ) } actions={ }>
{ keys.map( ( [ combo, what ] ) => (
{ combo.map( ( k, i ) => ( { i ? ' + ' : null } { k } ) ) }
{ what }
) ) }
); } /** Asks before leaving the page while changes are not saved. */ function LeaveGuard() { const state = useBuilder( ( s ) => s.save.state ); useEffect( () => { if ( 'saved' === state || 'locked' === state ) { return undefined; } const warn = ( event: BeforeUnloadEvent ): void => { event.preventDefault(); // Older browsers show the dialog only with a return value. event.returnValue = ''; }; window.addEventListener( 'beforeunload', warn ); return () => window.removeEventListener( 'beforeunload', warn ); }, [ state ] ); return null; }