Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 | /*
* External dependencies
*/
import { ThemeProvider } from '@automattic/jetpack-components';
import { useModuleStatus, hasFeatureFlag } from '@automattic/jetpack-shared-extension-utils';
import {
URLInput,
InspectorAdvancedControls,
InspectorControls,
useBlockProps,
InnerBlocks,
useInnerBlocksProps,
store as blockEditorStore,
BlockControls,
BlockContextProvider,
} from '@wordpress/block-editor';
import { createBlock } from '@wordpress/blocks';
import {
Button,
Notice as CoreNotice,
PanelBody,
TextareaControl,
TextControl,
ToggleControl,
RadioControl,
} from '@wordpress/components';
import { useInstanceId } from '@wordpress/compose';
import { store as coreStore } from '@wordpress/core-data';
import { useSelect, useDispatch } from '@wordpress/data';
import { store as editorStore } from '@wordpress/editor';
import {
useRef,
useEffect,
useCallback,
lazy,
Suspense,
useState,
createInterpolateElement,
} from '@wordpress/element';
import { __, _x } from '@wordpress/i18n';
import { Link, Notice } from '@wordpress/ui';
import clsx from 'clsx';
/*
* Internal dependencies
*/
import { PANEL_STATE_STORE } from '../../form-editor/store/panel-state.ts';
import useConfigValue from '../../hooks/use-config-value.ts';
import { store as singleStepStore } from '../../store/form-step-preview.js';
import {
PREVIOUS_BUTTON_TEMPLATE,
NEXT_BUTTON_TEMPLATE,
NAVIGATION_TEMPLATE,
} from '../form-step-navigation/edit.jsx';
import StepControls from '../shared/components/form-step-controls/index.jsx';
import JetpackManageResponsesSettings from '../shared/components/jetpack-manage-responses-settings.jsx';
import { useFindBlockRecursively } from '../shared/hooks/use-find-block-recursively.js';
import useFormSteps from '../shared/hooks/use-form-steps.js';
import { SyncedAttributeProvider } from '../shared/hooks/use-synced-attributes.jsx';
import { CORE_BLOCKS, FIELD_BLOCK_PREFIX, FORM_POST_TYPE } from '../shared/util/constants.js';
import { childBlocks } from './child-blocks.js';
import { ConvertFormToolbar } from './components/convert-form-toolbar.tsx';
import FormStatusNotice from './components/form-status-notice.tsx';
import { ContactFormPlaceholder } from './components/jetpack-contact-form-placeholder.jsx';
import ContactFormSkeletonLoader from './components/jetpack-contact-form-skeleton-loader.jsx';
import NotificationsSettings from './components/notifications-settings.jsx';
import WebhooksSettings from './components/webhooks-settings.jsx';
import WidgetEditorReadonlyView from './components/widget-editor-readonly-view.tsx';
import { useCreateSyncedFormOnInsertion } from './hooks/use-create-synced-form-on-insertion.ts';
import { useSyncedFormAutoSave } from './hooks/use-synced-form-auto-save.ts';
import { useSyncedFormLoader } from './hooks/use-synced-form-loader.ts';
import { useSyncedForm } from './hooks/use-synced-form.ts';
import useDeprecatedThankYouMigration from './shared/hooks/use-deprecated-thank-you-migration.js';
import useFormBlockDefaults from './shared/hooks/use-form-block-defaults.js';
import useSingleInputFieldRequired from './shared/hooks/use-single-input-field-required.js';
import { getAutoRecipient } from './util/auto-recipient.ts';
import { getEditorContext } from './util/get-editor-context.ts';
import { isCollectingResponses } from './util/is-collecting-responses.ts';
import VariationPicker from './variation-picker.jsx';
import './util/form-styles.js';
const IntegrationControls = lazy( () => import( './components/jetpack-integration-controls.jsx' ) );
// Transforms
const FormTransitionState = {
TO_MULTISTEP: 'to-multistep',
TO_FORM: 'to-form',
IS_MULTISTEP: 'is-multistep',
IS_FORM: 'is-form',
};
const validFields = childBlocks.filter( childBlock => {
const settings = childBlock.settings as typeof childBlock.settings & {
parent?: string | string[];
};
return (
! settings.parent ||
settings.parent === 'jetpack/contact-form' ||
( Array.isArray( settings.parent ) && settings.parent.includes( 'jetpack/contact-form' ) )
);
} );
const ALLOWED_BLOCKS = [ ...validFields.map( block => `jetpack/${ block.name }` ) ];
// At the top level of a multistep form we allow navigation, progress indicator
// and the step-container itself (users may add it manually before steps are
// auto-structured). The core block list remains unchanged.
const ALLOWED_MULTI_STEP_BLOCKS = [
'jetpack/form-step-navigation',
'jetpack/form-progress-indicator',
'jetpack/form-step-container',
'jetpack/form-step-divider',
].concat( CORE_BLOCKS );
const REMOVE_FIELDS_FROM_FORM = [
'jetpack/form-step-navigation',
'jetpack/form-progress-indicator',
'jetpack/form-step-container',
];
const ALLOWED_FORM_BLOCKS = ALLOWED_BLOCKS.concat( CORE_BLOCKS ).filter(
block => ! REMOVE_FIELDS_FROM_FORM.includes( block )
);
// Fields surfaced first in the block inserter. The quick inserter (the inline
// "+" inside a form) shows only the first 6 prioritized blocks, and that
// prioritized order fully overrides Gutenberg's usage-based "most used"
// ranking. Deriving the order from child-blocks.js alone buried the most
// commonly used fields (Name, Email, Textarea…) past the 6-item cutoff while
// surfacing incidental ones like Hidden. List the common fields explicitly
// here; the remaining valid fields follow in their child-blocks.js order. See
// DSGCOM-690.
const FEATURED_INSERTER_FIELDS = [
'jetpack/field-name',
'jetpack/field-email',
'jetpack/field-textarea',
'jetpack/field-text',
'jetpack/field-telephone',
'jetpack/field-select',
];
const PRIORITIZED_INSERTER_BLOCKS = ( () => {
const validFieldNames = validFields.map( block => `jetpack/${ block.name }` );
return [
...FEATURED_INSERTER_FIELDS.filter( name => validFieldNames.includes( name ) ),
...validFieldNames.filter( name => ! FEATURED_INSERTER_FIELDS.includes( name ) ),
];
} )();
type CustomThankyouType =
| '' // default message
| 'noSummary' // default message without a summary
| 'message' // custom message
| 'redirect'; // redirect to a new URL
type Webhook = {
webhook_id: string;
url: string;
format: 'urlencoded' | 'json';
method: 'POST' | 'GET' | 'PUT';
enabled: boolean;
};
type JetpackContactFormAttributes = {
ref?: number;
to: string;
subject: string;
// Legacy support for the customThankyou attribute
customThankyou: CustomThankyouType;
customThankyouHeading: string;
customThankyouMessage: string;
customThankyouRedirect: string;
confirmationType: 'text' | 'redirect';
formTitle: string;
variationName: string;
emailNotifications: boolean;
disableGoBack: boolean;
disableSummary: boolean;
notificationRecipients: string[];
webhooks: Webhook[];
// Layout support attributes (added by block supports)
layout?: {
type?: string;
orientation?: 'horizontal' | 'vertical';
flexWrap?: 'wrap' | 'nowrap';
justifyContent?: string;
verticalAlignment?: string;
};
};
type JetpackContactFormEditProps = {
name: string;
attributes: JetpackContactFormAttributes;
setAttributes: ( attributes: Partial< JetpackContactFormAttributes > ) => void;
clientId: string;
className: string;
isSelected: boolean;
};
function JetpackContactFormEdit( {
name,
attributes,
setAttributes,
clientId,
className,
isSelected,
}: JetpackContactFormEditProps ) {
// Initialize default form block settings as needed.
useFormBlockDefaults( { attributes, setAttributes } );
const {
ref,
to,
subject,
customThankyouHeading,
customThankyouMessage,
customThankyouRedirect,
confirmationType,
formTitle,
variationName,
emailNotifications,
disableGoBack,
disableSummary,
notificationRecipients,
webhooks,
layout,
} = attributes;
const isIntegrationsEnabled = useConfigValue( 'isIntegrationsEnabled' );
const showWebhooks = useConfigValue( 'isWebhooksEnabled' ) && hasFeatureFlag( 'form-webhooks' );
const showBlockIntegrations = useConfigValue( 'showBlockIntegrations' );
const isCentralFormManagementEnabled = hasFeatureFlag( 'central-form-management' );
const instanceId = useInstanceId( JetpackContactFormEdit );
// Check if we're in widget editor with a synced form (ref)
const isWidgetEditorWithRef = !! ref && getEditorContext() === 'widget';
// Load synced form data from the jetpack_form post type
const {
syncedForm,
isLoading: isResolvingSyncedForm,
syncedAttributes: syncedFormAttributes,
syncedInnerBlocks: syncedFormBlocks,
errorType: syncedFormErrorType,
} = useSyncedForm( ref );
const { replaceInnerBlocks, __unstableMarkNextChangeAsNotPersistent, updateBlockAttributes } =
useDispatch( blockEditorStore );
// Backward compatibility for the deprecated customThankyou attribute.
// Older forms will have a customThankyou attribute set, but not a confirmationType attribute
// and not a disableSummary attribute, so we need to set it here.
useDeprecatedThankYouMigration( { attributes, setAttributes } );
const steps = useFormSteps( clientId );
// Get current step info for context
const currentStepInfo = useSelect(
select => select( singleStepStore ).getCurrentStepInfo( clientId, steps ),
[ clientId, steps ]
);
const findButtonsBlock = useCallback(
block =>
block.name === 'jetpack/button' ||
( block.name === 'core/button' && block.attributes?.tagName === 'button' ),
[]
);
const submitButton = useFindBlockRecursively( clientId, findButtonsBlock );
const {
postTitle,
hasAnyInnerBlocks,
postAuthorEmail,
selectedBlockClientId,
onlySubmitBlock,
isJetpackFormEditor,
hasChildSelected,
} = useSelect(
select => {
const {
getBlocks,
getBlock,
getSelectedBlockClientId,
getBlockParentsByBlockName,
hasSelectedInnerBlock,
} = select( blockEditorStore );
const { getEditedPostAttribute, getCurrentPostType } = select( editorStore );
const selectedBlockId = getSelectedBlockClientId();
const selectedBlock = getBlock( selectedBlockId );
let selectedStepBlockId = selectedBlockId;
if ( selectedBlock && selectedBlock.name !== 'jetpack/form-step' ) {
selectedStepBlockId = getBlockParentsByBlockName(
selectedBlockId,
'jetpack/form-step'
)[ 0 ];
}
const { getUser } = select( coreStore );
const innerBlocksData = getBlocks( clientId );
const isSingleButtonBlock =
innerBlocksData.length === 1 &&
( innerBlocksData[ 0 ].name === 'jetpack/button' ||
( innerBlocksData[ 0 ].name === 'core/button' &&
innerBlocksData[ 0 ].attributes?.tagName === 'button' ) );
const title = getEditedPostAttribute( 'title' );
const authorId = getEditedPostAttribute( 'author' );
const authorEmail = authorId && getUser( authorId )?.email;
return {
postTitle: title,
hasAnyInnerBlocks: innerBlocksData.length > 0 || syncedFormBlocks?.length > 0,
postAuthorEmail: authorEmail,
selectedBlockClientId: selectedStepBlockId,
onlySubmitBlock: isSingleButtonBlock,
isJetpackFormEditor: getCurrentPostType() === FORM_POST_TYPE,
hasChildSelected: hasSelectedInnerBlock( clientId, true ),
};
},
[ clientId, syncedFormBlocks ]
);
const formBlockDefaults = window.jpFormsBlocks?.defaults || {};
const autoRecipient = getAutoRecipient( {
serverSource: formBlockDefaults.toSource,
serverAddress: formBlockDefaults.to,
postAuthorEmail,
isStandaloneForm: isJetpackFormEditor,
} );
useEffect( () => {
if ( submitButton && ! submitButton.attributes.lock ) {
const lock = { move: false, remove: true };
submitButton.attributes.lock = lock;
}
}, [ submitButton ] );
// Panel state management for pre-publish panel navigation
const activePanel = useSelect(
select => {
// Only subscribe to panel state in the form editor
if ( ! isJetpackFormEditor ) {
return null;
}
const panelStore = select( PANEL_STATE_STORE ) as {
getActivePanel: () => string | null;
};
return panelStore?.getActivePanel?.() ?? null;
},
[ isJetpackFormEditor ]
);
const { closePanel } = useDispatch( PANEL_STATE_STORE );
// Track open state for each panel - panels open when activePanel matches, then stay open
const [ openPanels, setOpenPanels ] = useState< Record< string, boolean > >( {} );
// When activePanel changes, open that panel and clear the store
useEffect( () => {
if ( activePanel ) {
setOpenPanels( prev => ( { ...prev, [ activePanel ]: true } ) );
// Clear the active panel from the store so it doesn't reopen on re-render
closePanel();
}
}, [ activePanel, closePanel ] );
const { isSingleStep, isFirstStep, isLastStep, currentStepClientId } = useSelect(
select => {
const { getCurrentStepInfo, isSingleStepMode, getActiveStepId } = select( singleStepStore );
const info = getCurrentStepInfo( clientId, steps );
return {
isSingleStep: isSingleStepMode( clientId ),
isFirstStep: info ? info.isFirstStep : false,
isLastStep: info ? info.isLastStep : false,
currentStepClientId: getActiveStepId( clientId ),
};
},
[ clientId, steps ]
);
const wrapperRef = useRef( undefined );
const innerRef = useRef( undefined );
const blockProps = useBlockProps( {
ref: wrapperRef,
className: clsx( className, {
'is-multistep': variationName === 'multistep',
} ),
} );
const formClassnames = clsx(
className,
'jetpack-contact-form',
isFirstStep && 'is-first-step',
isLastStep && 'is-last-step',
variationName === 'multistep' && isSingleStep && 'is-previewing-step',
attributes?.layout ? 'has-jetpack-form-layout' : 'has-no-jetpack-form-layout'
);
const innerBlocksProps = useInnerBlocksProps(
{
ref: innerRef,
className: formClassnames,
style: window.jetpackForms.generateStyleVariables( innerRef.current ),
},
{
allowedBlocks:
variationName === 'multistep' ? ALLOWED_MULTI_STEP_BLOCKS : ALLOWED_FORM_BLOCKS,
prioritizedInserterBlocks: PRIORITIZED_INSERTER_BLOCKS,
templateInsertUpdatesSelection: false,
}
);
const { isLoadingModules, isChangingStatus, isModuleActive, changeStatus } =
useModuleStatus( 'contact-form' );
const { editEntityRecord } = useDispatch( coreStore );
const { setActiveStep } = useDispatch( singleStepStore );
const currentInnerBlocks = useSelect(
select => select( blockEditorStore ).getBlocks( clientId ),
[ clientId ]
);
// Sync synced form content INTO the editor (one-time on ref change)
const { isSyncingRef, syncGeneration } = useSyncedFormLoader( {
ref,
syncedFormBlocks,
syncedFormAttributes,
clientId,
setAttributes,
replaceInnerBlocks,
__unstableMarkNextChangeAsNotPersistent,
setActiveStep,
} );
// Auto-save editor changes BACK to the synced form post
const { flushPendingSave } = useSyncedFormAutoSave( {
ref,
syncedForm,
attributes,
currentInnerBlocks,
isSyncingRef,
syncGeneration,
editEntityRecord,
} );
// Create synced form when a variation is inserted via the block inserter
useCreateSyncedFormOnInsertion( {
clientId,
ref,
innerBlocks: currentInnerBlocks,
attributes,
setAttributes,
} );
// Note: We don't clear attributes in memory when ref is set, as they're needed
// for the form to work properly in the editor. The save() method ensures that
// only the ref attribute is persisted to the database.
// Track previous block count to detect insertions
const previousBlockCountRef = useRef( currentInnerBlocks.length );
// Effect to handle block insertion and reordering
useEffect( () => {
const currentBlockCount = currentInnerBlocks.length;
const previousBlockCount = previousBlockCountRef.current;
// Detect if a block was just inserted
const blockWasInserted = currentBlockCount > previousBlockCount;
if ( blockWasInserted && currentInnerBlocks.length > 1 ) {
// Find the submit button
const submitButtonIndex = currentInnerBlocks.findIndex(
block =>
( block.name === 'core/button' || block.name === 'jetpack/button' ) &&
( block.attributes?.customVariant === 'submit' ||
block.attributes?.element === 'button' ||
block.attributes?.tagName === 'button' )
);
// If there's a submit button and it's not the last block, reorder
if ( submitButtonIndex !== -1 && submitButtonIndex === currentInnerBlocks.length - 2 ) {
// Move the submit button to the end
const reorderedBlocks = [ ...currentInnerBlocks ];
const [ submitButtonBlock ] = reorderedBlocks.splice( submitButtonIndex, 1 );
reorderedBlocks.push( submitButtonBlock );
// Update the blocks without creating an undo step
__unstableMarkNextChangeAsNotPersistent();
replaceInnerBlocks( clientId, reorderedBlocks, false );
}
}
// Update the previous block count
previousBlockCountRef.current = currentBlockCount;
}, [
currentInnerBlocks,
clientId,
replaceInnerBlocks,
__unstableMarkNextChangeAsNotPersistent,
] );
// A form with a single field has nothing to submit unless that field is filled in.
useSingleInputFieldRequired( { innerBlocks: currentInnerBlocks } );
// Helper function to get all field blocks (blocks with width attribute)
const getFieldBlocks = useCallback( ( blocks: typeof currentInnerBlocks ) => {
const fieldBlocks: typeof currentInnerBlocks = [];
const findFields = ( blockList: typeof currentInnerBlocks ) => {
blockList.forEach( block => {
// Check if block is a field (has jetpack/field- prefix)
if ( block.name.startsWith( FIELD_BLOCK_PREFIX ) ) {
fieldBlocks.push( block );
}
// Recursively check inner blocks (for multistep forms)
if ( block.innerBlocks && block.innerBlocks.length > 0 ) {
findFields( block.innerBlocks );
}
} );
};
findFields( blocks );
return fieldBlocks;
}, [] );
// Track previous orientation to detect changes
const prevOrientationRef = useRef< string | null >( null );
// Effect to sync field widths when layout orientation changes
useEffect( () => {
const orientation = layout?.orientation ?? 'horizontal';
// Skip initial render, only react to actual orientation changes
if ( prevOrientationRef.current !== null && prevOrientationRef.current !== orientation ) {
const fieldBlocks = getFieldBlocks( currentInnerBlocks );
const newWidth = orientation === 'vertical' ? 100 : 'auto';
fieldBlocks.forEach( field => {
updateBlockAttributes( field.clientId, { width: newWidth } );
} );
}
prevOrientationRef.current = orientation;
}, [ layout?.orientation, currentInnerBlocks, getFieldBlocks, updateBlockAttributes ] );
// Deep-scan helper – user might drop a Step block inside nested structures.
const containsMultistepBlock = useCallback( function hasMultistep( blocks ) {
return blocks.some(
b =>
b.name === 'jetpack/form-step' ||
b.name === 'jetpack/form-step-container' ||
b.name === 'jetpack/form-step-divider' ||
( b.innerBlocks?.length && hasMultistep( b.innerBlocks ) )
);
}, [] );
// Detect a conversion to a multistep form and structure inner blocks only once.
const formTransitionStateRef = useRef< string | null >( null );
useEffect( () => {
const hasMultistepBlock = containsMultistepBlock( currentInnerBlocks );
// Transition to single-step form state if no multistep blocks are present
// and the variation is not set to 'multistep'.
if ( ! hasMultistepBlock && variationName !== 'multistep' ) {
formTransitionStateRef.current = FormTransitionState.IS_FORM;
return;
}
// Transition to multistep form state if multistep blocks are present
// and the variation is set to 'multistep'.
if ( variationName === 'multistep' && hasMultistepBlock ) {
formTransitionStateRef.current = FormTransitionState.IS_MULTISTEP;
return;
}
// Transition from multistep form state to single-step form state.
if ( formTransitionStateRef.current === FormTransitionState.IS_MULTISTEP ) {
formTransitionStateRef.current = FormTransitionState.TO_FORM;
return;
}
// Transition from single-step form state to multistep form state.
formTransitionStateRef.current = FormTransitionState.TO_MULTISTEP;
// If the form is not multistep, we don't need to do anything.
}, [ variationName, currentInnerBlocks, containsMultistepBlock ] );
useEffect( () => {
// Early exit if we are still on the multistep variation or if there are
// no multistep-specific blocks to clean up.
if ( formTransitionStateRef.current !== FormTransitionState.TO_MULTISTEP ) {
return;
}
/*
* Only skip the expensive restructuring logic when the form is **already in a
* fully-structured multistep shape**:
* – exactly one `jetpack/step-container` anywhere in the block tree, and
* – there are **no** `form-step` blocks that live outside that container.
* In all other cases we still need to normalise the tree (e.g. when the user
* inserts a Step Container while other fields remain outside of it).
*/
const countBlocks = ( blocks, predicate ) =>
blocks.reduce(
( acc, b ) =>
acc + ( predicate( b ) ? 1 : 0 ) + countBlocks( b.innerBlocks || [], predicate ),
0
);
const stepContainerCount = countBlocks(
currentInnerBlocks,
b => b.name === 'jetpack/form-step-container'
);
// Helper: detect any form-step that is NOT inside a step-container.
const hasStrayFormStep = ( blocks, insideContainer = false ) => {
for ( const b of blocks ) {
const newInside = insideContainer || b.name === 'jetpack/form-step-container';
if ( b.name === 'jetpack/form-step' && ! newInside ) {
return true;
}
if ( b.innerBlocks?.length && hasStrayFormStep( b.innerBlocks, newInside ) ) {
return true;
}
}
return false;
};
const formIsFullyStructured =
stepContainerCount === 1 && ! hasStrayFormStep( currentInnerBlocks );
if ( formIsFullyStructured ) {
return;
}
// Helper functions
const findButtonBlock = () => {
const buttonIndex = currentInnerBlocks.findIndex(
block =>
block.name === 'jetpack/button' ||
( block.name === 'core/button' && block.attributes?.tagName === 'button' )
);
return buttonIndex !== -1
? {
block: currentInnerBlocks[ buttonIndex ],
index: buttonIndex,
}
: null;
};
const prepareSubmitButton = button => {
if ( ! button ) return null;
const preparedButton = button;
// Add the form-button-submit and is-submit classes for identification and CSS visibility
const existingClassName = preparedButton.attributes.className || '';
const existingClassTokens = existingClassName.split( /\s+/ ).filter( Boolean );
const classesToAdd = [];
if ( ! existingClassTokens.includes( 'form-button-submit' ) ) {
classesToAdd.push( 'form-button-submit' );
}
if ( ! existingClassTokens.includes( 'is-submit' ) ) {
classesToAdd.push( 'is-submit' );
}
if ( classesToAdd.length > 0 ) {
preparedButton.attributes.className = existingClassName
? `${ existingClassName } ${ classesToAdd.join( ' ' ) }`
: classesToAdd.join( ' ' );
}
// Set metadata name for core/button
preparedButton.attributes.metadata = {
...( preparedButton.attributes.metadata || {} ),
name: __( 'Submit button', 'jetpack-forms' ),
};
return preparedButton;
};
const createStepNavigation = button => {
// Find existing navigation block or create new one
const existingNavigation = currentInnerBlocks.find(
block => block.name === 'jetpack/form-step-navigation'
);
if ( existingNavigation && button ) {
// Add button to existing navigation
return createBlock( 'jetpack/form-step-navigation', existingNavigation.attributes, [
...( existingNavigation.innerBlocks || [] ),
button,
] );
} else if ( existingNavigation ) {
return existingNavigation;
}
// Create new navigation with or without button
return createBlock(
'jetpack/form-step-navigation',
{
layout: {
type: 'flex',
justifyContent: 'right',
},
},
button
? [
createBlock(
...( PREVIOUS_BUTTON_TEMPLATE as [ string, Record< string, unknown > ] )
),
createBlock( ...( NEXT_BUTTON_TEMPLATE as [ string, Record< string, unknown > ] ) ),
button,
]
: NAVIGATION_TEMPLATE.map( template =>
createBlock( ...( template as [ string, Record< string, unknown > ] ) )
)
);
};
const getProgressIndicator = () => {
const existingIndicator = currentInnerBlocks.find(
block => block.name === 'jetpack/form-progress-indicator'
);
return existingIndicator || createBlock( 'jetpack/form-progress-indicator', {}, [] );
};
// 1. Extract button if it exists
const buttonData = findButtonBlock();
const buttonBlock = buttonData ? buttonData.block : null;
// 2. Get blocks excluding the button
const blocksWithoutButton = buttonData
? currentInnerBlocks.filter( ( _, index ) => index !== buttonData.index )
: currentInnerBlocks;
// 3. Prepare step container based on current blocks
let stepBlocks = [];
const containerIndex = blocksWithoutButton.findIndex(
block => block.name === 'jetpack/form-step-container'
);
if ( containerIndex !== -1 ) {
// Case A: Step container was inserted.
const beforeBlocks = blocksWithoutButton.slice( 0, containerIndex );
const afterBlocks = blocksWithoutButton.slice( containerIndex + 1 );
const existingStepContainer = blocksWithoutButton[ containerIndex ];
// Use existing steps if available, otherwise create new ones
if ( existingStepContainer.innerBlocks && existingStepContainer.innerBlocks.length > 0 ) {
stepBlocks = existingStepContainer.innerBlocks;
} else {
// Create steps from blocks before and after the container
if ( beforeBlocks.length > 0 ) {
stepBlocks.push( createBlock( 'jetpack/form-step', {}, beforeBlocks ) );
}
if ( afterBlocks.length > 0 ) {
stepBlocks.push( createBlock( 'jetpack/form-step', {}, afterBlocks ) );
}
if ( stepBlocks.length === 0 ) {
stepBlocks.push( createBlock( 'jetpack/form-step', {}, [] ) );
}
}
} else {
// Case B: Has form-step block but no container
const stepIndex = blocksWithoutButton.findIndex(
block => block.name === 'jetpack/form-step'
);
if ( stepIndex !== -1 ) {
const beforeBlocks = blocksWithoutButton.slice( 0, stepIndex );
const afterBlocks = blocksWithoutButton.slice( stepIndex + 1 );
if ( beforeBlocks.length > 0 ) {
stepBlocks.push( createBlock( 'jetpack/form-step', {}, beforeBlocks ) );
}
stepBlocks.push( blocksWithoutButton[ stepIndex ] );
if ( afterBlocks.length > 0 ) {
stepBlocks.push( createBlock( 'jetpack/form-step', {}, afterBlocks ) );
}
}
// Case C: No step blocks or containers — build steps based on divider markers.
else if ( blocksWithoutButton.length > 0 ) {
const hasDivider = blocksWithoutButton.some( b => b.name === 'jetpack/form-step-divider' );
if ( hasDivider ) {
// Split by divider markers into groups
const groups = [];
let currentGroup = [];
blocksWithoutButton.forEach( block => {
if ( block.name === 'jetpack/form-step-divider' ) {
// Commit current group (even empty to respect explicit divider)
groups.push( currentGroup );
currentGroup = [];
} else {
currentGroup.push( block );
}
} );
// Add the trailing group
groups.push( currentGroup );
stepBlocks = groups.map( inner => createBlock( 'jetpack/form-step', {}, inner ) );
} else {
// Fallback: one step per top-level block
stepBlocks = blocksWithoutButton.map( block =>
createBlock( 'jetpack/form-step', {}, [ block ] )
);
}
// Ensure at least one step exists
if ( stepBlocks.length === 0 ) {
stepBlocks = [ createBlock( 'jetpack/form-step', {}, [] ) ];
}
} else {
stepBlocks = [ createBlock( 'jetpack/form-step', {}, [] ) ];
}
}
// Create the step container with the step blocks
const stepContainer = createBlock( 'jetpack/form-step-container', {}, stepBlocks );
// 4. Prepare all components for the final form
const preparedButton = prepareSubmitButton( buttonBlock );
const stepNavigation = createStepNavigation( preparedButton );
const progressIndicator = getProgressIndicator();
// 5. Replace all inner blocks with our structured form (no extra undo level),
// then flip the variation which *does* create the single desired snapshot.
__unstableMarkNextChangeAsNotPersistent();
replaceInnerBlocks( clientId, [ progressIndicator, stepContainer, stepNavigation ], false );
// Select the first step so the editor shows it immediately
if ( stepContainer.innerBlocks.length > 0 ) {
setActiveStep( clientId, stepContainer.innerBlocks[ 0 ].clientId );
}
// Ensure we are marked as multistep – this records the undo level.
if ( variationName !== 'multistep' ) {
setAttributes( { variationName: 'multistep' } );
}
formTransitionStateRef.current = FormTransitionState.IS_MULTISTEP;
}, [
variationName,
currentInnerBlocks,
clientId,
replaceInnerBlocks,
setActiveStep,
setAttributes,
containsMultistepBlock,
__unstableMarkNextChangeAsNotPersistent,
] );
/*───────────────────────────────────────────────────────────────────────────
* Flatten multistep structure → standard form
*───────────────────────────────────────────────────────────────────────*/
useEffect( () => {
// Early exit if we are still on the multistep variation or if there are
// no multistep-specific blocks to clean up.
if ( FormTransitionState.TO_FORM !== formTransitionStateRef.current ) {
return;
}
// Will hold a reference to the submit button that should remain after cleanup.
let finalSubmitButton = null;
// Flatten helper – collects blocks that should remain in the standard form.
const flattenBlocks = blocks => {
let flat = [];
blocks.forEach( block => {
if ( block.name === 'jetpack/form-step-container' ) {
// Extract inner content of each step.
block.innerBlocks.forEach( step => {
if ( step.name === 'jetpack/form-step' ) {
flat = flat.concat( step.innerBlocks );
}
} );
return;
}
if ( block.name === 'jetpack/form-step' ) {
flat = flat.concat( block.innerBlocks );
return;
}
if (
block.name === 'jetpack/form-step-navigation' ||
block.name === 'jetpack/form-progress-indicator' ||
block.name === 'jetpack/form-step-divider'
) {
// Capture submit button (if any) inside navigation but skip the wrapper.
if ( ! finalSubmitButton ) {
finalSubmitButton = block.innerBlocks?.find( inner => {
// Check for jetpack/button with customVariant (legacy)
if (
inner.name === 'jetpack/button' &&
inner.attributes?.customVariant === 'submit'
) {
return true;
}
// Check for core/button with form-button-submit class
if ( inner.name === 'core/button' ) {
const buttonClassName = inner.attributes?.className || '';
return buttonClassName.split( /\s+/ ).includes( 'form-button-submit' );
}
return false;
} );
}
return; // Omit multistep-specific blocks.
}
// For any other block, keep as-is.
flat.push( block );
} );
return flat;
};
const flattenedInnerBlocks = flattenBlocks( currentInnerBlocks );
// Ensure we have a submit button at the end of the form.
if ( ! finalSubmitButton ) {
// Create a fresh submit button if none was found.
finalSubmitButton = createBlock( 'core/button', {
text: __( 'Submit', 'jetpack-forms' ),
type: 'submit',
tagName: 'button',
} );
}
const finalBlocks = [ ...flattenedInnerBlocks, finalSubmitButton ];
__unstableMarkNextChangeAsNotPersistent();
replaceInnerBlocks( clientId, finalBlocks, false );
// Reset the variation attribute if still set to something else.
if ( variationName !== 'default-empty' ) {
__unstableMarkNextChangeAsNotPersistent();
setAttributes( { variationName: 'default-empty' } );
}
formTransitionStateRef.current = FormTransitionState.IS_FORM;
}, [
variationName,
currentInnerBlocks,
containsMultistepBlock,
clientId,
replaceInnerBlocks,
__unstableMarkNextChangeAsNotPersistent,
setAttributes,
] );
useEffect( () => {
if (
variationName === 'multistep' &&
isSingleStep &&
steps.length > 0 &&
! currentStepClientId
) {
setActiveStep( clientId, steps[ 0 ].clientId );
}
}, [ variationName, isSingleStep, steps, currentStepClientId, clientId, setActiveStep ] );
// Find the selected block and its parent step block
const selectedBlock = useFindBlockRecursively(
selectedBlockClientId,
block => block.clientId === selectedBlockClientId
);
const stepBlock = useFindBlockRecursively(
selectedBlock?.clientId || '',
block => block.name === 'jetpack/form-step'
);
useEffect( () => {
if ( ! isSingleStep ) {
return;
}
if (
selectedBlockClientId &&
stepBlock &&
stepBlock.clientId !== currentStepClientId &&
currentStepClientId
) {
setActiveStep( clientId, stepBlock.clientId );
}
}, [
selectedBlockClientId,
clientId,
steps,
setActiveStep,
isSingleStep,
currentStepClientId,
stepBlock,
] );
// Determine if form or any child is selected for status notice visibility
const isFormOrChildSelected = isSelected || hasChildSelected;
let elt;
if ( ref && isResolvingSyncedForm && ! hasAnyInnerBlocks ) {
return (
<div { ...blockProps }>
<ContactFormSkeletonLoader />
</div>
);
}
// Show error if referenced form not found or not accessible
else if ( ref && ! syncedForm && ! isResolvingSyncedForm ) {
// Note: The two __() calls must remain dissimilar to prevent Terser from
// compacting them into a single call with a ternary argument, which breaks i18n.
const errorMessage =
syncedFormErrorType === 'permission_denied'
? __( "You don't have permission to edit this form.", 'jetpack-forms' )
: _x( 'The referenced form could not be found.', 'synced form error', 'jetpack-forms' );
elt = (
<CoreNotice status="warning" isDismissible={ false }>
{ errorMessage }
</CoreNotice>
);
}
// In widget editor, synced forms (with ref) are not editable
else if ( isWidgetEditorWithRef ) {
return (
<WidgetEditorReadonlyView
blockProps={ blockProps }
innerBlocksProps={ innerBlocksProps }
isResolvingSyncedForm={ isResolvingSyncedForm }
formRef={ ref as number }
flushPendingSave={ flushPendingSave }
/>
);
} else if ( ! isModuleActive ) {
if ( isLoadingModules ) {
return (
<div { ...blockProps }>
<ContactFormSkeletonLoader />
</div>
);
}
elt = (
<ContactFormPlaceholder
changeStatus={ changeStatus }
isModuleActive={ isModuleActive }
isLoading={ isChangingStatus }
/>
);
} else if ( ! hasAnyInnerBlocks ) {
elt = (
<VariationPicker
blockName={ name }
setAttributes={ setAttributes }
clientId={ clientId }
classNames={ formClassnames }
/>
);
} else if ( onlySubmitBlock ) {
elt = (
<>
<div className="is-form-empty">
<InnerBlocks.ButtonBlockAppender />
</div>
<div { ...innerBlocksProps } />
</>
);
} else {
elt = (
<>
<BlockControls>
{ isCentralFormManagementEnabled && ! isJetpackFormEditor && (
<ConvertFormToolbar
clientId={ clientId }
attributes={ attributes }
onBeforeNavigate={ flushPendingSave }
/>
) }
{ variationName === 'multistep' && <StepControls formClientId={ clientId } /> }
</BlockControls>
<InspectorControls>
{ ! isCollectingResponses( attributes ) && (
<Notice.Root intent="warning" className="jetpack-contact-form__not-collecting-notice">
<Notice.Title>
{ __( 'This form isn’t collecting responses', 'jetpack-forms' ) }
</Notice.Title>
<Notice.Description>
{ createInterpolateElement(
__(
'Turn on <email>email notifications</email> or <storage>response storage</storage> settings to start collecting.',
'jetpack-forms'
),
{
email: (
<Button
variant="link"
onClick={ () =>
setOpenPanels( prev => ( { ...prev, 'form-notifications': true } ) )
}
children={ null }
/>
),
storage: (
<Button
variant="link"
onClick={ () =>
setOpenPanels( prev => ( { ...prev, 'responses-storage': true } ) )
}
children={ null }
/>
),
}
) }
</Notice.Description>
</Notice.Root>
) }
<PanelBody
title={ __( 'Action after submit', 'jetpack-forms' ) }
initialOpen={ false }
opened={ openPanels[ 'action-after-submit' ] }
onToggle={ () =>
setOpenPanels( prev => ( {
...prev,
'action-after-submit': ! prev[ 'action-after-submit' ],
} ) )
}
className="jetpack-contact-form__panel"
>
<RadioControl
label={ __( 'Confirmation type', 'jetpack-forms' ) }
selected={ confirmationType }
options={ [
{ label: __( 'Text', 'jetpack-forms' ), value: 'text' },
{ label: __( 'Redirect link', 'jetpack-forms' ), value: 'redirect' },
] }
onChange={ ( newValue: 'text' | 'redirect' ) =>
setAttributes( { confirmationType: newValue } )
}
/>
{ 'text' === confirmationType && (
<>
<TextControl
label={ __( 'Message heading', 'jetpack-forms' ) }
value={ customThankyouHeading }
placeholder={ __( 'Thank you for your response.', 'jetpack-forms' ) }
onChange={ ( newHeading: string ) =>
setAttributes( { customThankyouHeading: newHeading } )
}
__nextHasNoMarginBottom={ true }
__next40pxDefaultSize={ true }
/>
<TextareaControl
label={ __( 'Message text', 'jetpack-forms' ) }
value={ customThankyouMessage }
placeholder={ __( 'Thank you for your submission!', 'jetpack-forms' ) }
onChange={ ( newMessage: string ) =>
setAttributes( { customThankyouMessage: newMessage } )
}
__nextHasNoMarginBottom={ true }
/>
<ToggleControl
label={ __( 'Show summary', 'jetpack-forms' ) }
checked={ ! disableSummary }
onChange={ ( newDisableSummary: boolean ) =>
setAttributes( { disableSummary: ! newDisableSummary } )
}
__nextHasNoMarginBottom={ true }
/>
<ToggleControl
label={ __( 'Show "Go back" link', 'jetpack-forms' ) }
checked={ ! disableGoBack }
onChange={ ( newDisableGoBack: boolean ) =>
setAttributes( { disableGoBack: ! newDisableGoBack } )
}
__nextHasNoMarginBottom={ true }
/>
</>
) }
{ 'redirect' === confirmationType && (
<div>
<URLInput
label={ __( 'Redirect address', 'jetpack-forms' ) }
value={ customThankyouRedirect }
className="jetpack-contact-form__thankyou-redirect-url"
onChange={ ( newURL: string ) =>
setAttributes( { customThankyouRedirect: newURL } )
}
/>
</div>
) }
</PanelBody>
<PanelBody
title={ __( 'Form notifications', 'jetpack-forms' ) }
initialOpen={ false }
opened={ openPanels[ 'form-notifications' ] }
onToggle={ () =>
setOpenPanels( prev => ( {
...prev,
'form-notifications': ! prev[ 'form-notifications' ],
} ) )
}
className="jetpack-contact-form__panel"
>
<NotificationsSettings
notificationRecipients={ notificationRecipients }
emailAddress={ to }
emailSubject={ subject }
emailNotifications={ emailNotifications }
instanceId={ instanceId }
autoRecipient={ autoRecipient.address }
autoRecipientSource={ autoRecipient.source }
autoSubject={ formBlockDefaults.subject || '' }
setAttributes={ setAttributes }
/>
</PanelBody>
{ showWebhooks && (
<PanelBody
title={ __( 'Webhooks', 'jetpack-forms' ) }
className="jetpack-contact-form__panel"
initialOpen={ false }
>
<WebhooksSettings
webhooks={ webhooks }
setAttributes={ setAttributes }
clientId={ clientId }
/>
</PanelBody>
) }
<PanelBody
title={ __( 'Responses storage', 'jetpack-forms' ) }
className="jetpack-contact-form__panel jetpack-contact-form__responses-storage-panel"
initialOpen={ false }
opened={ openPanels[ 'responses-storage' ] }
onToggle={ () =>
setOpenPanels( prev => ( {
...prev,
'responses-storage': ! prev[ 'responses-storage' ],
} ) )
}
>
<JetpackManageResponsesSettings
attributes={ attributes }
setAttributes={ setAttributes }
/>
</PanelBody>
</InspectorControls>
{ /* A sibling of InspectorControls, not a child of it: IntegrationControls owns
its own inspector fill, and its other half -- a toolbar button and the dialog
that button opens -- must stay outside one. See the component for why.
Gated on selection because it is lazy(): rendered unconditionally, the
import fires on the block's first render, pulling ~30KB gz of chunk into
editor boot for a UI that nothing can reach until the block is selected.
Both halves render nothing when it isn't, so this costs no behaviour. */ }
{ isIntegrationsEnabled && showBlockIntegrations && isFormOrChildSelected && (
<Suspense fallback={ <div /> }>
<IntegrationControls attributes={ attributes } setAttributes={ setAttributes } />
</Suspense>
) }
<InspectorAdvancedControls>
<TextControl
label={ __( 'Accessible name', 'jetpack-forms' ) }
value={ formTitle }
placeholder={ postTitle }
onChange={ value => setAttributes( { formTitle: value } ) }
help={ __(
'Add an accessible name to help people using assistive technology identify the form. Defaults to page or post title.',
'jetpack-forms'
) }
__nextHasNoMarginBottom={ true }
__next40pxDefaultSize={ true }
/>
<p>
<Link openInNewTab href="https://developer.mozilla.org/docs/Glossary/Accessible_name">
{ __( 'Read more.', 'jetpack-forms' ) }
</Link>
</p>
</InspectorAdvancedControls>
<BlockContextProvider
value={ {
'jetpack/form-steps': steps,
'jetpack/form-current-step': currentStepInfo,
} }
>
<div { ...innerBlocksProps } />
</BlockContextProvider>
</>
);
}
return (
<SyncedAttributeProvider>
<ThemeProvider targetDom={ wrapperRef.current }>
<div { ...blockProps }>
{ ref && (
<FormStatusNotice
syncedForm={ syncedForm }
formRef={ ref }
isVisible={ isFormOrChildSelected }
clientId={ clientId }
/>
) }
{ elt }
</div>
</ThemeProvider>
</SyncedAttributeProvider>
);
}
export default JetpackContactFormEdit;
|