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: add sync progress
thecodrr250de16ff9d3
diff --git a/apps/web/src/app-effects.js b/apps/web/src/app-effects.jsindex 69024b0cf..d1df9e2a3 100644--- a/apps/web/src/app-effects.js+++ b/apps/web/src/app-effects.js@@ -38,6 +38,7 @@ export default function AppEffects({ setShow }) {const isFocusMode = useStore((store) => store.isFocusMode);const addReminder = useStore((store) => store.addReminder);const initUser = useUserStore((store) => store.init);+ const initStore = useStore((store) => store.init);const initNotes = useNotesStore((store) => store.init);const initAttachments = useAttachmentStore((store) => store.init);const setIsVaultCreated = useStore((store) => store.setIsVaultCreated);@@ -65,10 +66,14 @@ export default function AppEffects({ setShow }) {});- EV.subscribe(EVENTS.databaseSyncRequested, async (full, force) => {- await sync(full, force);- });+ db.eventManager.subscribe(+ EVENTS.databaseSyncRequested,+ async (full, force) => {+ await sync(full, force);+ }+ );+ initStore();initAttachments();refreshNavItems();initNotes();@@ -88,6 +93,7 @@ export default function AppEffects({ setShow }) {};},[+ initStore,initAttachments,sync,updateLastSynced,diff --git a/apps/web/src/common/dialogcontroller.js b/apps/web/src/common/dialogcontroller.jsindex fb424ef7d..54e21a5c9 100644--- a/apps/web/src/common/dialogcontroller.js+++ b/apps/web/src/common/dialogcontroller.js@@ -39,7 +39,8 @@ function showDialog(dialog) {}export function closeOpenedDialog() {- const root = document.getElementById("dialogContainer");+ const root = document.getElementById("ReactModalPortal");+ if (!root) return;ReactDOM.unmountComponentAtNode(root);}@@ -139,6 +140,10 @@ export function confirm({));}+export function showError(title, message) {+ return confirm({ title, message, yesText: "Okay" });+}+export function showMultiDeleteConfirmation(length) {return confirm({title: `Delete ${length} items?`,diff --git a/apps/web/src/components/attachment/index.js b/apps/web/src/components/attachment/index.jsindex ee89ae17f..00196c761 100644--- a/apps/web/src/components/attachment/index.js+++ b/apps/web/src/components/attachment/index.js@@ -161,8 +161,8 @@ const menuItems = [key: "recheck",title: () => "Recheck",icon: Icon.DoubleCheckmark,- disabled: ({ attachment }) => !attachment.dateUploaded,- disableReason: "This attachment is not uploaded yet.",+ disabled: ({ attachment }) =>+ !attachment.dateUploaded ? "This attachment is not uploaded yet." : false,onClick: async ({ items }) => {await store.recheck(items.map((i) => i.metadata.hash));},@@ -182,8 +182,8 @@ const menuItems = [title: ({ attachment }) =>attachment.status?.type === "download" ? "Cancel download" : "Download",icon: Icon.Download,- disabled: ({ attachment }) => !attachment.dateUploaded,- disableReason: "This attachment is not uploaded yet.",+ disabled: ({ attachment }) =>+ !attachment.dateUploaded ? "This attachment is not uploaded yet." : false,onClick: async ({ attachment }) => {const isDownloading = attachment.status?.type === "download";if (isDownloading) {diff --git a/apps/web/src/components/editor/header.js b/apps/web/src/components/editor/header.jsindex 650534fbc..200637bc9 100644--- a/apps/web/src/components/editor/header.js+++ b/apps/web/src/components/editor/header.js@@ -14,7 +14,6 @@ function Header({ readonly }) {const tags = useStore((store) => store.session.tags);const setTag = useStore((store) => store.setTag);const setTitle = useStore((store) => store.setTitle);- console.log(title, id);const filterableTags = useMemo(() => {return db.tags.all.filter((t) => tags.every((tag) => tag !== t.title));}, [tags]);diff --git a/apps/web/src/components/editor/index.js b/apps/web/src/components/editor/index.jsindex 1f5611bc1..96ce9deb3 100644--- a/apps/web/src/components/editor/index.js+++ b/apps/web/src/components/editor/index.js@@ -22,6 +22,7 @@ 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";const ReactMCE = React.lazy(() => import("./tinymce"));// const EMPTY_CONTENT = "<p><br></p>";@@ -94,6 +95,7 @@ function Editor({ noteId, nonce }) {if (!editor || !editor.initialized) return;editor.clearContent();updateWordCount(editor);+ editor.focus(); // TODO}, []);const setContent = useCallback(() => {@@ -102,6 +104,14 @@ function Editor({ noteId, nonce }) {if (!editor || !editor.initialized) return;async function setContents() {+ if (!db.notes.note(noteId)?.synced()) {+ await showError(+ "Note not synced",+ "This note is not fully synced. Please sync again to open this note for editing."+ );+ return;+ }+let content = await editorstore.get().getSessionContent();if (content?.data) editorSetContent(editor, content.data);else clearContent(editor);diff --git a/apps/web/src/components/editor/plugins/picker.ts b/apps/web/src/components/editor/plugins/picker.tsindex c39cd96d3..78a60b7f4 100644--- a/apps/web/src/components/editor/plugins/picker.ts+++ b/apps/web/src/components/editor/plugins/picker.ts@@ -129,7 +129,7 @@ async function getEncryptionKey(): Promise<SerializedKey> {type FilePickerOptions = { acceptedFileTypes: MimeType };-function showFilePicker({+export function showFilePicker({acceptedFileTypes,}: FilePickerOptions): Promise<File | undefined> {return new Promise((resolve) => {diff --git a/apps/web/src/components/editor/titlebox.js b/apps/web/src/components/editor/titlebox.jsindex 3cb95069e..a08c3ffde 100644--- a/apps/web/src/components/editor/titlebox.js+++ b/apps/web/src/components/editor/titlebox.js@@ -31,7 +31,6 @@ function TitleBox(props) {useEffect(() => {if (!inputRef.current) return;- console.log("TITLE!", title);inputRef.current.value = title;resize();}, [title, resize]);@@ -83,7 +82,6 @@ function TitleBox(props) {}export default React.memo(TitleBox, (prevProps, nextProps) => {- console.log("React.memo", prevProps.title === nextProps.title);return (prevProps.shouldFocus === nextProps.shouldFocus &&prevProps.title === nextProps.title &&diff --git a/apps/web/src/components/group-header/index.js b/apps/web/src/components/group-header/index.jsindex cd463fa66..2d59233ef 100644--- a/apps/web/src/components/group-header/index.js+++ b/apps/web/src/components/group-header/index.js@@ -9,6 +9,7 @@ import useMobile from "../../utils/use-mobile";const groupByToTitleMap = {[undefined]: "Default",+ none: "None",default: "Default",abc: "A - Z",year: "Year",@@ -84,6 +85,7 @@ const menuItems = [title: "Group by",icon: Icon.GroupBy,items: map([+ { key: "none", title: "None" },{ key: "default", title: "Default" },{ key: "year", title: "Year" },{ key: "month", title: "Month" },@@ -168,7 +170,7 @@ function GroupHeader(props) {]);const isCompact = useMemo(() => viewMode === "compact", [viewMode]);- if (!title) return null;+ // if (!title) return null;return (<Flexdiff --git a/apps/web/src/components/navigation-menu/index.js b/apps/web/src/components/navigation-menu/index.jsindex 7d3cab8c8..d14cb0c37 100644--- a/apps/web/src/components/navigation-menu/index.js+++ b/apps/web/src/components/navigation-menu/index.js@@ -28,7 +28,6 @@ import { useStore as useUserStore } from "../../stores/user-store";import { useStore as useThemeStore } from "../../stores/theme-store";import useLocation from "../../hooks/use-location";import { FlexScrollContainer } from "../scroll-container";-import { toTitleCase } from "../../utils/string";const navigationHistory = new Map();function shouldSelectNavItem(route, pin) {@@ -80,11 +79,7 @@ function NavigationMenu(props) {const colors = useAppStore((store) => store.colors);const pins = useAppStore((store) => store.menuPins);const refreshNavItems = useAppStore((store) => store.refreshNavItems);- const isSyncing = useAppStore((store) => store.syncStatus === "syncing");const isLoggedIn = useUserStore((store) => store.isLoggedIn);- const sync = useAppStore((store) => store.sync);- const theme = useThemeStore((store) => store.theme);- const toggleNightMode = useThemeStore((store) => store.toggleNightMode);const isMobile = useMobile();const _navigate = useCallback(@@ -227,7 +222,7 @@ function NavigationMenu(props) {</Flex></FlexScrollContainer><Flex flexDirection="column">- {theme === "light" ? (+ {/* {theme === "light" ? (<NavigationItemtitle="Dark mode"icon={DarkMode}@@ -239,17 +234,8 @@ function NavigationMenu(props) {icon={LightMode}onClick={toggleNightMode}/>- )}- {isLoggedIn ? (- <>- <NavigationItem- title="Sync"- isLoading={isSyncing}- icon={Sync}- onClick={sync}- />- </>- ) : (+ )} */}+ {!isLoggedIn && (<NavigationItemtitle="Login"icon={Login}diff --git a/apps/web/src/components/note/index.js b/apps/web/src/components/note/index.jsindex 3ab58d6a6..2d406703d 100644--- a/apps/web/src/components/note/index.js+++ b/apps/web/src/components/note/index.js@@ -249,6 +249,8 @@ const formats = [},];+const notFullySyncedText =+ "Cannot perform this action because note is not fully synced.";const menuItems = [{key: "pin",@@ -281,8 +283,11 @@ const menuItems = [},{key: "publish",- disabled: ({ note }) => !db.monographs.isPublished(note.id) && note.locked,- disableReason: "You cannot publish a locked note.",+ disabled: ({ note }) => {+ if (!db.notes.note(note.id).synced()) return notFullySyncedText;+ if (!db.monographs.isPublished(note.id) && note.locked)+ return "You cannot publish a locked note.";+ },icon: Icon.Publish,title: ({ note }) =>db.monographs.isPublished(note.id) ? "Unpublish" : "Publish",@@ -294,15 +299,19 @@ const menuItems = [key: "export",title: "Export as",icon: Icon.Export,- disabled: ({ note }) => note.locked,- disableReason: "Locked notes cannot be exported currently.",+ disabled: ({ note }) => {+ if (!db.notes.note(note.id).synced()) return notFullySyncedText;+ if (note.locked) return "Locked notes cannot be exported currently.";+ },items: formats.map((format) => ({key: format.type,title: format.title,tooltip: `Export as ${format.title} - ${format.subtitle}`,icon: format.icon,- disabled: ({ items }) => format.type === "pdf" && items.length > 1,- disableReason: "Multiple notes cannot be exported as PDF.",+ disabled: ({ items }) =>+ format.type === "pdf" && items.length > 1+ ? "Multiple notes cannot be exported as PDF."+ : false,onClick: async ({ items }) => {await exportNotes(format.type,@@ -316,8 +325,10 @@ const menuItems = [{key: "duplicate",title: "Duplicate",- disabled: ({ note }) => note.locked,- disableReason: "Locked notes cannot be duplicated",+ disabled: ({ note }) => {+ if (!db.notes.note(note.id).synced()) return notFullySyncedText;+ if (note.locked) return "Locked notes cannot be duplicated";+ },icon: Icon.Duplicate,onClick: async ({ note }) => {const id = await store.get().duplicate(note);@@ -335,6 +346,8 @@ const menuItems = [},{key: "lock",+ disabled: ({ note }) =>+ !db.notes.note(note.id).synced() ? notFullySyncedText : false,title: ({ note }) => (note.locked ? "Unlock" : "Lock"),icon: Icon.Lock,onClick: async ({ note }) => {@@ -351,6 +364,8 @@ const menuItems = [},{key: "sync-disable",+ disabled: ({ note }) =>+ !db.notes.note(note.id).synced() ? notFullySyncedText : false,title: ({ note }) => (note.localOnly ? "Enable sync" : "Disable sync"),icon: ({ note }) => (note.localOnly ? Icon.Sync : Icon.SyncOff),onClick: async ({ note }) => {@@ -373,9 +388,18 @@ const menuItems = [color: "error",iconColor: "error",icon: Icon.Trash,- disabled: ({ items }) =>- items.length === 1 && db.monographs.isPublished(items[0].id),- disableReason: "Please unpublish this note to move it to trash",+ disabled: ({ items }) => {+ const areAllSynced = items.reduce((prev, curr) => {+ if (!prev || !db.notes.note(curr.id).synced()) return false;+ return prev;+ }, true);+ if (!areAllSynced) return notFullySyncedText;++ if (items.length !== 1) return false;++ if (db.monographs.isPublished(items[0].id))+ return "Please unpublish this note to move it to trash";+ },onClick: async ({ items }) => {await Multiselect.moveNotesToTrash(items, items.length > 1);},@@ -403,7 +427,6 @@ const topicNoteMenuItems = [];function colorsToMenuItems() {- console.log(COLORS);return COLORS.map((label) => {const lowercase = label.toLowerCase();return {diff --git a/apps/web/src/components/status-bar/index.js b/apps/web/src/components/status-bar/index.jsindex e6c9ee074..5ecf95567 100644--- a/apps/web/src/components/status-bar/index.js+++ b/apps/web/src/components/status-bar/index.js@@ -55,7 +55,12 @@ function StatusBar() {size={7}color={user.isEmailConfirmed ? "success" : "warn"}/>- <Text className="selectable" variant="subBody" color="bgSecondaryText" ml={1}>+ <Text+ className="selectable"+ variant="subBody"+ color="bgSecondaryText"+ ml={1}+ >{user.email}{user.isEmailConfirmed ? "" : " (not verified)"}</Text>@@ -163,7 +168,7 @@ function SyncStatus() {const user = useUserStore((state) => state.user);const status = syncStatusFilters.find((f) =>- f.check(syncStatus, user, lastSynced)+ f.check(syncStatus.key, user, lastSynced));return (@@ -175,13 +180,25 @@ function SyncStatus() {title={status.tooltip}data-test-id={`sync-status-${status.key}`}>- <status.icon size={12} color={status.iconColor} rotate={status.loading} />- <Text variant="subBody" ml={1}>- {typeof status.text === "string" ? (- status.text- ) : (- <status.text lastSynced={lastSynced} />- )}+ {syncStatus.progress ? (+ <Text variant={"subBody"}>{syncStatus.progress}%</Text>+ ) : (+ <status.icon+ size={12}+ color={status.iconColor}+ rotate={status.loading}+ />+ )}+ <Text variant="subBody" ml={status.text ? "3px" : 0}>+ {status.text ? (+ <>+ {typeof status.text === "string" ? (+ status.text+ ) : (+ <status.text lastSynced={lastSynced} syncStatus={syncStatus} />+ )}{" "}+ </>+ ) : null}</Text></Button>);@@ -192,12 +209,12 @@ const syncStatusFilters = [key: "synced",check: (syncStatus) => syncStatus === "synced",icon: Sync,- text: ({ lastSynced }) => (- <>- {"Synced "}- <TimeAgo live={true} datetime={lastSynced} />- </>- ),+ text: ({ lastSynced }) =>+ lastSynced ? (+ <TimeAgo live={true} locale="en_short" datetime={lastSynced} />+ ) : (+ "click to sync"+ ),tooltip: "All changes are synced.",},{@@ -205,7 +222,7 @@ const syncStatusFilters = [check: (syncStatus) => syncStatus === "syncing",icon: Sync,loading: true,- text: "Syncing",+ text: ({ syncStatus }) => <>{syncStatus.type || "sync"}ing</>,tooltip: "Syncing your notes...",},{@@ -213,7 +230,7 @@ const syncStatusFilters = [check: (syncStatus) => syncStatus === "completed",icon: Checkmark,iconColor: "success",- text: "Sync completed",+ text: "",},{key: "conflicts",@@ -231,13 +248,6 @@ const syncStatusFilters = [text: "Sync disabled",tooltip: "Please confirm your email to start syncing.",},- {- key: "neverSynced",- check: (_syncStatus, _user, lastSynced) => !lastSynced,- icon: Sync,- text: "Synced never",- tooltip: "Click to sync your notes.",- },{key: "failed",check: (syncStatus) => syncStatus === "failed",diff --git a/apps/web/src/components/time-ago/index.js b/apps/web/src/components/time-ago/index.jsindex bad43351c..866031362 100644--- a/apps/web/src/components/time-ago/index.js+++ b/apps/web/src/components/time-ago/index.js@@ -2,7 +2,6 @@ import { formatDate } from "notes-core/utils/date";import React, { useEffect, useRef } from "react";import { Text } from "rebass";import { register, format, cancel, render } from "timeago.js";-import en_short from "timeago.js/lib/lang/en_short";const shortLocale = [["now", "now"],@@ -20,8 +19,25 @@ const shortLocale = [["1yr", "in 1yr"],["%syr", "in %syr"],];++const enShortLocale = [+ ["now", "now"],+ ["%ss ago", "in %ss"],+ ["1m ago", "in 1m"],+ ["%sm ago", "in %sm"],+ ["1h ago", "in 1h"],+ ["%sh ago", "in %sh"],+ ["1d ago", "in 1d"],+ ["%sd ago", "in %sd"],+ ["1w ago", "in 1w"],+ ["%sw ago", "in %sw"],+ ["1mo ago", "in 1mo"],+ ["%smo ago", "in %smo"],+ ["1yr ago", "in 1yr"],+ ["%syr ago", "in %syr"],+];register("short", (_n, index) => shortLocale[index]);-register("en_short", en_short);+register("en_short", (_n, index) => enShortLocale[index]);function TimeAgo({ datetime, live, locale, opts, ...restProps }) {const timeRef = useRef();diff --git a/apps/web/src/hooks/use-menu.js b/apps/web/src/hooks/use-menu.jsindex 8702eb7ed..9338e9998 100644--- a/apps/web/src/hooks/use-menu.js+++ b/apps/web/src/hooks/use-menu.js@@ -161,7 +161,6 @@ function mapMenuItems(items, data) {key,onClick: _onClick,color,- disableReason,disabled,hidden,checked,@@ -189,7 +188,7 @@ function mapMenuItems(items, data) {const onClick =typeof _onClick === "function" && _onClick.bind(this, data, item);- const tooltip = (isDisabled && disableReason) || item.tooltip || title;+ const tooltip = isDisabled || item.tooltip || title;const isPremium = isPro && !isUserPremium();const hasSubmenu = items?.length > 0;diff --git a/apps/web/src/hooks/useStatus.js b/apps/web/src/hooks/use-status.tssimilarity index 65%rename from apps/web/src/hooks/useStatus.jsrename to apps/web/src/hooks/use-status.tsindex c842c46b9..00af90693 100644--- a/apps/web/src/hooks/useStatus.js+++ b/apps/web/src/hooks/use-status.ts@@ -1,10 +1,22 @@import create from "zustand";import produce from "immer";-const useStatusStore = create((set, get) => ({+type Status = {+ key: string;+ status: string;+ progress?: number;+ icon?: string | null;+};+interface IStatusStore {+ statuses: Record<string, Status>;+ getStatus: (key: string) => Status;+ updateStatus: (status: Status) => void;+ removeStatus: (key: string) => void;+}+const useStatusStore = create<IStatusStore>((set, get) => ({statuses: {},- getStatus: (key) => get().statuses[key],- updateStatus: ({ key, status, progress, icon }) =>+ getStatus: (key: string) => get().statuses[key],+ updateStatus: ({ key, status, progress, icon }: Status) =>set(produce((state) => {if (!key) return;diff --git a/apps/web/src/interfaces/fs.js b/apps/web/src/interfaces/fs.jsindex 08dea456d..30e995e1c 100644--- a/apps/web/src/interfaces/fs.js+++ b/apps/web/src/interfaces/fs.js@@ -176,9 +176,12 @@ async function uploadFile(filename, requestOptions) {uploadId = "",} = fileHandle.file.additionalData || {};- if (uploaded) return true;-try {+ if (uploaded) {+ await checkUpload(filename);+ return true;+ }+const { headers, cancellationToken } = requestOptions;const initiateMultiPartUpload = await axios@@ -265,16 +268,21 @@ async function uploadFile(filename, requestOptions) {if (!fileHandle.file.type?.startsWith("image/")) {await streamablefs.deleteFile(filename);}-- if ((await getUploadedFileSize(filename)) <= 0) {- const error = `Upload verification failed: file size is 0. Please upload this file again. (File hash: ${filename})`;- throw new Error(error);- }-+ await checkUpload(filename);return true;} catch (e) {+ reportProgress(undefined, { type: "upload", hash: filename });if (e.handle) e.handle();else handleS3Error(e);++ return false;+ }+}++async function checkUpload(filename) {+ if ((await getUploadedFileSize(filename)) <= 0) {+ const error = `Upload verification failed: file size is 0. Please upload this file again. (File hash: ${filename})`;+ throw new Error(error);}}@@ -402,15 +410,20 @@ async function deleteFile(filename, requestOptions) {}async function getUploadedFileSize(filename) {- const url = `${hosts.API_HOST}/s3?name=${filename}`;- const token = await db.user.tokenManager.getAccessToken();+ try {+ const url = `${hosts.API_HOST}/s3?name=${filename}`;+ const token = await db.user.tokenManager.getAccessToken();- const attachmentInfo = await axios.head(url, {- headers: { Authorization: `Bearer ${token}` },- });+ const attachmentInfo = await axios.head(url, {+ headers: { Authorization: `Bearer ${token}` },+ });- const contentLength = parseInt(attachmentInfo.headers["content-length"]);- return isNaN(contentLength) ? 0 : contentLength;+ const contentLength = parseInt(attachmentInfo.headers["content-length"]);+ return isNaN(contentLength) ? 0 : contentLength;+ } catch (e) {+ console.error(e);+ return 0;+ }}function clearFileStorage() {@@ -552,8 +565,10 @@ function handleS3Error(e, message) {if (axios.isAxiosError(e) && e.response?.data) {const error = parseS3Error(e.response.data);showToast("error", `${message}: [${error.Code}] ${error.Message}`);- } else {+ } else if (message) {showToast("error", `${message}: ${e.message}`);+ } else {+ showToast("error", e.message);}}diff --git a/apps/web/src/navigation/hash-routes.js b/apps/web/src/navigation/hash-routes.jsindex 56b366549..7fcac4ae0 100644--- a/apps/web/src/navigation/hash-routes.js+++ b/apps/web/src/navigation/hash-routes.js@@ -5,6 +5,7 @@ import {showCreateTagDialog,showEditTagDialog,showEmailVerificationDialog,+ showError,showFeatureDialog,showOnboardingDialog,} from "../common/dialog-controller";@@ -27,6 +28,7 @@ import { hashNavigate } from ".";import { Suspense } from "react";import EditorLoading from "../components/editor/loading";import EditorPlaceholder from "../components/editor/-placeholder";+import { db } from "../common/db";const Editor = React.lazy(() => import("../components/editor"));const hashroutes = {@@ -69,6 +71,7 @@ const hashroutes = {},"/notes/:noteId/edit": ({ noteId }) => {closeOpenedDialog();+return (<Suspense fallback={<EditorLoading />}><Editor noteId={noteId} />diff --git a/apps/web/src/stores/app-store.js b/apps/web/src/stores/app-store.jsindex 9fa0ff01a..648685094 100644--- a/apps/web/src/stores/app-store.js+++ b/apps/web/src/stores/app-store.js@@ -9,21 +9,57 @@ import { store as attachmentStore } from "./attachment-store";import BaseStore from "./index";import { showToast } from "../utils/toast";import { resetReminders } from "../common/reminders";+import { EVENTS } from "notes-core/common";var syncStatusTimeout = 0;+const BATCH_SIZE = 50;class AppStore extends BaseStore {// default stateisSideMenuOpen = false;isFocusMode = false;isEditorOpen = false;isVaultCreated = false;- syncStatus = "synced";+ syncStatus = {+ key: "synced",+ progress: null,+ type: null,+ };colors = [];globalMenu = { items: [], data: {} };reminders = [];menuPins = [];lastSynced = 0;+ init = () => {+ let count = 0;+ db.eventManager.subscribe(+ EVENTS.syncProgress,+ ({ type, total, current }) => {+ if (total === current) return;+ this.set((state) => {+ state.syncStatus = {+ key: "syncing",+ progress: ((current / total) * 100).toFixed(),+ type,+ };+ });++ if (type === "download" && ++count >= BATCH_SIZE) {+ count = 0;+ this.refresh();+ }+ }+ );++ db.eventManager.subscribe(EVENTS.syncCompleted, () => {+ this.set((state) => {+ state.syncStatus = { key: "synced" };+ });+ count = 0;+ this.refresh();+ });+ };+refresh = async () => {await this.updateLastSynced();await resetReminders();@@ -135,15 +171,13 @@ class AppStore extends BaseStore {sync = async (full = true, force = false) => {clearTimeout(syncStatusTimeout);this.updateLastSynced();- this.set((state) => (state.isSyncing = true));- this.set((state) => (state.syncStatus = "syncing"));+ this.updateSyncStatus("syncing");return db.sync(full, force)- .then(async (result) => {- if (!result) return;+ .then(async () => {+ if (full) this.updateSyncStatus("completed");await this.updateLastSynced();- this.set((state) => (state.syncStatus = "completed"));return await this.refresh();}).catch(async (err) => {@@ -153,19 +187,27 @@ class AppStore extends BaseStore {if (editorstore.get().session.id)editorstore.openSession(editorstore.get().session.id, true);await this.refresh();- this.set((state) => (state.syncStatus = "conflicts"));+ this.updateSyncStatus("conflicts");} else {- this.set((state) => (state.syncStatus = "failed"));+ this.updateSyncStatus("failed");}}).finally(() => {- if (this.get().syncStatus === "conflicts") return;+ if (this.get().syncStatus.key === "conflicts") return;syncStatusTimeout = setTimeout(() => {- this.set((state) => (state.syncStatus = "synced"));+ this.updateSyncStatus("synced");}, 3000);});};++ /**+ *+ * @param {"synced" | "syncing" | "conflicts" | "failed" | "completed"} key+ */+ updateSyncStatus = (key) => {+ this.set((state) => (state.syncStatus.key = key));+ };}/**diff --git a/apps/web/src/stores/editor-store.js b/apps/web/src/stores/editor-store.jsindex 9a3713ff1..e98893899 100644--- a/apps/web/src/stores/editor-store.js+++ b/apps/web/src/stores/editor-store.js@@ -7,7 +7,6 @@ import { db } from "../common/db";import BaseStore from ".";import { EV, EVENTS } from "notes-core/common";import { hashNavigate } from "../navigation";-import { qclone } from "qclone";import { Mutex } from "async-mutex";const SESSION_STATES = {@@ -48,7 +47,6 @@ const getDefaultPreviewSession = () => ({dateCreated: 0,});-const savingMutex = new Mutex();class EditorStore extends BaseStore {session = getDefaultSession();arePropertiesVisible = false;diff --git a/apps/web/src/utils/debounce.ts b/apps/web/src/utils/debounce.tsindex c55b5a048..75af5eb01 100644--- a/apps/web/src/utils/debounce.ts+++ b/apps/web/src/utils/debounce.ts@@ -1,25 +1,3 @@-// type GenericFunction<TArgs, TReturn> = (...args: TArgs[]) => TReturn;--// export function debounce<TArgs>(fn: GenericFunction<TArgs, unknown>, wait: number) {-// let timeout: NodeJS.Timeout | null = null;-// let debounceId: string | null = null;--// var debounceWrapper = function (id: string, ...args: TArgs) {-// if (!wait) {-// return fn.apply(this, args);-// }--// if (id === debounceId) clearTimeout(timeout);-// debounceId = id;--// timeout = setTimeout(() => {-// fn(...args);-// }, wait);-// };--// return debounceWrapper;-// }-export function debounce<F extends (...args: any) => any>(func: F,waitFor: number@@ -45,7 +23,6 @@ export function debounceWithId<F extends (...args: any) => any>(if (timeout && id === debounceId) clearTimeout(timeout);debounceId = id;timeout = setTimeout(() => {- console.log(id, debounceId);func(...args);}, waitFor);};diff --git a/apps/web/src/views/notes.js b/apps/web/src/views/notes.jsindex b37d636ed..95d568fe0 100644--- a/apps/web/src/views/notes.js+++ b/apps/web/src/views/notes.js@@ -1,4 +1,4 @@-import { useEffect } from "react";+import { useEffect, useState } from "react";import ListContainer from "../components/list-container";import { useStore as useNotesStore } from "../stores/note-store";import NotesPlaceholder from "../components/placeholders/notesplacholder";@@ -6,8 +6,11 @@ import { hashNavigate, navigate } from "../navigation";import FavoritesPlaceholder from "../components/placeholders/favorites-placeholder";import { groupArray } from "notes-core/utils/grouping";import { db } from "../common/db";+import { Flex, Text } from "rebass";+import { SyncError } from "../components/icons";function Notes() {+ const [isSynced, setIsSynced] = useState(true);const context = useNotesStore((store) => store.context);const refreshContext = useNotesStore((store) => store.refreshContext);const type = context?.type === "favorite" ? "favorites" : "notes";@@ -18,6 +21,14 @@ function Notes() {}}, [context]);+ useEffect(() => {+ if (context?.type === "topic") {+ const { id, topic } = context.value;+ if (!db.notebooks.notebook(id)?.topics.topic(topic)?.synced())+ setIsSynced(false);+ }+ }, [context]);+if (!context) return null;return (<ListContainer@@ -26,6 +37,16 @@ function Notes() {refresh={refreshContext}context={{ ...context, notes: undefined }}items={groupArray(context.notes, db.settings.getGroupOptions(type))}+ header={+ isSynced ? null : (+ <Flex bg="errorBg" p={2} py={1} alignItems="center">+ <SyncError color="error" size={16} />+ <Text variant={"body"} color="error" ml={1}>+ Some notes of this topic are not synced.+ </Text>+ </Flex>+ )+ }placeholder={context.type === "favorite" ? FavoritesPlaceholder : NotesPlaceholder}