feat: use RESERVED_TAGS

This commit is contained in:
DIYgod
2023-08-01 20:52:57 +01:00
parent d644b14cf8
commit 338d6b46f6
7 changed files with 442 additions and 10 deletions
@@ -0,0 +1,428 @@
"use client"
import { nanoid } from "nanoid"
import { useParams, useRouter, useSearchParams } from "next/navigation"
import { ChangeEvent, memo, useCallback, useEffect, useState } from "react"
import toast from "react-hot-toast"
import { useQueryClient } from "@tanstack/react-query"
import { DashboardMain } from "~/components/dashboard/DashboardMain"
import { PublishButton } from "~/components/dashboard/PublishButton"
import { Button } from "~/components/ui/Button"
import { FieldLabel } from "~/components/ui/FieldLabel"
import { ImageUploader } from "~/components/ui/ImageUploader"
import { Input } from "~/components/ui/Input"
import { ModalContentProps, useModalStack } from "~/components/ui/ModalStack"
import { UniLink } from "~/components/ui/UniLink"
import {
Values,
initialEditorState,
useEditorState,
} from "~/hooks/useEditorState"
import { useGetState } from "~/hooks/useGetState"
import { useBeforeMounted } from "~/hooks/useSyncOnce"
import { showConfetti } from "~/lib/confetti"
import { CSB_SCAN } from "~/lib/env"
import { getTwitterShareUrl } from "~/lib/helpers"
import { useTranslation } from "~/lib/i18n/client"
import { getPageVisibility } from "~/lib/page-helpers"
import { delStorage, setStorage } from "~/lib/storage"
import { PageVisibilityEnum } from "~/lib/types"
import { cn } from "~/lib/utils"
import {
useCreatePage,
useDeletePage,
useGetPage,
useUpdatePage,
} from "~/queries/page"
import { useGetSite } from "~/queries/site"
export default function PortfolioEditor() {
const router = useRouter()
const queryClient = useQueryClient()
const { t } = useTranslation("dashboard")
const params = useParams()
const subdomain = params?.subdomain as string
const searchParams = useSearchParams()
let pageId = searchParams?.get("id") as string | undefined
const type = "portfolio"
const site = useGetSite(subdomain)
const [draftKey, setDraftKey] = useState<string>("")
useEffect(() => {
if (subdomain) {
let key
if (!pageId) {
const randomId = nanoid()
key = `draft-${site.data?.characterId}-!local-${randomId}`
setDraftKey(key)
queryClient.invalidateQueries([
"getPagesBySite",
site.data?.characterId,
])
router.replace(
`/dashboard/${subdomain}/editor?id=!local-${randomId}&type=${type}`,
)
} else {
key = `draft-${site.data?.characterId}-${pageId}`
}
setDraftKey(key)
}
}, [
subdomain,
pageId,
queryClient,
router,
site.data?.characterId,
searchParams,
])
const page = useGetPage({
characterId: site.data?.characterId,
noteId: pageId && /\d+/.test(pageId) ? +pageId : undefined,
slug: pageId || draftKey.replace(`draft-${site.data?.characterId}-`, ""),
handle: subdomain,
})
const [visibility, setVisibility] = useState<PageVisibilityEnum>()
useEffect(() => {
if (page.isSuccess) {
setVisibility(getPageVisibility(page.data || undefined))
}
}, [page.isSuccess, page.data])
// reset editor state when page changes
useBeforeMounted(() => {
useEditorState.setState({
...initialEditorState,
})
})
const values = useEditorState()
const getValues = useGetState(values)
const getDraftKey = useGetState(draftKey)
const updateValue = useCallback(
<K extends keyof Values>(key: K, value: Values[K]) => {
if (visibility !== PageVisibilityEnum.Draft) {
setVisibility(PageVisibilityEnum.Modified)
}
const values = getValues()
const draftKey = getDraftKey()
const newValues = { ...values, [key]: value }
if (draftKey) {
setStorage(draftKey, {
date: +new Date(),
values: newValues,
type,
})
queryClient.invalidateQueries([
"getPagesBySite",
site.data?.characterId,
])
}
useEditorState.setState(newValues)
},
[type, queryClient, subdomain, visibility],
)
const createPage = useCreatePage()
const updatePage = useUpdatePage()
const savePage = async () => {
const baseValues = {
...values,
characterId: site.data?.characterId,
cover: values.cover,
}
if (visibility === PageVisibilityEnum.Draft) {
createPage.mutate({
...baseValues,
type,
})
} else {
updatePage.mutate({
...baseValues,
noteId: page?.data?.noteId,
})
}
}
const deleteP = useDeletePage()
const deletePage = async () => {
if (page.data) {
if (!page.data?.noteId) {
// Is draft
delStorage(`draft-${page.data.characterId}-${page.data.draftKey}`)
} else {
// Is Note
return deleteP.mutate({
noteId: page.data.noteId,
characterId: page.data.characterId,
})
}
}
}
useEffect(() => {
if (deleteP.isSuccess) {
toast.success(t("Deleted!"))
deleteP.reset()
router.push(`/dashboard/${subdomain}/${type}s`)
}
}, [deleteP.isSuccess])
const { present } = useModalStack()
useEffect(() => {
if (createPage.isSuccess || updatePage.isSuccess) {
if (draftKey) {
delStorage(draftKey)
queryClient.invalidateQueries([
"getPagesBySite",
site.data?.characterId,
])
queryClient.invalidateQueries([
"getPage",
draftKey.replace(`draft-${site.data?.characterId}-`, ""),
])
} else {
queryClient.invalidateQueries(["getPage", pageId])
}
if (createPage.data?.noteId) {
router.replace(
`/dashboard/${subdomain}/editor?id=${createPage.data?.noteId}&type=${type}`,
)
}
const transactionUrl = `${CSB_SCAN}/tx/${
page.data?.updatedTransactionHash || page.data?.transactionHash // TODO
}`
const modalId = "publish-modal"
present({
title: `🎉 ${t("Published!")}`,
id: modalId,
content: (props) => (
<PublishedModal transactionUrl={transactionUrl} {...props} />
),
})
showConfetti()
createPage.reset()
updatePage.reset()
}
}, [createPage.isSuccess, updatePage.isSuccess])
useEffect(() => {
if (createPage.isError || updatePage.isError) {
toast.error("Error: " + (createPage.error || updatePage.error))
createPage.reset()
updatePage.reset()
}
}, [createPage.isError, updatePage.isSuccess])
useEffect(() => {
if (!page.data?.metadata || !draftKey) return
useEditorState.setState({
published: !!page.data.noteId,
title: page.data.metadata?.content?.title || "",
excerpt: page.data.metadata?.content?.summary || "",
cover: page.data.metadata?.content?.attachments?.find(
(attachment) => attachment.name === "cover",
) || {
address: "",
mime_type: "",
},
externalUrl: page.data.metadata?.content?.external_urls?.[0] || "",
})
}, [page.data, subdomain, draftKey, site.data?.characterId])
const discardChanges = useCallback(() => {
if (draftKey) {
delStorage(draftKey)
queryClient.invalidateQueries(["getPagesBySite", site.data?.characterId])
page.remove()
page.refetch()
}
}, [draftKey, site.data?.characterId])
return (
<>
<DashboardMain fullWidth>
<div className="min-w-[270px] max-w-screen-lg flex flex-col space-y-8">
{page.isLoading ? (
<div className="flex justify-center items-center min-h-[300px]">
{t("Loading")}...
</div>
) : (
<>
<div className={`pt-10 flex w-full min-w-[840px] px-5`}>
<EditorExtraProperties updateValue={updateValue} />
</div>
<div
className={`flex justify-between px-5 h-14 items-center text-sm`}
>
<div className="flex items-center space-x-3 flex-shrink-0">
<PublishButton
savePage={savePage}
deletePage={deletePage}
twitterShareUrl={
page.data && site.data
? getTwitterShareUrl({
page: page.data,
site: site.data,
t,
})
: ""
}
published={visibility !== PageVisibilityEnum.Draft}
isSaving={
createPage.isLoading ||
updatePage.isLoading ||
deleteP.isLoading
}
isDisabled={
visibility !== PageVisibilityEnum.Modified &&
visibility !== PageVisibilityEnum.Draft
}
type={type}
isModified={visibility === PageVisibilityEnum.Modified}
discardChanges={discardChanges}
/>
<span
className={cn(
`text-sm capitalize`,
visibility === PageVisibilityEnum.Draft
? `text-zinc-300`
: visibility === PageVisibilityEnum.Modified
? "text-orange-600"
: "text-green-600",
)}
>
{t(visibility as string)}
</span>
</div>
</div>
</>
)}
</div>
</DashboardMain>
</>
)
}
const EditorExtraProperties = memo(
({
updateValue,
}: {
updateValue: <K extends keyof Values>(key: K, value: Values[K]) => void
}) => {
const values = useEditorState()
const { t } = useTranslation("dashboard")
return (
<div className="w-full space-y-5">
<div>
<Input
label={t("External Url") || ""}
isBlock
name="externalUrl"
id="externalUrl"
value={values.externalUrl}
onChange={(e: ChangeEvent<HTMLInputElement>) => {
updateValue("externalUrl", e.target.value)
}}
/>
</div>
<div>
<FieldLabel label={t("Cover Image")} />
<ImageUploader
id="icon"
className="aspect-video rounded-lg w-[480px]"
value={values.cover as any}
hasClose={true}
withMimeType={true}
uploadEnd={(key) => {
const { address, mime_type } = key as {
address?: string
mime_type?: string
}
updateValue("cover", {
address,
mime_type,
})
}}
accept="image/*"
/>
</div>
<div>
<Input
label={t("Title") || ""}
isBlock
name="title"
id="title"
value={values.title}
onChange={(e: ChangeEvent<HTMLInputElement>) => {
updateValue("title", e.target.value)
}}
/>
</div>
<div>
<Input
label={t("Excerpt") || ""}
isBlock
name="excerpt"
id="excerpt"
value={values.excerpt}
multiline
rows={4}
onChange={(e: ChangeEvent<HTMLTextAreaElement>) => {
updateValue("excerpt", e.target.value)
}}
/>
</div>
</div>
)
},
)
EditorExtraProperties.displayName = "EditorExtraProperties"
const PublishedModal = ({
dismiss,
transactionUrl,
}: ModalContentProps<{
transactionUrl: string
}>) => {
const { t } = useTranslation("dashboard")
return (
<>
<div className="p-5">
{t(
"Your post has been securely stored on the blockchain. Now you may want to",
)}
<ul className="list-disc pl-5 mt-2 space-y-1">
<li>
<UniLink className="text-accent" href={transactionUrl}>
{t("View the transaction")}
</UniLink>
</li>
</ul>
</div>
<div className="h-16 border-t flex items-center px-5">
<Button isBlock onClick={() => dismiss()}>
{t("Got it, thanks!")}
</Button>
</div>
</>
)
}
@@ -46,6 +46,7 @@ import { useIsMobileLayout } from "~/hooks/useMobileLayout"
import { useBeforeMounted } from "~/hooks/useSyncOnce"
import { useUploadFile } from "~/hooks/useUploadFile"
import { showConfetti } from "~/lib/confetti"
import { RESERVED_TAGS } from "~/lib/constants"
import { getDefaultSlug } from "~/lib/default-slug"
import { CSB_SCAN } from "~/lib/env"
import { getSiteLink, getTwitterShareUrl } from "~/lib/helpers"
@@ -371,7 +372,7 @@ export default function PostEditor() {
slug: page.data.metadata?.content?.slug || "",
tags:
page.data.metadata?.content?.tags
?.filter((tag) => tag !== "post" && tag !== "page")
?.filter((tag) => !RESERVED_TAGS.includes(tag))
?.join(", ") || "",
content: page.data.metadata?.content?.content || "",
cover: page.data.metadata?.content?.attachments?.find(
+3 -3
View File
@@ -3,6 +3,7 @@ import dynamic from "next/dynamic"
import { useState } from "react"
import { useDate } from "~/hooks/useDate"
import { RESERVED_TAGS } from "~/lib/constants"
import { useTranslation } from "~/lib/i18n/client"
const DynamicPageContent = dynamic(() => import("../common/PageContent"), {
@@ -26,11 +27,10 @@ export const ImportPreview = ({ note }: { note: NoteMetadata }) => {
>
{date.formatDate(note.date_published!, undefined)}
</time>
{!!note.tags?.filter((tag) => tag !== "post" && tag !== "page")
.length && (
{!!note.tags?.filter((tag) => !RESERVED_TAGS.includes(tag)).length && (
<span className="xlog-post-tags space-x-1 truncate min-w-0">
{note.tags
?.filter((tag) => tag !== "post" && tag !== "page")
?.filter((tag) => !RESERVED_TAGS.includes(tag))
.map((tag) => (
<span className="hover:text-zinc-600" key={tag}>
#{tag}
+3 -2
View File
@@ -3,6 +3,7 @@ import { BlockchainIcon } from "~/components/icons/BlockchainIcon"
import { EditButton } from "~/components/site/EditButton"
import PostTag from "~/components/site/PostTag"
import { UniLink } from "~/components/ui/UniLink"
import { RESERVED_TAGS } from "~/lib/constants"
import { CSB_SCAN } from "~/lib/env"
import { ExpandedCharacter, ExpandedNote, NoteType } from "~/lib/types"
@@ -24,12 +25,12 @@ export default function PostMeta({
<div className="text-zinc-400 mt-5 space-x-5 flex items-center justify-center">
<Time isoString={page?.metadata?.content?.date_published} />
{page.metadata?.content?.tags?.filter(
(tag) => tag !== "post" && tag !== "page",
(tag) => !RESERVED_TAGS.includes(tag),
).length ? (
<>
<span className="xlog-post-tags space-x-1 truncate min-w-0">
{page.metadata?.content?.tags
?.filter((tag) => tag !== "post" && tag !== "page")
?.filter((tag) => !RESERVED_TAGS.includes(tag))
.map((tag) => <PostTag key={tag} tag={tag} />)}
</span>
</>
+2 -1
View File
@@ -6,6 +6,7 @@ import { useMemo } from "react"
import { Button } from "~/components/ui/Button"
import { useDate } from "~/hooks/useDate"
import { RESERVED_TAGS } from "~/lib/constants"
import { getSiteRelativeUrl } from "~/lib/helpers"
import { useTranslation } from "~/lib/i18n/client"
import { ExpandedNote, PageVisibilityEnum } from "~/lib/types"
@@ -63,7 +64,7 @@ export const SiteArchives = () => {
for (const page of posts.data.pages) {
for (const post of page.list) {
post.metadata?.content?.tags?.forEach((tag) => {
if (tag !== "post" && tag !== "page") {
if (!RESERVED_TAGS.includes(tag)) {
if (result.has(tag)) {
result.set(tag, result.get(tag) + 1)
} else {
+2
View File
@@ -17,3 +17,5 @@ export const COLOR_SCHEME_DARK = "dark"
export const COLOR_SCHEME_LIGHT = "light"
export const DEFAULT_COLOR_SCHEME: ColorScheme = "light"
export const DARK_MODE_STORAGE_KEY = "darkMode"
export const RESERVED_TAGS = ["page", "post", "portfolio", "comment"]
+2 -3
View File
@@ -13,6 +13,7 @@ import { indexer } from "@crossbell/indexer"
import { extractCharacterAttribute } from "@crossbell/util-metadata"
import { gql } from "@urql/core"
import { RESERVED_TAGS } from "~/lib/constants"
import { expandCrossbellNote } from "~/lib/expand-unit"
import { filterCommentCharacter } from "~/lib/filter-character"
import { getNoteSlug } from "~/lib/helpers"
@@ -736,9 +737,7 @@ export const getDistinctNoteTagsOfCharacter = async (characterId: number) => {
const result = await indexer.note.getDistinctTagsOfCharacter(characterId, {
sources: "xlog",
})
result.list = result.list.filter(
(tag) => ["post", "comment", "page"].findIndex((t) => t === tag) === -1,
)
result.list = result.list.filter((tag) => !RESERVED_TAGS.includes(tag))
return result
}