Skip to content

armgit / fider

Public Imported from GitHub
0

Open platform to collect and prioritize feedback

refactor: remove Fider service from some components (part 2) (#819)

Guilherme Oenning6b33391d1a02
diff --git a/public/components/VoteCounter.tsx b/public/components/VoteCounter.tsx
index 9d8500aad..f1973c8bc 100644
--- a/public/components/VoteCounter.tsx
+++ b/public/components/VoteCounter.tsx
@@ -1,80 +1,65 @@
import "./VoteCounter.scss";
-import React from "react";
+import React, { useState } from "react";
import { Post, PostStatus } from "@fider/models";
-import { actions, device, classSet, Fider } from "@fider/services";
+import { actions, device, classSet } from "@fider/services";
import { SignInModal } from "@fider/components";
import { FaCaretUp } from "react-icons/fa";
+import { useFider } from "@fider/hooks";
interface VoteCounterProps {
post: Post;
}
-interface VoteCounterState {
- voted: boolean;
- count: number;
- showSignIn: boolean;
-}
-
-export class VoteCounter extends React.Component<VoteCounterProps, VoteCounterState> {
- constructor(props: VoteCounterProps) {
- super(props);
- this.state = {
- voted: props.post.hasVoted,
- count: props.post.votesCount,
- showSignIn: false
- };
- }
+export const VoteCounter = (props: VoteCounterProps) => {
+ const fider = useFider();
+ const [hasVoted, setHasVoted] = useState(props.post.hasVoted);
+ const [votesCount, setVotesCount] = useState(props.post.votesCount);
+ const [isSignInModalOpen, setIsSignInModalOpen] = useState(false);
- private voteOrUndo = async () => {
- if (!Fider.session.isAuthenticated) {
- this.setState({ showSignIn: true });
+ const voteOrUndo = async () => {
+ if (!fider.session.isAuthenticated) {
+ setIsSignInModalOpen(true);
return;
}
- const action = this.state.voted ? actions.removeVote : actions.addVote;
+ const action = hasVoted ? actions.removeVote : actions.addVote;
- const response = await action(this.props.post.number);
+ const response = await action(props.post.number);
if (response.ok) {
- this.setState(state => ({
- voted: !state.voted,
- count: state.count + (state.voted ? -1 : 1)
- }));
+ setVotesCount(votesCount + (hasVoted ? -1 : 1));
+ setHasVoted(!hasVoted);
}
};
- private hideModal = () => {
- this.setState({ showSignIn: false });
- };
+ const hideModal = () => setIsSignInModalOpen(false);
- public render() {
- const status = PostStatus.Get(this.props.post.status);
+ const status = PostStatus.Get(props.post.status);
- const className = classSet({
- "m-voted": !status.closed && this.state.voted,
- "m-disabled": status.closed,
- "no-touch": !device.isTouch()
- });
+ const className = classSet({
+ "m-voted": !status.closed && hasVoted,
+ "m-disabled": status.closed,
+ "no-touch": !device.isTouch()
+ });
- const vote = (
- <button className={className} onClick={this.voteOrUndo}>
- <FaCaretUp />
- {this.state.count}
- </button>
- );
+ const vote = (
+ <button className={className} onClick={voteOrUndo}>
+ <FaCaretUp />
+ {votesCount}
+ </button>
+ );
- const disabled = (
- <button className={className}>
- <FaCaretUp />
- {this.state.count}
- </button>
- );
+ const disabled = (
+ <button className={className}>
+ <FaCaretUp />
+ {votesCount}
+ </button>
+ );
- return (
- <>
- <SignInModal isOpen={this.state.showSignIn} onClose={this.hideModal} />
- <div className="c-vote-counter">{status.closed ? disabled : vote}</div>
- </>
- );
- }
-}
+ return (
+ <>
+ <SignInModal isOpen={isSignInModalOpen} onClose={hideModal} />
+ <div className="c-vote-counter">{status.closed ? disabled : vote}</div>
+ </>
+ );
+};
diff --git a/public/components/common/CardInfo.tsx b/public/components/common/CardInfo.tsx
index 59e026a79..60a9413c1 100644
--- a/public/components/common/CardInfo.tsx
+++ b/public/components/common/CardInfo.tsx
@@ -1,6 +1,6 @@
import React from "react";
import "./CardInfo.scss";
-import { Fider } from "@fider/services";
+import { useFider } from "@fider/hooks";
const visa = require("@fider/assets/images/card-visa.svg");
const diners = require("@fider/assets/images/card-diners.svg");
@@ -18,9 +18,11 @@ interface CardBrandProps {
}
export const CardInfo = (props: CardBrandProps) => {
+ const fider = useFider();
+
return (
<p className="c-card-info">
- <img src={`${Fider.settings.globalAssetsURL}${brandImage(props.brand)}`} alt={props.brand} />
+ <img src={`${fider.settings.globalAssetsURL}${brandImage(props.brand)}`} alt={props.brand} />
<span>
**** **** **** {props.last4}{" "}
<span className="c-card-info-exp">
diff --git a/public/components/common/Header.tsx b/public/components/common/Header.tsx
index 9a9f3fcca..414211c23 100644
--- a/public/components/common/Header.tsx
+++ b/public/components/common/Header.tsx
@@ -1,97 +1,85 @@
import "./Header.scss";
-import React from "react";
+import React, { useState, useEffect } from "react";
import { SignInModal, EnvironmentInfo, Avatar, TenantLogo, TenantStatusInfo } from "@fider/components";
-import { actions, Fider } from "@fider/services";
+import { actions } from "@fider/services";
import { FaUser, FaCog, FaCaretDown } from "react-icons/fa";
+import { useFider } from "@fider/hooks";
-interface HeaderState {
- showSignIn: boolean;
- unreadNotifications: number;
-}
+export const Header = () => {
+ const fider = useFider();
+ const [isSignInModalOpen, setIsSignInModalOpen] = useState(false);
+ const [unreadNotifications, setUnreadNotifications] = useState(0);
-export class Header extends React.Component<{}, HeaderState> {
- constructor(props: {}) {
- super(props);
- this.state = {
- showSignIn: false,
- unreadNotifications: 0
- };
- }
-
- public componentDidMount(): void {
- if (Fider.session.isAuthenticated) {
+ useEffect(() => {
+ if (fider.session.isAuthenticated) {
actions.getTotalUnreadNotifications().then(result => {
if (result.ok && result.data > 0) {
- this.setState({ unreadNotifications: result.data });
+ setUnreadNotifications(result.data);
}
});
}
- }
+ }, [fider.session.isAuthenticated]);
- private showModal = () => {
- if (!Fider.session.isAuthenticated) {
- this.setState({ showSignIn: true });
+ const showModal = () => {
+ if (!fider.session.isAuthenticated) {
+ setIsSignInModalOpen(true);
}
};
- private hideModal = () => {
- this.setState({ showSignIn: false });
- };
+ const hideModal = () => setIsSignInModalOpen(false);
- public render() {
- const items = Fider.session.isAuthenticated && (
- <div className="c-menu-user">
- <div className="c-menu-user-heading">
- <FaUser /> <span>{Fider.session.user.name}</span>
- </div>
- <a href="/settings" className="c-menu-user-item">
- Settings
- </a>
- <a href="/notifications" className="c-menu-user-item">
- Notifications
- {this.state.unreadNotifications > 0 && <div className="c-unread-count">{this.state.unreadNotifications}</div>}
- </a>
- <div className="c-menu-user-divider" />
- {Fider.session.user.isCollaborator && [
- <div key={1} className="c-menu-user-heading">
- <FaCog /> <span>Administration</span>
- </div>,
- <a key={2} href="/admin" className="c-menu-user-item">
- Site Settings
- </a>,
- <div key={5} className="c-menu-user-divider" />
- ]}
- <a href="/signout?redirect=/" className="c-menu-user-item signout">
- Sign out
- </a>
+ const items = fider.session.isAuthenticated && (
+ <div className="c-menu-user">
+ <div className="c-menu-user-heading">
+ <FaUser /> <span>{fider.session.user.name}</span>
</div>
- );
+ <a href="/settings" className="c-menu-user-item">
+ Settings
+ </a>
+ <a href="/notifications" className="c-menu-user-item">
+ Notifications
+ {unreadNotifications > 0 && <div className="c-unread-count">{unreadNotifications}</div>}
+ </a>
+ <div className="c-menu-user-divider" />
+ {fider.session.user.isCollaborator && [
+ <div key={1} className="c-menu-user-heading">
+ <FaCog /> <span>Administration</span>
+ </div>,
+ <a key={2} href="/admin" className="c-menu-user-item">
+ Site Settings
+ </a>,
+ <div key={5} className="c-menu-user-divider" />
+ ]}
+ <a href="/signout?redirect=/" className="c-menu-user-item signout">
+ Sign out
+ </a>
+ </div>
+ );
- const showRightMenu = Fider.session.isAuthenticated || !Fider.session.tenant.isPrivate;
- return (
- <div id="c-header">
- <EnvironmentInfo />
- <SignInModal isOpen={this.state.showSignIn} onClose={this.hideModal} />
- <div className="c-menu">
- <div className="container">
- <a href="/" className="c-menu-item-title">
- <TenantLogo size={100} />
- <span>{Fider.session.tenant.name}</span>
- </a>
- {showRightMenu && (
- <div onClick={this.showModal} className="c-menu-item-signin">
- {Fider.session.isAuthenticated && <Avatar user={Fider.session.user} />}
- {this.state.unreadNotifications > 0 && <div className="c-unread-dot" />}
- {!Fider.session.isAuthenticated && <span>Sign in</span>}
- {Fider.session.isAuthenticated && <FaCaretDown />}
- {items}
- </div>
- )}
- </div>
+ const showRightMenu = fider.session.isAuthenticated || !fider.session.tenant.isPrivate;
+ return (
+ <div id="c-header">
+ <EnvironmentInfo />
+ <SignInModal isOpen={isSignInModalOpen} onClose={hideModal} />
+ <div className="c-menu">
+ <div className="container">
+ <a href="/" className="c-menu-item-title">
+ <TenantLogo size={100} />
+ <span>{fider.session.tenant.name}</span>
+ </a>
+ {showRightMenu && (
+ <div onClick={showModal} className="c-menu-item-signin">
+ {fider.session.isAuthenticated && <Avatar user={fider.session.user} />}
+ {unreadNotifications > 0 && <div className="c-unread-dot" />}
+ {!fider.session.isAuthenticated && <span>Sign in</span>}
+ {fider.session.isAuthenticated && <FaCaretDown />}
+ {items}
+ </div>
+ )}
</div>
- <TenantStatusInfo />
</div>
- );
- }
-}
+ <TenantStatusInfo />
+ </div>
+ );
+};
diff --git a/public/components/common/SignInControl.tsx b/public/components/common/SignInControl.tsx
index 6e1fdf09c..9b920a44a 100644
--- a/public/components/common/SignInControl.tsx
+++ b/public/components/common/SignInControl.tsx
@@ -2,7 +2,8 @@ import "./SignInControl.scss";
import React, { useState } from "react";
import { SocialSignInButton, Form, Button, Input, Message } from "@fider/components";
-import { device, actions, Failure, Fider, isCookieEnabled } from "@fider/services";
+import { device, actions, Failure, isCookieEnabled } from "@fider/services";
+import { useFider } from "@fider/hooks";
interface SignInControlProps {
useEmail: boolean;
@@ -11,6 +12,7 @@ interface SignInControlProps {
}
export const SignInControl: React.FunctionComponent<SignInControlProps> = props => {
+ const fider = useFider();
const [email, setEmail] = useState("");
const [error, setError] = useState<Failure | undefined>(undefined);
@@ -27,7 +29,7 @@ export const SignInControl: React.FunctionComponent<SignInControlProps> = props
}
};
- const providersLen = Fider.settings.oauth.length;
+ const providersLen = fider.settings.oauth.length;
if (!isCookieEnabled()) {
return (
@@ -43,7 +45,7 @@ export const SignInControl: React.FunctionComponent<SignInControlProps> = props
{providersLen > 0 && (
<div className="l-signin-social">
<div className="row">
- {Fider.settings.oauth.map((o, i) => (
+ {fider.settings.oauth.map((o, i) => (
<React.Fragment key={o.provider}>
{i % 4 === 0 && <div className="col-lf" />}
<div
diff --git a/public/components/common/form/TextArea.tsx b/public/components/common/form/TextArea.tsx
index 89e07237e..b8dfcb816 100644
--- a/public/components/common/form/TextArea.tsx
+++ b/public/components/common/form/TextArea.tsx
@@ -12,7 +12,7 @@ interface TextAreaProps {
minRows?: number;
placeholder?: string;
onChange?: (value: string) => void;
- inputRef?: (node: HTMLTextAreaElement) => void;
+ inputRef?: React.MutableRefObject<any>;
onFocus?: React.FocusEventHandler<HTMLTextAreaElement>;
}
diff --git a/public/pages/Home/components/PostFilter.tsx b/public/pages/Home/components/PostFilter.tsx
index 115c9900d..99cb08df6 100644
--- a/public/pages/Home/components/PostFilter.tsx
+++ b/public/pages/Home/components/PostFilter.tsx
@@ -3,7 +3,7 @@ import "./PostFilter.scss";
import React from "react";
import { PostStatus } from "@fider/models";
import { DropDown, DropDownItem } from "@fider/components";
-import { Fider } from "@fider/services";
+import { useFider } from "@fider/hooks";
interface PostFilterProps {
activeView: string;
@@ -12,6 +12,8 @@ interface PostFilterProps {
}
export const PostFilter = (props: PostFilterProps) => {
+ const fider = useFider();
+
const handleChangeView = (item: DropDownItem) => {
props.viewChanged(item.value as string);
};
@@ -23,7 +25,7 @@ export const PostFilter = (props: PostFilterProps) => {
{ value: "most-discussed", label: "Most Discussed" }
];
- if (Fider.session.isAuthenticated) {
+ if (fider.session.isAuthenticated) {
options.push({ value: "my-votes", label: "My Votes" });
}
diff --git a/public/pages/ShowPost/components/CommentInput.tsx b/public/pages/ShowPost/components/CommentInput.tsx
index 8b54e6272..084012271 100644
--- a/public/pages/ShowPost/components/CommentInput.tsx
+++ b/public/pages/ShowPost/components/CommentInput.tsx
@@ -1,114 +1,81 @@
-import React from "react";
+import React, { useState, useRef } from "react";
import { Post, ImageUpload } from "@fider/models";
import { Avatar, UserName, Button, TextArea, Form, MultiImageUploader } from "@fider/components/common";
import { SignInModal } from "@fider/components";
import { cache, actions, Failure, Fider } from "@fider/services";
+import { useFider } from "@fider/hooks";
interface CommentInputProps {
post: Post;
}
-interface CommentInputState {
- content: string;
- error?: Failure;
- showSignIn: boolean;
- attachments: ImageUpload[];
-}
-
const CACHE_TITLE_KEY = "CommentInput-Comment-";
-export class CommentInput extends React.Component<CommentInputProps, CommentInputState> {
- private input!: HTMLTextAreaElement;
-
- constructor(props: CommentInputProps) {
- super(props);
-
- this.state = {
- content: (Fider.session.isAuthenticated && cache.session.get(this.getCacheKey())) || "",
- showSignIn: false,
- attachments: []
- };
- }
-
- private getCacheKey(): string {
- return `${CACHE_TITLE_KEY}${this.props.post.id}`;
- }
+export const CommentInput = (props: CommentInputProps) => {
+ const getCacheKey = () => `${CACHE_TITLE_KEY}${props.post.id}`;
- private commentChanged = (content: string) => {
- cache.session.set(this.getCacheKey(), content);
- this.setState({ content });
- };
+ const fider = useFider();
+ const inputRef = useRef<HTMLTextAreaElement>();
+ const [content, setContent] = useState((fider.session.isAuthenticated && cache.session.get(getCacheKey())) || "");
+ const [isSignInModalOpen, setIsSignInModalOpen] = useState(false);
+ const [attachments, setAttachments] = useState<ImageUpload[]>([]);
+ const [error, setError] = useState<Failure | undefined>(undefined);
- private setAttachments = (attachments: ImageUpload[]) => {
- this.setState({ attachments });
+ const commentChanged = (newContent: string) => {
+ cache.session.set(getCacheKey(), newContent);
+ setContent(newContent);
};
- private hideModal = () => {
- this.setState({ showSignIn: false });
- };
+ const hideModal = () => setIsSignInModalOpen(false);
+ const clearError = () => setError(undefined);
- public submit = async () => {
- this.setState({
- error: undefined
- });
+ const submit = async () => {
+ clearError();
- const result = await actions.createComment(this.props.post.number, this.state.content, this.state.attachments);
+ const result = await actions.createComment(props.post.number, content, attachments);
if (result.ok) {
- cache.session.remove(this.getCacheKey());
+ cache.session.remove(getCacheKey());
location.reload();
} else {
- this.setState({
- error: result.error
- });
+ setError(result.error);
}
};
- private handleOnFocus = () => {
- if (!Fider.session.isAuthenticated) {
- this.input.blur();
- this.setState({ showSignIn: true });
+ const handleOnFocus = () => {
+ if (!fider.session.isAuthenticated && inputRef.current) {
+ inputRef.current.blur();
+ setIsSignInModalOpen(true);
}
};
- private setInputRef = (e: HTMLTextAreaElement) => {
- this.input = e;
- };
-
- public render() {
- return (
- <>
- <SignInModal isOpen={this.state.showSignIn} onClose={this.hideModal} />
- <div className={`c-comment-input ${Fider.session.isAuthenticated && "m-authenticated"}`}>
- {Fider.session.isAuthenticated && <Avatar user={Fider.session.user} />}
- <Form error={this.state.error}>
- {Fider.session.isAuthenticated && <UserName user={Fider.session.user} />}
- <TextArea
- placeholder="Write a comment..."
- field="content"
- value={this.state.content}
- minRows={1}
- onChange={this.commentChanged}
- onFocus={this.handleOnFocus}
- inputRef={this.setInputRef}
- />
- {this.state.content && (
- <MultiImageUploader
- field="attachments"
- maxUploads={2}
- previewMaxWidth={100}
- onChange={this.setAttachments}
- />
- )}
- {this.state.content && (
- <Button color="positive" onClick={this.submit}>
+ return (
+ <>
+ <SignInModal isOpen={isSignInModalOpen} onClose={hideModal} />
+ <div className={`c-comment-input ${Fider.session.isAuthenticated && "m-authenticated"}`}>
+ {Fider.session.isAuthenticated && <Avatar user={Fider.session.user} />}
+ <Form error={error}>
+ {Fider.session.isAuthenticated && <UserName user={Fider.session.user} />}
+ <TextArea
+ placeholder="Write a comment..."
+ field="content"
+ value={content}
+ minRows={1}
+ onChange={commentChanged}
+ onFocus={handleOnFocus}
+ inputRef={inputRef}
+ />
+ {content && (
+ <>
+ <MultiImageUploader field="attachments" maxUploads={2} previewMaxWidth={100} onChange={setAttachments} />
+ <Button color="positive" onClick={submit}>
Submit
</Button>
- )}
- </Form>
- </div>
- </>
- );
- }
-}
+ </>
+ )}
+ </Form>
+ </div>
+ </>
+ );
+};
diff --git a/public/pages/ShowPost/components/ModerationPanel.tsx b/public/pages/ShowPost/components/ModerationPanel.tsx
index e988d559e..8bc673f9f 100644
--- a/public/pages/ShowPost/components/ModerationPanel.tsx
+++ b/public/pages/ShowPost/components/ModerationPanel.tsx
@@ -1,95 +1,76 @@
-import React from "react";
+import React, { useState } from "react";
import { PostStatus, Post } from "@fider/models";
-import { actions, navigator, Failure, Fider } from "@fider/services";
+import { actions, navigator, Failure } from "@fider/services";
import { Form, Modal, Button, List, ListItem, TextArea } from "@fider/components";
+import { useFider } from "@fider/hooks";
interface ModerationPanelProps {
post: Post;
}
-interface ModerationPanelState {
- showConfirmation: boolean;
- text: string;
- error?: Failure;
-}
+export const ModerationPanel = (props: ModerationPanelProps) => {
+ const fider = useFider();
+ const [showConfirmation, setShowConfirmation] = useState(false);
+ const [text, setText] = useState("");
+ const [error, setError] = useState<Failure>();
-export class ModerationPanel extends React.Component<ModerationPanelProps, ModerationPanelState> {
- constructor(props: ModerationPanelProps) {
- super(props);
- this.state = {
- text: "",
- showConfirmation: false
- };
- }
+ const hideModal = async () => setShowConfirmation(false);
+ const showModal = async () => setShowConfirmation(true);
- private delete = async () => {
- const response = await actions.deletePost(this.props.post.number, this.state.text);
+ const handleDelete = async () => {
+ const response = await actions.deletePost(props.post.number, text);
if (response.ok) {
- await this.hideModal();
+ hideModal();
navigator.goHome();
} else if (response.error) {
- this.setState({ error: this.state.error });
+ setError(response.error);
}
};
- private hideModal = async () => {
- this.setState({ showConfirmation: false });
- };
-
- private showModal = async () => {
- this.setState({ showConfirmation: true });
- };
-
- private setText = (text: string) => {
- this.setState({ text });
- };
+ const status = PostStatus.Get(props.post.status);
+ if (!fider.session.isAuthenticated || !fider.session.user.isAdministrator || status.closed) {
+ return null;
+ }
- public render() {
- const status = PostStatus.Get(this.props.post.status);
- if (!Fider.session.isAuthenticated || !Fider.session.user.isAdministrator || status.closed) {
- return null;
- }
+ const modal = (
+ <Modal.Window isOpen={showConfirmation} onClose={hideModal} center={false} size="large">
+ <Modal.Content>
+ <Form error={error}>
+ <TextArea
+ field="text"
+ onChange={setText}
+ value={text}
+ placeholder="Why are you deleting this post? (optional)"
+ >
+ <span className="info">
+ This operation <strong>cannot</strong> be undone.
+ </span>
+ </TextArea>
+ </Form>
+ </Modal.Content>
- const modal = (
- <Modal.Window isOpen={this.state.showConfirmation} onClose={this.hideModal} center={false} size="large">
- <Modal.Content>
- <Form error={this.state.error}>
- <TextArea
- field="text"
- onChange={this.setText}
- value={this.state.text}
- placeholder="Why are you deleting this post? (optional)"
- >
- <span className="info">
- This operation <strong>cannot</strong> be undone.
- </span>
- </TextArea>
- </Form>
- </Modal.Content>
+ <Modal.Footer>
+ <Button color="danger" onClick={handleDelete}>
+ Delete
+ </Button>
+ <Button color="cancel" onClick={hideModal}>
+ Cancel
+ </Button>
+ </Modal.Footer>
+ </Modal.Window>
+ );
- <Modal.Footer>
- <Button color="danger" onClick={this.delete}>
+ return (
+ <>
+ {modal}
+ <span className="subtitle">Moderation</span>
+ <List>
+ <ListItem>
+ <Button color="danger" size="tiny" fluid={true} onClick={showModal}>
Delete
</Button>
- <Button color="cancel" onClick={this.hideModal}>
- Cancel
- </Button>
- </Modal.Footer>
- </Modal.Window>
- );
-
- return (
- <>
- {modal}
- <span className="subtitle">Moderation</span>
- <List>
- <ListItem>
- <Button color="danger" size="tiny" fluid={true} onClick={this.showModal}>
- Delete
- </Button>
- </ListItem>
- </List>
- </>
- );
- }
-}
+ </ListItem>
+ </List>
+ </>
+ );
+};
diff --git a/public/pages/ShowPost/components/ShowComment.tsx b/public/pages/ShowPost/components/ShowComment.tsx
index b4f6c116a..b8d4597d2 100644
--- a/public/pages/ShowPost/components/ShowComment.tsx
+++ b/public/pages/ShowPost/components/ShowComment.tsx
@@ -1,4 +1,4 @@
-import React from "react";
+import React, { useState } from "react";
import { Comment, Post, ImageUpload } from "@fider/models";
import {
Avatar,
@@ -14,98 +14,75 @@ import {
ImageViewer,
MultiImageUploader
} from "@fider/components";
-import { formatDate, Failure, actions, Fider } from "@fider/services";
+import { formatDate, Failure, actions } from "@fider/services";
import { FaEllipsisH } from "react-icons/fa";
+import { useFider } from "@fider/hooks";
interface ShowCommentProps {
post: Post;
comment: Comment;
}
-interface ShowCommentState {
- comment: Comment;
- isEditing: boolean;
- newContent: string;
- attachments: ImageUpload[];
- error?: Failure;
- showDeleteConfirmation: boolean;
-}
-
-export class ShowComment extends React.Component<ShowCommentProps, ShowCommentState> {
- constructor(props: ShowCommentProps) {
- super(props);
- this.state = {
- comment: props.comment,
- isEditing: false,
- newContent: "",
- showDeleteConfirmation: false,
- attachments: []
- };
- }
-
- private canEditComment(comment: Comment): boolean {
- if (Fider.session.isAuthenticated) {
- return Fider.session.user.isCollaborator || comment.user.id === Fider.session.user.id;
+export const ShowComment = (props: ShowCommentProps) => {
+ const fider = useFider();
+ const [isEditing, setIsEditing] = useState(false);
+ const [newContent, setNewContent] = useState("");
+ const [isDeleteConfirmationModalOpen, setIsDeleteConfirmationModalOpen] = useState(false);
+ const [attachments, setAttachments] = useState<ImageUpload[]>([]);
+ const [error, setError] = useState<Failure>();
+
+ const canEditComment = (): boolean => {
+ if (fider.session.isAuthenticated) {
+ return fider.session.user.isCollaborator || props.comment.user.id === fider.session.user.id;
}
return false;
- }
+ };
- private cancelEdit = async () => {
- this.setState({
- isEditing: false,
- newContent: "",
- error: undefined
- });
+ const clearError = () => setError(undefined);
+
+ const cancelEdit = async () => {
+ setIsEditing(false);
+ setNewContent("");
+ clearError();
};
- private saveEdit = async () => {
- const response = await actions.updateComment(
- this.props.post.number,
- this.state.comment.id,
- this.state.newContent,
- this.state.attachments
- );
+ const saveEdit = async () => {
+ const response = await actions.updateComment(props.post.number, props.comment.id, newContent, attachments);
if (response.ok) {
location.reload();
} else {
- this.setState({ error: response.error });
+ setError(response.error);
}
};
- private setNewContent = (newContent: string) => {
- this.setState({ newContent });
- };
-
- private setAttachments = (attachments: ImageUpload[]) => {
- this.setState({ attachments });
- };
-
- private renderEllipsis = () => {
+ const renderEllipsis = () => {
return <FaEllipsisH />;
};
- private closeModal = async () => {
- this.setState({ showDeleteConfirmation: false });
+ const closeModal = async () => {
+ setIsDeleteConfirmationModalOpen(false);
};
- private deleteComment = async () => {
- const response = await actions.deleteComment(this.props.post.number, this.props.comment.id);
+ const deleteComment = async () => {
+ const response = await actions.deleteComment(props.post.number, props.comment.id);
if (response.ok) {
location.reload();
}
};
- private onActionSelected = (item: DropDownItem) => {
+ const onActionSelected = (item: DropDownItem) => {
if (item.value === "edit") {
- this.setState({ isEditing: true, newContent: this.state.comment.content, error: undefined });
+ setIsEditing(true);
+ setNewContent(props.comment.content);
+ clearError();
} else if (item.value === "delete") {
- this.setState({ showDeleteConfirmation: true });
+ setIsDeleteConfirmationModalOpen(true);
}
};
- private modal() {
+ const modal = () => {
return (
- <Modal.Window isOpen={this.state.showDeleteConfirmation} onClose={this.closeModal} center={false} size="small">
+ <Modal.Window isOpen={isDeleteConfirmationModalOpen} onClose={closeModal} center={false} size="small">
<Modal.Header>Delete Comment</Modal.Header>
<Modal.Content>
<p>
@@ -114,84 +91,84 @@ export class ShowComment extends React.Component<ShowCommentProps, ShowCommentSt
</Modal.Content>
<Modal.Footer>
- <Button color="danger" onClick={this.deleteComment}>
+ <Button color="danger" onClick={deleteComment}>
Delete
</Button>
- <Button color="cancel" onClick={this.closeModal}>
+ <Button color="cancel" onClick={closeModal}>
Cancel
</Button>
</Modal.Footer>
</Modal.Window>
);
- }
-
- public render() {
- const c = this.state.comment;
-
- const editedMetadata = !!c.editedAt && !!c.editedBy && (
- <div className="c-comment-metadata">
- <span title={`This comment has been edited by ${c.editedBy!.name} on ${formatDate(c.editedAt)}`}>· edited</span>
- </div>
- );
+ };
- return (
- <div className="c-comment">
- {this.modal()}
- <Avatar user={c.user} />
- <div className="c-comment-content">
- <UserName user={c.user} />
- <div className="c-comment-metadata">
- · <Moment date={c.createdAt} />
- </div>
- {editedMetadata}
- {!this.state.isEditing && this.canEditComment(c) && (
- <DropDown
- className="l-more-actions"
- direction="left"
- inline={true}
- style="simple"
- highlightSelected={false}
- items={[
- { label: "Edit", value: "edit" },
- { label: "Delete", value: "delete", render: <span style={{ color: "red" }}>Delete</span> }
- ]}
- onChange={this.onActionSelected}
- renderControl={this.renderEllipsis}
- />
+ const comment = props.comment;
+
+ const editedMetadata = !!comment.editedAt && !!comment.editedBy && (
+ <div className="c-comment-metadata">
+ <span title={`This comment has been edited by ${comment.editedBy!.name} on ${formatDate(comment.editedAt)}`}>
+ · edited
+ </span>
+ </div>
+ );
+
+ return (
+ <div className="c-comment">
+ {modal()}
+ <Avatar user={comment.user} />
+ <div className="c-comment-content">
+ <UserName user={comment.user} />
+ <div className="c-comment-metadata">
+ · <Moment date={comment.createdAt} />
+ </div>
+ {editedMetadata}
+ {!isEditing && canEditComment() && (
+ <DropDown
+ className="l-more-actions"
+ direction="left"
+ inline={true}
+ style="simple"
+ highlightSelected={false}
+ items={[
+ { label: "Edit", value: "edit" },
+ { label: "Delete", value: "delete", render: <span style={{ color: "red" }}>Delete</span> }
+ ]}
+ onChange={onActionSelected}
+ renderControl={renderEllipsis}
+ />
+ )}
+ <div className="c-comment-text">
+ {isEditing ? (
+ <Form error={error}>
+ <TextArea
+ field="content"
+ minRows={1}
+ value={newContent}
+ placeholder={comment.content}
+ onChange={setNewContent}
+ />
+ <MultiImageUploader
+ field="attachments"
+ bkeys={comment.attachments}
+ maxUploads={2}
+ previewMaxWidth={100}
+ onChange={setAttachments}
+ />
+ <Button size="tiny" onClick={saveEdit} color="positive">
+ Save
+ </Button>
+ <Button color="cancel" size="tiny" onClick={cancelEdit}>
+ Cancel
+ </Button>
+ </Form>
+ ) : (
+ <>
+ <MultiLineText text={comment.content} style="simple" />
+ {comment.attachments && comment.attachments.map(x => <ImageViewer key={x} bkey={x} />)}
+ </>
)}
- <div className="c-comment-text">
- {this.state.isEditing ? (
- <Form error={this.state.error}>
- <TextArea
- field="content"
- minRows={1}
- value={this.state.newContent}
- placeholder={c.content}
- onChange={this.setNewContent}
- />
- <MultiImageUploader
- field="attachments"
- bkeys={c.attachments}
- maxUploads={2}
- previewMaxWidth={100}
- onChange={this.setAttachments}
- />
- <Button size="tiny" onClick={this.saveEdit} color="positive">
- Save
- </Button>
- <Button color="cancel" size="tiny" onClick={this.cancelEdit}>
- Cancel
- </Button>
- </Form>
- ) : (
- <>
- <MultiLineText text={c.content} style="simple" />
- {c.attachments && c.attachments.map(x => <ImageViewer key={x} bkey={x} />)}
- </>
- )}
- </div>
</div>
</div>
- );
- }
-}
+ </div>
+ );
+};
diff --git a/public/pages/ShowPost/components/VotesPanel.tsx b/public/pages/ShowPost/components/VotesPanel.tsx
index facc84ec2..7313a39a5 100644
--- a/public/pages/ShowPost/components/VotesPanel.tsx
+++ b/public/pages/ShowPost/components/VotesPanel.tsx
@@ -1,9 +1,10 @@
import "./VotesPanel.scss";
-import React from "react";
+import React, { useState } from "react";
import { Post, Vote } from "@fider/models";
import { Avatar } from "@fider/components";
import { Fider, classSet } from "@fider/services";
+import { useFider } from "@fider/hooks";
import { VotesModal } from "./VotesModal";
interface VotesPanelProps {
@@ -11,60 +12,45 @@ interface VotesPanelProps {
votes: Vote[];
}
-interface VotesPanelState {
- showModal: boolean;
-}
-
-export class VotesPanel extends React.Component<VotesPanelProps, VotesPanelState> {
- constructor(props: VotesPanelProps) {
- super(props);
- this.state = {
- showModal: false
- };
- }
+export const VotesPanel = (props: VotesPanelProps) => {
+ const fider = useFider();
+ const [isVotesModalOpen, setIsVotesModalOpen] = useState(false);
- private showModal = () => {
- if (this.canShowAll()) {
- this.setState({ showModal: true });
+ const openModal = () => {
+ if (canShowAll()) {
+ setIsVotesModalOpen(true);
}
};
- private hideModal = () => {
- this.setState({ showModal: false });
- };
-
- private canShowAll = () => {
- return Fider.session.isAuthenticated && Fider.session.user.isCollaborator;
- };
-
- public render() {
- const extraVotesCount = this.props.post.votesCount - this.props.votes.length;
- const moreVotesClassName = classSet({
- "l-votes-more": true,
- clickable: this.canShowAll()
- });
-
- return (
- <>
- <VotesModal post={this.props.post} isOpen={this.state.showModal} onClose={this.hideModal} />
- <span className="subtitle">Voters</span>
- <div className="l-votes-list">
- {this.props.votes.map(x => (
- <Avatar key={x.user.id} user={x.user} />
- ))}
- {extraVotesCount > 0 && (
- <span onClick={this.showModal} className={moreVotesClassName}>
- +{extraVotesCount} more
- </span>
- )}
- {this.props.votes.length > 0 && extraVotesCount === 0 && this.canShowAll() && (
- <span onClick={this.showModal} className={moreVotesClassName}>
- see details
- </span>
- )}
- {this.props.votes.length === 0 && <span className="info">None yet</span>}
- </div>
- </>
- );
- }
-}
+ const closeModal = () => setIsVotesModalOpen(false);
+ const canShowAll = () => fider.session.isAuthenticated && Fider.session.user.isCollaborator;
+
+ const extraVotesCount = props.post.votesCount - props.votes.length;
+ const moreVotesClassName = classSet({
+ "l-votes-more": true,
+ clickable: canShowAll()
+ });
+
+ return (
+ <>
+ <VotesModal post={props.post} isOpen={isVotesModalOpen} onClose={closeModal} />
+ <span className="subtitle">Voters</span>
+ <div className="l-votes-list">
+ {props.votes.map(x => (
+ <Avatar key={x.user.id} user={x.user} />
+ ))}
+ {extraVotesCount > 0 && (
+ <span onClick={openModal} className={moreVotesClassName}>
+ +{extraVotesCount} more
+ </span>
+ )}
+ {props.votes.length > 0 && extraVotesCount === 0 && canShowAll() && (
+ <span onClick={openModal} className={moreVotesClassName}>
+ see details
+ </span>
+ )}
+ {props.votes.length === 0 && <span className="info">None yet</span>}
+ </div>
+ </>
+ );
+};