Remix!
This commit is contained in:
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"extends": ["@remix-run/eslint-config", "@remix-run/eslint-config/node"]
|
||||
}
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
node_modules
|
||||
|
||||
.cache
|
||||
.env
|
||||
.vercel
|
||||
.output
|
||||
|
||||
/build/
|
||||
/public/build
|
||||
/api/index.js
|
||||
/api/**/*.js.map
|
||||
@@ -0,0 +1,13 @@
|
||||
function readPackage(pkg, context) {
|
||||
if (pkg.dependencies["sort-package-json"]) {
|
||||
pkg.dependencies["sort-package-json"] = "1.55.0"
|
||||
}
|
||||
|
||||
return pkg
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
hooks: {
|
||||
readPackage,
|
||||
},
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
## Development
|
||||
|
||||
Follow the steps to run it locally.
|
||||
|
||||
1. Copy `.env.example` to `.env`
|
||||
2. Run `postgres` locally, the easiest way on mac is `brew install postgresql`, you can also use docker
|
||||
3. Install dependencies: `pnpm i`
|
||||
4. Initialize the database by running `pnpm prisma db push`
|
||||
5. Start dev server: `pnpm dev`
|
||||
@@ -0,0 +1,71 @@
|
||||
import { Button } from "~/components/ui/Button"
|
||||
import { useStore } from "~/lib/store"
|
||||
import { Dialog } from "@headlessui/react"
|
||||
import { useEffect, useState } from "react"
|
||||
import { useFetcher } from "@remix-run/react"
|
||||
|
||||
export const LoginModal: React.FC = () => {
|
||||
const [loginModalOpened, setLoginModalOpened] = useStore((store) => [
|
||||
store.loginModalOpened,
|
||||
store.setLoginModalOpened,
|
||||
])
|
||||
const fetcher = useFetcher()
|
||||
|
||||
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">
|
||||
{fetcher.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>
|
||||
)}
|
||||
<fetcher.Form
|
||||
className="space-y-5"
|
||||
method="post"
|
||||
action="/api/request-login-link"
|
||||
>
|
||||
<div>
|
||||
<label
|
||||
className="block mb-1 font-medium text-zinc-600"
|
||||
htmlFor="email"
|
||||
>
|
||||
Email
|
||||
</label>
|
||||
<input
|
||||
id="email"
|
||||
name="email"
|
||||
type="email"
|
||||
className="input is-block"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<Button
|
||||
type="submit"
|
||||
isBlock
|
||||
isLoading={fetcher.state === "submitting"}
|
||||
>
|
||||
Continue
|
||||
</Button>
|
||||
</div>
|
||||
</fetcher.Form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
|
||||
export default LoginModal
|
||||
@@ -0,0 +1,69 @@
|
||||
import { useFetcher } from "@remix-run/react"
|
||||
import React from "react"
|
||||
import { useStore } from "~/lib/store"
|
||||
import { Badge } from "../ui/Badge"
|
||||
import { Button } from "../ui/Button"
|
||||
import { Modal } from "../ui/Modal"
|
||||
|
||||
export const SubscribeModal: React.FC<{
|
||||
siteId: string
|
||||
subscription?: {
|
||||
telegram?: boolean
|
||||
email?: boolean
|
||||
} | null
|
||||
}> = ({ siteId, subscription }) => {
|
||||
const [open, setOpen] = useStore((store) => [
|
||||
store.subscribeModalOpened,
|
||||
store.setSubscribeModalOpened,
|
||||
])
|
||||
const subscribeFetcher = useFetcher()
|
||||
const unsubscribeFetcher = useFetcher()
|
||||
|
||||
return (
|
||||
<Modal title="Become a subscriber" open={open} setOpen={setOpen}>
|
||||
<subscribeFetcher.Form
|
||||
className="p-5"
|
||||
method="post"
|
||||
action={`/api/sites/${siteId}/subscribe`}
|
||||
>
|
||||
<div>
|
||||
<label className="select-none flex items-center space-x-1">
|
||||
<input type="checkbox" defaultChecked={subscription?.email} />
|
||||
<Badge className="mr-1">Soon</Badge>
|
||||
<span>Receive updates via Email</span>
|
||||
</label>
|
||||
</div>
|
||||
<div className="">
|
||||
<label className="select-none flex items-center space-x-1">
|
||||
<input type="checkbox" defaultChecked={subscription?.telegram} />
|
||||
<Badge>Soon</Badge>
|
||||
<span>Receive updates via Telegram</span>
|
||||
</label>
|
||||
</div>
|
||||
<div className="mt-5 space-x-3">
|
||||
<Button
|
||||
type="submit"
|
||||
isLoading={subscribeFetcher.state === "submitting"}
|
||||
>
|
||||
<span>{subscription ? "Update" : "Subscribe"}</span>
|
||||
</Button>
|
||||
{subscription && (
|
||||
<unsubscribeFetcher.Form
|
||||
action={`/api/sites/${siteId}/unsubscribe`}
|
||||
method="post"
|
||||
className="inline"
|
||||
>
|
||||
<Button
|
||||
type="submit"
|
||||
variant="secondary"
|
||||
isLoading={unsubscribeFetcher.state === "submitting"}
|
||||
>
|
||||
Unsubscribe
|
||||
</Button>
|
||||
</unsubscribeFetcher.Form>
|
||||
)}
|
||||
</div>
|
||||
</subscribeFetcher.Form>
|
||||
</Modal>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
import { Dialog } from "@headlessui/react"
|
||||
import { useEffect, 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 { useFetcher } from "@remix-run/react"
|
||||
import toast from "react-hot-toast"
|
||||
|
||||
const AvatarEditorModal: React.FC<{
|
||||
isOpen: boolean
|
||||
image?: File | null
|
||||
setIsOpen: (open: boolean) => void
|
||||
site?: string
|
||||
}> = ({ isOpen, setIsOpen, image, site }) => {
|
||||
const editorRef = useRef<ReactAvatarEditor | null>(null)
|
||||
const fetcher = useFetcher()
|
||||
|
||||
const cropAndSave = async () => {
|
||||
if (!editorRef.current) return
|
||||
const canvas = editorRef.current.getImage()
|
||||
const blob = await new Promise<Blob>((resolve, reject) => {
|
||||
canvas.toBlob((blob) => {
|
||||
if (!blob) return reject(new Error("Canvas is empty"))
|
||||
resolve(blob)
|
||||
})
|
||||
})
|
||||
const form = new FormData()
|
||||
if (site) {
|
||||
form.append("site", site)
|
||||
}
|
||||
form.append("file", blob)
|
||||
fetcher.submit(form, {
|
||||
action: "/api/save-avatar",
|
||||
method: "post",
|
||||
encType: "multipart/form-data",
|
||||
})
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
if (fetcher.type === "done") {
|
||||
setIsOpen(false)
|
||||
toast.success("Updated!")
|
||||
}
|
||||
}, [fetcher.type, setIsOpen])
|
||||
|
||||
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={fetcher.state === "submitting"}
|
||||
>
|
||||
Crop and Save
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
|
||||
export const AvatarForm: React.FC<{
|
||||
filename: string | undefined
|
||||
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 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}
|
||||
/>
|
||||
<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,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,243 @@
|
||||
import { Fragment, useMemo, useState } 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 { Link, useFetcher, useLocation, useNavigate } from "@remix-run/react"
|
||||
import { DashboardMain } from "./DashboardMain"
|
||||
|
||||
export const PagesManager: React.FC<{
|
||||
isPost: boolean
|
||||
subdomain: string
|
||||
pages: {
|
||||
id: string
|
||||
title: string
|
||||
published: boolean
|
||||
publishedAt: Date
|
||||
}[]
|
||||
}> = ({ isPost, subdomain, pages }) => {
|
||||
const navi = useNavigate()
|
||||
const location = useLocation()
|
||||
const query = useMemo(
|
||||
() => Object.fromEntries(new URLSearchParams(location.search)),
|
||||
[location.search]
|
||||
)
|
||||
const visibility = useMemo<PageVisibilityEnum>(
|
||||
() =>
|
||||
query.visibility
|
||||
? (query.visibility as PageVisibilityEnum)
|
||||
: PageVisibilityEnum.All,
|
||||
[query.visibility]
|
||||
)
|
||||
|
||||
const deletePageFetcher = useFetcher()
|
||||
|
||||
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> = {
|
||||
...query,
|
||||
visibility: item.value,
|
||||
}
|
||||
if (item.value === PageVisibilityEnum.All) {
|
||||
delete newQuery["visibility"]
|
||||
}
|
||||
const search = new URLSearchParams(newQuery).toString()
|
||||
navi({
|
||||
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() {
|
||||
navi(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() {
|
||||
deletePageFetcher.submit(
|
||||
{},
|
||||
{ method: "delete", action: `/api/pages/${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={() =>
|
||||
navi(
|
||||
`/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}
|
||||
to={getPageEditLink(page)}
|
||||
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>
|
||||
</Link>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</DashboardMain>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import { Outlet } from "@remix-run/react"
|
||||
import { type TabItem, Tabs } from "../ui/Tabs"
|
||||
import { DashboardMain } from "./DashboardMain"
|
||||
|
||||
export const SettingsLayout: React.FC<{
|
||||
title: string
|
||||
tabItems: TabItem[]
|
||||
}> = ({ title, tabItems }) => {
|
||||
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">
|
||||
<Outlet />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</DashboardMain>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
import { Popover } from "@headlessui/react"
|
||||
import { Link } from "@remix-run/react"
|
||||
import { getUserContentsUrl } from "~/lib/user-contents"
|
||||
import { Avatar } from "../ui/Avatar"
|
||||
|
||||
export const SiteSwitcher: React.FC<{
|
||||
subdomain: string
|
||||
sites: { id: string; name: string; subdomain: string; icon?: string | null }[]
|
||||
viewer: { email: string }
|
||||
}> = ({ subdomain, sites, viewer }) => {
|
||||
const activeSite = sites.find((s) => s.subdomain === subdomain)
|
||||
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">
|
||||
<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}
|
||||
to={`/dashboard/${site.subdomain}`}
|
||||
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>
|
||||
)}
|
||||
</Link>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
<div className="border-t py-2 px-2">
|
||||
<Link
|
||||
to={`/dashboard/new-site`}
|
||||
className="rounded-lg text-sm text-zinc-500 flex px-2 h-8 items-center hover:bg-zinc-100"
|
||||
>
|
||||
Create a new site
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
</Popover.Panel>
|
||||
</Popover>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
import { Link } from "@remix-run/react"
|
||||
import { logout } from "~/lib/auth.client"
|
||||
import { useStore } from "~/lib/store"
|
||||
|
||||
export function MainLayout({
|
||||
isLoggedIn,
|
||||
appName,
|
||||
children,
|
||||
}: {
|
||||
isLoggedIn: boolean
|
||||
appName: string
|
||||
children: React.ReactNode
|
||||
}) {
|
||||
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">
|
||||
{appName}
|
||||
</span>
|
||||
</div>
|
||||
<div className="italic text-zinc-500 text-sm mt-1">
|
||||
..is under beta testing
|
||||
</div>
|
||||
<div className="space-x-5 mt-10">
|
||||
{links.map((link) => {
|
||||
if (link.href) {
|
||||
return (
|
||||
<Link
|
||||
to={link.href}
|
||||
className="font-bold nav-link underline"
|
||||
key={link.text}
|
||||
>
|
||||
{link.text}
|
||||
</Link>
|
||||
)
|
||||
}
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
className="font-bold nav-link underline"
|
||||
onClick={link.onClick}
|
||||
key={link.text}
|
||||
>
|
||||
{link.text}
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{children}
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
import { Link } from "@remix-run/react"
|
||||
import { formatDate } from "~/lib/date"
|
||||
import { type PostOnSiteHome } from "~/lib/types"
|
||||
|
||||
export const SiteHome: React.FC<{
|
||||
posts: PostOnSiteHome[]
|
||||
}> = ({ posts }) => {
|
||||
return (
|
||||
<div className="space-y-14">
|
||||
{posts?.map((post) => {
|
||||
return (
|
||||
<div key={post.id} className="block">
|
||||
<h3 className="text-2xl font-medium">
|
||||
<Link to={`/${post.slug}`} className="hover:text-indigo-500">
|
||||
{post.title}
|
||||
</Link>
|
||||
</h3>
|
||||
<div className="text-sm text-zinc-400 mt-1">
|
||||
{formatDate(post.publishedAt)}
|
||||
</div>
|
||||
<div className="mt-3 text-zinc-500">
|
||||
{post.excerpt}
|
||||
{"..."}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,173 @@
|
||||
import { useLocation } from "@remix-run/react"
|
||||
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, OUR_DOMAIN } from "~/lib/config.shared"
|
||||
|
||||
type MenuLink = {
|
||||
text: string
|
||||
href?: string
|
||||
onClick?: () => void
|
||||
hide?: boolean
|
||||
}
|
||||
|
||||
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 location = useLocation()
|
||||
const setSubscribeModalOpened = useStore(
|
||||
(store) => store.setSubscribeModalOpened
|
||||
)
|
||||
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={() => setSubscribeModalOpened(true)}
|
||||
>
|
||||
<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 = location.pathname === link.href
|
||||
return (
|
||||
<UniLink
|
||||
key={`${link.text}${i}`}
|
||||
href={link.href}
|
||||
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.text}
|
||||
</UniLink>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
)
|
||||
}
|
||||
|
||||
export const SiteLayout: React.FC<{
|
||||
site: {
|
||||
id: string
|
||||
name: string
|
||||
description: string
|
||||
icon?: string | null
|
||||
}
|
||||
isLoggedIn: boolean
|
||||
subscription?: { telegram?: boolean; email?: boolean } | null
|
||||
children: React.ReactNode
|
||||
}> = ({ site, isLoggedIn, subscription, children }) => {
|
||||
const avatars = [getUserContentsUrl(site?.icon)]
|
||||
const setLoginModalOpened = useStore((store) => store.setLoginModalOpened)
|
||||
|
||||
const links: MenuLink[] = [
|
||||
{ text: "Home", href: "/" },
|
||||
{
|
||||
text: "About",
|
||||
href: "/about",
|
||||
},
|
||||
{ text: "Archives", hide: true, href: "/archives" },
|
||||
!isLoggedIn && {
|
||||
text: "Log in",
|
||||
hide: true,
|
||||
onClick() {
|
||||
setLoginModalOpened(true)
|
||||
},
|
||||
},
|
||||
isLoggedIn && {
|
||||
text: "Dashboard",
|
||||
hide: true,
|
||||
href: `${IS_PROD ? "https" : "http"}://${OUR_DOMAIN}/dashboard`,
|
||||
},
|
||||
isLoggedIn && {
|
||||
text: "Log out",
|
||||
hide: true,
|
||||
onClick() {
|
||||
logout()
|
||||
},
|
||||
},
|
||||
].filter(truthy)
|
||||
|
||||
return (
|
||||
<>
|
||||
<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} />
|
||||
)}
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import type { PageType } from "@prisma/client"
|
||||
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,43 @@
|
||||
import React from "react"
|
||||
import clsx from "clsx"
|
||||
|
||||
export const Button: React.FC<
|
||||
React.ButtonHTMLAttributes<HTMLButtonElement> & {
|
||||
isLoading?: boolean
|
||||
isBlock?: boolean
|
||||
variant?: "primary" | "secondary" | "text"
|
||||
variantColor?: "green" | "red"
|
||||
size?: "sm"
|
||||
rounded?: "full" | "lg"
|
||||
}
|
||||
> = ({
|
||||
type,
|
||||
children,
|
||||
className,
|
||||
isLoading,
|
||||
isBlock,
|
||||
variant,
|
||||
variantColor,
|
||||
size,
|
||||
rounded,
|
||||
...props
|
||||
}) => {
|
||||
return (
|
||||
<button
|
||||
{...props}
|
||||
type={type || "button"}
|
||||
className={clsx(
|
||||
className,
|
||||
"button",
|
||||
isLoading && "is-loading",
|
||||
isBlock && `is-block`,
|
||||
variantColor && `is-${variantColor}`,
|
||||
size && `is-${size}`,
|
||||
`is-${variant || "primary"}`,
|
||||
rounded === "full" ? "rounded-full" : "rounded-lg"
|
||||
)}
|
||||
>
|
||||
{children}
|
||||
</button>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
import { useEffect, useRef, useState } from "react"
|
||||
import { EditorState } from "@codemirror/state"
|
||||
import { EditorView, keymap, ViewUpdate } from "@codemirror/view"
|
||||
import { indentWithTab } from "@codemirror/commands"
|
||||
import { markdown } from "@codemirror/lang-markdown"
|
||||
import { history } from "@codemirror/history"
|
||||
|
||||
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 Editor: React.FC<{
|
||||
value: string
|
||||
onChange: (value: string) => void
|
||||
}> = ({ value, onChange }) => {
|
||||
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: value,
|
||||
extensions: [
|
||||
keymap.of([indentWithTab]),
|
||||
markdown(),
|
||||
history(),
|
||||
updateListener,
|
||||
EditorView.lineWrapping,
|
||||
theme,
|
||||
],
|
||||
}),
|
||||
parent: editorRef.current!,
|
||||
})
|
||||
|
||||
setView(view)
|
||||
|
||||
return () => {
|
||||
view.destroy()
|
||||
setView(null)
|
||||
}
|
||||
}, [])
|
||||
|
||||
// Update view state when `value` changed
|
||||
useEffect(() => {
|
||||
const currentValue = view ? view.state.doc.toString() : ""
|
||||
if (view && value !== currentValue) {
|
||||
view.dispatch({
|
||||
changes: { from: 0, to: currentValue.length, insert: value || "" },
|
||||
})
|
||||
}
|
||||
}, [value, view])
|
||||
|
||||
return <div ref={editorRef}></div>
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
import clsx from "clsx"
|
||||
import { DetailedHTMLProps, InputHTMLAttributes } from "react"
|
||||
|
||||
export const Input: React.FC<
|
||||
DetailedHTMLProps<InputHTMLAttributes<HTMLInputElement>, HTMLInputElement> & {
|
||||
label?: string
|
||||
addon?: string
|
||||
isBlock?: boolean
|
||||
error?: string
|
||||
}
|
||||
> = ({ label, addon, className, isBlock, error, ...inputProps }) => {
|
||||
const hasAddon = !!addon
|
||||
return (
|
||||
<div>
|
||||
{label && (
|
||||
<label className="label" htmlFor={inputProps.id}>
|
||||
{label}
|
||||
</label>
|
||||
)}
|
||||
<div className="flex items-center">
|
||||
<input
|
||||
{...inputProps}
|
||||
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 "@remix-run/react"
|
||||
|
||||
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 noopener"
|
||||
>
|
||||
{children}
|
||||
</a>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<Link to={href} className={className}>
|
||||
{children}
|
||||
</Link>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,311 @@
|
||||
import { prisma } from "~/lib/db.server"
|
||||
import {
|
||||
checkPageSlug,
|
||||
checkSubdomain,
|
||||
getSite,
|
||||
getSitesByUser,
|
||||
} from "~/models/site.model"
|
||||
import { PageVisibilityEnum } from "~/lib/types"
|
||||
import { isUUID } from "~/lib/uuid"
|
||||
import { MembershipRole, PageType, Prisma } from "@prisma/client"
|
||||
import { nanoid } from "nanoid"
|
||||
import { z } from "zod"
|
||||
import { type AuthUser } from "~/lib/auth.server"
|
||||
import { createGate } from "~/lib/gate.server"
|
||||
|
||||
export const siteController = {
|
||||
async getSites(user: AuthUser | undefined | null) {
|
||||
const gate = createGate({ user, requireAuth: true })
|
||||
const sites = await getSitesByUser({ userId: gate.user.id })
|
||||
return sites
|
||||
},
|
||||
|
||||
async getSite(siteIdOrSubdomainOrDomain: string) {
|
||||
const site = await getSite(siteIdOrSubdomainOrDomain)
|
||||
return { site }
|
||||
},
|
||||
|
||||
async getPages(
|
||||
user: AuthUser | undefined | null,
|
||||
input: {
|
||||
site: string
|
||||
type: "post" | "page"
|
||||
visibility?: PageVisibilityEnum | null
|
||||
take?: number | null
|
||||
cursor?: string | null
|
||||
}
|
||||
) {
|
||||
const gate = createGate({ user })
|
||||
|
||||
const validated = 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().default(30),
|
||||
cursor: z.string().nullish(),
|
||||
})
|
||||
.parse(input)
|
||||
|
||||
const site = await getSite(validated.site)
|
||||
|
||||
const visibility = validated.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: validated.type === "post" ? "POST" : "PAGE",
|
||||
}
|
||||
if (validated.visibility === PageVisibilityEnum.Published) {
|
||||
where.published = true
|
||||
where.publishedAt = {
|
||||
lte: now,
|
||||
}
|
||||
} else if (validated.visibility === PageVisibilityEnum.Scheduled) {
|
||||
where.published = true
|
||||
where.publishedAt = {
|
||||
gt: now,
|
||||
}
|
||||
} else if (validated.visibility === PageVisibilityEnum.Draft) {
|
||||
where.published = false
|
||||
}
|
||||
|
||||
const [pages, total] = await Promise.all([
|
||||
prisma.page.findMany({
|
||||
where,
|
||||
orderBy: {
|
||||
createdAt: "desc",
|
||||
},
|
||||
take: validated.take + 1,
|
||||
cursor: validated.cursor
|
||||
? {
|
||||
id: validated.cursor,
|
||||
}
|
||||
: undefined,
|
||||
}),
|
||||
await prisma.page.count({
|
||||
where: {
|
||||
siteId: site.id,
|
||||
},
|
||||
}),
|
||||
])
|
||||
|
||||
const hasMore = pages.length > validated.take
|
||||
|
||||
return {
|
||||
pages,
|
||||
total,
|
||||
hasMore,
|
||||
}
|
||||
},
|
||||
|
||||
async createOrUpdatePage(
|
||||
user: AuthUser | null | undefined,
|
||||
input: {
|
||||
pageId?: string
|
||||
siteId: string
|
||||
slug?: string
|
||||
title?: string
|
||||
content?: string
|
||||
published?: boolean
|
||||
publishedAt?: Date
|
||||
excerpt?: string
|
||||
isPost?: boolean
|
||||
}
|
||||
) {
|
||||
const gate = createGate({ user })
|
||||
|
||||
const page = input.pageId
|
||||
? await prisma.page.findUnique({
|
||||
where: {
|
||||
id: input.pageId,
|
||||
},
|
||||
include: {
|
||||
site: true,
|
||||
},
|
||||
})
|
||||
: await prisma.page.create({
|
||||
data: {
|
||||
title: "Untitled",
|
||||
slug: `untitled-${nanoid(4)}`,
|
||||
site: {
|
||||
connect: {
|
||||
id: input.siteId,
|
||||
},
|
||||
},
|
||||
content: "",
|
||||
excerpt: "",
|
||||
},
|
||||
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 updated = await prisma.page.update({
|
||||
where: {
|
||||
id: page.id,
|
||||
},
|
||||
data: {
|
||||
title: input.title,
|
||||
content: input.content,
|
||||
published: input.published,
|
||||
publishedAt: input.publishedAt,
|
||||
excerpt: input.excerpt,
|
||||
slug,
|
||||
type: input.isPost ? "POST" : "PAGE",
|
||||
},
|
||||
})
|
||||
return { page: updated }
|
||||
},
|
||||
|
||||
async getPage(
|
||||
user: AuthUser | null | undefined,
|
||||
input: {
|
||||
/** page slug or id, `site` is needed when `page` is a slug */
|
||||
page: string
|
||||
site: string
|
||||
}
|
||||
) {
|
||||
const gate = createGate({ user })
|
||||
|
||||
const site = input.site ? await getSite(input.site) : null
|
||||
|
||||
if (input.site && !site) {
|
||||
throw new Error(`site not found`)
|
||||
}
|
||||
|
||||
const isPageUUID = isUUID(input.page)
|
||||
if (!isPageUUID && !input.site) {
|
||||
throw new Error("missing input site")
|
||||
}
|
||||
|
||||
const page = isPageUUID
|
||||
? await prisma.page.findUnique({
|
||||
where: {
|
||||
id: input.page,
|
||||
},
|
||||
})
|
||||
: site
|
||||
? await prisma.page.findFirst({
|
||||
where: { siteId: site.id, slug: input.page },
|
||||
})
|
||||
: null
|
||||
|
||||
if (!page || page.deletedAt) {
|
||||
throw new Response(`page ${input.page} not found`, {
|
||||
status: 404,
|
||||
})
|
||||
}
|
||||
|
||||
if (!gate.allows({ type: "can-read-page", page })) {
|
||||
throw gate.permissionError()
|
||||
}
|
||||
|
||||
return page
|
||||
},
|
||||
|
||||
async updateSite(
|
||||
user: AuthUser | undefined | null,
|
||||
payload: {
|
||||
site: string
|
||||
name?: string
|
||||
description?: string
|
||||
icon?: string | null
|
||||
subdomain?: string
|
||||
}
|
||||
) {
|
||||
const gate = createGate({ user, requireAuth: true })
|
||||
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 prisma.site.update({
|
||||
where: {
|
||||
id: site.id,
|
||||
},
|
||||
data: {
|
||||
name: payload.name,
|
||||
subdomain: payload.subdomain,
|
||||
description: payload.description,
|
||||
icon: payload.icon,
|
||||
},
|
||||
})
|
||||
|
||||
return {
|
||||
site: updated,
|
||||
subdomainUpdated: updated.subdomain !== site.subdomain,
|
||||
}
|
||||
},
|
||||
|
||||
async createSite(
|
||||
user: AuthUser | null | undefined,
|
||||
payload: { name: string; subdomain: string }
|
||||
) {
|
||||
const gate = createGate({ user, requireAuth: true })
|
||||
|
||||
await checkSubdomain({ subdomain: payload.subdomain })
|
||||
|
||||
const site = await prisma.site.create({
|
||||
data: {
|
||||
name: payload.name,
|
||||
subdomain: payload.subdomain,
|
||||
memberships: {
|
||||
create: {
|
||||
role: MembershipRole.OWNER,
|
||||
user: {
|
||||
connect: {
|
||||
id: gate.user.id,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
pages: {
|
||||
create: {
|
||||
title: "Aboute",
|
||||
slug: "about",
|
||||
excerpt: "",
|
||||
content: `My name is ${payload.name} and I'm a new site.`,
|
||||
published: true,
|
||||
publishedAt: new Date(),
|
||||
type: PageType.PAGE,
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
return { site }
|
||||
},
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
import { RemixBrowser } from "@remix-run/react";
|
||||
import { hydrate } from "react-dom";
|
||||
|
||||
hydrate(<RemixBrowser />, document);
|
||||
@@ -0,0 +1,21 @@
|
||||
import type { EntryContext } from "@remix-run/node"
|
||||
import { RemixServer } from "@remix-run/react"
|
||||
import { renderToString } from "react-dom/server"
|
||||
|
||||
export default function handleRequest(
|
||||
request: Request,
|
||||
responseStatusCode: number,
|
||||
responseHeaders: Headers,
|
||||
remixContext: EntryContext
|
||||
) {
|
||||
let markup = renderToString(
|
||||
<RemixServer context={remixContext} url={request.url} />
|
||||
)
|
||||
|
||||
responseHeaders.set("Content-Type", "text/html")
|
||||
|
||||
return new Response("<!DOCTYPE html>" + markup, {
|
||||
status: responseStatusCode,
|
||||
headers: responseHeaders,
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
import { useLocation } from "@remix-run/react"
|
||||
import { useMemo } from "react"
|
||||
|
||||
export const useRouteQuery = () => {
|
||||
const location = useLocation()
|
||||
const query = useMemo(() => {
|
||||
const search = new URLSearchParams(location.search)
|
||||
return Object.fromEntries(search)
|
||||
}, [location.search])
|
||||
return query
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
export const logout = () => {
|
||||
const url = new URL(`${location.protocol}//${ENV.OUR_DOMAIN}/api/logout`)
|
||||
if (location.host !== ENV.OUR_DOMAIN) {
|
||||
url.searchParams.set(
|
||||
"next",
|
||||
`${location.protocol}//${location.host}/api/logout`
|
||||
)
|
||||
}
|
||||
location.href = url.href
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
import type { User, Membership } from "@prisma/client"
|
||||
import { AUTH_COOKIE_NAME } from "./config.server"
|
||||
import { prisma } from "./db.server"
|
||||
import dayjs from "dayjs"
|
||||
import { type CookieSerializeOptions, createCookie } from "@remix-run/node"
|
||||
import { IS_PROD, OUR_DOMAIN } from "./config.shared"
|
||||
|
||||
export type AuthUser = User & {
|
||||
memberships: Membership[]
|
||||
}
|
||||
|
||||
export const getAuthTokenFromRequest = async (request: Request) => {
|
||||
let token = request.headers.get("authorization")?.replace(/[Bb]earer\s/, "")
|
||||
if (!token) {
|
||||
const cookie = createCookie(AUTH_COOKIE_NAME)
|
||||
const cookieHeader = request.headers.get("cookie")
|
||||
if (cookieHeader) {
|
||||
const value = await cookie.parse(cookieHeader)
|
||||
token = value
|
||||
}
|
||||
}
|
||||
return token
|
||||
}
|
||||
|
||||
const findUserFromToken = async (token: string) => {
|
||||
const accessToken = await prisma.accessToken.findUnique({
|
||||
where: {
|
||||
token,
|
||||
},
|
||||
include: {
|
||||
user: {
|
||||
include: {
|
||||
memberships: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
return accessToken?.user
|
||||
}
|
||||
|
||||
export const getAuthUser = async <TRequireAuth extends boolean | undefined>(
|
||||
request: Request,
|
||||
requireAuth?: TRequireAuth
|
||||
) => {
|
||||
const token = await 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 }
|
||||
) => {
|
||||
const cookie = createCookie(AUTH_COOKIE_NAME)
|
||||
|
||||
if (options.type === "clear") {
|
||||
return cookie.serialize(
|
||||
"",
|
||||
getAuthCookieOptions({ domain: options.domain, clearCookie: true })
|
||||
)
|
||||
}
|
||||
return cookie.serialize(
|
||||
options.token,
|
||||
getAuthCookieOptions({ domain: options.domain })
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
export const AUTH_COOKIE_NAME = process.env.AUTH_COOKIE_NAME
|
||||
export const S3_REGION = process.env.S3_REGION
|
||||
export const S3_ACCESS_KEY_ID = process.env.S3_ACCESS_KEY_ID
|
||||
export const S3_SECRET_ACCESS_KEY = process.env.S3_SECRET_ACCESS_KEY
|
||||
|
||||
export const S3_BUCKET_NAME = process.env.S3_BUCKET_NAME
|
||||
export const S3_ENDPOINT = process.env.S3_ENDPOINT
|
||||
export const MAILGUN_APIKEY = process.env.MAILGUN_APIKEY
|
||||
export const MAILGUN_DOMAIN = process.env.MAILGUN_DOMAIN
|
||||
export const MAILGUN_EU = process.env.MAILGUN_EU
|
||||
@@ -0,0 +1,8 @@
|
||||
export const IS_BROWSER = typeof window !== "undefined"
|
||||
|
||||
export const IS_PROD = IS_BROWSER
|
||||
? !location.hostname.endsWith("localhost")
|
||||
: process.env.NODE_ENV === "production"
|
||||
|
||||
export const APP_NAME = IS_BROWSER ? ENV.APP_NAME : process.env.APP_NAME
|
||||
export const OUR_DOMAIN = IS_BROWSER ? ENV.OUR_DOMAIN : process.env.OUR_DOMAIN
|
||||
@@ -0,0 +1,5 @@
|
||||
import dayjs from "dayjs"
|
||||
|
||||
export const formatDate = (date: string | Date) => {
|
||||
return dayjs(date).format("MMM D, YYYY")
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
import { PrismaClient } from "@prisma/client"
|
||||
import { singleton } from "./singleton.server"
|
||||
|
||||
export const prisma = /* @__PURE__ */ singleton(
|
||||
"prisma",
|
||||
() => new PrismaClient()
|
||||
)
|
||||
@@ -0,0 +1,105 @@
|
||||
import { MembershipRole, type Site, type Page } from "@prisma/client"
|
||||
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
|
||||
}
|
||||
export const createGate = <TRequiredAuth extends boolean | undefined>({
|
||||
user,
|
||||
requireAuth,
|
||||
}: {
|
||||
user: AuthUser | null | undefined
|
||||
requireAuth?: TRequiredAuth
|
||||
}) => {
|
||||
if (requireAuth && !user) {
|
||||
throw new Error("require auth")
|
||||
}
|
||||
|
||||
const isSiteMember = (siteId: string, roles: MembershipRole[]) => {
|
||||
if (!user) return false
|
||||
return user.memberships.some(
|
||||
(m) => m.siteId === siteId && roles.includes(m.role)
|
||||
)
|
||||
}
|
||||
|
||||
return {
|
||||
user: user as TRequiredAuth extends true
|
||||
? AuthUser
|
||||
: AuthUser | null | undefined,
|
||||
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,
|
||||
])
|
||||
}
|
||||
|
||||
return false
|
||||
},
|
||||
permissionError(message = "not allowed") {
|
||||
return new Error(message)
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
export type Gate = ReturnType<typeof createGate>
|
||||
@@ -0,0 +1,5 @@
|
||||
import { IS_PROD, OUR_DOMAIN } from "./config.shared"
|
||||
|
||||
export const getSiteLink = ({ subdomain }: { subdomain: string }) => {
|
||||
return `${IS_PROD ? "https" : "http"}://${subdomain}.${OUR_DOMAIN}`
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import Mailgun from "mailgun.js"
|
||||
import FormData from "form-data"
|
||||
import { singleton } from "./singleton.server"
|
||||
import { MAILGUN_APIKEY, MAILGUN_DOMAIN, MAILGUN_EU } from "~/lib/config.server"
|
||||
import type { MailgunMessageData } from "mailgun.js/interfaces/Messages"
|
||||
import { APP_NAME, IS_PROD, OUR_DOMAIN } from "./config.shared"
|
||||
|
||||
const getClient = () =>
|
||||
singleton("mailgun", () => {
|
||||
const mg = new Mailgun(FormData)
|
||||
const client = mg.client({
|
||||
username: "api",
|
||||
key: MAILGUN_APIKEY,
|
||||
url: MAILGUN_EU ? `https://api.eu.mailgun.net` : undefined,
|
||||
})
|
||||
return client
|
||||
})
|
||||
|
||||
export const sendLoginEmail = async (loginLink: string, email: string) => {
|
||||
const message: MailgunMessageData = {
|
||||
from: `${APP_NAME} <hi@${OUR_DOMAIN}>`,
|
||||
to: email,
|
||||
subject: `Log in to ${APP_NAME}`,
|
||||
html: `<p>Please use the link below to log in to ${APP_NAME}:</p>
|
||||
|
||||
<a href="${loginLink}">login</a>
|
||||
|
||||
<p>This link will expire in 10 minutes.</p>
|
||||
`,
|
||||
}
|
||||
|
||||
console.log(message)
|
||||
|
||||
if (!IS_PROD) {
|
||||
return
|
||||
}
|
||||
|
||||
const client = getClient()
|
||||
|
||||
await client.messages.create(MAILGUN_DOMAIN, message).then(console.log)
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
import Markdown from "markdown-it"
|
||||
|
||||
export const renderPageContent = async (content: string) => {
|
||||
const md = new Markdown({
|
||||
html: false,
|
||||
linkify: true,
|
||||
})
|
||||
const html = md.render(content)
|
||||
return { html }
|
||||
}
|
||||
|
||||
const stripHTML = (html: string) => {
|
||||
return html.replace(/<(?:.|\n)*?>/gm, "")
|
||||
}
|
||||
|
||||
export const getExcerpt = (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, 200)
|
||||
}
|
||||
@@ -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,37 @@
|
||||
import {
|
||||
S3_REGION,
|
||||
S3_ACCESS_KEY_ID,
|
||||
S3_SECRET_ACCESS_KEY,
|
||||
S3_BUCKET_NAME,
|
||||
S3_ENDPOINT,
|
||||
} from "~/lib/config.server"
|
||||
import {
|
||||
S3Client,
|
||||
PutObjectCommand,
|
||||
type PutObjectRequest,
|
||||
} from "@aws-sdk/client-s3"
|
||||
import { singleton } from "~/lib/singleton.server"
|
||||
|
||||
export const s3 = singleton("s3-client", () => {
|
||||
return new S3Client({
|
||||
endpoint: S3_ENDPOINT ? `https://${S3_ENDPOINT}` : undefined,
|
||||
region: S3_REGION,
|
||||
credentials: {
|
||||
accessKeyId: S3_ACCESS_KEY_ID,
|
||||
secretAccessKey: S3_SECRET_ACCESS_KEY,
|
||||
},
|
||||
})
|
||||
})
|
||||
|
||||
export const s3uploadFile = async (
|
||||
filename: string,
|
||||
file: PutObjectRequest["Body"] | string | Buffer
|
||||
) => {
|
||||
await s3.send(
|
||||
new PutObjectCommand({
|
||||
Bucket: S3_BUCKET_NAME,
|
||||
Key: filename,
|
||||
Body: file,
|
||||
})
|
||||
)
|
||||
}
|
||||
@@ -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>,
|
||||
singleton = true
|
||||
): { readonly value: T; wait: Promise<void> } => {
|
||||
if (globalThis._singletons[id] && singleton) {
|
||||
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,17 @@
|
||||
import { OUR_DOMAIN } from "./config.shared"
|
||||
|
||||
export const getTenant = (request: Request) => {
|
||||
const host = request.headers.get("host")
|
||||
|
||||
const OUR_DOMAIN_SUFFIX = `.${OUR_DOMAIN}`
|
||||
if (host) {
|
||||
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,51 @@
|
||||
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
|
||||
slug: string
|
||||
publishedAt: string | Date
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
export const uploadFileInBrowser = async (blob: Blob) => {
|
||||
const form = new FormData()
|
||||
form.append("file", blob)
|
||||
form.append("type", "image")
|
||||
const res = await fetch(`/api/upload`, {
|
||||
credentials: "same-origin",
|
||||
body: form,
|
||||
method: "POST",
|
||||
})
|
||||
if (!res.ok) {
|
||||
throw new Error(`Upload failed: ${res.statusText}`)
|
||||
}
|
||||
const json = await res.json()
|
||||
return json as { file: string }
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import { IS_PROD, OUR_DOMAIN } from "./config.shared"
|
||||
|
||||
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
|
||||
if (IS_PROD) {
|
||||
return `https://usercontents.${OUR_DOMAIN}/${filename}`
|
||||
}
|
||||
return `/dev-s3-proxy?${new URLSearchParams({
|
||||
filename: filename,
|
||||
}).toString()}`
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
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)
|
||||
+1754
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,157 @@
|
||||
import { prisma } from "~/lib/db.server"
|
||||
import { isUUID } from "~/lib/uuid"
|
||||
import { MembershipRole } from "@prisma/client"
|
||||
|
||||
export const checkSubdomain = async ({
|
||||
subdomain,
|
||||
updatingSiteId,
|
||||
}: {
|
||||
subdomain: string
|
||||
updatingSiteId?: string
|
||||
}) => {
|
||||
const existingSite = await prisma.site.findUnique({
|
||||
where: {
|
||||
subdomain,
|
||||
},
|
||||
})
|
||||
|
||||
if (existingSite?.deletedAt) {
|
||||
// Actuall delete the site so that the subdomain can be used again
|
||||
await prisma.site.delete({
|
||||
where: {
|
||||
id: existingSite.id,
|
||||
},
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
if (existingSite && (!updatingSiteId || existingSite.id !== updatingSiteId)) {
|
||||
throw new Error(`Subdomain already taken`)
|
||||
}
|
||||
}
|
||||
|
||||
export const getUserLastActiveSite = async (userId: string) => {
|
||||
const memberships = await prisma.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 prisma.site.findUnique({
|
||||
where: {
|
||||
id: input,
|
||||
},
|
||||
})
|
||||
: await prisma.site.findUnique({
|
||||
where: {
|
||||
subdomain: input,
|
||||
},
|
||||
})
|
||||
|
||||
if (!site || site.deletedAt) {
|
||||
throw new Error(`Site not found`)
|
||||
}
|
||||
|
||||
return site
|
||||
}
|
||||
|
||||
export const getMembership = async (data: {
|
||||
siteId: string
|
||||
userId: string
|
||||
role: MembershipRole
|
||||
}) => {
|
||||
const first = await prisma.membership.findFirst({
|
||||
where: {
|
||||
role: data.role,
|
||||
userId: data.userId,
|
||||
siteId: data.siteId,
|
||||
},
|
||||
})
|
||||
|
||||
return first
|
||||
}
|
||||
|
||||
export const getSitesByUser = async ({ userId }: { userId: string }) => {
|
||||
const memberships = await prisma.membership.findMany({
|
||||
where: {
|
||||
userId,
|
||||
role: {
|
||||
in: [MembershipRole.ADMIN, MembershipRole.OWNER],
|
||||
},
|
||||
},
|
||||
include: {
|
||||
site: true,
|
||||
},
|
||||
})
|
||||
return memberships.map((m) => m.site)
|
||||
}
|
||||
|
||||
export const checkPageSlug = async ({
|
||||
slug,
|
||||
excludePage,
|
||||
siteId,
|
||||
}: {
|
||||
slug: string
|
||||
excludePage?: string
|
||||
siteId: string
|
||||
}) => {
|
||||
if (!slug) {
|
||||
throw new Error("Missing page slug")
|
||||
}
|
||||
const page = await prisma.page.findFirst({
|
||||
where: {
|
||||
siteId,
|
||||
slug,
|
||||
id: excludePage && {
|
||||
not: excludePage,
|
||||
},
|
||||
},
|
||||
})
|
||||
if (!page) return
|
||||
|
||||
if (page.deletedAt) {
|
||||
await prisma.page.delete({
|
||||
where: {
|
||||
id: page.id,
|
||||
},
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
throw new Error("Page slug already used")
|
||||
}
|
||||
|
||||
export const getSubscription = async (data: {
|
||||
userId: string
|
||||
siteId: string
|
||||
}) => {
|
||||
const membership = await getMembership({
|
||||
...data,
|
||||
role: MembershipRole.SUBSCRIBER,
|
||||
})
|
||||
const config = membership?.config as any
|
||||
return {
|
||||
config: config && {
|
||||
telegram: config.telegram,
|
||||
email: config.email,
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
import { type AuthUser } from "~/lib/auth.server"
|
||||
import { prisma } from "~/lib/db.server"
|
||||
import { createGate } from "~/lib/gate.server"
|
||||
|
||||
export const userModel = {
|
||||
async updateProfile(
|
||||
user: AuthUser | null | undefined,
|
||||
payload: {
|
||||
name?: string
|
||||
username?: string
|
||||
avatar?: string
|
||||
bio?: string
|
||||
email?: string
|
||||
}
|
||||
) {
|
||||
const gate = createGate({ user, requireAuth: true })
|
||||
if (payload.email) {
|
||||
const userByEmail = await prisma.user.findUnique({
|
||||
where: {
|
||||
email: payload.email,
|
||||
},
|
||||
})
|
||||
if (userByEmail && userByEmail.id !== gate.user.id) {
|
||||
throw new Error("email already in use")
|
||||
}
|
||||
}
|
||||
|
||||
if (payload.username) {
|
||||
const userByUsername = await prisma.user.findUnique({
|
||||
where: {
|
||||
username: payload.username,
|
||||
},
|
||||
})
|
||||
if (userByUsername && userByUsername.id !== gate.user.id) {
|
||||
throw new Error("username already in use")
|
||||
}
|
||||
}
|
||||
|
||||
const updated = await prisma.user.update({
|
||||
where: {
|
||||
id: gate.user.id,
|
||||
},
|
||||
data: {
|
||||
name: payload.name,
|
||||
avatar: payload.avatar,
|
||||
username: payload.username,
|
||||
email: payload.email,
|
||||
emailVerified: payload.email !== gate.user.email ? null : undefined,
|
||||
},
|
||||
})
|
||||
|
||||
return {
|
||||
updated,
|
||||
}
|
||||
},
|
||||
}
|
||||
+168
@@ -0,0 +1,168 @@
|
||||
import {
|
||||
json,
|
||||
type LinksFunction,
|
||||
type LoaderFunction,
|
||||
type MetaFunction,
|
||||
} from "@remix-run/node"
|
||||
import {
|
||||
Links,
|
||||
LiveReload,
|
||||
Meta,
|
||||
Outlet,
|
||||
Scripts,
|
||||
ScrollRestoration,
|
||||
useLoaderData,
|
||||
} from "@remix-run/react"
|
||||
import LoginModal from "~/components/common/LoginModal"
|
||||
import { createStore, StoreProvider } from "./lib/store"
|
||||
import { Toaster } from "react-hot-toast"
|
||||
import css from "./main.css"
|
||||
import { getAuthUser } from "./lib/auth.server"
|
||||
import { getTenant } from "./lib/tenant.server"
|
||||
import { siteController } from "./controllers/site.controller"
|
||||
import { getSubscription } from "./models/site.model"
|
||||
import { APP_NAME } from "./lib/config.shared"
|
||||
import { SiteLayout } from "./components/site/SiteLayout"
|
||||
import { MainLayout } from "./components/main/MainLayout"
|
||||
|
||||
export const meta: MetaFunction = () => {
|
||||
return {
|
||||
charset: "utf-8",
|
||||
title: APP_NAME,
|
||||
viewport: "width=device-width,initial-scale=1",
|
||||
}
|
||||
}
|
||||
|
||||
export const links: LinksFunction = () => {
|
||||
return [{ href: css, rel: "stylesheet", type: "text/css" }]
|
||||
}
|
||||
|
||||
type LoaderData =
|
||||
| {
|
||||
type: "main"
|
||||
appName: string
|
||||
isLoggedIn: boolean
|
||||
ENV: Record<string, string>
|
||||
}
|
||||
| {
|
||||
type: "tenant"
|
||||
isLoggedIn: boolean
|
||||
appName: string
|
||||
tenant?: string
|
||||
site: {
|
||||
id: string
|
||||
name: string
|
||||
description: string
|
||||
icon?: string | null
|
||||
}
|
||||
subscription?: {
|
||||
telegram?: boolean
|
||||
email?: boolean
|
||||
} | null
|
||||
ENV: Record<string, string>
|
||||
}
|
||||
| {
|
||||
type: "dashboard"
|
||||
ENV: Record<string, string>
|
||||
}
|
||||
|
||||
export const loader: LoaderFunction = async ({ request }) => {
|
||||
const user = await getAuthUser(request)
|
||||
const tenant = getTenant(request)
|
||||
const env = {
|
||||
APP_NAME: process.env.APP_NAME,
|
||||
OUR_DOMAIN: process.env.OUR_DOMAIN,
|
||||
}
|
||||
|
||||
const isLoggedIn = !!user
|
||||
const url = new URL(request.url)
|
||||
const isDashboard =
|
||||
url.pathname === "/dashboard" || url.pathname.startsWith("/dashboard")
|
||||
|
||||
if (tenant) {
|
||||
if (isDashboard) {
|
||||
throw new Response("not found", { status: 404 })
|
||||
}
|
||||
|
||||
const { site } = await siteController.getSite(tenant)
|
||||
const subscription =
|
||||
user &&
|
||||
(await getSubscription({
|
||||
siteId: site.id,
|
||||
userId: user.id,
|
||||
}))
|
||||
|
||||
return json<LoaderData>({
|
||||
type: "tenant",
|
||||
isLoggedIn,
|
||||
appName: APP_NAME,
|
||||
tenant,
|
||||
site: {
|
||||
id: site.id,
|
||||
name: site.name,
|
||||
description: site.description || "",
|
||||
icon: site.icon,
|
||||
},
|
||||
subscription: subscription?.config,
|
||||
ENV: env,
|
||||
})
|
||||
}
|
||||
|
||||
if (isDashboard) {
|
||||
return json<LoaderData>({
|
||||
type: "dashboard",
|
||||
ENV: env,
|
||||
})
|
||||
}
|
||||
|
||||
return json<LoaderData>({
|
||||
type: "main",
|
||||
isLoggedIn,
|
||||
appName: APP_NAME,
|
||||
ENV: env,
|
||||
})
|
||||
}
|
||||
|
||||
export default function App() {
|
||||
const data = useLoaderData<LoaderData>()
|
||||
|
||||
return (
|
||||
<html>
|
||||
<head>
|
||||
<Meta />
|
||||
<Links />
|
||||
</head>
|
||||
<body>
|
||||
<StoreProvider createStore={createStore}>
|
||||
{data.type === "tenant" ? (
|
||||
<SiteLayout
|
||||
site={data.site}
|
||||
isLoggedIn={data.isLoggedIn}
|
||||
subscription={data.subscription}
|
||||
>
|
||||
<Outlet />
|
||||
</SiteLayout>
|
||||
) : data.type === "dashboard" ? (
|
||||
<Outlet />
|
||||
) : (
|
||||
<MainLayout isLoggedIn={data.isLoggedIn} appName={data.appName}>
|
||||
<Outlet />
|
||||
</MainLayout>
|
||||
)}
|
||||
<LoginModal />
|
||||
</StoreProvider>
|
||||
|
||||
<Toaster />
|
||||
|
||||
<ScrollRestoration />
|
||||
<script
|
||||
dangerouslySetInnerHTML={{
|
||||
__html: `ENV = ${JSON.stringify(data.ENV)}`,
|
||||
}}
|
||||
/>
|
||||
<Scripts />
|
||||
<LiveReload />
|
||||
</body>
|
||||
</html>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
import { json, type MetaFunction, type LoaderFunction } from "@remix-run/node"
|
||||
import { useLoaderData } from "@remix-run/react"
|
||||
import { SitePage } from "~/components/site/SitePage"
|
||||
import { siteController } from "~/controllers/site.controller"
|
||||
import { getAuthUser } from "~/lib/auth.server"
|
||||
import { renderPageContent } from "~/lib/markdown.server"
|
||||
import { getTenant } from "~/lib/tenant.server"
|
||||
|
||||
export const meta: MetaFunction = ({ data, parentsData }) => {
|
||||
return {
|
||||
title: `${data.page.title} - ${parentsData.root.site.name}`,
|
||||
description: parentsData.root.site.description,
|
||||
}
|
||||
}
|
||||
|
||||
export const loader: LoaderFunction = async ({ request, params }) => {
|
||||
const user = await getAuthUser(request)
|
||||
const tenant = getTenant(request)
|
||||
|
||||
if (!tenant) {
|
||||
throw new Response("not found", {
|
||||
status: 404,
|
||||
})
|
||||
}
|
||||
|
||||
const pageSlug = params.page as string
|
||||
const page = await siteController.getPage(user, {
|
||||
page: pageSlug,
|
||||
site: tenant,
|
||||
})
|
||||
const { html } = await renderPageContent(page.content)
|
||||
return json({
|
||||
type: "tenant",
|
||||
page: {
|
||||
id: page.id,
|
||||
title: page.title,
|
||||
type: page.type,
|
||||
content: html,
|
||||
publishedAt: page.publishedAt,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
export default function Page() {
|
||||
const data = useLoaderData()
|
||||
|
||||
if (data.type === "tenant") {
|
||||
return <SitePage page={data.page}></SitePage>
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
Vendored
BIN
Binary file not shown.
@@ -0,0 +1,61 @@
|
||||
import { LoaderFunction, redirect } from "@remix-run/node"
|
||||
import { z } from "zod"
|
||||
import { generateCookie } from "~/lib/auth.server"
|
||||
import { IS_PROD, OUR_DOMAIN } from "~/lib/config.shared"
|
||||
import { prisma } from "~/lib/db.server"
|
||||
|
||||
export const loader: LoaderFunction = async ({ request }) => {
|
||||
const url = new URL(request.url)
|
||||
const data = z
|
||||
.object({
|
||||
id: z.string(),
|
||||
path: z.string().default("/"),
|
||||
host: z.string(),
|
||||
})
|
||||
.parse({
|
||||
id: url.searchParams.get("id"),
|
||||
path: url.searchParams.get("path"),
|
||||
host: request.headers.get("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 prisma.accessToken.findUnique({
|
||||
where: {
|
||||
publicId: data.id,
|
||||
},
|
||||
})
|
||||
|
||||
if (
|
||||
!accessToken ||
|
||||
!accessToken.publicIdExpiresAt ||
|
||||
accessToken.publicIdExpiresAt < new Date()
|
||||
) {
|
||||
throw new Error("invalid id or id expired")
|
||||
}
|
||||
|
||||
await prisma.accessToken.update({
|
||||
where: {
|
||||
id: accessToken.id,
|
||||
},
|
||||
data: {
|
||||
publicId: null,
|
||||
publicIdExpiresAt: null,
|
||||
},
|
||||
})
|
||||
|
||||
return redirect(data.path, {
|
||||
headers: {
|
||||
"set-cookie": await generateCookie({
|
||||
type: "auth",
|
||||
domain: data.host,
|
||||
token: accessToken.token,
|
||||
}),
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
return redirect(data.path)
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
import { LoaderFunction, redirect } from "@remix-run/node"
|
||||
import { z } from "zod"
|
||||
import { prisma } from "~/lib/db.server"
|
||||
import { nanoid } from "nanoid"
|
||||
import UAParser from "ua-parser-js"
|
||||
import dayjs from "dayjs"
|
||||
import { IS_PROD, OUR_DOMAIN } from "~/lib/config.shared"
|
||||
import { generateCookie } from "~/lib/auth.server"
|
||||
|
||||
export const loader: LoaderFunction = async ({ request }) => {
|
||||
const url = new URL(request.url)
|
||||
const data = z
|
||||
.object({
|
||||
token: z.string(),
|
||||
next: z.string(),
|
||||
userAgent: z.string(),
|
||||
})
|
||||
.parse({
|
||||
token: url.searchParams.get("token"),
|
||||
next: url.searchParams.get("next"),
|
||||
userAgent: request.headers.get("user-agent"),
|
||||
})
|
||||
|
||||
const loginToken = await prisma.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 prisma.user.findUnique({
|
||||
where: {
|
||||
email: loginToken.email,
|
||||
},
|
||||
})
|
||||
|
||||
if (!user) {
|
||||
user = await prisma.user.create({
|
||||
data: {
|
||||
email: loginToken.email,
|
||||
name: loginToken.email.split("@")[0],
|
||||
username: nanoid(7),
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
await prisma.loginToken.delete({
|
||||
where: {
|
||||
id: loginToken.id,
|
||||
},
|
||||
})
|
||||
|
||||
const ua = new UAParser(data.userAgent)
|
||||
|
||||
const publicId = nanoid(32)
|
||||
const accessToken = await prisma.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)
|
||||
}
|
||||
|
||||
const nextUrl = new URL(data.next)
|
||||
if (
|
||||
nextUrl.host !== OUR_DOMAIN &&
|
||||
nextUrl.hostname.endsWith(`.${OUR_DOMAIN}`)
|
||||
) {
|
||||
// Check if the host belong to a site
|
||||
const existing = await prisma.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)
|
||||
|
||||
return redirect(nextUrl.href, {
|
||||
headers: {
|
||||
"set-cookie": await generateCookie({
|
||||
type: "auth",
|
||||
domain: OUR_DOMAIN,
|
||||
token: accessToken.token,
|
||||
}),
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import { LoaderFunction, redirect } from "@remix-run/node"
|
||||
import { generateCookie } from "~/lib/auth.server"
|
||||
|
||||
export const loader: LoaderFunction = async ({ request }) => {
|
||||
const url = new URL(request.url)
|
||||
const next = url.searchParams.get("next")
|
||||
const redirectUrl = next ? new URL(next) : new URL(url)
|
||||
if (!next) {
|
||||
redirectUrl.pathname = "/"
|
||||
}
|
||||
return redirect(redirectUrl.href, {
|
||||
headers: {
|
||||
"set-cookie": await generateCookie({ type: "clear" }),
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
import type { ActionFunction } from "@remix-run/node"
|
||||
import { z } from "zod"
|
||||
import { getAuthUser } from "~/lib/auth.server"
|
||||
import { prisma } from "~/lib/db.server"
|
||||
import { createGate } from "~/lib/gate.server"
|
||||
|
||||
export const action: ActionFunction = async ({ request, params }) => {
|
||||
if (request.method === "DELETE") {
|
||||
const user = await getAuthUser(request, true)
|
||||
const gate = createGate({ user })
|
||||
|
||||
const data = z
|
||||
.object({
|
||||
id: z.string(),
|
||||
})
|
||||
.parse({
|
||||
id: params.id,
|
||||
})
|
||||
|
||||
const page = await prisma.page.findUnique({
|
||||
where: {
|
||||
id: data.id,
|
||||
},
|
||||
})
|
||||
|
||||
if (!page) {
|
||||
throw new Error("page not found")
|
||||
}
|
||||
|
||||
if (!gate.allows({ type: "can-delete-page", siteId: page.siteId })) {
|
||||
throw gate.permissionError()
|
||||
}
|
||||
|
||||
await prisma.page.update({
|
||||
where: {
|
||||
id: page.id,
|
||||
},
|
||||
data: {
|
||||
deletedAt: new Date(),
|
||||
},
|
||||
})
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
throw new Error(`unsupported method: ${request.method}`)
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
import { ActionFunction, redirect } from "@remix-run/node"
|
||||
import dayjs from "dayjs"
|
||||
import { z } from "zod"
|
||||
import { IS_PROD, OUR_DOMAIN } from "~/lib/config.shared"
|
||||
import { prisma } from "~/lib/db.server"
|
||||
import { sendLoginEmail } from "~/lib/mailgun.server"
|
||||
|
||||
export const action: ActionFunction = async ({ request }) => {
|
||||
const form = await request.formData()
|
||||
const input = z
|
||||
.object({
|
||||
email: z.string(),
|
||||
referer: z.string(),
|
||||
})
|
||||
.parse({
|
||||
email: form.get("email"),
|
||||
referer: request.headers.get("referer"),
|
||||
})
|
||||
|
||||
const token = await prisma.loginToken.create({
|
||||
data: {
|
||||
email: input.email,
|
||||
expiresAt: dayjs().add(10, "minute").toDate(),
|
||||
},
|
||||
})
|
||||
|
||||
const { protocol, host, pathname } = new URL(input.referer)
|
||||
|
||||
const url = `${
|
||||
IS_PROD ? "https" : "http"
|
||||
}://${OUR_DOMAIN}/api/login?${new URLSearchParams([
|
||||
["token", token.id],
|
||||
["next", `${protocol}//${host}${pathname}`],
|
||||
]).toString()}`
|
||||
|
||||
await sendLoginEmail(url, input.email).catch(console.error)
|
||||
|
||||
return {}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
import {
|
||||
type ActionFunction,
|
||||
unstable_parseMultipartFormData,
|
||||
type UploadHandler,
|
||||
} from "@remix-run/node"
|
||||
import { nanoid } from "nanoid"
|
||||
import { z } from "zod"
|
||||
import { siteController } from "~/controllers/site.controller"
|
||||
import { getAuthUser } from "~/lib/auth.server"
|
||||
import { s3uploadFile } from "~/lib/s3.server"
|
||||
import { userModel } from "~/models/user.model"
|
||||
|
||||
export const action: ActionFunction = async ({ request }) => {
|
||||
const user = await getAuthUser(request, true)
|
||||
|
||||
const uploadHandler: UploadHandler = async ({ stream }) => {
|
||||
const chunks = []
|
||||
for await (let chunk of stream) {
|
||||
chunks.push(chunk)
|
||||
}
|
||||
const buffer = Buffer.concat(chunks)
|
||||
const filename = `${user.id}/${nanoid()}.jpg`
|
||||
await s3uploadFile(filename, buffer)
|
||||
return filename
|
||||
}
|
||||
const formData = await unstable_parseMultipartFormData(request, uploadHandler)
|
||||
|
||||
const values = z
|
||||
.object({
|
||||
file: z.string(),
|
||||
site: z.string().optional(),
|
||||
})
|
||||
.parse(Object.fromEntries(formData))
|
||||
|
||||
if (values.site) {
|
||||
await siteController.updateSite(user, {
|
||||
site: values.site,
|
||||
icon: values.file,
|
||||
})
|
||||
} else {
|
||||
await userModel.updateProfile(user, { avatar: values.file })
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import { json, redirect, type ActionFunction } from "@remix-run/node"
|
||||
import { z } from "zod"
|
||||
import { siteController } from "~/controllers/site.controller"
|
||||
import { getAuthUser } from "~/lib/auth.server"
|
||||
|
||||
export const action: ActionFunction = async ({ request, params }) => {
|
||||
try {
|
||||
const user = await getAuthUser(request)
|
||||
const formData = await request.formData()
|
||||
const values = z
|
||||
.object({
|
||||
name: z.string().optional(),
|
||||
description: z.string().optional(),
|
||||
icon: z.string().nullish().optional(),
|
||||
subdomain: z.string().optional(),
|
||||
})
|
||||
.parse(Object.fromEntries(formData))
|
||||
|
||||
const { site, subdomainUpdated } = await siteController.updateSite(user, {
|
||||
site: params.site as string,
|
||||
name: values.name,
|
||||
description: values.name,
|
||||
icon: values.icon,
|
||||
subdomain: values.subdomain,
|
||||
})
|
||||
|
||||
if (subdomainUpdated) {
|
||||
return redirect(`/dashboard/${site.subdomain}/settings/domains`)
|
||||
}
|
||||
|
||||
return json({ site })
|
||||
} catch (error: any) {
|
||||
console.error(error)
|
||||
return { error: error.message }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
import { ActionFunction } from "@remix-run/node"
|
||||
|
||||
export const action: ActionFunction = async () => {}
|
||||
@@ -0,0 +1,27 @@
|
||||
import type { ActionFunction } from "@remix-run/node"
|
||||
import { z } from "zod"
|
||||
import { getAuthUser } from "~/lib/auth.server"
|
||||
import { userModel } from "~/models/user.model"
|
||||
|
||||
export const action: ActionFunction = async ({ request }) => {
|
||||
const user = await getAuthUser(request, true)
|
||||
const formData = await request.formData()
|
||||
|
||||
const values = z
|
||||
.object({
|
||||
name: z.string().optional(),
|
||||
username: z.string().optional(),
|
||||
email: z.string().optional(),
|
||||
bio: z.string().optional(),
|
||||
})
|
||||
.parse(Object.fromEntries(formData))
|
||||
|
||||
await userModel.updateProfile(user, {
|
||||
username: values.username,
|
||||
name: values.name,
|
||||
email: values.email,
|
||||
bio: values.bio,
|
||||
})
|
||||
|
||||
return null
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
import { json, type MetaFunction, type LoaderFunction } from "@remix-run/node"
|
||||
import { Link, useLoaderData } from "@remix-run/react"
|
||||
import { siteController } from "~/controllers/site.controller"
|
||||
import { getAuthUser } from "~/lib/auth.server"
|
||||
import { formatDate } from "~/lib/date"
|
||||
import { getTenant } from "~/lib/tenant.server"
|
||||
import { PageVisibilityEnum, type PostOnArchivesPage } from "~/lib/types"
|
||||
|
||||
type LoaderData = {
|
||||
posts: PostOnArchivesPage[]
|
||||
}
|
||||
|
||||
export const meta: MetaFunction = ({ data, parentsData }) => {
|
||||
return {
|
||||
title: `Archives - ${parentsData.root.site.name}`,
|
||||
description: parentsData.root.site.description,
|
||||
}
|
||||
}
|
||||
|
||||
export const loader: LoaderFunction = async ({ request }) => {
|
||||
const tenant = getTenant(request)
|
||||
if (!tenant)
|
||||
throw new Response("not found", {
|
||||
status: 404,
|
||||
})
|
||||
|
||||
const user = await getAuthUser(request)
|
||||
const { pages } = await siteController.getPages(user, {
|
||||
site: tenant,
|
||||
type: "post",
|
||||
visibility: PageVisibilityEnum.Published,
|
||||
take: 1000,
|
||||
})
|
||||
return json<LoaderData>({
|
||||
posts: pages,
|
||||
})
|
||||
}
|
||||
|
||||
export default function ArchivesPage() {
|
||||
const { posts } = useLoaderData<LoaderData>()
|
||||
return (
|
||||
<>
|
||||
<h2 className="text-xl font-bold page-title">Archives</h2>
|
||||
<div className="mt-5">
|
||||
{posts.map((post) => {
|
||||
return (
|
||||
<div key={post.id} className="flex">
|
||||
<span className="text-zinc-400 mr-3">
|
||||
{formatDate(post.publishedAt)}
|
||||
</span>
|
||||
<Link
|
||||
to={`/${post.slug}`}
|
||||
className="flex text-accent hover:underline"
|
||||
>
|
||||
{post.title}
|
||||
</Link>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,200 @@
|
||||
import { type LoaderFunction, redirect } from "@remix-run/node"
|
||||
import {
|
||||
Link,
|
||||
Outlet,
|
||||
useLoaderData,
|
||||
useLocation,
|
||||
useParams,
|
||||
} from "@remix-run/react"
|
||||
import clsx from "clsx"
|
||||
import { SiteSwitcher } from "~/components/dashboard/SiteSwitcher"
|
||||
import { UniLink } from "~/components/ui/UniLink"
|
||||
import { siteController } from "~/controllers/site.controller"
|
||||
import { getAuthUser } from "~/lib/auth.server"
|
||||
import { getSiteLink } from "~/lib/helpers"
|
||||
|
||||
export const loader: LoaderFunction = async ({ request, params }) => {
|
||||
const user = await getAuthUser(request)
|
||||
if (!user) return redirect("/")
|
||||
|
||||
const sites = await siteController.getSites(user)
|
||||
|
||||
const subdomain = params.subdomain as string
|
||||
const site = sites.find((site) => site.subdomain === subdomain)
|
||||
if (!site) {
|
||||
throw new Response("not found", {
|
||||
status: 404,
|
||||
})
|
||||
}
|
||||
|
||||
return { sites, viewer: user }
|
||||
}
|
||||
|
||||
export const Sidebar: 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>
|
||||
)
|
||||
}
|
||||
|
||||
export default function DashboardLayout({}: {}) {
|
||||
const params = useParams()
|
||||
const subdomain = params.subdomain as string
|
||||
const { sites, viewer } = useLoaderData()
|
||||
const location = useLocation()
|
||||
|
||||
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">
|
||||
<Sidebar>
|
||||
<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: location.pathname,
|
||||
href: link.href,
|
||||
})
|
||||
return (
|
||||
<Link
|
||||
to={link.href}
|
||||
key={link.href}
|
||||
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>
|
||||
</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>
|
||||
</Sidebar>
|
||||
<Outlet />
|
||||
</div>
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import { useLocation, useParams } from "@remix-run/react"
|
||||
import { SettingsLayout } from "~/components/dashboard/SettingsLayout"
|
||||
import { type TabItem } from "~/components/ui/Tabs"
|
||||
|
||||
export default function AccountLayoutPage() {
|
||||
const params = useParams()
|
||||
const subdomain = params.subdomain as string
|
||||
const location = useLocation()
|
||||
const tabItems: TabItem[] = [
|
||||
{ text: "Profile", href: `/dashboard/${subdomain}/account/profile` },
|
||||
].map((item) => ({ ...item, active: location.pathname === item.href }))
|
||||
return <SettingsLayout title="Account" tabItems={tabItems} />
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
import { type LoaderFunction } from "@remix-run/node"
|
||||
import { useFetcher, useLoaderData } from "@remix-run/react"
|
||||
import { useEffect } from "react"
|
||||
import toast from "react-hot-toast"
|
||||
import { AvatarForm } from "~/components/dashboard/AvatarForm"
|
||||
import { Button } from "~/components/ui/Button"
|
||||
import { Input } from "~/components/ui/Input"
|
||||
import { getAuthUser } from "~/lib/auth.server"
|
||||
|
||||
export const loader: LoaderFunction = async ({ request }) => {
|
||||
const user = await getAuthUser(request, true)
|
||||
return {
|
||||
viewer: {
|
||||
id: user.id,
|
||||
avatar: user.avatar,
|
||||
name: user.name,
|
||||
username: user.username,
|
||||
email: user.email,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
export default function AccountProfilePage() {
|
||||
const { viewer } = useLoaderData()
|
||||
const fetcher = useFetcher()
|
||||
|
||||
useEffect(() => {
|
||||
if (fetcher.type === "done") {
|
||||
toast.success("Saved!")
|
||||
}
|
||||
}, [fetcher.type])
|
||||
|
||||
return (
|
||||
<>
|
||||
<div>
|
||||
<label className="label">Profile Picture</label>
|
||||
<AvatarForm filename={viewer.avatar} name={viewer.name} />
|
||||
</div>
|
||||
<fetcher.Form method="post" action={`/api/viewer`}>
|
||||
<div className="mt-5">
|
||||
<Input
|
||||
label="Display Name"
|
||||
id="name"
|
||||
name="name"
|
||||
required
|
||||
type="text"
|
||||
defaultValue={viewer.name}
|
||||
/>
|
||||
</div>
|
||||
<div className="mt-5">
|
||||
<Input
|
||||
label="Username"
|
||||
id="username"
|
||||
name="username"
|
||||
required
|
||||
type="text"
|
||||
defaultValue={viewer.username}
|
||||
/>
|
||||
</div>
|
||||
<div className="mt-5">
|
||||
<Input
|
||||
label="Email"
|
||||
id="email"
|
||||
name="email"
|
||||
required
|
||||
type="email"
|
||||
defaultValue={viewer.email}
|
||||
/>
|
||||
</div>
|
||||
<div className="mt-10">
|
||||
<Button type="submit" isLoading={fetcher.state === "submitting"}>
|
||||
Save
|
||||
</Button>
|
||||
</div>
|
||||
</fetcher.Form>
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,265 @@
|
||||
import { Popover } from "@headlessui/react"
|
||||
import { useFetcher, useLoaderData, useParams } from "@remix-run/react"
|
||||
import clsx from "clsx"
|
||||
import dayjs from "dayjs"
|
||||
import { 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 { useRouteQuery } from "~/hooks/useRouteQuery"
|
||||
import {
|
||||
type ActionFunction,
|
||||
json,
|
||||
type LoaderFunction,
|
||||
redirect,
|
||||
} from "@remix-run/node"
|
||||
import ReactCodeMirror from "@uiw/react-codemirror"
|
||||
import { siteController } from "~/controllers/site.controller"
|
||||
import { getAuthUser } from "~/lib/auth.server"
|
||||
import { getSite } from "~/models/site.model"
|
||||
import { z } from "zod"
|
||||
import toast from "react-hot-toast"
|
||||
import { Input } from "~/components/ui/Input"
|
||||
import { getSiteLink } from "~/lib/helpers"
|
||||
|
||||
export const loader: LoaderFunction = async ({ request, params }) => {
|
||||
const user = await getAuthUser(request)
|
||||
if (!user) return redirect("/")
|
||||
|
||||
const url = new URL(request.url)
|
||||
const pageId = url.searchParams.get("id") as string | undefined
|
||||
const subdomain = params.subdomain as string
|
||||
const page =
|
||||
pageId &&
|
||||
(await siteController.getPage(user, {
|
||||
page: pageId,
|
||||
site: subdomain,
|
||||
}))
|
||||
return json({
|
||||
page,
|
||||
})
|
||||
}
|
||||
|
||||
export const action: ActionFunction = async ({ request, params }) => {
|
||||
const isDelete = request.method === "delete"
|
||||
const user = await getAuthUser(request)
|
||||
const url = new URL(request.url)
|
||||
|
||||
if (!user) return redirect("/")
|
||||
|
||||
if (isDelete) {
|
||||
return null
|
||||
}
|
||||
|
||||
const formData = await request.formData()
|
||||
const values = z
|
||||
.object({
|
||||
pageId: z.string().optional(),
|
||||
title: z.string(),
|
||||
content: z.string(),
|
||||
published: z.boolean(),
|
||||
publishedAt: z.string().transform((v) => new Date(v)),
|
||||
isPost: z.boolean(),
|
||||
slug: z.string(),
|
||||
})
|
||||
.parse(JSON.parse(formData.get("input") as string))
|
||||
|
||||
const subdomain = params.subdomain as string
|
||||
const site = await getSite(subdomain)
|
||||
|
||||
const { page } = await siteController.createOrUpdatePage(user, {
|
||||
pageId: values.pageId,
|
||||
siteId: site.id,
|
||||
title: values.title,
|
||||
content: values.content,
|
||||
isPost: values.isPost,
|
||||
published: values.published,
|
||||
publishedAt: values.publishedAt,
|
||||
slug: values.slug,
|
||||
})
|
||||
|
||||
return redirect(
|
||||
`/dashboard/${subdomain}/editor?id=${page.id}&type=${
|
||||
values.isPost ? "post" : "page"
|
||||
}`
|
||||
)
|
||||
}
|
||||
|
||||
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 query = useRouteQuery()
|
||||
const params = useParams()
|
||||
const subdomain = params.subdomain as string
|
||||
const isPost = query.type === "post"
|
||||
const { page } = useLoaderData()
|
||||
const published = page?.published ?? false
|
||||
const visibility = getPageVisibility({
|
||||
published,
|
||||
publishedAt: page?.publishedAt || null,
|
||||
})
|
||||
const [values, setValues] = useState({
|
||||
title: "",
|
||||
content: "",
|
||||
publishedAt: new Date(),
|
||||
published: false,
|
||||
slug: "",
|
||||
})
|
||||
const updateValue = (field: string, value: any) => {
|
||||
setValues((values) => {
|
||||
return {
|
||||
...values,
|
||||
[field]: value,
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
if (page) {
|
||||
setValues({
|
||||
title: page.title,
|
||||
content: page.content,
|
||||
publishedAt: page.publishedAt,
|
||||
published: page.published,
|
||||
slug: page.slug,
|
||||
})
|
||||
}
|
||||
}, [page])
|
||||
|
||||
const fetcher = useFetcher()
|
||||
|
||||
useEffect(() => {
|
||||
if (fetcher.type === "done") {
|
||||
console.log("updated")
|
||||
toast.success("Updated!")
|
||||
}
|
||||
}, [fetcher.type])
|
||||
|
||||
return (
|
||||
<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={fetcher.state === "submitting"}
|
||||
onClick={() => {
|
||||
fetcher.submit(
|
||||
{
|
||||
input: JSON.stringify({
|
||||
...values,
|
||||
pageId: page?.id,
|
||||
isPost: isPost,
|
||||
}),
|
||||
},
|
||||
{
|
||||
method: "post",
|
||||
}
|
||||
)
|
||||
}}
|
||||
>
|
||||
{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-2xl font-bold w-full focus:outline-none"
|
||||
placeholder="Title goes here.."
|
||||
/>
|
||||
</div>
|
||||
<div className="mt-5">
|
||||
<div className="">
|
||||
<ReactCodeMirror
|
||||
value={values.content}
|
||||
onChange={(value) => updateValue("content", value)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="h-full overflow-auto flex-shrink-0 w-[280px] border-l bg-gray-50 p-5">
|
||||
<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{" "}
|
||||
{getSiteLink({ subdomain })}/{values.slug}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</DashboardMain>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
import { DashboardMain } from "~/components/dashboard/DashboardMain"
|
||||
|
||||
export default function SubdomainIndex() {
|
||||
return <DashboardMain>hi</DashboardMain>
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
import { createLoader } from "./posts"
|
||||
|
||||
export const loader = /* @__PURE__ */ createLoader(false)
|
||||
|
||||
export { default } from "./posts"
|
||||
@@ -0,0 +1,31 @@
|
||||
import { LoaderFunction, redirect } from "@remix-run/node"
|
||||
import { useLoaderData, useParams } from "@remix-run/react"
|
||||
import { PagesManager } from "~/components/dashboard/PagesManager"
|
||||
import { siteController } from "~/controllers/site.controller"
|
||||
import { getAuthUser } from "~/lib/auth.server"
|
||||
|
||||
export const createLoader =
|
||||
(isPost: boolean): LoaderFunction =>
|
||||
async ({ request, params }) => {
|
||||
const url = new URL(request.url)
|
||||
const subdomain = params.subdomain as string
|
||||
const user = await getAuthUser(request)
|
||||
if (!user) return redirect("/")
|
||||
const { pages } = await siteController.getPages(user, {
|
||||
site: subdomain,
|
||||
type: isPost ? "post" : "page",
|
||||
take: parseInt(url.searchParams.get("take") || "30", 10),
|
||||
cursor: url.searchParams.get("cursor"),
|
||||
visibility: url.searchParams.get("visibility") as any,
|
||||
})
|
||||
return { pages, isPost }
|
||||
}
|
||||
|
||||
export const loader: LoaderFunction = /* @__PURE__ */ createLoader(true)
|
||||
|
||||
export default function SubdomainPosts() {
|
||||
const params = useParams()
|
||||
const subdomain = params.subdomain as string
|
||||
const { pages, isPost } = useLoaderData()
|
||||
return <PagesManager isPost={isPost} pages={pages} subdomain={subdomain} />
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import { useLocation, useParams } from "@remix-run/react"
|
||||
import { SettingsLayout } from "~/components/dashboard/SettingsLayout"
|
||||
import { type TabItem } from "~/components/ui/Tabs"
|
||||
|
||||
export default function SettingsLayoutPage() {
|
||||
const params = useParams()
|
||||
const subdomain = params.subdomain as string
|
||||
const location = useLocation()
|
||||
const tabItems: TabItem[] = [
|
||||
{ text: "General", href: `/dashboard/${subdomain}/settings/general` },
|
||||
{ text: "Domains", href: `/dashboard/${subdomain}/settings/domains` },
|
||||
].map((item) => ({ ...item, active: location.pathname === item.href }))
|
||||
return <SettingsLayout title="Site Settings" tabItems={tabItems} />
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
import { type LoaderFunction } from "@remix-run/node"
|
||||
import { useFetcher, useLoaderData } from "@remix-run/react"
|
||||
import { useEffect } from "react"
|
||||
import toast from "react-hot-toast"
|
||||
import { Button } from "~/components/ui/Button"
|
||||
import { Input } from "~/components/ui/Input"
|
||||
import { siteController } from "~/controllers/site.controller"
|
||||
import { getAuthUser } from "~/lib/auth.server"
|
||||
import { OUR_DOMAIN } from "~/lib/config.shared"
|
||||
|
||||
export const loader: LoaderFunction = async ({ request, params }) => {
|
||||
await getAuthUser(request, true)
|
||||
const subdomain = params.subdomain as string
|
||||
const { site } = await siteController.getSite(subdomain)
|
||||
return {
|
||||
site: {
|
||||
id: site.id,
|
||||
name: site.name,
|
||||
subdomain: site.subdomain,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
export default function SettingsDomainsPage() {
|
||||
const { site } = useLoaderData()
|
||||
const fetcher = useFetcher()
|
||||
|
||||
useEffect(() => {
|
||||
if (fetcher.type === "done") {
|
||||
toast.success("Saved!")
|
||||
}
|
||||
}, [fetcher.type])
|
||||
|
||||
return (
|
||||
<fetcher.Form method="post" action={`/api/sites/${site.id}`}>
|
||||
<div className="">
|
||||
<Input
|
||||
name="subdomain"
|
||||
id="subdomain"
|
||||
label="Subdomain"
|
||||
addon={`.${OUR_DOMAIN}`}
|
||||
defaultValue={site.subdomain}
|
||||
className="w-28"
|
||||
error={fetcher.data?.error}
|
||||
/>
|
||||
</div>
|
||||
<div className="mt-5">
|
||||
<Button type="submit" isLoading={fetcher.state === "submitting"}>
|
||||
Save
|
||||
</Button>
|
||||
</div>
|
||||
</fetcher.Form>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
import { Button } from "~/components/ui/Button"
|
||||
import { Input } from "~/components/ui/Input"
|
||||
import { useFetcher, useLoaderData } from "@remix-run/react"
|
||||
import { type LoaderFunction } from "@remix-run/node"
|
||||
import { siteController } from "~/controllers/site.controller"
|
||||
import { AvatarForm } from "~/components/dashboard/AvatarForm"
|
||||
import { useEffect } from "react"
|
||||
import toast from "react-hot-toast"
|
||||
|
||||
export const loader: LoaderFunction = async ({ request, params }) => {
|
||||
const subdomain = params.subdomain as string
|
||||
const { site } = await siteController.getSite(subdomain)
|
||||
return {
|
||||
site,
|
||||
}
|
||||
}
|
||||
|
||||
export default function SiteSettingsGeneralPage() {
|
||||
const loaderData = useLoaderData()
|
||||
const site = loaderData.site
|
||||
const fetcher = useFetcher()
|
||||
|
||||
useEffect(() => {
|
||||
if (fetcher.type === "done") {
|
||||
toast.success("Updated!")
|
||||
}
|
||||
}, [fetcher.type])
|
||||
|
||||
return (
|
||||
<>
|
||||
<div>
|
||||
<label className="label">Icon</label>
|
||||
<AvatarForm site={site.id} name={site.name} filename={site.icon} />
|
||||
</div>
|
||||
<fetcher.Form method="post" action={`/api/sites/${site.id}`}>
|
||||
<div className="mt-5">
|
||||
<Input
|
||||
required
|
||||
label="Name"
|
||||
id="name"
|
||||
name="name"
|
||||
defaultValue={site.name}
|
||||
/>
|
||||
</div>
|
||||
<div className="mt-5">
|
||||
<label htmlFor="description" className="label">
|
||||
Description
|
||||
</label>
|
||||
<textarea
|
||||
id="description"
|
||||
className="input is-block"
|
||||
name="description"
|
||||
defaultValue={site.description}
|
||||
rows={6}
|
||||
/>
|
||||
</div>
|
||||
<div className="mt-5">
|
||||
<Button type="submit" isLoading={fetcher.state === "submitting"}>
|
||||
Save
|
||||
</Button>
|
||||
</div>
|
||||
</fetcher.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> */}
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import { type LoaderFunction, redirect } from "@remix-run/node"
|
||||
import { getAuthUser } from "~/lib/auth.server"
|
||||
import { getUserLastActiveSite } from "~/models/site.model"
|
||||
|
||||
export const loader: LoaderFunction = async ({ request }) => {
|
||||
const user = await getAuthUser(request)
|
||||
|
||||
if (!user) {
|
||||
return redirect("/")
|
||||
}
|
||||
const site = await getUserLastActiveSite(user.id)
|
||||
if (!site) {
|
||||
return redirect(`/dashboard/new-site`)
|
||||
}
|
||||
return redirect(`/dashboard/${site.subdomain}`)
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
import {
|
||||
type ActionFunction,
|
||||
json,
|
||||
type LoaderFunction,
|
||||
redirect,
|
||||
} from "@remix-run/node"
|
||||
import { Form, Link, useLoaderData, useTransition } from "@remix-run/react"
|
||||
import { z } from "zod"
|
||||
import { Button } from "~/components/ui/Button"
|
||||
import { Input } from "~/components/ui/Input"
|
||||
import { siteController } from "~/controllers/site.controller"
|
||||
import { getAuthUser } from "~/lib/auth.server"
|
||||
import { OUR_DOMAIN } from "~/lib/config.shared"
|
||||
|
||||
export const loader: LoaderFunction = async ({ request }) => {
|
||||
const user = await getAuthUser(request, true)
|
||||
|
||||
return json({
|
||||
viewer: {
|
||||
email: user.email,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
export const action: ActionFunction = async ({ request }) => {
|
||||
const user = await getAuthUser(request, true)
|
||||
const formData = await request.formData()
|
||||
const values = z
|
||||
.object({
|
||||
name: z.string(),
|
||||
subdomain: z.string(),
|
||||
})
|
||||
.parse(Object.fromEntries(formData))
|
||||
const { site } = await siteController.createSite(user, values)
|
||||
return redirect(`/dashboard/${site.subdomain}`)
|
||||
}
|
||||
|
||||
export default function NewSitePage() {
|
||||
const { viewer } = useLoaderData()
|
||||
const transition = useTransition()
|
||||
|
||||
return (
|
||||
<div>
|
||||
<header className="px-5 text-sm md:px-14 flex justify-between items-start py-10">
|
||||
<Link to="/dashboard" 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>
|
||||
</Link>
|
||||
<div>
|
||||
<div className="text-zinc-400">Logged in as:</div>
|
||||
<div>{viewer.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" method="post">
|
||||
<div>
|
||||
<Input name="name" id="name" label="Site Name" required isBlock />
|
||||
</div>
|
||||
<div>
|
||||
<Input
|
||||
name="subdomain"
|
||||
id="subdomain"
|
||||
label="Subdomain"
|
||||
required
|
||||
isBlock
|
||||
addon={`.${OUR_DOMAIN}`}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<Button
|
||||
type="submit"
|
||||
isBlock
|
||||
isLoading={transition.state === "submitting"}
|
||||
>
|
||||
Create
|
||||
</Button>
|
||||
</div>
|
||||
</Form>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import { LoaderFunction } from "@remix-run/node"
|
||||
import { S3_BUCKET_NAME, S3_ENDPOINT } from "~/lib/config.server"
|
||||
import { IS_PROD } from "~/lib/config.shared"
|
||||
|
||||
export const loader: LoaderFunction = ({ request }) => {
|
||||
if (IS_PROD) {
|
||||
return
|
||||
}
|
||||
const url = new URL(request.url)
|
||||
const filename = url.searchParams.get("filename")
|
||||
return fetch(`https://${S3_BUCKET_NAME}.${S3_ENDPOINT}/${filename}`)
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
import { json, type MetaFunction, type LoaderFunction } from "@remix-run/node"
|
||||
import { useLoaderData } from "@remix-run/react"
|
||||
import { SiteHome } from "~/components/site/SiteHome"
|
||||
import { siteController } from "~/controllers/site.controller"
|
||||
import { getAuthUser } from "~/lib/auth.server"
|
||||
import { APP_NAME } from "~/lib/config.shared"
|
||||
import { getTenant } from "~/lib/tenant.server"
|
||||
import { PageVisibilityEnum, type PostOnSiteHome } from "~/lib/types"
|
||||
|
||||
type LoaderData =
|
||||
| {
|
||||
type: "main"
|
||||
appName: string
|
||||
isLoggedIn: boolean
|
||||
}
|
||||
| {
|
||||
type: "tenant"
|
||||
isLoggedIn: boolean
|
||||
appName: string
|
||||
tenant?: string
|
||||
posts: PostOnSiteHome[]
|
||||
}
|
||||
|
||||
export const meta: MetaFunction = ({ parentsData }) => {
|
||||
return {
|
||||
title: `${parentsData.root.site.name}`,
|
||||
description: parentsData.root.site.description,
|
||||
}
|
||||
}
|
||||
|
||||
export const loader: LoaderFunction = async (ctx) => {
|
||||
const user = await getAuthUser(ctx.request)
|
||||
const tenant = getTenant(ctx.request)
|
||||
|
||||
const isLoggedIn = !!user
|
||||
|
||||
if (tenant) {
|
||||
const { pages } = await siteController.getPages(user, {
|
||||
visibility: PageVisibilityEnum.Published,
|
||||
type: "post",
|
||||
site: tenant,
|
||||
})
|
||||
return json<LoaderData>({
|
||||
type: "tenant",
|
||||
isLoggedIn,
|
||||
appName: APP_NAME,
|
||||
tenant,
|
||||
posts: pages,
|
||||
})
|
||||
}
|
||||
|
||||
return json<LoaderData>({ type: "main", isLoggedIn, appName: APP_NAME })
|
||||
}
|
||||
|
||||
export default function Home() {
|
||||
const data = useLoaderData<LoaderData>()
|
||||
|
||||
if (data.type === "tenant") {
|
||||
return <SiteHome posts={data.posts} />
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
@import "./variables.css";
|
||||
@import "./tailwind.css";
|
||||
@import "./prose.css";
|
||||
@@ -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,152 @@
|
||||
@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.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-sm {
|
||||
@apply h-7;
|
||||
@apply px-2;
|
||||
@apply text-sm;
|
||||
}
|
||||
|
||||
.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;
|
||||
}
|
||||
|
||||
.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,65 @@
|
||||
{
|
||||
"name": "remix-template-vercel",
|
||||
"private": true,
|
||||
"description": "",
|
||||
"license": "",
|
||||
"sideEffects": false,
|
||||
"scripts": {
|
||||
"build-remix": "remix build",
|
||||
"build": "pnpm build-css && pnpm build-remix",
|
||||
"dev-remix": "remix dev",
|
||||
"dev": "pnpm generate-css && run-p dev-*",
|
||||
"generate-css": "tailwindcss --input ./css/main.css --output ./app/main.css --postcss",
|
||||
"dev-css": "pnpm generate-css --watch",
|
||||
"build-css": "pnpm generate-css --minify"
|
||||
},
|
||||
"dependencies": {
|
||||
"@aws-sdk/client-s3": "^3.81.0",
|
||||
"@codemirror/commands": "^0.20.0",
|
||||
"@codemirror/history": "^0.19.2",
|
||||
"@codemirror/lang-markdown": "^0.20.0",
|
||||
"@codemirror/state": "^0.20.0",
|
||||
"@codemirror/view": "^0.20.3",
|
||||
"@headlessui/react": "^1.6.0",
|
||||
"@prisma/client": "^3.13.0",
|
||||
"@remix-run/node": "*",
|
||||
"@remix-run/react": "*",
|
||||
"@remix-run/vercel": "*",
|
||||
"@uiw/react-codemirror": "^4.7.0",
|
||||
"@vercel/node": "^1.14.0",
|
||||
"clsx": "^1.1.1",
|
||||
"dayjs": "^1.11.1",
|
||||
"form-data": "^4.0.0",
|
||||
"mailgun.js": "^5.2.2",
|
||||
"markdown-it": "^13.0.0",
|
||||
"nanoid": "^3.3.3",
|
||||
"react": "^17.0.2",
|
||||
"react-avatar-editor": "^12.0.0",
|
||||
"react-dom": "^17.0.2",
|
||||
"react-hot-toast": "^2.2.0",
|
||||
"ua-parser-js": "^1.0.2",
|
||||
"uuid": "^8.3.2",
|
||||
"zod": "^3.14.4",
|
||||
"zustand": "4.0.0-rc.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@remix-run/dev": "*",
|
||||
"@remix-run/eslint-config": "*",
|
||||
"@remix-run/serve": "*",
|
||||
"@types/markdown-it": "^12.2.3",
|
||||
"@types/react": "^17.0.24",
|
||||
"@types/react-avatar-editor": "^12.0.0",
|
||||
"@types/react-dom": "^17.0.9",
|
||||
"@types/ua-parser-js": "^0.7.36",
|
||||
"@types/uuid": "^8.3.4",
|
||||
"eslint": "^8.11.0",
|
||||
"npm-run-all": "^4.1.5",
|
||||
"postcss-import": "^14.1.0",
|
||||
"prisma": "^3.13.0",
|
||||
"tailwindcss": "^3.0.24",
|
||||
"typescript": "^4.5.5"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=14"
|
||||
}
|
||||
}
|
||||
Generated
+8390
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,6 @@
|
||||
module.exports = {
|
||||
plugins: {
|
||||
"postcss-import": {},
|
||||
tailwindcss: {},
|
||||
},
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
// This is your Prisma schema file,
|
||||
// learn more about it in the docs: https://pris.ly/d/prisma-schema
|
||||
|
||||
datasource db {
|
||||
provider = "postgresql"
|
||||
url = env("DATABASE_URL")
|
||||
}
|
||||
|
||||
generator client {
|
||||
provider = "prisma-client-js"
|
||||
}
|
||||
|
||||
model User {
|
||||
id String @id @default(uuid())
|
||||
name String
|
||||
username String @unique
|
||||
email String @unique
|
||||
emailVerified DateTime?
|
||||
avatar String?
|
||||
bio String?
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
deletedAt DateTime?
|
||||
memberships Membership[]
|
||||
accessTokens AccessToken[]
|
||||
|
||||
@@map("users")
|
||||
}
|
||||
|
||||
model LoginToken {
|
||||
id String @id @default(uuid())
|
||||
email String
|
||||
expiresAt DateTime
|
||||
|
||||
@@map("login_tokens")
|
||||
}
|
||||
|
||||
model AccessToken {
|
||||
id String @id @default(uuid())
|
||||
createdAt DateTime @default(now())
|
||||
name String
|
||||
token String @unique
|
||||
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||
userId String
|
||||
// Allow to get the access token via publicId in /api/login-complete
|
||||
publicId String? @unique
|
||||
publicIdExpiresAt DateTime?
|
||||
|
||||
@@map("access_tokens")
|
||||
}
|
||||
|
||||
enum MembershipRole {
|
||||
// The creator
|
||||
OWNER
|
||||
// The admins
|
||||
ADMIN
|
||||
// The subscribers
|
||||
SUBSCRIBER
|
||||
}
|
||||
|
||||
model Membership {
|
||||
id String @id @default(uuid())
|
||||
createdAt DateTime @default(now())
|
||||
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||
site Site @relation(fields: [siteId], references: [id], onDelete: Cascade)
|
||||
userId String
|
||||
siteId String
|
||||
role MembershipRole
|
||||
acceptedAt DateTime?
|
||||
lastSwitchedTo DateTime @default(now())
|
||||
config Json @default("{}")
|
||||
|
||||
@@map("memberships")
|
||||
}
|
||||
|
||||
model Site {
|
||||
id String @id @default(uuid())
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
name String
|
||||
icon String?
|
||||
subdomain String @unique
|
||||
pages Page[] @relation(name: "SitePages")
|
||||
domains Domain[] @relation(name: "SiteDomains")
|
||||
primaryDomain Domain? @relation(name: "SitePrimaryDomain", fields: [primaryDomainId], references: [id], onDelete: NoAction, onUpdate: NoAction)
|
||||
primaryDomainId String? @unique
|
||||
description String?
|
||||
twitter String?
|
||||
deletedAt DateTime?
|
||||
memberships Membership[]
|
||||
|
||||
@@map("sites")
|
||||
}
|
||||
|
||||
enum PageType {
|
||||
POST
|
||||
PAGE
|
||||
}
|
||||
|
||||
model Page {
|
||||
id String @id @default(uuid())
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
contentUpdatedAt DateTime @default(now())
|
||||
publishedAt DateTime @default(now())
|
||||
published Boolean @default(false)
|
||||
type PageType @default(POST)
|
||||
title String
|
||||
content String
|
||||
excerpt String
|
||||
format String @default("markdown")
|
||||
slug String
|
||||
site Site @relation(name: "SitePages", fields: [siteId], references: [id], onDelete: Cascade)
|
||||
siteId String
|
||||
deletedAt DateTime?
|
||||
|
||||
@@unique([siteId, slug])
|
||||
@@map("pages")
|
||||
}
|
||||
|
||||
model Domain {
|
||||
id String @id @default(uuid())
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
site Site @relation(name: "SiteDomains", fields: [siteId], references: [id], onDelete: Cascade)
|
||||
siteId String
|
||||
domain String @unique
|
||||
primaryDomainForSite Site? @relation(name: "SitePrimaryDomain")
|
||||
|
||||
@@map("domains")
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 17 KiB |
@@ -0,0 +1,15 @@
|
||||
/**
|
||||
* @type {import('@remix-run/dev').AppConfig}
|
||||
*/
|
||||
module.exports = {
|
||||
serverBuildTarget: "vercel",
|
||||
// When running locally in development mode, we use the built in remix
|
||||
// server. This does not understand the vercel lambda module format,
|
||||
// so we default back to the standard build output.
|
||||
server: process.env.NODE_ENV === "development" ? undefined : "./server.js",
|
||||
ignoredRouteFiles: ["**/.*"],
|
||||
// appDirectory: "app",
|
||||
// assetsBuildDirectory: "public/build",
|
||||
// serverBuildPath: "api/index.js",
|
||||
// publicPath: "/build/",
|
||||
}
|
||||
Vendored
+2
@@ -0,0 +1,2 @@
|
||||
/// <reference types="@remix-run/dev" />
|
||||
/// <reference types="@remix-run/node/globals" />
|
||||
@@ -0,0 +1,4 @@
|
||||
import { createRequestHandler } from "@remix-run/vercel";
|
||||
import * as build from "@remix-run/dev/server-build";
|
||||
|
||||
export default createRequestHandler({ build, mode: process.env.NODE_ENV });
|
||||
@@ -0,0 +1,22 @@
|
||||
module.exports = {
|
||||
content: ["./app/**/*.tsx"],
|
||||
theme: {
|
||||
extend: {
|
||||
boxShadow: {
|
||||
modal: `rgb(0 0 0 / 20%) 0px 0px 1px, rgb(0 0 0 / 20%) 0px 20px 40px`,
|
||||
"card-hover": `rgb(0 0 0 / 5%) 0px 0px 1px, rgb(0 0 0 / 12%) 0px 15px 30px`,
|
||||
card: `rgb(0 0 0 / 5%) 0px 0px 1px, rgb(0 0 0 / 4%) 0px 15px 30px`,
|
||||
button: `0 1.5px 1px var(--shadow-color-button)`,
|
||||
},
|
||||
colors: {
|
||||
border: "var(--border-color)",
|
||||
accent: "var(--accent-color)",
|
||||
},
|
||||
spacing: {
|
||||
sidebar: `240px`,
|
||||
},
|
||||
},
|
||||
},
|
||||
variants: {},
|
||||
plugins: [],
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
{
|
||||
"include": ["remix.env.d.ts", "**/*.ts", "**/*.tsx"],
|
||||
"compilerOptions": {
|
||||
"lib": ["DOM", "DOM.Iterable", "ES2019"],
|
||||
"isolatedModules": true,
|
||||
"esModuleInterop": true,
|
||||
"jsx": "react-jsx",
|
||||
"moduleResolution": "node",
|
||||
"resolveJsonModule": true,
|
||||
"target": "ES2019",
|
||||
"strict": true,
|
||||
"baseUrl": ".",
|
||||
"paths": {
|
||||
"~/*": ["./app/*"]
|
||||
},
|
||||
"noEmit": true,
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"allowJs": true
|
||||
}
|
||||
}
|
||||
Vendored
+23
@@ -0,0 +1,23 @@
|
||||
declare namespace NodeJS {
|
||||
interface ProcessEnv {
|
||||
// Additional environment variables
|
||||
APP_NAME: string
|
||||
DATABASE_URL: string
|
||||
AUTH_COOKIE_NAME: string
|
||||
AUTH_SECRET: string
|
||||
OUR_DOMAIN: string
|
||||
S3_REGION: string
|
||||
S3_ACCESS_KEY_ID: string
|
||||
S3_SECRET_ACCESS_KEY: string
|
||||
S3_BUCKET_NAME: string
|
||||
S3_ENDPOINT?: string
|
||||
MAILGUN_APIKEY: string
|
||||
MAILGUN_DOMAIN: string
|
||||
MAILGUN_EU?: string
|
||||
}
|
||||
}
|
||||
|
||||
declare const ENV: {
|
||||
APP_NAME: string
|
||||
OUR_DOMAIN: string
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"build": {
|
||||
"env": {
|
||||
"ENABLE_FILE_SYSTEM_API": "1"
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user