Skip to content
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

feat: social share experiment #4148

Merged
merged 23 commits into from
Feb 10, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
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
22 changes: 19 additions & 3 deletions packages/shared/src/components/cards/Freeform/FreeformList.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import type { ReactElement, Ref } from 'react';
import React, { forwardRef, useMemo, useRef } from 'react';
import React, { forwardRef, useMemo, useRef, useState } from 'react';
import classNames from 'classnames';
import { sanitize } from 'dompurify';

import type { PostCardProps } from '../common/common';
import { Container, generateTitleClamp } from '../common/common';
import {
useConditionalFeature,
useFeedPreviewMode,
useTruncatedSummary,
useViewSize,
Expand All @@ -23,7 +24,11 @@ import { HIGH_PRIORITY_IMAGE_PROPS } from '../../image/Image';
import { ClickbaitShield } from '../common/ClickbaitShield';
import { useSmartTitle } from '../../../hooks/post/useSmartTitle';
import { useFeature } from '../../GrowthBookProvider';
import { feedActionSpacing } from '../../../lib/featureManagement';
import {
featureSocialShare,
feedActionSpacing,
} from '../../../lib/featureManagement';
import SocialBar from '../socials/SocialBar';

export const FreeformList = forwardRef(function SharePostCard(
{
Expand Down Expand Up @@ -57,17 +62,27 @@ export const FreeformList = forwardRef(function SharePostCard(
post.contentHtml ? sanitize(post.contentHtml, { ALLOWED_TAGS: [] }) : '',
[post.contentHtml],
);
const [linkClicked, setLinkClicked] = useState(false);
const { value: socialShare } = useConditionalFeature({
feature: featureSocialShare,
shouldEvaluate: linkClicked,
});

const { title: truncatedTitle } = useTruncatedSummary(title, content);

const handleCopyLinkClick = (e) => {
setLinkClicked(true);
onCopyLinkClick?.(e, post);
};

const actionButtons = (
<Container ref={containerRef} className="pointer-events-none">
<ActionButtons
post={post}
onUpvoteClick={onUpvoteClick}
onDownvoteClick={onDownvoteClick}
onCommentClick={onCommentClick}
onCopyLinkClick={onCopyLinkClick}
onCopyLinkClick={handleCopyLinkClick}
onBookmarkClick={onBookmarkClick}
className={classNames(
feedActionSpacingExp ? 'mt-2 justify-between' : 'mt-4',
Expand Down Expand Up @@ -150,6 +165,7 @@ export const FreeformList = forwardRef(function SharePostCard(
{!shouldSwapActions && actionButtons}
{!image && <PostContentReminder post={post} className="z-1" />}
{children}
{socialShare && <SocialBar className="mt-4" post={post} />}
</FeedItemContainer>
);
});
42 changes: 42 additions & 0 deletions packages/shared/src/components/cards/socials/SocialBar.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import type { ReactElement } from 'react';
import React from 'react';
import classNames from 'classnames';
import type { Post } from '../../../graphql/posts';
import {
Typography,
TypographyColor,
TypographyType,
} from '../../typography/Typography';
import SocialIconButton from './SocialIconButton';
import { socials } from '../../../lib/socialMedia';

type SocialBarProps = {
post: Post;
className?: string;
};

const SocialBar = ({ post, className }: SocialBarProps): ReactElement => {
return (
<aside
className={classNames(
'flex flex-col items-center justify-between gap-2 rounded-16 border border-border-subtlest-tertiary px-4 py-3 tablet:flex-row',
className,
)}
>
<Typography
color={TypographyColor.Tertiary}
type={TypographyType.Callout}
bold
>
Why not share it on social, too?
</Typography>
<div className="flex flex-row items-center gap-2">
{socials.map((social) => (
<SocialIconButton key={social} post={post} platform={social} />
))}
</div>
</aside>
);
};

export default SocialBar;
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
import type { ReactElement } from 'react';
import React from 'react';
import { Button, ButtonVariant } from '../../buttons/Button';
import type { Post } from '../../../graphql/posts';
import {
LinkedInIcon,
RedditIcon,
TwitterIcon,
WhatsappIcon,
} from '../../icons';
import { SocialIconType } from '../../../lib/socialMedia';
import { useLogContext } from '../../../contexts/LogContext';
import { LogEvent, Origin } from '../../../lib/log';

type SocialShareButtonProps = {
post: Post;
platform: SocialIconType;
variant?: ButtonVariant;
};

const getBtnProps = ({ post, platform }: SocialShareButtonProps) => {
const commonProps = {
target: '_blank',
rel: 'noopener noreferrer',
};

switch (platform) {
case SocialIconType.Reddit:
return {
...commonProps,
href: `https://www.reddit.com/submit?url=${encodeURIComponent(
post.commentsPermalink,
)}&title=${encodeURIComponent(post.title)}`,
icon: <RedditIcon secondary />,
};
case SocialIconType.X:
return {
...commonProps,
href: `https://x.com/share?url=${encodeURIComponent(
post.commentsPermalink,
)}&text=${encodeURIComponent(post.title)}`,
icon: <TwitterIcon />,
};
case SocialIconType.LinkedIn:
return {
...commonProps,
href: `https://www.linkedin.com/shareArticle?url=${encodeURIComponent(
post.commentsPermalink,
)}&title=${encodeURIComponent(post.title)}`,
icon: <LinkedInIcon secondary />,
};
case SocialIconType.WhatsApp:
return {
...commonProps,
href: `https://wa.me/?text=${encodeURIComponent(
post.commentsPermalink,
)}`,
icon: <WhatsappIcon color="white" secondary />,
};
default:
return {};
}
};

const SocialIconButton = ({
post,
platform,
variant = ButtonVariant.Float,
}: SocialShareButtonProps): ReactElement => {
const { logEvent } = useLogContext();
return (
<Button
variant={variant}
tag="a"
onClick={() =>
logEvent({
event_name: LogEvent.SharePost,
extra: JSON.stringify({
provider: platform,
origin: Origin.Suggestions,
}),
})
}
{...getBtnProps({ post, platform })}
/>
);
};

export default SocialIconButton;
19 changes: 16 additions & 3 deletions packages/shared/src/components/post/PostEngagements.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,14 +22,16 @@ import {
import usePersistentContext from '../../hooks/usePersistentContext';
import { PostContentShare } from './common/PostContentShare';
import { SourceType } from '../../graphql/sources';
import { useActions } from '../../hooks';
import { useActions, useConditionalFeature } from '../../hooks';
import { ActionType } from '../../graphql/actions';
import { AdAsComment } from '../comments/AdAsComment';
import { PostContentReminder } from './common/PostContentReminder';
import { Typography, TypographyType } from '../typography/Typography';
import { Button, ButtonIconPosition, ButtonSize } from '../buttons/Button';
import { TimeSortIcon } from '../icons/Sort/Time';
import { usePlusSubscription } from '../../hooks/usePlusSubscription';
import SocialBar from '../cards/socials/SocialBar';
import { featureSocialShare } from '../../lib/featureManagement';
import { PostContentReminder } from './common/PostContentReminder';

const AuthorOnboarding = dynamic(
() => import(/* webpackChunkName: "authorOnboarding" */ './AuthorOnboarding'),
Expand Down Expand Up @@ -65,6 +67,16 @@ function PostEngagements({
SQUAD_COMMENT_JOIN_BANNER_KEY,
false,
);
const [linkClicked, setLinkClicked] = useState(false);
const { value: socialShare } = useConditionalFeature({
feature: featureSocialShare,
shouldEvaluate: linkClicked,
});

const handleLinkClick = () => {
setLinkClicked(true);
onCopyLinkClick?.(post);
};

const onCommented = (comment: Comment, isNew: boolean) => {
if (!isNew) {
Expand Down Expand Up @@ -99,7 +111,7 @@ function PostEngagements({
onUpvotesClick={(upvotes) => onShowUpvoted(post.id, upvotes)}
/>
<PostActions
onCopyLinkClick={onCopyLinkClick}
onCopyLinkClick={handleLinkClick}
post={post}
postQueryKey={postQueryKey}
onComment={() =>
Expand All @@ -110,6 +122,7 @@ function PostEngagements({
/>
<PostContentReminder post={post} />
<PostContentShare post={post} />
{socialShare && <SocialBar post={post} className="mt-6" />}
<span className="mt-6 flex flex-row items-center">
<Typography type={TypographyType.Callout}>Sort:</Typography>
<Button
Expand Down
22 changes: 22 additions & 0 deletions packages/shared/src/hooks/feed/useCardCover.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,10 @@ import { CardCoverShare } from '../../components/cards/common/CardCoverShare';
import { CardCoverContainer } from '../../components/cards/common/CardCoverContainer';
import { PostReminderOptions } from '../../components/post/common/PostReminderOptions';
import { ButtonSize, ButtonVariant } from '../../components/buttons/common';
import { socials } from '../../lib/socialMedia';
import SocialIconButton from '../../components/cards/socials/SocialIconButton';
import { useFeaturesReadyContext } from '../../components/GrowthBookProvider';
import { featureSocialShare } from '../../lib/featureManagement';

interface UseCardCover {
overlay: ReactNode;
Expand All @@ -32,8 +36,25 @@ export const useCardCover = ({
currentInteraction,
shouldShowReminder,
} = usePostShareLoop(post);
const { getFeatureValue } = useFeaturesReadyContext();

const overlay = useMemo(() => {
if (currentInteraction === 'copy' && getFeatureValue(featureSocialShare)) {
return (
<CardCoverContainer title="Why not share it on social, too?">
<div className="mt-2 flex flex-row gap-2">
{socials.map((social) => (
<SocialIconButton
variant={ButtonVariant.Primary}
key={social}
post={post}
platform={social}
/>
))}
</div>
</CardCoverContainer>
);
}
if (shouldShowOverlay && onShare && currentInteraction === 'upvote') {
return (
<CardCoverShare
Expand Down Expand Up @@ -74,6 +95,7 @@ export const useCardCover = ({
shouldShowOverlay,
shouldShowReminder,
currentInteraction,
getFeatureValue,
]);

return { overlay };
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,15 @@
import { renderHook, act } from '@testing-library/react';
import React from 'react';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { usePostShareLoop } from './usePostShareLoop';
import type { Post } from '../../graphql/posts';
import { UserVote } from '../../graphql/posts';
import type { UseMutationSubscriptionProps } from '../mutationSubscription';
import { useMutationSubscription } from '../mutationSubscription';
import { AuthContextProvider } from '../../contexts/AuthContext';
import loggedUser from '../../../__tests__/fixture/loggedUser';
import { getShortLinkProps } from '../utils/useGetShortUrl';
import { ReferralCampaignKey } from '../../lib';

const post = { id: '1' } as Post;
const feedName = 'testFeed';
Expand All @@ -16,6 +22,22 @@ jest.mock('../../contexts', () => {
useActiveFeedNameContext: jest.fn().mockReturnValue({ feedName }),
};
});
const client = new QueryClient();

const wrapper = ({ children }: { children: React.ReactNode }) => {
return (
<QueryClientProvider client={client}>
<AuthContextProvider
user={loggedUser}
updateUser={jest.fn()}
getRedirectUri={jest.fn()}
tokenRefreshed
>
{children}
</AuthContextProvider>
</QueryClientProvider>
);
};

// Mock the useMutationSubscription hook
jest.mock('../mutationSubscription', () => ({
Expand All @@ -42,11 +64,9 @@ describe('usePostShareLoop', () => {
});

it('should set shouldShowOverlay to true when justUpvoted is true and hasInteracted is false', () => {
const { result } = renderHook(() => usePostShareLoop(post));
const { result } = renderHook(() => usePostShareLoop(post), { wrapper });

act(() => {
expect(mockUseMutationSubscription).toHaveBeenCalledTimes(1);

// Simulate a successful vote mutation with the same post id and vote type as Up
callback({
variables: { id: post.id, vote: UserVote.Up },
Expand All @@ -59,13 +79,25 @@ describe('usePostShareLoop', () => {
expect(result.current.shouldShowOverlay).toBe(true);
});

it('should show social share options when link is copied', () => {
const { queryKey } = getShortLinkProps(
post?.commentsPermalink,
ReferralCampaignKey.SharePost,
loggedUser,
);
client.setQueryData(queryKey, {
getShortUrl: 'https://short.url',
});

const { result } = renderHook(() => usePostShareLoop(post), { wrapper });
expect(result.current.currentInteraction).toBe('copy');
});

// Regression test for https://dailydotdev.atlassian.net/browse/MI-281
it('should set shouldShowOverlay to false when downvoting', () => {
const { result } = renderHook(() => usePostShareLoop(post));
const { result } = renderHook(() => usePostShareLoop(post), { wrapper });

act(() => {
expect(mockUseMutationSubscription).toHaveBeenCalledTimes(1);

// Simulate a successful vote mutation with the same post id and vote type as Up
callback({
variables: { id: post.id, vote: UserVote.Down },
Expand All @@ -79,11 +111,9 @@ describe('usePostShareLoop', () => {
});

it('should set shouldShowOverlay to false when onInteract is called', () => {
const { result } = renderHook(() => usePostShareLoop(post));
const { result } = renderHook(() => usePostShareLoop(post), { wrapper });

act(() => {
expect(mockUseMutationSubscription).toHaveBeenCalledTimes(1);

// Simulate a successful vote mutation with the same post id and vote type as Up
callback({
variables: { id: post.id, vote: UserVote.Up },
Expand Down
Loading