WordPress.org

Making WordPress.org

Changeset 8480


Ignore:
Timestamp:
03/20/2019 10:36:09 PM (4 months ago)
Author:
coffee2code
Message:

Gutenberg: Reinstate copy of gutenberg_editor_scripts_and_styles() that was deleted from the Gutenberg plugin.

Includes a tweak to ensure the $locked variable is set so as to prevent a PHP warning.

We should eventually have the site use the code packaged with WP and not the plugin.

Props aduth, coffee2code.

File:
1 edited

Legend:

Unmodified
Added
Removed
  • sites/trunk/wordpress.org/public_html/wp-content/themes/pub/gutenberg/functions.php

    r8479 r8480  
    2020        return null;
    2121    }
     22}
     23
     24/**
     25 * This function was removed from the Gutenberg plugin in v5.3.
     26 */
     27if ( ! function_exists( 'gutenberg_editor_scripts_and_styles' ) ) {
     28/**
     29 * Scripts & Styles.
     30 *
     31 * Enqueues the needed scripts and styles when visiting the top-level page of
     32 * the Gutenberg editor.
     33 *
     34 * @since 0.1.0
     35 *
     36 * @param string $hook Screen name.
     37 */
     38function gutenberg_editor_scripts_and_styles( $hook ) {
     39    global $wp_meta_boxes;
     40
     41    // Enqueue heartbeat separately as an "optional" dependency of the editor.
     42    // Heartbeat is used for automatic nonce refreshing, but some hosts choose
     43    // to disable it outright.
     44    wp_enqueue_script( 'heartbeat' );
     45
     46    wp_enqueue_script( 'wp-edit-post' );
     47    wp_enqueue_script( 'wp-format-library' );
     48    wp_enqueue_style( 'wp-format-library' );
     49
     50    global $post;
     51
     52    // Set initial title to empty string for auto draft for duration of edit.
     53    // Otherwise, title defaults to and displays as "Auto Draft".
     54    $is_new_post = 'auto-draft' === $post->post_status;
     55
     56    // Set the post type name.
     57    $post_type        = get_post_type( $post );
     58    $post_type_object = get_post_type_object( $post_type );
     59    $rest_base        = ! empty( $post_type_object->rest_base ) ? $post_type_object->rest_base : $post_type_object->name;
     60
     61    $preload_paths = array(
     62        '/',
     63        '/wp/v2/types?context=edit',
     64        '/wp/v2/taxonomies?per_page=-1&context=edit',
     65        '/wp/v2/themes?status=active',
     66        sprintf( '/wp/v2/%s/%s?context=edit', $rest_base, $post->ID ),
     67        sprintf( '/wp/v2/types/%s?context=edit', $post_type ),
     68        sprintf( '/wp/v2/users/me?post_type=%s&context=edit', $post_type ),
     69        array( '/wp/v2/media', 'OPTIONS' ),
     70        array( '/wp/v2/blocks', 'OPTIONS' ),
     71    );
     72
     73    /**
     74     * Preload common data by specifying an array of REST API paths that will be preloaded.
     75     *
     76     * Filters the array of paths that will be preloaded.
     77     *
     78     * @param array $preload_paths Array of paths to preload
     79     * @param object $post         The post resource data.
     80     */
     81    $preload_paths = apply_filters( 'block_editor_preload_paths', $preload_paths, $post );
     82
     83    // Ensure the global $post remains the same after
     84    // API data is preloaded. Because API preloading
     85    // can call the_content and other filters, callbacks
     86    // can unexpectedly modify $post resulting in issues
     87    // like https://github.com/WordPress/gutenberg/issues/7468.
     88    $backup_global_post = $post;
     89
     90    $preload_data = array_reduce(
     91        $preload_paths,
     92        'rest_preload_api_request',
     93        array()
     94    );
     95
     96    // Restore the global $post as it was before API preloading.
     97    $post = $backup_global_post;
     98
     99    wp_add_inline_script(
     100        'wp-api-fetch',
     101        sprintf( 'wp.apiFetch.use( wp.apiFetch.createPreloadingMiddleware( %s ) );', wp_json_encode( $preload_data ) ),
     102        'after'
     103    );
     104
     105    wp_add_inline_script(
     106        'wp-blocks',
     107        sprintf( 'wp.blocks.setCategories( %s );', wp_json_encode( get_block_categories( $post ) ) ),
     108        'after'
     109    );
     110
     111    // Assign initial edits, if applicable. These are not initially assigned
     112    // to the persisted post, but should be included in its save payload.
     113    if ( $is_new_post ) {
     114        // Override "(Auto Draft)" new post default title with empty string,
     115        // or filtered value.
     116        $initial_edits = array(
     117            'title'   => $post->post_title,
     118            'content' => $post->post_content,
     119            'excerpt' => $post->post_excerpt,
     120        );
     121    } else {
     122        $initial_edits = null;
     123    }
     124
     125    // Preload server-registered block schemas.
     126    wp_add_inline_script(
     127        'wp-blocks',
     128        'wp.blocks.unstable__bootstrapServerSideBlockDefinitions(' . json_encode( get_block_editor_server_block_settings() ) . ');'
     129    );
     130
     131    // Get admin url for handling meta boxes.
     132    $meta_box_url = admin_url( 'post.php' );
     133    $meta_box_url = add_query_arg(
     134        array(
     135            'post'            => $post->ID,
     136            'action'          => 'edit',
     137            'meta-box-loader' => true,
     138            '_wpnonce'        => wp_create_nonce( 'meta-box-loader' ),
     139        ),
     140        $meta_box_url
     141    );
     142    wp_localize_script( 'wp-editor', '_wpMetaBoxUrl', $meta_box_url );
     143
     144    // Initialize the editor.
     145    $align_wide    = get_theme_support( 'align-wide' );
     146    $color_palette = current( (array) get_theme_support( 'editor-color-palette' ) );
     147    $font_sizes    = current( (array) get_theme_support( 'editor-font-sizes' ) );
     148
     149    /**
     150     * Filters the allowed block types for the editor, defaulting to true (all
     151     * block types supported).
     152     *
     153     * @param bool|array $allowed_block_types Array of block type slugs, or
     154     *                                        boolean to enable/disable all.
     155     * @param object $post                    The post resource data.
     156     */
     157    $allowed_block_types = apply_filters( 'allowed_block_types', true, $post );
     158
     159    // Get all available templates for the post/page attributes meta-box.
     160    // The "Default template" array element should only be added if the array is
     161    // not empty so we do not trigger the template select element without any options
     162    // besides the default value.
     163    $available_templates = wp_get_theme()->get_page_templates( get_post( $post->ID ) );
     164    $available_templates = ! empty( $available_templates ) ? array_merge(
     165        array(
     166            '' => apply_filters( 'default_page_template_title', __( 'Default template', 'gutenberg' ), 'rest-api' ),
     167        ),
     168        $available_templates
     169    ) : $available_templates;
     170
     171    // Media settings.
     172    $max_upload_size = wp_max_upload_size();
     173    if ( ! $max_upload_size ) {
     174        $max_upload_size = 0;
     175    }
     176
     177    // Editor Styles.
     178    global $editor_styles;
     179    $styles = array(
     180        array(
     181            'css' => file_get_contents(
     182                ABSPATH . WPINC . '/css/dist/editor/editor-styles.css'
     183            ),
     184        ),
     185    );
     186
     187    /* Translators: Use this to specify the CSS font family for the default font */
     188    $locale_font_family = esc_html_x( 'Noto Serif', 'CSS Font Family for Editor Font', 'gutenberg' );
     189    $styles[]           = array(
     190        'css' => "body { font-family: '$locale_font_family' }",
     191    );
     192
     193    if ( $editor_styles && current_theme_supports( 'editor-styles' ) ) {
     194        foreach ( $editor_styles as $style ) {
     195            if ( filter_var( $style, FILTER_VALIDATE_URL ) ) {
     196                $styles[] = array(
     197                    'css' => file_get_contents( $style ),
     198                );
     199            } else {
     200                $file = get_theme_file_path( $style );
     201                if ( file_exists( $file ) ) {
     202                    $styles[] = array(
     203                        'css'     => file_get_contents( $file ),
     204                        'baseURL' => get_theme_file_uri( $style ),
     205                    );
     206                }
     207            }
     208        }
     209    }
     210
     211    // Lock settings.
     212    $user_id = wp_check_post_lock( $post->ID );
     213    if ( $user_id ) {
     214        /**
     215         * Filters whether to show the post locked dialog.
     216         *
     217         * Returning a falsey value to the filter will short-circuit displaying the dialog.
     218         *
     219         * @since 3.6.0
     220         *
     221         * @param bool         $display Whether to display the dialog. Default true.
     222         * @param WP_Post      $post    Post object.
     223         * @param WP_User|bool $user    The user id currently editing the post.
     224         */
     225        if ( apply_filters( 'show_post_locked_dialog', true, $post, $user_id ) ) {
     226            $locked = true;
     227        } else {
     228            $locked = false;
     229        }
     230
     231        $user_details = null;
     232        if ( $locked ) {
     233            $user         = get_userdata( $user_id );
     234            $user_details = array(
     235                'name' => $user->display_name,
     236            );
     237            $avatar       = get_avatar( $user_id, 64 );
     238            if ( $avatar ) {
     239                if ( preg_match( "|src='([^']+)'|", $avatar, $matches ) ) {
     240                    $user_details['avatar'] = $matches[1];
     241                }
     242            }
     243        }
     244
     245        $lock_details = array(
     246            'isLocked' => $locked,
     247            'user'     => $user_details,
     248        );
     249    } else {
     250
     251        // Lock the post.
     252        $active_post_lock = wp_set_post_lock( $post->ID );
     253        $lock_details     = array(
     254            'isLocked'       => false,
     255            'activePostLock' => esc_attr( implode( ':', $active_post_lock ) ),
     256        );
     257    }
     258
     259    $editor_settings = array(
     260        'alignWide'              => $align_wide,
     261        'availableTemplates'     => $available_templates,
     262        'allowedBlockTypes'      => $allowed_block_types,
     263        'disableCustomColors'    => get_theme_support( 'disable-custom-colors' ),
     264        'disableCustomFontSizes' => get_theme_support( 'disable-custom-font-sizes' ),
     265        'disablePostFormats'     => ! current_theme_supports( 'post-formats' ),
     266        'titlePlaceholder'       => apply_filters( 'enter_title_here', __( 'Add title', 'gutenberg' ), $post ),
     267        'bodyPlaceholder'        => apply_filters( 'write_your_story', __( 'Start writing or type / to choose a block', 'gutenberg' ), $post ),
     268        'isRTL'                  => is_rtl(),
     269        'autosaveInterval'       => 10,
     270        'maxUploadFileSize'      => $max_upload_size,
     271        'allowedMimeTypes'       => get_allowed_mime_types(),
     272        'styles'                 => $styles,
     273        'imageSizes'             => gutenberg_get_available_image_sizes(),
     274        'richEditingEnabled'     => user_can_richedit(),
     275
     276        // Ideally, we'd remove this and rely on a REST API endpoint.
     277        'postLock'               => $lock_details,
     278        'postLockUtils'          => array(
     279            'nonce'       => wp_create_nonce( 'lock-post_' . $post->ID ),
     280            'unlockNonce' => wp_create_nonce( 'update-post_' . $post->ID ),
     281            'ajaxUrl'     => admin_url( 'admin-ajax.php' ),
     282        ),
     283
     284        // Whether or not to load the 'postcustom' meta box is stored as a user meta
     285        // field so that we're not always loading its assets.
     286        'enableCustomFields'     => (bool) get_user_meta( get_current_user_id(), 'enable_custom_fields', true ),
     287    );
     288
     289    $post_autosave = gutenberg_get_autosave_newer_than_post_save( $post );
     290    if ( $post_autosave ) {
     291        $editor_settings['autosave'] = array(
     292            'editLink' => get_edit_post_link( $post_autosave->ID ),
     293        );
     294    }
     295
     296    if ( false !== $color_palette ) {
     297        $editor_settings['colors'] = $color_palette;
     298    }
     299
     300    if ( false !== $font_sizes ) {
     301        $editor_settings['fontSizes'] = $font_sizes;
     302    }
     303
     304    if ( ! empty( $post_type_object->template ) ) {
     305        $editor_settings['template']     = $post_type_object->template;
     306        $editor_settings['templateLock'] = ! empty( $post_type_object->template_lock ) ? $post_type_object->template_lock : false;
     307    }
     308
     309    $current_screen  = get_current_screen();
     310    $core_meta_boxes = array();
     311
     312    // Make sure the current screen is set as well as the normal core metaboxes.
     313    if ( isset( $current_screen->id ) && isset( $wp_meta_boxes[ $current_screen->id ]['normal']['core'] ) ) {
     314        $core_meta_boxes = $wp_meta_boxes[ $current_screen->id ]['normal']['core'];
     315    }
     316
     317    // Check if the Custom Fields meta box has been removed at some point.
     318    if ( ! isset( $core_meta_boxes['postcustom'] ) || ! $core_meta_boxes['postcustom'] ) {
     319        unset( $editor_settings['enableCustomFields'] );
     320    }
     321
     322    /**
     323     * Filters the settings to pass to the block editor.
     324     *
     325     * @since 3.7.0
     326     *
     327     * @param array   $editor_settings Default editor settings.
     328     * @param WP_Post $post            Post being edited.
     329     */
     330    $editor_settings = apply_filters( 'block_editor_settings', $editor_settings, $post );
     331
     332    $init_script = <<<JS
     333( function() {
     334    window._wpLoadBlockEditor = new Promise( function( resolve ) {
     335        wp.domReady( function() {
     336            resolve( wp.editPost.initializeEditor( 'editor', "%s", %d, %s, %s ) );
     337        } );
     338    } );
     339} )();
     340JS;
     341
     342    $script = sprintf(
     343        $init_script,
     344        $post->post_type,
     345        $post->ID,
     346        wp_json_encode( $editor_settings ),
     347        wp_json_encode( $initial_edits )
     348    );
     349    wp_add_inline_script( 'wp-edit-post', $script );
     350
     351    /**
     352     * Scripts
     353     */
     354    wp_enqueue_media(
     355        array(
     356            'post' => $post->ID,
     357        )
     358    );
     359    wp_tinymce_inline_scripts();
     360    wp_enqueue_editor();
     361
     362    /**
     363     * Styles
     364     */
     365    wp_enqueue_style( 'wp-edit-post' );
     366
     367    /**
     368     * Fires after block assets have been enqueued for the editing interface.
     369     *
     370     * Call `add_action` on any hook before 'admin_enqueue_scripts'.
     371     *
     372     * In the function call you supply, simply use `wp_enqueue_script` and
     373     * `wp_enqueue_style` to add your functionality to the Gutenberg editor.
     374     *
     375     * @since 0.4.0
     376     */
     377    do_action( 'enqueue_block_editor_assets' );
     378}
     379
    22380}
    23381
     
    170528    }, 11 );
    171529
     530    add_action( 'wp_enqueue_scripts', function( $hook ) {
     531        // Gutenberg requires the post-locking functions defined within:
     532        // See `show_post_locked_dialog` and `get_post_metadata` filters below.
     533        include_once ABSPATH . 'wp-admin/includes/post.php';
     534
     535        gutenberg_editor_scripts_and_styles( $hook );
     536    } );
     537
    172538    add_action( 'enqueue_block_editor_assets', function() {
    173539        wp_enqueue_script( 'button-readonly', get_template_directory_uri() . '/js/button-readonly.js', array( 'wp-blocks', 'wp-element' ), null );
Note: See TracChangeset for help on using the changeset viewer.