so now we're on fly.io

This commit is contained in:
EGOIST
2022-05-16 14:13:44 +08:00
parent 358c6631cb
commit c3aa3fd967
116 changed files with 418 additions and 1828 deletions
+80
View File
@@ -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
+25
View File
@@ -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>
)
}
+118
View File
@@ -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>
)
}
+146
View File
@@ -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>
)
}
+255
View File
@@ -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>
)
}
+89
View File
@@ -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>
)
}
+84
View File
@@ -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}
</>
)
}
+56
View File
@@ -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>
</>
)
}
+32
View File
@@ -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>
)
}
+193
View File
@@ -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}
/>
)}
</>
)
}
+32
View File
@@ -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>
</>
)
}
+72
View File
@@ -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>
)
}
+18
View File
@@ -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>
)
}
+47
View File
@@ -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>
)
}
+118
View File
@@ -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,
}
}
+46
View File
@@ -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>
)
})
+51
View File
@@ -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>
)
}
+34
View File
@@ -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>
)
}
+42
View File
@@ -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>
)
}