From eb932db7937b0a3350deab2e310c23a8ab56424f Mon Sep 17 00:00:00 2001 From: Dave Smith Date: Thu, 19 Nov 2026 21:05:07 +0000 Subject: [PATCH 1/5] Try: Simplified publish, with Publish site in the top bar Phase 1 of the "Simplified publish" prototype, on today's in-memory edits. Anything visitors could see waits for Publish site; anything nobody can see yet saves straight away and is never counted. - A dark top bar on every screen: the site's logo and name (opens Name & logo), Go to page, and Publish site, "Up to date", or a quiet "N site changes waiting" note while a page or post is open. - Publish site lists the waiting changes, every page first, with Discard changes behind the Publish button's menu. - Pages and posts save and publish in the canvas with core's header pieces and pre-publish panel, which offers "Also publish N site changes", unticked. - Exit asks to save, exit without saving or keep editing, and only discards the page's own edits. A notice explains, once, when an edit shows on every page. - Menus: new menus are drafts and save as you go; any change to a published menu, its name included, waits. Publish site publishes the draft menus its header and footer changes use. - Edit and Exit/Save change in one view transition, the toolbar's buttons moving on their own rather than inside the canvas's picture. - Warn before leaving the editor with changes waiting, until they are kept between visits. Co-Authored-By: Claude Opus 5.5 --- docs/architecture.md | 10 + docs/webmcp.md | 6 +- packages/app-init/src/index.js | 4 +- src/pickers/identity.jsx | 2 +- src/routes/content/pages/homepage.jsx | 2 +- src/routes/home/site-card.jsx | 27 +- src/routes/navigation-edit/content.jsx | 145 +++++--- .../navigation-edit/menu-items-editor.jsx | 27 +- .../navigation-edit-canvas.jsx | 2 +- .../use-navigation-locations.js | 5 +- .../navigation/add-navigation-modal.jsx | 5 +- src/routes/navigation/canvas.jsx | 2 +- src/routes/navigation/content.jsx | 29 +- src/routes/navigation/menu-helpers.js | 57 ++- src/routes/navigation/menu-row.jsx | 72 +++- src/routes/navigation/use-navigation-menus.js | 44 ++- src/routes/shop/products-screen.jsx | 4 +- src/site-canvas/README.md | 10 +- src/site-canvas/_style.scss | 99 +++++- src/site-canvas/document-actions.jsx | 324 ++++++++++++++++++ src/site-canvas/exit-dialog.jsx | 100 ++++++ src/site-canvas/expansion.js | 13 +- src/site-canvas/mode.js | 122 +++++++ src/site-canvas/site-canvas.jsx | 46 ++- src/site-canvas/toolbar.jsx | 7 +- src/site-canvas/unsaved-changes-dialog.jsx | 62 ---- src/site-canvas/use-site-canvas.js | 176 ++++++++-- src/styles/_stage.scss | 40 +++ src/top-bar/README.md | 46 +++ src/top-bar/agent-status.jsx | 2 +- src/top-bar/index.jsx | 83 ++--- ...ew-changes.jsx => publish-site-dialog.jsx} | 226 +++++------- src/top-bar/publish-status.jsx | 204 +++++++++++ src/top-bar/save-controls.jsx | 119 ------- src/top-bar/site-button.jsx | 73 ++++ src/top-bar/style.scss | 270 ++++++++++----- src/top-bar/use-changes.js | 163 ++++++++- src/webmcp/declarations.js | 4 +- src/webmcp/tools.js | 6 +- 39 files changed, 1991 insertions(+), 647 deletions(-) create mode 100644 src/site-canvas/document-actions.jsx create mode 100644 src/site-canvas/exit-dialog.jsx delete mode 100644 src/site-canvas/unsaved-changes-dialog.jsx create mode 100644 src/top-bar/README.md rename src/top-bar/{review-changes.jsx => publish-site-dialog.jsx} (51%) create mode 100644 src/top-bar/publish-status.jsx delete mode 100644 src/top-bar/save-controls.jsx create mode 100644 src/top-bar/site-button.jsx diff --git a/docs/architecture.md b/docs/architecture.md index a417f660..7084dfdc 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -109,6 +109,16 @@ npm run wp-env run cli wp config delete CNL_EDITOR_UI_THEME The `create-not-learn-editor_ui_theme` filter can override it too. The theme's settings live in `src/theme/`. +## Saving and publishing + +Changes are published in two places, one for each scope, and only one save-like button shows at a time. + +- **The site's changes** are anything visitors would see on more than one page: the site's name, logo and colours, its header and footer, its layouts, a menu that is shown somewhere, which menu a place shows, and the homepage setting. Pages changed from a screen beside the canvas, their title or place in the menu say, count too. They wait for **Publish site** at the end of the dark top bar (`src/top-bar/`), which shows "Up to date" when there's nothing waiting. +- **The page or post open in the canvas** saves and publishes there, with core's post editor buttons. While one is open, Publish site steps back to a quiet note, "N site changes waiting", which does nothing. +- **Anything nobody can see yet** saves at once and is never counted. For menus that means drafts: new menus start as drafts, as core never shows one, and save as they are changed. A published menu may be shown anywhere, so every change to it waits, its name included. Publish site publishes a draft it puts somewhere. + +Nothing is kept between visits yet, so the editor warns before the page is left with anything unsaved. See `src/top-bar/README.md`. + ## Site changes are explicit The editor does not automatically create pages, navigation, or homepage settings, when it loads or when the plugin is activated. A new site keeps WordPress's own default of latest posts on the homepage. Home then offers to set the homepage up the way the workspace expects, step by step, and nothing changes until the person finishes. diff --git a/docs/webmcp.md b/docs/webmcp.md index f2b40f5b..c6643ef2 100644 --- a/docs/webmcp.md +++ b/docs/webmcp.md @@ -2,7 +2,7 @@ An agent working in the browser can use the editor through [WebMCP](https://github.com/webmachinelearning/webmcp), the same way a person would. The editor registers its own tools (`src/webmcp/`), and they change the page open in the canvas, so the person sees each change as it happens. -Every change is an unsaved edit, like one made by hand. It can be undone, and nothing goes live until the person saves it with Save or Review changes. There's no tool for saving. +Every change is an unsaved edit, like one made by hand. It can be undone, and nothing goes live until the person saves or publishes it: the page's own Save or Publish in the canvas, or Publish site in the top bar for the site's changes. There's no tool for saving. ## Connecting an agent @@ -36,7 +36,7 @@ The AI plugin's other features, and the AI the site uses itself, need an AI prov | `cnl-connect` | Gives the agent's name, for the canvas toolbar's list of its changes | | `cnl-start-task` | Names what the agent is working on, so its changes are grouped under it | | `cnl-set-workspace` | Switches workspace, such as to Agent, where the canvas fills the screen so the person can watch, and keeps the page open | -| `cnl-set-canvas` | Switches the canvas to Browse, Edit or Compose, and to desktop, tablet or mobile. Browse asks the person about unsaved changes first, as the canvas's own switch does | +| `cnl-set-canvas` | Switches the canvas to Browse, Edit or Compose, and to desktop, tablet or mobile. Browse asks the person about unsaved edits to the open page first, as Exit does, and stays in the editor while site changes it can't show are waiting | | `cnl-list-pages` | Lists the pages, which one is the homepage and which one is open | | `cnl-open-page` | Opens a page in the canvas, by ID, title or `home` | | `cnl-get-page` | Lists the open page's sections by number, as the canvas names them, with the colours, layouts and widths each can take | @@ -59,7 +59,7 @@ The tools work alongside the official [AI plugin](https://wordpress.org/plugins/ Each change is scrolled into view and flashed for three seconds, without being picked, so the person can watch without the editor's bars opening over the page. The flash is an orange outline and tint, the agent's own colour, with an "Updated by agent" badge in the block label's place (`src/webmcp/flash.js`, `includes/block-canvas-styles.php`). It looks like core's highlight, but is drawn by the editor, as core's `flashBlock` only highlights one block at a time. WebMCP doesn't tell the page which agent called a tool, so the badge can't name it. -In the Agent workspace, while an agent is connected, the canvas toolbar says "Agent: connected" before Save, with a green dot that pulses while the agent works (`src/top-bar/agent-status.jsx`). +In the Agent workspace, while an agent is connected, the top bar says "Agent: connected" before Publish site, with a green dot that pulses while the agent works (`src/top-bar/agent-status.jsx`). Opened, it lists what the agent has changed since the editor loaded, under its name, as one row for each request it worked on, newest first, so a long session stays short to read. The agent names each request with `cnl-start-task`, and its changes go under it until it names the next; changes it makes without naming one are grouped until it pauses for two minutes. diff --git a/packages/app-init/src/index.js b/packages/app-init/src/index.js index ee2976f8..2bb3daec 100644 --- a/packages/app-init/src/index.js +++ b/packages/app-init/src/index.js @@ -33,7 +33,7 @@ import { registerSectionPatterns } from '../../../src/editor-extensions/section- import { registerTemplatePartEditing } from '../../../src/editor-extensions/template-part-editing'; import { mountEditorLayer } from '../../../src/editor-layer'; import { registerLayoutWireframes } from '../../../src/layouts'; -import { mountSaveControls } from '../../../src/top-bar'; +import { mountTopBar } from '../../../src/top-bar'; import { mountWorkspaces } from '../../../src/workspaces'; import { registerWebMcpTools } from '../../../src/webmcp'; import { mountPreferences } from '../../../src/preferences'; @@ -79,7 +79,7 @@ export async function init() { mountMenuSections(); mountPreferences(); mountAdminBar(); - mountSaveControls(); + mountTopBar(); mountCommands(); enhanceSidebar(); registerWebMcpTools(); diff --git a/src/pickers/identity.jsx b/src/pickers/identity.jsx index 78b7e9e8..d5809838 100644 --- a/src/pickers/identity.jsx +++ b/src/pickers/identity.jsx @@ -381,7 +381,7 @@ export function SiteIdentityFields( {
{ __( - 'You are previewing changes. Visitors see them once you save.' + 'You are previewing changes. Visitors see them once you publish the site.' ) } diff --git a/src/routes/content/pages/homepage.jsx b/src/routes/content/pages/homepage.jsx index 67582a60..3fe921e4 100644 --- a/src/routes/content/pages/homepage.jsx +++ b/src/routes/content/pages/homepage.jsx @@ -338,7 +338,7 @@ export function useUseAsHomepage( state ) { { sprintf( /* translators: %s: page title. */ __( - '“%s” isn’t published yet. To be your homepage, visitors need to see it, so it will be published when you save your changes.' + '“%s” isn’t published yet. To be your homepage, visitors need to see it, so it will be published when you publish the site.' ), getPageTitle( pending ) ) } diff --git a/src/routes/home/site-card.jsx b/src/routes/home/site-card.jsx index 8d03e3ce..8bf7e763 100644 --- a/src/routes/home/site-card.jsx +++ b/src/routes/home/site-card.jsx @@ -17,19 +17,17 @@ import { useNavigate } from '@wordpress/route'; import { startHomeTrip } from '../../home-trip'; import { settings } from '../../settings'; import { getSiteAddress } from './site-address'; -import { ReviewChanges } from '../../top-bar/review-changes'; +import { PublishSiteDialog } from '../../top-bar/publish-site-dialog'; import { useChanges } from '../../top-bar/use-changes'; import { Badge, Icon, Link, Tooltip, - _n, __, coreDataStore, decodeEntities, pencilIcon, - sprintf, useSelect, useState, } from '../../wordpress-packages'; @@ -128,15 +126,16 @@ export function SiteAddress( { fallbackLabel } ) { } /** - * How many changes aren't saved yet, as a badge beside the site's name that - * opens the same review Save does. Nothing shows once everything is saved. + * Whether the site has changes waiting to go live, as a badge beside the + * site's name that opens the same dialog Publish site does. Nothing shows + * once everything is published. * * @return {?Element} The status. */ export function SiteStatus() { - const { changes, isSaving } = useChanges(); + const { siteChanges, isSaving } = useChanges(); const [ isReviewOpen, setIsReviewOpen ] = useState( false ); - const count = changes.length; + const count = siteChanges.length; let badge = null; @@ -157,19 +156,11 @@ export function SiteStatus() { render={
) } { isDeleting && ( - -

- { sprintf( - /* translators: %s: navigation menu title. */ - __( - 'Are you sure you want to delete "%s"? This cannot be undone.' - ), - menuTitle - ) } -

-
- - -
-
+ ) } ) } diff --git a/src/routes/navigation-edit/menu-items-editor.jsx b/src/routes/navigation-edit/menu-items-editor.jsx index 76d8e224..4d7e36bf 100644 --- a/src/routes/navigation-edit/menu-items-editor.jsx +++ b/src/routes/navigation-edit/menu-items-editor.jsx @@ -219,12 +219,8 @@ export function useMenuItemsEditor( navigationId ) { : createNavigationLinkBlockFromPage( page ), ], mode === 'submenu-page' - ? __( - 'Submenu added to menu. Review and save changes when you are ready.' - ) - : __( - 'Page added to menu. Review and save changes when you are ready.' - ) + ? __( 'Submenu added to menu.' ) + : __( 'Page added to menu.' ) ); const addCustomLinkToMenu = ( { isSubmenu, label, url } ) => @@ -243,12 +239,8 @@ export function useMenuItemsEditor( navigationId ) { } ), ], isSubmenu - ? __( - 'Submenu added to menu. Review and save changes when you are ready.' - ) - : __( - 'Link added to menu. Review and save changes when you are ready.' - ) + ? __( 'Submenu added to menu.' ) + : __( 'Link added to menu.' ) ); const addLabelOnlySubmenuToMenu = ( label ) => @@ -259,18 +251,11 @@ export function useMenuItemsEditor( navigationId ) { url: '#', } ), ], - __( - 'Submenu added to menu. Review and save changes when you are ready.' - ) + __( 'Submenu added to menu.' ) ); const addMenuItemsToMenu = ( blocks ) => - addNavigationBlocks( - blocks, - __( - 'Menu items added. Review and save changes when you are ready.' - ) - ); + addNavigationBlocks( blocks, __( 'Menu items added.' ) ); // Turn the auto menu into links to the pages it lists now, as a change to // review and save with the rest. diff --git a/src/routes/navigation-edit/navigation-edit-canvas.jsx b/src/routes/navigation-edit/navigation-edit-canvas.jsx index b6e5cb5e..91efb594 100644 --- a/src/routes/navigation-edit/navigation-edit-canvas.jsx +++ b/src/routes/navigation-edit/navigation-edit-canvas.jsx @@ -491,7 +491,7 @@ export default function NavigationEditCanvas() { setLocationModalMode( null ); createSuccessNotice( __( - 'Menu locations updated. Review and save changes when you are ready.' + 'Menu locations updated. They go live when you publish the site.' ), { type: 'snackbar' } ); diff --git a/src/routes/navigation-edit/use-navigation-locations.js b/src/routes/navigation-edit/use-navigation-locations.js index 44f018cc..113ff1f0 100644 --- a/src/routes/navigation-edit/use-navigation-locations.js +++ b/src/routes/navigation-edit/use-navigation-locations.js @@ -66,7 +66,10 @@ export function useNavigationLocations( navigationId ) { }, [ mergeEdits, navigationId ] ); - const fallbackMenuId = menus[ 0 ]?.id; + // The newest published menu, as core picks it. A draft is never shown. + const fallbackMenuId = menus.find( + ( item ) => item.status === 'publish' + )?.id; const locationsMap = useMemo( () => buildNavigationLocationsMap( templateParts, fallbackMenuId ), [ fallbackMenuId, templateParts ] diff --git a/src/routes/navigation/add-navigation-modal.jsx b/src/routes/navigation/add-navigation-modal.jsx index 5d672b2e..547ff01d 100644 --- a/src/routes/navigation/add-navigation-modal.jsx +++ b/src/routes/navigation/add-navigation-modal.jsx @@ -61,7 +61,10 @@ export function AddNavigationModal( { onClose } ) { ...( autoSyncWithPages ? { content: PAGE_LIST_BLOCK_CONTENT } : {} ), - status: 'publish', + // A draft until the site's changes put it somewhere and + // are published: core never shows a draft menu, nor picks + // it for a Navigation block with no menu of its own. + status: 'draft', title: trimmedTitle, }, { throwOnError: true } diff --git a/src/routes/navigation/canvas.jsx b/src/routes/navigation/canvas.jsx index ca429f9a..7482650d 100644 --- a/src/routes/navigation/canvas.jsx +++ b/src/routes/navigation/canvas.jsx @@ -140,7 +140,7 @@ export function Canvas() { setLocationModalMode( null ); createSuccessNotice( __( - 'Menu locations updated. Review and save changes when you are ready.' + 'Menu locations updated. They go live when you publish the site.' ), { type: 'snackbar' } ); diff --git a/src/routes/navigation/content.jsx b/src/routes/navigation/content.jsx index c3058aa9..610809c6 100644 --- a/src/routes/navigation/content.jsx +++ b/src/routes/navigation/content.jsx @@ -35,7 +35,9 @@ import { getMenuRowDescription, getMenuTitle, getNavigationMenuId, + getRenamedNotice, navigateToNavigationEditRoute, + renameMenu, } from './menu-helpers'; import useMainMenu from '../content/use-main-menu'; import { useNavigationMenus } from './use-navigation-menus'; @@ -58,7 +60,7 @@ const LOCATION_ICONS = { function Stage() { const navigate = useNavigate(); const searchParams = useSearch( { strict: false } ); - const { deleteEntityRecord, saveEntityRecord } = + const { deleteEntityRecord, editEntityRecord, saveEntityRecord } = useDispatch( coreDataStore ); const { invalidateNavigationMenus } = useDispatch( cnlEditorStore ); const { createErrorNotice, createSuccessNotice } = @@ -119,18 +121,16 @@ function Stage() { setIsRowActionSaving( true ); try { - await saveEntityRecord( - 'postType', - NAVIGATION_POST_TYPE, - { - id: menuId, - title, - }, - { throwOnError: true } - ); + await renameMenu( { + editEntityRecord, + id: menuId, + isLive: menuToRename.status === 'publish', + saveEntityRecord, + title, + } ); refreshNavigationMenus(); setMenuToRename( null ); - createSuccessNotice( __( 'Navigation menu renamed.' ), { + createSuccessNotice( getRenamedNotice( menuToRename ), { type: 'snackbar', } ); } catch ( renameError ) { @@ -157,7 +157,8 @@ function Stage() { NAVIGATION_POST_TYPE, { content: getMenuContent( menu ), - status: 'publish', + // A draft, as a new menu is: see `add-navigation-modal`. + status: 'draft', title: sprintf( /* translators: %s: navigation menu title. */ __( '%s (Copy)' ), @@ -364,7 +365,11 @@ function Stage() { menuToDelete && ( +

+ { sprintf( + /* translators: %s: where the menu is shown, like "Header". */ + __( + 'Choose another menu for your %s first, so visitors never see an empty space.' + ), + where.toLowerCase() + ) } +

+
+ +
+ + ); + } + return (

- { sprintf( - /* translators: %s: navigation menu title. */ - __( - 'Are you sure you want to delete "%s"? This cannot be undone.' - ), - menuTitle - ) } + { isLive + ? sprintf( + /* translators: %s: navigation menu title. */ + __( + 'If your site shows “%s” anywhere, it goes from there straight away. This can’t be undone.' + ), + menuTitle + ) + : sprintf( + /* translators: %s: navigation menu title. */ + __( + '“%s” isn’t shown anywhere, so visitors won’t notice. It’s deleted straight away, and this can’t be undone.' + ), + menuTitle + ) }

+ ); +} + +/** + * The buttons, after Exit in the canvas toolbar. Gone while the pre-publish + * panel is open, which has its own. + * + * @return {?Element} Save draft and Publish, or Save. + */ +export function DocumentActions() { + const isPanelOpen = useSelect( + ( select ) => select( editorStore ).isPublishSidebarOpened(), + [] + ); + + return ( +
+ + { ! isPanelOpen && } +
+ ); +} + +/** + * The one line for the site's changes in the pre-publish panel. + * + * @return {?Element} The checkbox, while the site has changes waiting. + */ +function AlsoPublishSiteChanges() { + const { count, isIncluded, setIsIncluded } = + useContext( AlsoPublishContext ); + + if ( ! count ) { + return null; + } + + return ( +
+ +
+ ); +} + +/** + * Core's pre- and post-publish panel, at the canvas's right while it is + * open. Its header's Publish is this file's, laid over core's (see + * `_style.scss`). Publishing with "Also publish" ticked publishes the site's + * changes once the page or post is live. + * + * @return {?Element} The panel. + */ +export function DocumentPublishPanel() { + const { isOpen, isPublished, isSaving } = useSelect( + ( select ) => ( { + isOpen: select( editorStore ).isPublishSidebarOpened(), + isPublished: select( editorStore ).isCurrentPostPublished(), + isSaving: select( editorStore ).isSavingPost(), + } ), + [] + ); + const { closePublishSidebar } = useDispatch( editorStore ); + const { siteChanges, publishSite } = useChanges(); + const [ isIncluded, setIsIncluded ] = useState( false ); + const wasPublished = useRef( isPublished ); + + useEffect( () => { + if ( isPublished && ! wasPublished.current && isIncluded ) { + setIsIncluded( false ); + publishSite(); + } + + wasPublished.current = isPublished; + // Only the page going live should publish. + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [ isPublished ] ); + + // Closed with the panel, so it's never ticked without being seen. + useEffect( () => { + if ( ! isOpen ) { + setIsIncluded( false ); + } + }, [ isOpen ] ); + + if ( ! isOpen ) { + return null; + } + + const isPrePublish = ! isPublished && ! isSaving; + + return ( + +
+ + { isPrePublish && ( +
+ +
+ ) } +
+
+ ); +} diff --git a/src/site-canvas/exit-dialog.jsx b/src/site-canvas/exit-dialog.jsx new file mode 100644 index 00000000..a18b66ff --- /dev/null +++ b/src/site-canvas/exit-dialog.jsx @@ -0,0 +1,100 @@ +/** + * Asked on Exit, or on leaving for another screen, when the page or post + * open in the canvas has unsaved edits: save them, leave without them, or + * keep editing. Only the open page or post's edits are at stake. The site's + * changes wait for Publish site whichever is picked. + * + * Not a `ConfirmDialog`: that puts Cancel on the left and its confirm on the + * right, and both dismiss. Here the left button is itself destructive, so + * the buttons are ordinary ones, and the modal's own close (Escape, the X, + * the overlay) means "keep editing" too. + */ + +/** + * WordPress dependencies + */ +import { store as editorStore } from '@wordpress/editor'; + +/** + * Internal dependencies + */ +import { + __, + Button, + decodeEntities, + Modal, + sprintf, + useSelect, +} from '../wordpress-packages'; + +export function ExitDialog( { isSaving, onCancel, onDiscard, onSave } ) { + const { title, isDraft } = useSelect( ( select ) => { + const editor = select( editorStore ); + + return { + title: editor.getEditedPostAttribute( 'title' ), + isDraft: ! editor.isCurrentPostPublished(), + }; + }, [] ); + + return ( + +

+ { isDraft + ? __( 'You have changes that aren’t saved.' ) + : __( + 'You have changes that aren’t saved. Saving updates the live page.' + ) } +

+
+ +
+ + +
+
+
+ ); +} diff --git a/src/site-canvas/expansion.js b/src/site-canvas/expansion.js index 1d823bc6..817632e0 100644 --- a/src/site-canvas/expansion.js +++ b/src/site-canvas/expansion.js @@ -46,17 +46,24 @@ function withTransition( update ) { /** * Expand the canvas, or put it back beside the sidebar and the screen, - * animated. Does nothing if it is already that way. + * animated. Does nothing more if it is already that way. * - * @param {boolean} next Whether to expand it. + * @param {boolean} next Whether to expand it. + * @param {?() => void} change Anything else that changes with it, such as + * the canvas's mode, so the transition's before + * and after pictures each show one state of the + * canvas, toolbar included, rather than the + * toolbar changing first and the canvas after. */ -export function expandCanvas( next ) { +export function expandCanvas( next, change = null ) { if ( next === document.body.classList.contains( EXPANDED_CLASS ) ) { + change?.(); setCanvasExpanded( next ); return; } withTransition( () => { + change?.(); setCanvasExpanded( next ); // Applied at once, so the transition's after picture has it. document.body.classList.toggle( EXPANDED_CLASS, next ); diff --git a/src/site-canvas/mode.js b/src/site-canvas/mode.js index 79928e38..4316e3b3 100644 --- a/src/site-canvas/mode.js +++ b/src/site-canvas/mode.js @@ -77,6 +77,9 @@ if ( ! select( STORE_NAME ) ) { pickedSection: null, postsTrip: null, editableSection: null, + openDocument: null, + exitRequest: null, + selfSaving: [], }, action ) { @@ -107,6 +110,19 @@ if ( ! select( STORE_NAME ) ) { ...state, editableSection: action.editableSection, }; + case 'SET_OPEN_DOCUMENT': + return { ...state, openDocument: action.openDocument }; + case 'SET_EXIT_REQUEST': + return { ...state, exitRequest: action.exitRequest }; + case 'SET_SELF_SAVING': + return { + ...state, + selfSaving: action.isSelfSaving + ? [ ...state.selfSaving, action.id ] + : state.selfSaving.filter( + ( id ) => id !== action.id + ), + }; } return state; @@ -152,6 +168,19 @@ if ( ! select( STORE_NAME ) ) { editableSection, type: 'SET_EDITABLE_SECTION', } ), + setOpenDocument: ( openDocument ) => ( { + openDocument, + type: 'SET_OPEN_DOCUMENT', + } ), + setExitRequest: ( exitRequest ) => ( { + exitRequest, + type: 'SET_EXIT_REQUEST', + } ), + setSelfSaving: ( id, isSelfSaving ) => ( { + id, + isSelfSaving, + type: 'SET_SELF_SAVING', + } ), }, selectors: { getCanvasMode: ( state ) => state.mode, @@ -164,6 +193,9 @@ if ( ! select( STORE_NAME ) ) { getPartRequest: ( state ) => state.partRequest, getPostsTrip: ( state ) => state.postsTrip, getEditableSection: ( state ) => state.editableSection, + getOpenDocument: ( state ) => state.openDocument, + getExitRequest: ( state ) => state.exitRequest, + getSelfSaving: ( state ) => state.selfSaving, }, } ) ); @@ -400,3 +432,93 @@ export function setEditableSection( editableSection ) { export function getEditableSection() { return select( STORE_NAME ).getEditableSection(); } + +/** + * Note the page or post open in the expanded canvas, or that none is. While + * one is, it saves and publishes from the canvas, and everything else waits + * for Publish site in the top bar. See `src/top-bar/README.md`. + * + * @param {?Object} entity `{ postType, postId }`, or null. + */ +export function setOpenDocument( entity ) { + const current = select( STORE_NAME ).getOpenDocument(); + + if ( + current?.postType !== entity?.postType || + String( current?.postId ) !== String( entity?.postId ) + ) { + dispatch( STORE_NAME ).setOpenDocument( + entity ? { postType: entity.postType, postId: entity.postId } : null + ); + } +} + +/** + * @return {?Object} `{ postType, postId }` of the page or post open in the + * expanded canvas, or null, kept up to date. + */ +export function useOpenDocument() { + return useSelect( + ( selectStore ) => selectStore( STORE_NAME ).getOpenDocument(), + [] + ); +} + +/** + * Ask the canvas to stop editing its page or post, as its Exit does, asking + * about unsaved edits first, then call `onLeave`. Without a document open, + * `onLeave` is called straight away. Keeping the request in the store lets + * the top bar, built in app init, ask a canvas built in a route's bundle. + * + * @param {Function} onLeave Called once the canvas has let go, not at all if + * the user keeps editing. + */ +export function requestExit( onLeave ) { + if ( ! select( STORE_NAME ).getOpenDocument() ) { + onLeave(); + return; + } + + dispatch( STORE_NAME ).setExitRequest( { onLeave } ); +} + +/** + * Take up a request to exit, clearing it. + * + * @return {?Object} `{ onLeave }`, or null. + */ +export function useExitRequest() { + return useSelect( + ( selectStore ) => selectStore( STORE_NAME ).getExitRequest(), + [] + ); +} + +export function clearExitRequest() { + dispatch( STORE_NAME ).setExitRequest( null ); +} + +/** + * Note that a record saves itself as it is changed, as a menu shown nowhere + * does, so its edits are never counted as waiting for Publish site. + * + * @param {string} id `kind|name|key`. + * @param {boolean} isSelfSaving Whether it does now. + */ +export function setSelfSaving( id, isSelfSaving ) { + const isListed = select( STORE_NAME ).getSelfSaving().includes( id ); + + if ( isListed !== isSelfSaving ) { + dispatch( STORE_NAME ).setSelfSaving( id, isSelfSaving ); + } +} + +/** + * @return {string[]} `kind|name|key` of every record that saves itself. + */ +export function useSelfSaving() { + return useSelect( + ( selectStore ) => selectStore( STORE_NAME ).getSelfSaving(), + [] + ); +} diff --git a/src/site-canvas/site-canvas.jsx b/src/site-canvas/site-canvas.jsx index c28825fb..d4536f0c 100644 --- a/src/site-canvas/site-canvas.jsx +++ b/src/site-canvas/site-canvas.jsx @@ -31,7 +31,9 @@ import { hasSections as hasSectionsFor } from '../sections'; import { useComposeZoom } from './compose/use-compose-zoom'; import { EDITOR_DEVICES } from './constants'; import { useEditSectionControls } from './edit-section-controls'; -import { MODE_COMPOSE, MODE_EDIT } from './mode'; +import { DocumentActions, DocumentPublishPanel } from './document-actions'; +import { ExitDialog } from './exit-dialog'; +import { MODE_COMPOSE, MODE_EDIT, setOpenDocument } from './mode'; import { expandCanvas, useCanvasExpansion } from './expansion'; import { SectionModesLayer } from './section-modes/section-modes-layer'; import { @@ -44,7 +46,6 @@ import { ViewMenu, ZoomOutToggle, } from './toolbar'; -import { UnsavedChangesDialog } from './unsaved-changes-dialog'; import { useOwnEditorSettings } from './use-own-editor-settings'; import { useSectionLock } from './use-section-lock'; import { useZoomGestures, ZoomControls } from './zoom-controls'; @@ -117,6 +118,22 @@ export function SiteCanvas( { // Only a change of mode should move it. // eslint-disable-next-line react-hooks/exhaustive-deps }, [ isPreviewing ] ); + /* + * A page or post, not a layout or a header, open in the expanded canvas + * saves and publishes here, with core's buttons. Everything else waits + * for Publish site. See `src/top-bar/README.md`. + */ + const openDocument = + isExpanded && + ! isPreviewing && + editorEntity && + ! editorEntity.postType.startsWith( 'wp_' ) + ? editorEntity + : null; + useEffect( () => { + setOpenDocument( openDocument ); + }, [ openDocument ] ); + useEffect( () => () => setOpenDocument( null ), [] ); // Document Overview's list closes as the canvas goes back. useEffect( () => { if ( ! isExpanded ) { @@ -215,7 +232,7 @@ export function SiteCanvas( { liveUrl={ canvas.liveUrl } editRoute={ canvas.editRoute } /> - { canZoom && ( + { canZoom && ! canvas.isAwaitingPreview && ( @@ -223,15 +240,21 @@ export function SiteCanvas( { } /> ) } - { /* Save goes after these, from `src/top-bar`. */ } - { isPreviewing && canvas.canEdit && ( + { /* + * Edit while the page is on view, or while the editor + * only shows a change made beside it. Exit once it + * fills the editor, then the open page or post's own + * buttons. + */ } + { ( isPreviewing || ! isExpanded ) && canvas.canEdit && ( - canvas.requestMode( MODE_EDIT ) } - /> + ) } - { ! isPreviewing && } + { ! isPreviewing && isExpanded && ( + + ) } + { openDocument && }
@@ -265,6 +288,7 @@ export function SiteCanvas( { onExitCompose={ () => canvas.requestMode( MODE_EDIT ) } /> ) } + { openDocument && } { canZoom && (
- { canvas.dialog.isOpen && ( - - ) } + { canvas.dialog.isOpen && } ); } diff --git a/src/site-canvas/toolbar.jsx b/src/site-canvas/toolbar.jsx index fbd99862..70155697 100644 --- a/src/site-canvas/toolbar.jsx +++ b/src/site-canvas/toolbar.jsx @@ -91,8 +91,9 @@ export function EditButton( { onEdit } ) { } /** - * Exit, beside Save while editing. It leaves without saving: unsaved changes - * are discarded, the page is on view again and the sidebar comes back. + * Exit, before the page or post's own buttons while editing. It stops + * editing, asking first about unsaved edits to the page or post, and the + * sidebar comes back. The site's changes keep waiting for Publish site. * * @param {Object} props * @param {Function} props.onExit Stops editing. @@ -103,7 +104,7 @@ export function ExitButton( { onExit } ) { - - -
- ); -} diff --git a/src/site-canvas/use-site-canvas.js b/src/site-canvas/use-site-canvas.js index da6c4251..b95bad87 100644 --- a/src/site-canvas/use-site-canvas.js +++ b/src/site-canvas/use-site-canvas.js @@ -9,9 +9,12 @@ * by every canvas, see `mode.js`. Because the preview only shows what is * saved: * - * - Moving to Browse with unsaved changes asks to save or discard them. - * A change the caller shows in the preview anyway, such as a page's - * layout passed along in its URL, doesn't count. + * - Exit, or moving to Browse, asks about unsaved edits to the open page or + * post, and only ever discards those. The site's changes wait for Publish + * site, and while any the preview can't show are waiting, the editor stays + * on show beside the screen to show them. A change the caller shows in the + * preview anyway, such as a page's layout passed along in its URL, doesn't + * count. * - Moving to Browse after saving, or from a page the preview isn't on, * holds the editor until the preview has loaded the page, so it never shows * an out-of-date page. @@ -29,7 +32,11 @@ import { unlock } from '../lock-unlock'; import { cnlEditorStore } from '../records'; import { namespace, settings } from '../settings'; -import { useChanges } from '../top-bar/use-changes'; +import { + getDirtyRecords, + isDocumentChange, + useChanges, +} from '../top-bar/use-changes'; import { blockEditorStore, coreDataStore, @@ -43,7 +50,9 @@ import { useState, } from '../wordpress-packages'; import { DEFAULT_DEVICE, EDITOR_DEVICES } from './constants'; +import { expandCanvas } from './expansion'; import { + clearExitRequest, getCanvasMode, isShowingChange, MODE_BROWSE, @@ -56,6 +65,8 @@ import { STORE_NAME as CANVAS_STORE, useCanvasDevice, useCanvasMode, + useExitRequest, + useOpenDocument, } from './mode'; import { getEditRoute, getLiveUrl, isSameLocation } from './urls'; import { usePreviewFrame } from './use-preview-frame'; @@ -280,7 +291,10 @@ export function useSiteCanvas( { const [ savedVersion, setSavedVersion ] = useState( 0 ); const savedVersionRef = useRef( 0 ); const waitRef = useRef( 0 ); - const { changes, isSaving, save, discardAll } = useChanges(); + const { changes, discard, documentChange, isSaving } = useChanges(); + const openDocument = useOpenDocument(); + // What to do once the user has left the open document, if they do. + const onLeaveRef = useRef( null ); /* * Counted in a selector so that it follows a record's own edits: a page * already changed is the same one change whatever else is edited on it. @@ -292,7 +306,6 @@ export function useSiteCanvas( { ).length, [ changes, isShownInPreview ] ); - const isDirty = unseenChangeCount > 0; // Every save that finishes leaves the preview showing an older site. const wasSavingRef = useRef( isSaving ); @@ -468,6 +481,20 @@ export function useSiteCanvas( { setShowingChange( true ); } + /* + * Shown beside the screen, and now published or discarded: nothing + * is left that the preview can't show, so the page is on view again. + */ + if ( + ! unseenChangeCount && + isShowingChange() && + ! isPreviewing && + ! openDocument + ) { + setShowingChange( false ); + showPreview(); + } + changeCountRef.current = unseenChangeCount; // Only a new change should switch, not the mode changing. // eslint-disable-next-line react-hooks/exhaustive-deps @@ -556,12 +583,7 @@ export function useSiteCanvas( { return; } - if ( isDirty ) { - setIsDialogOpen( true ); - return; - } - - showPreview(); + exit(); }; // A move asked for from outside the canvas, by `requestCanvasMode`, @@ -579,36 +601,120 @@ export function useSiteCanvas( { // eslint-disable-next-line react-hooks/exhaustive-deps }, [ modeRequest ] ); - const saveAndShowPreview = async () => { - await save(); + /* + * Leave editing. The site's changes stay waiting for Publish site, and the + * preview only shows what is published, so while any it can't show are + * waiting, the editor stays on show to show them, put back beside the + * screen. Otherwise the page is on view again. + */ + const leave = ( { hasSaved = false } = {} ) => { + const onLeave = onLeaveRef.current; + onLeaveRef.current = null; + setIsDialogOpen( false ); + + const unseen = getDirtyRecords( select ).filter( + ( record ) => + ! isDocumentChange( record, openDocument ) && + ! isShownInPreview( record, select ) + ); + + /* + * The canvas goes back beside the screen straight away, Edit in + * Exit's place, as one transition, even when the preview has to + * load before it shows. + */ + if ( unseen.length && editorEntity ) { + setShowingChange( true ); + expandCanvas( false ); + } else if ( hasSaved ) { + // The preview hasn't seen the save yet, whatever it last loaded. + expandCanvas( false, () => + showPreviewWhenLoaded( getEditorDestination() ) + ); + } else { + expandCanvas( false, showPreview ); + } + + onLeave?.(); + }; + + /** + * Exit: leave the open page or post, asking first if it has unsaved + * edits. Nothing else is discarded. + * + * @param {?Function} onLeave Called once left, as when the top bar asks. + */ + const exit = ( onLeave = null ) => { + onLeaveRef.current = onLeave; + + if ( documentChange ) { + setIsDialogOpen( true ); + return; + } + + leave(); + }; + + const saveAndExit = async () => { + await dispatch( 'core/editor' ).savePost(); - // Core reports a failed save in a snackbar and leaves the changes in + // Core reports a failed save in a notice and leaves the edits in // place. Stay in the editor with them. if ( - select( coreDataStore ).__experimentalGetDirtyEntityRecords().length + openDocument && + select( coreDataStore ).hasEditsForEntityRecord( + 'postType', + openDocument.postType, + openDocument.postId + ) ) { setIsDialogOpen( false ); + onLeaveRef.current = null; return; } - setIsDialogOpen( false ); - showPreviewWhenLoaded( getEditorDestination() ); + leave( { hasSaved: true } ); }; - const discardAndShowPreview = () => { - const destination = getEditorDestination(); + const discardAndExit = () => { + if ( documentChange ) { + discard( documentChange ); + } - discardAll(); - setIsDialogOpen( false ); - cancelWait(); + leave(); + }; + + // The top bar asking to leave, to open another screen. + const exitRequest = useExitRequest(); + useEffect( () => { + if ( exitRequest ) { + clearExitRequest(); + exit( exitRequest.onLeave ); + } + // Only a new request should exit. + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [ exitRequest ] ); + + /* + * Edit, while the editor is on show beside the screen to show a change: + * fill the editor to change the page, as Edit does from the preview. + */ + const expand = () => { + setShowingChange( false ); + expandCanvas( true ); + }; - if ( destination ) { - frame.navigate( destination ); - } else if ( isPreviewStale ) { - frame.reload(); + /* + * Edit, from the page on view: the editor and the expanded canvas come + * in one transition, so Exit and Save take Edit's place as it grows. + */ + const edit = () => { + if ( ! isPreviewing ) { + expand(); + return; } - setCanvasMode( MODE_BROWSE ); + expandCanvas( true, () => requestMode( MODE_EDIT ) ); }; const editRoute = canEdit ? getEditRoute( canvasEntity ) : null; @@ -620,10 +726,14 @@ export function useSiteCanvas( { dialog: { isOpen: isDialogOpen, isSaving, - onCancel: () => setIsDialogOpen( false ), - onDiscard: discardAndShowPreview, - onSave: saveAndShowPreview, + onCancel: () => { + onLeaveRef.current = null; + setIsDialogOpen( false ); + }, + onDiscard: discardAndExit, + onSave: saveAndExit, }, + edit, editorEntity, editRoute, isEditorReady, @@ -640,8 +750,8 @@ export function useSiteCanvas( { previewContextError, previewEntity, requestMode, - // Exit: leave editing without saving, as Discard in the dialog does. - exit: discardAndShowPreview, + exit: () => exit(), + expand, setDevice: setCanvasDevice, showEditor, }; diff --git a/src/styles/_stage.scss b/src/styles/_stage.scss index 91a5720a..46958e63 100644 --- a/src/styles/_stage.scss +++ b/src/styles/_stage.scss @@ -153,4 +153,44 @@ html:root.cnl-canvas-is-transitioning { &::view-transition-new(boot-safari--canvas) { object-position: left top; } + + /* + * The buttons at the end of the canvas's toolbar move on their own. In + * the canvas's picture, held at its start, they would slide sideways and + * be cut off as it grows or shrinks from that side. The View menu + * glides to its new place, and Edit fades into Exit and the page's own + * buttons where they sit, each picture at its natural size. + */ + .cnl-editor-homepage-toolbar__right { + + > .cnl-site-canvas__view-menu-toggle { + view-transition-name: cnl-canvas-view; + } + + > .cnl-site-canvas__zoom-out-toggle { + view-transition-name: cnl-canvas-zoom; + } + + > .cnl-site-canvas__edit, + > * > .cnl-site-canvas__edit { + view-transition-name: cnl-canvas-edit; + } + + > .cnl-site-canvas__exit { + view-transition-name: cnl-canvas-exit; + } + + > .cnl-document-actions { + view-transition-name: cnl-canvas-document-actions; + } + } + + // Above the canvas's own picture, which boot raises. + &::view-transition-group(cnl-canvas-view), + &::view-transition-group(cnl-canvas-zoom), + &::view-transition-group(cnl-canvas-edit), + &::view-transition-group(cnl-canvas-exit), + &::view-transition-group(cnl-canvas-document-actions) { + z-index: 2; + } } diff --git a/src/top-bar/README.md b/src/top-bar/README.md new file mode 100644 index 00000000..31111d3f --- /dev/null +++ b/src/top-bar/README.md @@ -0,0 +1,46 @@ +# Top bar and Publish site + +The strip of boot's dark frame above the sidebar, the screen and the canvas, on every screen. The expanded canvas and small screens keep it too. Only core's full-screen editor, opened with "Open in advanced editor", hides it, as that has a header of its own. `mountTopBar()` adds it to boot's layout, which has no slot for it. + +- **Start:** the site's logo and name (`site-button.jsx`). They open Name & logo, asking first about unsaved edits to a page or post open in the canvas, as Exit does. +- **Middle:** Go to page, the page finder (`src/page-finder`). It goes on small screens. +- **End:** which agent is connected, if one is (`agent-status.jsx`), and the publish status (`publish-status.jsx`). + +## Two scopes, one button at a time + +`use-changes.js` splits what is unsaved in two: + +- **The open document:** the page or post filling the canvas, as `src/site-canvas` notes it in the mode's store. It saves and publishes from the canvas, with core's buttons. See `src/site-canvas/README.md`. +- **The site's changes:** everything else. They wait for **Publish site**. + +The end of the bar shows one of three things: + +| State | Shows | +| --- | --- | +| Site changes waiting, no page or post open | **Publish site**, a primary button | +| Site changes waiting, a page or post open | "N site changes waiting", quiet text that does nothing. The page's own buttons are the button now, and Publish site comes back on leaving it | +| Nothing waiting | "✓ Up to date", quiet text, not a button | + +Publish site opens a dialog (`publish-site-dialog.jsx`), as does the Home site card's badge: the changes, those shown on every page first under a purple heading, then pages changed beside the canvas, and **Publish**. **Discard changes…** sits behind the arrow beside it, and asks first. + +Cmd+S follows the same rule: it saves the open page or post, or else opens Publish site. It is caught before boot's own shortcut, which would open boot's review of every change. + +An edit made while a page is open that turns out to be the site's, like the header, says once a session that it waits for Publish site. + +## What waits, and what doesn't + +The rule is whether visitors could see it: + +- **Could be seen on the site:** waits for Publish site. +- **Seen by nobody yet:** saves at once, and is never counted. + +For menus, the editor can't know every place one is shown: a Navigation block can sit in any template, page, post or widget, and one with no menu of its own shows the newest published menu. So the only safe line is the menu's status. Core never shows a draft menu, nor picks one as the fallback. + +- **New menus are drafts**, whether added or duplicated. A draft saves as it is changed, renamed or filled (`useSaveWhileDraft()` in `src/routes/navigation-edit/content.jsx`), and is listed in the mode's store as saving itself so it never shows as waiting. +- **A published menu may be live**, so every change to it waits for Publish site, its name included: the name labels the menu for screen readers on the site. +- **Putting a draft somewhere** is a change to the template part it goes in, so it waits. Publish site then publishes the draft with it (`publishDraftMenus()` in `use-changes.js`), so the place never shows an empty menu. +- **Deleting** a menu in a place the editor knows of, the header say, isn't possible until another takes its place. Any other menu can be deleted after a warning, which for a published menu says it goes from wherever the site shows it, at once. + +## Nothing kept between visits yet + +The site's changes live in the editor's memory, as core's edits do, so the editor warns before the page is left while anything is unsaved. Keeping them as a site draft between visits, site history and scheduling are the next steps. diff --git a/src/top-bar/agent-status.jsx b/src/top-bar/agent-status.jsx index abcf11d1..9666ce63 100644 --- a/src/top-bar/agent-status.jsx +++ b/src/top-bar/agent-status.jsx @@ -154,7 +154,7 @@ function BatchList( { batches, isActive, name, now, onClose } ) { ) }

- { __( 'Nothing goes live until you save.' ) } + { __( 'Nothing goes live until you publish.' ) }

); diff --git a/src/top-bar/index.jsx b/src/top-bar/index.jsx index 69390fac..1659c6ef 100644 --- a/src/top-bar/index.jsx +++ b/src/top-bar/index.jsx @@ -1,75 +1,76 @@ /** - * Save controls in the canvas toolbar. + * Top bar: the strip of boot's dark frame above the stage and canvas, on + * every screen, the expanded canvas and small screens included. * - * There used to be a top bar of its own above the stage and canvas, with Go - * to page, the save controls and an Options menu. Go to page is now the page's - * name in the canvas toolbar (`src/site-canvas/page-switcher.jsx`), and - * Preferences is in the workspace menu at the foot of the sidebar. What's left - * sits at the end of the canvas toolbar: which agent is connected, if one is - * (see `src/webmcp/connection.js`), and the save controls. The way to the - * full-screen editor is in the canvas's View menu. - * - * A screen with no canvas toolbar, like Media or Posts, keeps boot's own save - * button at the foot of the sidebar instead. `body.cnl-has-canvas-save` says - * which, for `style.scss`. + * The site's logo and name are at the start, and open Name & logo. Go to + * page, which opens the page finder (see `src/page-finder`), is in the + * middle. At the end are which agent is connected, if one is (see + * `src/webmcp/connection.js`), and Publish site, for the changes that are + * the site's rather than one page's. See `README.md` for how changes are + * split between Publish site and the canvas's own Save and Publish. */ /** * WordPress dependencies */ import { createRoot } from '@wordpress/element'; +import { __ } from '@wordpress/i18n'; /** * Internal dependencies */ +import { PageFinder } from '../page-finder'; import { AgentStatus } from './agent-status'; -import { SaveControls } from './save-controls'; - -const HAS_CANVAS_SAVE_CLASS = 'cnl-has-canvas-save'; +import { PublishStatus } from './publish-status'; +import { SiteButton } from './site-button'; -const TOOLBAR_END_SELECTOR = - '#create-not-learn-editor-app .cnl-editor-homepage-toolbar__right'; - -function CanvasSave() { +function TopBar() { return ( -
- - +
+
+ +
+
+ +
+
+ + +
); } /** - * Add the save controls to the canvas toolbar on show. + * Add the top bar to boot's layout. * - * Boot has no slot in the canvas's toolbar, and the toolbar comes and goes - * with the screen, so the controls are rendered once and moved into whichever - * toolbar is on show, whenever the page changes. + * Boot has no slot above its surfaces, so the bar is appended to boot's + * layout element, which covers the whole screen, and positioned in the margin + * `style.scss` opens above the surfaces. The layout can remount, so the bar + * is put back whenever it goes missing. */ -export function mountSaveControls() { +export function mountTopBar() { const container = document.createElement( 'div' ); - container.className = 'cnl-canvas-save-host'; - createRoot( container ).render( ); + container.className = 'cnl-top-bar-host'; + createRoot( container ).render( ); let isScheduled = false; const place = () => { isScheduled = false; - const toolbarEnd = document.querySelector( TOOLBAR_END_SELECTOR ); - - document.body.classList.toggle( - HAS_CANVAS_SAVE_CLASS, - Boolean( toolbarEnd ) - ); - - if ( ! toolbarEnd ) { - container.remove(); + if ( container.isConnected ) { return; } - // Last in the toolbar, as Save is in core's editor. - if ( toolbarEnd.lastElementChild !== container ) { - toolbarEnd.append( container ); + const layout = document.querySelector( + '#create-not-learn-editor-app [class*="__layout"]:has(> [class*="__surfaces"])' + ); + + if ( layout && container.parentElement !== layout ) { + layout.append( container ); } }; diff --git a/src/top-bar/review-changes.jsx b/src/top-bar/publish-site-dialog.jsx similarity index 51% rename from src/top-bar/review-changes.jsx rename to src/top-bar/publish-site-dialog.jsx index c3f01c4e..86ae0cc7 100644 --- a/src/top-bar/review-changes.jsx +++ b/src/top-bar/publish-site-dialog.jsx @@ -1,32 +1,35 @@ /** - * Review changes: every change waiting to be saved, each of which can be - * discarded, with Save and Discard all for the lot. + * Publish site: the site's changes waiting to go live, and Publish. * - * Discarding everything is asked about first, in the same dialog, because it - * cannot be undone. + * The site's changes are everything unsaved except the page or post open in + * the canvas, which publishes there (see `use-changes.js`). Those that show + * on every page, like the header, come first, under a purple heading with a + * globe, as the editor marks anything shared (see `src/global-scope`). Pages + * changed from a screen beside the canvas, their title or place say, follow. * - * Changes come in two groups, each saying what its changes reach. Those that - * show on every page, like the header, come first, under a purple heading - * with a globe and with purple Discard buttons, as the editor marks anything - * shared. Those that change only the page or post they were made on follow, - * unmarked. See `src/global-scope`. + * The dialog is a list and Publish. Discarding them all sits behind the menu + * beside Publish, and is asked about first, in the same dialog, because it + * can't be undone. */ /** * WordPress dependencies */ -import { Button, Modal } from '@wordpress/components'; +import { Button, DropdownMenu, MenuItem, Modal } from '@wordpress/components'; import { useDispatch } from '@wordpress/data'; import { Fragment, useEffect, useId, - useLayoutEffect, useRef, useState, } from '@wordpress/element'; import { __, _n, sprintf } from '@wordpress/i18n'; -import { globe as globeIcon, page as pageIcon } from '@wordpress/icons'; +import { + chevronDown as chevronDownIcon, + globe as globeIcon, + page as pageIcon, +} from '@wordpress/icons'; import { store as noticesStore } from '@wordpress/notices'; import { Icon, Stack, Text } from '@wordpress/ui'; @@ -41,14 +44,14 @@ const GROUPS = [ id: 'site-wide', isSiteWide: true, icon: globeIcon, - title: __( 'Site-wide changes' ), + title: __( 'Every page' ), description: __( 'These change every page of your site.' ), }, { id: 'page', isSiteWide: false, icon: pageIcon, - title: __( 'Page changes' ), + title: __( 'Pages and posts' ), description: __( 'These change only the page or post they were made on.' ), @@ -59,7 +62,7 @@ const GROUPS = [ // session's changes don't turn the dialog into a long scroll. const VISIBLE_CHANGES = 5; -function ChangeGroup( { group, changes, onDiscard } ) { +function ChangeGroup( { group, changes } ) { const headingId = useId(); const listRef = useRef(); const [ isExpanded, setIsExpanded ] = useState( false ); @@ -69,17 +72,7 @@ function ChangeGroup( { group, changes, onDiscard } ) { const visibleChanges = hiddenCount ? changes.slice( 0, VISIBLE_CHANGES ) : changes; - - // The button goes once pressed, so focus moves to the first row it showed. - const showAll = () => { - setIsExpanded( true ); - window.requestAnimationFrame( () => { - listRef.current - ?.querySelectorAll( '.cnl-review-changes__discard' ) - [ VISIBLE_CHANGES ]?.focus(); - } ); - }; - // Purple, from the heading to the Discard buttons, for what every page + // Purple, from the heading to the list's border, for what every page // shares. const Scope = group.isSiteWide ? GlobalScope : Fragment; @@ -103,9 +96,6 @@ function ChangeGroup( { group, changes, onDiscard } ) { className="cnl-review-changes__group-title" > { group.title } - - { changes.length } -
- ) ) } @@ -152,7 +129,7 @@ function ChangeGroup( { group, changes, onDiscard } ) {
- +
+ + + { ( { onClose: closeMenu } ) => ( + { + closeMenu(); + setIsConfirmingDiscard( true ); + } } + > + { __( 'Discard changes…' ) } + + ) } + +
diff --git a/src/top-bar/publish-status.jsx b/src/top-bar/publish-status.jsx new file mode 100644 index 00000000..a8505562 --- /dev/null +++ b/src/top-bar/publish-status.jsx @@ -0,0 +1,204 @@ +/** + * The end of the top bar: Publish site while the site has changes waiting, + * a quiet "Up to date" once it has none. + * + * Only one save-like button shows at a time. While a page or post is open in + * the canvas, its own Save and Publish are that button, so Publish site + * steps back to a quiet note of how many site changes are waiting, which + * does nothing. See `README.md`. + * + * Cmd+S follows the same rule: it saves the open page or post, and + * otherwise opens Publish site. + */ + +/** + * WordPress dependencies + */ +import { Button } from '@wordpress/components'; +import { dispatch, select, useDispatch } from '@wordpress/data'; +import { useEffect, useRef, useState } from '@wordpress/element'; +import { __, _n, sprintf } from '@wordpress/i18n'; +import { check as checkIcon, Icon } from '@wordpress/icons'; +import { isKeyboardEvent } from '@wordpress/keycodes'; +import { store as noticesStore } from '@wordpress/notices'; + +/** + * Internal dependencies + */ +import { + STORE_NAME as CANVAS_STORE, + useOpenDocument, +} from '../site-canvas/mode'; +import { PublishSiteDialog } from './publish-site-dialog'; +import { useChanges } from './use-changes'; + +const EDITOR_STORE = 'core/editor'; + +/* + * Said once a session, the first time an edit made while a page is open + * turns out to be the site's, like its header. + */ +let hasExplainedCrossing = false; + +/** + * Tell the user, once, that an edit made on a page changes the site, so it + * waits for Publish site rather than the page's own Save. + * + * @param {number} count Site changes waiting. + * @param {?Object} openDocument The page or post open in the canvas. + */ +function useExplainCrossing( count, openDocument ) { + const { createInfoNotice } = useDispatch( noticesStore ); + const previous = useRef( { count, openDocument } ); + + useEffect( () => { + const isSameDocument = + previous.current.openDocument && + previous.current.openDocument === openDocument; + + if ( + ! hasExplainedCrossing && + isSameDocument && + count > previous.current.count + ) { + hasExplainedCrossing = true; + createInfoNotice( + __( + 'That change shows on every page, so it waits for Publish site.' + ), + { type: 'snackbar' } + ); + } + + previous.current = { count, openDocument }; + }, [ count, openDocument, createInfoNotice ] ); +} + +/** + * Cmd+S: save the open page or post, or open Publish site. Caught before + * boot's own shortcut, which would open its review of every change. + * + * @param {Function} openDialog Opens Publish site. + * @param {number} count Site changes waiting. + */ +function useSaveShortcut( openDialog, count ) { + const latest = useRef(); + latest.current = { openDialog, count }; + + useEffect( () => { + const onKeyDown = ( event ) => { + if ( ! isKeyboardEvent.primary( event, 's' ) ) { + return; + } + + event.preventDefault(); + event.stopImmediatePropagation(); + + // The editor's store is only there once a canvas has loaded it. + const editor = select( EDITOR_STORE ); + + if ( editor && select( CANVAS_STORE ).getOpenDocument() ) { + if ( editor.isEditedPostDirty() ) { + dispatch( EDITOR_STORE ).savePost(); + } + + return; + } + + if ( latest.current.count ) { + latest.current.openDialog(); + } + }; + + window.addEventListener( 'keydown', onKeyDown, true ); + + return () => window.removeEventListener( 'keydown', onKeyDown, true ); + }, [] ); +} + +/** + * Warn before leaving the editor while anything is unsaved: nothing is kept + * between visits yet. + * + * @param {boolean} hasChanges Whether anything is unsaved. + */ +function useWarnBeforeLeaving( hasChanges ) { + useEffect( () => { + if ( ! hasChanges ) { + return undefined; + } + + const onBeforeUnload = ( event ) => { + event.preventDefault(); + // Older browsers need a value to ask. + event.returnValue = ''; + }; + + window.addEventListener( 'beforeunload', onBeforeUnload ); + + return () => + window.removeEventListener( 'beforeunload', onBeforeUnload ); + }, [ hasChanges ] ); +} + +export function PublishStatus() { + const [ isDialogOpen, setIsDialogOpen ] = useState( false ); + const { changes, siteChanges, isSaving } = useChanges(); + const openDocument = useOpenDocument(); + const count = siteChanges.length; + const openDialog = () => setIsDialogOpen( true ); + + useExplainCrossing( count, openDocument ); + useSaveShortcut( openDialog, count ); + useWarnBeforeLeaving( changes.length > 0 ); + + let control; + + if ( count && openDocument ) { + // Only a note while a page or post is being edited: its own buttons + // are the ones to use, and Publish site comes back on leaving it. + control = ( + + { sprintf( + /* translators: %d: Number of site changes waiting to be published. */ + _n( + '%d site change waiting', + '%d site changes waiting', + count + ), + count + ) } + + ); + } else if ( count || ( isSaving && ! openDocument ) ) { + control = ( + + ); + } else { + control = ( + + + { __( 'Up to date' ) } + + ); + } + + return ( +
+ { control } + { isDialogOpen && ( + setIsDialogOpen( false ) } /> + ) } +
+ ); +} diff --git a/src/top-bar/save-controls.jsx b/src/top-bar/save-controls.jsx deleted file mode 100644 index be3f38ae..00000000 --- a/src/top-bar/save-controls.jsx +++ /dev/null @@ -1,119 +0,0 @@ -/** - * Save controls: how many changes are waiting, and a way to review them. - * - * Changes made across the editor are held back until the user saves them, - * so Save opens the review, where they are saved or discarded. Save is always - * there, and disabled while there's nothing to save, so it's somewhere to - * look before there is. It sits in the canvas toolbar, and replaces boot's - * save button at the foot of the sidebar, which `style.scss` hides wherever - * there is a canvas toolbar. - * - * How many changes are waiting, or that they were all saved, is in Save's - * tooltip and read out as it changes, rather than written beside it: the - * toolbar is full, and its controls shouldn't move as changes come and go. - */ - -/** - * WordPress dependencies - */ -import { Button } from '@wordpress/components'; -import { useCallback, useEffect, useRef, useState } from '@wordpress/element'; -import { __, _n, sprintf } from '@wordpress/i18n'; -import { displayShortcut, rawShortcut } from '@wordpress/keycodes'; - -/** - * Internal dependencies - */ -import { ReviewChanges } from './review-changes'; -import { useChanges } from './use-changes'; - -export function SaveControls() { - const [ isReviewOpen, setIsReviewOpen ] = useState( false ); - const [ hasSaved, setHasSaved ] = useState( false ); - const { changes, isSaving } = useChanges(); - const changeCount = changes.length; - const hasChanges = changeCount > 0; - const closeReview = useCallback( () => setIsReviewOpen( false ), [] ); - const [ isPulsing, setIsPulsing ] = useState( false ); - const previousCount = useRef( changeCount ); - - /* - * Save pulses each time a new change joins the list, so it catches the - * eye while the user is working elsewhere. More edits to a change already - * listed don't add to the count, so typing doesn't keep it pulsing. The - * class is taken off for a frame first so a pulse already running starts - * again. - */ - useEffect( () => { - const isNewChange = changeCount > previousCount.current; - previousCount.current = changeCount; - - if ( ! isNewChange ) { - return; - } - - setIsPulsing( false ); - const frame = window.requestAnimationFrame( () => - setIsPulsing( true ) - ); - - return () => window.cancelAnimationFrame( frame ); - }, [ changeCount ] ); - - /* - * "All changes saved" is shown once a save has cleared every change, and - * stays until something new is changed. A save that fails leaves the - * changes in place, so the bar goes back to counting them. - */ - useEffect( () => { - if ( isSaving ) { - setHasSaved( true ); - } else if ( hasChanges ) { - setHasSaved( false ); - } - }, [ isSaving, hasChanges ] ); - - let status = ''; - - if ( hasChanges ) { - status = sprintf( - /* translators: %d: Number of changes waiting to be saved. */ - _n( '%d unsaved change', '%d unsaved changes', changeCount ), - changeCount - ); - } else if ( hasSaved ) { - status = __( 'All changes saved' ); - } - - return ( -
-
- { status } -
- - { isReviewOpen && } -
- ); -} diff --git a/src/top-bar/site-button.jsx b/src/top-bar/site-button.jsx new file mode 100644 index 00000000..b4816236 --- /dev/null +++ b/src/top-bar/site-button.jsx @@ -0,0 +1,73 @@ +/** + * The site's logo and name, at the start of the top bar. It opens Name & + * logo, where both are changed, asking first about unsaved edits to a page + * or post open in the canvas, as Exit does. + * + * It shows the site as it will be once published, so a new name shows here + * as it is typed. + */ + +/** + * WordPress dependencies + */ +import { store as coreDataStore } from '@wordpress/core-data'; +import { useSelect } from '@wordpress/data'; +import { decodeEntities } from '@wordpress/html-entities'; +import { __ } from '@wordpress/i18n'; + +/** + * Internal dependencies + */ +import { openRoute } from '../open-route'; +import { settings } from '../settings'; +import { requestExit } from '../site-canvas/mode'; + +const IDENTITY_PATH = '/design/identity'; + +function getMediaUrl( media ) { + return ( + media?.media_details?.sizes?.thumbnail?.source_url || + media?.source_url || + '' + ); +} + +export function SiteButton() { + const { name, imageUrl } = useSelect( ( select ) => { + const store = select( coreDataStore ); + const site = store.getEditedEntityRecord( 'root', 'site' ); + const imageId = Number( site?.site_logo ) || Number( site?.site_icon ); + const media = imageId + ? store.getEntityRecord( 'root', 'media', imageId ) + : null; + + return { + name: decodeEntities( site?.title || settings.siteName || '' ), + imageUrl: getMediaUrl( media ), + }; + }, [] ); + + return ( + + ); +} diff --git a/src/top-bar/style.scss b/src/top-bar/style.scss index ce90e8c2..1280263a 100644 --- a/src/top-bar/style.scss +++ b/src/top-bar/style.scss @@ -1,27 +1,179 @@ /* - * Save controls in the canvas toolbar, put there by `mountSaveControls()`, - * with which agent is connected before them when one is. + * Top bar, added to boot's layout by `mountTopBar()`, above the sidebar and + * the surfaces, on every screen, the expanded canvas and small screens + * included. Boot's layout is matched by its CSS-module suffixes. Its own + * Save, at the foot of the sidebar, gives way to Publish site here. */ @use "../colors" as *; +// Room for the 40px buttons in it and little more, so the bar stays slim. +$top-bar-height: 48px; +$layout: '#create-not-learn-editor-app [class*="__layout"]:has(> .cnl-top-bar-host)'; + +#{$layout} { + box-sizing: border-box; + padding-block-start: $top-bar-height; + + [class*="__sidebar"] [class*="__scrollable"] > [class*="__footer"] { + display: none; + } +} + /* - * Boot's own save button, at the foot of the sidebar, is only needed on a - * screen without a canvas toolbar to hold the save controls, like Media. + * Small screens: boot fixes the stage, the canvas and the sidebar's drawer + * just under the admin bar, so they move down by the bar too. */ -body.cnl-has-canvas-save #create-not-learn-editor-app [class*="__layout"]:not([class*="__has-full-canvas"]) [class*="__sidebar"] [class*="__scrollable"] > [class*="__footer"] { - display: none; +@media (max-width: 782px) { + + #{$layout} { + + [class*="__stage"], + [class*="__inspector"], + [class*="__canvas"]:not([class*="__has-mobile-drawer"]) { + top: calc(var(--wp-admin--admin-bar--height, 0px) + #{$top-bar-height}); + height: calc(100vh - var(--wp-admin--admin-bar--height, 0px) - #{$top-bar-height}); + } + + [class*="__mobile-sidebar-drawer"] { + top: calc(var(--wp-admin--admin-bar--height, 0px) + #{$top-bar-height}); + } + } } -.cnl-canvas-save-host { - display: contents; +/* + * Core's full-screen editor, opened with "Open in advanced editor", has a + * header of its own, with its own Save, so the bar steps aside. + */ +#{$layout}[class*="__has-full-canvas"] { + padding-block-start: 0; + + > .cnl-top-bar-host { + display: none; + } } -.cnl-canvas-save { +.cnl-top-bar-host { + position: absolute; + inset-block-start: 0; + inset-inline: 0; + z-index: 2; + height: $top-bar-height; + padding-inline: var(--wpds-dimension-gap-md); +} + +/* + * Three columns with equal outer tracks, so Go to page stays centred on the + * screen whatever the ends show. On a small screen Go to page goes, and the + * ends share the bar. + */ +.cnl-top-bar { + display: grid; + grid-template-columns: minmax(0, 1fr) minmax(160px, 360px) minmax(max-content, 1fr); + align-items: center; + gap: var(--wpds-dimension-gap-lg); + height: 100%; + color: var(--wpds-color-foreground-content-neutral); + font-size: var(--wpds-typography-font-size-md); +} + +@media (max-width: 781px) { + + .cnl-top-bar { + grid-template-columns: minmax(0, 1fr) max-content; + } + + .cnl-top-bar__center { + display: none; + } +} + +.cnl-top-bar__start { + min-width: 0; +} + +.cnl-top-bar__center { + min-width: 0; +} + +.cnl-top-bar__end { display: flex; align-items: center; + justify-content: flex-end; gap: var(--wpds-dimension-gap-md); - min-width: 0; - font-size: var(--wpds-typography-font-size-md); +} + +// The site's logo and name, quiet on the dark frame until hovered. +.cnl-top-bar__site { + display: inline-flex; + align-items: center; + gap: var(--wpds-dimension-gap-sm); + max-width: 100%; + height: var(--wpds-dimension-size-md); + padding-inline: var(--wpds-dimension-padding-xs) var(--wpds-dimension-padding-sm); + border: 0; + border-radius: var(--wpds-border-radius-sm); + background: none; + color: var(--wpds-color-foreground-interactive-neutral); + font: inherit; + font-weight: var(--wpds-typography-font-weight-emphasis); + cursor: pointer; + + &:hover { + background: var(--wpds-color-background-interactive-neutral-weak-active); + color: var(--wpds-color-foreground-interactive-neutral-active); + } + + &:focus-visible { + outline: var(--wpds-border-width-focus) solid var(--wp-admin-theme-color); + outline-offset: 0; + } +} + +.cnl-top-bar__site-logo { + display: inline-flex; + flex: none; + align-items: center; + justify-content: center; + width: 28px; + height: 28px; + border-radius: var(--wpds-border-radius-sm); + background: var(--wpds-color-background-surface-neutral-strong); + color: var(--wpds-color-foreground-content-neutral); + font-size: 13px; + font-weight: 600; + object-fit: cover; +} + +.cnl-top-bar__site-name { + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +// Go to page fills the middle track. The page finder styles it; see +// `src/page-finder/style.scss`. +.cnl-go-to-page { + width: 100%; +} + +.cnl-publish-status { + display: flex; + align-items: center; +} + +// "N site changes waiting": a quiet note while a page or post is open, not +// something to press. +.cnl-publish-status__waiting, +.cnl-publish-status__up-to-date { + display: inline-flex; + align-items: center; + gap: var(--wpds-dimension-gap-xs); + color: var(--wpds-color-foreground-content-neutral-weak); + white-space: nowrap; + + svg { + fill: currentcolor; + } } .cnl-agent-status { @@ -109,80 +261,8 @@ $agent-green: var(--wpds-color-stroke-surface-success-strong); border-top: var(--wpds-border-width-xs) solid var(--wpds-color-stroke-surface-neutral-weak); } -.cnl-save-controls { - position: relative; - display: flex; - align-items: center; -} - -// Read out as it changes; Save's tooltip shows it. -.cnl-save-controls__status { - position: absolute; - width: 1px; - height: 1px; - overflow: hidden; - clip-path: inset(50%); - white-space: nowrap; -} - /* - * Save with nothing to save. Core keeps a disabled primary button blue and - * only dims its words, which reads as ready, so it takes a faint fill - * instead. - */ -.components-button.is-primary.cnl-save-controls__button[aria-disabled="true"] { - - &, - &:hover, - &:active { - background: rgba(0, 0, 0, 0.05); - color: var(--wpds-color-foreground-content-neutral-weak); - box-shadow: none; - } -} - -// Pulses when a new change is added; see `save-controls.jsx`. -.cnl-save-controls__button.is-pulsing { - animation: cnl-save-controls-pulse 0.7s ease-out 2; -} - -// Lightened, so the ring reads as a glow round the button. -$save-pulse-color: color-mix(in srgb, var(--wp-admin-theme-color), #fff 40%); - -@keyframes cnl-save-controls-pulse { - - from { - box-shadow: 0 0 0 0 $save-pulse-color; - transform: scale(1.08); - } - - to { - box-shadow: 0 0 0 10px transparent; - transform: scale(1); - } -} - -// No movement, so the ring shows once and fades instead. -@media (prefers-reduced-motion: reduce) { - - .cnl-save-controls__button.is-pulsing { - animation: cnl-save-controls-glow 1.4s ease-out; - } -} - -@keyframes cnl-save-controls-glow { - - from { - box-shadow: 0 0 0 3px $save-pulse-color; - } - - to { - box-shadow: 0 0 0 3px transparent; - } -} - -/* - * Review changes dialog. + * Publish site dialog, `publish-site-dialog.jsx`. */ .cnl-review-changes__groups { display: flex; @@ -282,12 +362,6 @@ $save-pulse-color: color-mix(in srgb, var(--wp-admin-theme-color), #fff 40%); text-overflow: ellipsis; } -.cnl-review-changes__group-count { - margin-inline-start: var(--wpds-dimension-gap-sm); - color: var(--wpds-color-foreground-content-neutral-weak); - font-weight: var(--wpds-typography-font-weight-default); -} - .cnl-review-changes__show-more { align-self: flex-start; } @@ -317,3 +391,19 @@ $save-pulse-color: color-mix(in srgb, var(--wp-admin-theme-color), #fff 40%); gap: var(--wpds-dimension-gap-sm); margin-inline-start: auto; } + +// Publish, with the rest of the ways to publish behind the arrow beside it. +.cnl-review-changes__split { + display: flex; + gap: 1px; + + > .components-button:first-child { + border-start-end-radius: 0; + border-end-end-radius: 0; + } + + .components-dropdown-menu__toggle { + border-start-start-radius: 0; + border-end-start-radius: 0; + } +} diff --git a/src/top-bar/use-changes.js b/src/top-bar/use-changes.js index eb21e81e..bf9c7708 100644 --- a/src/top-bar/use-changes.js +++ b/src/top-bar/use-changes.js @@ -9,6 +9,7 @@ /** * WordPress dependencies */ +import { parse } from '@wordpress/block-serialization-default-parser'; import { store as coreStore } from '@wordpress/core-data'; import { useDispatch, useRegistry, useSelect } from '@wordpress/data'; import { useEntitiesSavedStatesIsDirty } from '@wordpress/editor'; @@ -18,6 +19,7 @@ import { __, sprintf } from '@wordpress/i18n'; * Internal dependencies */ import { unlock } from '../lock-unlock'; +import { useOpenDocument, useSelfSaving } from '../site-canvas/mode'; /* * Named as the editor names them, so a change reads as the place it was made. @@ -152,6 +154,23 @@ function getRecordId( { kind, name, key } ) { return [ kind, name, key ?? '' ].join( '|' ); } +/** + * Whether a change is to the page or post open in the canvas, which saves + * and publishes there, rather than with the site's changes. + * + * @param {Object} change A change or edited record. + * @param {?Object} openDocument `{ postType, postId }`, or null. + * @return {boolean} Whether it is the open document's. + */ +export function isDocumentChange( change, openDocument ) { + return ( + Boolean( openDocument ) && + change.kind === 'postType' && + change.name === openDocument.postType && + String( change.key ) === String( openDocument.postId ) + ); +} + /** * The changes waiting to be saved, in the user's terms. * @@ -225,6 +244,91 @@ export function getDirtyRecords( select ) { ]; } +const NAVIGATION_TYPE = 'wp_navigation'; + +/** + * The menus a record's edited blocks show, by ID. + * + * @param {Object} record An edited template, template part or post. + * @return {number[]} The menus its Navigation blocks point to. + */ +function getNavigationRefs( record ) { + const refs = []; + const walk = ( blocks ) => + ( blocks || [] ).forEach( ( block ) => { + if ( block.name === 'core/navigation' && block.attributes?.ref ) { + refs.push( Number( block.attributes.ref ) ); + } + walk( block.innerBlocks ); + } ); + + // What core saves: the content, unless it is to be made from the blocks. + if ( typeof record?.content === 'function' ) { + walk( record.blocks ); + } else if ( typeof record?.content === 'string' ) { + // Parsed blocks name their attributes `attrs`. + walk( + parse( record.content ).map( function toBlock( block ) { + return { + name: block.blockName, + attributes: block.attrs, + innerBlocks: block.innerBlocks.map( toBlock ), + }; + } ) + ); + } + + return refs; +} + +/** + * Menus still drafts that the site's changes put on the site, a new menu + * put in the header say, made ready to publish with them. Core only shows + * published menus, so a draft is never live until then. + * + * @param {Object} registry Data registry. + * @param {Object[]} records The records being published. + * @return {Object[]} The menus, as records for core's save. + */ +function publishDraftMenus( registry, records ) { + const store = registry.select( coreStore ); + const ids = new Set( + records + .filter( ( { kind } ) => kind === 'postType' ) + .flatMap( ( { name, key } ) => + getNavigationRefs( + store.getEditedEntityRecord( 'postType', name, key ) + ) + ) + ); + const isPublishing = ( id ) => + records.some( + ( { name, key } ) => + name === NAVIGATION_TYPE && Number( key ) === id + ); + + return [ ...ids ] + .filter( + ( id ) => + ! isPublishing( id ) && + store.getEntityRecord( 'postType', NAVIGATION_TYPE, id ) + ?.status === 'draft' + ) + .map( ( id ) => { + registry + .dispatch( coreStore ) + .editEntityRecord( + 'postType', + NAVIGATION_TYPE, + id, + { status: 'publish' }, + { undoIgnore: true } + ); + + return { kind: 'postType', name: NAVIGATION_TYPE, key: id }; + } ); +} + // Long enough for the editor to load a discarded layout's parts and menus. const DISCARD_SETTLE_MS = 1500; @@ -289,12 +393,27 @@ function putBackWhileSettling( registry, kept ) { } /** + * Every unsaved change, and the same changes split by where they are + * published: the page or post open in the canvas, if one is, publishes + * there, and everything else, the site's changes, with Publish site. + * * @return {Object} `changes`, each with an `id`, a `label`, a `detail` and - * `isSiteWide`, whether they are saving, and `save`, - * `discard` and `discardAll` actions. + * `isSiteWide`, `siteChanges`, `documentChange` (or null), + * whether they are saving, and `save`, `publishSite`, + * `discard`, `discardAll` and `discardSite` actions. */ export function useChanges() { - const { dirtyEntityRecords } = useEntitiesSavedStatesIsDirty(); + const { dirtyEntityRecords: allDirtyRecords } = + useEntitiesSavedStatesIsDirty(); + const openDocument = useOpenDocument(); + // A record that saves itself, like a menu shown nowhere, is never a + // change waiting for anything. + const selfSaving = useSelfSaving(); + const dirtyEntityRecords = selfSaving.length + ? allDirtyRecords.filter( + ( record ) => ! selfSaving.includes( getRecordId( record ) ) + ) + : allDirtyRecords; const { editedSite, savedSite, @@ -374,9 +493,45 @@ export function useChanges() { const discardAll = () => discardRecords( changes ); + const siteChanges = changes.filter( + ( change ) => ! isDocumentChange( change, openDocument ) + ); + const documentChange = + changes.find( ( change ) => + isDocumentChange( change, openDocument ) + ) || null; + + const discardSite = () => discardRecords( siteChanges ); + // Core's own save, as its review uses: it saves site settings together // and publishes menus, and reports success or failure in a snackbar. const save = () => saveDirtyEntities( { dirtyEntityRecords } ); - return { changes, isSaving, save, discard, discardAll }; + // The same save, leaving out the open page or post, which publishes from + // the canvas, and taking in the draft menus it puts on the site. + const publishSite = () => { + const records = dirtyEntityRecords.filter( + ( record ) => ! isDocumentChange( record, openDocument ) + ); + + return saveDirtyEntities( { + dirtyEntityRecords: [ + ...records, + ...publishDraftMenus( registry, records ), + ], + successNoticeContent: __( 'Site published.' ), + } ); + }; + + return { + changes, + documentChange, + isSaving, + save, + siteChanges, + publishSite, + discard, + discardAll, + discardSite, + }; } diff --git a/src/webmcp/declarations.js b/src/webmcp/declarations.js index 069de7b8..d07f4cb3 100644 --- a/src/webmcp/declarations.js +++ b/src/webmcp/declarations.js @@ -69,7 +69,7 @@ export const TOOLS = [ { name: 'cnl-set-canvas', description: - "Change how the editor's canvas shows the page open in it, as the canvas's own toolbar does: its mode, its device, or both. Browse shows the saved site as visitors see it, with links that can be followed; it only shows what is saved, so with unsaved changes the editor asks the person to save or discard them first, and the canvas moves to Browse only once they have. Edit is where the page is changed. Compose zooms out, to see the page's sections as a whole, and always shows it on a desktop. The tools that change the page move the canvas to Edit themselves. Returns the mode and device the canvas is on.", + "Change how the editor's canvas shows the page open in it, as the canvas's own toolbar does: its mode, its device, or both. Browse shows the saved site as visitors see it, with links that can be followed; it only shows what is published, so with unsaved edits to the open page the editor asks the person to save or discard them first, and while site changes are waiting the canvas stays in the editor to show them. Edit is where the page is changed. Compose zooms out, to see the page's sections as a whole, and always shows it on a desktop. The tools that change the page move the canvas to Edit themselves. Returns the mode and device the canvas is on.", inputSchema: { type: 'object', properties: { @@ -144,7 +144,7 @@ export const TOOLS = [ { name: 'cnl-get-changes', description: - "List the changes waiting to be saved, as the editor's Review changes lists them. Each says whether it shows on every page of the site or only on one. Changes nothing.", + "List the changes waiting to be saved, as the editor's Publish site lists them. Each says whether it shows on every page of the site or only on one. Changes nothing.", inputSchema: { type: 'object', properties: {} }, annotations: READ_ONLY, }, diff --git a/src/webmcp/tools.js b/src/webmcp/tools.js index e05d118b..cfcd5b04 100644 --- a/src/webmcp/tools.js +++ b/src/webmcp/tools.js @@ -164,9 +164,7 @@ const DEVICES = [ 'desktop', 'tablet', 'mobile' ]; const MODE_WAIT_MS = 20000; function isAskingAboutChanges() { - return Boolean( - document.querySelector( '.cnl-site-canvas__unsaved-dialog' ) - ); + return Boolean( document.querySelector( '.cnl-site-canvas__exit-dialog' ) ); } function describeCanvas() { @@ -355,7 +353,7 @@ function listChanges() { detail: change.detail, showsOn: change.isSiteWide ? 'every page' : 'one page', } ) ), - note: 'Nothing is live until the person saves, with Save or Review changes in the editor.', + note: 'Nothing is live until the person publishes, with Publish site or the page’s own Publish in the editor.', }; } From 12641c2eaf3ba6555ce9959c11b66fdae74c465d Mon Sep 17 00:00:00 2001 From: Dave Smith Date: Thu, 19 Nov 2026 21:56:52 +0000 Subject: [PATCH 2/5] Publish site: discard single changes again, and space Edit and Exit - Each change in Publish site has its own Discard again, as on trunk's review, with focus moving to the next row's Discard. - Edit and Exit sit a little apart from the View and Zoom buttons before them in the canvas toolbar. Co-Authored-By: Claude Opus 5.5 --- src/site-canvas/_style.scss | 4 +- src/top-bar/publish-site-dialog.jsx | 105 +++++++++++++++++++++------- 2 files changed, 83 insertions(+), 26 deletions(-) diff --git a/src/site-canvas/_style.scss b/src/site-canvas/_style.scss index 807e21d3..6ccaa085 100644 --- a/src/site-canvas/_style.scss +++ b/src/site-canvas/_style.scss @@ -54,10 +54,12 @@ } } -// Edit while viewing, and Exit beside Save while editing. +// Edit while viewing, and Exit beside Save while editing. Set apart from +// the flush View and Zoom cluster before them, as the action they are. .cnl-site-canvas__edit.components-button, .cnl-site-canvas__exit.components-button { flex-shrink: 0; + margin-inline-start: var(--wpds-dimension-gap-md); } .cnl-site-canvas__exit.components-button { diff --git a/src/top-bar/publish-site-dialog.jsx b/src/top-bar/publish-site-dialog.jsx index 86ae0cc7..482fb12e 100644 --- a/src/top-bar/publish-site-dialog.jsx +++ b/src/top-bar/publish-site-dialog.jsx @@ -7,9 +7,10 @@ * globe, as the editor marks anything shared (see `src/global-scope`). Pages * changed from a screen beside the canvas, their title or place say, follow. * - * The dialog is a list and Publish. Discarding them all sits behind the menu - * beside Publish, and is asked about first, in the same dialog, because it - * can't be undone. + * The dialog is a list and Publish. Each change can be discarded on its own, + * leaving the rest to publish, as in core's review. Discarding them all sits + * behind the menu beside Publish, and is asked about first, in the same + * dialog, because it can't be undone. */ /** @@ -21,6 +22,7 @@ import { Fragment, useEffect, useId, + useLayoutEffect, useRef, useState, } from '@wordpress/element'; @@ -62,7 +64,7 @@ const GROUPS = [ // session's changes don't turn the dialog into a long scroll. const VISIBLE_CHANGES = 5; -function ChangeGroup( { group, changes } ) { +function ChangeGroup( { group, changes, onDiscard } ) { const headingId = useId(); const listRef = useRef(); const [ isExpanded, setIsExpanded ] = useState( false ); @@ -72,7 +74,16 @@ function ChangeGroup( { group, changes } ) { const visibleChanges = hiddenCount ? changes.slice( 0, VISIBLE_CHANGES ) : changes; - // Purple, from the heading to the list's border, for what every page + // The button goes once pressed, so focus moves to the first row it showed. + const showAll = () => { + setIsExpanded( true ); + window.requestAnimationFrame( () => { + listRef.current + ?.querySelectorAll( '.cnl-review-changes__discard' ) + [ VISIBLE_CHANGES ]?.focus(); + } ); + }; + // Purple, from the heading to the Discard buttons, for what every page // shares. const Scope = group.isSiteWide ? GlobalScope : Fragment; @@ -122,6 +133,19 @@ function ChangeGroup( { group, changes } ) { { change.detail } + ) ) } @@ -129,7 +153,7 @@ function ChangeGroup( { group, changes } ) {