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

Newsletter signup gated by localstorage hook #936

Merged
merged 7 commits into from
Jan 4, 2025
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
1 change: 1 addition & 0 deletions .prettierrc
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
"^@craftwork/(.*)$",
"^@components/(.*)$",
"^@data/(.*)$",
"^@hooks/(.*)$",
"^@layouts/(.*)$",
"^@lib/(.*)$",
"^@ui/(.*)$",
Expand Down
18 changes: 9 additions & 9 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion src/components/Analytics/Fathom.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,11 @@
import { Suspense, useEffect } from 'react';
import { usePathname, useSearchParams } from 'next/navigation';
import { useRouter } from 'next/router';
import { useRouterType } from '@hooks/useRouterType';
import * as Fathom from 'fathom-client';
import posthog from 'posthog-js';

import { useRouterType } from '@hooks/useRouterType';

const FATHOM_DOMAINS = ['mikebifulco.com', 'www.mikebifulco.com'];

const FathomPagesRouter = ({ siteId }: { siteId: string }) => {
Expand Down
3 changes: 2 additions & 1 deletion src/components/NewsletterSignup/SubscriberCount.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import useNewsletterStats from '@hooks/useNewsletterStats';
import NumberFlow from '@number-flow/react';

import useNewsletterStats from '@hooks/useNewsletterStats';

type SubscriberCountProps = {
label?: string;
};
Expand Down
2 changes: 1 addition & 1 deletion src/components/Post/mentionsSummary.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { useRouter } from 'next/router';
import { useWebMentions } from '@hooks/useWebMentions';
import pluralize from 'pluralize';

import { useWebMentions } from '@hooks/useWebMentions';
import formatDate from '@utils/format-date';
import type { WebMention } from '@utils/webmentions';
import { Avatar, AvatarGroup } from '../Avatar';
Expand Down
35 changes: 29 additions & 6 deletions src/components/SubscriptionForm/SubscriptionForm.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
'use client';

import { useRef, useState } from 'react';
import Link from 'next/link';
import useNewsletterStats from '@hooks/useNewsletterStats';
import posthog from 'posthog-js';

import Button from '@components/Button';
import { useLocalStorage } from '@hooks/useLocalStorage';
import useNewsletterStats from '@hooks/useNewsletterStats';
import { trpc } from '@utils/trpc';

type SubscriptionFormProps = {
Expand All @@ -12,11 +15,19 @@ type SubscriptionFormProps = {
buttonText?: string;
};

type SubscriptionRecord = {
email?: string;
firstName?: string;
date?: string;
};

const SubscriptionForm: React.FC<SubscriptionFormProps> = ({
tags: _,
source,
buttonText = 'Subscribe',
}) => {
const [subscriptionRecord, setSubscriptionRecord] =
useLocalStorage<SubscriptionRecord>('tiny-improvements-subscribed', {});
const [getHoneypottedNerd, setGetHoneypottedNerd] = useState<boolean>(false);
const addSubscriberMutation = trpc.mailingList.subscribe.useMutation({
onSuccess: () => {
Expand All @@ -30,6 +41,12 @@ const SubscriptionForm: React.FC<SubscriptionFormProps> = ({
email,
firstName,
});

setSubscriptionRecord({
email,
firstName,
date: new Date().toISOString(),
});
},
onError: (error) => {
const email = emailRef.current?.value;
Expand Down Expand Up @@ -98,12 +115,16 @@ const SubscriptionForm: React.FC<SubscriptionFormProps> = ({
);
}

if (addSubscriberMutation.isSuccess || getHoneypottedNerd) {
if (
addSubscriberMutation.isSuccess ||
getHoneypottedNerd ||
subscriptionRecord?.date
) {
return (
<div className="flex flex-col gap-2">
<p className="text-xl font-semibold text-inherit">
🪩 Success! Thanks so much for subscribing. Don&apos;t forget to check
your spam folder for emails from{' '}
<p className="text-xl font-medium text-inherit">
🪩 Thanks so much for subscribing. Don&apos;t forget to check your
spam folder for emails from{' '}
<span className="text-pink-600">[email protected].</span>
</p>
</div>
Expand All @@ -115,7 +136,9 @@ const SubscriptionForm: React.FC<SubscriptionFormProps> = ({
<form ref={formRef} className="w-full" onSubmit={handleSubmission}>
<fieldset
disabled={
addSubscriberMutation.isPending || addSubscriberMutation.isSuccess
subscriptionRecord?.date !== undefined ||
addSubscriberMutation.isPending ||
addSubscriberMutation.isSuccess
}
>
<div data-style="clean">
Expand Down
85 changes: 85 additions & 0 deletions src/hooks/useLocalStorage.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
// Sourced (and typesafe-tweaked) from https://github.com/uidotdev/usehooks/blob/main/index.js#L616

// eslint-disable-next-line @typescript-eslint/no-unused-vars
import React, { useCallback, useEffect, useSyncExternalStore } from 'react';

function dispatchStorageEvent(key: string, newValue: string | null) {
window.dispatchEvent(new StorageEvent('storage', { key, newValue }));
}

const setLocalStorageItem = (key: string, value: unknown) => {
const stringifiedValue = JSON.stringify(value);
window.localStorage.setItem(key, stringifiedValue);
dispatchStorageEvent(key, stringifiedValue);
};

const removeLocalStorageItem = (key: string) => {
window.localStorage.removeItem(key);
dispatchStorageEvent(key, null);
};

const getLocalStorageItem = (key: string) => {
return window.localStorage.getItem(key);
};

const useLocalStorageSubscribe = (callback: (event: StorageEvent) => void) => {
window.addEventListener('storage', callback);
return () => window.removeEventListener('storage', callback);
};

const getLocalStorageServerSnapshot = () => {
// throw Error('useLocalStorage is a client-only hook');
return '{}';
};

export function useLocalStorage<T>(key: string, initialValue: T) {
const getSnapshot = () => {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
const stored = JSON.parse(getLocalStorageItem(key) ?? '');
return JSON.stringify({
...initialValue,
...stored,
});
};

const store = useSyncExternalStore(
useLocalStorageSubscribe,
getSnapshot,
getLocalStorageServerSnapshot
);

const setState = useCallback(
(v: unknown) => {
try {
/* eslint-disable @typescript-eslint/no-unsafe-call */
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
const nextState =
typeof v === 'function' ? v(JSON.parse(store || '{}')) : v;
/* eslint-enable @typescript-eslint/no-unsafe-call */

if (nextState === undefined || nextState === null) {
removeLocalStorageItem(key);
} else {
setLocalStorageItem(key, nextState);
}
} catch (e) {
console.warn(e);
}
},
[key, store]
);

useEffect(() => {
if (
getLocalStorageItem(key) === null &&
typeof initialValue !== 'undefined'
) {
setLocalStorageItem(key, initialValue);
}
}, [key, initialValue]);

return [store ? JSON.parse(store) : initialValue, setState] as [
T,
(v: unknown) => void,
];
}
Loading