diff --git a/packages/widget-dashboard/CHANGELOG.md b/packages/widget-dashboard/CHANGELOG.md
index c5c5b911223d70..3b541890cd13f2 100644
--- a/packages/widget-dashboard/CHANGELOG.md
+++ b/packages/widget-dashboard/CHANGELOG.md
@@ -30,6 +30,18 @@
nothing, and the wp-admin dashboard pins it where it reads its stored
settings, so preferences persisted by the removed Columns control stay
inert ([#82204](https://github.com/WordPress/gutenberg/pull/82204)).
+- The staging layer enforces the policy on every instance operation,
+ whichever trigger staged the mutation: a denied `move` holds the
+ instance's index, a denied `resize` keeps its spans, a denied `edit`
+ keeps its attributes, and a new instance of a rejected type is
+ dropped ([#82256](https://github.com/WordPress/gutenberg/pull/82256)).
+
+### Documentation
+
+- Policy contract: instance operations carry `widgetType` only while
+ the type is registered; a gone plugin or a failed load leaves it
+ absent, so locks keyed on the type do not fire
+ ([#82256](https://github.com/WordPress/gutenberg/pull/82256)).
### Internal
diff --git a/packages/widget-dashboard/README.md b/packages/widget-dashboard/README.md
index 426b1a87991c47..5400a38fa43e63 100644
--- a/packages/widget-dashboard/README.md
+++ b/packages/widget-dashboard/README.md
@@ -228,13 +228,17 @@ Each request names the operation and carries its subject, so a branch on `reques
| `customize` | none | The Customize button, the `core/dashboard/customize` command, the `core/dashboard/add-widgets` command outside edit mode, and the automatic entry into customize mode on an empty layout. |
| `reset` | none | The Reset to default entry in the overflow menu, the `core/dashboard/reset-to-default` command, and the confirmation prompt they open. A denied reset is hidden, not disabled. |
| `insert` | `widgetType` | Whether the inserter offers the type; a rejected type keeps rendering where already placed. The Add widget button and command show only while some registered type is insertable. |
-| `remove` | `widget`, `widgetType?` | The Remove control in customize mode. The staging layer re-asserts, in place, a locked instance dropped by any trigger. |
+| `remove` | `widget`, `widgetType?` | The Remove control in customize mode. |
| `move` | `widget`, `widgetType?` | Dragging the tile in customize mode. A denied tile is pinned: it holds its index while the other tiles reorder around it; a change ahead of it can still reflow the cell it lands in. |
| `resize` | `widget`, `widgetType?` | The resize handle and the width menu. |
| `edit` | `widget`, `widgetType?` | Attribute editing: the inline fields and the settings trigger in the header, the settings surface, and the widget's `setAttributes`, which is absent when denied so the widget renders read-only. |
The engine resolves the policy once, in its provider, and every surface asks that resolved answer, so further sources join at the same point without touching the surfaces.
+The staging layer enforces the same answers. Every mutation is diffed per instance on arrival, whichever trigger staged it, and each change the policy denies is re-asserted before it lands: a removed locked instance returns at its index, a denied move holds its index, a denied resize keeps its spans, a denied edit keeps its attributes, and a new instance of a rejected type is dropped. What the interface hides, the staging layer rejects.
+
+Instance operations carry `widgetType` only while that type is still in `widgetTypes`. A plugin that is gone, or a render module that failed to load, leaves the field absent: the engine still asks, because the instance is still on the board, but a policy that keys its locks on the type has nothing to match. Locks that must survive that case belong on the instance itself. The same absence is why a new instance of an unregistered type is not dropped: there is no type to ask about.
+
Rules of the contract:
- **Return `true` for operations you do not govern.** Policies compose restrictively, so a default `false` would deny every operation added later.
diff --git a/packages/widget-dashboard/src/context/dashboard-context.tsx b/packages/widget-dashboard/src/context/dashboard-context.tsx
index 4aabf89025cb43..2a618ee5458823 100644
--- a/packages/widget-dashboard/src/context/dashboard-context.tsx
+++ b/packages/widget-dashboard/src/context/dashboard-context.tsx
@@ -13,7 +13,9 @@ import type {
ResolveWidgetModule,
WidgetType,
} from '@wordpress/widget-primitives';
+import { canonicalizeLayout } from '../utils/canonicalize-layout';
import { DEFAULT_GRID } from '../utils/default-grid';
+import { enforceLayoutPolicy } from '../utils/enforce-layout-policy';
import { normalizeGridSettings } from '../utils/normalize-grid-settings';
import { resolveDashboardColumnCap } from '../utils/resolve-dashboard-column-count/resolve-dashboard-column-count';
import { DEFAULT_ROW_HEIGHT } from '../utils/row-height-presets';
@@ -45,33 +47,6 @@ const DEFAULT_RESOLVE_WIDGET_MODULE: ResolveWidgetModule = ( moduleId ) =>
*/
const AUTO_SAVE_DELAY_MS = 5000;
-/**
- * Canonical form of `layout`: widgets sorted by `placement.order` (falling
- * back to array index), then `order` stripped since position now implies it.
- * Used both as the comparison form for `hasUncommittedChanges` (so a change
- * and its undo compare equal) and as the publish form, keeping persisted
- * payloads free of redundant `order` fields.
- *
- * @param {DashboardWidget[]} layout Layout to canonicalize.
- * @return {DashboardWidget[]} Canonicalized layout.
- */
-function canonicalize( layout: DashboardWidget[] ): DashboardWidget[] {
- const indexed = layout.map( ( widget, index ) => ( {
- widget,
- order: widget.placement?.order ?? index,
- } ) );
-
- indexed.sort( ( a, b ) => a.order - b.order );
-
- return indexed.map( ( { widget } ) => {
- if ( ! widget.placement ) {
- return widget;
- }
- const { order: _stripped, ...placement } = widget.placement;
- return { ...widget, placement };
- } );
-}
-
/**
* Rich state distributed to every compound component inside `WidgetDashboard`.
* Internal — compounds reach the full state via `useDashboardInternalContext()`.
@@ -218,37 +193,23 @@ export function WidgetDashboardProvider( {
[ policy ]
);
- // Every mutation stages through here. Instances the policy locks against
- // removal are re-asserted right after the nearest preceding instance that
- // survived, so no composed trigger can drop or displace them.
+ // Every mutation stages through here, diffed against the current
+ // staging so every change the policy denies is re-asserted before it
+ // lands: what the interface hides, the staging layer rejects. Without
+ // a policy there is nothing to enforce, and staging stays byte-equal
+ // to what the trigger wrote.
const stageLayout = useCallback(
( next: DashboardWidget[] ) => {
- setStagingLayout( ( previous ) => {
- const staged = [ ...next ];
- let insertAt = 0;
- previous.forEach( ( widget ) => {
- const position = staged.findIndex(
- ( { uuid } ) => uuid === widget.uuid
- );
- if ( position !== -1 ) {
- insertAt = position + 1;
- return;
- }
- const removable = canPerform( {
- operation: 'remove',
- widget,
- widgetType: widgetTypes.find(
- ( type ) => type.name === widget.type
- ),
- } );
- if ( removable ) {
- return;
- }
- staged.splice( insertAt, 0, widget );
- insertAt += 1;
- } );
- return staged.length === next.length ? next : staged;
- } );
+ setStagingLayout( ( previous ) =>
+ canPerform === ALLOW_EVERY_OPERATION
+ ? next
+ : enforceLayoutPolicy( {
+ previous,
+ next,
+ canPerform,
+ widgetTypes,
+ } )
+ );
},
[ canPerform, widgetTypes ]
);
@@ -268,8 +229,8 @@ export function WidgetDashboardProvider( {
const hasLayoutChanges = useMemo(
() =>
! fastDeepEqual(
- canonicalize( committedLayout ),
- canonicalize( stagingLayout )
+ canonicalizeLayout( committedLayout ),
+ canonicalizeLayout( stagingLayout )
),
[ committedLayout, stagingLayout ]
);
@@ -279,7 +240,7 @@ export function WidgetDashboardProvider( {
const commit = useCallback(
( options?: CommitOptions ) => {
if ( hasLayoutChanges ) {
- onLayoutChange( canonicalize( stagingLayout ) );
+ onLayoutChange( canonicalizeLayout( stagingLayout ) );
}
if ( options?.exitEditMode !== false ) {
diff --git a/packages/widget-dashboard/src/stories/debug.story.tsx b/packages/widget-dashboard/src/stories/debug.story.tsx
new file mode 100644
index 00000000000000..3a3f31899653d1
--- /dev/null
+++ b/packages/widget-dashboard/src/stories/debug.story.tsx
@@ -0,0 +1,431 @@
+import type { Meta, StoryObj } from '@storybook/react-vite';
+import type { ComponentType } from 'react';
+// eslint-disable-next-line @wordpress/no-non-module-stylesheet-imports
+import '@wordpress/components/build-style/style.css';
+// eslint-disable-next-line @wordpress/no-non-module-stylesheet-imports
+import '@wordpress/dataviews/build-style/style.css';
+import { Button } from '@wordpress/components';
+import {
+ createContext,
+ useContext,
+ useMemo,
+ useState,
+} from '@wordpress/element';
+import { lockOutline } from '@wordpress/icons';
+import type {
+ ResolveWidgetModule,
+ WidgetRenderProps,
+ WidgetType,
+} from '@wordpress/widget-primitives';
+import { useDashboardInternalContext } from '../context/dashboard-context';
+import { useWidgetContext } from '../context/widget-context';
+import { WidgetDashboard } from '../widget-dashboard';
+import type {
+ CanPerformDashboardOperation,
+ DashboardInstanceOperation,
+ DashboardWidget,
+} from '../types';
+
+/*
+ * Debug fixture: the rogue triggers write to staging through the internal
+ * context, which is what only a composed trigger can do. Not a consumer
+ * example. Every tile is a lock card showing its live canonical position
+ * and one chip per instance operation; the story controls edit each
+ * card's denied operations. Customize mode shows the same locks on the
+ * chrome.
+ */
+
+const INSTANCE_OPERATIONS: DashboardInstanceOperation[] = [
+ 'move',
+ 'resize',
+ 'remove',
+ 'edit',
+];
+
+type TileLocks = Record< string, DashboardInstanceOperation[] | undefined >;
+
+/* Demo plumbing so the cards re-render when the controls change. */
+const TileLocksContext = createContext< TileLocks >( {} );
+
+/* Stable instance name from the uuid: `card-alpha` reads as `Alpha`. */
+const cardName = ( uuid: string ) => {
+ const raw = uuid.replace( /^card-/, '' ).replace( /-/g, ' ' );
+ return raw.charAt( 0 ).toUpperCase() + raw.slice( 1 );
+};
+
+/*
+ * Reads the demo's lock map by its own uuid purely to visualize it; real
+ * widgets never see the policy.
+ */
+function LockCardWidget( {
+ attributes,
+}: WidgetRenderProps< { label?: string } > ) {
+ const { label = 'Card' } = attributes ?? {};
+ const widget = useWidgetContext();
+ const locks = useContext( TileLocksContext )[ widget?.uuid ?? '' ] ?? [];
+
+ return (
+
+
+ { `#${ ( widget?.index ?? 0 ) + 1 } · ${ cardName(
+ widget?.uuid ?? ''
+ ) }` }
+
+
+ { `Label: ${ label }` }
+
+
+ { INSTANCE_OPERATIONS.map( ( operation ) => {
+ const denied = locks.includes( operation );
+ return (
+
+ { `${ denied ? '✕' : '✓' } ${ operation }` }
+
+ );
+ } ) }
+
+
+ );
+}
+
+const lockCardWidgetType: WidgetType = {
+ apiVersion: 1,
+ name: 'demo/lock-card',
+ title: 'Lock Card',
+ description:
+ 'Shows its canonical position and which operations the policy allows on it.',
+ icon: lockOutline,
+ renderModule: 'demo/widgets/lock-card/render',
+ attributes: [
+ { id: 'label', label: 'Label', type: 'text', relevance: 'high' },
+ ] as WidgetType[ 'attributes' ],
+ example: {
+ attributes: { label: 'Example' },
+ },
+};
+
+/*
+ * Registered so insert has a type to reject. The rogue trigger that
+ * tries it never lands, so the type does not need a render module.
+ */
+const rejectedWidgetType: WidgetType = {
+ apiVersion: 1,
+ name: 'demo/goal-progress',
+ title: 'Goal Progress',
+ renderModule: 'demo/widgets/goal-progress/render',
+};
+
+const resolveDebugModule: ResolveWidgetModule = async () => ( {
+ default: LockCardWidget as ComponentType< WidgetRenderProps< unknown > >,
+} );
+
+const ENFORCEMENT_LAYOUT: DashboardWidget[] = [
+ {
+ uuid: 'card-alpha',
+ type: 'demo/lock-card',
+ attributes: { label: 'Alpha' },
+ placement: { width: 1, height: 1 },
+ },
+ {
+ uuid: 'card-bravo',
+ type: 'demo/lock-card',
+ attributes: { label: 'Bravo' },
+ placement: { width: 2, height: 1 },
+ },
+ {
+ uuid: 'card-charlie',
+ type: 'demo/lock-card',
+ attributes: { label: 'Charlie' },
+ placement: { width: 1, height: 1 },
+ },
+ {
+ uuid: 'card-delta',
+ type: 'demo/lock-card',
+ attributes: { label: 'Delta' },
+ placement: { width: 1, height: 1 },
+ },
+];
+
+let stagedInstances = 0;
+
+function RogueTriggers() {
+ const { layout, onLayoutChange } = useDashboardInternalContext();
+
+ const insert = ( widget: Omit< DashboardWidget, 'uuid' > ) => {
+ stagedInstances += 1;
+ onLayoutChange( [
+ ...layout,
+ { ...widget, uuid: `staged-${ stagedInstances }` },
+ ] );
+ };
+
+ return (
+
+ onLayoutChange( [ ...layout ].reverse() ) }
+ >
+ Reverse the order
+
+
+ onLayoutChange(
+ layout.filter(
+ ( widget ) => widget.uuid !== 'card-delta'
+ )
+ )
+ }
+ >
+ Remove the Delta card
+
+
+ onLayoutChange(
+ layout.map( ( widget ) => ( {
+ ...widget,
+ placement: { ...widget.placement, width: 4 },
+ } ) )
+ )
+ }
+ >
+ Set every width to 4
+
+
+ onLayoutChange(
+ layout.map( ( widget ) => ( {
+ ...widget,
+ attributes: {
+ ...( widget.attributes as Record<
+ string,
+ unknown
+ > ),
+ label: 'Hijacked',
+ },
+ } ) )
+ )
+ }
+ >
+ Rename every label
+
+
+ insert( {
+ type: rejectedWidgetType.name,
+ attributes: { metric: 'orders', target: '1000' },
+ placement: { width: 1, height: 1 },
+ } )
+ }
+ >
+ Insert a goal (rejected)
+
+
+ insert( {
+ type: 'demo/lock-card',
+ attributes: { label: 'Staged' },
+ placement: { width: 1, height: 1 },
+ } )
+ }
+ >
+ Insert a card (allowed)
+
+ onLayoutChange( ENFORCEMENT_LAYOUT ) }
+ >
+ Stage the initial layout
+
+
+ );
+}
+
+interface StagingEnforcementArgs {
+ alpha?: DashboardInstanceOperation[];
+ bravo?: DashboardInstanceOperation[];
+ charlie?: DashboardInstanceOperation[];
+ delta?: DashboardInstanceOperation[];
+}
+
+function StagingEnforcementStory( {
+ alpha = [],
+ bravo = [],
+ charlie = [],
+ delta = [],
+}: StagingEnforcementArgs ) {
+ const [ layout, setLayout ] =
+ useState< DashboardWidget[] >( ENFORCEMENT_LAYOUT );
+ const [ editMode, setEditMode ] = useState( false );
+
+ const tileLocks = useMemo< TileLocks >(
+ () => ( {
+ 'card-alpha': alpha,
+ 'card-bravo': bravo,
+ 'card-charlie': charlie,
+ 'card-delta': delta,
+ } ),
+ [ alpha, bravo, charlie, delta ]
+ );
+
+ // Inserting Goal Progress is rejected; instance operations follow
+ // the per-card locks from the story controls.
+ const canPerform = useMemo< CanPerformDashboardOperation >(
+ () => ( request ) => {
+ if ( request.operation === 'insert' ) {
+ return request.widgetType.name !== rejectedWidgetType.name;
+ }
+ if ( ! ( 'widget' in request ) ) {
+ return true;
+ }
+ return ! tileLocks[ request.widget.uuid ]?.includes(
+ request.operation
+ );
+ },
+ [ tileLocks ]
+ );
+
+ return (
+
+
+
+
+
+
+
+
+
+
+
+ );
+}
+
+const meta: Meta< typeof WidgetDashboard > = {
+ title: 'Widget Dashboard/Playground/Debug',
+ component: WidgetDashboard,
+ tags: [ 'status-experimental' ],
+ parameters: {
+ // FIXME: Sortable widget chrome nests interactive controls (nested-interactive).
+ // See: https://github.com/WordPress/gutenberg/issues/81596
+ a11y: { test: 'todo' },
+ },
+};
+
+export default meta;
+
+const lockControl = {
+ control: 'check' as const,
+ options: INSTANCE_OPERATIONS,
+};
+
+export const StagingEnforcement: StoryObj< StagingEnforcementArgs > = {
+ render: ( args ) => ,
+ args: {
+ alpha: [],
+ bravo: [ 'move' ],
+ charlie: [ 'resize' ],
+ delta: [ 'remove', 'edit' ],
+ },
+ argTypes: {
+ alpha: {
+ ...lockControl,
+ description: 'Operations denied on the Alpha card.',
+ },
+ bravo: {
+ ...lockControl,
+ description: 'Operations denied on the Bravo card.',
+ },
+ charlie: {
+ ...lockControl,
+ description: 'Operations denied on the Charlie card.',
+ },
+ delta: {
+ ...lockControl,
+ description: 'Operations denied on the Delta card.',
+ },
+ },
+ parameters: {
+ docs: {
+ description: {
+ story: `
+Debug fixture. Every tile is a **Lock Card**: it shows its live position in the canonical order and one chip per instance operation, ✓ when the policy allows it and ✕ when it denies it. The controls edit each card's denied operations; by default Bravo cannot move, Charlie cannot resize, Delta cannot be removed or edited, and Alpha is free. Enter Customize to see the same locks on the chrome: a move-denied card refuses to drag and holds its position while the others reorder around it, a resize-denied card offers no resize handle or width menu, a remove-denied card has no Remove control, and the inserter rejects Goal Progress.
+
+The buttons bypass the chrome and write to the engine's staging directly, which is what the staging enforcement exists for: with the default locks, reversing holds Bravo in place, the width sweep skips Charlie, the rename skips Delta, and removing Delta re-asserts it, while the rejected insertion never lands and the allowed one does. Relax a lock from the controls and the same trigger goes through.
+`,
+ },
+ },
+ },
+};
diff --git a/packages/widget-dashboard/src/stories/index.story.tsx b/packages/widget-dashboard/src/stories/index.story.tsx
index 9debb2b63db025..bd2a63a83dd6bc 100644
--- a/packages/widget-dashboard/src/stories/index.story.tsx
+++ b/packages/widget-dashboard/src/stories/index.story.tsx
@@ -314,13 +314,19 @@ const goalProgressWidgetType: WidgetType = {
};
// What `import( widget.renderModule )` resolves to in a real host.
-const resolveDemoModule: ResolveWidgetModule = async ( moduleId ) => ( {
- default: ( moduleId === goalProgressWidgetType.renderModule
- ? GoalProgressWidget
- : TrafficSnapshotWidget ) as ComponentType<
- WidgetRenderProps< unknown >
- >,
-} );
+const resolveDemoModule: ResolveWidgetModule = async ( moduleId ) => {
+ let component: ComponentType< WidgetRenderProps< unknown > >;
+ if ( moduleId === goalProgressWidgetType.renderModule ) {
+ component = GoalProgressWidget as ComponentType<
+ WidgetRenderProps< unknown >
+ >;
+ } else {
+ component = TrafficSnapshotWidget as ComponentType<
+ WidgetRenderProps< unknown >
+ >;
+ }
+ return { default: component };
+};
// The snapshot type at two widths, plus a one-column goal tile whose
// attributes are all promoted, so the header presentations can be compared
diff --git a/packages/widget-dashboard/src/stories/policy.md b/packages/widget-dashboard/src/stories/policy.md
index 2ac196a48ad2fe..906cc3fbdf1e2b 100644
--- a/packages/widget-dashboard/src/stories/policy.md
+++ b/packages/widget-dashboard/src/stories/policy.md
@@ -35,13 +35,17 @@ The Customize button, the command palette entries, the tile controls, and the in
| `customize` | none | The Customize button, the `core/dashboard/customize` command, the `core/dashboard/add-widgets` command outside edit mode, and the automatic entry into customize mode on an empty layout. |
| `reset` | none | The Reset to default entry in the overflow menu, the `core/dashboard/reset-to-default` command, and the confirmation prompt they open. A denied reset is hidden, not disabled. |
| `insert` | `widgetType` | Whether the inserter offers the type; a rejected type keeps rendering where already placed. The Add widget button and command show only while some registered type is insertable. |
-| `remove` | `widget`, `widgetType?` | The Remove control in customize mode. The staging layer re-asserts, in place, a locked instance dropped by any trigger. |
+| `remove` | `widget`, `widgetType?` | The Remove control in customize mode. |
| `move` | `widget`, `widgetType?` | Dragging the tile in customize mode. A denied tile is pinned: it holds its index while the other tiles reorder around it; a change ahead of it can still reflow the cell it lands in. |
| `resize` | `widget`, `widgetType?` | The resize handle and the width menu. |
| `edit` | `widget`, `widgetType?` | Attribute editing: the inline fields and the settings trigger in the header, the settings surface, and the widget's `setAttributes`, which is absent when denied so the widget renders read-only. |
The vocabulary grows with what the engine enforces. Return `true` for operations you do not govern: policies compose restrictively, so a default `false` would deny every operation added later.
+The staging layer enforces the same answers. Every mutation is diffed per instance on arrival, whichever trigger staged it, and each change the policy denies is re-asserted before it lands: a removed locked instance returns at its index, a denied move holds its index, a denied resize keeps its spans, a denied edit keeps its attributes, and a new instance of a rejected type is dropped. What the interface hides, the staging layer rejects.
+
+Instance operations carry `widgetType` only while that type is still in `widgetTypes`. A plugin that is gone, or a render module that failed to load, leaves the field absent: the engine still asks, because the instance is still on the board, but a policy that keys its locks on the type has nothing to match. Locks that must survive that case belong on the instance itself. The same absence is why a new instance of an unregistered type is not dropped: there is no type to ask about.
+
## Composition
The provider mounts around ``, not inside it.
diff --git a/packages/widget-dashboard/src/test/enforce-layout-policy.test.ts b/packages/widget-dashboard/src/test/enforce-layout-policy.test.ts
new file mode 100644
index 00000000000000..eef14980606a45
--- /dev/null
+++ b/packages/widget-dashboard/src/test/enforce-layout-policy.test.ts
@@ -0,0 +1,519 @@
+import { describe, expect, it, vi } from 'vitest';
+import type { WidgetType } from '@wordpress/widget-primitives';
+import { enforceLayoutPolicy } from '../utils/enforce-layout-policy';
+import type {
+ CanPerformDashboardOperation,
+ DashboardInstanceOperation,
+ DashboardWidget,
+} from '../types';
+
+const widgetTypes: WidgetType[] = [
+ { apiVersion: 1, name: 'test/one', title: 'One', renderModule: 'one' },
+ { apiVersion: 1, name: 'test/two', title: 'Two', renderModule: 'two' },
+];
+
+const widget = (
+ uuid: string,
+ over: Partial< DashboardWidget > = {}
+): DashboardWidget => ( {
+ uuid,
+ type: 'test/one',
+ ...over,
+} );
+
+/* Denies the listed operations, allows everything else. */
+const deny =
+ (
+ ...operations: DashboardInstanceOperation[]
+ ): CanPerformDashboardOperation =>
+ ( request ) =>
+ ! ( operations as string[] ).includes( request.operation );
+
+const allowAll: CanPerformDashboardOperation = () => true;
+
+const uuids = ( layout: DashboardWidget[] ) =>
+ layout.map( ( { uuid } ) => uuid );
+
+describe( 'enforceLayoutPolicy', () => {
+ it( 'returns the incoming layout itself when the policy allows everything', () => {
+ const previous = [ widget( 'a' ), widget( 'b' ) ];
+ const next = [
+ { ...previous[ 1 ], placement: { width: 2 } },
+ { ...previous[ 0 ], attributes: { label: 'edited' } },
+ widget( 'c' ),
+ ];
+
+ const result = enforceLayoutPolicy( {
+ previous,
+ next,
+ canPerform: allowAll,
+ widgetTypes,
+ } );
+
+ expect( result ).toBe( next );
+ } );
+
+ it( 'asks with the previous instance and its resolved type', () => {
+ const canPerform = vi.fn( allowAll );
+ const previous = [ widget( 'a', { attributes: { label: 'one' } } ) ];
+ const next = [ { ...previous[ 0 ], attributes: { label: 'two' } } ];
+
+ enforceLayoutPolicy( { previous, next, canPerform, widgetTypes } );
+
+ expect( canPerform ).toHaveBeenCalledWith( {
+ operation: 'edit',
+ widget: previous[ 0 ],
+ widgetType: widgetTypes[ 0 ],
+ } );
+ } );
+
+ describe( 'insert', () => {
+ it( 'drops a new instance whose type the policy rejects', () => {
+ const previous = [ widget( 'a' ) ];
+ const next = [
+ previous[ 0 ],
+ widget( 'b', { type: 'test/two' } ),
+ widget( 'c' ),
+ ];
+ const rejectTwo: CanPerformDashboardOperation = ( request ) =>
+ ! (
+ request.operation === 'insert' &&
+ request.widgetType.name === 'test/two'
+ );
+
+ const result = enforceLayoutPolicy( {
+ previous,
+ next,
+ canPerform: rejectTwo,
+ widgetTypes,
+ } );
+
+ expect( uuids( result ) ).toEqual( [ 'a', 'c' ] );
+ } );
+
+ it( 'passes a new instance of an unregistered type through', () => {
+ const previous = [ widget( 'a' ) ];
+ const next = [
+ previous[ 0 ],
+ widget( 'b', { type: 'test/unknown' } ),
+ ];
+ const rejectInserts: CanPerformDashboardOperation = ( request ) =>
+ request.operation !== 'insert';
+
+ const result = enforceLayoutPolicy( {
+ previous,
+ next,
+ canPerform: rejectInserts,
+ widgetTypes,
+ } );
+
+ expect( result ).toBe( next );
+ } );
+ } );
+
+ describe( 'unregistered type', () => {
+ it( 'asks instance operations with widgetType absent', () => {
+ const canPerform = vi.fn( allowAll );
+ const previous = [ widget( 'a', { type: 'test/gone' } ) ];
+ const next = [ { ...previous[ 0 ], attributes: { label: 'x' } } ];
+
+ enforceLayoutPolicy( {
+ previous,
+ next,
+ canPerform,
+ widgetTypes,
+ } );
+
+ expect( canPerform ).toHaveBeenCalledWith( {
+ operation: 'edit',
+ widget: previous[ 0 ],
+ widgetType: undefined,
+ } );
+ } );
+
+ it( 'does not fire a lock keyed on the type', () => {
+ const previous = [
+ widget( 'a', { type: 'test/gone' } ),
+ widget( 'b' ),
+ ];
+ const next = [ previous[ 1 ], previous[ 0 ] ];
+ const denyGoneMoves: CanPerformDashboardOperation = ( request ) =>
+ ! (
+ request.operation === 'move' &&
+ request.widgetType?.name === 'test/gone'
+ );
+
+ const result = enforceLayoutPolicy( {
+ previous,
+ next,
+ canPerform: denyGoneMoves,
+ widgetTypes,
+ } );
+
+ expect( uuids( result ) ).toEqual( [ 'b', 'a' ] );
+ } );
+
+ it( 'still holds a lock decided from the instance', () => {
+ const previous = [
+ widget( 'a', { type: 'test/gone' } ),
+ widget( 'b' ),
+ ];
+ const next = [ previous[ 1 ], previous[ 0 ] ];
+ const pinA: CanPerformDashboardOperation = ( request ) =>
+ ! (
+ request.operation === 'move' &&
+ 'widget' in request &&
+ request.widget.uuid === 'a'
+ );
+
+ const result = enforceLayoutPolicy( {
+ previous,
+ next,
+ canPerform: pinA,
+ widgetTypes,
+ } );
+
+ expect( uuids( result ) ).toEqual( [ 'a', 'b' ] );
+ } );
+ } );
+
+ describe( 'edit', () => {
+ it( 're-asserts the staged attributes when edit is denied', () => {
+ const previous = [
+ widget( 'a', { attributes: { label: 'staged' } } ),
+ ];
+ const next = [ { ...previous[ 0 ], attributes: { label: 'x' } } ];
+
+ const result = enforceLayoutPolicy( {
+ previous,
+ next,
+ canPerform: deny( 'edit' ),
+ widgetTypes,
+ } );
+
+ expect( result[ 0 ].attributes ).toBe( previous[ 0 ].attributes );
+ } );
+
+ it( 'strips attributes a denied edit introduced', () => {
+ const previous = [ widget( 'a' ) ];
+ const next = [ { ...previous[ 0 ], attributes: { label: 'x' } } ];
+
+ const result = enforceLayoutPolicy( {
+ previous,
+ next,
+ canPerform: deny( 'edit' ),
+ widgetTypes,
+ } );
+
+ expect( 'attributes' in result[ 0 ] ).toBe( false );
+ } );
+
+ it( 'leaves deep-equal attributes untouched under a denied edit', () => {
+ const previous = [
+ widget( 'a', { attributes: { label: 'same' } } ),
+ ];
+ const next = [
+ { ...previous[ 0 ], attributes: { label: 'same' } },
+ ];
+
+ const result = enforceLayoutPolicy( {
+ previous,
+ next,
+ canPerform: deny( 'edit' ),
+ widgetTypes,
+ } );
+
+ expect( result ).toBe( next );
+ } );
+ } );
+
+ describe( 'resize', () => {
+ it( 're-asserts the placement spans when resize is denied', () => {
+ const previous = [
+ widget( 'a', { placement: { width: 1, height: 1 } } ),
+ ];
+ const next = [
+ {
+ ...previous[ 0 ],
+ placement: { width: 3, height: 2, order: 5 },
+ },
+ ];
+
+ const result = enforceLayoutPolicy( {
+ previous,
+ next,
+ canPerform: deny( 'resize' ),
+ widgetTypes,
+ } );
+
+ expect( result[ 0 ].placement ).toEqual( { width: 1, height: 1 } );
+ } );
+
+ it( 'drops spans a denied resize introduced on a bare instance', () => {
+ const previous = [ widget( 'a' ) ];
+ const next = [ { ...previous[ 0 ], placement: { width: 4 } } ];
+
+ const result = enforceLayoutPolicy( {
+ previous,
+ next,
+ canPerform: deny( 'resize' ),
+ widgetTypes,
+ } );
+
+ expect( 'placement' in result[ 0 ] ).toBe( false );
+ } );
+ } );
+
+ describe( 'move', () => {
+ it( 'holds the index of a move-denied instance through a reorder', () => {
+ const previous = [ widget( 'a' ), widget( 'b' ), widget( 'c' ) ];
+ const next = [ previous[ 2 ], previous[ 0 ], previous[ 1 ] ];
+ const pinB: CanPerformDashboardOperation = ( request ) =>
+ ! (
+ request.operation === 'move' && request.widget.uuid === 'b'
+ );
+
+ const result = enforceLayoutPolicy( {
+ previous,
+ next,
+ canPerform: pinB,
+ widgetTypes,
+ } );
+
+ expect( uuids( result ) ).toEqual( [ 'c', 'b', 'a' ] );
+ } );
+
+ it( 'accepts a layout where the pinned instance already holds its index', () => {
+ const previous = [ widget( 'a' ), widget( 'b' ), widget( 'c' ) ];
+ // What the grid emits for "move a after c" while b is pinned.
+ const next = [ previous[ 2 ], previous[ 1 ], previous[ 0 ] ];
+ const pinB: CanPerformDashboardOperation = ( request ) =>
+ ! (
+ request.operation === 'move' && request.widget.uuid === 'b'
+ );
+
+ const result = enforceLayoutPolicy( {
+ previous,
+ next,
+ canPerform: pinB,
+ widgetTypes,
+ } );
+
+ expect( result ).toBe( next );
+ } );
+
+ it( 'discounts an allowed removal when holding the index', () => {
+ const previous = [ widget( 'a' ), widget( 'b' ), widget( 'c' ) ];
+ const next = [ previous[ 1 ], previous[ 2 ] ];
+ const pinC: CanPerformDashboardOperation = ( request ) =>
+ ! (
+ request.operation === 'move' && request.widget.uuid === 'c'
+ );
+
+ const result = enforceLayoutPolicy( {
+ previous,
+ next,
+ canPerform: pinC,
+ widgetTypes,
+ } );
+
+ expect( result ).toBe( next );
+ } );
+
+ it( 'reads a reorder the grid expressed through order fields', () => {
+ const previous = [ widget( 'a' ), widget( 'b' ), widget( 'c' ) ];
+ // The grid emits reorders in the old array order with fresh
+ // `order` stamps: "move a after c" while b is pinned.
+ const next = [
+ { ...previous[ 0 ], placement: { order: 2 } },
+ { ...previous[ 1 ], placement: { order: 1 } },
+ { ...previous[ 2 ], placement: { order: 0 } },
+ ];
+ const pinB: CanPerformDashboardOperation = ( request ) =>
+ ! (
+ request.operation === 'move' && request.widget.uuid === 'b'
+ );
+
+ const result = enforceLayoutPolicy( {
+ previous,
+ next,
+ canPerform: pinB,
+ widgetTypes,
+ } );
+
+ expect( uuids( result ) ).toEqual( [ 'c', 'b', 'a' ] );
+ expect( result[ 0 ].placement ).toEqual( {} );
+ } );
+
+ it( 'holds the canonical position through a reorder followed by a removal', () => {
+ const previous = [
+ widget( 'a' ),
+ widget( 'b' ),
+ widget( 'c' ),
+ widget( 'd' ),
+ ];
+ const pinB: CanPerformDashboardOperation = ( request ) =>
+ ! (
+ request.operation === 'move' && request.widget.uuid === 'b'
+ );
+
+ // Grid emission for "move a after c" while b is pinned.
+ const afterDrag = enforceLayoutPolicy( {
+ previous,
+ next: [
+ { ...previous[ 0 ], placement: { order: 2 } },
+ { ...previous[ 1 ], placement: { order: 1 } },
+ { ...previous[ 2 ], placement: { order: 0 } },
+ { ...previous[ 3 ], placement: { order: 3 } },
+ ],
+ canPerform: pinB,
+ widgetTypes,
+ } );
+
+ expect( uuids( afterDrag ) ).toEqual( [ 'c', 'b', 'a', 'd' ] );
+
+ // Then remove the dragged tile: b keeps its second position.
+ const afterRemoval = enforceLayoutPolicy( {
+ previous: afterDrag,
+ next: afterDrag.filter( ( { uuid } ) => uuid !== 'a' ),
+ canPerform: pinB,
+ widgetTypes,
+ } );
+
+ expect( uuids( afterRemoval ) ).toEqual( [ 'c', 'b', 'd' ] );
+ } );
+
+ it( 're-asserts a move expressed through order fields alone', () => {
+ const previous = [ widget( 'a' ), widget( 'b' ), widget( 'c' ) ];
+ const next = [
+ previous[ 0 ],
+ { ...previous[ 1 ], placement: { order: 5 } },
+ previous[ 2 ],
+ ];
+ const pinB: CanPerformDashboardOperation = ( request ) =>
+ ! (
+ request.operation === 'move' && request.widget.uuid === 'b'
+ );
+
+ const result = enforceLayoutPolicy( {
+ previous,
+ next,
+ canPerform: pinB,
+ widgetTypes,
+ } );
+
+ expect( uuids( result ) ).toEqual( [ 'a', 'b', 'c' ] );
+ } );
+
+ it( 'keeps the lane of a move-denied instance', () => {
+ const previous = [ widget( 'a', { placement: { lane: 0 } } ) ];
+ const next = [ { ...previous[ 0 ], placement: { lane: 2 } } ];
+
+ const result = enforceLayoutPolicy( {
+ previous,
+ next,
+ canPerform: deny( 'move' ),
+ widgetTypes,
+ } );
+
+ expect( result[ 0 ].placement ).toEqual( { lane: 0 } );
+ } );
+ } );
+
+ describe( 'remove', () => {
+ it( 're-asserts a denied removal at its previous index', () => {
+ const previous = [ widget( 'a' ), widget( 'b' ), widget( 'c' ) ];
+ const next = [ previous[ 0 ], previous[ 2 ] ];
+ const lockB: CanPerformDashboardOperation = ( request ) =>
+ ! (
+ request.operation === 'remove' &&
+ request.widget.uuid === 'b'
+ );
+
+ const result = enforceLayoutPolicy( {
+ previous,
+ next,
+ canPerform: lockB,
+ widgetTypes,
+ } );
+
+ expect( uuids( result ) ).toEqual( [ 'a', 'b', 'c' ] );
+ expect( result[ 1 ] ).toBe( previous[ 1 ] );
+ } );
+
+ it( 'lets an allowed removal through', () => {
+ const previous = [ widget( 'a' ), widget( 'b' ) ];
+ const next = [ previous[ 1 ] ];
+
+ const result = enforceLayoutPolicy( {
+ previous,
+ next,
+ canPerform: allowAll,
+ widgetTypes,
+ } );
+
+ expect( result ).toBe( next );
+ } );
+ } );
+
+ it( 'enforces every facet of one staged layout at once', () => {
+ const previous = [
+ widget( 'locked', {
+ attributes: { label: 'keep' },
+ placement: { width: 1, height: 1 },
+ } ),
+ widget( 'free' ),
+ ];
+ const next = [
+ widget( 'added', { type: 'test/two' } ),
+ previous[ 1 ],
+ {
+ ...previous[ 0 ],
+ attributes: { label: 'changed' },
+ placement: { width: 4, height: 2 },
+ },
+ ];
+ const lockFirst: CanPerformDashboardOperation = ( request ) => {
+ if ( request.operation === 'insert' ) {
+ return request.widgetType.name !== 'test/two';
+ }
+ return ! (
+ 'widget' in request && request.widget.uuid === 'locked'
+ );
+ };
+
+ const result = enforceLayoutPolicy( {
+ previous,
+ next,
+ canPerform: lockFirst,
+ widgetTypes,
+ } );
+
+ expect( uuids( result ) ).toEqual( [ 'locked', 'free' ] );
+ expect( result[ 0 ].attributes ).toBe( previous[ 0 ].attributes );
+ expect( result[ 0 ].placement ).toEqual( { width: 1, height: 1 } );
+ } );
+
+ it( 'lets a move-denied instance take an allowed resize', () => {
+ const previous = [
+ widget( 'a', { placement: { width: 1, height: 1 } } ),
+ widget( 'b' ),
+ ];
+ const next = [
+ previous[ 1 ],
+ { ...previous[ 0 ], placement: { width: 3, height: 1 } },
+ ];
+ const pinA: CanPerformDashboardOperation = ( request ) =>
+ ! ( request.operation === 'move' && request.widget.uuid === 'a' );
+
+ const result = enforceLayoutPolicy( {
+ previous,
+ next,
+ canPerform: pinA,
+ widgetTypes,
+ } );
+
+ expect( uuids( result ) ).toEqual( [ 'a', 'b' ] );
+ expect( result[ 0 ].placement ).toEqual( { width: 3, height: 1 } );
+ } );
+} );
diff --git a/packages/widget-dashboard/src/test/policy.jsdom.test.tsx b/packages/widget-dashboard/src/test/policy.jsdom.test.tsx
index 5f33a010cd0906..15b248e8838768 100644
--- a/packages/widget-dashboard/src/test/policy.jsdom.test.tsx
+++ b/packages/widget-dashboard/src/test/policy.jsdom.test.tsx
@@ -1,8 +1,8 @@
import '@testing-library/jest-dom';
-import { render, screen, waitFor, within } from '@testing-library/react';
+import { act, render, screen, waitFor, within } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import type { ComponentType } from 'react';
-import { useMemo, useState } from '@wordpress/element';
+import { useEffect, useMemo, useState } from '@wordpress/element';
import type {
ResolveWidgetModule,
WidgetRenderProps,
@@ -108,10 +108,41 @@ function OpenSettings() {
);
}
+/* Reaches the engine's staging and commit paths directly. */
+interface EngineApi {
+ layout: DashboardWidget[];
+ mutate: ( next: DashboardWidget[] ) => void;
+ commit: () => void;
+ scheduleAutoSave: () => void;
+}
+
+const engineRef: { current: EngineApi | null } = { current: null };
+
+function EngineProbe() {
+ const ctx = useDashboardInternalContext();
+ useEffect( () => {
+ engineRef.current = {
+ layout: ctx.layout,
+ mutate: ctx.onLayoutChange,
+ commit: ctx.commit,
+ scheduleAutoSave: ctx.scheduleAutoSave,
+ };
+ } );
+ return null;
+}
+
+function readEngine(): EngineApi {
+ if ( ! engineRef.current ) {
+ throw new Error( 'EngineProbe not mounted yet' );
+ }
+ return engineRef.current;
+}
+
interface HarnessProps {
canPerform?: CanPerformDashboardOperation;
editMode?: boolean;
layout?: DashboardWidget[];
+ onLayoutChange?: ( next: DashboardWidget[] ) => void;
children?: React.ReactNode;
}
@@ -119,6 +150,7 @@ function Harness( {
canPerform,
editMode = false,
layout: seed = initialLayout,
+ onLayoutChange,
children,
}: HarnessProps ) {
const [ layout, setLayout ] = useState< DashboardWidget[] >( seed );
@@ -126,7 +158,10 @@ function Harness( {
const dashboard = (
{
+ onLayoutChange?.( next );
+ setLayout( next );
+ } }
widgetTypes={ widgetTypes }
editMode={ editMode }
onEditChange={ () => {} }
@@ -407,4 +442,199 @@ describe( 'WidgetDashboard.Policy instance operations', () => {
expect( screen.queryByTestId( 'label' ) ).not.toBeInTheDocument();
} );
+
+ describe( 'staging enforcement', () => {
+ const secondWidget: DashboardWidget = {
+ uuid: 'w2',
+ type: 'test/snapshot',
+ attributes: { metric: 'sales', label: 'Revenue' },
+ placement: { width: 1, height: 1 },
+ };
+
+ it( 'holds a move-denied instance and publishes nothing on Done', async () => {
+ const onLayoutChange = jest.fn();
+ const pinFirst: CanPerformDashboardOperation = ( request ) =>
+ ! (
+ request.operation === 'move' && request.widget.uuid === 'w1'
+ );
+ render(
+
+
+
+ );
+ await screen.findAllByTestId( 'label' );
+
+ act( () => {
+ const [ first, second ] = readEngine().layout;
+ readEngine().mutate( [ second, first ] );
+ } );
+
+ expect(
+ screen
+ .getAllByTestId( 'label' )
+ .map( ( node ) => node.textContent )
+ ).toEqual( [ 'Traffic', 'Revenue' ] );
+
+ act( () => {
+ readEngine().commit();
+ } );
+
+ expect( onLayoutChange ).not.toHaveBeenCalled();
+ } );
+
+ it( 'publishes only the allowed changes on Done', async () => {
+ const onLayoutChange = jest.fn();
+ const lockFirstEdit: CanPerformDashboardOperation = ( request ) =>
+ ! (
+ request.operation === 'edit' && request.widget.uuid === 'w1'
+ );
+ render(
+
+
+
+ );
+ await screen.findAllByTestId( 'label' );
+
+ act( () => {
+ const [ first, second ] = readEngine().layout;
+ readEngine().mutate( [
+ {
+ ...first,
+ attributes: { metric: 'views', label: 'Hijacked' },
+ },
+ {
+ ...second,
+ attributes: { metric: 'sales', label: 'Edited' },
+ },
+ ] );
+ } );
+
+ act( () => {
+ readEngine().commit();
+ } );
+
+ expect( onLayoutChange ).toHaveBeenCalledTimes( 1 );
+ expect(
+ onLayoutChange.mock.calls[ 0 ][ 0 ].map(
+ ( w: DashboardWidget< { label?: string } > ) =>
+ w.attributes?.label
+ )
+ ).toEqual( [ 'Traffic', 'Edited' ] );
+ } );
+
+ it( 'publishes nothing through the inline auto-save when every staged change was denied', async () => {
+ const onLayoutChange = jest.fn();
+ render(
+
+
+
+ );
+ await screen.findByTestId( 'label' );
+
+ jest.useFakeTimers();
+ try {
+ act( () => {
+ const [ first ] = readEngine().layout;
+ readEngine().mutate( [
+ {
+ ...first,
+ attributes: {
+ metric: 'views',
+ label: 'Hijacked',
+ },
+ },
+ ] );
+ readEngine().scheduleAutoSave();
+ } );
+
+ act( () => {
+ jest.runOnlyPendingTimers();
+ } );
+
+ expect( onLayoutChange ).not.toHaveBeenCalled();
+ } finally {
+ jest.useRealTimers();
+ }
+ } );
+
+ it( 'drops an insertion of a rejected type before it reaches a commit', async () => {
+ const onLayoutChange = jest.fn();
+ const rejectInserts: CanPerformDashboardOperation = ( request ) =>
+ request.operation !== 'insert';
+ render(
+
+
+
+ );
+ await screen.findByTestId( 'label' );
+
+ act( () => {
+ readEngine().mutate( [
+ ...readEngine().layout,
+ {
+ uuid: 'w-new',
+ type: 'test/snapshot',
+ placement: { width: 1, height: 1 },
+ },
+ ] );
+ } );
+
+ expect( screen.getAllByTestId( 'label' ) ).toHaveLength( 1 );
+
+ act( () => {
+ readEngine().commit();
+ } );
+
+ expect( onLayoutChange ).not.toHaveBeenCalled();
+ } );
+
+ it( 're-asserts the spans of a resize-denied instance in staging', async () => {
+ const onLayoutChange = jest.fn();
+ render(
+
+
+
+ );
+ await screen.findByTestId( 'label' );
+
+ act( () => {
+ const [ first ] = readEngine().layout;
+ readEngine().mutate( [
+ { ...first, placement: { width: 4, height: 2 } },
+ ] );
+ } );
+
+ expect( readEngine().layout[ 0 ].placement ).toEqual( {
+ width: 1,
+ height: 1,
+ } );
+
+ act( () => {
+ readEngine().commit();
+ } );
+
+ expect( onLayoutChange ).not.toHaveBeenCalled();
+ } );
+ } );
} );
diff --git a/packages/widget-dashboard/src/types.ts b/packages/widget-dashboard/src/types.ts
index f5d06024a3d40e..3bea25ca29ea73 100644
--- a/packages/widget-dashboard/src/types.ts
+++ b/packages/widget-dashboard/src/types.ts
@@ -195,7 +195,10 @@ export type DashboardInstanceOperation = 'remove' | 'move' | 'resize' | 'edit';
/**
* A request for an instance operation: the placed widget, and its type
- * when registered.
+ * when registered. The type is absent when it is not in `widgetTypes`
+ * (a plugin gone, a module that failed to load): the engine still asks,
+ * because the instance is still on the board, but a policy that keys
+ * locks on the type has nothing to match.
*/
export interface DashboardInstanceOperationRequest {
operation: DashboardInstanceOperation;
diff --git a/packages/widget-dashboard/src/utils/canonicalize-layout.ts b/packages/widget-dashboard/src/utils/canonicalize-layout.ts
new file mode 100644
index 00000000000000..1d39c33e471889
--- /dev/null
+++ b/packages/widget-dashboard/src/utils/canonicalize-layout.ts
@@ -0,0 +1,40 @@
+import type { DashboardWidget } from '../types';
+
+/**
+ * Canonical form of a layout: widgets sorted by `placement.order` (falling
+ * back to array index), then `order` stripped since position now implies
+ * it. The single positional encoding shared by the renderer, the commit
+ * payload, and the staging enforcement.
+ *
+ * Returns `layout` itself when it is already canonical, and keeps the
+ * reference of every widget without an `order` to strip, so untouched
+ * layouts stay identity-comparable.
+ *
+ * @param {DashboardWidget[]} layout Layout to canonicalize.
+ * @return {DashboardWidget[]} The canonical layout.
+ */
+export function canonicalizeLayout(
+ layout: DashboardWidget[]
+): DashboardWidget[] {
+ const indexed = layout.map( ( widget, index ) => ( {
+ widget,
+ order: widget.placement?.order ?? index,
+ } ) );
+
+ indexed.sort( ( a, b ) => a.order - b.order );
+
+ let changed = false;
+ const canonical = indexed.map( ( { widget }, index ) => {
+ if ( widget !== layout[ index ] ) {
+ changed = true;
+ }
+ if ( ! widget.placement || ! ( 'order' in widget.placement ) ) {
+ return widget;
+ }
+ changed = true;
+ const { order: _stripped, ...placement } = widget.placement;
+ return { ...widget, placement };
+ } );
+
+ return changed ? canonical : layout;
+}
diff --git a/packages/widget-dashboard/src/utils/enforce-layout-policy.ts b/packages/widget-dashboard/src/utils/enforce-layout-policy.ts
new file mode 100644
index 00000000000000..aa9456f4ab4cf6
--- /dev/null
+++ b/packages/widget-dashboard/src/utils/enforce-layout-policy.ts
@@ -0,0 +1,205 @@
+import fastDeepEqual from 'fast-deep-equal/es6/index.js';
+import type { WidgetType } from '@wordpress/widget-primitives';
+import { canonicalizeLayout } from './canonicalize-layout';
+import type {
+ CanPerformDashboardOperation,
+ DashboardInstanceOperation,
+ DashboardTilePlacement,
+ DashboardWidget,
+} from '../types';
+
+/*
+ * Placement fields by facet. `resize` owns the spans; `move` owns the
+ * masonry lane pin. Explicit `order` never reaches the diff: both
+ * layouts are canonicalized first, so position IS the array position.
+ */
+const SIZE_FIELDS = [ 'width', 'height' ] as const;
+const POSITION_FIELDS = [ 'lane' ] as const;
+
+type PlacementFields = readonly string[];
+
+function placementOf( widget: DashboardWidget ): Record< string, unknown > {
+ return ( widget.placement ?? {} ) as Record< string, unknown >;
+}
+
+function placementFieldsEqual(
+ a: DashboardWidget,
+ b: DashboardWidget,
+ fields: PlacementFields
+): boolean {
+ const pa = placementOf( a );
+ const pb = placementOf( b );
+ return fields.every( ( field ) => pa[ field ] === pb[ field ] );
+}
+
+function restorePlacementFields(
+ widget: DashboardWidget,
+ prior: DashboardWidget,
+ fields: PlacementFields
+): DashboardWidget {
+ const restored = { ...placementOf( widget ) };
+ const priorPlacement = placementOf( prior );
+ for ( const field of fields ) {
+ if ( field in priorPlacement ) {
+ restored[ field ] = priorPlacement[ field ];
+ } else {
+ delete restored[ field ];
+ }
+ }
+ if ( ! Object.keys( restored ).length && ! prior.placement ) {
+ const { placement: _dropped, ...rest } = widget;
+ return rest;
+ }
+ return { ...widget, placement: restored as DashboardTilePlacement };
+}
+
+interface EnforceLayoutPolicyArgs {
+ /**
+ * The staging layout the incoming one replaces.
+ */
+ previous: DashboardWidget[];
+
+ /**
+ * The incoming layout.
+ */
+ next: DashboardWidget[];
+
+ /**
+ * The resolved policy.
+ */
+ canPerform: CanPerformDashboardOperation;
+
+ /**
+ * Registered types, to resolve each instance's `WidgetType` for the
+ * policy request.
+ */
+ widgetTypes: WidgetType[];
+}
+
+/**
+ * Re-asserts every change the policy denies before a layout enters
+ * staging, so no composed trigger can slip a denied operation past the
+ * interface: what the UI hides, the staging layer rejects.
+ *
+ * Per instance: a new instance whose type the policy rejects for
+ * `insert` is dropped. An unregistered type has no type to ask about,
+ * so a new instance of one passes, and instance operations on a
+ * surviving tile still ask with `widgetType` absent: a lock keyed on
+ * the type does not fire. Denied `edit` keeps the staged `attributes`;
+ * denied `resize` keeps the placement spans; denied `move` keeps the
+ * masonry `lane` and holds the instance's canonical position, adjusted
+ * for allowed membership changes: the same hold `remove` uses, and the
+ * position the grid's pinned items keep.
+ *
+ * Both layouts are canonicalized before the diff (sorted by
+ * `order ?? index` with `order` stripped, as the renderer and the
+ * commit read them), so a move is a move whichever encoding expressed
+ * it. Returns `next` itself when it was already canonical and nothing
+ * was re-asserted.
+ *
+ * @param {EnforceLayoutPolicyArgs} args The layouts to diff and the policy.
+ * @return {DashboardWidget[]} The incoming layout with denied changes re-asserted.
+ */
+export function enforceLayoutPolicy( {
+ previous: rawPrevious,
+ next: rawNext,
+ canPerform,
+ widgetTypes,
+}: EnforceLayoutPolicyArgs ): DashboardWidget[] {
+ const previous = canonicalizeLayout( rawPrevious );
+ const next = canonicalizeLayout( rawNext );
+
+ const typeOf = ( widget: DashboardWidget ) =>
+ widgetTypes.find( ( type ) => type.name === widget.type );
+ const priorByUuid = new Map(
+ previous.map( ( widget ) => [ widget.uuid, widget ] )
+ );
+
+ // Instances free to take the position `next` gives them, in `next`
+ // order; move-denied survivors are staged aside to be held instead.
+ const free: DashboardWidget[] = [];
+ const heldByUuid = new Map< string, DashboardWidget >();
+
+ for ( const incoming of next ) {
+ const prior = priorByUuid.get( incoming.uuid );
+
+ if ( ! prior ) {
+ const widgetType = typeOf( incoming );
+ if (
+ widgetType &&
+ ! canPerform( { operation: 'insert', widgetType } )
+ ) {
+ continue;
+ }
+ free.push( incoming );
+ continue;
+ }
+
+ const widgetType = typeOf( prior );
+ const allows = ( operation: DashboardInstanceOperation ) =>
+ canPerform( { operation, widget: prior, widgetType } );
+
+ let staged = incoming;
+ if (
+ ! fastDeepEqual( prior.attributes, incoming.attributes ) &&
+ ! allows( 'edit' )
+ ) {
+ staged = { ...staged };
+ if ( 'attributes' in prior ) {
+ staged.attributes = prior.attributes;
+ } else {
+ delete staged.attributes;
+ }
+ }
+ if (
+ ! placementFieldsEqual( prior, staged, SIZE_FIELDS ) &&
+ ! allows( 'resize' )
+ ) {
+ staged = restorePlacementFields( staged, prior, SIZE_FIELDS );
+ }
+
+ if ( allows( 'move' ) ) {
+ free.push( staged );
+ continue;
+ }
+ if ( ! placementFieldsEqual( prior, staged, POSITION_FIELDS ) ) {
+ staged = restorePlacementFields( staged, prior, POSITION_FIELDS );
+ }
+ heldByUuid.set( staged.uuid, staged );
+ }
+
+ // Walk `previous` to place what holds a position: move-denied
+ // survivors and denied removals land at their previous index,
+ // discounting the instances that legitimately left.
+ const nextUuids = new Set( next.map( ( widget ) => widget.uuid ) );
+ const result = [ ...free ];
+ let absent = 0;
+ const place = ( widget: DashboardWidget, index: number ) =>
+ result.splice( Math.min( index - absent, result.length ), 0, widget );
+
+ previous.forEach( ( widget, index ) => {
+ if ( ! nextUuids.has( widget.uuid ) ) {
+ const removable = canPerform( {
+ operation: 'remove',
+ widget,
+ widgetType: typeOf( widget ),
+ } );
+ if ( removable ) {
+ absent += 1;
+ return;
+ }
+ place( widget, index );
+ return;
+ }
+
+ const held = heldByUuid.get( widget.uuid );
+ if ( held ) {
+ place( held, index );
+ }
+ } );
+
+ const untouched =
+ result.length === next.length &&
+ result.every( ( widget, index ) => widget === next[ index ] );
+ return untouched ? next : result;
+}