feat: update the UX for publishing posts

This commit is contained in:
EGOIST
2022-05-19 00:26:02 +08:00
parent c2d18a49b6
commit 4bae50d28e
9 changed files with 234 additions and 100 deletions
+1
View File
@@ -49,6 +49,7 @@
"react-sortablejs": "^6.1.1",
"sortablejs": "^1.15.0",
"ua-parser-js": "^1.0.2",
"use-onclickoutside": "^0.4.0",
"uuid": "^8.3.2",
"zod": "^3.15.1",
"zustand": "4.0.0-rc.1"
+45
View File
@@ -57,6 +57,7 @@ specifiers:
tailwindcss: ^3.0.24
typescript: ^4.5.5
ua-parser-js: ^1.0.2
use-onclickoutside: ^0.4.0
uuid: ^8.3.2
zod: ^3.15.1
zustand: 4.0.0-rc.1
@@ -99,6 +100,7 @@ dependencies:
react-sortablejs: 6.1.1_kjz72dk5lh6hp4ogspefhm7r2u
sortablejs: 1.15.0
ua-parser-js: 1.0.2
use-onclickoutside: 0.4.0_7cpxmzzodpxnolj5zcc5cr63ji
uuid: 8.3.2
zod: 3.15.1
zustand: 4.0.0-rc.1_react@18.1.0
@@ -1014,6 +1016,10 @@ packages:
picomatch: 2.3.1
dev: true
/are-passive-events-supported/1.1.1:
resolution: {integrity: sha512-5wnvlvB/dTbfrCvJ027Y4L4gW/6Mwoy1uFSavney0YO++GU+0e/flnjiBBwH+1kh7xNCgCOGvmJC3s32joYbww==}
dev: false
/arg/5.0.1:
resolution: {integrity: sha512-e0hDa9H2Z9AwFkk2qDlwhoMYE4eToKarchkQHovNdLTCYMHZHeRjI71crOh+dio4K6u1IcwubQqo79Ga4CyAQA==}
dev: true
@@ -3223,6 +3229,45 @@ packages:
resolution: {integrity: sha512-jk1+QP6ZJqyOiuEI9AEWQfju/nB2Pw466kbA0LEZljHwKeMgd9WrAEgEGxjPDD2+TNbbb37rTyhEfrCXfuKXnA==}
dev: false
/use-isomorphic-layout-effect/1.1.2_7cpxmzzodpxnolj5zcc5cr63ji:
resolution: {integrity: sha512-49L8yCO3iGT/ZF9QttjwLF/ZD9Iwto5LnH5LmEdk/6cFmXddqi2ulF0edxTwjj+7mqvpVVGQWvbXZdn32wRSHA==}
peerDependencies:
'@types/react': '*'
react: ^16.8.0 || ^17.0.0 || ^18.0.0
peerDependenciesMeta:
'@types/react':
optional: true
dependencies:
'@types/react': 18.0.9
react: 18.1.0
dev: false
/use-latest/1.2.1_7cpxmzzodpxnolj5zcc5cr63ji:
resolution: {integrity: sha512-xA+AVm/Wlg3e2P/JiItTziwS7FK92LWrDB0p+hgXloIMuVCeJJ8v6f0eeHyPZaJrM+usM1FkFfbNCrJGs8A/zw==}
peerDependencies:
'@types/react': '*'
react: ^16.8.0 || ^17.0.0 || ^18.0.0
peerDependenciesMeta:
'@types/react':
optional: true
dependencies:
'@types/react': 18.0.9
react: 18.1.0
use-isomorphic-layout-effect: 1.1.2_7cpxmzzodpxnolj5zcc5cr63ji
dev: false
/use-onclickoutside/0.4.0_7cpxmzzodpxnolj5zcc5cr63ji:
resolution: {integrity: sha512-lg1U+V8SaCfemgBs5dg+cfEOzjuwVS9ATH0VMLSBHI6R11tbfmiKci1lg6pjwXr1sj95XWd2+5EbffJEAPdkJQ==}
peerDependencies:
react: ^16.8.0 || ^17.0.0
dependencies:
are-passive-events-supported: 1.1.1
react: 18.1.0
use-latest: 1.2.1_7cpxmzzodpxnolj5zcc5cr63ji
transitivePeerDependencies:
- '@types/react'
dev: false
/use-sync-external-store/1.1.0_react@18.1.0:
resolution: {integrity: sha512-SEnieB2FPKEVne66NpXPd1Np4R1lTNKfjuy3XdIoPQKYBAFdzbzSZlSn1KJZUiihQLQC5Znot4SBz1EOTBwQAQ==}
peerDependencies:
@@ -0,0 +1,65 @@
import { useRef, useState } from "react"
import useOnClickOutside from "use-onclickoutside"
import { Button, ButtonGroup } from "../ui/Button"
export const PublishButton: React.FC<{
save: (published: boolean) => void
published: boolean
}> = ({ save, published }) => {
const [showDropdown, setShowDropdown] = useState(false)
const dropdownRef = useRef<HTMLDivElement | null>(null)
const triggerRef = useRef<HTMLButtonElement | null>(null)
useOnClickOutside(dropdownRef, (e) => {
if (triggerRef.current?.contains(e.target as any)) return
setShowDropdown(false)
})
return (
<div className="relative">
<ButtonGroup>
<Button
isAutoWidth
style={{ padding: "0 15px" }}
onClick={() => save(true)}
>
{published ? "Update" : "Publish"}
</Button>
<Button
isAutoWidth
style={{ padding: "0 5px" }}
onClick={() => {
setShowDropdown(!showDropdown)
}}
ref={triggerRef}
>
<svg className="w-7 h-7" viewBox="0 0 24 24">
<path fill="currentColor" d="m7 10l5 5l5-5z"></path>
</svg>
</Button>
</ButtonGroup>
{showDropdown && (
<div className="absolute right-0 min-w-[200px] pt-2" ref={dropdownRef}>
<div className="bg-white py-2 rounded-lg shadow-modal">
{published ? (
<button
className="flex w-full h-8 hover:bg-zinc-100 items-center px-5"
onClick={() => save(false)}
>
Unpublish
</button>
) : (
<button
className="flex w-full h-8 hover:bg-zinc-100 items-center px-5"
onClick={() => save(false)}
>
Save Draft
</button>
)}
</div>
</div>
)}
</div>
)
}
+38 -22
View File
@@ -1,32 +1,47 @@
import React from "react"
import clsx from "clsx"
export const Button: React.FC<
React.ButtonHTMLAttributes<HTMLButtonElement> & {
isLoading?: boolean
isBlock?: boolean
isDisabled?: boolean
variant?: "primary" | "secondary" | "text"
variantColor?: "green" | "red" | "gray"
size?: "sm"
rounded?: "full" | "lg"
}
> = ({
type,
export const ButtonGroup: React.FC<{ children: React.ReactNode }> = ({
children,
className,
isLoading,
isDisabled,
isBlock,
variant,
variantColor,
size,
rounded,
...props
}) => {
return <div className="button-group">{children}</div>
}
type ButtonProps = {
isLoading?: boolean
isBlock?: boolean
isDisabled?: boolean
isAutoWidth?: boolean
variant?: "primary" | "secondary" | "text"
variantColor?: "green" | "red" | "gray"
size?: "sm"
rounded?: "full" | "lg"
}
export const Button = React.forwardRef<
HTMLButtonElement,
React.ButtonHTMLAttributes<HTMLButtonElement> & ButtonProps
>(function Button(
{
type,
children,
className,
isLoading,
isDisabled,
isBlock,
variant,
variantColor,
size,
rounded,
isAutoWidth,
...props
},
ref
) {
return (
<button
{...props}
ref={ref}
type={type || "button"}
disabled={isDisabled}
className={clsx(
@@ -36,6 +51,7 @@ export const Button: React.FC<
isBlock && `is-block`,
variantColor && `is-${variantColor}`,
isDisabled && `is-disabled`,
isAutoWidth && `is-auto-width`,
size && `is-${size}`,
`is-${variant || "primary"}`,
rounded === "full" ? "rounded-full" : "rounded-lg"
@@ -44,4 +60,4 @@ export const Button: React.FC<
{children}
</button>
)
}
})
+5 -1
View File
@@ -9,10 +9,11 @@ type Props = DetailedHTMLProps<
addon?: string
isBlock?: boolean
error?: string
help?: React.ReactNode
}
export const Input = forwardRef<HTMLInputElement, Props>(function Input(
{ label, addon, className, isBlock, error, ...inputProps },
{ label, addon, className, isBlock, error, help, ...inputProps },
ref
) {
const hasAddon = !!addon
@@ -41,6 +42,9 @@ export const Input = forwardRef<HTMLInputElement, Props>(function Input(
)}
</div>
{error && <div className="text-sm mt-1 text-red-500">{error}</div>}
{help && !error && (
<div className="text-xs text-gray-400 mt-1">{help}</div>
)}
</div>
)
})
+16
View File
@@ -26,6 +26,10 @@
@apply transition-colors;
}
.button.is-auto-width {
@apply min-w-[auto];
}
.button.is-loading {
@apply opacity-50;
}
@@ -92,6 +96,18 @@
@apply min-w-[auto];
}
.button-group {
@apply flex items-center;
}
.button-group .button:not(:first-child) {
@apply rounded-l-none;
}
.button-group .button:not(:last-child) {
@apply rounded-r-none;
}
.input {
@apply border;
@apply outline-none;
+6 -4
View File
@@ -5,11 +5,11 @@ import {
prismaRead,
PageType,
MembershipRole,
Page,
} from "~/lib/db.server"
import { type Gate } from "~/lib/gate.server"
import { sendEmailForNewPost } from "~/lib/mailgun.server"
import { getAutoExcerpt, renderPageContent } from "~/lib/markdown.server"
import { checkReservedWords } from "~/lib/reserved-words"
import { notFound } from "~/lib/server-side-props"
import { PageVisibilityEnum } from "~/lib/types"
import { isUUID } from "~/lib/uuid"
@@ -28,8 +28,6 @@ const checkPageSlug = async ({
throw new Error("Missing page slug")
}
checkReservedWords(slug)
const page = await prismaPrimary.page.findFirst({
where: {
siteId,
@@ -269,7 +267,11 @@ export async function getPage(
}
if (!gate.allows({ type: "can-read-page", page })) {
throw gate.permissionError()
if (page.publishedAt > new Date()) {
throw notFound()
} else {
throw gate.permissionError()
}
}
if (input.renderContent) {
+3 -1
View File
@@ -28,12 +28,14 @@ export const getServerSideProps: GetServerSideProps = serverSidePropsHandler(
ssg.fetchQuery("site.subscription", { site: domainOrSubdomain }),
])
const trpcState = ssg.dehydrate()
return {
props: {
isLoggedIn,
domainOrSubdomain,
pageSlug,
trpcState: ssg.dehydrate(),
trpcState,
},
}
}
+55 -72
View File
@@ -1,9 +1,7 @@
import { Popover } from "@headlessui/react"
import clsx from "clsx"
import dayjs from "dayjs"
import { useCallback, useEffect, useState } from "react"
import { DashboardMain } from "~/components/dashboard/DashboardMain"
import { Button } from "~/components/ui/Button"
import { getPageVisibility } from "~/lib/page-helpers"
import { PageVisibilityEnum } from "~/lib/types"
import toast from "react-hot-toast"
@@ -16,6 +14,7 @@ import { useRouter } from "next/router"
import { DashboardLayout } from "~/components/dashboard/DashboardLayout"
import { UniLink } from "~/components/ui/UniLink"
import { useUploadFile } from "~/hooks/useUploadFile"
import { PublishButton } from "~/components/dashboard/PublishButton"
const getInputDatetimeValue = (date: Date | string) => {
const str = dayjs(date).format()
@@ -63,10 +62,20 @@ export default function SubdomainEditor() {
})
}
const savePage = (published: boolean) => {
createOrUpdatePage.mutate({
...values,
siteId: siteResult.data!.id,
pageId: page?.id,
isPost: isPost,
published,
})
}
useEffect(() => {
if (createOrUpdatePage.isSuccess) {
createOrUpdatePage.reset()
toast.success("Updated!")
toast.success(values.published ? "Updated" : "Saved!")
trpcContext.invalidateQueries("site.page")
router.replace(
`/dashboard/${subdomain}/editor?id=${createOrUpdatePage.data.id}&type=${
@@ -74,7 +83,14 @@ export default function SubdomainEditor() {
}`
)
}
}, [createOrUpdatePage, isPost, router, subdomain, trpcContext])
}, [
createOrUpdatePage,
isPost,
router,
subdomain,
trpcContext,
values.published,
])
useEffect(() => {
if (createOrUpdatePage.isError) {
@@ -158,62 +174,7 @@ export default function SubdomainEditor() {
? "Scheduled"
: "Draft"}
</span>
<Popover className="relative">
<Popover.Button className="button is-primary rounded-lg select-none">
Publish
</Popover.Button>
<Popover.Panel className="absolute right-0 z-10 pt-2">
{({ close }) => {
return (
<div className="border p-5 rounded-lg min-w-[240px] bg-white shadow-modal">
<div className="space-y-3">
<label className="block">
<span className="block text-zinc-400 font-medium text-sm">
Publish at
</span>
<input
type="datetime-local"
value={getInputDatetimeValue(values.publishedAt)}
onChange={(e) => {
updateValue("publishedAt", e.target.value)
}}
/>
</label>
<label className="block">
<span className="block text-zinc-400 font-medium text-sm">
Status
</span>
<input
type="checkbox"
checked={values.published}
onChange={(e) =>
updateValue("published", e.target.checked)
}
/>{" "}
{values.published ? "Published" : "Draft"}
</label>
</div>
<div className="mt-5">
<Button
isLoading={createOrUpdatePage.isLoading}
onClick={() => {
createOrUpdatePage.mutate({
...values,
siteId: siteResult.data!.id,
pageId: page?.id,
isPost: isPost,
})
}}
>
{published ? "Update" : "Publish"}
</Button>
</div>
</div>
)
}}
</Popover.Panel>
</Popover>
<PublishButton save={savePage} published={published} />
</div>
</header>
<div className="h-screen pt-14 flex w-full">
@@ -241,7 +202,23 @@ export default function SubdomainEditor() {
</div>
</div>
</div>
<div className="h-full overflow-auto flex-shrink-0 w-[280px] border-l bg-zinc-50 p-5">
<div className="h-full overflow-auto flex-shrink-0 w-[280px] border-l bg-zinc-50 p-5 space-y-5">
<div>
<Input
type="datetime-local"
label="Publish at"
isBlock
name="publishAt"
id="publishAt"
value={getInputDatetimeValue(values.publishedAt)}
onChange={(e) => {
updateValue("publishedAt", e.target.value)
}}
help={`This ${
isPost ? "post" : "page"
} will be accesisble from this time`}
/>
</div>
<div>
<Input
name="slug"
@@ -249,19 +226,25 @@ export default function SubdomainEditor() {
label="Page slug"
id="slug"
isBlock
placeholder="some-slug"
onChange={(e) => updateValue("slug", e.target.value)}
help={
<>
{values.slug && (
<>
This {isPost ? "post" : "page"} will be accessible at{" "}
<UniLink
href={`${getSiteLink({ subdomain })}/${values.slug}`}
className="hover:underline"
>
{getSiteLink({ subdomain, noProtocol: true })}/
{values.slug}
</UniLink>
</>
)}
</>
}
/>
{values.slug && (
<div className="text-xs text-gray-400 mt-1">
This {isPost ? "post" : "page"} will be accessible at{" "}
<UniLink
href={`${getSiteLink({ subdomain })}/${values.slug}`}
className="hover:underline"
>
{getSiteLink({ subdomain, noProtocol: true })}/{values.slug}
</UniLink>
</div>
)}
</div>
</div>
</div>