Skip to content
Closed
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
89 changes: 65 additions & 24 deletions resources/js/components/follow-button.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -270,55 +270,96 @@ export function FollowIconButton({
}) {
const {
component,
props: { log, commits },
props: { log, commits, suggestedUsers },
} = usePage<{ commits?: CursorPaginated<Commit> }>();
const [isFollowing, setIsFollowing] = useIsFollowing(
user,
initialIsFollowing,
);
const Icon = isFollowing ? UserCheck : UserPlus;
const [isPending, setIsPending] = useSharedState<boolean>(
isPendingKey(user),
false,
);
const shownIsFollowing = isPending
? (suggestedUsers?.find((suggested) => suggested.id === user.id)
?.is_followed ?? isFollowing)
: isFollowing;
const Icon = shownIsFollowing ? UserCheck : UserPlus;

return (
<Tooltip>
<TooltipTrigger asChild>
<Link
href={
isFollowing
? UserFollowController.destroy(user)
: UserFollowController.store(user)
}
as="button"
only={['auth']}
preserveState
preserveScroll
async
onHttpException={(response) =>
onFollowHttpException(user, response)
}
onSuccess={() => {
setIsFollowing(!isFollowing);
router.flushAll();
<button
type="button"
disabled={isPending}
onClick={() => {
const follows = !isFollowing;

router.visit(
follows
? UserFollowController.store(user)
: UserFollowController.destroy(user),
{
only: ['auth'],
preserveState: true,
preserveScroll: true,
async: true,
...followVisitOptions(component, log, commits),
optimistic: (props) => ({
...(props.suggestedUsers && {
suggestedUsers:
props.suggestedUsers.map(
(suggested) =>
suggested.id === user.id
? {
...suggested,
is_followed:
follows,
}
: suggested,
),
}),
}),
onBefore: () => {
let starts = false;
setIsPending((current) => {
starts = !current;

return true;
});

return starts;
},
onFinish: () => setIsPending(false),
onHttpException: (response) =>
onFollowHttpException(user, response),
onSuccess: () => {
setIsFollowing(follows);
router.flushAll();
},
},
);
}}
aria-label={
isFollowing
shownIsFollowing
? `Unfollow @${user.username}`
: `Follow @${user.username}${followsYou ? ' back' : ''}`
}
className={cn(
'shrink-0 rounded-md p-1.5 text-muted-foreground transition-colors hover:bg-accent hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none',
{
'text-primary hover:text-primary':
isFollowing || (marksFollowsYou && followsYou),
shownIsFollowing ||
(marksFollowsYou && followsYou),
},
)}
{...props}
{...followVisitOptions(component, log, commits)}
>
<Icon aria-hidden className="size-4" />
</Link>
</button>
</TooltipTrigger>
<TooltipContent>
{isFollowing
{shownIsFollowing
? `Following @${user.username}`
: followsYou
? `Follow @${user.username} back`
Expand Down
1 change: 1 addition & 0 deletions resources/js/types/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ export type Auth = {
};

export type SuggestedUser = User & {
is_followed?: boolean;
followed_by_following_count: number;
followers_count: number;
follows_you: boolean;
Expand Down
131 changes: 127 additions & 4 deletions tests/Unit/FollowState.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,11 @@ let log: string | undefined;
let loadedCommits: { data: { id: string }[] } | undefined;
let suggestedUsers: SuggestedUser[] | undefined;
type VisitOptions = {
optimistic?: (props: { suggestedUsers?: SuggestedUser[] }) => {
suggestedUsers?: SuggestedUser[];
};
onBefore?: () => boolean;
onStart?: () => void;
only?: string[];
headers?: Record<string, string>;
async?: boolean;
Expand Down Expand Up @@ -75,7 +80,10 @@ vi.doMock('@inertiajs/react', async () => ({
}

return () =>
navigateListeners.splice(navigateListeners.indexOf(listener), 1);
navigateListeners.splice(
navigateListeners.indexOf(listener),
1,
);
},
replaceProp: (
_key: string,
Expand Down Expand Up @@ -413,6 +421,121 @@ function suggestionFollowLink(user: SuggestedUser): Props {
return link.props;
}

function suggestionIcon(user: SuggestedUser): Props {
const button = find(
SuggestedUserRow({ user, onDismiss: () => false }),
(props) => props['data-test'] === 'suggested-follow-button',
);
assert.ok(button);
const control = find(render(button), (props) => 'aria-label' in props);
assert.ok(control);

return control.props;
}

function startSuggestionFollow(user: SuggestedUser): VisitOptions {
(suggestionIcon(user).onClick as () => void)();
const visit = visits.at(-1)!;
assert.equal(visit.onBefore?.(), true);
visit.onStart?.();
assert.ok(visit.optimistic);
suggestedUsers = visit.optimistic({ suggestedUsers }).suggestedUsers;

return visit;
}

test('a suggestion follows and unfollows immediately without flipping back on success', () => {
const user = suggestion('optimistic');
suggestedUsers = [user];
const follow = startSuggestionFollow(user);

assert.equal(suggestionIcon(user)['aria-label'], 'Unfollow @optimistic');
assert.equal(suggestionIcon(user).disabled, true);
assert.equal(
(suggestionFollowLink(user).onBefore as () => boolean)(),
false,
);
follow.onSuccess?.();
follow.onFinish?.();
assert.equal(suggestionIcon(user)['aria-label'], 'Unfollow @optimistic');

const unfollow = startSuggestionFollow(user);
assert.equal(visits.at(-1)?.method, 'delete');
assert.equal(suggestionIcon(user)['aria-label'], 'Follow @optimistic');
unfollow.onSuccess?.();
unfollow.onFinish?.();
assert.equal(suggestionIcon(user)['aria-label'], 'Follow @optimistic');
});

test('an optimistic suggestion prevents duplicate requests for the same person', () => {
const user = suggestion('pending-icon');
suggestedUsers = [user];
const follow = startSuggestionFollow(user);
assert.equal(suggestionIcon(user).disabled, true);

(suggestionIcon(user).onClick as () => void)();
assert.equal(visits.at(-1)?.onBefore?.(), false);
follow.onSuccess?.();
follow.onFinish?.();
assert.equal(suggestionIcon(user).disabled, false);
});

test('a failed optimistic unfollow restores the followed icon', () => {
const user = suggestion('failed-unfollow');
followFromProfile(user);
const baseline = [user];
suggestedUsers = baseline;
const unfollow = startSuggestionFollow(user);
assert.equal(suggestionIcon(user)['aria-label'], 'Follow @failed-unfollow');

suggestedUsers = baseline;
unfollow.onFinish?.();
assert.equal(
suggestionIcon(user)['aria-label'],
'Unfollow @failed-unfollow',
);
assert.equal(suggestionIcon(user).disabled, false);
});

test('rolling back a failed suggestion leaves a different successful follow intact', () => {
const first = suggestion('saved-optimistic');
const second = suggestion('failed-optimistic');
const baseline = [first, second];
suggestedUsers = baseline;
const saved = startSuggestionFollow(first);
const failed = startSuggestionFollow(second);
saved.onSuccess?.();
saved.onFinish?.();

suggestedUsers = baseline;
failed.onFinish?.();

assert.equal(
suggestionIcon(first)['aria-label'],
'Unfollow @saved-optimistic',
);
assert.equal(
suggestionIcon(second)['aria-label'],
'Follow @failed-optimistic',
);
assert.equal(suggestionIcon(second).disabled, false);
});

test('a block during an optimistic follow is not undone by rollback', () => {
const user = suggestion('optimistic-block');
suggestedUsers = [user];
const follow = startSuggestionFollow(user);
assert.equal(follow.onHttpException?.({ status: 403 }), false);
assert.equal(isSuggested(user), false);

suggestedUsers = [user];
follow.onFinish?.();
assert.equal(
suggestionIcon(user)['aria-label'],
'Follow @optimistic-block',
);
});

test('following several suggestions in a row sends every follow without cancelling the others', () => {
const first = suggestion('pauline');
const second = suggestion('brent');
Expand Down Expand Up @@ -541,9 +664,9 @@ function suggestionRow(user: SuggestedUser): Props {
}

function dismissSuggestion(user: SuggestedUser): boolean {
return (
suggestionRow(user).onDismiss as (onFailed: () => void) => boolean
)(() => {});
return (suggestionRow(user).onDismiss as (onFailed: () => void) => boolean)(
() => {},
);
}

function hasElementNamed(node: ReactNode, name: string): boolean {
Expand Down