import React, { act } from 'react'; import { readFileSync } from 'node:fs'; import { join } from 'node:path'; import { createRoot, type Root } from 'react-dom/client'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { ApiError, type BookingConfig, type FormDetail, type FormsApi, type FormSummary, type IconLibrary, type NewWhatsAppTemplate, type SiteDesign, type WhatsAppTemplate } from '../src/api'; import { createBuilderStore } from '../src/store'; import { Builder } from '../src/ui/Builder'; import { FormsList } from '../src/ui/FormsList'; import { parseExtensions } from '../src/ui/UploadProps'; import { placement } from '../src/ui/Tour'; import { addField, addStep, defaultPlacement } from '../src/document'; import { connectOutput } from '../src/ports'; import { setPrivacy } from '../src/privacy'; import { setCode } from '../src/code'; import { setIntegrationsUrl } from '../src/actions'; import type { ConnectApi, CrmProvider } from '../src/connect'; import { formProtection, setSpam } from '../src/spam'; import { today } from '../src/experiments'; import { periodDays } from '../src/stats'; import { blank } from './blank'; import { validateDocument, type Action, type ChoiceField, type ContactField, type ContentField, type FormDocument, type FormNode } from '@funnelforms/form-schema'; ( globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean } ).IS_REACT_ACT_ENVIRONMENT = true; const summary: FormSummary = { id: 7, uid: 'uid', title: 'Anfrage', category: '', status: 'draft', renderer: 'v5', legacyId: null, currentRevision: null, hasDraft: true, draftUpdatedAt: null, draftAuthor: null, lockedBy: null, entries: 3, shortcode: '[funnelforms uid="uid"]', createdAt: null, updatedAt: null, }; function bookingDefaults(): BookingConfig { return { version: 2, kind: 'personal', location: '', timezone: '', hours: [ { days: [ 1, 2, 3, 4, 5 ], from: '09:00', to: '16:00' } ], durations: [ 30 ], interval: 30, bufferBefore: 0, bufferAfter: 15, notice: 60, horizon: { mode: 'rolling', amount: 2, unit: 'week' }, closed: [], special: [], dailyLimit: 0, staff: [], assignment: 'roundRobin', invitation: true, reminders: [], calendars: { write: '', conflicts: [] } }; } function fakeApi( overrides: Partial = {} ): FormsApi { const detail = (): FormDetail => ( { ...summary, document: blank(), lockTtl: 150 } ); return { list: vi.fn( async () => ( { forms: [ summary ], total: 1, categories: [] } ) ), get: vi.fn( async () => detail() ), create: vi.fn( async () => detail() ), update: vi.fn( async () => detail() ), remove: vi.fn( async () => undefined ), saveDraft: vi.fn( async () => ( { problems: [], missingRights: [], form: summary } ) ), dropDraft: vi.fn( async () => detail() ), publish: vi.fn( async () => ( { revision: 1, renderer: 'v5' as const, warnings: [], form: { ...summary, status: 'published' as const } } ) ), revisions: vi.fn( async () => [] ), revision: vi.fn(), restore: vi.fn( async () => detail() ), duplicate: vi.fn( async () => detail() ), lock: vi.fn( async () => undefined ), unlock: vi.fn( async () => undefined ), exportForm: vi.fn( async () => ( {} ) ), importFile: vi.fn( async () => [] ), preview: vi.fn( async () => ( { html: '

Vorschau

' } ) ), templates: vi.fn( async () => ( { goals: [ 'quote' as const, 'consultation' as const ], categories: [ 'home' as const, 'health' as const ], languages: [ 'de_DE' ], locale: 'de_DE', templates: [ { id: 'moving', title: 'Umzugsunternehmen', description: 'Umzugsanfrage mit Preisrahmen.', goal: 'quote' as const, category: 'home' as const, icon: 'lucide:truck', features: [ 'calculation' as const ], steps: 8, firstQuestion: 'Wie viele Personen?', sample: { kind: 'choice', options: [], max: 0, style: '' } }, ], icons: {}, } ) ), templatePreview: vi.fn( async () => ( { html: '

Vorlage

' } ) ), fromTemplate: vi.fn( async () => detail() ), styles: vi.fn( async () => [ { id: 'st_000000000001', name: 'Hausstil', tokens: { 'color.primary': '#c2410c', 'font.family': 'Poppins' }, createdAt: '' } ] ), saveStyle: vi.fn( async ( name: string, tokens: Record ) => ( { id: 'st_000000000002', name, tokens, createdAt: '' } ) ), deleteStyle: vi.fn( async () => undefined ), fonts: vi.fn( async () => [ { file: 'Brand Sans.woff2', family: 'Brand Sans', size: 1000 } ] ), uploadFont: vi.fn( async ( _file: Blob, name: string ) => ( { file: name, family: name.replace( /\.[a-z0-9]+$/, '' ), size: 10 } ) ), googleFonts: vi.fn( async () => [ { family: 'Lobster', category: 'display' as const, installed: false }, { family: 'Lora', category: 'serif' as const, installed: false }, { family: 'Roboto', category: 'sans-serif' as const, installed: true }, ] ), installGoogleFont: vi.fn( async ( family: string ) => ( { family, category: 'display' as const, installed: true } ) ), branding: vi.fn( async ( url: string ) => ( { url, colors: [ '#0b7a75', '#1d1d1d', '#fafafa', '#e11d48' ], roles: { primary: '#0b7a75', text: '#1d1d1d' }, fonts: [ { family: 'Open Sans', value: 'Open Sans', local: false }, { family: 'Brand Sans', value: 'Brand Sans.woff2', local: true }, ], } ) ), bookingTypes: vi.fn( async () => ( { types: [ { ref: 'legacy:7001', id: 1, title: 'Erstgespräch', config: bookingDefaults(), legacy: true, cronofy: true } ], staff: [ { id: 1, name: 'Ada' }, { id: 2, name: 'Grace' } ], calendars: [], timezone: 'Europe/Berlin', defaults: bookingDefaults(), } ) ), saveBookingType: vi.fn( async ( id: number | null, title: string, config: BookingConfig ) => ( { ref: `bt:${ id ?? 2 }`, id: id ?? 2, title, config, legacy: false, cronofy: false } ) ), deleteBookingType: vi.fn( async () => undefined ), connections: vi.fn( async () => [ { ref: 'conn:3', type: 'slack', label: 'Vertrieb' } ] ), createConnection: vi.fn( async ( type: string, label: string ) => ( { ref: 'conn:9', type, label } ) ), updateConnection: vi.fn( async ( ref: string ) => ( { ref, type: 'stripe', label: 'Shop' } ) ), startCalendarSignIn: vi.fn( async ( provider: string ) => ( { url: `https://api.funnelforms.cloud/kunde/v1/oauth/${ provider }/authorize?state=s1`, state: 's1' } ) ), calendarSignIn: vi.fn( async () => null ), passwordHash: vi.fn( async ( password: string ) => '$wp$hash-of-' + password ), experimentStats: vi.fn( async () => [] ), formStats: vi.fn( async ( _id: number, from = '2026-09-17', to = '2026-10-16' ) => ( { form: 7, from, to, // The 30 days before the current 30-day period, whatever today is. totals: from < periodDays( 30 ).from ? { views: 100, starts: 40, completions: 10, conversionRate: 0.1 } : { views: 150, starts: 60, completions: 12, conversionRate: 0.08, averageSeconds: 125, medianSeconds: 70 }, devices: { desktop: 3, tablet: 0, mobile: 9 }, daily: [ { date: to, views: 150, starts: 60, completions: 12 } ], steps: [ { id: 'n1', type: 'step' as const, title: 'Wofür?', reached: 60, left: 20 } ], answers: [ { field: 'q1', step: 'n1', title: 'Wofür?', options: [ { id: 'o1', label: 'Haus', chosen: 30, completed: 9 }, { id: 'o2', label: 'Wohnung', chosen: 10, completed: 1 } ] } ], } ) ), ...overrides, } as FormsApi; } let container: HTMLElement; let root: Root; beforeEach( () => { container = document.createElement( 'div' ); document.body.appendChild( container ); root = createRoot( container ); } ); afterEach( () => { act( () => root.unmount() ); container.remove(); } ); /** The control of a field, by its label. */ function labelled( label: string ): T { const found = [ ...container.querySelectorAll( '.ffxb-field__label' ) ].find( ( l ) => l.textContent === label ); const control = found ? document.getElementById( found.htmlFor ) : null; if ( ! control ) { throw new Error( 'No field ' + label ); } return control as T; } async function choose( label: string, value: string ): Promise { const select = labelled( label ); await act( async () => { Object.getOwnPropertyDescriptor( HTMLSelectElement.prototype, 'value' )?.set?.call( select, value ); select.dispatchEvent( new Event( 'change', { bubbles: true } ) ); } ); } /** Picks the tile of a value in the group of tiles with this legend (ChoiceTiles). */ async function tile( legend: string, value: string ): Promise { const group = [ ...document.querySelectorAll( 'fieldset.ffxb-tiles' ) ].find( ( f ) => legend === f.querySelector( 'legend' )?.textContent ); const input = group?.querySelector( `input[value="${ value }"]` ); if ( ! input ) { throw new Error( `No tile ${ value } in ${ legend }` ); } await act( async () => input.click() ); } async function slide( label: string, value: number ): Promise { const input = labelled( label ); await act( async () => { Object.getOwnPropertyDescriptor( HTMLInputElement.prototype, 'value' )?.set?.call( input, String( value ) ); input.dispatchEvent( new Event( 'input', { bubbles: true } ) ); } ); } async function settle(): Promise { await act( async () => { for ( let i = 0; i < 5; i++ ) { await new Promise( ( resolve ) => setTimeout( resolve, 0 ) ); } } ); } /** Sets the value of the input, textarea or select with this label. */ async function fill( label: string, value: string, scope: ParentNode = container ): Promise { const found = [ ...scope.querySelectorAll( 'label' ) ].find( ( l ) => l.textContent?.trim() === label ); const el = found ? document.getElementById( found.htmlFor ) : null; if ( ! el ) { throw new Error( 'No field ' + label ); } const proto = el instanceof HTMLSelectElement ? HTMLSelectElement.prototype : el instanceof HTMLTextAreaElement ? HTMLTextAreaElement.prototype : HTMLInputElement.prototype; await act( async () => { Object.getOwnPropertyDescriptor( proto, 'value' )?.set?.call( el, value ); el.dispatchEvent( new Event( el instanceof HTMLSelectElement ? 'change' : 'input', { bubbles: true } ) ); } ); } function button( label: string ): HTMLButtonElement { const found = [ ...container.querySelectorAll( 'button' ) ].find( ( b ) => b.textContent?.trim() === label || b.getAttribute( 'aria-label' ) === label ); if ( ! found ) { throw new Error( 'No button ' + label ); } return found; } describe( 'forms list', () => { it( 'shows the forms with status, entries and shortcode', async () => { await act( async () => root.render( undefined } /> ) ); await settle(); expect( container.textContent ).toContain( 'Anfrage' ); expect( container.textContent ).toContain( '3 entries' ); expect( container.textContent ).toContain( '[funnelforms uid="uid"]' ); } ); it( 'shows key figures and the figures of each form of the last 30 days', async () => { const published = { ...summary, status: 'published' as const, currentRevision: 3, hasDraft: false }; const legacy = { ...summary, id: 8, title: 'Alt', status: 'published' as const, currentRevision: 1, renderer: 'legacy' as const, legacyId: 12, hasDraft: false }; const api = fakeApi( { list: vi.fn( async () => ( { forms: [ published, legacy ], total: 2, categories: [] } ) ), formFigures: vi.fn( async () => ( { forms: { total: 5, published: 2, draft: 3, trashed: 1 }, figures: { days: 30, views: 1200, entries: 90, rate: 0.075, viewsBefore: 1000, entriesBefore: 60, rateBefore: 0.06, forms: { '7': { views: 1200, entries: 80, rate: 0.0667, measured: true, series: [ 0, 2, 3 ] }, '8': { views: 0, entries: 10, rate: null, measured: false, series: [ 1, 0, 0 ] }, }, }, } ) ), } ); await act( async () => root.render( undefined } /> ) ); await settle(); const kpis = [ ...container.querySelectorAll( '.ffxb-kpis .ffx-kpi' ) ].map( ( k ) => k.textContent ); expect( kpis ).toEqual( [ 'Forms52 published', 'Views1,200Last 30 days, once per visit', 'Entries90+50 % against the 30 days before', 'Conversion rate7.5 %Entries per view, last 30 days' ] ); expect( [ ...container.querySelectorAll( '.ffxb-scope button' ) ].map( ( b ) => b.textContent ) ).toEqual( [ 'All5', 'Published2', 'Drafts3', 'Trash1' ] ); const rows = [ ...container.querySelectorAll( '.ffxb-list > li' ) ]; const cells = ( row: Element | undefined ): string[] => [ ...( row?.querySelectorAll( '.ffxb-row__figure' ) ?? [] ) ].map( ( c ) => c.getAttribute( 'data-label' ) + ' ' + c.querySelector( 'strong' )?.textContent ); expect( cells( rows[ 0 ] ) ).toEqual( [ 'Entries 80', 'Views 1,200', 'Conversion 6.7 %' ] ); expect( rows[ 0 ]?.querySelector( '.ffx-spark' )?.getAttribute( 'aria-label' ) ).toBe( 'Entries per day, last 30 days' ); // Views of forms on Funnelforms 3 are not measured. expect( cells( rows[ 1 ] ) ).toEqual( [ 'Entries 10', 'Views –', 'Conversion –' ] ); expect( rows[ 1 ]?.textContent ).toContain( 'Live on Funnelforms 3' ); // The total of all time gives way to the columns. expect( rows[ 0 ]?.textContent ).not.toContain( '3 entries' ); } ); it( 'names the two imports as the menu does and opens only the chosen one', async () => { await act( async () => root.render( undefined } importUrl="admin.php?page=funnelforms-import" importOwn="admin.php?page=funnelforms-import-funnelforms" /> ) ); await settle(); const links = [ ...container.querySelectorAll( '.ffx-frame__actions a, a.ffx-btn' ) ].map( ( a ) => [ a.textContent, a.getAttribute( 'href' ) ] ); expect( links ).toContainEqual( [ 'Import Funnelforms', 'admin.php?page=funnelforms-import-funnelforms' ] ); expect( links ).toContainEqual( [ 'Import from other plugins', 'admin.php?page=funnelforms-import' ] ); expect( [ ...container.querySelectorAll( 'button' ) ].some( ( b ) => b.textContent === 'Import' ) ).toBe( false ); // Without the page, the Funnelforms import picks the file right here, and takes only Funnelforms files. const api = fakeApi(); await act( async () => root.render( undefined } /> ) ); await settle(); expect( button( 'Import Funnelforms' ).getAttribute( 'title' ) ).toContain( 'Funnelforms 3 (.zip)' ); expect( container.querySelector( 'input[type="file"]' )?.getAttribute( 'accept' ) ).toBe( '.json,.zip,application/json,application/zip' ); expect( container.textContent ).not.toContain( 'Import from other plugins' ); } ); it( 'invites to create the first form', async () => { const api = fakeApi( { list: vi.fn( async () => ( { forms: [], total: 0, categories: [] } ) ) } ); await act( async () => root.render( undefined } /> ) ); await settle(); expect( container.textContent ).toContain( 'Create your first form' ); } ); it( 'opens the template gallery and starts a form from a template', async () => { const api = fakeApi(); const onOpen = vi.fn(); await act( async () => root.render( ) ); await settle(); await act( async () => button( 'New form' ).click() ); await settle(); expect( container.querySelector( '.ffxb-gallery' ) ).not.toBeNull(); await act( async () => button( 'Use template' ).click() ); await settle(); expect( api.fromTemplate ).toHaveBeenCalledWith( 'moving', undefined ); expect( onOpen ).toHaveBeenCalledWith( 7 ); expect( container.querySelector( '.ffxb-gallery' ) ).toBeNull(); } ); } ); /** Opens a workspace of the editor from the top bar. */ async function workspace( name: string ): Promise { const tab = [ ...container.querySelectorAll( '.ffxb-views__item' ) ].find( ( b ) => b.textContent === name ); if ( ! tab ) { throw new Error( 'No workspace ' + name ); } await act( async () => tab.click() ); await settle(); } /** Opens what happens after sending, from the contact step on the canvas. */ async function afterSending(): Promise { const open = container.querySelector( '.ffxb-node--contact .ffxb-node__after' ); if ( ! open ) { throw new Error( 'No contact step' ); } await act( async () => open.click() ); await settle(); } describe( 'builder', () => { it( 'shows the steps and adds, undoes and selects', async () => { const api = fakeApi(); const store = createBuilderStore( api, 7, { autosaveMs: 60000 } ); await act( async () => root.render( undefined } store={ store } /> ) ); await settle(); expect( container.querySelector( '.ffxb-node--contact' )?.textContent ).toContain( 'Deine Kontaktdaten' ); await act( async () => button( 'Choice' ).click() ); expect( store.getState().doc?.nodes ).toHaveLength( 3 ); // The new step is selected and shown in the properties. expect( container.querySelector( '.ffxb-inspector' )?.textContent ).toContain( 'Several answers allowed' ); await act( async () => { window.dispatchEvent( new KeyboardEvent( 'keydown', { key: 'z', ctrlKey: true } ) ); } ); expect( store.getState().doc?.nodes ).toHaveLength( 2 ); expect( container.textContent ).toContain( 'Unsaved changes' ); } ); it( 'says after publishing when the pages still show the Funnelforms 3 version of a form', async () => { const legacy = { ...summary, status: 'published' as const, renderer: 'legacy' as const, legacyId: 12, currentRevision: 2, hasDraft: false }; const stays = [ { title: 'No restore point yet', fix: 'Create a restore point. It takes a few seconds.', link: 'Go to the way back', url: 'admin.php?page=funnelforms-migration&tab=wayback' } ]; const api = fakeApi( { get: vi.fn( async () => ( { ...legacy, hasDraft: true, document: blank(), lockTtl: 150 } ) ), publish: vi.fn( async () => ( { revision: 3, renderer: 'legacy' as const, warnings: [ 'no_backup' ], stays, form: { ...legacy, currentRevision: 3 } } ) ), } ); const store = createBuilderStore( api, 7, { autosaveMs: 60000 } ); await act( async () => root.render( undefined } store={ store } /> ) ); await settle(); await act( async () => ( container.querySelector( '[data-tour="publish"]' ) as HTMLButtonElement ).click() ); await settle(); await act( async () => button( 'Publish now' ).click() ); await settle(); const dialog = container.querySelector( 'dialog.ffxb-dialog' ) as HTMLElement; expect( dialog.textContent ).toContain( 'Your pages still show the Funnelforms 3 version of this form' ); expect( dialog.textContent ).not.toContain( 'Visitors now see this version.' ); expect( dialog.textContent ).toContain( 'No restore point yet' ); expect( dialog.querySelector( 'a' )?.getAttribute( 'href' ) ).toBe( stays[ 0 ]?.url ); // The top bar keeps saying so. expect( container.querySelector( '.ffxb-topbar__meta' )?.textContent ).toContain( 'Live on Funnelforms 3' ); } ); it( 'copies a step or field with Ctrl+C and pastes it with Ctrl+V', async () => { const api = fakeApi(); const store = createBuilderStore( api, 7, { autosaveMs: 60000 } ); await act( async () => root.render( undefined } store={ store } /> ) ); await settle(); window.localStorage.removeItem( 'ffxb-clipboard' ); const key = async ( k: string ): Promise => { await act( async () => { window.dispatchEvent( new KeyboardEvent( 'keydown', { key: k, ctrlKey: true } ) ); } ); }; await act( async () => button( 'Choice' ).click() ); const step = store.getState().selection.node as string; await key( 'c' ); expect( container.querySelector( '.ffxb-toast' )?.textContent ).toContain( 'Step copied' ); expect( container.querySelector( '.ffxb-toast__action' ) ).toBeNull(); await key( 'v' ); const nodes = store.getState().doc?.nodes ?? []; expect( nodes ).toHaveLength( 4 ); const pasted = store.getState().selection.node as string; expect( pasted ).not.toBe( step ); expect( store.getState().doc?.edges.find( ( e ) => e.from === step && e.default )?.to ).toBe( pasted ); expect( container.querySelector( '.ffxb-toast' )?.textContent ).toContain( 'Step pasted' ); // A field of a step goes only into a step, below the selected field. const field = ( store.getState().doc?.nodes.find( ( n ) => n.id === step ) as Extract ).fields[ 0 ]?.id as string; await act( async () => store.getState().select( { node: step, field } ) ); await key( 'c' ); await act( async () => store.getState().select( { node: 'contact' } ) ); await key( 'v' ); expect( container.querySelector( '.ffxb-toast' )?.textContent ).toContain( 'Select a step to paste this field into.' ); await act( async () => store.getState().select( { node: step, field } ) ); await key( 'v' ); expect( ( store.getState().doc?.nodes.find( ( n ) => n.id === step ) as Extract ).fields ).toHaveLength( 2 ); expect( store.getState().selection.field ).not.toBe( field ); expect( validateDocument( store.getState().doc as FormDocument ).errors ).toEqual( [] ); await key( 'z' ); expect( ( store.getState().doc?.nodes.find( ( n ) => n.id === step ) as Extract ).fields ).toHaveLength( 1 ); window.localStorage.removeItem( 'ffxb-clipboard' ); } ); it( 'edits the fields of a repeat group, the unit of a number and the hours of a time', async () => { const api = fakeApi(); const store = createBuilderStore( api, 7, { autosaveMs: 60000 } ); await act( async () => root.render( undefined } store={ store } /> ) ); await settle(); await act( async () => button( 'Repeat group' ).click() ); const step = () => store.getState().doc?.nodes.find( ( n ) => n.id === store.getState().selection.node ) as Extract; const group = () => step().fields[ 0 ] as Extract[ 'fields' ][ number ] & { props: { fields: Array<{ type: string; required: boolean; label: Record }>; itemLabel: Record } }; await act( async () => store.getState().select( { node: step().id, field: group().id } ) ); await fill( 'Heading of each item', 'Person %d' ); await choose( 'Type of the new field', 'email' ); await act( async () => button( 'Add field' ).click() ); expect( group().props.fields.map( ( f ) => f.type ) ).toEqual( [ 'text', 'email' ] ); expect( group().props.itemLabel.de_DE ).toBe( 'Person %d' ); // The new field opens, with its question, type and settings. const opened = container.querySelector( '.ffxb-subfield[open]' ) as HTMLElement; await fill( 'Question', 'E-Mail der Person', opened ); await act( async () => ( [ ...opened.querySelectorAll( '.ffxb-toggle input, input[type=checkbox]' ) ][ 0 ] as HTMLInputElement ).click() ); expect( group().props.fields[ 1 ] ).toMatchObject( { label: { de_DE: 'E-Mail der Person' }, required: false } ); await fill( 'Type', 'dropdown', opened ); expect( group().props.fields[ 1 ] ).toMatchObject( { type: 'dropdown', label: { de_DE: 'E-Mail der Person' } } ); await fill( 'Answers', 'Klein\nGroß\nRiesig', container.querySelector( '.ffxb-subfield[open]' ) as HTMLElement ); expect( ( group().props.fields[ 1 ] as unknown as { options: Array<{ label: Record }> } ).options.map( ( o ) => o.label.de_DE ) ).toEqual( [ 'Klein', 'Groß', 'Riesig' ] ); expect( validateDocument( store.getState().doc as FormDocument ).errors ).toEqual( [] ); await act( async () => button( 'Number' ).click() ); const number = () => step().fields[ step().fields.length - 1 ] as unknown as { id: string; props: { step?: number; unit?: { text: Record; position: string } } }; await act( async () => store.getState().select( { node: step().id, field: number().id } ) ); await fill( 'Unit', 'm²' ); await fill( 'Steps of', '0.5' ); expect( number().props ).toMatchObject( { step: 0.5, unit: { text: { de_DE: 'm²' }, position: 'after' } } ); await act( async () => button( 'Time' ).click() ); const time = () => step().fields[ step().fields.length - 1 ] as unknown as { id: string; props: { min?: string; max?: string } }; await act( async () => store.getState().select( { node: step().id, field: time().id } ) ); await fill( 'Earliest time', '18:00' ); await fill( 'Latest time', '08:00' ); expect( time().props ).toMatchObject( { min: '18:00', max: '08:00' } ); expect( container.querySelector( '.ffxb-inspector' )?.textContent ).toContain( 'The latest time is before the earliest' ); expect( validateDocument( store.getState().doc as FormDocument ).errors ).toEqual( [] ); } ); it( 'finds field types and opens the design with a live preview from the form at a glance', async () => { const api = fakeApi(); const store = createBuilderStore( api, 7, { autosaveMs: 60000 } ); await act( async () => root.render( undefined } store={ store } /> ) ); await settle(); expect( document.body.classList.contains( 'folded' ) ).toBe( true ); const search = container.querySelector( '.ffxb-palette__search input' ) as HTMLInputElement; await act( async () => { Object.getOwnPropertyDescriptor( HTMLInputElement.prototype, 'value' )?.set?.call( search, 'mail' ); search.dispatchEvent( new Event( 'input', { bubbles: true } ) ); } ); expect( [ ...container.querySelectorAll( '.ffxb-tile' ) ].map( ( t ) => t.textContent ) ).toEqual( [ 'E-mail address' ] ); expect( container.querySelector( '.ffxb-overview' )?.textContent ).toContain( 'Steps' ); const jump = [ ...container.querySelectorAll( '.ffxb-jump' ) ].find( ( b ) => b.textContent?.startsWith( 'Design' ) ) as HTMLButtonElement; await act( async () => jump.click() ); await settle(); expect( container.querySelector( '.ffxb-views__item.is-active' )?.textContent ).toBe( 'Design' ); expect( container.querySelector( '.ffxb-canvas' ) ).toBeNull(); expect( api.preview ).toHaveBeenCalledTimes( 1 ); expect( container.querySelector( '.ffxb-live iframe' )?.getAttribute( 'srcdoc' ) ).toContain( 'Vorschau' ); // Resting on a theme shows it in the preview at once, before anything is saved; leaving shows the form's again. const frame = container.querySelector( '.ffxb-live iframe' ) as HTMLIFrameElement; const post = vi.spyOn( frame.contentWindow as Window, 'postMessage' ); const card = ( name: string ): HTMLButtonElement => [ ...container.querySelectorAll( '.ffxb-theme-card__name' ) ].find( ( n ) => n.textContent?.startsWith( name ) )?.closest( 'button' ) as HTMLButtonElement; await act( async () => card( 'Neon' ).dispatchEvent( new MouseEvent( 'mouseover', { bubbles: true } ) ) ); expect( post ).toHaveBeenLastCalledWith( expect.objectContaining( { type: 'ffx-preview-style', css: expect.stringContaining( '--ffx-color-background:#05060f;' ), classes: expect.stringContaining( 'ffx-dark' ) } ), '*' ); await act( async () => container.querySelector( '.ffxb-theme-gallery__grid' )?.dispatchEvent( new MouseEvent( 'mouseout', { bubbles: true, relatedTarget: document.body } ) ) ); expect( post ).toHaveBeenLastCalledWith( expect.objectContaining( { css: expect.not.stringContaining( '#05060f' ) } ), '*' ); expect( api.saveDraft ).not.toHaveBeenCalled(); // The gallery shows light, dark, colourful and industry themes on their own. const chip = [ ...container.querySelectorAll( '.ffxb-theme-gallery__chip' ) ].find( ( b ) => 'Dark' === b.textContent ) as HTMLButtonElement; await act( async () => chip.click() ); const shown = [ ...container.querySelectorAll( '.ffxb-theme-card__name' ) ].map( ( n ) => n.textContent ); expect( shown ).toEqual( expect.arrayContaining( [ 'Dark', 'Midnight', 'Neon', 'Luxury', 'Fitness' ] ) ); expect( shown ).not.toContain( 'Minimal' ); await act( async () => ( [ ...container.querySelectorAll( '.ffxb-theme-gallery__chip' ) ][ 0 ] as HTMLButtonElement ).click() ); // A change of the design is saved and shown after a moment. const dark = [ ...container.querySelectorAll( '.ffxb-theme-card' ) ].find( ( b ) => b.textContent?.includes( 'Dark' ) ) as HTMLButtonElement; await act( async () => dark.click() ); await act( async () => new Promise( ( resolve ) => setTimeout( resolve, 900 ) ) ); await settle(); expect( api.saveDraft ).toHaveBeenCalled(); expect( api.preview ).toHaveBeenCalledTimes( 2 ); // The progress bar is built by the runtime, so the preview is loaded again for it too. await tile( 'Progress', 'percent' ); await act( async () => new Promise( ( resolve ) => setTimeout( resolve, 900 ) ) ); await settle(); expect( api.preview ).toHaveBeenCalledTimes( 3 ); await act( async () => root.render(
) ); expect( document.body.classList.contains( 'folded' ) ).toBe( false ); } ); it( 'opens in the workspace the address asks for, and has no statistics of its own', async () => { const api = fakeApi(); await act( async () => root.render( undefined } view="design" /> ) ); await settle(); expect( container.querySelector( '.ffxb-views__item.is-active' )?.textContent ).toBe( 'Design' ); // The figures of a form are on the statistics page, not in the editor. expect( container.querySelector( '.ffxb-views__item[data-view="stats"]' ) ).toBeNull(); expect( container.textContent ).not.toContain( 'Statistics start when the form is published.' ); // Without the right to see entries, figures asked for by the address stay off. await act( async () => root.render( undefined } figures rights={ { entries: false, code: false, settings: false } } /> ) ); await settle(); expect( container.querySelector( '.ffxb-views__item.is-active' )?.textContent ).toBe( 'Structure' ); expect( api.formStats ).not.toHaveBeenCalled(); } ); it( 'shows who holds the lock and keeps the form read-only', async () => { const api = fakeApi( { lock: vi.fn( async () => Promise.reject( new ApiError( 'locked', 'Locked', 409, { lockedBy: { id: 2, name: 'Mia' } } ) ) ) } ); const store = createBuilderStore( api, 7 ); await act( async () => root.render( undefined } store={ store } /> ) ); await settle(); expect( container.textContent ).toContain( 'Mia is editing this form.' ); expect( button( 'Choice' ).disabled ).toBe( true ); expect( button( 'Take over' ) ).toBeTruthy(); } ); it( 'saves, then previews the draft in a sandboxed frame per device', async () => { const api = fakeApi(); const store = createBuilderStore( api, 7, { autosaveMs: 60000 } ); await act( async () => root.render( undefined } store={ store } /> ) ); await settle(); await act( async () => button( 'Choice' ).click() ); await act( async () => button( 'Preview' ).click() ); await settle(); expect( api.saveDraft ).toHaveBeenCalled(); expect( api.preview ).toHaveBeenCalledWith( 7 ); const frame = container.querySelector( 'iframe' ) as HTMLIFrameElement; expect( frame.getAttribute( 'sandbox' ) ).toBe( 'allow-scripts allow-forms' ); expect( frame.getAttribute( 'srcdoc' ) ).toContain( 'Vorschau' ); expect( frame.style.width ).toBe( '1280px' ); await act( async () => button( 'Mobile' ).click() ); expect( store.getState().device ).toBe( 'mobile' ); expect( ( container.querySelector( 'iframe' ) as HTMLIFrameElement ).style.width ).toBe( '390px' ); } ); it( 'lists what keeps the draft from being previewed', async () => { const api = fakeApi( { preview: vi.fn( async () => Promise.reject( new ApiError( 'not_ready', 'Fix the problems.', 409, { problems: [ 'start_missing' ] } ) ) ) } ); await act( async () => root.render( undefined } /> ) ); await settle(); await act( async () => button( 'Preview' ).click() ); await settle(); expect( container.textContent ).toContain( 'Fix these to see the preview' ); expect( container.querySelector( 'iframe' ) ).toBeNull(); } ); it( 'applies a theme and warns about colours that are hard to read', async () => { const api = fakeApi(); const store = createBuilderStore( api, 7, { autosaveMs: 60000 } ); await act( async () => root.render( undefined } store={ store } /> ) ); await settle(); await workspace( 'Design' ); const theme = ( name: string ): HTMLButtonElement => [ ...container.querySelectorAll( '.ffxb-theme-card' ) ].find( ( b ) => b.textContent?.includes( name ) ) as HTMLButtonElement; await act( async () => theme( 'Dark' ).click() ); expect( store.getState().doc?.style.theme ).toBe( 'dark' ); expect( theme( 'Dark' ).getAttribute( 'aria-pressed' ) ).toBe( 'true' ); expect( container.querySelector( '.ffxb-notice--warning' ) ).toBeNull(); const input = [ ...container.querySelectorAll( '.ffxb-color input[type="text"]' ) ][ 1 ] as HTMLInputElement; await act( async () => { Object.getOwnPropertyDescriptor( HTMLInputElement.prototype, 'value' )?.set?.call( input, '#333333' ); input.dispatchEvent( new Event( 'input', { bubbles: true } ) ); } ); expect( store.getState().doc?.style.tokens[ 'color.text' ] ).toBe( '#333333' ); expect( container.textContent ).toContain( 'Text is hard to read on the background' ); expect( container.textContent ).toContain( 'Based on Dark, with your changes.' ); // More styles: shadow, gradient and the form's own CSS. await choose( 'Shadow', 'soft' ); expect( store.getState().doc?.style.tokens.shadow ).toBe( 'soft' ); const gradient = [ ...container.querySelectorAll( '.ffxb-advanced .ffxb-toggle label' ) ].find( ( l ) => 'Background as gradient' === l.textContent ) as HTMLLabelElement; await act( async () => gradient.click() ); expect( store.getState().doc?.style.tokens[ 'color.backgroundEnd' ] ).toBe( '#efe9ff' ); const css = container.querySelector( '.ffxb-input--code' ) as HTMLTextAreaElement; await act( async () => { Object.getOwnPropertyDescriptor( HTMLTextAreaElement.prototype, 'value' )?.set?.call( css, '.ffx-question{color:red}' ); css.dispatchEvent( new Event( 'input', { bubbles: true } ) ); } ); expect( store.getState().doc?.style.css ).toBe( '.ffx-question{color:red}' ); expect( container.textContent ).toContain( '[data-ffx-form="uid"]' ); } ); it( 'sets fonts, sizes, colours, borders, background and progress of the design', async () => { const pickImage = vi.fn( async () => ( { id: 42, url: 'https://example.org/bg.jpg', alt: '' } ) ); const api = fakeApi( { pickImage, image: vi.fn( async () => ( { id: 42, url: 'https://example.org/bg.jpg', alt: '' } ) ) } ); const store = createBuilderStore( api, 7, { autosaveMs: 60000 } ); await act( async () => root.render( undefined } store={ store } /> ) ); await settle(); await workspace( 'Design' ); const tokens = (): Record => store.getState().doc?.style.tokens ?? {}; await choose( 'Font of questions and headings', 'Brand Sans.woff2' ); expect( tokens()[ 'font.heading' ] ).toBe( 'Brand Sans.woff2' ); await choose( 'Font of questions and headings', '' ); expect( tokens()[ 'font.heading' ] ).toBeUndefined(); await choose( 'Weight of questions', 'bold' ); await slide( 'Size of questions on phones', 22 ); await slide( 'Line height of text', 1.8 ); expect( tokens() ).toMatchObject( { 'font.weight.heading': 'bold', 'font.size.heading.mobile': '22', 'line.body': '1.8' } ); const button = labelled( 'Next and send button' ); await act( async () => { Object.getOwnPropertyDescriptor( HTMLInputElement.prototype, 'value' )?.set?.call( button, '#fde68a' ); button.dispatchEvent( new Event( 'input', { bubbles: true } ) ); } ); expect( tokens()[ 'color.button' ] ).toBe( '#fde68a' ); expect( tokens()[ 'color.onButton' ] ).toBe( '#1a1a1a' ); await choose( 'Border style', 'dashed' ); await choose( 'Shadow', 'custom' ); await slide( 'Blur', 40 ); await slide( 'Shadow colour: opacity', 30 ); expect( tokens() ).toMatchObject( { 'border.style': 'dashed', shadow: 'custom', 'shadow.blur': '40', 'shadow.color': 'rgba(16,24,40,0.3)' } ); await act( async () => ( [ ...container.querySelectorAll( 'button' ) ].find( ( b ) => 'Choose image' === b.textContent ) as HTMLButtonElement ).click() ); await settle(); expect( pickImage ).toHaveBeenCalled(); expect( tokens()[ 'background.image' ] ).toBe( '42' ); expect( container.querySelector( '.ffxb-image-pick__preview' )?.getAttribute( 'src' ) ).toBe( 'https://example.org/bg.jpg' ); await slide( 'Colour over the image: opacity', 40 ); expect( tokens()[ 'color.overlay' ] ).toBe( 'rgba(0,0,0,0.4)' ); await tile( 'Buttons', 'full' ); await tile( 'Transition between steps', 'backInRight' ); await tile( 'Alignment of questions', 'left' ); expect( tokens() ).toMatchObject( { 'button.align': 'full', animation: 'backInRight', 'align.text': 'left' } ); await tile( 'Progress', 'percent' ); expect( store.getState().doc?.settings.progressBar ).toEqual( { show: true, percent: true } ); await tile( 'Progress', 'none' ); expect( store.getState().doc?.settings.progressBar ).toEqual( { show: false } ); await tile( 'Progress', 'bar' ); expect( store.getState().doc?.settings.progressBar ).toEqual( { show: true } ); const height = [ ...container.querySelectorAll( '.ffxb-flow .ffxb-toggle label' ) ].find( ( l ) => 'Adjust height to each step' === l.textContent ) as HTMLLabelElement; const before = store.getState().doc?.settings.autoHeight; await act( async () => height.click() ); expect( store.getState().doc?.settings.autoHeight ).toBe( ! before ); } ); it( 'saves the style for other forms and applies a saved one', async () => { const api = fakeApi(); const store = createBuilderStore( api, 7, { autosaveMs: 60000 } ); await act( async () => root.render( undefined } store={ store } /> ) ); await settle(); await workspace( 'Design' ); await act( async () => ( container.querySelector( '.ffxb-saved-style__apply' ) as HTMLButtonElement ).click() ); expect( store.getState().doc?.style.tokens ).toEqual( { 'color.primary': '#c2410c', 'font.family': 'Poppins' } ); await act( async () => button( 'Save as style' ).click() ); const input = container.querySelector( '.ffxb-saved-styles__form input' ) as HTMLInputElement; await act( async () => { Object.getOwnPropertyDescriptor( HTMLInputElement.prototype, 'value' )?.set?.call( input, 'Kampagne' ); input.dispatchEvent( new Event( 'input', { bubbles: true } ) ); } ); await act( async () => button( 'Save style' ).click() ); await settle(); expect( api.saveStyle ).toHaveBeenCalledWith( 'Kampagne', { 'color.primary': '#c2410c', 'font.family': 'Poppins' } ); expect( [ ...container.querySelectorAll( '.ffxb-saved-style__apply' ) ].map( ( b ) => b.textContent ) ).toEqual( [ 'Kampagne', 'Hausstil' ] ); await act( async () => button( 'Delete style Hausstil' ).click() ); await settle(); expect( api.deleteStyle ).toHaveBeenCalledWith( 'st_000000000001' ); expect( container.querySelectorAll( '.ffxb-saved-style' ) ).toHaveLength( 1 ); } ); it( 'offers uploaded fonts and uploads a new one', async () => { const api = fakeApi(); const store = createBuilderStore( api, 7, { autosaveMs: 60000 } ); await act( async () => root.render( undefined } store={ store } /> ) ); await settle(); await workspace( 'Design' ); const select = [ ...container.querySelectorAll( '.ffxb-design-panel select' ) ].find( ( s ) => [ ...s.options ].some( ( o ) => 'Poppins' === o.value ) ) as HTMLSelectElement; expect( [ ...select.options ].map( ( o ) => o.textContent ) ).toContain( 'Brand Sans' ); const input = container.querySelector( 'input[type="file"][accept=".ttf,.otf,.woff,.woff2"]' ) as HTMLInputElement; const file = new File( [ 'wOF2' ], 'Hausschrift.woff2' ); Object.defineProperty( input, 'files', { value: [ file ], configurable: true } ); await act( async () => input.dispatchEvent( new Event( 'change', { bubbles: true } ) ) ); await settle(); expect( api.uploadFont ).toHaveBeenCalledWith( file, 'Hausschrift.woff2' ); expect( store.getState().doc?.style.tokens[ 'font.family' ] ).toBe( 'Hausschrift.woff2' ); } ); it( 'sets limits, look, images and a pasted list of answers', async () => { const pickImage = vi.fn( async () => ( { id: 9, url: 'https://example.org/rot.jpg', alt: '' } ) ); const api = fakeApi( { pickImage } ); const store = createBuilderStore( api, 7, { autosaveMs: 60000 } ); await act( async () => root.render( undefined } store={ store } /> ) ); await settle(); await act( async () => button( 'Choice' ).click() ); const field = (): ChoiceField => { const node = store.getState().doc?.nodes.find( ( n ) => n.id === store.getState().selection.node ); return ( node && 'step' === node.type ? node.fields[ 0 ] : undefined ) as ChoiceField; }; const toggle = async ( label: string ): Promise => { const found = [ ...container.querySelectorAll( '.ffxb-toggle label' ) ].find( ( l ) => l.textContent === label ) as HTMLLabelElement; await act( async () => ( document.getElementById( found.htmlFor ) as HTMLInputElement ).click() ); }; await toggle( 'Several answers allowed' ); await fill( 'At least', '2' ); await fill( 'At most', '1' ); expect( container.textContent ).toContain( 'The smallest number is above the largest.' ); await fill( 'At most', '3' ); await tile( 'Tiles per row on large screens', '3' ); await tile( 'Height of the answers', 'l' ); await tile( 'Position of icons and images', 'left' ); await toggle( 'Images fill the answer' ); expect( field().props ).toMatchObject( { multiple: true, minChoices: 2, maxChoices: 3, columns: { desktop: 3 }, size: 'l', iconPosition: 'left', imageFull: true } ); await tile( 'Format of the images', '1:1' ); expect( field().props.imageRatio ).toBe( '1:1' ); await tile( 'Format of the images', '4:3' ); expect( field().props.imageRatio ).toBeUndefined(); await tile( 'Format of the images', 'auto' ); await toggle( 'Images fill the answer' ); expect( field().props.imageFull ).toBeUndefined(); expect( field().props.imageRatio ).toBeUndefined(); await toggle( 'Images fill the answer' ); await tile( 'Tiles per row on large screens', '' ); await tile( 'Height of the answers', 'm' ); expect( field().props.columns ).toBeUndefined(); expect( field().props.size ).toBeUndefined(); await act( async () => button( 'Paste a list' ).click() ); const dialog = [ ...container.querySelectorAll( 'dialog' ) ].find( ( d ) => 'Paste a list of answers' === d.getAttribute( 'aria-label' ) ) as HTMLDialogElement; await fill( 'Answers', 'Rot\nGrün\n\nBlau', dialog ); await act( async () => button( 'Add 3 answers' ).click() ); expect( field().options.map( ( o ) => o.label ) ).toEqual( [ { de_DE: 'Rot' }, { de_DE: 'Grün' }, { de_DE: 'Blau' } ] ); // One button for icon or image; without the icon set the dialog opens on the image. await act( async () => button( 'Choose an icon or image for answer 1' ).click() ); const media = [ ...container.querySelectorAll( 'dialog' ) ].find( ( d ) => 'Icon or image of answer 1' === d.getAttribute( 'aria-label' ) ) as HTMLDialogElement; expect( media.textContent ).toContain( 'A photo or graphic from the media library' ); await act( async () => button( 'Choose from the media library' ).click() ); await settle(); expect( pickImage ).toHaveBeenCalledTimes( 1 ); expect( field().options[ 0 ]?.media ).toEqual( { kind: 'image', value: 'https://example.org/rot.jpg' } ); expect( ( container.querySelector( '.ffxb-icon-choice.has-image img' ) as HTMLImageElement ).src ).toBe( 'https://example.org/rot.jpg' ); await act( async () => button( 'Change the image of answer 1' ).click() ); await act( async () => button( 'Remove the image of answer 1' ).click() ); expect( field().options[ 0 ]?.media ).toBeUndefined(); } ); it( 'chooses icons for answers and contact fields', async () => { const library = { version: '1.58.0', icons: { house: [ [ 'path', { d: 'M3 10 12 3l9 7' } ] ], car: [ [ 'circle', { cx: '7', cy: '17', r: '2' } ] ], mail: [ [ 'rect', { x: '2', y: '4', width: '20', height: '16' } ] ] }, tags: { house: 'home living building', car: 'vehicle', mail: 'email message' }, } as unknown as IconLibrary; const icons = vi.fn( async () => library ); const api = fakeApi( { icons } ); const store = createBuilderStore( api, 7, { autosaveMs: 60000 } ); await act( async () => root.render( undefined } store={ store } /> ) ); await settle(); await act( async () => button( 'Choice' ).click() ); const field = (): ChoiceField => { const node = store.getState().doc?.nodes.find( ( n ) => n.id === store.getState().selection.node ); return ( node && 'step' === node.type ? node.fields[ 0 ] : undefined ) as ChoiceField; }; expect( icons ).not.toHaveBeenCalled(); await act( async () => button( 'Choose an icon for answer 1' ).click() ); await settle(); expect( icons ).toHaveBeenCalledTimes( 1 ); const dialog = [ ...container.querySelectorAll( 'dialog' ) ].find( ( d ) => 'Icon of answer 1' === d.getAttribute( 'aria-label' ) ) as HTMLDialogElement; // Without a search: the groups, the first with the icons of the set it names expect( [ ...dialog.querySelectorAll( '.ffxb-icon-picker__group' ) ].map( ( b ) => b.textContent ) ).toContain( 'Home and building' ); expect( dialog.querySelector( '.ffxb-icon-picker__group.is-selected' )?.textContent ).toBe( 'Popular' ); expect( [ ...dialog.querySelectorAll( '.ffxb-icon-picker__icon' ) ].map( ( b ) => b.getAttribute( 'aria-label' ) ) ).toEqual( [ 'house', 'car', 'mail' ] ); await act( async () => ( [ ...dialog.querySelectorAll( '.ffxb-icon-picker__group' ) ].find( ( b ) => 'All icons' === b.textContent ) as HTMLButtonElement ).click() ); expect( dialog.textContent ).toContain( 'Icons found: 3' ); expect( dialog.textContent ).toContain( 'Lucide 1.58.0' ); const search = dialog.querySelector( 'input[type="search"]' ) as HTMLInputElement; await act( async () => { Object.getOwnPropertyDescriptor( HTMLInputElement.prototype, 'value' )?.set?.call( search, 'home' ); search.dispatchEvent( new Event( 'input', { bubbles: true } ) ); } ); expect( [ ...dialog.querySelectorAll( '.ffxb-icon-picker__icon' ) ].map( ( b ) => b.getAttribute( 'aria-label' ) ) ).toEqual( [ 'house' ] ); await act( async () => ( dialog.querySelector( '[aria-label="house"]' ) as HTMLButtonElement ).click() ); expect( field().options[ 0 ]?.media ).toEqual( { kind: 'lucide', value: 'house' } ); expect( button( 'Change the icon of answer 1' ).querySelector( 'svg.ffxb-lucide path' )?.getAttribute( 'd' ) ).toBe( 'M3 10 12 3l9 7' ); await act( async () => button( 'Change the icon of answer 1' ).click() ); await act( async () => button( 'Remove icon' ).click() ); expect( field().options[ 0 ]?.media ).toBeUndefined(); expect( icons ).toHaveBeenCalledTimes( 1 ); const contact = (): Extract => store.getState().doc?.nodes.find( ( n ) => 'contact' === n.type ) as Extract; const email = contact().fields.find( ( f ) => 'email' === f.type ) as ContactField; await act( async () => store.getState().select( { node: contact().id, field: email.id } ) ); await act( async () => button( 'Choose an icon for the field' ).click() ); await settle(); await act( async () => ( container.querySelector( 'dialog[aria-label="Icon in the field"] [aria-label="mail"]' ) as HTMLButtonElement ).click() ); expect( ( contact().fields.find( ( f ) => f.id === email.id ) as ContactField ).props.icon ).toBe( 'lucide:mail' ); expect( container.querySelector( '.ffxb-icon-field' )?.textContent ).toContain( 'mail' ); } ); it( 'offers an icon or an own image in one dialog, each replacing the other', async () => { const library = { version: '1.58.0', icons: { house: [ [ 'path', { d: 'M3 10 12 3l9 7' } ] ] }, tags: { house: 'home' } } as unknown as IconLibrary; const pickImage = vi.fn( async () => ( { id: 9, url: 'https://example.org/haus.jpg', alt: '' } ) ); const api = fakeApi( { icons: vi.fn( async () => library ), pickImage } ); const store = createBuilderStore( api, 7, { autosaveMs: 60000 } ); await act( async () => root.render( undefined } store={ store } /> ) ); await settle(); await act( async () => button( 'Choice' ).click() ); const media = (): unknown => { const node = store.getState().doc?.nodes.find( ( n ) => n.id === store.getState().selection.node ); return node && 'step' === node.type ? ( node.fields[ 0 ] as ChoiceField ).options[ 0 ]?.media : undefined; }; const dialog = (): HTMLDialogElement => [ ...container.querySelectorAll( 'dialog' ) ].find( ( d ) => 'Icon or image of answer 1' === d.getAttribute( 'aria-label' ) ) as HTMLDialogElement; await act( async () => button( 'Choose an icon or image for answer 1' ).click() ); await settle(); expect( [ ...dialog().querySelectorAll( '[role="tab"]' ) ].map( ( t ) => [ t.textContent, t.getAttribute( 'aria-selected' ) ] ) ).toEqual( [ [ 'Icon', 'true' ], [ 'Own image', 'false' ] ] ); await act( async () => ( dialog().querySelector( '[aria-label="house"]' ) as HTMLButtonElement ).click() ); expect( media() ).toEqual( { kind: 'lucide', value: 'house' } ); await act( async () => button( 'Change the icon of answer 1' ).click() ); await act( async () => ( [ ...dialog().querySelectorAll( '[role="tab"]' ) ][ 1 ] as HTMLButtonElement ).click() ); await act( async () => button( 'Choose from the media library' ).click() ); await settle(); expect( media() ).toEqual( { kind: 'image', value: 'https://example.org/haus.jpg' } ); // An answer with an image opens on its image. await act( async () => button( 'Change the image of answer 1' ).click() ); expect( dialog().querySelector( '[role="tab"][aria-selected="true"]' )?.textContent ).toBe( 'Own image' ); expect( ( dialog().querySelector( '.ffxb-media-choice__preview' ) as HTMLImageElement ).src ).toBe( 'https://example.org/haus.jpg' ); } ); it( 'lists the questions, warns about a shared variable name and sorts answers', async () => { const api = fakeApi(); const store = createBuilderStore( api, 7, { autosaveMs: 60000 } ); await act( async () => root.render( undefined } store={ store } /> ) ); await settle(); await act( async () => button( 'Choice' ).click() ); const first = store.getState().selection; await act( async () => button( 'Choice' ).click() ); const second = store.getState().selection; // The second click adds the field to the selected step. expect( second.node ).toBe( first.node ); const fieldOf = ( sel: typeof first ): ChoiceField => { const node = store.getState().doc?.nodes.find( ( n ) => n.id === sel.node ); return ( node && 'step' === node.type ? node.fields.find( ( f ) => f.id === ( sel.field ?? node.fields[ 0 ]?.id ) ) : undefined ) as ChoiceField; }; expect( container.querySelector( '.ffxb-inspector .ffxb-notice' )?.textContent ?? '' ).not.toContain( 'variable name' ); await act( async () => store.getState().change( ( d ) => { const node = d.nodes.find( ( n ) => n.id === second.node ); const field = node && 'step' === node.type ? node.fields.find( ( f ) => f.id === second.field ) : undefined; if ( field ) { field.key = fieldOf( first ).key; field.required = false; } } ) ); expect( container.querySelector( '.ffxb-inspector' )?.textContent ).toContain( `The variable name "${ fieldOf( first ).key }" is used by` ); await act( async () => button( 'Move answer 1' ).dispatchEvent( new KeyboardEvent( 'keydown', { key: 'ArrowDown', bubbles: true } ) ) ); expect( fieldOf( second ).options.map( ( o ) => o.value ) ).toEqual( [ '2', '1' ] ); await act( async () => button( 'Questions' ).click() ); const items = (): string[] => [ ...container.querySelectorAll( '.ffxb-questions__item .ffxb-questions__title' ) ].map( ( e ) => e.textContent ?? '' ); expect( container.querySelector( '.ffxb-palette .ffxb-palette__hint' )?.textContent ).toMatch( /^\d+ of \d+ questions$/ ); const all = items().length; await fill( 'Search questions', 'e-mail' ); expect( items().length ).toBeLessThan( all ); expect( items().every( ( t ) => /e-mail/i.test( t ) ) ).toBe( true ); await fill( 'Search questions', '' ); await choose( 'Type', 'choice' ); expect( items() ).toHaveLength( 2 ); await choose( 'Type', '' ); await act( async () => ( container.querySelector( '.ffxb-palette .ffxb-toggle input' ) as HTMLInputElement ).click() ); expect( items().length ).toBeLessThan( all ); const reveal = vi.fn(); window.addEventListener( 'ffxb:reveal', reveal ); await act( async () => ( container.querySelector( '.ffxb-questions__item' ) as HTMLButtonElement ).click() ); window.removeEventListener( 'ffxb:reveal', reveal ); expect( store.getState().selection.field ).toBeDefined(); expect( reveal ).toHaveBeenCalledTimes( 1 ); expect( container.querySelector( '.ffxb-questions__item' )?.classList.contains( 'is-selected' ) ).toBe( true ); } ); it( 'gives dropdowns a search box, a placeholder and several answers', async () => { const api = fakeApi(); const store = createBuilderStore( api, 7, { autosaveMs: 60000 } ); await act( async () => root.render( undefined } store={ store } /> ) ); await settle(); await act( async () => button( 'Dropdown' ).click() ); const props = (): Record => { const node = store.getState().doc?.nodes.find( ( n ) => n.id === store.getState().selection.node ); return ( node && 'step' === node.type ? node.fields[ 0 ]?.props : {} ) as Record; }; await fill( 'Text while nothing is chosen', 'Farbe wählen' ); for ( const label of [ 'Search box above the answers', 'Several answers allowed' ] ) { const found = [ ...container.querySelectorAll( '.ffxb-toggle label' ) ].find( ( l ) => l.textContent === label ) as HTMLLabelElement; await act( async () => ( document.getElementById( found.htmlFor ) as HTMLInputElement ).click() ); } await fill( 'At most', '2' ); expect( props() ).toEqual( { placeholder: { de_DE: 'Farbe wählen' }, search: true, multiple: true, maxChoices: 2 } ); expect( container.textContent ).not.toContain( 'Continue on its own' ); } ); it( 'sets periods and limits of dates and ranges of sliders', async () => { const api = fakeApi(); const store = createBuilderStore( api, 7, { autosaveMs: 60000 } ); await act( async () => root.render( undefined } store={ store } /> ) ); await settle(); const props = (): Record => { const node = store.getState().doc?.nodes.find( ( n ) => n.id === store.getState().selection.node ); return ( node && 'step' === node.type ? node.fields.at( -1 )?.props : {} ) as Record; }; const toggle = async ( label: string ): Promise => { const found = [ ...container.querySelectorAll( '.ffxb-toggle label' ) ].find( ( l ) => l.textContent === label ) as HTMLLabelElement; await act( async () => ( document.getElementById( found.htmlFor ) as HTMLInputElement ).click() ); }; await act( async () => button( 'Date' ).click() ); await toggle( 'A period with start and end' ); await tile( 'Dates that can be chosen', 'future' ); await fill( 'Latest date', '2027-06-30' ); expect( props() ).toMatchObject( { format: 'dd.mm.yy', range: true, allow: 'future', max: '2027-06-30' } ); await tile( 'Dates that can be chosen', '' ); await fill( 'Latest date', '' ); expect( props() ).not.toHaveProperty( 'allow' ); expect( props() ).not.toHaveProperty( 'max' ); await act( async () => button( 'Slider' ).click() ); expect( container.textContent ).not.toContain( 'First handle starts at' ); await toggle( 'A range with two handles' ); await fill( 'First handle starts at', '20' ); await fill( 'Second handle starts at', '80' ); await choose( 'Thousands separator', "'" ); expect( props() ).toMatchObject( { range: true, start: 20, startEnd: 80, thousandsSeparator: true, separator: "'" } ); await choose( 'Thousands separator', 'none' ); expect( props() ).toMatchObject( { thousandsSeparator: false } ); expect( props() ).not.toHaveProperty( 'separator' ); await tile( 'Position of the unit', 'before' ); expect( props().unit ).toMatchObject( { position: 'before' } ); } ); it( 'gives scales colours, faces and own texts', async () => { const api = fakeApi(); const store = createBuilderStore( api, 7, { autosaveMs: 60000 } ); await act( async () => root.render( undefined } store={ store } /> ) ); await settle(); await act( async () => button( 'Rating' ).click() ); const props = (): Record => { const node = store.getState().doc?.nodes.find( ( n ) => n.id === store.getState().selection.node ); return ( node && 'step' === node.type ? node.fields.at( -1 )?.props : {} ) as Record; }; await fill( 'Highest rating', '3' ); await tile( 'Look', 'colors' ); await tile( 'Points show', 'emojis' ); expect( props() ).toMatchObject( { min: 1, max: 3, style: 'colors', show: 'emojis' } ); await tile( 'Points show', 'labels' ); await fill( 'Text for 3', 'Super' ); await fill( 'Text for 1', 'Schlecht' ); expect( props().labels ).toEqual( [ { de_DE: 'Schlecht' }, {}, { de_DE: 'Super' } ] ); await tile( 'Look', 'stars' ); expect( container.textContent ).toContain( 'Below the stars' ); await tile( 'Below the stars', '' ); expect( props() ).not.toHaveProperty( 'show' ); expect( container.textContent ).not.toContain( 'Text for 1' ); } ); it( 'adds lists to the contact step and sets its look', async () => { const api = fakeApi(); const store = createBuilderStore( api, 7, { autosaveMs: 60000 } ); await act( async () => root.render( undefined } store={ store } /> ) ); await settle(); const contact = (): Extract => store.getState().doc?.nodes.find( ( n ) => 'contact' === n.type ) as Extract; await act( async () => store.getState().select( { node: contact().id } ) ); await act( async () => button( 'List' ).click() ); const list = (): ContactField => contact().fields.at( -1 ) as ContactField; expect( list().type ).toBe( 'select' ); await fill( 'Answers', 'Küche\n\nBad\nGarten' ); expect( list().props.options ).toEqual( [ { id: 'o1', label: { de_DE: 'Küche' } }, { id: 'o2', label: { de_DE: 'Bad' } }, { id: 'o3', label: { de_DE: 'Garten' } }, ] ); expect( labelled( 'Answers' ).value ).toBe( 'Küche\n\nBad\nGarten' ); await act( async () => store.getState().select( { node: contact().id } ) ); await tile( 'On large screens', '2' ); await tile( 'Button position', 'right' ); await tile( 'Button size', 'l' ); const found = [ ...container.querySelectorAll( '.ffxb-toggle label' ) ].find( ( l ) => l.textContent === 'Hide labels' ) as HTMLLabelElement; await act( async () => ( document.getElementById( found.htmlFor ) as HTMLInputElement ).click() ); expect( contact().layout ).toEqual( { columns: { desktop: 2 }, button: { align: 'right', size: 'l' }, hideLabels: true } ); await tile( 'On large screens', '1' ); await tile( 'Button position', '' ); await tile( 'Button size', '' ); await act( async () => ( document.getElementById( found.htmlFor ) as HTMLInputElement ).click() ); expect( contact().layout ).toBeUndefined(); } ); it( 'adds a hidden field and fills fields from the page address', async () => { const api = fakeApi(); const store = createBuilderStore( api, 7, { autosaveMs: 60000 } ); await act( async () => root.render( undefined } store={ store } /> ) ); await settle(); const contact = (): Extract => store.getState().doc?.nodes.find( ( n ) => 'contact' === n.type ) as Extract; const toggle = async ( label: string ): Promise => { const found = [ ...container.querySelectorAll( '.ffxb-toggle label' ) ].find( ( l ) => l.textContent === label ) as HTMLLabelElement | undefined; if ( ! found ) { throw new Error( 'No switch ' + label ); } await act( async () => ( document.getElementById( found.htmlFor ) as HTMLInputElement ).click() ); }; await act( async () => store.getState().select( { node: contact().id } ) ); await act( async () => button( 'Hidden field' ).click() ); const hidden = (): ContactField => contact().fields.at( -1 ) as ContactField; expect( hidden() ).toMatchObject( { type: 'text', required: false, props: { hidden: true, prefillFromQuery: hidden().key } } ); // No placeholder, icon or required switch: visitors never see the field. expect( () => labelled( 'Placeholder' ) ).toThrow(); expect( [ ...container.querySelectorAll( '.ffxb-toggle label' ) ].map( ( l ) => l.textContent ) ).not.toContain( 'Required' ); await fill( 'Label', 'Kundennummer' ); await fill( 'URL parameter', 'kunden nummer' ); await fill( 'Fixed value', 'unbekannt' ); expect( hidden().props ).toEqual( { hidden: true, prefillFromQuery: 'kunden_nummer', defaultValue: 'unbekannt' } ); expect( container.querySelector( '.ffxb-prefill code' )?.textContent ).toBe( '?kunden_nummer=…' ); expect( container.textContent ).toContain( `{{field:${ hidden().key }}}` ); expect( validateDocument( store.getState().doc ).errors ).toEqual( [] ); // A visible field: off by default, on with its variable name. const name = contact().fields.find( ( f ) => 'name' === f.type ) as ContactField; await act( async () => store.getState().select( { node: contact().id, field: name.id } ) ); expect( labelled( 'Placeholder' ) ).toBeTruthy(); await toggle( 'Fill from the page address' ); expect( ( contact().fields.find( ( f ) => f.id === name.id ) as ContactField ).props.prefillFromQuery ).toBe( name.key ); expect( container.querySelector( '.ffxb-prefill code' )?.textContent ).toBe( `?${ name.key }=Max+Muster` ); await toggle( 'Fill from the page address' ); expect( ( contact().fields.find( ( f ) => f.id === name.id ) as ContactField ).props ).not.toHaveProperty( 'prefillFromQuery' ); // The hidden field turned back into a text field loses its fixed value. await act( async () => store.getState().select( { node: contact().id, field: hidden().id } ) ); await toggle( 'Hidden field' ); expect( hidden().props ).toEqual( { prefillFromQuery: 'kunden_nummer', placeholder: { de_DE: '' } } ); expect( labelled( 'Placeholder' ) ).toBeTruthy(); } ); it( 'sets custom code on the contact step and points to it from the thank-you page', async () => { const api = fakeApi(); const store = createBuilderStore( api, 7, { autosaveMs: 60000 } ); setCode( { allowed: false, settingsUrl: 'https://example.org/wp-admin/admin.php?page=funnelforms-settings#ffx-tracking' } ); try { await act( async () => root.render( undefined } store={ store } /> ) ); await settle(); const contact = (): Extract => store.getState().doc?.nodes.find( ( n ) => 'contact' === n.type ) as Extract; const end = store.getState().doc?.nodes.find( ( n ) => 'end' === n.type ) as FormNode; await act( async () => store.getState().select( { node: end.id } ) ); expect( container.textContent ).toContain( 'Code for this thank-you page, such as a conversion pixel, is set on the contact step.' ); await act( async () => button( 'Custom code' ).click() ); expect( store.getState().selection.node ).toBe( contact().id ); expect( container.textContent ).toContain( 'This site does not run custom code yet.' ); expect( container.querySelector( 'a[href$="#ffx-tracking"]' )?.textContent ).toBe( 'Allow in the settings' ); // In Pro, code after sending is an action; the step shows its own only while it has one (forms from 3.x). expect( () => labelled( 'After sending (thank-you page)' ) ).toThrow(); expect( container.textContent ).toContain( 'For code after sending, add the action "Custom code" under Actions.' ); await fill( 'When the step appears', "fbq('track', 'Lead');" ); await act( async () => store.getState().change( ( d ) => { const n = d.nodes.find( ( x ) => x.id === contact().id ) as Extract; n.tracking = { ...n.tracking, afterSubmit: 'gtag();' }; } ) ); await fill( 'After sending (thank-you page)', "gtag('event', 'conversion');" ); expect( contact().tracking ).toEqual( { onShow: "fbq('track', 'Lead');", afterSubmit: "gtag('event', 'conversion');" } ); expect( validateDocument( store.getState().doc as FormDocument ).errors ).toEqual( [] ); await fill( 'When the step appears', '' ); expect( contact().tracking ).toEqual( { afterSubmit: "gtag('event', 'conversion');" } ); await fill( 'After sending (thank-you page)', '' ); expect( contact().tracking ).toBeUndefined(); } finally { setCode( undefined ); } } ); it( 'shows the custom code read-only without the right to use unfiltered HTML', async () => { const api = fakeApi(); const store = createBuilderStore( api, 7, { autosaveMs: 60000 } ); await act( async () => root.render( undefined } store={ store } rights={ { entries: true, code: false, settings: false } } /> ) ); await settle(); const contact = store.getState().doc?.nodes.find( ( n ) => 'contact' === n.type ) as FormNode; await act( async () => store.getState().select( { node: contact.id } ) ); expect( labelled( 'When the step appears' ).disabled ).toBe( true ); expect( container.textContent ).toContain( 'Tracking code, scripts and custom CSS need the right to use unfiltered HTML.' ); expect( container.textContent ).not.toContain( 'This site does not run custom code yet.' ); } ); it( 'adds custom code after sending as an action, with placeholders at the cursor', async () => { const api = fakeApi(); const store = createBuilderStore( api, 7, { autosaveMs: 60000 } ); setCode( { allowed: false, settingsUrl: null } ); try { await act( async () => root.render( undefined } store={ store } /> ) ); await settle(); await afterSending(); await fill( 'Add an action', 'customCode' ); const action = (): Extract => store.getState().doc?.actions[ 0 ] as Extract; expect( action() ).toMatchObject( { on: 'submit', kind: 'customCode', config: { code: '' } } ); expect( container.textContent ).toContain( 'Enter the code that runs after sending.' ); expect( container.textContent ).toContain( 'This site does not run custom code yet. An administrator can allow it under Funnelforms → Settings.' ); await fill( 'Code', "" ); const box = labelled( 'Code' ); await act( async () => { box.focus(); box.setSelectionRange( 46, 46 ); box.blur(); } ); const email = store.getState().doc?.nodes.flatMap( ( n ) => ( 'contact' === n.type ? n.fields : [] ) ).find( ( f ) => 'email' === f.type ); await fill( 'Placeholders', `{{field:${ email?.key }}}` ); expect( action().config.code ).toBe( `` ); expect( container.querySelector( '.ffxb-action__target' )?.textContent ).toBe( "' ); source?.dispatchEvent( new Event( 'input', { bubbles: true } ) ); } ); const stored = store.getState().doc?.actions[ 0 ]; expect( stored && 'email' === stored.kind ? stored.config.body.de_DE : '' ).toContain( '