diff --git a/create-not-learn-editor.php b/create-not-learn-editor.php index 8b8fbd5..4778503 100644 --- a/create-not-learn-editor.php +++ b/create-not-learn-editor.php @@ -68,6 +68,7 @@ function cnl_editor_bootstrap() { require_once CNL_EDITOR_PATH . 'includes/plugin-compat.php'; require_once CNL_EDITOR_PATH . 'includes/post-kinds.php'; require_once CNL_EDITOR_PATH . 'includes/page-list.php'; + require_once CNL_EDITOR_PATH . 'includes/site-history.php'; cnl_editor_register_content_type_hooks(); cnl_editor_register_sections_hooks(); @@ -86,4 +87,5 @@ function cnl_editor_bootstrap() { cnl_editor_register_page_list_hooks(); cnl_editor_register_post_kind_hooks(); cnl_editor_register_setup_default_hooks(); + cnl_editor_register_site_history_hooks(); } diff --git a/includes/site-history.php b/includes/site-history.php new file mode 100644 index 0000000..9e62d44 --- /dev/null +++ b/includes/site-history.php @@ -0,0 +1,498 @@ + 'ids', 'posts_per_page' => 1 ) ) ) { + _wp_put_post_revision( get_post( $post_id ) ); + } +} + +/** + * Note the revision a save just made, so the entry for this Publish site + * points at it rather than at whatever revision is newest when the entry is + * logged, which may be someone else's by then. + * + * @param int $revision_id The revision. + * @param int $post_id The record it is a revision of. + */ +function cnl_editor_note_site_history_revision( $revision_id, $post_id = 0 ) { + // An autosave isn't a save anyone published. + if ( wp_is_post_autosave( $revision_id ) ) { + return; + } + + $post_id = $post_id ? (int) $post_id : (int) wp_get_post_parent_id( $revision_id ); + $user_id = get_current_user_id(); + + if ( ! $user_id || ! $post_id || ! in_array( get_post_type( $post_id ), CNL_EDITOR_SITE_HISTORY_POST_TYPES, true ) ) { + return; + } + + $pending = cnl_editor_get_site_history_pending( $user_id ); + $pending[ $post_id ] = (int) $revision_id; + + set_transient( CNL_EDITOR_SITE_HISTORY_PENDING_TRANSIENT . $user_id, $pending, HOUR_IN_SECONDS ); +} + +/** + * The revisions a person's saves have made since their last Publish site + * was logged. + * + * @param int $user_id The person. + * @return int[] Revision IDs, by the ID of the record each is of. + */ +function cnl_editor_get_site_history_pending( $user_id ) { + $pending = get_transient( CNL_EDITOR_SITE_HISTORY_PENDING_TRANSIENT . $user_id ); + + return is_array( $pending ) ? $pending : array(); +} + +/** + * The site settings the history may hold, by the names REST gives them. + * + * @return string[] Setting names. + */ +function cnl_editor_get_site_history_settings() { + $names = array(); + + foreach ( get_registered_settings() as $option => $args ) { + if ( empty( $args['show_in_rest'] ) ) { + continue; + } + + $names[] = is_array( $args['show_in_rest'] ) && ! empty( $args['show_in_rest']['name'] ) ? $args['show_in_rest']['name'] : $option; + } + + return $names; +} + +/** + * Tidy a map of site settings to their values: only settings REST knows, + * and only plain values. + * + * @param mixed $values From the editor. + * @return array The values kept. + */ +function cnl_editor_prepare_site_history_values( $values ) { + $kept = array(); + $allowed = cnl_editor_get_site_history_settings(); + + foreach ( is_array( $values ) ? $values : array() as $setting => $value ) { + if ( ! in_array( $setting, $allowed, true ) || ! ( is_scalar( $value ) || null === $value ) ) { + continue; + } + + $kept[ $setting ] = is_string( $value ) ? sanitize_text_field( $value ) : $value; + } + + return $kept; +} + +/** + * The revision saved just before another, the record as it was before the + * save that made `$revision_id`. + * + * @param int $post_id The record. + * @param int $revision_id One of its revisions. + * @return int The revision before it, or 0 when it was the first. + */ +function cnl_editor_get_previous_revision( $post_id, $revision_id ) { + $revisions = array_map( + 'intval', + wp_get_post_revisions( + $post_id, + array( + 'fields' => 'ids', + 'posts_per_page' => -1, + ) + ) + ); + $index = array_search( (int) $revision_id, $revisions, true ); + + return false !== $index && isset( $revisions[ $index + 1 ] ) ? $revisions[ $index + 1 ] : 0; +} + +/** + * Register the site history routes. + */ +function cnl_editor_register_site_history_routes() { + $can_edit = static function () { + return current_user_can( 'edit_theme_options' ); + }; + + register_rest_route( + CNL_EDITOR_REST_NAMESPACE, + '/site-history', + array( + array( + 'methods' => WP_REST_Server::READABLE, + 'callback' => static function () { + return rest_ensure_response( cnl_editor_get_site_history() ); + }, + 'permission_callback' => $can_edit, + ), + array( + 'methods' => WP_REST_Server::CREATABLE, + 'callback' => 'cnl_editor_rest_record_site_history', + 'permission_callback' => $can_edit, + 'args' => array( + 'changes' => array( + 'type' => 'array', + 'required' => true, + ), + ), + ), + ) + ); +} + +/** + * Record a Publish site, from the editor once its save has finished. + * + * @param WP_REST_Request $request Request. + * @return WP_REST_Response|WP_Error The entry, or an error when nothing in it + * belongs in the history. + */ +function cnl_editor_rest_record_site_history( $request ) { + $entry = cnl_editor_record_site_history( (array) $request['changes'] ); + + if ( ! $entry ) { + return new WP_Error( + 'cnl_editor_no_history_changes', + __( 'None of those changes belong in the site history.', 'create-not-learn-editor' ), + array( 'status' => 400 ) + ); + } + + $response = rest_ensure_response( cnl_editor_prepare_site_history_entry( $entry ) ); + $response->set_status( 201 ); + + return $response; +} + +/** + * The post behind a change, if it is one the site history keeps. + * + * @param string $kind Entity kind, as the editor names it. + * @param string $name Entity name. + * @param string|int $key Entity key: a template's ID is `theme//slug`. + * @return int Post ID, or 0 when it isn't there or isn't kept. + */ +function cnl_editor_get_site_history_post_id( $kind, $name, $key ) { + if ( 'root' === $kind && 'globalStyles' === $name ) { + $post_type = 'wp_global_styles'; + } elseif ( 'postType' === $kind && in_array( $name, array( 'wp_template', 'wp_template_part', 'wp_navigation' ), true ) ) { + $post_type = $name; + } else { + return 0; + } + + if ( in_array( $post_type, array( 'wp_template', 'wp_template_part' ), true ) && ! is_numeric( $key ) ) { + $template = get_block_template( (string) $key, $post_type ); + + return $template && ! empty( $template->wp_id ) ? (int) $template->wp_id : 0; + } + + $post_id = (int) $key; + + return $post_id && get_post_type( $post_id ) === $post_type ? $post_id : 0; +} + +/** + * Tidy the changes the editor reports into what the log keeps. Anything the + * history doesn't cover is dropped, so a page can't end up in it. + * + * @param array $changes Each `kind`, `name`, `key`, `label`, and for site + * settings `values`, a map of setting to value, and + * `previous`, what they were before. + * @param int $user_id Who published. Defaults to the current user. + * @return array[] The changes to keep. + */ +function cnl_editor_prepare_site_history_changes( array $changes, $user_id = 0 ) { + $kept = array(); + $user_id = (int) ( $user_id ? $user_id : get_current_user_id() ); + $pending = cnl_editor_get_site_history_pending( $user_id ); + + foreach ( $changes as $change ) { + if ( ! is_array( $change ) ) { + continue; + } + + $kind = isset( $change['kind'] ) ? sanitize_text_field( $change['kind'] ) : ''; + $name = isset( $change['name'] ) ? sanitize_text_field( $change['name'] ) : ''; + $label = isset( $change['label'] ) ? sanitize_text_field( $change['label'] ) : ''; + $item = array_merge( + array( + 'kind' => $kind, + 'name' => $name, + 'label' => $label, + ), + cnl_editor_prepare_site_history_description( $change ) + ); + + if ( 'root' === $kind && 'site' === $name ) { + $values = cnl_editor_prepare_site_history_values( isset( $change['values'] ) ? $change['values'] : array() ); + + if ( ! $values ) { + continue; + } + + $item['values'] = $values; + + // What they were before, which Restore puts back when it goes to + // a version older than this one. + $previous = array_intersect_key( + cnl_editor_prepare_site_history_values( isset( $change['previous'] ) ? $change['previous'] : array() ), + $values + ); + + if ( $previous ) { + $item['previous'] = $previous; + } + + $kept[] = $item; + continue; + } + + $key = isset( $change['key'] ) && is_scalar( $change['key'] ) ? (string) $change['key'] : ''; + $post_id = cnl_editor_get_site_history_post_id( $kind, $name, $key ); + + if ( ! $post_id ) { + continue; + } + + $item['key'] = $key; + + if ( isset( $pending[ $post_id ] ) ) { + // The revision this person's save made, and the one before it, + // the record as it was before that save. + $item['revision'] = (int) $pending[ $post_id ]; + $previous = cnl_editor_get_previous_revision( $post_id, $item['revision'] ); + + if ( $previous ) { + $item['previous_revision'] = $previous; + } + + unset( $pending[ $post_id ] ); + } else { + // The save made no revision, as when nothing differed, so the + // record is as the newest revision has it, before and after. + $revisions = wp_get_post_revisions( + $post_id, + array( + 'posts_per_page' => 1, + 'fields' => 'ids', + ) + ); + + if ( $revisions ) { + $item['revision'] = (int) reset( $revisions ); + $item['previous_revision'] = $item['revision']; + } + } + + $kept[] = $item; + } + + if ( $user_id ) { + // What is left over was saved some other way; it is no longer this + // Publish site's to claim. + delete_transient( CNL_EDITOR_SITE_HISTORY_PENDING_TRANSIENT . $user_id ); + } + + return $kept; +} + +/** + * Tidy what the editor says a change changed: a summary, and each detail + * from what to what. The editor works these out before saving, while it + * still has the old values; see `src/top-bar/site-history-diff.js`. + * + * @param array $change A change, with `summary`, `details` and `more`. + * @return array The kept parts, empty when there are none. + */ +function cnl_editor_prepare_site_history_description( array $change ) { + if ( empty( $change['details'] ) || ! is_array( $change['details'] ) ) { + return array(); + } + + $details = array(); + + foreach ( array_slice( $change['details'], 0, CNL_EDITOR_SITE_HISTORY_DETAIL_LIMIT ) as $detail ) { + if ( ! is_array( $detail ) || empty( $detail['label'] ) ) { + continue; + } + + $kept = array( + 'label' => sanitize_text_field( $detail['label'] ), + 'kind' => isset( $detail['kind'] ) && in_array( $detail['kind'], array( 'added', 'removed' ), true ) ? $detail['kind'] : 'changed', + ); + + foreach ( array( 'from', 'to' ) as $side ) { + $value = isset( $detail[ $side ] ) && is_array( $detail[ $side ] ) ? cnl_editor_prepare_site_history_value( $detail[ $side ] ) : null; + + if ( $value ) { + $kept[ $side ] = $value; + } + } + + $details[] = $kept; + } + + if ( ! $details ) { + return array(); + } + + $description = array( + 'summary' => isset( $change['summary'] ) ? sanitize_text_field( $change['summary'] ) : '', + 'details' => $details, + ); + $more = ( isset( $change['more'] ) ? absint( $change['more'] ) : 0 ) + max( 0, count( $change['details'] ) - CNL_EDITOR_SITE_HISTORY_DETAIL_LIMIT ); + + if ( $more ) { + $description['more'] = $more; + } + + return $description; +} + +/** + * One side of a detail, as text with a colour or image to show beside it. + * Only a colour CSS can read plainly, and only a web address, are kept. + * + * @param array $value `text`, and maybe `color` or `image`. + * @return array|null The value, or null without text. + */ +function cnl_editor_prepare_site_history_value( array $value ) { + if ( ! isset( $value['text'] ) || ! is_scalar( $value['text'] ) ) { + return null; + } + + $kept = array( 'text' => sanitize_text_field( (string) $value['text'] ) ); + + if ( isset( $value['color'] ) && is_string( $value['color'] ) && preg_match( '/^(#[0-9a-f]{3,8}|(rgb|hsl)a?\([0-9a-z.,%\s\/-]*\)|[a-z]+)$/i', trim( $value['color'] ) ) ) { + $kept['color'] = trim( $value['color'] ); + } + + if ( isset( $value['image'] ) && is_string( $value['image'] ) ) { + $url = esc_url_raw( $value['image'], array( 'http', 'https' ) ); + + if ( $url ) { + $kept['image'] = $url; + } + } + + return $kept; +} + +/** + * Add an entry to the log. + * + * @param array $changes What was published, as `cnl_editor_prepare_site_history_changes()` + * takes it. + * @param int $user_id Who published. Defaults to the current user. + * @return array|null The entry, or null when nothing in it belongs here. + */ +function cnl_editor_record_site_history( array $changes, $user_id = 0 ) { + $user_id = (int) ( $user_id ? $user_id : get_current_user_id() ); + $changes = cnl_editor_prepare_site_history_changes( $changes, $user_id ); + + if ( ! $changes ) { + return null; + } + + $entry = array( + 'id' => wp_generate_uuid4(), + 'time' => time(), + 'user_id' => $user_id, + 'changes' => $changes, + ); + $history = get_option( CNL_EDITOR_SITE_HISTORY_OPTION, array() ); + $history = is_array( $history ) ? $history : array(); + + array_unshift( $history, $entry ); + + // Not autoloaded: only the history panel reads it. + update_option( CNL_EDITOR_SITE_HISTORY_OPTION, array_slice( $history, 0, CNL_EDITOR_SITE_HISTORY_LIMIT ), false ); + + return $entry; +} + +/** + * An entry as the editor reads it, with the person's name. + * + * @param array $entry A logged entry. + * @return array The entry. + */ +function cnl_editor_prepare_site_history_entry( array $entry ) { + $user = get_userdata( $entry['user_id'] ); + + return array( + 'id' => $entry['id'], + 'time' => $entry['time'], + 'user' => array( + 'id' => $entry['user_id'], + 'name' => $user ? $user->display_name : '', + ), + 'changes' => $entry['changes'], + ); +} + +/** + * The log, newest first. + * + * @return array[] Entries, each with `id`, `time`, `user` and `changes`. + */ +function cnl_editor_get_site_history() { + $history = get_option( CNL_EDITOR_SITE_HISTORY_OPTION, array() ); + + return array_map( 'cnl_editor_prepare_site_history_entry', is_array( $history ) ? $history : array() ); +} diff --git a/src/top-bar/README.md b/src/top-bar/README.md index 71e78de..f023da8 100644 --- a/src/top-bar/README.md +++ b/src/top-bar/README.md @@ -51,6 +51,28 @@ For menus, the editor can't know every place one is shown: a Navigation block ca - **Putting a draft in a page or post** is a change to that page or post, which publishes from the canvas. Publishing, scheduling or saving it while live publishes the drafts its content shows with it (`publishDocumentMenus()` in `src/site-canvas/document-actions.jsx`), for the same reason. - **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. +## Site history + +A clock in the top bar, before Publish site, opens a panel down the right (`site-history-panel.jsx`). It lists what **Publish site** published, newest first, grouped by day, at three levels of detail: + +1. **The entry:** "Published N changes", the time, who published it and the names of the changes. +2. **Its changes:** clicking the entry opens it in place. Each change has one line on what it changed: from → to when it is one thing, the names of the first few settings, or for blocks "2 edits, 1 block added". +3. **Every detail:** a change with more than one detail opens a screen of its own, listing each one from → to, with colours as swatches. Back, or Escape, returns to the list where it was. + +The details are worked out just before the save, while the editor still holds both the saved record and the edited one (`site-history-diff.js`). They are kept in the log with the entry, so an entry still reads the same after the theme or palette has changed. Style values name the preset they point at, "Contrast" rather than `var:preset|color|contrast`, and blocks are matched before and after as a text diff matches lines. + +- **Latest** marks the newest entry instead of Restore: it is what the site shows, so restoring it would change nothing. +- **Restore** on any other entry asks first, in a dialog: the editor's preview goes back to that version, and the site itself doesn't change until it is published with Publish site. It also says when restoring would replace changes not yet published. +- The clock is disabled until something has been published. +- The panel slides in over the canvas and closes on Escape, Close, or a click anywhere else, since it covers the canvas's toolbar. + +Only what Publish site publishes is in it: templates, template parts, site styles, menus and site settings. Pages and posts keep core's own revisions. + +- **Built on core revisions.** Core already keeps a revision of each template, part, styles record and menu it saves. What it doesn't say is which were saved together, and site settings have no revisions. So `includes/site-history.php` keeps a small log, the option `create-not-learn-editor_site_history`, newest 50, not autoloaded. Each entry has the time, the user and its changes. A change holds the revision the save made or, for site settings, the values saved, and its summary and details, the first 60 of them, with only plain colours and web addresses kept. It is read and added to through `/site-history` (`edit_theme_options`); anything that isn't one of those kinds is dropped. +- **Logged after the save.** `publishSite()` in `use-changes.js` posts what was saved once core's save finishes, leaving out whatever is still unsaved after it. A failure to log doesn't fail the publish. +- **Restore goes back to how the site was just after that publish.** A revision holds a record as a save left it, so an entry's own revisions are already live unless a later publish changed the same thing. Restore therefore undoes every later publish: each record they changed goes back to how it was before the oldest of them (`previous_revision`, logged with each change), and each site setting to its `previous` value. The PHP side notes the revision each person's save made, so a save by someone else before the entry is logged isn't claimed, and keeps a record's original as a revision before its first update, so there is something to go back to. +- **Restore is an edit, not a save.** `site-history.js` fetches each revision and loads it into the record as an unsaved edit, so it waits for Publish site like any other change. A revision core has since pruned is skipped, and the snackbar says so; so is a menu a later publish created, which has no earlier version. A template or part a later publish first changed goes back to the theme's file, as core's reset does but as an edit. When everything already matches, the snackbar says there was nothing to put back. There is no preview of an old version. + ## 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. +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 and scheduling are the next steps. diff --git a/src/top-bar/index.jsx b/src/top-bar/index.jsx index 1659c6e..bc0e1c5 100644 --- a/src/top-bar/index.jsx +++ b/src/top-bar/index.jsx @@ -5,7 +5,7 @@ * 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 + * `src/webmcp/connection.js`), the site history, 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. */ @@ -22,6 +22,7 @@ import { __ } from '@wordpress/i18n'; import { PageFinder } from '../page-finder'; import { AgentStatus } from './agent-status'; import { PublishStatus } from './publish-status'; +import { SiteHistory } from './site-history-panel'; import { SiteButton } from './site-button'; function TopBar() { @@ -38,6 +39,7 @@ function TopBar() {
+
diff --git a/src/top-bar/site-history-diff.js b/src/top-bar/site-history-diff.js new file mode 100644 index 0000000..64cf9ff --- /dev/null +++ b/src/top-bar/site-history-diff.js @@ -0,0 +1,750 @@ +/** + * What each change of a Publish site changed, from what to what, for the + * site history to show at two levels: a one-line summary, and every detail. + * + * Worked out just before the save, while the editor still holds both the + * saved record and the edited one, and kept in the log with the entry. So + * an entry reads the same later, whatever the theme or palette has become, + * and needs no revisions to describe itself. Restore still uses revisions. + * + * A detail is `{ label, kind, from, to }`: `kind` is "changed", "added" or + * "removed", and `from` and `to` are `{ text, color?, image? }`, ready to + * show. + */ + +/** + * WordPress dependencies + */ +import { parse } from '@wordpress/block-serialization-default-parser'; +import { getBlockType } from '@wordpress/blocks'; +import { store as coreStore } from '@wordpress/core-data'; +import { __, _n, sprintf } from '@wordpress/i18n'; + +// Kept short, so a big publish doesn't bloat the log. +const MAX_DETAILS = 60; +const MAX_TEXT = 140; + +const SETTING_LABELS = { + title: __( 'Site name' ), + description: __( 'Tagline' ), + site_logo: __( 'Logo' ), + site_icon: __( 'Browser icon' ), + show_on_front: __( 'Homepage' ), + page_on_front: __( 'Homepage' ), + page_for_posts: __( 'Blog page' ), + posts_per_page: __( 'Posts shown at once' ), +}; + +/* + * Style paths in the editor's words. Pairs first, as `color.text` reads + * "Text color" where `text` alone, under an element, reads "Text". + */ +const PATH_LABELS = { + 'color.background': __( 'Background color' ), + 'color.text': __( 'Text color' ), + 'color.gradient': __( 'Gradient' ), + 'color.palette': __( 'Colors' ), + 'color.gradients': __( 'Gradients' ), + 'color.duotone': __( 'Duotone' ), + 'typography.fontFamilies': __( 'Fonts' ), + 'typography.fontSizes': __( 'Font sizes' ), + 'spacing.spacingSizes': __( 'Spacing sizes' ), +}; + +const SEGMENT_LABELS = { + fontFamily: __( 'Font' ), + fontSize: __( 'Font size' ), + fontWeight: __( 'Font weight' ), + fontStyle: __( 'Font style' ), + lineHeight: __( 'Line height' ), + letterSpacing: __( 'Letter spacing' ), + textTransform: __( 'Letter case' ), + textDecoration: __( 'Decoration' ), + padding: __( 'Padding' ), + margin: __( 'Margin' ), + blockGap: __( 'Block spacing' ), + border: __( 'Border' ), + radius: __( 'Radius' ), + width: __( 'Width' ), + style: __( 'Style' ), + shadow: __( 'Shadow' ), + top: __( 'top' ), + right: __( 'right' ), + bottom: __( 'bottom' ), + left: __( 'left' ), + link: __( 'Links' ), + button: __( 'Buttons' ), + heading: __( 'Headings' ), + h1: __( 'Heading 1' ), + h2: __( 'Heading 2' ), + h3: __( 'Heading 3' ), + h4: __( 'Heading 4' ), + h5: __( 'Heading 5' ), + h6: __( 'Heading 6' ), + caption: __( 'Captions' ), + cite: __( 'Citations' ), + ':hover': __( 'on hover' ), + ':focus': __( 'on focus' ), + background: __( 'Background' ), + text: __( 'Text' ), + backgroundColor: __( 'Background color' ), + textColor: __( 'Text color' ), + content: __( 'Text' ), + label: __( 'Label' ), + url: __( 'Link' ), + ref: __( 'Menu' ), +}; + +// Grouping keys that say nothing on their own. +const SILENT_SEGMENTS = [ + 'styles', + 'settings', + 'elements', + 'blocks', + 'color', + 'typography', + 'spacing', + 'theme', + 'custom', + 'default', +]; + +const PRESET = + /^var(?::preset\|([a-z-]+)\||\(--wp--preset--([a-z-]+)--)([^)|]+)\)?$/; +const COLOR = /^(#[0-9a-f]{3,8}|(rgb|hsl)a?\([^)]*\))$/i; + +function clip( text ) { + const value = String( text ?? '' ) + .replace( /\s+/g, ' ' ) + .trim(); + + return value.length > MAX_TEXT + ? `${ value.slice( 0, MAX_TEXT - 1 ) }…` + : value; +} + +function stripTags( html ) { + return clip( String( html || '' ).replace( /<[^>]*>/g, ' ' ) ); +} + +function isPlainObject( value ) { + return ( + value !== null && typeof value === 'object' && ! Array.isArray( value ) + ); +} + +function blockTitle( name ) { + return ( + getBlockType( name )?.title || + String( name || '' ) + .replace( /^core\//, '' ) + .replace( /-/g, ' ' ) + .replace( /^./, ( first ) => first.toUpperCase() ) + ); +} + +/** + * A style path, `elements.link.color.text` say, as words: "Links › Text + * color". + * + * @param {string[]} path Keys, from the top. + * @return {string} The label. + */ +export function describePath( path ) { + const words = []; + + for ( let i = 0; i < path.length; i++ ) { + const segment = path[ i ]; + const pair = PATH_LABELS[ `${ segment }.${ path[ i + 1 ] }` ]; + + if ( pair ) { + words.push( pair ); + i++; + } else if ( segment.startsWith( '[' ) ) { + // An item of a preset list, by its name, added when flattened. + words.push( segment.slice( 1, -1 ) ); + } else if ( path[ i - 1 ] === 'blocks' ) { + words.push( blockTitle( segment ) ); + } else if ( SEGMENT_LABELS[ segment ] ) { + words.push( SEGMENT_LABELS[ segment ] ); + } else if ( ! SILENT_SEGMENTS.includes( segment ) ) { + words.push( segment ); + } + } + + return words.join( ' › ' ) || __( 'Style' ); +} + +/** + * Every leaf of a styles or settings object, by its path. A list of + * presets, a palette say, is opened up by slug, so one colour changing is + * one change, not the whole list. + * + * @param {*} value Object to flatten. + * @param {string[]} path Keys so far. + * @param {Object} out Leaves, by joined path. + * @return {Object} `{ [path]: { path, value } }`. + */ +function flatten( value, path = [], out = {} ) { + if ( isPlainObject( value ) ) { + Object.keys( value ).forEach( ( key ) => + flatten( value[ key ], [ ...path, key ], out ) + ); + } else if ( + Array.isArray( value ) && + value.length && + value.every( ( item ) => isPlainObject( item ) && item.slug ) + ) { + value.forEach( ( item ) => { + const itemPath = [ ...path, `[${ item.name || item.slug }]` ]; + out[ `${ path.join( '.' ) }.${ item.slug }` ] = { + path: itemPath, + value: item, + }; + } ); + } else { + out[ path.join( '.' ) ] = { path, value }; + } + + return out; +} + +/** + * The site's presets by kind and slug, to name what a style points at. + * + * @param {Object[]} settingsList Settings to look in, most specific first. + * @return {Function} `( kind, slug ) => preset`, or undefined. + */ +function makePresetLookup( settingsList ) { + const lists = { + color: [ 'color', 'palette' ], + gradient: [ 'color', 'gradients' ], + 'font-family': [ 'typography', 'fontFamilies' ], + 'font-size': [ 'typography', 'fontSizes' ], + spacing: [ 'spacing', 'spacingSizes' ], + }; + + return ( kind, slug ) => { + const [ group, key ] = lists[ kind ] || []; + + for ( const settings of settingsList ) { + const origins = settings?.[ group ]?.[ key ]; + const all = Array.isArray( origins ) + ? origins + : Object.values( origins || {} ).flat(); + const found = all.find( ( preset ) => preset?.slug === slug ); + + if ( found ) { + return found; + } + } + + return undefined; + }; +} + +/** + * A style value, ready to show. + * + * @param {*} value The value. + * @param {Function} findPreset From `makePresetLookup`. + * @return {Object} `{ text, color? }`. + */ +function describeValue( value, findPreset ) { + if ( value === undefined || value === null || value === '' ) { + return { text: __( 'Default' ) }; + } + + if ( isPlainObject( value ) ) { + // A preset itself, from a list opened up by `flatten`. + if ( value.color ) { + return { text: clip( value.color ), color: value.color }; + } + + if ( value.fontFamily || value.size ) { + return { + text: clip( value.name || value.fontFamily || value.size ), + }; + } + + return { text: clip( JSON.stringify( value ) ) }; + } + + if ( Array.isArray( value ) ) { + return { text: clip( value.join( ', ' ) ) }; + } + + const text = String( value ); + const preset = text.match( PRESET ); + + if ( preset ) { + const kind = preset[ 1 ] || preset[ 2 ]; + const found = findPreset( kind, preset[ 3 ] ); + const name = found?.name || preset[ 3 ]; + + return found?.color + ? { text: clip( name ), color: found.color } + : { text: clip( name ) }; + } + + if ( COLOR.test( text.trim() ) ) { + return { text: clip( text ), color: text.trim() }; + } + + return { text: clip( text ) }; +} + +function isSame( a, b ) { + return JSON.stringify( a ) === JSON.stringify( b ); +} + +function diffObjects( before, after, findPreset, prefix = [] ) { + const from = flatten( before || {}, prefix ); + const to = flatten( after || {}, prefix ); + + return [ ...new Set( [ ...Object.keys( from ), ...Object.keys( to ) ] ) ] + .filter( ( key ) => ! isSame( from[ key ]?.value, to[ key ]?.value ) ) + .map( ( key ) => { + const path = ( to[ key ] || from[ key ] ).path; + let kind = 'changed'; + + if ( ! from[ key ] ) { + kind = path[ path.length - 1 ].startsWith( '[' ) + ? 'added' + : 'changed'; + } else if ( ! to[ key ] ) { + kind = path[ path.length - 1 ].startsWith( '[' ) + ? 'removed' + : 'changed'; + } + + return { + label: describePath( path ), + kind, + from: describeValue( from[ key ]?.value, findPreset ), + to: describeValue( to[ key ]?.value, findPreset ), + }; + } ); +} + +/* + * Blocks. + */ + +function flattenBlocks( blocks, out = [] ) { + ( blocks || [] ).forEach( ( block ) => { + if ( block.blockName ) { + out.push( { + name: block.blockName, + attrs: block.attrs || {}, + text: stripTags( block.innerHTML ), + } ); + } + + flattenBlocks( block.innerBlocks, out ); + } ); + + return out; +} + +function describeBlock( block ) { + return clip( + block.text || + block.attrs.label || + block.attrs.content || + block.attrs.slug || + '' + ); +} + +/** + * Pair the blocks before and after that are the same block, in order, by + * name: the longest common run, as a text diff pairs lines. + * + * @param {Object[]} before Blocks before, flattened. + * @param {Object[]} after Blocks after, flattened. + * @return {Array[]} `[ beforeBlock|null, afterBlock|null ]` pairs. + */ +function pairBlocks( before, after ) { + const rows = before.length; + const cols = after.length; + const lengths = Array.from( { length: rows + 1 }, () => + new Array( cols + 1 ).fill( 0 ) + ); + + for ( let i = rows - 1; i >= 0; i-- ) { + for ( let j = cols - 1; j >= 0; j-- ) { + lengths[ i ][ j ] = + before[ i ].name === after[ j ].name + ? lengths[ i + 1 ][ j + 1 ] + 1 + : Math.max( lengths[ i + 1 ][ j ], lengths[ i ][ j + 1 ] ); + } + } + + const pairs = []; + let i = 0; + let j = 0; + + while ( i < rows || j < cols ) { + if ( i < rows && j < cols && before[ i ].name === after[ j ].name ) { + pairs.push( [ before[ i++ ], after[ j++ ] ] ); + } else if ( + j < cols && + ( i >= rows || lengths[ i ][ j + 1 ] >= lengths[ i + 1 ][ j ] ) + ) { + pairs.push( [ null, after[ j++ ] ] ); + } else { + pairs.push( [ before[ i++ ], null ] ); + } + } + + return pairs; +} + +function diffBlocks( beforeContent, afterContent, findPreset ) { + const before = flattenBlocks( parse( beforeContent || '' ) ); + const after = flattenBlocks( parse( afterContent || '' ) ); + const details = []; + + pairBlocks( before, after ).forEach( ( [ from, to ] ) => { + const title = blockTitle( ( from || to ).name ); + + if ( ! from ) { + details.push( { + label: sprintf( + /* translators: %s: A block's name. */ + __( '%s added' ), + title + ), + kind: 'added', + to: { text: describeBlock( to ) || title }, + } ); + return; + } + + if ( ! to ) { + details.push( { + label: sprintf( + /* translators: %s: A block's name. */ + __( '%s removed' ), + title + ), + kind: 'removed', + from: { text: describeBlock( from ) || title }, + } ); + return; + } + + if ( from.text !== to.text ) { + details.push( { + label: sprintf( + /* translators: %s: A block's name. */ + __( '%s › Text' ), + title + ), + kind: 'changed', + from: { text: from.text || __( 'Empty' ) }, + to: { text: to.text || __( 'Empty' ) }, + } ); + } + + const { style: fromStyle, ...fromAttrs } = from.attrs; + const { style: toStyle, ...toAttrs } = to.attrs; + + diffObjects( fromStyle, toStyle, findPreset ).forEach( ( detail ) => + details.push( { + ...detail, + label: `${ title } › ${ detail.label }`, + } ) + ); + + [ + ...new Set( [ + ...Object.keys( fromAttrs ), + ...Object.keys( toAttrs ), + ] ), + ] + .filter( + ( key ) => + key !== 'metadata' && + ! isSame( fromAttrs[ key ], toAttrs[ key ] ) + ) + .forEach( ( key ) => { + // A colour attribute holds a palette slug. + const asPreset = ( value ) => + /color$/i.test( key ) && typeof value === 'string' + ? `var:preset|color|${ value }` + : value; + + details.push( { + label: `${ title } › ${ SEGMENT_LABELS[ key ] || key }`, + kind: 'changed', + from: describeValue( + asPreset( fromAttrs[ key ] ), + findPreset + ), + to: describeValue( asPreset( toAttrs[ key ] ), findPreset ), + } ); + } ); + } ); + + return details; +} + +function summariseBlocks( details ) { + const count = ( kind ) => + details.filter( ( detail ) => detail.kind === kind ).length; + const parts = []; + const added = count( 'added' ); + const removed = count( 'removed' ); + const changed = count( 'changed' ); + + if ( changed ) { + parts.push( + sprintf( + /* translators: %d: Number of changes to blocks. */ + _n( '%d edit', '%d edits', changed ), + changed + ) + ); + } + + if ( added ) { + parts.push( + sprintf( + /* translators: %d: Number of blocks added. */ + _n( '%d block added', '%d blocks added', added ), + added + ) + ); + } + + if ( removed ) { + parts.push( + sprintf( + /* translators: %d: Number of blocks removed. */ + _n( '%d block removed', '%d blocks removed', removed ), + removed + ) + ); + } + + return parts.join( ', ' ); +} + +/** + * One line for a change, from its details. + * + * @param {Object[]} details The change's details. + * @param {boolean} isContent Whether it is a record of blocks. + * @return {string} The summary. + */ +export function summarise( details, isContent ) { + if ( ! details.length ) { + return ''; + } + + if ( details.length === 1 ) { + const [ only ] = details; + + if ( only.kind === 'added' || only.kind === 'removed' ) { + return only.label; + } + + return sprintf( + /* translators: 1: What changed, 2: its old value, 3: its new value. */ + __( '%1$s: %2$s → %3$s' ), + only.label, + only.from?.text, + only.to?.text + ); + } + + if ( isContent ) { + return summariseBlocks( details ); + } + + // What changed, by the last word of each label: "Background, Text and 5 + // more". + const names = [ + ...new Set( + details.map( ( { label } ) => label.split( ' › ' ).pop() ) + ), + ]; + + if ( names.length <= 3 ) { + return names.join( ', ' ); + } + + return sprintf( + /* translators: 1: Names of the first changes, 2: how many more. */ + _n( '%1$s and %2$d more', '%1$s and %2$d more', names.length - 2 ), + names.slice( 0, 2 ).join( ', ' ), + names.length - 2 + ); +} + +/* + * Site settings. + */ + +function describeSetting( property, site, { getPageTitle, getMediaUrl } ) { + const value = site?.[ property ]; + + if ( property === 'site_logo' || property === 'site_icon' ) { + const url = Number( value ) ? getMediaUrl( Number( value ) ) : ''; + + return Number( value ) + ? { text: __( 'Image' ), ...( url ? { image: url } : {} ) } + : { text: __( 'None' ) }; + } + + if ( property === 'show_on_front' || property === 'page_on_front' ) { + if ( site?.show_on_front !== 'page' ) { + return { text: __( 'Latest posts' ) }; + } + + return { + text: clip( getPageTitle( site?.page_on_front ) || __( 'A page' ) ), + }; + } + + if ( property === 'page_for_posts' ) { + return { text: clip( getPageTitle( value ) || __( 'None' ) ) }; + } + + return { text: value === '' ? __( 'Empty' ) : clip( value ) }; +} + +function getContent( record ) { + const content = record?.content; + + if ( typeof content === 'function' ) { + return content( record ); + } + + return typeof content === 'string' ? content : content?.raw || ''; +} + +function getTitle( record ) { + const title = record?.title; + + return clip( typeof title === 'string' ? title : title?.raw || '' ); +} + +/** + * What a change about to be published changes, from what to what. Called + * before the save, while the saved record is still the old one. + * + * @param {Object} change A described change: `kind`, `name`, `key`, + * `property` for a site setting. + * @param {Object} registry Data registry. + * @return {{summary: string, details: Object[]}} The summary and details. + */ +export function describeChangeDetails( change, registry ) { + const store = registry.select( coreStore ); + const { kind, name, key, property } = change; + let details = []; + let isContent = false; + + if ( kind === 'root' && name === 'site' ) { + const saved = store.getRawEntityRecord( 'root', 'site' ); + const edited = store.getEditedEntityRecord( 'root', 'site' ); + const context = { + getPageTitle: ( id ) => + ( Number( id ) && + getTitle( + store.getEditedEntityRecord( + 'postType', + 'page', + Number( id ) + ) + ) ) || + '', + getMediaUrl: ( id ) => { + const media = store.getEntityRecord( + 'postType', + 'attachment', + id + ); + + return ( + media?.media_details?.sizes?.thumbnail?.source_url || + media?.source_url || + '' + ); + }, + }; + + details = [ + { + label: SETTING_LABELS[ property ] || property, + kind: 'changed', + from: describeSetting( property, saved, context ), + to: describeSetting( property, edited, context ), + }, + ]; + } else if ( kind === 'root' && name === 'globalStyles' ) { + const saved = store.getRawEntityRecord( kind, name, key ) || {}; + const edited = store.getEditedEntityRecord( kind, name, key ) || {}; + const findPreset = makePresetLookup( [ + edited.settings, + saved.settings, + store.__experimentalGetCurrentThemeBaseGlobalStyles?.()?.settings, + ] ); + + details = [ + ...diffObjects( saved.styles, edited.styles, findPreset, [ + 'styles', + ] ), + ...diffObjects( saved.settings, edited.settings, findPreset, [ + 'settings', + ] ), + ]; + } else if ( kind === 'postType' ) { + const saved = store.getRawEntityRecord( kind, name, key ) || {}; + const edited = store.getEditedEntityRecord( kind, name, key ) || {}; + const findPreset = makePresetLookup( [ + store.__experimentalGetCurrentThemeBaseGlobalStyles?.()?.settings, + ] ); + const fromTitle = getTitle( saved ); + const toTitle = getTitle( edited ); + + isContent = true; + + if ( fromTitle !== toTitle ) { + details.push( { + label: __( 'Name' ), + kind: 'changed', + from: { text: fromTitle || __( 'Untitled' ) }, + to: { text: toTitle || __( 'Untitled' ) }, + } ); + } + + details.push( + ...diffBlocks( + getContent( saved ), + getContent( edited ), + findPreset + ) + ); + + // Publishing a draft menu. + if ( saved.status && edited.status && saved.status !== edited.status ) { + details.push( { + label: __( 'Status' ), + kind: 'changed', + from: { text: saved.status }, + to: { text: edited.status }, + } ); + } + } + + return { + summary: clip( summarise( details, isContent ) ), + details: details.slice( 0, MAX_DETAILS ), + ...( details.length > MAX_DETAILS + ? { more: details.length - MAX_DETAILS } + : {} ), + }; +} diff --git a/src/top-bar/site-history-panel.jsx b/src/top-bar/site-history-panel.jsx new file mode 100644 index 0000000..8f18679 --- /dev/null +++ b/src/top-bar/site-history-panel.jsx @@ -0,0 +1,999 @@ +/** + * Site history: a clock in the top bar that opens a panel down the right of + * the screen, listing what each Publish site saved. + * + * Only what Publish site publishes is here, as `site-history.js` explains. + * Entries are grouped by day. Each says how many changes it published, what + * they were, when and who by, and has Restore, which loads that version back + * in as unsaved edits for Publish site to publish. The newest is what the + * site shows, so it has nothing to restore. Every Restore asks first, in a + * dialog saying the editor changes and the site doesn't until Publish site. + * There is no preview of an old version. + */ + +/** + * WordPress dependencies + */ +import { Button, Modal } from '@wordpress/components'; +import { useRegistry } from '@wordpress/data'; +import { + useCallback, + useEffect, + useId, + useRef, + useState, +} from '@wordpress/element'; +import { __, _n, sprintf } from '@wordpress/i18n'; +import { + backup as historyIcon, + chevronDownSmall, + chevronLeft, + chevronRightSmall, + close as closeIcon, + Icon, +} from '@wordpress/icons'; +import { store as noticesStore } from '@wordpress/notices'; +import { Badge, Stack, Text } from '@wordpress/ui'; + +/** + * Internal dependencies + */ +import { getTimeAgo } from './agent-status'; +import { + getSiteHistory, + countReplaced, + planRestore, + onSiteHistoryChanged, + restoreEntry, + RESTORE_FAILED_MESSAGE, +} from './site-history'; +import { summarise } from './site-history-diff'; +import { useChanges } from './use-changes'; + +const HOUR_MS = 60 * 60 * 1000; + +function startOfDay( time ) { + const date = new Date( time ); + date.setHours( 0, 0, 0, 0 ); + + return date.getTime(); +} + +function describeDay( dayStart, now ) { + const today = startOfDay( now ); + + if ( dayStart === today ) { + return __( 'Today' ); + } + + // Not 24 hours back, which a clock change would throw out. + if ( dayStart === startOfDay( today - 1 ) ) { + return __( 'Yesterday' ); + } + + return new Date( dayStart ).toLocaleDateString( undefined, { + weekday: 'long', + day: 'numeric', + month: 'long', + year: + new Date( dayStart ).getFullYear() === new Date( now ).getFullYear() + ? undefined + : 'numeric', + } ); +} + +/** + * The entries by the day they were published, newest first, as the log + * keeps them. + * + * @param {Object[]} entries The log's entries. + * @param {number} now Now, in milliseconds. + * @return {Object[]} `{ key, label, entries }` for each day. + */ +function groupByDay( entries, now ) { + const days = []; + + entries.forEach( ( entry ) => { + const dayStart = startOfDay( entry.time * 1000 ); + const last = days[ days.length - 1 ]; + + if ( last?.key === dayStart ) { + last.entries.push( entry ); + } else { + days.push( { + key: dayStart, + label: describeDay( dayStart, now ), + entries: [ entry ], + } ); + } + } ); + + return days; +} + +// The day heads the group, so an entry only needs its time. +function formatTime( seconds, now ) { + const time = seconds * 1000; + + return now - time < HOUR_MS + ? getTimeAgo( time, now ) + : new Date( time ).toLocaleTimeString( undefined, { + hour: 'numeric', + minute: '2-digit', + } ); +} + +function describeEntry( entry ) { + return sprintf( + /* translators: %d: Number of changes a publish saved together. */ + _n( + 'Published %d change', + 'Published %d changes', + entry.changes.length + ), + entry.changes.length + ); +} + +/** + * One side of a change, with its colour or image beside it. + * + * @param {Object} props + * @param {Object} props.value `{ text, color?, image? }`. + * @return {Element} The value. + */ +function Value( { value } ) { + if ( ! value ) { + return null; + } + + return ( + + { value.color && ( + + ); +} + +/** + * A detail's from and to, or what was added or taken away. + * + * @param {Object} props + * @param {Object} props.detail `{ kind, from, to }`. + * @return {Element} The values. + */ +function FromTo( { detail } ) { + if ( detail.kind === 'added' ) { + return ( + + + + + + ); + } + + if ( detail.kind === 'removed' ) { + return ( + + − + + + ); + } + + return ( + + + + + + → + + + + ); +} + +function getChangeKey( entry, index ) { + return `${ entry.id }:${ index }`; +} + +/** + * The second level: an entry's changes, each with a line saying what it + * changed. One with details opens the third level. + * + * @param {Object} props + * @param {Object} props.entry The entry. + * @param {Function} props.onDrill Open a change's details, by its index. + * @param {boolean} props.isOpen Whether the entry is open. + * @return {Element} The changes. + */ +function EntryChanges( { entry, onDrill, isOpen } ) { + return ( +
+ +
+ ); +} + +/** + * Asked before every Restore: it changes what the editor shows, and that + * the site itself stays as it is until Publish site. + * + * @param {Object} props + * @param {Object} props.entry The entry to restore. + * @param {number} props.now Now, in milliseconds. + * @param {number} props.replacedCount How many of its changes land on + * something with unpublished changes. + * @param {boolean} props.isBusy Whether it is restoring. + * @param {Function} props.onConfirm Restore. + * @param {Function} props.onCancel Keep things as they are. + * @return {Element} The dialog. + */ +function RestoreDialog( { + entry, + now, + replacedCount, + isBusy, + onConfirm, + onCancel, +} ) { + // "8 mins ago" alone, or the day and time: "Yesterday, 3:12 PM". + const when = + now - entry.time * 1000 < HOUR_MS + ? formatTime( entry.time, now ) + : sprintf( + /* translators: 1: A day, like "Today", 2: a time. */ + __( '%1$s, %2$s' ), + describeDay( startOfDay( entry.time * 1000 ), now ), + formatTime( entry.time, now ) + ); + const labels = entry.changes + .map( ( { label } ) => label ) + .filter( Boolean ) + .join( ', ' ); + + return ( + + +
+ + { labels || describeEntry( entry ) } + + + { [ + sprintf( + /* translators: %s: When it was published. */ + __( 'Published %s' ), + when + ), + entry.user?.name, + ] + .filter( Boolean ) + .join( ' · ' ) } + +
+ + { __( + 'The editor’s preview goes back to how this version looked.' + ) } + + + { __( + 'Your site doesn’t change yet. Visitors see this version only once you publish it with Publish site.' + ) } + + { replacedCount > 0 && ( + + { __( + 'This replaces changes you haven’t published yet.' + ) } + + ) } +
+ + +
+
+
+ ); +} + +function HistoryEntry( { + entry, + index, + now, + isLatest, + isBusy, + isDisabled, + replacedCount, + onRestore, + onDrill, + isOpen, + onToggle, +} ) { + const [ isConfirming, setIsConfirming ] = useState( false ); + // Every Restore reads the same, so each says which publish it is for. + const headId = useId(); + const changesId = useId(); + const labels = entry.changes + .map( ( { label } ) => label ) + .filter( Boolean ) + .join( ', ' ); + + let action = null; + + if ( isLatest ) { + // What visitors see now, unless something has changed since, so + // putting it back would change nothing. + action = { __( 'Latest' ) }; + } else { + action = ( + + ); + } + + return ( +
  • +
  • + ); +} + +/** + * The third level: every detail of one change, from what to what. + * + * @param {Object} props + * @param {Object} props.entry The entry. + * @param {Object} props.change The change. + * @param {number} props.now Now, in milliseconds. + * @param {Function} props.onBack Back to the list. + * @return {Element} The details. + */ +function ChangeDetails( { entry, change, now, onBack } ) { + const screenRef = useRef(); + + // On the screen, not Back, so no focus ring flashes up; Tab reaches Back. + useEffect( () => { + screenRef.current?.focus( { preventScroll: true } ); + }, [] ); + + return ( +
    +
    +
    + + } + > + { change.label } + + + { [ + describeEntry( entry ), + formatTime( entry.time, now ), + entry.user?.name, + ] + .filter( Boolean ) + .join( ' · ' ) } + +
    +
    +
    +
      + { change.details.map( ( detail, index ) => ( +
    • + + { detail.label } + + +
    • + ) ) } +
    + { change.more > 0 && ( + + { sprintf( + /* translators: %d: Number of details not kept. */ + _n( + 'And %d more change', + 'And %d more changes', + change.more + ), + change.more + ) } + + ) } +
    +
    + ); +} + +function HistoryPanel( { entries, isShown, onClose, toggleRef } ) { + const registry = useRegistry(); + const { siteChanges } = useChanges(); + const [ restoringId, setRestoringId ] = useState( null ); + const [ openIds, setOpenIds ] = useState( () => new Set() ); + // The change whose details are showing: `{ entryId, index }`. + const [ drilled, setDrilled ] = useState( null ); + // Which way the last move went, for the screens' slide. + const [ direction, setDirection ] = useState( null ); + const [ now ] = useState( Date.now ); + const panelRef = useRef(); + const listScrollRef = useRef( 0 ); + const returnKeyRef = useRef( null ); + + // Once it has arrived, so focus doesn't pull the page while it slides. + useEffect( () => { + if ( isShown ) { + panelRef.current?.focus( { preventScroll: true } ); + } + }, [ isShown ] ); + + // A click anywhere else puts it away, as a popover would: it sits over + // the canvas's own toolbar. + useEffect( () => { + const onPointerDown = ( event ) => { + if ( + ! panelRef.current?.contains( event.target ) && + ! toggleRef.current?.contains( event.target ) && + // Snackbars, and dialogs opened from it, aren't elsewhere. + ! event.target.closest?.( + '.components-snackbar-list, .components-modal__screen-overlay' + ) + ) { + onClose( { returnFocus: false } ); + } + }; + + document.addEventListener( 'pointerdown', onPointerDown ); + + return () => + document.removeEventListener( 'pointerdown', onPointerDown ); + }, [ onClose, toggleRef ] ); + + // Back on the list: where it was, and on the change that was opened. + useEffect( () => { + if ( drilled || ! returnKeyRef.current ) { + return; + } + + const body = panelRef.current?.querySelector( + '.cnl-site-history__body' + ); + + if ( body ) { + body.scrollTop = listScrollRef.current; + } + + panelRef.current + ?.querySelector( `[data-change-key="${ returnKeyRef.current }"]` ) + ?.focus( { preventScroll: true } ); + returnKeyRef.current = null; + }, [ drilled ] ); + + const toggleEntry = ( id ) => + setOpenIds( ( ids ) => { + const next = new Set( ids ); + + if ( next.has( id ) ) { + next.delete( id ); + } else { + next.add( id ); + } + + return next; + } ); + + const drill = ( entry, index ) => { + listScrollRef.current = + panelRef.current?.querySelector( '.cnl-site-history__body' ) + ?.scrollTop || 0; + returnKeyRef.current = getChangeKey( entry, index ); + setDirection( 'forward' ); + setDrilled( { entryId: entry.id, index } ); + }; + + const back = () => { + setDirection( 'back' ); + setDrilled( null ); + }; + + const onRestore = async ( entry ) => { + setRestoringId( entry.id ); + + const { restored, failed } = await restoreEntry( + entries, + entries.indexOf( entry ), + registry + ); + const { createSuccessNotice, createErrorNotice } = + registry.dispatch( noticesStore ); + + setRestoringId( null ); + + if ( ! restored ) { + createErrorNotice( + failed + ? RESTORE_FAILED_MESSAGE + : __( + 'Nothing to put back. The editor already shows this version.' + ), + { type: 'snackbar' } + ); + return; + } + + createSuccessNotice( + failed + ? sprintf( + /* translators: 1: changes put back, 2: changes that couldn't be. */ + __( + 'Put back %1$d changes, but %2$d couldn’t be. Publish site to keep them.' + ), + restored, + failed + ) + : __( 'Version put back. Publish site to keep it.' ), + { type: 'snackbar' } + ); + onClose(); + }; + + const drilledEntry = + drilled && entries.find( ( { id } ) => id === drilled.entryId ); + const drilledChange = drilledEntry?.changes[ drilled.index ]; + let index = 0; + + return ( + // eslint-disable-next-line jsx-a11y/no-noninteractive-element-interactions -- Escape closes it, as it does a dialog. + + ); +} + +// Long enough for the panel to leave, as the stylesheet times it. +const LEAVE_MS = 260; + +/** + * Keep something mounted while it animates out. `isShown` follows `isOpen` + * a frame after mounting, so the first styles are painted and the panel + * has something to move from. + * + * @param {boolean} isOpen Whether it should be open. + * @return {{isMounted: boolean, isShown: boolean}} Whether to render it, and + * whether it is in place. + */ +function usePresence( isOpen ) { + const [ isMounted, setIsMounted ] = useState( false ); + const [ isShown, setIsShown ] = useState( false ); + + useEffect( () => { + if ( isOpen ) { + setIsMounted( true ); + + const frame = window.requestAnimationFrame( () => + window.requestAnimationFrame( () => setIsShown( true ) ) + ); + + return () => window.cancelAnimationFrame( frame ); + } + + setIsShown( false ); + + const timer = window.setTimeout( + () => setIsMounted( false ), + LEAVE_MS + ); + + return () => window.clearTimeout( timer ); + }, [ isOpen ] ); + + return { isMounted, isShown }; +} + +/** + * The history, loaded once and again whenever a publish is added. + * + * @return {?Object[]} The entries, or null until they have loaded. + */ +function useSiteHistory() { + const [ entries, setEntries ] = useState( null ); + + useEffect( () => { + let isCurrent = true; + const load = () => + getSiteHistory().then( + ( history ) => isCurrent && setEntries( history ), + // Without it the button stays off, as with no history. + () => isCurrent && setEntries( [] ) + ); + + load(); + + const stopListening = onSiteHistoryChanged( load ); + + return () => { + isCurrent = false; + stopListening(); + }; + }, [] ); + + return entries; +} + +export function SiteHistory() { + const [ isOpen, setIsOpen ] = useState( false ); + const toggleRef = useRef(); + const entries = useSiteHistory(); + const { isMounted, isShown } = usePresence( isOpen ); + const hasHistory = !! entries?.length; + + const close = useCallback( ( { returnFocus = true } = {} ) => { + setIsOpen( false ); + + // Not when a click elsewhere closed it: focus follows that click. + if ( returnFocus ) { + toggleRef.current?.focus(); + } + }, [] ); + + return ( + <> +