chore: move all the update logic to the page store

This commit is contained in:
Aaryan Khandelwal 2024-05-13 01:04:25 +05:30
parent b736bbb503
commit 52fddaec15
7 changed files with 98 additions and 128 deletions

View File

@ -1,4 +1,4 @@
import { useCallback, useEffect } from "react";
import { useEffect } from "react";
import { observer } from "mobx-react";
import { useRouter } from "next/router";
import { Control, Controller } from "react-hook-form";
@ -34,7 +34,7 @@ type Props = {
control: Control<TPage, any>;
editorRef: React.RefObject<EditorRefApi>;
readOnlyEditorRef: React.RefObject<EditorReadOnlyRefApi>;
handleSubmit: () => void;
handleDescriptionUpdate: (binaryString: string, descriptionHTML: string) => Promise<void>;
markings: IMarking[];
pageStore: IPageStore;
sidePeekVisible: boolean;
@ -47,11 +47,11 @@ export const PageEditorBody: React.FC<Props> = observer((props) => {
const {
control,
handleReadOnlyEditorReady,
handleDescriptionUpdate,
handleEditorReady,
editorRef,
markings,
readOnlyEditorRef,
// handleSubmit,
pageStore,
sidePeekVisible,
updateMarkings,
@ -71,7 +71,7 @@ export const PageEditorBody: React.FC<Props> = observer((props) => {
const pageId = pageStore?.id ?? "";
const pageTitle = pageStore?.name ?? "";
const pageDescription = pageStore?.description_html;
const { description_html, isContentEditable, updateTitle, isSubmitting, setIsSubmitting } = pageStore;
const { description_html, isContentEditable, isSubmitting, updateTitle, setIsSubmitting } = pageStore;
const projectMemberIds = projectId ? getProjectMemberIds(projectId.toString()) : [];
const projectMemberDetails = projectMemberIds?.map((id) => getUserDetails(id) as IUserLite);
// use-mention
@ -97,21 +97,6 @@ export const PageEditorBody: React.FC<Props> = observer((props) => {
);
const pageDescriptionYJS = new Uint8Array(descriptionYJS);
const handleDescriptionChange = useCallback(
(binaryString: string, descriptionHTML: string) => {
if (!workspaceSlug || !projectId || !pageId) return;
pageService.updateDescriptionYJS(workspaceSlug.toString(), projectId.toString(), pageId.toString(), {
description_yjs: binaryString,
description_html: descriptionHTML,
});
// setIsSubmitting("submitting");
// setShowAlert(true);
// onChange(description_html);
// handleSubmit();
},
[pageId, projectId, workspaceSlug]
);
useEffect(() => {
updateMarkings(description_html ?? "<p></p>");
}, [description_html, updateMarkings]);
@ -167,7 +152,7 @@ export const PageEditorBody: React.FC<Props> = observer((props) => {
ref={editorRef}
containerClassName="p-0 pb-64"
editorClassName="lg:px-10 pl-8"
onChange={handleDescriptionChange}
onChange={handleDescriptionUpdate}
mentionHandler={{
highlights: mentionHighlights,
suggestions: mentionSuggestions,

View File

@ -19,14 +19,13 @@ import { IPageStore } from "@/store/pages/page.store";
type Props = {
editorRef: React.RefObject<EditorRefApi>;
handleDuplicatePage: () => void;
isSyncing: boolean;
pageStore: IPageStore;
projectId: string;
readOnlyEditorRef: React.RefObject<EditorReadOnlyRefApi>;
};
export const PageExtraOptions: React.FC<Props> = observer((props) => {
const { editorRef, handleDuplicatePage, isSyncing, pageStore, projectId, readOnlyEditorRef } = props;
const { editorRef, handleDuplicatePage, pageStore, projectId, readOnlyEditorRef } = props;
// states
const [gptModalOpen, setGptModal] = useState(false);
// store hooks
@ -51,12 +50,6 @@ export const PageExtraOptions: React.FC<Props> = observer((props) => {
<span className="text-sm text-custom-text-300">{isSubmitting === "submitting" ? "Saving..." : "Saved"}</span>
</div>
)}
{isSyncing && (
<div className="flex items-center gap-x-2">
<RefreshCw className="h-4 w-4 stroke-custom-text-300" />
<span className="text-sm text-custom-text-300">Syncing...</span>
</div>
)}
{is_locked && (
<div className="flex h-7 items-center gap-2 rounded-full bg-custom-background-80 px-3 py-0.5 text-xs font-medium text-custom-text-300">
<Lock className="h-3 w-3" />

View File

@ -11,7 +11,6 @@ type Props = {
editorRef: React.RefObject<EditorRefApi>;
readOnlyEditorRef: React.RefObject<EditorReadOnlyRefApi>;
handleDuplicatePage: () => void;
isSyncing: boolean;
markings: IMarking[];
pageStore: IPageStore;
projectId: string;
@ -29,7 +28,6 @@ export const PageEditorMobileHeaderRoot: React.FC<Props> = observer((props) => {
markings,
readOnlyEditorReady,
handleDuplicatePage,
isSyncing,
pageStore,
projectId,
sidePeekVisible,
@ -57,7 +55,6 @@ export const PageEditorMobileHeaderRoot: React.FC<Props> = observer((props) => {
<PageExtraOptions
editorRef={editorRef}
handleDuplicatePage={handleDuplicatePage}
isSyncing={isSyncing}
pageStore={pageStore}
projectId={projectId}
readOnlyEditorRef={readOnlyEditorRef}

View File

@ -13,7 +13,6 @@ type Props = {
editorRef: React.RefObject<EditorRefApi>;
readOnlyEditorRef: React.RefObject<EditorReadOnlyRefApi>;
handleDuplicatePage: () => void;
isSyncing: boolean;
markings: IMarking[];
pageStore: IPageStore;
projectId: string;
@ -31,7 +30,6 @@ export const PageEditorHeaderRoot: React.FC<Props> = observer((props) => {
markings,
readOnlyEditorReady,
handleDuplicatePage,
isSyncing,
pageStore,
projectId,
sidePeekVisible,
@ -67,7 +65,6 @@ export const PageEditorHeaderRoot: React.FC<Props> = observer((props) => {
<PageExtraOptions
editorRef={editorRef}
handleDuplicatePage={handleDuplicatePage}
isSyncing={isSyncing}
pageStore={pageStore}
projectId={projectId}
readOnlyEditorRef={readOnlyEditorRef}
@ -81,7 +78,6 @@ export const PageEditorHeaderRoot: React.FC<Props> = observer((props) => {
readOnlyEditorReady={readOnlyEditorReady}
markings={markings}
handleDuplicatePage={handleDuplicatePage}
isSyncing={isSyncing}
pageStore={pageStore}
projectId={projectId}
sidePeekVisible={sidePeekVisible}

View File

@ -33,7 +33,6 @@ export const PageEditorTitle: React.FC<Props> = observer((props) => {
) : (
<>
<TextArea
onChange={(e) => updateTitle(e.target.value)}
className="w-full bg-custom-background text-[1.75rem] font-semibold outline-none p-0 border-none resize-none rounded-none"
style={{
lineHeight: "1.2",
@ -46,6 +45,7 @@ export const PageEditorTitle: React.FC<Props> = observer((props) => {
}
}}
value={title}
onChange={(e) => updateTitle(e.target.value)}
maxLength={255}
onFocus={() => setIsLengthVisible(true)}
onBlur={() => setIsLengthVisible(false)}

View File

@ -1,4 +1,4 @@
import { ReactElement, useEffect, useRef, useState } from "react";
import { ReactElement, useCallback, useRef, useState } from "react";
import { observer } from "mobx-react-lite";
import Link from "next/link";
import { useRouter } from "next/router";
@ -38,10 +38,11 @@ const PageDetailsPage: NextPageWithLayout = observer(() => {
// store hooks
const { createPage, getPageById } = useProjectPages(projectId?.toString() ?? "");
const pageStore = usePage(pageId?.toString() ?? "");
const { description_html, id, name, setIsSubmitting, updateDescription } = pageStore;
// editor markings hook
const { markings, updateMarkings } = useEditorMarkings();
// form info
const { handleSubmit, getValues, control } = useForm<TPage>({
const { getValues, control } = useForm<TPage>({
defaultValues: {
name: "",
description_html: "",
@ -49,23 +50,25 @@ const PageDetailsPage: NextPageWithLayout = observer(() => {
});
// fetching page details
const {
isValidating,
error: pageDetailsError,
} = useSWR(pageId ? `PAGE_DETAILS_${pageId}` : null, pageId ? () => getPageById(pageId.toString()) : null, {
const { error: pageDetailsError } = useSWR(
pageId ? `PAGE_DETAILS_${pageId}` : null,
pageId ? () => getPageById(pageId.toString()) : null,
{
revalidateIfStale: false,
revalidateOnFocus: true,
revalidateOnReconnect: true,
});
useEffect(
() => () => {
if (pageStore.cleanup) pageStore.cleanup();
},
[pageStore]
revalidateOnFocus: false,
revalidateOnReconnect: false,
}
);
if ((!pageStore || !pageStore.id) && !pageDetailsError)
const handleDescriptionChange = useCallback(
async (binaryString: string, descriptionHTML: string) => {
setIsSubmitting("submitting");
await updateDescription(binaryString, descriptionHTML).finally(() => setIsSubmitting("saved"));
},
[setIsSubmitting, updateDescription]
);
if ((!pageStore || !id) && !pageDetailsError)
return (
<div className="h-full w-full grid place-items-center">
<Spinner />
@ -88,27 +91,15 @@ const PageDetailsPage: NextPageWithLayout = observer(() => {
</div>
);
// we need to get the values of title and description from the page store but we don't have to subscribe to those values
const pageTitle = pageStore?.name;
const handleCreatePage = async (payload: Partial<TPage>) => await createPage(payload);
const handleUpdatePage = async (formData: TPage) => {
let updatedDescription = formData.description_html;
if (!updatedDescription || updatedDescription.trim() === "") updatedDescription = "<p></p>";
pageStore.updateDescription(updatedDescription);
};
const handleDuplicatePage = async () => {
const currentPageValues = getValues();
if (!currentPageValues?.description_html) {
// TODO: We need to get latest data the above variable will give us stale data
currentPageValues.description_html = pageStore.description_html;
}
if (!currentPageValues?.description_html) currentPageValues.description_html = description_html;
const formData: Partial<TPage> = {
name: "Copy of " + pageStore.name,
name: "Copy of " + name,
description_html: currentPageValues.description_html,
};
@ -125,7 +116,7 @@ const PageDetailsPage: NextPageWithLayout = observer(() => {
return (
<>
<PageHead title={pageTitle} />
<PageHead title={name} />
<div className="flex h-full flex-col justify-between">
<div className="h-full w-full flex-shrink-0 flex flex-col overflow-hidden">
{projectId && (
@ -135,7 +126,6 @@ const PageDetailsPage: NextPageWithLayout = observer(() => {
editorReady={editorReady}
readOnlyEditorReady={readOnlyEditorReady}
handleDuplicatePage={handleDuplicatePage}
isSyncing={isValidating}
markings={markings}
pageStore={pageStore}
projectId={projectId.toString()}
@ -149,7 +139,7 @@ const PageDetailsPage: NextPageWithLayout = observer(() => {
handleEditorReady={(val) => setEditorReady(val)}
readOnlyEditorRef={readOnlyEditorRef}
handleReadOnlyEditorReady={() => setReadOnlyEditorReady(true)}
handleSubmit={() => handleSubmit(handleUpdatePage)()}
handleDescriptionUpdate={handleDescriptionChange}
markings={markings}
pageStore={pageStore}
sidePeekVisible={sidePeekVisible}

View File

@ -9,12 +9,11 @@ import { EUserProjectRoles } from "@/constants/project";
import { PageService } from "@/services/page.service";
import { RootStore } from "../root.store";
export type TLoader = "submitting" | "submitted" | "saved" | undefined;
export type TLoader = "submitting" | "submitted" | "saved";
export interface IPageStore extends TPage {
// observables
isSubmitting: "submitting" | "submitted" | "saved";
loader: TLoader;
isSubmitting: TLoader;
// computed
asJSON: TPage | undefined;
isCurrentUserOwner: boolean; // it will give the user is the owner of the page or not
@ -27,12 +26,12 @@ export interface IPageStore extends TPage {
isContentEditable: boolean;
// helpers
oldName: string;
updateTitle: (name: string) => void;
updateDescription: (description: string) => void;
setIsSubmitting: (isSubmitting: "submitting" | "submitted" | "saved") => void;
setIsSubmitting: (value: TLoader) => void;
cleanup: () => void;
// actions
update: (pageData: Partial<TPage>) => Promise<TPage | undefined>;
updateTitle: (title: string) => void;
updateDescription: (binaryString: string, descriptionHTML: string) => Promise<void>;
makePublic: () => Promise<void>;
makePrivate: () => Promise<void>;
lock: () => Promise<void>;
@ -45,8 +44,7 @@ export interface IPageStore extends TPage {
export class PageStore implements IPageStore {
// loaders
isSubmitting: "submitting" | "submitted" | "saved" = "saved";
loader: TLoader = undefined;
isSubmitting: TLoader = "saved";
// page properties
id: string | undefined;
name: string | undefined;
@ -68,7 +66,7 @@ export class PageStore implements IPageStore {
oldName: string = "";
// reactions
disposers: Array<() => void> = [];
// service
// services
pageService: PageService;
constructor(
@ -96,7 +94,6 @@ export class PageStore implements IPageStore {
makeObservable(this, {
// loaders
isSubmitting: observable.ref,
loader: observable.ref,
// page properties
id: observable.ref,
name: observable.ref,
@ -115,7 +112,9 @@ export class PageStore implements IPageStore {
created_at: observable.ref,
updated_at: observable.ref,
// helpers
oldName: observable,
oldName: observable.ref,
setIsSubmitting: action,
cleanup: action,
// computed
asJSON: computed,
isCurrentUserOwner: computed,
@ -126,13 +125,10 @@ export class PageStore implements IPageStore {
canCurrentUserArchivePage: computed,
canCurrentUserDeletePage: computed,
isContentEditable: computed,
// helper actions
updateTitle: action,
updateDescription: action.bound,
setIsSubmitting: action,
cleanup: action,
// actions
update: action,
updateTitle: action,
updateDescription: action,
makePublic: action,
makePrivate: action,
lock: action,
@ -169,27 +165,7 @@ export class PageStore implements IPageStore {
{ delay: 2000 }
);
const descriptionDisposer = reaction(
() => this.description_html,
(description_html) => {
//TODO: Fix reaction to only run when the data is changed, not when the page is loaded
const { workspaceSlug, projectId } = this.store.router;
if (!workspaceSlug || !projectId || !this.id) return;
this.isSubmitting = "submitting";
this.pageService
.update(workspaceSlug, projectId, this.id, {
description_html,
})
.finally(() =>
runInAction(() => {
this.isSubmitting = "submitted";
})
);
},
{ delay: 3000 }
);
this.disposers.push(titleDisposer, descriptionDisposer);
this.disposers.push(titleDisposer);
}
// computed
@ -284,24 +260,21 @@ export class PageStore implements IPageStore {
);
}
updateTitle = action("updateTitle", (name: string) => {
this.oldName = this.name ?? "";
this.name = name;
/**
* @description update the submitting state
* @param value
*/
setIsSubmitting = (value: TLoader) => {
runInAction(() => {
this.isSubmitting = value;
});
};
updateDescription = action("updateDescription", (description_html: string) => {
this.description_html = description_html;
});
setIsSubmitting = action("setIsSubmitting", (isSubmitting: "submitting" | "submitted" | "saved") => {
this.isSubmitting = isSubmitting;
});
cleanup = action("cleanup", () => {
cleanup = () => {
this.disposers.forEach((disposer) => {
disposer();
});
});
};
/**
* @description update the page
@ -313,14 +286,14 @@ export class PageStore implements IPageStore {
const currentPage = this.asJSON;
try {
const currentPageResponse = await this.pageService.update(workspaceSlug, projectId, this.id, currentPage);
if (currentPageResponse)
runInAction(() => {
Object.keys(pageData).forEach((key) => {
const currentPageKey = key as keyof TPage;
set(this, key, currentPageResponse?.[currentPageKey] || undefined);
set(this, key, pageData[currentPageKey] || undefined);
});
});
await this.pageService.update(workspaceSlug, projectId, this.id, currentPage);
} catch (error) {
runInAction(() => {
Object.keys(pageData).forEach((key) => {
@ -332,6 +305,42 @@ export class PageStore implements IPageStore {
}
};
/**
* @description update the page title
* @param title
*/
updateTitle = (title: string) => {
this.oldName = this.name ?? "";
this.name = title;
};
/**
* @description update the page description
* @param {string} binaryString
* @param {string} descriptionHTML
*/
updateDescription = async (binaryString: string, descriptionHTML: string) => {
const { workspaceSlug, projectId } = this.store.router;
if (!workspaceSlug || !projectId || !this.id) return undefined;
const currentDescription = this.description_html;
runInAction(() => {
this.description_html = descriptionHTML;
});
try {
await this.pageService.updateDescriptionYJS(workspaceSlug, projectId, this.id, {
description_yjs: binaryString,
description_html: descriptionHTML,
});
} catch (error) {
runInAction(() => {
this.description_html = currentDescription;
});
throw error;
}
};
/**
* @description make the page public
*/