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

View File

@ -19,14 +19,13 @@ import { IPageStore } from "@/store/pages/page.store";
type Props = { type Props = {
editorRef: React.RefObject<EditorRefApi>; editorRef: React.RefObject<EditorRefApi>;
handleDuplicatePage: () => void; handleDuplicatePage: () => void;
isSyncing: boolean;
pageStore: IPageStore; pageStore: IPageStore;
projectId: string; projectId: string;
readOnlyEditorRef: React.RefObject<EditorReadOnlyRefApi>; readOnlyEditorRef: React.RefObject<EditorReadOnlyRefApi>;
}; };
export const PageExtraOptions: React.FC<Props> = observer((props) => { export const PageExtraOptions: React.FC<Props> = observer((props) => {
const { editorRef, handleDuplicatePage, isSyncing, pageStore, projectId, readOnlyEditorRef } = props; const { editorRef, handleDuplicatePage, pageStore, projectId, readOnlyEditorRef } = props;
// states // states
const [gptModalOpen, setGptModal] = useState(false); const [gptModalOpen, setGptModal] = useState(false);
// store hooks // 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> <span className="text-sm text-custom-text-300">{isSubmitting === "submitting" ? "Saving..." : "Saved"}</span>
</div> </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 && ( {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"> <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" /> <Lock className="h-3 w-3" />

View File

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

View File

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

View File

@ -33,7 +33,6 @@ export const PageEditorTitle: React.FC<Props> = observer((props) => {
) : ( ) : (
<> <>
<TextArea <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" className="w-full bg-custom-background text-[1.75rem] font-semibold outline-none p-0 border-none resize-none rounded-none"
style={{ style={{
lineHeight: "1.2", lineHeight: "1.2",
@ -46,6 +45,7 @@ export const PageEditorTitle: React.FC<Props> = observer((props) => {
} }
}} }}
value={title} value={title}
onChange={(e) => updateTitle(e.target.value)}
maxLength={255} maxLength={255}
onFocus={() => setIsLengthVisible(true)} onFocus={() => setIsLengthVisible(true)}
onBlur={() => setIsLengthVisible(false)} 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 { observer } from "mobx-react-lite";
import Link from "next/link"; import Link from "next/link";
import { useRouter } from "next/router"; import { useRouter } from "next/router";
@ -38,10 +38,11 @@ const PageDetailsPage: NextPageWithLayout = observer(() => {
// store hooks // store hooks
const { createPage, getPageById } = useProjectPages(projectId?.toString() ?? ""); const { createPage, getPageById } = useProjectPages(projectId?.toString() ?? "");
const pageStore = usePage(pageId?.toString() ?? ""); const pageStore = usePage(pageId?.toString() ?? "");
const { description_html, id, name, setIsSubmitting, updateDescription } = pageStore;
// editor markings hook // editor markings hook
const { markings, updateMarkings } = useEditorMarkings(); const { markings, updateMarkings } = useEditorMarkings();
// form info // form info
const { handleSubmit, getValues, control } = useForm<TPage>({ const { getValues, control } = useForm<TPage>({
defaultValues: { defaultValues: {
name: "", name: "",
description_html: "", description_html: "",
@ -49,23 +50,25 @@ const PageDetailsPage: NextPageWithLayout = observer(() => {
}); });
// fetching page details // fetching page details
const { const { error: pageDetailsError } = useSWR(
isValidating, pageId ? `PAGE_DETAILS_${pageId}` : null,
error: pageDetailsError, pageId ? () => getPageById(pageId.toString()) : null,
} = useSWR(pageId ? `PAGE_DETAILS_${pageId}` : null, pageId ? () => getPageById(pageId.toString()) : null, { {
revalidateIfStale: false, revalidateIfStale: false,
revalidateOnFocus: true, revalidateOnFocus: false,
revalidateOnReconnect: true, revalidateOnReconnect: false,
}); }
useEffect(
() => () => {
if (pageStore.cleanup) pageStore.cleanup();
},
[pageStore]
); );
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 ( return (
<div className="h-full w-full grid place-items-center"> <div className="h-full w-full grid place-items-center">
<Spinner /> <Spinner />
@ -88,27 +91,15 @@ const PageDetailsPage: NextPageWithLayout = observer(() => {
</div> </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 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 handleDuplicatePage = async () => {
const currentPageValues = getValues(); const currentPageValues = getValues();
if (!currentPageValues?.description_html) { if (!currentPageValues?.description_html) currentPageValues.description_html = description_html;
// TODO: We need to get latest data the above variable will give us stale data
currentPageValues.description_html = pageStore.description_html;
}
const formData: Partial<TPage> = { const formData: Partial<TPage> = {
name: "Copy of " + pageStore.name, name: "Copy of " + name,
description_html: currentPageValues.description_html, description_html: currentPageValues.description_html,
}; };
@ -125,7 +116,7 @@ const PageDetailsPage: NextPageWithLayout = observer(() => {
return ( return (
<> <>
<PageHead title={pageTitle} /> <PageHead title={name} />
<div className="flex h-full flex-col justify-between"> <div className="flex h-full flex-col justify-between">
<div className="h-full w-full flex-shrink-0 flex flex-col overflow-hidden"> <div className="h-full w-full flex-shrink-0 flex flex-col overflow-hidden">
{projectId && ( {projectId && (
@ -135,7 +126,6 @@ const PageDetailsPage: NextPageWithLayout = observer(() => {
editorReady={editorReady} editorReady={editorReady}
readOnlyEditorReady={readOnlyEditorReady} readOnlyEditorReady={readOnlyEditorReady}
handleDuplicatePage={handleDuplicatePage} handleDuplicatePage={handleDuplicatePage}
isSyncing={isValidating}
markings={markings} markings={markings}
pageStore={pageStore} pageStore={pageStore}
projectId={projectId.toString()} projectId={projectId.toString()}
@ -149,7 +139,7 @@ const PageDetailsPage: NextPageWithLayout = observer(() => {
handleEditorReady={(val) => setEditorReady(val)} handleEditorReady={(val) => setEditorReady(val)}
readOnlyEditorRef={readOnlyEditorRef} readOnlyEditorRef={readOnlyEditorRef}
handleReadOnlyEditorReady={() => setReadOnlyEditorReady(true)} handleReadOnlyEditorReady={() => setReadOnlyEditorReady(true)}
handleSubmit={() => handleSubmit(handleUpdatePage)()} handleDescriptionUpdate={handleDescriptionChange}
markings={markings} markings={markings}
pageStore={pageStore} pageStore={pageStore}
sidePeekVisible={sidePeekVisible} sidePeekVisible={sidePeekVisible}

View File

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