Skip to content

Commit

Permalink
refactor: refactor hook file
Browse files Browse the repository at this point in the history
  • Loading branch information
sundasnoreen12 committed Jul 15, 2024
1 parent 00e5de6 commit 42a2c94
Show file tree
Hide file tree
Showing 5 changed files with 93 additions and 77 deletions.
4 changes: 0 additions & 4 deletions src/discussions/data/selectors.js
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,3 @@ export const selectIsUserLearner = createSelector(
) || false
),
);

export const selectDraftComments = state => state.comments.draftComments || null;

export const selectDraftResponses = state => state.comments.draftResponses || null;
66 changes: 27 additions & 39 deletions src/discussions/post-comments/comments/comment/CommentEditor.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,16 +17,14 @@ import PostPreviewPanel from '../../../../components/PostPreviewPanel';
import useDispatchWithState from '../../../../data/hooks';
import DiscussionContext from '../../../common/context';
import {
selectDraftComments,
selectDraftResponses,
selectModerationSettings,
selectUserHasModerationPrivileges,
selectUserIsGroupTa,
selectUserIsStaff,
} from '../../../data/selectors';
import { formikCompatibleHandler, isFormikFieldInvalid } from '../../../utils';
import { getObjectById, useAddDraftContent, useRemoveDraftContent } from '../../data/hooks';
import { setDraftComment, setDraftResponse } from '../../data/slices';
import { useDraftContent } from '../../data/hooks';
import { setDraftComments, setDraftResponses } from '../../data/slices';
import { addComment, editComment } from '../../data/thunks';
import messages from '../../messages';

Expand All @@ -48,10 +46,9 @@ const CommentEditor = ({
const userIsGroupTa = useSelector(selectUserIsGroupTa);
const userIsStaff = useSelector(selectUserIsStaff);
const { editReasons } = useSelector(selectModerationSettings);
const comments = useSelector(selectDraftComments);
const responses = useSelector(selectDraftResponses);
const [submitting, dispatch] = useDispatchWithState();
const [editorContent, setEditorContent] = useState();
const draftContent = useDraftContent();

const canDisplayEditReason = (edit
&& (userHasModerationPrivileges || userIsGroupTa || userIsStaff)
Expand All @@ -69,7 +66,7 @@ const CommentEditor = ({
});

const initialValues = {
comment: rawBody,
comment: editorContent,
editReasonCode: lastEdit?.reasonCode || (userIsStaff && canDisplayEditReason ? 'violates-guidelines' : undefined),
};

Expand All @@ -79,25 +76,23 @@ const CommentEditor = ({
}, [onCloseEditor, initialValues]);

const DeleteEditorContent = async () => {
const { updatedResponses, updatedComments } = useRemoveDraftContent(responses, comments, parentId, id, threadId);
const { updatedResponses, updatedComments } = draftContent.removeDraftContent(parentId, id, threadId);
if (parentId) {
await dispatch(setDraftComment(updatedComments));
await dispatch(setDraftComments(updatedComments));
} else {
await dispatch(setDraftResponse(updatedResponses));
await dispatch(setDraftResponses(updatedResponses));
}
};

const saveUpdatedComment = useCallback(async (values, { resetForm }) => {
const clonedValues = { ...values };
clonedValues.comment = editorContent;
if (id) {
const payload = {
...clonedValues,
editReasonCode: clonedValues.editReasonCode || undefined,
...values,
editReasonCode: values.editReasonCode || undefined,
};
await dispatch(editComment(id, payload));
} else {
await dispatch(addComment(clonedValues.comment, threadId, parentId, enableInContextSidebar));
await dispatch(addComment(values.comment, threadId, parentId, enableInContextSidebar));
}
/* istanbul ignore if: TinyMCE is mocked so this cannot be easily tested */
if (editorRef.current) {
Expand All @@ -117,39 +112,33 @@ const CommentEditor = ({
}, [formRef]);

useEffect(() => {
let draftObject = null;
const draftHtml = draftContent.getDraftContent(parentId, threadId, id) || rawBody;
setEditorContent(draftHtml);
initialValues.comment = draftHtml;
}, [parentId, threadId, id]);

if (id) {
draftObject = parentId ? comments?.[id] : responses?.[id];
} else {
draftObject = parentId ? getObjectById(comments, parentId, true)
: getObjectById(responses, threadId, false);
const extractContent = (content) => {
if (typeof content === 'object') {
return content.target.getContent();
}

setEditorContent(draftObject?.content || '');
}, [responses, comments, parentId, threadId, id]);

return content;
};
const SaveDraftComment = async (content) => {
const { updatedResponses, updatedComments } = useAddDraftContent(
content,
responses,
comments,
const draftDataContent = extractContent(content);

const { updatedResponses, updatedComments } = draftContent.addDraftContent(
draftDataContent,
parentId,
id,
threadId,
);
if (parentId) {
await dispatch(setDraftComment(updatedComments));
await dispatch(setDraftComments(updatedComments));
} else {
await dispatch(setDraftResponse(updatedResponses));
await dispatch(setDraftResponses(updatedResponses));
}
};

const handleEditorChange = (content, setFieldValue) => {
setEditorContent(content);
setFieldValue('comment', content);
};

return (
<Formik
initialValues={initialValues}
Expand All @@ -164,7 +153,6 @@ const CommentEditor = ({
handleBlur,
handleChange,
resetForm,
setFieldValue,
}) => (
<Form onSubmit={handleSubmit} className={formClasses} ref={formRef}>
{canDisplayEditReason && (
Expand Down Expand Up @@ -203,8 +191,8 @@ const CommentEditor = ({
}
}
id={editorId}
value={editorContent || values.comment}
onEditorChange={(content) => handleEditorChange(content, setFieldValue)}
value={values.comment}
onEditorChange={formikCompatibleHandler(handleChange, 'comment')}
onBlur={(content) => {
formikCompatibleHandler(handleChange, 'comment');
SaveDraftComment(typeof content === 'object' ? content.target.getContent() : content);
Expand Down
88 changes: 58 additions & 30 deletions src/discussions/post-comments/data/hooks.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,8 @@ import { selectThread } from '../../posts/data/selectors';
import { markThreadAsRead } from '../../posts/data/thunks';
import { filterPosts } from '../../utils';
import {
selectCommentSortOrder, selectThreadComments, selectThreadCurrentPage, selectThreadHasMorePages,
selectCommentSortOrder, selectDraftComments, selectDraftResponses,
selectThreadComments, selectThreadCurrentPage, selectThreadHasMorePages,
} from './selectors';
import { fetchThreadComments } from './thunks';

Expand Down Expand Up @@ -104,42 +105,69 @@ export function useCommentsCount(postId) {
return commentsLength;
}

export const getObjectById = (draftList, id, isComment) => Object.values(draftList)
.find(draft => (isComment ? draft.parentId === id : draft.threadId === id));
export const useDraftContent = () => {
const comments = useSelector(selectDraftComments);
const responses = useSelector(selectDraftResponses);

export const useRemoveDraftContent = (responses, comments, parentId, id, threadId) => {
const updatedResponses = { ...responses };
const updatedComments = { ...comments };
const getObjectByParentId = (data, parentId, isComment, id) => Object.values(data)
.find(draft => (isComment ? draft.parentId === parentId && (id ? draft.id === id : draft.isNewContent === true)
: draft.threadId === parentId && (id ? draft.id === id : draft.isNewContent === true)));

if (!parentId) {
const responseObj = id ? updatedResponses[id] : getObjectById(responses, threadId, false);
delete updatedResponses[responseObj.id];
} else {
const commentObj = id ? updatedComments[id] : getObjectById(comments, parentId, true);
delete updatedComments[commentObj.id];
}
const updateDraftData = (draftData, newDraftObject) => ({
...draftData,
[newDraftObject.id]: newDraftObject,
});

return { updatedResponses, updatedComments };
};
const addDraftContent = (content, parentId, id, threadId) => {
const newObject = {
threadId, content, parentId, id: id || uuidv4(), isNewContent: !id,
};

const updateDraftList = (draftList, newDraftObject) => ({
...draftList,
[newDraftObject.id]: newDraftObject,
});
const updatedComments = parentId ? updateDraftData(comments, newObject) : comments;
const updatedResponses = !parentId ? updateDraftData(responses, newObject) : responses;

export const useAddDraftContent = (content, responses, comments, parentId, id, threadId) => {
let updatedResponses = { ...responses };
let updatedComments = { ...comments };
return { updatedComments, updatedResponses };
};

const newObject = {
threadId, content, parentId, id: id || uuidv4(),
const getDraftContent = (parentId, threadId, id) => {
if (id) {
return parentId ? comments?.[id]?.content : responses?.[id]?.content;
}

const data = parentId ? comments : responses;
const draftParentId = parentId || threadId;
const isComment = !!parentId;

return getObjectByParentId(data, draftParentId, isComment, id)?.content;
};

if (!parentId) {
updatedResponses = updateDraftList(responses, newObject);
} else {
updatedComments = updateDraftList(comments, newObject);
}
const removeDraftContent = (parentId, id, threadId) => {
const removeItem = (draftData, objId) => {
const { [objId]: _, ...newDraftData } = draftData;
return newDraftData;
};

return { updatedResponses, updatedComments };
let updatedResponses = responses;
let updatedComments = comments;

if (!parentId) {
const responseObj = id ? responses[id] : getObjectByParentId(responses, threadId, false, id);
if (responseObj) {
updatedResponses = removeItem(responses, responseObj.id);
}
} else {
const commentObj = id ? comments[id] : getObjectByParentId(comments, parentId, true, id);
if (commentObj) {
updatedComments = removeItem(comments, commentObj.id);
}
}

return { updatedResponses, updatedComments };
};

return {
addDraftContent,
getDraftContent,
removeDraftContent,
};
};
4 changes: 4 additions & 0 deletions src/discussions/post-comments/data/selectors.js
Original file line number Diff line number Diff line change
Expand Up @@ -47,3 +47,7 @@ export const selectCommentCurrentPage = commentId => (
export const selectCommentsStatus = state => state.comments.status;

export const selectCommentSortOrder = state => state.comments.sortOrder;

export const selectDraftComments = state => state.comments.draftComments;

export const selectDraftResponses = state => state.comments.draftResponses;
8 changes: 4 additions & 4 deletions src/discussions/post-comments/data/slices.js
Original file line number Diff line number Diff line change
Expand Up @@ -259,13 +259,13 @@ const commentsSlice = createSlice({
sortOrder: payload,
}
),
setDraftComment: (state, { payload }) => (
setDraftComments: (state, { payload }) => (
{
...state,
draftComments: payload,
}
),
setDraftResponse: (state, { payload }) => (
setDraftResponses: (state, { payload }) => (
{
...state,
draftResponses: payload,
Expand Down Expand Up @@ -296,8 +296,8 @@ export const {
deleteCommentRequest,
deleteCommentSuccess,
setCommentSortOrder,
setDraftComment,
setDraftResponse,
setDraftComments,
setDraftResponses,
} = commentsSlice.actions;

export const commentsReducer = commentsSlice.reducer;

0 comments on commit 42a2c94

Please sign in to comment.