From 3f2ac3e15335b97ddafb4402e98c4158afc5404f Mon Sep 17 00:00:00 2001 From: Dave Smith Date: Mon, 16 Nov 2026 10:50:49 +0000 Subject: [PATCH 1/3] Site overview: rearrange pages and the main menu by dragging MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Adds a Rearrange mode to the Site overview. Drag a page onto another to put it under it, onto its edge to put it beside it, or onto the homepage to move it to the top level. A Main menu tray along the top takes pages dropped on it, reorders by dragging its pills, and takes items out with their ×, by dragging them off, or from a switch on each card. The menu stays tied to the pages: an auto menu stays an auto menu, its order follows page order, and pages are left out rather than the menu being set by hand. Every change is an unsaved edit, through the same helpers the Pages screen uses, so it waits for Save and can be undone. Co-Authored-By: Claude Opus 5.5 --- src/routes/content/pages/menu-switches.js | 102 +++- src/routes/site-overview/_style.scss | 240 +++++++++ src/routes/site-overview/arrange.js | 200 ++++++++ src/routes/site-overview/canvas.jsx | 135 +++++- src/routes/site-overview/card.jsx | 43 +- src/routes/site-overview/menu-tray.jsx | 231 +++++++++ src/routes/site-overview/use-arrange.js | 566 ++++++++++++++++++++++ 7 files changed, 1480 insertions(+), 37 deletions(-) create mode 100644 src/routes/site-overview/arrange.js create mode 100644 src/routes/site-overview/menu-tray.jsx create mode 100644 src/routes/site-overview/use-arrange.js diff --git a/src/routes/content/pages/menu-switches.js b/src/routes/content/pages/menu-switches.js index 9831dbdb..e4deee83 100644 --- a/src/routes/content/pages/menu-switches.js +++ b/src/routes/content/pages/menu-switches.js @@ -307,7 +307,34 @@ export function useMenuSwitches( { homepage, menuId, pages } ) { }; }; - const toggle = ( target ) => { + /** + * Put a top-level item of a menu set by hand in another place. + * + * @param {Object[]} items Top-level blocks. + * @param {number} from Its place now. + * @param {number} to Its place once moved. + * @return {Object[]} Blocks. + */ + const placeTopLevel = ( items, from, to ) => { + const next = items.slice(); + const [ item ] = next.splice( from, 1 ); + + next.splice( Math.max( 0, Math.min( to, next.length ) ), 0, item ); + + return next; + }; + + /** + * Switch a page in or out of the menu. + * + * @param {number|string} target Page ID, or `HOMEPAGE`. + * @param {Object} [options] + * @param {number} [options.index] Where at the top of a menu set by + * hand it goes, rather than the end. + * A menu that lists pages keeps + * them in page order. + */ + const toggle = ( target, { index } = {} ) => { if ( getSwitch( target ).disabled ) { return; } @@ -350,8 +377,10 @@ export function useMenuSwitches( { homepage, menuId, pages } ) { // The homepage goes in as a Home link, first, whatever it shows. if ( target === HOMEPAGE ) { + const next = addItemFirst( blocks, createHomeLink() ); + apply( - addItemFirst( blocks, createHomeLink() ), + index === undefined ? next : placeTopLevel( next, 0, index ), __( 'Your homepage is in your menu.' ) ); @@ -365,28 +394,40 @@ export function useMenuSwitches( { homepage, menuId, pages } ) { const parentPlace = parentId ? getItemPlace( blocks, ( block ) => isPageItem( block, parentId ) ) : null; - const under = parentPlace?.depth === 0 ? parentId : 0; - const next = addItem( + const under = + parentPlace?.depth === 0 && index === undefined ? parentId : 0; + let next = addItem( blocks, createPageLink( page ), under ? ( block ) => isPageItem( block, under ) : null ); - apply( - next, - under - ? sprintf( - /* translators: 1: page title, 2: parent page title. */ - __( '“%1$s” added to the %2$s dropdown.' ), - title, - getPageTitle( pagesById.get( under ) ) - ) - : sprintf( - /* translators: %s: page title. */ - __( '“%s” added to the end of your menu.' ), - title - ) + if ( ! under && index !== undefined ) { + next = placeTopLevel( next, next.length - 1, index ); + } + + let message = sprintf( + /* translators: %s: page title. */ + __( '“%s” added to the end of your menu.' ), + title ); + + if ( under ) { + message = sprintf( + /* translators: 1: page title, 2: parent page title. */ + __( '“%1$s” added to the %2$s dropdown.' ), + title, + getPageTitle( pagesById.get( under ) ) + ); + } else if ( index !== undefined ) { + message = sprintf( + /* translators: %s: page title. */ + __( '“%s” added to your menu.' ), + title + ); + } + + apply( next, message ); }; /** @@ -491,10 +532,35 @@ export function useMenuSwitches( { homepage, menuId, pages } ) { } }; + /** + * Move a top-level item of a menu set by hand to another place. + * + * @param {number} from Its place now. + * @param {number} to Its place once moved. + * @param {string} label What the item says, to say what moved. + */ + const moveTopLevelItem = ( from, to, label ) => { + if ( listsPages || from === to ) { + return; + } + + apply( + placeTopLevel( blocks, from, to ), + sprintf( + /* translators: %s: Menu item label. */ + __( 'Moved “%s” in your menu.' ), + label + ) + ); + }; + return { + blocks, getMenuMoves, getSwitch, isAutomatic, + listsPages, + moveTopLevelItem, isReady: Boolean( edited ), removePage, toggle, diff --git a/src/routes/site-overview/_style.scss b/src/routes/site-overview/_style.scss index f61ccd2c..1e050d0b 100644 --- a/src/routes/site-overview/_style.scss +++ b/src/routes/site-overview/_style.scss @@ -509,3 +509,243 @@ $cnl-site-overview-canvas: #e9eef2; .cnl-site-overview__selected-detail { color: var(--wpds-color-foreground-content-neutral-weak); } + +// --------------------------------------------------------------------------- +// Rearrange: pages dragged onto each other, and into the main menu. +// --------------------------------------------------------------------------- + +.cnl-site-overview__viewport.is-arranging { + user-select: none; + + .cnl-site-overview-card.is-draggable, + .cnl-site-overview-card.is-draggable .cnl-site-overview-card__select { + cursor: grab; + } + + &.is-dragging-page, + &.is-dragging-page .cnl-site-overview-card, + &.is-dragging-page .cnl-site-overview-card__select { + cursor: grabbing; + } +} + +.cnl-site-overview-card { + + &.is-dragged { + opacity: 0.4; + } + + // Under this page. + &.is-drop-under, + &.is-drop-top { + border-color: $cnl-site-overview-accent; + box-shadow: + 0 0 0 cnl-site-overview-screen-px(3px) $cnl-site-overview-accent, + $cnl-rest-shadow; + } + + // Beside this page: a bar in the gap on that side. + &.is-drop-before::before, + &.is-drop-after::after { + content: ""; + position: absolute; + top: 0; + bottom: 0; + width: cnl-site-overview-screen-px(4px); + border-radius: 2px; + background: $cnl-site-overview-accent; + } + + &.is-drop-before::before { + inset-inline-start: -22px; + } + + &.is-drop-after::after { + inset-inline-end: -22px; + } +} + +// The menu as a bucket along the top, where the menu sits on most sites. It +// takes a row of its own, so it never covers a page. +.cnl-site-overview__body.is-arranging { + grid-template-rows: auto minmax(0, 1fr); + + > .cnl-site-overview__viewport { + grid-area: 2 / 1; + } +} + +.cnl-site-overview-menu-tray { + grid-area: 1 / 1; + justify-self: center; + display: flex; + gap: 16px; + align-items: center; + box-sizing: border-box; + width: min(720px, calc(100% - 32px)); + min-height: 56px; + margin: 16px 0 0; + padding: 8px 16px; + border: 2px dashed var(--wpds-color-stroke-surface-neutral-strong); + border-radius: var(--wpds-border-radius-lg); + background: rgba(255, 255, 255, 0.92); + transition: + border-color var(--wpds-motion-duration-sm) var(--wpds-motion-easing-subtle), + background-color var(--wpds-motion-duration-sm) var(--wpds-motion-easing-subtle); + + &.is-dragging { + border-color: $cnl-site-overview-accent; + } + + &.is-over { + background: color-mix(in srgb, $cnl-site-overview-accent 10%, #fff); + } +} + +.cnl-site-overview-menu-tray__header { + display: flex; + flex: none; + flex-direction: column; +} + +.cnl-site-overview-menu-tray__title { + font-size: 13px; + font-weight: 600; +} + +.cnl-site-overview-menu-tray__subtitle { + color: var(--wpds-color-foreground-content-neutral-weak); + font-size: 12px; +} + +.cnl-site-overview-menu-tray__empty { + margin: 0; + color: var(--wpds-color-foreground-content-neutral-weak); + font-size: 13px; +} + +.cnl-site-overview-menu-tray__items { + display: flex; + flex-wrap: wrap; + gap: 8px; + align-items: flex-start; + margin: 0; + padding: 0; + list-style: none; +} + +.cnl-site-overview-menu-tray__item { + display: inline-flex; + gap: 2px; + align-items: center; + margin: 0; + padding-inline-start: 10px; + border: 1px solid var(--wpds-color-stroke-surface-neutral); + border-radius: var(--wpds-border-radius-md); + background: #fff; + font-size: 13px; + + // Links that aren't to a page keep the chip's padding on both sides. + > span:last-child { + padding: 4px 10px 4px 0; + } +} + +// Pills that can be dragged into a new order. +.cnl-site-overview-menu-tray__item.is-movable { + cursor: grab; + user-select: none; + touch-action: none; +} + +.cnl-site-overview-menu-tray__item.is-dragged { + opacity: 0.4; +} + +// Where a pill, or a page, will land. +.cnl-site-overview-menu-tray__marker { + align-self: stretch; + width: 3px; + margin: 0 -5px; + border-radius: 2px; + background: $cnl-site-overview-accent; +} + +// A top-level item, with the items in its dropdown hanging under it. +.cnl-site-overview-menu-tray__group { + display: flex; + flex-direction: column; + gap: 4px; + align-items: flex-start; + margin: 0; +} + +.cnl-site-overview-menu-tray__sub-items { + display: flex; + flex-direction: column; + gap: 4px; + align-items: flex-start; + margin: 0; + padding-inline-start: 12px; + border-inline-start: 1px solid var(--wpds-color-stroke-surface-neutral); + list-style: none; + + > li { + margin: 0; + } + + .cnl-site-overview-menu-tray__item { + font-size: 12px; + } +} + +// Whether the page is in the main menu, switched from its card. +.cnl-site-overview-card__caption { + position: relative; +} + +.cnl-site-overview-card__menu-toggle.components-button { + position: absolute; + inset-inline-end: 8px; + bottom: 8px; + height: 24px; + padding-inline: 4px 8px; + border-radius: var(--wpds-border-radius-md); + font-size: 11px; + + &.is-on { + background: color-mix(in srgb, #{$cnl-site-overview-accent} 12%, #fff); + color: $cnl-site-overview-accent; + } + + &.is-off { + box-shadow: inset 0 0 0 1px var(--wpds-color-stroke-surface-neutral); + color: var(--wpds-color-foreground-content-neutral-weak); + } +} + +// What dropping here will do, following the pointer. +.cnl-site-overview__drag-label { + position: fixed; + z-index: 100000; + display: flex; + flex-direction: column; + gap: 2px; + padding: 6px 10px; + border-radius: var(--wpds-border-radius-md); + background: var(--wpds-color-background-interactive-neutral-strong); + color: #fff; + font-size: 12px; + line-height: 1.4; + white-space: nowrap; + pointer-events: none; + translate: 14px 14px; +} + +.cnl-site-overview__drag-title { + font-weight: 600; +} + +.cnl-site-overview__drag-action { + opacity: 0.8; +} diff --git a/src/routes/site-overview/arrange.js b/src/routes/site-overview/arrange.js new file mode 100644 index 00000000..56a2f373 --- /dev/null +++ b/src/routes/site-overview/arrange.js @@ -0,0 +1,200 @@ +/** + * Rearranging the Site overview: pages dragged onto each other, and into the + * main menu. Kept free of React so it can be tested on its own. + */ + +/** + * Internal dependencies + */ +import { getPageMoveChanges } from '../content/pages/page-tree'; + +// How far into a card, from either side, a drop puts the page beside it +// rather than under it. +export const SIDE_DROP_FRACTION = 0.25; + +const pageNodeId = ( pageId ) => `page-${ pageId }`; + +/** + * The overview with the pages where their unsaved changes put them: each + * hand-made page under its new parent and in its new place among the pages + * beside it. + * + * Pages the overview leaves out, like the homepage's own page, still count + * as parents: a page under one hangs from the nearest page that is drawn, or + * from the homepage. + * + * @param {Object} siteOverview Site overview from the REST API. + * @param {Object[]} tree Pages as a tree, from `buildPageTree`. + * @return {Object} Site overview. + */ +export function applyPageTree( siteOverview, tree ) { + if ( ! siteOverview || ! tree?.length ) { + return siteOverview; + } + + const pageNodes = new Map( + siteOverview.nodes + .filter( ( node ) => node.kind === 'page' ) + .map( ( node ) => [ node.id, node ] ) + ); + const orderedNodes = []; + const pageEdges = []; + + const visit = ( items, drawnParent ) => + items.forEach( ( item ) => { + const id = pageNodeId( item.page.id ); + + if ( ! pageNodes.has( id ) ) { + visit( item.children, drawnParent ); + return; + } + + orderedNodes.push( pageNodes.get( id ) ); + pageNodes.delete( id ); + pageEdges.push( { from: drawnParent, kind: 'child', to: id } ); + visit( item.children, id ); + } ); + + visit( tree, 'home' ); + + const placed = new Set( orderedNodes.map( ( node ) => node.id ) ); + + return { + ...siteOverview, + edges: [ + ...pageEdges, + ...siteOverview.edges.filter( ( edge ) => ! placed.has( edge.to ) ), + ], + nodes: [ + ...siteOverview.nodes.filter( ( node ) => node.kind !== 'page' ), + ...orderedNodes, + // Pages the tree doesn't know, left where the server put them. + ...pageNodes.values(), + ], + }; +} + +function findInTree( items, pageId, parent = 0 ) { + for ( let index = 0; index < items.length; index++ ) { + const item = items[ index ]; + + if ( Number( item.page.id ) === pageId ) { + return { index, item, parent, siblings: items }; + } + + const found = findInTree( + item.children, + pageId, + Number( item.page.id ) + ); + + if ( found ) { + return found; + } + } + + return null; +} + +function containsPage( item, pageId ) { + return item.children.some( + ( child ) => + Number( child.page.id ) === pageId || containsPage( child, pageId ) + ); +} + +/** + * Where a drop on a card puts a page, from how far across the card it lands. + * + * @param {number} fraction How far across the card, 0 to 1. + * @return {string} `before`, `under` or `after`. + */ +export function getDropPosition( fraction ) { + if ( fraction < SIDE_DROP_FRACTION ) { + return 'before'; + } + + if ( fraction > 1 - SIDE_DROP_FRACTION ) { + return 'after'; + } + + return 'under'; +} + +/** + * Whether one page can be dropped on another: not on itself, nor on a page + * under it. + * + * @param {Object[]} tree Pages as a tree. + * @param {number} pageId Page being dragged. + * @param {number} targetId Page it would be dropped on. + * @return {boolean} Whether it can. + */ +export function canDropOnPage( tree, pageId, targetId ) { + if ( pageId === targetId ) { + return false; + } + + const dragged = findInTree( tree, pageId ); + + return Boolean( dragged ) && ! containsPage( dragged.item, targetId ); +} + +/** + * The page changes a drop makes. + * + * @param {Object[]} tree Pages as a tree. + * @param {number} pageId Page being dropped. + * @param {Object} drop `{ position, targetId }`, where + * `position` is `before`, `after`, + * `under`, or `top` for the top + * level, at the end. + * @param {Object} [options] + * @param {number} [options.frontPageId] The homepage's page. + * @return {Object[]} `{ id, parent, menu_order }` for each page that changes. + */ +export function getDropChanges( tree, pageId, drop, { frontPageId = 0 } = {} ) { + if ( drop.position === 'top' ) { + return getPageMoveChanges( + tree, + pageId, + { index: tree.length, parent: 0 }, + { frontPageId } + ); + } + + if ( ! canDropOnPage( tree, pageId, drop.targetId ) ) { + return []; + } + + const target = findInTree( tree, drop.targetId ); + + if ( drop.position === 'under' ) { + return getPageMoveChanges( + tree, + pageId, + { + index: target.item.children.filter( + ( child ) => Number( child.page.id ) !== pageId + ).length, + parent: drop.targetId, + }, + { frontPageId } + ); + } + + // Its place among the target's siblings once it has left them. + const index = target.siblings + .filter( ( item ) => Number( item.page.id ) !== pageId ) + .findIndex( ( item ) => Number( item.page.id ) === drop.targetId ); + + return getPageMoveChanges( + tree, + pageId, + { + index: index + ( drop.position === 'after' ? 1 : 0 ), + parent: target.parent, + }, + { frontPageId } + ); +} diff --git a/src/routes/site-overview/canvas.jsx b/src/routes/site-overview/canvas.jsx index 56a7c5f3..09d2a8e9 100644 --- a/src/routes/site-overview/canvas.jsx +++ b/src/routes/site-overview/canvas.jsx @@ -34,8 +34,11 @@ import { MemoizedStackSheets, } from './lanes'; import { ZoomControls } from './zoom-controls'; +import { MenuTray } from './menu-tray'; +import useArrange from './use-arrange'; import { SelectedPage } from './selected-page'; import { + Button, Notice, Page, Spinner, @@ -96,6 +99,19 @@ export default function Canvas() { const didFitRef = useRef( false ); const boundsRef = useRef( null ); const hasSize = size.width > 0 && size.height > 0; + const [ isArranging, setIsArranging ] = useState( false ); + // The click that ends dragging a page shouldn't select one. + const onDragEnd = useCallback( () => { + suppressClickRef.current = true; + setTimeout( () => { + suppressClickRef.current = false; + } ); + }, [] ); + const arrange = useArrange( { + isArranging, + onDragEnd, + siteOverview, + } ); viewRef.current = view; sizeRef.current = size; @@ -131,8 +147,9 @@ export default function Canvas() { }, [ invalidateSiteOverview ] ); const layout = useMemo( - () => ( siteOverview ? layoutSiteOverview( siteOverview ) : null ), - [ siteOverview ] + () => + arrange.overview ? layoutSiteOverview( arrange.overview ) : null, + [ arrange.overview ] ); boundsRef.current = layout?.bounds || null; const scaleLimits = @@ -503,13 +520,23 @@ export default function Canvas() { return ( + <> + + + } className="cnl-editor-stage cnl-editor-content-page cnl-site-overview-page" hasPadding={ false } @@ -522,14 +549,23 @@ export default function Canvas() { .join( ' · ' ) } title={ __( 'Site overview' ) } > -
+
{ /* eslint-disable-next-line jsx-a11y/no-noninteractive-element-interactions -- The canvas pans and zooms from the pointer and keyboard. */ }
( - { __( - 'Drag or scroll to move around. Pinch, or hold Ctrl or ⌘ and scroll, to zoom. Click a page for details, or double-click it to edit it.' - ) } + { isArranging + ? __( + 'Drag a page onto another to put it under it, or onto its edge to put it beside it. Drag a page into Main menu to add it, or drag an item out of Main menu to take it out.' + ) + : __( + 'Drag or scroll to move around. Pinch, or hold Ctrl or ⌘ and scroll, to zoom. Click a page for details, or double-click it to edit it.' + ) }

- { selectedNode && hasSize && ( + { isArranging && ( + + ) } + { arrange.drag && ( +
+ + { arrange.drag.title } + + { arrange.drag.label && ( + + { arrange.drag.label } + + ) } +
+ ) } + { selectedNode && hasSize && ! isArranging && ( onOpen( node ) } onMouseEnter={ () => onHover( node.id ) } onMouseLeave={ () => onHover( '' ) } + onPointerDown={ + isDraggable + ? ( event ) => onDragStart( event, node ) + : undefined + } style={ { height: node.height, left: node.x, @@ -152,6 +176,23 @@ function SiteOverviewCard( { ) }
+ { menuState && ( + + ) }
); diff --git a/src/routes/site-overview/menu-tray.jsx b/src/routes/site-overview/menu-tray.jsx new file mode 100644 index 00000000..5354bc7b --- /dev/null +++ b/src/routes/site-overview/menu-tray.jsx @@ -0,0 +1,231 @@ +/** + * The main menu as a tray along the top of the Site overview, while it is + * being rearranged. Each top-level item is a pill, with the items in its + * dropdown under it. Pages dropped on it join the menu, pills dragged along it + * change its order, and any item can be taken out, with its × or by dragging + * it off the tray. + */ + +/** + * Internal dependencies + */ +import { getPageTitle } from '../content/pages/data'; +import { HOMEPAGE } from '../content/pages/homepage-state'; +import { getNavigationItemLabel } from '../navigation-edit/navigation-blocks'; +import { Button, __, closeSmallIcon, sprintf } from '../../wordpress-packages'; + +/** + * The menu's items, each with the page or homepage it links to and the items + * under it. A Page List stands for the pages it lists, nested as they are. + * + * @param {Object} args Arguments. + * @param {Object[]} args.blocks The menu's blocks. + * @param {Object[]} args.tree Pages as a tree. + * @param {Function} args.getSwitch From `useMenuSwitches`. + * @param {number} args.frontPageId The homepage's page. + * @return {Object[]} `{ children, key, label, pageId, target }`, `target` + * null for links that aren't to a page. + */ +export function getMenuTrayItems( { blocks, tree, getSwitch, frontPageId } ) { + const getTarget = ( id ) => ( id === frontPageId ? HOMEPAGE : id ); + const fromPages = ( items ) => + items + .filter( + ( item ) => + item.page.status === 'publish' && + getSwitch( Number( item.page.id ) ).checked + ) + .map( ( item ) => ( { + children: fromPages( item.children ), + key: `page-${ item.page.id }`, + label: getPageTitle( item.page ), + pageId: Number( item.page.id ), + target: getTarget( Number( item.page.id ) ), + } ) ); + const fromBlocks = ( items, prefix ) => + ( items || [] ).flatMap( ( block, index ) => { + const attributes = block.attributes || {}; + + if ( block.name === 'core/page-list' ) { + return fromPages( tree ); + } + + let target = null; + + if ( block.name === 'core/home-link' ) { + target = HOMEPAGE; + } else if ( attributes.type === 'page' && attributes.id ) { + target = getTarget( Number( attributes.id ) ); + } + + const key = `${ prefix }${ index }`; + + return [ + { + children: fromBlocks( block.innerBlocks, `${ key }-` ), + key: `${ block.name }-${ key }`, + label: getNavigationItemLabel( block ), + pageId: Number( attributes.id ) || 0, + target, + }, + ]; + } ); + + return fromBlocks( blocks, '' ); +} + +function Pill( { + draggedKey, + index, + isMovable, + item, + onPointerDown, + onRemove, +} ) { + const canTakeOut = item.target !== null; + + return ( +
onPointerDown( event, item, index ) + : undefined + } + > + { item.label } + { canTakeOut && ( +
+ ); +} + +function SubItems( { items, ...props } ) { + if ( ! items.length ) { + return null; + } + + return ( +
    + { items.map( ( item ) => ( +
  • + + +
  • + ) ) } +
+ ); +} + +export function MenuTray( { + canReorder, + draggedKey, + hasMenu, + insertIndex, + isAutomatic, + isDragging, + isOver, + items, + menuTitle, + onItemPointerDown, + onRemove, +} ) { + const className = [ + 'cnl-site-overview-menu-tray', + isDragging && 'is-dragging', + isOver && 'is-over', + ] + .filter( Boolean ) + .join( ' ' ); + let subtitle = ''; + + if ( isAutomatic ) { + subtitle = __( 'Auto menu, in page order' ); + } else if ( menuTitle && menuTitle !== __( 'Main menu' ) ) { + subtitle = menuTitle; + } + + const pillProps = { + draggedKey, + onPointerDown: onItemPointerDown, + onRemove, + }; + const marker = ( +
  • + ); + const groups = items.flatMap( ( item, index ) => { + const group = ( +
  • + + +
  • + ); + + return index === insertIndex ? [ marker, group ] : [ group ]; + } ); + + if ( insertIndex === items.length ) { + groups.push( marker ); + } + + return ( +
    +
    + + { __( 'Main menu' ) } + + { subtitle && ( + + { subtitle } + + ) } +
    + { ! hasMenu && ( +

    + { __( 'Your site has no menu yet.' ) } +

    + ) } + { hasMenu && ! items.length && ( +

    + { isOver + ? __( 'Drop to add it to your menu' ) + : __( 'Drag pages here to add them to your menu' ) } +

    + ) } + { hasMenu && !! items.length && ( +
      + { groups } +
    + ) } +
    + ); +} diff --git a/src/routes/site-overview/use-arrange.js b/src/routes/site-overview/use-arrange.js new file mode 100644 index 00000000..e5ca69f6 --- /dev/null +++ b/src/routes/site-overview/use-arrange.js @@ -0,0 +1,566 @@ +/** + * Rearranging the Site overview: dragging a page onto another to put it + * under it or beside it, and dragging pages into the main menu. + * + * Every change is an unsaved edit, the same ones the Pages screen makes, so + * it waits for Save with the rest and comes with a way to undo it. The map + * shows the pages where those edits put them at once. + */ + +/** + * Internal dependencies + */ +import { usePages } from '../content/pages/data'; +import { useHomepageState } from '../content/pages/homepage'; +import { HOMEPAGE } from '../content/pages/homepage-state'; +import { useMenuSwitches } from '../content/pages/menu-switches'; +import usePageOrder from '../content/pages/use-page-order'; +import useMainMenu from '../content/use-main-menu'; +import { + applyPageTree, + canDropOnPage, + getDropChanges, + getDropPosition, +} from './arrange'; +import { getMenuTrayItems } from './menu-tray'; +import { + __, + noticesStore, + sprintf, + useCallback, + useDispatch, + useEffect, + useMemo, + useRef, + useState, +} from '../../wordpress-packages'; + +const DRAG_THRESHOLD = 4; +const TRAY_SELECTOR = '.cnl-site-overview-menu-tray'; +// Top-level pills only: the items in their dropdowns move with them. +const PILL_SELECTOR = + '.cnl-site-overview-menu-tray__group > .cnl-site-overview-menu-tray__item'; + +/** + * What a card stands for in the menu: the homepage, a page, or the page a + * collection is listed on. + * + * @param {Object} node Site overview node. + * @return {number|string|null} Page ID, `HOMEPAGE`, or null. + */ +export function getMenuTarget( node ) { + if ( node?.kind === 'home' ) { + return HOMEPAGE; + } + + if ( + ( node?.kind === 'page' || node?.kind === 'collection' ) && + node.postId + ) { + return Number( node.postId ); + } + + return null; +} + +/** + * What dropping here will do, in words, for the label that follows the + * pointer. + * + * @param {Object} drop Drop target. + * @param {Map} nodesById Overview nodes. + * @return {string} Label. + */ +function getDropLabel( drop, nodesById ) { + const title = nodesById.get( drop?.nodeId )?.title || ''; + + switch ( drop?.position ) { + case 'menu': + return __( 'Add to menu' ); + case 'remove': + return __( 'Take out of menu' ); + case 'reorder': + return __( 'Move here in menu' ); + case 'top': + return __( 'Move to the top level' ); + case 'under': + /* translators: %s: Page title. */ + return sprintf( __( 'Put under “%s”' ), title ); + case 'before': + /* translators: %s: Page title. */ + return sprintf( __( 'Move before “%s”' ), title ); + case 'after': + /* translators: %s: Page title. */ + return sprintf( __( 'Move after “%s”' ), title ); + default: + return ''; + } +} + +/** + * @param {Object} args Arguments. + * @param {boolean} args.isArranging Whether the map is being rearranged. + * @param {Object} args.siteOverview Site overview from the REST API. + * @param {Function} args.onDragEnd Called when a drag ends, so the click + * that ends it doesn't select a page. + * @return {Object} The overview to draw, the menu, and the drag. + */ +export default function useArrange( { isArranging, siteOverview, onDragEnd } ) { + const { frontPageId, isLoading, pages } = usePages(); + const { movePages, tree } = usePageOrder( { frontPageId, pages } ); + const homepage = useHomepageState(); + const mainMenu = useMainMenu(); + const switches = useMenuSwitches( { + homepage, + menuId: mainMenu.menuId, + pages, + } ); + const { createInfoNotice } = useDispatch( noticesStore ); + const [ drag, setDrag ] = useState( null ); + + const overview = useMemo( + () => + isLoading || ! pages.length + ? siteOverview + : applyPageTree( siteOverview, tree ), + [ isLoading, pages.length, siteOverview, tree ] + ); + const nodesById = useMemo( + () => + new Map( + ( overview?.nodes || [] ).map( ( node ) => [ node.id, node ] ) + ), + [ overview ] + ); + const menuItems = useMemo( + () => + switches.isReady + ? getMenuTrayItems( { + blocks: switches.blocks, + frontPageId, + getSwitch: switches.getSwitch, + tree, + } ) + : [], + // `getSwitch` is new each render; the blocks and tree are what it reads. + // eslint-disable-next-line react-hooks/exhaustive-deps + [ switches.isReady, switches.blocks, frontPageId, tree, pages ] + ); + const menuTargets = useMemo( () => { + const targets = new Set(); + const visit = ( items ) => + items.forEach( ( item ) => { + targets.add( item.target ); + visit( item.children ); + } ); + + visit( menuItems ); + + return targets; + }, [ menuItems ] ); + + // Pills can be put in order in a menu set by hand, and in an auto menu, + // whose order is the pages' own. A menu mixing the two is left to the + // Menus screen. + const canReorderMenu = + switches.isReady && + menuItems.length > 1 && + ( ! switches.listsPages || switches.isAutomatic ); + + // The drag's handlers live for the whole drag, so they read the latest + // pages and menu from here. + const latest = useRef(); + latest.current = { + // A page dropped on a menu set by hand goes where it lands. An auto + // menu keeps page order. + canPlaceInMenu: switches.isReady && ! switches.listsPages, + canReorderMenu, + frontPageId, + menuItems, + menuId: mainMenu.menuId, + menuTargets, + movePages, + nodesById, + switches, + tree, + }; + + const isDraggable = useCallback( + ( node ) => + isArranging && + ( node.kind === 'page' || getMenuTarget( node ) !== null ), + [ isArranging ] + ); + + /** + * Where among the pills a drop at the pointer lands: before the first pill + * the pointer is left of, or above, or else at the end. + * + * @param {Document} doc Document. + * @param {number} clientX Pointer. + * @param {number} clientY Pointer. + * @return {number} Index, 0 to the number of pills. + */ + const getMenuIndex = ( doc, clientX, clientY ) => { + const pills = [ ...doc.querySelectorAll( PILL_SELECTOR ) ]; + const index = pills.findIndex( ( pill ) => { + const rect = pill.getBoundingClientRect(); + + return ( + clientY < rect.top || + ( clientY <= rect.bottom && + clientX < rect.left + rect.width / 2 ) + ); + } ); + + return index === -1 ? pills.length : index; + }; + + const getCardDrop = ( node, clientX, clientY, doc ) => { + const current = latest.current; + const element = doc.elementFromPoint( clientX, clientY ); + + if ( element?.closest( TRAY_SELECTOR ) ) { + if ( ! current.menuId || getMenuTarget( node ) === null ) { + return null; + } + + return { + index: current.canPlaceInMenu + ? getMenuIndex( doc, clientX, clientY ) + : undefined, + position: 'menu', + }; + } + + const card = element?.closest( '[data-node-id]' ); + + if ( ! card || node.kind !== 'page' ) { + return null; + } + + const nodeId = card.getAttribute( 'data-node-id' ); + + if ( nodeId === 'home' ) { + return { nodeId, position: 'top' }; + } + + const target = current.nodesById.get( nodeId ); + + if ( + target?.kind !== 'page' || + ! canDropOnPage( + current.tree, + Number( node.postId ), + Number( target.postId ) + ) + ) { + return null; + } + + const rect = card.getBoundingClientRect(); + + return { + nodeId, + position: getDropPosition( ( clientX - rect.left ) / rect.width ), + targetId: Number( target.postId ), + }; + }; + + const dropCard = ( node, target ) => { + const current = latest.current; + + if ( target.position === 'menu' ) { + const menuTarget = getMenuTarget( node ); + const state = current.switches.getSwitch( menuTarget ); + + if ( current.menuTargets.has( menuTarget ) || state.checked ) { + createInfoNotice( + sprintf( + /* translators: %s: Page title. */ + __( '“%s” is already in your menu.' ), + node.title + ), + { id: 'cnl-site-overview-menu', type: 'snackbar' } + ); + } else if ( state.disabled ) { + createInfoNotice( state.note, { + id: 'cnl-site-overview-menu', + type: 'snackbar', + } ); + } else { + current.switches.toggle( menuTarget, { index: target.index } ); + } + + return; + } + + current.movePages( + getDropChanges( current.tree, Number( node.postId ), target, { + frontPageId: current.frontPageId, + } ) + ); + }; + + /** + * Where a dragged pill would go: off the tray takes it out of the menu, + * and along the top row puts it in a new place. + * + * @param {Object} item The pill's menu item. + * @param {?number} from Its place in the top row, if it is in it. + * @param {number} clientX Pointer. + * @param {number} clientY Pointer. + * @param {Document} doc Document. + * @return {?Object} Drop, or null. + */ + const getPillDrop = ( item, from, clientX, clientY, doc ) => { + const element = doc.elementFromPoint( clientX, clientY ); + + if ( ! element?.closest( TRAY_SELECTOR ) ) { + return item.target !== null ? { position: 'remove' } : null; + } + + if ( from === undefined || ! latest.current.canReorderMenu ) { + return null; + } + + const index = getMenuIndex( doc, clientX, clientY ); + + // Back where it was. + if ( index === from || index === from + 1 ) { + return null; + } + + return { index, position: 'reorder' }; + }; + + /** + * Move a pill to a new place. An auto menu lists pages in their own + * order, so there the page moves among the pages beside it, on the map + * too. + * + * @param {number} from The pill's place. + * @param {number} index Where it lands, counting it in its old place. + */ + const dropPill = ( from, index ) => { + const current = latest.current; + const items = current.menuItems; + const item = items[ from ]; + + if ( ! current.switches.listsPages ) { + current.switches.moveTopLevelItem( + from, + index > from ? index - 1 : index, + item.label + ); + return; + } + + const isEnd = index >= items.length; + const target = items[ isEnd ? items.length - 1 : index ]; + + current.movePages( + getDropChanges( + current.tree, + item.pageId, + { + position: isEnd ? 'after' : 'before', + targetId: target.pageId, + }, + { frontPageId: current.frontPageId } + ) + ); + }; + + /** + * Follow a drag from a pointer press until it is let go. + * + * @param {Event} event The press. + * @param {Object} options + * @param {Object} options.drag What the drag is, kept in its state. + * @param {Function} options.find Returns where the pointer would drop, + * or null. + * @param {Function} options.place Makes the drop. + */ + const followDrag = ( event, { drag: dragged, find, place } ) => { + const view = event.currentTarget.ownerDocument.defaultView; + const { clientX: startX, clientY: startY, pointerId } = event; + let isDragging = false; + + const stop = () => { + view.removeEventListener( 'pointermove', onMove ); + view.removeEventListener( 'pointerup', onUp ); + view.removeEventListener( 'pointercancel', onCancel ); + view.removeEventListener( 'keydown', onKeyDown, true ); + setDrag( null ); + + if ( isDragging ) { + onDragEnd?.(); + } + }; + + function onMove( moveEvent ) { + if ( moveEvent.pointerId !== pointerId ) { + return; + } + + if ( + ! isDragging && + Math.hypot( + moveEvent.clientX - startX, + moveEvent.clientY - startY + ) < DRAG_THRESHOLD + ) { + return; + } + + isDragging = true; + setDrag( { + ...dragged, + drop: find( + moveEvent.clientX, + moveEvent.clientY, + view.document + ), + x: moveEvent.clientX, + y: moveEvent.clientY, + } ); + } + + function onUp( upEvent ) { + if ( upEvent.pointerId !== pointerId ) { + return; + } + + const target = isDragging + ? find( upEvent.clientX, upEvent.clientY, view.document ) + : null; + + stop(); + + if ( target ) { + place( target ); + } + } + + function onCancel( cancelEvent ) { + if ( cancelEvent.pointerId === pointerId ) { + stop(); + } + } + + function onKeyDown( keyEvent ) { + if ( keyEvent.key === 'Escape' ) { + keyEvent.preventDefault(); + keyEvent.stopPropagation(); + stop(); + } + } + + view.addEventListener( 'pointermove', onMove ); + view.addEventListener( 'pointerup', onUp ); + view.addEventListener( 'pointercancel', onCancel ); + view.addEventListener( 'keydown', onKeyDown, true ); + }; + + // Stable, so the cards don't all draw again on every change. The drop + // reads the latest pages and menu through `latest`. + const onCardPointerDown = useCallback( + ( event, node ) => { + if ( + event.button !== 0 || + ! isDraggable( node ) || + event.target.closest( '.cnl-site-overview-card__menu-toggle' ) + ) { + return; + } + + // The card is dragged rather than the canvas panned. + event.stopPropagation(); + followDrag( event, { + drag: { nodeId: node.id, title: node.title }, + find: ( x, y, doc ) => getCardDrop( node, x, y, doc ), + place: ( target ) => dropCard( node, target ), + } ); + }, + // eslint-disable-next-line react-hooks/exhaustive-deps + [ isDraggable, onDragEnd ] + ); + + const onPillPointerDown = ( event, item, index ) => { + // Its × takes it out rather than dragging it. + if ( event.button !== 0 || event.target.closest( 'button' ) ) { + return; + } + + followDrag( event, { + drag: { pillKey: item.key, title: item.label }, + find: ( x, y, doc ) => getPillDrop( item, index, x, y, doc ), + place: ( target ) => + target.position === 'remove' + ? latest.current.switches.toggle( item.target ) + : dropPill( index, target.index ), + } ); + }; + + // Stable, so the cards don't all draw again on every change. + const onToggleMenu = useCallback( ( node ) => { + const target = getMenuTarget( node ); + + if ( target !== null ) { + latest.current.switches.toggle( target ); + } + }, [] ); + + // Leaving Rearrange drops any drag under way. + useEffect( () => { + if ( ! isArranging ) { + setDrag( null ); + } + }, [ isArranging ] ); + + return { + drag: drag && { + ...drag, + label: getDropLabel( drag.drop, nodesById ), + }, + isDraggable, + /** + * Whether a card's page is in the menu, for its switch. + * + * @param {Object} node Site overview node. + * @return {Object} `{ state, note }`, `state` being `on`, `off`, + * `disabled`, or undefined for no switch. + */ + getMenuState: ( node ) => { + const target = getMenuTarget( node ); + + if ( target === null || ! switches.isReady || ! mainMenu.menuId ) { + return {}; + } + + const state = switches.getSwitch( target ); + let value = state.checked ? 'on' : 'off'; + + if ( state.disabled ) { + value = 'disabled'; + } + + return { note: state.note, state: value }; + }, + menu: { + canReorder: canReorderMenu, + hasMenu: Boolean( mainMenu.menuId ), + insertIndex: + drag?.drop?.index !== undefined ? drag.drop.index : undefined, + isAutomatic: switches.isAutomatic, + items: menuItems, + menuTitle: mainMenu.menuTitle, + onPillPointerDown, + remove: ( target ) => switches.toggle( target ), + }, + onCardPointerDown, + onToggleMenu, + overview, + }; +} From 8a93e51405881662ed0730f6a6d286466cb1404c Mon Sep 17 00:00:00 2001 From: Dave Smith Date: Fri, 20 Nov 2026 23:09:01 +0000 Subject: [PATCH 2/3] Site overview: drop menu editing, move pages by dragging any time The Main menu tray gave the Site overview another way to show and edit menus, which made it harder to read. Moving pages stays, without a mode to turn on: a page card can be dragged whenever the map is open, and the background still pans. Co-Authored-By: Claude Opus 5.5 --- src/routes/content/pages/menu-switches.js | 102 +--- src/routes/site-overview/_style.scss | 176 +------ src/routes/site-overview/canvas.jsx | 117 ++--- src/routes/site-overview/card.jsx | 40 +- src/routes/site-overview/menu-tray.jsx | 231 --------- src/routes/site-overview/use-arrange.js | 566 --------------------- src/routes/site-overview/use-page-moves.js | 250 +++++++++ 7 files changed, 312 insertions(+), 1170 deletions(-) delete mode 100644 src/routes/site-overview/menu-tray.jsx delete mode 100644 src/routes/site-overview/use-arrange.js create mode 100644 src/routes/site-overview/use-page-moves.js diff --git a/src/routes/content/pages/menu-switches.js b/src/routes/content/pages/menu-switches.js index e4deee83..9831dbdb 100644 --- a/src/routes/content/pages/menu-switches.js +++ b/src/routes/content/pages/menu-switches.js @@ -307,34 +307,7 @@ export function useMenuSwitches( { homepage, menuId, pages } ) { }; }; - /** - * Put a top-level item of a menu set by hand in another place. - * - * @param {Object[]} items Top-level blocks. - * @param {number} from Its place now. - * @param {number} to Its place once moved. - * @return {Object[]} Blocks. - */ - const placeTopLevel = ( items, from, to ) => { - const next = items.slice(); - const [ item ] = next.splice( from, 1 ); - - next.splice( Math.max( 0, Math.min( to, next.length ) ), 0, item ); - - return next; - }; - - /** - * Switch a page in or out of the menu. - * - * @param {number|string} target Page ID, or `HOMEPAGE`. - * @param {Object} [options] - * @param {number} [options.index] Where at the top of a menu set by - * hand it goes, rather than the end. - * A menu that lists pages keeps - * them in page order. - */ - const toggle = ( target, { index } = {} ) => { + const toggle = ( target ) => { if ( getSwitch( target ).disabled ) { return; } @@ -377,10 +350,8 @@ export function useMenuSwitches( { homepage, menuId, pages } ) { // The homepage goes in as a Home link, first, whatever it shows. if ( target === HOMEPAGE ) { - const next = addItemFirst( blocks, createHomeLink() ); - apply( - index === undefined ? next : placeTopLevel( next, 0, index ), + addItemFirst( blocks, createHomeLink() ), __( 'Your homepage is in your menu.' ) ); @@ -394,40 +365,28 @@ export function useMenuSwitches( { homepage, menuId, pages } ) { const parentPlace = parentId ? getItemPlace( blocks, ( block ) => isPageItem( block, parentId ) ) : null; - const under = - parentPlace?.depth === 0 && index === undefined ? parentId : 0; - let next = addItem( + const under = parentPlace?.depth === 0 ? parentId : 0; + const next = addItem( blocks, createPageLink( page ), under ? ( block ) => isPageItem( block, under ) : null ); - if ( ! under && index !== undefined ) { - next = placeTopLevel( next, next.length - 1, index ); - } - - let message = sprintf( - /* translators: %s: page title. */ - __( '“%s” added to the end of your menu.' ), - title + apply( + next, + under + ? sprintf( + /* translators: 1: page title, 2: parent page title. */ + __( '“%1$s” added to the %2$s dropdown.' ), + title, + getPageTitle( pagesById.get( under ) ) + ) + : sprintf( + /* translators: %s: page title. */ + __( '“%s” added to the end of your menu.' ), + title + ) ); - - if ( under ) { - message = sprintf( - /* translators: 1: page title, 2: parent page title. */ - __( '“%1$s” added to the %2$s dropdown.' ), - title, - getPageTitle( pagesById.get( under ) ) - ); - } else if ( index !== undefined ) { - message = sprintf( - /* translators: %s: page title. */ - __( '“%s” added to your menu.' ), - title - ); - } - - apply( next, message ); }; /** @@ -532,35 +491,10 @@ export function useMenuSwitches( { homepage, menuId, pages } ) { } }; - /** - * Move a top-level item of a menu set by hand to another place. - * - * @param {number} from Its place now. - * @param {number} to Its place once moved. - * @param {string} label What the item says, to say what moved. - */ - const moveTopLevelItem = ( from, to, label ) => { - if ( listsPages || from === to ) { - return; - } - - apply( - placeTopLevel( blocks, from, to ), - sprintf( - /* translators: %s: Menu item label. */ - __( 'Moved “%s” in your menu.' ), - label - ) - ); - }; - return { - blocks, getMenuMoves, getSwitch, isAutomatic, - listsPages, - moveTopLevelItem, isReady: Boolean( edited ), removePage, toggle, diff --git a/src/routes/site-overview/_style.scss b/src/routes/site-overview/_style.scss index 1e050d0b..8c236e01 100644 --- a/src/routes/site-overview/_style.scss +++ b/src/routes/site-overview/_style.scss @@ -511,21 +511,24 @@ $cnl-site-overview-canvas: #e9eef2; } // --------------------------------------------------------------------------- -// Rearrange: pages dragged onto each other, and into the main menu. +// Moving pages: dragged onto each other. // --------------------------------------------------------------------------- -.cnl-site-overview__viewport.is-arranging { - user-select: none; +.cnl-site-overview__viewport { .cnl-site-overview-card.is-draggable, .cnl-site-overview-card.is-draggable .cnl-site-overview-card__select { cursor: grab; } - &.is-dragging-page, - &.is-dragging-page .cnl-site-overview-card, - &.is-dragging-page .cnl-site-overview-card__select { - cursor: grabbing; + &.is-dragging-page { + user-select: none; + + &, + .cnl-site-overview-card, + .cnl-site-overview-card__select { + cursor: grabbing; + } } } @@ -565,165 +568,6 @@ $cnl-site-overview-canvas: #e9eef2; } } -// The menu as a bucket along the top, where the menu sits on most sites. It -// takes a row of its own, so it never covers a page. -.cnl-site-overview__body.is-arranging { - grid-template-rows: auto minmax(0, 1fr); - - > .cnl-site-overview__viewport { - grid-area: 2 / 1; - } -} - -.cnl-site-overview-menu-tray { - grid-area: 1 / 1; - justify-self: center; - display: flex; - gap: 16px; - align-items: center; - box-sizing: border-box; - width: min(720px, calc(100% - 32px)); - min-height: 56px; - margin: 16px 0 0; - padding: 8px 16px; - border: 2px dashed var(--wpds-color-stroke-surface-neutral-strong); - border-radius: var(--wpds-border-radius-lg); - background: rgba(255, 255, 255, 0.92); - transition: - border-color var(--wpds-motion-duration-sm) var(--wpds-motion-easing-subtle), - background-color var(--wpds-motion-duration-sm) var(--wpds-motion-easing-subtle); - - &.is-dragging { - border-color: $cnl-site-overview-accent; - } - - &.is-over { - background: color-mix(in srgb, $cnl-site-overview-accent 10%, #fff); - } -} - -.cnl-site-overview-menu-tray__header { - display: flex; - flex: none; - flex-direction: column; -} - -.cnl-site-overview-menu-tray__title { - font-size: 13px; - font-weight: 600; -} - -.cnl-site-overview-menu-tray__subtitle { - color: var(--wpds-color-foreground-content-neutral-weak); - font-size: 12px; -} - -.cnl-site-overview-menu-tray__empty { - margin: 0; - color: var(--wpds-color-foreground-content-neutral-weak); - font-size: 13px; -} - -.cnl-site-overview-menu-tray__items { - display: flex; - flex-wrap: wrap; - gap: 8px; - align-items: flex-start; - margin: 0; - padding: 0; - list-style: none; -} - -.cnl-site-overview-menu-tray__item { - display: inline-flex; - gap: 2px; - align-items: center; - margin: 0; - padding-inline-start: 10px; - border: 1px solid var(--wpds-color-stroke-surface-neutral); - border-radius: var(--wpds-border-radius-md); - background: #fff; - font-size: 13px; - - // Links that aren't to a page keep the chip's padding on both sides. - > span:last-child { - padding: 4px 10px 4px 0; - } -} - -// Pills that can be dragged into a new order. -.cnl-site-overview-menu-tray__item.is-movable { - cursor: grab; - user-select: none; - touch-action: none; -} - -.cnl-site-overview-menu-tray__item.is-dragged { - opacity: 0.4; -} - -// Where a pill, or a page, will land. -.cnl-site-overview-menu-tray__marker { - align-self: stretch; - width: 3px; - margin: 0 -5px; - border-radius: 2px; - background: $cnl-site-overview-accent; -} - -// A top-level item, with the items in its dropdown hanging under it. -.cnl-site-overview-menu-tray__group { - display: flex; - flex-direction: column; - gap: 4px; - align-items: flex-start; - margin: 0; -} - -.cnl-site-overview-menu-tray__sub-items { - display: flex; - flex-direction: column; - gap: 4px; - align-items: flex-start; - margin: 0; - padding-inline-start: 12px; - border-inline-start: 1px solid var(--wpds-color-stroke-surface-neutral); - list-style: none; - - > li { - margin: 0; - } - - .cnl-site-overview-menu-tray__item { - font-size: 12px; - } -} - -// Whether the page is in the main menu, switched from its card. -.cnl-site-overview-card__caption { - position: relative; -} - -.cnl-site-overview-card__menu-toggle.components-button { - position: absolute; - inset-inline-end: 8px; - bottom: 8px; - height: 24px; - padding-inline: 4px 8px; - border-radius: var(--wpds-border-radius-md); - font-size: 11px; - - &.is-on { - background: color-mix(in srgb, #{$cnl-site-overview-accent} 12%, #fff); - color: $cnl-site-overview-accent; - } - - &.is-off { - box-shadow: inset 0 0 0 1px var(--wpds-color-stroke-surface-neutral); - color: var(--wpds-color-foreground-content-neutral-weak); - } -} - // What dropping here will do, following the pointer. .cnl-site-overview__drag-label { position: fixed; diff --git a/src/routes/site-overview/canvas.jsx b/src/routes/site-overview/canvas.jsx index 09d2a8e9..92d3474d 100644 --- a/src/routes/site-overview/canvas.jsx +++ b/src/routes/site-overview/canvas.jsx @@ -34,11 +34,9 @@ import { MemoizedStackSheets, } from './lanes'; import { ZoomControls } from './zoom-controls'; -import { MenuTray } from './menu-tray'; -import useArrange from './use-arrange'; +import usePageMoves from './use-page-moves'; import { SelectedPage } from './selected-page'; import { - Button, Notice, Page, Spinner, @@ -99,7 +97,6 @@ export default function Canvas() { const didFitRef = useRef( false ); const boundsRef = useRef( null ); const hasSize = size.width > 0 && size.height > 0; - const [ isArranging, setIsArranging ] = useState( false ); // The click that ends dragging a page shouldn't select one. const onDragEnd = useCallback( () => { suppressClickRef.current = true; @@ -107,11 +104,7 @@ export default function Canvas() { suppressClickRef.current = false; } ); }, [] ); - const arrange = useArrange( { - isArranging, - onDragEnd, - siteOverview, - } ); + const pageMoves = usePageMoves( { onDragEnd, siteOverview } ); viewRef.current = view; sizeRef.current = size; @@ -148,8 +141,10 @@ export default function Canvas() { const layout = useMemo( () => - arrange.overview ? layoutSiteOverview( arrange.overview ) : null, - [ arrange.overview ] + pageMoves.overview + ? layoutSiteOverview( pageMoves.overview ) + : null, + [ pageMoves.overview ] ); boundsRef.current = layout?.bounds || null; const scaleLimits = @@ -520,23 +515,13 @@ export default function Canvas() { return ( - - - + } className="cnl-editor-stage cnl-editor-content-page cnl-site-overview-page" hasPadding={ false } @@ -549,11 +534,7 @@ export default function Canvas() { .join( ' · ' ) } title={ __( 'Site overview' ) } > -
    +
    { /* eslint-disable-next-line jsx-a11y/no-noninteractive-element-interactions -- The canvas pans and zooms from the pointer and keyboard. */ }
    ( - { isArranging - ? __( - 'Drag a page onto another to put it under it, or onto its edge to put it beside it. Drag a page into Main menu to add it, or drag an item out of Main menu to take it out.' - ) - : __( - 'Drag or scroll to move around. Pinch, or hold Ctrl or ⌘ and scroll, to zoom. Click a page for details, or double-click it to edit it.' - ) } + { __( + 'Drag the background or scroll to move around. Pinch, or hold Ctrl or ⌘ and scroll, to zoom. Click a page for details, or double-click it to edit it. Drag a page onto another to put it under it, or onto its edge to put it beside it.' + ) }

    - { isArranging && ( - - ) } - { arrange.drag && ( + { pageMoves.drag && (
    - { arrange.drag.title } + { pageMoves.drag.title } - { arrange.drag.label && ( + { pageMoves.drag.label && ( - { arrange.drag.label } + { pageMoves.drag.label } ) }
    ) } - { selectedNode && hasSize && ! isArranging && ( + { selectedNode && hasSize && ( onOpen( node ) } onMouseEnter={ () => onHover( node.id ) } onMouseLeave={ () => onHover( '' ) } - onPointerDown={ - isDraggable - ? ( event ) => onDragStart( event, node ) - : undefined - } + onPointerDown={ ( event ) => onDragStart( event, node ) } style={ { height: node.height, left: node.x, @@ -176,23 +159,6 @@ function SiteOverviewCard( { ) }
    - { menuState && ( - - ) }
    ); diff --git a/src/routes/site-overview/menu-tray.jsx b/src/routes/site-overview/menu-tray.jsx deleted file mode 100644 index 5354bc7b..00000000 --- a/src/routes/site-overview/menu-tray.jsx +++ /dev/null @@ -1,231 +0,0 @@ -/** - * The main menu as a tray along the top of the Site overview, while it is - * being rearranged. Each top-level item is a pill, with the items in its - * dropdown under it. Pages dropped on it join the menu, pills dragged along it - * change its order, and any item can be taken out, with its × or by dragging - * it off the tray. - */ - -/** - * Internal dependencies - */ -import { getPageTitle } from '../content/pages/data'; -import { HOMEPAGE } from '../content/pages/homepage-state'; -import { getNavigationItemLabel } from '../navigation-edit/navigation-blocks'; -import { Button, __, closeSmallIcon, sprintf } from '../../wordpress-packages'; - -/** - * The menu's items, each with the page or homepage it links to and the items - * under it. A Page List stands for the pages it lists, nested as they are. - * - * @param {Object} args Arguments. - * @param {Object[]} args.blocks The menu's blocks. - * @param {Object[]} args.tree Pages as a tree. - * @param {Function} args.getSwitch From `useMenuSwitches`. - * @param {number} args.frontPageId The homepage's page. - * @return {Object[]} `{ children, key, label, pageId, target }`, `target` - * null for links that aren't to a page. - */ -export function getMenuTrayItems( { blocks, tree, getSwitch, frontPageId } ) { - const getTarget = ( id ) => ( id === frontPageId ? HOMEPAGE : id ); - const fromPages = ( items ) => - items - .filter( - ( item ) => - item.page.status === 'publish' && - getSwitch( Number( item.page.id ) ).checked - ) - .map( ( item ) => ( { - children: fromPages( item.children ), - key: `page-${ item.page.id }`, - label: getPageTitle( item.page ), - pageId: Number( item.page.id ), - target: getTarget( Number( item.page.id ) ), - } ) ); - const fromBlocks = ( items, prefix ) => - ( items || [] ).flatMap( ( block, index ) => { - const attributes = block.attributes || {}; - - if ( block.name === 'core/page-list' ) { - return fromPages( tree ); - } - - let target = null; - - if ( block.name === 'core/home-link' ) { - target = HOMEPAGE; - } else if ( attributes.type === 'page' && attributes.id ) { - target = getTarget( Number( attributes.id ) ); - } - - const key = `${ prefix }${ index }`; - - return [ - { - children: fromBlocks( block.innerBlocks, `${ key }-` ), - key: `${ block.name }-${ key }`, - label: getNavigationItemLabel( block ), - pageId: Number( attributes.id ) || 0, - target, - }, - ]; - } ); - - return fromBlocks( blocks, '' ); -} - -function Pill( { - draggedKey, - index, - isMovable, - item, - onPointerDown, - onRemove, -} ) { - const canTakeOut = item.target !== null; - - return ( -
    onPointerDown( event, item, index ) - : undefined - } - > - { item.label } - { canTakeOut && ( -
    - ); -} - -function SubItems( { items, ...props } ) { - if ( ! items.length ) { - return null; - } - - return ( -
      - { items.map( ( item ) => ( -
    • - - -
    • - ) ) } -
    - ); -} - -export function MenuTray( { - canReorder, - draggedKey, - hasMenu, - insertIndex, - isAutomatic, - isDragging, - isOver, - items, - menuTitle, - onItemPointerDown, - onRemove, -} ) { - const className = [ - 'cnl-site-overview-menu-tray', - isDragging && 'is-dragging', - isOver && 'is-over', - ] - .filter( Boolean ) - .join( ' ' ); - let subtitle = ''; - - if ( isAutomatic ) { - subtitle = __( 'Auto menu, in page order' ); - } else if ( menuTitle && menuTitle !== __( 'Main menu' ) ) { - subtitle = menuTitle; - } - - const pillProps = { - draggedKey, - onPointerDown: onItemPointerDown, - onRemove, - }; - const marker = ( -
  • - ); - const groups = items.flatMap( ( item, index ) => { - const group = ( -
  • - - -
  • - ); - - return index === insertIndex ? [ marker, group ] : [ group ]; - } ); - - if ( insertIndex === items.length ) { - groups.push( marker ); - } - - return ( -
    -
    - - { __( 'Main menu' ) } - - { subtitle && ( - - { subtitle } - - ) } -
    - { ! hasMenu && ( -

    - { __( 'Your site has no menu yet.' ) } -

    - ) } - { hasMenu && ! items.length && ( -

    - { isOver - ? __( 'Drop to add it to your menu' ) - : __( 'Drag pages here to add them to your menu' ) } -

    - ) } - { hasMenu && !! items.length && ( -
      - { groups } -
    - ) } -
    - ); -} diff --git a/src/routes/site-overview/use-arrange.js b/src/routes/site-overview/use-arrange.js deleted file mode 100644 index e5ca69f6..00000000 --- a/src/routes/site-overview/use-arrange.js +++ /dev/null @@ -1,566 +0,0 @@ -/** - * Rearranging the Site overview: dragging a page onto another to put it - * under it or beside it, and dragging pages into the main menu. - * - * Every change is an unsaved edit, the same ones the Pages screen makes, so - * it waits for Save with the rest and comes with a way to undo it. The map - * shows the pages where those edits put them at once. - */ - -/** - * Internal dependencies - */ -import { usePages } from '../content/pages/data'; -import { useHomepageState } from '../content/pages/homepage'; -import { HOMEPAGE } from '../content/pages/homepage-state'; -import { useMenuSwitches } from '../content/pages/menu-switches'; -import usePageOrder from '../content/pages/use-page-order'; -import useMainMenu from '../content/use-main-menu'; -import { - applyPageTree, - canDropOnPage, - getDropChanges, - getDropPosition, -} from './arrange'; -import { getMenuTrayItems } from './menu-tray'; -import { - __, - noticesStore, - sprintf, - useCallback, - useDispatch, - useEffect, - useMemo, - useRef, - useState, -} from '../../wordpress-packages'; - -const DRAG_THRESHOLD = 4; -const TRAY_SELECTOR = '.cnl-site-overview-menu-tray'; -// Top-level pills only: the items in their dropdowns move with them. -const PILL_SELECTOR = - '.cnl-site-overview-menu-tray__group > .cnl-site-overview-menu-tray__item'; - -/** - * What a card stands for in the menu: the homepage, a page, or the page a - * collection is listed on. - * - * @param {Object} node Site overview node. - * @return {number|string|null} Page ID, `HOMEPAGE`, or null. - */ -export function getMenuTarget( node ) { - if ( node?.kind === 'home' ) { - return HOMEPAGE; - } - - if ( - ( node?.kind === 'page' || node?.kind === 'collection' ) && - node.postId - ) { - return Number( node.postId ); - } - - return null; -} - -/** - * What dropping here will do, in words, for the label that follows the - * pointer. - * - * @param {Object} drop Drop target. - * @param {Map} nodesById Overview nodes. - * @return {string} Label. - */ -function getDropLabel( drop, nodesById ) { - const title = nodesById.get( drop?.nodeId )?.title || ''; - - switch ( drop?.position ) { - case 'menu': - return __( 'Add to menu' ); - case 'remove': - return __( 'Take out of menu' ); - case 'reorder': - return __( 'Move here in menu' ); - case 'top': - return __( 'Move to the top level' ); - case 'under': - /* translators: %s: Page title. */ - return sprintf( __( 'Put under “%s”' ), title ); - case 'before': - /* translators: %s: Page title. */ - return sprintf( __( 'Move before “%s”' ), title ); - case 'after': - /* translators: %s: Page title. */ - return sprintf( __( 'Move after “%s”' ), title ); - default: - return ''; - } -} - -/** - * @param {Object} args Arguments. - * @param {boolean} args.isArranging Whether the map is being rearranged. - * @param {Object} args.siteOverview Site overview from the REST API. - * @param {Function} args.onDragEnd Called when a drag ends, so the click - * that ends it doesn't select a page. - * @return {Object} The overview to draw, the menu, and the drag. - */ -export default function useArrange( { isArranging, siteOverview, onDragEnd } ) { - const { frontPageId, isLoading, pages } = usePages(); - const { movePages, tree } = usePageOrder( { frontPageId, pages } ); - const homepage = useHomepageState(); - const mainMenu = useMainMenu(); - const switches = useMenuSwitches( { - homepage, - menuId: mainMenu.menuId, - pages, - } ); - const { createInfoNotice } = useDispatch( noticesStore ); - const [ drag, setDrag ] = useState( null ); - - const overview = useMemo( - () => - isLoading || ! pages.length - ? siteOverview - : applyPageTree( siteOverview, tree ), - [ isLoading, pages.length, siteOverview, tree ] - ); - const nodesById = useMemo( - () => - new Map( - ( overview?.nodes || [] ).map( ( node ) => [ node.id, node ] ) - ), - [ overview ] - ); - const menuItems = useMemo( - () => - switches.isReady - ? getMenuTrayItems( { - blocks: switches.blocks, - frontPageId, - getSwitch: switches.getSwitch, - tree, - } ) - : [], - // `getSwitch` is new each render; the blocks and tree are what it reads. - // eslint-disable-next-line react-hooks/exhaustive-deps - [ switches.isReady, switches.blocks, frontPageId, tree, pages ] - ); - const menuTargets = useMemo( () => { - const targets = new Set(); - const visit = ( items ) => - items.forEach( ( item ) => { - targets.add( item.target ); - visit( item.children ); - } ); - - visit( menuItems ); - - return targets; - }, [ menuItems ] ); - - // Pills can be put in order in a menu set by hand, and in an auto menu, - // whose order is the pages' own. A menu mixing the two is left to the - // Menus screen. - const canReorderMenu = - switches.isReady && - menuItems.length > 1 && - ( ! switches.listsPages || switches.isAutomatic ); - - // The drag's handlers live for the whole drag, so they read the latest - // pages and menu from here. - const latest = useRef(); - latest.current = { - // A page dropped on a menu set by hand goes where it lands. An auto - // menu keeps page order. - canPlaceInMenu: switches.isReady && ! switches.listsPages, - canReorderMenu, - frontPageId, - menuItems, - menuId: mainMenu.menuId, - menuTargets, - movePages, - nodesById, - switches, - tree, - }; - - const isDraggable = useCallback( - ( node ) => - isArranging && - ( node.kind === 'page' || getMenuTarget( node ) !== null ), - [ isArranging ] - ); - - /** - * Where among the pills a drop at the pointer lands: before the first pill - * the pointer is left of, or above, or else at the end. - * - * @param {Document} doc Document. - * @param {number} clientX Pointer. - * @param {number} clientY Pointer. - * @return {number} Index, 0 to the number of pills. - */ - const getMenuIndex = ( doc, clientX, clientY ) => { - const pills = [ ...doc.querySelectorAll( PILL_SELECTOR ) ]; - const index = pills.findIndex( ( pill ) => { - const rect = pill.getBoundingClientRect(); - - return ( - clientY < rect.top || - ( clientY <= rect.bottom && - clientX < rect.left + rect.width / 2 ) - ); - } ); - - return index === -1 ? pills.length : index; - }; - - const getCardDrop = ( node, clientX, clientY, doc ) => { - const current = latest.current; - const element = doc.elementFromPoint( clientX, clientY ); - - if ( element?.closest( TRAY_SELECTOR ) ) { - if ( ! current.menuId || getMenuTarget( node ) === null ) { - return null; - } - - return { - index: current.canPlaceInMenu - ? getMenuIndex( doc, clientX, clientY ) - : undefined, - position: 'menu', - }; - } - - const card = element?.closest( '[data-node-id]' ); - - if ( ! card || node.kind !== 'page' ) { - return null; - } - - const nodeId = card.getAttribute( 'data-node-id' ); - - if ( nodeId === 'home' ) { - return { nodeId, position: 'top' }; - } - - const target = current.nodesById.get( nodeId ); - - if ( - target?.kind !== 'page' || - ! canDropOnPage( - current.tree, - Number( node.postId ), - Number( target.postId ) - ) - ) { - return null; - } - - const rect = card.getBoundingClientRect(); - - return { - nodeId, - position: getDropPosition( ( clientX - rect.left ) / rect.width ), - targetId: Number( target.postId ), - }; - }; - - const dropCard = ( node, target ) => { - const current = latest.current; - - if ( target.position === 'menu' ) { - const menuTarget = getMenuTarget( node ); - const state = current.switches.getSwitch( menuTarget ); - - if ( current.menuTargets.has( menuTarget ) || state.checked ) { - createInfoNotice( - sprintf( - /* translators: %s: Page title. */ - __( '“%s” is already in your menu.' ), - node.title - ), - { id: 'cnl-site-overview-menu', type: 'snackbar' } - ); - } else if ( state.disabled ) { - createInfoNotice( state.note, { - id: 'cnl-site-overview-menu', - type: 'snackbar', - } ); - } else { - current.switches.toggle( menuTarget, { index: target.index } ); - } - - return; - } - - current.movePages( - getDropChanges( current.tree, Number( node.postId ), target, { - frontPageId: current.frontPageId, - } ) - ); - }; - - /** - * Where a dragged pill would go: off the tray takes it out of the menu, - * and along the top row puts it in a new place. - * - * @param {Object} item The pill's menu item. - * @param {?number} from Its place in the top row, if it is in it. - * @param {number} clientX Pointer. - * @param {number} clientY Pointer. - * @param {Document} doc Document. - * @return {?Object} Drop, or null. - */ - const getPillDrop = ( item, from, clientX, clientY, doc ) => { - const element = doc.elementFromPoint( clientX, clientY ); - - if ( ! element?.closest( TRAY_SELECTOR ) ) { - return item.target !== null ? { position: 'remove' } : null; - } - - if ( from === undefined || ! latest.current.canReorderMenu ) { - return null; - } - - const index = getMenuIndex( doc, clientX, clientY ); - - // Back where it was. - if ( index === from || index === from + 1 ) { - return null; - } - - return { index, position: 'reorder' }; - }; - - /** - * Move a pill to a new place. An auto menu lists pages in their own - * order, so there the page moves among the pages beside it, on the map - * too. - * - * @param {number} from The pill's place. - * @param {number} index Where it lands, counting it in its old place. - */ - const dropPill = ( from, index ) => { - const current = latest.current; - const items = current.menuItems; - const item = items[ from ]; - - if ( ! current.switches.listsPages ) { - current.switches.moveTopLevelItem( - from, - index > from ? index - 1 : index, - item.label - ); - return; - } - - const isEnd = index >= items.length; - const target = items[ isEnd ? items.length - 1 : index ]; - - current.movePages( - getDropChanges( - current.tree, - item.pageId, - { - position: isEnd ? 'after' : 'before', - targetId: target.pageId, - }, - { frontPageId: current.frontPageId } - ) - ); - }; - - /** - * Follow a drag from a pointer press until it is let go. - * - * @param {Event} event The press. - * @param {Object} options - * @param {Object} options.drag What the drag is, kept in its state. - * @param {Function} options.find Returns where the pointer would drop, - * or null. - * @param {Function} options.place Makes the drop. - */ - const followDrag = ( event, { drag: dragged, find, place } ) => { - const view = event.currentTarget.ownerDocument.defaultView; - const { clientX: startX, clientY: startY, pointerId } = event; - let isDragging = false; - - const stop = () => { - view.removeEventListener( 'pointermove', onMove ); - view.removeEventListener( 'pointerup', onUp ); - view.removeEventListener( 'pointercancel', onCancel ); - view.removeEventListener( 'keydown', onKeyDown, true ); - setDrag( null ); - - if ( isDragging ) { - onDragEnd?.(); - } - }; - - function onMove( moveEvent ) { - if ( moveEvent.pointerId !== pointerId ) { - return; - } - - if ( - ! isDragging && - Math.hypot( - moveEvent.clientX - startX, - moveEvent.clientY - startY - ) < DRAG_THRESHOLD - ) { - return; - } - - isDragging = true; - setDrag( { - ...dragged, - drop: find( - moveEvent.clientX, - moveEvent.clientY, - view.document - ), - x: moveEvent.clientX, - y: moveEvent.clientY, - } ); - } - - function onUp( upEvent ) { - if ( upEvent.pointerId !== pointerId ) { - return; - } - - const target = isDragging - ? find( upEvent.clientX, upEvent.clientY, view.document ) - : null; - - stop(); - - if ( target ) { - place( target ); - } - } - - function onCancel( cancelEvent ) { - if ( cancelEvent.pointerId === pointerId ) { - stop(); - } - } - - function onKeyDown( keyEvent ) { - if ( keyEvent.key === 'Escape' ) { - keyEvent.preventDefault(); - keyEvent.stopPropagation(); - stop(); - } - } - - view.addEventListener( 'pointermove', onMove ); - view.addEventListener( 'pointerup', onUp ); - view.addEventListener( 'pointercancel', onCancel ); - view.addEventListener( 'keydown', onKeyDown, true ); - }; - - // Stable, so the cards don't all draw again on every change. The drop - // reads the latest pages and menu through `latest`. - const onCardPointerDown = useCallback( - ( event, node ) => { - if ( - event.button !== 0 || - ! isDraggable( node ) || - event.target.closest( '.cnl-site-overview-card__menu-toggle' ) - ) { - return; - } - - // The card is dragged rather than the canvas panned. - event.stopPropagation(); - followDrag( event, { - drag: { nodeId: node.id, title: node.title }, - find: ( x, y, doc ) => getCardDrop( node, x, y, doc ), - place: ( target ) => dropCard( node, target ), - } ); - }, - // eslint-disable-next-line react-hooks/exhaustive-deps - [ isDraggable, onDragEnd ] - ); - - const onPillPointerDown = ( event, item, index ) => { - // Its × takes it out rather than dragging it. - if ( event.button !== 0 || event.target.closest( 'button' ) ) { - return; - } - - followDrag( event, { - drag: { pillKey: item.key, title: item.label }, - find: ( x, y, doc ) => getPillDrop( item, index, x, y, doc ), - place: ( target ) => - target.position === 'remove' - ? latest.current.switches.toggle( item.target ) - : dropPill( index, target.index ), - } ); - }; - - // Stable, so the cards don't all draw again on every change. - const onToggleMenu = useCallback( ( node ) => { - const target = getMenuTarget( node ); - - if ( target !== null ) { - latest.current.switches.toggle( target ); - } - }, [] ); - - // Leaving Rearrange drops any drag under way. - useEffect( () => { - if ( ! isArranging ) { - setDrag( null ); - } - }, [ isArranging ] ); - - return { - drag: drag && { - ...drag, - label: getDropLabel( drag.drop, nodesById ), - }, - isDraggable, - /** - * Whether a card's page is in the menu, for its switch. - * - * @param {Object} node Site overview node. - * @return {Object} `{ state, note }`, `state` being `on`, `off`, - * `disabled`, or undefined for no switch. - */ - getMenuState: ( node ) => { - const target = getMenuTarget( node ); - - if ( target === null || ! switches.isReady || ! mainMenu.menuId ) { - return {}; - } - - const state = switches.getSwitch( target ); - let value = state.checked ? 'on' : 'off'; - - if ( state.disabled ) { - value = 'disabled'; - } - - return { note: state.note, state: value }; - }, - menu: { - canReorder: canReorderMenu, - hasMenu: Boolean( mainMenu.menuId ), - insertIndex: - drag?.drop?.index !== undefined ? drag.drop.index : undefined, - isAutomatic: switches.isAutomatic, - items: menuItems, - menuTitle: mainMenu.menuTitle, - onPillPointerDown, - remove: ( target ) => switches.toggle( target ), - }, - onCardPointerDown, - onToggleMenu, - overview, - }; -} diff --git a/src/routes/site-overview/use-page-moves.js b/src/routes/site-overview/use-page-moves.js new file mode 100644 index 00000000..dd22a254 --- /dev/null +++ b/src/routes/site-overview/use-page-moves.js @@ -0,0 +1,250 @@ +/** + * Moving pages on the Site overview by dragging them: onto another page to + * put it under it, onto its edge to put it beside it, or onto the homepage + * to move it to the top level. + * + * Every move is an unsaved edit, the same one the Pages screen makes, so it + * waits for Save with the rest and comes with a way to undo it. The map shows + * the pages where those edits put them at once. + */ + +/** + * Internal dependencies + */ +import { usePages } from '../content/pages/data'; +import usePageOrder from '../content/pages/use-page-order'; +import { + applyPageTree, + canDropOnPage, + getDropChanges, + getDropPosition, +} from './arrange'; +import { + __, + sprintf, + useCallback, + useMemo, + useRef, + useState, +} from '../../wordpress-packages'; + +const DRAG_THRESHOLD = 4; + +/** + * What dropping here will do, in words, for the label that follows the + * pointer. + * + * @param {Object} drop Drop target. + * @param {Map} nodesById Overview nodes. + * @return {string} Label. + */ +function getDropLabel( drop, nodesById ) { + const title = nodesById.get( drop?.nodeId )?.title || ''; + + switch ( drop?.position ) { + case 'top': + return __( 'Move to the top level' ); + case 'under': + /* translators: %s: Page title. */ + return sprintf( __( 'Put under “%s”' ), title ); + case 'before': + /* translators: %s: Page title. */ + return sprintf( __( 'Move before “%s”' ), title ); + case 'after': + /* translators: %s: Page title. */ + return sprintf( __( 'Move after “%s”' ), title ); + default: + return ''; + } +} + +/** + * @param {Object} args Arguments. + * @param {Object} args.siteOverview Site overview from the REST API. + * @param {Function} args.onDragEnd Called when a drag ends, so the click + * that ends it doesn't select a page. + * @return {Object} The overview to draw, the drag, and a handler for a + * card's pointer press. + */ +export default function usePageMoves( { siteOverview, onDragEnd } ) { + const { frontPageId, isLoading, pages } = usePages(); + const { movePages, tree } = usePageOrder( { frontPageId, pages } ); + const [ drag, setDrag ] = useState( null ); + + const overview = useMemo( + () => + isLoading || ! pages.length + ? siteOverview + : applyPageTree( siteOverview, tree ), + [ isLoading, pages.length, siteOverview, tree ] + ); + const nodesById = useMemo( + () => + new Map( + ( overview?.nodes || [] ).map( ( node ) => [ node.id, node ] ) + ), + [ overview ] + ); + + // A drag's handlers live for the whole drag, so they read the latest + // pages from here. + const latest = useRef(); + latest.current = { frontPageId, movePages, nodesById, tree }; + + const getDrop = ( node, clientX, clientY, doc ) => { + const current = latest.current; + const card = doc + .elementFromPoint( clientX, clientY ) + ?.closest( '[data-node-id]' ); + + if ( ! card ) { + return null; + } + + const nodeId = card.getAttribute( 'data-node-id' ); + + if ( nodeId === 'home' ) { + return { nodeId, position: 'top' }; + } + + const target = current.nodesById.get( nodeId ); + + if ( + target?.kind !== 'page' || + ! canDropOnPage( + current.tree, + Number( node.postId ), + Number( target.postId ) + ) + ) { + return null; + } + + const rect = card.getBoundingClientRect(); + + return { + nodeId, + position: getDropPosition( ( clientX - rect.left ) / rect.width ), + targetId: Number( target.postId ), + }; + }; + + // Stable, so the cards don't all draw again on every change. The drop + // reads the latest pages through `latest`. + const onCardPointerDown = useCallback( + ( event, node ) => { + if ( event.button !== 0 || node.kind !== 'page' ) { + return; + } + + // The card is dragged rather than the canvas panned. + event.stopPropagation(); + + const view = event.currentTarget.ownerDocument.defaultView; + const { clientX: startX, clientY: startY, pointerId } = event; + let isDragging = false; + + const stop = () => { + view.removeEventListener( 'pointermove', onMove ); + view.removeEventListener( 'pointerup', onUp ); + view.removeEventListener( 'pointercancel', onCancel ); + view.removeEventListener( 'keydown', onKeyDown, true ); + setDrag( null ); + + if ( isDragging ) { + onDragEnd?.(); + } + }; + + function onMove( moveEvent ) { + if ( moveEvent.pointerId !== pointerId ) { + return; + } + + if ( + ! isDragging && + Math.hypot( + moveEvent.clientX - startX, + moveEvent.clientY - startY + ) < DRAG_THRESHOLD + ) { + return; + } + + isDragging = true; + setDrag( { + drop: getDrop( + node, + moveEvent.clientX, + moveEvent.clientY, + view.document + ), + nodeId: node.id, + title: node.title, + x: moveEvent.clientX, + y: moveEvent.clientY, + } ); + } + + function onUp( upEvent ) { + if ( upEvent.pointerId !== pointerId ) { + return; + } + + const target = isDragging + ? getDrop( + node, + upEvent.clientX, + upEvent.clientY, + view.document + ) + : null; + + stop(); + + if ( target ) { + const current = latest.current; + + current.movePages( + getDropChanges( + current.tree, + Number( node.postId ), + target, + { frontPageId: current.frontPageId } + ) + ); + } + } + + function onCancel( cancelEvent ) { + if ( cancelEvent.pointerId === pointerId ) { + stop(); + } + } + + function onKeyDown( keyEvent ) { + if ( keyEvent.key === 'Escape' ) { + keyEvent.preventDefault(); + keyEvent.stopPropagation(); + stop(); + } + } + + view.addEventListener( 'pointermove', onMove ); + view.addEventListener( 'pointerup', onUp ); + view.addEventListener( 'pointercancel', onCancel ); + view.addEventListener( 'keydown', onKeyDown, true ); + }, + + [ onDragEnd ] + ); + + return { + drag: drag && { + ...drag, + label: getDropLabel( drag.drop, nodesById ), + }, + onCardPointerDown, + overview, + }; +} From e560d9f5571d29c25602424d62ed4a83b6ab02ea Mon Sep 17 00:00:00 2001 From: Dave Smith Date: Fri, 20 Nov 2026 23:17:25 +0000 Subject: [PATCH 3/3] Test moving pages on the Site overview Unit tests for where a drop puts a page, and an e2e smoke test that drags one page under another and checks that a click still selects. Co-Authored-By: Claude Opus 5.5 --- src/routes/site-overview/test/arrange.js | 114 +++++++++++++++++++ tests/e2e/interactions/site-overview.spec.js | 77 +++++++++++++ 2 files changed, 191 insertions(+) create mode 100644 src/routes/site-overview/test/arrange.js create mode 100644 tests/e2e/interactions/site-overview.spec.js diff --git a/src/routes/site-overview/test/arrange.js b/src/routes/site-overview/test/arrange.js new file mode 100644 index 00000000..2782e206 --- /dev/null +++ b/src/routes/site-overview/test/arrange.js @@ -0,0 +1,114 @@ +/** + * External dependencies + */ +import { describe, expect, test } from 'vitest'; + +/** + * Internal dependencies + */ +import { buildPageTree } from '../../content/pages/page-tree'; +import { + applyPageTree, + canDropOnPage, + getDropChanges, + getDropPosition, +} from '../arrange'; + +// About (1) with Team (2) under it, then Contact (3). +const PAGES = [ + { id: 1, menu_order: 0, parent: 0, title: 'About' }, + { id: 2, menu_order: 0, parent: 1, title: 'Team' }, + { id: 3, menu_order: 1, parent: 0, title: 'Contact' }, +]; +const TREE = buildPageTree( PAGES ); + +// The top level's page IDs, in order, once some changes are made. +function getTopLevel( changes ) { + return buildPageTree( + PAGES.map( ( page ) => ( { + ...page, + ...changes.find( ( change ) => change.id === page.id ), + } ) ) + ).map( ( item ) => item.page.id ); +} + +describe( 'getDropPosition', () => { + test( 'puts a page beside a card near its edges, and under it in the middle', () => { + expect( getDropPosition( 0.1 ) ).toBe( 'before' ); + expect( getDropPosition( 0.5 ) ).toBe( 'under' ); + expect( getDropPosition( 0.9 ) ).toBe( 'after' ); + } ); +} ); + +describe( 'canDropOnPage', () => { + test( 'refuses a page on itself or on a page under it', () => { + expect( canDropOnPage( TREE, 1, 1 ) ).toBe( false ); + expect( canDropOnPage( TREE, 1, 2 ) ).toBe( false ); + expect( canDropOnPage( TREE, 3, 2 ) ).toBe( true ); + } ); +} ); + +describe( 'getDropChanges', () => { + test( 'puts a page under another, after the pages already there', () => { + expect( + getDropChanges( TREE, 3, { position: 'under', targetId: 1 } ) + ).toEqual( [ { id: 3, menu_order: 1, parent: 1 } ] ); + } ); + + test( 'puts a page before another, among its siblings', () => { + expect( + getTopLevel( + getDropChanges( TREE, 3, { position: 'before', targetId: 1 } ) + ) + ).toEqual( [ 3, 1 ] ); + } ); + + test( 'moves a sub-page to the top level, at the end', () => { + expect( + getTopLevel( getDropChanges( TREE, 2, { position: 'top' } ) ) + ).toEqual( [ 1, 3, 2 ] ); + } ); + + test( 'does nothing for a drop it refuses', () => { + expect( + getDropChanges( TREE, 1, { position: 'under', targetId: 2 } ) + ).toEqual( [] ); + } ); +} ); + +describe( 'applyPageTree', () => { + test( 'draws pages where their unsaved moves put them', () => { + const overview = { + edges: [ + { from: 'home', kind: 'child', to: 'page-1' }, + { from: 'home', kind: 'child', to: 'page-3' }, + { from: 'page-1', kind: 'child', to: 'page-2' }, + ], + nodes: [ + { id: 'home', kind: 'home' }, + { id: 'page-1', kind: 'page' }, + { id: 'page-2', kind: 'page' }, + { id: 'page-3', kind: 'page' }, + ], + }; + // Contact moved under About, before Team. + const moved = buildPageTree( [ + { id: 1, menu_order: 0, parent: 0 }, + { id: 2, menu_order: 1, parent: 1 }, + { id: 3, menu_order: 0, parent: 1 }, + ] ); + const result = applyPageTree( overview, moved ); + + expect( result.edges ).toEqual( [ + { from: 'home', kind: 'child', to: 'page-1' }, + { from: 'page-1', kind: 'child', to: 'page-3' }, + { from: 'page-1', kind: 'child', to: 'page-2' }, + ] ); + expect( result.nodes.map( ( node ) => node.id ) ).toEqual( [ + 'home', + 'page-1', + 'page-3', + 'page-2', + ] ); + } ); +} ); diff --git a/tests/e2e/interactions/site-overview.spec.js b/tests/e2e/interactions/site-overview.spec.js new file mode 100644 index 00000000..fc225c49 --- /dev/null +++ b/tests/e2e/interactions/site-overview.spec.js @@ -0,0 +1,77 @@ +const { expect, test, visitEditor } = require( '../utils' ); + +// The Site overview has no save bar of its own: changes waiting to be saved +// are counted on the sidebar's Save button. +const getReviewButton = ( page ) => + page.getByRole( 'button', { name: /^Review \d+ changes?/ } ); + +test.describe( 'Site overview interactions', () => { + test( 'drags a page under another page, waiting to be saved', async ( { + page, + rest, + } ) => { + const stamp = Date.now(); + const parent = await rest.createPage( { + title: `Overview parent ${ stamp }`, + } ); + const child = await rest.createPage( { + title: `Overview sub-page ${ stamp }`, + } ); + const getCard = ( id ) => + page.locator( `[data-node-id="page-${ id }"]` ); + const getParent = async () => + ( await rest.fetch( `/wp/v2/pages/${ child.id }` ) ).parent; + + await visitEditor( page, '/site-overview' ); + await expect( getCard( child.id ) ).toBeVisible(); + + const from = await getCard( child.id ).boundingBox(); + const to = await getCard( parent.id ).boundingBox(); + + // The middle of a page's card puts the dragged page under it. + await page.mouse.move( + from.x + from.width / 2, + from.y + from.height / 2 + ); + await page.mouse.down(); + await page.mouse.move( to.x + to.width / 2, to.y + to.height / 2, { + steps: 10, + } ); + await expect( + page.locator( '.cnl-site-overview__drag-label' ) + ).toContainText( `Put under “${ parent.title }”` ); + await page.mouse.up(); + + await expect( + page + .getByTestId( 'snackbar' ) + .getByText( + `Moved “${ child.title }” under “${ parent.title }”.` + ) + ).toBeVisible(); + + // The move waits for Save, like any other change. + await expect( getReviewButton( page ) ).toHaveText( + /^Review 1 change/ + ); + expect( await getParent() ).toBe( 0 ); + } ); + + test( 'a click on a page still selects it rather than moving it', async ( { + page, + rest, + } ) => { + const testPage = await rest.createPage(); + + await visitEditor( page, '/site-overview' ); + await page + .locator( `[data-node-id="page-${ testPage.id }"]` ) + .getByRole( 'button', { name: testPage.title } ) + .click(); + + await expect( page ).toHaveURL( + new RegExp( `node%3Dpage-${ testPage.id }` ) + ); + await expect( getReviewButton( page ) ).toHaveCount( 0 ); + } ); +} );