Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
90.96% covered (success)
90.96%
674 / 741
54.17% covered (warning)
54.17%
13 / 24
CRAP
0.00% covered (danger)
0.00%
0 / 1
Contact_Form_Block
90.96% covered (success)
90.96%
674 / 741
54.17% covered (warning)
54.17%
13 / 24
85.85
0.00% covered (danger)
0.00%
0 / 1
 register_block
98.21% covered (success)
98.21%
55 / 56
0.00% covered (danger)
0.00%
0 / 1
2
 disable_field_visibility_support
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
7
 drop_field_hidden_everywhere
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
3
 register_feature
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
1
 register_central_form_management_default
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
 find_nested_html_block
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
5
 render_wrapped_html_block
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
 register_child_blocks
99.80% covered (success)
99.80%
490 / 491
0.00% covered (danger)
0.00%
0 / 1
2
 set_file_field_extension_available
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
6
 pre_render_contact_form
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
6
 count_form_steps_in_block
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
4
 get_form_step_count
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 render_fallback
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
1
 render_email
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 submit_button_element
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 gutenblock_render_form
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
1
 render_form
81.82% covered (warning)
81.82%
9 / 11
0.00% covered (danger)
0.00%
0 / 1
9.49
 apply_background_support
96.97% covered (success)
96.97%
32 / 33
0.00% covered (danger)
0.00%
0 / 1
12
 load_editor_styles
n/a
0 / 0
n/a
0 / 0
1
 load_editor_scripts
0.00% covered (danger)
0.00%
0 / 34
0.00% covered (danger)
0.00%
0 / 1
6
 maybe_load_ai_integration
0.00% covered (danger)
0.00%
0 / 20
0.00% covered (danger)
0.00%
0 / 1
30
 preload_endpoints
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
2
 load_view_scripts
92.31% covered (success)
92.31%
12 / 13
0.00% covered (danger)
0.00%
0 / 1
2.00
 maybe_register_blocks_editor_script
94.74% covered (success)
94.74%
18 / 19
0.00% covered (danger)
0.00%
0 / 1
4.00
 can_manage_block
80.00% covered (warning)
80.00%
4 / 5
0.00% covered (danger)
0.00%
0 / 1
4.13
1<?php
2/**
3 * Contact Form Block.
4 *
5 * @package automattic/jetpack
6 */
7
8namespace Automattic\Jetpack\Extensions\Contact_Form;
9
10use Automattic\Jetpack\Assets;
11use Automattic\Jetpack\Assets\Shared_Stores_Assets;
12use Automattic\Jetpack\Blocks;
13use Automattic\Jetpack\Current_Plan;
14use Automattic\Jetpack\Forms\ContactForm\Conditional_Logic_Container;
15use Automattic\Jetpack\Forms\ContactForm\Contact_Form;
16use Automattic\Jetpack\Forms\ContactForm\Contact_Form_Field;
17use Automattic\Jetpack\Forms\ContactForm\Contact_Form_Plugin;
18use Automattic\Jetpack\Forms\ContactForm\Form_Preview;
19use Automattic\Jetpack\Forms\Dashboard\Dashboard as Forms_Dashboard;
20use Automattic\Jetpack\Forms\Jetpack_Forms;
21use Automattic\Jetpack\Modules;
22use Automattic\Jetpack\Status\Request;
23use Jetpack;
24
25/**
26 * Contact Form block render callback.
27 */
28class Contact_Form_Block {
29    /**
30     * Class on the Form block's own element, the one carrying its style supports.
31     *
32     * @var string
33     */
34    const FORM_BLOCK_CLASS = 'wp-block-jetpack-contact-form';
35
36    /**
37     * Class on the Step block's own element, the one carrying its style supports.
38     *
39     * @var string
40     */
41    const STEP_BLOCK_CLASS = 'wp-block-jetpack-form-step';
42
43    /**
44     * Register the Contact Form block.
45     * We are core block dependent only on whether the jetpack contact form plugin
46     * is active or not. This is allowing us to make it more discoverable
47     * and enable the plugin in one click
48     */
49    public static function register_block() {
50        /*
51         * The block is available even when the module is not active,
52         * so we can display a nudge to activate the module instead of the block.
53         * However, since non-admins cannot activate modules, we do not display the empty block for them.
54         */
55        if ( ! self::can_manage_block() ) {
56            return;
57        }
58
59        Blocks::jetpack_register_block(
60            'jetpack/contact-form',
61            array(
62                'render_email_callback' => array( __CLASS__, 'render_email' ),
63                'render_callback'       => array( __CLASS__, 'gutenblock_render_form' ),
64                'supports'              => array(
65
66                    /*
67                     * Deliberately not mirrored in block.json: serialization is skipped here so
68                     * self::apply_background_support() can put the image on the block's own
69                     * element, and skipping it in JS too would drop the editor preview.
70                     */
71                    'background'           => array(
72                        'backgroundImage'                 => true,
73                        'backgroundSize'                  => true,
74                        '__experimentalSkipSerialization' => true,
75                        '__experimentalDefaultControls'   => array(
76                            'backgroundImage' => true,
77                        ),
78                    ),
79                    'layout'               => array(
80                        'default'                => array(
81                            'type'              => 'flex',
82                            'flexWrap'          => 'wrap',
83                            'orientation'       => 'horizontal',
84                            'justifyContent'    => 'left',
85                            'verticalAlignment' => 'top',
86                        ),
87                        'allowSwitching'         => false,
88                        'allowEditing'           => true,
89                        'allowOrientation'       => true,
90                        'allowVerticalAlignment' => true,
91                        'allowJustification'     => true,
92                        'allowWrap'              => false,
93                    ),
94                    '__experimentalBorder' => array(
95                        'color'                         => true,
96                        'radius'                        => true,
97                        'style'                         => true,
98                        'width'                         => true,
99                        '__experimentalDefaultControls' => array(
100                            'color'  => true,
101                            'radius' => true,
102                            'style'  => true,
103                            'width'  => true,
104                        ),
105                    ),
106                    'listView'             => true,
107                ),
108                'style_handles'         => array( 'jetpack-forms-layout' ),
109            )
110        );
111
112        // Container blocks carry conditional logic of their own; this stamps the ones that do
113        // as they render, before the form parses the field shortcodes around them.
114        Conditional_Logic_Container::init();
115
116        add_filter( 'render_block_data', array( __CLASS__, 'find_nested_html_block' ), 10, 3 );
117        add_filter( 'render_block_core/html', array( __CLASS__, 'render_wrapped_html_block' ), 10, 2 );
118        add_filter( 'jetpack_block_editor_feature_flags', array( __CLASS__, 'register_feature' ) );
119        add_filter( 'pre_render_block', array( __CLASS__, 'pre_render_contact_form' ), 10, 3 );
120
121        add_filter( 'block_editor_rest_api_preload_paths', array( __CLASS__, 'preload_endpoints' ) );
122
123        // Load scripts for the editing interface
124        add_action( 'enqueue_block_editor_assets', array( __CLASS__, 'load_editor_scripts' ), 9 );
125
126        // Load AI integration after Jetpack_Gutenberg registers extensions (priority 10)
127        add_action( 'enqueue_block_editor_assets', array( __CLASS__, 'maybe_load_ai_integration' ), 11 );
128    }
129
130    /**
131     * Disable the block "visibility" support on form field and input blocks.
132     *
133     * FORMS-694 (interim). The per-viewport "Hide on…" option is not honored in
134     * the forms render pipeline â€” fields flatten to a shortcode and bypass core's
135     * render_block class injection â€” and on a required field it cannot be made
136     * safe (server- and client-side validation are both viewport-blind). "Hide
137     * everywhere" does work for fields, but the control bundles both modes under
138     * one boolean, so we disable it wholesale on fields, inputs, and choice/option
139     * blocks as an interim. This mirrors the JS registration. The label is the
140     * only block that keeps visibility support â€” it honors hiding (full-hide via
141     * labelhiddenbyblockvisibility, per-viewport via wp-block-hidden-* classes)
142     * and never affects validation or submission. Full field visibility is a
143     * separate decision.
144     *
145     * @param array  $args       Block type registration args.
146     * @param string $block_name Block name being registered.
147     * @return array
148     */
149    public static function disable_field_visibility_support( $args, $block_name ) {
150        // TODO: refactor into an array_merge'd shared supports array mirroring the JS defaultSettings, instead of this filter.
151        // Fields, incl. the deprecated field-option-* choice blocks.
152        $is_field = strpos( $block_name, 'jetpack/field-' ) === 0;
153        // All input variants: jetpack/input, input-range, input-rating,
154        // input-image-option, plus the differently-named phone-input and dropzone.
155        $is_input = strpos( $block_name, 'jetpack/input' ) === 0 || in_array( $block_name, array( 'jetpack/phone-input', 'jetpack/dropzone' ), true );
156        // Choice/option containers.
157        $is_option = in_array( $block_name, array( 'jetpack/option', 'jetpack/options', 'jetpack/fieldset-image-options' ), true );
158
159        if ( $is_input || $is_field || $is_option ) {
160            if ( ! isset( $args['supports'] ) || ! is_array( $args['supports'] ) ) {
161                $args['supports'] = array();
162            }
163            $args['supports']['visibility'] = false;
164        }
165
166        return $args;
167    }
168
169    /**
170     * Drop a field that has been hidden everywhere via block visibility.
171     *
172     * FORMS-694. "Hide everywhere" (metadata.blockVisibility === false) must keep
173     * working on fields even though we disable the visibility *support* on them
174     * (see disable_field_visibility_support). We can't rely on core's render_block
175     * visibility filter for this: on released WP it gates the full-hide branch
176     * behind the support check, so once support is false the field would reappear
177     * (the fix that reorders those â€” WordPress/gutenberg#78780 â€” is unreleased).
178     *
179     * Dropping the field's rendered output ('') before Contact_Form::parse() sees
180     * it removes the [contact-field] shortcode entirely, so the field is never
181     * parsed, rendered, or validated â€” which is what makes this required-safe (a
182     * required hidden-everywhere field simply isn't in the form). This is a full
183     * removal, not a CSS hide; the per-viewport "Hide on…" mode (which leaves the
184     * field in place and only display:none's it) is intentionally not honored on
185     * fields for exactly that reason.
186     *
187     * @param string $block_content Rendered block content.
188     * @param array  $block         Parsed block.
189     * @return string
190     */
191    public static function drop_field_hidden_everywhere( $block_content, $block ) {
192        $block_name       = $block['blockName'] ?? '';
193        $block_visibility = $block['attrs']['metadata']['blockVisibility'] ?? null;
194
195        if ( false === $block_visibility && strpos( $block_name, 'jetpack/field-' ) === 0 ) {
196            return '';
197        }
198
199        return $block_content;
200    }
201
202    /**
203     * Register the contact form block feature flag.
204     *
205     * @param array $features - the features array.
206     *
207     * @return array
208     */
209    public static function register_feature( $features ) {
210        // Features that are only available to users with a paid plan.
211        $features['multistep-form'] = Current_Plan::supports( 'multistep-form' );
212        $features['form-webhooks']  = Current_Plan::supports( 'form-webhooks' );
213
214        // Bridges the jetpack-feature-flags registration to the editor, so JS `hasFeatureFlag()`
215        // and PHP `Feature_Flags::is_enabled()` answer from one source under one name.
216        $features[ Jetpack_Forms::CONDITIONAL_LOGIC_FLAG ] = Jetpack_Forms::is_conditional_logic_enabled();
217
218        return self::register_central_form_management_default( $features );
219    }
220
221    /**
222     * Lightweight bootstrap default for the `central-form-management` feature flag.
223     *
224     * Registered from Util::init() so that early callers of
225     * Contact_Form_Plugin::has_editor_feature_flag() â€” such as the Forms dashboard
226     * default-tab redirect, which runs before the WP `init` hook fires â€” see the
227     * correct flag value. Kept separate from register_feature() so the early-boot
228     * code path avoids the Current_Plan::supports() calls used by the paid-plan flags.
229     *
230     * @param array $features - the features array.
231     *
232     * @return array
233     */
234    public static function register_central_form_management_default( $features ) {
235        if ( ! isset( $features['central-form-management'] ) ) {
236            $features['central-form-management'] = true;
237        }
238
239        return $features;
240    }
241
242    /**
243     *  Find nested html block that reside in the contact form block.
244     *  We are using this to wrap the html block with div if it is nested inside contact form block. So that the elements render as expected.
245     *
246     *  @param array  $parsed_block - the parsed block.
247     *  @param array  $source_block - the source block.
248     *  @param object $parent_block - the parent WP_Block.
249     *
250     *  @return array
251     */
252    public static function find_nested_html_block( $parsed_block, $source_block, $parent_block ) {
253        if ( ! empty( $parsed_block['blockName'] ) && $parsed_block['blockName'] === 'core/html' && isset( $parent_block->parsed_block ) && $parent_block->parsed_block['blockName'] === 'jetpack/contact-form' ) {
254            $parsed_block['hasJPFormParent'] = true;
255        }
256        return $parsed_block;
257    }
258
259    /**
260     * Render wrapped html block that is inside the form block with a wrapped div so that the elements render as expected.
261     * The extra div is needed because the form block has a `flex: 0 0 100%;` applied to all the children of the form block.
262     * This cases all the elementes inside the block to render in a single line and make it not possible to add have inline elements.
263     *
264     * @param string $content - the content of the block.
265     * @param array  $parsed_block - the parsed block.
266     *
267     * @return string
268     */
269    public static function render_wrapped_html_block( $content, $parsed_block ) {
270        if ( ! empty( $parsed_block['hasJPFormParent'] ) ) {
271            return '<div>' . $content . '</div>';
272        }
273
274        return $content;
275    }
276
277    /**
278     * Register the Child blocks of Contact Form
279     * We are registering child blocks only when Contact Form plugin is Active
280     */
281    public static function register_child_blocks() {
282        // Bail early if the user cannot manage the block.
283        if ( ! self::can_manage_block() ) {
284            return;
285        }
286
287        // Keep the PHP-registered "visibility" support in sync with the JS
288        // registration (src/blocks/shared/settings/index.js and
289        // src/blocks/input/index.js), which disables it on fields and inputs.
290        add_filter( 'register_block_type_args', array( __CLASS__, 'disable_field_visibility_support' ), 10, 2 );
291
292        // Honor "hide everywhere" on fields ourselves, independent of core's
293        // version-dependent visibility filter. See drop_field_hidden_everywhere().
294        add_filter( 'render_block', array( __CLASS__, 'drop_field_hidden_everywhere' ), 10, 2 );
295
296        // Field inner block types.
297        Blocks::jetpack_register_block(
298            'jetpack/input',
299            array(
300                'supports'     => array(
301                    '__experimentalBorder' => array(
302                        'color'  => true,
303                        'radius' => true,
304                        'style'  => true,
305                        'width'  => true,
306                    ),
307                    'color'                => array(
308                        'text'       => true,
309                        'background' => true,
310                        'gradients'  => false,
311                    ),
312                    'typography'           => array(
313                        'fontSize'                     => true,
314                        'lineHeight'                   => true,
315                        '__experimentalFontFamily'     => true,
316                        '__experimentalFontWeight'     => true,
317                        '__experimentalFontStyle'      => true,
318                        '__experimentalTextTransform'  => true,
319                        '__experimentalTextDecoration' => true,
320                        '__experimentalLetterSpacing'  => true,
321                    ),
322                ),
323                'selectors'    => array(
324                    'border' => '.wp-block-jetpack-input, .is-style-outlined .notched-label:has(+ .wp-block-jetpack-input) > *,.is-style-outlined .wp-block-jetpack-input + .notched-label > *, .is-style-outlined .wp-block-jetpack-field-select .notched-label > *',
325                    'color'  => '.wp-block-jetpack-input, .is-style-outlined .notched-label:has(+ .wp-block-jetpack-input) > *,.is-style-outlined .wp-block-jetpack-input + .notched-label > *, .is-style-outlined .wp-block-jetpack-field-select .notched-label > *',
326                ),
327                'uses_context' => array( 'jetpack/field-default-value' ),
328            )
329        );
330        Blocks::jetpack_register_block(
331            'jetpack/label',
332            array(
333                'supports'     => array(
334                    'color'      => array(
335                        'text'       => true,
336                        'background' => false,
337                        'gradients'  => false,
338                    ),
339                    'typography' => array(
340                        'fontSize'                     => true,
341                        'lineHeight'                   => true,
342                        '__experimentalFontFamily'     => true,
343                        '__experimentalFontWeight'     => true,
344                        '__experimentalFontStyle'      => true,
345                        '__experimentalTextTransform'  => true,
346                        '__experimentalTextDecoration' => true,
347                        '__experimentalLetterSpacing'  => true,
348                    ),
349                    // The real support key is `visibility`, not `blockVisibility`
350                    // (that's the per-instance saved attribute). The label is the
351                    // only forms block that keeps the control â€” see FORMS-694.
352                    'visibility' => true,
353                ),
354                'uses_context' => array(
355                    'jetpack/field-required',
356                ),
357            )
358        );
359        Blocks::jetpack_register_block(
360            'jetpack/options',
361            array(
362                'supports'         => array(
363                    '__experimentalBorder' => array(
364                        'color'  => true,
365                        'radius' => true,
366                        'style'  => true,
367                        'width'  => true,
368                    ),
369                    'color'                => array(
370                        'text'       => false,
371                        'background' => true,
372                    ),
373                    'spacing'              => array(
374                        'blockGap' => false,
375                    ),
376                ),
377                'provides_context' => array(
378                    'jetpack/field-options-type' => 'type',
379                ),
380                'selectors'        => array(
381                    'border' => '.wp-block-jetpack-options, .is-style-outlined .notched-label:has(+ .wp-block-jetpack-options) > *',
382                    'color'  => '.wp-block-jetpack-options, .is-style-outlined .notched-label:has(+ .wp-block-jetpack-options) > *',
383                ),
384            )
385        );
386        Blocks::jetpack_register_block(
387            'jetpack/option',
388            array(
389                'supports'     => array(
390                    'color'      => array(
391                        'text'       => true,
392                        'background' => false,
393                        'gradients'  => false,
394                    ),
395                    'typography' => array(
396                        'fontSize'                     => true,
397                        'lineHeight'                   => true,
398                        '__experimentalFontFamily'     => true,
399                        '__experimentalFontWeight'     => true,
400                        '__experimentalFontStyle'      => true,
401                        '__experimentalTextTransform'  => true,
402                        '__experimentalTextDecoration' => true,
403                        '__experimentalLetterSpacing'  => true,
404                    ),
405                ),
406                'uses_context' => array(
407                    'jetpack/field-default-value',
408                    'jetpack/field-options-type',
409                    'jetpack/field-required',
410                ),
411            )
412        );
413
414        Blocks::jetpack_register_block(
415            'jetpack/phone-input',
416            array(
417                'supports'     => array(
418                    '__experimentalBorder' => array(
419                        'color'  => true,
420                        'radius' => true,
421                        'style'  => true,
422                        'width'  => true,
423                    ),
424                    'color'                => array(
425                        'text'       => true,
426                        'background' => true,
427                        'gradients'  => false,
428                    ),
429                    'typography'           => array(
430                        'fontSize'                     => true,
431                        'lineHeight'                   => true,
432                        '__experimentalFontFamily'     => true,
433                        '__experimentalFontWeight'     => true,
434                        '__experimentalFontStyle'      => true,
435                        '__experimentalTextTransform'  => true,
436                        '__experimentalTextDecoration' => true,
437                        '__experimentalLetterSpacing'  => true,
438                    ),
439                ),
440                'uses_context' => array(
441                    'jetpack/field-share-attributes',
442                    'jetpack/field-prefix-options',
443                    'jetpack/field-prefix-default',
444                    'jetpack/field-prefix-onChange',
445                    'jetpack/field-phone-country-toggle',
446                ),
447            )
448        );
449
450        Blocks::jetpack_register_block(
451            'jetpack/input-rating',
452            array(
453                'supports' => array(
454                    'color'      => array(
455                        'text'       => true,
456                        'background' => false,
457                    ),
458                    'typography' => array(
459                        'fontSize' => true,
460                    ),
461                ),
462            )
463        );
464
465        Blocks::jetpack_register_block(
466            'jetpack/input-range',
467            array(
468                'supports' => array(
469                    'color'      => array(
470                        'text'       => true,
471                        'background' => false,
472                    ),
473                    'typography' => array(
474                        'fontSize'                     => true,
475                        '__experimentalFontFamily'     => true,
476                        '__experimentalFontWeight'     => true,
477                        '__experimentalFontStyle'      => true,
478                        '__experimentalTextTransform'  => true,
479                        '__experimentalTextDecoration' => true,
480                        '__experimentalLetterSpacing'  => true,
481                    ),
482                ),
483            )
484        );
485
486        // Field render methods.
487        Blocks::jetpack_register_block(
488            'jetpack/field-text',
489            array(
490                'render_callback'  => array( Contact_Form_Plugin::class, 'gutenblock_render_field_text' ),
491                'provides_context' => array( 'jetpack/field-required' => 'required' ),
492            )
493        );
494        Blocks::jetpack_register_block(
495            'jetpack/field-name',
496            array(
497                'render_callback'  => array( Contact_Form_Plugin::class, 'gutenblock_render_field_name' ),
498                'provides_context' => array( 'jetpack/field-required' => 'required' ),
499            )
500        );
501        Blocks::jetpack_register_block(
502            'jetpack/field-email',
503            array(
504                'render_callback'  => array( Contact_Form_Plugin::class, 'gutenblock_render_field_email' ),
505                'provides_context' => array( 'jetpack/field-required' => 'required' ),
506            )
507        );
508        Blocks::jetpack_register_block(
509            'jetpack/field-url',
510            array(
511                'render_callback'  => array( Contact_Form_Plugin::class, 'gutenblock_render_field_url' ),
512                'provides_context' => array( 'jetpack/field-required' => 'required' ),
513            )
514        );
515        Blocks::jetpack_register_block(
516            'jetpack/field-date',
517            array(
518                'render_callback'  => array( Contact_Form_Plugin::class, 'gutenblock_render_field_date' ),
519                'provides_context' => array( 'jetpack/field-required' => 'required' ),
520            )
521        );
522        Blocks::jetpack_register_block(
523            'jetpack/field-telephone',
524            array(
525                'render_callback'  => array( Contact_Form_Plugin::class, 'gutenblock_render_field_telephone' ),
526                'attributes'       => array(
527                    'showCountrySelector' => array(
528                        'type' => 'boolean',
529                    ),
530                    'default'             => array(
531                        'type' => 'string',
532                        'role' => 'content',
533                    ),
534                    'searchPlaceholder'   => array(
535                        'type' => 'string',
536                        'role' => 'content',
537                    ),
538                ),
539                'supports'         => array(
540                    'interactivity' => true,
541                ),
542                'provides_context' => array(
543                    'jetpack/field-share-attributes'     => 'shareAttributes',
544                    'jetpack/field-required'             => 'required',
545                    'jetpack/field-prefix-default'       => 'default',
546                    'jetpack/field-phone-country-toggle' => 'showCountrySelector',
547                    'jetpack/field-phone-search-placeholder' => 'searchPlaceholder',
548                ),
549            )
550        );
551        Blocks::jetpack_register_block(
552            'jetpack/field-textarea',
553            array(
554                'render_callback'  => array( Contact_Form_Plugin::class, 'gutenblock_render_field_textarea' ),
555                'provides_context' => array( 'jetpack/field-required' => 'required' ),
556            )
557        );
558        Blocks::jetpack_register_block(
559            'jetpack/field-checkbox',
560            array(
561                'render_callback'  => array( Contact_Form_Plugin::class, 'gutenblock_render_field_checkbox' ),
562                'provides_context' => array(
563                    'jetpack/field-required'      => 'required',
564                    'jetpack/field-default-value' => 'defaultValue',
565                ),
566            )
567        );
568        Blocks::jetpack_register_block(
569            'jetpack/field-checkbox-multiple',
570            array(
571                'render_callback' => array( Contact_Form_Plugin::class, 'gutenblock_render_field_checkbox_multiple' ),
572            )
573        );
574
575        Blocks::jetpack_register_block(
576            'jetpack/field-option-checkbox',
577            array(
578                'render_callback' => array( Contact_Form_Plugin::class, 'gutenblock_render_field_option' ),
579            )
580        );
581
582        Blocks::jetpack_register_block(
583            'jetpack/field-radio',
584            array(
585                'render_callback' => array( Contact_Form_Plugin::class, 'gutenblock_render_field_radio' ),
586            )
587        );
588
589        Blocks::jetpack_register_block(
590            'jetpack/field-option-radio',
591            array(
592                'render_callback' => array( Contact_Form_Plugin::class, 'gutenblock_render_field_option' ),
593            )
594        );
595        Blocks::jetpack_register_block(
596            'jetpack/field-select',
597            array(
598                'render_callback'  => array( Contact_Form_Plugin::class, 'gutenblock_render_field_select' ),
599                'provides_context' => array( 'jetpack/field-required' => 'required' ),
600            )
601        );
602        Blocks::jetpack_register_block(
603            'jetpack/field-consent',
604            array(
605                'render_callback' => array( Contact_Form_Plugin::class, 'gutenblock_render_field_consent' ),
606            )
607        );
608
609        Blocks::jetpack_register_block(
610            'jetpack/field-number',
611            array(
612                'render_callback'  => array( Contact_Form_Plugin::class, 'gutenblock_render_field_number' ),
613                'provides_context' => array( 'jetpack/field-required' => 'required' ),
614            )
615        );
616
617        Blocks::jetpack_register_block(
618            'jetpack/field-file',
619            array(
620                'render_callback'  => array( Contact_Form_Plugin::class, 'gutenblock_render_field_file' ),
621                'provides_context' => array( 'jetpack/field-required' => 'required' ),
622                'plan_check'       => apply_filters( 'jetpack_unauth_file_upload_plan_check', true ),
623            )
624        );
625
626        Blocks::jetpack_register_block(
627            'jetpack/dropzone',
628            array(
629                'render_callback' => array( Contact_Form_Plugin::class, 'gutenblock_render_dropzone' ),
630            )
631        );
632
633        Blocks::jetpack_register_block(
634            'jetpack/field-hidden',
635            array(
636                'render_callback' => array( Contact_Form_Plugin::class, 'gutenblock_render_field_hidden' ),
637            )
638        );
639
640        Blocks::jetpack_register_block(
641            'jetpack/field-rating',
642            array(
643                'render_callback'  => array( Contact_Form_Plugin::class, 'gutenblock_render_field_rating' ),
644                'provides_context' => array(
645                    'jetpack/field-required' => 'required',
646                ),
647            )
648        );
649
650        Blocks::jetpack_register_block(
651            'jetpack/field-slider',
652            array(
653                'render_callback'  => array( Contact_Form_Plugin::class, 'gutenblock_render_field_slider' ),
654                'provides_context' => array( 'jetpack/field-required' => 'required' ),
655            )
656        );
657
658        Blocks::jetpack_register_block(
659            'jetpack/field-time',
660            array(
661                'render_callback'  => array( Contact_Form_Plugin::class, 'gutenblock_render_field_time' ),
662                'provides_context' => array( 'jetpack/field-required' => 'required' ),
663            )
664        );
665
666        // Paid file field block
667        add_action(
668            'jetpack_register_gutenberg_extensions',
669            array( __CLASS__, 'set_file_field_extension_available' )
670        );
671
672        /**
673         * The blocks 'jetpack/field-checkbox-multiple' and 'jetpack/field-radio' are wrapper blocks.
674         * Styles must be registered so that they are available to be overridden by the theme or global styles.
675         * Form field blocks define the block style via the settings in their index.js files.
676         * A follow up issue is to update them to use block.json files, which can be reused
677         * in both JS and PHP block registration.
678         */
679        register_block_style(
680            array( 'jetpack/field-checkbox-multiple', 'jetpack/field-radio' ),
681            array(
682                'name'       => 'list',
683                'label'      => __( 'List', 'jetpack-forms' ),
684                'is_default' => true,
685            )
686        );
687
688        register_block_style(
689            array( 'jetpack/field-checkbox-multiple', 'jetpack/field-radio' ),
690            array(
691                'name'  => 'button',
692                'label' => __( 'Button', 'jetpack-forms' ),
693            )
694        );
695
696        Blocks::jetpack_register_block(
697            'jetpack/form-step',
698            array(
699                'render_callback' => array( Contact_Form_Plugin::class, 'gutenblock_render_form_step' ),
700
701                /*
702                 * Deliberately not mirrored in the block's index.js: serialization is skipped
703                 * here so Contact_Form_Block::apply_background_support() can put the image on
704                 * the block's own element, and skipping it in JS too would drop the editor
705                 * preview.
706                 */
707                'supports'        => array(
708                    'background' => array(
709                        'backgroundImage'                 => true,
710                        'backgroundSize'                  => true,
711                        '__experimentalSkipSerialization' => true,
712                        '__experimentalDefaultControls'   => array(
713                            'backgroundImage' => true,
714                        ),
715                    ),
716                ),
717            )
718        );
719
720        Blocks::jetpack_register_block(
721            'jetpack/form-step-navigation',
722            array(
723                'render_callback' => array( Contact_Form_Plugin::class, 'gutenblock_render_form_step_navigation' ),
724            )
725        );
726
727        Blocks::jetpack_register_block(
728            'jetpack/form-progress-indicator',
729            array(
730                'render_callback' => array( Contact_Form_Plugin::class, 'gutenblock_render_form_progress_indicator' ),
731            )
732        );
733
734        Blocks::jetpack_register_block(
735            'jetpack/form-step-container'
736        );
737
738        Blocks::jetpack_register_block(
739            'jetpack/field-image-select',
740            array(
741                'render_callback'  => array( Contact_Form_Plugin::class, 'gutenblock_render_field_image_select' ),
742                'provides_context' => array(
743                    'jetpack/field-required' => 'required',
744                    'jetpack/field-image-select-show-labels' => 'showLabels',
745                    'jetpack/field-image-select-is-supersized' => 'isSupersized',
746                    'jetpack/field-image-select-is-multiple' => 'isMultiple',
747                    'jetpack/field-image-select-randomize-options' => 'randomizeOptions',
748                    'jetpack/field-image-select-show-other-option' => 'showOtherOption',
749                ),
750            )
751        );
752
753        Blocks::jetpack_register_block(
754            'jetpack/fieldset-image-options',
755            array(
756                'uses_context'     => array(
757                    'jetpack/field-image-select-is-supersized',
758                    'jetpack/field-image-select-is-multiple',
759                    'jetpack/field-share-attributes',
760                ),
761                'provides_context' => array(
762                    'jetpack/field-image-options-type' => 'type',
763                ),
764            )
765        );
766
767        Blocks::jetpack_register_block(
768            'jetpack/input-image-option',
769            array(
770                'supports'         => array(
771                    'color'                => array(
772                        'background'                    => true,
773                        'text'                          => true,
774                        'gradients'                     => false,
775                        '__experimentalDefaultControls' => array(
776                            'background' => true,
777                            'text'       => true,
778                        ),
779                    ),
780                    'typography'           => array(
781                        'fontSize'                      => true,
782                        'lineHeight'                    => true,
783                        '__experimentalFontFamily'      => true,
784                        '__experimentalFontWeight'      => true,
785                        '__experimentalFontStyle'       => true,
786                        '__experimentalTextTransform'   => true,
787                        '__experimentalTextDecoration'  => true,
788                        '__experimentalLetterSpacing'   => true,
789                        '__experimentalDefaultControls' => array(
790                            'fontSize' => true,
791                        ),
792                    ),
793                    '__experimentalBorder' => array(
794                        'color'                         => true,
795                        'radius'                        => true,
796                        'style'                         => true,
797                        'width'                         => true,
798                        '__experimentalDefaultControls' => array(
799                            'color'  => true,
800                            'radius' => true,
801                            'style'  => true,
802                            'width'  => true,
803                        ),
804                    ),
805                    'spacing'              => array(
806                        'margin'                        => true,
807                        'padding'                       => true,
808                        '__experimentalDefaultControls' => array(
809                            'margin'  => true,
810                            'padding' => true,
811                        ),
812                    ),
813                ),
814                'uses_context'     => array(
815                    'jetpack/field-image-select-is-supersized',
816                    'jetpack/field-image-select-show-labels',
817                    'jetpack/field-image-options-type',
818                    'jetpack/field-share-attributes',
819                ),
820                'provides_context' => array(
821                    'allowResize' => 'allowResize',
822                    'imageCrop'   => 'imageCrop',
823                    'fixedHeight' => 'fixedHeight',
824                ),
825            )
826        );
827    }
828
829    /**
830     * Set field-file extension available hook handler
831     */
832    public static function set_file_field_extension_available() {
833        if ( ! apply_filters( 'jetpack_unauth_file_upload_plan_check', true ) ) {
834            \Jetpack_Gutenberg::set_extension_available( 'field-file' );
835        }
836    }
837
838    /**
839     * Render the gutenblock form.
840     *
841     * @param array  $atts - the block attributes.
842     * @param string $content - html content.
843     *
844     * @return string
845     */
846    /**
847     * Static storage for form step count.
848     *
849     * @var int
850     */
851    private static $form_step_count = 1;
852
853    /**
854     * Hook into pre_render_block to count form steps before inner blocks render.
855     *
856     * @param string|null $pre_render   The pre-rendered content. Default null.
857     * @param array       $parsed_block The block being rendered.
858     * @return string|null
859     */
860    public static function pre_render_contact_form( $pre_render, $parsed_block ) {
861        // Only process contact form blocks
862        if ( ! isset( $parsed_block['blockName'] ) || $parsed_block['blockName'] !== 'jetpack/contact-form' ) {
863            return $pre_render;
864        }
865
866        // Count and store form steps
867        self::$form_step_count = self::count_form_steps_in_block( $parsed_block );
868
869        if ( isset( $parsed_block['attrs']['ref'] ) || null === $pre_render ) {
870            // This happends only important for lagacy reasons and when code is programatically generated.
871            // Since it can include the previous jetpack button.
872            // Which by default renders as a link instead of a button resulting in the form not submitting.
873            add_filter( 'jetpack_button_default_element', array( __CLASS__, 'submit_button_element' ) );
874        }
875
876        // For ref (synced) forms, render here via pre_render_block to short-circuit
877        // render_block(). This prevents wp_render_layout_support_flag from adding
878        // layout classes to the outer ref block's container div. The synced form's
879        // inner jetpack/contact-form block renders through the normal pipeline and
880        // gets layout classes on the correct element (wp-block-jetpack-contact-form).
881        if ( isset( $parsed_block['attrs']['ref'] ) ) {
882            return self::gutenblock_render_form( $parsed_block['attrs'], '' );
883        }
884
885        return $pre_render; // Don't actually pre-render, let normal rendering continue
886    }
887
888    /**
889     * Count form step blocks in a contact form block.
890     *
891     * @param array $block The contact form block.
892     * @return int Number of form steps found.
893     */
894    private static function count_form_steps_in_block( $block ) {
895        $step_count = 0;
896
897        if ( isset( $block['innerBlocks'] ) ) {
898            foreach ( $block['innerBlocks'] as $inner_block ) {
899                if ( $inner_block['blockName'] === 'jetpack/form-step' ) {
900                    ++$step_count;
901                }
902                // Also check nested blocks (like step containers)
903                $step_count += self::count_form_steps_in_block( $inner_block );
904            }
905        }
906
907        return $step_count;
908    }
909
910    /**
911     * Get the step count for forms (used by progress indicator).
912     *
913     * @return int The step count.
914     */
915    public static function get_form_step_count() {
916        return self::$form_step_count;
917    }
918
919    /**
920     * Render fallback for non-interactive contexts (email, feed, API, etc.).
921     *
922     * @param array $atts - the block attributes.
923     *
924     * @return string
925     */
926    private static function render_fallback( $atts ) {
927        return sprintf(
928            '<div class="%1$s"><a href="%2$s" target="_blank" rel="noopener noreferrer">%3$s</a></div>',
929            esc_attr( Blocks::classes( 'contact-form', $atts ) ),
930            esc_url( get_the_permalink() ),
931            esc_html__( 'Submit a form.', 'jetpack-forms' )
932        );
933    }
934
935    /**
936     * Render the contact form block for email contexts.
937     *
938     * This method is called by WordPress/WooCommerce email rendering system when a form block
939     * appears in email content. Forms are not interactive in email contexts, so we always return
940     * a fallback link that directs recipients to the form on the website.
941     *
942     * Note: The $block_content and $rendering_context parameters are required by the
943     * render_email_callback signature but are intentionally unused here. We only need the
944     * block attributes from $parsed_block to generate the fallback HTML, and we don't need
945     * to process the block content or use email-specific rendering context since we're
946     * always returning a simple fallback.
947     *
948     * @param string $block_content     The original block HTML content. Unused - we always return a fallback.
949     * @param array  $parsed_block      The parsed block data including attributes.
950     * @param object $rendering_context Email rendering context. Unused - not needed for fallback rendering.
951     *
952     * @return string HTML fallback with link to submit the form on the website.
953     */
954    public static function render_email( $block_content, array $parsed_block, $rendering_context ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
955        $atts = $parsed_block['attrs'] ?? array();
956
957        return self::render_fallback( $atts );
958    }
959
960    /**
961     * The element a Button block inside a form falls back to when it doesn't set one.
962     *
963     * Filters `jetpack_button_default_element` for the duration of a form's render.
964     *
965     * @return string
966     */
967    public static function submit_button_element() {
968        return 'button';
969    }
970
971    /**
972     * Render the gutenblock form.
973     *
974     * @param array  $atts - the block attributes.
975     * @param string $content - html content.
976     *
977     * @return string
978     */
979    public static function gutenblock_render_form( $atts, $content ) {
980        $form = self::render_form( $atts, $content );
981
982        // The form and its buttons are rendered by now, so stop defaulting Button blocks
983        // to `button` â€” any further button on the page is not a submit button.
984        remove_filter( 'jetpack_button_default_element', array( __CLASS__, 'submit_button_element' ) );
985
986        return $form;
987    }
988
989    /**
990     * Render the gutenblock form markup.
991     *
992     * @param array  $atts - the block attributes.
993     * @param string $content - html content.
994     *
995     * @return string
996     */
997    private static function render_form( $atts, $content ) {
998        // We should not render block if the module is disabled on a site using the Jetpack plugin.
999        // Exception: allow rendering in preview mode so form previews work.
1000        if ( class_exists( 'Jetpack' ) && ! ( new Modules() )->is_active( 'contact-form' ) && ! Form_Preview::is_preview_mode() ) {
1001            return '';
1002        }
1003        // Render fallback in other contexts than frontend (i.e. feed, emails, API, etc.), unless the form is being submitted.
1004        // Exception: allow rendering in preview mode.
1005        if ( ! Request::is_frontend() && ! isset( $_POST['contact-form-id'] ) && ! Form_Preview::is_preview_mode() ) { // phpcs:ignore WordPress.Security.NonceVerification.Missing
1006            return self::render_fallback( $atts );
1007        }
1008
1009        self::load_view_scripts();
1010
1011        // Handle ref attribute - load form from jetpack_form post
1012        if ( isset( $atts['ref'] ) ) {
1013            $ref_id = absint( $atts['ref'] );
1014            if ( $ref_id > 0 ) {
1015                return self::apply_background_support( Contact_Form::render_synced_form( $ref_id ), $atts, self::FORM_BLOCK_CLASS );
1016            } else {
1017                return ''; // Invalid ref ID.
1018            }
1019        }
1020
1021        return self::apply_background_support( Contact_Form::parse( $atts, do_blocks( $content ) ), $atts, self::FORM_BLOCK_CLASS );
1022    }
1023
1024    /**
1025     * Apply a block's background image styles to the block's own element.
1026     *
1027     * Core's `wp_render_background_support()` targets the first tag of the rendered output.
1028     * Both form blocks wrap themselves at render time â€” the interactivity wrapper for a step,
1029     * the container div and any admin-only notices for a form â€” so the first tag is not the
1030     * element carrying the block's color, padding and radius, and for a synced form it varies
1031     * with who is viewing. Serialization is skipped in the block registration (PHP only: adding
1032     * it to block.json or index.js would kill the editor preview) and the styles are applied
1033     * here, on the element matching $target_class.
1034     *
1035     * Mirrors core's `wp_render_background_support()`, including its `cover` and `50% 50%`
1036     * defaults. Core 7.1 added gradient handling this does not implement, so `gradient` must
1037     * stay out of the JS supports until it is mirrored here too.
1038     *
1039     * @param string $html         Rendered HTML containing the block's own element.
1040     * @param array  $atts         Block attributes.
1041     * @param string $target_class Class of the element that should carry the background.
1042     *
1043     * @return string The HTML, with background styles applied when the block has an image.
1044     */
1045    public static function apply_background_support( $html, $atts, $target_class ) {
1046        $background = $atts['style']['background'] ?? null;
1047
1048        if ( ! is_array( $background ) || empty( $background['backgroundImage'] ) ) {
1049            return $html;
1050        }
1051
1052        $background_styles = array(
1053            'backgroundImage'      => $background['backgroundImage'],
1054            'backgroundSize'       => $background['backgroundSize'] ?? 'cover',
1055            'backgroundPosition'   => $background['backgroundPosition'] ?? null,
1056            'backgroundRepeat'     => $background['backgroundRepeat'] ?? null,
1057            'backgroundAttachment' => $background['backgroundAttachment'] ?? null,
1058        );
1059
1060        if ( 'contain' === $background_styles['backgroundSize'] && ! $background_styles['backgroundPosition'] ) {
1061            $background_styles['backgroundPosition'] = '50% 50%';
1062        }
1063
1064        // A step's styles are still ahead of the do_shortcode() pass in Contact_Form::parse(),
1065        // so percent-encode the brackets that would otherwise make this URL look like a
1066        // shortcode: unencoded they are stripped out of the attribute, taking the background
1067        // with them, and the shortcode's side effects run.
1068        if ( isset( $background_styles['backgroundImage']['url'] ) && is_string( $background_styles['backgroundImage']['url'] ) ) {
1069            $background_styles['backgroundImage']['url'] = strtr(
1070                $background_styles['backgroundImage']['url'],
1071                array(
1072                    '[' => '%5B',
1073                    ']' => '%5D',
1074                )
1075            );
1076        }
1077
1078        $styles = wp_style_engine_get_styles( array( 'background' => $background_styles ) );
1079
1080        if ( empty( $styles['css'] ) ) {
1081            return $html;
1082        }
1083
1084        $tags = new \WP_HTML_Tag_Processor( $html );
1085
1086        if ( ! $tags->next_tag( array( 'class_name' => $target_class ) ) ) {
1087            return $html;
1088        }
1089
1090        $existing_style = $tags->get_attribute( 'style' );
1091
1092        if ( is_string( $existing_style ) && '' !== $existing_style ) {
1093            $separator = str_ends_with( $existing_style, ';' ) ? '' : ';';
1094            $tags->set_attribute( 'style', $existing_style . $separator . $styles['css'] );
1095        } else {
1096            $tags->set_attribute( 'style', $styles['css'] );
1097        }
1098
1099        $tags->add_class( 'has-background' );
1100
1101        return $tags->get_updated_html();
1102    }
1103
1104    /**
1105     * Load editor styles for the block.
1106     *
1107     * @deprecated 7.5.0 This function is deprecated and will be removed in a future version.
1108     */
1109    public static function load_editor_styles() {
1110        _deprecated_function( __FUNCTION__, 'jetpack-7.5.0' );
1111    }
1112
1113    /**
1114     * Loads scripts
1115     */
1116    public static function load_editor_scripts() {
1117        global $post;
1118        // Bail early if the user cannot manage the block.
1119        if ( ! self::can_manage_block() ) {
1120            return;
1121        }
1122
1123        $handle = 'jp-forms-blocks';
1124
1125        // Ensure the jetpack-blocks-editor dependency exists. When the Blocks module
1126        // is inactive, nothing registers it, but the Forms editor JS needs the
1127        // Jetpack_Editor_Initial_State global (with availability data) it provides.
1128        self::maybe_register_blocks_editor_script();
1129
1130        Assets::register_script(
1131            $handle,
1132            '../../../dist/blocks/editor.js',
1133            __FILE__,
1134            array(
1135                'dependencies' => array( 'jetpack-blocks-editor' ),
1136                'in_footer'    => true,
1137                'textdomain'   => 'jetpack-forms',
1138                'enqueue'      => true,
1139                'css_path'     => '../../../dist/blocks/editor.css',
1140            )
1141        );
1142
1143        // Create a Contact_Form instance to get the default values
1144        $form_responses_url      = Forms_Dashboard::get_forms_admin_url();
1145        $akismet_active_with_key = Jetpack::is_akismet_active();
1146        $akismet_key_url         = admin_url( 'admin.php?page=akismet-key-config' );
1147
1148        $default_recipient = Contact_Form::get_default_to_with_source( $post );
1149
1150        $data = array(
1151            'defaults' => array(
1152                'to'                   => $default_recipient['to'],
1153                'toSource'             => $default_recipient['source'],
1154                // Decoded for display only: get_option( 'blogname' ) stores the site title HTML-encoded,
1155                // which would otherwise surface raw entities such as &#039; in the editor's placeholder.
1156                'subject'              => wp_specialchars_decode( Contact_Form::get_default_subject( array() ), ENT_QUOTES ),
1157                'formsResponsesUrl'    => $form_responses_url,
1158                'akismetActiveWithKey' => $akismet_active_with_key,
1159                'akismetUrl'           => $akismet_key_url,
1160                'assetsUrl'            => Jetpack_Forms::assets_url(),
1161                'isMailPoetEnabled'    => Jetpack_Forms::is_mailpoet_enabled(),
1162                // So the file field's "Maximum files" control offers exactly what the site will honour,
1163                // including when a filter has raised the ceiling.
1164                'maxFilesLimit'        => Contact_Form_Field::get_file_field_max_files_limit(),
1165            ),
1166        );
1167
1168        wp_add_inline_script( $handle, 'window.jpFormsBlocks = ' . wp_json_encode( $data, JSON_UNESCAPED_SLASHES | JSON_HEX_TAG | JSON_HEX_AMP ) . ';', 'before' );
1169    }
1170
1171    /**
1172     * Conditionally loads the AI form generation integration script.
1173     *
1174     * This script is only loaded when:
1175     * 1. The AI Assistant extension is available (ai-assistant-form-support)
1176     * 2. The central-form-management feature flag is enabled
1177     *
1178     * By checking these conditions in PHP, we ensure no JavaScript is loaded
1179     * when either the AI extension is disabled or central form management is off.
1180     *
1181     * This is hooked at priority 11 on enqueue_block_editor_assets to ensure
1182     * it runs after Jetpack_Gutenberg registers extensions at priority 10.
1183     */
1184    public static function maybe_load_ai_integration() {
1185        // Bail if the user cannot manage the block â€” jp-forms-blocks won't be registered.
1186        if ( ! self::can_manage_block() ) {
1187            return;
1188        }
1189
1190        // Check if central form management is enabled.
1191        if ( ! Contact_Form_Plugin::has_editor_feature_flag( 'central-form-management' ) ) {
1192            return;
1193        }
1194
1195        // Check if AI Assistant form support is available.
1196        // This extension is set as available when the AI Assistant block is registered.
1197        if ( ! class_exists( 'Jetpack_Gutenberg' ) ) {
1198            return;
1199        }
1200
1201        // Ensure extensions are registered by calling get_cached_availability().
1202        \Jetpack_Gutenberg::get_cached_availability();
1203        if ( ! \Jetpack_Gutenberg::is_available( 'ai-assistant-form-support' ) ) {
1204            return;
1205        }
1206
1207        Assets::register_script(
1208            'jp-forms-ai-plugin',
1209            '../../../dist/blocks/ai-form-plugin.js',
1210            __FILE__,
1211            array(
1212                'dependencies' => array( 'jp-forms-blocks' ),
1213                'in_footer'    => true,
1214                'textdomain'   => 'jetpack-forms',
1215                'enqueue'      => true,
1216            )
1217        );
1218    }
1219
1220    /**
1221     * Add REST API endpoints to the block editor preload list.
1222     *
1223     * @param array $paths Existing paths to preload.
1224     * @return array Updated paths to preload.
1225     */
1226    public static function preload_endpoints( $paths ) {
1227        $paths[] = array( '/wp/v2/feedback/config', 'GET' );
1228        $paths[] = array( '/wp/v2/feedback/config?_locale=user', 'GET' );
1229        return $paths;
1230    }
1231
1232    /**
1233     * Loads scripts
1234     */
1235    public static function load_view_scripts() {
1236        if ( is_admin() ) {
1237            // A block's view assets will not be required in wp-admin.
1238            return;
1239        }
1240
1241        Assets::register_script(
1242            'jp-forms-blocks',
1243            '../../../dist/blocks/view.js',
1244            __FILE__,
1245            array(
1246                'in_footer'  => true,
1247                'strategy'   => 'defer',
1248                'textdomain' => 'jetpack-forms',
1249                'enqueue'    => true,
1250            )
1251        );
1252    }
1253
1254    /**
1255     * Register a minimal jetpack-blocks-editor script when the Blocks module is inactive.
1256     *
1257     * The Forms editor JS depends on jetpack-blocks-editor for the
1258     * Jetpack_Editor_Initial_State global, which includes block availability data.
1259     * Normally the Blocks module registers this, but Forms needs to work independently.
1260     */
1261    private static function maybe_register_blocks_editor_script() {
1262        if ( wp_script_is( 'jetpack-blocks-editor', 'registered' ) ) {
1263            return;
1264        }
1265
1266        // When the Blocks module is active it will register the real script, so bail.
1267        if ( class_exists( 'Jetpack' ) && ( new Modules() )->is_active( 'blocks' ) ) {
1268            return;
1269        }
1270
1271        // Register a minimal script to satisfy the dependency.
1272        wp_register_script( 'jetpack-blocks-editor', '', array(), JETPACK__VERSION, true );
1273        wp_register_style( 'jetpack-blocks-editor', false, array(), JETPACK__VERSION );
1274
1275        // Provide the initial state the Forms editor JS expects:
1276        // - available_blocks: the JS block registration checks this before calling registerBlockType.
1277        // - modules: the useModuleStatus hook reads this to decide whether to show the block
1278        // or an "Activate Forms" placeholder.
1279        // - feature_flags: hasFeatureFlag() reads this for central-form-management,
1280        // form-webhooks, and multistep-form.
1281        wp_localize_script(
1282            Shared_Stores_Assets::SCRIPT_HANDLE,
1283            'Jetpack_Editor_Initial_State',
1284            array(
1285                'available_blocks' => array(
1286                    'contact-form' => array( 'available' => true ),
1287                ),
1288                'modules'          => array(
1289                    'contact-form' => array( 'activated' => true ),
1290                ),
1291                'feature_flags'    => apply_filters( 'jetpack_block_editor_feature_flags', array() ),
1292            )
1293        );
1294    }
1295
1296    /**
1297     * Check if the current user can view the block.
1298     * Every user can see it if the Contact Form module is active,
1299     * but if it is inactive, only admins can see it.
1300     *
1301     * This is only useful when the Contact Form package is used within the Jetpack plugin,
1302     * where the module logic exists.
1303     *
1304     * @since 0.49.0
1305     *
1306     * @return bool
1307     */
1308    public static function can_manage_block() {
1309        if (
1310            /**
1311             * Allow third-parties to override the form block's visibility.
1312             *
1313             * @since 0.49.0
1314             *
1315             * @module contact-form
1316             *
1317             * @param bool $can_manage_block Whether the current user can manage the block.
1318             */
1319            apply_filters( 'jetpack_contact_form_can_manage_block', false )
1320        ) {
1321            return true;
1322        }
1323
1324        if ( ! class_exists( 'Jetpack' ) ) {
1325            return true;
1326        }
1327
1328        return ( new Modules() )->is_active( 'contact-form' ) || current_user_can( 'jetpack_activate_modules' );
1329    }
1330}