so now we're on fly.io
This commit is contained in:
@@ -0,0 +1,80 @@
|
||||
import { Button } from "~/components/ui/Button"
|
||||
import { useStore } from "~/lib/store"
|
||||
import { Dialog } from "@headlessui/react"
|
||||
import { trpc } from "~/lib/trpc"
|
||||
import { useForm } from "react-hook-form"
|
||||
|
||||
export const LoginModal: React.FC = () => {
|
||||
const [loginModalOpened, setLoginModalOpened] = useStore((store) => [
|
||||
store.loginModalOpened,
|
||||
store.setLoginModalOpened,
|
||||
])
|
||||
const requestLoginLink = trpc.useMutation("auth.requestLoginLink")
|
||||
|
||||
const form = useForm({
|
||||
defaultValues: {
|
||||
email: "",
|
||||
},
|
||||
})
|
||||
|
||||
const handleSubmit = form.handleSubmit((values) => {
|
||||
requestLoginLink.mutate({
|
||||
email: values.email,
|
||||
url: location.href,
|
||||
})
|
||||
})
|
||||
|
||||
return (
|
||||
<Dialog
|
||||
open={loginModalOpened}
|
||||
onClose={() => setLoginModalOpened(false)}
|
||||
className="fixed z-10 inset-0 overflow-y-auto"
|
||||
>
|
||||
<div className="flex items-center justify-center min-h-screen">
|
||||
<Dialog.Overlay className="fixed inset-0 bg-white opacity-75" />
|
||||
|
||||
<div className="relative bg-white rounded-lg overflow-hidden max-w-sm shadow-modal w-full mx-auto">
|
||||
<Dialog.Title className="bg-zinc-200 h-12 flex items-center px-3 text-sm text-zinc-600 justify-center">
|
||||
Continue with Email
|
||||
</Dialog.Title>
|
||||
|
||||
<div className="p-8">
|
||||
{requestLoginLink.data && (
|
||||
<div className="mb-5">
|
||||
We just emailed you with a link to log in, please check your
|
||||
inbox and spam folder in case you can{`'`}t find it.
|
||||
</div>
|
||||
)}
|
||||
<form className="space-y-5" onSubmit={handleSubmit}>
|
||||
<div>
|
||||
<label
|
||||
className="block mb-1 font-medium text-zinc-600"
|
||||
htmlFor="email"
|
||||
>
|
||||
Email
|
||||
</label>
|
||||
<input
|
||||
id="email"
|
||||
type="email"
|
||||
className="input is-block"
|
||||
{...form.register("email")}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<Button
|
||||
type="submit"
|
||||
isBlock
|
||||
isLoading={requestLoginLink.isLoading}
|
||||
>
|
||||
Continue
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
|
||||
export default LoginModal
|
||||
@@ -0,0 +1,25 @@
|
||||
import Head from "next/head"
|
||||
|
||||
export const SEOHead: React.FC<{
|
||||
title: string
|
||||
description?: string | null
|
||||
image?: string | null
|
||||
}> = ({ title, description, image }) => {
|
||||
return (
|
||||
<Head>
|
||||
<title>{title}</title>
|
||||
<meta name="og:title" content={title} />
|
||||
<meta name="twitter:title" content={title} />
|
||||
<meta name="description" content={description || ""} />
|
||||
<meta name="og:description" content={description || ""} />
|
||||
<meta name="twitter:description" content={description || ""} />
|
||||
<meta name="twitter:card" content="summary" />
|
||||
{image && (
|
||||
<>
|
||||
<meta name="og:image" content={image} />
|
||||
<meta name="twitter:image" content={image} />
|
||||
</>
|
||||
)}
|
||||
</Head>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
import React, { useEffect } from "react"
|
||||
import { useStore } from "~/lib/store"
|
||||
import { Button } from "../ui/Button"
|
||||
import { Modal } from "../ui/Modal"
|
||||
import toast from "react-hot-toast"
|
||||
import { trpc } from "~/lib/trpc"
|
||||
import { Input } from "../ui/Input"
|
||||
import { useForm } from "react-hook-form"
|
||||
|
||||
export const SubscribeModal: React.FC<{
|
||||
siteId: string
|
||||
subscription?: {
|
||||
telegram?: boolean
|
||||
email?: boolean
|
||||
} | null
|
||||
isLoggedIn: boolean
|
||||
}> = ({ siteId, subscription, isLoggedIn }) => {
|
||||
const [open, setOpen] = useStore((store) => [
|
||||
store.subscribeModalOpened,
|
||||
store.setSubscribeModalOpened,
|
||||
])
|
||||
const subscribe = trpc.useMutation("site.subscribe")
|
||||
const unsubscribe = trpc.useMutation("site.unsubscribe")
|
||||
const trpcContext = trpc.useContext()
|
||||
|
||||
const subscribeForm = useForm({
|
||||
defaultValues: {
|
||||
newUserEmail: "",
|
||||
email: subscription?.email ?? true,
|
||||
telegram: subscription?.telegram ?? false,
|
||||
},
|
||||
})
|
||||
|
||||
const handleSubscribe = subscribeForm.handleSubmit((values) => {
|
||||
subscribe.mutate({
|
||||
siteId,
|
||||
email: values.email,
|
||||
telegram: values.telegram,
|
||||
newUser: isLoggedIn
|
||||
? undefined
|
||||
: {
|
||||
email: values.newUserEmail,
|
||||
url: location.href,
|
||||
},
|
||||
})
|
||||
})
|
||||
|
||||
useEffect(() => {
|
||||
if (subscribe.isSuccess && isLoggedIn) {
|
||||
subscribe.reset()
|
||||
toast.success(subscription ? "Updated!" : "Subscribed!")
|
||||
trpcContext.invalidateQueries("site.subscription")
|
||||
}
|
||||
}, [subscribe, isLoggedIn, subscription, trpcContext])
|
||||
|
||||
useEffect(() => {
|
||||
if (unsubscribe.isSuccess) {
|
||||
unsubscribe.reset()
|
||||
toast.success("Unsubscribed!")
|
||||
trpcContext.invalidateQueries("site.subscription")
|
||||
}
|
||||
}, [unsubscribe, trpcContext])
|
||||
|
||||
return (
|
||||
<Modal title="Become a subscriber" open={open} setOpen={setOpen}>
|
||||
{subscribe.isSuccess && !isLoggedIn ? (
|
||||
<div className="p-5 space-y-3">
|
||||
<p>
|
||||
We have sent you an email with a link to confirm your subscription.
|
||||
</p>
|
||||
<p>Please check your inbox (and spam folder).</p>
|
||||
</div>
|
||||
) : (
|
||||
<form className="p-5" onSubmit={handleSubscribe}>
|
||||
{!isLoggedIn && (
|
||||
<div className="mb-5">
|
||||
<Input
|
||||
label="Email"
|
||||
type="email"
|
||||
id="email"
|
||||
isBlock
|
||||
required
|
||||
{...subscribeForm.register("newUserEmail", {})}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
<div>
|
||||
<label className="select-none flex items-center space-x-1">
|
||||
<input type="checkbox" {...subscribeForm.register("email")} />
|
||||
<span>Receive updates via Email</span>
|
||||
</label>
|
||||
</div>
|
||||
<div className="">
|
||||
<label className="select-none flex items-center space-x-1">
|
||||
<input type="checkbox" {...subscribeForm.register("telegram")} />
|
||||
<span>Receive updates via Telegram</span>
|
||||
</label>
|
||||
</div>
|
||||
<div className="mt-5 space-x-3">
|
||||
<Button type="submit" isLoading={subscribe.isLoading}>
|
||||
<span>{subscription ? "Update" : "Subscribe"}</span>
|
||||
</Button>
|
||||
{subscription && (
|
||||
<Button
|
||||
type="button"
|
||||
variant="secondary"
|
||||
isLoading={unsubscribe.isLoading}
|
||||
onClick={() => unsubscribe.mutate({ siteId })}
|
||||
>
|
||||
Unsubscribe
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</form>
|
||||
)}
|
||||
</Modal>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
import { Dialog } from "@headlessui/react"
|
||||
import { useRef, useState } from "react"
|
||||
import ReactAvatarEditor from "react-avatar-editor"
|
||||
import { getUserContentsUrl } from "~/lib/user-contents"
|
||||
import { Avatar } from "~/components/ui/Avatar"
|
||||
import { Button } from "~/components/ui/Button"
|
||||
import toast from "react-hot-toast"
|
||||
import createPica from "pica"
|
||||
import { trpc } from "~/lib/trpc"
|
||||
import { UploadFile, useUploadFile } from "~/hooks/useUploadFile"
|
||||
|
||||
const AvatarEditorModal: React.FC<{
|
||||
isOpen: boolean
|
||||
image?: File | null
|
||||
setIsOpen: (open: boolean) => void
|
||||
site?: string
|
||||
uploadFile: UploadFile
|
||||
}> = ({ isOpen, setIsOpen, image, site, uploadFile }) => {
|
||||
const editorRef = useRef<ReactAvatarEditor | null>(null)
|
||||
const [isSaving, setIsSaving] = useState(false)
|
||||
const ctx = trpc.useContext()
|
||||
const updateProfile = trpc.useMutation("user.updateProfile")
|
||||
const updateSite = trpc.useMutation("site.updateSite")
|
||||
|
||||
const cropAndSave = async () => {
|
||||
if (!editorRef.current) return
|
||||
|
||||
try {
|
||||
setIsSaving(true)
|
||||
|
||||
// Get cropped image
|
||||
const fromCanvas = editorRef.current.getImage()
|
||||
const toCanvas = document.createElement("canvas")
|
||||
toCanvas.width = 460
|
||||
toCanvas.height = 460
|
||||
const pica = createPica()
|
||||
const result = await pica.resize(fromCanvas, toCanvas)
|
||||
const blob = await pica.toBlob(result, "image/jpeg", 0.9)
|
||||
|
||||
// Upload image to R2
|
||||
const { key } = await uploadFile(blob, image!.name)
|
||||
|
||||
// Save the image to profile / site
|
||||
if (site) {
|
||||
await updateSite.mutateAsync({ site, icon: key })
|
||||
} else {
|
||||
await updateProfile.mutateAsync({ avatar: key })
|
||||
}
|
||||
|
||||
setIsOpen(false)
|
||||
toast.success("Updated!")
|
||||
ctx.invalidateQueries()
|
||||
} catch (error: any) {
|
||||
console.error(error)
|
||||
toast.error(error.message)
|
||||
} finally {
|
||||
setIsSaving(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog
|
||||
open={isOpen}
|
||||
onClose={() => setIsOpen(false)}
|
||||
className="fixed z-10 inset-0 overflow-y-auto"
|
||||
>
|
||||
<div className="flex items-center justify-center min-h-screen">
|
||||
<Dialog.Overlay className="fixed inset-0 bg-black opacity-30" />
|
||||
|
||||
<div className="relative bg-white rounded-lg max-w-md w-full mx-auto">
|
||||
<Dialog.Title className="px-5 h-12 flex items-center border-b">
|
||||
Adjust the picture
|
||||
</Dialog.Title>
|
||||
|
||||
<div className="py-5">
|
||||
{image && (
|
||||
<ReactAvatarEditor
|
||||
ref={editorRef}
|
||||
className="mx-auto rounded"
|
||||
image={image}
|
||||
borderRadius={9999}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="h-16 border-t flex items-center px-5">
|
||||
<Button isBlock onClick={cropAndSave} isLoading={isSaving}>
|
||||
Crop and Save
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
|
||||
export const AvatarForm: React.FC<{
|
||||
filename: string | undefined | null
|
||||
name: string
|
||||
site?: string
|
||||
}> = ({ filename, name, site }) => {
|
||||
const [isOpen, setIsOpen] = useState(false)
|
||||
const inputEl = useRef<HTMLInputElement>(null)
|
||||
const [image, setImage] = useState<File | null>(null)
|
||||
const uploadFile = useUploadFile()
|
||||
|
||||
const onClick = () => {
|
||||
inputEl.current?.click()
|
||||
}
|
||||
|
||||
const handleChange = (e: any) => {
|
||||
const files = e.target.files as File[]
|
||||
if (files.length > 0) {
|
||||
setImage(files[0])
|
||||
setIsOpen(true)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<AvatarEditorModal
|
||||
isOpen={isOpen}
|
||||
setIsOpen={setIsOpen}
|
||||
image={image}
|
||||
site={site}
|
||||
uploadFile={uploadFile}
|
||||
/>
|
||||
<input
|
||||
aria-hidden
|
||||
className="hidden"
|
||||
type="file"
|
||||
ref={inputEl}
|
||||
onChange={handleChange}
|
||||
accept="image/*"
|
||||
/>
|
||||
<Avatar
|
||||
images={[getUserContentsUrl(filename)]}
|
||||
size={140}
|
||||
name={name}
|
||||
tabIndex={-1}
|
||||
className="cursor-default focus:ring-2 ring-offset-1 ring-zinc-200"
|
||||
onClick={onClick}
|
||||
/>
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,175 @@
|
||||
import clsx from "clsx"
|
||||
import Link from "next/link"
|
||||
import { useRouter } from "next/router"
|
||||
import React from "react"
|
||||
import { getSiteLink } from "~/lib/helpers"
|
||||
import { trpc } from "~/lib/trpc"
|
||||
import { UniLink } from "../ui/UniLink"
|
||||
import { DashboardSidebar } from "./DashboardSidebar"
|
||||
import { SiteSwitcher } from "./SiteSwitcher"
|
||||
|
||||
export function DashboardLayout({ children }: { children: React.ReactNode }) {
|
||||
const router = useRouter()
|
||||
const subdomain = router.query.subdomain as string
|
||||
|
||||
const sitesResult = trpc.useQuery(["dashbaord.sitesForSwitcher"], {})
|
||||
const sites = sitesResult.data
|
||||
|
||||
const viewerResult = trpc.useQuery(["auth.viewer"])
|
||||
const viewer = viewerResult.data
|
||||
|
||||
const links: {
|
||||
href: string
|
||||
isActive: (ctx: { href: string; pathname: string }) => boolean
|
||||
icon: React.ReactNode
|
||||
text: string
|
||||
}[] = [
|
||||
{
|
||||
href: `/dashboard/${subdomain}`,
|
||||
isActive: ({ href, pathname }) => href === pathname,
|
||||
icon: (
|
||||
<svg width="1em" height="1em" viewBox="0 0 24 24">
|
||||
<path
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth="2"
|
||||
d="M3 3h7v9H3zm11 0h7v5h-7zm0 9h7v9h-7zM3 16h7v5H3z"
|
||||
></path>
|
||||
</svg>
|
||||
),
|
||||
text: "Dashboard",
|
||||
},
|
||||
{
|
||||
href: `/dashboard/${subdomain}/posts`,
|
||||
isActive: ({ href, pathname }) => href === pathname,
|
||||
icon: (
|
||||
<svg width="1em" height="1em" viewBox="0 0 24 24">
|
||||
<path
|
||||
fill="currentColor"
|
||||
d="M19 5v14H5V5h14m0-2H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2z"
|
||||
></path>
|
||||
<path
|
||||
fill="currentColor"
|
||||
d="M14 17H7v-2h7v2zm3-4H7v-2h10v2zm0-4H7V7h10v2z"
|
||||
></path>
|
||||
</svg>
|
||||
),
|
||||
text: "Posts",
|
||||
},
|
||||
{
|
||||
href: `/dashboard/${subdomain}/pages`,
|
||||
isActive: ({ href, pathname }) => href === pathname,
|
||||
icon: (
|
||||
<svg width="1em" height="1em" viewBox="0 0 24 24">
|
||||
<g
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth="2.2"
|
||||
>
|
||||
<path d="M12 11h5m-5-4h5m-9 8V3.6a.6.6 0 0 1 .6-.6h11.8a.6.6 0 0 1 .6.6V17a4 4 0 0 1-4 4v0"></path>
|
||||
<path d="M5 15h7.4c.331 0 .603.267.63.597C13.153 17.115 13.78 21 17 21H6a3 3 0 0 1-3-3v-1a2 2 0 0 1 2-2Z"></path>
|
||||
</g>
|
||||
</svg>
|
||||
),
|
||||
text: "Pages",
|
||||
},
|
||||
{
|
||||
href: `/dashboard/${subdomain}/settings/general`,
|
||||
isActive: ({ pathname }) =>
|
||||
pathname.startsWith(`/dashboard/${subdomain}/settings`),
|
||||
icon: (
|
||||
<svg width="1em" height="1em" viewBox="0 0 16 16">
|
||||
<g
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth="1.5"
|
||||
>
|
||||
<circle cx="8" cy="8" r="1.75"></circle>
|
||||
<path d="m6.75 1.75l-.5 1.5l-1.5 1l-2-.5l-1 2l1.5 1.5v1.5l-1.5 1.5l1 2l2-.5l1.5 1l.5 1.5h2.5l.5-1.5l1.5-1l2 .5l1-2l-1.5-1.5v-1.5l1.5-1.5l-1-2l-2 .5l-1.5-1l-.5-1.5z"></path>
|
||||
</g>
|
||||
</svg>
|
||||
),
|
||||
text: "Settings",
|
||||
},
|
||||
{
|
||||
href: `/dashboard/${subdomain}/account/profile`,
|
||||
isActive: ({ pathname }) =>
|
||||
pathname.startsWith(`/dashboard/${subdomain}/account`),
|
||||
icon: (
|
||||
<svg width="1em" height="1em" viewBox="0 0 24 24">
|
||||
<path
|
||||
fill="currentColor"
|
||||
d="M12 22C6.477 22 2 17.523 2 12S6.477 2 12 2s10 4.477 10 10s-4.477 10-10 10zm-4.987-3.744A7.966 7.966 0 0 0 12 20a7.97 7.97 0 0 0 5.167-1.892A6.979 6.979 0 0 0 12.16 16a6.981 6.981 0 0 0-5.147 2.256zM5.616 16.82A8.975 8.975 0 0 1 12.16 14a8.972 8.972 0 0 1 6.362 2.634a8 8 0 1 0-12.906.187zM12 13a4 4 0 1 1 0-8a4 4 0 0 1 0 8zm0-2a2 2 0 1 0 0-4a2 2 0 0 0 0 4z"
|
||||
></path>
|
||||
</svg>
|
||||
),
|
||||
text: "Account",
|
||||
},
|
||||
]
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="flex">
|
||||
<DashboardSidebar>
|
||||
<div className="mb-2">
|
||||
<SiteSwitcher
|
||||
subdomain={subdomain}
|
||||
sites={sites || []}
|
||||
viewer={viewer}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="px-3 space-y-[2px] text-zinc-500">
|
||||
{links.map((link) => {
|
||||
const active = link.isActive({
|
||||
pathname: router.asPath,
|
||||
href: link.href,
|
||||
})
|
||||
return (
|
||||
<Link href={link.href} key={link.href}>
|
||||
<a
|
||||
className={clsx(
|
||||
`flex px-2 h-8 text-sm items-center rounded-lg`,
|
||||
active
|
||||
? `bg-gray-200 font-medium text-gray-800`
|
||||
: `hover:bg-gray-200 hover:bg-opacity-50`
|
||||
)}
|
||||
>
|
||||
<span className="mr-2 text-lg">{link.icon}</span>
|
||||
<span>{link.text}</span>
|
||||
</a>
|
||||
</Link>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
|
||||
<div className="absolute bottom-0 left-0 right-0 h-20 flex items-center px-4">
|
||||
<UniLink
|
||||
href={getSiteLink({ subdomain })}
|
||||
className="space-x-2 border rounded-lg bg-gray-100 border-gray-200 text-gray-500 hover:border-indigo-300 hover:bg-indigo-100 hover:text-indigo-500 flex w-full h-12 items-center justify-center transition-colors"
|
||||
>
|
||||
<svg width="1em" height="1em" viewBox="0 0 32 32">
|
||||
<path
|
||||
fill="none"
|
||||
stroke="currentcolor"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth="2"
|
||||
d="M14 9H3v20h20V18M18 4h10v10m0-10L14 18"
|
||||
></path>
|
||||
</svg>
|
||||
<span>View Site</span>
|
||||
</UniLink>
|
||||
</div>
|
||||
</DashboardSidebar>
|
||||
{children}
|
||||
</div>
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import clsx from "clsx"
|
||||
|
||||
export const DashboardMain: React.FC<{
|
||||
children: React.ReactNode
|
||||
fullWidth?: boolean
|
||||
}> = ({ children, fullWidth }) => {
|
||||
return (
|
||||
<div className="md:pl-sidebar w-full">
|
||||
<div
|
||||
className={clsx(
|
||||
fullWidth ? "relative" : "max-w-screen-xl relative px-5 py-5 md:px-10"
|
||||
)}
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
export const DashboardSidebar: React.FC<{
|
||||
children: React.ReactNode
|
||||
}> = ({ children }) => {
|
||||
return (
|
||||
<div className="w-sidebar fixed top-0 bottom-0 left-0 bg-zinc-50 z-10">
|
||||
{children}
|
||||
<div className="w-[1px] bg-border absolute top-0 right-0 bottom-0"></div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,255 @@
|
||||
import { Fragment, useEffect, useMemo } from "react"
|
||||
import { getPageVisibility } from "~/lib/page-helpers"
|
||||
import { formatDate } from "~/lib/date"
|
||||
import { TabItem, Tabs } from "../ui/Tabs"
|
||||
import { Menu } from "@headlessui/react"
|
||||
import clsx from "clsx"
|
||||
import { PageVisibilityEnum } from "~/lib/types"
|
||||
import { DashboardMain } from "./DashboardMain"
|
||||
import { useRouter } from "next/router"
|
||||
import { trpc } from "~/lib/trpc"
|
||||
import Link from "next/link"
|
||||
import toast from "react-hot-toast"
|
||||
|
||||
export const PagesManager: React.FC<{
|
||||
isPost: boolean
|
||||
}> = ({ isPost }) => {
|
||||
const router = useRouter()
|
||||
const subdomain = router.query.subdomain as string
|
||||
|
||||
const visibility = useMemo<PageVisibilityEnum>(
|
||||
() =>
|
||||
router.query.visibility
|
||||
? (router.query.visibility as PageVisibilityEnum)
|
||||
: PageVisibilityEnum.All,
|
||||
[router.query.visibility]
|
||||
)
|
||||
const deletePage = trpc.useMutation("site.deletePage")
|
||||
const trpcContext = trpc.useContext()
|
||||
|
||||
useEffect(() => {
|
||||
if (deletePage.isSuccess) {
|
||||
deletePage.reset()
|
||||
toast.success("Deleted!")
|
||||
trpcContext.invalidateQueries("site.pages")
|
||||
}
|
||||
}, [deletePage, trpcContext])
|
||||
|
||||
const pagesResult = trpc.useQuery(
|
||||
[
|
||||
"site.pages",
|
||||
{
|
||||
type: isPost ? "post" : "page",
|
||||
site: subdomain!,
|
||||
take: 1000,
|
||||
visibility,
|
||||
},
|
||||
],
|
||||
{
|
||||
enabled: !!subdomain,
|
||||
}
|
||||
)
|
||||
const pages = pagesResult.data?.nodes
|
||||
|
||||
const tabItems: TabItem[] = [
|
||||
{
|
||||
value: PageVisibilityEnum.All,
|
||||
text: `All ${isPost ? "Posts" : "Pages"}`,
|
||||
},
|
||||
{
|
||||
value: PageVisibilityEnum.Published,
|
||||
text: "Published",
|
||||
},
|
||||
{
|
||||
value: PageVisibilityEnum.Draft,
|
||||
text: "Draft",
|
||||
},
|
||||
{
|
||||
value: PageVisibilityEnum.Scheduled,
|
||||
text: "Scheduled",
|
||||
},
|
||||
].map((item) => ({
|
||||
text: item.text,
|
||||
onClick: () => {
|
||||
const newQuery: Record<string, any> = {
|
||||
...router.query,
|
||||
visibility: item.value,
|
||||
}
|
||||
if (item.value === PageVisibilityEnum.All) {
|
||||
delete newQuery["visibility"]
|
||||
}
|
||||
const search = new URLSearchParams(newQuery).toString()
|
||||
router.push({
|
||||
search,
|
||||
})
|
||||
},
|
||||
active: item.value === visibility,
|
||||
}))
|
||||
|
||||
const getPageEditLink = (page: { id: string }) => {
|
||||
return `/dashboard/${subdomain}/editor?id=${page.id}&type=${
|
||||
isPost ? "post" : "page"
|
||||
}`
|
||||
}
|
||||
|
||||
const getPageMenuItems = (page: { id: string }) => {
|
||||
return [
|
||||
{
|
||||
text: "Edit",
|
||||
icon: (
|
||||
<svg
|
||||
className="w-4 h-4"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="2"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
>
|
||||
<path d="M12 20h9"></path>
|
||||
<path d="M16.5 3.5a2.121 2.121 0 0 1 3 3L7 19l-4 1 1-4L16.5 3.5z"></path>
|
||||
</svg>
|
||||
),
|
||||
onClick() {
|
||||
router.push(getPageEditLink(page))
|
||||
},
|
||||
},
|
||||
{
|
||||
text: "Delete",
|
||||
icon: (
|
||||
<svg
|
||||
className="w-4 h-4"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="2"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
>
|
||||
<polyline points="3 6 5 6 21 6"></polyline>
|
||||
<path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"></path>
|
||||
<line x1="10" y1="11" x2="10" y2="17"></line>
|
||||
<line x1="14" y1="11" x2="14" y2="17"></line>
|
||||
</svg>
|
||||
),
|
||||
onClick() {
|
||||
deletePage.mutate({ pageId: page.id })
|
||||
},
|
||||
},
|
||||
]
|
||||
}
|
||||
|
||||
const title = isPost ? "Posts" : "Pages"
|
||||
|
||||
return (
|
||||
<DashboardMain>
|
||||
<header className="mb-8 flex justify-between items-center">
|
||||
<h2 className="text-2xl font-bold">{title}</h2>
|
||||
<button
|
||||
type="button"
|
||||
className={clsx(
|
||||
`space-x-2 px-3 h-9 inline-flex items-center justify-center text-white rounded-lg text-sm`,
|
||||
|
||||
isPost ? `bg-pink-500` : `bg-blue-500`
|
||||
)}
|
||||
onClick={() =>
|
||||
router.push(
|
||||
`/dashboard/${subdomain}/editor?type=${isPost ? "post" : "page"}`
|
||||
)
|
||||
}
|
||||
>
|
||||
<svg
|
||||
className="w-5 h-5"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="2"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
>
|
||||
<path d="M12 20h9"></path>
|
||||
<path d="M16.5 3.5a2.121 2.121 0 0 1 3 3L7 19l-4 1 1-4L16.5 3.5z"></path>
|
||||
</svg>
|
||||
<span>New {isPost ? "Post" : "Page"}</span>
|
||||
</button>
|
||||
</header>
|
||||
<Tabs items={tabItems} />
|
||||
|
||||
<div className="-mt-3">
|
||||
{pages && pages.length === 0 && (
|
||||
<div className="my-20 text-center text-3xl text-zinc-400">
|
||||
No {isPost ? "Posts" : "Pages"} Yet.
|
||||
</div>
|
||||
)}
|
||||
|
||||
{pages?.map((page) => {
|
||||
return (
|
||||
<Link key={page.id} href={getPageEditLink(page)}>
|
||||
<a className="group relative hover:bg-zinc-100 rounded-lg py-3 px-3 transition-colors -mx-3 flex justify-between">
|
||||
<div>
|
||||
<div className="flex items-center">
|
||||
<span>{page.title}</span>
|
||||
</div>
|
||||
<div className="text-zinc-400 text-xs mt-1">
|
||||
<span className="capitalize">
|
||||
{getPageVisibility(page).toLowerCase()}
|
||||
</span>
|
||||
<span className="mx-2">·</span>
|
||||
<span>{formatDate(page.publishedAt)}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div className="w-10 flex-shrink-0">
|
||||
<Menu>
|
||||
{({ open }) => (
|
||||
<>
|
||||
<Menu.Button as={Fragment}>
|
||||
<button
|
||||
className={clsx(
|
||||
`text-gray-400 relative z-50 w-8 h-8 rounded inline-flex invisible group-hover:visible justify-center items-center`,
|
||||
open ? `bg-gray-200` : `hover:bg-gray-200`
|
||||
)}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
}}
|
||||
>
|
||||
<svg
|
||||
className="w-5 h-5"
|
||||
fill="currentColor"
|
||||
viewBox="0 0 20 20"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
>
|
||||
<path d="M6 10a2 2 0 11-4 0 2 2 0 014 0zM12 10a2 2 0 11-4 0 2 2 0 014 0zM16 12a2 2 0 100-4 2 2 0 000 4z" />
|
||||
</svg>
|
||||
</button>
|
||||
</Menu.Button>
|
||||
<Menu.Items className="text-sm absolute z-20 right-0 bg-white shadow-modal rounded-lg overflow-hidden py-2 w-64">
|
||||
{getPageMenuItems(page).map((item) => {
|
||||
return (
|
||||
<Menu.Item key={item.text}>
|
||||
<button
|
||||
type="button"
|
||||
className="h-10 flex w-full space-x-2 items-center px-3 hover:bg-gray-100"
|
||||
onClick={(e) => {
|
||||
e.preventDefault()
|
||||
item.onClick()
|
||||
}}
|
||||
>
|
||||
<span>{item.icon}</span>
|
||||
<span>{item.text}</span>
|
||||
</button>
|
||||
</Menu.Item>
|
||||
)
|
||||
})}
|
||||
</Menu.Items>
|
||||
</>
|
||||
)}
|
||||
</Menu>
|
||||
</div>
|
||||
</a>
|
||||
</Link>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</DashboardMain>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
import { useRouter } from "next/router"
|
||||
import React from "react"
|
||||
import { type TabItem, Tabs } from "../ui/Tabs"
|
||||
import { DashboardMain } from "./DashboardMain"
|
||||
|
||||
export const SettingsLayout: React.FC<{
|
||||
title: string
|
||||
children: React.ReactNode
|
||||
type: "site" | "account"
|
||||
}> = ({ title, children, type }) => {
|
||||
const router = useRouter()
|
||||
|
||||
const subdomain = router.query.subdomain as string
|
||||
const tabItems: TabItem[] = (
|
||||
type === "site"
|
||||
? [
|
||||
{ text: "General", href: `/dashboard/${subdomain}/settings/general` },
|
||||
{
|
||||
text: "Navigation",
|
||||
href: `/dashboard/${subdomain}/settings/navigation`,
|
||||
},
|
||||
{ text: "Domains", href: `/dashboard/${subdomain}/settings/domains` },
|
||||
]
|
||||
: [{ text: "Profile", href: `/dashboard/${subdomain}/account/profile` }]
|
||||
).map((item) => ({ ...item, active: router.asPath === item.href }))
|
||||
|
||||
return (
|
||||
<DashboardMain>
|
||||
<div className="">
|
||||
<header className="mb-8">
|
||||
<h2 className="text-2xl font-bold">{title}</h2>
|
||||
</header>
|
||||
<div>
|
||||
<Tabs items={tabItems} />
|
||||
<div className="max-w-screen-md">{children}</div>
|
||||
</div>
|
||||
</div>
|
||||
</DashboardMain>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
import { Popover } from "@headlessui/react"
|
||||
import Link from "next/link"
|
||||
import { useMemo } from "react"
|
||||
import { getUserContentsUrl } from "~/lib/user-contents"
|
||||
import { Avatar } from "../ui/Avatar"
|
||||
|
||||
type Props = {
|
||||
subdomain: string
|
||||
sites: { id: string; name: string; subdomain: string; icon?: string | null }[]
|
||||
viewer?: { email: string } | null
|
||||
}
|
||||
|
||||
export const SiteSwitcher: React.FC<Props> = ({ subdomain, sites, viewer }) => {
|
||||
const activeSite = useMemo(
|
||||
() => sites.find((s) => s.subdomain === subdomain),
|
||||
[subdomain, sites]
|
||||
)
|
||||
return (
|
||||
<div className="px-3 pt-3 pb-2 text-sm">
|
||||
<Popover className="relative">
|
||||
<Popover.Button className="h-8 px-2 justify-between flex w-full rounded-lg hover:bg-gray-200 hover:bg-opacity-50 transition-colors items-center">
|
||||
<div className="flex items-center space-x-2">
|
||||
<Avatar
|
||||
images={[getUserContentsUrl(activeSite?.icon)]}
|
||||
name={activeSite?.name}
|
||||
size={22}
|
||||
/>
|
||||
<span className="truncate">{activeSite?.name}</span>
|
||||
</div>
|
||||
<span className="w-5 h-5 text-zinc-400 rounded-full bg-zinc-100 inline-flex items-center justify-center">
|
||||
<svg className="w-4 h-4" viewBox="0 0 14 14">
|
||||
<g
|
||||
stroke="none"
|
||||
strokeWidth="1"
|
||||
fill="currentColor"
|
||||
fillRule="evenodd"
|
||||
>
|
||||
<path d="M7.00,9.48 C7.08,9.48 7.16,9.46 7.24,9.43 C7.31,9.40 7.38,9.35 7.44,9.29 L11.16,5.48 C11.27,5.37 11.32,5.24 11.32,5.08 C11.32,4.98 11.30,4.88 11.25,4.79 C11.20,4.70 11.13,4.64 11.04,4.59 C10.96,4.54 10.86,4.51 10.76,4.51 C10.60,4.51 10.46,4.57 10.34,4.68 L6.76,8.36 L7.24,8.36 L3.65,4.68 C3.53,4.57 3.39,4.51 3.24,4.51 C3.13,4.51 3.03,4.54 2.95,4.59 C2.86,4.64 2.80,4.70 2.75,4.79 C2.70,4.88 2.67,4.98 2.67,5.08 C2.67,5.16 2.68,5.23 2.71,5.30 C2.74,5.37 2.78,5.43 2.83,5.48 L6.55,9.29 C6.69,9.42 6.83,9.48 7.00,9.48 Z"></path>
|
||||
</g>
|
||||
</svg>
|
||||
</span>
|
||||
</Popover.Button>
|
||||
<Popover.Panel className="absolute left-0 z-10 pt-1">
|
||||
<div className="min-w-[280px] rounded-lg shadow-modal bg-white">
|
||||
{viewer && (
|
||||
<div className="px-4 py-2 border-b text-sm text-zinc-500">
|
||||
{viewer.email}
|
||||
</div>
|
||||
)}
|
||||
<div className="p-2">
|
||||
{sites?.map((site) => {
|
||||
return (
|
||||
<Link key={site.id} href={`/dashboard/${site.subdomain}`}>
|
||||
<a className="flex px-2 h-8 rounded-lg items-center justify-between hover:bg-zinc-100">
|
||||
<span className="truncate w-8/12">{site.name}</span>
|
||||
{activeSite?.id === site.id && (
|
||||
<span className="text-accent">
|
||||
<svg
|
||||
className="w-5 h-5"
|
||||
fill="currentColor"
|
||||
viewBox="0 0 20 20"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
>
|
||||
<path
|
||||
fillRule="evenodd"
|
||||
d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z"
|
||||
clipRule="evenodd"
|
||||
/>
|
||||
</svg>
|
||||
</span>
|
||||
)}
|
||||
</a>
|
||||
</Link>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
<div className="border-t py-2 px-2">
|
||||
<Link href={`/dashboard/new-site`}>
|
||||
<a className="rounded-lg text-sm text-zinc-500 flex px-2 h-8 items-center hover:bg-zinc-100">
|
||||
Create a new site
|
||||
</a>
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
</Popover.Panel>
|
||||
</Popover>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
import Link from "next/link"
|
||||
import { logout } from "~/lib/auth.client"
|
||||
import { APP_NAME } from "~/lib/env"
|
||||
import { useStore } from "~/lib/store"
|
||||
|
||||
export function MainLayout({
|
||||
isLoggedIn,
|
||||
children,
|
||||
region,
|
||||
}: {
|
||||
isLoggedIn: boolean
|
||||
children?: React.ReactNode
|
||||
region: string | null
|
||||
}) {
|
||||
const setLoginModalOpened = useStore((store) => store.setLoginModalOpened)
|
||||
|
||||
const links: Array<{ text: string; href?: string; onClick?: () => void }> =
|
||||
isLoggedIn
|
||||
? [
|
||||
{
|
||||
text: "Dashboard",
|
||||
href: "/dashboard",
|
||||
},
|
||||
{
|
||||
text: "Log out",
|
||||
onClick() {
|
||||
logout()
|
||||
},
|
||||
},
|
||||
]
|
||||
: [
|
||||
{
|
||||
text: "Log in",
|
||||
onClick() {
|
||||
setLoginModalOpened(true)
|
||||
},
|
||||
},
|
||||
]
|
||||
return (
|
||||
<>
|
||||
<div className="h-screen flex items-center justify-center">
|
||||
<div className="-mt-20">
|
||||
<div className="max-w-screen-md mx-auto px-5">
|
||||
<div>
|
||||
<span className="inline-block text-3xl lg:text-7xl px-3 rounded-lg py-2 font-bold bg-indigo-600 text-white">
|
||||
{APP_NAME}
|
||||
</span>
|
||||
</div>
|
||||
<div className="italic text-zinc-500 text-sm mt-1">
|
||||
..is under early testing, don{`'`}t use this app in production.
|
||||
</div>
|
||||
<div className="space-x-5 mt-10">
|
||||
{links.map((link) => {
|
||||
if (link.href) {
|
||||
return (
|
||||
<Link href={link.href} key={link.text}>
|
||||
<a className="font-bold nav-link underline">
|
||||
{link.text}
|
||||
</a>
|
||||
</Link>
|
||||
)
|
||||
}
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
className="font-bold nav-link underline"
|
||||
onClick={link.onClick}
|
||||
key={link.text}
|
||||
>
|
||||
{link.text}
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
<div className="mt-10 text-zinc-300 text-xs">
|
||||
<span className="uppercase">Region: {region}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{children}
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
import Link from "next/link"
|
||||
import { useMemo } from "react"
|
||||
import { formatDate } from "~/lib/date"
|
||||
|
||||
type Post = { id: string; publishedAt: string; slug: string; title: string }
|
||||
|
||||
export const SiteArchives: React.FC<{
|
||||
posts: Post[] | undefined
|
||||
}> = ({ posts }) => {
|
||||
const groupedByYear = useMemo<Map<string, Post[]>>(() => {
|
||||
const map = new Map()
|
||||
|
||||
if (posts) {
|
||||
for (const post of posts) {
|
||||
const year = formatDate(post.publishedAt, "YYYY")
|
||||
const items = map.get(year) || []
|
||||
items.push(post)
|
||||
map.set(year, items)
|
||||
}
|
||||
}
|
||||
|
||||
return map
|
||||
}, [posts])
|
||||
|
||||
if (!posts) return null
|
||||
|
||||
return (
|
||||
<>
|
||||
<h2 className="text-xl font-bold page-title">Archives</h2>
|
||||
<div className="mt-5 space-y-5">
|
||||
{[...groupedByYear.keys()].map((year) => {
|
||||
const posts = groupedByYear.get(year)!
|
||||
return (
|
||||
<div key={year}>
|
||||
<h3 className="text-lg font-bold mb-1 text-zinc-700">{year}</h3>
|
||||
{posts.map((post) => {
|
||||
return (
|
||||
<Link key={post.id} href={`/${post.slug}`}>
|
||||
<a className="flex justify-between items-center p-1 px-2 rounded-lg -mx-2 hover:bg-zinc-50">
|
||||
<span className="text-accent font-medium">
|
||||
{post.title}
|
||||
</span>
|
||||
<span className="text-zinc-400 mr-3 font-medium whitespace-nowrap">
|
||||
{formatDate(post.publishedAt, "MMM D")}
|
||||
</span>
|
||||
</a>
|
||||
</Link>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import Link from "next/link"
|
||||
import { formatDate } from "~/lib/date"
|
||||
import { Paginated, type PostOnSiteHome } from "~/lib/types"
|
||||
|
||||
export const SiteHome: React.FC<{
|
||||
posts?: Paginated<PostOnSiteHome>
|
||||
}> = ({ posts }) => {
|
||||
if (!posts) return null
|
||||
return (
|
||||
<div className="space-y-14">
|
||||
{posts.nodes.map((post) => {
|
||||
const excerpt = post.excerpt || post.autoExcerpt
|
||||
return (
|
||||
<div key={post.id} className="block">
|
||||
<h3 className="text-2xl font-medium">
|
||||
<Link href={`/${post.slug}`}>
|
||||
<a className="hover:text-indigo-500">{post.title}</a>
|
||||
</Link>
|
||||
</h3>
|
||||
<div className="text-sm text-zinc-400 mt-1">
|
||||
{formatDate(post.publishedAt)}
|
||||
</div>
|
||||
<div className="mt-3 text-zinc-500">
|
||||
{excerpt}
|
||||
{excerpt && "..."}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,193 @@
|
||||
import clsx from "clsx"
|
||||
import React from "react"
|
||||
import { truthy } from "~/lib/utils"
|
||||
import { logout } from "~/lib/auth.client"
|
||||
import { useStore } from "~/lib/store"
|
||||
import { getUserContentsUrl } from "~/lib/user-contents"
|
||||
import { SubscribeModal } from "../common/SubscribeModal"
|
||||
import { Avatar } from "../ui/Avatar"
|
||||
import { Button } from "../ui/Button"
|
||||
import { UniLink } from "../ui/UniLink"
|
||||
import { IS_PROD } from "~/lib/constants"
|
||||
import { OUR_DOMAIN } from "~/lib/env"
|
||||
import { useRouter } from "next/router"
|
||||
import { SEOHead } from "../common/SEOHead"
|
||||
import { SiteNavigationItem } from "~/lib/types"
|
||||
|
||||
type MenuLink = {
|
||||
label: string
|
||||
url?: string
|
||||
onClick?: () => void
|
||||
}
|
||||
|
||||
const Header: React.FC<{
|
||||
siteName: string | undefined
|
||||
description: string | undefined | null
|
||||
avatars: (string | null | undefined)[]
|
||||
links: MenuLink[]
|
||||
subscribed?: boolean
|
||||
}> = ({ siteName, description, avatars, links, subscribed }) => {
|
||||
const setSubscribeModalOpened = useStore(
|
||||
(store) => store.setSubscribeModalOpened
|
||||
)
|
||||
const router = useRouter()
|
||||
const handleClickSubscribe = () => {
|
||||
setSubscribeModalOpened(true)
|
||||
}
|
||||
|
||||
return (
|
||||
<header className="border-b">
|
||||
<div className="px-5 max-w-screen-md mx-auto">
|
||||
<div className="flex py-10">
|
||||
<div className="flex space-x-6 items-center">
|
||||
<Avatar images={avatars} size={100} name={siteName} />
|
||||
<div>
|
||||
<div className="text-2xl font-bold">{siteName}</div>
|
||||
{description && (
|
||||
<div className="text-gray-500 text-sm">{description}</div>
|
||||
)}
|
||||
<div className="mt-3 text-sm">
|
||||
<Button
|
||||
rounded="full"
|
||||
size="sm"
|
||||
variant={subscribed ? "secondary" : "primary"}
|
||||
onClick={handleClickSubscribe}
|
||||
>
|
||||
<span className="-ml-1">
|
||||
{subscribed ? (
|
||||
<svg
|
||||
className="w-4 h-4 mr-[2px]"
|
||||
fill="currentColor"
|
||||
viewBox="0 0 20 20"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
>
|
||||
<path
|
||||
fillRule="evenodd"
|
||||
d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z"
|
||||
clipRule="evenodd"
|
||||
/>
|
||||
</svg>
|
||||
) : (
|
||||
<svg
|
||||
className="w-5 h-5"
|
||||
fill="currentColor"
|
||||
viewBox="0 0 20 20"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
>
|
||||
<path
|
||||
fillRule="evenodd"
|
||||
d="M10 5a1 1 0 011 1v3h3a1 1 0 110 2h-3v3a1 1 0 11-2 0v-3H6a1 1 0 110-2h3V6a1 1 0 011-1z"
|
||||
clipRule="evenodd"
|
||||
/>
|
||||
</svg>
|
||||
)}
|
||||
</span>
|
||||
<span>{subscribed ? "Subscribed" : "Subscribe"}</span>
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="text-sm text-gray-400">
|
||||
<div className="flex items-center space-x-5">
|
||||
{links.map((link, i) => {
|
||||
const active = router.asPath === link.url
|
||||
return (
|
||||
<UniLink
|
||||
key={`${link.label}${i}`}
|
||||
href={link.url}
|
||||
onClick={link.onClick}
|
||||
className={clsx(
|
||||
`h-10 flex items-center border-b-2 hover:border-gray-500 hover:text-gray-700`,
|
||||
active
|
||||
? `text-indigo-700 border-accent`
|
||||
: `border-transparent`
|
||||
)}
|
||||
>
|
||||
{link.label}
|
||||
</UniLink>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
)
|
||||
}
|
||||
|
||||
export type SiteLayoutProps = {
|
||||
site: {
|
||||
id: string
|
||||
name: string
|
||||
description?: string | null
|
||||
icon?: string | null
|
||||
navigation?: SiteNavigationItem[] | null
|
||||
}
|
||||
isLoggedIn: boolean
|
||||
subscription?: { telegram?: boolean; email?: boolean } | null
|
||||
children: React.ReactNode
|
||||
title?: string | null
|
||||
}
|
||||
|
||||
export const SiteLayout: React.FC<SiteLayoutProps> = ({
|
||||
site,
|
||||
isLoggedIn,
|
||||
subscription,
|
||||
children,
|
||||
title,
|
||||
}) => {
|
||||
const avatars = [getUserContentsUrl(site?.icon)]
|
||||
const setLoginModalOpened = useStore((store) => store.setLoginModalOpened)
|
||||
|
||||
const links: MenuLink[] = [
|
||||
{ label: "Home", url: "/" },
|
||||
...(site.navigation || []),
|
||||
!isLoggedIn && {
|
||||
label: "Log in",
|
||||
onClick() {
|
||||
setLoginModalOpened(true)
|
||||
},
|
||||
},
|
||||
isLoggedIn && {
|
||||
label: "Dashboard",
|
||||
url: `${IS_PROD ? "https" : "http"}://${OUR_DOMAIN}/dashboard`,
|
||||
},
|
||||
isLoggedIn && {
|
||||
label: "Log out",
|
||||
onClick() {
|
||||
logout()
|
||||
},
|
||||
},
|
||||
].filter(truthy)
|
||||
|
||||
const docTitle = title ? `${title} - ${site.name}` : site.name
|
||||
|
||||
return (
|
||||
<>
|
||||
<SEOHead
|
||||
title={docTitle}
|
||||
description={site.description}
|
||||
image={getUserContentsUrl(site.icon)}
|
||||
/>
|
||||
<div>
|
||||
<Header
|
||||
links={links}
|
||||
siteName={site?.name}
|
||||
description={site?.description}
|
||||
avatars={avatars}
|
||||
subscribed={!!subscription}
|
||||
/>
|
||||
<div className={clsx(`max-w-screen-md mx-auto px-5 pb-12`, `pt-12`)}>
|
||||
{children}
|
||||
</div>
|
||||
</div>
|
||||
{site.id && (
|
||||
<SubscribeModal
|
||||
siteId={site.id}
|
||||
subscription={subscription}
|
||||
isLoggedIn={isLoggedIn}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import type { PageType } from "~/lib/db.server"
|
||||
import { formatDate } from "~/lib/date"
|
||||
|
||||
export const SitePage: React.FC<{
|
||||
page: {
|
||||
type: PageType
|
||||
publishedAt: string
|
||||
title: string
|
||||
content: string
|
||||
}
|
||||
}> = ({ page }) => {
|
||||
return (
|
||||
<>
|
||||
<div className="">
|
||||
{page.type === "POST" ? (
|
||||
<h2 className="text-4xl font-bold">{page.title}</h2>
|
||||
) : (
|
||||
<h2 className="text-xl font-bold page-title">{page.title}</h2>
|
||||
)}
|
||||
{page.type === "POST" && (
|
||||
<div className="text-zinc-400 italic mt-2">
|
||||
{formatDate(page.publishedAt)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div
|
||||
className="my-8 prose"
|
||||
dangerouslySetInnerHTML={{ __html: page.content }}
|
||||
></div>
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
import clsx from "clsx"
|
||||
import React, { useMemo } from "react"
|
||||
|
||||
export const Avatar: React.FC<
|
||||
{
|
||||
images: (string | null | undefined)[]
|
||||
name?: string | null
|
||||
size?: number
|
||||
rounded?: boolean
|
||||
} & React.HTMLAttributes<HTMLSpanElement>
|
||||
> = ({ images, size, name, className, rounded, ...props }) => {
|
||||
size = size || 60
|
||||
|
||||
const fontSize = size * 0.5
|
||||
|
||||
const nameAbbr = (name || "")
|
||||
.split(" ")
|
||||
.slice(0, 2)
|
||||
.map((word) => word[0])
|
||||
.join("")
|
||||
|
||||
const image = useMemo(() => {
|
||||
for (const image of images) {
|
||||
if (image) return image
|
||||
}
|
||||
}, [images])
|
||||
|
||||
const borderRadius = rounded === false ? "rounded-lg" : "rounded-full"
|
||||
|
||||
if (!image) {
|
||||
return (
|
||||
<span
|
||||
{...props}
|
||||
className={clsx(
|
||||
`inline-flex text-white bg-pink-400 items-center justify-center text-xl font-medium uppercase flex-shrink-0`,
|
||||
borderRadius,
|
||||
className
|
||||
)}
|
||||
style={{
|
||||
width: `${size}px`,
|
||||
height: `${size}px`,
|
||||
fontSize: `${fontSize}px`,
|
||||
}}
|
||||
>
|
||||
{nameAbbr}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<span
|
||||
{...props}
|
||||
className={clsx(
|
||||
`inline-flex text-zinc-500 bg-pink-400 flex-shrink-0 items-center justify-center text-xl font-medium uppercase`,
|
||||
borderRadius,
|
||||
className
|
||||
)}
|
||||
style={{
|
||||
width: `${size}px`,
|
||||
height: `${size}px`,
|
||||
}}
|
||||
>
|
||||
<img
|
||||
className={borderRadius}
|
||||
src={image}
|
||||
width={size}
|
||||
height={size}
|
||||
alt={name || ""}
|
||||
/>
|
||||
</span>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import clsx from "clsx"
|
||||
import React from "react"
|
||||
|
||||
export const Badge: React.FC<{
|
||||
children: React.ReactNode
|
||||
className?: string
|
||||
}> = ({ children, className }) => {
|
||||
return (
|
||||
<span
|
||||
className={clsx(
|
||||
`relative rounded uppercase bg-yellow-400 text-white h-5 inline-flex items-center px-1 font-semibold text-xs`,
|
||||
className,
|
||||
)}
|
||||
>
|
||||
{children}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
import React from "react"
|
||||
import clsx from "clsx"
|
||||
|
||||
export const Button: React.FC<
|
||||
React.ButtonHTMLAttributes<HTMLButtonElement> & {
|
||||
isLoading?: boolean
|
||||
isBlock?: boolean
|
||||
isDisabled?: boolean
|
||||
variant?: "primary" | "secondary" | "text"
|
||||
variantColor?: "green" | "red" | "gray"
|
||||
size?: "sm"
|
||||
rounded?: "full" | "lg"
|
||||
}
|
||||
> = ({
|
||||
type,
|
||||
children,
|
||||
className,
|
||||
isLoading,
|
||||
isDisabled,
|
||||
isBlock,
|
||||
variant,
|
||||
variantColor,
|
||||
size,
|
||||
rounded,
|
||||
...props
|
||||
}) => {
|
||||
return (
|
||||
<button
|
||||
{...props}
|
||||
type={type || "button"}
|
||||
disabled={isDisabled}
|
||||
className={clsx(
|
||||
className,
|
||||
"button",
|
||||
isLoading && "is-loading",
|
||||
isBlock && `is-block`,
|
||||
variantColor && `is-${variantColor}`,
|
||||
isDisabled && `is-disabled`,
|
||||
size && `is-${size}`,
|
||||
`is-${variant || "primary"}`,
|
||||
rounded === "full" ? "rounded-full" : "rounded-lg"
|
||||
)}
|
||||
>
|
||||
{children}
|
||||
</button>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
import { useEffect, useRef, useState } from "react"
|
||||
import { EditorState } from "@codemirror/state"
|
||||
import {
|
||||
EditorView,
|
||||
keymap,
|
||||
type ViewUpdate,
|
||||
dropCursor,
|
||||
drawSelection,
|
||||
crosshairCursor,
|
||||
placeholder as placeholderExtension,
|
||||
} from "@codemirror/view"
|
||||
import {
|
||||
history,
|
||||
defaultKeymap,
|
||||
historyKeymap,
|
||||
indentWithTab,
|
||||
} from "@codemirror/commands"
|
||||
import { markdown } from "@codemirror/lang-markdown"
|
||||
import {
|
||||
defaultHighlightStyle,
|
||||
indentOnInput,
|
||||
syntaxHighlighting,
|
||||
} from "@codemirror/language"
|
||||
import { IS_PROD } from "~/lib/constants"
|
||||
|
||||
const theme = EditorView.theme({
|
||||
".cm-scroller": {
|
||||
fontFamily: "var(--font-sans)",
|
||||
fontSize: "1rem",
|
||||
overflow: "auto",
|
||||
},
|
||||
".cm-content": {
|
||||
minHeight: "400px",
|
||||
},
|
||||
"&.cm-editor.cm-focused": {
|
||||
outline: "none",
|
||||
},
|
||||
})
|
||||
|
||||
export const useEditor = ({
|
||||
value,
|
||||
onChange,
|
||||
placeholder,
|
||||
onDropFile,
|
||||
}: {
|
||||
value: string
|
||||
onChange: (value: string) => void
|
||||
placeholder?: string
|
||||
onDropFile?: (file: File, view: EditorView) => void
|
||||
}) => {
|
||||
const editorRef = useRef<HTMLDivElement | null>(null)
|
||||
const [view, setView] = useState<EditorView | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
const updateListener = EditorView.updateListener.of((vu: ViewUpdate) => {
|
||||
if (vu.docChanged && typeof onChange === "function") {
|
||||
const doc = vu.state.doc
|
||||
const value = doc.toString()
|
||||
onChange(value)
|
||||
}
|
||||
})
|
||||
|
||||
const view = new EditorView({
|
||||
state: EditorState.create({
|
||||
doc: "",
|
||||
extensions: [
|
||||
keymap.of([indentWithTab, ...defaultKeymap, ...historyKeymap]),
|
||||
history(),
|
||||
dropCursor(),
|
||||
drawSelection(),
|
||||
indentOnInput(),
|
||||
crosshairCursor(),
|
||||
EditorState.allowMultipleSelections.of(true),
|
||||
updateListener,
|
||||
EditorView.lineWrapping,
|
||||
markdown(),
|
||||
placeholderExtension(placeholder || ""),
|
||||
syntaxHighlighting(defaultHighlightStyle, { fallback: true }),
|
||||
theme,
|
||||
EditorView.domEventHandlers({
|
||||
drop(e) {
|
||||
const file = e.dataTransfer?.items[0]?.getAsFile()
|
||||
if (!file) return
|
||||
|
||||
onDropFile?.(file, view)
|
||||
},
|
||||
}),
|
||||
],
|
||||
}),
|
||||
parent: editorRef.current!,
|
||||
})
|
||||
|
||||
setView(view)
|
||||
|
||||
return () => {
|
||||
view.destroy()
|
||||
setView(null)
|
||||
}
|
||||
}, [onChange, placeholder, onDropFile])
|
||||
|
||||
// Update view state when `value` changed
|
||||
useEffect(() => {
|
||||
const currentValue = view ? view.state.doc.toString() : ""
|
||||
if (view && value !== currentValue) {
|
||||
if (!IS_PROD) {
|
||||
console.log("updating editor value", value)
|
||||
}
|
||||
view.dispatch({
|
||||
changes: { from: 0, to: currentValue.length, insert: value || "" },
|
||||
})
|
||||
}
|
||||
}, [value, view])
|
||||
|
||||
return {
|
||||
view,
|
||||
editorRef,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
import clsx from "clsx"
|
||||
import { DetailedHTMLProps, forwardRef, InputHTMLAttributes } from "react"
|
||||
|
||||
type Props = DetailedHTMLProps<
|
||||
InputHTMLAttributes<HTMLInputElement>,
|
||||
HTMLInputElement
|
||||
> & {
|
||||
label?: string
|
||||
addon?: string
|
||||
isBlock?: boolean
|
||||
error?: string
|
||||
}
|
||||
|
||||
export const Input = forwardRef<HTMLInputElement, Props>(function Input(
|
||||
{ label, addon, className, isBlock, error, ...inputProps },
|
||||
ref
|
||||
) {
|
||||
const hasAddon = !!addon
|
||||
return (
|
||||
<div>
|
||||
{label && (
|
||||
<label className="form-label" htmlFor={inputProps.id}>
|
||||
{label}
|
||||
</label>
|
||||
)}
|
||||
<div className="flex items-center">
|
||||
<input
|
||||
{...inputProps}
|
||||
ref={ref}
|
||||
className={clsx(
|
||||
"input",
|
||||
hasAddon && `has-addon`,
|
||||
isBlock && `is-block`,
|
||||
className
|
||||
)}
|
||||
/>
|
||||
{addon && (
|
||||
<span className="flex items-center px-3 text-gray-600 bg-gray-50 h-10 border border-l-0 rounded-r-lg relative -z-10">
|
||||
{addon}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
{error && <div className="text-sm mt-1 text-red-500">{error}</div>}
|
||||
</div>
|
||||
)
|
||||
})
|
||||
@@ -0,0 +1,51 @@
|
||||
import { Dialog } from "@headlessui/react"
|
||||
import clsx from "clsx"
|
||||
import React from "react"
|
||||
|
||||
export const Modal: React.FC<{
|
||||
open: boolean
|
||||
setOpen: (open: boolean) => void
|
||||
children: React.ReactNode
|
||||
title?: string
|
||||
titleIcon?: React.ReactNode
|
||||
size?: "md" | "lg" | "sm"
|
||||
}> = ({ open, setOpen, children, title, titleIcon, size = "md" }) => {
|
||||
return (
|
||||
<Dialog
|
||||
open={open}
|
||||
onClose={() => setOpen(false)}
|
||||
className="relative z-50"
|
||||
>
|
||||
{/* The backdrop, rendered as a fixed sibling to the panel container */}
|
||||
<div className="fixed inset-0 bg-black/30 z-40" aria-hidden="true" />
|
||||
|
||||
{/* Full-screen container to center the panel */}
|
||||
<div
|
||||
className={clsx(
|
||||
`fixed inset-0 flex items-center justify-center p-4 z-40`,
|
||||
)}
|
||||
>
|
||||
{/* The actual dialog panel */}
|
||||
<Dialog.Panel
|
||||
className={clsx(
|
||||
`mx-auto rounded-lg bg-white w-full shadow-modal -mt-40`,
|
||||
|
||||
size === "md"
|
||||
? `max-w-md`
|
||||
: size === "lg"
|
||||
? `max-w-lg`
|
||||
: `max-w-sm`,
|
||||
)}
|
||||
>
|
||||
{title && (
|
||||
<Dialog.Title className="text-lg border-b h-14 flex items-center px-5 space-x-2">
|
||||
{titleIcon && <span>{titleIcon}</span>}
|
||||
<span>{title}</span>
|
||||
</Dialog.Title>
|
||||
)}
|
||||
{children}
|
||||
</Dialog.Panel>
|
||||
</div>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
import clsx from "clsx"
|
||||
import React from "react"
|
||||
import { UniLink } from "./UniLink"
|
||||
|
||||
export type TabItem = {
|
||||
text: string
|
||||
href?: string
|
||||
onClick?: () => void
|
||||
active?: boolean
|
||||
}
|
||||
|
||||
export const Tabs: React.FC<{ items: TabItem[] }> = ({ items }) => {
|
||||
return (
|
||||
<div className="flex border-b space-x-5 mb-8">
|
||||
{items.map((item) => {
|
||||
return (
|
||||
<UniLink
|
||||
href={item.href}
|
||||
onClick={item.onClick}
|
||||
key={item.text}
|
||||
className={clsx(
|
||||
`border-b-2 text-sm inline-flex items-center h-10`,
|
||||
item.active
|
||||
? `border-accent text-black font-medium`
|
||||
: `text-gray-500 border-transparent hover:border-gray-300`,
|
||||
)}
|
||||
>
|
||||
{item.text}
|
||||
</UniLink>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
import Link from "next/link"
|
||||
|
||||
export const UniLink: React.FC<{
|
||||
href?: string
|
||||
onClick?: () => void
|
||||
children: React.ReactNode
|
||||
className?: string
|
||||
}> = ({ href, onClick, children, className }) => {
|
||||
if (onClick) {
|
||||
return (
|
||||
<button className={className} onClick={onClick}>
|
||||
{children}
|
||||
</button>
|
||||
)
|
||||
}
|
||||
|
||||
if (!href) {
|
||||
console.error("missing href")
|
||||
return null
|
||||
}
|
||||
|
||||
const isExternal = href && /^https?:\/\//.test(href)
|
||||
|
||||
if (isExternal) {
|
||||
return (
|
||||
<a
|
||||
className={className}
|
||||
href={href}
|
||||
target="_blank"
|
||||
rel="nofollow noreferrer"
|
||||
>
|
||||
{children}
|
||||
</a>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<Link href={href}>
|
||||
<a className={className}>{children}</a>
|
||||
</Link>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
.code {
|
||||
@apply my-5;
|
||||
@apply relative;
|
||||
color: var(--code-fg);
|
||||
}
|
||||
|
||||
.code pre {
|
||||
@apply p-5;
|
||||
@apply rounded-lg;
|
||||
@apply whitespace-pre;
|
||||
@apply font-mono;
|
||||
background-color: var(--code-bg);
|
||||
}
|
||||
|
||||
.code:before {
|
||||
content: attr(data-lang);
|
||||
color: var(--lang-color);
|
||||
@apply absolute;
|
||||
@apply right-3;
|
||||
@apply top-2;
|
||||
@apply text-xs;
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
@import "./variables.css";
|
||||
@import "./tailwind.css";
|
||||
@import "./prose.css";
|
||||
@import "./code.css";
|
||||
@import "./prism-dark.css";
|
||||
@@ -0,0 +1,81 @@
|
||||
/** based on prism tomorror */
|
||||
|
||||
.code {
|
||||
--lang-color: #8d8c8c;
|
||||
--code-bg: #2d2d2d;
|
||||
--code-fg: #ccc;
|
||||
}
|
||||
|
||||
.token.comment,
|
||||
.token.block-comment,
|
||||
.token.prolog,
|
||||
.token.doctype,
|
||||
.token.cdata {
|
||||
color: #999;
|
||||
}
|
||||
|
||||
.token.punctuation {
|
||||
color: #ccc;
|
||||
}
|
||||
|
||||
.token.tag,
|
||||
.token.attr-name,
|
||||
.token.namespace,
|
||||
.token.deleted {
|
||||
color: #e2777a;
|
||||
}
|
||||
|
||||
.token.function-name {
|
||||
color: #6196cc;
|
||||
}
|
||||
|
||||
.token.boolean,
|
||||
.token.number,
|
||||
.token.function {
|
||||
color: #f08d49;
|
||||
}
|
||||
|
||||
.token.property,
|
||||
.token.class-name,
|
||||
.token.constant,
|
||||
.token.symbol {
|
||||
color: #f8c555;
|
||||
}
|
||||
|
||||
.token.selector,
|
||||
.token.important,
|
||||
.token.atrule,
|
||||
.token.keyword,
|
||||
.token.builtin {
|
||||
color: #cc99cd;
|
||||
}
|
||||
|
||||
.token.string,
|
||||
.token.char,
|
||||
.token.attr-value,
|
||||
.token.regex,
|
||||
.token.variable {
|
||||
color: #7ec699;
|
||||
}
|
||||
|
||||
.token.operator,
|
||||
.token.entity,
|
||||
.token.url {
|
||||
color: #67cdcc;
|
||||
}
|
||||
|
||||
.token.important,
|
||||
.token.bold {
|
||||
font-weight: bold;
|
||||
}
|
||||
.token.italic {
|
||||
font-style: italic;
|
||||
}
|
||||
|
||||
.token.entity {
|
||||
cursor: help;
|
||||
}
|
||||
|
||||
.token.inserted {
|
||||
color: green;
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
.prose > p {
|
||||
@apply my-5;
|
||||
}
|
||||
|
||||
.prose > *:first-child {
|
||||
@apply mt-0;
|
||||
}
|
||||
|
||||
.prose {
|
||||
@apply text-lg;
|
||||
}
|
||||
|
||||
.prose h2 {
|
||||
@apply text-3xl font-semibold;
|
||||
@apply my-5;
|
||||
}
|
||||
|
||||
.prose h3 {
|
||||
@apply text-2xl font-semibold;
|
||||
}
|
||||
|
||||
.prose h4 {
|
||||
@apply text-xl font-semibold;
|
||||
}
|
||||
|
||||
.prose blockquote {
|
||||
@apply border-l-4 border-indigo-300;
|
||||
@apply pl-4;
|
||||
@apply italic;
|
||||
@apply text-zinc-600;
|
||||
}
|
||||
|
||||
.prose ul {
|
||||
@apply list-disc;
|
||||
@apply pl-5;
|
||||
}
|
||||
|
||||
.prose ol {
|
||||
@apply list-decimal;
|
||||
@apply pl-5;
|
||||
}
|
||||
|
||||
.prose > ul,
|
||||
.prose > ol {
|
||||
@apply my-5;
|
||||
}
|
||||
|
||||
.prose a {
|
||||
@apply text-indigo-600;
|
||||
@apply underline;
|
||||
}
|
||||
|
||||
.prose pre {
|
||||
@apply overflow-auto;
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
@tailwind base;
|
||||
@tailwind components;
|
||||
@tailwind utilities;
|
||||
|
||||
*,
|
||||
*:after,
|
||||
*:before {
|
||||
border-color: var(--border-color);
|
||||
}
|
||||
|
||||
.container {
|
||||
@apply max-w-screen-xl;
|
||||
@apply mx-auto;
|
||||
}
|
||||
|
||||
.button {
|
||||
@apply inline-flex;
|
||||
@apply items-center;
|
||||
@apply justify-center;
|
||||
@apply h-8;
|
||||
@apply px-3;
|
||||
@apply min-w-[100px];
|
||||
@apply shadow-button;
|
||||
@apply whitespace-nowrap;
|
||||
@apply font-medium;
|
||||
@apply transition-colors;
|
||||
}
|
||||
|
||||
.button.is-loading {
|
||||
@apply opacity-50;
|
||||
}
|
||||
|
||||
.button[disabled] {
|
||||
@apply opacity-50;
|
||||
@apply cursor-not-allowed;
|
||||
}
|
||||
|
||||
.button.is-loading:before {
|
||||
margin-right: 0.5rem;
|
||||
height: 1rem;
|
||||
width: 1rem;
|
||||
border-radius: 9999px;
|
||||
border-width: 2px;
|
||||
content: "";
|
||||
border-top-color: transparent;
|
||||
border-left-color: transparent;
|
||||
border-bottom-color: currentColor;
|
||||
border-right-color: currentColor;
|
||||
@apply animate-spin;
|
||||
}
|
||||
|
||||
.button.is-block {
|
||||
@apply w-full;
|
||||
}
|
||||
|
||||
.button.is-primary {
|
||||
--shadow-color-button: theme("colors.indigo.700");
|
||||
@apply bg-indigo-500 hover:bg-indigo-600 focus:bg-indigo-700;
|
||||
@apply text-white;
|
||||
}
|
||||
|
||||
.button.is-secondary {
|
||||
@apply bg-gray-50 hover:bg-gray-100 focus:bg-gray-200;
|
||||
@apply text-gray-500;
|
||||
}
|
||||
|
||||
.button.is-text {
|
||||
@apply shadow-none;
|
||||
@apply text-gray-500;
|
||||
@apply hover:bg-gray-50 focus:bg-gray-100;
|
||||
}
|
||||
|
||||
.button.is-green {
|
||||
--shadow-color-button: theme("colors.green.700");
|
||||
@apply bg-green-500 hover:bg-green-600 focus:bg-green-700;
|
||||
}
|
||||
|
||||
.button.is-red {
|
||||
--shadow-color-button: theme("colors.red.700");
|
||||
@apply bg-red-500 hover:bg-red-600 focus:bg-red-700;
|
||||
}
|
||||
|
||||
.button.is-gray {
|
||||
--shadow-color-button: theme("colors.gray.700");
|
||||
@apply bg-gray-500 hover:bg-gray-600 focus:bg-gray-700;
|
||||
}
|
||||
|
||||
.button.is-sm {
|
||||
@apply h-7;
|
||||
@apply px-2;
|
||||
@apply text-xs;
|
||||
@apply min-w-[auto];
|
||||
}
|
||||
|
||||
.input {
|
||||
@apply border;
|
||||
@apply outline-none;
|
||||
@apply rounded-lg;
|
||||
@apply px-3;
|
||||
@apply h-10;
|
||||
@apply inline-flex;
|
||||
@apply items-center;
|
||||
@apply focus:ring-1;
|
||||
@apply focus:ring-indigo-400;
|
||||
@apply focus:border-indigo-400;
|
||||
}
|
||||
|
||||
.input.is-block {
|
||||
@apply w-full;
|
||||
}
|
||||
|
||||
.input.has-addon {
|
||||
@apply rounded-r-none;
|
||||
}
|
||||
|
||||
textarea.input {
|
||||
@apply h-auto;
|
||||
@apply py-3;
|
||||
@apply px-3;
|
||||
}
|
||||
|
||||
.form-label {
|
||||
@apply block;
|
||||
@apply mb-2;
|
||||
@apply text-sm;
|
||||
@apply font-bold;
|
||||
@apply text-gray-700;
|
||||
}
|
||||
|
||||
.post-status-circle {
|
||||
@apply h-[15px] w-[15px];
|
||||
@apply bg-green-500;
|
||||
@apply inline-block;
|
||||
@apply rounded-full;
|
||||
@apply relative;
|
||||
}
|
||||
|
||||
.post-status-circle:before {
|
||||
content: "";
|
||||
@apply absolute;
|
||||
@apply left-1/2;
|
||||
@apply top-1/2;
|
||||
@apply bg-white;
|
||||
@apply h-[10px] w-[10px];
|
||||
@apply rounded-full;
|
||||
@apply -translate-x-1/2;
|
||||
@apply -translate-y-1/2;
|
||||
}
|
||||
|
||||
.post-status-circle.is-draft {
|
||||
@apply bg-gray-300;
|
||||
}
|
||||
|
||||
.post-status-circle.is-scheduled {
|
||||
@apply bg-yellow-500;
|
||||
}
|
||||
|
||||
.page-title {
|
||||
@apply relative;
|
||||
@apply text-3xl;
|
||||
@apply font-extrabold;
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
:root {
|
||||
--border-color: #eee;
|
||||
--font-fans: theme("fontFamily.sans");
|
||||
--shadow-color-button: theme("colors.gray.300");
|
||||
--accent-color: theme("colors.indigo.500");
|
||||
/* Accent color for form controls */
|
||||
accent-color: var(--accent-color);
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
import { trpc } from "~/lib/trpc"
|
||||
|
||||
export const useSignedJwt = () => {
|
||||
const jwt = trpc.useQuery(["user.getSignedJwt"], {
|
||||
refetchInterval: 60_000,
|
||||
})
|
||||
return jwt.data
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
import { useCallback } from "react"
|
||||
import { R2_URL } from "~/lib/env"
|
||||
import { useSignedJwt } from "./useSignedJwt"
|
||||
|
||||
export const useUploadFile = () => {
|
||||
const signedJwt = useSignedJwt()
|
||||
|
||||
const uploadFile = useCallback<UploadFile>(
|
||||
async (blob, filename) => {
|
||||
if (!signedJwt) {
|
||||
throw new Error("failed to retrieve signed jwt, please try again")
|
||||
}
|
||||
|
||||
const form = new FormData()
|
||||
form.append("file", blob, filename)
|
||||
const res = await fetch(R2_URL, {
|
||||
body: form,
|
||||
method: "post",
|
||||
headers: {
|
||||
authorization: `Bearer ${signedJwt}`,
|
||||
},
|
||||
})
|
||||
if (!res.ok) {
|
||||
throw new Error(await res.text())
|
||||
}
|
||||
const data = await res.json()
|
||||
return data
|
||||
},
|
||||
[signedJwt]
|
||||
)
|
||||
|
||||
return uploadFile
|
||||
}
|
||||
|
||||
export type UploadFile = (
|
||||
blob: Blob,
|
||||
filename: string
|
||||
) => Promise<{ key: string }>
|
||||
@@ -0,0 +1,12 @@
|
||||
import { OUR_DOMAIN } from "./env"
|
||||
|
||||
export const logout = () => {
|
||||
const url = new URL(`${location.protocol}//${OUR_DOMAIN}/api/logout`)
|
||||
if (location.host !== OUR_DOMAIN) {
|
||||
url.searchParams.set(
|
||||
"next",
|
||||
`${location.protocol}//${location.host}/api/logout`
|
||||
)
|
||||
}
|
||||
location.href = url.href
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
import type { User, Membership } from "~/lib/db.server"
|
||||
import { prismaRead } from "./db.server"
|
||||
import dayjs from "dayjs"
|
||||
import Cookie, { CookieSerializeOptions } from "cookie"
|
||||
import { AUTH_COOKIE_NAME } from "./env.server"
|
||||
import { IS_PROD } from "./constants"
|
||||
import { IncomingMessage } from "http"
|
||||
import { OUR_DOMAIN } from "./env"
|
||||
|
||||
export type AuthUser = User & {
|
||||
memberships: Membership[]
|
||||
}
|
||||
|
||||
export const getAuthTokenFromRequest = (request: IncomingMessage) => {
|
||||
let token = request.headers.authorization?.replace(/[Bb]earer\s/, "")
|
||||
if (!token) {
|
||||
const cookieHeader = request.headers.cookie
|
||||
if (cookieHeader) {
|
||||
const value = Cookie.parse(cookieHeader)[AUTH_COOKIE_NAME]
|
||||
token = value
|
||||
}
|
||||
}
|
||||
return token
|
||||
}
|
||||
|
||||
const findUserFromToken = async (token: string) => {
|
||||
const accessToken = await prismaRead.accessToken.findUnique({
|
||||
where: {
|
||||
token,
|
||||
},
|
||||
include: {
|
||||
user: {
|
||||
include: {
|
||||
memberships: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
return accessToken?.user
|
||||
}
|
||||
|
||||
export const getAuthUser = async <TRequireAuth extends boolean | undefined>(
|
||||
request: IncomingMessage,
|
||||
requireAuth?: TRequireAuth
|
||||
) => {
|
||||
const token = getAuthTokenFromRequest(request)
|
||||
|
||||
let user: AuthUser | null | undefined = null
|
||||
|
||||
if (token) {
|
||||
user = await findUserFromToken(token)
|
||||
}
|
||||
|
||||
if (!user && requireAuth) {
|
||||
throw new Error("require auth")
|
||||
}
|
||||
|
||||
return user as TRequireAuth extends true
|
||||
? AuthUser
|
||||
: AuthUser | null | undefined
|
||||
}
|
||||
|
||||
export const getAuthCookieOptions = ({
|
||||
domain,
|
||||
clearCookie,
|
||||
}: {
|
||||
domain?: string
|
||||
clearCookie?: boolean
|
||||
}): CookieSerializeOptions => {
|
||||
return {
|
||||
path: "/",
|
||||
httpOnly: true,
|
||||
sameSite: "lax",
|
||||
expires: clearCookie ? new Date() : dayjs().add(6, "month").toDate(),
|
||||
secure: IS_PROD,
|
||||
domain: IS_PROD ? `.${domain || OUR_DOMAIN}` : undefined,
|
||||
}
|
||||
}
|
||||
|
||||
export const generateCookie = (
|
||||
options:
|
||||
| { type: "clear"; domain?: string }
|
||||
| { type: "auth"; token: string; domain?: string }
|
||||
) => {
|
||||
if (options.type === "clear") {
|
||||
return Cookie.serialize(
|
||||
AUTH_COOKIE_NAME,
|
||||
"",
|
||||
getAuthCookieOptions({ domain: options.domain, clearCookie: true })
|
||||
)
|
||||
}
|
||||
return Cookie.serialize(
|
||||
AUTH_COOKIE_NAME,
|
||||
options.token,
|
||||
getAuthCookieOptions({ domain: options.domain })
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
export const IS_BROWSER = typeof document !== "undefined"
|
||||
|
||||
export const IS_PROD = IS_BROWSER
|
||||
? !location.hostname.endsWith("localhost")
|
||||
: process.env.NODE_ENV === "production"
|
||||
@@ -0,0 +1,8 @@
|
||||
import dayjs from "dayjs"
|
||||
|
||||
export const formatDate = (
|
||||
date: string | Date,
|
||||
format: "MMM D" | "MMM D, YYYY" | "YYYY" = "MMM D, YYYY"
|
||||
) => {
|
||||
return dayjs(date).format(format)
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
import { PrismaClient, type Prisma } from "@prisma/client"
|
||||
import { IS_BROWSER, IS_PROD } from "./constants"
|
||||
import { singleton } from "./singleton.server"
|
||||
|
||||
const logLevel: Prisma.LogLevel[] = IS_PROD
|
||||
? ["info", "error", "warn"]
|
||||
: ["info", "warn", "error", "query"]
|
||||
|
||||
const createPrisma = (readonly: boolean) => {
|
||||
if (!IS_PROD && !IS_BROWSER) {
|
||||
for (const k in require.cache) {
|
||||
if (k.includes("prisma")) {
|
||||
delete require.cache[k]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let url = process.env.DATABASE_URL
|
||||
|
||||
// DATABASE_URL is not set during production build in docker
|
||||
// But Prisma is actually used there, so just return a fake one
|
||||
// It's weird that @__PURE__ doesn't work for Next.js
|
||||
if (!url) return {} as PrismaClient
|
||||
|
||||
if (url && readonly && IS_PROD) {
|
||||
url = url.replace(":5432", ":5433")
|
||||
}
|
||||
|
||||
console.log("connecting to", url)
|
||||
|
||||
const client = new PrismaClient({
|
||||
log: logLevel,
|
||||
datasources: url
|
||||
? {
|
||||
db: {
|
||||
url,
|
||||
},
|
||||
}
|
||||
: undefined,
|
||||
})
|
||||
|
||||
client.$use(async (params, next) => {
|
||||
const now = Date.now()
|
||||
const result = await next(params)
|
||||
const end = Date.now()
|
||||
const duration = Math.floor(end - now)
|
||||
console.log("query took", duration, "ms")
|
||||
// See results here
|
||||
return result
|
||||
})
|
||||
|
||||
return client
|
||||
}
|
||||
|
||||
export const prismaPrimary = /* @__PURE__ */ singleton("prisma-primary", () =>
|
||||
createPrisma(false)
|
||||
)
|
||||
|
||||
export const prismaRead = /* @__PURE__ */ singleton("prisma-read", () =>
|
||||
createPrisma(true)
|
||||
)
|
||||
|
||||
export * from "@prisma/client"
|
||||
@@ -0,0 +1,9 @@
|
||||
export const R2_API_TOKEN = process.env.R2_API_TOKEN
|
||||
export const MAILGUN_APIKEY = process.env.MAILGUN_APIKEY
|
||||
export const MAILGUN_DOMAIN = process.env.MAILGUN_DOMAIN
|
||||
export const ENCRYPT_SECRET = process.env.ENCRYPT_SECRET
|
||||
|
||||
export const AUTH_COOKIE_NAME = process.env.AUTH_COOKIE_NAME
|
||||
export const PRIMARY_REGION = process.env.PRIMARY_REGION
|
||||
export const FLY_REGION = process.env.FLY_REGION || "local"
|
||||
export const IS_PRIMARY_REGION = FLY_REGION === PRIMARY_REGION
|
||||
@@ -0,0 +1,6 @@
|
||||
import { IS_PROD } from "./constants"
|
||||
|
||||
export const APP_NAME = process.env.NEXT_PUBLIC_APP_NAME
|
||||
export const OUR_DOMAIN = process.env.NEXT_PUBLIC_OUR_DOMAIN
|
||||
export const SITE_URL = `${IS_PROD ? "https" : "http"}://${OUR_DOMAIN}`
|
||||
export const R2_URL = process.env.NEXT_PUBLIC_R2_URL
|
||||
@@ -0,0 +1,126 @@
|
||||
import { MembershipRole, type Site, type Page } from "~/lib/db.server"
|
||||
import type { AuthUser } from "./auth.server"
|
||||
import { PageVisibilityEnum } from "./types"
|
||||
|
||||
type Action =
|
||||
| {
|
||||
type: "can-delete-page"
|
||||
/** The site id this page belongs to */
|
||||
siteId: string
|
||||
}
|
||||
| {
|
||||
type: "can-list-page"
|
||||
visibility: PageVisibilityEnum
|
||||
siteId: string
|
||||
}
|
||||
| {
|
||||
type: "can-create-page"
|
||||
siteId: string
|
||||
}
|
||||
| {
|
||||
type: "can-read-page"
|
||||
page: Page
|
||||
}
|
||||
| {
|
||||
type: "can-update-site"
|
||||
site: Site
|
||||
}
|
||||
| {
|
||||
type: "can-notify-site-subscribers"
|
||||
site: Site
|
||||
}
|
||||
export const createGate = <TRequiredAuth extends boolean | undefined>({
|
||||
user,
|
||||
}: {
|
||||
user: AuthUser | null | undefined
|
||||
}) => {
|
||||
const isSiteMember = (siteId: string, roles: MembershipRole[]) => {
|
||||
if (!user) return false
|
||||
return user.memberships.some(
|
||||
(m) => m.siteId === siteId && roles.includes(m.role)
|
||||
)
|
||||
}
|
||||
|
||||
return {
|
||||
getUser<TRequiredAuth extends boolean | undefined>(
|
||||
requireAuth?: TRequiredAuth
|
||||
) {
|
||||
if (requireAuth && !user) {
|
||||
throw new Error("unauthorized")
|
||||
}
|
||||
return user as TRequiredAuth extends true
|
||||
? AuthUser
|
||||
: AuthUser | null | undefined
|
||||
},
|
||||
|
||||
hasRoles(siteId: string, roles: MembershipRole[]) {
|
||||
return isSiteMember(siteId, roles)
|
||||
},
|
||||
|
||||
isOwnerOrAdmin(siteId: string) {
|
||||
return this.hasRoles(siteId, [MembershipRole.OWNER, MembershipRole.ADMIN])
|
||||
},
|
||||
|
||||
allows(action: Action): boolean {
|
||||
if (action.type === "can-delete-page") {
|
||||
return isSiteMember(action.siteId, [
|
||||
MembershipRole.ADMIN,
|
||||
MembershipRole.OWNER,
|
||||
])
|
||||
}
|
||||
|
||||
if (action.type === "can-list-page") {
|
||||
if (action.visibility === PageVisibilityEnum.Published) {
|
||||
return true
|
||||
}
|
||||
return isSiteMember(action.siteId, [
|
||||
MembershipRole.ADMIN,
|
||||
MembershipRole.OWNER,
|
||||
])
|
||||
}
|
||||
|
||||
if (action.type === "can-create-page") {
|
||||
return isSiteMember(action.siteId, [
|
||||
MembershipRole.ADMIN,
|
||||
MembershipRole.OWNER,
|
||||
])
|
||||
}
|
||||
|
||||
if (action.type === "can-read-page") {
|
||||
const isPublished =
|
||||
action.page.published &&
|
||||
action.page.publishedAt &&
|
||||
action.page.publishedAt <= new Date()
|
||||
|
||||
return isPublished
|
||||
? !action.page.deletedAt
|
||||
: !action.page.deletedAt &&
|
||||
isSiteMember(action.page.siteId, [
|
||||
MembershipRole.ADMIN,
|
||||
MembershipRole.OWNER,
|
||||
])
|
||||
}
|
||||
|
||||
if (action.type === "can-update-site") {
|
||||
return isSiteMember(action.site.id, [
|
||||
MembershipRole.ADMIN,
|
||||
MembershipRole.OWNER,
|
||||
])
|
||||
}
|
||||
|
||||
if (action.type === "can-notify-site-subscribers") {
|
||||
return isSiteMember(action.site.id, [
|
||||
MembershipRole.ADMIN,
|
||||
MembershipRole.OWNER,
|
||||
])
|
||||
}
|
||||
|
||||
return false
|
||||
},
|
||||
permissionError(message = "not allowed") {
|
||||
return new Error(message)
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
export type Gate = ReturnType<typeof createGate>
|
||||
@@ -0,0 +1,15 @@
|
||||
import { IS_PROD } from "./constants"
|
||||
import { OUR_DOMAIN } from "./env"
|
||||
|
||||
export const getSiteLink = ({
|
||||
subdomain,
|
||||
noProtocol,
|
||||
}: {
|
||||
subdomain: string
|
||||
noProtocol?: boolean
|
||||
}) => {
|
||||
if (noProtocol) {
|
||||
return `${subdomain}.${OUR_DOMAIN}`
|
||||
}
|
||||
return `${IS_PROD ? "https" : "http"}://${subdomain}.${OUR_DOMAIN}`
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
import Mailgun from "mailgun.js"
|
||||
import FormData from "form-data"
|
||||
import { singleton } from "./singleton.server"
|
||||
import {
|
||||
ENCRYPT_SECRET,
|
||||
MAILGUN_APIKEY,
|
||||
MAILGUN_DOMAIN,
|
||||
} from "~/lib/env.server"
|
||||
import type { MailgunMessageData } from "mailgun.js/interfaces/Messages"
|
||||
import { IS_PROD } from "./constants"
|
||||
import { APP_NAME, OUR_DOMAIN, SITE_URL } from "./env"
|
||||
import { SubscribeFormData } from "./types"
|
||||
import { getSite } from "~/models/site.model"
|
||||
import { type Site } from "~/lib/db.server"
|
||||
import Iron from "@hapi/iron"
|
||||
|
||||
const enableMailgun = Boolean(MAILGUN_APIKEY && MAILGUN_DOMAIN)
|
||||
|
||||
const getClient = () =>
|
||||
singleton("mailgun", () => {
|
||||
const mg = new Mailgun(FormData)
|
||||
const client = mg.client({
|
||||
username: "api",
|
||||
key: MAILGUN_APIKEY,
|
||||
timeout: 60000,
|
||||
})
|
||||
return client
|
||||
})
|
||||
|
||||
const sendEmail = async (message: MailgunMessageData) => {
|
||||
console.log(message)
|
||||
|
||||
if (!enableMailgun) {
|
||||
console.error(
|
||||
"not sending email because no mailgun apikey or domain configured"
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
const client = getClient()
|
||||
|
||||
await client.messages.create(MAILGUN_DOMAIN, message).then(console.log)
|
||||
}
|
||||
|
||||
export const sendLoginEmail = async (payload: {
|
||||
token: string
|
||||
email: string
|
||||
url: string
|
||||
subscribeForm?: SubscribeFormData
|
||||
}) => {
|
||||
const { protocol, host, pathname } = new URL(payload.url)
|
||||
const query = new URLSearchParams([
|
||||
["token", payload.token],
|
||||
["next", `${protocol}//${host}${pathname}`],
|
||||
])
|
||||
if (payload.subscribeForm) {
|
||||
query.append("subscribe", JSON.stringify(payload.subscribeForm))
|
||||
}
|
||||
const loginLink = `${
|
||||
IS_PROD ? "https" : "http"
|
||||
}://${OUR_DOMAIN}/api/login?${query.toString()}`
|
||||
|
||||
let subject = `Sign in to ${APP_NAME}`
|
||||
|
||||
let html = `
|
||||
<p>Hello,</p>
|
||||
|
||||
<p>We received a request to sign in to ${APP_NAME} using this email address, please click the link below to sign in:</p>
|
||||
|
||||
<a href="${loginLink}">Sign in to ${APP_NAME}</a>
|
||||
|
||||
<p>This link will expire in 10 minutes. If you did not request this link, you can safely ignore this email.</p>
|
||||
|
||||
<p>Thanks,</p>
|
||||
|
||||
<p>Your Proselog Team</p>
|
||||
`
|
||||
|
||||
if (payload.subscribeForm) {
|
||||
const site = await getSite(payload.subscribeForm.siteId)
|
||||
subject = `Confirm your subscription to ${site.name}`
|
||||
html = `
|
||||
<p>Please confirm your subscription to ${site.name} by clicking the link below:</p>
|
||||
|
||||
<a href="${loginLink}">confirm</a>
|
||||
|
||||
<p>This link will expire in 10 minutes.</p>`
|
||||
}
|
||||
|
||||
const message: MailgunMessageData = {
|
||||
from: `${APP_NAME} <hi@proselog.com>`,
|
||||
to: payload.email,
|
||||
subject,
|
||||
html,
|
||||
}
|
||||
|
||||
await sendEmail(message)
|
||||
}
|
||||
|
||||
export const sendEmailForNewPost = async (payload: {
|
||||
post: { slug: string; title: string; content: string }
|
||||
site: Site
|
||||
subscribers: { id: string; email: string }[]
|
||||
}) => {
|
||||
try {
|
||||
const from = `${payload.site.name} <updates@${payload.site.subdomain}.proselog.com>`
|
||||
const subject = `${payload.post.title} - ${payload.site.name}`
|
||||
const html = `
|
||||
|
||||
<h2>${payload.post.title}</h2>
|
||||
<div>
|
||||
${payload.post.content}
|
||||
</div>
|
||||
<p>
|
||||
<a href="${SITE_URL}/api/unsubscribe?token=%recipient.unsubscribeToken%">Unsubscribe (no login required)</a>
|
||||
</p>`
|
||||
|
||||
const recipientVariables: {
|
||||
[email in string]: { unsubscribeToken: string }
|
||||
} = {}
|
||||
|
||||
await Promise.allSettled(
|
||||
payload.subscribers.map(async (sub) => {
|
||||
const unsubscribeToken = await Iron.seal(
|
||||
{
|
||||
userId: sub.id,
|
||||
siteId: payload.site.id,
|
||||
},
|
||||
ENCRYPT_SECRET,
|
||||
Iron.defaults
|
||||
)
|
||||
recipientVariables[sub.email] = {
|
||||
unsubscribeToken,
|
||||
}
|
||||
})
|
||||
)
|
||||
|
||||
const message: MailgunMessageData = {
|
||||
from,
|
||||
subject,
|
||||
html,
|
||||
to: Object.keys(recipientVariables),
|
||||
"recipient-variables": JSON.stringify(recipientVariables),
|
||||
}
|
||||
|
||||
await sendEmail(message)
|
||||
} catch (error) {
|
||||
console.error(error)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
import Markdown from "markdown-it"
|
||||
import Prism from "prismjs"
|
||||
import loadLanguages from "prismjs/components/index"
|
||||
import { getUserContentsUrl } from "./user-contents"
|
||||
|
||||
const isExternLink = (url: string) => /^https?:\/\//.test(url)
|
||||
|
||||
const handleImages = (md: Markdown) => {
|
||||
const imageRule = md.renderer.rules.image!
|
||||
md.renderer.rules.image = (tokens, idx, options, env, self) => {
|
||||
const token = tokens[idx]
|
||||
const url = token.attrGet("src")
|
||||
|
||||
// Don't allow images from other domains.
|
||||
if (!url || isExternLink(url)) {
|
||||
return ""
|
||||
}
|
||||
|
||||
token.attrSet("src", getUserContentsUrl(url))
|
||||
return imageRule(tokens, idx, options, env, self)
|
||||
}
|
||||
}
|
||||
|
||||
const codeBlock = (md: Markdown) => {
|
||||
const highlight = (code: string, lang: string) => {
|
||||
if (lang === "vue" || lang === "svelte") {
|
||||
lang = "html"
|
||||
}
|
||||
loadLanguages(lang)
|
||||
const grammer = Prism.languages[lang]
|
||||
const html = grammer
|
||||
? `<pre><code>${Prism.highlight(code, grammer, lang)}</code></pre>`
|
||||
: `<pre><code>${md.utils.escapeHtml(code)}</code></pre>`
|
||||
|
||||
return html
|
||||
}
|
||||
|
||||
md.renderer.rules.fence = (tokens, idx, options, env, self) => {
|
||||
const token = tokens[idx]
|
||||
const code = highlight(token.content, token.info)
|
||||
return `<div class="code" data-lang="${token.info}">${code}</div>`
|
||||
}
|
||||
}
|
||||
|
||||
export const renderPageContent = async (content: string) => {
|
||||
const md = new Markdown({
|
||||
html: false,
|
||||
linkify: true,
|
||||
})
|
||||
|
||||
md.use(handleImages)
|
||||
md.use(codeBlock)
|
||||
|
||||
const html = md.render(content)
|
||||
return { html }
|
||||
}
|
||||
|
||||
const stripHTML = (html: string) => {
|
||||
return html.replace(/<(?:.|\n)*?>/gm, "")
|
||||
}
|
||||
|
||||
export const getAutoExcerpt = (content: string) => {
|
||||
const indexOfMore = content.indexOf("<!--more-->")
|
||||
const md = new Markdown({
|
||||
html: false,
|
||||
linkify: true,
|
||||
})
|
||||
if (indexOfMore > -1) {
|
||||
content = content.substring(0, indexOfMore)
|
||||
return stripHTML(md.render(content))
|
||||
}
|
||||
return stripHTML(md.render(content)).slice(0, 400)
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import dayjs from "dayjs"
|
||||
import { useMemo } from "react"
|
||||
import { PageVisibilityEnum } from "./types"
|
||||
|
||||
export const usePageVisibility = ({
|
||||
published,
|
||||
publishedAt,
|
||||
}: {
|
||||
published: boolean
|
||||
publishedAt: string | Date | null
|
||||
}) => {
|
||||
const visibility = useMemo<
|
||||
Omit<PageVisibilityEnum, PageVisibilityEnum.All>
|
||||
>(() => {
|
||||
return getPageVisibility({ published, publishedAt })
|
||||
}, [published, publishedAt])
|
||||
|
||||
return visibility
|
||||
}
|
||||
|
||||
export const getPageVisibility = ({
|
||||
published,
|
||||
publishedAt,
|
||||
}: {
|
||||
published: boolean
|
||||
publishedAt: string | Date | null
|
||||
}) => {
|
||||
if (!published) {
|
||||
return PageVisibilityEnum.Draft
|
||||
}
|
||||
if (published && publishedAt && dayjs(publishedAt).isBefore(new Date())) {
|
||||
return PageVisibilityEnum.Published
|
||||
}
|
||||
return PageVisibilityEnum.Scheduled
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
export const promiseAll = (obj: Record<string, Promise<any>>) => {}
|
||||
@@ -0,0 +1,63 @@
|
||||
import { GetServerSidePropsContext, GetServerSideProps } from "next"
|
||||
|
||||
class Redirect extends Error {
|
||||
constructor(public url: string) {
|
||||
super("")
|
||||
}
|
||||
}
|
||||
|
||||
class NotFound extends Error {}
|
||||
|
||||
export const redirect = (url: string) => new Redirect(url)
|
||||
|
||||
export const notFound = (message?: string) => new NotFound(message)
|
||||
|
||||
export const isNotFoundError = (error: unknown) => error instanceof NotFound
|
||||
|
||||
export const serverSidePropsHandler = <TProps extends object>(
|
||||
fn: (
|
||||
ctx: GetServerSidePropsContext
|
||||
) => Promise<{ props: TProps } | Redirect | NotFound>
|
||||
): GetServerSideProps => {
|
||||
return async (ctx) => {
|
||||
try {
|
||||
const result = await fn(ctx)
|
||||
if (result instanceof Redirect) {
|
||||
return {
|
||||
redirect: {
|
||||
destination: result.url,
|
||||
permanent: false,
|
||||
},
|
||||
}
|
||||
}
|
||||
if (result instanceof NotFound) {
|
||||
return {
|
||||
notFound: true,
|
||||
}
|
||||
}
|
||||
return result
|
||||
} catch (error: any) {
|
||||
console.log("serverSidePropsHandler error", error)
|
||||
const actualError = error.cause || error
|
||||
if (actualError instanceof Redirect) {
|
||||
return {
|
||||
redirect: {
|
||||
destination: actualError.url,
|
||||
permanent: false,
|
||||
},
|
||||
}
|
||||
}
|
||||
if (actualError instanceof NotFound) {
|
||||
return {
|
||||
notFound: true,
|
||||
}
|
||||
}
|
||||
ctx.res.statusCode = 500
|
||||
return {
|
||||
props: {
|
||||
error: error.message,
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
// @ts-nocheck
|
||||
globalThis._singletons = globalThis._singletons || {}
|
||||
|
||||
export const singleton = <T>(id: string, factory: () => T): T => {
|
||||
if (!globalThis._singletons[id]) {
|
||||
globalThis._singletons[id] = factory()
|
||||
}
|
||||
return globalThis._singletons[id]
|
||||
}
|
||||
|
||||
export const singletonAsync = <T>(
|
||||
id: string,
|
||||
factory: () => Promise<T>,
|
||||
enableSingleton = true
|
||||
): { readonly value: T; wait: Promise<void> } => {
|
||||
if (globalThis._singletons[id] && enableSingleton) {
|
||||
return {
|
||||
wait: Promise.resolve(),
|
||||
|
||||
get value() {
|
||||
return globalThis._singletons[id]
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
let ready = false
|
||||
|
||||
const wait = factory().then((value) => {
|
||||
ready = true
|
||||
globalThis._singletons[id] = value
|
||||
})
|
||||
|
||||
return {
|
||||
wait,
|
||||
|
||||
get value() {
|
||||
if (!ready) {
|
||||
throw new Error(`please await .wait before using the value of '${id}'`)
|
||||
}
|
||||
return globalThis._singletons[id]
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import create, { StoreApi } from "zustand"
|
||||
import createContext from "zustand/context"
|
||||
|
||||
export type Store = {
|
||||
loginModalOpened: boolean
|
||||
setLoginModalOpened: (open: boolean) => void
|
||||
|
||||
subscribeModalOpened: boolean
|
||||
setSubscribeModalOpened: (open: boolean) => void
|
||||
}
|
||||
|
||||
const { Provider, useStore } = createContext<StoreApi<Store>>()
|
||||
|
||||
export { useStore }
|
||||
|
||||
export const StoreProvider = Provider
|
||||
|
||||
export const createStore = () =>
|
||||
create<Store>((set) => ({
|
||||
loginModalOpened: false,
|
||||
setLoginModalOpened(open) {
|
||||
set({ loginModalOpened: open })
|
||||
},
|
||||
|
||||
subscribeModalOpened: false,
|
||||
setSubscribeModalOpened(open) {
|
||||
set({ subscribeModalOpened: open })
|
||||
},
|
||||
}))
|
||||
@@ -0,0 +1,28 @@
|
||||
import { OUR_DOMAIN } from "./env"
|
||||
|
||||
export const getTenant = (request: Request, search: URLSearchParams) => {
|
||||
const host = request.headers.get("host")
|
||||
|
||||
if (!OUR_DOMAIN) {
|
||||
throw new Error("missing OUR_DOMAIN env")
|
||||
}
|
||||
|
||||
if (search.has("tenant")) {
|
||||
return search.get("tenant")
|
||||
}
|
||||
|
||||
const OUR_DOMAIN_SUFFIX = `.${OUR_DOMAIN}`
|
||||
if (host) {
|
||||
if (host.endsWith(".fly.dev")) {
|
||||
return
|
||||
}
|
||||
if (host.endsWith(OUR_DOMAIN_SUFFIX)) {
|
||||
const subdomain = host.replace(OUR_DOMAIN_SUFFIX, "")
|
||||
return subdomain
|
||||
}
|
||||
if (host !== OUR_DOMAIN) {
|
||||
return host
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import * as trpc from "@trpc/server"
|
||||
import { IncomingMessage } from "http"
|
||||
import { AuthUser, getAuthUser } from "./auth.server"
|
||||
import { createGate, Gate } from "./gate.server"
|
||||
|
||||
export type TRPCContext = { user: AuthUser | null | undefined; gate: Gate }
|
||||
|
||||
export const getTRPCContext = async ({
|
||||
req,
|
||||
}: {
|
||||
req: IncomingMessage
|
||||
}): Promise<TRPCContext> => {
|
||||
const user = await getAuthUser(req)
|
||||
const gate = createGate({ user })
|
||||
return {
|
||||
user,
|
||||
gate,
|
||||
}
|
||||
}
|
||||
|
||||
export const createRouter = () => {
|
||||
return trpc.router<TRPCContext>()
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import { createReactQueryHooks } from "@trpc/react"
|
||||
import { withTRPC } from "@trpc/next"
|
||||
import type { AppRouter } from "~/router"
|
||||
|
||||
export const trpc = createReactQueryHooks<AppRouter>()
|
||||
|
||||
export const wrapTrpc = ({ ssr }: { ssr?: boolean } = {}) => {
|
||||
return withTRPC({
|
||||
config() {
|
||||
const url = "/api/trpc"
|
||||
|
||||
return {
|
||||
url,
|
||||
fetch(url, init) {
|
||||
return fetch(url, {
|
||||
...init,
|
||||
credentials: "same-origin",
|
||||
})
|
||||
},
|
||||
}
|
||||
},
|
||||
ssr,
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
export type Site = {
|
||||
id: string
|
||||
name: string
|
||||
subdomain: string
|
||||
icon?: string | null
|
||||
}
|
||||
|
||||
export type SiteSubscription = {
|
||||
email?: boolean
|
||||
telegram?: boolean
|
||||
}
|
||||
|
||||
export type Viewer = {
|
||||
id: string
|
||||
name: string
|
||||
username: string
|
||||
email: string
|
||||
avatar?: string | null
|
||||
}
|
||||
|
||||
export enum PageVisibilityEnum {
|
||||
All = "all",
|
||||
Published = "published",
|
||||
Scheduled = "scheduled",
|
||||
Draft = "draft",
|
||||
}
|
||||
|
||||
export type PostOnSiteHome = {
|
||||
id: string
|
||||
title: string
|
||||
excerpt?: string | null
|
||||
autoExcerpt?: string | null
|
||||
slug: string
|
||||
publishedAt: string | Date
|
||||
}
|
||||
|
||||
export type Paginated<T> = {
|
||||
nodes: T[]
|
||||
total: number
|
||||
hasMore: boolean
|
||||
}
|
||||
|
||||
export type Page = {
|
||||
id: string
|
||||
title: string
|
||||
contentHTML: string
|
||||
excerpt: string
|
||||
permalink: string
|
||||
publishedAt: Date
|
||||
published: boolean
|
||||
}
|
||||
|
||||
export type PostOnArchivesPage = {
|
||||
id: string
|
||||
title: string
|
||||
slug: string
|
||||
publishedAt: string | Date
|
||||
}
|
||||
|
||||
/**
|
||||
* The subscribe form data to store in loginToken
|
||||
*/
|
||||
export type SubscribeFormData = {
|
||||
email?: boolean
|
||||
telegram?: boolean
|
||||
siteId: string
|
||||
}
|
||||
|
||||
export type SiteNavigationItem = {
|
||||
id: string
|
||||
label: string
|
||||
url: string
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
import { R2_URL } from "./env"
|
||||
|
||||
export function getUserContentsUrl(filename: string): string
|
||||
export function getUserContentsUrl(filename: undefined | null): undefined
|
||||
export function getUserContentsUrl<T extends string | undefined | null>(
|
||||
filename: T
|
||||
): T
|
||||
export function getUserContentsUrl(filename: string | undefined | null) {
|
||||
if (!filename) return undefined
|
||||
return `${R2_URL}/${filename}`
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
import { IS_PROD } from "./constants"
|
||||
import { OUR_DOMAIN } from "./env"
|
||||
|
||||
type Truthy<T> = T extends false | "" | 0 | null | undefined ? never : T // from lodash
|
||||
|
||||
export function truthy<T>(value: T): value is Truthy<T> {
|
||||
return Boolean(value)
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
import { validate } from "uuid"
|
||||
|
||||
export const isUUID = (id: string) => validate(id)
|
||||
@@ -0,0 +1,326 @@
|
||||
import { nanoid } from "nanoid"
|
||||
import {
|
||||
prismaPrimary,
|
||||
Prisma,
|
||||
prismaRead,
|
||||
PageType,
|
||||
MembershipRole,
|
||||
} from "~/lib/db.server"
|
||||
import { type Gate } from "~/lib/gate.server"
|
||||
import { sendEmailForNewPost } from "~/lib/mailgun.server"
|
||||
import { getAutoExcerpt, renderPageContent } from "~/lib/markdown.server"
|
||||
import { notFound } from "~/lib/server-side-props"
|
||||
import { PageVisibilityEnum } from "~/lib/types"
|
||||
import { isUUID } from "~/lib/uuid"
|
||||
import { getSite } from "./site.model"
|
||||
|
||||
const checkPageSlug = async ({
|
||||
slug,
|
||||
excludePage,
|
||||
siteId,
|
||||
}: {
|
||||
slug: string
|
||||
excludePage?: string
|
||||
siteId: string
|
||||
}) => {
|
||||
if (!slug) {
|
||||
throw new Error("Missing page slug")
|
||||
}
|
||||
const page = await prismaPrimary.page.findFirst({
|
||||
where: {
|
||||
siteId,
|
||||
slug,
|
||||
id: excludePage && {
|
||||
not: excludePage,
|
||||
},
|
||||
},
|
||||
})
|
||||
if (!page) return
|
||||
|
||||
if (page.deletedAt) {
|
||||
await prismaPrimary.page.delete({
|
||||
where: {
|
||||
id: page.id,
|
||||
},
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
throw new Error("Page slug already used")
|
||||
}
|
||||
|
||||
export async function createOrUpdatePage(
|
||||
gate: Gate,
|
||||
input: {
|
||||
pageId?: string
|
||||
siteId: string
|
||||
slug?: string
|
||||
title?: string
|
||||
content?: string
|
||||
published?: boolean
|
||||
publishedAt?: string
|
||||
excerpt?: string
|
||||
isPost?: boolean
|
||||
}
|
||||
) {
|
||||
const page = input.pageId
|
||||
? await prismaPrimary.page.findUnique({
|
||||
where: {
|
||||
id: input.pageId,
|
||||
},
|
||||
include: {
|
||||
site: true,
|
||||
},
|
||||
})
|
||||
: await prismaPrimary.page.create({
|
||||
data: {
|
||||
title: "Untitled",
|
||||
slug: `untitled-${nanoid(4)}`,
|
||||
site: {
|
||||
connect: {
|
||||
id: input.siteId,
|
||||
},
|
||||
},
|
||||
content: "",
|
||||
excerpt: "",
|
||||
autoExcerpt: "",
|
||||
},
|
||||
include: {
|
||||
site: true,
|
||||
},
|
||||
})
|
||||
|
||||
if (!page || page.deletedAt) {
|
||||
throw new Error(`Page not found`)
|
||||
}
|
||||
|
||||
if (!gate.allows({ type: "can-create-page", siteId: page.siteId })) {
|
||||
throw gate.permissionError()
|
||||
}
|
||||
|
||||
const slug = input.slug || page.slug
|
||||
await checkPageSlug({ slug, excludePage: page.id, siteId: page.siteId })
|
||||
|
||||
const autoExcerpt = input.content ? getAutoExcerpt(input.content) : undefined
|
||||
|
||||
const updated = await prismaPrimary.page.update({
|
||||
where: {
|
||||
id: page.id,
|
||||
},
|
||||
data: {
|
||||
title: input.title,
|
||||
content: input.content,
|
||||
published: input.published,
|
||||
publishedAt: input.publishedAt && new Date(input.publishedAt),
|
||||
excerpt: input.excerpt,
|
||||
slug,
|
||||
type: input.isPost ? "POST" : "PAGE",
|
||||
autoExcerpt,
|
||||
},
|
||||
})
|
||||
|
||||
if (
|
||||
updated.type === PageType.POST &&
|
||||
!updated.subscribersNotifiedAt &&
|
||||
updated.published &&
|
||||
updated.publishedAt <= new Date()
|
||||
) {
|
||||
await notifySubscribersForNewPost(gate, {
|
||||
pageId: updated.id,
|
||||
})
|
||||
}
|
||||
|
||||
return { page: updated }
|
||||
}
|
||||
|
||||
export async function getPagesBySite(
|
||||
gate: Gate,
|
||||
input: {
|
||||
site: string
|
||||
type: "post" | "page"
|
||||
visibility?: PageVisibilityEnum | null
|
||||
take?: number | null
|
||||
cursor?: string | null
|
||||
autoExcerpt?: boolean
|
||||
}
|
||||
) {
|
||||
const site = await getSite(input.site)
|
||||
|
||||
const visibility = input.visibility || PageVisibilityEnum.Published
|
||||
|
||||
if (!gate.allows({ type: "can-list-page", visibility, siteId: site.id })) {
|
||||
throw gate.permissionError()
|
||||
}
|
||||
|
||||
const now = new Date()
|
||||
|
||||
const where: Prisma.PageWhereInput = {
|
||||
siteId: site.id,
|
||||
deletedAt: null,
|
||||
type: input.type === "post" ? "POST" : "PAGE",
|
||||
}
|
||||
if (visibility === PageVisibilityEnum.Published) {
|
||||
where.published = true
|
||||
where.publishedAt = {
|
||||
lte: now,
|
||||
}
|
||||
} else if (visibility === PageVisibilityEnum.Scheduled) {
|
||||
where.published = true
|
||||
where.publishedAt = {
|
||||
gt: now,
|
||||
}
|
||||
} else if (visibility === PageVisibilityEnum.Draft) {
|
||||
where.published = false
|
||||
}
|
||||
|
||||
const take = input.take || 100
|
||||
const [nodes, total] = await Promise.all([
|
||||
prismaRead.page.findMany({
|
||||
where,
|
||||
orderBy: {
|
||||
publishedAt: "desc",
|
||||
},
|
||||
take: take + 1,
|
||||
cursor: input.cursor
|
||||
? {
|
||||
id: input.cursor,
|
||||
}
|
||||
: undefined,
|
||||
}),
|
||||
await prismaRead.page.count({
|
||||
where: {
|
||||
siteId: site.id,
|
||||
},
|
||||
}),
|
||||
])
|
||||
|
||||
const hasMore = nodes.length > take
|
||||
|
||||
return {
|
||||
nodes: nodes,
|
||||
total,
|
||||
hasMore,
|
||||
}
|
||||
}
|
||||
|
||||
export async function deletePage(gate: Gate, { id }: { id: string }) {
|
||||
const page = await prismaPrimary.page.findUnique({
|
||||
where: {
|
||||
id,
|
||||
},
|
||||
})
|
||||
|
||||
if (!page) {
|
||||
throw notFound("page not found")
|
||||
}
|
||||
|
||||
if (!gate.allows({ type: "can-delete-page", siteId: page.siteId })) {
|
||||
throw gate.permissionError()
|
||||
}
|
||||
|
||||
await prismaPrimary.page.update({
|
||||
where: {
|
||||
id: page.id,
|
||||
},
|
||||
data: {
|
||||
deletedAt: new Date(),
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
export async function getPage(
|
||||
gate: Gate,
|
||||
input: {
|
||||
/** page slug or id, `site` is needed when `page` is a slug */
|
||||
page: string
|
||||
site?: string
|
||||
renderContent?: boolean
|
||||
}
|
||||
) {
|
||||
const site = input.site ? await getSite(input.site) : null
|
||||
|
||||
if (input.site && !site) {
|
||||
throw notFound(`site not found`)
|
||||
}
|
||||
|
||||
const isPageUUID = isUUID(input.page)
|
||||
if (!isPageUUID && !input.site) {
|
||||
throw new Error("input.site is required because input.page is a slug")
|
||||
}
|
||||
|
||||
const page = isPageUUID
|
||||
? await prismaRead.page.findUnique({
|
||||
where: {
|
||||
id: input.page,
|
||||
},
|
||||
})
|
||||
: site
|
||||
? await prismaRead.page.findFirst({
|
||||
where: { siteId: site.id, slug: input.page },
|
||||
})
|
||||
: null
|
||||
|
||||
if (!page || page.deletedAt) {
|
||||
throw notFound(`page ${input.page} not found`)
|
||||
}
|
||||
|
||||
if (!gate.allows({ type: "can-read-page", page })) {
|
||||
throw gate.permissionError()
|
||||
}
|
||||
|
||||
if (input.renderContent) {
|
||||
const rendered = await renderPageContent(page.content)
|
||||
page.content = rendered.html
|
||||
}
|
||||
|
||||
return page
|
||||
}
|
||||
|
||||
export const notifySubscribersForNewPost = async (
|
||||
gate: Gate,
|
||||
input: {
|
||||
pageId: string
|
||||
}
|
||||
) => {
|
||||
const page = await getPage(gate, { page: input.pageId, renderContent: true })
|
||||
const site = await getSite(page.siteId)
|
||||
|
||||
if (!gate.allows({ type: "can-notify-site-subscribers", site })) {
|
||||
throw gate.permissionError()
|
||||
}
|
||||
|
||||
if (page.subscribersNotifiedAt) {
|
||||
throw new Error("You have already notified subscribers for this post")
|
||||
}
|
||||
|
||||
const memberships = await prismaPrimary.membership.findMany({
|
||||
where: {
|
||||
role: MembershipRole.SUBSCRIBER,
|
||||
siteId: site.id,
|
||||
},
|
||||
include: {
|
||||
user: true,
|
||||
},
|
||||
})
|
||||
|
||||
if (memberships.length === 0) return
|
||||
|
||||
await prismaPrimary.page.update({
|
||||
where: {
|
||||
id: page.id,
|
||||
},
|
||||
data: {
|
||||
subscribersNotifiedAt: new Date(),
|
||||
},
|
||||
})
|
||||
|
||||
const emailSubscribers = memberships
|
||||
.filter((member) => (member.config as Prisma.JsonObject).email)
|
||||
.map((member) => member.user)
|
||||
|
||||
await sendEmailForNewPost({
|
||||
post: page,
|
||||
site,
|
||||
subscribers: emailSubscribers,
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,332 @@
|
||||
import { prismaPrimary, prismaRead } from "~/lib/db.server"
|
||||
import { isUUID } from "~/lib/uuid"
|
||||
import { MembershipRole, PageType, type Site } from "~/lib/db.server"
|
||||
import { Gate } from "~/lib/gate.server"
|
||||
import dayjs from "dayjs"
|
||||
import { sendLoginEmail } from "~/lib/mailgun.server"
|
||||
import { SiteNavigationItem, SubscribeFormData } from "~/lib/types"
|
||||
import { nanoid } from "nanoid"
|
||||
|
||||
export const checkSubdomain = async ({
|
||||
subdomain,
|
||||
updatingSiteId,
|
||||
}: {
|
||||
subdomain: string
|
||||
updatingSiteId?: string
|
||||
}) => {
|
||||
const existingSite = await prismaPrimary.site.findUnique({
|
||||
where: {
|
||||
subdomain,
|
||||
},
|
||||
})
|
||||
|
||||
if (existingSite?.deletedAt) {
|
||||
// Actuall delete the site so that the subdomain can be used again
|
||||
await prismaPrimary.site.delete({
|
||||
where: {
|
||||
id: existingSite.id,
|
||||
},
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
if (existingSite && (!updatingSiteId || existingSite.id !== updatingSiteId)) {
|
||||
throw new Error(`Subdomain already taken`)
|
||||
}
|
||||
}
|
||||
|
||||
export async function getSitesForViewer(gate: Gate) {
|
||||
const user = gate.getUser(true)
|
||||
const sites = await getSitesByUser({ userId: user.id })
|
||||
return sites
|
||||
}
|
||||
|
||||
export const getUserLastActiveSite = async (userId: string) => {
|
||||
const memberships = await prismaPrimary.membership.findMany({
|
||||
where: {
|
||||
userId,
|
||||
role: {
|
||||
in: [MembershipRole.OWNER, MembershipRole.ADMIN],
|
||||
},
|
||||
},
|
||||
include: {
|
||||
site: true,
|
||||
},
|
||||
orderBy: {
|
||||
lastSwitchedTo: "desc",
|
||||
},
|
||||
})
|
||||
|
||||
const site = memberships[0]?.site
|
||||
|
||||
if (!site || site.deletedAt) return null
|
||||
|
||||
return site
|
||||
}
|
||||
|
||||
export const getSite = async (input: string) => {
|
||||
const site = isUUID(input)
|
||||
? await prismaRead.site.findUnique({
|
||||
where: {
|
||||
id: input,
|
||||
},
|
||||
})
|
||||
: await prismaRead.site.findUnique({
|
||||
where: {
|
||||
subdomain: input,
|
||||
},
|
||||
})
|
||||
|
||||
if (!site || site.deletedAt) {
|
||||
throw new Error(`Site not found`)
|
||||
}
|
||||
|
||||
return site as Omit<Site, "navigation"> & {
|
||||
navigation: SiteNavigationItem[] | null
|
||||
}
|
||||
}
|
||||
|
||||
export const getMembership = async (data: {
|
||||
siteId: string
|
||||
userId: string
|
||||
role: MembershipRole
|
||||
}) => {
|
||||
const first = await prismaRead.membership.findFirst({
|
||||
where: {
|
||||
role: data.role,
|
||||
userId: data.userId,
|
||||
siteId: data.siteId,
|
||||
},
|
||||
})
|
||||
|
||||
return first
|
||||
}
|
||||
|
||||
export const getSitesByUser = async ({ userId }: { userId: string }) => {
|
||||
const memberships = await prismaRead.membership.findMany({
|
||||
where: {
|
||||
userId,
|
||||
role: {
|
||||
in: [MembershipRole.ADMIN, MembershipRole.OWNER],
|
||||
},
|
||||
},
|
||||
include: {
|
||||
site: true,
|
||||
},
|
||||
})
|
||||
return memberships.map((m) => m.site)
|
||||
}
|
||||
|
||||
export const getSubscription = async (data: {
|
||||
userId: string
|
||||
siteId: string
|
||||
}) => {
|
||||
const membership = await getMembership({
|
||||
...data,
|
||||
role: MembershipRole.SUBSCRIBER,
|
||||
})
|
||||
if (!membership) return
|
||||
const config = membership.config as any
|
||||
return {
|
||||
...membership,
|
||||
config: config && {
|
||||
telegram: config.telegram,
|
||||
email: config.email,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
export async function updateSite(
|
||||
gate: Gate,
|
||||
payload: {
|
||||
site: string
|
||||
name?: string
|
||||
description?: string
|
||||
icon?: string | null
|
||||
subdomain?: string
|
||||
navigation?: SiteNavigationItem[]
|
||||
}
|
||||
) {
|
||||
const site = await getSite(payload.site)
|
||||
|
||||
if (!gate.allows({ type: "can-update-site", site })) {
|
||||
throw gate.permissionError()
|
||||
}
|
||||
|
||||
if (payload.subdomain) {
|
||||
await checkSubdomain({
|
||||
subdomain: payload.subdomain,
|
||||
updatingSiteId: site.id,
|
||||
})
|
||||
}
|
||||
|
||||
const updated = await prismaPrimary.site.update({
|
||||
where: {
|
||||
id: site.id,
|
||||
},
|
||||
data: {
|
||||
name: payload.name,
|
||||
subdomain: payload.subdomain,
|
||||
description: payload.description,
|
||||
icon: payload.icon,
|
||||
navigation: payload.navigation,
|
||||
},
|
||||
})
|
||||
|
||||
return {
|
||||
site: updated,
|
||||
subdomainUpdated: updated.subdomain !== site.subdomain,
|
||||
}
|
||||
}
|
||||
|
||||
export async function createSite(
|
||||
gate: Gate,
|
||||
payload: { name: string; subdomain: string }
|
||||
) {
|
||||
const user = gate.getUser(true)
|
||||
await checkSubdomain({ subdomain: payload.subdomain })
|
||||
|
||||
const navigation: SiteNavigationItem[] = [
|
||||
{
|
||||
id: nanoid(),
|
||||
label: "About",
|
||||
url: "/about",
|
||||
},
|
||||
{
|
||||
id: nanoid(),
|
||||
label: "Archives",
|
||||
url: "/archives",
|
||||
},
|
||||
]
|
||||
const site = await prismaPrimary.site.create({
|
||||
data: {
|
||||
name: payload.name,
|
||||
subdomain: payload.subdomain,
|
||||
navigation,
|
||||
memberships: {
|
||||
create: {
|
||||
role: MembershipRole.OWNER,
|
||||
user: {
|
||||
connect: {
|
||||
id: user.id,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
pages: {
|
||||
create: {
|
||||
title: "About",
|
||||
slug: "about",
|
||||
excerpt: "",
|
||||
autoExcerpt: "",
|
||||
content: `My name is ${payload.name} and I'm a new site.`,
|
||||
published: true,
|
||||
publishedAt: new Date(),
|
||||
type: PageType.PAGE,
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
return { site }
|
||||
}
|
||||
|
||||
export async function subscribeToSite(
|
||||
gate: Gate,
|
||||
input: {
|
||||
siteId: string
|
||||
email?: boolean
|
||||
telegram?: boolean
|
||||
newUser?: {
|
||||
email: string
|
||||
url: string
|
||||
}
|
||||
}
|
||||
) {
|
||||
const { newUser } = input
|
||||
if (newUser) {
|
||||
// Create the login token instead
|
||||
const subscribeFormData: SubscribeFormData = {
|
||||
email: input.email,
|
||||
telegram: input.telegram,
|
||||
siteId: input.siteId,
|
||||
}
|
||||
const loginToken = await prismaPrimary.loginToken.create({
|
||||
data: {
|
||||
email: newUser.email,
|
||||
expiresAt: dayjs().add(10, "minutes").toDate(),
|
||||
subscribeForm: subscribeFormData,
|
||||
},
|
||||
})
|
||||
sendLoginEmail({
|
||||
token: loginToken.id,
|
||||
email: loginToken.email,
|
||||
url: newUser.url,
|
||||
subscribeForm: subscribeFormData,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
const user = gate.getUser(true)
|
||||
|
||||
const site = await getSite(input.siteId)
|
||||
const subscription = await getSubscription({
|
||||
userId: user.id,
|
||||
siteId: site.id,
|
||||
})
|
||||
if (!subscription) {
|
||||
await prismaPrimary.membership.create({
|
||||
data: {
|
||||
role: MembershipRole.SUBSCRIBER,
|
||||
user: {
|
||||
connect: {
|
||||
id: user.id,
|
||||
},
|
||||
},
|
||||
site: {
|
||||
connect: {
|
||||
id: site.id,
|
||||
},
|
||||
},
|
||||
config: {
|
||||
email: input.email,
|
||||
telegram: input.telegram,
|
||||
},
|
||||
},
|
||||
})
|
||||
} else {
|
||||
await prismaPrimary.membership.update({
|
||||
where: {
|
||||
id: subscription.id,
|
||||
},
|
||||
data: {
|
||||
config: {
|
||||
email: input.email,
|
||||
telegram: input.telegram,
|
||||
},
|
||||
},
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
export async function unsubscribeFromSite(
|
||||
gate: Gate,
|
||||
input: { siteId: string }
|
||||
) {
|
||||
const user = gate.getUser(true)
|
||||
|
||||
const subscription = await getSubscription({
|
||||
userId: user.id,
|
||||
siteId: input.siteId,
|
||||
})
|
||||
|
||||
if (!subscription) {
|
||||
throw new Error(`Subscription not found`)
|
||||
}
|
||||
|
||||
await prismaPrimary.membership.delete({
|
||||
where: {
|
||||
id: subscription.id,
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
import { prismaPrimary } from "~/lib/db.server"
|
||||
import { Gate } from "~/lib/gate.server"
|
||||
|
||||
export const userModel = {
|
||||
async updateProfile(
|
||||
gate: Gate,
|
||||
payload: {
|
||||
name?: string
|
||||
username?: string
|
||||
avatar?: string
|
||||
bio?: string
|
||||
email?: string
|
||||
}
|
||||
) {
|
||||
const user = gate.getUser(true)
|
||||
|
||||
if (payload.email) {
|
||||
const userByEmail = await prismaPrimary.user.findUnique({
|
||||
where: {
|
||||
email: payload.email,
|
||||
},
|
||||
})
|
||||
if (userByEmail && userByEmail.id !== user.id) {
|
||||
throw new Error("email already in use")
|
||||
}
|
||||
}
|
||||
|
||||
if (payload.username) {
|
||||
const userByUsername = await prismaPrimary.user.findUnique({
|
||||
where: {
|
||||
username: payload.username,
|
||||
},
|
||||
})
|
||||
if (userByUsername && userByUsername.id !== user.id) {
|
||||
throw new Error("username already in use")
|
||||
}
|
||||
}
|
||||
|
||||
const updated = await prismaPrimary.user.update({
|
||||
where: {
|
||||
id: user.id,
|
||||
},
|
||||
data: {
|
||||
name: payload.name,
|
||||
avatar: payload.avatar,
|
||||
username: payload.username,
|
||||
email: payload.email,
|
||||
emailVerified: payload.email !== user.email ? null : undefined,
|
||||
},
|
||||
})
|
||||
|
||||
return {
|
||||
updated,
|
||||
}
|
||||
},
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import { Toaster } from "react-hot-toast"
|
||||
import LoginModal from "~/components/common/LoginModal"
|
||||
import "~/css/main.css"
|
||||
import { StoreProvider, createStore } from "~/lib/store"
|
||||
import { wrapTrpc } from "~/lib/trpc"
|
||||
|
||||
function MyApp({ Component, pageProps }: any) {
|
||||
return (
|
||||
<StoreProvider createStore={createStore}>
|
||||
<Component {...pageProps} />
|
||||
<LoginModal />
|
||||
<Toaster />
|
||||
</StoreProvider>
|
||||
)
|
||||
}
|
||||
|
||||
// Only uncomment this method if you have blocking data requirements for
|
||||
// every single page in your application. This disables the ability to
|
||||
// perform automatic static optimization, causing every page in your app to
|
||||
// be server-side rendered.
|
||||
//
|
||||
// MyApp.getInitialProps = async (appContext) => {
|
||||
// // calls page's `getInitialProps` and fills `appProps.pageProps`
|
||||
// const appProps = await App.getInitialProps(appContext);
|
||||
//
|
||||
// return { ...appProps }
|
||||
// }
|
||||
|
||||
export default wrapTrpc()(MyApp)
|
||||
@@ -0,0 +1,43 @@
|
||||
import { NextRequest, NextResponse } from "next/server"
|
||||
import { IS_PROD } from "~/lib/constants"
|
||||
import { FLY_REGION, IS_PRIMARY_REGION, PRIMARY_REGION } from "~/lib/env.server"
|
||||
import { getTenant } from "~/lib/tenant.server"
|
||||
|
||||
const METHODS_TO_NOT_REPLAY = ["GET", "HEAD", "OPTIONS"]
|
||||
|
||||
export default function middleware(req: NextRequest) {
|
||||
const { pathname } = req.nextUrl
|
||||
|
||||
console.log(`${req.method} ${req.nextUrl.pathname}${req.nextUrl.search}`)
|
||||
|
||||
if (
|
||||
IS_PROD &&
|
||||
!IS_PRIMARY_REGION &&
|
||||
!METHODS_TO_NOT_REPLAY.includes(req.method)
|
||||
) {
|
||||
console.log("replayed", {
|
||||
PRIMARY_REGION,
|
||||
FLY_REGION,
|
||||
url: req.url,
|
||||
})
|
||||
return new Response("replayed", {
|
||||
headers: {
|
||||
"fly-replay": `region=${PRIMARY_REGION}`,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
const tenant = getTenant(req, req.nextUrl.searchParams)
|
||||
|
||||
if (pathname.startsWith("/api/") || pathname.startsWith("/dashboard")) {
|
||||
return NextResponse.next()
|
||||
}
|
||||
|
||||
if (tenant) {
|
||||
const url = req.nextUrl.clone()
|
||||
url.pathname = `/_site/${tenant}${url.pathname}`
|
||||
return NextResponse.rewrite(url)
|
||||
}
|
||||
|
||||
return NextResponse.next()
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
import { GetServerSideProps } from "next"
|
||||
import { SiteLayout } from "~/components/site/SiteLayout"
|
||||
import { getAuthUser } from "~/lib/auth.server"
|
||||
import { trpc } from "~/lib/trpc"
|
||||
import { createSSGHelpers } from "@trpc/react/ssg"
|
||||
import { appRouter } from "~/router"
|
||||
import { getTRPCContext } from "~/lib/trpc.server"
|
||||
import { SitePage } from "~/components/site/SitePage"
|
||||
import { serverSidePropsHandler } from "~/lib/server-side-props"
|
||||
|
||||
export const getServerSideProps: GetServerSideProps = serverSidePropsHandler(
|
||||
async (ctx) => {
|
||||
const user = await getAuthUser(ctx.req)
|
||||
const isLoggedIn = !!user
|
||||
const domainOrSubdomain = ctx.params!.site as string
|
||||
const pageSlug = ctx.params!.page as string
|
||||
|
||||
const trpcContext = await getTRPCContext(ctx)
|
||||
const ssg = createSSGHelpers({ router: appRouter, ctx: trpcContext })
|
||||
|
||||
await Promise.all([
|
||||
ssg.fetchQuery("site", { site: domainOrSubdomain }),
|
||||
ssg.fetchQuery("site.page", {
|
||||
site: domainOrSubdomain,
|
||||
page: pageSlug,
|
||||
renderContent: true,
|
||||
}),
|
||||
ssg.fetchQuery("site.subscription", { site: domainOrSubdomain }),
|
||||
])
|
||||
|
||||
return {
|
||||
props: {
|
||||
isLoggedIn,
|
||||
domainOrSubdomain,
|
||||
pageSlug,
|
||||
trpcState: ssg.dehydrate(),
|
||||
},
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
function SitePagePage({
|
||||
isLoggedIn,
|
||||
domainOrSubdomain,
|
||||
pageSlug,
|
||||
}: {
|
||||
isLoggedIn: boolean
|
||||
domainOrSubdomain: string
|
||||
pageSlug: string
|
||||
}) {
|
||||
const siteResult = trpc.useQuery(["site", { site: domainOrSubdomain }], {})
|
||||
const subscriptionResult = trpc.useQuery([
|
||||
"site.subscription",
|
||||
{ site: domainOrSubdomain },
|
||||
])
|
||||
const pageResult = trpc.useQuery([
|
||||
"site.page",
|
||||
{ site: domainOrSubdomain, page: pageSlug, renderContent: true },
|
||||
])
|
||||
|
||||
const site = siteResult.data
|
||||
const subscription = subscriptionResult.data
|
||||
const page = pageResult.data!
|
||||
|
||||
return (
|
||||
<SiteLayout
|
||||
site={site!}
|
||||
title={page.title}
|
||||
isLoggedIn={isLoggedIn}
|
||||
subscription={subscription}
|
||||
>
|
||||
<SitePage page={page} />
|
||||
</SiteLayout>
|
||||
)
|
||||
}
|
||||
|
||||
export default SitePagePage
|
||||
@@ -0,0 +1,69 @@
|
||||
import { GetServerSideProps } from "next"
|
||||
import { SiteLayout } from "~/components/site/SiteLayout"
|
||||
import { getAuthUser } from "~/lib/auth.server"
|
||||
import { trpc } from "~/lib/trpc"
|
||||
import { createSSGHelpers } from "@trpc/react/ssg"
|
||||
import { appRouter } from "~/router"
|
||||
import { getTRPCContext } from "~/lib/trpc.server"
|
||||
import { serverSidePropsHandler } from "~/lib/server-side-props"
|
||||
import { SiteArchives } from "~/components/site/SiteArchives"
|
||||
|
||||
export const getServerSideProps: GetServerSideProps = serverSidePropsHandler(
|
||||
async (ctx) => {
|
||||
const user = await getAuthUser(ctx.req)
|
||||
const isLoggedIn = !!user
|
||||
const domainOrSubdomain = ctx.params!.site as string
|
||||
|
||||
const trpcContext = await getTRPCContext(ctx)
|
||||
const ssg = createSSGHelpers({ router: appRouter, ctx: trpcContext })
|
||||
|
||||
await Promise.all([
|
||||
ssg.fetchQuery("site", { site: domainOrSubdomain }),
|
||||
ssg.fetchQuery("site.pages", { site: domainOrSubdomain, take: 1000 }),
|
||||
ssg.fetchQuery("site.subscription", { site: domainOrSubdomain }),
|
||||
])
|
||||
|
||||
return {
|
||||
props: {
|
||||
isLoggedIn,
|
||||
domainOrSubdomain,
|
||||
trpcState: ssg.dehydrate(),
|
||||
},
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
function SiteArchivesPage({
|
||||
isLoggedIn,
|
||||
domainOrSubdomain,
|
||||
}: {
|
||||
isLoggedIn: boolean
|
||||
domainOrSubdomain: string
|
||||
}) {
|
||||
const siteResult = trpc.useQuery(["site", { site: domainOrSubdomain }], {})
|
||||
const subscriptionResult = trpc.useQuery([
|
||||
"site.subscription",
|
||||
{ site: domainOrSubdomain },
|
||||
])
|
||||
const postsResult = trpc.useQuery([
|
||||
"site.pages",
|
||||
{ site: domainOrSubdomain, take: 1000 },
|
||||
])
|
||||
|
||||
const site = siteResult.data
|
||||
const subscription = subscriptionResult.data
|
||||
const posts = postsResult.data?.nodes
|
||||
|
||||
return (
|
||||
<SiteLayout
|
||||
site={site!}
|
||||
title="Archives"
|
||||
isLoggedIn={isLoggedIn}
|
||||
subscription={subscription}
|
||||
>
|
||||
<SiteArchives posts={posts} />
|
||||
</SiteLayout>
|
||||
)
|
||||
}
|
||||
|
||||
export default SiteArchivesPage
|
||||
@@ -0,0 +1,62 @@
|
||||
import { GetServerSideProps } from "next"
|
||||
import { SiteHome } from "~/components/site/SiteHome"
|
||||
import { SiteLayout } from "~/components/site/SiteLayout"
|
||||
import { getAuthUser } from "~/lib/auth.server"
|
||||
import { trpc } from "~/lib/trpc"
|
||||
import { createSSGHelpers } from "@trpc/react/ssg"
|
||||
import { appRouter } from "~/router"
|
||||
import { getTRPCContext } from "~/lib/trpc.server"
|
||||
|
||||
export const getServerSideProps: GetServerSideProps = async (ctx) => {
|
||||
const user = await getAuthUser(ctx.req)
|
||||
const isLoggedIn = !!user
|
||||
const domainOrSubdomain = ctx.params!.site as string
|
||||
|
||||
const trpcContext = await getTRPCContext(ctx)
|
||||
const ssg = createSSGHelpers({ router: appRouter, ctx: trpcContext })
|
||||
|
||||
await Promise.all([
|
||||
ssg.fetchQuery("site", { site: domainOrSubdomain }),
|
||||
ssg.fetchQuery("site.subscription", { site: domainOrSubdomain }),
|
||||
])
|
||||
|
||||
return {
|
||||
props: {
|
||||
isLoggedIn,
|
||||
domainOrSubdomain,
|
||||
trpcState: ssg.dehydrate(),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
function SiteIndexPage({
|
||||
isLoggedIn,
|
||||
domainOrSubdomain,
|
||||
}: {
|
||||
isLoggedIn: boolean
|
||||
domainOrSubdomain: string
|
||||
}) {
|
||||
const siteResult = trpc.useQuery(["site", { site: domainOrSubdomain }], {})
|
||||
|
||||
const subscriptionResult = trpc.useQuery([
|
||||
"site.subscription",
|
||||
{ site: domainOrSubdomain },
|
||||
])
|
||||
const postsResult = trpc.useQuery(["site.pages", { site: domainOrSubdomain }])
|
||||
|
||||
const site = siteResult.data
|
||||
const subscription = subscriptionResult.data
|
||||
const posts = postsResult.data
|
||||
|
||||
return (
|
||||
<SiteLayout
|
||||
site={site!}
|
||||
isLoggedIn={isLoggedIn}
|
||||
subscription={subscription}
|
||||
>
|
||||
<SiteHome posts={posts} />
|
||||
</SiteLayout>
|
||||
)
|
||||
}
|
||||
|
||||
export default SiteIndexPage
|
||||
@@ -0,0 +1,64 @@
|
||||
import { NextApiHandler } from "next"
|
||||
import { z } from "zod"
|
||||
import { generateCookie } from "~/lib/auth.server"
|
||||
import { IS_PROD } from "~/lib/constants"
|
||||
import { prismaPrimary } from "~/lib/db.server"
|
||||
import { OUR_DOMAIN } from "~/lib/env"
|
||||
|
||||
const handler: NextApiHandler = async (req, res) => {
|
||||
const data = z
|
||||
.object({
|
||||
id: z.string(),
|
||||
path: z.string().default("/"),
|
||||
host: z.string(),
|
||||
})
|
||||
.parse({
|
||||
id: req.query.id,
|
||||
path: req.query.path,
|
||||
host: req.headers.host,
|
||||
})
|
||||
|
||||
const isCustomDomain = data.host && !data.host.endsWith(`.${OUR_DOMAIN}`)
|
||||
|
||||
// Set cookie again for custom domain and subdomain.localhost (because *.localhost in cookie domain doesn't work)
|
||||
if (isCustomDomain || !IS_PROD) {
|
||||
const accessToken = await prismaPrimary.accessToken.findUnique({
|
||||
where: {
|
||||
publicId: data.id,
|
||||
},
|
||||
})
|
||||
|
||||
if (
|
||||
!accessToken ||
|
||||
!accessToken.publicIdExpiresAt ||
|
||||
accessToken.publicIdExpiresAt < new Date()
|
||||
) {
|
||||
throw new Error("invalid id or id expired")
|
||||
}
|
||||
|
||||
await prismaPrimary.accessToken.update({
|
||||
where: {
|
||||
id: accessToken.id,
|
||||
},
|
||||
data: {
|
||||
publicId: null,
|
||||
publicIdExpiresAt: null,
|
||||
},
|
||||
})
|
||||
|
||||
res.setHeader(
|
||||
"set-cookie",
|
||||
generateCookie({
|
||||
type: "auth",
|
||||
domain: data.host,
|
||||
token: accessToken.token,
|
||||
})
|
||||
)
|
||||
res.redirect(data.path)
|
||||
return
|
||||
}
|
||||
|
||||
res.redirect(data.path)
|
||||
}
|
||||
|
||||
export default handler
|
||||
@@ -0,0 +1,140 @@
|
||||
import { z } from "zod"
|
||||
import { prismaPrimary } from "~/lib/db.server"
|
||||
import { nanoid } from "nanoid"
|
||||
import UAParser from "ua-parser-js"
|
||||
import dayjs from "dayjs"
|
||||
import { generateCookie } from "~/lib/auth.server"
|
||||
import { OUR_DOMAIN } from "~/lib/env"
|
||||
import { IS_PROD } from "~/lib/constants"
|
||||
import { NextApiHandler } from "next"
|
||||
import { subscribeToSite } from "~/models/site.model"
|
||||
import { createGate } from "~/lib/gate.server"
|
||||
|
||||
const handler: NextApiHandler = async (req, res) => {
|
||||
const data = z
|
||||
.object({
|
||||
token: z.string(),
|
||||
next: z.string(),
|
||||
userAgent: z.string(),
|
||||
subscribe: z
|
||||
.object({
|
||||
siteId: z.string(),
|
||||
email: z.boolean().optional(),
|
||||
telegram: z.boolean().optional(),
|
||||
})
|
||||
.optional(),
|
||||
})
|
||||
.parse({
|
||||
token: req.query.token,
|
||||
next: req.query.next,
|
||||
userAgent: req.headers["user-agent"],
|
||||
subscribe:
|
||||
req.query.subscribe && JSON.parse(req.query.subscribe as string),
|
||||
})
|
||||
|
||||
const loginToken = await prismaPrimary.loginToken.findUnique({
|
||||
where: {
|
||||
id: data.token,
|
||||
},
|
||||
})
|
||||
|
||||
if (!loginToken) {
|
||||
throw new Error("invalid token")
|
||||
}
|
||||
|
||||
if (loginToken.expiresAt < new Date()) {
|
||||
throw new Error(`token expired`)
|
||||
}
|
||||
|
||||
let user = await prismaPrimary.user.findUnique({
|
||||
where: {
|
||||
email: loginToken.email,
|
||||
},
|
||||
include: {
|
||||
memberships: true,
|
||||
},
|
||||
})
|
||||
|
||||
if (!user) {
|
||||
user = await prismaPrimary.user.create({
|
||||
data: {
|
||||
email: loginToken.email,
|
||||
name: loginToken.email.split("@")[0],
|
||||
username: nanoid(7),
|
||||
},
|
||||
include: {
|
||||
memberships: true,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
if (data.subscribe) {
|
||||
// Subscribe the user to the site
|
||||
const gate = createGate({ user })
|
||||
await subscribeToSite(gate, {
|
||||
siteId: data.subscribe.siteId,
|
||||
email: data.subscribe.email,
|
||||
telegram: data.subscribe.telegram,
|
||||
})
|
||||
}
|
||||
|
||||
await prismaPrimary.loginToken.delete({
|
||||
where: {
|
||||
id: loginToken.id,
|
||||
},
|
||||
})
|
||||
|
||||
const ua = new UAParser(data.userAgent)
|
||||
|
||||
const publicId = nanoid(32)
|
||||
const accessToken = await prismaPrimary.accessToken.create({
|
||||
data: {
|
||||
user: {
|
||||
connect: {
|
||||
id: user.id,
|
||||
},
|
||||
},
|
||||
token: nanoid(32),
|
||||
name: `Login via ${ua.getOS().name} ${ua.getBrowser().name}`,
|
||||
publicId,
|
||||
publicIdExpiresAt: dayjs().add(1, "minute").toDate(),
|
||||
},
|
||||
})
|
||||
|
||||
if (!IS_PROD) {
|
||||
console.log("login with token", accessToken.token)
|
||||
}
|
||||
|
||||
// Custom domain
|
||||
const nextUrl = new URL(data.next)
|
||||
|
||||
if (nextUrl.host !== OUR_DOMAIN && !nextUrl.host.endsWith(`.${OUR_DOMAIN}`)) {
|
||||
// Check if the host belong to a site
|
||||
const existing = await prismaPrimary.domain.findUnique({
|
||||
where: {
|
||||
domain: nextUrl.hostname,
|
||||
},
|
||||
})
|
||||
if (!existing) {
|
||||
throw new Error("invalid next url")
|
||||
}
|
||||
}
|
||||
|
||||
nextUrl.searchParams.set("id", publicId)
|
||||
nextUrl.searchParams.set("path", nextUrl.pathname)
|
||||
nextUrl.pathname = "/api/login-complete"
|
||||
console.log("redirecting to", nextUrl.href)
|
||||
|
||||
res.setHeader(
|
||||
"set-cookie",
|
||||
generateCookie({
|
||||
type: "auth",
|
||||
domain: OUR_DOMAIN,
|
||||
token: accessToken.token,
|
||||
})
|
||||
)
|
||||
|
||||
res.redirect(nextUrl.href)
|
||||
}
|
||||
|
||||
export default handler
|
||||
@@ -0,0 +1,14 @@
|
||||
import { NextApiHandler } from "next"
|
||||
import { generateCookie } from "~/lib/auth.server"
|
||||
|
||||
const handler: NextApiHandler = async (req, res) => {
|
||||
res.setHeader("set-cookie", generateCookie({ type: "clear" }))
|
||||
const next = req.query.next as string | undefined
|
||||
if (next) {
|
||||
res.redirect(next)
|
||||
} else {
|
||||
res.redirect("/")
|
||||
}
|
||||
}
|
||||
|
||||
export default handler
|
||||
@@ -0,0 +1,10 @@
|
||||
import * as trpcNext from "@trpc/server/adapters/next"
|
||||
import { getTRPCContext } from "~/lib/trpc.server"
|
||||
|
||||
import { appRouter } from "~/router"
|
||||
|
||||
// export API handler
|
||||
export default trpcNext.createNextApiHandler({
|
||||
router: appRouter,
|
||||
createContext: getTRPCContext,
|
||||
})
|
||||
@@ -0,0 +1,32 @@
|
||||
import { NextApiHandler } from "next"
|
||||
import Iron from "@hapi/iron"
|
||||
import { ENCRYPT_SECRET } from "~/lib/env.server"
|
||||
import { unsubscribeFromSite } from "~/models/site.model"
|
||||
import { prismaPrimary } from "~/lib/db.server"
|
||||
import { createGate } from "~/lib/gate.server"
|
||||
|
||||
const handler: NextApiHandler = async (req, res) => {
|
||||
const token = req.query.token as string
|
||||
const payload: {
|
||||
siteId: string
|
||||
userId: string
|
||||
} = await Iron.unseal(token, ENCRYPT_SECRET, Iron.defaults)
|
||||
|
||||
const user = await prismaPrimary.user.findUnique({
|
||||
where: {
|
||||
id: payload.userId,
|
||||
},
|
||||
include: {
|
||||
memberships: true,
|
||||
},
|
||||
})
|
||||
if (!user) return res.send("invalid token")
|
||||
|
||||
const gate = createGate({ user })
|
||||
|
||||
await unsubscribeFromSite(gate, { siteId: payload.siteId })
|
||||
|
||||
res.send("unsubscribed!")
|
||||
}
|
||||
|
||||
export default handler
|
||||
@@ -0,0 +1,93 @@
|
||||
import { useEffect } from "react"
|
||||
import { useForm } from "react-hook-form"
|
||||
import toast from "react-hot-toast"
|
||||
import { AvatarForm } from "~/components/dashboard/AvatarForm"
|
||||
import { DashboardLayout } from "~/components/dashboard/DashboardLayout"
|
||||
import { SettingsLayout } from "~/components/dashboard/SettingsLayout"
|
||||
import { Button } from "~/components/ui/Button"
|
||||
import { Input } from "~/components/ui/Input"
|
||||
import { trpc } from "~/lib/trpc"
|
||||
|
||||
export default function AccountProfilePage() {
|
||||
const viewer = trpc.useQuery(["auth.viewer"], {
|
||||
refetchOnWindowFocus: false,
|
||||
refetchOnReconnect: false,
|
||||
})
|
||||
const updateProfile = trpc.useMutation("user.updateProfile")
|
||||
|
||||
const form = useForm({
|
||||
defaultValues: {
|
||||
name: "",
|
||||
username: "",
|
||||
bio: "",
|
||||
email: "",
|
||||
},
|
||||
})
|
||||
|
||||
const handleSubmit = form.handleSubmit((values) => {
|
||||
updateProfile.mutate(values)
|
||||
})
|
||||
|
||||
useEffect(() => {
|
||||
if (updateProfile.isSuccess) {
|
||||
toast.success("Saved!")
|
||||
updateProfile.reset()
|
||||
}
|
||||
}, [updateProfile])
|
||||
|
||||
useEffect(() => {
|
||||
if (viewer.data) {
|
||||
form.setValue("name", viewer.data.name)
|
||||
form.setValue("username", viewer.data.username)
|
||||
form.setValue("bio", viewer.data.bio || "")
|
||||
form.setValue("email", viewer.data.email || "")
|
||||
}
|
||||
}, [viewer.data, form])
|
||||
|
||||
return (
|
||||
<DashboardLayout>
|
||||
<SettingsLayout title="Account" type="account">
|
||||
{viewer.data && (
|
||||
<div>
|
||||
<label className="form-label">Profile Picture</label>
|
||||
<AvatarForm filename={viewer.data.avatar} name={viewer.data.name} />
|
||||
</div>
|
||||
)}
|
||||
<form onSubmit={handleSubmit}>
|
||||
<div className="mt-5">
|
||||
<Input
|
||||
label="Display Name"
|
||||
id="name"
|
||||
required
|
||||
type="text"
|
||||
{...form.register("name")}
|
||||
/>
|
||||
</div>
|
||||
<div className="mt-5">
|
||||
<Input
|
||||
label="Username"
|
||||
id="username"
|
||||
required
|
||||
type="text"
|
||||
{...form.register("username")}
|
||||
/>
|
||||
</div>
|
||||
<div className="mt-5">
|
||||
<Input
|
||||
label="Email"
|
||||
id="email"
|
||||
required
|
||||
type="email"
|
||||
{...form.register("email")}
|
||||
/>
|
||||
</div>
|
||||
<div className="mt-10">
|
||||
<Button type="submit" isLoading={updateProfile.isLoading}>
|
||||
Save
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</SettingsLayout>
|
||||
</DashboardLayout>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,262 @@
|
||||
import { Popover } from "@headlessui/react"
|
||||
import clsx from "clsx"
|
||||
import dayjs from "dayjs"
|
||||
import { useCallback, useEffect, useState } from "react"
|
||||
import { DashboardMain } from "~/components/dashboard/DashboardMain"
|
||||
import { Button } from "~/components/ui/Button"
|
||||
import { getPageVisibility } from "~/lib/page-helpers"
|
||||
import { PageVisibilityEnum } from "~/lib/types"
|
||||
import toast from "react-hot-toast"
|
||||
import { Input } from "~/components/ui/Input"
|
||||
import { getSiteLink } from "~/lib/helpers"
|
||||
import { useEditor } from "~/components/ui/Editor"
|
||||
import { type EditorView } from "@codemirror/view"
|
||||
import { trpc } from "~/lib/trpc"
|
||||
import { useRouter } from "next/router"
|
||||
import { DashboardLayout } from "~/components/dashboard/DashboardLayout"
|
||||
import { UniLink } from "~/components/ui/UniLink"
|
||||
import { useUploadFile } from "~/hooks/useUploadFile"
|
||||
|
||||
const getInputDatetimeValue = (date: Date | string) => {
|
||||
const str = dayjs(date).format()
|
||||
return str.substring(0, ((str.indexOf("T") | 0) + 6) | 0)
|
||||
}
|
||||
|
||||
export default function SubdomainEditor() {
|
||||
const router = useRouter()
|
||||
|
||||
const subdomain = router.query.subdomain as string
|
||||
const isPost = router.query.type === "post"
|
||||
const pageId = router.query.id as string | undefined
|
||||
const trpcContext = trpc.useContext()
|
||||
const siteResult = trpc.useQuery(["site", { site: subdomain }], {
|
||||
enabled: !!subdomain,
|
||||
})
|
||||
const pageResult = trpc.useQuery(
|
||||
["site.page", { page: pageId!, site: subdomain }],
|
||||
{
|
||||
enabled: !!pageId,
|
||||
}
|
||||
)
|
||||
const page = pageResult.data
|
||||
const published = page?.published ?? false
|
||||
const visibility = getPageVisibility({
|
||||
published,
|
||||
publishedAt: page?.publishedAt || null,
|
||||
})
|
||||
const createOrUpdatePage = trpc.useMutation("site.createOrUpdatePage")
|
||||
const uploadFile = useUploadFile()
|
||||
|
||||
const [values, setValues] = useState({
|
||||
title: "",
|
||||
content: "",
|
||||
publishedAt: new Date().toISOString(),
|
||||
published: false,
|
||||
slug: "",
|
||||
})
|
||||
const updateValue = (field: string, value: any) => {
|
||||
setValues((values) => {
|
||||
return {
|
||||
...values,
|
||||
[field]: value,
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
if (createOrUpdatePage.isSuccess) {
|
||||
createOrUpdatePage.reset()
|
||||
toast.success("Updated!")
|
||||
trpcContext.invalidateQueries("site.page")
|
||||
router.replace(
|
||||
`/dashboard/${subdomain}/editor?id=${createOrUpdatePage.data.id}&type=${
|
||||
isPost ? "post" : "page"
|
||||
}`
|
||||
)
|
||||
}
|
||||
}, [createOrUpdatePage, isPost, router, subdomain, trpcContext])
|
||||
|
||||
useEffect(() => {
|
||||
if (createOrUpdatePage.isError) {
|
||||
createOrUpdatePage.reset()
|
||||
toast.error(createOrUpdatePage.error.message)
|
||||
}
|
||||
}, [createOrUpdatePage])
|
||||
|
||||
useEffect(() => {
|
||||
if (!page) return
|
||||
|
||||
setValues((values) => {
|
||||
return {
|
||||
...values,
|
||||
title: page.title,
|
||||
content: page.content,
|
||||
publishedAt: page.publishedAt,
|
||||
published: page.published,
|
||||
slug: page.slug,
|
||||
}
|
||||
})
|
||||
}, [page])
|
||||
|
||||
const handleEditorContentChange = useCallback(
|
||||
(value: string) => updateValue("content", value),
|
||||
[]
|
||||
)
|
||||
|
||||
const handleDropFile = useCallback(
|
||||
async (file: File, view: EditorView) => {
|
||||
const toastId = toast.loading("Uploading...")
|
||||
try {
|
||||
if (!file.type.startsWith("image/")) {
|
||||
throw new Error("You can only upload images")
|
||||
}
|
||||
|
||||
const { key } = await uploadFile(file, file.name)
|
||||
toast.success("Uploaded!", {
|
||||
id: toastId,
|
||||
})
|
||||
view.dispatch(
|
||||
view.state.replaceSelection(
|
||||
`\n\n\n\n`
|
||||
)
|
||||
)
|
||||
} catch (error) {
|
||||
if (error instanceof Error) {
|
||||
toast.error(error.message, { id: toastId })
|
||||
}
|
||||
}
|
||||
},
|
||||
[uploadFile]
|
||||
)
|
||||
|
||||
const { editorRef } = useEditor({
|
||||
value: values.content,
|
||||
onChange: handleEditorContentChange,
|
||||
onDropFile: handleDropFile,
|
||||
placeholder: "Start writing here..",
|
||||
})
|
||||
|
||||
return (
|
||||
<DashboardLayout>
|
||||
<DashboardMain fullWidth>
|
||||
<header className="flex justify-between absolute top-0 left-0 right-0 z-10 px-5 h-14 border-b items-center text-sm">
|
||||
<div></div>
|
||||
<div className="flex items-center space-x-3">
|
||||
<span
|
||||
className={clsx(
|
||||
`text-sm`,
|
||||
published ? `text-accent` : `text-zinc-300`
|
||||
)}
|
||||
>
|
||||
{visibility === PageVisibilityEnum.Published
|
||||
? "Published"
|
||||
: visibility === PageVisibilityEnum.Scheduled
|
||||
? "Scheduled"
|
||||
: "Draft"}
|
||||
</span>
|
||||
<Popover className="relative">
|
||||
<Popover.Button className="button is-primary rounded-lg select-none">
|
||||
Publish
|
||||
</Popover.Button>
|
||||
|
||||
<Popover.Panel className="absolute right-0 z-10 pt-2">
|
||||
{({ close }) => {
|
||||
return (
|
||||
<div className="border p-5 rounded-lg min-w-[240px] bg-white shadow-modal">
|
||||
<div className="space-y-3">
|
||||
<label className="block">
|
||||
<span className="block text-zinc-400 font-medium text-sm">
|
||||
Publish at
|
||||
</span>
|
||||
<input
|
||||
type="datetime-local"
|
||||
value={getInputDatetimeValue(values.publishedAt)}
|
||||
onChange={(e) => {
|
||||
updateValue("publishedAt", e.target.value)
|
||||
}}
|
||||
/>
|
||||
</label>
|
||||
<label className="block">
|
||||
<span className="block text-zinc-400 font-medium text-sm">
|
||||
Status
|
||||
</span>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={values.published}
|
||||
onChange={(e) =>
|
||||
updateValue("published", e.target.checked)
|
||||
}
|
||||
/>{" "}
|
||||
{values.published ? "Published" : "Draft"}
|
||||
</label>
|
||||
</div>
|
||||
<div className="mt-5">
|
||||
<Button
|
||||
isLoading={createOrUpdatePage.isLoading}
|
||||
onClick={() => {
|
||||
createOrUpdatePage.mutate({
|
||||
...values,
|
||||
siteId: siteResult.data!.id,
|
||||
pageId: page?.id,
|
||||
isPost: isPost,
|
||||
})
|
||||
}}
|
||||
>
|
||||
{published ? "Update" : "Publish"}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}}
|
||||
</Popover.Panel>
|
||||
</Popover>
|
||||
</div>
|
||||
</header>
|
||||
<div className="h-screen pt-14 flex w-full">
|
||||
<div className="h-full overflow-auto w-full">
|
||||
<div className="max-w-screen-md mx-auto py-5 px-5">
|
||||
<div>
|
||||
<input
|
||||
type="text"
|
||||
name="title"
|
||||
value={values.title}
|
||||
onChange={(e) => updateValue("title", e.target.value)}
|
||||
className="h-12 ml-1 inline-flex items-center border-none text-3xl font-bold w-full focus:outline-none"
|
||||
placeholder="Title goes here.."
|
||||
/>
|
||||
</div>
|
||||
<div className="mt-5">
|
||||
<div className="">
|
||||
<div ref={editorRef}></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="h-full overflow-auto flex-shrink-0 w-[280px] border-l bg-zinc-50 p-5">
|
||||
<div>
|
||||
<Input
|
||||
name="slug"
|
||||
value={values.slug}
|
||||
label="Page slug"
|
||||
id="slug"
|
||||
isBlock
|
||||
onChange={(e) => updateValue("slug", e.target.value)}
|
||||
/>
|
||||
{values.slug && (
|
||||
<div className="text-xs text-gray-400 mt-1">
|
||||
This {isPost ? "post" : "page"} will be accessible at{" "}
|
||||
<UniLink
|
||||
href={`${getSiteLink({ subdomain })}/${values.slug}`}
|
||||
className="hover:underline"
|
||||
>
|
||||
{getSiteLink({ subdomain, noProtocol: true })}/{values.slug}
|
||||
</UniLink>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</DashboardMain>
|
||||
</DashboardLayout>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
import { DashboardLayout } from "~/components/dashboard/DashboardLayout"
|
||||
import { DashboardMain } from "~/components/dashboard/DashboardMain"
|
||||
|
||||
export default function SubdomainIndex() {
|
||||
return (
|
||||
<DashboardLayout>
|
||||
<DashboardMain>hi</DashboardMain>
|
||||
</DashboardLayout>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
import { DashboardLayout } from "~/components/dashboard/DashboardLayout"
|
||||
import { PagesManager } from "~/components/dashboard/PagesManager"
|
||||
|
||||
export default function SubdomainPages() {
|
||||
return (
|
||||
<DashboardLayout>
|
||||
<PagesManager isPost={false} />
|
||||
</DashboardLayout>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
import { DashboardLayout } from "~/components/dashboard/DashboardLayout"
|
||||
import { PagesManager } from "~/components/dashboard/PagesManager"
|
||||
|
||||
export default function SubdomainPosts() {
|
||||
return (
|
||||
<DashboardLayout>
|
||||
<PagesManager isPost={true} />
|
||||
</DashboardLayout>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
import { useRouter } from "next/router"
|
||||
import { useEffect } from "react"
|
||||
import { useForm } from "react-hook-form"
|
||||
import toast from "react-hot-toast"
|
||||
import { DashboardLayout } from "~/components/dashboard/DashboardLayout"
|
||||
import { SettingsLayout } from "~/components/dashboard/SettingsLayout"
|
||||
import { Button } from "~/components/ui/Button"
|
||||
import { Input } from "~/components/ui/Input"
|
||||
import { OUR_DOMAIN } from "~/lib/env"
|
||||
import { trpc } from "~/lib/trpc"
|
||||
|
||||
export default function SettingsDomainsPage() {
|
||||
const router = useRouter()
|
||||
const subdomain = router.query.subdomain as string
|
||||
const siteResult = trpc.useQuery(["site", { site: subdomain }], {
|
||||
enabled: !!subdomain,
|
||||
refetchOnWindowFocus: false,
|
||||
refetchOnReconnect: false,
|
||||
})
|
||||
const ctx = trpc.useContext()
|
||||
const updateSite = trpc.useMutation("site.updateSite")
|
||||
|
||||
const form = useForm({
|
||||
defaultValues: {
|
||||
subdomain: "",
|
||||
},
|
||||
})
|
||||
|
||||
const handleSubmit = form.handleSubmit((values) => {
|
||||
updateSite.mutate({
|
||||
site: siteResult.data!.id,
|
||||
subdomain: values.subdomain,
|
||||
})
|
||||
})
|
||||
|
||||
useEffect(() => {
|
||||
if (updateSite.isSuccess && updateSite.data) {
|
||||
toast.success("Saved!")
|
||||
updateSite.reset()
|
||||
ctx.invalidateQueries()
|
||||
if (updateSite.data.subdomainUpdated) {
|
||||
router.replace(
|
||||
`/dashboard/${updateSite.data.site.subdomain}/settings/domains`
|
||||
)
|
||||
}
|
||||
}
|
||||
}, [ctx, router, updateSite])
|
||||
|
||||
useEffect(() => {
|
||||
if (siteResult.data) {
|
||||
form.setValue("subdomain", siteResult.data.subdomain)
|
||||
}
|
||||
}, [form, siteResult.data])
|
||||
|
||||
return (
|
||||
<DashboardLayout>
|
||||
<SettingsLayout title="Site Settings" type="site">
|
||||
<form onSubmit={handleSubmit}>
|
||||
<div className="">
|
||||
<Input
|
||||
id="subdomain"
|
||||
label="Subdomain"
|
||||
addon={`.${OUR_DOMAIN}`}
|
||||
className="w-28"
|
||||
{...form.register("subdomain")}
|
||||
error={updateSite.error?.message}
|
||||
/>
|
||||
</div>
|
||||
<div className="mt-5">
|
||||
<Button type="submit" isLoading={updateSite.isLoading}>
|
||||
Save
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</SettingsLayout>
|
||||
</DashboardLayout>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
import { Button } from "~/components/ui/Button"
|
||||
import { Input } from "~/components/ui/Input"
|
||||
import { AvatarForm } from "~/components/dashboard/AvatarForm"
|
||||
import { useEffect } from "react"
|
||||
import toast from "react-hot-toast"
|
||||
import { SettingsLayout } from "~/components/dashboard/SettingsLayout"
|
||||
import { useRouter } from "next/router"
|
||||
import { DashboardLayout } from "~/components/dashboard/DashboardLayout"
|
||||
import { trpc } from "~/lib/trpc"
|
||||
import { useForm } from "react-hook-form"
|
||||
|
||||
export default function SiteSettingsGeneralPage() {
|
||||
const router = useRouter()
|
||||
|
||||
const subdomain = router.query.subdomain as string
|
||||
|
||||
const siteResult = trpc.useQuery(["site", { site: subdomain }], {
|
||||
enabled: !!subdomain,
|
||||
refetchOnWindowFocus: false,
|
||||
refetchOnReconnect: false,
|
||||
})
|
||||
const site = siteResult.data
|
||||
const updateSite = trpc.useMutation("site.updateSite")
|
||||
|
||||
const form = useForm({
|
||||
defaultValues: {
|
||||
name: "",
|
||||
description: "",
|
||||
},
|
||||
})
|
||||
|
||||
const handleSubmit = form.handleSubmit((values) => {
|
||||
updateSite.mutate({
|
||||
site: subdomain,
|
||||
name: values.name,
|
||||
description: values.description,
|
||||
})
|
||||
})
|
||||
|
||||
useEffect(() => {
|
||||
if (site) {
|
||||
form.setValue("name", site.name)
|
||||
form.setValue("description", site.description || "")
|
||||
}
|
||||
}, [site, form])
|
||||
|
||||
useEffect(() => {
|
||||
if (updateSite.isSuccess && updateSite.data) {
|
||||
toast.success("Site updated")
|
||||
updateSite.reset()
|
||||
}
|
||||
}, [updateSite])
|
||||
|
||||
return (
|
||||
<DashboardLayout>
|
||||
<SettingsLayout title="Site Settings" type="site">
|
||||
{site && (
|
||||
<div>
|
||||
<label className="form-label">Icon</label>
|
||||
<AvatarForm
|
||||
site={site.id}
|
||||
name={site.name}
|
||||
filename={site.icon || undefined}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
<form onSubmit={handleSubmit}>
|
||||
<div className="mt-5">
|
||||
<Input required label="Name" id="name" {...form.register("name")} />
|
||||
</div>
|
||||
<div className="mt-5">
|
||||
<label htmlFor="description" className="form-label">
|
||||
Description
|
||||
</label>
|
||||
<textarea
|
||||
id="description"
|
||||
className="input is-block"
|
||||
rows={6}
|
||||
{...form.register("description")}
|
||||
/>
|
||||
</div>
|
||||
<div className="mt-5">
|
||||
<Button type="submit" isLoading={updateSite.isLoading}>
|
||||
Save
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
{/* <div className="mt-14 border-t pt-8">
|
||||
<h3 className="text-red-500 text-lg mb-5">Danger Zone</h3>
|
||||
<form>
|
||||
<Button variantColor="red" type="submit">
|
||||
Delete Site
|
||||
</Button>
|
||||
</form>
|
||||
</div> */}
|
||||
</SettingsLayout>
|
||||
</DashboardLayout>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,173 @@
|
||||
import { Button } from "~/components/ui/Button"
|
||||
import { Input } from "~/components/ui/Input"
|
||||
import { FormEvent, useEffect, useMemo, useState } from "react"
|
||||
import toast from "react-hot-toast"
|
||||
import { SettingsLayout } from "~/components/dashboard/SettingsLayout"
|
||||
import { useRouter } from "next/router"
|
||||
import { DashboardLayout } from "~/components/dashboard/DashboardLayout"
|
||||
import { trpc } from "~/lib/trpc"
|
||||
import { SiteNavigationItem } from "~/lib/types"
|
||||
import { nanoid } from "nanoid"
|
||||
import { ReactSortable } from "react-sortablejs"
|
||||
import equal from "fast-deep-equal"
|
||||
|
||||
type UpdateItem = (id: string, newItem: Partial<SiteNavigationItem>) => void
|
||||
|
||||
type RemoveItem = (id: string) => void
|
||||
|
||||
const SortableNavigationItem: React.FC<{
|
||||
item: SiteNavigationItem
|
||||
updateItem: UpdateItem
|
||||
removeItem: RemoveItem
|
||||
}> = ({ item, updateItem, removeItem }) => {
|
||||
return (
|
||||
<div className="flex space-x-5 border-b p-5 bg-zinc-50 last:border-0">
|
||||
<div>
|
||||
<button
|
||||
type="button"
|
||||
className="drag-handle cursor-grab -mt-1 text-zinc-400 rounded-lg h-8 w-6 flex items-center justify-center hover:text-zinc-800 hover:bg-zinc-200"
|
||||
>
|
||||
<svg className="w-5 h-8" viewBox="0 0 24 24">
|
||||
<path
|
||||
fill="currentColor"
|
||||
d="M9 20q-.825 0-1.412-.587Q7 18.825 7 18q0-.825.588-1.413Q8.175 16 9 16t1.413.587Q11 17.175 11 18q0 .825-.587 1.413Q9.825 20 9 20Zm0-6q-.825 0-1.412-.588Q7 12.825 7 12t.588-1.413Q8.175 10 9 10t1.413.587Q11 11.175 11 12q0 .825-.587 1.412Q9.825 14 9 14Zm0-6q-.825 0-1.412-.588Q7 6.825 7 6t.588-1.412Q8.175 4 9 4t1.413.588Q11 5.175 11 6t-.587 1.412Q9.825 8 9 8Zm6 0q-.825 0-1.412-.588Q13 6.825 13 6t.588-1.412Q14.175 4 15 4t1.413.588Q17 5.175 17 6t-.587 1.412Q15.825 8 15 8Zm0 6q-.825 0-1.412-.588Q13 12.825 13 12t.588-1.413Q14.175 10 15 10t1.413.587Q17 11.175 17 12q0 .825-.587 1.412Q15.825 14 15 14Zm0 6q-.825 0-1.412-.587Q13 18.825 13 18q0-.825.588-1.413Q14.175 16 15 16t1.413.587Q17 17.175 17 18q0 .825-.587 1.413Q15.825 20 15 20Z"
|
||||
></path>
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
<Input
|
||||
label="Label"
|
||||
required
|
||||
id={`${item.id}-label`}
|
||||
value={item.label}
|
||||
onChange={(e) => updateItem(item.id, { label: e.target.value })}
|
||||
/>
|
||||
<Input
|
||||
label="URL"
|
||||
required
|
||||
id={`${item.id}-url`}
|
||||
type="text"
|
||||
value={item.url}
|
||||
pattern="(https?://|/).+"
|
||||
title="URL must start with / or http:// or https://"
|
||||
onChange={(e) => updateItem(item.id, { url: e.target.value })}
|
||||
/>
|
||||
<div className="flex items-end relative -top-[5px]">
|
||||
<Button onClick={() => removeItem(item.id)} variantColor="red">
|
||||
Remove
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default function SiteSettingsNavigationPage() {
|
||||
const router = useRouter()
|
||||
|
||||
const subdomain = router.query.subdomain as string
|
||||
const trpcContext = trpc.useContext()
|
||||
const siteResult = trpc.useQuery(["site", { site: subdomain }], {
|
||||
enabled: !!subdomain,
|
||||
refetchOnWindowFocus: false,
|
||||
})
|
||||
|
||||
const updateSite = trpc.useMutation("site.updateSite")
|
||||
|
||||
const [items, setItems] = useState<SiteNavigationItem[]>([])
|
||||
|
||||
const itemsModified = useMemo(() => {
|
||||
if (!siteResult.data) return false
|
||||
return !equal(items, siteResult.data.navigation)
|
||||
}, [items, siteResult.data])
|
||||
|
||||
const updateItem: UpdateItem = (id, newItem) => {
|
||||
setItems((items) => {
|
||||
return items.map((item) => {
|
||||
if (item.id === id) {
|
||||
return { ...item, ...newItem }
|
||||
}
|
||||
return item
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
const newEmptyItem = () => {
|
||||
setItems((items) => [...items, { id: nanoid(), label: "", url: "" }])
|
||||
}
|
||||
|
||||
const handleSubmit = (e: FormEvent<HTMLFormElement>) => {
|
||||
e.preventDefault()
|
||||
updateSite.mutate({
|
||||
site: siteResult.data!.id,
|
||||
navigation: items,
|
||||
})
|
||||
}
|
||||
|
||||
const removeItem: RemoveItem = (id) => {
|
||||
setItems((items) => items.filter((item) => item.id !== id))
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
if (siteResult.data?.navigation) {
|
||||
setItems(siteResult.data.navigation)
|
||||
}
|
||||
}, [siteResult.data?.navigation])
|
||||
|
||||
useEffect(() => {
|
||||
if (updateSite.isSuccess) {
|
||||
updateSite.reset()
|
||||
toast.success("Saved")
|
||||
trpcContext.invalidateQueries(["site", { site: subdomain }])
|
||||
}
|
||||
}, [updateSite, trpcContext, subdomain])
|
||||
|
||||
return (
|
||||
<DashboardLayout>
|
||||
<SettingsLayout title="Site Settings" type="site">
|
||||
<form onSubmit={handleSubmit}>
|
||||
<div className="bg-zinc-50 rounded-lg overflow-hidden">
|
||||
{items.length === 0 && (
|
||||
<div className="text-center text-zinc-500 p-5">
|
||||
No navigation items yet
|
||||
</div>
|
||||
)}
|
||||
{/** @ts-expect-error */}
|
||||
<ReactSortable
|
||||
list={items}
|
||||
setList={setItems}
|
||||
handle=".drag-handle"
|
||||
>
|
||||
{items.map((item) => {
|
||||
return (
|
||||
<SortableNavigationItem
|
||||
key={item.id}
|
||||
item={item}
|
||||
updateItem={updateItem}
|
||||
removeItem={removeItem}
|
||||
/>
|
||||
)
|
||||
})}
|
||||
<style jsx global>{`
|
||||
.sortable-ghost {
|
||||
opacity: 0.4;
|
||||
}
|
||||
`}</style>
|
||||
</ReactSortable>
|
||||
</div>
|
||||
<div className="border-t pt-5 mt-10 space-x-3 flex items-center">
|
||||
<Button
|
||||
type="submit"
|
||||
isLoading={updateSite.isLoading}
|
||||
isDisabled={!itemsModified}
|
||||
>
|
||||
Save
|
||||
</Button>
|
||||
<Button variant="secondary" onClick={newEmptyItem}>
|
||||
New Item
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</SettingsLayout>
|
||||
</DashboardLayout>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import { NextRequest, NextResponse } from "next/server"
|
||||
import { AUTH_COOKIE_NAME } from "~/lib/env.server"
|
||||
|
||||
export default function middleware(req: NextRequest) {
|
||||
// Redirect unauthenticated users to the home page
|
||||
if (!req.cookies[AUTH_COOKIE_NAME]) {
|
||||
const url = req.nextUrl.clone()
|
||||
url.pathname = "/"
|
||||
return NextResponse.redirect(url)
|
||||
}
|
||||
return NextResponse.next()
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import { getAuthUser } from "~/lib/auth.server"
|
||||
import { redirect, serverSidePropsHandler } from "~/lib/server-side-props"
|
||||
import { getUserLastActiveSite } from "~/models/site.model"
|
||||
|
||||
export const getServerSideProps = serverSidePropsHandler(async (ctx) => {
|
||||
const user = await getAuthUser(ctx.req)
|
||||
|
||||
if (!user) {
|
||||
return redirect("/")
|
||||
}
|
||||
const site = await getUserLastActiveSite(user.id)
|
||||
if (!site) {
|
||||
return redirect(`/dashboard/new-site`)
|
||||
}
|
||||
return redirect(`/dashboard/${site.subdomain}`)
|
||||
})
|
||||
|
||||
export default function Dashboard() {
|
||||
return <div>You should never see this</div>
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
import Link from "next/link"
|
||||
import { useRouter } from "next/router"
|
||||
import { useEffect } from "react"
|
||||
import { useForm } from "react-hook-form"
|
||||
import toast from "react-hot-toast"
|
||||
import { Button } from "~/components/ui/Button"
|
||||
import { Input } from "~/components/ui/Input"
|
||||
import { OUR_DOMAIN } from "~/lib/env"
|
||||
import { trpc } from "~/lib/trpc"
|
||||
|
||||
export default function NewSitePage() {
|
||||
const router = useRouter()
|
||||
const viewer = trpc.useQuery(["auth.viewer"])
|
||||
const createSite = trpc.useMutation("site.create")
|
||||
|
||||
const form = useForm({
|
||||
defaultValues: {
|
||||
name: "",
|
||||
subdomain: "",
|
||||
},
|
||||
})
|
||||
|
||||
const handleSubmit = form.handleSubmit((values) => {
|
||||
createSite.mutate(values)
|
||||
})
|
||||
|
||||
useEffect(() => {
|
||||
if (createSite.isError) {
|
||||
createSite.reset()
|
||||
toast.error(createSite.error.message)
|
||||
} else if (createSite.isSuccess) {
|
||||
createSite.reset()
|
||||
router.push(`/dashboard/${createSite.data.subdomain}`)
|
||||
}
|
||||
}, [createSite, router])
|
||||
|
||||
return (
|
||||
<div>
|
||||
<header className="px-5 text-sm md:px-14 flex justify-between items-start py-10">
|
||||
<Link href="/dashboard">
|
||||
<a className="flex space-x-1 items-center">
|
||||
<svg
|
||||
className="w-4 h-4"
|
||||
fill="currentColor"
|
||||
viewBox="0 0 20 20"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
>
|
||||
<path
|
||||
fillRule="evenodd"
|
||||
d="M12.707 5.293a1 1 0 010 1.414L9.414 10l3.293 3.293a1 1 0 01-1.414 1.414l-4-4a1 1 0 010-1.414l4-4a1 1 0 011.414 0z"
|
||||
clipRule="evenodd"
|
||||
/>
|
||||
</svg>
|
||||
<span>Back to dashboard</span>
|
||||
</a>
|
||||
</Link>
|
||||
<div>
|
||||
<div className="text-zinc-400">Logged in as:</div>
|
||||
<div>{viewer.data?.email}</div>
|
||||
</div>
|
||||
</header>
|
||||
<div className="max-w-sm mx-auto mt-20">
|
||||
<h2 className="text-3xl mb-10 text-center">Create a new site</h2>
|
||||
<form className="space-y-5" onSubmit={handleSubmit}>
|
||||
<div>
|
||||
<Input
|
||||
id="name"
|
||||
label="Site Name"
|
||||
isBlock
|
||||
required
|
||||
maxLength={30}
|
||||
{...form.register("name", {})}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<Input
|
||||
id="subdomain"
|
||||
label="Subdomain"
|
||||
isBlock
|
||||
required
|
||||
addon={`.${OUR_DOMAIN}`}
|
||||
minLength={2}
|
||||
maxLength={20}
|
||||
{...form.register("subdomain", {})}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<Button type="submit" isBlock isLoading={createSite.isLoading}>
|
||||
Create
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import { GetServerSideProps } from "next"
|
||||
import { MainLayout } from "~/components/main/MainLayout"
|
||||
import { getAuthUser } from "~/lib/auth.server"
|
||||
import { FLY_REGION } from "~/lib/env.server"
|
||||
|
||||
export const getServerSideProps: GetServerSideProps = async (ctx) => {
|
||||
const user = await getAuthUser(ctx.req)
|
||||
const isLoggedIn = !!user
|
||||
return {
|
||||
props: {
|
||||
isLoggedIn,
|
||||
region: FLY_REGION,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
export default function Home({
|
||||
isLoggedIn,
|
||||
region,
|
||||
}: {
|
||||
isLoggedIn: boolean
|
||||
region: string | null
|
||||
}) {
|
||||
return <MainLayout isLoggedIn={isLoggedIn} region={region}></MainLayout>
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
import dayjs from "dayjs"
|
||||
import { z } from "zod"
|
||||
import { prismaPrimary } from "~/lib/db.server"
|
||||
import { sendLoginEmail } from "~/lib/mailgun.server"
|
||||
import { createRouter } from "~/lib/trpc.server"
|
||||
|
||||
export const authRouter = createRouter()
|
||||
.query("viewer", {
|
||||
output: z
|
||||
.object({
|
||||
id: z.string(),
|
||||
email: z.string(),
|
||||
name: z.string(),
|
||||
username: z.string(),
|
||||
avatar: z.string().nullish(),
|
||||
bio: z.string().nullish(),
|
||||
})
|
||||
.nullable(),
|
||||
async resolve({ ctx }) {
|
||||
return ctx.user || null
|
||||
},
|
||||
})
|
||||
.mutation("requestLoginLink", {
|
||||
input: z.object({
|
||||
email: z.string(),
|
||||
url: z.string(),
|
||||
}),
|
||||
output: z.boolean(),
|
||||
async resolve({ input }) {
|
||||
const token = await prismaPrimary.loginToken.create({
|
||||
data: {
|
||||
email: input.email,
|
||||
expiresAt: dayjs().add(10, "minute").toDate(),
|
||||
},
|
||||
})
|
||||
|
||||
await sendLoginEmail({
|
||||
url: input.url,
|
||||
email: input.email,
|
||||
token: token.id,
|
||||
}).catch(console.error)
|
||||
|
||||
return true
|
||||
},
|
||||
})
|
||||
@@ -0,0 +1,19 @@
|
||||
import { z } from "zod"
|
||||
import { createRouter } from "~/lib/trpc.server"
|
||||
import { getSitesForViewer } from "~/models/site.model"
|
||||
|
||||
export const dashboardRouter = createRouter().query("sitesForSwitcher", {
|
||||
output: z.array(
|
||||
z.object({
|
||||
id: z.string(),
|
||||
name: z.string(),
|
||||
subdomain: z.string(),
|
||||
createdAt: z.date().transform((v) => v.toISOString()),
|
||||
icon: z.string().nullable(),
|
||||
})
|
||||
),
|
||||
async resolve({ ctx }) {
|
||||
const sites = await getSitesForViewer(ctx.gate)
|
||||
return sites
|
||||
},
|
||||
})
|
||||
@@ -0,0 +1,53 @@
|
||||
import * as trpc from "@trpc/server"
|
||||
import { z } from "zod"
|
||||
import { isNotFoundError } from "~/lib/server-side-props"
|
||||
import { TRPCContext } from "~/lib/trpc.server"
|
||||
import { getSite } from "~/models/site.model"
|
||||
import { authRouter } from "./auth"
|
||||
import { dashboardRouter } from "./dashboard"
|
||||
import { siteRouter } from "./site"
|
||||
import { userRouter } from "./user"
|
||||
|
||||
export const appRouter = trpc
|
||||
.router<TRPCContext>()
|
||||
.query("site", {
|
||||
input: z.object({
|
||||
site: z.string(),
|
||||
}),
|
||||
output: z.object({
|
||||
id: z.string(),
|
||||
name: z.string(),
|
||||
description: z.string().nullable(),
|
||||
icon: z.string().nullable(),
|
||||
subdomain: z.string(),
|
||||
navigation: z
|
||||
.array(
|
||||
z.object({
|
||||
id: z.string(),
|
||||
label: z.string(),
|
||||
url: z.string(),
|
||||
})
|
||||
)
|
||||
.nullable(),
|
||||
}),
|
||||
async resolve({ input }) {
|
||||
const site = await getSite(input.site)
|
||||
return site
|
||||
},
|
||||
})
|
||||
.merge("auth.", authRouter)
|
||||
.merge("dashbaord.", dashboardRouter)
|
||||
.merge("site.", siteRouter)
|
||||
.merge("user.", userRouter)
|
||||
.formatError(({ error, shape }) => {
|
||||
return {
|
||||
...shape,
|
||||
data: {
|
||||
...shape.data,
|
||||
notFound: isNotFoundError(error.cause),
|
||||
},
|
||||
}
|
||||
})
|
||||
|
||||
// export type definition of API
|
||||
export type AppRouter = typeof appRouter
|
||||
@@ -0,0 +1,229 @@
|
||||
import { z } from "zod"
|
||||
import { createRouter } from "~/lib/trpc.server"
|
||||
import { PageVisibilityEnum } from "~/lib/types"
|
||||
import {
|
||||
getSite,
|
||||
getSubscription,
|
||||
updateSite,
|
||||
createSite,
|
||||
subscribeToSite,
|
||||
unsubscribeFromSite,
|
||||
} from "~/models/site.model"
|
||||
import {
|
||||
createOrUpdatePage,
|
||||
getPage,
|
||||
deletePage,
|
||||
getPagesBySite,
|
||||
notifySubscribersForNewPost,
|
||||
} from "~/models/page.model"
|
||||
|
||||
export const siteRouter = createRouter()
|
||||
.query("subscribersNotifiedAt", {
|
||||
input: z.object({
|
||||
pageId: z.string(),
|
||||
}),
|
||||
output: z
|
||||
.date()
|
||||
.transform((v) => v.toISOString())
|
||||
.nullable(),
|
||||
async resolve({ input, ctx }) {
|
||||
const page = await getPage(ctx.gate, { page: input.pageId })
|
||||
if (!ctx.gate.isOwnerOrAdmin(page.siteId)) {
|
||||
throw ctx.gate.permissionError()
|
||||
}
|
||||
return page.subscribersNotifiedAt
|
||||
},
|
||||
})
|
||||
.query("subscription", {
|
||||
input: z.object({
|
||||
site: z.string(),
|
||||
}),
|
||||
output: z
|
||||
.object({
|
||||
email: z.boolean().optional(),
|
||||
telegram: z.boolean().optional(),
|
||||
})
|
||||
.nullable(),
|
||||
async resolve({ input, ctx }) {
|
||||
const user = ctx.gate.getUser()
|
||||
if (!user) return null
|
||||
const site = await getSite(input.site)
|
||||
const subscription = await getSubscription({
|
||||
siteId: site.id,
|
||||
userId: user.id,
|
||||
})
|
||||
return subscription ? subscription.config : null
|
||||
},
|
||||
})
|
||||
.query("pages", {
|
||||
input: z.object({
|
||||
site: z.string(),
|
||||
type: z.enum(["post", "page"]).default("post"),
|
||||
visibility: z
|
||||
.enum([
|
||||
PageVisibilityEnum.All,
|
||||
PageVisibilityEnum.Published,
|
||||
PageVisibilityEnum.Draft,
|
||||
PageVisibilityEnum.Scheduled,
|
||||
])
|
||||
.nullish(),
|
||||
take: z.number().optional(),
|
||||
cursor: z.string().optional(),
|
||||
}),
|
||||
output: z.object({
|
||||
nodes: z.array(
|
||||
z.object({
|
||||
id: z.string(),
|
||||
title: z.string(),
|
||||
content: z.string(),
|
||||
publishedAt: z.date().transform((v) => v.toISOString()),
|
||||
published: z.boolean(),
|
||||
slug: z.string(),
|
||||
excerpt: z.string().nullable(),
|
||||
autoExcerpt: z.string().nullable(),
|
||||
})
|
||||
),
|
||||
total: z.number(),
|
||||
hasMore: z.boolean(),
|
||||
}),
|
||||
async resolve({ input, ctx }) {
|
||||
const result = await getPagesBySite(ctx.gate, input)
|
||||
return result
|
||||
},
|
||||
})
|
||||
.query("page", {
|
||||
input: z.object({
|
||||
site: z.string(),
|
||||
page: z.string(),
|
||||
renderContent: z.boolean().optional(),
|
||||
}),
|
||||
output: z.object({
|
||||
id: z.string(),
|
||||
title: z.string(),
|
||||
content: z.string(),
|
||||
excerpt: z.string().nullable(),
|
||||
autoExcerpt: z.string().nullable(),
|
||||
published: z.boolean(),
|
||||
publishedAt: z.date().transform((v) => v.toISOString()),
|
||||
slug: z.string(),
|
||||
type: z.enum(["PAGE", "POST"]),
|
||||
}),
|
||||
async resolve({ input, ctx }) {
|
||||
const page = await getPage(ctx.gate, input)
|
||||
return page
|
||||
},
|
||||
})
|
||||
.mutation("updateSite", {
|
||||
input: z.object({
|
||||
site: z.string(),
|
||||
name: z.string().optional(),
|
||||
description: z.string().optional(),
|
||||
icon: z.string().nullish(),
|
||||
subdomain: z.string().optional(),
|
||||
navigation: z
|
||||
.array(
|
||||
z.object({
|
||||
id: z.string(),
|
||||
label: z.string(),
|
||||
url: z
|
||||
.string()
|
||||
.regex(
|
||||
/^(https?:\/\/|\/)/,
|
||||
"URL must start with / or http:// or https://"
|
||||
),
|
||||
})
|
||||
)
|
||||
.optional(),
|
||||
}),
|
||||
output: z.object({
|
||||
site: z.object({
|
||||
id: z.string(),
|
||||
name: z.string(),
|
||||
subdomain: z.string(),
|
||||
}),
|
||||
subdomainUpdated: z.boolean(),
|
||||
}),
|
||||
async resolve({ ctx, input }) {
|
||||
const { site, subdomainUpdated } = await updateSite(ctx.gate, input)
|
||||
return {
|
||||
site,
|
||||
subdomainUpdated,
|
||||
}
|
||||
},
|
||||
})
|
||||
.mutation("createOrUpdatePage", {
|
||||
input: z.object({
|
||||
siteId: z.string(),
|
||||
pageId: z.string().optional(),
|
||||
title: z.string().optional(),
|
||||
content: z.string().optional(),
|
||||
published: z.boolean().optional(),
|
||||
publishedAt: z.string().optional(),
|
||||
excerpt: z.string().optional(),
|
||||
isPost: z.boolean(),
|
||||
slug: z.string().optional(),
|
||||
}),
|
||||
output: z.object({
|
||||
id: z.string(),
|
||||
}),
|
||||
async resolve({ input, ctx }) {
|
||||
const { page } = await createOrUpdatePage(ctx.gate, input)
|
||||
return page
|
||||
},
|
||||
})
|
||||
.mutation("create", {
|
||||
input: z.object({
|
||||
name: z.string(),
|
||||
subdomain: z.string().min(2).max(20),
|
||||
}),
|
||||
output: z.object({
|
||||
id: z.string(),
|
||||
subdomain: z.string(),
|
||||
}),
|
||||
async resolve({ input, ctx }) {
|
||||
const { site } = await createSite(ctx.gate, input)
|
||||
return site
|
||||
},
|
||||
})
|
||||
.mutation("deletePage", {
|
||||
input: z.object({
|
||||
pageId: z.string(),
|
||||
}),
|
||||
async resolve({ ctx, input }) {
|
||||
await deletePage(ctx.gate, { id: input.pageId })
|
||||
},
|
||||
})
|
||||
.mutation("subscribe", {
|
||||
input: z.object({
|
||||
email: z.boolean().optional(),
|
||||
telegram: z.boolean().optional(),
|
||||
siteId: z.string(),
|
||||
newUser: z
|
||||
.object({
|
||||
email: z.string(),
|
||||
url: z.string(),
|
||||
})
|
||||
.optional(),
|
||||
}),
|
||||
async resolve({ input, ctx }) {
|
||||
await subscribeToSite(ctx.gate, input)
|
||||
},
|
||||
})
|
||||
.mutation("unsubscribe", {
|
||||
input: z.object({
|
||||
siteId: z.string(),
|
||||
}),
|
||||
async resolve({ input, ctx }) {
|
||||
await unsubscribeFromSite(ctx.gate, input)
|
||||
},
|
||||
})
|
||||
.mutation("notifySubscribersForNewPost", {
|
||||
input: z.object({
|
||||
pageId: z.string(),
|
||||
}),
|
||||
async resolve({ ctx, input }) {
|
||||
await notifySubscribersForNewPost(ctx.gate, {
|
||||
pageId: input.pageId,
|
||||
})
|
||||
},
|
||||
})
|
||||
@@ -0,0 +1,35 @@
|
||||
import { encrypt, getDerivedKey } from "@proselog/jwt"
|
||||
import { z } from "zod"
|
||||
import { IS_PROD } from "~/lib/constants"
|
||||
import { ENCRYPT_SECRET } from "~/lib/env.server"
|
||||
import { createRouter } from "~/lib/trpc.server"
|
||||
import { userModel } from "~/models/user.model"
|
||||
|
||||
export const userRouter = createRouter()
|
||||
.query("getSignedJwt", {
|
||||
output: z.string(),
|
||||
async resolve({ ctx }) {
|
||||
const user = ctx.gate.getUser(true)
|
||||
const key = await getDerivedKey(ENCRYPT_SECRET)
|
||||
const token = await encrypt(
|
||||
{ prefix: IS_PROD ? `${user.id}/` : `dev/${user.id}/` },
|
||||
key,
|
||||
{
|
||||
expiresIn: "1h",
|
||||
}
|
||||
)
|
||||
return token
|
||||
},
|
||||
})
|
||||
.mutation("updateProfile", {
|
||||
input: z.object({
|
||||
username: z.string().optional(),
|
||||
name: z.string().optional(),
|
||||
email: z.string().optional(),
|
||||
bio: z.string().optional(),
|
||||
avatar: z.string().optional(),
|
||||
}),
|
||||
async resolve({ ctx, input }) {
|
||||
await userModel.updateProfile(ctx.gate, input)
|
||||
},
|
||||
})
|
||||
Reference in New Issue
Block a user