Skip to content

Editor doesn't switch back to visual editor if codeEditingEnabled is false #49211

@kraftner

Description

@kraftner

Description

The block editor has a visual and a text mode (aka Code Editor). A user can freely switch between those and what a user has chosen is stored in local storage.

Text mode can be disabled using the block_editor_settings_all filter and the codeEditingEnabled setting.

Using that filter you can also disable the code editor only under some specific conditions, e.g. for a specific post type.

The problem is that although this then disables the UI and keyboard shortcuts to switch, you can still end up in the text mode although you shouldn't be able to:

  • When you change the setting globally while users are already in the text mode.
  • When you switch to text mode in a post type where it is enabled and then open another post type.

Step-by-step reproduction instructions

  1. Disable Code Editing for a post type, e.g. page, e.g. like this:
    add_filter('block_editor_settings_all', function (
        array $editorSettings,
        WP_Block_Editor_Context $editorContext
    ) {
        if (get_post_type($editorContext->post) === 'page') {
            $editorSettings['codeEditingEnabled'] = false;
        }
        return $editorSettings;
    }, 10, 2);
    
  2. Open the block editor in a post of post type post.
  3. Switch to the Code editor.
  4. Open the block editor in a post of post type page.
  5. You are in the Code editor.

You can then still exit the Code editor by clicking the "Exit code editor" button (not using the keyboard shortcut) but you shouldn't even be able to end up here.


What I think should happen is that when opening a block editor where codeEditingEnabled is false the editor should automatically switch back to the visual editor or already get initialized in it.

This is a quick fix the does this checking and switching back after initialization of the editor:

if(
!wp.data.select('core/editor').getEditorSettings().codeEditingEnabled
&&
wp.data.select('core/edit-post').getEditorMode() === 'text'
){
   wp.data.dispatch('core/edit-post').switchEditorMode('visual');
}

Screenshots, screen recording, code snippet

codeEditingEnabled.webm

Environment info

  • WordPress 6.1.1 with and without Gutenberg 15.3.1, any theme
  • Firefox
  • Desktop Ubuntu 22.04

Please confirm that you have searched existing issues in the repo.

Yes

Please confirm that you have tested with all plugins deactivated except Gutenberg.

Yes

Metadata

Metadata

Assignees

Labels

[Feature] Code EditorHandling the code view of the editing experience[Status] In ProgressTracking issues with work in progress[Type] BugAn existing feature does not function as intended

Type

No type
No fields configured for issues without a type.

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions