Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
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
67 changes: 65 additions & 2 deletions lib/experimental/dashboard-widgets/dashboard-layout.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,17 @@
*/
const GUTENBERG_DASHBOARD_LAYOUT_KEY = 'dashboardLayout';

/**
* Identifier of the bundled dashboard surface, formatted as
* `<plugin>_<page>` to match the underscore form produced by the
* wp-build pipeline (mirrors the `{{PREFIX}}_{{PAGE_SLUG_UNDERSCORE}}`
* pair used in generated page templates).
*
* Passed as context to `gutenberg_dashboard_default_layout` and used
* as the `{name}` segment of the REST default-layout route.
*/
const GUTENBERG_DASHBOARD_NAME = 'gutenberg_dashboard';

/**
* Injects a registered default dashboard layout into the user's
* `persisted_preferences` read when the stored layout is empty.
Expand Down Expand Up @@ -69,9 +80,13 @@ function gutenberg_inject_dashboard_default_layout( $value, $user_id, $meta_key
* Each entry should match the dashboard's widget instance shape:
* `uuid`, `type`, optional `attributes`, optional `placement`.
*
* @param array $default_layout Default array of widget instances.
* @param array $default_layout Default array of widget instances.
* @param string $dashboard_name Identifier of the dashboard surface
* receiving the default. Callbacks
* targeting a specific dashboard
* should switch on this value.
*/
$default = apply_filters( 'gutenberg_dashboard_default_layout', array() );
$default = apply_filters( 'gutenberg_dashboard_default_layout', array(), GUTENBERG_DASHBOARD_NAME );

if ( empty( $default ) || ! is_array( $default ) ) {
return $value;
Expand All @@ -87,3 +102,51 @@ function gutenberg_inject_dashboard_default_layout( $value, $user_id, $meta_key
}

add_filter( 'get_user_metadata', 'gutenberg_inject_dashboard_default_layout', 99, 3 );

/**
* Returns the default layout registered for a dashboard surface.
*
* Resolves `gutenberg_dashboard_default_layout` for the supplied
* dashboard name, returning a fresh evaluation of the filter chain
* each call. Used by the JS surface to back a "reset to default"
* action without depending on the user-meta hydration path.
*
* @param WP_REST_Request $request REST request carrying the
* dashboard name segment.
* @return WP_REST_Response Response wrapping the default layout
* array.
*/
function gutenberg_get_dashboard_default_layout( $request ) {
$name = $request['name'];
$default = apply_filters( 'gutenberg_dashboard_default_layout', array(), $name );

if ( ! is_array( $default ) ) {
$default = array();
}

return rest_ensure_response( array_values( $default ) );
}

/**
* Registers the REST route that exposes per-dashboard default layouts.
*/
function gutenberg_register_dashboard_default_layout_route() {
register_rest_route(
'wp/v2',
'/dashboards/(?P<name>[a-z][a-z0-9]*(?:_[a-z0-9]+)+)/default-layout',
array(
'methods' => WP_REST_Server::READABLE,
'callback' => 'gutenberg_get_dashboard_default_layout',
'permission_callback' => function () {
return current_user_can( 'read' );
},
'args' => array(
'name' => array(
'description' => __( 'Dashboard identifier as produced by the build pipeline.', 'gutenberg' ),
'type' => 'string',
),
),
)
);
}
add_action( 'rest_api_init', 'gutenberg_register_dashboard_default_layout_route' );
17 changes: 13 additions & 4 deletions lib/experimental/dashboard-widgets/default-layout-seed.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,20 @@
* Appends the bundled `core/hello-world` instance to the default layout
* unless something earlier in the filter chain already added it.
*
* @param array $dashboard_layout Default layout produced by previous
* callbacks on `gutenberg_dashboard_default_layout`.
* Only contributes to the bundled `gutenberg_dashboard` surface; other
* dashboards are left untouched.
*
* @param array $dashboard_layout Default layout produced by previous
* callbacks on `gutenberg_dashboard_default_layout`.
* @param string $dashboard_name Identifier of the dashboard surface
* receiving the default.
* @return array The layout extended with the bundled widget instance.
*/
function gutenberg_seed_default_dashboard_layout( $dashboard_layout ) {
function gutenberg_seed_default_dashboard_layout( $dashboard_layout, $dashboard_name = '' ) {
if ( 'gutenberg_dashboard' !== $dashboard_name ) {
return $dashboard_layout;
}

$uuids = array_column( $dashboard_layout, 'uuid' );

if ( in_array( 'default-hello-world-widget-instance', $uuids, true ) ) {
Expand All @@ -37,4 +46,4 @@ function gutenberg_seed_default_dashboard_layout( $dashboard_layout ) {
return $dashboard_layout;
}

add_filter( 'gutenberg_dashboard_default_layout', 'gutenberg_seed_default_dashboard_layout' );
add_filter( 'gutenberg_dashboard_default_layout', 'gutenberg_seed_default_dashboard_layout', 10, 2 );
2 changes: 2 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

41 changes: 33 additions & 8 deletions routes/dashboard/hooks/test/use-dashboard-layout.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import { act, renderHook } from '@testing-library/react';
/**
* WordPress dependencies
*/
import apiFetch from '@wordpress/api-fetch';
import { dispatch } from '@wordpress/data';
import { store as preferencesStore } from '@wordpress/preferences';

Expand All @@ -19,27 +20,41 @@ import { store as preferencesStore } from '@wordpress/preferences';
import useDashboardLayout from '../use-dashboard-layout/use-dashboard-layout';
import type { DashboardWidget } from '../../widget-dashboard';

jest.mock( '@wordpress/api-fetch' );

const mockedApiFetch = apiFetch as unknown as jest.Mock;

const SCOPE = 'core/dashboard';
const KEY = 'dashboardLayout';
const DASHBOARD_NAME = 'gutenberg_dashboard';

const SAMPLE_LAYOUT: DashboardWidget[] = [
{ uuid: 'a', type: 'core/quick-draft' },
{ uuid: 'b', type: 'core/at-a-glance' },
];

const DEFAULT_LAYOUT: DashboardWidget[] = [
{ uuid: 'default-hello-world-widget-instance', type: 'core/hello-world' },
];

describe( 'useDashboardLayout', () => {
beforeEach( () => {
dispatch( preferencesStore ).set( SCOPE, KEY, undefined );
mockedApiFetch.mockReset();
} );

it( 'returns an empty array when nothing is persisted', () => {
const { result } = renderHook( () => useDashboardLayout() );
const { result } = renderHook( () =>
useDashboardLayout( DASHBOARD_NAME )
);
const [ layout ] = result.current;
expect( layout ).toEqual( [] );
} );

it( 'persists updates written through setLayout', () => {
const { result } = renderHook( () => useDashboardLayout() );
const { result } = renderHook( () =>
useDashboardLayout( DASHBOARD_NAME )
);

act( () => {
const [ , setLayout ] = result.current;
Expand All @@ -53,25 +68,35 @@ describe( 'useDashboardLayout', () => {
it( 'reads the layout written from outside the hook', () => {
dispatch( preferencesStore ).set( SCOPE, KEY, SAMPLE_LAYOUT );

const { result } = renderHook( () => useDashboardLayout() );
const { result } = renderHook( () =>
useDashboardLayout( DASHBOARD_NAME )
);
const [ layout ] = result.current;
expect( layout ).toEqual( SAMPLE_LAYOUT );
} );

it( 'clears the layout via resetLayout', () => {
const { result } = renderHook( () => useDashboardLayout() );
it( 'restores the registered default via resetLayout', async () => {
mockedApiFetch.mockResolvedValueOnce( DEFAULT_LAYOUT );

const { result } = renderHook( () =>
useDashboardLayout( DASHBOARD_NAME )
);

act( () => {
const [ , setLayout ] = result.current;
setLayout( SAMPLE_LAYOUT );
} );

act( () => {
await act( async () => {
const [ , , resetLayout ] = result.current;
resetLayout();
await resetLayout();
} );

expect( mockedApiFetch ).toHaveBeenCalledWith( {
path: `/wp/v2/dashboards/${ DASHBOARD_NAME }/default-layout`,
} );

const [ layout ] = result.current;
expect( layout ).toEqual( [] );
expect( layout ).toEqual( DEFAULT_LAYOUT );
} );
} );
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
/**
* WordPress dependencies
*/
import apiFetch from '@wordpress/api-fetch';
import { useDispatch, useSelect } from '@wordpress/data';
import { store as preferencesStore } from '@wordpress/preferences';

Expand All @@ -12,20 +13,31 @@ import type { DashboardWidget } from '../../widget-dashboard';
const SCOPE = 'core/dashboard';
const KEY = 'dashboardLayout';

/**
* Identifier of a dashboard surface, structured as `<plugin>_<page>` to
* mirror the underscore form produced by the wp-build pipeline (see
* `{{PREFIX}}_{{PAGE_SLUG_UNDERSCORE}}` in the page templates).
*/
export type DashboardName = `${ string }_${ string }`;

/**
* Hook for managing dashboard layout preferences.
*
* Returns the persisted layout, a setter that writes through to the
* preferences store, and a reset action that clears the layout to its
* empty state. Plugin-provided defaults will replace the empty fallback
* once the defaults source lands.
* preferences store, and a reset action that fetches the dashboard's
* registered default from the REST API and applies it locally.
*
* @param dashboardName Identifier of the dashboard surface as
* produced by the build pipeline. Used as the
* `{name}` segment of the default-layout route.
* @return Tuple `[ layout, setLayout, resetLayout ]`.
*/
function useDashboardLayout(): [
function useDashboardLayout(
dashboardName: DashboardName
): [
DashboardWidget[],
( layout: DashboardWidget[] ) => void,
() => void,
() => Promise< void >,
] {
const layout = useSelect(
( select ) =>
Expand All @@ -41,8 +53,12 @@ function useDashboardLayout(): [
void set( SCOPE, KEY, newLayout );
}

function resetLayout() {
void set( SCOPE, KEY, [] );
async function resetLayout() {
const fresh = ( await apiFetch( {
path: `/wp/v2/dashboards/${ dashboardName }/default-layout`,
} ) ) as DashboardWidget[];

void set( SCOPE, KEY, fresh );
}

return [ layout, setLayout, resetLayout ];
Expand Down
10 changes: 10 additions & 0 deletions routes/dashboard/lock-unlock.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
/**
* WordPress dependencies
*/
import { __dangerousOptInToUnstableAPIsOnlyForCoreModules } from '@wordpress/private-apis';

export const { lock, unlock } =
__dangerousOptInToUnstableAPIsOnlyForCoreModules(
'I acknowledge private features are not for use in themes or plugins and doing so will break in the next version of WordPress.',
'@wordpress/routes'
);
2 changes: 2 additions & 0 deletions routes/dashboard/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
},
"dependencies": {
"@wordpress/admin-ui": "file:../../packages/admin-ui",
"@wordpress/api-fetch": "file:../../packages/api-fetch",
"@wordpress/base-styles": "file:../../packages/base-styles",
"@wordpress/core-data": "file:../../packages/core-data",
"@wordpress/components": "file:../../packages/components",
Expand All @@ -22,6 +23,7 @@
"@wordpress/i18n": "file:../../packages/i18n",
"@wordpress/icons": "file:../../packages/icons",
"@wordpress/preferences": "file:../../packages/preferences",
"@wordpress/private-apis": "file:../../packages/private-apis",
"@wordpress/ui": "file:../../packages/ui",
"@wordpress/warning": "file:../../packages/warning",
"clsx": "^2.1.1"
Expand Down
7 changes: 5 additions & 2 deletions routes/dashboard/stage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,17 +14,20 @@ import { useWidgetTypes } from './widget-types';
import styles from './stage.module.css';

function Dashboard() {
const [ layout, setLayout ] = useDashboardLayout();
const [ layout, setLayout, resetLayout ] = useDashboardLayout(
'gutenberg_dashboard'
);

const widgetTypes = useWidgetTypes();

const [ editMode, setEditMode ] = useState( false );

return (
<WidgetDashboard
widgetTypes={ widgetTypes }
layout={ layout }
onLayoutChange={ setLayout }
widgetTypes={ widgetTypes }
onLayoutReset={ resetLayout }
editMode={ editMode }
onEditChange={ setEditMode }
>
Expand Down
Loading
Loading