diff --git a/lib/experimental/content-guidelines/class-gutenberg-content-guidelines-post-type.php b/lib/experimental/content-guidelines/class-gutenberg-content-guidelines-post-type.php
index 4b281db11bbce6..6758498bee6071 100644
--- a/lib/experimental/content-guidelines/class-gutenberg-content-guidelines-post-type.php
+++ b/lib/experimental/content-guidelines/class-gutenberg-content-guidelines-post-type.php
@@ -71,8 +71,8 @@ class Gutenberg_Content_Guidelines_Post_Type {
public static function register() {
$args = array(
'labels' => array(
- 'name' => __( 'Content Guidelines', 'gutenberg' ),
- 'singular_name' => __( 'Content Guidelines', 'gutenberg' ),
+ 'name' => __( 'Guidelines', 'gutenberg' ),
+ 'singular_name' => __( 'Guidelines', 'gutenberg' ),
),
'public' => false,
'publicly_queryable' => false,
diff --git a/lib/experimental/content-guidelines/class-gutenberg-content-guidelines-rest-controller.php b/lib/experimental/content-guidelines/class-gutenberg-content-guidelines-rest-controller.php
index f1d65ba4cf40fc..03d502f4001c21 100644
--- a/lib/experimental/content-guidelines/class-gutenberg-content-guidelines-rest-controller.php
+++ b/lib/experimental/content-guidelines/class-gutenberg-content-guidelines-rest-controller.php
@@ -111,7 +111,7 @@ public function get_guidelines_permissions_check( $request ) { // phpcs:ignore V
if ( ! current_user_can( $post_type->cap->read ) ) {
return new WP_Error(
'rest_forbidden',
- __( 'Sorry, you are not allowed to view content guidelines.', 'gutenberg' ),
+ __( 'Sorry, you are not allowed to view the guidelines.', 'gutenberg' ),
array( 'status' => rest_authorization_required_code() )
);
}
@@ -161,14 +161,14 @@ public function create_item( $request ) {
if ( $existing ) {
return new WP_Error(
'rest_guidelines_exists',
- __( 'Content guidelines already exist. Use PATCH to update.', 'gutenberg' ),
+ __( 'Guidelines already exist. Use PATCH to update.', 'gutenberg' ),
array( 'status' => 400 )
);
}
$prepared = $this->prepare_item_for_database( $request );
$prepared->post_type = $this->post_type;
- $prepared->post_title = __( 'Content Guidelines', 'gutenberg' );
+ $prepared->post_title = __( 'Guidelines', 'gutenberg' );
if ( ! isset( $prepared->post_status ) ) {
$prepared->post_status = 'draft';
diff --git a/lib/experimental/content-guidelines/class-gutenberg-content-guidelines-revisions-controller.php b/lib/experimental/content-guidelines/class-gutenberg-content-guidelines-revisions-controller.php
index a77e0bfcb2120f..4045f77eefe7e2 100644
--- a/lib/experimental/content-guidelines/class-gutenberg-content-guidelines-revisions-controller.php
+++ b/lib/experimental/content-guidelines/class-gutenberg-content-guidelines-revisions-controller.php
@@ -103,6 +103,15 @@ public function prepare_item_for_response( $item, $request ) {
$response->set_data( $data );
}
+ // Add embeddable author link to get author name in revision history screen
+ if ( ! empty( $item->post_author ) ) {
+ $response->add_link(
+ 'author',
+ rest_url( 'wp/v2/users/' . $item->post_author ),
+ array( 'embeddable' => true )
+ );
+ }
+
return $response;
}
@@ -137,7 +146,7 @@ public function restore_revision_permissions_check( $request ) {
if ( ! $parent || $this->parent_post_type !== $parent->post_type ) {
return new WP_Error(
'rest_post_not_found',
- __( 'Content guidelines not found.', 'gutenberg' ),
+ __( 'Guidelines not found.', 'gutenberg' ),
array( 'status' => 404 )
);
}
@@ -169,7 +178,7 @@ public function restore_revision( $request ) {
if ( ! $parent || $this->parent_post_type !== $parent->post_type ) {
return new WP_Error(
'rest_post_not_found',
- __( 'Content guidelines not found.', 'gutenberg' ),
+ __( 'Guidelines not found.', 'gutenberg' ),
array( 'status' => 404 )
);
}
diff --git a/lib/experimental/content-guidelines/load.php b/lib/experimental/content-guidelines/load.php
index e72f17eb4e42da..10447caf00c1a4 100644
--- a/lib/experimental/content-guidelines/load.php
+++ b/lib/experimental/content-guidelines/load.php
@@ -15,8 +15,8 @@
function gutenberg_register_content_guidelines_settings_submenu() {
add_submenu_page(
'options-general.php',
- __( 'Content Guidelines', 'gutenberg' ),
- __( 'Content Guidelines', 'gutenberg' ),
+ __( 'Guidelines', 'gutenberg' ),
+ __( 'Guidelines', 'gutenberg' ),
'manage_options',
'content-guidelines-wp-admin',
'gutenberg_content_guidelines_wp_admin_render_page'
diff --git a/lib/experiments-page.php b/lib/experiments-page.php
index 99baa773955adf..c42e758ca02713 100644
--- a/lib/experiments-page.php
+++ b/lib/experiments-page.php
@@ -211,12 +211,12 @@ function gutenberg_initialize_experiments_settings() {
add_settings_field(
'gutenberg-content-guidelines',
- __( 'Content Guidelines', 'gutenberg' ),
+ __( 'Guidelines', 'gutenberg' ),
'gutenberg_display_experiment_field',
'gutenberg-experiments',
'gutenberg_experiments_section',
array(
- 'label' => __( 'Enables Content Guidelines feature for managing editorial voice and tone guidelines under Settings.', 'gutenberg' ),
+ 'label' => __( 'Enables guidelines feature for managing editorial voice and tone guidelines under Settings.', 'gutenberg' ),
'id' => 'gutenberg-content-guidelines',
)
);
diff --git a/package-lock.json b/package-lock.json
index f4b34748741872..f048abcce4b29a 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -62987,11 +62987,13 @@
"@wordpress/admin-ui": "file:../../packages/admin-ui",
"@wordpress/api-fetch": "file:../../packages/api-fetch",
"@wordpress/base-styles": "file:../../packages/base-styles",
+ "@wordpress/blob": "file:../../packages/blob",
"@wordpress/block-library": "file:../../packages/block-library",
"@wordpress/blocks": "file:../../packages/blocks",
"@wordpress/components": "file:../../packages/components",
"@wordpress/data": "file:../../packages/data",
"@wordpress/dataviews": "file:../../packages/dataviews",
+ "@wordpress/date": "file:../../packages/date",
"@wordpress/element": "file:../../packages/element",
"@wordpress/i18n": "file:../../packages/i18n",
"@wordpress/icons": "file:../../packages/icons",
diff --git a/routes/content-guidelines/api.ts b/routes/content-guidelines/api.ts
index 32f38a5a010030..6e2b97af99b27c 100644
--- a/routes/content-guidelines/api.ts
+++ b/routes/content-guidelines/api.ts
@@ -2,13 +2,36 @@
* WordPress dependencies
*/
import apiFetch from '@wordpress/api-fetch';
+import { downloadBlob } from '@wordpress/blob';
import { dispatch, select } from '@wordpress/data';
+import { __ } from '@wordpress/i18n';
+import { store as noticesStore } from '@wordpress/notices';
/**
* Internal dependencies
*/
import { STORE_NAME } from './store';
-import type { Categories, RestGuidelinesResponse } from './types';
+import type {
+ Categories,
+ RestGuidelinesResponse,
+ GuidelinesImportData,
+ ContentGuidelinesRevision,
+} from './types';
+
+const FLAT_CATEGORIES = [ 'site', 'copy', 'images', 'additional' ] as const;
+
+function isValidGuidelinesImport(
+ data: unknown
+): data is GuidelinesImportData {
+ return (
+ !! data &&
+ typeof data === 'object' &&
+ 'guideline_categories' in data &&
+ typeof ( data as Record< string, unknown > ).guideline_categories ===
+ 'object' &&
+ ( data as Record< string, unknown > ).guideline_categories !== null
+ );
+}
export async function fetchContentGuidelines(): Promise< RestGuidelinesResponse > {
const { setFromResponse } = dispatch( STORE_NAME ) as {
@@ -83,3 +106,164 @@ export async function saveContentGuidelines(): Promise< RestGuidelinesResponse >
return response;
}
+
+/**
+ * Opens file selector, reads the selected file and imports the content guidelines.
+ * @param file Content Guidelines JSON file
+ */
+export async function importContentGuidelines( file: File ): Promise< void > {
+ // @ts-ignore
+ const { setGuideline, setBlockGuideline } = dispatch( STORE_NAME );
+ const { createSuccessNotice } = dispatch( noticesStore );
+
+ const parsed: unknown = JSON.parse( await file.text() );
+
+ if ( ! isValidGuidelinesImport( parsed ) ) {
+ throw new Error(
+ __(
+ 'Check that your file contains valid JSON markup and try again.'
+ )
+ );
+ }
+
+ const guidelinesStore = select( STORE_NAME ) as unknown as {
+ getAllGuidelines: () => Categories;
+ getBlockGuidelines: () => Record< string, string >;
+ };
+ const previousCategories = guidelinesStore.getAllGuidelines();
+ const previousBlocks = { ...guidelinesStore.getBlockGuidelines() };
+
+ const { guideline_categories: contentGuidelinesCategories } = parsed;
+
+ FLAT_CATEGORIES.forEach( ( guidelineCategory ) => {
+ const guidelines =
+ contentGuidelinesCategories[ guidelineCategory ]?.guidelines;
+ if ( typeof guidelines === 'string' ) {
+ setGuideline( guidelineCategory, guidelines );
+ }
+ } );
+
+ const blocksData = contentGuidelinesCategories.blocks;
+ if ( blocksData && typeof blocksData === 'object' ) {
+ Object.entries( blocksData ).forEach( ( [ blockName, blockData ] ) => {
+ if ( blockData && typeof blockData.guidelines === 'string' ) {
+ setBlockGuideline( blockName, blockData.guidelines );
+ }
+ } );
+ }
+
+ try {
+ await saveContentGuidelines();
+ createSuccessNotice( __( 'Guidelines imported.' ), {
+ type: 'snackbar',
+ } );
+ } catch ( error ) {
+ FLAT_CATEGORIES.forEach( ( cat ) => {
+ setGuideline( cat, previousCategories[ cat ] ?? '' );
+ } );
+
+ const currentBlocks = guidelinesStore.getBlockGuidelines();
+ Object.keys( currentBlocks ).forEach( ( blockName ) =>
+ setBlockGuideline( blockName, '' )
+ );
+ Object.entries( previousBlocks ).forEach( ( [ blockName, value ] ) =>
+ setBlockGuideline( blockName, value )
+ );
+
+ throw error;
+ }
+}
+
+/**
+ * Exports the content guidelines as a JSON file.
+ */
+export function exportContentGuidelines(): void {
+ const { createSuccessNotice } = dispatch( noticesStore );
+
+ const guidelinesStore = select( STORE_NAME ) as unknown as {
+ getAllGuidelines: () => Categories;
+ getBlockGuidelines: () => Record< string, string >;
+ };
+ const contentGuidelinesCategories = guidelinesStore.getAllGuidelines();
+ const blockGuidelines = guidelinesStore.getBlockGuidelines();
+
+ const data = {
+ guideline_categories: {
+ ...Object.fromEntries(
+ FLAT_CATEGORIES.map( ( guidelineCategory ) => [
+ guidelineCategory,
+ {
+ guidelines:
+ contentGuidelinesCategories[ guidelineCategory ] ??
+ '',
+ },
+ ] )
+ ),
+ blocks: Object.fromEntries(
+ Object.entries( blockGuidelines ).map(
+ ( [ blockName, guidelines ] ) => [
+ blockName,
+ { guidelines },
+ ]
+ )
+ ),
+ },
+ };
+
+ downloadBlob(
+ 'guidelines.json',
+ JSON.stringify( data, null, 2 ),
+ 'application/json'
+ );
+
+ createSuccessNotice( __( 'Guidelines exported.' ), {
+ type: 'snackbar',
+ } );
+}
+
+export async function fetchContentGuidelinesRevisions( {
+ guidelinesId,
+ page = 1,
+ perPage = 10,
+ search,
+}: {
+ guidelinesId: number;
+ page?: number;
+ perPage?: number;
+ search?: string;
+} ): Promise< {
+ revisions: ContentGuidelinesRevision[];
+ total: number;
+ totalPages: number;
+} > {
+ const params = new URLSearchParams( {
+ page: String( page ),
+ per_page: String( perPage ),
+ _embed: 'author',
+ ...( search ? { search } : {} ),
+ } );
+
+ const response = ( await apiFetch( {
+ path: `/wp/v2/content-guidelines/${ guidelinesId }/revisions?${ params }`,
+ parse: false,
+ } ) ) as Response;
+
+ const revisions = ( await response.json() ) as ContentGuidelinesRevision[];
+ const total = parseInt( response.headers.get( 'X-WP-Total' ) ?? '0', 10 );
+ const totalPages = parseInt(
+ response.headers.get( 'X-WP-TotalPages' ) ?? '0',
+ 10
+ );
+
+ return { revisions, total, totalPages };
+}
+
+export async function restoreContentGuidelinesRevision(
+ guidelinesId: number,
+ revisionId: number
+): Promise< RestGuidelinesResponse > {
+ return ( await apiFetch( {
+ path: `/wp/v2/content-guidelines/${ guidelinesId }/revisions/${ revisionId }/restore`,
+ method: 'POST',
+ } ) ) as RestGuidelinesResponse;
+}
diff --git a/routes/content-guidelines/components/actions-section.tsx b/routes/content-guidelines/components/actions-section.tsx
new file mode 100644
index 00000000000000..c2c681e48d1796
--- /dev/null
+++ b/routes/content-guidelines/components/actions-section.tsx
@@ -0,0 +1,252 @@
+/**
+ * WordPress dependencies
+ */
+import {
+ Button,
+ Card,
+ Modal,
+ useNavigator,
+ __experimentalText as Text,
+ __experimentalHeading as Heading,
+ __experimentalVStack as VStack,
+ __experimentalHStack as HStack,
+} from '@wordpress/components';
+import { __, sprintf } from '@wordpress/i18n';
+import { useRef, useState } from '@wordpress/element';
+import { Notice } from '@wordpress/ui';
+
+/**
+ * Internal dependencies
+ */
+import { importContentGuidelines, exportContentGuidelines } from '../api';
+
+function getErrorMessage( error: unknown ): string {
+ if ( error instanceof Error ) {
+ return error.message;
+ }
+ if ( typeof error === 'object' && error !== null && 'message' in error ) {
+ return String( ( error as { message: unknown } ).message );
+ }
+ return __( 'Unknown error.' );
+}
+
+const ACTIONS = [
+ {
+ slug: 'import',
+ title: __( 'Import' ),
+ description: __( 'Upload a JSON file to import your guidelines.' ),
+ buttonLabel: __( 'Upload' ),
+ ariaLabel: __( 'Import guidelines' ),
+ },
+ {
+ slug: 'export',
+ title: __( 'Export' ),
+ description: __( 'Export your guidelines to a JSON file.' ),
+ buttonLabel: __( 'Download' ),
+ ariaLabel: __( 'Export guidelines' ),
+ },
+ {
+ slug: 'revert',
+ title: __( 'Revert' ),
+ description: __( 'Use a previous version of your guidelines.' ),
+ buttonLabel: __( 'View history' ),
+ ariaLabel: __( 'View history of guidelines' ),
+ },
+];
+
+export default function ActionsSection() {
+ const { goTo } = useNavigator();
+ const fileInputRef = useRef< HTMLInputElement >( null );
+ const [ isImporting, setIsImporting ] = useState( false );
+ const [ error, setError ] = useState< string | null >( null );
+ const [ pendingImport, setPendingImport ] = useState< File | null >( null );
+
+ function handleImportClick() {
+ fileInputRef.current?.click();
+ }
+
+ function handleFileChange( event: React.ChangeEvent< HTMLInputElement > ) {
+ const file = event.target.files?.[ 0 ];
+ event.target.value = ''; // allow re-selecting the same file
+ if ( ! file ) {
+ return;
+ }
+ setPendingImport( file );
+ }
+
+ async function handleModalContinue() {
+ if ( ! pendingImport ) {
+ return;
+ }
+ const file = pendingImport;
+ setPendingImport( null );
+ setIsImporting( true );
+ try {
+ await importContentGuidelines( file );
+ setError( null );
+ } catch ( importError ) {
+ setError(
+ sprintf(
+ /* translators: %s: Error message. */
+ __( 'We ran into a problem importing your guidelines. %s' ),
+ getErrorMessage( importError )
+ )
+ );
+ } finally {
+ setIsImporting( false );
+ }
+ }
+
+ async function handleExportClick() {
+ try {
+ exportContentGuidelines();
+ setError( null );
+ } catch ( exportError ) {
+ setError(
+ sprintf(
+ /* translators: %s: Error message. */
+ __( 'We ran into a problem exporting your guidelines: %s' ),
+ getErrorMessage( exportError )
+ )
+ );
+ }
+ }
+
+ const buttonProps: Partial<
+ Record<
+ string,
+ {
+ onClick: () => void | Promise< void >;
+ isBusy?: boolean;
+ disabled?: boolean;
+ }
+ >
+ > = {
+ import: {
+ onClick: handleImportClick,
+ isBusy: isImporting,
+ disabled: isImporting || !! pendingImport,
+ },
+ export: { onClick: handleExportClick },
+ revert: { onClick: () => goTo( '/revision-history' ) },
+ };
+
+ return (
+
+ { ACTIONS.map( ( action ) => {
+ const descriptionId = `content-guidelines-action-${ action.slug }-description`;
+ return (
+
+ { /* eslint-enable jsx-a11y/no-redundant-roles */ }
+