diff --git a/src/routes/site-overview/_style.scss b/src/routes/site-overview/_style.scss index f61ccd2..8c236e0 100644 --- a/src/routes/site-overview/_style.scss +++ b/src/routes/site-overview/_style.scss @@ -509,3 +509,87 @@ $cnl-site-overview-canvas: #e9eef2; .cnl-site-overview__selected-detail { color: var(--wpds-color-foreground-content-neutral-weak); } + +// --------------------------------------------------------------------------- +// Moving pages: dragged onto each other. +// --------------------------------------------------------------------------- + +.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 { + user-select: none; + + &, + .cnl-site-overview-card, + .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; + } +} + +// 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 0000000..56a2f37 --- /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 56a7c5f..92d3474 100644 --- a/src/routes/site-overview/canvas.jsx +++ b/src/routes/site-overview/canvas.jsx @@ -34,6 +34,7 @@ import { MemoizedStackSheets, } from './lanes'; import { ZoomControls } from './zoom-controls'; +import usePageMoves from './use-page-moves'; import { SelectedPage } from './selected-page'; import { Notice, @@ -96,6 +97,14 @@ export default function Canvas() { const didFitRef = useRef( false ); const boundsRef = useRef( null ); const hasSize = size.width > 0 && size.height > 0; + // The click that ends dragging a page shouldn't select one. + const onDragEnd = useCallback( () => { + suppressClickRef.current = true; + setTimeout( () => { + suppressClickRef.current = false; + } ); + }, [] ); + const pageMoves = usePageMoves( { onDragEnd, siteOverview } ); viewRef.current = view; sizeRef.current = size; @@ -131,8 +140,11 @@ export default function Canvas() { }, [ invalidateSiteOverview ] ); const layout = useMemo( - () => ( siteOverview ? layoutSiteOverview( siteOverview ) : null ), - [ siteOverview ] + () => + pageMoves.overview + ? layoutSiteOverview( pageMoves.overview ) + : null, + [ pageMoves.overview ] ); boundsRef.current = layout?.bounds || null; const scaleLimits = @@ -527,9 +539,13 @@ export default function Canvas() {
( { __( - '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.' ) }

+ { pageMoves.drag && ( +
+ + { pageMoves.drag.title } + + { pageMoves.drag.label && ( + + { pageMoves.drag.label } + + ) } +
+ ) } { selectedNode && hasSize && ( onOpen( node ) } onMouseEnter={ () => onHover( node.id ) } onMouseLeave={ () => onHover( '' ) } + onPointerDown={ ( event ) => onDragStart( event, node ) } style={ { height: node.height, left: node.x, diff --git a/src/routes/site-overview/test/arrange.js b/src/routes/site-overview/test/arrange.js new file mode 100644 index 0000000..2782e20 --- /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/src/routes/site-overview/use-page-moves.js b/src/routes/site-overview/use-page-moves.js new file mode 100644 index 0000000..dd22a25 --- /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, + }; +} diff --git a/tests/e2e/interactions/site-overview.spec.js b/tests/e2e/interactions/site-overview.spec.js new file mode 100644 index 0000000..fc225c4 --- /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 ); + } ); +} );