diff --git a/projects/packages/sharing-likes/AGENTS.md b/projects/packages/sharing-likes/AGENTS.md index a8feda79219d..aa463ea69267 100644 --- a/projects/packages/sharing-likes/AGENTS.md +++ b/projects/packages/sharing-likes/AGENTS.md @@ -67,6 +67,12 @@ back, which is why that one removal asks first instead of offering Undo. Deletin a custom service leaves its ID in `sharing-services`, so `useCustomService` saves the lists again without it. +In `BLOCK_CALL_TO_ACTION`, `TemplatePlacements` replaces the Site Editor link with +two cards per section, saving the template placements (see "Template placements" +below). Each save sends a one-item list, or an empty one, so ticking one card +unticks the other. It falls back to the Site Editor link only where `settings` does +not offer the key and no write is pending; while one is, the cards show disabled. + ## Per-post switches `Post_Likes_Switch` and `Post_Sharing_Switch` own the Likes and Sharing switches diff --git a/projects/packages/sharing-likes/changelog/add-sharing-likes-placement-cards b/projects/packages/sharing-likes/changelog/add-sharing-likes-placement-cards new file mode 100644 index 000000000000..5b707102e96b --- /dev/null +++ b/projects/packages/sharing-likes/changelog/add-sharing-likes-placement-cards @@ -0,0 +1,4 @@ +Significance: minor +Type: added + +Add cards to the React version of Settings > Sharing that place the Sharing Buttons and Like blocks before or after the content of posts and pages. diff --git a/projects/packages/sharing-likes/src/settings-app/components/feature-variant.tsx b/projects/packages/sharing-likes/src/settings-app/components/feature-variant.tsx index 7ca67c79e0d0..1a530c58136d 100644 --- a/projects/packages/sharing-likes/src/settings-app/components/feature-variant.tsx +++ b/projects/packages/sharing-likes/src/settings-app/components/feature-variant.tsx @@ -4,6 +4,7 @@ import { Button, ButtonLink, Notice, Stack, Text } from '@wordpress/ui'; import { useStatus } from '../data/queries'; import { useFeatureAction } from '../data/use-feature-action'; import { SECTION_GAP, SettingGroup } from './section-card'; +import { TemplatePlacements } from './template-placements'; import type { Feature, SectionState } from '../types'; import type { JSX, ReactNode } from 'react'; @@ -91,14 +92,19 @@ export function FeatureVariant( { switch ( state ) { case 'block_call_to_action': content = ( - - }>{ copy.addBlock } -
- - { __( 'Open Site Editor', 'jetpack-sharing-likes' ) } - -
-
+ + }>{ copy.addBlock } +
+ + { __( 'Open Site Editor', 'jetpack-sharing-likes' ) } + +
+ + } + /> ); break; case 'off': diff --git a/projects/packages/sharing-likes/src/settings-app/components/placement-illustrations.tsx b/projects/packages/sharing-likes/src/settings-app/components/placement-illustrations.tsx new file mode 100644 index 000000000000..078aabdb0693 --- /dev/null +++ b/projects/packages/sharing-likes/src/settings-app/components/placement-illustrations.tsx @@ -0,0 +1,166 @@ +import type { TemplatePlacement } from '../types'; +import type { JSX } from 'react'; + +export type PlacedBlock = 'sharing-buttons' | 'like'; + +// Ten lines of post content, as Newsletter's wireframes draw them. +const LINE_WIDTHS = [ 139.44, 145.32, 141.96, 143.64, 142.8, 144.48, 143.64, 139.44, 145.32, 96 ]; +const LINE_GAP = 4.62; +const COLUMN_X = 74; +const TITLE_Y = 50; +const ROW_HEIGHT = 14; + +/** + * Points of a five-pointed star, the Like button's icon. + * + * @param cx - Centre x. + * @param cy - Centre y. + * @param r - Outer radius. + * @return SVG polygon points. + */ +function starPoints( cx: number, cy: number, r: number ): string { + return Array.from( { length: 10 }, ( _, i ) => { + const radius = i % 2 ? r * 0.45 : r; + const angle = ( Math.PI / 5 ) * i - Math.PI / 2; + return `${ cx + radius * Math.cos( angle ) },${ cy + radius * Math.sin( angle ) }`; + } ).join( ' ' ); +} + +/** + * A row of share buttons. + * + * @param props - Props. + * @param props.y - Top of the row. + * @return Row. + */ +function SharingButtonsRow( { y }: { y: number } ): JSX.Element { + return ( + + { [ 0, 1, 2, 3 ].map( index => ( + + + + + ) ) } + + ); +} + +/** + * A Like button and the avatars of a few readers who liked the post. + * + * @param props - Props. + * @param props.y - Top of the row. + * @return Row. + */ +function LikeRow( { y }: { y: number } ): JSX.Element { + const middle = y + ROW_HEIGHT / 2; + + return ( + + + + + { [ 0, 1, 2 ].map( index => ( + + ) ) } + + + ); +} + +/** + * Wireframe of a post with the block before or after its content, drawn 294×192 to fill a `CheckboxCard`. + * + * @param props - Props. + * @param props.block - Block being placed. + * @param props.placement - Where it goes. + * @return Decorative SVG. + */ +export function PlacementIllustration( { + block, + placement, +}: { + block: PlacedBlock; + placement: TemplatePlacement; +} ): JSX.Element { + const blockFirst = placement === 'before_content'; + const contentY = TITLE_Y + 16 + ( blockFirst ? ROW_HEIGHT + 12 : 0 ); + const rowY = blockFirst ? TITLE_Y + 16 : contentY + LINE_WIDTHS.length * LINE_GAP + 8; + const Row = block === 'like' ? LikeRow : SharingButtonsRow; + + return ( + + ); +} diff --git a/projects/packages/sharing-likes/src/settings-app/components/template-placements.tsx b/projects/packages/sharing-likes/src/settings-app/components/template-placements.tsx new file mode 100644 index 000000000000..42ce14673286 --- /dev/null +++ b/projects/packages/sharing-likes/src/settings-app/components/template-placements.tsx @@ -0,0 +1,130 @@ +import CheckboxCard, { CheckboxCardGrid } from '@automattic/jetpack-components/checkbox-card'; +import { createInterpolateElement, useCallback } from '@wordpress/element'; +import { __, _x } from '@wordpress/i18n'; +import { Fieldset, Link, Text } from '@wordpress/ui'; +import { useIsSaving, useSettings, useStatus } from '../data/queries'; +import { useSaveSetting } from '../data/use-save-setting'; +import { PlacementIllustration, type PlacedBlock } from './placement-illustrations'; +import { SettingGroup } from './section-card'; +import type { Feature, TemplatePlacement } from '../types'; +import type { JSX, ReactNode } from 'react'; + +const SETTING_KEYS = { + sharing: 'sharing_buttons_auto_add', + likes: 'likes_auto_add', +} as const; + +const PLACED_BLOCKS: Record< Feature, PlacedBlock > = { + sharing: 'sharing-buttons', + likes: 'like', +}; + +const PLACEMENTS: TemplatePlacement[] = [ 'before_content', 'after_content' ]; + +/** + * The copy for each feature, one complete sentence per string. + * + * @param feature - Feature. + * @return Copy. + */ +function copyFor( feature: Feature ) { + return { + legend: + feature === 'sharing' + ? __( 'Add the Sharing Buttons block to posts and pages', 'jetpack-sharing-likes' ) + : __( 'Add the Like block to posts and pages', 'jetpack-sharing-likes' ), + before: _x( 'Before the content', 'Where the block goes', 'jetpack-sharing-likes' ), + after: _x( 'After the content', 'Where the block goes', 'jetpack-sharing-likes' ), + }; +} + +/** + * Cards that add the feature's block before or after the content of single posts and pages. + * + * @param props - Props. + * @param props.feature - Feature. + * @param props.fallback - Shown where the settings do not offer the placements. + * @return Cards, or the fallback. + */ +export function TemplatePlacements( { + feature, + fallback, +}: { + feature: Feature; + fallback: ReactNode; +} ): JSX.Element { + const status = useStatus(); + const key = SETTING_KEYS[ feature ]; + const offered = useSettings()?.[ key ]; + const selected = offered ?? []; + const saveSetting = useSaveSetting(); + // While a write is pending the stored settings may not be what the server has yet. A feature action + // counts until settings are read again, so right after "Switch to the … block" the key can still be missing. + const saving = useIsSaving(); + + const handleChange = useCallback( + ( name: string, next: boolean ) => { + // The block goes on one side only, so ticking a card replaces the other. + saveSetting( key, next ? [ name as TemplatePlacement ] : [] ); + }, + [ key, saveSetting ] + ); + + if ( ! offered && ! saving ) { + return <>{ fallback }; + } + + const copy = copyFor( feature ); + const block = PLACED_BLOCKS[ feature ]; + const previewUrl = status?.site_editor_url ?? ''; + const pageTemplateUrl = status?.page_template_editor_url ?? ''; + + return ( + + + { copy.legend } + + { __( 'Pick one place: before or after the content.', 'jetpack-sharing-likes' ) } + + + { PLACEMENTS.map( placement => ( + } + checked={ selected.includes( placement ) } + onChange={ handleChange } + previewUrl={ + // The template only has the block once the save has gone through. + selected.includes( placement ) && ! saving ? previewUrl : undefined + } + disabled={ ! offered } + /> + ) ) } + + { /* Not Fieldset.Details: the fieldset takes one description, and it would replace the hint above. */ } + + { pageTemplateUrl && ( + }> + { createInterpolateElement( + __( + 'Want pages to look different? Edit the page template.', + 'jetpack-sharing-likes' + ), + { link: } + ) } + + ) } + }> + { __( + 'Once you’ve saved a template in the Site Editor, move or remove its blocks there: picking a place here won’t move a block that template already has, or bring back one you removed.', + 'jetpack-sharing-likes' + ) } + + + + + ); +} diff --git a/projects/packages/sharing-likes/src/settings-app/sections/placement-section.tsx b/projects/packages/sharing-likes/src/settings-app/sections/placement-section.tsx index f3a51ad3550b..ea7b83e1259f 100644 --- a/projects/packages/sharing-likes/src/settings-app/sections/placement-section.tsx +++ b/projects/packages/sharing-likes/src/settings-app/sections/placement-section.tsx @@ -36,14 +36,26 @@ export function PlacementSection(): JSX.Element | null { return null; } + // A section that offers its block sits next to this one, and the block ignores these choices. + const offersBlock = + status.sharing.state === 'block_call_to_action' || + ( status.likes.state === 'block_call_to_action' && status.likes.supported ); + return ( + { __( + 'These choices apply to every feature named in the heading.', + 'jetpack-sharing-likes' + ) } + { offersBlock && + ' ' + + __( 'Blocks you add to your templates aren’t affected.', 'jetpack-sharing-likes' ) } + + } > diff --git a/projects/packages/sharing-likes/src/settings-app/style.scss b/projects/packages/sharing-likes/src/settings-app/style.scss index 49a46140dc88..cf3f20d87a5e 100644 --- a/projects/packages/sharing-likes/src/settings-app/style.scss +++ b/projects/packages/sharing-likes/src/settings-app/style.scss @@ -29,3 +29,27 @@ body.settings_page_sharing { .jetpack-sharing-likes__variant:focus { outline: none; } + +// Placement card wireframes; the card paints the background. +.jetpack-sharing-likes__wireframe-line { + fill: var(--wpds-color-stroke-surface-neutral); +} + +.jetpack-sharing-likes__wireframe-block { + fill: var(--wpds-color-background-interactive-brand-strong); +} + +.jetpack-sharing-likes__wireframe-surface { + fill: var(--wpds-color-background-surface-neutral-strong); +} + +.jetpack-sharing-likes__wireframe-button { + fill: var(--wpds-color-background-surface-neutral-strong); + stroke: var(--wpds-color-background-interactive-brand-strong); +} + +.jetpack-sharing-likes__wireframe-avatar { + fill: var(--wpds-color-stroke-surface-neutral-strong); + stroke: var(--wpds-color-background-surface-neutral-strong); + stroke-width: 1.5; +} diff --git a/projects/packages/sharing-likes/src/settings-app/test/feature-variant.test.tsx b/projects/packages/sharing-likes/src/settings-app/test/feature-variant.test.tsx index 9df3f9217d3d..1dd94ac001b5 100644 --- a/projects/packages/sharing-likes/src/settings-app/test/feature-variant.test.tsx +++ b/projects/packages/sharing-likes/src/settings-app/test/feature-variant.test.tsx @@ -49,7 +49,7 @@ describe( 'FeatureVariant', () => { [ 'likes', 'block_call_to_action', [ 'Add the Like block to your theme’s template.' ], null ], [ 'likes', 'off', [ 'Like buttons are turned off for this site.' ], 'Turn on Like buttons' ], ] as [ Feature, SectionState, string[], string | null ][] )( - '%s %s', + '%s %s, on a server that does not offer the placements', ( feature, state, texts, button ) => { renderWithData( diff --git a/projects/packages/sharing-likes/src/settings-app/test/placement-section.test.tsx b/projects/packages/sharing-likes/src/settings-app/test/placement-section.test.tsx index 0c97266277a6..6b3b252e3a44 100644 --- a/projects/packages/sharing-likes/src/settings-app/test/placement-section.test.tsx +++ b/projects/packages/sharing-likes/src/settings-app/test/placement-section.test.tsx @@ -3,6 +3,7 @@ import userEvent from '@testing-library/user-event'; import apiFetch from '@wordpress/api-fetch'; import { PlacementSection } from '../sections/placement-section'; import { apiCalls, baseSettings, baseStatus, renderWithData, setScriptData } from './helpers'; +import type { Status } from '../types'; jest.mock( '@wordpress/api-fetch' ); const mockApiFetch = apiFetch as jest.MockedFunction< typeof apiFetch >; @@ -30,6 +31,27 @@ describe( 'PlacementSection', () => { ).not.toBeChecked(); } ); + // Unticking Pages here doesn't keep the Sharing Buttons or Like block off pages. + it.each( [ + [ 'sharing', { ...baseStatus, sharing: { state: 'block_call_to_action' } }, true ], + [ 'likes', { ...baseStatus, likes: { state: 'block_call_to_action', supported: true } }, true ], + [ + 'offline likes', + { ...baseStatus, likes: { state: 'block_call_to_action', supported: false } }, + false, + ], + [ 'no', baseStatus, false ], + ] as [ string, Status, boolean ][] )( + 'with %s section on the block, says blocks are not affected: %s', + ( _section, status, shown ) => { + renderWithData( , { status } ); + + expect( + screen.queryByText( /Blocks you add to your templates aren’t affected\./ ) !== null + ).toBe( shown ); + } + ); + it( 'saves the whole list when one place changes', async () => { const user = userEvent.setup(); renderWithData( ); diff --git a/projects/packages/sharing-likes/src/settings-app/test/template-placements.test.tsx b/projects/packages/sharing-likes/src/settings-app/test/template-placements.test.tsx new file mode 100644 index 000000000000..1620de9197d7 --- /dev/null +++ b/projects/packages/sharing-likes/src/settings-app/test/template-placements.test.tsx @@ -0,0 +1,187 @@ +import { screen, waitFor, within } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import apiFetch from '@wordpress/api-fetch'; +import { TemplatePlacements } from '../components/template-placements'; +import { LikeButtonsSection } from '../sections/like-buttons-section'; +import { apiCalls, baseSettings, baseStatus, renderWithData, setScriptData } from './helpers'; +import type { Feature, Settings, Status, TemplatePlacement } from '../types'; + +jest.mock( '@wordpress/api-fetch' ); +const mockApiFetch = apiFetch as jest.MockedFunction< typeof apiFetch >; + +const PAGE_TEMPLATE_URL = 'https://example.com/wp-admin/site-editor.php?p=page'; + +const KEYS = { sharing: 'sharing_buttons_auto_add', likes: 'likes_auto_add' } as const; + +/** + * A promise and the functions that settle it. + * + * @return Deferred. + */ +function deferred< T >() { + let resolve!: ( value: T ) => void; + let reject!: ( reason: unknown ) => void; + const promise = new Promise< T >( ( res, rej ) => { + resolve = res; + reject = rej; + } ); + return { promise, resolve, reject }; +} + +/** + * Render the cards with a placement list for the feature. + * + * @param feature - Feature. + * @param stored - The feature's placements. + * @param status - Status overrides. + * @return Render result. + */ +function renderCards( + feature: Feature, + stored: TemplatePlacement[], + status: Partial< Status > = {} +) { + return renderWithData( fallback

} />, { + status: { ...baseStatus, ...status }, + settings: { ...baseSettings, [ KEYS[ feature ] ]: stored }, + } ); +} + +/** + * The card's checkbox. + * + * @param name - Card title. + * @return Checkbox. + */ +function card( name: string ) { + return screen.getByRole( 'checkbox', { name } ); +} + +/** + * The "Preview and edit" links, by the card title they sit under. + * + * @return Titles of the cards showing a link. + */ +function cardsWithPreview(): string[] { + return [ 'Before the content', 'After the content' ].filter( title => + within( screen.getByText( title ).parentElement as HTMLElement ).queryByRole( 'link', { + name: 'Preview and edit', + } ) + ); +} + +beforeEach( () => { + mockApiFetch.mockReset(); + setScriptData(); +} ); + +afterEach( () => { + delete ( window as unknown as { JetpackScriptData?: unknown } ).JetpackScriptData; +} ); + +describe( 'TemplatePlacements', () => { + it.each( [ + [ 'sharing', [ 'after_content' ], 'Before the content', [ 'before_content' ] ], + [ 'likes', [ 'after_content' ], 'After the content', [] ], + ] as [ Feature, TemplatePlacement[], string, TemplatePlacement[] ][] )( + '%s: from %j, clicking "%s" saves and ticks %j', + async ( feature, stored, clicked, sent ) => { + const user = userEvent.setup(); + mockApiFetch.mockImplementation( ( { data } ) => + Promise.resolve( { ...baseSettings, ...( data as Settings ) } ) + ); + renderCards( feature, stored ); + + await user.click( card( clicked ) ); + + expect( apiCalls( 'PUT' ) ).toEqual( [ + { + path: '/wpcom/v2/sharing-likes/settings', + method: 'PUT', + data: { [ KEYS[ feature ] ]: sent }, + }, + ] ); + expect( card( 'Before the content' ) ).toHaveAttribute( + 'aria-checked', + String( sent.includes( 'before_content' ) ) + ); + expect( card( 'After the content' ) ).toHaveAttribute( + 'aria-checked', + String( sent.includes( 'after_content' ) ) + ); + } + ); + + it( 'only links a ticked card once its save lands', async () => { + const user = userEvent.setup(); + const save = deferred< Settings >(); + mockApiFetch.mockImplementation( ( { method } ) => + method === 'PUT' ? save.promise : Promise.resolve( baseStatus ) + ); + renderCards( 'sharing', [ 'after_content' ] ); + + expect( cardsWithPreview() ).toEqual( [ 'After the content' ] ); + await user.click( card( 'Before the content' ) ); + + expect( card( 'Before the content' ) ).toHaveAttribute( 'aria-checked', 'true' ); + expect( card( 'After the content' ) ).not.toHaveAttribute( 'aria-disabled', 'true' ); + expect( cardsWithPreview() ).toEqual( [] ); + save.resolve( { ...baseSettings, sharing_buttons_auto_add: [ 'before_content' ] } ); + await waitFor( () => expect( cardsWithPreview() ).toEqual( [ 'Before the content' ] ) ); + expect( screen.getByRole( 'link', { name: 'Preview and edit' } ) ).toHaveAttribute( + 'href', + baseStatus.site_editor_url + ); + } ); + + it.each( [ PAGE_TEMPLATE_URL, '' ] )( + 'links the page template only with a URL, keeping the notes: "%s"', + url => { + renderCards( 'sharing', [], { page_template_editor_url: url } ); + + // By text: an anchor with an empty href has no link role, so a role query would pass on a broken link. + expect( screen.queryByText( 'Edit the page template' )?.getAttribute( 'href' ) ).toBe( + url || undefined + ); + expect( + screen.getByText( /Once you’ve saved a template in the Site Editor/ ) + ).toBeInTheDocument(); + expect( screen.getByRole( 'group' ) ).toHaveAccessibleDescription( + 'Pick one place: before or after the content.' + ); + } + ); + + it( 'shows the cards disabled, not the Site Editor button, while settings catch up with a switch', async () => { + const user = userEvent.setup(); + const settings = deferred< Settings >(); + mockApiFetch.mockImplementation( ( { path, method } ) => { + if ( method === 'POST' ) { + return Promise.resolve( { + ...baseStatus, + likes: { state: 'block_call_to_action', supported: true }, + } ); + } + return path?.endsWith( '/settings' ) ? settings.promise : Promise.resolve( baseStatus ); + } ); + renderWithData( , { + status: { ...baseStatus, likes: { state: 'configure_with_block_nudge', supported: true } }, + } ); + + await user.click( screen.getByRole( 'button', { name: 'Switch to the Like block' } ) ); + + await waitFor( () => expect( screen.getAllByRole( 'checkbox' ) ).toHaveLength( 2 ) ); + screen + .getAllByRole( 'checkbox' ) + .forEach( checkbox => expect( checkbox ).toHaveAttribute( 'aria-disabled', 'true' ) ); + const group = screen.getByRole( 'group', { name: 'Add the Like block to posts and pages' } ); + expect( group ).toHaveAttribute( 'aria-busy', 'true' ); + expect( screen.queryByRole( 'link', { name: 'Open Site Editor' } ) ).not.toBeInTheDocument(); + + settings.resolve( { ...baseSettings, likes_auto_add: [] } ); + await waitFor( () => + expect( card( 'Before the content' ) ).not.toHaveAttribute( 'aria-disabled', 'true' ) + ); + expect( group ).toHaveAttribute( 'aria-busy', 'false' ); + } ); +} ); diff --git a/projects/packages/sharing-likes/src/settings-app/test/use-save-setting.test.tsx b/projects/packages/sharing-likes/src/settings-app/test/use-save-setting.test.tsx index b7ac5112cd4f..1deeeaddf473 100644 --- a/projects/packages/sharing-likes/src/settings-app/test/use-save-setting.test.tsx +++ b/projects/packages/sharing-likes/src/settings-app/test/use-save-setting.test.tsx @@ -10,7 +10,7 @@ import { snackbarMessages, wrapperFor, } from './helpers'; -import type { Settings } from '../types'; +import type { SettingKey, Settings } from '../types'; jest.mock( '@wordpress/api-fetch' ); const mockApiFetch = apiFetch as jest.MockedFunction< typeof apiFetch >; @@ -76,28 +76,34 @@ describe( 'useSaveSetting', () => { expect( registry.select( store ).getSettings() ).toEqual( saved ); } ); - it( 'rolls back and shows the server message when a save fails', async () => { - mockApiFetch.mockImplementation( ( { method, path } ) => { - if ( method === 'PUT' ) { - return Promise.reject( { - code: 'rest_sharing_likes_comment_likes_unchanged', - message: 'Comment Likes could not be switched on or off on this site.', - } ); - } - // A settings read that never lands, so only the rollback can restore the value. - return path?.endsWith( '/status' ) ? Promise.resolve( baseStatus ) : new Promise( () => {} ); - } ); - const { result, registry } = renderSave(); + it.each( [ + [ 'comment_likes_enabled', true ], + [ 'show', [ 'post' ] ], + ] as [ SettingKey, Settings[ SettingKey ] ][] )( + 'rolls %s back and shows the server message when a save fails', + async ( key, value ) => { + mockApiFetch.mockImplementation( ( { method, path } ) => { + if ( method === 'PUT' ) { + return Promise.reject( { + code: 'rest_sharing_likes_comment_likes_unchanged', + message: 'Comment Likes could not be switched on or off on this site.', + } ); + } + // A settings read that never lands, so only the rollback can restore the value. + return path?.endsWith( '/status' ) + ? Promise.resolve( baseStatus ) + : new Promise( () => {} ); + } ); + const { result, registry } = renderSave(); - await act( () => result.current( 'comment_likes_enabled', true ) ); + await act( () => result.current( key, value ) ); - expect( registry.select( store ).getSettings() ).toMatchObject( { - comment_likes_enabled: false, - } ); - expect( snackbarMessages() ).toContain( - 'Comment Likes could not be switched on or off on this site.' - ); - } ); + expect( registry.select( store ).getSettings()?.[ key ] ).toEqual( baseSettings[ key ] ); + expect( snackbarMessages() ).toContain( + 'Comment Likes could not be switched on or off on this site.' + ); + } + ); it.each( [ {