Skip to content

Commit

Permalink
Patterns: edit source pattern in focus mode in post editor (#57036)
Browse files Browse the repository at this point in the history
* Move synced patterns global editing to focus mode in editor

* Add back padding to focus mode and notice to indicate global nature of changes

* Update experiment wording

* Move the edit mode function to the editor package

* Change label on edit button

* Remove `pattern-only` mode

* Revert more pattern-only mode code

* Another revert

* Add basic routing to post editor

* Add document bar and padding

* Fix initialisation of post id and post type

* Only show header bar and padding if edit mode is set to focused

* refine check for edit mode

* Remove routing

* Switch to a simple postHistory array for switching back from pattern editing

* move postHistory to a ref

* Move history settings into hook

* refine history stack slightly

* Refactor `usePostHistory` to keep all history in a single array. Use useReducer.

* fix edit post specific classname

* Fix iframe classes

* Editing in focus mode - pass onSelectPost as editor setting

* Minor tidy ups

* Move from onSelectPost to getPostLinkProps and add new hook in site editor instead of trying to reuse useLink

* Fixes from code review

* Another fix from review

* Add optional state param to call to history.push

* Remove code duplication in usePostLinkProps hook

* make sure block editing mode set to default when going to edit original

* Tidy up edit mode assignment

* Don't adjust the url if moving to focused mode of entity from post

* Change how updating of url is bypassed when switching to focused mode editing

---------

Co-authored-by: Daniel Richards <daniel.richards@automattic.com>
  • Loading branch information
glendaviesnz and talldan committed Jan 3, 2024
1 parent f08b307 commit 55a170b
Show file tree
Hide file tree
Showing 19 changed files with 298 additions and 85 deletions.
4 changes: 2 additions & 2 deletions lib/experiments-page.php
Original file line number Diff line number Diff line change
Expand Up @@ -140,12 +140,12 @@ function gutenberg_initialize_experiments_settings() {

add_settings_field(
'gutenberg-pattern-partial-syncing',
__( 'Synced patterns partial syncing', 'gutenberg' ),
__( 'Pattern overrides', 'gutenberg' ),
'gutenberg_display_experiment_field',
'gutenberg-experiments',
'gutenberg_experiments_section',
array(
'label' => __( 'Test partial syncing of patterns', 'gutenberg' ),
'label' => __( 'Test overrides in synced patterns', 'gutenberg' ),
'id' => 'gutenberg-pattern-partial-syncing',
)
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,9 @@ const BlockInspector = ( { showNoBlockSelectedMessage = true } ) => {
blockType: _blockType,
topLevelLockedBlock:
__unstableGetContentLockingParent( _selectedBlockClientId ) ||
( getTemplateLock( _selectedBlockClientId ) === 'contentOnly'
( getTemplateLock( _selectedBlockClientId ) === 'contentOnly' ||
( _selectedBlockName === 'core/block' &&
window.__experimentalPatternPartialSyncing )
? _selectedBlockClientId
: undefined ),
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ export function useInBetweenInserter() {
getTemplateLock,
__unstableIsWithinBlockOverlay,
getBlockEditingMode,
getBlockName,
} = useSelect( blockEditorStore );
const { showInsertionPoint, hideInsertionPoint } =
useDispatch( blockEditorStore );
Expand Down Expand Up @@ -75,7 +76,9 @@ export function useInBetweenInserter() {

if (
getTemplateLock( rootClientId ) ||
getBlockEditingMode( rootClientId ) === 'disabled'
getBlockEditingMode( rootClientId ) === 'disabled' ||
( getBlockName( rootClientId ) === 'core/block' &&
window.__experimentalPatternPartialSyncing )
) {
return;
}
Expand Down
7 changes: 5 additions & 2 deletions packages/block-editor/src/store/selectors.js
Original file line number Diff line number Diff line change
Expand Up @@ -2742,8 +2742,11 @@ export const __unstableGetContentLockingParent = createSelector(
while ( state.blocks.parents.has( current ) ) {
current = state.blocks.parents.get( current );
if (
current &&
getTemplateLock( state, current ) === 'contentOnly'
( current &&
getBlockName( state, current ) === 'core/block' &&
window.__experimentalPatternPartialSyncing ) ||
( current &&
getTemplateLock( state, current ) === 'contentOnly' )
) {
result = current;
}
Expand Down
96 changes: 68 additions & 28 deletions packages/block-library/src/block/edit.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,24 +8,24 @@ import classnames from 'classnames';
*/
import { useRegistry, useSelect, useDispatch } from '@wordpress/data';
import { useRef, useMemo, useEffect } from '@wordpress/element';
import { useEntityProp, useEntityRecord } from '@wordpress/core-data';
import { useEntityRecord, store as coreStore } from '@wordpress/core-data';
import {
Placeholder,
Spinner,
TextControl,
PanelBody,
ToolbarButton,
ToolbarGroup,
} from '@wordpress/components';
import { __ } from '@wordpress/i18n';
import {
useInnerBlocksProps,
__experimentalRecursionProvider as RecursionProvider,
__experimentalUseHasRecursion as useHasRecursion,
InnerBlocks,
InspectorControls,
useBlockProps,
Warning,
privateApis as blockEditorPrivateApis,
store as blockEditorStore,
BlockControls,
} from '@wordpress/block-editor';
import { getBlockSupport, parse } from '@wordpress/blocks';

Expand Down Expand Up @@ -132,6 +132,15 @@ function getOverridesFromBlocks( blocks, defaultValues ) {
return Object.keys( overrides ).length > 0 ? overrides : undefined;
}

function setBlockEditMode( setEditMode, blocks, mode ) {
blocks.forEach( ( block ) => {
const editMode =
mode || ( isPartiallySynced( block ) ? 'contentOnly' : 'disabled' );
setEditMode( block.clientId, editMode );
setBlockEditMode( setEditMode, block.innerBlocks, mode );
} );
}

export default function ReusableBlockEdit( {
name,
attributes: { ref, overrides },
Expand All @@ -149,14 +158,51 @@ export default function ReusableBlockEdit( {
const isMissing = hasResolved && ! record;
const initialOverrides = useRef( overrides );
const defaultValuesRef = useRef( {} );

const {
replaceInnerBlocks,
__unstableMarkNextChangeAsNotPersistent,
setBlockEditingMode,
} = useDispatch( blockEditorStore );
const { getBlockEditingMode } = useSelect( blockEditorStore );
const { syncDerivedUpdates } = unlock( useDispatch( blockEditorStore ) );

const { innerBlocks, userCanEdit, getBlockEditingMode, getPostLinkProps } =
useSelect(
( select ) => {
const { canUser } = select( coreStore );
const {
getBlocks,
getBlockEditingMode: editingMode,
getSettings,
} = select( blockEditorStore );
const blocks = getBlocks( patternClientId );
const canEdit = canUser( 'update', 'blocks', ref );

// For editing link to the site editor if the theme and user permissions support it.
return {
innerBlocks: blocks,
userCanEdit: canEdit,
getBlockEditingMode: editingMode,
getPostLinkProps:
getSettings().__experimentalGetPostLinkProps,
};
},
[ patternClientId, ref ]
);

const editOriginalProps = getPostLinkProps
? getPostLinkProps( {
postId: ref,
postType: 'wp_block',
canvas: 'edit',
} )
: {};

useEffect(
() => setBlockEditMode( setBlockEditingMode, innerBlocks ),
[ innerBlocks, setBlockEditingMode ]
);

// Apply the initial overrides from the pattern block to the inner blocks.
useEffect( () => {
const initialBlocks =
Expand Down Expand Up @@ -193,18 +239,6 @@ export default function ReusableBlockEdit( {
syncDerivedUpdates,
] );

const innerBlocks = useSelect(
( select ) => select( blockEditorStore ).getBlocks( patternClientId ),
[ patternClientId ]
);

const [ title, setTitle ] = useEntityProp(
'postType',
'wp_block',
'title',
ref
);

const { alignment, layout } = useInferredLayout(
innerBlocks,
parentLayout
Expand Down Expand Up @@ -247,6 +281,11 @@ export default function ReusableBlockEdit( {
}, blockEditorStore );
}, [ syncDerivedUpdates, patternClientId, registry, setAttributes ] );

const handleEditOriginal = ( event ) => {
setBlockEditMode( setBlockEditingMode, innerBlocks, 'default' );
editOriginalProps.onClick( event );
};

let children = null;

if ( hasAlreadyRendered ) {
Expand Down Expand Up @@ -275,17 +314,18 @@ export default function ReusableBlockEdit( {

return (
<RecursionProvider uniqueId={ ref }>
<InspectorControls>
<PanelBody>
<TextControl
label={ __( 'Name' ) }
value={ title }
onChange={ setTitle }
__nextHasNoMarginBottom
__next40pxDefaultSize
/>
</PanelBody>
</InspectorControls>
{ userCanEdit && editOriginalProps && (
<BlockControls>
<ToolbarGroup>
<ToolbarButton
href={ editOriginalProps.href }
onClick={ handleEditOriginal }
>
{ __( 'Edit original' ) }
</ToolbarButton>
</ToolbarGroup>
</BlockControls>
) }
{ children === null ? (
<div { ...innerBlocksProps } />
) : (
Expand Down
6 changes: 4 additions & 2 deletions packages/edit-post/src/components/browser-url/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,8 @@ export class BrowserURL extends Component {
}

componentDidUpdate( prevProps ) {
const { postId, postStatus, postType, isSavingPost } = this.props;
const { postId, postStatus, postType, isSavingPost, hasHistory } =
this.props;
const { historyId } = this.state;

// Posts are still dirty while saving so wait for saving to finish
Expand All @@ -56,7 +57,8 @@ export class BrowserURL extends Component {
if (
( postId !== prevProps.postId || postId !== historyId ) &&
postStatus !== 'auto-draft' &&
postId
postId &&
! hasHistory
) {
this.setBrowserURL( postId );
}
Expand Down
4 changes: 3 additions & 1 deletion packages/edit-post/src/components/header/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@ function Header( { setEntitiesSavedStatesCallback } ) {
isEditingTemplate,
isPublishSidebarOpened,
showIconLabels,
hasHistory,
} = useSelect( ( select ) => {
const { get: getPreference } = select( preferencesStore );
const { getEditorMode } = select( editPostStore );
Expand All @@ -76,6 +77,7 @@ function Header( { setEntitiesSavedStatesCallback } ) {
hasBlockSelection:
!! select( blockEditorStore ).getBlockSelectionStart(),
hasActiveMetaboxes: select( editPostStore ).hasMetaBoxes(),
hasHistory: !! select( editorStore ).getEditorSettings().goBack,
isEditingTemplate:
select( editorStore ).getRenderingMode() === 'template-only',
isPublishSidebarOpened:
Expand Down Expand Up @@ -161,7 +163,7 @@ function Header( { setEntitiesSavedStatesCallback } ) {
isLargeViewport,
} ) }
>
{ isEditingTemplate && <DocumentBar /> }
{ ( isEditingTemplate || hasHistory ) && <DocumentBar /> }
</div>
</motion.div>
<motion.div
Expand Down
4 changes: 3 additions & 1 deletion packages/edit-post/src/components/layout/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,7 @@ function Layout() {
showMetaBoxes,
showMostUsedBlocks,
documentLabel,
hasHistory,
} = useSelect( ( select ) => {
const { getEditorSettings, getPostTypeLabel } = select( editorStore );
const editorSettings = getEditorSettings();
Expand Down Expand Up @@ -201,6 +202,7 @@ function Layout() {
documentLabel: postTypeLabel || _x( 'Document', 'noun' ),
hasBlockSelected:
!! select( blockEditorStore ).getBlockSelectionStart(),
hasHistory: !! getEditorSettings().goBack,
};
}, [] );

Expand Down Expand Up @@ -290,7 +292,7 @@ function Layout() {
return (
<>
<FullscreenMode isActive={ isFullscreenActive } />
<BrowserURL />
<BrowserURL hasHistory={ hasHistory } />
<UnsavedChangesWarning />
<AutosaveMonitor />
<LocalAutosaveMonitor />
Expand Down
44 changes: 34 additions & 10 deletions packages/edit-post/src/editor.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,11 +23,22 @@ import Layout from './components/layout';
import EditorInitialization from './components/editor-initialization';
import { store as editPostStore } from './store';
import { unlock } from './lock-unlock';
import usePostHistory from './hooks/use-post-history';

const { ExperimentalEditorProvider } = unlock( editorPrivateApis );

function Editor( { postId, postType, settings, initialEdits, ...props } ) {
function Editor( {
postId: initialPostId,
postType: initialPostType,
settings,
initialEdits,
...props
} ) {
const isLargeViewport = useViewportMatch( 'medium' );
const { currentPost, getPostLinkProps, goBack } = usePostHistory(
initialPostId,
initialPostType
);

const {
hasFixedToolbar,
Expand All @@ -52,22 +63,31 @@ function Editor( { postId, postType, settings, initialEdits, ...props } ) {
const { getEditorSettings } = select( editorStore );
const { getBlockTypes } = select( blocksStore );
const isTemplate = [ 'wp_template', 'wp_template_part' ].includes(
postType
currentPost.postType
);
// Ideally the initializeEditor function should be called using the ID of the REST endpoint.
// to avoid the special case.
let postObject;
if ( isTemplate ) {
const posts = getEntityRecords( 'postType', postType, {
wp_id: postId,
} );
const posts = getEntityRecords(
'postType',
currentPost.postType,
{
wp_id: currentPost.postId,
}
);
postObject = posts?.[ 0 ];
} else {
postObject = getEntityRecord( 'postType', postType, postId );
postObject = getEntityRecord(
'postType',
currentPost.postType,
currentPost.postId
);
}
const supportsTemplateMode =
getEditorSettings().supportsTemplateMode;
const isViewable = getPostType( postType )?.viewable ?? false;
const isViewable =
getPostType( currentPost.postType )?.viewable ?? false;
const canEditTemplate = canUser( 'create', 'templates' );
return {
hasFixedToolbar:
Expand All @@ -89,14 +109,16 @@ function Editor( { postId, postType, settings, initialEdits, ...props } ) {
post: postObject,
};
},
[ postType, postId, isLargeViewport ]
[ currentPost.postType, currentPost.postId, isLargeViewport ]
);

const { updatePreferredStyleVariations } = useDispatch( editPostStore );

const editorSettings = useMemo( () => {
const result = {
...settings,
getPostLinkProps,
goBack,
__experimentalPreferredStyleVariations: {
value: preferredStyleVariations,
onChange: updatePreferredStyleVariations,
Expand Down Expand Up @@ -134,11 +156,13 @@ function Editor( { postId, postType, settings, initialEdits, ...props } ) {
hasInlineToolbar,
focusMode,
isDistractionFree,
keepCaretInsideBlock,
hiddenBlockTypes,
blockTypes,
preferredStyleVariations,
updatePreferredStyleVariations,
keepCaretInsideBlock,
getPostLinkProps,
goBack,
] );

if ( ! post ) {
Expand All @@ -157,7 +181,7 @@ function Editor( { postId, postType, settings, initialEdits, ...props } ) {
>
<ErrorBoundary>
<CommandMenu />
<EditorInitialization postId={ postId } />
<EditorInitialization postId={ currentPost.postId } />
<Layout />
</ErrorBoundary>
<PostLockedModal />
Expand Down
Loading

0 comments on commit 55a170b

Please sign in to comment.