Skip to content

A fully open source & end-to-end encrypted note taking alternative to Evernote.

web: fix editor dom structure

Abdullah Atta65c988cf3694
diff --git a/apps/web/src/components/editor/action-bar.tsx b/apps/web/src/components/editor/action-bar.tsx
index b90546763..596207783 100644
--- a/apps/web/src/components/editor/action-bar.tsx
+++ b/apps/web/src/components/editor/action-bar.tsx
@@ -148,7 +148,7 @@ export function EditorActionBar() {
];
return (
- <Flex sx={{ mb: 2, gap: 2 }}>
+ <Flex sx={{ mb: 1, gap: 2 }}>
<TabStrip />
<Flex
bg="background"
diff --git a/apps/web/src/components/editor/index.tsx b/apps/web/src/components/editor/index.tsx
index 064dd0f88..298730c84 100644
--- a/apps/web/src/components/editor/index.tsx
+++ b/apps/web/src/components/editor/index.tsx
@@ -35,7 +35,8 @@ import {
DeletedEditorSession,
NewEditorSession,
ReadonlyEditorSession,
- EditorSession
+ EditorSession,
+ DocumentPreview
} from "../../stores/editor-store";
import {
useStore as useAppStore,
@@ -70,11 +71,6 @@ import { IEditor } from "./types";
const PDFPreview = React.lazy(() => import("../pdf-preview"));
-type DocumentPreview = {
- url?: string;
- hash: string;
-};
-
function saveContent(noteId: string, ignoreEdit: boolean, content: string) {
useEditorStore.getState().saveSessionContent(noteId, ignoreEdit, {
type: "tiptap",
@@ -85,46 +81,119 @@ const deferredSave = debounceWithId(saveContent, 100);
export default function TabsView() {
const sessions = useEditorStore((store) => store.sessions);
+ const documentPreview = useEditorStore((store) => store.documentPreview);
const activeSessionId = useEditorStore((store) => store.activeSessionId);
+ const arePropertiesVisible = useEditorStore(
+ (store) => store.arePropertiesVisible
+ );
+ const isTOCVisible = useEditorStore((store) => store.isTOCVisible);
+ const [dropRef, overlayRef] = useDragOverlay();
return (
<>
<EditorActionBar />
- {sessions.map((session) => (
- <Freeze
- key={session.id}
- freeze={session.needsHydration || session.id !== activeSessionId}
+ <ScopedThemeProvider
+ scope="editor"
+ ref={dropRef}
+ sx={{
+ flex: 1,
+ overflow: "hidden",
+ display: "flex",
+ flexDirection: "column"
+ }}
+ >
+ <Allotment
+ proportionalLayout={true}
+ onDragEnd={(sizes) => {
+ Config.set("editor:panesize", sizes[1]);
+ }}
>
- {session.type === "locked" ? (
- <UnlockView
- buttonTitle="Open note"
- subtitle="Please enter the password to unlock this note."
- title={session.note.title}
- unlock={async (password) => {
- const note = await db.vault.open(session.id, password);
- if (!note || !note.content)
- throw new Error("note with this id does not exist.");
-
- useEditorStore.getState().addSession({
- type: "default",
- locked: true,
- id: session.id,
- note: session.note,
- saveState: SaveState.Saved,
- sessionId: `${Date.now()}`,
- pinned: session.pinned,
- preview: session.preview,
- content: note.content
- });
- }}
- />
- ) : session.type === "conflicted" || session.type === "diff" ? (
- <DiffViewer session={session} />
- ) : (
- <MemoizedEditorView session={session} />
+ <Allotment.Pane className="editor-pane">
+ {sessions.map((session) => (
+ <Freeze
+ key={session.id}
+ freeze={
+ session.needsHydration || session.id !== activeSessionId
+ }
+ >
+ {session.type === "locked" ? (
+ <UnlockView
+ buttonTitle="Open note"
+ subtitle="Please enter the password to unlock this note."
+ title={session.note.title}
+ unlock={async (password) => {
+ const note = await db.vault.open(session.id, password);
+ if (!note || !note.content)
+ throw new Error("note with this id does not exist.");
+
+ useEditorStore.getState().addSession({
+ type: "default",
+ locked: true,
+ id: session.id,
+ note: session.note,
+ saveState: SaveState.Saved,
+ sessionId: `${Date.now()}`,
+ pinned: session.pinned,
+ preview: session.preview,
+ content: note.content
+ });
+ }}
+ />
+ ) : session.type === "conflicted" || session.type === "diff" ? (
+ <DiffViewer session={session} />
+ ) : (
+ <MemoizedEditorView session={session} />
+ )}
+ </Freeze>
+ ))}
+ </Allotment.Pane>
+
+ {documentPreview && (
+ <Allotment.Pane
+ minSize={450}
+ preferredSize={Config.get("editor:panesize", 500)}
+ >
+ <ScopedThemeProvider
+ scope="editorSidebar"
+ id="editorSidebar"
+ sx={{
+ display: "flex",
+ flexDirection: "column",
+ overflow: "hidden",
+ borderLeft: "1px solid var(--border)",
+ height: "100%",
+ bg: "background"
+ }}
+ >
+ {documentPreview.url ? (
+ <Suspense
+ fallback={
+ <DownloadAttachmentProgress hash={documentPreview.hash} />
+ }
+ >
+ <PDFPreview
+ fileUrl={documentPreview.url}
+ hash={documentPreview.hash}
+ onClose={() =>
+ useEditorStore.setState({ documentPreview: undefined })
+ }
+ />
+ </Suspense>
+ ) : (
+ <DownloadAttachmentProgress hash={documentPreview.hash} />
+ )}
+ </ScopedThemeProvider>
+ </Allotment.Pane>
)}
- </Freeze>
- ))}
+ </Allotment>
+ <DropZone overlayRef={overlayRef} />
+ {arePropertiesVisible && activeSessionId && (
+ <Properties sessionId={activeSessionId} />
+ )}
+ {isTOCVisible && activeSessionId && (
+ <TableOfContents sessionId={activeSessionId} />
+ )}
+ </ScopedThemeProvider>
</>
);
}
@@ -145,15 +214,8 @@ function EditorView({
| DeletedEditorSession;
}) {
const lastChangedTime = useRef<number>(Date.now());
- const [docPreview, setDocPreview] = useState<DocumentPreview>();
-
- const [dropRef, overlayRef] = useDragOverlay();
const root = useRef<HTMLDivElement>(null);
- const arePropertiesVisible = useEditorStore(
- (store) => store.arePropertiesVisible
- );
- const isTOCVisible = useEditorStore((store) => store.isTOCVisible);
const toggleProperties = useEditorStore((store) => store.toggleProperties);
const isFocusMode = useAppStore((store) => store.isFocusMode);
const editor = useEditorManager((store) => store.editors[session.id]?.editor);
@@ -210,95 +272,42 @@ function EditorView({
}, [editor]);
return (
- <ScopedThemeProvider ref={root} scope="editor" sx={{ flex: 1 }}>
- <div id="dialogContainer" />
- <Allotment
- proportionalLayout={true}
- onDragEnd={(sizes) => {
- Config.set("editor:panesize", sizes[1]);
+ <Flex
+ ref={root}
+ id="editorContainer"
+ sx={{
+ position: "relative",
+ alignSelf: "stretch",
+ overflow: "hidden",
+ flex: 1,
+ flexDirection: "column",
+ background: "background"
+ }}
+ >
+ <div className="dialogContainer" />
+ <Editor
+ id={session.id}
+ nonce={1}
+ content={() => session.content?.data}
+ editor={editor}
+ session={session}
+ onPreviewDocument={(preview) =>
+ useEditorStore.setState({ documentPreview: preview })
+ }
+ onContentChange={() => (lastChangedTime.current = Date.now())}
+ onSave={(content, ignoreEdit) => {
+ const data = content();
+ if (!session.content) session.content = { type: "tiptap", data };
+ else session.content.data = data;
+ deferredSave(session.id, session.id, ignoreEdit, data);
}}
- >
- <Allotment.Pane className="editor-pane">
- <Flex
- ref={dropRef}
- id="editorContainer"
- sx={{
- position: "relative",
- alignSelf: "stretch",
- overflow: "hidden",
- flex: 1,
- flexDirection: "column",
- background: "background"
- }}
- >
- <Editor
- id={session.id}
- nonce={1}
- content={() => session.content?.data}
- editor={editor}
- session={session}
- onPreviewDocument={(url) => setDocPreview(url)}
- onContentChange={() => (lastChangedTime.current = Date.now())}
- onSave={(content, ignoreEdit) => {
- const data = content();
- if (!session.content)
- session.content = { type: "tiptap", data };
- else session.content.data = data;
- deferredSave(session.id, session.id, ignoreEdit, data);
- }}
- options={{
- readonly:
- session?.type === "readonly" || session?.type === "deleted",
- onRequestFocus: () => toggleProperties(false),
- focusMode: isFocusMode
- }}
- />
- {editor && <DropZone editor={editor} overlayRef={overlayRef} />}
- </Flex>
- </Allotment.Pane>
- {docPreview && (
- <Allotment.Pane
- minSize={450}
- preferredSize={Config.get("editor:panesize", 500)}
- >
- <ScopedThemeProvider
- scope="editorSidebar"
- id="editorSidebar"
- sx={{
- display: "flex",
- flexDirection: "column",
- overflow: "hidden",
- borderLeft: "1px solid var(--border)",
- height: "100%",
- bg: "background"
- }}
- >
- {docPreview.url ? (
- <Suspense
- fallback={
- <DownloadAttachmentProgress hash={docPreview.hash} />
- }
- >
- <PDFPreview
- fileUrl={docPreview.url}
- hash={docPreview.hash}
- onClose={() => setDocPreview(undefined)}
- />
- </Suspense>
- ) : (
- <DownloadAttachmentProgress hash={docPreview.hash} />
- )}
- </ScopedThemeProvider>
- </Allotment.Pane>
- )}
- </Allotment>
- {session.type !== "new" && (
- <>
- {arePropertiesVisible && <Properties session={session} />}
- {isTOCVisible && <TableOfContents session={session} />}
- </>
- )}
- </ScopedThemeProvider>
+ options={{
+ readonly: session?.type === "readonly" || session?.type === "deleted",
+ onRequestFocus: () => toggleProperties(false),
+ focusMode: isFocusMode
+ }}
+ />
+ </Flex>
);
}
@@ -406,8 +415,8 @@ export function Editor(props: EditorProps) {
downloadOptions={{
corsHost: Config.get("corsProxy", "https://cors.notesnook.com")
}}
- onLoad={() => {
- if (editor) restoreSelection(editor, id);
+ onLoad={(editor) => {
+ restoreSelection(editor, id);
restoreScrollPosition(session);
setIsLoading(false);
}}
@@ -540,8 +549,8 @@ function EditorChrome(
display: "flex",
flexDirection: "column",
flex: 1
- // minHeight: Config.get(`${id}:scroll-position`, 0) + 100
}}
+ suppressScrollX
onScroll={debounce((e) => {
if (e.target instanceof HTMLElement) {
const scrollTop = e.target.scrollTop;
@@ -571,10 +580,9 @@ function EditorChrome(
type DropZoneProps = {
overlayRef: React.MutableRefObject<HTMLElement | undefined>;
- editor: IEditor;
};
function DropZone(props: DropZoneProps) {
- const { overlayRef, editor } = props;
+ const { overlayRef } = props;
return (
<Box
@@ -591,9 +599,11 @@ function DropZone(props: DropZoneProps) {
display: "none"
}}
onDrop={async (e) => {
- if (!e.dataTransfer.files?.length) return;
- e.preventDefault();
+ const { activeEditorId, getEditor } = useEditorManager.getState();
+ const editor = getEditor(activeEditorId || "")?.editor;
+ if (!e.dataTransfer.files?.length || !editor) return;
+ e.preventDefault();
const attachments = await attachFiles(Array.from(e.dataTransfer.files));
for (const attachment of attachments || []) {
editor.attachFile(attachment);
@@ -619,7 +629,7 @@ function DropZone(props: DropZoneProps) {
}
function useDragOverlay() {
- const dropElementRef = useRef<HTMLElement>(null);
+ const dropElementRef = useRef<HTMLDivElement>(null);
const overlayRef = useRef<HTMLElement>();
useEffect(() => {
@@ -690,10 +700,12 @@ function restoreScrollPosition(session: EditorSession) {
const scrollContainer = document.getElementById(`editorScroll_${session.id}`);
const scrollPosition = Config.get(`${session.id}:scroll-position`, 0);
if (scrollContainer) {
- requestAnimationFrame(() => {
- if (scrollContainer.scrollHeight < scrollPosition)
- scrollContainer.style.minHeight = `${scrollPosition + 100}px`;
- scrollContainer.scrollTop = scrollPosition;
+ setTimeout(() => {
+ requestAnimationFrame(() => {
+ if (scrollContainer.scrollHeight < scrollPosition)
+ scrollContainer.style.minHeight = `${scrollPosition + 100}px`;
+ scrollContainer.scrollTop = scrollPosition;
+ });
});
}
}
diff --git a/apps/web/src/components/editor/table-of-contents.tsx b/apps/web/src/components/editor/table-of-contents.tsx
index 992e9c122..671619c4b 100644
--- a/apps/web/src/components/editor/table-of-contents.tsx
+++ b/apps/web/src/components/editor/table-of-contents.tsx
@@ -38,12 +38,7 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.
import React, { useEffect, useState } from "react";
import { ArrowLeft } from "../icons";
-import {
- DefaultEditorSession,
- DeletedEditorSession,
- ReadonlyEditorSession,
- useEditorStore
-} from "../../stores/editor-store";
+import { useEditorStore } from "../../stores/editor-store";
import { AnimatedFlex } from "../animated";
import ScrollContainer from "../scroll-container";
import { ScopedThemeProvider } from "../theme-provider";
@@ -53,21 +48,21 @@ import { Button, Flex, Text } from "@theme-ui/components";
import { useEditorManager } from "./manager";
type TableOfContentsProps = {
- session: DefaultEditorSession | ReadonlyEditorSession | DeletedEditorSession;
+ sessionId: string;
};
function TableOfContents(props: TableOfContentsProps) {
- const { session } = props;
+ const { sessionId } = props;
const [active, setActive] = useState<string[]>([]);
const toggleTableOfContents = useEditorStore(
(store) => store.toggleTableOfContents
);
const tableOfContents = useEditorManager(
- (store) => store.editors[session.id]?.tableOfContents || []
+ (store) => store.editors[sessionId]?.tableOfContents || []
);
useEffect(() => {
- const editorScroll = document.getElementById(`${session.id}_editorScroll`);
+ const editorScroll = document.getElementById(`editorScroll_${sessionId}`);
if (!editorScroll) return;
function onScroll() {
const scrollTop = editorScroll?.scrollTop || 0;
@@ -87,9 +82,8 @@ function TableOfContents(props: TableOfContentsProps) {
return () => {
editorScroll.removeEventListener("scroll", onScroll);
};
- }, [session.id, tableOfContents]);
+ }, [sessionId, tableOfContents]);
- if (!session) return null;
return (
<AnimatedFlex
animate={{
diff --git a/apps/web/src/components/editor/tiptap.tsx b/apps/web/src/components/editor/tiptap.tsx
index 3fe9da51d..89dd3c855 100644
--- a/apps/web/src/components/editor/tiptap.tsx
+++ b/apps/web/src/components/editor/tiptap.tsx
@@ -67,7 +67,7 @@ export type OnChangeHandler = (
type TipTapProps = {
id: string;
editorContainer: () => HTMLElement | undefined;
- onLoad?: () => void;
+ onLoad?: (editor: IEditor) => void;
onChange?: OnChangeHandler;
onContentChange?: () => void;
onSelectionChange?: (range: { from: number; to: number }) => void;
@@ -189,13 +189,14 @@ function TipTap(props: TipTapProps) {
autofocus: "start",
onFocus,
onCreate: async ({ editor }) => {
- if (onLoad) onLoad();
if (oldNonce.current !== nonce)
editor.commands.focus("start", { scrollIntoView: true });
oldNonce.current = nonce;
+ const instance = toIEditor(editor as Editor);
+ if (onLoad) onLoad(instance);
useEditorManager.getState().setEditor(id, {
- editor: toIEditor(editor as Editor),
+ editor: instance,
canRedo: editor.can().redo(),
canUndo: editor.can().undo(),
statistics: {
@@ -206,7 +207,6 @@ function TipTap(props: TipTapProps) {
},
tableOfContents: getTableOfContents(editor.view.dom)
});
- // editor.commands.refreshSearch();
},
onUpdate: ({ editor, transaction }) => {
const changedHeadings = getChangedNodes(transaction, {
@@ -336,7 +336,7 @@ function TipTap(props: TipTapProps) {
position: "sticky",
top: 0,
bg: "background",
- zIndex: 2
+ zIndex: 1
}}
>
<Toolbar
diff --git a/apps/web/src/components/pdf-preview/index.tsx b/apps/web/src/components/pdf-preview/index.tsx
index 246162a45..01b2961e8 100644
--- a/apps/web/src/components/pdf-preview/index.tsx
+++ b/apps/web/src/components/pdf-preview/index.tsx
@@ -56,7 +56,7 @@ export function PdfPreview(props: PdfPreviewProps) {
return (
<Worker workerUrl="/pdf.worker.min.js">
- <Flex sx={{ p: 1, justifyContent: "space-between" }}>
+ <Flex sx={{ p: 1, pt: 0, justifyContent: "space-between" }}>
<Toolbar>
{(props: ToolbarSlot) => {
const {
diff --git a/apps/web/src/components/properties/index.tsx b/apps/web/src/components/properties/index.tsx
index 477f52e8a..72a93da05 100644
--- a/apps/web/src/components/properties/index.tsx
+++ b/apps/web/src/components/properties/index.tsx
@@ -34,8 +34,7 @@ import { Box, Button, Flex, Text } from "@theme-ui/components";
import {
useEditorStore,
ReadonlyEditorSession,
- DefaultEditorSession,
- DeletedEditorSession
+ DefaultEditorSession
} from "../../stores/editor-store";
import { db } from "../../common/db";
import { useStore as useAppStore } from "../../stores/app-store";
@@ -106,13 +105,13 @@ const metadataItems = [
];
type EditorPropertiesProps = {
- session: DefaultEditorSession | ReadonlyEditorSession | DeletedEditorSession;
+ sessionId: string;
};
function EditorProperties(props: EditorPropertiesProps) {
const toggleProperties = useEditorStore((store) => store.toggleProperties);
const isFocusMode = useAppStore((store) => store.isFocusMode);
const session = useEditorStore((store) =>
- store.getSession(props.session.id, [props.session.type])
+ store.getSession(props.sessionId, ["default", "readonly", "deleted"])
);
if (isFocusMode || !session) return null;
return (
@@ -132,7 +131,7 @@ function EditorProperties(props: EditorPropertiesProps) {
position: "absolute",
top: 0,
right: 0,
- zIndex: 1,
+ zIndex: 999,
height: "100%",
width: "300px",
borderLeft: "1px solid",
@@ -237,7 +236,7 @@ function InternalLinks({ noteId }: { noteId: string }) {
? db.relations.from({ id: noteId, type: "note" }, "note")
: db.relations.to({ id: noteId, type: "note" }, "note");
return links.selector.sorted(db.settings.getGroupOptions("notes"));
- }, [tabIndex]);
+ }, [tabIndex, noteId]);
return (
<Flex sx={{ flexDirection: "column", mt: 2 }}>
@@ -585,10 +584,12 @@ function Colors({ noteId, color }: { noteId: string; color?: string }) {
}
function Notebooks({ noteId }: { noteId: string }) {
- const result = usePromise(() =>
- db.relations
- .to({ id: noteId, type: "note" }, "notebook")
- .selector.sorted(db.settings.getGroupOptions("notebooks"))
+ const result = usePromise(
+ () =>
+ db.relations
+ .to({ id: noteId, type: "note" }, "notebook")
+ .selector.sorted(db.settings.getGroupOptions("notebooks")),
+ [noteId]
);
if (result.status !== "fulfilled" || result.value.length <= 0) return null;
@@ -613,10 +614,12 @@ function Notebooks({ noteId }: { noteId: string }) {
}
function Reminders({ noteId }: { noteId: string }) {
- const result = usePromise(() =>
- db.relations
- .from({ id: noteId, type: "note" }, "reminder")
- .selector.sorted(db.settings.getGroupOptions("reminders"))
+ const result = usePromise(
+ () =>
+ db.relations
+ .from({ id: noteId, type: "note" }, "reminder")
+ .selector.sorted(db.settings.getGroupOptions("reminders")),
+ [noteId]
);
if (result.status !== "fulfilled" || result.value.length <= 0) return null;
@@ -639,10 +642,12 @@ function Reminders({ noteId }: { noteId: string }) {
);
}
function Attachments({ noteId }: { noteId: string }) {
- const result = usePromise(() =>
- db.attachments
- .ofNote(noteId, "all")
- .sorted({ sortBy: "dateCreated", sortDirection: "desc" })
+ const result = usePromise(
+ () =>
+ db.attachments
+ .ofNote(noteId, "all")
+ .sorted({ sortBy: "dateCreated", sortDirection: "desc" }),
+ [noteId]
);
if (result.status !== "fulfilled" || result.value.length <= 0) return null;
@@ -664,10 +669,12 @@ function Attachments({ noteId }: { noteId: string }) {
);
}
function SessionHistory({ noteId }: { noteId: string }) {
- const result = usePromise(() =>
- db.noteHistory
- .get(noteId)
- .sorted({ sortBy: "dateModified", sortDirection: "desc" })
+ const result = usePromise(
+ () =>
+ db.noteHistory
+ .get(noteId)
+ .sorted({ sortBy: "dateModified", sortDirection: "desc" }),
+ [noteId]
);
if (result.status !== "fulfilled" || result.value.length <= 0) return null;
diff --git a/apps/web/src/stores/editor-store.ts b/apps/web/src/stores/editor-store.ts
index f3cf99206..01b1e9c16 100644
--- a/apps/web/src/stores/editor-store.ts
+++ b/apps/web/src/stores/editor-store.ts
@@ -140,6 +140,11 @@ type SessionTypeMap = {
deleted: DeletedEditorSession;
};
+export type DocumentPreview = {
+ url?: string;
+ hash: string;
+};
+
export function isLockedSession(session: EditorSession): boolean {
return (
session.type === "locked" ||
@@ -156,6 +161,7 @@ class EditorStore extends BaseStore<EditorStore> {
activeSessionId?: string;
arePropertiesVisible = false;
+ documentPreview?: DocumentPreview;
isTOCVisible = false;
editorMargins = Config.get("editor:margins", true);
history: string[] = [];
@@ -431,7 +437,6 @@ class EditorStore extends BaseStore<EditorStore> {
this.set({ activeSessionId: id });
appStore.setIsEditorOpen(!!id);
- this.toggleProperties(false);
if (id) {
const { history } = this.get();