Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

♻️(frontend) simplify stores #402

Merged
merged 2 commits into from
Nov 13, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ and this project adheres to

- 🚸(backend) improve users similarity search and sort results #391
- 🌐(backend) add german translation #259
- ♻️(frontend) simplify stores #402

## Fixed

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,11 @@ import { useTranslation } from 'react-i18next';
import { Box, TextErrors } from '@/components';
import { mediaUrl } from '@/core';
import { useAuthStore } from '@/core/auth';
import { Doc, useDocStore } from '@/features/docs/doc-management';
import { Doc } from '@/features/docs/doc-management';

import { useCreateDocAttachment } from '../api/useCreateDocUpload';
import useSaveDoc from '../hook/useSaveDoc';
import { useHeadingStore } from '../stores';
import { useEditorStore, useHeadingStore } from '../stores';
import { randomColor } from '../utils';

import { BlockNoteToolbar } from './BlockNoteToolbar';
Expand Down Expand Up @@ -86,11 +86,10 @@ export const BlockNoteEditor = ({
}: BlockNoteEditorProps) => {
const isVersion = doc.id !== storeId;
const { userData } = useAuthStore();
const { setStore, docsStore } = useDocStore();
const { setEditor } = useEditorStore();

const readOnly = !doc.abilities.partial_update || isVersion;
useSaveDoc(doc.id, provider.document, !readOnly);
const storedEditor = docsStore?.[storeId]?.editor;
const {
mutateAsync: createDocAttachment,
isError: isErrorAttachment,
Expand Down Expand Up @@ -132,8 +131,12 @@ export const BlockNoteEditor = ({
);

useEffect(() => {
setStore(storeId, { editor });
}, [setStore, storeId, editor]);
setEditor(editor);

return () => {
setEditor(undefined);
};
}, [setEditor, editor]);

useEffect(() => {
setHeadings(editor);
Expand All @@ -160,7 +163,7 @@ export const BlockNoteEditor = ({
)}

<BlockNoteView
editor={storedEditor ?? editor}
editor={editor}
formattingToolbar={false}
editable={!readOnly}
theme="light"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,8 @@ export const DocEditor = ({ doc }: DocEditorProps) => {

const { colorsTokens } = useCunninghamTheme();

const { docsStore } = useDocStore();
const provider = docsStore?.[doc.id]?.provider;
const { providers } = useDocStore();
const provider = providers?.[doc.id];

if (!provider) {
return null;
Expand Down Expand Up @@ -98,7 +98,7 @@ export const DocVersionEditor = ({ doc, versionId }: DocVersionEditorProps) => {
docId: doc.id,
versionId,
});
const { createProvider, docsStore } = useDocStore();
const { createProvider, providers } = useDocStore();

const navigate = useNavigate();

Expand All @@ -107,11 +107,11 @@ export const DocVersionEditor = ({ doc, versionId }: DocVersionEditorProps) => {
return;
}

const provider = docsStore?.[version.id]?.provider;
const provider = providers?.[version.id];
if (!provider || provider.document.guid !== version.id) {
createProvider(version.id, version.content);
}
}, [createProvider, docsStore, version]);
}, [createProvider, providers, version]);

if (isError && error) {
if (error.status === 404) {
Expand Down Expand Up @@ -143,7 +143,7 @@ export const DocVersionEditor = ({ doc, versionId }: DocVersionEditorProps) => {
);
}

const provider = docsStore?.[version.id]?.provider;
const provider = providers?.[version.id];

if (!provider) {
return null;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -127,9 +127,7 @@ export const PanelEditor = ({
</BoxButton>
)}
</Box>
{isPanelTableContentOpen && (
<TableContent doc={doc} headings={headings} />
)}
{isPanelTableContentOpen && <TableContent headings={headings} />}
{!isPanelTableContentOpen && doc.abilities.versions_list && (
<VersionList doc={doc} />
)}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
export * from './useEditorStore';
export * from './useHeadingStore';
export * from './usePanelEditorStore';
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { BlockNoteEditor } from '@blocknote/core';
import { create } from 'zustand';

export interface UseEditorstore {
editor?: BlockNoteEditor;
setEditor: (editor: BlockNoteEditor | undefined) => void;
}

export const useEditorStore = create<UseEditorstore>((set) => ({
editor: undefined,
setEditor: (editor) => {
set({ editor });
},
}));
Original file line number Diff line number Diff line change
Expand Up @@ -8,17 +8,18 @@ import { useTranslation } from 'react-i18next';

import { Box, DropButton, IconOptions } from '@/components';
import { useAuthStore } from '@/core';
import { usePanelEditorStore } from '@/features/docs/doc-editor/';
import {
useEditorStore,
usePanelEditorStore,
} from '@/features/docs/doc-editor/';
import {
Doc,
ModalRemoveDoc,
ModalShare,
useDocStore,
} from '@/features/docs/doc-management';
import { ModalVersion, Versions } from '@/features/docs/doc-versioning';
import { useResponsiveStore } from '@/stores';

import { ModalVersion, Versions } from '../../doc-versioning';

import { ModalPDF } from './ModalExport';

interface DocToolBoxProps {
Expand All @@ -36,13 +37,12 @@ export const DocToolBox = ({ doc, versionId }: DocToolBoxProps) => {
const [isModalVersionOpen, setIsModalVersionOpen] = useState(false);
const { isSmallMobile } = useResponsiveStore();
const { authenticated } = useAuthStore();
const { docsStore } = useDocStore();
const { editor } = useEditorStore();
const { toast } = useToastProvider();

const copyCurrentEditorToClipboard = async (
asFormat: 'html' | 'markdown',
) => {
const editor = docsStore[doc.id]?.editor;
if (!editor) {
toast(t('Editor unavailable'), VariantType.ERROR, { duration: 3000 });
return;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,8 @@ import { t } from 'i18next';
import { useEffect, useMemo, useState } from 'react';

import { Box, Text } from '@/components';
import { Doc, useDocStore } from '@/features/docs/doc-management';
import { useEditorStore } from '@/features/docs/doc-editor';
import { Doc } from '@/features/docs/doc-management';

import { useExport } from '../api/useExport';
import { TemplatesOrdering, useTemplates } from '../api/useTemplates';
Expand All @@ -30,7 +31,7 @@ export const ModalPDF = ({ onClose, doc }: ModalPDFProps) => {
ordering: TemplatesOrdering.BY_CREATED_ON_DESC,
});
const { toast } = useToastProvider();
const { docsStore } = useDocStore();
const { editor } = useEditorStore();
const {
mutate: createExport,
data: documentGenerated,
Expand Down Expand Up @@ -103,8 +104,6 @@ export const ModalPDF = ({ onClose, doc }: ModalPDFProps) => {
return;
}

const editor = docsStore[doc.id].editor;

if (!editor) {
toast(t('No editor found'), VariantType.ERROR);
return;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,29 +1,23 @@
import { BlockNoteEditor } from '@blocknote/core';
import { HocuspocusProvider } from '@hocuspocus/provider';
import * as Y from 'yjs';
import { create } from 'zustand';

import { providerUrl } from '@/core';
import { Base64, Doc, blocksToYDoc } from '@/features/docs/doc-management';

interface DocStore {
provider: HocuspocusProvider;
editor?: BlockNoteEditor;
}

export interface UseDocStore {
currentDoc?: Doc;
docsStore: {
[storeId: string]: DocStore;
providers: {
[storeId: string]: HocuspocusProvider;
};
createProvider: (storeId: string, initialDoc: Base64) => HocuspocusProvider;
setStore: (storeId: string, props: Partial<DocStore>) => void;
setProviders: (storeId: string, providers: HocuspocusProvider) => void;
setCurrentDoc: (doc: Doc | undefined) => void;
}

export const useDocStore = create<UseDocStore>((set, get) => ({
currentDoc: undefined,
docsStore: {},
providers: {},
createProvider: (storeId: string, initialDoc: Base64) => {
const doc = new Y.Doc({
guid: storeId,
Expand All @@ -48,23 +42,17 @@ export const useDocStore = create<UseDocStore>((set, get) => ({
document: doc,
});

get().setStore(storeId, { provider });
get().setProviders(storeId, provider);

return provider;
},
setStore: (storeId, props) => {
set(({ docsStore }, ...store) => {
return {
...store,
docsStore: {
...docsStore,
[storeId]: {
...docsStore[storeId],
...props,
},
},
};
});
setProviders: (storeId, provider) => {
set(({ providers }) => ({
providers: {
...providers,
[storeId]: provider,
},
}));
},
setCurrentDoc: (doc) => {
set({ currentDoc: doc });
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,22 +2,19 @@ import React, { useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';

import { Box, BoxButton, Text } from '@/components';
import { HeadingBlock } from '@/features/docs/doc-editor';
import { Doc, useDocStore } from '@/features/docs/doc-management';
import { HeadingBlock, useEditorStore } from '@/features/docs/doc-editor';
import { useResponsiveStore } from '@/stores';

import { Heading } from './Heading';

interface TableContentProps {
doc: Doc;
headings: HeadingBlock[];
}

export const TableContent = ({ doc, headings }: TableContentProps) => {
const { docsStore } = useDocStore();
export const TableContent = ({ headings }: TableContentProps) => {
const { editor } = useEditorStore();
const { isMobile } = useResponsiveStore();
const { t } = useTranslation();
const editor = docsStore?.[doc.id]?.editor;
const [headingIdHighlight, setHeadingIdHighlight] = useState<string>();

// To highlight the first heading in the viewport
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ export const ModalVersion = ({
}: ModalVersionProps) => {
const { toast } = useToastProvider();
const router = useRouter();
const { docsStore, setStore } = useDocStore();
const { providers } = useDocStore();
const { mutate: updateDoc } = useUpdateDoc({
listInvalideQueries: [KEY_LIST_DOC_VERSIONS],
onSuccess: () => {
Expand All @@ -41,19 +41,15 @@ export const ModalVersion = ({
router.push(`/docs/${docId}`);
};

if (!docsStore?.[docId]?.provider || !docsStore?.[versionId]?.provider) {
if (!providers?.[docId] || !providers?.[versionId]) {
onDisplaySuccess();
return;
}

setStore(docId, {
editor: undefined,
});

revertUpdate(
docsStore[docId].provider.document,
docsStore[docId].provider.document,
docsStore[versionId].provider.document,
providers[docId].document,
providers[docId].document,
providers[versionId].document,
);

onDisplaySuccess();
Expand Down Expand Up @@ -83,7 +79,7 @@ export const ModalVersion = ({
fullWidth
onClick={() => {
const newDoc = toBase64(
Y.encodeStateAsUpdate(docsStore?.[versionId]?.provider.document),
Y.encodeStateAsUpdate(providers?.[versionId].document),
);

updateDoc({
Expand Down
4 changes: 2 additions & 2 deletions src/frontend/apps/impress/src/pages/docs/[id]/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -43,11 +43,11 @@ const DocPage = ({ id }: DocProps) => {
const { login } = useAuthStore();
const { data: docQuery, isError, error } = useDoc({ id });
const [doc, setDoc] = useState(docQuery);
const { setCurrentDoc, createProvider, docsStore } = useDocStore();
const { setCurrentDoc, createProvider, providers } = useDocStore();
const { setBroadcastProvider, addTask } = useBroadcastStore();
const queryClient = useQueryClient();
const navigate = useNavigate();
const provider = docsStore?.[id]?.provider;
const provider = providers?.[id];

useEffect(() => {
if (doc?.title) {
Expand Down
Loading