Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Share the editor settings between the post and site editors #55970

Merged
merged 8 commits into from
Nov 9, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,15 @@
import { useDispatch, useSelect } from '@wordpress/data';
import { useMemo } from '@wordpress/element';
import { store as coreStore } from '@wordpress/core-data';
import { privateApis as editorPrivateApis } from '@wordpress/editor';

/**
* Internal dependencies
*/
import { store as editSiteStore } from '../../store';
import { unlock } from '../../lock-unlock';
import inserterMediaCategories from './inserter-media-categories';

const { useBlockEditorSettings } = unlock( editorPrivateApis );
Copy link
Contributor Author

Choose a reason for hiding this comment

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

This is the existing hook that was already present in the "editor" package that I exposed temporarily to share the logic. (later I'll remove it once the site editor is able to use EditorProvider directly).


function useArchiveLabel( templateSlug ) {
const taxonomyMatches = templateSlug?.match(
Expand Down Expand Up @@ -85,40 +88,25 @@ function useArchiveLabel( templateSlug ) {

export default function useSiteEditorSettings() {
const { setIsInserterOpened } = useDispatch( editSiteStore );
const { storedSettings, canvasMode, templateType, siteSettings } =
useSelect(
( select ) => {
const { canUser, getEntityRecord } = select( coreStore );
const { getSettings, getCanvasMode, getEditedPostType } =
unlock( select( editSiteStore ) );
return {
storedSettings: getSettings( setIsInserterOpened ),
canvasMode: getCanvasMode(),
templateType: getEditedPostType(),
siteSettings: canUser( 'read', 'settings' )
? getEntityRecord( 'root', 'site' )
: undefined,
};
},
[ setIsInserterOpened ]
);

const settingsBlockPatterns =
storedSettings.__experimentalAdditionalBlockPatterns ?? // WP 6.0
storedSettings.__experimentalBlockPatterns; // WP 5.9
const settingsBlockPatternCategories =
storedSettings.__experimentalAdditionalBlockPatternCategories ?? // WP 6.0
storedSettings.__experimentalBlockPatternCategories; // WP 5.9

const {
restBlockPatterns,
restBlockPatternCategories,
templateSlug,
userPatternCategories,
focusMode,
isDistractionFree,
hasFixedToolbar,
keepCaretInsideBlock,
canvasMode,
settings,
postType,
postId,
} = useSelect( ( select ) => {
const { getEditedPostType, getEditedPostId } = select( editSiteStore );
const { getEditedEntityRecord, getUserPatternCategories } =
select( coreStore );
const {
getEditedPostType,
getEditedPostId,
__unstableGetPreference,
getCanvasMode,
getSettingsFromServer,
} = unlock( select( editSiteStore ) );
const { getEditedEntityRecord } = select( coreStore );
const usedPostType = getEditedPostType();
const usedPostId = getEditedPostId();
const _record = getEditedEntityRecord(
Expand All @@ -127,75 +115,46 @@ export default function useSiteEditorSettings() {
usedPostId
);
return {
restBlockPatterns: select( coreStore ).getBlockPatterns(),
restBlockPatternCategories:
select( coreStore ).getBlockPatternCategories(),
templateSlug: _record.slug,
userPatternCategories: getUserPatternCategories(),
focusMode: !! __unstableGetPreference( 'focusMode' ),
isDistractionFree: !! __unstableGetPreference( 'distractionFree' ),
hasFixedToolbar: !! __unstableGetPreference( 'fixedToolbar' ),
keepCaretInsideBlock: !! __unstableGetPreference(
'keepCaretInsideBlock'
),
youknowriad marked this conversation as resolved.
Show resolved Hide resolved
canvasMode: getCanvasMode(),
settings: getSettingsFromServer(),
postType: usedPostType,
postId: usedPostId,
};
}, [] );
const archiveLabels = useArchiveLabel( templateSlug );

const blockPatterns = useMemo(
() =>
[
...( settingsBlockPatterns || [] ),
...( restBlockPatterns || [] ),
]
.filter(
( x, index, arr ) =>
index === arr.findIndex( ( y ) => x.name === y.name )
)
.filter( ( { postTypes } ) => {
return (
! postTypes ||
( Array.isArray( postTypes ) &&
postTypes.includes( templateType ) )
);
} ),
[ settingsBlockPatterns, restBlockPatterns, templateType ]
);

const blockPatternCategories = useMemo(
() =>
[
...( settingsBlockPatternCategories || [] ),
...( restBlockPatternCategories || [] ),
].filter(
( x, index, arr ) =>
index === arr.findIndex( ( y ) => x.name === y.name )
),
[ settingsBlockPatternCategories, restBlockPatternCategories ]
);
return useMemo( () => {
const {
__experimentalAdditionalBlockPatterns,
__experimentalAdditionalBlockPatternCategories,
focusMode,
...restStoredSettings
} = storedSettings;

const defaultEditorSettings = useMemo( () => {
return {
...restStoredSettings,
inserterMediaCategories,
__experimentalBlockPatterns: blockPatterns,
__experimentalBlockPatternCategories: blockPatternCategories,
__experimentalUserPatternCategories: userPatternCategories,
...settings,

__experimentalSetIsInserterOpened: setIsInserterOpened,
focusMode: canvasMode === 'view' && focusMode ? false : focusMode,
isDistractionFree,
hasFixedToolbar,
keepCaretInsideBlock,

// I wonder if they should be set in the post editor too
__experimentalArchiveTitleTypeLabel: archiveLabels.archiveTypeLabel,
__experimentalArchiveTitleNameLabel: archiveLabels.archiveNameLabel,
Copy link
Contributor Author

Choose a reason for hiding this comment

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

These two settings are added by the site editor but I wonder if they make sense in the post editor. (Imagine you're using the post editor to edit the archive template, which is possible if you switch the wp_template show_admin flag to true.

I think also regardless of whether it's possible or not to actually access the page right now, we just have to think about this setting, why it's only defined in site editor but not post editor. cc @ntsekouras

Copy link
Contributor

Choose a reason for hiding this comment

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

I haven't added these, but it seems they are used by Query Title to show more intuitive titles if the block is inside an archive template.

using the post editor to edit the archive template, which is possible if you switch the wp_template show_admin flag to true.

I wasn't aware of that, and I thought there is no way you can edit such a template in post editor. I think that's the reasoning it was only defined in site editor.

pageOnFront: siteSettings?.page_on_front,
pageForPosts: siteSettings?.page_for_posts,
};
}, [
storedSettings,
blockPatterns,
blockPatternCategories,
userPatternCategories,
settings,
setIsInserterOpened,
focusMode,
isDistractionFree,
hasFixedToolbar,
keepCaretInsideBlock,
canvasMode,
archiveLabels.archiveTypeLabel,
archiveLabels.archiveNameLabel,
siteSettings?.page_on_front,
siteSettings?.page_for_posts,
] );

return useBlockEditorSettings( defaultEditorSettings, postType, postId );
Copy link
Contributor Author

Choose a reason for hiding this comment

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

Here I'm trying to mimic exactly what the EditorProvider is going to be doing when we use it directly.

Copy link
Member

Choose a reason for hiding this comment

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

There's a lot of moving parts here. All the above already exists in useBlockEditorSettings? I didn't see it being added there, so assuming it already exists there.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

yes, I checked all the settings one by one.

}
2 changes: 2 additions & 0 deletions packages/edit-site/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,10 @@ export function initializeEditor( id, settings ) {
const target = document.getElementById( id );
const root = createRoot( target );

// This might not be needed anymore.
settings.__experimentalFetchLinkSuggestions = ( search, searchOptions ) =>
fetchLinkSuggestions( search, searchOptions, settings );
// This might not be needed anymore.
settings.__experimentalFetchRichUrlData = fetchUrlData;

dispatch( blocksStore ).reapplyBlockTypeFilters();
Expand Down
4 changes: 4 additions & 0 deletions packages/edit-site/src/store/private-selectors.js
Original file line number Diff line number Diff line change
Expand Up @@ -41,3 +41,7 @@ export function getEditorCanvasContainerView( state ) {
export function getPageContentFocusType( state ) {
return hasPageContentFocus( state ) ? state.pageContentFocusType : null;
}

export function getSettingsFromServer( state ) {
return state.settings;
}
28 changes: 11 additions & 17 deletions packages/editor/src/components/provider/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -40,30 +40,24 @@ export const ExperimentalEditorProvider = withRegistryProvider(
}
return { postId: post.id, postType: post.type };
}, [ post.id, post.type ] );
const { editorSettings, selection, isReady } = useSelect(
( select ) => {
const {
getEditorSettings,
getEditorSelection,
__unstableIsEditorReady,
} = select( editorStore );
return {
editorSettings: getEditorSettings(),
isReady: __unstableIsEditorReady(),
selection: getEditorSelection(),
};
},
[]
);
const { selection, isReady } = useSelect( ( select ) => {
const { getEditorSelection, __unstableIsEditorReady } =
select( editorStore );
return {
isReady: __unstableIsEditorReady(),
selection: getEditorSelection(),
};
}, [] );
const { id, type } = __unstableTemplate ?? post;
const [ blocks, onInput, onChange ] = useEntityBlockEditor(
'postType',
type,
{ id }
);
const blockEditorSettings = useBlockEditorSettings(
editorSettings,
!! __unstableTemplate
settings,
type,
id
);
const {
updatePostLock,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -76,54 +76,63 @@ const BLOCK_EDITOR_SETTINGS = [
'__unstableIsPreviewMode',
'__unstableResolvedAssets',
'__unstableIsBlockBasedTheme',
'__experimentalArchiveTitleTypeLabel',
'__experimentalArchiveTitleNameLabel',
];

/**
* React hook used to compute the block editor settings to use for the post editor.
*
* @param {Object} settings EditorProvider settings prop.
* @param {boolean} hasTemplate Whether template mode is enabled.
* @param {Object} settings EditorProvider settings prop.
* @param {string} postType Editor root level post type.
* @param {string} postId Editor root level post ID.
*
* @return {Object} Block Editor Settings.
*/
function useBlockEditorSettings( settings, hasTemplate ) {
function useBlockEditorSettings( settings, postType, postId ) {
const {
reusableBlocks,
hasUploadPermissions,
canUseUnfilteredHTML,
userCanCreatePages,
pageOnFront,
pageForPosts,
postType,
userPatternCategories,
} = useSelect( ( select ) => {
const { canUserUseUnfilteredHTML, getCurrentPostType } =
select( editorStore );
const isWeb = Platform.OS === 'web';
const { canUser, getEntityRecord, getUserPatternCategories } =
select( coreStore );
} = useSelect(
( select ) => {
const isWeb = Platform.OS === 'web';
const {
canUser,
getRawEntityRecord,
getEntityRecord,
getUserPatternCategories,
getEntityRecords,
} = select( coreStore );

const siteSettings = canUser( 'read', 'settings' )
? getEntityRecord( 'root', 'site' )
: undefined;
const siteSettings = canUser( 'read', 'settings' )
? getEntityRecord( 'root', 'site' )
: undefined;

return {
canUseUnfilteredHTML: canUserUseUnfilteredHTML(),
reusableBlocks: isWeb
? select( coreStore ).getEntityRecords(
'postType',
'wp_block',
{ per_page: -1 }
)
: EMPTY_BLOCKS_LIST, // Reusable blocks are fetched in the native version of this hook.
hasUploadPermissions: canUser( 'create', 'media' ) ?? true,
userCanCreatePages: canUser( 'create', 'pages' ),
pageOnFront: siteSettings?.page_on_front,
pageForPosts: siteSettings?.page_for_posts,
postType: getCurrentPostType(),
userPatternCategories: getUserPatternCategories(),
};
}, [] );
return {
canUseUnfilteredHTML: getRawEntityRecord(
'postType',
postType,
postId
)?._links?.hasOwnProperty( 'wp:action-unfiltered-html' ),
reusableBlocks: isWeb
? getEntityRecords( 'postType', 'wp_block', {
per_page: -1,
} )
: EMPTY_BLOCKS_LIST, // Reusable blocks are fetched in the native version of this hook.
hasUploadPermissions: canUser( 'create', 'media' ) ?? true,
userCanCreatePages: canUser( 'create', 'pages' ),
pageOnFront: siteSettings?.page_on_front,
pageForPosts: siteSettings?.page_for_posts,
userPatternCategories: getUserPatternCategories(),
};
},
[ postType, postId ]
);

const settingsBlockPatterns =
settings.__experimentalAdditionalBlockPatterns ?? // WP 6.0
Expand Down Expand Up @@ -214,14 +223,20 @@ function useBlockEditorSettings( settings, hasTemplate ) {
fetchLinkSuggestions( search, searchOptions, settings ),
inserterMediaCategories,
__experimentalFetchRichUrlData: fetchUrlData,
// Todo: This only checks the top level post, not the post within a template or any other entity that can be edited.
// This might be better as a generic "canUser" selector.
__experimentalCanUserUseUnfilteredHTML: canUseUnfilteredHTML,
//Todo: this is only needed for native and should probably be removed.
__experimentalUndo: undo,
outlineMode: hasTemplate,
// Check whether we want all site editor frames to have outlines
// including the navigation / pattern / parts editors.
outlineMode: postType === 'wp_template',
// Check these two properties: they were not present in the site editor.
__experimentalCreatePageEntity: createPageEntity,
__experimentalUserCanCreatePages: userCanCreatePages,
pageOnFront,
pageForPosts,
__experimentalPreferPatternsOnRoot: hasTemplate,
__experimentalPreferPatternsOnRoot: postType === 'wp_template',
} ),
[
settings,
Expand All @@ -232,11 +247,11 @@ function useBlockEditorSettings( settings, hasTemplate ) {
blockPatternCategories,
canUseUnfilteredHTML,
undo,
hasTemplate,
createPageEntity,
userCanCreatePages,
pageOnFront,
pageForPosts,
postType,
]
);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@ import { store as editorStore } from '../../store';

const EMPTY_BLOCKS_LIST = [];

function useNativeBlockEditorSettings( settings, hasTemplate ) {
const editorSettings = useBlockEditorSettings( settings, hasTemplate );
function useNativeBlockEditorSettings( settings, postType, postId ) {
const editorSettings = useBlockEditorSettings( settings, postType, postId );
const supportReusableBlock = settings.capabilities?.reusableBlock === true;

const { reusableBlocks, isTitleSelected } = useSelect(
Expand Down
4 changes: 4 additions & 0 deletions packages/editor/src/private-apis.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,13 @@
import { ExperimentalEditorProvider } from './components/provider';
import { lock } from './lock-unlock';
import { EntitiesSavedStatesExtensible } from './components/entities-saved-states';
import useBlockEditorSettings from './components/provider/use-block-editor-settings';

export const privateApis = {};
lock( privateApis, {
ExperimentalEditorProvider,
EntitiesSavedStatesExtensible,

// This is a temporary private API while we're updating the site editor to use EditorProvider.
useBlockEditorSettings,
} );
Loading