Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
89.05% covered (warning)
89.05%
122 / 137
82.35% covered (warning)
82.35%
14 / 17
CRAP
0.00% covered (danger)
0.00%
0 / 1
Jetpack_Email_Design_Editor
91.04% covered (success)
91.04%
122 / 134
82.35% covered (warning)
82.35%
14 / 17
35.88
0.00% covered (danger)
0.00%
0 / 1
 init
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
2
 add_script_data
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
 get_url
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
2
 register_feature_flags
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
2
 is_enabled
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 add_admin_page
100.00% covered (success)
100.00%
11 / 11
100.00% covered (success)
100.00%
1 / 1
3
 on_load
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 add_fullscreen_body_class
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 enqueue_assets
100.00% covered (success)
100.00%
33 / 33
100.00% covered (success)
100.00%
1 / 1
2
 get_layout_css
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
1
 enqueue_block_editor_assets
100.00% covered (success)
100.00%
19 / 19
100.00% covered (success)
100.00%
1 / 1
1
 get_screen_data
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
1 / 1
1
 exit_url
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
4
 get_iframe_asset_settings
85.71% covered (warning)
85.71%
6 / 7
0.00% covered (danger)
0.00%
0 / 1
2.01
 get_allowed_iframe_style_handles
100.00% covered (success)
100.00%
14 / 14
100.00% covered (success)
100.00%
1 / 1
6
 get_resolved_assets
100.00% covered (success)
100.00%
12 / 12
100.00% covered (success)
100.00%
1 / 1
5
 render
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
1<?php
2/**
3 * The newsletter email design screen.
4 *
5 * @package automattic/jetpack
6 */
7
8use Automattic\Jetpack\Feature_Flags\Feature_Flags;
9
10if ( ! defined( 'ABSPATH' ) ) {
11    exit( 0 );
12}
13
14/**
15 * Registers an Appearance page that mounts the WooCommerce email editor against the
16 * newsletter template, so a creator sets their email design once for the whole site.
17 *
18 * The design itself lives on the WordPress.com shadow blog: the browser fetches it from
19 * `/wpcom/v2/email-editor-bootstrap` and this page supplies only what describes *this*
20 * installation. See NL-839.
21 */
22class Jetpack_Email_Design_Editor {
23
24    /**
25     * The `page` query arg the screen answers to.
26     */
27    const PAGE_SLUG = 'jetpack-email-design';
28
29    /**
30     * The feature flag gating the screen. Registered off, forced on for testing with
31     * `wp companion feature-flag enable jetpack-email-design`.
32     */
33    const FEATURE_FLAG = 'jetpack-email-design';
34
35    /**
36     * The script handle, and the id of the element the editor mounts into.
37     */
38    const HANDLE = 'jetpack-email-design-editor';
39
40    /**
41     * Flags for JSON handed to a `<script>` tag.
42     */
43    const JSON_FLAGS = JSON_UNESCAPED_SLASHES | JSON_HEX_TAG | JSON_HEX_AMP;
44
45    /**
46     * The hook suffix `add_theme_page()` returned, or null when the page is not registered.
47     *
48     * @var string|null
49     */
50    private static $hook_suffix = null;
51
52    /**
53     * Wire the screen up.
54     */
55    public static function init() {
56        // Registered here rather than on `admin_menu` so the flag exists under WP-CLI, REST
57        // and cron too — `wp companion feature-flag list` reads it from one of those.
58        self::register_feature_flags();
59
60        add_action( 'admin_menu', array( __CLASS__, 'add_admin_page' ) );
61
62        // Priority 20, because `Newsletter\Settings::add_script_data()` replaces the whole
63        // `newsletter` key at the default priority on the page this link appears on.
64        add_filter( 'jetpack_admin_js_script_data', array( __CLASS__, 'add_script_data' ), 20 );
65    }
66
67    /**
68     * Tell the admin where this screen is, or that there is none.
69     *
70     * The bare URL: each surface that links here adds its own `return` arg, because each one is
71     * somewhere different to go back to. {@see self::exit_url()} reads and validates it.
72     *
73     * @param array $data The script data so far.
74     * @return array The script data, with `newsletter.emailDesignUrl` null when there is no screen.
75     */
76    public static function add_script_data( $data ) {
77        $url = self::get_url();
78
79        $data['newsletter']['emailDesignUrl'] = '' === $url ? null : $url;
80
81        return $data;
82    }
83
84    /**
85     * The screen's own URL, or an empty string when this request has no such screen.
86     *
87     * Read back from the registration, not built from the slug, so a link cannot outlive the page:
88     * `add_theme_page()` registers nothing without `edit_theme_options`, which `manage_options` --
89     * all the Newsletter settings page asks for -- does not imply.
90     *
91     * @return string
92     */
93    public static function get_url() {
94        return function_exists( 'menu_page_url' ) ? (string) menu_page_url( self::PAGE_SLUG, false ) : '';
95    }
96
97    /**
98     * Declare the screen's feature flag.
99     */
100    public static function register_feature_flags() {
101        Feature_Flags::register(
102            self::FEATURE_FLAG,
103            array(
104                'default'     => false,
105                'description' => 'Edit the newsletter email design in wp-admin, under Appearance.',
106                'owner'       => 'jetpack-newsletter',
107            )
108        );
109    }
110
111    /**
112     * Whether the screen should exist on this site.
113     *
114     * The WordPress.com `email-design-editor` sticker gates the bootstrap endpoint, not this
115     * page: a Jetpack site cannot read stickers without an API call, so the screen carries
116     * its own gate.
117     *
118     * @return bool
119     */
120    public static function is_enabled() {
121        return Feature_Flags::is_enabled( self::FEATURE_FLAG );
122    }
123
124    /**
125     * Add the screen under Appearance.
126     */
127    public static function add_admin_page() {
128        if ( ! self::is_enabled() ) {
129            return;
130        }
131
132        self::$hook_suffix = add_theme_page(
133            __( 'Email Design', 'jetpack' ),
134            __( 'Email Design', 'jetpack' ),
135            'edit_theme_options',
136            self::PAGE_SLUG,
137            array( __CLASS__, 'render' )
138        );
139
140        if ( self::$hook_suffix ) {
141            add_action( 'load-' . self::$hook_suffix, array( __CLASS__, 'on_load' ) );
142        }
143    }
144
145    /**
146     * Scope everything else to this one screen.
147     */
148    public static function on_load() {
149        add_action( 'admin_enqueue_scripts', array( __CLASS__, 'enqueue_assets' ) );
150        add_filter( 'admin_body_class', array( __CLASS__, 'add_fullscreen_body_class' ) );
151    }
152
153    /**
154     * Put the screen in fullscreen mode before the bundle has loaded.
155     *
156     * `wp-editor` hides the admin menu on this class, and the editor sets it from a React
157     * component — so it cannot apply until the bundle has loaded and the bootstrap has answered,
158     * and the page visibly reflows a few seconds in. Setting it here makes fullscreen the layout
159     * from first paint. The admin bar is untouched, which keeps a way out if the editor fails.
160     *
161     * @param string $classes Space-separated admin body classes.
162     * @return string
163     */
164    public static function add_fullscreen_body_class( $classes ) {
165        return trim( $classes . ' is-fullscreen-mode' );
166    }
167
168    /**
169     * Enqueue the editor bundle and the block-editor assets it expects to find.
170     */
171    public static function enqueue_assets() {
172        $asset_path = JETPACK__PLUGIN_DIR . '_inc/build/email-design-editor.asset.php';
173
174        if ( ! file_exists( $asset_path ) ) {
175            return;
176        }
177
178        $asset = include $asset_path;
179
180        self::enqueue_block_editor_assets();
181
182        // `@woocommerce/email-editor` opts into core's private APIs as `@wordpress/edit-site`,
183        // resolved against the site's `wp-private-apis`. Re-check on a package bump. NL-839 (j).
184        wp_enqueue_script(
185            self::HANDLE,
186            plugins_url( '_inc/build/email-design-editor.js', JETPACK__PLUGIN_FILE ),
187            $asset['dependencies'],
188            $asset['version'],
189            true
190        );
191        wp_set_script_translations( self::HANDLE, 'jetpack' );
192
193        // `wp-editor`, `wp-block-editor` and `wp-preferences` are what lay the editor's frame
194        // out; without them every region stacks into one narrow column. Keep the list to
195        // handles WordPress registers — an unregistered one drops this stylesheet silently,
196        // which is `wp-interface`'s trap.
197        wp_enqueue_style(
198            self::HANDLE,
199            plugins_url( '_inc/build/email-design-editor.css', JETPACK__PLUGIN_FILE ),
200            array(
201                'wp-components',
202                'wp-block-editor',
203                'wp-editor',
204                'wp-edit-blocks',
205                'wp-preferences',
206                'wp-format-library',
207            ),
208            $asset['version']
209        );
210        wp_style_add_data( self::HANDLE, 'rtl', 'replace' );
211        wp_add_inline_style( self::HANDLE, self::get_layout_css() );
212
213        wp_add_inline_script(
214            self::HANDLE,
215            'window.JetpackEmailDesignEditor = ' . wp_json_encode( self::get_screen_data(), self::JSON_FLAGS ) . ';',
216            'before'
217        );
218    }
219
220    /**
221     * Fill the screen with the editor.
222     *
223     * The editor's frame expects a viewport, not the flow of an admin page: inside the usual
224     * wp-admin content column it collapses to a fraction of the height and scrolls its own
225     * regions. Woo avoids this by running on `post.php`, which is already fullscreen.
226     *
227     * @return string
228     */
229    private static function get_layout_css() {
230        return '
231            #wpcontent { padding-inline-start: 0; }
232            #wpfooter { display: none; }
233            #' . self::HANDLE . ' {
234                position: fixed;
235                /* Below #wpadminbar (99999) so the editor\'s own popovers and snackbars, which ask
236                   for 100000, cannot cover it — this caps everything inside. The admin menu is
237                   hidden on this screen, so there is nothing else left to clear. */
238                z-index: 99990;
239                inset-block: var(--wp-admin--admin-bar--height, 32px) 0;
240                inset-inline: 0;
241            }
242            /* wp-edit-post pins this and the screen does not load it, so without this the
243               snackbar renders in flow beside the header instead of over the canvas. */
244            #' . self::HANDLE . ' .components-editor-notices__snackbar {
245                position: absolute;
246                inset-block-end: 20px;
247                inset-inline-start: 20px;
248            }
249        ';
250    }
251
252    /**
253     * Reproduce what the package's `Assets_Manager` does on WooCommerce's own screen.
254     *
255     * None of this happens automatically on a custom admin page: without it the editor
256     * mounts against no block library, no block categories and no server-side block
257     * definitions. See NL-839 (a).
258     *
259     * @todo Firing `enqueue_block_editor_assets` wholesale is the leading suspect for the
260     *       second Styles button — it pulls in core's site-editing global styles UI. NL-839 (e).
261     */
262    private static function enqueue_block_editor_assets() {
263        // Named rather than built from a post: there is no post here, and `get_block_categories()`
264        // hands whatever it gets to filters that type-hint the context.
265        $context = new WP_Block_Editor_Context( array( 'name' => 'jetpack/email-design' ) );
266
267        wp_enqueue_media();
268
269        do_action( 'enqueue_block_assets' );
270        do_action( 'enqueue_block_editor_assets' );
271
272        wp_enqueue_style( 'wp-edit-blocks' );
273        wp_enqueue_style( 'wp-format-library' );
274
275        wp_add_inline_script(
276            'wp-blocks',
277            sprintf( 'wp.blocks.setCategories( %s );', wp_json_encode( get_block_categories( $context ), self::JSON_FLAGS ) ),
278            'after'
279        );
280        wp_add_inline_script(
281            'wp-blocks',
282            sprintf(
283                'wp.blocks.unstable__bootstrapServerSideBlockDefinitions( %s );',
284                wp_json_encode( get_block_editor_server_block_settings(), self::JSON_FLAGS )
285            ),
286            'after'
287        );
288    }
289
290    /**
291     * What the page hands the bundle, as `window.JetpackEmailDesignEditor`.
292     *
293     * Every WordPress.com id — the template's, the global-styles record's — comes from the
294     * bootstrap response instead, because they are namespaced to the shadow blog's theme and
295     * a locally computed one is right on Simple and wrong everywhere else. See NL-839 (c).
296     *
297     * @return array
298     */
299    private static function get_screen_data() {
300        $exit_url = self::exit_url();
301
302        return array(
303            'elementId'      => self::HANDLE,
304            'editorSettings' => self::get_iframe_asset_settings(),
305
306            // The editor assigns these to `window.location.href` from its header buttons. Both
307            // leave the editor, and there is one design rather than a list, so both go to the
308            // same place.
309            'urls'           => array(
310                'back'     => $exit_url,
311                'listings' => $exit_url,
312            ),
313            'userEmail'      => wp_get_current_user()->user_email,
314        );
315    }
316
317    /**
318     * Where the editor's header buttons leave to.
319     *
320     * The `return` arg, where the surface that linked here sent one, so the editor goes back the
321     * way the reader came. Validated like core's Customizer validates its own
322     * (`wp-admin/customize.php`), and narrowed to wp-admin so the button cannot be aimed off it.
323     *
324     * Without a usable one -- Appearance, a bookmark, a reload, or the previewer's new tab, which
325     * sends none on purpose -- the dashboard, as the site editor does from the same menu
326     * (`__experimentalDashboardLink`).
327     *
328     * @return string
329     */
330    private static function exit_url() {
331        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read as a navigation target only, and validated below.
332        $return = isset( $_GET['return'] ) ? wp_validate_redirect( esc_url_raw( wp_unslash( $_GET['return'] ) ), '' ) : '';
333
334        if ( '' !== $return && 0 === strpos( $return, admin_url() ) ) {
335            return $return;
336        }
337
338        return admin_url( '/' );
339    }
340
341    /**
342     * The two editor settings that describe this installation rather than the design.
343     *
344     * WordPress.com strips both from the bootstrap bundle, because there they would name
345     * WordPress.com's own asset URLs and push them into the site's canvas.
346     *
347     * @return array
348     */
349    private static function get_iframe_asset_settings() {
350        // Absent before WP 6.3, and private, but it is what core's own block editors call to
351        // resolve the assets an iframed canvas needs.
352        if ( ! function_exists( '_wp_get_iframed_editor_assets' ) ) {
353            return array();
354        }
355
356        $handles = self::get_allowed_iframe_style_handles();
357
358        return array(
359            '__unstableResolvedAssets'  => self::get_resolved_assets( $handles ),
360            'allowedIframeStyleHandles' => $handles,
361        );
362    }
363
364    /**
365     * The stylesheet handles the canvas is allowed to keep.
366     *
367     * Mirrors the package's `Settings_Controller::get_allowed_iframe_style_handles()`. An empty
368     * list is not a no-op: the client strips every stylesheet not named here, so omitting this
369     * leaves the canvas painted in the site's own styles rather than the email's.
370     *
371     * @return string[]
372     */
373    private static function get_allowed_iframe_style_handles() {
374        $handles = array(
375            'wp-components-css',
376            'wp-reset-editor-styles-css',
377            'wp-block-library-css',
378            'wp-block-editor-content-css',
379            'wp-edit-blocks-css',
380        );
381
382        // Registration args reach the block type verbatim — `WP_Block_Type::set_props()` normalizes
383        // only `attributes`, and `register_block_type_args` can rewrite the rest — so a block
384        // declaring a bare string here would otherwise fatal the screen inside `array_merge()`.
385        foreach ( WP_Block_Type_Registry::get_instance()->get_all_registered() as $block ) {
386            if ( ! is_array( $block->supports ) || empty( $block->supports['email'] ) ) {
387                continue;
388            }
389
390            foreach ( array_merge( (array) $block->style_handles, (array) $block->editor_style_handles ) as $handle ) {
391                if ( is_string( $handle ) ) {
392                    $handles[] = $handle . '-css';
393                }
394            }
395        }
396
397        return $handles;
398    }
399
400    /**
401     * The iframe assets, trimmed to the allowed handles.
402     *
403     * @param string[] $allowed Handles to keep.
404     * @return array The `_wp_get_iframed_editor_assets()` shape, with `styles` filtered.
405     */
406    private static function get_resolved_assets( array $allowed ) {
407        // Core collects the canvas's assets by buffering `wp_print_footer_scripts()`, one of the two
408        // actions `wp_auth_check_load()` puts its "Session expired" dialog on. Core's own editor is
409        // built before `admin_enqueue_scripts` registers that; this screen is not. NL-957.
410        $had_auth_check = remove_action( 'wp_print_footer_scripts', 'wp_auth_check_html', 5 );
411
412        $assets = _wp_get_iframed_editor_assets();
413
414        if ( $had_auth_check ) {
415            add_action( 'wp_print_footer_scripts', 'wp_auth_check_html', 5 );
416        }
417
418        $kept = array();
419
420        foreach ( explode( "\n", (string) $assets['styles'] ) as $asset ) {
421            foreach ( $allowed as $handle ) {
422                if ( str_contains( $asset, $handle ) ) {
423                    $kept[] = $asset;
424                    break;
425                }
426            }
427        }
428
429        $assets['styles'] = implode( "\n", $kept );
430
431        return $assets;
432    }
433
434    /**
435     * Render the container the editor mounts into.
436     */
437    public static function render() {
438        printf( '<div id="%s" class="jetpack-email-design-editor"></div>', esc_attr( self::HANDLE ) );
439    }
440}
441
442Jetpack_Email_Design_Editor::init();