Skip to content

Commit

Permalink
Migrate store and actions from editor package to fields package
Browse files Browse the repository at this point in the history
  • Loading branch information
gigitux committed Sep 12, 2024
1 parent f073eb1 commit 67ff043
Show file tree
Hide file tree
Showing 30 changed files with 5,336 additions and 50,407 deletions.
55,042 changes: 4,659 additions & 50,383 deletions package-lock.json

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions packages/editor/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@
"@wordpress/deprecated": "file:../deprecated",
"@wordpress/dom": "file:../dom",
"@wordpress/element": "file:../element",
"@wordpress/fields": "file:../fields",
"@wordpress/hooks": "file:../hooks",
"@wordpress/html-entities": "file:../html-entities",
"@wordpress/i18n": "file:../i18n",
Expand Down
21 changes: 19 additions & 2 deletions packages/editor/src/components/post-actions/actions.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
*/
import { useDispatch, useSelect } from '@wordpress/data';
import { useMemo, useEffect } from '@wordpress/element';
import { store as fieldsStore } from '@wordpress/fields';

/**
* Internal dependencies
Expand All @@ -14,17 +15,33 @@ export function usePostActions( { postType, onActionPerformed, context } ) {
const { defaultActions } = useSelect(
( select ) => {
const { getEntityActions } = unlock( select( editorStore ) );
const { getEntityActions: getEntityActionsFromFieldsPackage } =
select( fieldsStore );

return {
defaultActions: getEntityActions( 'postType', postType ),
defaultActions: [
...getEntityActions( 'postType', postType ),
...getEntityActionsFromFieldsPackage(
'postType',
postType
),
],
};
},
[ postType ]
);

const { registerPostTypeActions } = unlock( useDispatch( editorStore ) );
const { registerPostTypeActions: registerPostTypeActionFromFieldsPackage } =
useDispatch( fieldsStore );
useEffect( () => {
registerPostTypeActions( postType );
}, [ registerPostTypeActions, postType ] );
registerPostTypeActionFromFieldsPackage( postType );
}, [
registerPostTypeActions,
postType,
registerPostTypeActionFromFieldsPackage,
] );

return useMemo( () => {
// Filter actions based on provided context. If not provided
Expand Down
18 changes: 1 addition & 17 deletions packages/editor/src/dataviews/store/private-actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,21 +9,16 @@ import { doAction } from '@wordpress/hooks';
* Internal dependencies
*/
import deletePost from '../actions/delete-post';
import duplicatePattern from '../actions/duplicate-pattern';
import duplicateTemplatePart from '../actions/duplicate-template-part';
import exportPattern from '../actions/export-pattern';
import resetPost from '../actions/reset-post';
import trashPost from '../actions/trash-post';
import permanentlyDeletePost from '../actions/permanently-delete-post';
import renamePost from '../actions/rename-post';
import reorderPage from '../actions/reorder-page';
import restorePost from '../actions/restore-post';
import type { PostType } from '../types';
import { store as editorStore } from '../../store';
import { unlock } from '../../lock-unlock';
import duplicatePost from '../actions/duplicate-post';
import viewPostRevisions from '../actions/view-post-revisions';
import viewPost from '../actions/view-post';
import permanentlyDeletePost from '../actions/permanently-delete-post';

export function registerEntityAction< Item >(
kind: string,
Expand Down Expand Up @@ -90,10 +85,6 @@ export const registerPostTypeActions =
.getCurrentTheme();

const actions = [
postTypeConfig.viewable ? viewPost : undefined,
!! postTypeConfig?.supports?.revisions
? viewPostRevisions
: undefined,
// @ts-ignore
globalThis.IS_GUTENBERG_PLUGIN
? ! [ 'wp_template', 'wp_block', 'wp_template_part' ].includes(
Expand All @@ -107,14 +98,7 @@ export const registerPostTypeActions =
currentTheme?.is_block_theme
? duplicateTemplatePart
: undefined,
canCreate && postTypeConfig.slug === 'wp_block'
? duplicatePattern
: undefined,
postTypeConfig.supports?.title ? renamePost : undefined,
postTypeConfig?.supports?.[ 'page-attributes' ]
? reorderPage
: undefined,
postTypeConfig.slug === 'wp_block' ? exportPattern : undefined,
resetPost,
restorePost,
deletePost,
Expand Down
1 change: 1 addition & 0 deletions packages/editor/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
{ "path": "../deprecated" },
{ "path": "../dom" },
{ "path": "../element" },
{ "path": "../fields" },
{ "path": "../hooks" },
{ "path": "../html-entities" },
{ "path": "../i18n" },
Expand Down
32 changes: 31 additions & 1 deletion packages/fields/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,37 @@ npm install @wordpress/fields --save

<!-- START TOKEN(Autogenerated API docs) -->

Nothing to document.
### orderField

Undocumented declaration.

### store

Store definition for the editor namespace.

_Related_

- <https://github.com/WordPress/gutenberg/blob/HEAD/packages/data/README.md#createReduxStore>

_Type_

- `Object`

### storeConfig

Post editor data store configuration.

_Related_

- <https://github.com/WordPress/gutenberg/blob/HEAD/packages/data/README.md#registerStore>

_Type_

- `Object`

### titleField

Undocumented declaration.

<!-- END TOKEN(Autogenerated API docs) -->

Expand Down
22 changes: 21 additions & 1 deletion packages/fields/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,27 @@
"src/**/*.scss"
],
"dependencies": {
"@babel/runtime": "^7.16.0"
"@babel/runtime": "^7.16.0",
"@wordpress/blob": "file:../blob",
"@wordpress/blocks": "file:../blocks",
"@wordpress/components": "file:../components",
"@wordpress/compose": "file:../compose",
"@wordpress/core-data": "file:../core-data",
"@wordpress/data": "file:../data",
"@wordpress/dataviews": "file:../dataviews",
"@wordpress/element": "file:../element",
"@wordpress/hooks": "file:../hooks",
"@wordpress/html-entities": "file:../html-entities",
"@wordpress/i18n": "file:../i18n",
"@wordpress/icons": "file:../icons",
"@wordpress/notices": "file:../notices",
"@wordpress/patterns": "file:../patterns",
"@wordpress/primitives": "file:../primitives",
"@wordpress/private-apis": "file:../private-apis",
"@wordpress/url": "file:../url",
"@wordpress/warning": "file:../warning",
"change-case": "4.1.2",
"client-zip": "^2.4.5"
},
"peerDependencies": {
"react": "^18.0.0"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import type { Action } from '@wordpress/dataviews';
/**
* Internal dependencies
*/
import { unlock } from '../../lock-unlock';
import { unlock } from '../lock-unlock';
import type { Pattern } from '../types';

// Patterns.
Expand Down
174 changes: 174 additions & 0 deletions packages/fields/src/actions/duplicate-post.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,174 @@
/**
* WordPress dependencies
*/
import { useDispatch } from '@wordpress/data';
import { decodeEntities } from '@wordpress/html-entities';
import { store as coreStore } from '@wordpress/core-data';
import { __, sprintf, _x } from '@wordpress/i18n';
import { store as noticesStore } from '@wordpress/notices';
import { useState } from '@wordpress/element';
import { DataForm } from '@wordpress/dataviews';
import {
Button,
__experimentalHStack as HStack,
__experimentalVStack as VStack,
} from '@wordpress/components';
import type { Action } from '@wordpress/dataviews';

/**
* Internal dependencies
*/
import { getItemTitle } from './utils';
import type { CoreDataError, BasePost } from '../types';
import { titleField } from '../fields';

const fields = [ titleField ];
const formDuplicateAction = {
fields: [ 'title' ],
};

const duplicatePost: Action< BasePost > = {
id: 'duplicate-post',
label: _x( 'Duplicate', 'action label' ),
isEligible( { status } ) {
return status !== 'trash';
},
RenderModal: ( { items, closeModal, onActionPerformed } ) => {
const [ item, setItem ] = useState< BasePost >( {
...items[ 0 ],
title: sprintf(
/* translators: %s: Existing template title */
__( '%s (Copy)' ),
getItemTitle( items[ 0 ] )
),
} );

const [ isCreatingPage, setIsCreatingPage ] = useState( false );
const { saveEntityRecord } = useDispatch( coreStore );
const { createSuccessNotice, createErrorNotice } =
useDispatch( noticesStore );

async function createPage( event: React.FormEvent ) {
event.preventDefault();

if ( isCreatingPage ) {
return;
}

const newItemOject = {
status: 'draft',
title: item.title,
slug: item.title || __( 'No title' ),
comment_status: item.comment_status,
content:
typeof item.content === 'string'
? item.content
: item.content.raw,
excerpt:
typeof item.excerpt === 'string'
? item.excerpt
: item.excerpt?.raw,
meta: item.meta,
parent: item.parent,
password: item.password,
template: item.template,
format: item.format,
featured_media: item.featured_media,
menu_order: item.menu_order,
ping_status: item.ping_status,
};
const assignablePropertiesPrefix = 'wp:action-assign-';
// Get all the properties that the current user is able to assign normally author, categories, tags,
// and custom taxonomies.
const assignableProperties = Object.keys( item?._links || {} )
.filter( ( property ) =>
property.startsWith( assignablePropertiesPrefix )
)
.map( ( property ) =>
property.slice( assignablePropertiesPrefix.length )
);
assignableProperties.forEach( ( property ) => {
if ( item.hasOwnProperty( property ) ) {
// @ts-ignore
newItemOject[ property ] = item[ property ];
}
} );
setIsCreatingPage( true );
try {
const newItem = await saveEntityRecord(
'postType',
item.type,
newItemOject,
{ throwOnError: true }
);

createSuccessNotice(
sprintf(
// translators: %s: Title of the created template e.g: "Category".
__( '"%s" successfully created.' ),
decodeEntities( newItem.title?.rendered || item.title )
),
{
id: 'duplicate-post-action',
type: 'snackbar',
}
);

if ( onActionPerformed ) {
onActionPerformed( [ newItem ] );
}
} catch ( error ) {
const typedError = error as CoreDataError;
const errorMessage =
typedError.message && typedError.code !== 'unknown_error'
? typedError.message
: __( 'An error occurred while duplicating the page.' );

createErrorNotice( errorMessage, {
type: 'snackbar',
} );
} finally {
setIsCreatingPage( false );
closeModal?.();
}
}

return (
<form onSubmit={ createPage }>
<VStack spacing={ 3 }>
<DataForm
data={ item }
fields={ fields }
form={ formDuplicateAction }
onChange={ ( changes ) =>
setItem( ( prev ) => ( {
...prev,
...changes,
} ) )
}
/>
<HStack spacing={ 2 } justify="end">
<Button
variant="tertiary"
onClick={ closeModal }
__next40pxDefaultSize
>
{ __( 'Cancel' ) }
</Button>
<Button
variant="primary"
type="submit"
isBusy={ isCreatingPage }
aria-disabled={ isCreatingPage }
__next40pxDefaultSize
>
{ _x( 'Duplicate', 'action label' ) }
</Button>
</HStack>
</VStack>
</form>
);
},
};

export default duplicatePost;
21 changes: 21 additions & 0 deletions packages/fields/src/actions/utils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
/**
* WordPress dependencies
*/
import { decodeEntities } from '@wordpress/html-entities';
/**
* Internal dependencies
*/
import type { Post } from '../types';

export function getItemTitle( item: Post ) {
if ( typeof item.title === 'string' ) {
return decodeEntities( item.title );
}
if ( 'rendered' in item.title ) {
return decodeEntities( item.title.rendered );
}
if ( 'raw' in item.title ) {
return decodeEntities( item.title.raw );
}
return '';
}
File renamed without changes.
2 changes: 2 additions & 0 deletions packages/fields/src/fields/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export { default as titleField } from './title';
export { default as orderField } from './order';
Loading

0 comments on commit 67ff043

Please sign in to comment.