diff --git a/src/app/dashboard/[subdomain]/achievements/page-component.tsx b/src/app/dashboard/[subdomain]/achievements/page-component.tsx new file mode 100644 index 00000000..99695f4d --- /dev/null +++ b/src/app/dashboard/[subdomain]/achievements/page-component.tsx @@ -0,0 +1,49 @@ +"use client" + +import { useParams } from "next/navigation" + +import { AchievementItem } from "~/components/common/AchievementItem" +import { DashboardMain } from "~/components/dashboard/DashboardMain" +import { useGetAchievements, useGetSite } from "~/queries/site" + +export default function AchievementsPage() { + const params = useParams() + const subdomain = params?.subdomain as string + const site = useGetSite(subdomain) + + const achievement = useGetAchievements(site.data?.characterId) + + return ( + +
+ <> + {achievement.data?.list?.map((series) => { + let length = series.groups?.length + if (!length) { + return null + } + return ( +
+
+ {series.info.title} +
+
+ {series.groups?.map((group) => ( + + ))} +
+
+ ) + })} + +
+
+ ) +} diff --git a/src/app/dashboard/[subdomain]/achievements/page.tsx b/src/app/dashboard/[subdomain]/achievements/page.tsx index 99695f4d..4c3a7717 100644 --- a/src/app/dashboard/[subdomain]/achievements/page.tsx +++ b/src/app/dashboard/[subdomain]/achievements/page.tsx @@ -1,49 +1,5 @@ -"use client" - -import { useParams } from "next/navigation" - -import { AchievementItem } from "~/components/common/AchievementItem" -import { DashboardMain } from "~/components/dashboard/DashboardMain" -import { useGetAchievements, useGetSite } from "~/queries/site" +import PageComponent from "./page-component" export default function AchievementsPage() { - const params = useParams() - const subdomain = params?.subdomain as string - const site = useGetSite(subdomain) - - const achievement = useGetAchievements(site.data?.characterId) - - return ( - -
- <> - {achievement.data?.list?.map((series) => { - let length = series.groups?.length - if (!length) { - return null - } - return ( -
-
- {series.info.title} -
-
- {series.groups?.map((group) => ( - - ))} -
-
- ) - })} - -
-
- ) + return } diff --git a/src/app/dashboard/[subdomain]/comments/page-component.tsx b/src/app/dashboard/[subdomain]/comments/page-component.tsx new file mode 100644 index 00000000..4df79fc1 --- /dev/null +++ b/src/app/dashboard/[subdomain]/comments/page-component.tsx @@ -0,0 +1,150 @@ +"use client" + +import { useParams } from "next/navigation" +import { useEffect } from "react" +import { Virtuoso } from "react-virtuoso" + +import { CommentItem } from "~/components/common/CommentItem" +import { DashboardMain } from "~/components/dashboard/DashboardMain" +import { UniLink } from "~/components/ui/UniLink" +import { getSiteLink } from "~/lib/helpers" +import { Trans, useTranslation } from "~/lib/i18n/client" +import { useGetCommentsBySite, useGetSite } from "~/queries/site" + +export default function CommentsPage() { + const params = useParams() + const subdomain = params?.subdomain as string + const { t, i18n } = useTranslation("dashboard") + + const site = useGetSite(subdomain) + + const comments = useGetCommentsBySite({ + characterId: site.data?.characterId, + }) + + // fetch next page when we get a empty list + useEffect(() => { + if ( + comments.data?.pages && + comments.data.pages.at(-1)?.list.length === 0 && + comments.hasNextPage + ) { + comments.fetchNextPage() + } + }, [comments.data, comments.hasNextPage, comments.fetchNextPage]) + + const data = comments.data?.pages.filter((page) => page.list.length > 0) + + const feedUrl = + getSiteLink({ + subdomain: subdomain, + }) + "/feed/comments" + + return ( + +
+
+

+ {t( + "You can subscribe to comments through an RSS reader to receive timely reminders.", + )} +

+

+ {t("Subscription address:")}{" "} + + {feedUrl} + +

+
+
+
+ + comments.hasNextPage && comments.fetchNextPage() + } + components={{ + Footer: comments.isLoading ? Loader : undefined, + }} + itemContent={(_, p) => + p?.list?.map((comment, idx) => { + const type = comment.toNote?.metadata?.content?.tags?.[0] + let toTitle + if (type === "post" || type === "page") { + toTitle = comment.toNote?.metadata?.content?.title + } else { + if ( + (comment.toNote?.metadata?.content?.content?.length || + 0) > 30 + ) { + toTitle = + comment.toNote?.metadata?.content?.content?.slice( + 0, + 30, + ) + "..." + } else { + toTitle = comment.toNote?.metadata?.content?.content + } + } + const name = + comment?.character?.metadata?.content?.name || + `@${comment?.character?.handle}` + + return ( +
+
+ {name}{" "} + + . + + ), + }} + ns="dashboard" + /> + : +
+ +
+ ) + }) + } + >
+
+
+
+
+ ) +} + +const Loader = () => { + const { t } = useTranslation("common") + return ( +
+ {t("Loading")}... +
+ ) +} diff --git a/src/app/dashboard/[subdomain]/comments/page.tsx b/src/app/dashboard/[subdomain]/comments/page.tsx index 4df79fc1..7a2cce15 100644 --- a/src/app/dashboard/[subdomain]/comments/page.tsx +++ b/src/app/dashboard/[subdomain]/comments/page.tsx @@ -1,150 +1,5 @@ -"use client" - -import { useParams } from "next/navigation" -import { useEffect } from "react" -import { Virtuoso } from "react-virtuoso" - -import { CommentItem } from "~/components/common/CommentItem" -import { DashboardMain } from "~/components/dashboard/DashboardMain" -import { UniLink } from "~/components/ui/UniLink" -import { getSiteLink } from "~/lib/helpers" -import { Trans, useTranslation } from "~/lib/i18n/client" -import { useGetCommentsBySite, useGetSite } from "~/queries/site" +import PageComponent from "./page-component" export default function CommentsPage() { - const params = useParams() - const subdomain = params?.subdomain as string - const { t, i18n } = useTranslation("dashboard") - - const site = useGetSite(subdomain) - - const comments = useGetCommentsBySite({ - characterId: site.data?.characterId, - }) - - // fetch next page when we get a empty list - useEffect(() => { - if ( - comments.data?.pages && - comments.data.pages.at(-1)?.list.length === 0 && - comments.hasNextPage - ) { - comments.fetchNextPage() - } - }, [comments.data, comments.hasNextPage, comments.fetchNextPage]) - - const data = comments.data?.pages.filter((page) => page.list.length > 0) - - const feedUrl = - getSiteLink({ - subdomain: subdomain, - }) + "/feed/comments" - - return ( - -
-
-

- {t( - "You can subscribe to comments through an RSS reader to receive timely reminders.", - )} -

-

- {t("Subscription address:")}{" "} - - {feedUrl} - -

-
-
-
- - comments.hasNextPage && comments.fetchNextPage() - } - components={{ - Footer: comments.isLoading ? Loader : undefined, - }} - itemContent={(_, p) => - p?.list?.map((comment, idx) => { - const type = comment.toNote?.metadata?.content?.tags?.[0] - let toTitle - if (type === "post" || type === "page") { - toTitle = comment.toNote?.metadata?.content?.title - } else { - if ( - (comment.toNote?.metadata?.content?.content?.length || - 0) > 30 - ) { - toTitle = - comment.toNote?.metadata?.content?.content?.slice( - 0, - 30, - ) + "..." - } else { - toTitle = comment.toNote?.metadata?.content?.content - } - } - const name = - comment?.character?.metadata?.content?.name || - `@${comment?.character?.handle}` - - return ( -
-
- {name}{" "} - - . - - ), - }} - ns="dashboard" - /> - : -
- -
- ) - }) - } - >
-
-
-
-
- ) -} - -const Loader = () => { - const { t } = useTranslation("common") - return ( -
- {t("Loading")}... -
- ) + return } diff --git a/src/app/dashboard/[subdomain]/editor/page-component.tsx b/src/app/dashboard/[subdomain]/editor/page-component.tsx new file mode 100644 index 00000000..18b52d18 --- /dev/null +++ b/src/app/dashboard/[subdomain]/editor/page-component.tsx @@ -0,0 +1,982 @@ +"use client" + +import { useDebounceEffect } from "ahooks" +import type { Root } from "mdast" +import { nanoid } from "nanoid" +import dynamic from "next/dynamic" +import { useParams, useRouter, useSearchParams } from "next/navigation" +import { + ChangeEvent, + memo, + useCallback, + useEffect, + useMemo, + useRef, + useState, +} from "react" +import toast from "react-hot-toast" +import { shallow } from "zustand/shallow" + +import type { EditorView } from "@codemirror/view" +import { DateInput } from "@mantine/dates" +import { useQueryClient } from "@tanstack/react-query" + +import { DashboardMain } from "~/components/dashboard/DashboardMain" +import { OptionsButton } from "~/components/dashboard/OptionsButton" +import { PublishButton } from "~/components/dashboard/PublishButton" +import { Button } from "~/components/ui/Button" +import { CodeMirrorEditor } from "~/components/ui/CodeMirror" +import { EditorToolbar } from "~/components/ui/EditorToolbar" +import { FieldLabel } from "~/components/ui/FieldLabel" +import { ImageUploader } from "~/components/ui/ImageUploader" +import { Input } from "~/components/ui/Input" +import { Modal } from "~/components/ui/Modal" +import { Switch } from "~/components/ui/Switch" +import { TagInput } from "~/components/ui/TagInput" +import { UniLink } from "~/components/ui/UniLink" +import { toolbarShortcuts, toolbars } from "~/editor" +import { editorUpload } from "~/editor/Multimedia" +import { + Values, + initialEditorState, + useEditorState, +} from "~/hooks/useEdtiorState" +import { useGetState } from "~/hooks/useGetState" +import { useIsMobileLayout } from "~/hooks/useMobileLayout" +import { useBeforeMounted } from "~/hooks/useSyncOnce" +import { useUploadFile } from "~/hooks/useUploadFile" +import { showConfetti } from "~/lib/confetti" +import { getDefaultSlug } from "~/lib/default-slug" +import { CSB_SCAN } from "~/lib/env" +import { getSiteLink, 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, pick } from "~/lib/utils" +import { Rendered, renderPageContent } from "~/markdown" +import { checkPageSlug } from "~/models/page.model" +import { + useCreatePage, + useDeletePage, + useGetDistinctNoteTagsOfCharacter, + useGetPage, + useUpdatePage, +} from "~/queries/page" +import { useGetSite } from "~/queries/site" + +const DynamicPageContent = dynamic( + () => import("~/components/common/PageContent"), + { + ssr: false, + }, +) + +export default function SubdomainEditor() { + 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 isPost = searchParams?.get("type") === "post" + + const site = useGetSite(subdomain) + + const [draftKey, setDraftKey] = useState("") + 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=${searchParams?.get( + "type", + )}`, + ) + } else { + key = `draft-${site.data?.characterId}-${pageId}` + } + setDraftKey(key) + setDefaultSlug( + key + .replace(`draft-${site.data?.characterId}-local-`, "") + .replace(`draft-${site.data?.characterId}-`, ""), + ) + } + }, [ + 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 userTags = useGetDistinctNoteTagsOfCharacter(site.data?.characterId) + + const [visibility, setVisibility] = useState() + + useEffect(() => { + if (page.isSuccess) { + setVisibility(getPageVisibility(page.data || undefined)) + } + }, [page.isSuccess, page.data]) + + const uploadFile = useUploadFile() + + // reset editor state when page changes + useBeforeMounted(() => { + useEditorState.setState(initialEditorState) + }) + + const values = useEditorState() + + const [initialContent, setInitialContent] = useState("") + const [defaultSlug, setDefaultSlug] = useState("") + + const getValues = useGetState(values) + const getDraftKey = useGetState(draftKey) + + const updateValue = useCallback( + (key: K, value: Values[K]) => { + if (visibility !== PageVisibilityEnum.Draft) { + setVisibility(PageVisibilityEnum.Modified) + } + + const values = getValues() + const draftKey = getDraftKey() + if (key === "title") { + setDefaultSlug( + getDefaultSlug( + value as string, + draftKey.replace(`draft-${site.data?.characterId}-`, ""), + ), + ) + } + if (key === "slug" && !/^[a-zA-Z0-9\-_]*$/.test(value as string)) { + // Replace all invalid chars + ;(value as string) = (value as string).replace(/[^\w\-]/g, "-") + toast.error( + t( + "Slug can only contain letters, numbers, hyphens, and underscores.", + ), + ) + } + const newValues = { ...values, [key]: value } + if (draftKey) { + setStorage(draftKey, { + date: +new Date(), + values: newValues, + isPost: isPost, + }) + queryClient.invalidateQueries([ + "getPagesBySite", + site.data?.characterId, + ]) + } + useEditorState.setState(newValues) + }, + [isPost, queryClient, subdomain, visibility], + ) + + const createPage = useCreatePage() + const updatePage = useUpdatePage() + + const isMobileLayout = useIsMobileLayout() + const [isRendering, setIsRendering] = useState(!isMobileLayout) + + const savePage = async () => { + const check = await checkPageSlug({ + slug: values.slug || defaultSlug, + characterId: site.data?.characterId, + noteId: page?.data?.noteId, + }) + if (check) { + toast.error(check) + } else { + const uniqueTags = Array.from(new Set(values.tags.split(","))).join(",") + + const baseValues = { + ...values, + tags: uniqueTags, + slug: values.slug || defaultSlug, + characterId: site.data?.characterId, + cover: values.cover, + disableAISummary: values.disableAISummary, + } + if (visibility === PageVisibilityEnum.Draft) { + createPage.mutate({ + ...baseValues, + isPost: isPost, + }) + } 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}/${searchParams?.get("type")}s`) + } + }, [deleteP.isSuccess]) + + const [isCheersOpen, setIsCheersOpen] = useState(false) + + 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=${searchParams?.get("type")}`, + ) + } + + setIsCheersOpen(true) + 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 || !draftKey) return + setInitialContent(page.data.metadata?.content?.content || "") + useEditorState.setState({ + title: page.data.metadata?.content?.title || "", + publishedAt: page.data.metadata?.content?.date_published, + published: !!page.data.noteId, + excerpt: page.data.metadata?.content?.summary || "", + slug: page.data.metadata?.content?.slug || "", + tags: + page.data.metadata?.content?.tags + ?.filter((tag) => tag !== "post" && tag !== "page") + ?.join(", ") || "", + content: page.data.metadata?.content?.content || "", + cover: page.data.metadata?.content?.attachments?.find( + (attachment) => attachment.name === "cover", + ) || { + address: "", + mime_type: "", + }, + disableAISummary: page.data.metadata?.content?.disableAISummary, + }) + setDefaultSlug( + getDefaultSlug( + page.data.metadata?.content?.title || "", + draftKey.replace(`draft-${site.data?.characterId}-`, ""), + ), + ) + }, [page.data, subdomain, draftKey, site.data?.characterId]) + + const [currentScrollArea, setCurrentScrollArea] = useState("") + const [view, setView] = useState() + const [tree, setTree] = useState() + + // preview + + const [parsedContent, setParsedContent] = useState() + + useDebounceEffect( + () => { + const result = renderPageContent(values.content) + setTree(result.tree) + setParsedContent(result) + }, + [values.content], + { + wait: 500, + }, + ) + + const previewRef = useRef(null) + + // editor + const onCreateEditor = useCallback( + (view: EditorView) => { + setView?.(view) + }, + [setView], + ) + + const onChange = useCallback( + (value: string) => { + updateValue("content", value) + }, + [updateValue], + ) + + const handleDropFile = useCallback( + async (file: File) => { + if (view) { + editorUpload(file, view) + } + }, + [uploadFile, view], + ) + + const computedPosition = useCallback(() => { + let previewChildNodes = previewRef.current?.childNodes[0]?.childNodes + const editorElementList: number[] = [] + const previewElementList: number[] = [] + if (view?.state && previewChildNodes) { + tree?.children.forEach((child, index) => { + if ( + child.position && + previewChildNodes?.[index] && + (child as any).tagName !== "style" + ) { + if (child.position.start.line > view.state.doc.lines) return + const line = view.state?.doc.line(child.position.start.line) + const block = view.lineBlockAt(line.from) + if (block) { + editorElementList.push(block.top) + previewElementList.push( + (previewChildNodes[index] as HTMLElement).offsetTop, + ) + } + } + }) + } + return { + editorElementList, + previewElementList, + } + }, [view, tree]) + + const onScroll = useCallback( + (scrollTop: number, area: string) => { + if ( + currentScrollArea === area && + previewRef.current?.parentElement && + view + ) { + const position = computedPosition() + + let selfElement + let selfPosition + let targetElement + let targetPosition + if (area === "preview") { + selfElement = previewRef.current.parentElement + selfPosition = position.previewElementList + targetElement = view.scrollDOM + targetPosition = position.editorElementList + } else { + selfElement = view.scrollDOM + selfPosition = position.editorElementList + targetElement = previewRef.current.parentElement + targetPosition = position.previewElementList + } + + let scrollElementIndex = 0 + for (let i = 0; i < selfPosition.length; i++) { + if (scrollTop < selfPosition[i]) { + scrollElementIndex = i - 1 + break + } + } + + // scroll to bottom + if (scrollTop >= selfElement.scrollHeight - selfElement.clientHeight) { + targetElement.scrollTop = + targetElement.scrollHeight - targetElement.clientHeight + return + } + + // scroll to position + if (scrollElementIndex >= 0) { + let ratio = + (scrollTop - selfPosition[scrollElementIndex]) / + (selfPosition[scrollElementIndex + 1] - + selfPosition[scrollElementIndex]) + targetElement.scrollTop = + ratio * + (targetPosition[scrollElementIndex + 1] - + targetPosition[scrollElementIndex]) + + targetPosition[scrollElementIndex] + } + } + }, + [view, computedPosition, currentScrollArea], + ) + + const onEditorScroll = useCallback( + (scrollTop: number) => { + onScroll(scrollTop, "editor") + }, + [onScroll], + ) + + const onPreviewScroll = useCallback( + (scrollTop: number) => { + onScroll(scrollTop, "preview") + }, + [onScroll], + ) + + const onPreviewButtonClick = useCallback(() => { + window.open( + `/site/${subdomain}/preview/${draftKey.replace( + `draft-${site.data?.characterId}-`, + "", + )}`, + ) + }, [draftKey, subdomain, site.data?.characterId]) + + const [isAdvancedOptionsOpen, setIsAdvancedOptionsOpen] = + useState(false) + + const extraProperties = ( + setIsAdvancedOptionsOpen(true)} + /> + ) + + const discardChanges = useCallback(() => { + if (draftKey) { + delStorage(draftKey) + queryClient.invalidateQueries(["getPagesBySite", site.data?.characterId]) + page.remove() + page.refetch() + } + }, [draftKey, site.data?.characterId]) + + const cmStyle = useMemo( + () => ({ + ".cm-scroller": { + padding: "0 1.25rem", + }, + ".cm-content": { + paddingBottom: "600px", + }, + }), + [], + ) + + return ( + <> + + {page.isLoading ? ( +
+ {t("Loading")}... +
+ ) : ( + <> +
+
+ +
+ {isMobileLayout ? ( +
+ +
+ ) : ( +
+ + {t(visibility as string)} + + + +
+ )} +
+
+
+
+ { + if (e.key === "Enter" && !e.nativeEvent.isComposing) { + view?.focus() + } + }} + onChange={(e) => updateValue("title", e.target.value)} + className="h-12 ml-1 inline-flex items-center border-none text-3xl font-bold w-full focus:outline-none bg-white" + placeholder={t("Title goes here...") || ""} + /> +
+
+ {!(isMobileLayout && isRendering) && ( + { + setCurrentScrollArea("editor") + }} + className={cn( + "h-full flex-1", + isRendering ? "border-r" : "", + )} + shortcuts={toolbarShortcuts} + /> + )} + {!isMobileLayout && ( +
+
setIsRendering(!isRendering)} + > + {isRendering ? ( + + ) : ( + + )} +
+
+ )} + {isRendering && ( + { + setCurrentScrollArea("preview") + }} + /> + )} +
+
+ {!isMobileLayout && ( + setIsAdvancedOptionsOpen(true)} + /> + )} +
+ + )} +
+ + +
+ {t( + "Your post has been securely stored on the blockchain. Now you may want to", + )} +
    +
  • + + {t("View the post")} + +
  • +
  • + + {t("View the transaction")} + +
  • +
  • + + {t("Share to Twitter")} + +
  • +
+
+
+ +
+
+ + ) +} + +const EditorExtraProperties = memo( + ({ + isPost, + updateValue, + subdomain, + defaultSlug, + userTags, + openAdvancedOptions, + }: { + updateValue: (key: K, value: Values[K]) => void + isPost: boolean + + subdomain: string + defaultSlug: string + userTags: string[] + + openAdvancedOptions: () => void + }) => { + const values = useEditorState( + (state) => + pick(state, ["publishedAt", "slug", "excerpt", "tags", "cover"]), + shallow, + ) + const { t } = useTranslation("dashboard") + const site = useGetSite(subdomain) + + return ( +
+
+ + { + if (value) { + updateValue("publishedAt", value.toISOString()) + } else { + updateValue("publishedAt", "") + } + }} + styles={{ + input: { + borderRadius: "0.5rem", + borderColor: "var(--border-color)", + height: "2.5rem", + "&:focus-within": { + borderColor: "var(--theme-color)", + }, + }, + }} + /> +
+ {t( + `This ${ + isPost ? "post" : "page" + } will be accessible from this time. Leave blank to use the current time.`, + )} +
+ {values.publishedAt > new Date().toISOString() && ( +
+ {t( + "The post is currently not public as its publication date has been scheduled for a future time.", + )} +
+ )} +
+
+ ) => + updateValue("slug", e.target.value) + } + help={ + <> + {(values.slug || defaultSlug) && ( + <> + {t( + `This ${isPost ? "post" : "page"} will be accessible at`, + )}{" "} + + {getSiteLink({ + subdomain, + domain: site.data?.metadata?.content?.custom_domain, + noProtocol: true, + })} + /{encodeURIComponent(values.slug || defaultSlug)} + + + )} + + } + /> +
+
+ ( + updateValue("tags", value)} + /> + )} + /> +
+
+ ) => { + updateValue("excerpt", e.target.value) + }} + help={t("Leave it blank to use auto-generated excerpt")} + /> +
+
+ + { + const { address, mime_type } = key as { + address?: string + mime_type?: string + } + updateValue("cover", { + address, + mime_type, + }) + }} + accept="image/*" + /> +
+ {t("Leave blank to use the first image in the post")} +
+
+
+ +
+
+ ) + }, +) + +EditorExtraProperties.displayName = "EditorExtraProperties" + +const EditorAdvancedOptions = memo( + ({ + updateValue, + isAdvancedOptionsOpen, + setIsAdvancedOptionsOpen, + }: { + updateValue: (key: K, value: Values[K]) => void + + isAdvancedOptionsOpen: boolean + setIsAdvancedOptionsOpen: (state: boolean) => void + }) => { + const values = useEditorState( + (state) => pick(state, ["disableAISummary"]), + shallow, + ) + const { t } = useTranslation("dashboard") + + return ( + +
+
+ updateValue("disableAISummary", state)} + /> +
+
+
+ ) + }, +) + +EditorAdvancedOptions.displayName = "EditorAdvancedOptions" diff --git a/src/app/dashboard/[subdomain]/editor/page.tsx b/src/app/dashboard/[subdomain]/editor/page.tsx index 18b52d18..79834a29 100644 --- a/src/app/dashboard/[subdomain]/editor/page.tsx +++ b/src/app/dashboard/[subdomain]/editor/page.tsx @@ -1,982 +1,5 @@ -"use client" - -import { useDebounceEffect } from "ahooks" -import type { Root } from "mdast" -import { nanoid } from "nanoid" -import dynamic from "next/dynamic" -import { useParams, useRouter, useSearchParams } from "next/navigation" -import { - ChangeEvent, - memo, - useCallback, - useEffect, - useMemo, - useRef, - useState, -} from "react" -import toast from "react-hot-toast" -import { shallow } from "zustand/shallow" - -import type { EditorView } from "@codemirror/view" -import { DateInput } from "@mantine/dates" -import { useQueryClient } from "@tanstack/react-query" - -import { DashboardMain } from "~/components/dashboard/DashboardMain" -import { OptionsButton } from "~/components/dashboard/OptionsButton" -import { PublishButton } from "~/components/dashboard/PublishButton" -import { Button } from "~/components/ui/Button" -import { CodeMirrorEditor } from "~/components/ui/CodeMirror" -import { EditorToolbar } from "~/components/ui/EditorToolbar" -import { FieldLabel } from "~/components/ui/FieldLabel" -import { ImageUploader } from "~/components/ui/ImageUploader" -import { Input } from "~/components/ui/Input" -import { Modal } from "~/components/ui/Modal" -import { Switch } from "~/components/ui/Switch" -import { TagInput } from "~/components/ui/TagInput" -import { UniLink } from "~/components/ui/UniLink" -import { toolbarShortcuts, toolbars } from "~/editor" -import { editorUpload } from "~/editor/Multimedia" -import { - Values, - initialEditorState, - useEditorState, -} from "~/hooks/useEdtiorState" -import { useGetState } from "~/hooks/useGetState" -import { useIsMobileLayout } from "~/hooks/useMobileLayout" -import { useBeforeMounted } from "~/hooks/useSyncOnce" -import { useUploadFile } from "~/hooks/useUploadFile" -import { showConfetti } from "~/lib/confetti" -import { getDefaultSlug } from "~/lib/default-slug" -import { CSB_SCAN } from "~/lib/env" -import { getSiteLink, 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, pick } from "~/lib/utils" -import { Rendered, renderPageContent } from "~/markdown" -import { checkPageSlug } from "~/models/page.model" -import { - useCreatePage, - useDeletePage, - useGetDistinctNoteTagsOfCharacter, - useGetPage, - useUpdatePage, -} from "~/queries/page" -import { useGetSite } from "~/queries/site" - -const DynamicPageContent = dynamic( - () => import("~/components/common/PageContent"), - { - ssr: false, - }, -) +import PageComponent from "./page-component" export default function SubdomainEditor() { - 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 isPost = searchParams?.get("type") === "post" - - const site = useGetSite(subdomain) - - const [draftKey, setDraftKey] = useState("") - 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=${searchParams?.get( - "type", - )}`, - ) - } else { - key = `draft-${site.data?.characterId}-${pageId}` - } - setDraftKey(key) - setDefaultSlug( - key - .replace(`draft-${site.data?.characterId}-local-`, "") - .replace(`draft-${site.data?.characterId}-`, ""), - ) - } - }, [ - 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 userTags = useGetDistinctNoteTagsOfCharacter(site.data?.characterId) - - const [visibility, setVisibility] = useState() - - useEffect(() => { - if (page.isSuccess) { - setVisibility(getPageVisibility(page.data || undefined)) - } - }, [page.isSuccess, page.data]) - - const uploadFile = useUploadFile() - - // reset editor state when page changes - useBeforeMounted(() => { - useEditorState.setState(initialEditorState) - }) - - const values = useEditorState() - - const [initialContent, setInitialContent] = useState("") - const [defaultSlug, setDefaultSlug] = useState("") - - const getValues = useGetState(values) - const getDraftKey = useGetState(draftKey) - - const updateValue = useCallback( - (key: K, value: Values[K]) => { - if (visibility !== PageVisibilityEnum.Draft) { - setVisibility(PageVisibilityEnum.Modified) - } - - const values = getValues() - const draftKey = getDraftKey() - if (key === "title") { - setDefaultSlug( - getDefaultSlug( - value as string, - draftKey.replace(`draft-${site.data?.characterId}-`, ""), - ), - ) - } - if (key === "slug" && !/^[a-zA-Z0-9\-_]*$/.test(value as string)) { - // Replace all invalid chars - ;(value as string) = (value as string).replace(/[^\w\-]/g, "-") - toast.error( - t( - "Slug can only contain letters, numbers, hyphens, and underscores.", - ), - ) - } - const newValues = { ...values, [key]: value } - if (draftKey) { - setStorage(draftKey, { - date: +new Date(), - values: newValues, - isPost: isPost, - }) - queryClient.invalidateQueries([ - "getPagesBySite", - site.data?.characterId, - ]) - } - useEditorState.setState(newValues) - }, - [isPost, queryClient, subdomain, visibility], - ) - - const createPage = useCreatePage() - const updatePage = useUpdatePage() - - const isMobileLayout = useIsMobileLayout() - const [isRendering, setIsRendering] = useState(!isMobileLayout) - - const savePage = async () => { - const check = await checkPageSlug({ - slug: values.slug || defaultSlug, - characterId: site.data?.characterId, - noteId: page?.data?.noteId, - }) - if (check) { - toast.error(check) - } else { - const uniqueTags = Array.from(new Set(values.tags.split(","))).join(",") - - const baseValues = { - ...values, - tags: uniqueTags, - slug: values.slug || defaultSlug, - characterId: site.data?.characterId, - cover: values.cover, - disableAISummary: values.disableAISummary, - } - if (visibility === PageVisibilityEnum.Draft) { - createPage.mutate({ - ...baseValues, - isPost: isPost, - }) - } 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}/${searchParams?.get("type")}s`) - } - }, [deleteP.isSuccess]) - - const [isCheersOpen, setIsCheersOpen] = useState(false) - - 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=${searchParams?.get("type")}`, - ) - } - - setIsCheersOpen(true) - 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 || !draftKey) return - setInitialContent(page.data.metadata?.content?.content || "") - useEditorState.setState({ - title: page.data.metadata?.content?.title || "", - publishedAt: page.data.metadata?.content?.date_published, - published: !!page.data.noteId, - excerpt: page.data.metadata?.content?.summary || "", - slug: page.data.metadata?.content?.slug || "", - tags: - page.data.metadata?.content?.tags - ?.filter((tag) => tag !== "post" && tag !== "page") - ?.join(", ") || "", - content: page.data.metadata?.content?.content || "", - cover: page.data.metadata?.content?.attachments?.find( - (attachment) => attachment.name === "cover", - ) || { - address: "", - mime_type: "", - }, - disableAISummary: page.data.metadata?.content?.disableAISummary, - }) - setDefaultSlug( - getDefaultSlug( - page.data.metadata?.content?.title || "", - draftKey.replace(`draft-${site.data?.characterId}-`, ""), - ), - ) - }, [page.data, subdomain, draftKey, site.data?.characterId]) - - const [currentScrollArea, setCurrentScrollArea] = useState("") - const [view, setView] = useState() - const [tree, setTree] = useState() - - // preview - - const [parsedContent, setParsedContent] = useState() - - useDebounceEffect( - () => { - const result = renderPageContent(values.content) - setTree(result.tree) - setParsedContent(result) - }, - [values.content], - { - wait: 500, - }, - ) - - const previewRef = useRef(null) - - // editor - const onCreateEditor = useCallback( - (view: EditorView) => { - setView?.(view) - }, - [setView], - ) - - const onChange = useCallback( - (value: string) => { - updateValue("content", value) - }, - [updateValue], - ) - - const handleDropFile = useCallback( - async (file: File) => { - if (view) { - editorUpload(file, view) - } - }, - [uploadFile, view], - ) - - const computedPosition = useCallback(() => { - let previewChildNodes = previewRef.current?.childNodes[0]?.childNodes - const editorElementList: number[] = [] - const previewElementList: number[] = [] - if (view?.state && previewChildNodes) { - tree?.children.forEach((child, index) => { - if ( - child.position && - previewChildNodes?.[index] && - (child as any).tagName !== "style" - ) { - if (child.position.start.line > view.state.doc.lines) return - const line = view.state?.doc.line(child.position.start.line) - const block = view.lineBlockAt(line.from) - if (block) { - editorElementList.push(block.top) - previewElementList.push( - (previewChildNodes[index] as HTMLElement).offsetTop, - ) - } - } - }) - } - return { - editorElementList, - previewElementList, - } - }, [view, tree]) - - const onScroll = useCallback( - (scrollTop: number, area: string) => { - if ( - currentScrollArea === area && - previewRef.current?.parentElement && - view - ) { - const position = computedPosition() - - let selfElement - let selfPosition - let targetElement - let targetPosition - if (area === "preview") { - selfElement = previewRef.current.parentElement - selfPosition = position.previewElementList - targetElement = view.scrollDOM - targetPosition = position.editorElementList - } else { - selfElement = view.scrollDOM - selfPosition = position.editorElementList - targetElement = previewRef.current.parentElement - targetPosition = position.previewElementList - } - - let scrollElementIndex = 0 - for (let i = 0; i < selfPosition.length; i++) { - if (scrollTop < selfPosition[i]) { - scrollElementIndex = i - 1 - break - } - } - - // scroll to bottom - if (scrollTop >= selfElement.scrollHeight - selfElement.clientHeight) { - targetElement.scrollTop = - targetElement.scrollHeight - targetElement.clientHeight - return - } - - // scroll to position - if (scrollElementIndex >= 0) { - let ratio = - (scrollTop - selfPosition[scrollElementIndex]) / - (selfPosition[scrollElementIndex + 1] - - selfPosition[scrollElementIndex]) - targetElement.scrollTop = - ratio * - (targetPosition[scrollElementIndex + 1] - - targetPosition[scrollElementIndex]) + - targetPosition[scrollElementIndex] - } - } - }, - [view, computedPosition, currentScrollArea], - ) - - const onEditorScroll = useCallback( - (scrollTop: number) => { - onScroll(scrollTop, "editor") - }, - [onScroll], - ) - - const onPreviewScroll = useCallback( - (scrollTop: number) => { - onScroll(scrollTop, "preview") - }, - [onScroll], - ) - - const onPreviewButtonClick = useCallback(() => { - window.open( - `/site/${subdomain}/preview/${draftKey.replace( - `draft-${site.data?.characterId}-`, - "", - )}`, - ) - }, [draftKey, subdomain, site.data?.characterId]) - - const [isAdvancedOptionsOpen, setIsAdvancedOptionsOpen] = - useState(false) - - const extraProperties = ( - setIsAdvancedOptionsOpen(true)} - /> - ) - - const discardChanges = useCallback(() => { - if (draftKey) { - delStorage(draftKey) - queryClient.invalidateQueries(["getPagesBySite", site.data?.characterId]) - page.remove() - page.refetch() - } - }, [draftKey, site.data?.characterId]) - - const cmStyle = useMemo( - () => ({ - ".cm-scroller": { - padding: "0 1.25rem", - }, - ".cm-content": { - paddingBottom: "600px", - }, - }), - [], - ) - - return ( - <> - - {page.isLoading ? ( -
- {t("Loading")}... -
- ) : ( - <> -
-
- -
- {isMobileLayout ? ( -
- -
- ) : ( -
- - {t(visibility as string)} - - - -
- )} -
-
-
-
- { - if (e.key === "Enter" && !e.nativeEvent.isComposing) { - view?.focus() - } - }} - onChange={(e) => updateValue("title", e.target.value)} - className="h-12 ml-1 inline-flex items-center border-none text-3xl font-bold w-full focus:outline-none bg-white" - placeholder={t("Title goes here...") || ""} - /> -
-
- {!(isMobileLayout && isRendering) && ( - { - setCurrentScrollArea("editor") - }} - className={cn( - "h-full flex-1", - isRendering ? "border-r" : "", - )} - shortcuts={toolbarShortcuts} - /> - )} - {!isMobileLayout && ( -
-
setIsRendering(!isRendering)} - > - {isRendering ? ( - - ) : ( - - )} -
-
- )} - {isRendering && ( - { - setCurrentScrollArea("preview") - }} - /> - )} -
-
- {!isMobileLayout && ( - setIsAdvancedOptionsOpen(true)} - /> - )} -
- - )} -
- - -
- {t( - "Your post has been securely stored on the blockchain. Now you may want to", - )} -
    -
  • - - {t("View the post")} - -
  • -
  • - - {t("View the transaction")} - -
  • -
  • - - {t("Share to Twitter")} - -
  • -
-
-
- -
-
- - ) + return } - -const EditorExtraProperties = memo( - ({ - isPost, - updateValue, - subdomain, - defaultSlug, - userTags, - openAdvancedOptions, - }: { - updateValue: (key: K, value: Values[K]) => void - isPost: boolean - - subdomain: string - defaultSlug: string - userTags: string[] - - openAdvancedOptions: () => void - }) => { - const values = useEditorState( - (state) => - pick(state, ["publishedAt", "slug", "excerpt", "tags", "cover"]), - shallow, - ) - const { t } = useTranslation("dashboard") - const site = useGetSite(subdomain) - - return ( -
-
- - { - if (value) { - updateValue("publishedAt", value.toISOString()) - } else { - updateValue("publishedAt", "") - } - }} - styles={{ - input: { - borderRadius: "0.5rem", - borderColor: "var(--border-color)", - height: "2.5rem", - "&:focus-within": { - borderColor: "var(--theme-color)", - }, - }, - }} - /> -
- {t( - `This ${ - isPost ? "post" : "page" - } will be accessible from this time. Leave blank to use the current time.`, - )} -
- {values.publishedAt > new Date().toISOString() && ( -
- {t( - "The post is currently not public as its publication date has been scheduled for a future time.", - )} -
- )} -
-
- ) => - updateValue("slug", e.target.value) - } - help={ - <> - {(values.slug || defaultSlug) && ( - <> - {t( - `This ${isPost ? "post" : "page"} will be accessible at`, - )}{" "} - - {getSiteLink({ - subdomain, - domain: site.data?.metadata?.content?.custom_domain, - noProtocol: true, - })} - /{encodeURIComponent(values.slug || defaultSlug)} - - - )} - - } - /> -
-
- ( - updateValue("tags", value)} - /> - )} - /> -
-
- ) => { - updateValue("excerpt", e.target.value) - }} - help={t("Leave it blank to use auto-generated excerpt")} - /> -
-
- - { - const { address, mime_type } = key as { - address?: string - mime_type?: string - } - updateValue("cover", { - address, - mime_type, - }) - }} - accept="image/*" - /> -
- {t("Leave blank to use the first image in the post")} -
-
-
- -
-
- ) - }, -) - -EditorExtraProperties.displayName = "EditorExtraProperties" - -const EditorAdvancedOptions = memo( - ({ - updateValue, - isAdvancedOptionsOpen, - setIsAdvancedOptionsOpen, - }: { - updateValue: (key: K, value: Values[K]) => void - - isAdvancedOptionsOpen: boolean - setIsAdvancedOptionsOpen: (state: boolean) => void - }) => { - const values = useEditorState( - (state) => pick(state, ["disableAISummary"]), - shallow, - ) - const { t } = useTranslation("dashboard") - - return ( - -
-
- updateValue("disableAISummary", state)} - /> -
-
-
- ) - }, -) - -EditorAdvancedOptions.displayName = "EditorAdvancedOptions" diff --git a/src/app/dashboard/[subdomain]/events/page-component.tsx b/src/app/dashboard/[subdomain]/events/page-component.tsx new file mode 100644 index 00000000..81ecbf63 --- /dev/null +++ b/src/app/dashboard/[subdomain]/events/page-component.tsx @@ -0,0 +1,176 @@ +"use client" + +import { useEffect, useState } from "react" + +import { CharacterFloatCard } from "~/components/common/CharacterFloatCard" +import { DashboardMain } from "~/components/dashboard/DashboardMain" +import { Avatar } from "~/components/ui/Avatar" +import { Image } from "~/components/ui/Image" +import { UniLink } from "~/components/ui/UniLink" +import { useDate } from "~/hooks/useDate" +import { getSiteLink } from "~/lib/helpers" +import { useTranslation } from "~/lib/i18n/client" +import { getStorage, setStorage } from "~/lib/storage" +import { cn } from "~/lib/utils" +import { useGetPagesBySite } from "~/queries/page" +import { useGetSite } from "~/queries/site" + +function SiteAvatar({ siteId }: { siteId: string }) { + const site = useGetSite(siteId) + return ( +
+ + + + + +
+ ) +} + +export default function EventsPage() { + const date = useDate() + const { t } = useTranslation("dashboard") + const pages = useGetPagesBySite({ + type: "post", + characterId: 50153, + limit: 100, + }) + + const [latestEventRead, setLatestEventRead] = useState() + + const [isMounted, setIsMounted] = useState(false) + + useEffect(() => { + setIsMounted(true) + setLatestEventRead(new Date(getStorage("latestEventRead")?.value || 0)) + setStorage("latestEventRead", { + value: new Date().toISOString(), + }) + }, []) + + pages.data?.pages[0]?.list.forEach((item) => { + item.metadata?.content?.frontMatter?.Winners + }) + + return ( + +
+
+ {pages.data?.pages[0]?.list.map((item) => { + let status + if (item.metadata?.content?.frontMatter?.EndTime < new Date()) { + status = "Ended" + } else if ( + item.metadata?.content?.frontMatter?.StartTime > new Date() + ) { + status = "Upcoming" + } else { + status = "Ongoing" + } + + let isUnread = false + if (latestEventRead && new Date(item.createdAt) > latestEventRead) { + isUnread = true + } + return ( +
+ {isUnread && ( +
+ +
+ )} +
+
+
+ + {t(status)} + +
+ {item.metadata?.content?.cover && ( +
+ cover +
+ )} +
+ {item.metadata?.content?.title} +
+
+
+
+ {t("Date")}:{" "} + {date.formatDate( + item.metadata?.content?.frontMatter?.StartTime, + "lll", + isMounted ? undefined : "America/Los_Angeles", + )}{" "} + -{" "} + {date.formatDate( + item.metadata?.content?.frontMatter?.EndTime, + "lll", + isMounted ? undefined : "America/Los_Angeles", + )} +
+
+ {t("Prize")}:{" "} + {item.metadata?.content?.frontMatter?.Prize} +
+ {item.metadata?.content?.frontMatter?.Winners?.map && ( +
+ {t("Winners")}: +
+ {item.metadata?.content?.frontMatter?.Winners?.map?.( + (winner: string) => ( + + ), + )} +
+
+ )} +
+ + {t("Learn more")}{" "} + + +
+
+ ) + })} +
+
+
+ ) +} diff --git a/src/app/dashboard/[subdomain]/events/page.tsx b/src/app/dashboard/[subdomain]/events/page.tsx index 81ecbf63..0ee181a5 100644 --- a/src/app/dashboard/[subdomain]/events/page.tsx +++ b/src/app/dashboard/[subdomain]/events/page.tsx @@ -1,176 +1,5 @@ -"use client" - -import { useEffect, useState } from "react" - -import { CharacterFloatCard } from "~/components/common/CharacterFloatCard" -import { DashboardMain } from "~/components/dashboard/DashboardMain" -import { Avatar } from "~/components/ui/Avatar" -import { Image } from "~/components/ui/Image" -import { UniLink } from "~/components/ui/UniLink" -import { useDate } from "~/hooks/useDate" -import { getSiteLink } from "~/lib/helpers" -import { useTranslation } from "~/lib/i18n/client" -import { getStorage, setStorage } from "~/lib/storage" -import { cn } from "~/lib/utils" -import { useGetPagesBySite } from "~/queries/page" -import { useGetSite } from "~/queries/site" - -function SiteAvatar({ siteId }: { siteId: string }) { - const site = useGetSite(siteId) - return ( -
- - - - - -
- ) -} +import PageComponent from "./page-component" export default function EventsPage() { - const date = useDate() - const { t } = useTranslation("dashboard") - const pages = useGetPagesBySite({ - type: "post", - characterId: 50153, - limit: 100, - }) - - const [latestEventRead, setLatestEventRead] = useState() - - const [isMounted, setIsMounted] = useState(false) - - useEffect(() => { - setIsMounted(true) - setLatestEventRead(new Date(getStorage("latestEventRead")?.value || 0)) - setStorage("latestEventRead", { - value: new Date().toISOString(), - }) - }, []) - - pages.data?.pages[0]?.list.forEach((item) => { - item.metadata?.content?.frontMatter?.Winners - }) - - return ( - -
-
- {pages.data?.pages[0]?.list.map((item) => { - let status - if (item.metadata?.content?.frontMatter?.EndTime < new Date()) { - status = "Ended" - } else if ( - item.metadata?.content?.frontMatter?.StartTime > new Date() - ) { - status = "Upcoming" - } else { - status = "Ongoing" - } - - let isUnread = false - if (latestEventRead && new Date(item.createdAt) > latestEventRead) { - isUnread = true - } - return ( -
- {isUnread && ( -
- -
- )} -
-
-
- - {t(status)} - -
- {item.metadata?.content?.cover && ( -
- cover -
- )} -
- {item.metadata?.content?.title} -
-
-
-
- {t("Date")}:{" "} - {date.formatDate( - item.metadata?.content?.frontMatter?.StartTime, - "lll", - isMounted ? undefined : "America/Los_Angeles", - )}{" "} - -{" "} - {date.formatDate( - item.metadata?.content?.frontMatter?.EndTime, - "lll", - isMounted ? undefined : "America/Los_Angeles", - )} -
-
- {t("Prize")}:{" "} - {item.metadata?.content?.frontMatter?.Prize} -
- {item.metadata?.content?.frontMatter?.Winners?.map && ( -
- {t("Winners")}: -
- {item.metadata?.content?.frontMatter?.Winners?.map?.( - (winner: string) => ( - - ), - )} -
-
- )} -
- - {t("Learn more")}{" "} - - -
-
- ) - })} -
-
-
- ) + return } diff --git a/src/app/dashboard/[subdomain]/import/markdown/page-component.tsx b/src/app/dashboard/[subdomain]/import/markdown/page-component.tsx new file mode 100644 index 00000000..71f15779 --- /dev/null +++ b/src/app/dashboard/[subdomain]/import/markdown/page-component.tsx @@ -0,0 +1,112 @@ +"use client" + +import type { NoteMetadata } from "crossbell" +import { useParams } from "next/navigation" +import { useEffect, useState } from "react" +import { useForm } from "react-hook-form" +import { toast } from "react-hot-toast" + +import { DashboardMain } from "~/components/dashboard/DashboardMain" +import { ImportPreview } from "~/components/dashboard/ImportPreview" +import { Button } from "~/components/ui/Button" +import { Input } from "~/components/ui/Input" +import { useTranslation } from "~/lib/i18n/client" +import { readFiles } from "~/lib/read-files" +import { usePostNotes } from "~/queries/page" +import { useGetSite } from "~/queries/site" + +export default function ImportMarkdownPage() { + const params = useParams() + const subdomain = params?.subdomain as string + const site = useGetSite(subdomain) + const { t } = useTranslation("dashboard") + const form = useForm({ + defaultValues: { + type: "post", + files: [], + }, + }) + const postNotes = usePostNotes() + + const [notes, setNotes] = useState() + + const handleSubmit = form.handleSubmit(async (values) => { + if (notes?.length && site.data?.handle && site.data.characterId) { + postNotes.mutate({ + siteId: site.data.handle, + characterId: site.data.characterId, + notes, + }) + } + }) + + form.register("files", { + onChange: async (e) => { + const files = await readFiles(e.target.files) + const notes = files.map((file) => { + return { + title: file.title, + content: file.content, + tags: ["post", ...file.tags], + sources: ["xlog"], + attributes: [ + { + trait_type: "xlog_slug", + value: file.slug, + }, + ], + date_published: file.date_published, + } + }) + setNotes(notes) + }, + }) + + useEffect(() => { + if (postNotes.isSuccess) { + form.reset() + toast.success("Notes imported successfully") + } + }, [postNotes.isSuccess, form]) + + return ( + +
+
+ +
+
{t("Preview")}
+ {notes?.length ? ( + notes?.map((note) => ( + + )) + ) : ( +
{t("No files chosen")}
+ )} +
+
+ +
+
+
+
+ ) +} diff --git a/src/app/dashboard/[subdomain]/import/markdown/page.tsx b/src/app/dashboard/[subdomain]/import/markdown/page.tsx index 71f15779..f41bbec3 100644 --- a/src/app/dashboard/[subdomain]/import/markdown/page.tsx +++ b/src/app/dashboard/[subdomain]/import/markdown/page.tsx @@ -1,112 +1,5 @@ -"use client" - -import type { NoteMetadata } from "crossbell" -import { useParams } from "next/navigation" -import { useEffect, useState } from "react" -import { useForm } from "react-hook-form" -import { toast } from "react-hot-toast" - -import { DashboardMain } from "~/components/dashboard/DashboardMain" -import { ImportPreview } from "~/components/dashboard/ImportPreview" -import { Button } from "~/components/ui/Button" -import { Input } from "~/components/ui/Input" -import { useTranslation } from "~/lib/i18n/client" -import { readFiles } from "~/lib/read-files" -import { usePostNotes } from "~/queries/page" -import { useGetSite } from "~/queries/site" +import PageComponent from "./page-component" export default function ImportMarkdownPage() { - const params = useParams() - const subdomain = params?.subdomain as string - const site = useGetSite(subdomain) - const { t } = useTranslation("dashboard") - const form = useForm({ - defaultValues: { - type: "post", - files: [], - }, - }) - const postNotes = usePostNotes() - - const [notes, setNotes] = useState() - - const handleSubmit = form.handleSubmit(async (values) => { - if (notes?.length && site.data?.handle && site.data.characterId) { - postNotes.mutate({ - siteId: site.data.handle, - characterId: site.data.characterId, - notes, - }) - } - }) - - form.register("files", { - onChange: async (e) => { - const files = await readFiles(e.target.files) - const notes = files.map((file) => { - return { - title: file.title, - content: file.content, - tags: ["post", ...file.tags], - sources: ["xlog"], - attributes: [ - { - trait_type: "xlog_slug", - value: file.slug, - }, - ], - date_published: file.date_published, - } - }) - setNotes(notes) - }, - }) - - useEffect(() => { - if (postNotes.isSuccess) { - form.reset() - toast.success("Notes imported successfully") - } - }, [postNotes.isSuccess, form]) - - return ( - -
-
- -
-
{t("Preview")}
- {notes?.length ? ( - notes?.map((note) => ( - - )) - ) : ( -
{t("No files chosen")}
- )} -
-
- -
-
-
-
- ) + return } diff --git a/src/app/dashboard/[subdomain]/import/mirror/page-component.tsx b/src/app/dashboard/[subdomain]/import/mirror/page-component.tsx new file mode 100644 index 00000000..0efbff1b --- /dev/null +++ b/src/app/dashboard/[subdomain]/import/mirror/page-component.tsx @@ -0,0 +1,104 @@ +"use client" + +import type { NoteMetadata } from "crossbell" +import { useParams } from "next/navigation" +import { useEffect } from "react" +import { useForm } from "react-hook-form" +import { toast } from "react-hot-toast" + +import { DashboardMain } from "~/components/dashboard/DashboardMain" +import { ImportPreview } from "~/components/dashboard/ImportPreview" +import { Button } from "~/components/ui/Button" +import { useTranslation } from "~/lib/i18n/client" +import { useCheckMirror, useGetMirrorXyz, usePostNotes } from "~/queries/page" +import { useGetSite } from "~/queries/site" + +export default function ImportMirrorPage() { + const params = useParams() + const subdomain = params?.subdomain as string + const site = useGetSite(subdomain) + const { t } = useTranslation("dashboard") + const form = useForm({ + defaultValues: { + type: "post", + }, + }) + const postNotes = usePostNotes() + const mirrorXyz = useGetMirrorXyz({ + address: site.data?.owner, + }) + const checkMirror = useCheckMirror(site.data?.characterId) + + const notes = mirrorXyz?.data?.map((note) => ({ + title: note.title, + content: note.content, + tags: ["post", ...note.tags], + sources: ["xlog"], + attributes: [ + { + trait_type: "xlog_slug", + value: note.slug, + }, + ], + date_published: note.date_published, + external_urls: [...note.external_urls], + })) + + const handleSubmit = form.handleSubmit(async (values) => { + if (notes?.length && site.data?.handle && site.data.characterId) { + postNotes.mutate({ + siteId: site.data.handle, + characterId: site.data.characterId, + notes: notes, + }) + } + }) + + useEffect(() => { + if (postNotes.isSuccess) { + form.reset() + toast.success("Notes imported successfully") + } + }, [postNotes.isSuccess, form]) + + return ( + + {checkMirror?.data ? ( +
+
+
+
+ {t("Preview your Mirror.xyz entries")} +
+ {notes?.length ? ( + notes?.map((note: NoteMetadata) => ( + + )) + ) : ( +
{t("No entries")}
+ )} +
+
+ +
+
+
+ ) : ( +
+ {t( + "You have already imported them, please enter the post page to create a new post!", + )} +
+ )} +
+ ) +} diff --git a/src/app/dashboard/[subdomain]/import/mirror/page.tsx b/src/app/dashboard/[subdomain]/import/mirror/page.tsx index 08eb12c4..23d1f1c3 100644 --- a/src/app/dashboard/[subdomain]/import/mirror/page.tsx +++ b/src/app/dashboard/[subdomain]/import/mirror/page.tsx @@ -1,104 +1,5 @@ -"use client" +import PageComponent from "./page-component" -import type { NoteMetadata } from "crossbell" -import { useParams } from "next/navigation" -import { useEffect } from "react" -import { useForm } from "react-hook-form" -import { toast } from "react-hot-toast" - -import { DashboardMain } from "~/components/dashboard/DashboardMain" -import { ImportPreview } from "~/components/dashboard/ImportPreview" -import { Button } from "~/components/ui/Button" -import { useTranslation } from "~/lib/i18n/client" -import { useCheckMirror, useGetMirrorXyz, usePostNotes } from "~/queries/page" -import { useGetSite } from "~/queries/site" - -export default function ImportMarkdownPage() { - const params = useParams() - const subdomain = params?.subdomain as string - const site = useGetSite(subdomain) - const { t } = useTranslation("dashboard") - const form = useForm({ - defaultValues: { - type: "post", - }, - }) - const postNotes = usePostNotes() - const mirrorXyz = useGetMirrorXyz({ - address: site.data?.owner, - }) - const checkMirror = useCheckMirror(site.data?.characterId) - - const notes = mirrorXyz?.data?.map((note) => ({ - title: note.title, - content: note.content, - tags: ["post", ...note.tags], - sources: ["xlog"], - attributes: [ - { - trait_type: "xlog_slug", - value: note.slug, - }, - ], - date_published: note.date_published, - external_urls: [...note.external_urls], - })) - - const handleSubmit = form.handleSubmit(async (values) => { - if (notes?.length && site.data?.handle && site.data.characterId) { - postNotes.mutate({ - siteId: site.data.handle, - characterId: site.data.characterId, - notes: notes, - }) - } - }) - - useEffect(() => { - if (postNotes.isSuccess) { - form.reset() - toast.success("Notes imported successfully") - } - }, [postNotes.isSuccess, form]) - - return ( - - {checkMirror?.data ? ( -
-
-
-
- {t("Preview your Mirror.xyz entries")} -
- {notes?.length ? ( - notes?.map((note: NoteMetadata) => ( - - )) - ) : ( -
{t("No entries")}
- )} -
-
- -
-
-
- ) : ( -
- {t( - "You have already imported them, please enter the post page to create a new post!", - )} -
- )} -
- ) +export default function ImportMirrorPage() { + return } diff --git a/src/app/dashboard/[subdomain]/import/page-component.tsx b/src/app/dashboard/[subdomain]/import/page-component.tsx new file mode 100644 index 00000000..d1bac6d6 --- /dev/null +++ b/src/app/dashboard/[subdomain]/import/page-component.tsx @@ -0,0 +1,51 @@ +"use client" + +import { usePathname } from "next/navigation" + +import { DashboardMain } from "~/components/dashboard/DashboardMain" +import { Image } from "~/components/ui/Image" +import { UniLink } from "~/components/ui/UniLink" +import { useTranslation } from "~/lib/i18n/client" + +export default function ImportPage() { + const pathname = usePathname() + const { t } = useTranslation("dashboard") + + const options = [ + { + name: "Markdown files", + path: "/markdown", + icon: "markdown.svg", + }, + { + name: "Mirror.xyz", + path: "/mirror", + icon: "mirror.xyz.svg", + }, + ] + + return ( + +
+ {options.map((option) => ( + + + {option.name} + + + {t(`Import from ${option.name}`)} + + + ))} +
+
+ ) +} diff --git a/src/app/dashboard/[subdomain]/import/page.tsx b/src/app/dashboard/[subdomain]/import/page.tsx index d1bac6d6..0d966207 100644 --- a/src/app/dashboard/[subdomain]/import/page.tsx +++ b/src/app/dashboard/[subdomain]/import/page.tsx @@ -1,51 +1,5 @@ -"use client" - -import { usePathname } from "next/navigation" - -import { DashboardMain } from "~/components/dashboard/DashboardMain" -import { Image } from "~/components/ui/Image" -import { UniLink } from "~/components/ui/UniLink" -import { useTranslation } from "~/lib/i18n/client" +import PageComponent from "./page-component" export default function ImportPage() { - const pathname = usePathname() - const { t } = useTranslation("dashboard") - - const options = [ - { - name: "Markdown files", - path: "/markdown", - icon: "markdown.svg", - }, - { - name: "Mirror.xyz", - path: "/mirror", - icon: "mirror.xyz.svg", - }, - ] - - return ( - -
- {options.map((option) => ( - - - {option.name} - - - {t(`Import from ${option.name}`)} - - - ))} -
-
- ) + return } diff --git a/src/app/dashboard/[subdomain]/layout-component.tsx b/src/app/dashboard/[subdomain]/layout-component.tsx new file mode 100644 index 00000000..7993265a --- /dev/null +++ b/src/app/dashboard/[subdomain]/layout-component.tsx @@ -0,0 +1,388 @@ +"use client" + +import { useParams, usePathname } from "next/navigation" +import React, { useEffect } from "react" +import { useTranslation } from "react-i18next" + +import { useAccountState, useConnectModal } from "@crossbell/connect-kit" +import { + useNotifications, + useShowNotificationModal, +} from "@crossbell/notification" + +import { ConnectButton } from "~/components/common/ConnectButton" +import { Logo } from "~/components/common/Logo" +import { DashboardSidebar } from "~/components/dashboard/DashboardSidebar" +import { DashboardTopbar } from "~/components/dashboard/DashboardTopbar" +import { Avatar } from "~/components/ui/Avatar" +import { UniLink } from "~/components/ui/UniLink" +import { useIsMobileLayout } from "~/hooks/useMobileLayout" +import { useUserRole } from "~/hooks/useUserRole" +import { DISCORD_LINK } from "~/lib/env" +import { getSiteLink } from "~/lib/helpers" +import { toGateway } from "~/lib/ipfs-parser" +import { getStorage } from "~/lib/storage" +import { cn } from "~/lib/utils" +import { useGetPagesBySite } from "~/queries/page" +import { useGetSite } from "~/queries/site" + +export default function DashboardLayout({ + children, +}: { + children: React.ReactNode +}) { + const params = useParams() + const subdomain = params?.subdomain as string + const site = useGetSite(subdomain) + + const userRole = useUserRole(subdomain) + const [ssrReady, account] = useAccountState(({ ssrReady, computed }) => [ + ssrReady, + computed.account, + ]) + const connectModal = useConnectModal() + const [ready, setReady] = React.useState(false) + const [hasPermission, setHasPermission] = React.useState(false) + const { t } = useTranslation("dashboard") + + const isMobileLayout = useIsMobileLayout() + const pathname = usePathname() + + useEffect(() => { + if (ssrReady) { + if (!account) { + setReady(false) + setHasPermission(false) + connectModal.show() + } else if (userRole.isSuccess) { + setReady(true) + if (userRole.data) { + setHasPermission(true) + } else { + setHasPermission(false) + } + } + } + }, [ssrReady, userRole.isSuccess, userRole.data, account, connectModal]) + + const showNotificationModal = useShowNotificationModal() + const { isAllRead } = useNotifications() + + const pages = useGetPagesBySite({ + type: "post", + characterId: 50153, + limit: 1, + }) + const [isEventsAllRead, setIsEventsAllRead] = React.useState(true) + const latestEventRead = getStorage("latestEventRead")?.value || 0 + useEffect(() => { + if (pages.isSuccess) { + if ( + new Date(pages.data.pages[0].list?.[0].createdAt) > + new Date(latestEventRead) + ) { + setIsEventsAllRead(false) + } else { + setIsEventsAllRead(true) + } + } + }, [pages.isSuccess, pages.data?.pages, latestEventRead]) + + const links: { + href?: string + onClick?: () => void + isActive: (ctx: { href: string; pathname: string | null }) => boolean + icon: React.ReactNode + text: string + }[] = [ + { + href: `/dashboard/${subdomain}`, + isActive: ({ href, pathname }) => href === pathname, + icon: "icon-[mingcute--grid-line]", + text: "Dashboard", + }, + { + href: `/dashboard/${subdomain}/posts`, + isActive: ({ href, pathname }) => href === pathname, + icon: "icon-[mingcute--news-line]", + text: "Posts", + }, + { + href: `/dashboard/${subdomain}/pages`, + isActive: ({ href, pathname }) => href === pathname, + icon: "icon-[mingcute--file-line]", + text: "Pages", + }, + { + href: `/dashboard/${subdomain}/comments`, + isActive: ({ href, pathname }) => href === pathname, + icon: "icon-[mingcute--comment-line]", + text: "Comments", + }, + { + onClick: showNotificationModal, + isActive: ({ href, pathname }) => href === pathname, + icon: isAllRead + ? "icon-[mingcute--notification-line]" + : "icon-[mingcute--notification-fill]", + text: isAllRead ? "Notifications" : "Unread notifications", + }, + { + href: `/dashboard/${subdomain}/import`, + isActive: ({ pathname }) => + !!pathname?.startsWith(`/dashboard/${subdomain}/import`), + icon: "icon-[mingcute--file-import-line]", + text: "Import", + }, + { + href: `/dashboard/${subdomain}/events`, + isActive: ({ href, pathname }) => href === pathname, + icon: isEventsAllRead + ? "icon-[mingcute--flag-4-line]" + : "icon-[mingcute--flag-4-fill]", + text: isEventsAllRead ? "Events" : "New Events", + }, + { + href: `/dashboard/${subdomain}/achievements`, + isActive: ({ href, pathname }) => href === pathname, + icon: "icon-[mingcute--trophy-line]", + text: "Achievements", + }, + { + href: `/dashboard/${subdomain}/tokens`, + isActive: ({ href, pathname }) => href === pathname, + icon: "icon-[mingcute--pig-money-line]", + text: "Tokens", + }, + { + href: `/dashboard/${subdomain}/settings/general`, + isActive: ({ pathname }) => + !!pathname?.startsWith(`/dashboard/${subdomain}/settings`), + icon: "icon-[mingcute--settings-3-line]", + text: "Settings", + }, + ] + + return ready ? ( + hasPermission ? ( + <> + {/* TODO */} + {/* */} + {site?.data?.metadata?.content?.css && ( + + )} +
+ {isMobileLayout ? ( + + +
+ } + drawerWidget={(close: any) => ( + <> +
+
+
+ +
+ {"xLog"} +
+
+ {links.map((link) => { + const active = + link.href && + link.isActive({ + pathname: pathname, + href: link.href, + }) + return ( +
close()}> + + + {t(link.text)} + +
+ ) + })} +
+
+ + + {{t("Need help?")}} + + + + {{t("View Site")}} + +
+
+ + )} + > + {(isOpen) =>
233
} + + ) : ( + + {(isOpen) => ( + <> +
+
+
+ +
+ {isOpen && "xLog"} +
+ {account?.character?.handle && + subdomain && + account?.character?.handle !== subdomain && ( +
+
+ {isOpen && "You are operating"} +
+ + {isOpen && ( + + + {site.data?.metadata?.content?.name} + + + @{site.data?.handle} + + + )} +
+ )} +
+ +
+ +
+ {links.map((link) => { + const active = + link.href && + link.isActive({ + pathname: pathname, + href: link.href, + }) + return ( + + + {isOpen && {t(link.text)}} + + ) + })} +
+
+
+ + + {isOpen && {t("Need help?")}} + + + + {isOpen && {t("View Site")}} + +
+ + )} +
+ )} + +
+ {children} +
+ + + ) : ( +
+ +
+ Sorry, you do not have permission to access the current page. +
+
+ Please switch account or request the owner to set you as the operator. +
+ + Take me to my own dashboard + +
+ ) + ) : ( +
+ Loading... +
+ ) +} diff --git a/src/app/dashboard/[subdomain]/layout.tsx b/src/app/dashboard/[subdomain]/layout.tsx index 7993265a..b2ba8bce 100644 --- a/src/app/dashboard/[subdomain]/layout.tsx +++ b/src/app/dashboard/[subdomain]/layout.tsx @@ -1,388 +1,9 @@ -"use client" - -import { useParams, usePathname } from "next/navigation" -import React, { useEffect } from "react" -import { useTranslation } from "react-i18next" - -import { useAccountState, useConnectModal } from "@crossbell/connect-kit" -import { - useNotifications, - useShowNotificationModal, -} from "@crossbell/notification" - -import { ConnectButton } from "~/components/common/ConnectButton" -import { Logo } from "~/components/common/Logo" -import { DashboardSidebar } from "~/components/dashboard/DashboardSidebar" -import { DashboardTopbar } from "~/components/dashboard/DashboardTopbar" -import { Avatar } from "~/components/ui/Avatar" -import { UniLink } from "~/components/ui/UniLink" -import { useIsMobileLayout } from "~/hooks/useMobileLayout" -import { useUserRole } from "~/hooks/useUserRole" -import { DISCORD_LINK } from "~/lib/env" -import { getSiteLink } from "~/lib/helpers" -import { toGateway } from "~/lib/ipfs-parser" -import { getStorage } from "~/lib/storage" -import { cn } from "~/lib/utils" -import { useGetPagesBySite } from "~/queries/page" -import { useGetSite } from "~/queries/site" +import LayoutComponent from "./layout-component" export default function DashboardLayout({ children, }: { children: React.ReactNode }) { - const params = useParams() - const subdomain = params?.subdomain as string - const site = useGetSite(subdomain) - - const userRole = useUserRole(subdomain) - const [ssrReady, account] = useAccountState(({ ssrReady, computed }) => [ - ssrReady, - computed.account, - ]) - const connectModal = useConnectModal() - const [ready, setReady] = React.useState(false) - const [hasPermission, setHasPermission] = React.useState(false) - const { t } = useTranslation("dashboard") - - const isMobileLayout = useIsMobileLayout() - const pathname = usePathname() - - useEffect(() => { - if (ssrReady) { - if (!account) { - setReady(false) - setHasPermission(false) - connectModal.show() - } else if (userRole.isSuccess) { - setReady(true) - if (userRole.data) { - setHasPermission(true) - } else { - setHasPermission(false) - } - } - } - }, [ssrReady, userRole.isSuccess, userRole.data, account, connectModal]) - - const showNotificationModal = useShowNotificationModal() - const { isAllRead } = useNotifications() - - const pages = useGetPagesBySite({ - type: "post", - characterId: 50153, - limit: 1, - }) - const [isEventsAllRead, setIsEventsAllRead] = React.useState(true) - const latestEventRead = getStorage("latestEventRead")?.value || 0 - useEffect(() => { - if (pages.isSuccess) { - if ( - new Date(pages.data.pages[0].list?.[0].createdAt) > - new Date(latestEventRead) - ) { - setIsEventsAllRead(false) - } else { - setIsEventsAllRead(true) - } - } - }, [pages.isSuccess, pages.data?.pages, latestEventRead]) - - const links: { - href?: string - onClick?: () => void - isActive: (ctx: { href: string; pathname: string | null }) => boolean - icon: React.ReactNode - text: string - }[] = [ - { - href: `/dashboard/${subdomain}`, - isActive: ({ href, pathname }) => href === pathname, - icon: "icon-[mingcute--grid-line]", - text: "Dashboard", - }, - { - href: `/dashboard/${subdomain}/posts`, - isActive: ({ href, pathname }) => href === pathname, - icon: "icon-[mingcute--news-line]", - text: "Posts", - }, - { - href: `/dashboard/${subdomain}/pages`, - isActive: ({ href, pathname }) => href === pathname, - icon: "icon-[mingcute--file-line]", - text: "Pages", - }, - { - href: `/dashboard/${subdomain}/comments`, - isActive: ({ href, pathname }) => href === pathname, - icon: "icon-[mingcute--comment-line]", - text: "Comments", - }, - { - onClick: showNotificationModal, - isActive: ({ href, pathname }) => href === pathname, - icon: isAllRead - ? "icon-[mingcute--notification-line]" - : "icon-[mingcute--notification-fill]", - text: isAllRead ? "Notifications" : "Unread notifications", - }, - { - href: `/dashboard/${subdomain}/import`, - isActive: ({ pathname }) => - !!pathname?.startsWith(`/dashboard/${subdomain}/import`), - icon: "icon-[mingcute--file-import-line]", - text: "Import", - }, - { - href: `/dashboard/${subdomain}/events`, - isActive: ({ href, pathname }) => href === pathname, - icon: isEventsAllRead - ? "icon-[mingcute--flag-4-line]" - : "icon-[mingcute--flag-4-fill]", - text: isEventsAllRead ? "Events" : "New Events", - }, - { - href: `/dashboard/${subdomain}/achievements`, - isActive: ({ href, pathname }) => href === pathname, - icon: "icon-[mingcute--trophy-line]", - text: "Achievements", - }, - { - href: `/dashboard/${subdomain}/tokens`, - isActive: ({ href, pathname }) => href === pathname, - icon: "icon-[mingcute--pig-money-line]", - text: "Tokens", - }, - { - href: `/dashboard/${subdomain}/settings/general`, - isActive: ({ pathname }) => - !!pathname?.startsWith(`/dashboard/${subdomain}/settings`), - icon: "icon-[mingcute--settings-3-line]", - text: "Settings", - }, - ] - - return ready ? ( - hasPermission ? ( - <> - {/* TODO */} - {/* */} - {site?.data?.metadata?.content?.css && ( - - )} -
- {isMobileLayout ? ( - - -
- } - drawerWidget={(close: any) => ( - <> -
-
-
- -
- {"xLog"} -
-
- {links.map((link) => { - const active = - link.href && - link.isActive({ - pathname: pathname, - href: link.href, - }) - return ( -
close()}> - - - {t(link.text)} - -
- ) - })} -
-
- - - {{t("Need help?")}} - - - - {{t("View Site")}} - -
-
- - )} - > - {(isOpen) =>
233
} - - ) : ( - - {(isOpen) => ( - <> -
-
-
- -
- {isOpen && "xLog"} -
- {account?.character?.handle && - subdomain && - account?.character?.handle !== subdomain && ( -
-
- {isOpen && "You are operating"} -
- - {isOpen && ( - - - {site.data?.metadata?.content?.name} - - - @{site.data?.handle} - - - )} -
- )} -
- -
- -
- {links.map((link) => { - const active = - link.href && - link.isActive({ - pathname: pathname, - href: link.href, - }) - return ( - - - {isOpen && {t(link.text)}} - - ) - })} -
-
-
- - - {isOpen && {t("Need help?")}} - - - - {isOpen && {t("View Site")}} - -
- - )} -
- )} - -
- {children} -
- - - ) : ( -
- -
- Sorry, you do not have permission to access the current page. -
-
- Please switch account or request the owner to set you as the operator. -
- - Take me to my own dashboard - -
- ) - ) : ( -
- Loading... -
- ) + return {children} } diff --git a/src/app/dashboard/[subdomain]/page-component.tsx b/src/app/dashboard/[subdomain]/page-component.tsx new file mode 100644 index 00000000..d3398340 --- /dev/null +++ b/src/app/dashboard/[subdomain]/page-component.tsx @@ -0,0 +1,269 @@ +"use client" + +import { useParams } from "next/navigation" + +import { CharacterFloatCard } from "~/components/common/CharacterFloatCard" +import { DashboardMain } from "~/components/dashboard/DashboardMain" +import { Image } from "~/components/ui/Image" +import { UniLink } from "~/components/ui/UniLink" +import { useDate } from "~/hooks/useDate" +import { CSB_SCAN, DISCORD_LINK, GITHUB_LINK, TWITTER_LINK } from "~/lib/env" +import { getSiteLink } from "~/lib/helpers" +import { Trans, useTranslation } from "~/lib/i18n/client" +import { cn } from "~/lib/utils" +import { useGetShowcase } from "~/queries/home" +import { useGetPagesBySite } from "~/queries/page" +import { useGetSite, useGetStat, useGetTips } from "~/queries/site" + +export default function SubdomainIndex() { + const params = useParams() + const subdomain = params?.subdomain as string + const site = useGetSite(subdomain) + const characterId = site.data?.characterId + const stat = useGetStat({ + characterId, + }) + const date = useDate() + const { t, i18n } = useTranslation("dashboard") + const tips = useGetTips({ + toCharacterId: characterId, + limit: 1000, + }) + + const statMap = [ + { + icon: "icon-[mingcute--news-line]", + name: "Published posts", + value: stat.data?.notesCount, + url: `/dashboard/${subdomain}/posts`, + }, + { + icon: "icon-[mingcute--comment-line]", + name: "Received comments", + value: stat.data?.commentsCount, + url: `/dashboard/${subdomain}/comments`, + }, + { + icon: "icon-[mingcute--heart-line]", + name: "Received tips", + value: `${ + tips.data?.pages?.[0]?.list + ?.map((i) => +i.amount) + .reduce((acr, cur) => acr + cur, 0) ?? 0 + } MIRA`, + url: `/dashboard/${subdomain}/tokens`, + }, + { + icon: "icon-[mingcute--user-follow-line]", + name: "Followers", + value: stat.data?.subscriptionCount, + url: getSiteLink({ + subdomain, + }), + }, + { + icon: "icon-[mingcute--eye-line]", + name: "Viewed", + value: stat.data?.viewsCount, + url: getSiteLink({ + subdomain, + }), + }, + { + icon: "icon-[mingcute--history-line]", + name: "Site Duration", + value: + date.dayjs().diff(date.dayjs(stat.data?.createdAt), "day") + + " " + + t("days"), + url: `${CSB_SCAN}/tx/${stat.data?.createTx}`, + }, + ] + + const pages = useGetPagesBySite({ + type: "post", + characterId: 32022, + limit: 4, + }) + + const showcaseSites = useGetShowcase() + + return ( + +
+
+
+ {statMap.map((item) => ( + + + + {t(item.name)} + + {item.value} + + ))} +
+
+ , + }} + ns="dashboard" + /> +
    +
  • + + {t("View Site")} + +
  • +
  • + + {t("Create a Post")} + +
  • +
  • + + {t("Change Site Icon or domain")} + +
  • +
+ , + }} + ns="dashboard" + /> +
    +
  • + + {t("Check out the updates of other bloggers")} + +
  • +
  • + + {t("Join xLog's Discord channel")} + +
  • +
  • + + {t("Participate in the development of xLog")} + +
  • +
  • + + {t("Follow xLog's Twitter")} + +
  • +
+
+
+
+
+
+ +
+ {t("More")} +
+
+

+ {t("xLog News")} +

+
+ {pages.data?.pages[0]?.list.map((item) => ( + + {item.metadata?.content?.cover && ( +
+ cover +
+ )} + + {item.metadata?.content?.title} + +
+ ))} +
+
+
+

+ {t("Meet New Friends")} +

+
    + {showcaseSites.data?.slice(0, 6)?.map((site) => ( +
  • + + + + {site.handle} + + + + + {site.metadata.content?.name} + + {site.metadata.content?.bio && ( + + {site.metadata.content?.bio} + + )} + + +
  • + ))} +
+
+
+
+
+ ) +} diff --git a/src/app/dashboard/[subdomain]/page.tsx b/src/app/dashboard/[subdomain]/page.tsx index d3398340..3726558f 100644 --- a/src/app/dashboard/[subdomain]/page.tsx +++ b/src/app/dashboard/[subdomain]/page.tsx @@ -1,269 +1,5 @@ -"use client" - -import { useParams } from "next/navigation" - -import { CharacterFloatCard } from "~/components/common/CharacterFloatCard" -import { DashboardMain } from "~/components/dashboard/DashboardMain" -import { Image } from "~/components/ui/Image" -import { UniLink } from "~/components/ui/UniLink" -import { useDate } from "~/hooks/useDate" -import { CSB_SCAN, DISCORD_LINK, GITHUB_LINK, TWITTER_LINK } from "~/lib/env" -import { getSiteLink } from "~/lib/helpers" -import { Trans, useTranslation } from "~/lib/i18n/client" -import { cn } from "~/lib/utils" -import { useGetShowcase } from "~/queries/home" -import { useGetPagesBySite } from "~/queries/page" -import { useGetSite, useGetStat, useGetTips } from "~/queries/site" +import PageComponent from "./page-component" export default function SubdomainIndex() { - const params = useParams() - const subdomain = params?.subdomain as string - const site = useGetSite(subdomain) - const characterId = site.data?.characterId - const stat = useGetStat({ - characterId, - }) - const date = useDate() - const { t, i18n } = useTranslation("dashboard") - const tips = useGetTips({ - toCharacterId: characterId, - limit: 1000, - }) - - const statMap = [ - { - icon: "icon-[mingcute--news-line]", - name: "Published posts", - value: stat.data?.notesCount, - url: `/dashboard/${subdomain}/posts`, - }, - { - icon: "icon-[mingcute--comment-line]", - name: "Received comments", - value: stat.data?.commentsCount, - url: `/dashboard/${subdomain}/comments`, - }, - { - icon: "icon-[mingcute--heart-line]", - name: "Received tips", - value: `${ - tips.data?.pages?.[0]?.list - ?.map((i) => +i.amount) - .reduce((acr, cur) => acr + cur, 0) ?? 0 - } MIRA`, - url: `/dashboard/${subdomain}/tokens`, - }, - { - icon: "icon-[mingcute--user-follow-line]", - name: "Followers", - value: stat.data?.subscriptionCount, - url: getSiteLink({ - subdomain, - }), - }, - { - icon: "icon-[mingcute--eye-line]", - name: "Viewed", - value: stat.data?.viewsCount, - url: getSiteLink({ - subdomain, - }), - }, - { - icon: "icon-[mingcute--history-line]", - name: "Site Duration", - value: - date.dayjs().diff(date.dayjs(stat.data?.createdAt), "day") + - " " + - t("days"), - url: `${CSB_SCAN}/tx/${stat.data?.createTx}`, - }, - ] - - const pages = useGetPagesBySite({ - type: "post", - characterId: 32022, - limit: 4, - }) - - const showcaseSites = useGetShowcase() - - return ( - -
-
-
- {statMap.map((item) => ( - - - - {t(item.name)} - - {item.value} - - ))} -
-
- , - }} - ns="dashboard" - /> -
    -
  • - - {t("View Site")} - -
  • -
  • - - {t("Create a Post")} - -
  • -
  • - - {t("Change Site Icon or domain")} - -
  • -
- , - }} - ns="dashboard" - /> -
    -
  • - - {t("Check out the updates of other bloggers")} - -
  • -
  • - - {t("Join xLog's Discord channel")} - -
  • -
  • - - {t("Participate in the development of xLog")} - -
  • -
  • - - {t("Follow xLog's Twitter")} - -
  • -
-
-
-
-
-
- -
- {t("More")} -
-
-

- {t("xLog News")} -

-
- {pages.data?.pages[0]?.list.map((item) => ( - - {item.metadata?.content?.cover && ( -
- cover -
- )} - - {item.metadata?.content?.title} - -
- ))} -
-
-
-

- {t("Meet New Friends")} -

-
    - {showcaseSites.data?.slice(0, 6)?.map((site) => ( -
  • - - - - {site.handle} - - - - - {site.metadata.content?.name} - - {site.metadata.content?.bio && ( - - {site.metadata.content?.bio} - - )} - - -
  • - ))} -
-
-
-
-
- ) + return } diff --git a/src/app/dashboard/[subdomain]/pages/page.tsx b/src/app/dashboard/[subdomain]/pages/page.tsx index e4b17db4..a0c6d31b 100644 --- a/src/app/dashboard/[subdomain]/pages/page.tsx +++ b/src/app/dashboard/[subdomain]/pages/page.tsx @@ -1,5 +1,3 @@ -"use client" - import { PagesManager } from "~/components/dashboard/PagesManager" export default function SubdomainPages() { diff --git a/src/app/dashboard/[subdomain]/posts/page.tsx b/src/app/dashboard/[subdomain]/posts/page.tsx index 2ba92c48..51cc1b40 100644 --- a/src/app/dashboard/[subdomain]/posts/page.tsx +++ b/src/app/dashboard/[subdomain]/posts/page.tsx @@ -1,5 +1,3 @@ -"use client" - import { PagesManager } from "~/components/dashboard/PagesManager" export default function SubdomainPosts() { diff --git a/src/app/dashboard/[subdomain]/settings/css/page-component.tsx b/src/app/dashboard/[subdomain]/settings/css/page-component.tsx new file mode 100644 index 00000000..c26c55bf --- /dev/null +++ b/src/app/dashboard/[subdomain]/settings/css/page-component.tsx @@ -0,0 +1,117 @@ +"use client" + +import { useParams } from "next/navigation" +import { useEffect, useState } from "react" +import toast from "react-hot-toast" + +import { MonacoEditor } from "~/components/common/Monaco" +import { SettingsLayout } from "~/components/dashboard/SettingsLayout" +import { Button } from "~/components/ui/Button" +import { FieldLabel } from "~/components/ui/FieldLabel" +import { useTranslation } from "~/lib/i18n/client" +import { useGetSite, useUpdateSite } from "~/queries/site" + +export default function SettingsCSSPage() { + const params = useParams() + const subdomain = params?.subdomain as string + + const updateSite = useUpdateSite() + const site = useGetSite(subdomain) + const { t } = useTranslation("dashboard") + + const [css, setCss] = useState("") + const handleSubmit = (e: any) => { + e.preventDefault() + updateSite.mutate({ + characterId: site.data?.characterId, + css: css, + }) + } + + useEffect(() => { + if (updateSite.isSuccess) { + toast.success("Saved!") + updateSite.reset() + } else if (updateSite.isError) { + toast.error("Failed to update site") + updateSite.reset() + } + }, [updateSite.isSuccess, updateSite.isError]) + + const [hasSet, setHasSet] = useState(false) + useEffect(() => { + if (site.isSuccess && site.data && !css && !hasSet) { + setCss(site.data.metadata?.content?.css || "") + setHasSet(true) + } + }, [site.data, site.isSuccess, css, hasSet]) + + return ( + +
+
+
+

{t("Tips")}:

+

+ {t( + "Scope: These styles will be applied to your entire blog, including this dashboard.", + )} +

+

+ {t( + "Using a browser plugin that can modify page styles, such as Stylebot, can help with debugging.", + )} +

+

+ {t("Support")} ipfs:// +

+

+ {t("CSS variables: xLog provides some built-in CSS variables")} +

+

+ + --theme-color: #4f46e5; + +

+

+ + --header-height: auto; + +

+

+ + --banner-bg-color: #000; + +

+

+ + --font-fans: ui-sans-serif, system-ui, -apple-system, + BlinkMacSystemFont, "Segoe UI", Roboto, + "Helvetica Neue", Arial, "Noto Sans", + sans-serif, "Apple Color Emoji", "Segoe UI + Emoji", "Segoe UI Symbol", "Noto Color + Emoji"; + +

+
+ + setCss(value || "")} + options={{ + fontSize: 14, + minimap: { enabled: false }, + }} + /> +
+
+ +
+
+
+ ) +} diff --git a/src/app/dashboard/[subdomain]/settings/css/page.tsx b/src/app/dashboard/[subdomain]/settings/css/page.tsx index c26c55bf..ebb318be 100644 --- a/src/app/dashboard/[subdomain]/settings/css/page.tsx +++ b/src/app/dashboard/[subdomain]/settings/css/page.tsx @@ -1,117 +1,5 @@ -"use client" - -import { useParams } from "next/navigation" -import { useEffect, useState } from "react" -import toast from "react-hot-toast" - -import { MonacoEditor } from "~/components/common/Monaco" -import { SettingsLayout } from "~/components/dashboard/SettingsLayout" -import { Button } from "~/components/ui/Button" -import { FieldLabel } from "~/components/ui/FieldLabel" -import { useTranslation } from "~/lib/i18n/client" -import { useGetSite, useUpdateSite } from "~/queries/site" +import PageComponent from "./page-component" export default function SettingsCSSPage() { - const params = useParams() - const subdomain = params?.subdomain as string - - const updateSite = useUpdateSite() - const site = useGetSite(subdomain) - const { t } = useTranslation("dashboard") - - const [css, setCss] = useState("") - const handleSubmit = (e: any) => { - e.preventDefault() - updateSite.mutate({ - characterId: site.data?.characterId, - css: css, - }) - } - - useEffect(() => { - if (updateSite.isSuccess) { - toast.success("Saved!") - updateSite.reset() - } else if (updateSite.isError) { - toast.error("Failed to update site") - updateSite.reset() - } - }, [updateSite.isSuccess, updateSite.isError]) - - const [hasSet, setHasSet] = useState(false) - useEffect(() => { - if (site.isSuccess && site.data && !css && !hasSet) { - setCss(site.data.metadata?.content?.css || "") - setHasSet(true) - } - }, [site.data, site.isSuccess, css, hasSet]) - - return ( - -
-
-
-

{t("Tips")}:

-

- {t( - "Scope: These styles will be applied to your entire blog, including this dashboard.", - )} -

-

- {t( - "Using a browser plugin that can modify page styles, such as Stylebot, can help with debugging.", - )} -

-

- {t("Support")} ipfs:// -

-

- {t("CSS variables: xLog provides some built-in CSS variables")} -

-

- - --theme-color: #4f46e5; - -

-

- - --header-height: auto; - -

-

- - --banner-bg-color: #000; - -

-

- - --font-fans: ui-sans-serif, system-ui, -apple-system, - BlinkMacSystemFont, "Segoe UI", Roboto, - "Helvetica Neue", Arial, "Noto Sans", - sans-serif, "Apple Color Emoji", "Segoe UI - Emoji", "Segoe UI Symbol", "Noto Color - Emoji"; - -

-
- - setCss(value || "")} - options={{ - fontSize: 14, - minimap: { enabled: false }, - }} - /> -
-
- -
-
-
- ) + return } diff --git a/src/app/dashboard/[subdomain]/settings/domains/page-component.tsx b/src/app/dashboard/[subdomain]/settings/domains/page-component.tsx new file mode 100644 index 00000000..b974838d --- /dev/null +++ b/src/app/dashboard/[subdomain]/settings/domains/page-component.tsx @@ -0,0 +1,309 @@ +"use client" + +import { useParams, useRouter } from "next/navigation" +import { useEffect, useState } from "react" +import { useForm } from "react-hook-form" +import toast from "react-hot-toast" + +import { + useAccountState, + useUpgradeEmailAccountModal, + validateHandle, +} from "@crossbell/connect-kit" + +import { SettingsLayout } from "~/components/dashboard/SettingsLayout" +import { Button } from "~/components/ui/Button" +import { Input } from "~/components/ui/Input" +import { UniLink } from "~/components/ui/UniLink" +import { useUserRole } from "~/hooks/useUserRole" +import { OUR_DOMAIN } from "~/lib/env" +import { getSiteLink } from "~/lib/helpers" +import { useTranslation } from "~/lib/i18n/client" +import { checkDomain } from "~/models/site.model" +import { useGetSite, useUpdateHandle, useUpdateSite } from "~/queries/site" + +export default function SettingsDomainsPage() { + const params = useParams() + const subdomain = params?.subdomain as string + + const updateSite = useUpdateSite() + const updateHandle = useUpdateHandle() + const site = useGetSite(subdomain) + const userRole = useUserRole(subdomain) + const { t } = useTranslation("dashboard") + const router = useRouter() + + const isEmailAccount = useAccountState( + (s) => s.computed.account?.type === "email", + ) + const upgradeAccountModal = useUpgradeEmailAccountModal() + + const form = useForm({ + defaultValues: { + subdomain: "", + custom_domain: "", + }, + }) + + const handleSubmit = form.handleSubmit((values) => { + if (site.data?.metadata?.content?.custom_domain !== values.custom_domain) { + updateSite.mutate({ + characterId: site.data?.characterId, + custom_domain: values.custom_domain, + }) + } + if (subdomain !== values.subdomain) { + updateHandle.mutate({ + characterId: site.data?.characterId, + handle: values.subdomain, + }) + } + }) + + const [customDomain, setCustomDomain] = useState("") + form.register("custom_domain", { + onChange: (e) => { + setCustomDomain(e.target.value) + toCheckDomain(e.target.value) + }, + }) + + const customSubdomain = customDomain?.split(".").slice(0, -2).join(".") || "" + + useEffect(() => { + if (!updateSite.isLoading && !updateHandle.isLoading) { + if (updateSite.isError || updateHandle.isError) { + toast.error("Failed to update site") + } else if (updateSite.isSuccess || updateHandle.isSuccess) { + toast.success("Saved!") + if (updateHandle.isSuccess) { + useAccountState + .getState() + .refresh() + .then(() => { + router.replace( + `/dashboard/${updateHandle.variables?.handle}/settings/domains`, + ) + }) + } + } + } + }, [ + updateSite.isSuccess, + updateSite.isLoading, + updateHandle.isSuccess, + updateHandle.isLoading, + ]) + + const [domainCheckResult, setDomainCheckResult] = useState<{ + isLoading: boolean + data?: boolean + }>({ + isLoading: false, + data: true, + }) + + // eslint-disable-next-line react-hooks/exhaustive-deps + const toCheckDomain = (custom: string) => { + if (custom) { + setDomainCheckResult({ + isLoading: true, + }) + checkDomain(custom, form.getValues().subdomain).then((r) => + setDomainCheckResult({ + isLoading: false, + data: r, + }), + ) + } + } + + const [subdomainCheckResult, setSubdomainCheckResult] = useState<{ + isLoading: boolean + data?: boolean + error?: string + }>({ + isLoading: false, + data: true, + error: "", + }) + const toCheckSubdomain = (subdomain: string) => { + if (subdomain) { + setSubdomainCheckResult({ + isLoading: true, + }) + validateHandle(subdomain).then(({ isValid, error, errorMsg }) => { + setSubdomainCheckResult({ + isLoading: false, + data: isValid, + error: errorMsg, + }) + }) + } + } + + const [subdomainChanged, setSubdomainChanged] = useState(false) + form.register("subdomain", { + onChange: (e) => { + if (e.target.value !== site.data?.handle) { + toCheckSubdomain(e.target.value) + setSubdomainChanged(true) + } else { + setSubdomainChanged(false) + } + }, + }) + + const [hasSet, setHasSet] = useState(false) + useEffect(() => { + if (site.isSuccess && site.data && !hasSet) { + setHasSet(true) + form.setValue("subdomain", site.data.handle || "") + form.setValue( + "custom_domain", + site.data.metadata?.content?.custom_domain || "", + ) + setCustomDomain(site.data.metadata?.content?.custom_domain || "") + toCheckDomain(site.data.metadata?.content?.custom_domain || "") + } + }, [form, site.data, site.isSuccess, customDomain, hasSet, toCheckDomain]) + + return ( + +
+
+ + {subdomainChanged && ( +
+ {subdomainCheckResult.isLoading ? ( + {t("Subdomain Checking")}... + ) : ( + + {t( + subdomainCheckResult.data + ? "Subdomain Available." + : subdomainCheckResult.error || "Subdomain Unavailable.", + )} + + )} +
+ )} + {isEmailAccount && ( +
+ Email users cannot change subdomain/handle.{" "} + + Learn more + {" "} + or{" "} + + upgrade account + + . +
+ )} + {userRole.data === "operator" && ( +
+ Operators cannot change subdomain/handle. Please contact the site + owner. +
+ )} +
+
+ + {customDomain && ( +
+

+ {t( + "Set the following record on your DNS provider to active your custom domain", + )} + : +

+ + + + + + + + + + + + + + + + + + +
TypeNameValue
CNAME + {customSubdomain || "@"} + cname.{OUR_DOMAIN}
TXT{`_xlog-challenge${ + customSubdomain ? `.${customSubdomain}` : customSubdomain + }`}{subdomain}
+
+ {domainCheckResult.isLoading ? ( + {t("DNS Checking")}... + ) : domainCheckResult.data ? ( + + {t("DNS check passed.")} + + ) : ( + + + {t("DNS check failed.")} + + + + )} +
+
+ )} +
+
+ +
+
+
+ ) +} diff --git a/src/app/dashboard/[subdomain]/settings/domains/page.tsx b/src/app/dashboard/[subdomain]/settings/domains/page.tsx index b974838d..1aa97b5f 100644 --- a/src/app/dashboard/[subdomain]/settings/domains/page.tsx +++ b/src/app/dashboard/[subdomain]/settings/domains/page.tsx @@ -1,309 +1,5 @@ -"use client" - -import { useParams, useRouter } from "next/navigation" -import { useEffect, useState } from "react" -import { useForm } from "react-hook-form" -import toast from "react-hot-toast" - -import { - useAccountState, - useUpgradeEmailAccountModal, - validateHandle, -} from "@crossbell/connect-kit" - -import { SettingsLayout } from "~/components/dashboard/SettingsLayout" -import { Button } from "~/components/ui/Button" -import { Input } from "~/components/ui/Input" -import { UniLink } from "~/components/ui/UniLink" -import { useUserRole } from "~/hooks/useUserRole" -import { OUR_DOMAIN } from "~/lib/env" -import { getSiteLink } from "~/lib/helpers" -import { useTranslation } from "~/lib/i18n/client" -import { checkDomain } from "~/models/site.model" -import { useGetSite, useUpdateHandle, useUpdateSite } from "~/queries/site" +import PageComponent from "./page-component" export default function SettingsDomainsPage() { - const params = useParams() - const subdomain = params?.subdomain as string - - const updateSite = useUpdateSite() - const updateHandle = useUpdateHandle() - const site = useGetSite(subdomain) - const userRole = useUserRole(subdomain) - const { t } = useTranslation("dashboard") - const router = useRouter() - - const isEmailAccount = useAccountState( - (s) => s.computed.account?.type === "email", - ) - const upgradeAccountModal = useUpgradeEmailAccountModal() - - const form = useForm({ - defaultValues: { - subdomain: "", - custom_domain: "", - }, - }) - - const handleSubmit = form.handleSubmit((values) => { - if (site.data?.metadata?.content?.custom_domain !== values.custom_domain) { - updateSite.mutate({ - characterId: site.data?.characterId, - custom_domain: values.custom_domain, - }) - } - if (subdomain !== values.subdomain) { - updateHandle.mutate({ - characterId: site.data?.characterId, - handle: values.subdomain, - }) - } - }) - - const [customDomain, setCustomDomain] = useState("") - form.register("custom_domain", { - onChange: (e) => { - setCustomDomain(e.target.value) - toCheckDomain(e.target.value) - }, - }) - - const customSubdomain = customDomain?.split(".").slice(0, -2).join(".") || "" - - useEffect(() => { - if (!updateSite.isLoading && !updateHandle.isLoading) { - if (updateSite.isError || updateHandle.isError) { - toast.error("Failed to update site") - } else if (updateSite.isSuccess || updateHandle.isSuccess) { - toast.success("Saved!") - if (updateHandle.isSuccess) { - useAccountState - .getState() - .refresh() - .then(() => { - router.replace( - `/dashboard/${updateHandle.variables?.handle}/settings/domains`, - ) - }) - } - } - } - }, [ - updateSite.isSuccess, - updateSite.isLoading, - updateHandle.isSuccess, - updateHandle.isLoading, - ]) - - const [domainCheckResult, setDomainCheckResult] = useState<{ - isLoading: boolean - data?: boolean - }>({ - isLoading: false, - data: true, - }) - - // eslint-disable-next-line react-hooks/exhaustive-deps - const toCheckDomain = (custom: string) => { - if (custom) { - setDomainCheckResult({ - isLoading: true, - }) - checkDomain(custom, form.getValues().subdomain).then((r) => - setDomainCheckResult({ - isLoading: false, - data: r, - }), - ) - } - } - - const [subdomainCheckResult, setSubdomainCheckResult] = useState<{ - isLoading: boolean - data?: boolean - error?: string - }>({ - isLoading: false, - data: true, - error: "", - }) - const toCheckSubdomain = (subdomain: string) => { - if (subdomain) { - setSubdomainCheckResult({ - isLoading: true, - }) - validateHandle(subdomain).then(({ isValid, error, errorMsg }) => { - setSubdomainCheckResult({ - isLoading: false, - data: isValid, - error: errorMsg, - }) - }) - } - } - - const [subdomainChanged, setSubdomainChanged] = useState(false) - form.register("subdomain", { - onChange: (e) => { - if (e.target.value !== site.data?.handle) { - toCheckSubdomain(e.target.value) - setSubdomainChanged(true) - } else { - setSubdomainChanged(false) - } - }, - }) - - const [hasSet, setHasSet] = useState(false) - useEffect(() => { - if (site.isSuccess && site.data && !hasSet) { - setHasSet(true) - form.setValue("subdomain", site.data.handle || "") - form.setValue( - "custom_domain", - site.data.metadata?.content?.custom_domain || "", - ) - setCustomDomain(site.data.metadata?.content?.custom_domain || "") - toCheckDomain(site.data.metadata?.content?.custom_domain || "") - } - }, [form, site.data, site.isSuccess, customDomain, hasSet, toCheckDomain]) - - return ( - -
-
- - {subdomainChanged && ( -
- {subdomainCheckResult.isLoading ? ( - {t("Subdomain Checking")}... - ) : ( - - {t( - subdomainCheckResult.data - ? "Subdomain Available." - : subdomainCheckResult.error || "Subdomain Unavailable.", - )} - - )} -
- )} - {isEmailAccount && ( -
- Email users cannot change subdomain/handle.{" "} - - Learn more - {" "} - or{" "} - - upgrade account - - . -
- )} - {userRole.data === "operator" && ( -
- Operators cannot change subdomain/handle. Please contact the site - owner. -
- )} -
-
- - {customDomain && ( -
-

- {t( - "Set the following record on your DNS provider to active your custom domain", - )} - : -

- - - - - - - - - - - - - - - - - - -
TypeNameValue
CNAME - {customSubdomain || "@"} - cname.{OUR_DOMAIN}
TXT{`_xlog-challenge${ - customSubdomain ? `.${customSubdomain}` : customSubdomain - }`}{subdomain}
-
- {domainCheckResult.isLoading ? ( - {t("DNS Checking")}... - ) : domainCheckResult.data ? ( - - {t("DNS check passed.")} - - ) : ( - - - {t("DNS check failed.")} - - - - )} -
-
- )} -
-
- -
-
-
- ) + return } diff --git a/src/app/dashboard/[subdomain]/settings/general/page-component.tsx b/src/app/dashboard/[subdomain]/settings/general/page-component.tsx new file mode 100644 index 00000000..fb4e8029 --- /dev/null +++ b/src/app/dashboard/[subdomain]/settings/general/page-component.tsx @@ -0,0 +1,294 @@ +"use client" + +import { useParams } from "next/navigation" +import { useEffect, useState } from "react" +import { Controller, useForm } from "react-hook-form" +import toast from "react-hot-toast" + +import { SettingsLayout } from "~/components/dashboard/SettingsLayout" +import { Button } from "~/components/ui/Button" +import { ImageUploader } from "~/components/ui/ImageUploader" +import { Input } from "~/components/ui/Input" +import { UniLink } from "~/components/ui/UniLink" +import { Trans, useTranslation } from "~/lib/i18n/client" +import { toIPFS } from "~/lib/ipfs-parser" +import { useGetSite, useUpdateSite } from "~/queries/site" + +export default function SiteSettingsGeneralPage() { + const params = useParams() + const subdomain = params?.subdomain as string + + const updateSite = useUpdateSite() + const site = useGetSite(subdomain) + const { t, i18n } = useTranslation("dashboard") + + const form = useForm({ + defaultValues: { + icon: "", + banner: undefined, + name: "", + site_name: "", + description: "", + ga: "", + ua: "", + uh: "", + } as { + icon: string + banner?: { + address: string + mime_type: string + } + name: string + site_name: string + description: string + ga: string + ua: string + uh: string + }, + }) + + const handleSubmit = form.handleSubmit((values) => { + updateSite.mutate({ + characterId: site.data?.characterId, + icon: values.icon, + banner: values.banner, + name: values.name, + site_name: values.site_name, + description: values.description, + ga: values.ga, + ua: values.ua, + uh: values.uh, + }) + }) + + useEffect(() => { + if (updateSite.isSuccess) { + toast.success("Site updated") + } else if (updateSite.isError) { + toast.error("Failed to update site") + } + }, [updateSite.isSuccess, updateSite.isError]) + + useEffect(() => { + if (site.data) { + !form.getValues("icon") && + form.setValue( + "icon", + toIPFS(site.data?.metadata?.content?.avatars?.[0] || ""), + ) + !form.getValues("banner") && + form.setValue( + "banner", + site.data?.metadata?.content?.banners?.[0]?.address + ? { + address: toIPFS( + site.data?.metadata?.content?.banners?.[0].address || "", + ), + mime_type: site.data?.metadata?.content?.banners?.[0].mime_type, + } + : undefined, + ) + !form.getValues("name") && + form.setValue("name", site.data.metadata?.content?.name || "") + !form.getValues("site_name") && + form.setValue("site_name", site.data.metadata?.content?.site_name || "") + !form.getValues("description") && + form.setValue("description", site.data.metadata?.content?.bio || "") + !form.getValues("ga") && + form.setValue("ga", site.data.metadata?.content?.ga || "") + !form.getValues("ua") && + form.setValue("ua", site.data.metadata?.content?.ua || "") + !form.getValues("uh") && + form.setValue("uh", site.data.metadata?.content?.uh || "") + } + }, [site.data, form]) + + const [iconUploading, setIconUploading] = useState(false) + const [bannerUploading, setBannerUploading] = useState(false) + + return ( + +
+
+ + ( + { + setIconUploading(true) + }} + uploadEnd={(key) => { + form.setValue("icon", key as string) + setIconUploading(false) + }} + accept="image/*" + {...field} + /> + )} + /> +
+
+ + ( +
+
+ +
+
+ +
+
+ + +
+
+ + + Integrate Google Analytics into your site. You can follow the + instructions{" "} + + here + {" "} + to find your Measurement ID. + +

+ } + /> +
+
+ + + Leave blank to use{" "} + + the Umami Cloud + + . + +

+ } + /> + + + Integrate Umami Cloud Analytics into your site. You can follow + the instructions{" "} + + here + {" "} + to find your Website ID. + +

+ } + /> +
+
+ +
+
+ {/*
+

Danger Zone

+
+ +
+
*/} +
+ ) +} diff --git a/src/app/dashboard/[subdomain]/settings/general/page.tsx b/src/app/dashboard/[subdomain]/settings/general/page.tsx index fb4e8029..a186c94e 100644 --- a/src/app/dashboard/[subdomain]/settings/general/page.tsx +++ b/src/app/dashboard/[subdomain]/settings/general/page.tsx @@ -1,294 +1,5 @@ -"use client" - -import { useParams } from "next/navigation" -import { useEffect, useState } from "react" -import { Controller, useForm } from "react-hook-form" -import toast from "react-hot-toast" - -import { SettingsLayout } from "~/components/dashboard/SettingsLayout" -import { Button } from "~/components/ui/Button" -import { ImageUploader } from "~/components/ui/ImageUploader" -import { Input } from "~/components/ui/Input" -import { UniLink } from "~/components/ui/UniLink" -import { Trans, useTranslation } from "~/lib/i18n/client" -import { toIPFS } from "~/lib/ipfs-parser" -import { useGetSite, useUpdateSite } from "~/queries/site" +import PageComponent from "./page-component" export default function SiteSettingsGeneralPage() { - const params = useParams() - const subdomain = params?.subdomain as string - - const updateSite = useUpdateSite() - const site = useGetSite(subdomain) - const { t, i18n } = useTranslation("dashboard") - - const form = useForm({ - defaultValues: { - icon: "", - banner: undefined, - name: "", - site_name: "", - description: "", - ga: "", - ua: "", - uh: "", - } as { - icon: string - banner?: { - address: string - mime_type: string - } - name: string - site_name: string - description: string - ga: string - ua: string - uh: string - }, - }) - - const handleSubmit = form.handleSubmit((values) => { - updateSite.mutate({ - characterId: site.data?.characterId, - icon: values.icon, - banner: values.banner, - name: values.name, - site_name: values.site_name, - description: values.description, - ga: values.ga, - ua: values.ua, - uh: values.uh, - }) - }) - - useEffect(() => { - if (updateSite.isSuccess) { - toast.success("Site updated") - } else if (updateSite.isError) { - toast.error("Failed to update site") - } - }, [updateSite.isSuccess, updateSite.isError]) - - useEffect(() => { - if (site.data) { - !form.getValues("icon") && - form.setValue( - "icon", - toIPFS(site.data?.metadata?.content?.avatars?.[0] || ""), - ) - !form.getValues("banner") && - form.setValue( - "banner", - site.data?.metadata?.content?.banners?.[0]?.address - ? { - address: toIPFS( - site.data?.metadata?.content?.banners?.[0].address || "", - ), - mime_type: site.data?.metadata?.content?.banners?.[0].mime_type, - } - : undefined, - ) - !form.getValues("name") && - form.setValue("name", site.data.metadata?.content?.name || "") - !form.getValues("site_name") && - form.setValue("site_name", site.data.metadata?.content?.site_name || "") - !form.getValues("description") && - form.setValue("description", site.data.metadata?.content?.bio || "") - !form.getValues("ga") && - form.setValue("ga", site.data.metadata?.content?.ga || "") - !form.getValues("ua") && - form.setValue("ua", site.data.metadata?.content?.ua || "") - !form.getValues("uh") && - form.setValue("uh", site.data.metadata?.content?.uh || "") - } - }, [site.data, form]) - - const [iconUploading, setIconUploading] = useState(false) - const [bannerUploading, setBannerUploading] = useState(false) - - return ( - -
-
- - ( - { - setIconUploading(true) - }} - uploadEnd={(key) => { - form.setValue("icon", key as string) - setIconUploading(false) - }} - accept="image/*" - {...field} - /> - )} - /> -
-
- - ( -
-
- -
-
- -
-
- - -
-
- - - Integrate Google Analytics into your site. You can follow the - instructions{" "} - - here - {" "} - to find your Measurement ID. - -

- } - /> -
-
- - - Leave blank to use{" "} - - the Umami Cloud - - . - -

- } - /> - - - Integrate Umami Cloud Analytics into your site. You can follow - the instructions{" "} - - here - {" "} - to find your Website ID. - -

- } - /> -
-
- -
-
- {/*
-

Danger Zone

-
- -
-
*/} -
- ) + return } diff --git a/src/app/dashboard/[subdomain]/settings/navigation/page-component.tsx b/src/app/dashboard/[subdomain]/settings/navigation/page-component.tsx new file mode 100644 index 00000000..3a895f86 --- /dev/null +++ b/src/app/dashboard/[subdomain]/settings/navigation/page-component.tsx @@ -0,0 +1,198 @@ +"use client" + +import equal from "fast-deep-equal" +import { nanoid } from "nanoid" +import { useParams } from "next/navigation" +import { ChangeEvent, FormEvent, useEffect, useMemo, useState } from "react" +import toast from "react-hot-toast" +import { ReactSortable } from "react-sortablejs" + +import { SettingsLayout } from "~/components/dashboard/SettingsLayout" +import { Button } from "~/components/ui/Button" +import { Input } from "~/components/ui/Input" +import { useTranslation } from "~/lib/i18n/client" +import { SiteNavigationItem } from "~/lib/types" +import { useGetSite, useUpdateSite } from "~/queries/site" + +type UpdateItem = (id: string, newItem: Partial) => void + +type RemoveItem = (id: string) => void + +const SortableNavigationItem = ({ + item, + updateItem, + removeItem, +}: { + item: SiteNavigationItem + updateItem: UpdateItem + removeItem: RemoveItem +}) => { + const { t } = useTranslation("dashboard") + return ( +
+
+ +
+ ) => + updateItem(item.id, { label: e.target.value }) + } + /> + ) => + updateItem(item.id, { url: e.target.value }) + } + /> +
+ +
+
+ ) +} + +export default function SiteSettingsNavigationPage() { + const params = useParams() + const subdomain = params?.subdomain as string + + const updateSite = useUpdateSite() + const site = useGetSite(subdomain) + const { t } = useTranslation("dashboard") + + const [items, setItems] = useState([]) + + const itemsModified = useMemo(() => { + if (!site.isSuccess) return false + return !equal(items, site.data?.metadata?.content?.navigation) + }, [items, site.data, site.isSuccess]) + + const updateItem: UpdateItem = (id, newItem) => { + setItems((items) => { + return items.map((item) => { + if (item.id === id) { + return { ...item, ...newItem } + } + return item + }) + }) + } + + const newEmptyItem = () => { + setItems((items) => [...items, { id: nanoid(), label: "", url: "" }]) + } + + const handleSubmit = (e: FormEvent) => { + e.preventDefault() + if (site.data?.handle) { + updateSite.mutate({ + characterId: site.data?.characterId, + navigation: items, + }) + } + } + + useEffect(() => { + if (updateSite.isSuccess) { + toast.success("Saved") + } else if (updateSite.isError) { + toast.error("Failed to save") + } + }, [updateSite.isSuccess, updateSite.isError]) + + const removeItem: RemoveItem = (id) => { + setItems((items) => items.filter((item) => item.id !== id)) + } + + const [hasSet, setHasSet] = useState(false) + useEffect(() => { + if (site.data?.metadata?.content?.navigation && !hasSet) { + setHasSet(true) + setItems(site.data?.metadata?.content?.navigation) + } + }, [site.data?.metadata?.content?.navigation, hasSet]) + + return ( + +
+

{t("Tips")}:

+

+ + {t("xLog provides some out-of-the-box built-in pages")}: + +

+

+ - {t("Home page")}:{" "} + / +

+

+ - {t("Archives page")}:{" "} + /archives +

+

+ - {t("Tag page")}:{" "} + /tag/[tag] +

+

+ - {t("NFT Showcase page")}:{" "} + /nft +

+
+
+
+ {items.length === 0 && ( +
+ No navigation items yet +
+ )} + + {items.map((item) => { + return ( + + ) + })} + {/* eslint-disable-next-line react/no-unknown-property */} + + +
+
+ + +
+
+
+ ) +} diff --git a/src/app/dashboard/[subdomain]/settings/navigation/page.tsx b/src/app/dashboard/[subdomain]/settings/navigation/page.tsx index 3a895f86..fc708a55 100644 --- a/src/app/dashboard/[subdomain]/settings/navigation/page.tsx +++ b/src/app/dashboard/[subdomain]/settings/navigation/page.tsx @@ -1,198 +1,5 @@ -"use client" - -import equal from "fast-deep-equal" -import { nanoid } from "nanoid" -import { useParams } from "next/navigation" -import { ChangeEvent, FormEvent, useEffect, useMemo, useState } from "react" -import toast from "react-hot-toast" -import { ReactSortable } from "react-sortablejs" - -import { SettingsLayout } from "~/components/dashboard/SettingsLayout" -import { Button } from "~/components/ui/Button" -import { Input } from "~/components/ui/Input" -import { useTranslation } from "~/lib/i18n/client" -import { SiteNavigationItem } from "~/lib/types" -import { useGetSite, useUpdateSite } from "~/queries/site" - -type UpdateItem = (id: string, newItem: Partial) => void - -type RemoveItem = (id: string) => void - -const SortableNavigationItem = ({ - item, - updateItem, - removeItem, -}: { - item: SiteNavigationItem - updateItem: UpdateItem - removeItem: RemoveItem -}) => { - const { t } = useTranslation("dashboard") - return ( -
-
- -
- ) => - updateItem(item.id, { label: e.target.value }) - } - /> - ) => - updateItem(item.id, { url: e.target.value }) - } - /> -
- -
-
- ) -} +import PageComponent from "./page-component" export default function SiteSettingsNavigationPage() { - const params = useParams() - const subdomain = params?.subdomain as string - - const updateSite = useUpdateSite() - const site = useGetSite(subdomain) - const { t } = useTranslation("dashboard") - - const [items, setItems] = useState([]) - - const itemsModified = useMemo(() => { - if (!site.isSuccess) return false - return !equal(items, site.data?.metadata?.content?.navigation) - }, [items, site.data, site.isSuccess]) - - const updateItem: UpdateItem = (id, newItem) => { - setItems((items) => { - return items.map((item) => { - if (item.id === id) { - return { ...item, ...newItem } - } - return item - }) - }) - } - - const newEmptyItem = () => { - setItems((items) => [...items, { id: nanoid(), label: "", url: "" }]) - } - - const handleSubmit = (e: FormEvent) => { - e.preventDefault() - if (site.data?.handle) { - updateSite.mutate({ - characterId: site.data?.characterId, - navigation: items, - }) - } - } - - useEffect(() => { - if (updateSite.isSuccess) { - toast.success("Saved") - } else if (updateSite.isError) { - toast.error("Failed to save") - } - }, [updateSite.isSuccess, updateSite.isError]) - - const removeItem: RemoveItem = (id) => { - setItems((items) => items.filter((item) => item.id !== id)) - } - - const [hasSet, setHasSet] = useState(false) - useEffect(() => { - if (site.data?.metadata?.content?.navigation && !hasSet) { - setHasSet(true) - setItems(site.data?.metadata?.content?.navigation) - } - }, [site.data?.metadata?.content?.navigation, hasSet]) - - return ( - -
-

{t("Tips")}:

-

- - {t("xLog provides some out-of-the-box built-in pages")}: - -

-

- - {t("Home page")}:{" "} - / -

-

- - {t("Archives page")}:{" "} - /archives -

-

- - {t("Tag page")}:{" "} - /tag/[tag] -

-

- - {t("NFT Showcase page")}:{" "} - /nft -

-
-
-
- {items.length === 0 && ( -
- No navigation items yet -
- )} - - {items.map((item) => { - return ( - - ) - })} - {/* eslint-disable-next-line react/no-unknown-property */} - - -
-
- - -
-
-
- ) + return } diff --git a/src/app/dashboard/[subdomain]/settings/operator/page-component.tsx b/src/app/dashboard/[subdomain]/settings/operator/page-component.tsx new file mode 100644 index 00000000..5452e6f8 --- /dev/null +++ b/src/app/dashboard/[subdomain]/settings/operator/page-component.tsx @@ -0,0 +1,267 @@ +"use client" + +import { useParams } from "next/navigation" +import { useEffect, useState } from "react" +import toast from "react-hot-toast" + +import { + useAccountState, + useUpgradeEmailAccountModal, +} from "@crossbell/connect-kit" +import { Dialog } from "@headlessui/react" + +import { CharacterCard } from "~/components/common/CharacterCard" +import { SettingsLayout } from "~/components/dashboard/SettingsLayout" +import { Button } from "~/components/ui/Button" +import { Input } from "~/components/ui/Input" +import { UniLink } from "~/components/ui/UniLink" +import { useUserRole } from "~/hooks/useUserRole" +import { getSiteLink } from "~/lib/helpers" +import { useTranslation } from "~/lib/i18n/client" +import { + useAddOperator, + useGetOperators, + useGetSite, + useRemoveOperator, +} from "~/queries/site" + +type RemoveItem = (operator: string) => void + +const SortableNavigationItem = ({ + item, + removeItem, + isLoading, + disabled, +}: { + item: string + removeItem: RemoveItem + isLoading: boolean + disabled?: boolean +}) => { + const { t } = useTranslation("dashboard") + return ( +
+
+
+ {t("Address")}: {item} +
+
{t("Character")}:
+ +
+
+ +
+
+ ) +} + +export default function SettingsOperatorPage() { + const params = useParams() + const subdomain = params?.subdomain as string + + const addOperator = useAddOperator() + const removeOperator = useRemoveOperator() + const site = useGetSite(subdomain) + const operators = useGetOperators({ + characterId: site.data?.characterId, + }) + const isEmailAccount = useAccountState( + (s) => s.computed.account?.type === "email", + ) + const upgradeAccountModal = useUpgradeEmailAccountModal() + const userRole = useUserRole(subdomain) + const { t } = useTranslation("dashboard") + + const [items, setItems] = useState([]) + + const newEmptyItem = () => { + setIsOpen(true) + setAddress("") + } + + useEffect(() => { + if (addOperator.isSuccess) { + toast.success("Operator added") + } else if (addOperator.isError) { + toast.error("Failed to add operator") + } + setIsOpen(false) + }, [addOperator.isSuccess, addOperator.isError]) + + useEffect(() => { + if (removeOperator.isSuccess) { + toast.success("Operator removed") + } else if (removeOperator.isError) { + toast.error("Failed to remove operator") + } + }, [removeOperator.isSuccess, removeOperator.isError]) + + const removeItem: RemoveItem = (operator) => { + removeOperator.mutate({ + characterId: site.data?.characterId, + operator: operator, + }) + } + const addItem = () => { + if (address) { + addOperator.mutate({ + characterId: site.data?.characterId, + operator: address, + }) + } + } + + useEffect(() => { + setItems(operators.data?.list.map((o) => o.operator) || []) + }, [operators.data]) + + const [isOpen, setIsOpen] = useState(false) + const [address, setAddress] = useState("") + + return ( + + setIsOpen(false)} + className="fixed z-10 inset-0 overflow-y-auto" + > +
+ + +
+ + {t("New operator")} + + +
+ { + setAddress(e.target.value) + }} + /> +
+ {t("Operator Character Check")} +
+
+ +
+
+ +
+ +
+
+
+
+
+

⚠️ {t("Warning")}:

+

+ + {isEmailAccount && ( + + Email users cannot set operators.{" "} + + Learn more + {" "} + or{" "} + + upgrade account + + . + + )} + {userRole.data === "operator" && ( + + Operators cannot set other operators. Please contact the site + owner. + + )} + {!isEmailAccount && userRole.data !== "operator" && ( + + {t( + "Operators have permissions to enter your dashboard, change your settings(excluding xLog subdomain) and post, modify, delete contents on your site.", + )} + + )} + +

+
+
+
+ {items.length === 0 && ( +
+ No operators yet +
+ )} + {items.map((item, index) => { + return ( + + ) + })} + {/* eslint-disable-next-line react/no-unknown-property */} + +
+
+ +
+
+
+ ) +} diff --git a/src/app/dashboard/[subdomain]/settings/operator/page.tsx b/src/app/dashboard/[subdomain]/settings/operator/page.tsx index 5452e6f8..bb50e70a 100644 --- a/src/app/dashboard/[subdomain]/settings/operator/page.tsx +++ b/src/app/dashboard/[subdomain]/settings/operator/page.tsx @@ -1,267 +1,5 @@ -"use client" - -import { useParams } from "next/navigation" -import { useEffect, useState } from "react" -import toast from "react-hot-toast" - -import { - useAccountState, - useUpgradeEmailAccountModal, -} from "@crossbell/connect-kit" -import { Dialog } from "@headlessui/react" - -import { CharacterCard } from "~/components/common/CharacterCard" -import { SettingsLayout } from "~/components/dashboard/SettingsLayout" -import { Button } from "~/components/ui/Button" -import { Input } from "~/components/ui/Input" -import { UniLink } from "~/components/ui/UniLink" -import { useUserRole } from "~/hooks/useUserRole" -import { getSiteLink } from "~/lib/helpers" -import { useTranslation } from "~/lib/i18n/client" -import { - useAddOperator, - useGetOperators, - useGetSite, - useRemoveOperator, -} from "~/queries/site" - -type RemoveItem = (operator: string) => void - -const SortableNavigationItem = ({ - item, - removeItem, - isLoading, - disabled, -}: { - item: string - removeItem: RemoveItem - isLoading: boolean - disabled?: boolean -}) => { - const { t } = useTranslation("dashboard") - return ( -
-
-
- {t("Address")}: {item} -
-
{t("Character")}:
- -
-
- -
-
- ) -} +import PageComponent from "./page-component" export default function SettingsOperatorPage() { - const params = useParams() - const subdomain = params?.subdomain as string - - const addOperator = useAddOperator() - const removeOperator = useRemoveOperator() - const site = useGetSite(subdomain) - const operators = useGetOperators({ - characterId: site.data?.characterId, - }) - const isEmailAccount = useAccountState( - (s) => s.computed.account?.type === "email", - ) - const upgradeAccountModal = useUpgradeEmailAccountModal() - const userRole = useUserRole(subdomain) - const { t } = useTranslation("dashboard") - - const [items, setItems] = useState([]) - - const newEmptyItem = () => { - setIsOpen(true) - setAddress("") - } - - useEffect(() => { - if (addOperator.isSuccess) { - toast.success("Operator added") - } else if (addOperator.isError) { - toast.error("Failed to add operator") - } - setIsOpen(false) - }, [addOperator.isSuccess, addOperator.isError]) - - useEffect(() => { - if (removeOperator.isSuccess) { - toast.success("Operator removed") - } else if (removeOperator.isError) { - toast.error("Failed to remove operator") - } - }, [removeOperator.isSuccess, removeOperator.isError]) - - const removeItem: RemoveItem = (operator) => { - removeOperator.mutate({ - characterId: site.data?.characterId, - operator: operator, - }) - } - const addItem = () => { - if (address) { - addOperator.mutate({ - characterId: site.data?.characterId, - operator: address, - }) - } - } - - useEffect(() => { - setItems(operators.data?.list.map((o) => o.operator) || []) - }, [operators.data]) - - const [isOpen, setIsOpen] = useState(false) - const [address, setAddress] = useState("") - - return ( - - setIsOpen(false)} - className="fixed z-10 inset-0 overflow-y-auto" - > -
- - -
- - {t("New operator")} - - -
- { - setAddress(e.target.value) - }} - /> -
- {t("Operator Character Check")} -
-
- -
-
- -
- -
-
-
-
-
-

⚠️ {t("Warning")}:

-

- - {isEmailAccount && ( - - Email users cannot set operators.{" "} - - Learn more - {" "} - or{" "} - - upgrade account - - . - - )} - {userRole.data === "operator" && ( - - Operators cannot set other operators. Please contact the site - owner. - - )} - {!isEmailAccount && userRole.data !== "operator" && ( - - {t( - "Operators have permissions to enter your dashboard, change your settings(excluding xLog subdomain) and post, modify, delete contents on your site.", - )} - - )} - -

-
-
-
- {items.length === 0 && ( -
- No operators yet -
- )} - {items.map((item, index) => { - return ( - - ) - })} - {/* eslint-disable-next-line react/no-unknown-property */} - -
-
- -
-
-
- ) + return } diff --git a/src/app/dashboard/[subdomain]/settings/social-platforms/page-component.tsx b/src/app/dashboard/[subdomain]/settings/social-platforms/page-component.tsx new file mode 100644 index 00000000..66673984 --- /dev/null +++ b/src/app/dashboard/[subdomain]/settings/social-platforms/page-component.tsx @@ -0,0 +1,239 @@ +"use client" + +import equal from "fast-deep-equal" +import { nanoid } from "nanoid" +import { useParams } from "next/navigation" +import { ChangeEvent, FormEvent, useEffect, useMemo, useState } from "react" +import toast from "react-hot-toast" +import { ReactSortable } from "react-sortablejs" + +import { SettingsLayout } from "~/components/dashboard/SettingsLayout" +import { Platform, PlatformsSyncMap } from "~/components/site/Platform" +import { Button } from "~/components/ui/Button" +import { Input } from "~/components/ui/Input" +import { UniLink } from "~/components/ui/UniLink" +import { Trans, useTranslation } from "~/lib/i18n/client" +import { useGetSite, useUpdateSite } from "~/queries/site" + +type Item = { + identity: string + platform: string + url?: string | undefined +} & { + id: string +} + +type UpdateItem = (id: string, newItem: Partial) => void + +type RemoveItem = (id: string) => void + +const SortableNavigationItem = ({ + item, + updateItem, + removeItem, +}: { + item: Item + updateItem: UpdateItem + removeItem: RemoveItem +}) => { + const { t } = useTranslation("dashboard") + return ( +
+
+ +
+ ) => + updateItem(item.id, { platform: e.target.value }) + } + /> + ) => + updateItem(item.id, { identity: e.target.value }) + } + /> +
+ +
+
+ +
+
+ ) +} + +export default function SiteSettingsNavigationPage() { + const params = useParams() + const subdomain = params?.subdomain as string + + const updateSite = useUpdateSite() + const site = useGetSite(subdomain) + const { t, i18n } = useTranslation("dashboard") + + const [items, setItems] = useState([]) + + const itemsModified = useMemo(() => { + if (!site.isSuccess) return false + return !equal(items, site.data?.metadata?.content?.connected_accounts) + }, [items, site.data, site.isSuccess]) + + const updateItem: UpdateItem = (id, newItem) => { + setItems((items) => { + return items.map((item) => { + if (item.id === id) { + return { ...item, ...newItem } + } + return item + }) + }) + } + + const newEmptyItem = () => { + setItems((items) => [ + ...items, + { id: nanoid(), platform: "", identity: "" }, + ]) + } + + const handleSubmit = (e: FormEvent) => { + e.preventDefault() + if (site.data?.handle) { + updateSite.mutate({ + characterId: site.data?.characterId, + connected_accounts: items.map(({ id, ...item }) => item), + }) + } + } + + useEffect(() => { + if (updateSite.isSuccess) { + toast.success("Saved") + } else if (updateSite.isError) { + toast.error("Failed to save") + } + }, [updateSite.isSuccess, updateSite.isError]) + + const removeItem: RemoveItem = (id) => { + setItems((items) => items.filter((item) => item.id !== id)) + } + + const [hasSet, setHasSet] = useState(false) + useEffect(() => { + if (site.data?.metadata?.content?.connected_accounts && !hasSet) { + setHasSet(true) + setItems( + site.data?.metadata?.content?.connected_accounts.map((item) => { + const match = item.match(/:\/\/account:(.*)@(.*)/) + if (match) { + return { + id: nanoid(), + identity: match[1], + platform: match[2], + } + } else { + return { + id: nanoid(), + identity: item, + platform: "", + } + } + }), + ) + } + }, [site.data?.metadata?.content?.connected_accounts, hasSet]) + + return ( + +
+

{t("Tips")}:

+

+ {t("social tips.p1")} +

+

+ + + We support{" "} + + these platforms + {" "} + with automatic display of logos and links, other platforms will + display a default logo. Please feel free to submit an issue or pr + to us to support more platforms. + + +

+

+ + + You can also connect to Twitter, Telegram Channel, Medium, + Substack and more and automatically sync content on{" "} + + xSync + + . When you have set up the sync there, it will also show here. + + +

+
+
+
+ {items.length === 0 && ( +
+ No navigation items yet +
+ )} + + {items.map((item) => { + return ( + + ) + })} + {/* eslint-disable-next-line react/no-unknown-property */} + + +
+
+ + +
+
+
+ ) +} diff --git a/src/app/dashboard/[subdomain]/settings/social-platforms/page.tsx b/src/app/dashboard/[subdomain]/settings/social-platforms/page.tsx index 66673984..fc708a55 100644 --- a/src/app/dashboard/[subdomain]/settings/social-platforms/page.tsx +++ b/src/app/dashboard/[subdomain]/settings/social-platforms/page.tsx @@ -1,239 +1,5 @@ -"use client" - -import equal from "fast-deep-equal" -import { nanoid } from "nanoid" -import { useParams } from "next/navigation" -import { ChangeEvent, FormEvent, useEffect, useMemo, useState } from "react" -import toast from "react-hot-toast" -import { ReactSortable } from "react-sortablejs" - -import { SettingsLayout } from "~/components/dashboard/SettingsLayout" -import { Platform, PlatformsSyncMap } from "~/components/site/Platform" -import { Button } from "~/components/ui/Button" -import { Input } from "~/components/ui/Input" -import { UniLink } from "~/components/ui/UniLink" -import { Trans, useTranslation } from "~/lib/i18n/client" -import { useGetSite, useUpdateSite } from "~/queries/site" - -type Item = { - identity: string - platform: string - url?: string | undefined -} & { - id: string -} - -type UpdateItem = (id: string, newItem: Partial) => void - -type RemoveItem = (id: string) => void - -const SortableNavigationItem = ({ - item, - updateItem, - removeItem, -}: { - item: Item - updateItem: UpdateItem - removeItem: RemoveItem -}) => { - const { t } = useTranslation("dashboard") - return ( -
-
- -
- ) => - updateItem(item.id, { platform: e.target.value }) - } - /> - ) => - updateItem(item.id, { identity: e.target.value }) - } - /> -
- -
-
- -
-
- ) -} +import PageComponent from "./page-component" export default function SiteSettingsNavigationPage() { - const params = useParams() - const subdomain = params?.subdomain as string - - const updateSite = useUpdateSite() - const site = useGetSite(subdomain) - const { t, i18n } = useTranslation("dashboard") - - const [items, setItems] = useState([]) - - const itemsModified = useMemo(() => { - if (!site.isSuccess) return false - return !equal(items, site.data?.metadata?.content?.connected_accounts) - }, [items, site.data, site.isSuccess]) - - const updateItem: UpdateItem = (id, newItem) => { - setItems((items) => { - return items.map((item) => { - if (item.id === id) { - return { ...item, ...newItem } - } - return item - }) - }) - } - - const newEmptyItem = () => { - setItems((items) => [ - ...items, - { id: nanoid(), platform: "", identity: "" }, - ]) - } - - const handleSubmit = (e: FormEvent) => { - e.preventDefault() - if (site.data?.handle) { - updateSite.mutate({ - characterId: site.data?.characterId, - connected_accounts: items.map(({ id, ...item }) => item), - }) - } - } - - useEffect(() => { - if (updateSite.isSuccess) { - toast.success("Saved") - } else if (updateSite.isError) { - toast.error("Failed to save") - } - }, [updateSite.isSuccess, updateSite.isError]) - - const removeItem: RemoveItem = (id) => { - setItems((items) => items.filter((item) => item.id !== id)) - } - - const [hasSet, setHasSet] = useState(false) - useEffect(() => { - if (site.data?.metadata?.content?.connected_accounts && !hasSet) { - setHasSet(true) - setItems( - site.data?.metadata?.content?.connected_accounts.map((item) => { - const match = item.match(/:\/\/account:(.*)@(.*)/) - if (match) { - return { - id: nanoid(), - identity: match[1], - platform: match[2], - } - } else { - return { - id: nanoid(), - identity: item, - platform: "", - } - } - }), - ) - } - }, [site.data?.metadata?.content?.connected_accounts, hasSet]) - - return ( - -
-

{t("Tips")}:

-

- {t("social tips.p1")} -

-

- - - We support{" "} - - these platforms - {" "} - with automatic display of logos and links, other platforms will - display a default logo. Please feel free to submit an issue or pr - to us to support more platforms. - - -

-

- - - You can also connect to Twitter, Telegram Channel, Medium, - Substack and more and automatically sync content on{" "} - - xSync - - . When you have set up the sync there, it will also show here. - - -

-
-
-
- {items.length === 0 && ( -
- No navigation items yet -
- )} - - {items.map((item) => { - return ( - - ) - })} - {/* eslint-disable-next-line react/no-unknown-property */} - - -
-
- - -
-
-
- ) + return } diff --git a/src/app/dashboard/[subdomain]/tokens/page-component.tsx b/src/app/dashboard/[subdomain]/tokens/page-component.tsx new file mode 100644 index 00000000..9d537758 --- /dev/null +++ b/src/app/dashboard/[subdomain]/tokens/page-component.tsx @@ -0,0 +1,149 @@ +"use client" + +import { useParams } from "next/navigation" + +import { + useAccountBalance, + useClaimCSBStatus, + useWalletClaimCSBModal, +} from "@crossbell/connect-kit" + +import { DashboardMain } from "~/components/dashboard/DashboardMain" +import { Button } from "~/components/ui/Button" +import { UniLink } from "~/components/ui/UniLink" +import { MIRA_LINK } from "~/lib/env" +import { getSiteLink } from "~/lib/helpers" +import { useTranslation } from "~/lib/i18n/client" +import { useGetMiraBalance, useGetSite } from "~/queries/site" + +export default function TokensPage() { + const params = useParams() + const { t } = useTranslation("dashboard") + const { t: indexT } = useTranslation("index") + const subdomain = params?.subdomain as string + const site = useGetSite(subdomain) + + const miraBalance = useGetMiraBalance(site.data?.characterId) + const csbBalance = useAccountBalance() + const claimCSBStatus = useClaimCSBStatus() + const claimCSBModal = useWalletClaimCSBModal() + + const tokens = [ + { + name: "MIRA", + balance: miraBalance.isLoading + ? "Loading..." + : miraBalance.data?.data || 0, + description: ( + <> +

+ {t( + "$MIRA is a valuable token in the Crossbell world, and can be easily exchanged on the Crosschain Bridge and Uniswap.", + )} +

+

+ {t("In the early stage, xLog will use $MIRA to motivate creators.")} +

+

{t("You can obtain $MIRA through the following ways:")}

+
    +
  • + 1.{" "} + + {t("Creator incentive program.")} + +
  • +
  • + 2.{" "} + + {t("Participate in events.")} + +
  • +
  • + 3.{" "} + + {t("Swap from USDC.")} + +
  • +
  • 4. {t("Received tips and sponsorships from readers.")}
  • +
+ + ), + buttons: ( +
+ + + {t("Swap Tutorial")} + +
+ ), + }, + { + name: "CSB", + balance: csbBalance?.balance?.formatted || 0, + description: ( + <> + {t( + "This is a token used for interaction on the Crossbell blockchain, which can be claimed for free from the faucet, so there's no need to worry about its balance.", + )} + + ), + buttons: ( + <> + + + ), + }, + { + name: "XLOG", + description: t( + "$XLOG is related to xLog DAO, but it's too early now, please stay tuned.", + ), + balance: t("Stay tuned"), + }, + ] + + return ( + +
+
+ {indexT("features.Earn.description")} +
+ {tokens.map((token) => { + return ( +
+
+ ${token.name} +
+
+ {token.description} +
+
+ {t("Balance")}:{" "} + {`${token.balance}`} +
+
{token.buttons}
+
+ ) + })} +
+
+ ) +} diff --git a/src/app/dashboard/[subdomain]/tokens/page.tsx b/src/app/dashboard/[subdomain]/tokens/page.tsx index 9d537758..e6446668 100644 --- a/src/app/dashboard/[subdomain]/tokens/page.tsx +++ b/src/app/dashboard/[subdomain]/tokens/page.tsx @@ -1,149 +1,5 @@ -"use client" - -import { useParams } from "next/navigation" - -import { - useAccountBalance, - useClaimCSBStatus, - useWalletClaimCSBModal, -} from "@crossbell/connect-kit" - -import { DashboardMain } from "~/components/dashboard/DashboardMain" -import { Button } from "~/components/ui/Button" -import { UniLink } from "~/components/ui/UniLink" -import { MIRA_LINK } from "~/lib/env" -import { getSiteLink } from "~/lib/helpers" -import { useTranslation } from "~/lib/i18n/client" -import { useGetMiraBalance, useGetSite } from "~/queries/site" +import PageComponent from "./page-component" export default function TokensPage() { - const params = useParams() - const { t } = useTranslation("dashboard") - const { t: indexT } = useTranslation("index") - const subdomain = params?.subdomain as string - const site = useGetSite(subdomain) - - const miraBalance = useGetMiraBalance(site.data?.characterId) - const csbBalance = useAccountBalance() - const claimCSBStatus = useClaimCSBStatus() - const claimCSBModal = useWalletClaimCSBModal() - - const tokens = [ - { - name: "MIRA", - balance: miraBalance.isLoading - ? "Loading..." - : miraBalance.data?.data || 0, - description: ( - <> -

- {t( - "$MIRA is a valuable token in the Crossbell world, and can be easily exchanged on the Crosschain Bridge and Uniswap.", - )} -

-

- {t("In the early stage, xLog will use $MIRA to motivate creators.")} -

-

{t("You can obtain $MIRA through the following ways:")}

-
    -
  • - 1.{" "} - - {t("Creator incentive program.")} - -
  • -
  • - 2.{" "} - - {t("Participate in events.")} - -
  • -
  • - 3.{" "} - - {t("Swap from USDC.")} - -
  • -
  • 4. {t("Received tips and sponsorships from readers.")}
  • -
- - ), - buttons: ( -
- - - {t("Swap Tutorial")} - -
- ), - }, - { - name: "CSB", - balance: csbBalance?.balance?.formatted || 0, - description: ( - <> - {t( - "This is a token used for interaction on the Crossbell blockchain, which can be claimed for free from the faucet, so there's no need to worry about its balance.", - )} - - ), - buttons: ( - <> - - - ), - }, - { - name: "XLOG", - description: t( - "$XLOG is related to xLog DAO, but it's too early now, please stay tuned.", - ), - balance: t("Stay tuned"), - }, - ] - - return ( - -
-
- {indexT("features.Earn.description")} -
- {tokens.map((token) => { - return ( -
-
- ${token.name} -
-
- {token.description} -
-
- {t("Balance")}:{" "} - {`${token.balance}`} -
-
{token.buttons}
-
- ) - })} -
-
- ) + return } diff --git a/src/app/dashboard/page-component.tsx b/src/app/dashboard/page-component.tsx new file mode 100644 index 00000000..a2a6f324 --- /dev/null +++ b/src/app/dashboard/page-component.tsx @@ -0,0 +1,60 @@ +"use client" + +import { useRouter } from "next/navigation" +import { useEffect, useRef } from "react" + +import { + useAccountState, + useConnectModal, + useWalletMintNewCharacterModal, +} from "@crossbell/connect-kit" + +export default function Dashboard() { + const router = useRouter() + const walletMintNewCharacterModal = useWalletMintNewCharacterModal() + const [ssrReady, account] = useAccountState(({ ssrReady, computed }) => [ + ssrReady, + computed.account, + ]) + const connectModal = useConnectModal() + + const isConnectModalShown = useRef(false) + const isMintCharacterModalShown = useRef(false) + + useEffect(() => { + if (ssrReady) { + // Wait till SSR is ready + if (!account) { + // Wallet not connected + if (!isConnectModalShown.current) { + // Not shown + isConnectModalShown.current = true + connectModal.show() + } else if (!connectModal.isActive) { + // Shown, but closed by user + router.push("/") // Go back home + } + } else { + // Wallet is connected, wait till site is ready + // Reset connect wallet status to prevent unexpected redirect + isConnectModalShown.current = false + if (!account.character) { + // No character found, prompt to mint one + if (!isMintCharacterModalShown.current) { + // Not shown + isMintCharacterModalShown.current = true + walletMintNewCharacterModal.show() + } else if (!walletMintNewCharacterModal.isActive) { + // Shown, but closed by user + router.push("/") // Go back home + } + } else { + // Already have characters, redirect to primary + router.push(`/dashboard/${account.character.handle}`) + } + } + } + }, [ssrReady, router, walletMintNewCharacterModal, account, connectModal]) + + return null +} diff --git a/src/app/dashboard/page.tsx b/src/app/dashboard/page.tsx index 465d981c..68d105b3 100644 --- a/src/app/dashboard/page.tsx +++ b/src/app/dashboard/page.tsx @@ -1,64 +1,12 @@ -"use client" - -import { useRouter } from "next/navigation" -import { useEffect, useRef } from "react" - -import { - useAccountState, - useConnectModal, - useWalletMintNewCharacterModal, -} from "@crossbell/connect-kit" +import PageComponent from "./page-component" export default function Dashboard() { - const router = useRouter() - const walletMintNewCharacterModal = useWalletMintNewCharacterModal() - const [ssrReady, account] = useAccountState(({ ssrReady, computed }) => [ - ssrReady, - computed.account, - ]) - const connectModal = useConnectModal() - - const isConnectModalShown = useRef(false) - const isMintCharacterModalShown = useRef(false) - - useEffect(() => { - if (ssrReady) { - // Wait till SSR is ready - if (!account) { - // Wallet not connected - if (!isConnectModalShown.current) { - // Not shown - isConnectModalShown.current = true - connectModal.show() - } else if (!connectModal.isActive) { - // Shown, but closed by user - router.push("/") // Go back home - } - } else { - // Wallet is connected, wait till site is ready - // Reset connect wallet status to prevent unexpected redirect - isConnectModalShown.current = false - if (!account.character) { - // No character found, prompt to mint one - if (!isMintCharacterModalShown.current) { - // Not shown - isMintCharacterModalShown.current = true - walletMintNewCharacterModal.show() - } else if (!walletMintNewCharacterModal.isActive) { - // Shown, but closed by user - router.push("/") // Go back home - } - } else { - // Already have characters, redirect to primary - router.push(`/dashboard/${account.character.handle}`) - } - } - } - }, [ssrReady, router, walletMintNewCharacterModal, account, connectModal]) - return ( -
- Loading... -
+ <> + +
+ Loading... +
+ ) } diff --git a/src/app/oia/page-component.tsx b/src/app/oia/page-component.tsx new file mode 100644 index 00000000..3a62678b --- /dev/null +++ b/src/app/oia/page-component.tsx @@ -0,0 +1,55 @@ +"use client" + +import { useCallback, useEffect } from "react" + +import { Image } from "~/components/ui/Image" +import { useTranslation } from "~/lib/i18n/client" + +async function OIAPage() { + const { t } = useTranslation("site") + + useEffect(() => { + document.body.style.backgroundColor = "#fb9148" + return () => { + document.body.style.backgroundColor = "" + } + }, []) + + const download = useCallback(() => { + window.open( + "itms-apps://apps.apple.com/app/xlog-on-chain-blogging/id6449499296", + ) + }, []) + + const goBack = useCallback(() => { + window.history.back() + }, []) + + return ( +
+ Download Preview +
+ {t("Pull down to open the app")} +
+ + +
+ ) +} + +export default OIAPage diff --git a/src/app/oia/page.tsx b/src/app/oia/page.tsx index 3a62678b..f967dc7d 100644 --- a/src/app/oia/page.tsx +++ b/src/app/oia/page.tsx @@ -1,55 +1,5 @@ -"use client" +import PageComponent from "./page-component" -import { useCallback, useEffect } from "react" - -import { Image } from "~/components/ui/Image" -import { useTranslation } from "~/lib/i18n/client" - -async function OIAPage() { - const { t } = useTranslation("site") - - useEffect(() => { - document.body.style.backgroundColor = "#fb9148" - return () => { - document.body.style.backgroundColor = "" - } - }, []) - - const download = useCallback(() => { - window.open( - "itms-apps://apps.apple.com/app/xlog-on-chain-blogging/id6449499296", - ) - }, []) - - const goBack = useCallback(() => { - window.history.back() - }, []) - - return ( -
- Download Preview -
- {t("Pull down to open the app")} -
- - -
- ) +export default function OIAPage() { + return } - -export default OIAPage diff --git a/src/app/site/[site]/preview/[previewId]/page-component.tsx b/src/app/site/[site]/preview/[previewId]/page-component.tsx new file mode 100644 index 00000000..5a5dbaf8 --- /dev/null +++ b/src/app/site/[site]/preview/[previewId]/page-component.tsx @@ -0,0 +1,60 @@ +"use client" + +import dynamic from "next/dynamic" +import { useParams } from "next/navigation" + +import { useTranslation } from "~/lib/i18n/client" +import { useGetPage } from "~/queries/page" +import { useGetSite } from "~/queries/site" + +const DynamicPageContent = dynamic( + () => import("~/components/common/PageContent"), + { + ssr: false, + }, +) + +export default function SitePreviewPage() { + const params = useParams() + const site = useGetSite(params.site) + + const page = useGetPage({ + characterId: site.data?.characterId, + noteId: + params.previewId && /\d+/.test(params.previewId) + ? +params.previewId + : undefined, + slug: params.previewId, + useStat: true, + }) + + const { t } = useTranslation("site") + + return ( + <> +
+ {t( + "This address is in local editing preview mode and cannot be viewed by the public.", + )} +
+
+
+ {page.data?.metadata?.content?.tags?.includes("post") ? ( +

+ {page.data.metadata?.content?.title} +

+ ) : ( +

+ {page.data?.metadata?.content?.title} +

+ )} +
+ +
+ + ) +} diff --git a/src/app/site/[site]/preview/[previewId]/page.tsx b/src/app/site/[site]/preview/[previewId]/page.tsx index bb6703c8..a1d04c29 100644 --- a/src/app/site/[site]/preview/[previewId]/page.tsx +++ b/src/app/site/[site]/preview/[previewId]/page.tsx @@ -1,65 +1,5 @@ -"use client" +import PageComponent from "./page-component" -import dynamic from "next/dynamic" - -import { useTranslation } from "~/lib/i18n/client" -import { useGetPage } from "~/queries/page" -import { useGetSite } from "~/queries/site" - -const DynamicPageContent = dynamic( - () => import("~/components/common/PageContent"), - { - ssr: false, - }, -) - -export default function SitePreviewPage({ - params, -}: { - params: { - site: string - previewId: string - } -}) { - const site = useGetSite(params.site) - - const page = useGetPage({ - characterId: site.data?.characterId, - noteId: - params.previewId && /\d+/.test(params.previewId) - ? +params.previewId - : undefined, - slug: params.previewId, - useStat: true, - }) - - const { t } = useTranslation("site") - - return ( - <> -
- {t( - "This address is in local editing preview mode and cannot be viewed by the public.", - )} -
-
-
- {page.data?.metadata?.content?.tags?.includes("post") ? ( -

- {page.data.metadata?.content?.title} -

- ) : ( -

- {page.data?.metadata?.content?.title} -

- )} -
- -
- - ) +export default function SitePreviewPage() { + return } diff --git a/src/components/dashboard/PagesManager.tsx b/src/components/dashboard/PagesManager.tsx index 78acb1a0..165a1953 100644 --- a/src/components/dashboard/PagesManager.tsx +++ b/src/components/dashboard/PagesManager.tsx @@ -1,3 +1,5 @@ +"use client" + import { nanoid } from "nanoid" import Link from "next/link" import {