A fully open source & end-to-end encrypted note taking alternative to Evernote.
TypeScript asp-net-coredotnet-coreelectronfosshacktoberfestnote-managmentnote-takingnote-taking-appnotebooknotesnotes-appopen-sourceopensourceprivacyproductivityreactreact-nativereactjsself-hosted
refactor: simplify editor logic
thecodrr24ba1377df51
diff --git a/apps/web/src/common/db.js b/apps/web/src/common/db.jsindex af9d2a52c..3af1c4987 100644--- a/apps/web/src/common/db.js+++ b/apps/web/src/common/db.js@@ -11,24 +11,24 @@ async function initializeDatabase(persistence) {db = new Database(new NNStorage(persistence), EventSource, FS);// if (isTesting()) {- db.host({- API_HOST: "https://api.notesnook.com",- AUTH_HOST: "https://auth.streetwriters.co",- SSE_HOST: "https://events.streetwriters.co",- });+ // db.host({+ // API_HOST: "https://api.notesnook.com",+ // AUTH_HOST: "https://auth.streetwriters.co",+ // SSE_HOST: "https://events.streetwriters.co",+ // });// } else {// db.host({// API_HOST: "http://localhost:5264",// AUTH_HOST: "http://localhost:8264",// SSE_HOST: "http://localhost:7264",// });- // db.host({- // API_HOST: "http://192.168.10.29:5264",- // AUTH_HOST: "http://192.168.10.29:8264",- // SSE_HOST: "http://192.168.10.29:7264",- // ISSUES_HOST: "http://192.168.10.29:2624",- // SUBSCRIPTIONS_HOST: "http://192.168.10.29:9264",- // });+ db.host({+ API_HOST: "http://192.168.10.29:5264",+ AUTH_HOST: "http://192.168.10.29:8264",+ SSE_HOST: "http://192.168.10.29:7264",+ ISSUES_HOST: "http://192.168.10.29:2624",+ SUBSCRIPTIONS_HOST: "http://192.168.10.29:9264",+ });// }await db.init();diff --git a/apps/web/src/components/editor/context.ts b/apps/web/src/components/editor/context.tsnew file mode 100644index 000000000..d1a4ee375--- /dev/null+++ b/apps/web/src/components/editor/context.ts@@ -0,0 +1,68 @@+import React, { useCallback, useContext } from "react";+import { IEditor } from "./types";+import createStore from "../../common/store";+import BaseStore from "../../stores";+import { UseStore } from "zustand";+import shallow from "zustand/shallow";++type EditorSubState = {+ editor?: IEditor;+ canUndo?: boolean;+ canRedo?: boolean;+ searching?: boolean;+};+class EditorContext extends BaseStore {+ subState: EditorSubState = {};++ configure = (partial: Partial<EditorSubState>) => {+ this.set((state: EditorContext) => {+ state.subState = { ...state.subState, ...partial };+ });+ };+}++const [useEditorContext] = createStore(EditorContext) as [+ UseStore<EditorContext>,+ EditorContext+];++export function useEditorInstance() {+ return useEditorContext((store) => store.subState.editor);+}++export function useConfigureEditor() {+ return useEditorContext((store) => store.configure);+}++export function useHistory() {+ return useEditorContext(+ (store) =>+ ({+ canUndo: store.subState.canUndo,+ canRedo: store.subState.canRedo,+ undo: store.subState.editor?.undo,+ redo: store.subState.editor?.redo,+ } as const),+ shallow+ );+}++export function useSearch() {+ const isSearching = useEditorContext((store) => store.subState.searching);+ const configure = useEditorContext((store) => store.configure);+ const toggleSearch = useCallback(+ () => configure({ searching: !isSearching }),+ [isSearching, configure]+ );+ return { isSearching, toggleSearch };+}++// const EditorInstanceContext = React.createContext<IEditor | undefined>(+// undefined+// );++// export const EditorInstanceProvider = EditorInstanceContext.Provider;++// export function useEditorInstance() {+// return useContext(EditorInstanceContext);+// }diff --git a/apps/web/src/components/editor/index.tsx b/apps/web/src/components/editor/index.tsxindex 2fca56142..1cf0429d8 100644--- a/apps/web/src/components/editor/index.tsx+++ b/apps/web/src/components/editor/index.tsx@@ -1,43 +1,15 @@-import React, {- useEffect,- useRef,- Suspense,- useCallback,- useMemo,- useState,-} from "react";+import { useEffect, useCallback, useState } from "react";import { Box, Button, Flex, Text } from "rebass";import Properties from "../properties";-import {- useStore,- SESSION_STATES,- store as editorstore,-} from "../../stores/editor-store";-import { useStore as useAppStore } from "../../stores/app-store";-import Header from "./header";+import { useStore, store as editorstore } from "../../stores/editor-store";import Toolbar from "./toolbar";-import EditorLoading from "./loading";-import { db } from "../../common/db";import { AppEventManager, AppEvents } from "../../common/app-events";import { FlexScrollContainer } from "../scroll-container";import { formatDate } from "notes-core/utils/date";import { debounce, debounceWithId } from "../../utils/debounce";-import { showError } from "../../common/dialog-controller";-import { CharacterCounter, IEditor } from "./tiptap";--const ReactMCE = React.lazy(() => import("./tinymce"));-const TipTap = React.lazy(() => import("./tiptap"));-// const EMPTY_CONTENT = "<p><br></p>";-// function editorSetContent(editor, content) {-// const editorScroll = document.querySelector(".editorScroll");-// if (editorScroll) editorScroll.scrollTop = 0;--// editor.setHTML(content);--// updateWordCount(editor);--// editor.focus();-// }+import { CharacterCounter } from "./types";+import Tiptap from "./tiptap";+import Header from "./header";function updateWordCount(counter?: CharacterCounter) {AppEventManager.publish(@@ -57,153 +29,51 @@ function onEditorChange(noteId: string, sessionId: string, content: string) {const debouncedUpdateWordCount = debounce(updateWordCount, 1000);const debouncedOnEditorChange = debounceWithId(onEditorChange, 100);-function Editor({+export default function EditorManager({noteId,nonce,}: {- noteId?: string | number;+ noteId: string | number;nonce?: string;}) {- const sessionId = useStore((store) => store.session.id);- const sessionState = useStore((store) => store.session.state);- const sessionType = useStore((store) => store.session.sessionType);- const isPreviewMode = sessionType === "preview";+ const isNewSession = !!nonce && noteId === 0;+ const isOldSession = !nonce && !!noteId;++ const [content, setContent] = useState<string>("");+ const arePropertiesVisible = useStore((store) => store.arePropertiesVisible);+ const toggleProperties = useStore((store) => store.toggleProperties);+ const isPreviewMode = useStore(+ (store) => store.session.sessionType === "preview"+ );const isReadonly = useStore((store) => store.session.readonly || isPreviewMode);- const contentId = useStore((store) => store.session.contentId);- const saveSession = useStore((store) => store.saveSession);- const newSession = useStore((store) => store.newSession);- const openSession = useStore((store) => store.openSession);- const toggleProperties = useStore((store) => store.toggleProperties);- const arePropertiesVisible = useStore((store) => store.arePropertiesVisible);- const init = useStore((store) => store.init);- const isFocusMode = useAppStore((store) => store.isFocusMode);- const isSessionReady = useMemo(() => nonce || sessionId, [nonce, sessionId]);- const [editor, setEditor] = useState<IEditor>();- // const editor = useRef<IEditor>();- // const [content, setContent] = useState<string>();- // const [isEditorFocused, setIsEditorFocused] = useState<boolean>();+ // TODO move this somewhere more appropriate+ // const init = useStore((store) => store.init);useEffect(() => {- init();- }, [init]);+ if (!isNewSession) return;+ editorstore.newSession(nonce);+ setContent("");+ }, [isNewSession, nonce]);- const startSession = useCallback(- async function startSession(noteId: string | number, force?: boolean) {- if (noteId === 0) newSession(nonce);- else if (noteId) {- await openSession(noteId, force);- }- },- [newSession, openSession, nonce]- );+ useEffect(() => {+ (async function () {+ const content = await editorstore.get().getSessionContent();+ setContent(content?.data);+ })();+ }, [isPreviewMode]);- const clearContent = useCallback(() => {- if (!editor) return;- editor.clearContent();- editor.focus();- updateWordCount();- }, [editor]);+ useEffect(() => {+ if (!isOldSession) return;- const setEditorContent = useCallback(() => {- const { id } = editorstore.get().session;- async function setContents() {- if (!editor) return;- // TODO move this somewhere more appropriate- if (!db.notes?.note(id)?.synced()) {- await showError(- "Note not synced",- "This note is not fully synced. Please sync again to open this note for editing."- );- return;- }+ (async function () {+ await editorstore.openSession(noteId);let content = await editorstore.get().getSessionContent();- if (content?.data) {- editor.setContent(content.data);- editor.focus();- } else clearContent();-- editorstore.set(- (state: any) => (state.session.state = SESSION_STATES.stale)- );- if (id && content) await db.attachments?.downloadImages(id);- }- setContents();- }, [clearContent, editor]);-- const enabledPreviewMode = useCallback(() => {- // const editor = editorRef.current?.editor;- // editor.mode.set("readonly");- }, []);-- const disablePreviewMode = useCallback(- async (cancelled) => {- const { id, sessionId, content } = editorstore.get().session;- if (!cancelled) {- await editorstore.get().saveSessionContent(id, sessionId, content);- }- await startSession(id, true);- },- [startSession]- );-- useEffect(- function clearSession() {- // clearSession makes sessionId && contentId both undefined- if (!sessionId && !contentId) clearContent();- },- [sessionId, contentId, clearContent]- );-- useEffect(- function openSession() {- const { title, nonce } = editorstore.get().session;- // there can be notes that only have a title so we need to- // handle that.- if (!contentId && (!title || !!nonce)) return;- setEditorContent();- },- [sessionId, contentId, setEditorContent]- );-- useEffect(- function openPreviewSession() {- if (!isPreviewMode || sessionState !== SESSION_STATES.new) return;-- setEditorContent();- enabledPreviewMode();- },- [isPreviewMode, sessionState, setEditorContent, enabledPreviewMode]- );-- // useEffect(() => {- // if (isEditorLoading) return;- // const editor = editorRef.current?.editor;- // if (!editor) return;- // if (isReadonly) {- // editor.mode.set("readonly");- // } else {- // editor.mode.set("design");- // }- // }, [isReadonly, isEditorLoading]);-- useEffect(- function newSession() {- if (!nonce) return;-- clearContent();- },- [nonce, clearContent]- );-- useEffect(() => {- (async () => {- if (noteId === undefined) return;- await startSession(noteId);+ setContent(content?.data);})();- }, [startSession, noteId, nonce]);+ }, [noteId, isOldSession]);return (<Flex@@ -216,115 +86,101 @@ function Editor({overflow: "hidden",}}>- {!editor ? (- <Flex- sx={{- position: "absolute",- width: "full",- height: "full",- bg: "background",- zIndex: 999,- }}- >- <EditorLoading />- </Flex>- ) : null}+ {isPreviewMode && <PreviewModeNotice />}+ <Editor+ content={content}+ readonly={isReadonly}+ onRequestFocus={() => toggleProperties(false)}+ />+ {arePropertiesVisible && <Properties />}+ </Flex>+ );+}++type EditorProps = {+ readonly?: boolean;+ focusMode?: boolean;+ content: string;+ onRequestFocus?: () => void;+};+function Editor({ content, readonly, focusMode, onRequestFocus }: EditorProps) {+ useEffect(() => {+ console.log("new contentn");+ }, [content]);++ useEffect(() => {+ console.log("rerender");+ }, []);++ return (+ <><Toolbar /><FlexScrollContainerclassName="editorScroll"style={{}}viewStyle={{ display: "flex", flexDirection: "column" }}>- <Box- id="editorToolbar"- sx={{- display: isReadonly ? "none" : "flex",- bg: "background",- position: "sticky",- top: 0,- zIndex: 2,- borderBottom: "1px solid",- borderBottomColor: "border",- justifyContent: "center",- alignItems: "center",- py: 1,- }}- />- {isPreviewMode && (- <Notice- title={"Preview"}- subtitle={`You are previewing note version edited from ${formatDate(- editorstore.get().session.dateCreated- )} to ${formatDate(editorstore.get().session.dateEdited)}.`}- onCancel={() => disablePreviewMode(true)}- action={{- text: "Restore",- onClick: async () => {- await disablePreviewMode(false);- await editorstore.get().saveSession();- },- }}- />- )}<Flexvariant="columnFill"className="editor"sx={{- alignSelf: [- "stretch",- isFocusMode ? "center" : "stretch",- "center",- ],+ alignSelf: ["stretch", focusMode ? "center" : "stretch", "center"],}}- maxWidth={isFocusMode ? "min(100%,850px)" : "935px"}+ maxWidth={focusMode ? "min(100%, 850px)" : "935px"}width="100%"px={[2, 2, 35]}- mt={[2, 2, 25]}+ onClick={onRequestFocus}+ // mt={[2, 2, 25]}>- {/* <Header readonly={isReadonly} /> */}-- {isSessionReady && (- <Suspense fallback={<div />}>- <TipTap- onFocus={() => {- toggleProperties(false);- }}- onInit={(_editor) => {- setEditor(_editor);- }}- onDestroy={() => {- setEditor(undefined);- }}- onChange={(content, counter) => {- const { id, sessionId } = editorstore.get().session;- debouncedOnEditorChange(sessionId, id, sessionId, content);- if (counter) debouncedUpdateWordCount(counter);- }}- />- </Suspense>- )}+ <Box+ id="editorToolbar"+ sx={{+ display: readonly ? "none" : "flex",+ bg: "background",+ position: "sticky",+ top: 0,+ mb: 1,+ zIndex: 2,+ }}+ />+ <Header readonly={readonly} />+ <Tiptap+ readonly={readonly}+ toolbarContainerId="editorToolbar"+ content={content}+ onChange={(content, counter) => {+ const { id, sessionId } = editorstore.get().session;+ debouncedOnEditorChange(sessionId, id, sessionId, content);+ if (counter) debouncedUpdateWordCount(counter);+ }}+ /></Flex></FlexScrollContainer>- {arePropertiesVisible && <Properties />}- </Flex>+ {/* TODO <Box+ id="editorToolbar"+ sx={{+ display: readonly ? "none" : "flex",+ bg: "background",+ position: "sticky",+ top: 0,+ mb: 1,+ zIndex: 2,+ px: [2, 2, 35],+ }}+ /> */}+ </>);}-export default Editor;-function Notice({- title,- subtitle,- onCancel,- action,-}: {- title: string;- subtitle: string;- onCancel: () => void;- action?: {- text: string;- onClick: () => void;- };-}) {+function PreviewModeNotice() {+ const disablePreviewMode = useCallback(async (cancelled) => {+ const { id, sessionId, content } = editorstore.get().session;+ if (!cancelled) {+ await editorstore.saveSessionContent(id, sessionId, content);+ }+ await editorstore.openSession(id, true);+ }, []);+return (<Flexbg="bgSecondary"@@ -333,30 +189,33 @@ function Notice({alignItems={"center"}><Flex flexDirection={"column"} mr={4}>- <Text variant={"subtitle"}>{title}</Text>- <Text variant={"body"}>{subtitle}</Text>+ <Text variant={"subtitle"}>Preview</Text>+ <Text variant={"body"}>+ You are previewing note version edited from{" "}+ {formatDate(editorstore.get().session.dateCreated)} to{" "}+ {formatDate(editorstore.get().session.dateEdited)}.+ </Text></Flex><Flex>- {onCancel && (- <Button- data-test-id="editor-notice-cancel"- variant={"secondary"}- mr={1}- px={4}- onClick={onCancel}- >- Cancel- </Button>- )}- {action && (- <Button- data-test-id="editor-notice-action"- px={4}- onClick={action.onClick}- >- {action.text}- </Button>- )}+ <Button+ data-test-id="editor-notice-cancel"+ variant={"secondary"}+ mr={1}+ px={4}+ onClick={() => disablePreviewMode(true)}+ >+ Cancel+ </Button>+ <Button+ data-test-id="editor-notice-action"+ px={4}+ onClick={async () => {+ await disablePreviewMode(false);+ await editorstore.get().saveSession();+ }}+ >+ Restore+ </Button></Flex></Flex>);diff --git a/apps/web/src/components/editor/plugins/picker.ts b/apps/web/src/components/editor/plugins/picker.tsindex 78a60b7f4..d72e1babe 100644--- a/apps/web/src/components/editor/plugins/picker.ts+++ b/apps/web/src/components/editor/plugins/picker.ts@@ -14,21 +14,7 @@ const IMAGE_SIZE_LIMIT = 50 * 1024 * 1024;type MimeType = string; //`${string}/${string}`;-function register(editor: Editor) {- editor.ui.registry.addButton("attachment", {- icon: "attachment",- tooltip: "Attach a file",- onAction: () => insertAttachment(editor, "*/*"),- });-- editor.ui.registry.addButton("image", {- icon: "image",- tooltip: "Insert image",- onAction: () => insertAttachment(editor, "image/*"),- });-}--async function insertAttachment(editor: Editor, type: MimeType) {+export async function insertAttachment(type: MimeType = "*/*") {if (!isUserPremium()) {await showBuyDialog();return;@@ -39,24 +25,18 @@ async function insertAttachment(editor: Editor, type: MimeType) {});if (!selectedFile) return;- await attachFile(editor, selectedFile);+ return await attachFile(selectedFile);}-export async function attachFile(editor: Editor, selectedFile: File) {+export async function attachFile(selectedFile: File) {if (!isUserPremium()) {await showBuyDialog();return;}if (selectedFile.type.startsWith("image/")) {- const image = await pickImage(selectedFile);- if (!image) return;- //@ts-ignore- editor.execCommand("mceAttachImage", image);+ return await pickImage(selectedFile);} else {- const file = await pickFile(selectedFile);- if (!file) return;- //@ts-ignore- editor.execCommand("mceAttachFile", file);+ return await pickFile(selectedFile);}}@@ -84,10 +64,6 @@ export async function reuploadAttachment(}}-export function addPickerPlugin(tinymce: TinyMCE) {- tinymce.PluginManager.add("picker", register);-}-/*** @param {File} selectedFile* @returns@@ -176,7 +152,8 @@ function compressImage(file: File): Promise<CompressionResult> {});}-type AttachmentProgress = {+export type AttachmentProgress = {+ hash: string;type: "encrypt" | "download" | "upload";total: number;loaded: number;diff --git a/apps/web/src/components/editor/tinymce.js b/apps/web/src/components/editor/tinymce.jsindex 089b26410..f31cc5e75 100644--- a/apps/web/src/components/editor/tinymce.js+++ b/apps/web/src/components/editor/tinymce.js@@ -32,7 +32,7 @@ import "@streetwriters/tinymce-plugins/keyboardquirks";import "@streetwriters/tinymce-plugins/attachmentshandler";import "@streetwriters/tinymce-plugins/contenthandler";import "@streetwriters/tinymce-plugins/bettertable";-import { addPickerPlugin, attachFile } from "./plugins/picker";+import { attachFile } from "./plugins/picker";import "./plugins/icons";import "./plugins/attachmentshandler.css";import "@streetwriters/tinymce-plugins/blockescape";@@ -249,7 +249,7 @@ function TinyMCE(props) {onInit && onInit(editor);},setup: (editor) => {- addPickerPlugin(global.tinymce);+ // addPickerPlugin(global.tinymce);function onTap(e) {if (diff --git a/apps/web/src/components/editor/tiptap.tsx b/apps/web/src/components/editor/tiptap.tsxindex 448a23ffb..1af3efa9a 100644--- a/apps/web/src/components/editor/tiptap.tsx+++ b/apps/web/src/components/editor/tiptap.tsx@@ -1,103 +1,187 @@import { Theme } from "@notesnook/theme";import { useTheme } from "emotion-theming";-import {- Toolbar,- useTiptap,- PortalProvider,- PortalProviderAPI,- PortalRenderer,-} from "notesnook-editor";-import { EditorContent, HTMLContent } from "@tiptap/react";+import { Toolbar, useTiptap, PortalProvider } from "notesnook-editor";+import { EditorContent } from "@tiptap/react";import { Flex } from "rebass";+import { Editor } from "@tiptap/core";import "notesnook-editor/dist/styles.css";-import React from "react";+import React, { PropsWithChildren, useEffect, useRef } from "react";import useMobile from "../../utils/use-mobile";--export type CharacterCounter = {- words: () => number;- characters: () => number;-};--export interface IEditor {- focus: () => void;- setContent: (content: HTMLContent) => void;- clearContent: () => void;-}+import { AttachmentProgress, insertAttachment } from "./plugins/picker";+import { AppEventManager, AppEvents } from "../../common/app-events";+import { EV, EVENTS } from "notes-core/common";+import { CharacterCounter, IEditor } from "./types";+import { useConfigureEditor, useSearch } from "./context";+import { createPortal } from "react-dom";type TipTapProps = {- onInit?: (editor: IEditor) => void;- onDestroy?: () => void;onChange?: (content: string, counter?: CharacterCounter) => void;onFocus?: () => void;+ content?: string;+ toolbarContainerId?: string;+ readonly?: boolean;};-function TipTap(props: TipTapProps & { portalProviderAPI: PortalProviderAPI }) {+function TipTap(props: TipTapProps) {+ const {+ onChange,+ onFocus = () => {},+ content,+ toolbarContainerId,+ readonly,+ } = props;+const theme: Theme = useTheme();const isMobile = useMobile();+ const counter = useRef<CharacterCounter>();+ const configure = useConfigureEditor();+ const { isSearching, toggleSearch } = useSearch();- const { onInit, onChange, onFocus, onDestroy, portalProviderAPI } = props;- let counter: CharacterCounter | undefined;const editor = useTiptap({+ editable: !readonly,+ content,autofocus: "start",onFocus,onCreate: ({ editor }) => {- counter = editor.storage.characterCount as CharacterCounter;- if (onInit)- onInit({- focus: () => editor.commands.focus("start"),- setContent: (content) => {- editor.commands.clearContent(false);- editor.commands.setContent(content, false);- console.log("SETTING CONTENT", content);- },- clearContent: () => editor.commands.clearContent(false),- });+ counter.current = editor.storage.characterCount as CharacterCounter;+ console.log("Init!");+ configure({+ editor: toIEditor(editor),+ canRedo: editor.can().redo(),+ canUndo: editor.can().undo(),+ });},onUpdate: ({ editor }) => {- if (onChange) onChange(editor.getHTML(), counter);+ if (onChange) onChange(editor.getHTML(), counter.current);+ },+ onDestroy: () => {+ console.log("Destory!");+ configure({ editor: undefined });+ },+ onTransaction: ({ editor }) => {+ configure({+ canRedo: editor.can().redo(),+ canUndo: editor.can().undo(),+ });},- onDestroy,theme,- portalProviderAPI,- onOpenAttachmentPicker: (type) => {- console.log(type);- return false;+ onOpenAttachmentPicker: (editor, type) => {+ if (type === "file") {+ insertAttachment().then((file) => {+ if (!file) return;+ setTimeout(() => {+ editor.commands.insertAttachment(file);+ });+ });+ } else if (type === "image") {+ insertAttachment("image/*").then((image) => {+ setTimeout(() => {+ if (!image || !image.dataurl) return;+ editor.commands.insertImage({ ...image, src: image.dataurl });+ });+ });+ }+ return true;},},- [theme, portalProviderAPI]+ [content, readonly, theme]);+ useEffect(() => {+ if (isSearching) editor?.commands.startSearch();+ else editor?.commands.endSearch();+ }, [isSearching]);++ useEffect(() => {+ const isEditorSearching = editor?.storage.searchreplace?.isSearching;+ if (isSearching && !isEditorSearching) toggleSearch();+ }, [toggleSearch, editor?.storage.searchreplace?.isSearching]);++ useEffect(() => {+ if (!editor) return;++ const event = AppEventManager.subscribe(+ AppEvents.UPDATE_ATTACHMENT_PROGRESS,+ (progress: AttachmentProgress) => {+ setTimeout(() =>+ editor.commands.setAttachmentProgress({+ hash: progress.hash,+ type: progress.type,+ progress: Math.round((progress.loaded / progress.total) * 100),+ })+ );+ }+ );++ const mediaAttachmentDownloadedEvent = EV.subscribe(+ EVENTS.mediaAttachmentDownloaded,+ ({+ groupId,+ hash,+ src,+ }: {+ groupId?: string;+ hash: string;+ src: string;+ }) => {+ console.log(src, hash);+ if (groupId?.startsWith("monograph")) return;+ setTimeout(() => editor?.commands?.updateImage({ hash, src }));+ }+ );+ return () => {+ event.unsubscribe();+ mediaAttachmentDownloadedEvent.unsubscribe();+ };+ }, [editor]);+return (<Flex sx={{ flex: 1, flexDirection: "column" }}>+ <Portal containerId={toolbarContainerId}>+ <Toolbar+ editor={editor}+ theme={theme}+ location={isMobile ? "bottom" : "top"}+ isMobile={isMobile || false}+ />+ </Portal><EditorContentstyle={{ flex: 1, cursor: "text", color: theme.colors.text }}- onClick={() => {- editor?.commands.focus();- }}editor={editor}/>- <Toolbar- editor={editor}- theme={theme}- location={isMobile ? "bottom" : "top"}- isMobile={isMobile || false}- /></Flex>);}+function Portal(props: PropsWithChildren<{ containerId?: string }>) {+ const { containerId, children } = props;+ return containerId && document.getElementById(containerId) ? (+ <>+ {createPortal(+ children,+ document.getElementById(containerId),+ containerId+ )}+ </>+ ) : (+ <>{children}</>+ );+}+function TiptapProvider(props: TipTapProps) {- console.log("Rerendering tiptap provider");return (- <PortalProvider- render={(portalProviderAPI) => (- <>- <TipTap {...props} portalProviderAPI={portalProviderAPI} />- <PortalRenderer portalProviderAPI={portalProviderAPI} />- </>- )}- />+ <PortalProvider>+ <TipTap {...props} />+ </PortalProvider>);}-export default React.memo(TiptapProvider);+export default TiptapProvider;++function toIEditor(editor: Editor): IEditor {+ return {+ focus: () => editor.commands.focus("start"),+ undo: () => editor.commands.undo(),+ redo: () => editor.commands.redo(),+ };+}diff --git a/apps/web/src/components/editor/titlebox.js b/apps/web/src/components/editor/titlebox.jsindex a2fe2876d..960225adf 100644--- a/apps/web/src/components/editor/titlebox.js+++ b/apps/web/src/components/editor/titlebox.js@@ -5,79 +5,43 @@ import { Input } from "@rebass/forms";function TitleBox(props) {const { title, setTitle, shouldFocus, readonly, placeholder } = props;- const [height, setHeight] = useState(0);const inputRef = useRef();- const resize = useCallback(() => {- const textarea = document.querySelector(".editorTitle");- const dummy = document.querySelector(".dummyEditorTitle");- dummy.innerHTML = textarea.value;- setHeight(dummy.scrollHeight);- }, []);-- useEffect(() => {- if (!window.ResizeObserver) return;- const myObserver = new ResizeObserver((entries) => {- window.requestAnimationFrame(() => {- const newHeight = entries[0].contentRect.height;- setHeight(newHeight);- });- });- myObserver.observe(document.querySelector(".dummyEditorTitle"));- return () => {- myObserver.disconnect();- };- }, []);-useEffect(() => {if (!inputRef.current) return;inputRef.current.value = title;- resize();- }, [title, resize]);+ }, [title]);useEffect(() => {if (shouldFocus) inputRef.current.focus();}, [shouldFocus]);return (- <Flex width="100%" sx={{ position: "relative" }} flexShrink={0}>- <Text- className="dummyEditorTitle"- variant="heading"- minHeight={[30, 30, 60]}- fontSize={["1.625em", "1.625em", "2.625em"]}- sx={{ whiteSpace: "pre-wrap", position: "absolute", zIndex: -1 }}- ></Text>- <Input- ref={inputRef}- variant="clean"- data-test-id="editor-title"- className="editorTitle"- autoFocus={shouldFocus}- placeholder={placeholder}- as="textarea"- width="100%"- minHeight={[30, 30, 60]}- readOnly={readonly}- p={0}- sx={{- height,- overflowY: "hidden",- fontFamily: "heading",- fontSize: ["1.625em", "1.625em", "2.625em"],- fontWeight: "heading",- border: "none",- resize: "none",- }}- onKeyDown={(e) => {- if (e.key === "Enter") e.preventDefault();- }}- onChange={(e) => {- resize();- setTitle(e.target.value);- }}- />- </Flex>+ <Input+ ref={inputRef}+ variant="clean"+ data-test-id="editor-title"+ className="editorTitle"+ autoFocus={shouldFocus}+ placeholder={placeholder}+ width="100%"+ readOnly={readonly}+ p={0}+ sx={{+ overflowY: "hidden",+ fontFamily: "heading",+ fontSize: ["1.625em", "1.625em", "2.625em"],+ fontWeight: "heading",+ border: "none",+ resize: "none",+ }}+ onKeyDown={(e) => {+ if (e.key === "Enter") e.preventDefault();+ }}+ onChange={(e) => {+ setTitle(e.target.value);+ }}+ />);}diff --git a/apps/web/src/components/editor/toolbar.js b/apps/web/src/components/editor/toolbar.jsindex 5466ad21c..17a3fe418 100644--- a/apps/web/src/components/editor/toolbar.js+++ b/apps/web/src/components/editor/toolbar.js@@ -1,5 +1,4 @@-import React, { useEffect, useMemo, useState } from "react";-import tinymce from "tinymce/tinymce";+import { useEffect, useMemo, useState } from "react";import { Button, Flex, Text } from "rebass";import * as Icon from "../icons";import { useStore as useAppStore } from "../../stores/app-store";@@ -10,14 +9,11 @@ import { showToast } from "../../utils/toast";import { AnimatedInput } from "../animated";import { showPublishView } from "../publish-view";import { db } from "../../common/db";+import { useHistory, useSearch } from "./context";-const undoRedoEvents = "Undo BeforeAddUndo AddUndo Redo ClearUndos TypingUndo";function Toolbar(props) {- const sessionState = useStore((store) => store.session.state);const sessionId = useStore((store) => store.session.id);const isLocked = useStore((store) => store.session.locked);- const [undoable, setUndoable] = useState(false);- const [redoable, setRedoable] = useState(false);const [isFullscreen, setIsFullscreen] = useState(false);const isFocusMode = useAppStore((store) => store.isFocusMode);const toggleFocusMode = useAppStore((store) => store.toggleFocusMode);@@ -29,6 +25,8 @@ function Toolbar(props) {const toggleNightMode = useThemeStore((store) => store.toggleNightMode);const [isTitleVisible, setIsTitleVisible] = useState(false);const monographs = useMonographStore((store) => store.monographs);+ const { canRedo, canUndo, redo, undo } = useHistory();+ const { toggleSearch } = useSearch();const isNotePublished = useMemo(() => sessionId && db.monographs.isPublished(sessionId),@@ -40,12 +38,11 @@ function Toolbar(props) {if (!editorScroll) return;function onScroll(e) {- // const headerOffset = document.querySelector(".editorTitle").scrollHeight;- // const hideOffset = headerOffset + 60;- // if (e.target.scrollTop > hideOffset && !isTitleVisible)- // setIsTitleVisible(true);- // else if (e.target.scrollTop <= hideOffset && isTitleVisible)- // setIsTitleVisible(false);+ const hideOffset = document.querySelector(".editorTitle").scrollHeight;+ if (e.target.scrollTop > hideOffset && !isTitleVisible)+ setIsTitleVisible(e.target.scrollTop > hideOffset && !isTitleVisible);+ else if (e.target.scrollTop <= hideOffset && isTitleVisible)+ setIsTitleVisible(false);}editorScroll.addEventListener("scroll", onScroll);return () => {@@ -53,20 +50,6 @@ function Toolbar(props) {};}, [isTitleVisible]);- useEffect(() => {- function updateState() {- if (!tinymce.activeEditor) return;- setUndoable(tinymce.activeEditor.undoManager.hasUndo());- setRedoable(tinymce.activeEditor.undoManager.hasRedo());- }- tinymce.EditorManager.once("AddEditor", () => {- tinymce.activeEditor.on(undoRedoEvents, updateState);- tinymce.activeEditor.on("remove", () => {- tinymce.activeEditor.off(undoRedoEvents, updateState);- });- });- }, [sessionState]);-const tools = useMemo(() => [{@@ -89,7 +72,6 @@ function Toolbar(props) {enabled: true,onClick: () => toggleNightMode(),},-{title: isFocusMode ? "Normal mode" : "Focus mode",icon: isFocusMode ? Icon.NormalMode : Icon.FocusMode,@@ -101,7 +83,7 @@ function Toolbar(props) {exitFullscreen(document);setIsFullscreen(false);}- if (tinymce.activeEditor) tinymce.activeEditor.focus();+ // if (tinymce.activeEditor) tinymce.activeEditor.focus();},},{@@ -119,19 +101,26 @@ function Toolbar(props) {setIsFullscreen((s) => !s);},},+ {+ title: "Search",+ icon: Icon.Search,+ enabled: true,+ hidden: !sessionId,+ onClick: () => toggleSearch(),+ },{title: "Undo",icon: Icon.Undo,- enabled: undoable,+ enabled: canUndo,hidden: !sessionId,- onClick: () => tinymce.activeEditor.execCommand("Undo"),+ onClick: () => undo(),},{title: "Redo",icon: Icon.Redo,- enabled: redoable,+ enabled: canRedo,hidden: !sessionId,- onClick: () => tinymce.activeEditor.execCommand("Redo"),+ onClick: () => redo(),},{title: "Properties",@@ -142,15 +131,18 @@ function Toolbar(props) {},],[+ undo,+ redo,isFullscreen,- redoable,- undoable,+ canRedo,+ canUndo,toggleFocusMode,toggleProperties,isFocusMode,theme,toggleNightMode,sessionId,+ toggleSearch,]);diff --git a/apps/web/src/components/editor/types.ts b/apps/web/src/components/editor/types.tsnew file mode 100644index 000000000..c29685a89--- /dev/null+++ b/apps/web/src/components/editor/types.ts@@ -0,0 +1,12 @@+import { HTMLContent } from "@tiptap/react";++export type CharacterCounter = {+ words: () => number;+ characters: () => number;+};++export interface IEditor {+ focus: () => void;+ undo: () => void;+ redo: () => void;+}diff --git a/apps/web/src/stores/app-store.js b/apps/web/src/stores/app-store.jsindex 9ef080d9d..648685094 100644--- a/apps/web/src/stores/app-store.js+++ b/apps/web/src/stores/app-store.js@@ -169,7 +169,6 @@ class AppStore extends BaseStore {};sync = async (full = true, force = false) => {- return;clearTimeout(syncStatusTimeout);this.updateLastSynced();diff --git a/apps/web/src/stores/editor-store.js b/apps/web/src/stores/editor-store.jsindex e98893899..3a154b29a 100644--- a/apps/web/src/stores/editor-store.js+++ b/apps/web/src/stores/editor-store.js@@ -17,7 +17,7 @@ const SESSION_STATES = {opening: "opening",};-const getDefaultSession = (sessionId = Date.now()) => {+export const getDefaultSession = (sessionId = Date.now()) => {return {sessionType: "default",readonly: false,