Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
import { getRedirectUrl } from '@automattic/jetpack-components';
import { __ } from '@wordpress/i18n';
import { InputControl, Link, Stack, SwitchControl, Text } from '@wordpress/ui';
import { useCallback, useId, useState } from 'react';
import { PanelModuleToggle } from './panel-module-toggle';
import styles from './styles.module.scss';
import { useModuleOption, useModuleSetting } from './use-module-option';
import type { ModuleSettingsProps } from './registry';

/**
* The Comments options.
*
* @param props - Component props.
* @param props.module - The module.
* @param props.disabled - Whether the site cannot use the module.
* @return The settings.
*/
export function CommentsSettings( { module: $module, disabled }: ModuleSettingsProps ) {
const blocks = useModuleOption( $module, 'enable_blocks_comments' );
const prompt = useModuleSetting( $module, 'highlander_comment_form_prompt', v =>
String( v ?? '' )
);
// The introduction as typed, until it is saved; null shows the stored one.
const [ draft, setDraft ] = useState< string | null >( null );
const optionsDisabled = ! $module.activated || disabled;
const labelId = useId();
// Jetpack versions without block comments do not send the option.
const blocksAvailable =
! Array.isArray( $module.options ) && undefined !== $module.options?.enable_blocks_comments;

const { value: storedPrompt, setValue: savePrompt } = prompt;
// Saved on blur.
const onBlur = useCallback( async () => {
if ( draft === null || draft === storedPrompt ) {
return;
}
if ( await savePrompt( draft ) ) {
setDraft( null );
}
}, [ draft, storedPrompt, savePrompt ] );

return (
<Stack direction="column" gap="lg">
<Text variant="body-md">
{ __(
'Replace the standard WordPress comment form with one that lets readers comment with their social media accounts.',
'jetpack-my-jetpack'
) }
</Text>
<Link
href={ getRedirectUrl( 'jetpack-support-comments' ) }
target="_blank"
rel="noopener noreferrer"
>
{ __( 'Learn more about Comments', 'jetpack-my-jetpack' ) }
</Link>

<Stack
direction="row"
align="center"
justify="space-between"
className={ styles[ 'settings-panel__toggle' ] }
>
<Text variant="body-md" id={ labelId }>
{ __( 'Use the Jetpack comment form', 'jetpack-my-jetpack' ) }
</Text>
<PanelModuleToggle module={ $module } labelledby={ labelId } disabled={ disabled } />
</Stack>

{ blocksAvailable && (
<SwitchControl
label={ __( 'Enable blocks in comments', 'jetpack-my-jetpack' ) }
checked={ blocks.value }
disabled={ optionsDisabled || blocks.isSaving }
onCheckedChange={ blocks.setValue }
/>
) }
<InputControl
label={ __( 'Comment form introduction', 'jetpack-my-jetpack' ) }
description={ __(
'A few catchy words to motivate your visitors to comment.',
'jetpack-my-jetpack'
) }
value={ draft ?? storedPrompt }
onValueChange={ setDraft }
onBlur={ onBlur }
disabled={ optionsDisabled || prompt.isSaving }
/>
</Stack>
);
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { CarouselSettings } from './carousel';
import { CommentsSettings } from './comments';
import { GoogleAnalyticsSettings } from './google-analytics';
import { InfiniteScrollSettings } from './infinite-scroll';
import { MarkdownSettings } from './markdown';
Expand All @@ -23,6 +24,7 @@ export type ModuleSettingsProps = {
*/
export const moduleSettings: Record< string, ComponentType< ModuleSettingsProps > > = {
carousel: CarouselSettings,
comments: CommentsSettings,
'infinite-scroll': InfiniteScrollSettings,
markdown: MarkdownSettings,
'post-by-email': PostByEmailSettings,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
import { render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import apiFetch from '@wordpress/api-fetch';
import { CommentsSettings } from '../comments';
import type { MyJetpackModule } from '../../../types';

jest.mock( '@wordpress/api-fetch', () => jest.fn() );
jest.mock( '@automattic/jetpack-shared-stores', () => ( { store: {} } ) );
jest.mock( '@wordpress/notices', () => ( { store: 'core/notices' } ) );
jest.mock( '@wordpress/data', () => ( {
useDispatch: () => ( {
fetchModules: jest.fn(),
createErrorNotice: jest.fn(),
createSuccessNotice: jest.fn(),
} ),
} ) );
jest.mock( '../../../hooks/use-analytics', () => ( {
__esModule: true,
default: () => ( { recordEvent: jest.fn() } ),
} ) );
jest.mock( '../../module-toggle', () => ( {
ModuleToggle: ( { labelledby, disabled }: { labelledby?: string; disabled?: boolean } ) => (
<input type="checkbox" aria-labelledby={ labelledby } disabled={ disabled } />
),
} ) );

const mockFetch = apiFetch as unknown as jest.Mock;

const build = ( overrides: Partial< MyJetpackModule > = {} ) =>
( {
module: 'comments',
name: 'Comments',
activated: true,
override: false,
options: {
enable_blocks_comments: { current_value: true },
highlander_comment_form_prompt: { current_value: 'Leave a Reply' },
},
...overrides,
} ) as unknown as MyJetpackModule;

const blocksSwitch = () => screen.queryByRole( 'switch', { name: 'Enable blocks in comments' } );
const introField = () => screen.getByRole( 'textbox', { name: 'Comment form introduction' } );
const posts = () => mockFetch.mock.calls.map( ( [ options ] ) => options.data );

beforeEach( () => {
jest.clearAllMocks();
mockFetch.mockResolvedValue( {} );
} );

describe( 'CommentsSettings', () => {
it.each( [
[ 'offers', 'Jetpack sends it', {}, true ],
[
'hides',
'an older Jetpack leaves it out',
{ options: { highlander_comment_form_prompt: { current_value: '' } } },
false,
],
[ 'hides', 'Jetpack sends no options', { options: [] }, false ],
] )( '%s the blocks option when %s', ( _verb, _when, overrides, shown ) => {
render(
<CommentsSettings
module={ build( overrides as Partial< MyJetpackModule > ) }
disabled={ false }
/>
);

expect( blocksSwitch() !== null ).toBe( shown );
} );

it( 'saves the blocks option on its own', async () => {
render( <CommentsSettings module={ build() } disabled={ false } /> );
await userEvent.click( blocksSwitch()! );

expect( posts() ).toEqual( [ { enable_blocks_comments: false } ] );
} );

it( 'saves the introduction on blur, and only when it changed', async () => {
render( <CommentsSettings module={ build() } disabled={ false } /> );

await userEvent.click( introField() );
await userEvent.tab();
expect( posts() ).toHaveLength( 0 );

await userEvent.clear( introField() );
await userEvent.type( introField(), 'Say hello' );
expect( posts() ).toHaveLength( 0 );
await userEvent.tab();

await waitFor( () =>
expect( posts() ).toEqual( [ { highlander_comment_form_prompt: 'Say hello' } ] )
);
} );

it( 'locks the introduction while it saves, and keeps the typed text when the save fails', async () => {
let failSave: () => void = () => undefined;
mockFetch.mockImplementation(
() =>
new Promise( ( _resolve, reject ) => {
failSave = () => reject( new Error( 'nope' ) );
} )
);
render( <CommentsSettings module={ build() } disabled={ false } /> );

await userEvent.clear( introField() );
await userEvent.type( introField(), 'Say hello' );
await userEvent.tab();
expect( introField() ).toBeDisabled();

failSave();
await waitFor( () => expect( introField() ).toBeEnabled() );
expect( introField() ).toHaveValue( 'Say hello' );
} );

it.each( [
[ 'the module is off', { activated: false }, false ],
[ 'the site cannot use it', {}, true ],
] )( 'locks the options when %s', ( _name, overrides, disabled ) => {
render( <CommentsSettings module={ build( overrides ) } disabled={ disabled } /> );

expect( blocksSwitch() ).toHaveAttribute( 'aria-disabled', 'true' );
expect( introField() ).toBeDisabled();
} );

it( 'locks the module switch when the site cannot use it', () => {
render( <CommentsSettings module={ build() } disabled /> );

expect(
screen.getByRole( 'checkbox', { name: 'Use the Jetpack comment form' } )
).toBeDisabled();
} );
} );
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ type ModuleOptionValue = boolean | string;
* @param $module - The module that owns the option.
* @param name - The option name, such as `carousel_background_color`.
* @param parse - Turns the stored `current_value` into the value to show.
* @return The value to show, whether a save is running, and the setter.
* @return The value to show, whether a save is running, and the setter, which resolves to whether the save worked.
*/
export function useModuleSetting< T extends ModuleOptionValue >(
$module: MyJetpackModule,
Expand All @@ -44,10 +44,12 @@ export function useModuleSetting< T extends ModuleOptionValue >(
createSuccessNotice( __( 'Updated settings.', 'jetpack-my-jetpack' ), {
type: 'snackbar',
} );
return true;
} catch {
createErrorNotice( __( 'Failed to save the setting.', 'jetpack-my-jetpack' ), {
type: 'snackbar',
} );
return false;
} finally {
setRequested( null );
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
Significance: patch
Type: changed
Comment: Settings panel: Add the Comments settings, behind the settings consolidation flag.


2 changes: 1 addition & 1 deletion projects/packages/my-jetpack/src/class-initializer.php
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,7 @@ class Initializer {
/**
* Modules whose Jetpack settings link opens in the Features panel. A subset of `moduleSettings` in `settings-panel/registry.ts`; see there for which modules stay out.
*/
public const SETTINGS_PANEL_MODULES = array( 'carousel', 'infinite-scroll', 'markdown', 'post-by-email', 'related-posts' );
public const SETTINGS_PANEL_MODULES = array( 'carousel', 'comments', 'infinite-scroll', 'markdown', 'post-by-email', 'related-posts' );

/**
* Holds info/data about the site (from the /sites/%d endpoint)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,11 @@ const SettingsNavTabs = props => {
) {
visibleTabs.push( '/sharing' );
}
if ( hasModules( [ 'comments', 'gravatar-hovercards', 'markdown' ] ) ) {
// Once settings move out, admins find every Discussion setting in Features.
if (
! isSettingsConsolidationEnabled() &&
hasModules( [ 'comments', 'gravatar-hovercards', 'markdown' ] )
) {
visibleTabs.push( '/discussion' );
}
if (
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,9 @@ describe( 'SettingsNavTabs', () => {
[ 'hides', 'Writing', 'Infinite Scroll', 'infinite-scroll', true, 0 ],
[ 'shows', 'Writing', 'custom content types', null, false, 1 ],
[ 'hides', 'Writing', 'custom content types', null, true, 0 ],
[ 'shows', 'Discussion', 'Comments', 'comments', false, 1 ],
[ 'hides', 'Discussion', 'Comments', 'comments', true, 0 ],
[ 'hides', 'Discussion', 'Gravatar Hovercards', 'gravatar-hovercards', true, 0 ],
[ 'shows', 'Reader', 'the Reader', 'wpcom-reader', false, 1 ],
[ 'hides', 'Reader', 'the Reader', 'wpcom-reader', true, 0 ],
] )(
Expand Down
19 changes: 19 additions & 0 deletions projects/plugins/jetpack/_inc/client/discussion/comments-moved.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { __ } from '@wordpress/i18n';
import PointerCard from 'components/pointer-card';

/**
* Search result that sends the Comments settings to the panel in Features.
*
* @param {object} props - Component props.
* @param {Function} props.getModule - Reads a module by slug.
* @return {import('react').ReactNode} The card.
*/
export const CommentsMoved = ( { getModule } ) => (
<PointerCard
header={ __( 'Comments', 'jetpack' ) }
href={ getModule( 'comments' )?.configure_url }
linkText={ __( 'Open the Comments settings', 'jetpack' ) }
>
<p>{ __( 'The Comments settings are now in Features, in My Jetpack.', 'jetpack' ) }</p>
</PointerCard>
);
Loading
Loading