Skip to content

A Q&A platform software for teams at any scales. Whether it's a community forum, help center, or knowledge management platform, you can always count on Apache Answer.

feat: add draft for write answer or question #117

shuaib03269b38322
diff --git a/i18n/en_US.yaml b/i18n/en_US.yaml
index 69a39c12..c0ebc03e 100644
--- a/i18n/en_US.yaml
+++ b/i18n/en_US.yaml
@@ -819,6 +819,7 @@ ui:
approve: Approve
reject: Reject
skip: Skip
+ discard_draft: Discard draft
search:
title: Search Results
keywords: Keywords
@@ -1409,4 +1410,6 @@ ui:
prompt:
leave_page: "Are you sure you want to leave the page?"
changes_not_save: "Your changes may not be saved."
+ draft:
+ discard_confirm: "Are you sure you want to discard your draft?"
diff --git a/ui/src/common/constants.ts b/ui/src/common/constants.ts
index 23844d4f..ce692b6a 100644
--- a/ui/src/common/constants.ts
+++ b/ui/src/common/constants.ts
@@ -6,6 +6,9 @@ export const LOGGED_USER_STORAGE_KEY = '_a_lui_';
export const LOGGED_TOKEN_STORAGE_KEY = '_a_ltk_';
export const REDIRECT_PATH_STORAGE_KEY = '_a_rp_';
export const CAPTCHA_CODE_STORAGE_KEY = '_a_captcha_';
+export const DRAFT_QUESTION_STORAGE_KEY = '_a_dq_';
+export const DRAFT_ANSWER_STORAGE_KEY = '_a_da_';
+export const DRAFT_TIMESIGH_STORAGE_KEY = '|_a_t_s_|';
export const ADMIN_LIST_STATUS = {
// normal;
diff --git a/ui/src/components/SchemaForm/index.tsx b/ui/src/components/SchemaForm/index.tsx
index a004deb6..7ea53322 100644
--- a/ui/src/components/SchemaForm/index.tsx
+++ b/ui/src/components/SchemaForm/index.tsx
@@ -206,7 +206,6 @@ const SchemaForm: ForwardRefRenderFunction<IRef, IProps> = (
const errors = requiredValidator();
if (errors.length > 0) {
formData = errors.reduce((acc, cur) => {
- console.log('schema.properties[cur]', cur);
acc[cur] = {
...formData[cur],
isInvalid: true,
diff --git a/ui/src/pages/Questions/Ask/index.tsx b/ui/src/pages/Questions/Ask/index.tsx
index 016c27d6..ac973634 100644
--- a/ui/src/pages/Questions/Ask/index.tsx
+++ b/ui/src/pages/Questions/Ask/index.tsx
@@ -10,6 +10,7 @@ import { isEqual } from 'lodash';
import { usePageTags, usePromptWithUnload } from '@/hooks';
import { Editor, EditorRef, TagSelector } from '@/components';
import type * as Type from '@/common/interface';
+import { DRAFT_QUESTION_STORAGE_KEY } from '@/common/constants';
import {
saveQuestion,
questionDetail,
@@ -19,7 +20,7 @@ import {
useQueryQuestionByTitle,
getTagsBySlugName,
} from '@/services';
-import { handleFormError } from '@/utils';
+import { handleFormError, SaveDraft, storageExpires } from '@/utils';
import { pathFactory } from '@/router/pathFactory';
import SearchQuestion from './components/SearchQuestion';
@@ -32,6 +33,8 @@ interface FormDataItem {
edit_summary: Type.FormValue<string>;
}
+const saveDraft = new SaveDraft({ type: 'question' });
+
const Ask = () => {
const initFormData = {
title: {
@@ -66,6 +69,7 @@ const Ask = () => {
const [checked, setCheckState] = useState(false);
const [contentChanged, setContentChanged] = useState(false);
const [focusType, setForceType] = useState('');
+ const [hasDraft, setHasDraft] = useState(false);
const resetForm = () => {
setFormData(initFormData);
setCheckState(false);
@@ -98,6 +102,33 @@ const Ask = () => {
isEdit ? '' : formData.title.value,
);
+ const removeDraft = () => {
+ saveDraft.remove();
+ setHasDraft(false);
+ };
+
+ useEffect(() => {
+ if (!qid) {
+ initQueryTags();
+ const draft = storageExpires.get(DRAFT_QUESTION_STORAGE_KEY);
+ if (draft) {
+ formData.title.value = draft.title;
+ formData.content.value = draft.content;
+ formData.tags.value = draft.tags;
+ formData.answer.value = draft.answer;
+ setCheckState(Boolean(draft.answer));
+ setHasDraft(true);
+ setFormData({ ...formData });
+ } else {
+ resetForm();
+ }
+ }
+
+ return () => {
+ resetForm();
+ };
+ }, [qid]);
+
useEffect(() => {
const { title, tags, content, answer } = formData;
const { title: editTitle, tags: editTags, content: editContent } = immData;
@@ -119,10 +150,22 @@ const Ask = () => {
return;
}
+ // save draft
+ saveDraft.save({
+ params: {
+ title: title.value,
+ tags: tags.value,
+ content: content.value,
+ answer: answer.value,
+ },
+ callback: () => setHasDraft(true),
+ });
+
// write
if (title.value || tags.value.length > 0 || content.value || answer.value) {
setContentChanged(true);
} else {
+ removeDraft();
setContentChanged(false);
}
}, [formData]);
@@ -131,12 +174,6 @@ const Ask = () => {
when: contentChanged,
});
- useEffect(() => {
- if (!isEdit) {
- resetForm();
- initQueryTags();
- }
- }, [isEdit]);
const { data: revisions = [] } = useQueryRevisions(qid);
useEffect(() => {
@@ -191,6 +228,14 @@ const Ask = () => {
},
});
+ const deleteDraft = () => {
+ const res = window.confirm(t('discard_confirm', { keyPrefix: 'draft' }));
+ if (res) {
+ removeDraft();
+ resetForm();
+ }
+ };
+
const handleSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
setContentChanged(false);
event.preventDefault();
@@ -248,6 +293,7 @@ const Ask = () => {
navigate(pathFactory.questionLanding(id));
}
}
+ deleteDraft();
}
};
const backPage = () => {
@@ -380,6 +426,12 @@ const Ask = () => {
<Button variant="link" onClick={backPage}>
{t('cancel', { keyPrefix: 'btns' })}
</Button>
+
+ {hasDraft && (
+ <Button variant="link" onClick={deleteDraft}>
+ {t('discard_draft', { keyPrefix: 'btns' })}
+ </Button>
+ )}
</div>
)}
{!isEdit && (
@@ -411,7 +463,6 @@ const Ask = () => {
}}
/>
<Form.Control
- value={formData.answer.value}
type="text"
isInvalid={formData.answer.isInvalid}
hidden
@@ -424,9 +475,14 @@ const Ask = () => {
</>
)}
{checked && (
- <Button type="submit" className="mt-3">
- {t('post_question&answer')}
- </Button>
+ <div className="mt-3">
+ <Button type="submit">{t('post_question&answer')}</Button>
+ {hasDraft && (
+ <Button variant="link" className="ms-2" onClick={deleteDraft}>
+ {t('discard_draft', { keyPrefix: 'btns' })}
+ </Button>
+ )}
+ </div>
)}
</Form>
</Col>
diff --git a/ui/src/pages/Questions/Detail/components/WriteAnswer/index.tsx b/ui/src/pages/Questions/Detail/components/WriteAnswer/index.tsx
index 6886a36c..18dec7df 100644
--- a/ui/src/pages/Questions/Detail/components/WriteAnswer/index.tsx
+++ b/ui/src/pages/Questions/Detail/components/WriteAnswer/index.tsx
@@ -1,4 +1,4 @@
-import { memo, useState, FC } from 'react';
+import { memo, useState, FC, useEffect } from 'react';
import { Form, Button } from 'react-bootstrap';
import { useTranslation } from 'react-i18next';
@@ -9,7 +9,8 @@ import { usePromptWithUnload } from '@/hooks';
import { Editor, Modal, TextArea } from '@/components';
import { FormDataType } from '@/common/interface';
import { postAnswer } from '@/services';
-import { guard, handleFormError } from '@/utils';
+import { guard, handleFormError, SaveDraft, storageExpires } from '@/utils';
+import { DRAFT_ANSWER_STORAGE_KEY } from '@/common/constants';
interface Props {
visible?: boolean;
@@ -21,6 +22,8 @@ interface Props {
callback?: (obj) => void;
}
+const saveDraft = new SaveDraft({ type: 'answer' });
+
const Index: FC<Props> = ({ visible = false, data, callback }) => {
const { t } = useTranslation('translation', {
keyPrefix: 'question_detail.write_answer',
@@ -35,11 +38,48 @@ const Index: FC<Props> = ({ visible = false, data, callback }) => {
const [showEditor, setShowEditor] = useState<boolean>(visible);
const [focusType, setFocusType] = useState('');
const [editorFocusState, setEditorFocusState] = useState(false);
+ const [hasDraft, setHasDraft] = useState(false);
usePromptWithUnload({
when: Boolean(formData.content.value),
});
+ const removeDraft = () => {
+ saveDraft.remove();
+ setHasDraft(false);
+ };
+
+ useEffect(() => {
+ const draft = storageExpires.get(DRAFT_ANSWER_STORAGE_KEY);
+ if (draft?.questionId === data.qid && draft?.content) {
+ setFormData({
+ content: {
+ value: draft.content,
+ isInvalid: false,
+ errorMsg: '',
+ },
+ });
+ setShowEditor(true);
+ setHasDraft(true);
+ }
+ }, []);
+
+ useEffect(() => {
+ const { content } = formData;
+
+ // save Draft
+ saveDraft.save({
+ questionId: data?.qid,
+ content: content.value,
+ });
+
+ if (content.value) {
+ setHasDraft(true);
+ } else {
+ removeDraft();
+ }
+ }, [formData.content.value]);
+
const checkValidated = (): boolean => {
let bol = true;
const { content } = formData;
@@ -65,6 +105,24 @@ const Index: FC<Props> = ({ visible = false, data, callback }) => {
return bol;
};
+ const resetForm = () => {
+ setFormData({
+ content: {
+ value: '',
+ isInvalid: false,
+ errorMsg: '',
+ },
+ });
+ };
+
+ const deleteDraft = () => {
+ const res = window.confirm(t('discard_confirm', { keyPrefix: 'draft' }));
+ if (res) {
+ removeDraft();
+ resetForm();
+ }
+ };
+
const handleSubmit = () => {
if (!guard.tryNormalLogged(true)) {
return;
@@ -86,6 +144,7 @@ const Index: FC<Props> = ({ visible = false, data, callback }) => {
errorMsg: '',
},
});
+ deleteDraft();
callback?.(res.info);
})
.catch((ex) => {
@@ -128,7 +187,6 @@ const Index: FC<Props> = ({ visible = false, data, callback }) => {
setShowEditor(true);
setEditorFocusState(true);
};
-
return (
<Form noValidate className="mt-4">
{(!data.answered || showEditor) && (
@@ -187,6 +245,11 @@ const Index: FC<Props> = ({ visible = false, data, callback }) => {
) : (
<Button onClick={clickBtn}>{t('btn_name')}</Button>
)}
+ {hasDraft && (
+ <Button variant="link" className="ms-2" onClick={deleteDraft}>
+ {t('discard_draft', { keyPrefix: 'btns' })}
+ </Button>
+ )}
</Form>
);
};
diff --git a/ui/src/utils/index.ts b/ui/src/utils/index.ts
index 180a1da0..dc31d743 100644
--- a/ui/src/utils/index.ts
+++ b/ui/src/utils/index.ts
@@ -1,6 +1,8 @@
export { default as request } from './request';
export { default as Storage } from './storage';
export { floppyNavigation } from './floppyNavigation';
+export { default as storageExpires } from './storageWithExpires';
+export { default as SaveDraft } from './saveDraft';
export * as guard from './guard';
export * as localize from './localize';
diff --git a/ui/src/utils/saveDraft.ts b/ui/src/utils/saveDraft.ts
new file mode 100644
index 00000000..a6dc03e1
--- /dev/null
+++ b/ui/src/utils/saveDraft.ts
@@ -0,0 +1,100 @@
+import { debounce } from 'lodash';
+
+import {
+ DRAFT_QUESTION_STORAGE_KEY,
+ DRAFT_ANSWER_STORAGE_KEY,
+} from '@/common/constants';
+import { storageExpires as storage } from '@/utils';
+
+export type QuestionDraft = {
+ params: {
+ title: string;
+ content: string;
+ tags: any[];
+ answer: string;
+ };
+ callback?: () => void;
+};
+
+export type AnswerDraft = {
+ questionId: string;
+ content: string;
+ callback?: () => void;
+};
+
+type DraftType = {
+ type: 'question' | 'answer';
+};
+
+export type DraftParams = QuestionDraft | AnswerDraft;
+
+class SaveDraft {
+ type: DraftType['type'];
+
+ status: 'save' | 'remove';
+
+ constructor({ type = 'question' }: DraftType) {
+ this.type = type;
+ this.status = 'save';
+ }
+
+ save = debounce((data: DraftParams) => {
+ // TODO
+ if (this.status === 'remove') {
+ return;
+ }
+ if (this.type === 'question') {
+ const { params, callback } = data as QuestionDraft;
+ if (
+ !params.title &&
+ !params.content &&
+ !params.tags.length &&
+ !params.answer
+ ) {
+ this.remove();
+ return;
+ }
+
+ this.storeDraft(params, callback);
+ }
+
+ if (this.type === 'answer') {
+ const { content, questionId, callback } = data as AnswerDraft;
+ if (!questionId) {
+ return;
+ }
+
+ if (!content) {
+ this.remove();
+ return;
+ }
+ this.storeDraft({ content, questionId }, callback);
+ }
+ }, 3000);
+
+ remove() {
+ this.status = 'remove';
+ const that = this;
+ if (this.type === 'question') {
+ storage.remove(DRAFT_QUESTION_STORAGE_KEY, () => {
+ that.status = 'save';
+ });
+ }
+ if (this.type === 'answer') {
+ storage.remove(DRAFT_ANSWER_STORAGE_KEY, () => {
+ that.status = 'save';
+ });
+ }
+ }
+
+ private storeDraft = (params: any, callback) => {
+ const key =
+ this.type === 'question'
+ ? DRAFT_QUESTION_STORAGE_KEY
+ : DRAFT_ANSWER_STORAGE_KEY;
+ storage.set(key, params);
+ callback?.();
+ };
+}
+
+export default SaveDraft;
diff --git a/ui/src/utils/storageWithExpires.ts b/ui/src/utils/storageWithExpires.ts
new file mode 100644
index 00000000..2365782a
--- /dev/null
+++ b/ui/src/utils/storageWithExpires.ts
@@ -0,0 +1,50 @@
+import { DRAFT_TIMESIGH_STORAGE_KEY as timeSign } from '@/common/constants';
+
+const store = {
+ storage: localStorage || window.localStorage,
+ set(key: string, value, time?: number): void {
+ const t = time || Date.now() + 1000 * 60 * 60 * 24 * 7; // default 7 days
+ try {
+ this.storage.setItem(key, `${t}${timeSign}${JSON.stringify(value)}`);
+ } catch {
+ // ignore
+ console.error('set storage error: the key is', key);
+ }
+ },
+ get(key: string): any {
+ const timeSignLen = timeSign.length;
+ let index = 0;
+ let time = 0;
+ let res;
+ try {
+ res = this.storage.getItem(key);
+ } catch {
+ console.error('get storage error: the key is', key);
+ }
+ if (res) {
+ index = res.indexOf(timeSign);
+ time = +res.slice(0, index);
+ if (time > new Date().getTime()) {
+ res = res.slice(index + timeSignLen);
+ try {
+ res = JSON.parse(res);
+ } catch {
+ // ignore
+ }
+ } else {
+ // timeout remove storage
+ res = null;
+ this.storage.removeItem(key);
+ }
+ return res;
+ }
+
+ return res;
+ },
+ remove(key: string, callback?: () => void): void {
+ this.storage.removeItem(key);
+ callback?.();
+ },
+};
+
+export default store;