diff --git a/packages/editor/CHANGELOG.md b/packages/editor/CHANGELOG.md index 2d095dfe5f018a..efb82ee086f96d 100644 --- a/packages/editor/CHANGELOG.md +++ b/packages/editor/CHANGELOG.md @@ -5,6 +5,7 @@ ### Enhancements - Notes: Add one note to several selected blocks, or to text selected across them ([#86051](https://github.com/WordPress/gutenberg/pull/86051)). +- Style revisions: Compare the selected revision with the current version side by side, as a visual preview or as a code diff of the styles and settings, with a header naming each ([#85288](https://github.com/WordPress/gutenberg/pull/85288)). ### Bug Fixes diff --git a/packages/editor/src/components/post-revisions-preview/revisions-code-diff.jsx b/packages/editor/src/components/post-revisions-preview/revisions-code-diff.jsx index c4d10f136f7c4c..ded3240e0e3b80 100644 --- a/packages/editor/src/components/post-revisions-preview/revisions-code-diff.jsx +++ b/packages/editor/src/components/post-revisions-preview/revisions-code-diff.jsx @@ -1,4 +1,5 @@ import { diffLines } from 'diff'; +import clsx from 'clsx'; import { Spinner as WCSpinner } from '@wordpress/components'; import { store as coreStore } from '@wordpress/core-data'; import { useSelect } from '@wordpress/data'; @@ -27,6 +28,30 @@ function splitLines( value ) { return lines; } +/** + * Diffs two contents line by line. + * + * @param {string} previousContent Previous content. + * @param {string} currentContent Current content. + * @return {Array} Diff parts, each marked as added, removed or neither. + */ +function getDiffParts( previousContent, currentContent ) { + const parts = diffLines( previousContent, currentContent, { + maxEditLength: MAX_DIFF_EDIT_LENGTH, + timeout: DIFF_TIMEOUT, + } ); + + // Line diffing can be quadratic for unrelated revisions. If it exceeds + // either limit, mark every old and new line instead. + if ( ! parts ) { + return [ + { value: previousContent, removed: true }, + { value: currentContent, added: true }, + ]; + } + return parts; +} + /** * Creates the rows shown in the code diff and adds line numbers for both * revisions. @@ -37,22 +62,9 @@ function splitLines( value ) { * @return {Array} Code-diff rows. */ export function getCodeDiffRows( previousContent, currentContent, showDiff ) { - let parts = [ { value: currentContent } ]; - if ( showDiff ) { - parts = diffLines( previousContent, currentContent, { - maxEditLength: MAX_DIFF_EDIT_LENGTH, - timeout: DIFF_TIMEOUT, - } ); - - // Line diffing can be quadratic for unrelated revisions. If it exceeds - // either limit, mark every old and new line instead. - if ( ! parts ) { - parts = [ - { value: previousContent, removed: true }, - { value: currentContent, added: true }, - ]; - } - } + const parts = showDiff + ? getDiffParts( previousContent, currentContent ) + : [ { value: currentContent } ]; let previousLineNumber = 1; let currentLineNumber = 1; @@ -84,6 +96,78 @@ export function getCodeDiffRows( previousContent, currentContent, showDiff ) { } ); } +/** + * Creates the rows of a side-by-side code diff. Each row holds a line of the + * previous content and a line of the current content. Unchanged lines show on + * both sides; a run of changes pairs its removed and added lines up in order, + * leaving a side empty where the other has more lines. + * + * @param {string} previousContent Previous content. + * @param {string} currentContent Current content. + * @return {Array<{previous: Object|null, current: Object|null}>} Rows. + */ +export function getSplitCodeDiffRows( previousContent, currentContent ) { + const parts = getDiffParts( previousContent, currentContent ); + const rows = []; + let previousLineNumber = 1; + let currentLineNumber = 1; + let removedLines = []; + let addedLines = []; + + const flushChanges = () => { + const length = Math.max( removedLines.length, addedLines.length ); + for ( let index = 0; index < length; index++ ) { + rows.push( { + previous: + index < removedLines.length + ? { + value: removedLines[ index ], + status: 'removed', + lineNumber: previousLineNumber++, + } + : null, + current: + index < addedLines.length + ? { + value: addedLines[ index ], + status: 'added', + lineNumber: currentLineNumber++, + } + : null, + } ); + } + removedLines = []; + addedLines = []; + }; + + for ( const part of parts ) { + if ( part.removed ) { + removedLines.push( ...splitLines( part.value ) ); + } else if ( part.added ) { + addedLines.push( ...splitLines( part.value ) ); + } else { + flushChanges(); + for ( const value of splitLines( part.value ) ) { + rows.push( { + previous: { + value, + status: 'unchanged', + lineNumber: previousLineNumber++, + }, + current: { + value, + status: 'unchanged', + lineNumber: currentLineNumber++, + }, + } ); + } + } + } + flushChanges(); + + return rows; +} + /** * Determines whether the code diff should wait for an older revision or fall * back to showing the selected revision without a diff. @@ -206,76 +290,241 @@ export function RevisionsCodeDiff( { ); } - const label = showDiff ? __( 'Code changes' ) : __( 'Revision code' ); + return ( + + ); +} +/** + * The scrollable, focusable region both code-diff tables render in, with the + * message shown instead of a table when there is nothing to list. + * + * @param {Object} props Component props. + * @param {string} [props.className] Extra class for the region. + * @param {string} props.label Accessible name of the region. + * @param {boolean} props.isEmpty Whether to show the message instead of the table. + * @param {string} props.emptyMessage Message shown when there is nothing to list. + * @param {React.ReactNode} props.children The table. + * @return {React.JSX.Element} The code-diff region. + */ +function CodeDiffRegion( { + className, + label, + isEmpty, + emptyMessage, + children, +} ) { return (
- { rows.length ? ( - - }> - { label } - - }> - - { showDiff && } - - { showDiff && } - - - - - { rows.map( ( row, index ) => { - let marker = ''; - let statusLabel = __( 'Unchanged' ); - if ( row.status === 'added' ) { - marker = '+'; - statusLabel = __( 'Added' ); - } else if ( row.status === 'removed' ) { - marker = '−'; - statusLabel = __( 'Removed' ); - } - - return ( - - { showDiff && ( - - ) } - - { showDiff && ( - - ) } - - - ); - } ) } - -
{ __( 'Previous line' ) }{ __( 'Current line' ) }{ _x( 'Change', 'noun' ) }{ __( 'Code' ) }
- { row.previousLineNumber } - - { row.currentLineNumber } - - - { statusLabel } - - - - { row.value } -
- ) : ( + { isEmpty ? (

- { __( 'This revision is empty.' ) } + { emptyMessage }

+ ) : ( + children ) }
); } + +/** + * Renders code-diff rows as a scrollable, read-only table, with both line + * numbers in one column of code. `SplitCodeDiffTable` shows them side by side. + * + * @param {Object} props Component props. + * @param {Array} props.rows Rows from `getCodeDiffRows`. + * @param {boolean} props.showDiff Whether rows carry change markers. + * @param {string} props.label Accessible name of the region. + * @param {string} props.emptyMessage Message shown when there are no rows. + * @return {React.JSX.Element} The code-diff table. + */ +export function CodeDiffTable( { rows, showDiff, label, emptyMessage } ) { + return ( + + + }> + { label } + + }> + + { showDiff && } + + { showDiff && } + + + + + { rows.map( ( row, index ) => { + let marker = ''; + let statusLabel = __( 'Unchanged' ); + if ( row.status === 'added' ) { + marker = '+'; + statusLabel = __( 'Added' ); + } else if ( row.status === 'removed' ) { + marker = '−'; + statusLabel = __( 'Removed' ); + } + + return ( + + { showDiff && ( + + ) } + + { showDiff && ( + + ) } + + + ); + } ) } + +
{ __( 'Previous line' ) }{ __( 'Current line' ) }{ _x( 'Change', 'noun' ) }{ __( 'Code' ) }
+ { row.previousLineNumber } + + { row.currentLineNumber } + + + { statusLabel } + + + + { row.value } +
+
+ ); +} + +/** + * Renders one side of a side-by-side code-diff row: its line number, change + * marker and code, or empty cells when the side has no line. + * + * @param {Object} props Component props. + * @param {Object|null} props.line The side's line, from `getSplitCodeDiffRows`. + * @return {React.JSX.Element} The side's cells. + */ +function SplitCodeDiffSide( { line } ) { + if ( ! line ) { + return ( + <> + + + + + ); + } + + let marker = ''; + let statusLabel = __( 'Unchanged' ); + if ( line.status === 'added' ) { + marker = '+'; + statusLabel = __( 'Added' ); + } else if ( line.status === 'removed' ) { + marker = '−'; + statusLabel = __( 'Removed' ); + } + + return ( + <> + + { line.lineNumber } + + + { statusLabel } + + + + { line.value } + + + ); +} + +/** + * Renders side-by-side code-diff rows as a read-only table, the previous + * content on the start side and the current content on the end side. + * + * @param {Object} props Component props. + * @param {Array} props.rows Rows from `getSplitCodeDiffRows`. + * @param {string} props.label Accessible name of the region. + * @param {string} props.previousLabel Name of the previous content. + * @param {string} props.currentLabel Name of the current content. + * @param {string} props.emptyMessage Message shown when there are no rows. + * @return {React.JSX.Element} The side-by-side code diff. + */ +export function SplitCodeDiffTable( { + rows, + label, + previousLabel, + currentLabel, + emptyMessage, +} ) { + return ( + + + }> + { label } + + + + + + + + + + }> + + + + + + + + + + + { rows.map( ( row, index ) => ( + + + + + ) ) } + +
{ __( 'Line' ) }{ _x( 'Change', 'noun' ) }{ previousLabel }{ __( 'Line' ) }{ _x( 'Change', 'noun' ) }{ currentLabel }
+
+ ); +} diff --git a/packages/editor/src/components/post-revisions-preview/style.scss b/packages/editor/src/components/post-revisions-preview/style.scss index 6f2001e1faeb39..5e8b1fa79c0f7a 100644 --- a/packages/editor/src/components/post-revisions-preview/style.scss +++ b/packages/editor/src/components/post-revisions-preview/style.scss @@ -147,6 +147,54 @@ $revision-code-diff-marker-width: 3ch; color: $gray-700; } +// Side by side: each half takes half the width, so it lines up with what sits +// above it, and long lines wrap rather than scrolling the halves together. +.editor-revisions-code-diff.is-split { + .editor-revisions-code-diff__table { + min-width: 0; + table-layout: fixed; + } + + .editor-revisions-code-diff__line-number-column { + width: $revision-code-diff-line-number-width; + } + + .editor-revisions-code-diff__marker-column { + width: $revision-code-diff-marker-width; + } + + .editor-revisions-code-diff__line-number, + .editor-revisions-code-diff__marker { + position: static; + vertical-align: top; + } + + .editor-revisions-code-diff__code { + // The two code columns share the remaining width equally. + width: auto; + vertical-align: top; + white-space: pre-wrap; + overflow-wrap: anywhere; + } + + // The current side starts at the fourth cell. + td:nth-child(4) { + border-left: $border-width solid $gray-200; + } + + td.is-removed { + background: rgba($revision-diff-removed-color, 0.12); + } + + td.is-added { + background: rgba($revision-diff-added-color, 0.12); + } + + td.is-empty { + background: $gray-100; + } +} + // Diff markers minimap .revision-diff-markers { position: relative; diff --git a/packages/editor/src/components/post-revisions-preview/test/revisions-code-diff.jsdom.test.jsx b/packages/editor/src/components/post-revisions-preview/test/revisions-code-diff.jsdom.test.jsx index 0a9f1d4f584867..b22afe07d3ea4b 100644 --- a/packages/editor/src/components/post-revisions-preview/test/revisions-code-diff.jsdom.test.jsx +++ b/packages/editor/src/components/post-revisions-preview/test/revisions-code-diff.jsdom.test.jsx @@ -4,6 +4,7 @@ import { RevisionsCodeDiff, getCodeDiffDisplayState, getCodeDiffRows, + getSplitCodeDiffRows, } from '../revisions-code-diff'; vi.hoisted( () => globalThis.wpVitest.mockMatchMedia() ); @@ -132,6 +133,70 @@ describe( 'getCodeDiffRows', () => { } ); } ); +describe( 'getSplitCodeDiffRows', () => { + it( 'shows unchanged lines on both sides', () => { + expect( getSplitCodeDiffRows( 'Same\n', 'Same\n' ) ).toEqual( [ + { + previous: { value: 'Same', status: 'unchanged', lineNumber: 1 }, + current: { value: 'Same', status: 'unchanged', lineNumber: 1 }, + }, + ] ); + } ); + + it( 'pairs removed and added lines in order', () => { + expect( + getSplitCodeDiffRows( + 'First\nBefore\nLast\n', + 'First\nAfter\nLast\n' + ) + ).toEqual( [ + { + previous: { + value: 'First', + status: 'unchanged', + lineNumber: 1, + }, + current: { value: 'First', status: 'unchanged', lineNumber: 1 }, + }, + { + previous: { value: 'Before', status: 'removed', lineNumber: 2 }, + current: { value: 'After', status: 'added', lineNumber: 2 }, + }, + { + previous: { value: 'Last', status: 'unchanged', lineNumber: 3 }, + current: { value: 'Last', status: 'unchanged', lineNumber: 3 }, + }, + ] ); + } ); + + it( 'leaves a side empty where the other has more changed lines', () => { + expect( + getSplitCodeDiffRows( 'First\nLast\n', 'First\nOne\nTwo\nLast\n' ) + ).toEqual( [ + { + previous: { + value: 'First', + status: 'unchanged', + lineNumber: 1, + }, + current: { value: 'First', status: 'unchanged', lineNumber: 1 }, + }, + { + previous: null, + current: { value: 'One', status: 'added', lineNumber: 2 }, + }, + { + previous: null, + current: { value: 'Two', status: 'added', lineNumber: 3 }, + }, + { + previous: { value: 'Last', status: 'unchanged', lineNumber: 2 }, + current: { value: 'Last', status: 'unchanged', lineNumber: 4 }, + }, + ] ); + } ); +} ); + describe( 'getCodeDiffDisplayState', () => { it( 'waits for an older revision from the next page', () => { expect( diff --git a/packages/editor/src/components/styles-canvas/revision-details.tsx b/packages/editor/src/components/styles-canvas/revision-details.tsx new file mode 100644 index 00000000000000..3f30dd0f85ef9c --- /dev/null +++ b/packages/editor/src/components/styles-canvas/revision-details.tsx @@ -0,0 +1,89 @@ +import { dateI18n, getDate, getSettings } from '@wordpress/date'; +import { __ } from '@wordpress/i18n'; + +/** + * The parts of a global styles revision the details show. The revisions hook + * adds the author, including the current user for unsaved changes. + */ +export interface RevisionDetailsRevision { + id: string | number; + modified?: string | Date; + author?: { + name?: string; + avatar_urls?: Record< string, string >; + }; +} + +interface RevisionDetailsProps { + /** + * The revision to describe. + */ + revision: RevisionDetailsRevision; + /** + * Whether the revision holds the styles the editor shows. + */ + isCurrent?: boolean; +} + +/** + * Returns the label for when a revision was made: its date, or what the entry + * stands for when it isn't a saved revision. + * + * @param revision The revision. + * @return The label. + */ +function getRevisionDateLabel( revision: RevisionDetailsRevision ): string { + if ( 'parent' === revision.id ) { + return __( 'Default styles' ); + } + if ( 'unsaved' === revision.id ) { + return __( 'Unsaved changes' ); + } + if ( ! revision.modified ) { + return ''; + } + const modified = + revision.modified instanceof Date + ? revision.modified.toISOString() + : revision.modified; + return dateI18n( getSettings().formats.datetime, getDate( modified ) ); +} + +/** + * Describes a global styles revision: when it was made and by whom. + * + * @param props Component props. + * @param props.revision The revision to describe. + * @param props.isCurrent Whether the revision holds the styles the editor shows. + * @return The revision details. + */ +export default function RevisionDetails( { + revision, + isCurrent = false, +}: RevisionDetailsProps ) { + // The theme defaults have no author. Any other entry names one, falling + // back as the revisions list does when the author isn't known. + const hasAuthor = 'parent' !== revision.id; + const avatarUrl = revision.author?.avatar_urls?.[ '48' ]; + const dateLabel = getRevisionDateLabel( revision ); + + return ( +

+ { isCurrent && ( + + { __( 'Current version' ) } + + ) } + { dateLabel && { dateLabel } } + { hasAuthor && ( + + { avatarUrl && ( + // The name follows, so the avatar is decorative. + + ) } + { revision.author?.name || __( 'User' ) } + + ) } +

+ ); +} diff --git a/packages/editor/src/components/styles-canvas/revisions-code-diff.tsx b/packages/editor/src/components/styles-canvas/revisions-code-diff.tsx new file mode 100644 index 00000000000000..418126c88b971b --- /dev/null +++ b/packages/editor/src/components/styles-canvas/revisions-code-diff.tsx @@ -0,0 +1,130 @@ +import { useMemo } from '@wordpress/element'; +import { __ } from '@wordpress/i18n'; +import { + areGlobalStylesEqual, + type GlobalStylesConfig, +} from '@wordpress/global-styles-engine'; +import { + SplitCodeDiffTable, + getSplitCodeDiffRows, +} from '../post-revisions-preview/revisions-code-diff'; + +type StylesConfig = Pick< GlobalStylesConfig, 'settings' | 'styles' >; + +/** + * Returns the value with the keys of every nested object sorted, so that two + * configs with the same content serialize the same. Arrays keep their order, + * as the order of entries such as palette colors is meaningful. + * + * @param value Value to sort. + * @return The value with sorted object keys. + */ +function sortObjectKeys( value: unknown ): unknown { + if ( Array.isArray( value ) ) { + return value.map( sortObjectKeys ); + } + if ( value !== null && typeof value === 'object' ) { + return Object.fromEntries( + Object.keys( value ) + .sort() + .map( ( key ) => [ + key, + sortObjectKeys( + ( value as Record< string, unknown > )[ key ] + ), + ] ) + ); + } + return value; +} + +/** + * Serializes the styles and settings of a global styles config for a code diff. + * Revision metadata such as the id, author and date is left out, and keys are + * sorted, as the REST endpoints and the editor need not order them the same. + * + * @param config Global styles config or revision. + * @return The config's styles and settings as formatted JSON. + */ +export function getStylesRevisionCode( + config?: Partial< StylesConfig > | null +): string { + return JSON.stringify( + sortObjectKeys( { + settings: config?.settings ?? {}, + styles: config?.styles ?? {}, + } ), + null, + 2 + ); +} + +interface StylesRevisionsCodeDiffProps { + /** + * The revision to compare, or `null` when there is none to compare. + */ + revision?: Partial< StylesConfig > | null; + /** + * The styles the editor currently shows, unsaved changes included. + */ + currentConfig?: Partial< StylesConfig > | null; +} + +/** + * Shows how the current global styles differ from a revision, as a read-only + * side-by-side diff of their styles and settings: the revision on the start + * side and the current styles on the end side, as in the canvas header. + * + * @param props Component props. + * @param props.revision The revision to compare. + * @param props.currentConfig The styles the editor currently shows. + * @return The code diff. + */ +export default function StylesRevisionsCodeDiff( { + revision, + currentConfig, +}: StylesRevisionsCodeDiffProps ) { + // Matching styles leave nothing to compare, so show the empty message + // rather than the whole config marked as unchanged. The sidebar's Apply + // button decides "matching" the same way. + const hasChanges = useMemo( + () => + !! revision && + ! areGlobalStylesEqual( + revision as GlobalStylesConfig, + ( currentConfig ?? {} ) as GlobalStylesConfig + ), + [ revision, currentConfig ] + ); + // The current styles stay the same while revisions are browsed, so they + // are serialized once rather than for every revision. + const currentCode = useMemo( + () => ( hasChanges ? getStylesRevisionCode( currentConfig ) : null ), + [ currentConfig, hasChanges ] + ); + const rows = useMemo( () => { + if ( ! revision || currentCode === null ) { + return []; + } + return getSplitCodeDiffRows( + getStylesRevisionCode( revision ), + currentCode + ); + }, [ revision, currentCode ] ); + + return ( + + ); +} diff --git a/packages/editor/src/components/styles-canvas/revisions.jsx b/packages/editor/src/components/styles-canvas/revisions.jsx index 47ef007d7f8363..f0d01c56ce4ef5 100644 --- a/packages/editor/src/components/styles-canvas/revisions.jsx +++ b/packages/editor/src/components/styles-canvas/revisions.jsx @@ -1,4 +1,9 @@ -import { Disabled } from '@wordpress/components'; +import clsx from 'clsx'; +import { + Disabled, + __experimentalToggleGroupControl as ToggleGroupControl, + __experimentalToggleGroupControlOption as ToggleGroupControlOption, +} from '@wordpress/components'; import { BlockList, privateApis as blockEditorPrivateApis, @@ -7,12 +12,16 @@ import { __unstableIframe as Iframe, } from '@wordpress/block-editor'; import { useSelect } from '@wordpress/data'; -import { useMemo, forwardRef } from '@wordpress/element'; +import { useMemo, useState, forwardRef } from '@wordpress/element'; +import { __, _x } from '@wordpress/i18n'; import { useGlobalStylesRevisions } from '@wordpress/global-styles-ui'; import { mergeGlobalStyles } from '@wordpress/global-styles-engine'; import { useGlobalStyles } from '../global-styles/hooks'; import { useGlobalStylesOutputWithConfig } from '../../hooks/use-global-styles-output'; import { unlock } from '../../lock-unlock'; +import StylesRevisionsCodeDiff from './revisions-code-diff'; +import RevisionDetails from './revision-details'; +import useSyncedScroll from './use-synced-scroll'; const { ExperimentalBlockEditorProvider, @@ -23,10 +32,83 @@ function isObjectEmpty( object ) { return ! object || Object.keys( object ).length === 0; } +/** + * Previews the editor's blocks with a global styles config. + * + * @param {Object} props Component props. + * @param {Object} props.config The global styles config to preview. + * @param {Object} props.baseConfig The theme's base global styles. + * @param {Array} props.blocks The blocks to preview. + * @param {Object} props.settings Block editor settings. + * @param {string} props.name The iframe name. + * @param {string} [props.title] The iframe's accessible name. + * @param {React.Ref} [props.frameRef] Receives the iframe element. + * @return {React.JSX.Element} The preview. + */ +function RevisionPreview( { + config, + baseConfig, + blocks, + settings, + name, + title, + frameRef, +} ) { + const mergedConfig = useMemo( () => { + if ( ! isObjectEmpty( config ) && ! isObjectEmpty( baseConfig ) ) { + return mergeGlobalStyles( baseConfig, config ); + } + return {}; + }, [ baseConfig, config ] ); + + const [ globalStyles ] = useGlobalStylesOutputWithConfig( mergedConfig ); + + const editorStyles = + ! isObjectEmpty( globalStyles ) && ! isObjectEmpty( config ) + ? globalStyles + : settings.styles; + + return ( + + ); +} + /** * Revisions content component for global styles. * Coordinates with ScreenRevisions through the path parameter to display - * the currently selected revision. + * the currently selected revision. When that isn't the current version, the + * visual view shows the two side by side, and the code view shows what + * changed between them. * * @param {Object} props Component props. * @param {string} props.path Current path in global styles. @@ -59,20 +141,6 @@ function StylesCanvasRevisions( { path }, ref ) { ); }, [ revisionId, revisions ] ); - // Use the selected revision's config if available, otherwise use current user config - const displayConfig = selectedRevision || userConfig; - - // Merge the display config with the base config - const mergedConfig = useMemo( () => { - if ( - ! isObjectEmpty( displayConfig ) && - ! isObjectEmpty( baseConfig ) - ) { - return mergeGlobalStyles( baseConfig, displayConfig ); - } - return {}; - }, [ baseConfig, displayConfig ] ); - const renderedBlocksArray = useMemo( () => ( Array.isArray( blocks ) ? blocks : [ blocks ] ), [ blocks ] @@ -90,48 +158,129 @@ function StylesCanvasRevisions( { path }, ref ) { [ originalSettings ] ); - const [ globalStyles ] = useGlobalStylesOutputWithConfig( mergedConfig ); + const [ view, setView ] = useState( 'visual' ); - const editorStyles = - ! isObjectEmpty( globalStyles ) && ! isObjectEmpty( displayConfig ) - ? globalStyles - : settings.styles; + // The selected revision's preview is only there when comparing in the + // visual view, so the previews scroll together only then. + const [ selectedFrame, setSelectedFrame ] = useState( null ); + const [ currentFrame, setCurrentFrame ] = useState( null ); + useSyncedScroll( selectedFrame, currentFrame ); if ( isLoading ) { return null; } + // The first entry is the styles the editor shows: the unsaved changes + // when there are any, else the latest revision. + const currentRevision = revisions[ 0 ]; + // Comparing the current version with itself would show the same styles + // twice, so only another revision is shown next to it. + const isComparingRevision = + !! selectedRevision && selectedRevision.id !== currentRevision?.id; + + // The code view compares the selected revision with the current styles. + // The current version itself is compared as the editor holds it, as the + // sidebar does: the two endpoints need not serialize the same styles + // identically. A revision the path names but the list doesn't hold has + // nothing to compare. + let codeRevision = userConfig; + if ( isComparingRevision ) { + codeRevision = selectedRevision; + } else if ( revisionId && ! selectedRevision ) { + codeRevision = null; + } + + const previewProps = { + baseConfig, + blocks: renderedBlocksArray, + settings, + }; + + // Each header is placed over its pane by grid area, so that the panes can + // stack with their headers when the canvas is narrow. return ( - + { /* The container query needs an ancestor container, so the grid is a child of it. */ } +
+ { isComparingRevision && ( +
+ +
+ ) } +
+ { currentRevision && ( + + ) } +
+ + + + +
+
+ { view === 'code' && ( +
+ +
+ ) } + { view === 'visual' && isComparingRevision && ( +
+ { /* The `revisions` name is what tests and tooling look up, so it stays on the pane showing the selected revision. */ } + +
+ ) } + { view === 'visual' && ( +
+ +
+ ) } +
+ ); } export default forwardRef( StylesCanvasRevisions ); diff --git a/packages/editor/src/components/styles-canvas/style.scss b/packages/editor/src/components/styles-canvas/style.scss index 092259c5f92853..2a28a4e750fd4a 100644 --- a/packages/editor/src/components/styles-canvas/style.scss +++ b/packages/editor/src/components/styles-canvas/style.scss @@ -36,6 +36,172 @@ } } +.editor-styles-canvas-revisions { + height: 100%; + // Stack the panes when the canvas, not the window, is narrow. The grid + // is a child, as an element can't be its own query container. + container-type: inline-size; +} + +.editor-styles-canvas-revisions__layout { + height: 100%; + display: grid; + grid-template-columns: minmax(0, 1fr); + grid-template-rows: auto minmax(0, 1fr); + grid-template-areas: + "current-header" + "current"; + + // The code view takes the whole width under the headers. + .editor-styles-canvas-revisions:not(.is-visual) > & { + grid-template-areas: + "current-header" + "code"; + } + + // Comparing, each pane sits under its own header. + .is-comparing > & { + grid-template-columns: repeat(2, minmax(0, 1fr)); + grid-template-areas: + "selected-header current-header" + "selected current"; + } + + .is-comparing:not(.is-visual) > & { + grid-template-areas: + "selected-header current-header" + "code code"; + } +} + +.editor-styles-canvas-revisions__pane-header { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: $grid-unit-10 $grid-unit-20; + // A 40px row under 4px of padding puts the toggle and the details on the + // same centre line as the 32px close button at 8px from the top. + min-height: $button-size-compact + $grid-unit-10; + padding: $grid-unit-05 $grid-unit-20; + border-bottom: $border-width solid $gray-200; + background: $white; + + // The details take the room they need, and the toggle moves to its own + // line when both don't fit, rather than squeezing the details. + > .editor-styles-canvas-revision-details { + flex: 1 1 14rem; + } + + &.is-selected { + grid-area: selected-header; + } + + &.is-current { + grid-area: current-header; + // This header holds the toggle, in the top right corner, so it leaves + // room for the close button that sits over it. + padding-right: $grid-unit-10 + $button-size-compact + $grid-unit-10; + } + + .is-comparing &.is-current { + border-left: $border-width solid $gray-200; + } +} + +.editor-styles-canvas-revisions__view-toggle { + display: flex; + justify-content: flex-end; + margin-left: auto; +} + +.editor-styles-canvas-revisions__code { + grid-area: code; + min-height: 0; +} + +.editor-styles-canvas-revisions__pane { + min-width: 0; + min-height: 0; + + &.is-selected { + grid-area: selected; + } + + &.is-current { + grid-area: current; + } + + .is-comparing &.is-current { + border-left: $border-width solid $gray-200; + } +} + +// Below this width each pane would be too narrow to read, so the visual +// panes stack, each under its header. The current version goes first, as in +// the revisions list, which keeps the view toggle in the top row. The code +// view stays side by side. +@container (width < 782px) { + .is-comparing.is-visual > .editor-styles-canvas-revisions__layout { + grid-template-columns: minmax(0, 1fr); + grid-template-rows: auto minmax(0, 1fr) auto minmax(0, 1fr); + grid-template-areas: + "current-header" + "current" + "selected-header" + "selected"; + + .editor-styles-canvas-revisions__pane-header.is-current, + .editor-styles-canvas-revisions__pane.is-current { + border-left: 0; + } + + .editor-styles-canvas-revisions__pane-header.is-selected { + border-top: $border-width solid $gray-200; + } + } +} + +// In preview mode there is no close button to leave room for. +.editor-styles-canvas.is-preview-mode .editor-styles-canvas-revisions__pane-header { + padding-right: $grid-unit-20; +} + +.editor-styles-canvas-revision-details { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: $grid-unit-05 $grid-unit-10; + margin: 0; + color: $gray-900; + font-size: $default-font-size; +} + +.editor-styles-canvas-revision-details__current { + display: inline-flex; + align-items: center; + gap: $grid-unit-05; + + &::before { + content: ""; + width: $grid-unit-10; + height: $grid-unit-10; + border-radius: 50%; + background: var(--wp-admin-theme-color); + } +} + +.editor-styles-canvas-revision-details__author { + display: inline-flex; + align-items: center; + gap: $grid-unit-05; + + img { + width: $grid-unit-20; + height: $grid-unit-20; + border-radius: 50%; + } +} + .editor-styles-canvas__close-button { position: absolute; right: $grid-unit-10; diff --git a/packages/editor/src/components/styles-canvas/test/revision-details.jsdom.test.tsx b/packages/editor/src/components/styles-canvas/test/revision-details.jsdom.test.tsx new file mode 100644 index 00000000000000..4db54900ecd005 --- /dev/null +++ b/packages/editor/src/components/styles-canvas/test/revision-details.jsdom.test.tsx @@ -0,0 +1,82 @@ +import { describe, expect, it, vi } from 'vitest'; +import { render, screen } from '@testing-library/react'; +import RevisionDetails from '../revision-details'; + +vi.hoisted( () => globalThis.wpVitest.mockMatchMedia() ); + +const author = { + name: 'joen', + avatar_urls: { '48': 'https://example.com/avatar.png' }, +}; + +describe( 'RevisionDetails', () => { + it( 'shows when a saved revision was made and by whom', () => { + render( + + ); + + expect( screen.getByText( /2026/ ) ).toBeVisible(); + expect( screen.getByText( 'joen' ) ).toBeVisible(); + expect( + screen.queryByText( 'Current version' ) + ).not.toBeInTheDocument(); + } ); + + it( 'marks the current version', () => { + render( + + ); + + expect( screen.getByText( 'Current version' ) ).toBeVisible(); + } ); + + it( 'names unsaved changes instead of a date', () => { + render( ); + + expect( screen.getByText( 'Unsaved changes' ) ).toBeVisible(); + expect( screen.getByText( 'joen' ) ).toBeVisible(); + } ); + + it( 'names the theme defaults, which have no author', () => { + render( ); + + expect( screen.getByText( 'Default styles' ) ).toBeVisible(); + expect( screen.queryByText( 'joen' ) ).not.toBeInTheDocument(); + } ); + + it( 'falls back to a generic name when the author is unknown', () => { + render( + + ); + + expect( screen.getByText( 'User' ) ).toBeVisible(); + } ); + + it( 'shows no date for a revision without one', () => { + render( ); + + expect( screen.queryByText( /20\d\d/ ) ).not.toBeInTheDocument(); + expect( screen.getByText( 'joen' ) ).toBeVisible(); + } ); + + it( 'keeps the avatar out of the accessibility tree', () => { + render( + + ); + + expect( screen.queryByRole( 'img' ) ).not.toBeInTheDocument(); + } ); +} ); diff --git a/packages/editor/src/components/styles-canvas/test/revisions-code-diff.jsdom.test.tsx b/packages/editor/src/components/styles-canvas/test/revisions-code-diff.jsdom.test.tsx new file mode 100644 index 00000000000000..8c20bdf658b903 --- /dev/null +++ b/packages/editor/src/components/styles-canvas/test/revisions-code-diff.jsdom.test.tsx @@ -0,0 +1,129 @@ +import { describe, expect, it, vi } from 'vitest'; +import { render, screen, within } from '@testing-library/react'; +import StylesRevisionsCodeDiff, { + getStylesRevisionCode, +} from '../revisions-code-diff'; + +vi.hoisted( () => globalThis.wpVitest.mockMatchMedia() ); + +describe( 'getStylesRevisionCode', () => { + it( 'leaves out revision metadata', () => { + const code = getStylesRevisionCode( { + id: 12, + author: { name: 'Admin' }, + modified: '2026-01-01T00:00:00', + _links: { self: [] }, + styles: { color: { text: 'red' } }, + settings: {}, + } as Parameters< typeof getStylesRevisionCode >[ 0 ] ); + + expect( JSON.parse( code ) ).toEqual( { + settings: {}, + styles: { color: { text: 'red' } }, + } ); + } ); + + it( 'serializes the same content the same whatever the key order', () => { + expect( + getStylesRevisionCode( { + styles: { color: { text: 'red', background: 'blue' } }, + settings: { layout: { contentSize: '600px' } }, + } ) + ).toBe( + getStylesRevisionCode( { + settings: { layout: { contentSize: '600px' } }, + styles: { color: { background: 'blue', text: 'red' } }, + } ) + ); + } ); + + it( 'keeps the order of array entries', () => { + const code = getStylesRevisionCode( { + settings: { + color: { + palette: { + custom: [ + { name: 'Black', slug: 'b', color: '#000' }, + { name: 'White', slug: 'a', color: '#fff' }, + ], + }, + }, + }, + } ); + + expect( + JSON.parse( code ).settings.color.palette.custom.map( + ( { slug }: { slug: string } ) => slug + ) + ).toEqual( [ 'b', 'a' ] ); + } ); + + it( 'treats missing styles and settings as empty', () => { + expect( JSON.parse( getStylesRevisionCode( null ) ) ).toEqual( { + settings: {}, + styles: {}, + } ); + } ); +} ); + +describe( 'StylesRevisionsCodeDiff', () => { + it( 'shows the revision value removed next to the current value added', () => { + render( + + ); + + expect( + screen.getByRole( 'region', { + name: 'Changes since this revision', + } ) + ).toBeVisible(); + + // The changed line pairs up in one row: the revision on the start + // side, the current styles on the end side. + const row = screen.getByRole( 'row', { + name: /Removed.*"background": "blue".*Added.*"background": "red"/, + } ); + expect( + within( row ).getByRole( 'cell', { name: /"background": "blue"/ } ) + ).toHaveClass( 'is-removed' ); + expect( + within( row ).getByRole( 'cell', { name: /"background": "red"/ } ) + ).toHaveClass( 'is-added' ); + } ); + + it( 'says so when the revision matches the current styles', () => { + render( + + ); + + expect( + screen.getByText( 'This revision matches the current styles.' ) + ).toBeVisible(); + expect( screen.queryByRole( 'table' ) ).not.toBeInTheDocument(); + } ); + + it( 'asks for a revision when there is none to compare', () => { + render( + + ); + + expect( + screen.getByText( + 'Select a revision to compare it with the current styles.' + ) + ).toBeVisible(); + } ); +} ); diff --git a/packages/editor/src/components/styles-canvas/use-synced-scroll.ts b/packages/editor/src/components/styles-canvas/use-synced-scroll.ts new file mode 100644 index 00000000000000..9eb9fa13be406f --- /dev/null +++ b/packages/editor/src/components/styles-canvas/use-synced-scroll.ts @@ -0,0 +1,116 @@ +import { useEffect } from '@wordpress/element'; + +interface ScrollSide { + frame: HTMLIFrameElement; + // Where this side was last scrolled to by the other, or -1. + echo: number; +} + +const isNear = ( a: number, b: number ) => Math.abs( a - b ) < 1; + +function getScroller( { frame }: ScrollSide ) { + return frame.contentDocument?.scrollingElement ?? null; +} + +function getScrollRange( scroller: Element ) { + return scroller.scrollHeight - scroller.clientHeight; +} + +/** + * Scrolls `target` to the same relative position as `source`. + * + * @param source The side that was scrolled. + * @param target The side to follow it. + */ +function follow( source: ScrollSide, target: ScrollSide ) { + const from = getScroller( source ); + const to = getScroller( target ); + if ( ! from || ! to ) { + return; + } + + // A programmatic scroll fires its own `scroll` event a frame later. Each + // side remembers where it was scrolled to and ignores that echo, or the + // two would drag each other back and forth. + const top = from.scrollTop; + const isEcho = isNear( top, source.echo ); + source.echo = -1; + if ( isEcho ) { + return; + } + + // The two previews render different styles, so their heights differ: + // they're kept at the same fraction of their scroll range, not the same + // offset. + const fromRange = getScrollRange( from ); + const next = fromRange > 0 ? ( top / fromRange ) * getScrollRange( to ) : 0; + if ( isNear( to.scrollTop, next ) ) { + return; + } + + // `instant` overrides a theme's `scroll-behavior: smooth`, which would + // animate every sync. + to.scrollTo( { top: next, behavior: 'instant' } ); + target.echo = to.scrollTop; +} + +/** + * Listens for scrolling in one side's document and has the other follow. + * + * @param side The side to listen to. + * @param other The side to follow it. + * @return A function that stops listening. + */ +function listen( side: ScrollSide, other: ScrollSide ) { + // The root scroller fires `scroll` on the document, which bubbles to the + // window. + const onScroll = ( event: Event ) => { + if ( event.target === side.frame.contentDocument ) { + follow( side, other ); + } + }; + + // The frame's window is only ready once its document has loaded, which + // may be before or after the frame reaches this hook. + let view: Window | null = null; + const attach = () => { + view?.removeEventListener( 'scroll', onScroll ); + view = side.frame.contentWindow; + view?.addEventListener( 'scroll', onScroll, { passive: true } ); + }; + attach(); + side.frame.addEventListener( 'load', attach ); + + return () => { + side.frame.removeEventListener( 'load', attach ); + view?.removeEventListener( 'scroll', onScroll ); + }; +} + +/** + * Keeps two iframes scrolled to the same relative position, so their + * documents can be compared as either is scrolled. + * + * @param first The first iframe, or null to not sync. + * @param second The second iframe, or null to not sync. + */ +export default function useSyncedScroll( + first: HTMLIFrameElement | null, + second: HTMLIFrameElement | null +) { + useEffect( () => { + if ( ! first || ! second ) { + return; + } + + const firstSide = { frame: first, echo: -1 }; + const secondSide = { frame: second, echo: -1 }; + const stopFirst = listen( firstSide, secondSide ); + const stopSecond = listen( secondSide, firstSide ); + + return () => { + stopFirst(); + stopSecond(); + }; + }, [ first, second ] ); +} diff --git a/test/e2e/specs/site-editor/user-global-styles-revisions.spec.js b/test/e2e/specs/site-editor/user-global-styles-revisions.spec.js index 86574ba12bf633..43b5c8f43a0958 100644 --- a/test/e2e/specs/site-editor/user-global-styles-revisions.spec.js +++ b/test/e2e/specs/site-editor/user-global-styles-revisions.spec.js @@ -553,6 +553,236 @@ test.describe( 'Style Revisions', () => { ).toBeVisible(); } ); + test( 'should show what changed since a revision as code', async ( { + page, + userGlobalStylesRevisions, + } ) => { + await userGlobalStylesRevisions.saveRevision( stylesPostId, { + color: { background: 'blue' }, + } ); + await userGlobalStylesRevisions.saveRevision( stylesPostId, { + color: { background: 'red' }, + } ); + await userGlobalStylesRevisions.openStylesPanel(); + await page.getByRole( 'button', { name: 'Revisions' } ).click(); + + // Revisions are listed newest first, so the second one is the blue + // background saved before the current red one. + await page + .getByRole( 'option', { name: /^Changes saved by / } ) + .nth( 1 ) + .click(); + await page.getByRole( 'radio', { name: 'Code' } ).click(); + + const changes = page.getByRole( 'region', { + name: 'Changes since this revision', + } ); + await expect( + changes.getByRole( 'row', { + name: /Removed.*"background": "blue"/, + } ) + ).toBeVisible(); + await expect( + changes.getByRole( 'row', { name: /Added.*"background": "red"/ } ) + ).toBeVisible(); + + // The visual preview comes back in place of the code. + await page.getByRole( 'radio', { name: 'Visual' } ).click(); + await expect( changes ).toBeHidden(); + await expect( + page.locator( 'iframe[name="revisions"]' ) + ).toBeVisible(); + } ); + + test( 'should say when a revision matches the current styles', async ( { + page, + userGlobalStylesRevisions, + } ) => { + await userGlobalStylesRevisions.saveRevision( stylesPostId, { + color: { background: 'green' }, + } ); + await userGlobalStylesRevisions.openStylesPanel(); + await page.getByRole( 'button', { name: 'Revisions' } ).click(); + + // The newest revision is the styles the editor shows. + await page + .getByRole( 'option', { name: /^Changes saved by / } ) + .first() + .click(); + await page.getByRole( 'radio', { name: 'Code' } ).click(); + + const changes = page.getByRole( 'region', { + name: 'Changes since this revision', + } ); + await expect( changes ).toHaveText( + 'This revision matches the current styles.' + ); + await expect( changes.getByRole( 'table' ) ).toBeHidden(); + } ); + + test( 'should show the selected revision next to the current version', async ( { + page, + userGlobalStylesRevisions, + } ) => { + await userGlobalStylesRevisions.saveRevision( stylesPostId, { + color: { background: 'blue' }, + } ); + await userGlobalStylesRevisions.saveRevision( stylesPostId, { + color: { background: 'red' }, + } ); + await userGlobalStylesRevisions.openStylesPanel(); + await page.getByRole( 'button', { name: 'Revisions' } ).click(); + + // Revisions are listed newest first, so the second one is the blue + // background saved before the current red one. + await page + .getByRole( 'option', { name: /^Changes saved by / } ) + .nth( 1 ) + .click(); + + await expect( + page.frameLocator( '[name="revisions"]' ).locator( 'body' ) + ).toHaveCSS( 'background-color', 'rgb(0, 0, 255)' ); + await expect( + page.frameLocator( '[name="revisions-current"]' ).locator( 'body' ) + ).toHaveCSS( 'background-color', 'rgb(255, 0, 0)' ); + } ); + + test( 'should scroll the selected revision and the current version together', async ( { + page, + userGlobalStylesRevisions, + } ) => { + // Different padding makes the two previews scroll by different + // lengths, so following by position alone would fall out of step. + await userGlobalStylesRevisions.saveRevision( stylesPostId, { + spacing: { padding: { top: '2000px' } }, + } ); + await userGlobalStylesRevisions.saveRevision( stylesPostId, { + spacing: { padding: { top: '3000px' } }, + } ); + await userGlobalStylesRevisions.openStylesPanel(); + await page.getByRole( 'button', { name: 'Revisions' } ).click(); + + // Revisions are listed newest first, so the second one is the + // smaller padding saved before the current one. + await page + .getByRole( 'option', { name: /^Changes saved by / } ) + .nth( 1 ) + .click(); + + await expect( + page.frameLocator( '[name="revisions"]' ).locator( 'body' ) + ).toHaveCSS( 'padding-top', '2000px' ); + await expect( + page.frameLocator( '[name="revisions-current"]' ).locator( 'body' ) + ).toHaveCSS( 'padding-top', '3000px' ); + + const selected = await ( + await page.locator( 'iframe[name="revisions"]' ).elementHandle() + ).contentFrame(); + const current = await ( + await page + .locator( 'iframe[name="revisions-current"]' ) + .elementHandle() + ).contentFrame(); + const scrollTo = ( frame, fraction ) => + frame.evaluate( ( _fraction ) => { + const scroller = document.scrollingElement; + scroller.scrollTo( { + top: + _fraction * + ( scroller.scrollHeight - scroller.clientHeight ), + behavior: 'instant', + } ); + }, fraction ); + const getScrollFraction = ( frame ) => + frame.evaluate( () => { + const scroller = document.scrollingElement; + return ( + scroller.scrollTop / + ( scroller.scrollHeight - scroller.clientHeight ) + ); + } ); + + // Halfway down the selected revision is halfway down the current + // version, though the current version is the longer of the two. + await scrollTo( selected, 0.5 ); + await expect + .poll( () => getScrollFraction( current ) ) + .toBeCloseTo( 0.5, 1 ); + + // Either one can lead. + await scrollTo( current, 0 ); + await expect.poll( () => getScrollFraction( selected ) ).toBe( 0 ); + } ); + + test( 'should show a single preview when the current version is selected', async ( { + page, + userGlobalStylesRevisions, + } ) => { + await userGlobalStylesRevisions.saveRevision( stylesPostId, { + color: { background: 'green' }, + } ); + await userGlobalStylesRevisions.openStylesPanel(); + await page.getByRole( 'button', { name: 'Revisions' } ).click(); + + // The newest revision is the styles the editor shows. + await page + .getByRole( 'option', { name: /^Changes saved by / } ) + .first() + .click(); + + await expect( + page.locator( 'iframe[name="revisions"]' ) + ).toBeVisible(); + await expect( + page.locator( 'iframe[name="revisions-current"]' ) + ).toBeHidden(); + } ); + + test( 'should keep unsaved changes in the current version after comparing', async ( { + page, + editor, + userGlobalStylesRevisions, + } ) => { + await userGlobalStylesRevisions.saveRevision( stylesPostId, { + color: { background: 'blue' }, + } ); + await userGlobalStylesRevisions.openStylesPanel(); + await page.getByRole( 'button', { name: 'Background styles' } ).click(); + await page + .getByRole( 'button', { name: 'Color', exact: true } ) + .click(); + await page + .getByRole( 'option', { name: 'Luminous vivid amber' } ) + .click( { force: true } ); + await page.getByRole( 'button', { name: 'Revisions' } ).click(); + + // Compare the saved revision with the unsaved changes. + await page + .getByRole( 'option', { name: /^Changes saved by / } ) + .first() + .click(); + await expect( + page.frameLocator( '[name="revisions"]' ).locator( 'body' ) + ).toHaveCSS( 'background-color', 'rgb(0, 0, 255)' ); + await expect( + page.frameLocator( '[name="revisions-current"]' ).locator( 'body' ) + ).toHaveCSS( 'background-color', 'rgb(252, 185, 0)' ); + + // Back on the current version, the unsaved changes still show. + await page.getByRole( 'option', { name: /^Unsaved changes/ } ).click(); + await expect( + page.locator( 'iframe[name="revisions-current"]' ) + ).toBeHidden(); + await expect( + page.frameLocator( '[name="revisions"]' ).locator( 'body' ) + ).toHaveCSS( 'background-color', 'rgb(252, 185, 0)' ); + + // Later tests start from saved styles. + await editor.saveSiteEditorEntities(); + } ); + test( 'should paginate', async ( { page, userGlobalStylesRevisions } ) => { // Create > 10 revisions to display pagination navigation component. for ( let i = 9; i < 21; i++ ) {