Skip to content

armgit / fider

Public Imported from GitHub
0

Open platform to collect and prioritize feedback

Turning the post details into a modal that opens without a page reload.

Matt Robertseb306c087cb9
diff --git a/public/components/PostDetails/PostDetails.scss b/public/components/PostDetails/PostDetails.scss
new file mode 100644
index 000000000..087b0ea14
--- /dev/null
+++ b/public/components/PostDetails/PostDetails.scss
@@ -0,0 +1,41 @@
+@use "~@fider/assets/styles/variables.scss" as *;
+
+.post-details {
+ &__loading {
+ text-align: center;
+ padding: spacing(8);
+ font-size: 1.2rem;
+ color: var(--colors-gray-500);
+ }
+
+ &__main-col {
+ padding: spacing(4);
+ border-radius: get("border.radius.large");
+ margin-bottom: spacing(4);
+ }
+
+ &__action-col {
+ > :first-child {
+ padding: spacing(4);
+ }
+ }
+
+ @include media("lg") {
+ display: grid;
+ gap: spacing(6);
+ grid-template-columns: 2fr 6fr 1fr;
+ grid-template-rows: auto;
+ grid-template-areas:
+ "Action Main"
+ "Action Main";
+
+ &__main-col {
+ grid-area: Main;
+ overflow: auto;
+ }
+
+ &__action-col {
+ grid-area: Action;
+ }
+ }
+}
diff --git a/public/components/PostDetails/PostDetails.tsx b/public/components/PostDetails/PostDetails.tsx
new file mode 100644
index 000000000..461e4de74
--- /dev/null
+++ b/public/components/PostDetails/PostDetails.tsx
@@ -0,0 +1,374 @@
+import "./PostDetails.scss"
+
+import React, { useState, useEffect, useCallback } from "react"
+
+import { Comment, Post, Tag, Vote, CurrentUser, PostStatus } from "@fider/models"
+import { actions, cache, clearUrlHash, Failure, Fider, notify, timeAgo } from "@fider/services"
+import IconDotsHorizontal from "@fider/assets/images/heroicons-dots-horizontal.svg"
+import IconDuplicate from "@fider/assets/images/heroicons-duplicate.svg"
+import { i18n } from "@lingui/core"
+import IconRSS from "@fider/assets/images/heroicons-rss.svg"
+import IconPencil from "@fider/assets/images/heroicons-pencil-alt.svg"
+import IconChat from "@fider/assets/images/heroicons-chat-alt-2.svg"
+
+import { ResponseDetails, Button, UserName, Moment, Markdown, Input, Form, Icon, Avatar, Dropdown, RSSModal } from "@fider/components"
+import { DiscussionPanel } from "@fider/pages/ShowPost/components/DiscussionPanel"
+import CommentEditor from "@fider/components/common/form/CommentEditor"
+
+import IconX from "@fider/assets/images/heroicons-x.svg"
+import IconThumbsUp from "@fider/assets/images/heroicons-thumbsup.svg"
+import { HStack, VStack } from "@fider/components/layout"
+import { Trans } from "@lingui/react/macro"
+import { FollowButton } from "@fider/pages/ShowPost/components/FollowButton"
+import { VoteSection } from "@fider/pages/ShowPost/components/VoteSection"
+import { DeletePostModal } from "@fider/pages/ShowPost/components/DeletePostModal"
+import { ResponseModal } from "@fider/pages/ShowPost/components/ResponseModal"
+import { VotesPanel } from "@fider/pages/ShowPost/components/VotesPanel"
+import { TagsPanel } from "@fider/pages/ShowPost/components/TagsPanel"
+import { t } from "@lingui/macro"
+import { useFider } from "@fider/hooks"
+import { useAttachments } from "@fider/hooks/useAttachments"
+
+interface PostDetailsProps {
+ postNumber: number
+ onClose?: () => void
+ // Optional initial data for SSR
+ initialPost?: Post
+ initialSubscribed?: boolean
+ initialComments?: Comment[]
+ initialTags?: Tag[]
+ initialVotes?: Vote[]
+ initialAttachments?: string[]
+}
+
+const oneHour = 3600
+const canEditPost = (user: CurrentUser, post: Post) => {
+ if (user.isCollaborator) {
+ return true
+ }
+
+ return user.id === post.user.id && timeAgo(post.createdAt) <= oneHour
+}
+
+export const PostDetails: React.FC<PostDetailsProps> = (props) => {
+ // If we have initial data, use it; otherwise we'll fetch
+ const [post, setPost] = useState<Post | null>(props.initialPost || null)
+ const [subscribed, setSubscribed] = useState(props.initialSubscribed || false)
+ const [comments, setComments] = useState<Comment[]>(props.initialComments || [])
+ const [tags, setTags] = useState<Tag[]>(props.initialTags || [])
+ const [votes, setVotes] = useState<Vote[]>(props.initialVotes || [])
+ const [loading, setLoading] = useState(!props.initialPost)
+
+ const [editMode, setEditMode] = useState(false)
+ const [showDeleteModal, setShowDeleteModal] = useState(false)
+ const [isRSSModalOpen, setIsRSSModalOpen] = useState(false)
+ const [showResponseModal, setShowResponseModal] = useState(false)
+ const [newTitle, setNewTitle] = useState(post?.title || "")
+ const [newDescription, setNewDescription] = useState(post?.description || "")
+ const { attachments, handleImageUploaded, getImageSrc } = useAttachments({
+ maxAttachments: 3,
+ })
+ const [highlightedComment, setHighlightedComment] = useState<number | undefined>(undefined)
+ const [error, setError] = useState<Failure | undefined>(undefined)
+ const fider = useFider()
+
+ // Fetch data if not provided initially
+ useEffect(() => {
+ if (props.initialPost) {
+ return // Already have data from SSR
+ }
+
+ const fetchData = async () => {
+ setLoading(true)
+ try {
+ const [postResponse, commentsResult, tagsResult, votesResult] = await Promise.all([
+ fetch(`/api/v1/posts/${props.postNumber}`).then((r) => r.json()),
+ fetch(`/api/v1/posts/${props.postNumber}/comments`).then((r) => r.json()),
+ fetch(`/api/v1/tags`).then((r) => r.json()),
+ actions.listVotes(props.postNumber),
+ ])
+
+ if (postResponse) {
+ setPost(postResponse)
+ setNewTitle(postResponse.title)
+ setNewDescription(postResponse.description)
+ }
+
+ setComments(commentsResult || [])
+ setTags(tagsResult || [])
+ setVotes(votesResult.ok ? votesResult.data : [])
+
+ // Fetch subscription status if authenticated
+ if (Fider.session.isAuthenticated) {
+ try {
+ const subResponse = await fetch(`/api/v1/posts/${props.postNumber}/subscription`)
+ if (subResponse.ok) {
+ const subData = await subResponse.json()
+ setSubscribed(subData.subscribed || false)
+ }
+ } catch (e) {
+ // Ignore subscription errors
+ }
+ }
+ } catch (err) {
+ console.error("Failed to fetch post data:", err)
+ } finally {
+ setLoading(false)
+ }
+ }
+
+ fetchData()
+ }, [props.postNumber, props.initialPost])
+
+ const handleHashChange = useCallback(
+ (e?: Event) => {
+ const hash = window.location.hash
+ const result = /#comment-([0-9]+)/.exec(hash)
+
+ let newHighlightedComment
+ if (result === null) {
+ newHighlightedComment = undefined
+ } else {
+ const id = parseInt(result[1])
+ if (comments.map((comment) => comment.id).includes(id)) {
+ newHighlightedComment = id
+ } else {
+ if (e?.cancelable) {
+ e.preventDefault()
+ } else {
+ clearUrlHash(true)
+ }
+ notify.error(<Trans id="showpost.comment.unknownhighlighted">Unknown comment ID #{id}</Trans>)
+ newHighlightedComment = undefined
+ }
+ }
+ setHighlightedComment(newHighlightedComment)
+ },
+ [comments]
+ )
+
+ useEffect(() => {
+ handleHashChange()
+ window.addEventListener("hashchange", handleHashChange)
+ return () => {
+ window.removeEventListener("hashchange", handleHashChange)
+ }
+ }, [handleHashChange])
+
+ useEffect(() => {
+ const showSuccess = cache.session.get("POST_CREATED_SUCCESS")
+ if (showSuccess) {
+ cache.session.remove("POST_CREATED_SUCCESS")
+ notify.success(t({ id: "mysettings.notification.event.newpostcreated", message: "Your idea has been added 👍" }))
+ }
+ }, [])
+
+ const saveChanges = async () => {
+ if (!post) return
+ const result = await actions.updatePost(post.number, newTitle, newDescription, attachments)
+ if (result.ok) {
+ setEditMode(false)
+ // Update local state with new values
+ setPost({
+ ...post,
+ title: newTitle,
+ description: newDescription,
+ })
+ notify.success(<Trans id="showpost.save.success">Post updated successfully</Trans>)
+ } else {
+ setError(result.error)
+ }
+ }
+
+ const canDeletePost = () => {
+ if (!post) return false
+ const status = PostStatus.Get(post.status)
+ if (!Fider.session.isAuthenticated || !Fider.session.user.isAdministrator || status.closed) {
+ return false
+ }
+ return true
+ }
+
+ const cancelEdit = () => {
+ setError(undefined)
+ setEditMode(false)
+ }
+
+ const startEdit = () => {
+ setEditMode(true)
+ }
+
+ const handleDescriptionChange = (value: string) => {
+ setNewDescription(value)
+ }
+
+ const onActionSelected = (action: "copy" | "delete" | "status" | "feed" | "edit") => () => {
+ if (action === "copy") {
+ navigator.clipboard.writeText(window.location.href)
+ notify.success(<Trans id="showpost.copylink.success">Link copied to clipboard</Trans>)
+ } else if (action === "delete") {
+ setShowDeleteModal(true)
+ } else if (action === "status") {
+ setShowResponseModal(true)
+ } else if (action === "edit") {
+ startEdit()
+ } else if (action == "feed") {
+ setIsRSSModalOpen(true)
+ }
+ }
+
+ const hideRSSModal = () => setIsRSSModalOpen(false)
+
+ if (loading || !post) {
+ return (
+ <div className="post-details">
+ <div className="post-details__loading">Loading...</div>
+ </div>
+ )
+ }
+
+ return (
+ <div className="post-details">
+ <div className="post-details__main-col">
+ <div className="post-details__header-col">
+ <VStack spacing={8}>
+ <HStack justify="between">
+ <VStack align="start">
+ {!editMode && (
+ <HStack>
+ <Avatar user={post.user} />
+ <VStack spacing={1}>
+ <UserName user={post.user} />
+ <Moment className="text-muted" locale={Fider.currentLocale} date={post.createdAt} />
+ </VStack>
+ </HStack>
+ )}
+ </VStack>
+ <RSSModal isOpen={isRSSModalOpen} onClose={hideRSSModal} url={`${fider.settings.baseURL}/feed/posts/${post.number}.atom`} />
+
+ {!editMode && (
+ <HStack>
+ {props.onClose && (
+ <Button onClick={props.onClose}>
+ <Icon sprite={IconX} />
+ </Button>
+ )}
+ <Dropdown position="left" renderHandle={<Icon sprite={IconDotsHorizontal} width="24" height="24" />}>
+ <Dropdown.ListItem onClick={onActionSelected("copy")} icon={IconDuplicate}>
+ <Trans id="action.copylink">Copy link</Trans>
+ </Dropdown.ListItem>
+ {Fider.session.tenant.isFeedEnabled && (
+ <Dropdown.ListItem onClick={onActionSelected("feed")} icon={IconRSS}>
+ <Trans id="action.commentsfeed">Comment Feed</Trans>
+ </Dropdown.ListItem>
+ )}
+ {Fider.session.isAuthenticated && canEditPost(Fider.session.user, post) && (
+ <>
+ <Dropdown.ListItem onClick={onActionSelected("edit")} icon={IconPencil}>
+ <Trans id="action.edit">Edit</Trans>
+ </Dropdown.ListItem>
+ {Fider.session.user.isCollaborator && (
+ <Dropdown.ListItem onClick={onActionSelected("status")} icon={IconChat}>
+ <Trans id="action.respond">Respond</Trans>
+ </Dropdown.ListItem>
+ )}
+ </>
+ )}
+ {canDeletePost() && (
+ <Dropdown.ListItem onClick={onActionSelected("delete")} className="text-red-700" icon={IconX}>
+ <Trans id="action.delete">Delete</Trans>
+ </Dropdown.ListItem>
+ )}
+ </Dropdown>
+ </HStack>
+ )}
+ </HStack>
+
+ <div className="flex-grow">
+ {editMode ? (
+ <Form error={error}>
+ <Input field="title" maxLength={100} value={newTitle} onChange={setNewTitle} />
+ </Form>
+ ) : (
+ <>
+ <h1 className="text-large text-break">{post.title}</h1>
+ </>
+ )}
+ </div>
+
+ <DeletePostModal onModalClose={() => setShowDeleteModal(false)} showModal={showDeleteModal} post={post} />
+ {Fider.session.isAuthenticated && Fider.session.user.isCollaborator && (
+ <ResponseModal onCloseModal={() => setShowResponseModal(false)} showModal={showResponseModal} post={post} />
+ )}
+ <VStack>
+ {editMode ? (
+ <Form error={error}>
+ <CommentEditor
+ field="description"
+ onChange={handleDescriptionChange}
+ initialValue={newDescription}
+ disabled={false}
+ maxAttachments={3}
+ maxImageSizeKB={5 * 1024}
+ placeholder={i18n._({
+ id: "newpost.modal.description.placeholder",
+ message: "Tell us about it. Explain it fully, don't hold back, the more information the better.",
+ })}
+ onImageUploaded={handleImageUploaded}
+ onGetImageSrc={getImageSrc}
+ />
+ </Form>
+ ) : (
+ <>
+ {post.description && <Markdown className="description" text={post.description} style="full" />}
+ {!post.description && (
+ <em className="text-muted">
+ <Trans id="showpost.message.nodescription">No description provided.</Trans>
+ </em>
+ )}
+ </>
+ )}
+ </VStack>
+ <div className="mt-2">
+ <TagsPanel post={post} tags={tags} />
+ </div>
+
+ <VStack spacing={4}>
+ {!editMode ? (
+ <HStack justify="between" align="start">
+ <VoteSection post={post} votes={post.votesCount} />
+ <FollowButton post={post} subscribed={subscribed} />
+ </HStack>
+ ) : (
+ <HStack>
+ <Button variant="primary" onClick={saveChanges} disabled={Fider.isReadOnly}>
+ <Icon sprite={IconThumbsUp} />{" "}
+ <span>
+ <Trans id="action.save">Save</Trans>
+ </span>
+ </Button>
+ <Button onClick={cancelEdit} disabled={Fider.isReadOnly}>
+ <Icon sprite={IconX} />
+ <span>
+ <Trans id="action.cancel">Cancel</Trans>
+ </span>
+ </Button>
+ </HStack>
+ )}
+ <div className="border-4 border-blue-500" />
+ </VStack>
+
+ <ResponseDetails status={post.status} response={post.response} />
+ </VStack>
+ </div>
+
+ <div className="post-details__discussion_col">
+ <DiscussionPanel post={post} comments={comments} highlightedComment={highlightedComment} />
+ </div>
+ </div>
+ <div className="post-details__action-col">
+ <VotesPanel post={post} votes={votes} />
+ </div>
+ </div>
+ )
+}
diff --git a/public/components/PostDetails/PostDetailsOverlay.scss b/public/components/PostDetails/PostDetailsOverlay.scss
new file mode 100644
index 000000000..70877281d
--- /dev/null
+++ b/public/components/PostDetails/PostDetailsOverlay.scss
@@ -0,0 +1,37 @@
+@use "~@fider/assets/styles/variables.scss" as *;
+
+@keyframes fadeIn {
+ from {
+ opacity: 0;
+ }
+ to {
+ opacity: 1;
+ }
+}
+
+.post-details-overlay {
+ position: fixed;
+ top: 0;
+ left: 0;
+ right: 0;
+ bottom: 0;
+ z-index: 9999;
+ background-color: var(--colors-white);
+ animation: fadeIn 0.2s ease-out;
+ overflow-y: auto;
+
+ &__backdrop {
+ display: none;
+ }
+
+ &__panel {
+ width: 100%;
+ height: 100%;
+ display: flex;
+ flex-direction: column;
+ }
+
+ &__content {
+ flex: 1;
+ }
+}
diff --git a/public/components/PostDetails/PostDetailsOverlay.tsx b/public/components/PostDetails/PostDetailsOverlay.tsx
new file mode 100644
index 000000000..85df524bd
--- /dev/null
+++ b/public/components/PostDetails/PostDetailsOverlay.tsx
@@ -0,0 +1,38 @@
+import "./PostDetailsOverlay.scss"
+
+import React, { ReactNode, useEffect } from "react"
+
+interface PostDetailsOverlayProps {
+ children: ReactNode
+ onClose: () => void
+}
+
+export const PostDetailsOverlay: React.FC<PostDetailsOverlayProps> = ({ children, onClose }) => {
+ // Handle escape key to close
+ useEffect(() => {
+ const handleEscape = (e: KeyboardEvent) => {
+ if (e.key === "Escape") {
+ onClose()
+ }
+ }
+
+ document.addEventListener("keydown", handleEscape)
+ return () => document.removeEventListener("keydown", handleEscape)
+ }, [onClose])
+
+ // Prevent body scroll when overlay is open
+ useEffect(() => {
+ document.body.style.overflow = "hidden"
+ return () => {
+ document.body.style.overflow = ""
+ }
+ }, [])
+
+ return (
+ <div className="post-details-overlay">
+ <div className="post-details-overlay__panel">
+ <div className="post-details-overlay__content">{children}</div>
+ </div>
+ </div>
+ )
+}
diff --git a/public/components/PostDetails/index.ts b/public/components/PostDetails/index.ts
new file mode 100644
index 000000000..84fb92d83
--- /dev/null
+++ b/public/components/PostDetails/index.ts
@@ -0,0 +1,2 @@
+export * from "./PostDetails"
+export * from "./PostDetailsOverlay"
diff --git a/public/pages/Home/Home.page.tsx b/public/pages/Home/Home.page.tsx
index f7a30b6af..313155ede 100644
--- a/public/pages/Home/Home.page.tsx
+++ b/public/pages/Home/Home.page.tsx
@@ -11,6 +11,7 @@ import { ShareFeedback } from "./components/ShareFeedback"
import { i18n } from "@lingui/core"
import { Trans } from "@lingui/react/macro"
import { isPostPending, setPostPending } from "./components/PostCache"
+import { PostDetails, PostDetailsOverlay } from "@fider/components/PostDetails"
export interface HomePageProps {
posts: Post[]
@@ -46,8 +47,9 @@ const Lonely = () => {
const HomePage = (props: HomePageProps) => {
const fider = useFider()
- // const [title, setTitle] = useState("")
const [isShareFeedbackOpen, setIsShareFeedbackOpen] = useState(isPostPending())
+ const [selectedPostId, setSelectedPostId] = useState<number | null>(null)
+ const [savedScrollPosition, setSavedScrollPosition] = useState<number>(0)
useEffect(() => {
// If we're showing the share feedback, make sure we clear the show pending flag (for draft posts)
@@ -58,6 +60,50 @@ const HomePage = (props: HomePageProps) => {
}
})
+ // Handle post clicks from ListPosts
+ const handlePostClick = (postNumber: number, slug: string) => {
+ // Save current scroll position
+ setSavedScrollPosition(window.scrollY)
+ setSelectedPostId(postNumber)
+ window.history.pushState({ selectedPostId: postNumber }, "", `/posts/${postNumber}/${slug}`)
+ }
+
+ // Handle closing the overlay
+ const handleCloseOverlay = () => {
+ setSelectedPostId(null)
+ window.history.pushState({}, "", "/")
+ // Restore scroll position after state updates
+ setTimeout(() => {
+ window.scrollTo(0, savedScrollPosition)
+ }, 0)
+ }
+
+ // Handle browser back/forward buttons
+ useEffect(() => {
+ const handlePopState = () => {
+ const path = window.location.pathname
+ if (path === "/" || path === "") {
+ setSelectedPostId(null)
+ // Restore scroll position when going back to home
+ setTimeout(() => {
+ window.scrollTo(0, savedScrollPosition)
+ }, 0)
+ } else if (path.startsWith("/posts/")) {
+ // Save scroll position before opening post
+ setSavedScrollPosition(window.scrollY)
+ // Extract post number from URL
+ const match = path.match(/\/posts\/(\d+)/)
+ if (match) {
+ const postNumber = parseInt(match[1], 10)
+ setSelectedPostId(postNumber)
+ }
+ }
+ }
+
+ window.addEventListener("popstate", handlePopState)
+ return () => window.removeEventListener("popstate", handlePopState)
+ }, [savedScrollPosition])
+
const defaultWelcomeMessage = i18n._({
id: "home.form.defaultwelcomemessage",
message: `We'd love to hear what you're thinking about.
@@ -92,24 +138,35 @@ What can we do better? This is the place for you to vote, discuss and share idea
isOpen={isShareFeedbackOpen && !fider.isReadOnly}
onClose={() => setIsShareFeedbackOpen(false)}
/>
- <Header hasInert={isShareFeedbackOpen && !fider.isReadOnly} />
- <div id="p-home" className="page container" {...(isShareFeedbackOpen && !fider.isReadOnly && { inert: "true" })}>
- <div className="p-home__welcome-col">
- <VStack spacing={2} className="p-4">
- <Markdown text={fider.session.tenant.welcomeMessage || defaultWelcomeMessage} style="full" />
- <Button className="c-input" type="submit" variant="secondary" onClick={handleNewPost}>
- {fider.session.tenant.invitation || defaultInvitation}
- </Button>
- </VStack>
- <div onClick={() => setIsShareFeedbackOpen(true)}>
- <PoweredByFider slot="home-input" className="sm:hidden md:hidden lg:block mt-3" />
+ <div style={{ display: selectedPostId ? "none" : "block" }}>
+ <Header hasInert={isShareFeedbackOpen && !fider.isReadOnly} />
+ <div id="p-home" className="page container" {...(isShareFeedbackOpen && !fider.isReadOnly && { inert: "true" })}>
+ <div className="p-home__welcome-col">
+ <VStack spacing={2} className="p-4">
+ <Markdown text={fider.session.tenant.welcomeMessage || defaultWelcomeMessage} style="full" />
+ <Button className="c-input" type="submit" variant="secondary" onClick={handleNewPost}>
+ {fider.session.tenant.invitation || defaultInvitation}
+ </Button>
+ </VStack>
+ <div onClick={() => setIsShareFeedbackOpen(true)}>
+ <PoweredByFider slot="home-input" className="sm:hidden md:hidden lg:block mt-3" />
+ </div>
+ </div>
+ <div className="p-home__posts-col p-4">
+ {isLonely() ? <Lonely /> : <PostsContainer posts={props.posts} tags={props.tags} countPerStatus={props.countPerStatus} onPostClick={handlePostClick} />}
+ <PoweredByFider slot="home-footer" className="lg:hidden xl:hidden mt-8" />
</div>
- </div>
- <div className="p-home__posts-col p-4">
- {isLonely() ? <Lonely /> : <PostsContainer posts={props.posts} tags={props.tags} countPerStatus={props.countPerStatus} />}
- <PoweredByFider slot="home-footer" className="lg:hidden xl:hidden mt-8" />
</div>
</div>
+
+ {selectedPostId && (
+ <PostDetailsOverlay onClose={handleCloseOverlay}>
+ <Header />
+ <div className="page container">
+ <PostDetails postNumber={selectedPostId} onClose={handleCloseOverlay} />
+ </div>
+ </PostDetailsOverlay>
+ )}
</>
)
}
diff --git a/public/pages/Home/components/ListPosts.tsx b/public/pages/Home/components/ListPosts.tsx
index 341d5ba87..bca042cdd 100644
--- a/public/pages/Home/components/ListPosts.tsx
+++ b/public/pages/Home/components/ListPosts.tsx
@@ -9,9 +9,17 @@ interface ListPostsProps {
tags: Tag[]
emptyText: string
minimalView?: boolean
+ onPostClick?: (postNumber: number, slug: string) => void
}
-const ListPostItem = (props: { post: Post; user?: CurrentUser; tags: Tag[] }) => {
+const ListPostItem = (props: { post: Post; user?: CurrentUser; tags: Tag[]; onPostClick?: (postNumber: number, slug: string) => void }) => {
+ const handleClick = (e: React.MouseEvent<HTMLAnchorElement>) => {
+ if (props.onPostClick) {
+ e.preventDefault()
+ props.onPostClick(props.post.number, props.post.slug)
+ }
+ }
+
return (
<HStack spacing={4} align="start" className="c-posts-container__post">
<div>
@@ -24,7 +32,7 @@ const ListPostItem = (props: { post: Post; user?: CurrentUser; tags: Tag[] }) =>
</div>
)}
<HStack justify="between">
- <a className="text-title text-break hover:text-primary-base" href={`/posts/${props.post.number}/${props.post.slug}`}>
+ <a className="text-title text-break hover:text-primary-base" href={`/posts/${props.post.number}/${props.post.slug}`} onClick={handleClick}>
{props.post.title}
</a>
{props.post.commentsCount > 0 && (
@@ -46,11 +54,18 @@ const ListPostItem = (props: { post: Post; user?: CurrentUser; tags: Tag[] }) =>
)
}
-const MinimalListPostItem = (props: { post: Post; tags: Tag[] }) => {
+const MinimalListPostItem = (props: { post: Post; tags: Tag[]; onPostClick?: (postNumber: number, slug: string) => void }) => {
+ const handleClick = (e: React.MouseEvent<HTMLAnchorElement>) => {
+ if (props.onPostClick) {
+ e.preventDefault()
+ props.onPostClick(props.post.number, props.post.slug)
+ }
+ }
+
return (
<HStack spacing={4} align="start" className="c-posts-container__post">
<HStack className="w-full" justify="between" align="start">
- <a className="text-link" href={`/posts/${props.post.number}/${props.post.slug}`}>
+ <a className="text-link" href={`/posts/${props.post.number}/${props.post.slug}`} onClick={handleClick}>
{props.post.title}
</a>
{props.post.status !== "open" ? (
@@ -81,13 +96,13 @@ export const ListPosts = (props: ListPostsProps) => {
{minimalView ? (
<VStack spacing={2}>
{props.posts.map((post) => (
- <MinimalListPostItem key={post.id} post={post} tags={props.tags.filter((tag) => post.tags.indexOf(tag.slug) >= 0)} />
+ <MinimalListPostItem key={post.id} post={post} tags={props.tags.filter((tag) => post.tags.indexOf(tag.slug) >= 0)} onPostClick={props.onPostClick} />
))}
</VStack>
) : (
<VStack spacing={4} divide>
{props.posts.map((post) => (
- <ListPostItem key={post.id} post={post} tags={props.tags.filter((tag) => post.tags.indexOf(tag.slug) >= 0)} />
+ <ListPostItem key={post.id} post={post} tags={props.tags.filter((tag) => post.tags.indexOf(tag.slug) >= 0)} onPostClick={props.onPostClick} />
))}
</VStack>
)}
diff --git a/public/pages/Home/components/PostsContainer.tsx b/public/pages/Home/components/PostsContainer.tsx
index 7f0c0b0ab..9d67a0605 100644
--- a/public/pages/Home/components/PostsContainer.tsx
+++ b/public/pages/Home/components/PostsContainer.tsx
@@ -18,6 +18,7 @@ interface PostsContainerProps {
posts: Post[]
tags: Tag[]
countPerStatus: { [key: string]: number }
+ onPostClick?: (postNumber: number, slug: string) => void
}
interface PostsContainerState {
@@ -171,6 +172,7 @@ export class PostsContainer extends React.Component<PostsContainerProps, PostsCo
posts={this.state.posts}
tags={this.props.tags}
emptyText={i18n._({ id: "home.postscontainer.label.noresults", message: "No results matched your search, try something different." })}
+ onPostClick={this.props.onPostClick}
/>
{this.state.loading && <Loader />}
{showMoreLink && (
diff --git a/public/pages/ShowPost/ShowPost.page.tsx b/public/pages/ShowPost/ShowPost.page.tsx
index 90cec7f30..66decae29 100644
--- a/public/pages/ShowPost/ShowPost.page.tsx
+++ b/public/pages/ShowPost/ShowPost.page.tsx
@@ -1,33 +1,10 @@
import "./ShowPost.page.scss"
-import React, { useState, useEffect, useCallback } from "react"
+import React from "react"
-import { Comment, Post, Tag, Vote, CurrentUser, PostStatus } from "@fider/models"
-import { actions, cache, clearUrlHash, Failure, Fider, notify, timeAgo } from "@fider/services"
-import IconDotsHorizontal from "@fider/assets/images/heroicons-dots-horizontal.svg"
-import IconDuplicate from "@fider/assets/images/heroicons-duplicate.svg"
-import { i18n } from "@lingui/core"
-import IconRSS from "@fider/assets/images/heroicons-rss.svg"
-import IconPencil from "@fider/assets/images/heroicons-pencil-alt.svg"
-import IconChat from "@fider/assets/images/heroicons-chat-alt-2.svg"
-
-import { ResponseDetails, Button, UserName, Moment, Markdown, Input, Form, Icon, Header, PoweredByFider, Avatar, Dropdown, RSSModal } from "@fider/components"
-import { DiscussionPanel } from "./components/DiscussionPanel"
-import CommentEditor from "@fider/components/common/form/CommentEditor"
-
-import IconX from "@fider/assets/images/heroicons-x.svg"
-import IconThumbsUp from "@fider/assets/images/heroicons-thumbsup.svg"
-import { HStack, VStack } from "@fider/components/layout"
-import { Trans } from "@lingui/react/macro"
-import { FollowButton } from "./components/FollowButton"
-import { VoteSection } from "./components/VoteSection"
-import { DeletePostModal } from "./components/DeletePostModal"
-import { ResponseModal } from "./components/ResponseModal"
-import { VotesPanel } from "./components/VotesPanel"
-import { TagsPanel } from "@fider/pages/ShowPost/components/TagsPanel"
-import { t } from "@lingui/macro"
-import { useFider } from "@fider/hooks"
-import { useAttachments } from "@fider/hooks/useAttachments"
+import { Comment, Post, Tag, Vote } from "@fider/models"
+import { Header, PoweredByFider } from "@fider/components"
+import { PostDetails } from "@fider/components/PostDetails"
interface ShowPostPageProps {
post: Post
@@ -38,265 +15,21 @@ interface ShowPostPageProps {
attachments: string[]
}
-const oneHour = 3600
-const canEditPost = (user: CurrentUser, post: Post) => {
- if (user.isCollaborator) {
- return true
- }
-
- return user.id === post.user.id && timeAgo(post.createdAt) <= oneHour
-}
-
export default function ShowPostPage(props: ShowPostPageProps) {
- const [editMode, setEditMode] = useState(false)
- const [showDeleteModal, setShowDeleteModal] = useState(false)
- const [isRSSModalOpen, setIsRSSModalOpen] = useState(false)
- const [showResponseModal, setShowResponseModal] = useState(false)
- const [newTitle, setNewTitle] = useState(props.post.title)
- const [newDescription, setNewDescription] = useState(props.post.description)
- const { attachments, handleImageUploaded, getImageSrc } = useAttachments({
- maxAttachments: 3,
- })
- const [highlightedComment, setHighlightedComment] = useState<number | undefined>(undefined)
- const [error, setError] = useState<Failure | undefined>(undefined)
- const fider = useFider()
-
- const handleHashChange = useCallback(
- (e?: Event) => {
- const hash = window.location.hash
- const result = /#comment-([0-9]+)/.exec(hash)
-
- let newHighlightedComment
- if (result === null) {
- // No match
- newHighlightedComment = undefined
- } else {
- // Match, extract numeric ID
- const id = parseInt(result[1])
- if (props.comments.map((comment) => comment.id).includes(id)) {
- newHighlightedComment = id
- } else {
- // Unknown comment
- if (e?.cancelable) {
- e.preventDefault()
- } else {
- clearUrlHash(true)
- }
- notify.error(<Trans id="showpost.comment.unknownhighlighted">Unknown comment ID #{id}</Trans>)
- newHighlightedComment = undefined
- }
- }
- setHighlightedComment(newHighlightedComment)
- },
- [props.comments]
- )
-
- useEffect(() => {
- handleHashChange()
- window.addEventListener("hashchange", handleHashChange)
- return () => {
- window.removeEventListener("hashchange", handleHashChange)
- }
- }, [handleHashChange])
-
- useEffect(() => {
- const showSuccess = cache.session.get("POST_CREATED_SUCCESS")
- if (showSuccess) {
- cache.session.remove("POST_CREATED_SUCCESS")
- // Show success message/toast
- notify.success(t({ id: "mysettings.notification.event.newpostcreated", message: "Your idea has been added 👍" }))
- }
- }, [])
-
- const saveChanges = async () => {
- const result = await actions.updatePost(props.post.number, newTitle, newDescription, attachments)
- if (result.ok) {
- location.reload()
- } else {
- setError(result.error)
- }
- }
-
- const canDeletePost = () => {
- const status = PostStatus.Get(props.post.status)
- if (!Fider.session.isAuthenticated || !Fider.session.user.isAdministrator || status.closed) {
- return false
- }
- return true
- }
-
- const cancelEdit = () => {
- setError(undefined)
- setEditMode(false)
- }
-
- const startEdit = () => {
- setEditMode(true)
- }
-
- const handleDescriptionChange = (value: string) => {
- setNewDescription(value)
- }
-
- const onActionSelected = (action: "copy" | "delete" | "status" | "feed" | "edit") => () => {
- if (action === "copy") {
- navigator.clipboard.writeText(window.location.href)
- notify.success(<Trans id="showpost.copylink.success">Link copied to clipboard</Trans>)
- } else if (action === "delete") {
- setShowDeleteModal(true)
- } else if (action === "status") {
- setShowResponseModal(true)
- } else if (action === "edit") {
- startEdit()
- } else if (action == "feed") {
- setIsRSSModalOpen(true)
- }
- }
-
- const hideRSSModal = () => setIsRSSModalOpen(false)
-
return (
<>
<Header />
<div id="p-show-post" className="page container">
- <div className="p-show-post">
- <div className="p-show-post__main-col">
- <div className="p-show-post__header-col">
- <VStack spacing={8}>
- <HStack justify="between">
- <VStack align="start">
- {!editMode && (
- <HStack>
- <Avatar user={props.post.user} />
- <VStack spacing={1}>
- <UserName user={props.post.user} />
- <Moment className="text-muted" locale={Fider.currentLocale} date={props.post.createdAt} />
- </VStack>
- </HStack>
- )}
- </VStack>
- <RSSModal isOpen={isRSSModalOpen} onClose={hideRSSModal} url={`${fider.settings.baseURL}/feed/posts/${props.post.number}.atom`} />
-
- {!editMode && (
- <HStack>
- <Dropdown position="left" renderHandle={<Icon sprite={IconDotsHorizontal} width="24" height="24" />}>
- <Dropdown.ListItem onClick={onActionSelected("copy")} icon={IconDuplicate}>
- <Trans id="action.copylink">Copy link</Trans>
- </Dropdown.ListItem>
- {Fider.session.tenant.isFeedEnabled && (
- <Dropdown.ListItem onClick={onActionSelected("feed")} icon={IconRSS}>
- <Trans id="action.commentsfeed">Comment Feed</Trans>
- </Dropdown.ListItem>
- )}
- {Fider.session.isAuthenticated && canEditPost(Fider.session.user, props.post) && (
- <>
- <Dropdown.ListItem onClick={onActionSelected("edit")} icon={IconPencil}>
- <Trans id="action.edit">Edit</Trans>
- </Dropdown.ListItem>
- {Fider.session.user.isCollaborator && (
- <Dropdown.ListItem onClick={onActionSelected("status")} icon={IconChat}>
- <Trans id="action.respond">Respond</Trans>
- </Dropdown.ListItem>
- )}
- </>
- )}
- {canDeletePost() && (
- <Dropdown.ListItem onClick={onActionSelected("delete")} className="text-red-700" icon={IconX}>
- <Trans id="action.delete">Delete</Trans>
- </Dropdown.ListItem>
- )}
- </Dropdown>
- </HStack>
- )}
- </HStack>
-
- <div className="flex-grow">
- {editMode ? (
- <Form error={error}>
- <Input field="title" maxLength={100} value={newTitle} onChange={setNewTitle} />
- </Form>
- ) : (
- <>
- <h1 className="text-large text-break">{props.post.title}</h1>
- </>
- )}
- </div>
-
- <DeletePostModal onModalClose={() => setShowDeleteModal(false)} showModal={showDeleteModal} post={props.post} />
- {Fider.session.isAuthenticated && Fider.session.user.isCollaborator && (
- <ResponseModal onCloseModal={() => setShowResponseModal(false)} showModal={showResponseModal} post={props.post} />
- )}
- <VStack>
- {editMode ? (
- <Form error={error}>
- <CommentEditor
- field="description"
- onChange={handleDescriptionChange}
- initialValue={newDescription}
- disabled={false}
- maxAttachments={3}
- maxImageSizeKB={5 * 1024}
- placeholder={i18n._({
- id: "newpost.modal.description.placeholder",
- message: "Tell us about it. Explain it fully, don't hold back, the more information the better.",
- })}
- onImageUploaded={handleImageUploaded}
- onGetImageSrc={getImageSrc}
- />
- </Form>
- ) : (
- <>
- {props.post.description && <Markdown className="description" text={props.post.description} style="full" />}
- {!props.post.description && (
- <em className="text-muted">
- <Trans id="showpost.message.nodescription">No description provided.</Trans>
- </em>
- )}
- </>
- )}
- </VStack>
- <div className="mt-2">
- <TagsPanel post={props.post} tags={props.tags} />
- </div>
-
- <VStack spacing={4}>
- {!editMode ? (
- <HStack justify="between" align="start">
- <VoteSection post={props.post} votes={props.post.votesCount} />
- <FollowButton post={props.post} subscribed={props.subscribed} />
- </HStack>
- ) : (
- <HStack>
- <Button variant="primary" onClick={saveChanges} disabled={Fider.isReadOnly}>
- <Icon sprite={IconThumbsUp} />{" "}
- <span>
- <Trans id="action.save">Save</Trans>
- </span>
- </Button>
- <Button onClick={cancelEdit} disabled={Fider.isReadOnly}>
- <Icon sprite={IconX} />
- <span>
- <Trans id="action.cancel">Cancel</Trans>
- </span>
- </Button>
- </HStack>
- )}
- <div className="border-4 border-blue-500" />
- </VStack>
-
- <ResponseDetails status={props.post.status} response={props.post.response} />
- </VStack>
- </div>
-
- <div className="p-show-post__discussion_col">
- <DiscussionPanel post={props.post} comments={props.comments} highlightedComment={highlightedComment} />
- </div>
- </div>
- <div className="p-show-post__action-col">
- <VotesPanel post={props.post} votes={props.votes} />
- <PoweredByFider slot="show-post" className="mt-3" />
- </div>
- </div>
+ <PostDetails
+ postNumber={props.post.number}
+ initialPost={props.post}
+ initialSubscribed={props.subscribed}
+ initialComments={props.comments}
+ initialTags={props.tags}
+ initialVotes={props.votes}
+ initialAttachments={props.attachments}
+ />
+ <PoweredByFider slot="show-post" className="mt-3" />
</div>
</>
)