Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
Significance: minor
Type: added

Add ConvertFormToolbar component for managing synced form conversions in the block editor
Copy link

Copilot AI Dec 12, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The changelog entry only mentions adding the ConvertFormToolbar component, but this PR introduces several other significant changes including the useSyncedForm hook, form-sync-manager utilities, PHP rendering logic for synced forms, and the ref attribute. Consider updating the changelog to provide a more comprehensive summary of all the changes.

Suggested change
Add ConvertFormToolbar component for managing synced form conversions in the block editor
Add ConvertFormToolbar component for managing synced form conversions in the block editor.
Also introduce the useSyncedForm hook, form-sync-manager utilities, PHP rendering logic for synced forms, and support for the ref attribute to enhance form synchronization and rendering capabilities.

Copilot uses AI. Check for mistakes.
7 changes: 5 additions & 2 deletions projects/packages/forms/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,19 +16,20 @@
"author": "Automattic",
"type": "module",
"scripts": {
"build": "pnpm run clean && pnpm run build:blocks && pnpm run build:contact-form && pnpm run build:dashboard && pnpm run module:build",
"build": "pnpm run clean && pnpm run build:blocks && pnpm run build:contact-form && pnpm run build:dashboard && pnpm run build:form-editor && pnpm run module:build",
"build-production": "NODE_ENV=production BABEL_ENV=production pnpm run build && pnpm run validate",
"build:blocks": "webpack --config ./tools/webpack.config.blocks.js",
"build:contact-form": "webpack --config ./tools/webpack.config.contact-form.js",
"build:dashboard": "webpack --config ./tools/webpack.config.dashboard.js",
"build:form-editor": "webpack --config ./tools/webpack.config.form-editor.js",
"clean": "rm -rf dist/ .cache/",
"module:build": "webpack --config ./tools/webpack.config.modules.js",
"module:watch": "webpack --watch --config ./tools/webpack.config.modules.js",
"test": "NODE_OPTIONS=--experimental-vm-modules jest --config=tests/jest.config.js",
"test-coverage": "pnpm run test --coverage",
"typecheck": "tsc --noEmit",
"validate": "pnpm exec validate-es --no-error-on-unmatched-pattern dist/",
"watch": "concurrently 'pnpm:build:blocks --watch' 'pnpm:build:contact-form --watch' 'pnpm:build:dashboard --watch' 'pnpm:module:watch'"
"watch": "concurrently 'pnpm:build:blocks --watch' 'pnpm:build:contact-form --watch' 'pnpm:build:dashboard --watch' 'pnpm:build:form-editor --watch' 'pnpm:module:watch'"
},
"browserslist": [
"extends @wordpress/browserslist-config"
Expand Down Expand Up @@ -99,6 +100,8 @@
"@wordpress/api-fetch": "7.36.0",
"@wordpress/browserslist-config": "6.36.0",
"@wordpress/date": "5.36.0",
"@wordpress/edit-post": "8.36.0",
"@wordpress/plugins": "7.36.0",
"autoprefixer": "10.4.20",
"concurrently": "9.2.1",
"glob": "11.1.0",
Expand Down
3 changes: 3 additions & 0 deletions projects/packages/forms/src/blocks/contact-form/attributes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@
import { __ } from '@wordpress/i18n';

export default {
ref: {
type: 'number' as const,
},
subject: {
type: 'string',
default: window.jpFormsBlocks?.defaults?.subject || '',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -728,9 +728,62 @@ public static function gutenblock_render_form( $atts, $content ) {

self::load_view_scripts();

// Handle ref attribute - load form from jetpack-form post
if ( isset( $atts['ref'] ) && is_numeric( $atts['ref'] ) ) {
return self::render_synced_form( $atts['ref'] );
}
Comment on lines +731 to +734
Copy link

Copilot AI Dec 12, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The new ref attribute handling in gutenblock_render_form lacks test coverage. Consider adding tests to verify that forms with a ref attribute are properly delegated to render_synced_form and that validation of the ref value works correctly.

Copilot uses AI. Check for mistakes.

return Contact_Form::parse( $atts, do_blocks( $content ) );
}

/**
* Render a synced form by reference ID.
*
* @param int $ref_id The jetpack_form post ID.
* @return string Rendered form HTML.
*/
private static function render_synced_form( $ref_id ) {
// Circular reference prevention.
static $seen_refs = array();

if ( isset( $seen_refs[ $ref_id ] ) ) {
return sprintf(
'<div class="wp-block-jetpack-contact-form">%s</div>',
esc_html__( 'Circular reference detected in form.', 'jetpack-forms' )
);
}

// Load the jetpack-form post.
$synced_form = get_post( $ref_id );
Comment on lines +732 to +757
Copy link

Copilot AI Dec 12, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The ref_id parameter is validated with is_numeric(), but this doesn't prevent negative numbers or ensure the value is a valid positive integer. Consider using absint() or additional validation to ensure only valid positive integers are processed as post IDs.

Copilot uses AI. Check for mistakes.

// Validate post.
if ( ! $synced_form || 'jetpack_form' !== $synced_form->post_type ) {
return '';
}

// Only render published and draft post statuses.
// todo: add a "active" status so that we can disable forms without deleting them.
Copy link

Copilot AI Dec 12, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This TODO comment should be tracked in an issue rather than left inline. Consider creating a GitHub issue to track the implementation of an 'active' status for forms and removing this comment.

Suggested change
// todo: add a "active" status so that we can disable forms without deleting them.

Copilot uses AI. Check for mistakes.
if ( ! in_array( $synced_form->post_status, array( 'publish', 'draft' ), true ) ) {
Comment on lines +764 to +766
Copy link

Copilot AI Dec 12, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The check allowing jetpack_form posts with post_status of draft to be rendered means draft forms can be displayed on public pages if a block references their ref ID. This bypasses the usual WordPress expectation that drafts are not publicly visible and could unintentionally expose in-progress or disabled forms and their configuration to unauthenticated visitors. Restrict rendering to publish status for front-end requests (and/or gate draft rendering behind appropriate capability checks or editor-only contexts) so that non-public form statuses cannot be surfaced to general users.

Suggested change
// Only render published and draft post statuses.
// todo: add a "active" status so that we can disable forms without deleting them.
if ( ! in_array( $synced_form->post_status, array( 'publish', 'draft' ), true ) ) {
// Only render published forms on the front end.
// Allow drafts only in admin/editor contexts or for users with edit capability.
if (
'publish' !== $synced_form->post_status &&
(
! is_admin() &&
! ( defined( 'REST_REQUEST' ) && REST_REQUEST ) &&
! ( defined( 'DOING_AJAX' ) && DOING_AJAX ) &&
! current_user_can( 'edit_post', $synced_form->ID )
)
) {

Copilot uses AI. Check for mistakes.
return '';
Comment on lines +761 to +767
Copy link

Copilot AI Dec 12, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

When a synced form post is not found or has an invalid post type, the function returns an empty string, giving no feedback to users. Consider returning a user-friendly error message (similar to the circular reference case) so users understand why the form isn't displaying. This would improve the debugging experience.

Suggested change
return '';
}
// Only render published and draft post statuses.
// todo: add a "active" status so that we can disable forms without deleting them.
if ( ! in_array( $synced_form->post_status, array( 'publish', 'draft' ), true ) ) {
return '';
return sprintf(
'<div class="wp-block-jetpack-contact-form">%s</div>',
esc_html__( 'Referenced form not found or invalid.', 'jetpack-forms' )
);
}
// Only render published and draft post statuses.
// todo: add a "active" status so that we can disable forms without deleting them.
if ( ! in_array( $synced_form->post_status, array( 'publish', 'draft' ), true ) ) {
return sprintf(
'<div class="wp-block-jetpack-contact-form">%s</div>',
esc_html__( 'Referenced form is not published or is inactive.', 'jetpack-forms' )
);

Copilot uses AI. Check for mistakes.
}

// Mark as seen for circular reference prevention.
$seen_refs[ $ref_id ] = true;

// Parse and render blocks from post_content.
$blocks = parse_blocks( $synced_form->post_content );
$output = '';

foreach ( $blocks as $block ) {
$output .= render_block( $block );
}

// Clean up.
unset( $seen_refs[ $ref_id ] );
Comment on lines +746 to +782
Copy link

Copilot AI Dec 12, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The static $seen_refs array for circular reference prevention will persist across multiple requests in persistent PHP environments (like PHP-FPM). If an error occurs between marking a ref as seen and unsetting it, subsequent requests could incorrectly detect circular references. Consider adding cleanup logic or using instance-level tracking instead of static variables.

Copilot uses AI. Check for mistakes.

return $output;
}
Comment on lines +745 to +785
Copy link

Copilot AI Dec 12, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The new render_synced_form method lacks test coverage. Consider adding tests for: 1) successful rendering of synced forms, 2) circular reference detection, 3) validation of post type, 4) handling of different post statuses (publish, draft, trash), and 5) handling of non-existent post IDs.

Copilot uses AI. Check for mistakes.

/**
* Load editor styles for the block.
* These are loaded via enqueue_block_assets to ensure proper loading in the editor iframe context.
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,141 @@
/**
* Convert Form Toolbar Component
* Provides toolbar buttons to convert forms to synced mode and edit synced forms
*/

import { store as blockEditorStore } from '@wordpress/block-editor';
import { ToolbarGroup, ToolbarButton } from '@wordpress/components';
import { useSelect, useDispatch } from '@wordpress/data';
import { store as editorStore } from '@wordpress/editor';
import { useState } from '@wordpress/element';
import { __ } from '@wordpress/i18n';
import { store as noticesStore } from '@wordpress/notices';
import { FORM_POST_TYPE } from '../../shared/util/constants.js';
import { createSyncedForm } from '../utils/form-sync-manager';

interface ConvertFormToolbarProps {
clientId: string;
attributes: Record< string, unknown >;
setAttributes: ( attrs: Record< string, unknown > ) => void;
Copy link

Copilot AI Dec 12, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The setAttributes parameter in the ConvertFormToolbarProps interface is defined but never used in the component. Consider removing it from both the interface and the component's parameter destructuring, or document why it's included if it's needed for future functionality.

Suggested change
setAttributes: ( attrs: Record< string, unknown > ) => void;

Copilot uses AI. Check for mistakes.
}

export function ConvertFormToolbar( { clientId, attributes }: ConvertFormToolbarProps ) {
const [ isConverting, setIsConverting ] = useState( false );

// Get the current page/post title and navigation function from settings
const { postTitle, onNavigateToEntityRecord } = useSelect( select => {
const editedPost = select( editorStore ).getEditedPostAttribute( 'title' );
const { getSettings } = select( blockEditorStore );
return {
postTitle: editedPost || 'Untitled',
onNavigateToEntityRecord: getSettings().onNavigateToEntityRecord,
};
}, [] );
Copy link

Copilot AI Dec 12, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The useSelect hook on line 25 has an empty dependency array, which means it only runs once on mount. If the post title changes during editing, the postTitle value won't update, potentially causing the synced form to be created with an outdated title. Add postTitle or relevant dependencies to the array to ensure the value stays current.

Suggested change
}, [] );
} );

Copilot uses AI. Check for mistakes.

// Get block data
const block = useSelect(
select => select( blockEditorStore ).getBlock( clientId ),
[ clientId ]
);

// Get functions to manipulate blocks
const { replaceInnerBlocks, updateBlockAttributes } = useDispatch( blockEditorStore );
const { createSuccessNotice, createErrorNotice } = useDispatch( noticesStore );

const hasRef = !! attributes.ref;

/**
* Convert inline form to synced form
*/
const convertToSynced = async () => {
if ( ! block || isConverting ) {
return;
}

setIsConverting( true );

try {
// Remove ref from attributes if it exists (shouldn't, but safety check)
const { ...cleanAttributes } = attributes;
Copy link

Copilot AI Dec 12, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The destructuring syntax here doesn't actually remove the 'ref' property from attributes. The spread operator ...cleanAttributes creates a shallow copy of all properties in attributes. To properly exclude the 'ref' property, you should use: const { ref, ...cleanAttributes } = attributes;

Suggested change
const { ...cleanAttributes } = attributes;
const { ref, ...cleanAttributes } = attributes;

Copilot uses AI. Check for mistakes.

// Create the synced form post with all attributes and innerBlocks
const postId = await createSyncedForm(
{
attributes: cleanAttributes,
innerBlocks: block.innerBlocks || [],
},
postTitle
);

// Clear innerBlocks first
replaceInnerBlocks( clientId, [], false );

// Get all current attribute keys
const attributeKeys = Object.keys( attributes );
const clearedAttributes: Record< string, unknown > = {};

// Set all attributes to undefined to clear them
attributeKeys.forEach( key => {
clearedAttributes[ key ] = undefined;
} );

// Then set only the ref
clearedAttributes.ref = postId;

// Update attributes using updateBlockAttributes which properly clears them
updateBlockAttributes( clientId, clearedAttributes );

createSuccessNotice( __( 'Form converted successfully', 'jetpack-forms' ), {
type: 'snackbar',
isDismissible: true,
} );
// eslint-disable-next-line @typescript-eslint/no-unused-vars
} catch ( error ) {
Copy link

Copilot AI Dec 12, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The error variable is caught but not logged or used for debugging. While the eslint-disable comment acknowledges this, consider logging the error to the console for debugging purposes, especially since this involves network operations and post creation that could fail in various ways.

Suggested change
} catch ( error ) {
} catch ( error ) {
console.error( 'Error converting form to synced form:', error );

Copilot uses AI. Check for mistakes.
createErrorNotice(
__( 'Failed to convert form to synced form. Please try again.', 'jetpack-forms' ),
{
type: 'snackbar',
isDismissible: true,
}
);
} finally {
setIsConverting( false );
}
};

/**
* Navigate to edit the synced form post
*/
const handleEditOriginal = () => {
if ( ! attributes.ref || ! onNavigateToEntityRecord ) {
return;
}

onNavigateToEntityRecord( {
postId: attributes.ref as number,
postType: FORM_POST_TYPE,
} );
};

const showEditButton = hasRef && onNavigateToEntityRecord;
const showConvertButton = ! hasRef;

return (
<ToolbarGroup>
{ showEditButton && (
<ToolbarButton onClick={ handleEditOriginal } label={ __( 'Edit form', 'jetpack-forms' ) }>
{ __( 'Edit Form', 'jetpack-forms' ) }
</ToolbarButton>
) }
{ showConvertButton && (
<ToolbarButton
onClick={ convertToSynced }
disabled={ isConverting }
label={ __( 'Convert to synced form', 'jetpack-forms' ) }
>
{ __( 'Convert Form', 'jetpack-forms' ) }
</ToolbarButton>
) }
</ToolbarGroup>
);
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Edit form. It's a bit odd to have an 'Edit Form' button on the form block, when I just edit it directly on the screen. I understand why the button is there, but it may not be obvious to users. I'm also not sure what the better solution is.

edit-form

Loading
Loading