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
feat: implement note version history
thecodrr9a89baddcbcb
diff --git a/apps/web/__e2e__/notehistory.test.js b/apps/web/__e2e__/notehistory.test.jsnew file mode 100644index 000000000..da6092281--- /dev/null+++ b/apps/web/__e2e__/notehistory.test.js@@ -0,0 +1,88 @@+const { Page, test, expect } = require("@playwright/test");+const { NOTE, getTestId, getEditorContent, editNote } = require("./utils");+const { createNoteAndCheckPresence, isPresent } = require("./utils/conditions");+const List = require("./utils/listitemidbuilder");++/**+ * @type {Page}+ */+var page = null;+global.page = null;+test.beforeEach(async ({ page: _page, baseURL }) => {+ global.page = _page;+ page = _page;+ await page.goto(baseURL);+ await page.waitForSelector(getTestId("routeHeader"));+});++async function createAndEditNote() {+ const noteSelector = await createNoteAndCheckPresence();++ await page.click(getTestId("notes-action-button"));++ await page.click(noteSelector);++ await editNote(null, "Some edited text.");++ return noteSelector;+}++test("editing a note should create a new session in its session history", async () => {+ await createAndEditNote();++ await page.click(getTestId("properties"));++ for (let i = 0; i < 2; ++i) {+ expect(await isPresent(List.new("session").atIndex(i).build())).toBe(true);+ }+});++test("switching sessions should change editor content", async () => {+ await createAndEditNote();++ await page.click(getTestId("properties"));++ await page.click(List.new("session").atIndex(1).build());++ expect(await getEditorContent()).toBe(NOTE.content);++ await page.click(getTestId("properties"));++ await page.click(List.new("session").atIndex(0).build());++ expect(await getEditorContent()).toBe(`Some edited text.${NOTE.content}`);+});++test("cancelling session restore should bring editor content back to original", async () => {+ await createAndEditNote();++ await page.click(getTestId("properties"));++ await page.click(List.new("session").atIndex(1).build());++ expect(await getEditorContent()).toBe(NOTE.content);++ await page.click(getTestId("editor-notice-cancel"));++ expect(await getEditorContent()).toBe(`Some edited text.${NOTE.content}`);+});++test("restoring a session should change note's content", async () => {+ const noteSelector = await createAndEditNote();++ await page.click(getTestId("properties"));++ await page.click(List.new("session").atIndex(1).build());++ expect(await getEditorContent()).toBe(NOTE.content);++ await page.click(getTestId("editor-notice-action"));++ expect(await getEditorContent()).toBe(NOTE.content);++ await page.click(getTestId("notes-action-button"));++ await page.click(noteSelector);++ expect(await getEditorContent()).toBe(NOTE.content);+});diff --git a/apps/web/package.json b/apps/web/package.jsonindex cba3e9524..8cc78d474 100644--- a/apps/web/package.json+++ b/apps/web/package.json@@ -11,7 +11,7 @@"@mdi/react": "^1.4.0","@notesnook/desktop": "file:desktop","@rebass/forms": "^4.0.6",- "@streetwritersco/tinymce-plugins": "^1.4.9",+ "@streetwritersco/tinymce-plugins": "^1.4.11","@tinymce/tinymce-react": "^3.13.0","async-mutex": "^0.3.2","axios": "^0.21.4",diff --git a/apps/web/src/common/dialogcontroller.js b/apps/web/src/common/dialogcontroller.jsindex e090853d4..7360c014b 100644--- a/apps/web/src/common/dialogcontroller.js+++ b/apps/web/src/common/dialogcontroller.js@@ -357,6 +357,12 @@ function getDialogData(type) {"All locked notes will be re-encrypted with the new password.",positiveButtonText: "Change password",};+ case "ask_vault_password":+ return {+ title: "Unlock vault",+ subtitle: "Please enter your vault password to continue.",+ positiveButtonText: "Unlock",+ };case "change_account_password":return {title: "Change account password",diff --git a/apps/web/src/common/vault.js b/apps/web/src/common/vault.jsindex b8bf44a3f..01e8c996b 100644--- a/apps/web/src/common/vault.js+++ b/apps/web/src/common/vault.js@@ -88,5 +88,11 @@ class Vault {.then((result) => result && lock(resolve));});}++ static askPassword(action) {+ return showPasswordDialog("ask_vault_password", ({ password }) => {+ return action(password);+ });+ }}export default Vault;diff --git a/apps/web/src/components/editor/header.js b/apps/web/src/components/editor/header.jsindex c8b3aeb8f..a9b64778b 100644--- a/apps/web/src/components/editor/header.js+++ b/apps/web/src/components/editor/header.js@@ -7,7 +7,7 @@ import { Button, Flex, Text } from "rebass";import IconTag from "../icon-tag";import { db } from "../../common/db";-function Header() {+function Header({ readonly }) {const title = useStore((store) => store.session.title);const id = useStore((store) => store.session.id);const tags = useStore((store) => store.session.tags);@@ -17,6 +17,7 @@ function Header() {return (<><TitleBox+ readonly={readonly}title={title}changeInterval={100}setTitle={(title) =>@@ -26,7 +27,7 @@ function Header() {}/>- {id && (+ {!readonly && id && (<Flex alignItems="center" flexWrap="wrap" sx={{ lineHeight: 2.5 }}>{tags.map((tag) => (<IconTagdiff --git a/apps/web/src/components/editor/index.js b/apps/web/src/components/editor/index.jsindex 9d76f3462..5540aed7d 100644--- a/apps/web/src/components/editor/index.js+++ b/apps/web/src/components/editor/index.js@@ -6,7 +6,7 @@ import React, {useMemo,useState,} from "react";-import { Flex } from "rebass";+import { Button, Flex, Text } from "rebass";import Properties from "../properties";import {useStore,@@ -21,6 +21,7 @@ import { db } from "../../common/db";import { AppEventManager, AppEvents } from "../../common";import debounce from "just-debounce-it";import { FlexScrollContainer } from "../scroll-container";+import { formatDate } from "notes-core/utils/date";const ReactMCE = React.lazy(() => import("./tinymce"));const EMPTY_CONTENT = "<p><br></p>";@@ -43,11 +44,14 @@ function Editor({ noteId, nonce }) {const editorRef = useRef();const [isEditorLoading, setIsEditorLoading] = useState(true);const sessionId = useStore((store) => store.session.id);+ const sessionState = useStore((store) => store.session.state);+ const isReadonly = useStore((store) => store.session.readonly);const contentId = useStore((store) => store.session.contentId);const contentType = useStore((store) => store.session.content?.type);const saveSession = useStore((store) => store.saveSession);const newSession = useStore((store) => store.newSession);const openSession = useStore((store) => store.openSession);+ const closePreviewSession = useStore((store) => store.closePreviewSession);const toggleProperties = useStore((store) => store.toggleProperties);const arePropertiesVisible = useStore((store) => store.arePropertiesVisible);const init = useStore((store) => store.init);@@ -63,6 +67,7 @@ function Editor({ noteId, nonce }) {const startSession = useCallback(async function startSession(noteId) {+ console.log("starting session");if (noteId === 0) newSession(nonce);else if (noteId) {await openSession(noteId);@@ -96,6 +101,34 @@ function Editor({ noteId, nonce }) {setContents();}, [clearContent]);+ const enabledPreviewMode = useCallback(() => {+ const editor = editorRef.current?.editor;+ editor.mode.set("readonly");+ }, []);++ const disablePreviewMode = useCallback(+ async (cancelled) => {+ const {+ content,+ oldContent,+ oldDateEdited,+ oldSessionId,+ oldDateCreated,+ } = editorstore.get().session;++ closePreviewSession({+ dateCreated: oldDateCreated,+ dateEdited: cancelled ? oldDateEdited : Date.now(),+ sessionId: cancelled ? oldSessionId : Date.now(),+ content: cancelled ? oldContent : content,+ });+ if (cancelled) setContent();++ editorRef.current?.editor?.mode.set("design");+ },+ [closePreviewSession, setContent]+ );+useEffect(function clearSession() {// clearSession makes sessionId && contentId both undefined@@ -112,7 +145,17 @@ function Editor({ noteId, nonce }) {if (!contentId && (!title || !!nonce)) return;setContent();},- [sessionId, contentId, setContent, clearContent]+ [sessionId, contentId, setContent]+ );++ useEffect(+ function openPreviewSession() {+ if (!isReadonly || sessionState !== SESSION_STATES.new) return;++ setContent();+ enabledPreviewMode();+ },+ [isReadonly, sessionState, setContent, enabledPreviewMode]);useEffect(@@ -170,6 +213,22 @@ function Editor({ noteId, nonce }) {minHeight: "39px",}}/>+ {isReadonly && (+ <Notice+ title={"Readonly mode"}+ 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 this version",+ onClick: async () => {+ await editorstore.get().saveSession();+ await disablePreviewMode(false);+ },+ }}+ />+ )}<Flexvariant="columnFill"className="editor"@@ -185,7 +244,7 @@ function Editor({ noteId, nonce }) {px={[2, 2, 35]}mt={[2, 2, 25]}>- <Header />+ <Header readonly={isReadonly} />{isSessionReady && (<Suspense fallback={<div />}>@@ -229,3 +288,41 @@ function Editor({ noteId, nonce }) {);}export default Editor;++function Notice({ title, subtitle, onCancel, action }) {+ return (+ <Flex+ bg="bgSecondary"+ p={2}+ justifyContent={"space-between"}+ alignItems={"center"}+ >+ <Flex flexDirection={"column"} mr={4}>+ <Text variant={"subtitle"}>{title}</Text>+ <Text variant={"body"}>{subtitle}</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>+ )}+ </Flex>+ </Flex>+ );+}diff --git a/apps/web/src/components/editor/titlebox.js b/apps/web/src/components/editor/titlebox.jsindex ac0ea8554..e91b72e09 100644--- a/apps/web/src/components/editor/titlebox.js+++ b/apps/web/src/components/editor/titlebox.js@@ -4,7 +4,7 @@ import { Input } from "@rebass/forms";var changeTimeout;function TitleBox(props) {- const { title, setTitle, changeInterval, shouldFocus } = props;+ const { title, setTitle, changeInterval, shouldFocus, readonly } = props;const [height, setHeight] = useState(0);const inputRef = useRef();@@ -60,6 +60,7 @@ function TitleBox(props) {as="textarea"width="100%"minHeight={[30, 30, 60]}+ readOnly={readonly}p={0}sx={{height,@@ -89,6 +90,7 @@ function TitleBox(props) {export default React.memo(TitleBox, (prevProps, nextProps) => {return (prevProps.shouldFocus === nextProps.shouldFocus &&- prevProps.title === nextProps.title+ prevProps.title === nextProps.title &&+ prevProps.readonly === nextProps.readonly);});diff --git a/apps/web/src/components/properties/index.js b/apps/web/src/components/properties/index.jsindex ea1dafa35..cdef05f13 100644--- a/apps/web/src/components/properties/index.js+++ b/apps/web/src/components/properties/index.js@@ -13,6 +13,7 @@ import { formatBytes, truncateFilename } from "../../utils/filename";import ScrollContainer from "../scroll-container";import { downloadAttachment } from "../../common/attachments";import { formatDate } from "notes-core/utils/date";+import Vault from "../../common/vault";const tools = [{ key: "pinned", icon: Icon.Pin, label: "Pin" },@@ -39,16 +40,24 @@ const metadataItems = [function Properties({ noteId }) {const [attachmentsStatus, setAttachmentsStatus] = useState({});- const session = useStore((store) => store.session);- const { color, notebooks, attachments } = session;+ const [versionHistory, setVersionHistory] = useState([]);const toggleLocked = useStore((store) => store.toggleLocked);const setSession = useStore((store) => store.setSession);- const sessionId = useStore((store) => store.session.id);+ const openPreviewSession = useStore((store) => store.openPreviewSession);const setColor = useStore((store) => store.setColor);const toggleProperties = useStore((store) => store.toggleProperties);const isFocusMode = useAppStore((store) => store.isFocusMode);+ const session = useStore((store) => store.session);+ const {+ id: sessionId,+ color,+ notebooks,+ attachments,+ readonly: isReadonly,+ } = session;+const changeState = useCallback(function changeState(prop, value) {if (prop === "locked") {@@ -87,6 +96,15 @@ function Properties({ noteId }) {};}, [attachments]);+ useEffect(() => {+ if (!sessionId) return;++ (async () => {+ const history = await db.noteHistory.get(sessionId);+ setVersionHistory(history);+ })();+ }, [sessionId]);+if (isFocusMode || !sessionId) return null;return (<>@@ -129,15 +147,19 @@ function Properties({ noteId }) {/>}>- {tools.map((tool, _) => (- <Toggle- {...tool}- key={tool.key}- toggleKey={tool.key}- onToggle={(state) => changeState(tool.key, state)}- testId={`properties-${tool.key}`}- />- ))}+ {!isReadonly && (+ <>+ {tools.map((tool, _) => (+ <Toggle+ {...tool}+ key={tool.key}+ toggleKey={tool.key}+ onToggle={(state) => changeState(tool.key, state)}+ testId={`properties-${tool.key}`}+ />+ ))}+ </>+ )}{metadataItems.map((item) => (<Flexkey={item.key}@@ -157,38 +179,42 @@ function Properties({ noteId }) {</Text></Flex>))}- <Flex- py={2}- px={2}- sx={{- cursor: "pointer",- }}- justifyContent="center"- >- {COLORS.map((label) => (+ {!isReadonly && (+ <><Flex- key={label}- justifyContent="space-between"- alignItems="center"- onClick={() => setColor(label)}+ py={2}+ px={2}sx={{cursor: "pointer",- position: "relative",}}- data-test-id={`properties-${label}`}+ justifyContent="center">- <Icon.Circle size={35} color={label.toLowerCase()} />- {label.toLowerCase() === color?.toLowerCase() && (- <Icon.Checkmark- color="static"- size={18}- sx={{ position: "absolute", left: "8px" }}- data-test-id={`properties-${label}-check`}- />- )}+ {COLORS.map((label) => (+ <Flex+ key={label}+ justifyContent="space-between"+ alignItems="center"+ onClick={() => setColor(label)}+ sx={{+ cursor: "pointer",+ position: "relative",+ }}+ data-test-id={`properties-${label}`}+ >+ <Icon.Circle size={35} color={label.toLowerCase()} />+ {label.toLowerCase() === color?.toLowerCase() && (+ <Icon.Checkmark+ color="static"+ size={18}+ sx={{ position: "absolute", left: "8px" }}+ data-test-id={`properties-${label}-check`}+ />+ )}+ </Flex>+ ))}</Flex>- ))}- </Flex>+ </>+ )}</Card>{!!notebooks?.length && (<Card title="Referenced In">@@ -346,6 +372,75 @@ function Properties({ noteId }) {})}</Card>)}+ <Card+ title="Previous Sessions"+ subtitle={"Your session history is local only."}+ >+ {versionHistory.map((session, index) => {+ const fromDate = formatDate(session.dateCreated, {+ dateStyle: "short",+ });+ const toDate = formatDate(session.dateModified, {+ dateStyle: "short",+ });+ const fromTime = formatDate(session.dateCreated, {+ timeStyle: "short",+ });+ const toTime = formatDate(session.dateModified, {+ timeStyle: "short",+ });+ const label = `${fromDate}, ${fromTime} — ${+ fromDate !== toDate ? `${toDate}, ` : ""+ }${toTime}`;++ return (+ <Flex+ data-test-id={`session-${index}`}+ py={1}+ px={2}+ sx={{+ cursor: "pointer",+ ":hover": {+ bg: "hover",+ },+ }}+ justifyContent={"space-between"}+ alignItems={"center"}+ title="Click to preview"+ onClick={async () => {+ toggleProperties(false);+ const content = await db.noteHistory.content(session.id);++ if (session.locked) {+ await Vault.askPassword(async (password) => {+ try {+ const decryptedContent =+ await db.vault.decryptContent(content, password);+ openPreviewSession({+ content: decryptedContent,+ dateCreated: session.dateCreated,+ dateEdited: session.dateModified,+ });+ return true;+ } catch (e) {+ return false;+ }+ });+ } else {+ openPreviewSession({+ content,+ dateCreated: session.dateCreated,+ dateEdited: session.dateModified,+ });+ }+ }}+ >+ <Text variant={"body"}>{label}</Text>+ {session.locked && <Icon.Lock size={14} />}+ </Flex>+ );+ })}+ </Card></ScrollContainer></AnimatedFlex></>@@ -353,7 +448,7 @@ function Properties({ noteId }) {}export default React.memo(Properties);-function Card({ title, button, children }) {+function Card({ title, subtitle, button, children }) {return (<FlexflexDirection="column"@@ -361,12 +456,15 @@ function Card({ title, button, children }) {borderRadius: "default",}}>- <Flex mx={2} my={2} alignItems="center">+ <Flex mx={2} mt={2} alignItems="center">{button}- <Text variant="subtitle" fontSize="subtitle" color="fontTertiary">- {title}- </Text>+ <Text variant="subtitle">{title}</Text></Flex>+ {subtitle && (+ <Text variant="subBody" mb={1} mx={2}>+ {subtitle}+ </Text>+ )}{children}</Flex>);diff --git a/apps/web/src/stores/editor-store.js b/apps/web/src/stores/editor-store.jsindex 019bf6a00..364808722 100644--- a/apps/web/src/stores/editor-store.js+++ b/apps/web/src/stores/editor-store.js@@ -15,8 +15,11 @@ const SESSION_STATES = {unlocked: "unlocked",opening: "opening",};-const getDefaultSession = () => {++const getDefaultSession = (sessionId = Date.now()) => {return {+ readonly: false,+ sessionId,contentId: undefined,notebooks: undefined,state: undefined,@@ -61,7 +64,7 @@ class EditorStore extends BaseStore {openLockedSession = async (note) => {this.set((state) => {state.session = {- ...getDefaultSession(),+ ...getDefaultSession(note.dateEdited),...note,id: undefined, // NOTE: we give a session id only after the note is opened.content: note.content,@@ -72,6 +75,39 @@ class EditorStore extends BaseStore {hashNavigate(`/notes/${note.id}/edit`, { replace: true });};+ openPreviewSession = (session) => {+ const { content, dateCreated, dateEdited } = session;+ this.set((state) => {+ state.session.oldContent = state.session.content;+ state.session.oldDateCreated = state.session.dateCreated;+ state.session.oldDateEdited = state.session.dateEdited;+ state.session.oldSessionId = state.session.sessionId;++ state.session.content = content;+ state.session.sessionId = undefined;+ state.session.dateCreated = dateCreated;+ state.session.dateEdited = dateEdited;+ state.session.readonly = true;+ state.session.state = SESSION_STATES.new;+ });+ };++ closePreviewSession = (newSession) => {+ this.set((state) => {+ state.session.content = newSession.content;+ state.session.sessionId = newSession.sessionId;+ state.session.dateCreated = newSession.dateCreated;+ state.session.dateEdited = newSession.dateEdited;+ state.session.readonly = false;+ state.session.state = SESSION_STATES.stale;++ delete state.session.oldContent;+ delete state.session.oldDateCreated;+ delete state.session.oldDateEdited;+ delete state.session.oldSessionId;+ });+ };+openSession = async (noteId, force) => {await db.notes.init();@@ -102,7 +138,7 @@ class EditorStore extends BaseStore {let content = await db.content.raw(note.contentId, false);this.set((state) => {- const defaultSession = getDefaultSession();+ const defaultSession = getDefaultSession(note.dateEdited);state.session = {...defaultSession,...note,@@ -117,8 +153,10 @@ class EditorStore extends BaseStore {saveSession = (oldSession) => {const session = this.get().session;if (session.isSaving) return; // avoid multiple in-queue saves; only save one time.+ if (session.state === SESSION_STATES.preview) return; // do not allow saving of preview-only content+this.set((state) => (state.session.isSaving = true));- this._saveFn()(session)+ return this._saveFn()(session).then(async (id) => {let note = db.notes.note(id)?.data;if (!note) {@@ -156,13 +194,18 @@ class EditorStore extends BaseStore {db.attachments.ofNote(note.id, "all") || [];});+ if (!oldSession) {+ noteStore.refresh();+ return;+ }+if (note.headline !== oldSession.headline ||note.title !== oldSession.title)noteStore.refresh();- if (!oldSession?.id) {+ if (!oldSession.id) {hashNavigate(`/notes/${id}/edit`, { replace: true });}})@@ -210,13 +253,13 @@ class EditorStore extends BaseStore {setSession = (set) => {const oldSession = qclone(this.get().session);this.set(set);- this.get().saveSession(oldSession);+ return this.saveSession(oldSession);};setSessionContent = (content) => {const oldSession = qclone(this.get().session);this.get().session.content = content;- this.saveSession(oldSession);+ return this.saveSession(oldSession);};toggleLocked = () => {