Initial work on the recent emails feature

This commit is contained in:
Jackson Harper 2023-01-25 16:50:39 +08:00
parent f36eb0ed32
commit 9f20920ddc
3 changed files with 508 additions and 0 deletions

View file

@ -0,0 +1,78 @@
import { gql } from 'graphql-request'
import useSWR from 'swr'
import { publicGqlFetcher } from '../networkHelpers'
export interface RecentEmail {
id: string
from: string
to: string
subject: string
type: string
text: string
createdAt: string
}
interface RecentEmailsResponse {
isValidating: boolean
recentEmails: RecentEmail[]
revalidate: () => void
}
interface RecentEmailsResponseData {
recentEmails: RecentEmailsData
}
interface RecentEmailsData {
recentEmails: RecentEmail[]
}
export function useGetRecentEmailsQuery(): RecentEmailsResponse {
const query = gql`
query GetRecentEmails {
recentEmails {
... on RecentEmailsSuccess {
recentEmails {
id
from
to
subject
type
text
createdAt
}
}
... on RecentEmailsError {
errorCodes
}
}
}
`
const { data, mutate, error, isValidating } = useSWR(query, publicGqlFetcher)
try {
if (error) {
throw error
}
if (data) {
const result = data as RecentEmailsResponseData
const recentEmails = result.recentEmails.recentEmails as RecentEmail[]
return {
isValidating,
recentEmails,
revalidate: () => {
mutate()
},
}
}
} catch (error) {
console.log('error', error)
}
return {
isValidating: false,
recentEmails: [],
// eslint-disable-next-line @typescript-eslint/no-empty-function
revalidate: () => {},
}
}

View file

@ -0,0 +1,234 @@
import { Button } from '../../../components/elements/Button'
import { useGetNewsletterEmailsQuery } from '../../../lib/networking/queries/useGetNewsletterEmailsQuery'
import { createNewsletterEmailMutation } from '../../../lib/networking/mutations/createNewsletterEmailMutation'
import { deleteNewsletterEmailMutation } from '../../../lib/networking/mutations/deleteNewsletterEmailMutation'
import { MoreOptionsIcon } from '../../../components/elements/images/MoreOptionsIcon'
import { Trash, Copy } from 'phosphor-react'
import {
Dropdown,
DropdownOption,
} from '../../../components/elements/DropdownElements'
import { theme, styled } from '../../../components/tokens/stitches.config'
import { Box, HStack } from '../../../components/elements/LayoutPrimitives'
import { useCopyLink } from '../../../lib/hooks/useCopyLink'
import { useCallback, useMemo, useState } from 'react'
import { StyledText } from '../../../components/elements/StyledText'
import { applyStoredTheme } from '../../../lib/themeUpdater'
import { showErrorToast, showSuccessToast } from '../../../lib/toastHelpers'
import { formattedShortDate } from '../../../lib/dateFormatting'
import Link from 'next/link'
import {
EmptySettingsRow,
SettingsTable,
SettingsTableRow,
} from '../../../components/templates/settings/SettingsTable'
import { ConfirmationModal } from '../../../components/patterns/ConfirmationModal'
enum TextType {
EmailAddress,
ConfirmationCode,
}
type CopyTextButtonProps = {
text: string
type: TextType
}
const CopyTextBtnWrapper = styled(Box, {
background: '$grayBgActive',
borderRadius: '6px',
border: '1px solid rgba(0, 0, 0, 0.06)',
width: '32px',
height: '32px',
display: 'flex',
color: '#3D3D3D',
alignItems: 'center',
justifyContent: 'center',
})
function CopyTextButton(props: CopyTextButtonProps): JSX.Element {
const { copyLink, isLinkCopied } = useCopyLink(
props.text,
'newsletter_' +
(props.type == TextType.EmailAddress
? 'email_address'
: 'confirmation_code')
)
const copy = useCallback(() => {
copyLink()
showSuccessToast(
props.type == TextType.EmailAddress
? 'Email Address Copied'
: 'Confirmation Code Copied'
)
}, [])
return (
<Button style="plainIcon" onClick={copy}>
<Copy
width={16}
height={16}
color={theme.colors.grayTextContrast.toString()}
/>
</Button>
)
}
export default function EmailsPage(): JSX.Element {
const { emailAddresses, revalidate, isValidating } =
useGetNewsletterEmailsQuery()
const [confirmDeleteEmailId, setConfirmDeleteEmailId] = useState<
undefined | string
>(undefined)
applyStoredTheme(false)
async function createEmail(): Promise<void> {
const email = await createNewsletterEmailMutation()
if (!email) {
showErrorToast('Error Creating Email')
return
}
showSuccessToast('Email Created')
revalidate()
}
async function deleteEmail(id: string): Promise<void> {
const result = await deleteNewsletterEmailMutation(id)
if (!result) {
showErrorToast('Error Deleting Email')
return
}
revalidate()
showSuccessToast('Email Deleted')
}
const sortedEmailAddresses = useMemo(() => {
if (!emailAddresses) {
return []
}
return emailAddresses.sort((a, b) => a.createdAt.localeCompare(b.createdAt))
}, [emailAddresses])
return (
<>
<SettingsTable
pageId="settings-emails-tag"
pageHeadline="Email Addresses"
pageInfoLink="/help/newsletters"
headerTitle="Address"
createTitle="Create a new email address"
createAction={createEmail}
>
{sortedEmailAddresses.length > 0 ? (
sortedEmailAddresses.map((email, i) => {
return (
<SettingsTableRow
key={email.address}
title={email.address}
isLast={i === sortedEmailAddresses.length - 1}
onDelete={() => setConfirmDeleteEmailId(email.id)}
deleteTitle="Delete"
sublineElement={
<StyledText
css={{
my: '5px',
fontSize: '11px',
a: {
color: '$omnivoreCtaYellow',
},
}}
>
{`created ${formattedShortDate(email.createdAt)}, `}
<Link href="/settings/subscriptions">{`${email.subscriptionCount} subscriptions`}</Link>
</StyledText>
}
titleElement={
<CopyTextBtnWrapper
css={{
marginLeft: '20px',
'@mdDown': {
marginRight: '10px',
},
}}
>
<CopyTextButton
text={email.address}
type={TextType.EmailAddress}
/>
</CopyTextBtnWrapper>
}
extraElement={
email.confirmationCode ? (
<HStack
alignment="start"
distribution="center"
css={{
width: '100%',
backgroundColor: '$grayBgActive',
borderRadius: '6px',
padding: '4px 4px 4px 0px',
'@md': {
width: '30%',
backgroundColor: 'transparent',
},
}}
>
<>
<StyledText
css={{
fontSize: '11px',
'@md': {
marginTop: '5px',
},
'@mdDown': {
marginLeft: 'auto',
},
marginRight: '10px',
}}
>
{`Gmail: ${email.confirmationCode}`}
</StyledText>
<Box>
<CopyTextBtnWrapper>
<CopyTextButton
text={email.confirmationCode || ''}
type={TextType.ConfirmationCode}
/>
</CopyTextBtnWrapper>
</Box>
</>
</HStack>
) : (
<></>
)
}
/>
)
})
) : (
<EmptySettingsRow
text={isValidating ? '-' : 'No Email Addresses Found'}
/>
)}
</SettingsTable>
{confirmDeleteEmailId ? (
<ConfirmationModal
message={
'Are you sure? You will stop receiving emails sent to this address.'
}
onAccept={async () => {
await deleteEmail(confirmDeleteEmailId)
setConfirmDeleteEmailId(undefined)
}}
onOpenChange={() => setConfirmDeleteEmailId(undefined)}
/>
) : null}
</>
)
}

View file

@ -0,0 +1,196 @@
import { useEffect, useMemo, useState } from 'react'
import { useRouter } from 'next/router'
import { showErrorToast, showSuccessToast } from '../../../lib/toastHelpers'
import { applyStoredTheme } from '../../../lib/themeUpdater'
import { FormInputProps } from '../../../components/elements/FormElements'
import {
EmptySettingsRow,
SettingsTable,
SettingsTableRow,
} from '../../../components/templates/settings/SettingsTable'
import { StyledText } from '../../../components/elements/StyledText'
import { formattedShortDate } from '../../../lib/dateFormatting'
import {
RecentEmail,
useGetRecentEmailsQuery,
} from '../../../lib/networking/queries/useGetRecentEmails'
import Link from 'next/link'
export default function RecentEmails(): JSX.Element {
const { recentEmails, revalidate, isValidating } = useGetRecentEmailsQuery()
const [onDeleteId, setOnDeleteId] = useState<string>('')
const [addModalOpen, setAddModalOpen] = useState(false)
const [name, setName] = useState<string>('')
const [value, setValue] = useState<string>('')
const [expiresAt, setExpiresAt] = useState<Date>(new Date())
const [formInputs, setFormInputs] = useState<FormInputProps[]>([])
const [apiKeyGenerated, setApiKeyGenerated] = useState('')
const neverExpiresDate = new Date(8640000000000000)
const defaultExpiresAt = 'Never'
applyStoredTheme(false)
// async function onDelete(id: string): Promise<void> {
// const result = await revokeApiKeyMutation(id)
// if (result) {
// showSuccessToast('API Key deleted', { position: 'bottom-right' })
// } else {
// showErrorToast('Failed to delete', { position: 'bottom-right' })
// }
// revalidate()
// }
// async function onCreate(): Promise<void> {
// const result = await generateApiKeyMutation({ name, expiresAt })
// if (result) {
// setApiKeyGenerated(result)
// showSuccessToast('API key generated', { position: 'bottom-right' })
// } else {
// showErrorToast('Failed to add', { position: 'bottom-right' })
// }
// revalidate()
// }
// function onAdd() {
// return setFormInputs([
// {
// label: 'Name',
// onChange: setName,
// name: 'name',
// value: value,
// required: true,
// },
// {
// label: 'Expires',
// name: 'expiredAt',
// required: true,
// onChange: (e) => {
// console.log('onChange: ', e)
// let additionalDays = 0
// switch (e.target.value) {
// case 'in 7 days':
// additionalDays = 7
// break
// case 'in 30 days':
// additionalDays = 30
// break
// case 'in 90 days':
// additionalDays = 90
// break
// case 'in 1 year':
// additionalDays = 365
// break
// case 'Never':
// break
// }
// const newExpires = additionalDays ? new Date() : neverExpiresDate
// if (additionalDays) {
// newExpires.setDate(newExpires.getDate() + additionalDays)
// }
// setExpiresAt(newExpires)
// },
// type: 'select',
// options: [
// 'in 7 days',
// 'in 30 days',
// 'in 90 days',
// 'in 1 year',
// 'Never',
// ],
// value: defaultExpiresAt,
// },
// ])
// }
const sortedRecentEmails = useMemo(() => {
if (!recentEmails) {
return []
}
return recentEmails.sort((a, b) => a.createdAt.localeCompare(b.createdAt))
}, [recentEmails])
return (
<SettingsTable
pageId="api-keys"
pageHeadline="Recently Received Emails"
pageInfoLink="https://docs.omnivore.app/using/inbox.html"
headerTitle="Recently Received Emails"
>
{sortedRecentEmails.length > 0 ? (
sortedRecentEmails.map((recentEmail: RecentEmail, i) => {
return (
<SettingsTableRow
key={recentEmail.id}
title={recentEmail.subject}
isLast={i === sortedRecentEmails.length - 1}
onDelete={() => {
console.log('onDelete triggered: ', recentEmail.id)
setOnDeleteId(recentEmail.id)
}}
deleteTitle="Delete"
sublineElement={
<StyledText
css={{
my: '5px',
fontSize: '11px',
a: {
color: '$omnivoreCtaYellow',
},
}}
>
{`From ${formattedShortDate(recentEmail.from)},`}
{`Received ${formattedShortDate(recentEmail.createdAt)} at `}
<Link href={`/settings/emails?address=${recentEmail.to}`}>
{recentEmail.to}
</Link>
</StyledText>
}
/>
)
})
) : (
<EmptySettingsRow
text={isValidating ? '-' : 'No recent emails Found'}
/>
)}
{/*
{addModalOpen && (
<FormModal
title={'Generate API Key'}
onSubmit={onCreate}
onOpenChange={setAddModalOpen}
inputs={formInputs}
acceptButtonLabel={'Generate'}
/>
)}
{apiKeyGenerated && (
<ConfirmationModal
message={`API key generated. Copy the key and use it in your application.
You wont be able to see it again!
Key: ${apiKeyGenerated}`}
acceptButtonLabel="Copy"
cancelButtonLabel="Close"
onAccept={async () => {
await navigator.clipboard.writeText(apiKeyGenerated)
setApiKeyGenerated('')
}}
onOpenChange={() => setApiKeyGenerated('')}
/>
)}
{onDeleteId && (
<ConfirmationModal
message={'API key will be revoked. This action cannot be undone.'}
onAccept={async () => {
await onDelete(onDeleteId)
setOnDeleteId('')
}}
onOpenChange={() => setOnDeleteId('')}
/>
)} */}
</SettingsTable>
)
}