-
Notifications
You must be signed in to change notification settings - Fork 30
14890 show or hide the sign up newsletter component #14929
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
Marianaguardian
wants to merge
28
commits into
main
Choose a base branch
from
14890-show-or-hide-the-sign-up-newsletter-component
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+643
−43
Open
Changes from all commits
Commits
Show all changes
28 commits
Select commit
Hold shift + click to select a range
74f916e
Hide signUp card for signed in users in newsletter
Marianaguardian 6c6ffc1
removed unused imports
Marianaguardian 177412b
fixed lint issues
Marianaguardian b999d89
Merge branch 'main' of https://github.com/guardian/dotcom-rendering i…
Marianaguardian da6e644
Merge branch 'main' of https://github.com/guardian/dotcom-rendering i…
Marianaguardian a5b9c4b
remove console
Marianaguardian 7ad7a22
Merge branch 'main' of https://github.com/guardian/dotcom-rendering i…
Marianaguardian 6f12d91
updated from main branch
Marianaguardian bb54b31
updated idApiUrl type
Marianaguardian 4927841
Merge branch 'main' of https://github.com/guardian/dotcom-rendering i…
Marianaguardian 8582503
Minor changes for testing
Marianaguardian b56c69f
Merge branch 'main' into 14890-show-or-hide-the-sign-up-newsletter-co…
Marianaguardian 618f558
reverted test changes and correct response structure for user newslet…
Marianaguardian 08ba7cc
Merge branch '14890-show-or-hide-the-sign-up-newsletter-component' of…
Marianaguardian 6e620a5
Merge branch 'main' into 14890-show-or-hide-the-sign-up-newsletter-co…
Marianaguardian 8eed71c
render newsletter list id of current news letter for testing and upda…
Marianaguardian 97e519d
added console logs for debuging
Marianaguardian f0de441
render auth status and api reponse
Marianaguardian d5dbdaa
fix lint error
Marianaguardian 6161c89
Removed debugging logs and cleaned up code
Marianaguardian 67ce48a
Wrapped email signup wrapper in Island for runtime render
Marianaguardian c190059
Addressed PR comments
Marianaguardian 0a9eb75
Merge branch 'main' of https://github.com/guardian/dotcom-rendering i…
Marianaguardian c2f8825
resolved lint issue
Marianaguardian 060eca6
added placeholder to avoid layout shifting
Marianaguardian 57f734c
Merge branch 'main' of https://github.com/guardian/dotcom-rendering i…
Marianaguardian 52c929d
test case updated
Marianaguardian 66dc49d
removed lint issues
Marianaguardian File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,63 @@ | ||
| import type { Decorator } from '@storybook/react-webpack5'; | ||
| import { customMockFetch } from '../../src/lib/mockRESTCalls'; | ||
|
|
||
| // Extend window type for auth state mock | ||
| declare global { | ||
| interface Window { | ||
| __STORYBOOK_AUTH_STATE__?: 'SignedIn' | 'SignedOut' | 'Pending'; | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Decorator for pending auth state. | ||
| */ | ||
| export const pendingAuthDecorator: Decorator = (Story) => { | ||
| window.__STORYBOOK_AUTH_STATE__ = 'Pending'; | ||
| return <Story />; | ||
| }; | ||
|
|
||
| /** | ||
| * Decorator for signed-out user state. | ||
| * Sets the auth state to 'SignedOut' so useAuthStatus returns { kind: 'SignedOut' }. | ||
| */ | ||
| export const signedOutDecorator: Decorator = (Story) => { | ||
| window.__STORYBOOK_AUTH_STATE__ = 'SignedOut'; | ||
| return <Story />; | ||
| }; | ||
|
|
||
| /** | ||
| * Creates a decorator for signed-in user state with custom newsletter subscriptions. | ||
| * Sets the auth state to 'SignedIn' and mocks the newsletters API response. | ||
| * | ||
| * @param subscriptions - Array of newsletter subscriptions to return from the API. | ||
| * Each subscription should have a `listId` string. | ||
| * @returns A Storybook decorator | ||
| * | ||
| * @example | ||
| * // User signed in but not subscribed to any newsletters | ||
| * decorators: [signedInDecorator([])] | ||
| * | ||
| * @example | ||
| * // User signed in and subscribed to newsletter with listId 4147 | ||
| * decorators: [signedInDecorator([{ listId: '4147' }])] | ||
| */ | ||
| export const signedInDecorator = ( | ||
| subscriptions: Array<{ listId: string }> = [], | ||
| ): Decorator => { | ||
| return (Story) => { | ||
| window.__STORYBOOK_AUTH_STATE__ = 'SignedIn'; | ||
| window.fetch = customMockFetch([ | ||
| { | ||
| mockedMethod: 'GET', | ||
| mockedUrl: /.*idapi\.theguardian\.com\/users\/me\/newsletters/, | ||
| mockedStatus: 200, | ||
| mockedBody: { | ||
| result: { | ||
| subscriptions, | ||
| }, | ||
| }, | ||
| }, | ||
| ]) as typeof window.fetch; | ||
| return <Story />; | ||
| }; | ||
| }; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,144 @@ | ||
| /** | ||
| * Mock identity module for Storybook. | ||
| * | ||
| * This allows stories to control the authentication state | ||
| * by setting window.__STORYBOOK_AUTH_STATE__ before rendering. | ||
| */ | ||
|
|
||
| import type { AuthStatus, SignedIn } from '../../src/lib/identity'; | ||
|
|
||
| // Extend window type for our mock | ||
| declare global { | ||
| interface Window { | ||
| __STORYBOOK_AUTH_STATE__?: 'SignedIn' | 'SignedOut' | 'Pending'; | ||
| } | ||
| } | ||
|
|
||
| const mockAccessToken = { | ||
| expiresAt: Date.now() / 1000 + 3600, | ||
| scopes: ['openid', 'profile', 'email'], | ||
| clockSkew: 0, | ||
| accessToken: 'mock-access-token-for-storybook', | ||
| claims: { | ||
| aud: 'guardian-frontend', | ||
| auth_time: Date.now() / 1000, | ||
| cid: 'guardian-frontend', | ||
| exp: Date.now() / 1000 + 3600, | ||
| iat: Date.now() / 1000, | ||
| iss: 'https://profile.theguardian.com', | ||
| jti: 'mock-jti', | ||
| scp: ['openid', 'profile', 'email'], | ||
| sub: 'mock-user-id', | ||
| uid: 'mock-uid', | ||
| ver: 1, | ||
| email_validated: true, | ||
| identity_username: 'storybook-user', | ||
| legacy_identity_id: 'mock-legacy-id', | ||
| user_groups: [], | ||
| }, | ||
| tokenType: 'Bearer' as const, | ||
| }; | ||
|
|
||
| const mockIdToken = { | ||
| idToken: 'mock-id-token-for-storybook', | ||
| issuer: 'https://profile.theguardian.com', | ||
| clientId: 'guardian-frontend', | ||
| nonce: 'mock-nonce', | ||
| clockSkew: 0, | ||
| expiresAt: Date.now() / 1000 + 3600, | ||
| scopes: ['openid', 'profile', 'email'], | ||
| claims: { | ||
| aud: 'guardian-frontend', | ||
| auth_time: Date.now() / 1000, | ||
| exp: Date.now() / 1000 + 3600, | ||
| iat: Date.now() / 1000, | ||
| iss: 'https://profile.theguardian.com', | ||
| sub: 'mock-user-id', | ||
| identity_username: 'storybook-user', | ||
| email_validated: true, | ||
| email: '[email protected]', | ||
| braze_uuid: 'mock-braze-uuid', | ||
| user_groups: [], | ||
| legacy_identity_id: 'mock-legacy-id', | ||
| amr: ['pwd'], | ||
| at_hash: 'mock-at-hash', | ||
| idp: 'guardian', | ||
| jti: 'mock-jti', | ||
| name: 'Storybook User', | ||
| nonce: 'mock-nonce', | ||
| ver: 1, | ||
| }, | ||
| }; | ||
|
|
||
| type MockAuthState = { | ||
| isAuthenticated: boolean; | ||
| accessToken?: typeof mockAccessToken; | ||
| idToken?: typeof mockIdToken; | ||
| }; | ||
|
|
||
| export async function getAuthState(): Promise<MockAuthState> { | ||
| const authState = window.__STORYBOOK_AUTH_STATE__ ?? 'SignedOut'; | ||
|
|
||
| // For Pending state, return a promise that never resolves | ||
| // This keeps useAuthStatus in the 'Pending' state indefinitely for testing | ||
| if (authState === 'Pending') { | ||
| return new Promise<MockAuthState>(() => {}); | ||
| } | ||
|
|
||
| if (authState === 'SignedIn') { | ||
| return { | ||
| isAuthenticated: true, | ||
| accessToken: mockAccessToken, | ||
| idToken: mockIdToken, | ||
| }; | ||
| } | ||
|
|
||
| return { | ||
| isAuthenticated: false, | ||
| accessToken: undefined, | ||
| idToken: undefined, | ||
| }; | ||
| } | ||
|
|
||
| export function getSignedInStatus(authState: { | ||
| isAuthenticated: boolean; | ||
| accessToken?: typeof mockAccessToken; | ||
| idToken?: typeof mockIdToken; | ||
| }): AuthStatus { | ||
| if ( | ||
| authState.isAuthenticated && | ||
| authState.accessToken && | ||
| authState.idToken | ||
| ) { | ||
| return { | ||
| kind: 'SignedIn', | ||
| accessToken: authState.accessToken, | ||
| idToken: authState.idToken, | ||
| } as unknown as SignedIn; | ||
| } | ||
|
|
||
| return { kind: 'SignedOut' }; | ||
| } | ||
|
|
||
| export const getOptionsHeaders = (authStatus: SignedIn): RequestInit => { | ||
| return { | ||
| headers: { | ||
| Authorization: `Bearer ${authStatus.accessToken.accessToken}`, | ||
| 'X-GU-IS-OAUTH': 'true', | ||
| }, | ||
| }; | ||
| }; | ||
|
|
||
| export const isUserLoggedIn = (): Promise<boolean> => | ||
| getAuthStatus().then((authStatus) => | ||
| authStatus.kind === 'SignedIn' ? true : false, | ||
| ); | ||
|
|
||
| export const getAuthStatus = async (): Promise<AuthStatus> => { | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I think this is the only one that's actually used - would it be simpler to just mock this instead |
||
| const authState = await getAuthState(); | ||
| return getSignedInStatus(authState); | ||
| }; | ||
|
|
||
| export async function isSignedInAuthState() { | ||
| return getAuthState(); | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
79 changes: 79 additions & 0 deletions
79
dotcom-rendering/src/components/EmailSignUpWrapper.importable.tsx
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,79 @@ | ||
| import { useState } from 'react'; | ||
| import { useNewsletterSubscription } from '../lib/useNewsletterSubscription'; | ||
| import type { EmailSignUpProps } from './EmailSignup'; | ||
| import { EmailSignup } from './EmailSignup'; | ||
| import { InlineSkipToWrapper } from './InlineSkipToWrapper'; | ||
| import { Island } from './Island'; | ||
| import { NewsletterPrivacyMessage } from './NewsletterPrivacyMessage'; | ||
| import { Placeholder } from './Placeholder'; | ||
| import { SecureSignup } from './SecureSignup.importable'; | ||
|
|
||
| /** | ||
| * Approximate heights of the EmailSignup component at different breakpoints. | ||
| */ | ||
| const PLACEHOLDER_HEIGHTS = new Map([ | ||
| ['mobile', 220], | ||
| ['tablet', 180], | ||
| ['desktop', 180], | ||
| ] as const) as Map<'mobile' | 'tablet' | 'desktop', number>; | ||
|
|
||
| interface EmailSignUpWrapperProps extends EmailSignUpProps { | ||
| index: number; | ||
| listId: number; | ||
| identityName: string; | ||
| successDescription: string; | ||
| /** You should only set this to true if the privacy message will be shown elsewhere on the page */ | ||
| hidePrivacyMessage?: boolean; | ||
| } | ||
|
|
||
| /** | ||
| * EmailSignUpWrapper as an importable island component. | ||
| * | ||
| * This component needs to be hydrated client-side because it uses | ||
| * the useNewsletterSubscription hook which depends on auth status | ||
| * to determine if the user is already subscribed to the newsletter. | ||
| * | ||
| * If the user is signed in and already subscribed, this component | ||
| * will return null (hide the signup form). | ||
| */ | ||
| export const EmailSignUpWrapper = ({ | ||
| index, | ||
| listId, | ||
| ...emailSignUpProps | ||
| }: EmailSignUpWrapperProps) => { | ||
| const [idApiUrl] = useState(() => { | ||
| if (typeof window === 'undefined') return undefined; | ||
| return window.guardian?.config?.page?.idApiUrl ?? undefined; | ||
| }); | ||
| const isSubscribed = useNewsletterSubscription(listId, idApiUrl); | ||
|
|
||
| // Show placeholder while subscription status is being determined | ||
| // This prevents layout shift in both subscribed and non-subscribed cases | ||
| if (isSubscribed === undefined) { | ||
| return <Placeholder heights={PLACEHOLDER_HEIGHTS} />; | ||
| } | ||
|
|
||
| // Don't render if user is signed in and already subscribed | ||
| if (isSubscribed) { | ||
| return null; | ||
| } | ||
|
|
||
| return ( | ||
| <InlineSkipToWrapper | ||
| id={`EmailSignup-skip-link-${index}`} | ||
| blockDescription="newsletter promotion" | ||
| > | ||
| <EmailSignup {...emailSignUpProps}> | ||
| <Island priority="feature" defer={{ until: 'visible' }}> | ||
| <SecureSignup | ||
| newsletterId={emailSignUpProps.identityName} | ||
| successDescription={emailSignUpProps.description} | ||
| /> | ||
| </Island> | ||
| {!emailSignUpProps.hidePrivacyMessage && ( | ||
| <NewsletterPrivacyMessage /> | ||
| )} | ||
| </EmailSignup> | ||
| </InlineSkipToWrapper> | ||
| ); | ||
| }; |
45 changes: 42 additions & 3 deletions
45
dotcom-rendering/src/components/EmailSignUpWrapper.stories.tsx
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,35 +1,74 @@ | ||
| import type { Meta, StoryObj } from '@storybook/react-webpack5'; | ||
| import { EmailSignUpWrapper } from './EmailSignUpWrapper'; | ||
| import { | ||
| pendingAuthDecorator, | ||
| signedInDecorator, | ||
| signedOutDecorator, | ||
| } from '../../.storybook/decorators/authDecorator'; | ||
| import { EmailSignUpWrapper } from './EmailSignUpWrapper.importable'; | ||
|
|
||
| const meta: Meta<typeof EmailSignUpWrapper> = { | ||
| title: 'Components/EmailSignUpWrapper', | ||
| component: EmailSignUpWrapper, | ||
| }; | ||
|
|
||
| type Story = StoryObj<typeof EmailSignUpWrapper>; | ||
|
|
||
| const defaultArgs = { | ||
| index: 10, | ||
| listId: 4147, | ||
| identityName: 'the-recap', | ||
| description: | ||
| 'The best of our sports journalism from the past seven days and a heads-up on the weekend’s action', | ||
| "The best of our sports journalism from the past seven days and a heads-up on the weekend's action", | ||
| name: 'The Recap', | ||
| frequency: 'Weekly', | ||
| successDescription: "We'll send you The Recap every week", | ||
| theme: 'sport', | ||
| } satisfies Story['args']; | ||
| type Story = StoryObj<typeof EmailSignUpWrapper>; | ||
|
|
||
| // Loading state - shows placeholder while auth status is being determined | ||
| // This prevents layout shift when subscription status is resolved | ||
| export const LoadingState: Story = { | ||
| args: { | ||
| hidePrivacyMessage: false, | ||
| ...defaultArgs, | ||
| }, | ||
| decorators: [pendingAuthDecorator], | ||
| }; | ||
|
|
||
| // Default story - signed out user sees the signup form | ||
| export const DefaultStory: Story = { | ||
| args: { | ||
| hidePrivacyMessage: true, | ||
| ...defaultArgs, | ||
| }, | ||
| decorators: [signedOutDecorator], | ||
| }; | ||
|
|
||
| export const DefaultStoryWithPrivacy: Story = { | ||
| args: { | ||
| hidePrivacyMessage: false, | ||
| ...defaultArgs, | ||
| }, | ||
| decorators: [signedOutDecorator], | ||
| }; | ||
|
|
||
| // User is signed in but NOT subscribed - signup form is visible | ||
| export const SignedInNotSubscribed: Story = { | ||
| args: { | ||
| hidePrivacyMessage: false, | ||
| ...defaultArgs, | ||
| }, | ||
| decorators: [signedInDecorator([])], | ||
| }; | ||
|
|
||
| // User is signed in and IS subscribed - component returns null (hidden) | ||
| // Note: This story will render nothing as the component returns null when subscribed | ||
| export const SignedInAlreadySubscribed: Story = { | ||
| args: { | ||
| hidePrivacyMessage: false, | ||
| ...defaultArgs, | ||
| }, | ||
| decorators: [signedInDecorator([{ listId: String(defaultArgs.listId) }])], | ||
| }; | ||
|
|
||
| export default meta; |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Do we have to mock all this? Is it not possible to just mock the useAuthStatus hook?