Skip to content

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

web: get rid of dialog controller

Abdullah Atta1eb80ccc8854
diff --git a/apps/web/src/app-effects.tsx b/apps/web/src/app-effects.tsx
index e7fc966b8..d049f1442 100644
--- a/apps/web/src/app-effects.tsx
+++ b/apps/web/src/app-effects.tsx
@@ -30,17 +30,17 @@ import { db } from "./common/db";
import { EV, EVENTS } from "@notesnook/core/dist/common";
import { registerKeyMap } from "./common/key-map";
import { isUserPremium } from "./hooks/use-is-user-premium";
-import {
- showAnnouncementDialog,
- showBuyDialog,
- showFeatureDialog,
- showOnboardingDialog
-} from "./common/dialog-controller";
import { updateStatus, removeStatus, getStatus } from "./hooks/use-status";
import { showToast } from "./utils/toast";
-import { interruptedOnboarding } from "./dialogs/onboarding-dialog";
+import {
+ interruptedOnboarding,
+ OnboardingDialog
+} from "./dialogs/onboarding-dialog";
import { hashNavigate } from "./navigation";
import { desktop } from "./common/desktop-bridge";
+import { BuyDialog } from "./dialogs/buy-dialog";
+import { FeatureDialog } from "./dialogs/feature-dialog";
+import { AnnouncementDialog } from "./dialogs/announcement-dialog";
type AppEffectsProps = {
setShow: (show: boolean) => void;
@@ -69,7 +69,7 @@ export default function AppEffects({ setShow }: AppEffectsProps) {
showToast(
"error",
"Please upgrade your account to Pro to use this feature.",
- [{ text: "Upgrade now", onClick: () => showBuyDialog() }]
+ [{ text: "Upgrade now", onClick: () => BuyDialog.show({}) }]
);
return { type, result: false };
}
@@ -89,8 +89,9 @@ export default function AppEffects({ setShow }: AppEffectsProps) {
await resetNotices();
setIsVaultCreated(await db.vault.exists());
- await showOnboardingDialog(interruptedOnboarding());
- await showFeatureDialog("highlights");
+ const onboardingKey = interruptedOnboarding();
+ if (onboardingKey) await OnboardingDialog.show({ type: onboardingKey });
+ await FeatureDialog.show({ featureName: "highlights" });
await scheduleBackups();
})();
@@ -224,7 +225,7 @@ export default function AppEffects({ setShow }: AppEffectsProps) {
useEffect(() => {
if (!dialogAnnouncements.length || IS_TESTING) return;
(async () => {
- await showAnnouncementDialog(dialogAnnouncements[0]);
+ await AnnouncementDialog.show({ announcement: dialogAnnouncements[0] });
})();
}, [dialogAnnouncements]);
diff --git a/apps/web/src/common/db.ts b/apps/web/src/common/db.ts
index 73829caa1..da16c96de 100644
--- a/apps/web/src/common/db.ts
+++ b/apps/web/src/common/db.ts
@@ -20,7 +20,6 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.
import { EventSourcePolyfill as EventSource } from "event-source-polyfill";
import { DatabasePersistence, NNStorage } from "../interfaces/storage";
import { logger } from "../utils/logger";
-import { showMigrationDialog } from "./dialog-controller";
import { database } from "@notesnook/common";
import { createDialect } from "./sqlite";
import { isFeatureSupported } from "../utils/feature-check";
@@ -119,7 +118,9 @@ async function initializeDatabase(persistence: DatabasePersistence) {
logger.measure("Database initialization");
if (db.migrations?.required()) {
- await showMigrationDialog();
+ await import("../dialogs/migration-dialog").then(({ MigrationDialog }) =>
+ MigrationDialog.show({})
+ );
}
return db;
diff --git a/apps/web/src/common/dialog-controller.tsx b/apps/web/src/common/dialog-controller.tsx
deleted file mode 100644
index e533f1bd5..000000000
--- a/apps/web/src/common/dialog-controller.tsx
+++ /dev/null
@@ -1,577 +0,0 @@
-/*
-This file is part of the Notesnook project (https://notesnook.com/)
-
-Copyright (C) 2023 Streetwriters (Private) Limited
-
-This program is free software: you can redistribute it and/or modify
-it under the terms of the GNU General Public License as published by
-the Free Software Foundation, either version 3 of the License, or
-(at your option) any later version.
-
-This program is distributed in the hope that it will be useful,
-but WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-GNU General Public License for more details.
-
-You should have received a copy of the GNU General Public License
-along with this program. If not, see <http://www.gnu.org/licenses/>.
-*/
-
-import { Dialogs } from "../dialogs";
-import { store as tagStore } from "../stores/tag-store";
-import { store as appStore } from "../stores/app-store";
-import { useEditorStore } from "../stores/editor-store";
-import { store as noteStore } from "../stores/note-store";
-import { db } from "./db";
-import { showToast } from "../utils/toast";
-import Config from "../utils/config";
-import { AppVersion, getChangelog } from "../utils/version";
-import { Period } from "../dialogs/buy-dialog/types";
-import { FeatureKeys } from "../dialogs/feature-dialog";
-import { Suspense } from "react";
-import { ConfirmDialogProps } from "../dialogs/confirm";
-import { getFormattedDate } from "@notesnook/common";
-import { downloadUpdate } from "../utils/updater";
-import { ThemeMetadata } from "@notesnook/themes-server";
-import {
- Color,
- Profile,
- Reminder,
- Tag,
- AuthenticatorType
-} from "@notesnook/core";
-import { createRoot } from "react-dom/client";
-import { PasswordDialogProps } from "../dialogs/password-dialog";
-import { LinkAttributes } from "@notesnook/editor/dist/extensions/link";
-
-type DialogTypes = typeof Dialogs;
-type DialogIds = keyof DialogTypes;
-export type Perform<T = boolean> = (result: T) => void;
-type RenderDialog<TId extends DialogIds, TReturnType> = (
- dialog: DialogTypes[TId],
- perform: (result: TReturnType) => void
-) => JSX.Element;
-
-let openDialogs: Partial<Record<DialogIds, boolean>> = {};
-function showDialog<TId extends DialogIds, TReturnType>(
- id: TId,
- render: RenderDialog<TId, TReturnType>
-): Promise<TReturnType> {
- return new Promise((resolve) => {
- if (openDialogs[id]) return false;
-
- const container = document.createElement("div");
- container.id = id;
- const root = createRoot(container);
-
- const perform = (result: TReturnType) => {
- openDialogs[id] = false;
- root.unmount();
- container.remove();
- resolve(result);
- };
- const PropDialog = () => render(Dialogs[id], perform);
- root.render(
- <Suspense fallback={<div />}>
- <PropDialog />
- </Suspense>
- );
- openDialogs[id] = true;
- });
-}
-
-export function closeOpenedDialog() {
- openDialogs = {};
- const dialogs = document.querySelectorAll(
- ".ReactModalPortal,[data-react-modal-body-trap]"
- );
- dialogs.forEach((elem) => elem.remove());
-}
-
-export function showAddTagsDialog(noteIds: string[]) {
- return showDialog("AddTagsDialog", (Dialog, perform) => (
- <Dialog onClose={(res: any) => perform(res)} noteIds={noteIds} />
- ));
-}
-
-export function showCreateColorDialog() {
- return showDialog<"CreateColorDialog", string | undefined>(
- "CreateColorDialog",
- (Dialog, perform) => (
- <Dialog onClose={() => perform(undefined)} onDone={(id) => perform(id)} />
- )
- );
-}
-
-export function showAddNotebookDialog(parentId?: string) {
- return showDialog("AddNotebookDialog", (Dialog, perform) => (
- <Dialog
- parentId={parentId}
- onClose={() => {
- perform(false);
- }}
- />
- ));
-}
-
-export function showNoteLinkingDialog(attr?: LinkAttributes) {
- return showDialog<"NoteLinkingDialog", LinkAttributes | undefined>(
- "NoteLinkingDialog",
- (Dialog, perform) => (
- <Dialog
- attributes={attr}
- onDone={(link) => perform(link)}
- onClose={() => perform(undefined)}
- />
- )
- );
-}
-
-export async function showEditNotebookDialog(notebookId: string) {
- const notebook = await db.notebooks.notebook(notebookId);
- if (!notebook) return;
- return await showDialog("AddNotebookDialog", (Dialog, perform) => (
- <Dialog
- notebook={notebook}
- edit={true}
- onClose={() => {
- perform(false);
- }}
- />
- ));
-}
-
-export function showBuyDialog(plan?: Period, couponCode?: string) {
- return showDialog("BuyDialog", (Dialog, perform) => (
- <Dialog
- plan={plan}
- couponCode={couponCode}
- onClose={() => perform(false)}
- />
- ));
-}
-
-export function confirm<TCheckId extends string>(
- props: Omit<ConfirmDialogProps<TCheckId>, "onClose">
-) {
- return showDialog<"Confirm", false | Record<TCheckId, boolean>>(
- "Confirm",
- (Dialog, perform) => (
- <Dialog {...props} onClose={(result) => perform(result)} />
- )
- );
-}
-
-export function showPromptDialog(props: {
- title: string;
- description?: string;
- defaultValue?: string;
-}) {
- return showDialog<"Prompt", string | null>("Prompt", (Dialog, perform) => (
- <Dialog
- {...props}
- onClose={() => perform(null)}
- onSave={(text) => {
- perform(text);
- }}
- />
- ));
-}
-
-export function showEmailChangeDialog() {
- return showDialog("EmailChangeDialog", (Dialog, perform) => (
- <Dialog onClose={() => perform(null)} />
- ));
-}
-
-export function showError(title: string, message: string) {
- return confirm({ title, message, positiveButtonText: "Okay" });
-}
-
-export function showMultiDeleteConfirmation(length: number) {
- return confirm({
- title: `Delete ${length} items?`,
- message: `These items will be **kept in your Trash for ${
- db.settings.getTrashCleanupInterval() || 7
- } days** after which they will be permanently deleted.`,
- positiveButtonText: "Yes",
- negativeButtonText: "No"
- });
-}
-
-export function showMultiPermanentDeleteConfirmation(length: number) {
- return confirm({
- title: `Permanently delete ${length} items?`,
- message:
- "These items will be **permanently deleted**. This is IRREVERSIBLE.",
- positiveButtonText: "Yes",
- negativeButtonText: "No"
- });
-}
-
-export function showLogoutConfirmation() {
- return confirm({
- title: `Logout?`,
- message:
- "Logging out will clear all data stored on THIS DEVICE. Make sure you have synced all your changes before logging out.",
- positiveButtonText: "Yes",
- negativeButtonText: "No"
- });
-}
-
-export function showClearSessionsConfirmation() {
- return confirm({
- title: `Logout from other devices?`,
- message:
- "All other logged-in devices will be forced to logout stopping sync. Use with care lest you lose important notes.",
- positiveButtonText: "Yes",
- negativeButtonText: "No"
- });
-}
-
-export function showAccountLoggedOutNotice(reason?: string) {
- return confirm({
- title: "You were logged out",
- message: reason,
- negativeButtonText: "Okay"
- });
-}
-
-export function showAppUpdatedNotice(
- version: AppVersion & { changelog?: string }
-) {
- return confirm({
- title: `Welcome to v${version.formatted}`,
- message: `## Changelog:
-
-\`\`\`
-${version.changelog || "No change log."}
-\`\`\`
-`,
- positiveButtonText: `Continue`
- });
-}
-
-export function showEmailVerificationDialog() {
- return showDialog("EmailVerificationDialog", (Dialog, perform) => (
- <Dialog onCancel={() => perform(false)} />
- ));
-}
-
-export function showMigrationDialog() {
- return showDialog("MigrationDialog", (Dialog, perform) => (
- <Dialog onClose={() => perform(false)} />
- ));
-}
-
-type LoadingDialogProps<T> = {
- title: string;
- message?: string;
- subtitle: string;
- action: () => T | Promise<T>;
-};
-export function showLoadingDialog<T>(dialogData: LoadingDialogProps<T>) {
- const { title, message, subtitle, action } = dialogData;
- return showDialog<"LoadingDialog", T | boolean>(
- "LoadingDialog",
- (Dialog, perform) => (
- <Dialog
- title={title}
- description={subtitle}
- message={message}
- action={action}
- onClose={(e) => perform(e as T | boolean)}
- />
- )
- );
-}
-
-type ProgressDialogProps = {
- title: string;
- subtitle: string;
- action: (...args: never[]) => void;
-};
-export function showProgressDialog<T>(dialogData: ProgressDialogProps) {
- const { title, subtitle, action } = dialogData;
- return showDialog<"ProgressDialog", T>(
- "ProgressDialog",
- (Dialog, perform) => (
- <Dialog
- title={title}
- subtitle={subtitle}
- action={action}
- onDone={(e: T) => perform(e)}
- />
- )
- );
-}
-
-export function showThemeDetails(theme: ThemeMetadata) {
- return showDialog("ThemeDetailsDialog", (Dialog, perform) => (
- <Dialog theme={theme} onClose={(res: boolean) => perform(res)} />
- ));
-}
-
-export function showMoveNoteDialog(noteIds: string[]) {
- return showDialog("MoveDialog", (Dialog, perform) => (
- <Dialog noteIds={noteIds} onClose={(res: boolean) => perform(res)} />
- ));
-}
-
-export function showPasswordDialog<
- TInputId extends string,
- TCheckId extends string
->(props: Omit<PasswordDialogProps<TInputId, TCheckId>, "onClose">) {
- return showDialog<
- "PasswordDialog",
- string extends TCheckId ? boolean : false | Record<TCheckId, boolean>
- >("PasswordDialog", (Dialog, perform) => (
- <Dialog
- {...props}
- onClose={(result) =>
- perform(
- result as string extends TCheckId
- ? boolean
- : false | Record<TCheckId, boolean>
- )
- }
- />
- ));
-}
-
-export function showBackupPasswordDialog(
- validate: (outputs: {
- password?: string;
- key?: string;
- }) => boolean | Promise<boolean>
-) {
- return showDialog("BackupPasswordDialog", (Dialog, perform) => (
- <Dialog onClose={() => perform(false)} validate={validate} />
- ));
-}
-
-export function showRecoveryKeyDialog() {
- return showDialog("RecoveryKeyDialog", (Dialog, perform) => (
- <Dialog onDone={() => perform(true)} />
- ));
-}
-
-export function showCreateTagDialog() {
- return showDialog("ItemDialog", (Dialog, perform) => (
- <Dialog
- title={"Create tag"}
- subtitle={"You can create as many tags as you want."}
- onClose={() => {
- perform(false);
- }}
- onAction={async (title: string) => {
- await db.tags.add({ title });
- showToast("success", "Tag created!");
- tagStore.refresh();
- perform(true);
- }}
- />
- ));
-}
-
-export function showEditTagDialog(tag: Tag) {
- return showDialog("ItemDialog", (Dialog, perform) => (
- <Dialog
- title={"Edit tag"}
- subtitle={`You are editing #${tag.title}.`}
- defaultValue={tag.title}
- onClose={() => perform(false)}
- onAction={async (title: string) => {
- await db.tags.add({ id: tag.id, title });
- showToast("success", "Tag edited!");
- await tagStore.refresh();
- await useEditorStore.getState().refreshTags();
- await noteStore.refresh();
- await appStore.refreshNavItems();
- perform(true);
- }}
- />
- ));
-}
-
-export function showRenameColorDialog(color: Color) {
- return showDialog("ItemDialog", (Dialog, perform) => (
- <Dialog
- title={"Rename color"}
- subtitle={`You are renaming color ${color.title}.`}
- defaultValue={color.title}
- onClose={() => perform(false)}
- onAction={async (title: string) => {
- if (!title) return;
- await db.colors.add({ id: color.id, title });
- showToast("success", "Color renamed!");
- appStore.refreshNavItems();
- perform(true);
- }}
- />
- ));
-}
-
-export function showFeatureDialog(featureName: FeatureKeys) {
- return showDialog("FeatureDialog", (Dialog, perform) => (
- <Dialog featureName={featureName} onClose={(res) => perform(res)} />
- ));
-}
-
-export function showReminderDialog(reminderKey: string) {
- if (Config.get(reminderKey, false)) return;
-
- return showDialog("ReminderDialog", (Dialog, perform) => (
- <Dialog
- reminderKey={reminderKey}
- onClose={(res: boolean) => {
- Config.set(reminderKey, true);
- perform(res);
- }}
- />
- ));
-}
-
-export function showReminderPreviewDialog(reminder: Reminder) {
- return showDialog("ReminderPreviewDialog", (Dialog, perform) => (
- <Dialog reminder={reminder} onClose={perform} />
- ));
-}
-
-export async function showAddReminderDialog(noteId?: string) {
- const note = noteId ? await db.notes.note(noteId) : undefined;
- return showDialog("AddReminderDialog", (Dialog, perform) => (
- <Dialog onClose={(res: boolean) => perform(res)} note={note} />
- ));
-}
-
-export async function showEditReminderDialog(reminderId: string) {
- const reminder = await db.reminders.reminder(reminderId);
- if (!reminder) return null;
- return showDialog("AddReminderDialog", (Dialog, perform) => (
- <Dialog onClose={(res: boolean) => perform(res)} reminder={reminder} />
- ));
-}
-
-export function showAnnouncementDialog(announcement: any) {
- return showDialog("AnnouncementDialog", (Dialog, perform) => (
- <Dialog
- announcement={announcement}
- onClose={(res: boolean) => perform(res)}
- />
- ));
-}
-
-export function showIssueDialog() {
- return showDialog("IssueDialog", (Dialog, perform) => (
- <Dialog
- onClose={(res: boolean) => {
- perform(res);
- }}
- />
- ));
-}
-
-export function showMultifactorDialog(primaryMethod?: AuthenticatorType) {
- return showDialog("MultifactorDialog", (Dialog, perform) => (
- <Dialog onClose={(res) => perform(res)} primaryMethod={primaryMethod} />
- ));
-}
-
-export function show2FARecoveryCodesDialog(primaryMethod: AuthenticatorType) {
- return showDialog("RecoveryCodesDialog", (Dialog, perform) => (
- <Dialog onClose={(res) => perform(res)} primaryMethod={primaryMethod} />
- ));
-}
-
-export function showAttachmentsDialog() {
- return showDialog("AttachmentsDialog", (Dialog, perform) => (
- <Dialog onClose={(res: boolean) => perform(res)} />
- ));
-}
-
-export function showEditProfilePictureDialog(profile?: Profile) {
- return showDialog("EditProfilePictureDialog", (Dialog, perform) => (
- <Dialog onClose={(res: boolean) => perform(res)} profile={profile} />
- ));
-}
-
-export function showImagePickerDialog(images: File[]): Promise<false | File[]> {
- if (images.length <= 0) return Promise.resolve(false);
-
- return showDialog("ImagePickerDialog", (Dialog, perform) => (
- <Dialog onClose={(res) => perform(res)} images={images} />
- ));
-}
-
-export function showSettings() {
- return showDialog("SettingsDialog", (Dialog, perform) => (
- <Dialog onClose={(res: boolean) => perform(res)} />
- ));
-}
-
-export function showOnboardingDialog(type?: string) {
- if (!type) return;
- return showDialog("OnboardingDialog", (Dialog, perform) => (
- <Dialog type={type} onClose={(res: boolean) => perform(res)} />
- ));
-}
-
-export async function showInvalidSystemTimeDialog({
- serverTime,
- localTime
-}: {
- serverTime: number;
- localTime: number;
-}) {
- const result = await confirm({
- title: "Your system clock is out of sync",
- subtitle:
- "Please correct your system date & time and reload the app to avoid syncing issues.",
- message: `Server time: ${getFormattedDate(serverTime)}
-Local time: ${getFormattedDate(localTime)}
-Please sync your system time with [https://time.is](https://time.is).`,
- positiveButtonText: "Reload app"
- });
- if (result) window.location.reload();
-}
-
-export async function showUpdateAvailableNotice({
- version
-}: {
- version: string;
-}) {
- const changelog = await getChangelog(version);
-
- return showUpdateDialog({
- title: `New version available`,
- subtitle: `v${version} is available for download`,
- changelog,
- action: { text: `Update now`, onClick: () => downloadUpdate() }
- });
-}
-
-type UpdateDialogProps = {
- title: string;
- subtitle: string;
- changelog: string;
- action: {
- text: string;
- onClick: () => void;
- };
-};
-async function showUpdateDialog({
- title,
- subtitle,
- changelog,
- action
-}: UpdateDialogProps) {
- const result = await confirm({
- title,
- subtitle,
- message: changelog,
- width: 500,
- positiveButtonText: action.text
- });
- if (result && action.onClick) action.onClick();
-}
diff --git a/apps/web/src/common/dialog-manager.tsx b/apps/web/src/common/dialog-manager.tsx
new file mode 100644
index 000000000..9ce63e7a9
--- /dev/null
+++ b/apps/web/src/common/dialog-manager.tsx
@@ -0,0 +1,88 @@
+/*
+This file is part of the Notesnook project (https://notesnook.com/)
+
+Copyright (C) 2023 Streetwriters (Private) Limited
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+import React from "react";
+import { createRoot } from "react-dom/client";
+
+export interface BaseDialogProps<T = unknown> {
+ onClose: (result: T) => void;
+}
+
+class _DialogManager {
+ private openedDialogs: Set<React.JSXElementConstructor<any>> = new Set();
+
+ open<
+ Props extends BaseDialogProps<any>,
+ Result extends Props extends BaseDialogProps<infer T> ? T : unknown
+ >(
+ component: React.ComponentType<Props>,
+ props: Omit<Props, "onClose">
+ ): Promise<Result | false> {
+ if (this.openedDialogs.has(component)) return Promise.resolve(false);
+
+ const container = document.createElement("div");
+ const root = createRoot(container);
+
+ const close = () => {
+ this.openedDialogs.delete(component);
+ root.unmount();
+ container.remove();
+ };
+
+ const Dialog = component as React.FunctionComponent<
+ Omit<Props, "onClose"> & {
+ onClose: (result: any) => void;
+ }
+ >;
+ this.openedDialogs.add(component);
+ return new Promise<Result>((resolve, reject) =>
+ root.render(
+ <Dialog
+ {...props}
+ onClose={(result: Result) => {
+ try {
+ close();
+ resolve(result);
+ } catch (e) {
+ reject(e);
+ }
+ }}
+ />
+ )
+ );
+ }
+
+ closeAll() {
+ this.openedDialogs.clear();
+ const dialogs = document.querySelectorAll(
+ ".ReactModalPortal,[data-react-modal-body-trap]"
+ );
+ dialogs.forEach((elem) => elem.remove());
+ }
+
+ register<Props extends BaseDialogProps<any>>(
+ component: React.ComponentType<Props>
+ ) {
+ return {
+ show: (props: Omit<Props, "onClose">) => this.open(component, props)
+ };
+ }
+}
+
+export const DialogManager = new _DialogManager();
diff --git a/apps/web/src/common/export.ts b/apps/web/src/common/export.ts
index ebee275e7..d95c5e68c 100644
--- a/apps/web/src/common/export.ts
+++ b/apps/web/src/common/export.ts
@@ -32,7 +32,7 @@ import {
import Vault from "./vault";
import { ExportStream } from "../utils/streams/export-stream";
import { showToast } from "../utils/toast";
-import { confirm } from "./dialog-controller";
+import { ConfirmDialog } from "../dialogs/confirm";
export async function exportToPDF(
title: string,
@@ -101,14 +101,14 @@ export async function exportNotes(
}
});
if (result instanceof Error) {
- confirm({
+ ConfirmDialog.show({
title: `Export failed`,
message: result.stack || result.message,
positiveButtonText: "Okay"
});
return false;
} else {
- confirm({
+ ConfirmDialog.show({
title: `Exported ${result.count} notes`,
message:
result.errors.length > 0
diff --git a/apps/web/src/common/index.ts b/apps/web/src/common/index.ts
index d01c20f16..03c6d4c00 100644
--- a/apps/web/src/common/index.ts
+++ b/apps/web/src/common/index.ts
@@ -17,12 +17,6 @@ You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
-import {
- showBackupPasswordDialog,
- showFeatureDialog,
- showPasswordDialog,
- showReminderDialog
-} from "./dialog-controller";
import Config from "../utils/config";
import { hashNavigate, getCurrentHash } from "../navigation";
import { db } from "./db";
@@ -38,12 +32,15 @@ import { TaskManager } from "./task-manager";
import { EVENTS } from "@notesnook/core/dist/common";
import { createWritableStream } from "./desktop-bridge";
import { createZipStream } from "../utils/streams/zip-stream";
-import { FeatureKeys } from "../dialogs/feature-dialog";
+import { FeatureDialog, FeatureKeys } from "../dialogs/feature-dialog";
import { ZipEntry, createUnzipIterator } from "../utils/streams/unzip-stream";
import { User } from "@notesnook/core";
import { LegacyBackupFile } from "@notesnook/core";
import { useEditorStore } from "../stores/editor-store";
import { formatDate } from "@notesnook/core/dist/utils/date";
+import { showPasswordDialog } from "../dialogs/password-dialog";
+import { BackupPasswordDialog } from "../dialogs/backup-password-dialog";
+import { ReminderDialog } from "../dialogs/reminder-dialog";
export const CREATE_BUTTON_MAP = {
notes: {
@@ -70,7 +67,7 @@ export async function introduceFeatures() {
const features: FeatureKeys[] = [];
for (const feature of features) {
if (!Config.get(`feature:${feature}`)) {
- await showFeatureDialog(feature);
+ await FeatureDialog.show({ featureName: feature });
}
}
}
@@ -173,10 +170,12 @@ export async function restoreBackupFile(backupFile: File) {
const backup = JSON.parse(await readFile(backupFile));
if (backup.data.iv && backup.data.salt) {
- await showBackupPasswordDialog(async ({ password, key }) => {
- if (!password && !key) return false;
- const error = await restoreWithProgress(backup, password, key);
- return !error;
+ await BackupPasswordDialog.show({
+ validate: async ({ password, key }) => {
+ if (!password && !key) return false;
+ const error = await restoreWithProgress(backup, password, key);
+ return !error;
+ }
});
} else {
await restoreWithProgress(backup);
@@ -212,15 +211,15 @@ export async function restoreBackupFile(backupFile: File) {
const backup = JSON.parse(await entry.text());
if (backup.encrypted) {
if (!cachedPassword && !cachedKey) {
- const result = await showBackupPasswordDialog(
- async ({ password, key }) => {
+ const result = await BackupPasswordDialog.show({
+ validate: async ({ password, key }) => {
if (!password && !key) return false;
await db.backup?.import(backup, password, key);
cachedPassword = password;
cachedKey = key;
return true;
}
- );
+ });
if (!result) break;
} else await db.backup?.import(backup, cachedPassword, cachedKey);
} else {
@@ -318,9 +317,9 @@ export async function showUpgradeReminderDialogs() {
const isTrial = user.subscription?.type === SUBSCRIPTION_STATUS.TRIAL;
const isBasic = user.subscription?.type === SUBSCRIPTION_STATUS.BASIC;
if (isBasic && consumed >= 100) {
- await showReminderDialog("trialexpired");
+ await ReminderDialog.show({ reminderKey: "trialexpired" });
} else if (isTrial && consumed >= 75) {
- await showReminderDialog("trialexpiring");
+ await ReminderDialog.show({ reminderKey: "trialexpiring" });
}
}
diff --git a/apps/web/src/common/multi-select.ts b/apps/web/src/common/multi-select.ts
index d67b429cc..3c20e969f 100644
--- a/apps/web/src/common/multi-select.ts
+++ b/apps/web/src/common/multi-select.ts
@@ -17,7 +17,6 @@ You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
-import { confirm, showMultiDeleteConfirmation } from "./dialog-controller";
import { store as noteStore } from "../stores/note-store";
import { store as notebookStore } from "../stores/notebook-store";
import { store as attachmentStore } from "../stores/attachment-store";
@@ -27,6 +26,7 @@ import { showToast } from "../utils/toast";
import Vault from "./vault";
import { TaskManager } from "./task-manager";
import { pluralize } from "@notesnook/common";
+import { ConfirmDialog, showMultiDeleteConfirmation } from "../dialogs/confirm";
async function moveNotesToTrash(ids: string[], confirm = true) {
if (confirm && !(await showMultiDeleteConfirmation(ids.length))) return;
@@ -79,7 +79,7 @@ async function moveNotebooksToTrash(ids: string[]) {
async function deleteAttachments(ids: string[]) {
if (
- !(await confirm({
+ !(await ConfirmDialog.show({
title: "Are you sure?",
message:
"Are you sure you want to permanently delete these attachments? This action is IRREVERSIBLE.",
diff --git a/apps/web/src/common/notices.ts b/apps/web/src/common/notices.ts
index 5f541b12c..d79f70ff1 100644
--- a/apps/web/src/common/notices.ts
+++ b/apps/web/src/common/notices.ts
@@ -23,12 +23,12 @@ import { db } from "./db";
import { store as appStore } from "../stores/app-store";
import { Backup, User, Email, Warn, Icon } from "../components/icons";
import dayjs from "dayjs";
-import { showBuyDialog, showRecoveryKeyDialog } from "./dialog-controller";
import { hardNavigate, hashNavigate } from "../navigation";
-
import { isUserPremium } from "../hooks/use-is-user-premium";
import { showToast } from "../utils/toast";
import { TaskScheduler } from "../utils/task-scheduler";
+import { BuyDialog } from "../dialogs/buy-dialog";
+import { RecoveryKeyDialog } from "../dialogs/recovery-key-dialog";
export type NoticeType = "autoBackupsOff" | "login" | "email" | "recoverykey";
@@ -119,7 +119,7 @@ export const NoticesData: Record<NoticeType, NoticeData> = {
key: "autoBackupsOff",
title: "Automatic backups disabled",
subtitle: "Please upgrade to Pro to enable automatic backups.",
- action: () => showBuyDialog(),
+ action: () => BuyDialog.show({}),
dismissable: true,
icon: Backup
},
@@ -143,7 +143,7 @@ export const NoticesData: Record<NoticeType, NoticeData> = {
subtitle: "Keep your recovery key safe",
dismissable: true,
action: async () => {
- if (await verifyAccount()) await showRecoveryKeyDialog();
+ if (await verifyAccount()) await RecoveryKeyDialog.show({});
},
icon: Warn
}
diff --git a/apps/web/src/common/task-manager.ts b/apps/web/src/common/task-manager.ts
index 9e4b0bac7..87e7627a0 100644
--- a/apps/web/src/common/task-manager.ts
+++ b/apps/web/src/common/task-manager.ts
@@ -17,8 +17,8 @@ You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
+import { ProgressDialog } from "../dialogs/progress-dialog";
import { removeStatus, updateStatus } from "../hooks/use-status";
-import { showProgressDialog } from "./dialog-controller";
type TaskType = "status" | "modal";
type TaskAction<T> = (report: ProgressReportCallback) => T | Promise<T>;
@@ -74,11 +74,11 @@ export class TaskManager {
return result;
}
case "modal": {
- return await showProgressDialog<T | Error>({
+ return (await ProgressDialog.show({
title: task.title,
subtitle: task.subtitle,
action: task.action
- });
+ })) as T;
}
}
}
diff --git a/apps/web/src/common/vault.ts b/apps/web/src/common/vault.ts
index c7ba2811c..ec75a63aa 100644
--- a/apps/web/src/common/vault.ts
+++ b/apps/web/src/common/vault.ts
@@ -18,7 +18,7 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import { db } from "./db";
-import { showPasswordDialog } from "./dialog-controller";
+import { showPasswordDialog } from "../dialogs/password-dialog";
import { showToast } from "../utils/toast";
import { VAULT_ERRORS } from "@notesnook/core/dist/api/vault";
diff --git a/apps/web/src/components/announcements/body.jsx b/apps/web/src/components/announcements/body.jsx
index 80952eae4..600a4c437 100644
--- a/apps/web/src/components/announcements/body.jsx
+++ b/apps/web/src/components/announcements/body.jsx
@@ -24,10 +24,6 @@ import {
Image as RebassImage,
Text as RebassText
} from "@theme-ui/components";
-import {
- closeOpenedDialog,
- showBuyDialog
-} from "../../common/dialog-controller";
import { ANALYTICS_EVENTS, trackEvent } from "../../utils/analytics";
import {
Sync,
@@ -43,6 +39,8 @@ import { store as appStore } from "../../stores/app-store";
import { createBackup } from "../../common";
import { allowedPlatforms } from "../../stores/announcement-store";
import { alpha } from "@theme-ui/color";
+import { BuyDialog } from "../../dialogs/buy-dialog/buy-dialog";
+import { DialogManager } from "../../common/dialog-manager";
var margins = [0, 2];
var HORIZONTAL_MARGIN = 3;
@@ -285,7 +283,7 @@ function CalltoAction({ action, variant, sx, dismissAnnouncement }) {
sx={sx}
onClick={async () => {
if (dismissAnnouncement) dismissAnnouncement();
- closeOpenedDialog();
+ DialogManager.closeAll();
trackEvent(ANALYTICS_EVENTS.announcementCta, action);
switch (action.type) {
case "link": {
@@ -299,7 +297,7 @@ function CalltoAction({ action, variant, sx, dismissAnnouncement }) {
}
case "promo": {
const [coupon, plan] = action.data.split(":");
- await showBuyDialog(plan, coupon);
+ await BuyDialog.show({ plan, coupon });
break;
}
case "force-sync": {
diff --git a/apps/web/src/components/attachment/index.tsx b/apps/web/src/components/attachment/index.tsx
index 649709812..676299d7d 100644
--- a/apps/web/src/components/attachment/index.tsx
+++ b/apps/web/src/components/attachment/index.tsx
@@ -38,10 +38,6 @@ import {
Reupload,
Uploading
} from "../icons";
-import {
- closeOpenedDialog,
- showPromptDialog
-} from "../../common/dialog-controller";
import { store, useStore } from "../../stores/attachment-store";
import { db } from "../../common/db";
import { saveAttachment } from "../../common/attachments";
@@ -59,6 +55,8 @@ import { getFormattedDate } from "@notesnook/common";
import { MenuItem } from "@notesnook/ui";
import { Attachment as AttachmentType } from "@notesnook/core";
import { useEditorStore } from "../../stores/editor-store";
+import { PromptDialog } from "../../dialogs/prompt";
+import { DialogManager } from "../../common/dialog-manager";
const FILE_ICONS: Record<string, Icon> = {
"image/": FileImage,
@@ -259,7 +257,7 @@ const AttachmentMenuItems: (
title: note.title,
onClick: () => {
useEditorStore.getState().openSession(note.id);
- closeOpenedDialog();
+ DialogManager.closeAll();
}
});
}
@@ -291,7 +289,7 @@ const AttachmentMenuItems: (
title: "Rename",
icon: Rename.path,
onClick: async () => {
- const newName = await showPromptDialog({
+ const newName = await PromptDialog.show({
title: "Rename attachment",
description: attachment.filename,
defaultValue: attachment.filename
diff --git a/apps/web/src/components/editor/index.tsx b/apps/web/src/components/editor/index.tsx
index c89ca59a6..1bb12ca71 100644
--- a/apps/web/src/components/editor/index.tsx
+++ b/apps/web/src/components/editor/index.tsx
@@ -64,12 +64,12 @@ import { Freeze } from "react-freeze";
import { UnlockView } from "../unlock";
import DiffViewer from "../diff-viewer";
import TableOfContents from "./table-of-contents";
-import { showNoteLinkingDialog } from "../../common/dialog-controller";
import { scrollIntoViewById } from "@notesnook/editor";
import { IEditor } from "./types";
import { EditorActionBar } from "./action-bar";
import { logger } from "../../utils/logger";
import { PanelGroup, Panel, PanelResizeHandle } from "react-resizable-panels";
+import { NoteLinkingDialog } from "../../dialogs/note-linking-dialog";
const PDFPreview = React.lazy(() => import("../pdf-preview"));
@@ -545,8 +545,8 @@ export function Editor(props: EditorProps) {
result.forEach((attachment) => editor?.attachFile(attachment));
}}
onInsertInternalLink={async (attributes) => {
- const link = await showNoteLinkingDialog(attributes);
- return link;
+ const link = await NoteLinkingDialog.show({ attributes });
+ return link || undefined;
}}
>
{headless ? null : (
diff --git a/apps/web/src/components/editor/picker.ts b/apps/web/src/components/editor/picker.ts
index 51bfd2ddc..ada538d60 100644
--- a/apps/web/src/components/editor/picker.ts
+++ b/apps/web/src/components/editor/picker.ts
@@ -20,22 +20,20 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.
import { SerializedKey } from "@notesnook/crypto/dist/src/types";
import { AppEventManager, AppEvents } from "../../common/app-events";
import { db } from "../../common/db";
-import {
- showBuyDialog,
- showImagePickerDialog
-} from "../../common/dialog-controller";
import { TaskManager } from "../../common/task-manager";
import { isUserPremium } from "../../hooks/use-is-user-premium";
import { showToast } from "../../utils/toast";
import { showFilePicker } from "../../utils/file-picker";
import { Attachment } from "@notesnook/editor";
+import { ImagePickerDialog } from "../../dialogs/image-picker-dialog";
+import { BuyDialog } from "../../dialogs/buy-dialog";
const FILE_SIZE_LIMIT = 500 * 1024 * 1024;
const IMAGE_SIZE_LIMIT = 50 * 1024 * 1024;
export async function insertAttachments(type = "*/*") {
if (!isUserPremium()) {
- await showBuyDialog();
+ await BuyDialog.show({});
return;
}
@@ -49,14 +47,14 @@ export async function insertAttachments(type = "*/*") {
export async function attachFiles(files: File[]) {
if (!isUserPremium()) {
- await showBuyDialog();
+ await BuyDialog.show({});
return;
}
const images =
- (await showImagePickerDialog(
- files.filter((f) => f.type.startsWith("image/"))
- )) || [];
+ (await ImagePickerDialog.show({
+ images: files.filter((f) => f.type.startsWith("image/"))
+ })) || [];
const documents = files.filter((f) => !f.type.startsWith("image/"));
const attachments: Attachment[] = [];
for (const file of [...images, ...documents]) {
diff --git a/apps/web/src/components/editor/tiptap.tsx b/apps/web/src/components/editor/tiptap.tsx
index 0efdbccee..d25526e4d 100644
--- a/apps/web/src/components/editor/tiptap.tsx
+++ b/apps/web/src/components/editor/tiptap.tsx
@@ -48,7 +48,6 @@ import {
import { IEditor, MAX_AUTO_SAVEABLE_WORDS } from "./types";
import { useEditorConfig, useToolbarConfig, useEditorManager } from "./manager";
import { useIsUserPremium } from "../../hooks/use-is-user-premium";
-import { showBuyDialog } from "../../common/dialog-controller";
import { useStore as useSettingsStore } from "../../stores/setting-store";
import { debounce } from "@notesnook/common";
import { ScopedThemeProvider } from "../theme-provider";
@@ -62,6 +61,7 @@ import Skeleton from "react-loading-skeleton";
import useMobile from "../../hooks/use-mobile";
import useTablet from "../../hooks/use-tablet";
import { TimeFormat } from "@notesnook/core/dist/utils/date";
+import { BuyDialog } from "../../dialogs/buy-dialog";
export type OnChangeHandler = (
content: () => string,
@@ -155,7 +155,7 @@ function TipTap(props: TipTapProps) {
premium: isUserPremium
},
onPermissionDenied: (claim) => {
- if (claim === "premium") showBuyDialog();
+ if (claim === "premium") BuyDialog.show({});
}
});
diff --git a/apps/web/src/components/navigation-menu/index.tsx b/apps/web/src/components/navigation-menu/index.tsx
index b9630f40f..c75aab33d 100644
--- a/apps/web/src/components/navigation-menu/index.tsx
+++ b/apps/web/src/components/navigation-menu/index.tsx
@@ -43,7 +43,6 @@ import NavigationItem, { SortableNavigationItem } from "./navigation-item";
import { hardNavigate, hashNavigate, navigate } from "../../navigation";
import { db } from "../../common/db";
import useMobile from "../../hooks/use-mobile";
-import { showRenameColorDialog } from "../../common/dialog-controller";
import { useStore as useAppStore } from "../../stores/app-store";
import { useStore as useUserStore } from "../../stores/user-store";
import { useStore as useThemeStore } from "../../stores/theme-store";
@@ -72,6 +71,7 @@ import { MenuItem } from "@notesnook/ui";
import { Notebook, Tag } from "@notesnook/core";
import { handleDrop } from "../../common/drop-handler";
import { Menu } from "../../hooks/use-menu";
+import { RenameColorDialog } from "../../dialogs/item-dialog";
type Route = {
id: string;
@@ -368,7 +368,7 @@ function NavigationMenu(props: NavigationMenuProps) {
type: "button",
key: "rename-color",
title: "Rename color",
- onClick: () => showRenameColorDialog(color)
+ onClick: () => RenameColorDialog.show(color)
},
{
type: "button",
diff --git a/apps/web/src/components/note/index.tsx b/apps/web/src/components/note/index.tsx
index 4b431fbbe..0e752e9c6 100644
--- a/apps/web/src/components/note/index.tsx
+++ b/apps/web/src/components/note/index.tsx
@@ -54,13 +54,6 @@ import {
} from "../icons";
import TimeAgo from "../time-ago";
import ListItem from "../list-item";
-import {
- confirm,
- showAddReminderDialog,
- showAddTagsDialog,
- showCreateColorDialog,
- showMoveNoteDialog
-} from "../../common/dialog-controller";
import { store } from "../../stores/note-store";
import { store as userstore } from "../../stores/user-store";
import { useEditorStore } from "../../stores/editor-store";
@@ -97,12 +90,16 @@ import { SchemeColors } from "@notesnook/theme";
import { writeToClipboard } from "../../utils/clipboard";
import Vault from "../../common/vault";
import { isUserPremium } from "../../hooks/use-is-user-premium";
+import { AddTagsDialog } from "../../dialogs/add-tags-dialog";
+import { CreateColorDialog } from "../../dialogs/create-color-dialog";
+import { ConfirmDialog } from "../../dialogs/confirm";
+import { MoveNoteDialog } from "../../dialogs/move-note-dialog";
+import { AddReminderDialog } from "../../dialogs/add-reminder-dialog";
type NoteProps = NoteResolvedData & {
item: NoteType;
context?: Context;
date: number;
- simplified?: boolean;
compact?: boolean;
};
@@ -116,7 +113,6 @@ function Note(props: NoteProps) {
item,
date,
reminder,
- simplified,
compact,
context
} = props;
@@ -130,7 +126,6 @@ function Note(props: NoteProps) {
draggable={true}
isFocused={isOpened}
isCompact={compact}
- isSimple={simplified}
item={note}
title={note.title}
body={note.headline as string}
@@ -391,7 +386,7 @@ const menuItems: (
title: "Remind me",
icon: AddReminder.path,
onClick: async () => {
- await showAddReminderDialog(note.id);
+ await AddReminderDialog.show({ note });
}
},
{ key: "sep1", type: "separator" },
@@ -541,7 +536,7 @@ const menuItems: (
onClick: async () => {
if (
note.localOnly ||
- (await confirm({
+ (await ConfirmDialog.show({
title: `Prevent ${pluralize(ids.length, "note")} from syncing?`,
message: `${pluralize(
ids.length,
@@ -580,7 +575,7 @@ function colorsToMenuItems(
title: "Add new color",
icon: Plus.path,
onClick: async () => {
- const id = await showCreateColorDialog();
+ const id = await CreateColorDialog.show({});
if (!id) return;
await store.get().setColor(id, noteColor?.id === id, ...ids);
}
@@ -620,7 +615,7 @@ function notebooksMenuItems(ids: string[]): MenuItem[] {
key: "link-notebooks",
title: "Link to...",
icon: AddToNotebook.path,
- onClick: () => showMoveNoteDialog(ids)
+ onClick: () => MoveNoteDialog.show({ noteIds: ids })
},
{
type: "lazy-loader",
@@ -700,7 +695,7 @@ function tagsMenuItems(ids: string[]): MenuItem[] {
key: "assign-tags",
title: "Assign to...",
icon: Plus.path,
- onClick: () => showAddTagsDialog(ids)
+ onClick: () => AddTagsDialog.show({ noteIds: ids })
},
{
type: "lazy-loader",
@@ -732,7 +727,6 @@ function tagsMenuItems(ids: string[]): MenuItem[] {
await db.relations.to({ id, type: "note" }, "tag").unlink();
}
tagStore.get().refresh();
- await useEditorStore.getState().refreshTags();
await store.get().refresh();
}
},
@@ -753,7 +747,6 @@ function tagsMenuItems(ids: string[]): MenuItem[] {
await db.relations.add(tag, { id, type: "note" });
}
await tagStore.get().refresh();
- await useEditorStore.getState().refreshTags();
await store.get().refresh();
}
});
@@ -774,7 +767,6 @@ function tagsMenuItems(ids: string[]): MenuItem[] {
await db.relations.unlink(tag, { id, type: "note" });
}
await tagStore.get().refresh();
- await useEditorStore.getState().refreshTags();
await store.get().refresh();
}
});
diff --git a/apps/web/src/components/notebook/index.tsx b/apps/web/src/components/notebook/index.tsx
index 63d761ae3..c547a4fa4 100644
--- a/apps/web/src/components/notebook/index.tsx
+++ b/apps/web/src/components/notebook/index.tsx
@@ -38,12 +38,12 @@ import { hashNavigate, navigate } from "../../navigation";
import IconTag from "../icon-tag";
import { Multiselect } from "../../common/multi-select";
import { pluralize } from "@notesnook/common";
-import { confirm } from "../../common/dialog-controller";
import { getFormattedDate } from "@notesnook/common";
import { MenuItem } from "@notesnook/ui";
import { Notebook as NotebookType } from "@notesnook/core";
import { handleDrop } from "../../common/drop-handler";
import { useDragHandler } from "../../hooks/use-drag-handler";
+import { ConfirmDialog } from "../../dialogs/confirm";
type NotebookProps = {
item: NotebookType;
@@ -202,7 +202,7 @@ export const notebookMenuItems: (
variant: "dangerous",
icon: Trash.path,
onClick: async () => {
- const result = await confirm({
+ const result = await ConfirmDialog.show({
title: `Delete ${pluralize(ids.length, "notebook")}?`,
positiveButtonText: `Yes`,
negativeButtonText: "No",
diff --git a/apps/web/src/components/reminder/index.tsx b/apps/web/src/components/reminder/index.tsx
index 256f4db0f..9681fccc0 100644
--- a/apps/web/src/components/reminder/index.tsx
+++ b/apps/web/src/components/reminder/index.tsx
@@ -37,14 +37,12 @@ import { hashNavigate } from "../../navigation";
import { Multiselect } from "../../common/multi-select";
import { store } from "../../stores/reminder-store";
import { db } from "../../common/db";
-import {
- confirm,
- showEditReminderDialog
-} from "../../common/dialog-controller";
import { pluralize } from "@notesnook/common";
import { getFormattedReminderTime } from "@notesnook/common";
import { MenuItem } from "@notesnook/ui";
import { Reminder as ReminderType } from "@notesnook/core/dist/types";
+import { ConfirmDialog } from "../../dialogs/confirm";
+import { EditReminderDialog } from "../../dialogs/add-reminder-dialog";
const RECURRING_MODE_MAP = {
week: "Weekly",
@@ -75,7 +73,7 @@ function Reminder(props: ReminderProps) {
body={reminder.description}
isDisabled={reminder.disabled}
isCompact={compact}
- onClick={() => showEditReminderDialog(reminder.id)}
+ onClick={() => EditReminderDialog.show({ reminderId: reminder.id })}
footer={
<Flex
sx={{
@@ -145,7 +143,7 @@ const menuItems: (reminder: ReminderType, items?: string[]) => MenuItem[] = (
variant: "dangerous",
icon: Trash.path,
onClick: async () => {
- confirm({
+ ConfirmDialog.show({
title: `Delete ${pluralize(items.length, "reminder")}`,
message: `Are you sure you want to proceed? **This action is IRREVERSIBLE**.`,
positiveButtonText: "Yes",
diff --git a/apps/web/src/components/status-bar/index.tsx b/apps/web/src/components/status-bar/index.tsx
index 1cb7146df..b9f8aea03 100644
--- a/apps/web/src/components/status-bar/index.tsx
+++ b/apps/web/src/components/status-bar/index.tsx
@@ -34,15 +34,13 @@ import { useStore as useUserStore } from "../../stores/user-store";
import { useStore as useAppStore } from "../../stores/app-store";
import { hardNavigate, hashNavigate } from "../../navigation";
import { useAutoUpdater, UpdateStatus } from "../../hooks/use-auto-updater";
-import {
- showIssueDialog,
- showUpdateAvailableNotice
-} from "../../common/dialog-controller";
import useStatus, { statusToString } from "../../hooks/use-status";
import { ScopedThemeProvider } from "../theme-provider";
import { checkForUpdate, installUpdate } from "../../utils/updater";
import { getTimeAgo, toTitleCase } from "@notesnook/common";
import { User } from "@notesnook/core";
+import { showUpdateAvailableNotice } from "../../dialogs/confirm";
+import { IssueDialog } from "../../dialogs/issue-dialog";
function StatusBar() {
const user = useUserStore((state) => state.user);
@@ -114,7 +112,7 @@ function StatusBar() {
) : null}
<Button
variant="statusitem"
- onClick={() => showIssueDialog()}
+ onClick={() => IssueDialog.show({})}
sx={{
alignItems: "center",
justifyContent: "center",
diff --git a/apps/web/src/components/sub-notebook/index.tsx b/apps/web/src/components/sub-notebook/index.tsx
index 4b58e1709..560517709 100644
--- a/apps/web/src/components/sub-notebook/index.tsx
+++ b/apps/web/src/components/sub-notebook/index.tsx
@@ -24,11 +24,11 @@ import { Notebook } from "@notesnook/core";
import { notebookMenuItems } from "../notebook";
import { ChevronDown, ChevronRight, Plus } from "../icons";
import { MenuItem } from "@notesnook/ui";
-import { showAddNotebookDialog } from "../../common/dialog-controller";
import { navigate } from "../../navigation";
import { useCallback, useRef } from "react";
import { handleDrop } from "../../common/drop-handler";
import { useDragHandler } from "../../hooks/use-drag-handler";
+import { AddNotebookDialog } from "../../dialogs/add-notebook-dialog";
type SubNotebookProps = {
item: Notebook;
@@ -173,7 +173,6 @@ const subNotebookMenuItems: (
context?: { refresh?: () => void }
) => MenuItem[] = (notebook, ids = [], context) => {
const menuItems = notebookMenuItems(notebook, ids);
- console.log("ITEMS", context);
return [
{
type: "button",
@@ -181,7 +180,9 @@ const subNotebookMenuItems: (
title: "New notebook",
icon: Plus.path,
onClick: () =>
- showAddNotebookDialog(notebook.id).then(() => context?.refresh?.())
+ AddNotebookDialog.show({ parentId: notebook.id }).then((res) =>
+ res ? context?.refresh?.() : null
+ )
},
{ type: "separator", key: "sepep2" },
...menuItems
diff --git a/apps/web/src/components/tag/index.tsx b/apps/web/src/components/tag/index.tsx
index a00395b31..6607e0837 100644
--- a/apps/web/src/components/tag/index.tsx
+++ b/apps/web/src/components/tag/index.tsx
@@ -23,15 +23,14 @@ import { Text } from "@theme-ui/components";
import { store as appStore } from "../../stores/app-store";
import { store as tagStore } from "../../stores/tag-store";
import { store as noteStore } from "../../stores/note-store";
-import { useEditorStore } from "../../stores/editor-store";
import { db } from "../../common/db";
import { Edit, Shortcut, DeleteForver } from "../icons";
import { showToast } from "../../utils/toast";
import { pluralize } from "@notesnook/common";
import { MenuItem } from "@notesnook/ui";
import { Tag as TagType } from "@notesnook/core";
-import { showEditTagDialog } from "../../common/dialog-controller";
import { handleDrop } from "../../common/drop-handler";
+import { EditTagDialog } from "../../dialogs/item-dialog";
type TagProps = { item: TagType; totalNotes: number };
function Tag(props: TagProps) {
@@ -78,9 +77,7 @@ const menuItems: (tag: TagType, ids?: string[]) => MenuItem[] = (
key: "edit",
title: "Rename tag",
icon: Edit.path,
- onClick: () => {
- showEditTagDialog(tag);
- }
+ onClick: () => EditTagDialog.show(tag)
},
{
type: "button",
diff --git a/apps/web/src/components/toggle/index.jsx b/apps/web/src/components/toggle/index.jsx
index 29e91da7f..d82f64a82 100644
--- a/apps/web/src/components/toggle/index.jsx
+++ b/apps/web/src/components/toggle/index.jsx
@@ -18,11 +18,11 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import { useCallback, useState } from "react";
-import { showBuyDialog } from "../../common/dialog-controller";
import Tip from "../tip";
import { isUserPremium } from "../../hooks/use-is-user-premium";
import { Flex, Switch } from "@theme-ui/components";
import { Loading } from "../icons";
+import { BuyDialog } from "../../dialogs/buy-dialog/buy-dialog";
function Toggle(props) {
const {
@@ -46,7 +46,7 @@ function Toggle(props) {
setIsLoading(false);
}
} else {
- await showBuyDialog();
+ await BuyDialog.show({});
}
}, [onToggled, premium, isToggled]);
diff --git a/apps/web/src/components/trash-item/index.tsx b/apps/web/src/components/trash-item/index.tsx
index 813d45bfc..eed80a193 100644
--- a/apps/web/src/components/trash-item/index.tsx
+++ b/apps/web/src/components/trash-item/index.tsx
@@ -18,7 +18,6 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import ListItem from "../list-item";
-import { showMultiPermanentDeleteConfirmation } from "../../common/dialog-controller";
import { Restore, DeleteForver } from "../icons";
import { store } from "../../stores/trash-store";
import { Flex, Text } from "@theme-ui/components";
@@ -28,6 +27,7 @@ import { showToast } from "../../utils/toast";
import { MenuItem } from "@notesnook/ui";
import { TrashItem as TrashItemType } from "@notesnook/core/dist/types";
import { useEditorStore } from "../../stores/editor-store";
+import { showMultiPermanentDeleteConfirmation } from "../../dialogs/confirm";
type TrashItemProps = { item: TrashItemType; date: number };
function TrashItem(props: TrashItemProps) {
diff --git a/apps/web/src/dialogs/add-notebook-dialog.tsx b/apps/web/src/dialogs/add-notebook-dialog.tsx
index ec8067aee..54996d79e 100644
--- a/apps/web/src/dialogs/add-notebook-dialog.tsx
+++ b/apps/web/src/dialogs/add-notebook-dialog.tsx
@@ -22,96 +22,104 @@ import Dialog from "../components/dialog";
import Field from "../components/field";
import { showToast } from "../utils/toast";
import { Notebook } from "@notesnook/core";
-import { Perform } from "../common/dialog-controller";
import { store as noteStore } from "../stores/note-store";
import { store as notebookStore } from "../stores/notebook-store";
import { store as appStore } from "../stores/app-store";
import { db } from "../common/db";
+import { BaseDialogProps, DialogManager } from "../common/dialog-manager";
-type AddNotebookDialogProps = {
+type AddNotebookDialogProps = BaseDialogProps<boolean> & {
parentId?: string;
edit?: boolean;
notebook?: Notebook;
- onClose: Perform;
};
-function AddNotebookDialog(props: AddNotebookDialogProps) {
- const { notebook, onClose, parentId } = props;
- const title = useRef<string>(notebook?.title || "");
- const description = useRef<string>(notebook?.description || "");
+export const AddNotebookDialog = DialogManager.register(
+ function AddNotebookDialog(props: AddNotebookDialogProps) {
+ const { notebook, onClose, parentId } = props;
+ const title = useRef<string>(notebook?.title || "");
+ const description = useRef<string>(notebook?.description || "");
- const onSubmit = useCallback(async () => {
- if (!title.current.trim())
- return showToast("error", "Notebook title cannot be empty.");
+ const onSubmit = useCallback(async () => {
+ if (!title.current.trim())
+ return showToast("error", "Notebook title cannot be empty.");
- const id = await db.notebooks.add({
- id: props.notebook?.id,
- title: title.current,
- description: description.current
- });
- if (parentId) {
- await db.relations.add(
- { type: "notebook", id: parentId },
- { type: "notebook", id }
- );
- }
+ const id = await db.notebooks.add({
+ id: props.notebook?.id,
+ title: title.current,
+ description: description.current
+ });
+ if (parentId) {
+ await db.relations.add(
+ { type: "notebook", id: parentId },
+ { type: "notebook", id }
+ );
+ }
- await notebookStore.refresh();
- await noteStore.refresh();
- await appStore.refreshNavItems();
+ await notebookStore.refresh();
+ await noteStore.refresh();
+ await appStore.refreshNavItems();
- showToast(
- "success",
- props.edit
- ? "Notebook edited successfully!"
- : "Notebook created successfully"
- );
- onClose(true);
- }, [props.notebook?.id, props.edit, onClose, parentId]);
- return (
- <Dialog
- testId="add-notebook-dialog"
- isOpen={true}
- title={props.edit ? "Edit Notebook" : "Create a Notebook"}
- description={
+ showToast(
+ "success",
props.edit
- ? `You are editing "${notebook?.title}".`
- : "Notebooks are the best way to organize your notes."
- }
- onClose={() => onClose(false)}
- positiveButton={{
- text: props.edit ? "Save" : "Create",
- onClick: onSubmit
- }}
- negativeButton={{ text: "Cancel", onClick: () => onClose(false) }}
- >
- <Field
- defaultValue={title.current}
- data-test-id="title-input"
- autoFocus
- required
- label="Title"
- name="title"
- id="title"
- onChange={(e) => (title.current = e.target.value)}
- onKeyUp={async (e) => {
- if (e.key === "Enter") {
- await onSubmit();
- }
+ ? "Notebook edited successfully!"
+ : "Notebook created successfully"
+ );
+ onClose(true);
+ }, [props.notebook?.id, props.edit, onClose, parentId]);
+ return (
+ <Dialog
+ testId="add-notebook-dialog"
+ isOpen={true}
+ title={props.edit ? "Edit Notebook" : "Create a Notebook"}
+ description={
+ props.edit
+ ? `You are editing "${notebook?.title}".`
+ : "Notebooks are the best way to organize your notes."
+ }
+ onClose={() => onClose(false)}
+ positiveButton={{
+ text: props.edit ? "Save" : "Create",
+ onClick: onSubmit
}}
- />
- <Field
- data-test-id="description-input"
- label="Description"
- name="description"
- id="description"
- onChange={(e) => (description.current = e.target.value)}
- defaultValue={description.current}
- helpText="Optional"
- sx={{ mt: 1 }}
- />
- </Dialog>
- );
-}
+ negativeButton={{ text: "Cancel", onClick: () => onClose(false) }}
+ >
+ <Field
+ defaultValue={title.current}
+ data-test-id="title-input"
+ autoFocus
+ required
+ label="Title"
+ name="title"
+ id="title"
+ onChange={(e) => (title.current = e.target.value)}
+ onKeyUp={async (e) => {
+ if (e.key === "Enter") {
+ await onSubmit();
+ }
+ }}
+ />
+ <Field
+ data-test-id="description-input"
+ label="Description"
+ name="description"
+ id="description"
+ onChange={(e) => (description.current = e.target.value)}
+ defaultValue={description.current}
+ helpText="Optional"
+ sx={{ mt: 1 }}
+ />
+ </Dialog>
+ );
+ }
+);
-export default AddNotebookDialog;
+type EditNotebookDialogProps = { notebookId: string };
+export const EditNotebookDialog = {
+ show: async (props: EditNotebookDialogProps) => {
+ const notebook = await db.notebooks.notebook(props.notebookId);
+ if (!notebook) return;
+ return AddNotebookDialog.show({ edit: true, notebook });
+ }
+};
diff --git a/apps/web/src/dialogs/add-reminder-dialog.tsx b/apps/web/src/dialogs/add-reminder-dialog.tsx
index 48cc23943..c4071c0e9 100644
--- a/apps/web/src/dialogs/add-reminder-dialog.tsx
+++ b/apps/web/src/dialogs/add-reminder-dialog.tsx
@@ -17,7 +17,6 @@ You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
-import { Perform } from "../common/dialog-controller";
import Dialog from "../components/dialog";
import Field from "../components/field";
import { Box, Button, Flex, Label, Radio, Text } from "@theme-ui/components";
@@ -37,11 +36,11 @@ import { useStore as useThemeStore } from "../stores/theme-store";
import { getFormattedDate } from "@notesnook/common";
import { MONTHS_FULL, getTimeFormat } from "@notesnook/core/dist/utils/date";
import { Note, Reminder } from "@notesnook/core";
+import { BaseDialogProps, DialogManager } from "../common/dialog-manager";
dayjs.extend(customParseFormat);
-export type AddReminderDialogProps = {
- onClose: Perform;
+export type AddReminderDialogProps = BaseDialogProps<boolean> & {
reminder?: Reminder;
note?: Note;
};
@@ -116,419 +115,425 @@ const recurringModes = [
}
];
-export default function AddReminderDialog(props: AddReminderDialogProps) {
- const { reminder, note } = props;
+export const AddReminderDialog = DialogManager.register(
+ function AddReminderDialog(props: AddReminderDialogProps) {
+ const { reminder, note } = props;
- const [selectedDays, setSelectedDays] = useState<number[]>(
- reminder?.selectedDays ?? []
- );
- const [recurringMode, setRecurringMode] = useState<
- ValueOf<typeof RecurringModes>
- >(reminder?.recurringMode ?? RecurringModes.DAY);
- const [mode, setMode] = useState<ValueOf<typeof Modes>>(
- reminder?.mode ?? Modes.ONCE
- );
- const [priority, setPriority] = usePersistentState<
- ValueOf<typeof Priorities>
- >("reminders:default_priority", reminder?.priority ?? Priorities.VIBRATE);
- const [date, setDate] = useState(dayjs(reminder?.date));
- const [title, setTitle] = useState<string>(
- note?.title ?? reminder?.title ?? ""
- );
- const [description, setDescription] = useState<string>(
- note?.headline ?? reminder?.description ?? ""
- );
- const [showCalendar, setShowCalendar] = useState(false);
- const refresh = useStore((state) => state.refresh);
- const isUserPremium = useIsUserPremium();
- const theme = useThemeStore((store) => store.colorScheme);
- const dateInputRef = useRef<HTMLInputElement>(null);
+ const [selectedDays, setSelectedDays] = useState<number[]>(
+ reminder?.selectedDays ?? []
+ );
+ const [recurringMode, setRecurringMode] = useState<
+ ValueOf<typeof RecurringModes>
+ >(reminder?.recurringMode ?? RecurringModes.DAY);
+ const [mode, setMode] = useState<ValueOf<typeof Modes>>(
+ reminder?.mode ?? Modes.ONCE
+ );
+ const [priority, setPriority] = usePersistentState<
+ ValueOf<typeof Priorities>
+ >("reminders:default_priority", reminder?.priority ?? Priorities.VIBRATE);
+ const [date, setDate] = useState(dayjs(reminder?.date));
+ const [title, setTitle] = useState<string>(
+ note?.title ?? reminder?.title ?? ""
+ );
+ const [description, setDescription] = useState<string>(
+ note?.headline ?? reminder?.description ?? ""
+ );
+ const [showCalendar, setShowCalendar] = useState(false);
+ const refresh = useStore((state) => state.refresh);
+ const isUserPremium = useIsUserPremium();
+ const theme = useThemeStore((store) => store.colorScheme);
+ const dateInputRef = useRef<HTMLInputElement>(null);
- const repeatsDaily =
- (selectedDays.length === 7 && recurringMode === RecurringModes.WEEK) ||
- (selectedDays.length === 31 && recurringMode === RecurringModes.MONTH) ||
- recurringMode === RecurringModes.DAY;
+ const repeatsDaily =
+ (selectedDays.length === 7 && recurringMode === RecurringModes.WEEK) ||
+ (selectedDays.length === 31 && recurringMode === RecurringModes.MONTH) ||
+ recurringMode === RecurringModes.DAY;
- return (
- <Dialog
- isOpen={true}
- title={reminder ? "Edit reminder" : "Add a reminder"}
- testId="add-reminder-dialog"
- onClose={() => props.onClose(false)}
- sx={{ fontFamily: "body" }}
- positiveButton={{
- text: reminder ? "Save" : "Add",
- disabled:
- !title ||
- (mode !== Modes.ONCE &&
- recurringMode !== RecurringModes.DAY &&
- recurringMode !== RecurringModes.YEAR &&
- !selectedDays.length),
- onClick: async () => {
- if (!("Notification" in window))
- showToast(
- "warn",
- "Reminders will not be active on this device as it does not support notifications."
- );
+ return (
+ <Dialog
+ isOpen={true}
+ title={reminder ? "Edit reminder" : "Add a reminder"}
+ testId="add-reminder-dialog"
+ onClose={() => props.onClose(false)}
+ sx={{ fontFamily: "body" }}
+ positiveButton={{
+ text: reminder ? "Save" : "Add",
+ disabled:
+ !title ||
+ (mode !== Modes.ONCE &&
+ recurringMode !== RecurringModes.DAY &&
+ recurringMode !== RecurringModes.YEAR &&
+ !selectedDays.length),
+ onClick: async () => {
+ if (!("Notification" in window))
+ showToast(
+ "warn",
+ "Reminders will not be active on this device as it does not support notifications."
+ );
- const permissionResult = await Notification.requestPermission();
- if (!IS_TESTING && permissionResult !== "granted") {
- showToast(
- "error",
- "Please grant notifications permission to add new reminders."
- );
- return;
- }
+ const permissionResult = await Notification.requestPermission();
+ if (!IS_TESTING && permissionResult !== "granted") {
+ showToast(
+ "error",
+ "Please grant notifications permission to add new reminders."
+ );
+ return;
+ }
- if (mode !== Modes.REPEAT && date.isBefore(dayjs())) {
- showToast(
- "error",
- "Reminder time cannot be earlier than the current time."
- );
- return;
- }
+ if (mode !== Modes.REPEAT && date.isBefore(dayjs())) {
+ showToast(
+ "error",
+ "Reminder time cannot be earlier than the current time."
+ );
+ return;
+ }
- const id = await db.reminders.add({
- id: reminder?.id,
- recurringMode,
- mode,
- priority,
- selectedDays,
- date: date.valueOf(),
- title,
- description,
- disabled: false,
- ...(date.isAfter(dayjs()) ? { snoozeUntil: 0 } : {})
- });
+ const id = await db.reminders.add({
+ id: reminder?.id,
+ recurringMode,
+ mode,
+ priority,
+ selectedDays,
+ date: date.valueOf(),
+ title,
+ description,
+ disabled: false,
+ ...(date.isAfter(dayjs()) ? { snoozeUntil: 0 } : {})
+ });
- if (id && note) {
- await db.relations.add(note, { id, type: "reminder" });
- }
+ if (id && note) {
+ await db.relations.add(note, { id, type: "reminder" });
+ }
- refresh();
- props.onClose(true);
- }
- }}
- negativeButton={{ text: "Cancel", onClick: () => props.onClose(false) }}
- >
- <Field
- id="title"
- label="Title"
- required
- value={title}
- data-test-id="title-input"
- onChange={(e: React.ChangeEvent<HTMLInputElement>) =>
- setTitle(e.target.value)
- }
- />
- <Field
- as="textarea"
- id="description"
- label="Description"
- data-test-id="description-input"
- helpText="Optional"
- value={description}
- styles={{
- input: {
- height: 100
+ refresh();
+ props.onClose(true);
}
}}
- onChange={(e: React.ChangeEvent<HTMLInputElement>) =>
- setDescription(e.target.value)
- }
- />
- <Flex sx={{ gap: 2, mt: 2 }}>
- {modes.map((m) => (
- <Label
- key={m.id}
- variant="text.body"
- data-test-id={`mode-${m.id}`}
- sx={{
- width: "auto",
- justifyContent: "center",
- alignItems: "center"
- }}
- >
- <Radio
- id="mode"
- name="mode"
- defaultChecked={m.id === Modes.ONCE}
- checked={m.id === mode}
- disabled={m.premium && !isUserPremium}
- sx={{ color: m.id === mode ? "accent" : "icon" }}
- onChange={() => {
- if (m.premium && !isUserPremium) return;
- setMode(m.id);
- setRecurringMode(RecurringModes.DAY);
- setSelectedDays([]);
- }}
- />
- {m.title}
- {m.premium && !isUserPremium && (
- <Pro size={18} color="accent" sx={{ ml: 1 }} />
- )}
- </Label>
- ))}
- </Flex>
- {mode === Modes.REPEAT ? (
- <Flex
- sx={{
- mt: 2,
- bg: "var(--background-secondary)",
- borderRadius: "default",
- p: 1,
- flexDirection: "column"
+ negativeButton={{ text: "Cancel", onClick: () => props.onClose(false) }}
+ >
+ <Field
+ id="title"
+ label="Title"
+ required
+ value={title}
+ data-test-id="title-input"
+ onChange={(e: React.ChangeEvent<HTMLInputElement>) =>
+ setTitle(e.target.value)
+ }
+ />
+ <Field
+ as="textarea"
+ id="description"
+ label="Description"
+ data-test-id="description-input"
+ helpText="Optional"
+ value={description}
+ styles={{
+ input: {
+ height: 100
+ }
}}
- >
- <Flex sx={{ alignItems: "center", gap: 1 }}>
- {recurringModes.map((mode) => (
- <Button
- key={mode.id}
- variant="secondary"
- data-test-id={`recurring-mode-${mode.id}`}
- onClick={() => {
- setRecurringMode(mode.id);
+ onChange={(e: React.ChangeEvent<HTMLInputElement>) =>
+ setDescription(e.target.value)
+ }
+ />
+ <Flex sx={{ gap: 2, mt: 2 }}>
+ {modes.map((m) => (
+ <Label
+ key={m.id}
+ variant="text.body"
+ data-test-id={`mode-${m.id}`}
+ sx={{
+ width: "auto",
+ justifyContent: "center",
+ alignItems: "center"
+ }}
+ >
+ <Radio
+ id="mode"
+ name="mode"
+ defaultChecked={m.id === Modes.ONCE}
+ checked={m.id === mode}
+ disabled={m.premium && !isUserPremium}
+ sx={{ color: m.id === mode ? "accent" : "icon" }}
+ onChange={() => {
+ if (m.premium && !isUserPremium) return;
+ setMode(m.id);
+ setRecurringMode(RecurringModes.DAY);
setSelectedDays([]);
}}
- sx={{
- borderRadius: 100,
- py: 1,
- px: 2,
- flexShrink: 0,
- bg:
- mode.id === recurringMode
- ? "background-selected"
- : "transparent",
- color:
- mode.id === recurringMode
- ? "paragraph-selected"
- : "paragraph"
- }}
- >
- {mode.title}
- </Button>
- ))}
- </Flex>
- {recurringModes.map((mode) =>
- mode.id === recurringMode ? (
- <Box
- key={mode.id}
- sx={{
- display: "grid",
- gridTemplateColumns:
- mode.id === RecurringModes.WEEK
- ? "1fr 1fr 1fr 1fr 1fr 1fr 1fr"
- : "1fr 1fr 1fr 1fr 1fr 1fr 1fr",
- mt: mode.options.length > 0 ? 1 : 0,
- maxHeight: 150,
- overflowY: "auto",
- gap: 1
- }}
- >
- {mode.options.map((day, i) => (
- <Button
- key={day}
- variant="secondary"
- data-test-id={`day-${day}`}
- onClick={() => {
- setSelectedDays((days) => {
- const clone = days.slice();
- if (clone.indexOf(day) > -1)
- clone.splice(clone.indexOf(day), 1);
- else clone.push(day);
- return clone;
- });
- }}
- sx={{
- borderRadius: "default",
- py: 1,
- px: 2,
- flexShrink: 0,
- textAlign: "left",
- bg: selectedDays.includes(day)
+ />
+ {m.title}
+ {m.premium && !isUserPremium && (
+ <Pro size={18} color="accent" sx={{ ml: 1 }} />
+ )}
+ </Label>
+ ))}
+ </Flex>
+ {mode === Modes.REPEAT ? (
+ <Flex
+ sx={{
+ mt: 2,
+ bg: "var(--background-secondary)",
+ borderRadius: "default",
+ p: 1,
+ flexDirection: "column"
+ }}
+ >
+ <Flex sx={{ alignItems: "center", gap: 1 }}>
+ {recurringModes.map((mode) => (
+ <Button
+ key={mode.id}
+ variant="secondary"
+ data-test-id={`recurring-mode-${mode.id}`}
+ onClick={() => {
+ setRecurringMode(mode.id);
+ setSelectedDays([]);
+ }}
+ sx={{
+ borderRadius: 100,
+ py: 1,
+ px: 2,
+ flexShrink: 0,
+ bg:
+ mode.id === recurringMode
? "background-selected"
: "transparent",
- color: selectedDays.includes(day)
+ color:
+ mode.id === recurringMode
? "paragraph-selected"
: "paragraph"
- }}
- >
- {mode.id === "week" ? WEEK_DAYS[i] : day}
- </Button>
- ))}
- </Box>
- ) : null
- )}
- </Flex>
- ) : null}
+ }}
+ >
+ {mode.title}
+ </Button>
+ ))}
+ </Flex>
+ {recurringModes.map((mode) =>
+ mode.id === recurringMode ? (
+ <Box
+ key={mode.id}
+ sx={{
+ display: "grid",
+ gridTemplateColumns:
+ mode.id === RecurringModes.WEEK
+ ? "1fr 1fr 1fr 1fr 1fr 1fr 1fr"
+ : "1fr 1fr 1fr 1fr 1fr 1fr 1fr",
+ mt: mode.options.length > 0 ? 1 : 0,
+ maxHeight: 150,
+ overflowY: "auto",
+ gap: 1
+ }}
+ >
+ {mode.options.map((day, i) => (
+ <Button
+ key={day}
+ variant="secondary"
+ data-test-id={`day-${day}`}
+ onClick={() => {
+ setSelectedDays((days) => {
+ const clone = days.slice();
+ if (clone.indexOf(day) > -1)
+ clone.splice(clone.indexOf(day), 1);
+ else clone.push(day);
+ return clone;
+ });
+ }}
+ sx={{
+ borderRadius: "default",
+ py: 1,
+ px: 2,
+ flexShrink: 0,
+ textAlign: "left",
+ bg: selectedDays.includes(day)
+ ? "background-selected"
+ : "transparent",
+ color: selectedDays.includes(day)
+ ? "paragraph-selected"
+ : "paragraph"
+ }}
+ >
+ {mode.id === "week" ? WEEK_DAYS[i] : day}
+ </Button>
+ ))}
+ </Box>
+ ) : null
+ )}
+ </Flex>
+ ) : null}
- <Flex sx={{ gap: 2, overflowX: "auto", mt: 2 }}>
- {mode === Modes.ONCE ? (
- <>
- <Field
- id="date"
- label="Date"
- required
- inputRef={dateInputRef}
- data-test-id="date-input"
- helpText={`${db.settings.getDateFormat()}`}
- action={{
- icon: Calendar,
- onClick() {
- setShowCalendar(true);
+ <Flex sx={{ gap: 2, overflowX: "auto", mt: 2 }}>
+ {mode === Modes.ONCE ? (
+ <>
+ <Field
+ id="date"
+ label="Date"
+ required
+ inputRef={dateInputRef}
+ data-test-id="date-input"
+ helpText={`${db.settings.getDateFormat()}`}
+ action={{
+ icon: Calendar,
+ onClick() {
+ setShowCalendar(true);
+ }
+ }}
+ validate={(t) =>
+ dayjs(t, db.settings.getDateFormat(), true).isValid()
}
- }}
- validate={(t) =>
- dayjs(t, db.settings.getDateFormat(), true).isValid()
- }
- defaultValue={date.format(db.settings.getDateFormat())}
- onChange={(e) => setDate((d) => setDateOnly(e.target.value, d))}
- />
- <PopupPresenter
- isOpen={showCalendar}
- onClose={() => setShowCalendar(false)}
- position={{
- isTargetAbsolute: true,
- target: dateInputRef.current,
- location: "top"
- }}
- sx={{
- ".rdp": {
- bg: "background",
- p: 1,
- boxShadow: `0px 0px 25px 5px ${
- theme === "dark" ? "#000000aa" : "#0000004e"
- }`,
- borderRadius: "dialog",
- fontFamily: "body",
- "--rdp-accent-color": "var(--accent)",
- "--rdp-background-color": "var(--background)",
- "--rdp-background-color-dark": "var(--background)",
- "--rdp-selected-color": "var(--paragraph-selected)",
- color: "paragraph"
- },
- ".rdp-caption_label": { fontWeight: "heading" }
- }}
- >
- <DayPicker
- mode="single"
- captionLayout="dropdown-buttons"
- fromYear={new Date().getFullYear()}
- toYear={new Date().getFullYear() + 99}
- modifiers={{
- disabled: { before: new Date() }
+ defaultValue={date.format(db.settings.getDateFormat())}
+ onChange={(e) => setDate((d) => setDateOnly(e.target.value, d))}
+ />
+ <PopupPresenter
+ isOpen={showCalendar}
+ onClose={() => setShowCalendar(false)}
+ position={{
+ isTargetAbsolute: true,
+ target: dateInputRef.current,
+ location: "top"
}}
- selected={dayjs(date).toDate()}
- onSelect={(day) => {
- if (!day) return;
- const date = getFormattedDate(day, "date");
- setDate((d) => setDateOnly(date, d));
- if (dateInputRef.current) dateInputRef.current.value = date;
+ sx={{
+ ".rdp": {
+ bg: "background",
+ p: 1,
+ boxShadow: `0px 0px 25px 5px ${
+ theme === "dark" ? "#000000aa" : "#0000004e"
+ }`,
+ borderRadius: "dialog",
+ fontFamily: "body",
+ "--rdp-accent-color": "var(--accent)",
+ "--rdp-background-color": "var(--background)",
+ "--rdp-background-color-dark": "var(--background)",
+ "--rdp-selected-color": "var(--paragraph-selected)",
+ color: "paragraph"
+ },
+ ".rdp-caption_label": { fontWeight: "heading" }
}}
- styles={{
- day: {
- fontFamily: "inherit",
- fontSize: 14
- }
+ >
+ <DayPicker
+ mode="single"
+ captionLayout="dropdown-buttons"
+ fromYear={new Date().getFullYear()}
+ toYear={new Date().getFullYear() + 99}
+ modifiers={{
+ disabled: { before: new Date() }
+ }}
+ selected={dayjs(date).toDate()}
+ onSelect={(day) => {
+ if (!day) return;
+ const date = getFormattedDate(day, "date");
+ setDate((d) => setDateOnly(date, d));
+ if (dateInputRef.current) dateInputRef.current.value = date;
+ }}
+ styles={{
+ day: {
+ fontFamily: "inherit",
+ fontSize: 14
+ }
+ }}
+ />
+ </PopupPresenter>
+ </>
+ ) : recurringMode === RecurringModes.YEAR ? (
+ <>
+ <LabeledSelect
+ id="month"
+ label="Month"
+ value={`${dayjs(date).month()}`}
+ options={MONTHS_FULL.map((month, index) => ({
+ value: `${index}`,
+ title: month
+ }))}
+ onSelectionChanged={(month) => {
+ setDate((d) => d.month(parseInt(month)));
}}
/>
- </PopupPresenter>
- </>
- ) : recurringMode === RecurringModes.YEAR ? (
- <>
- <LabeledSelect
- id="month"
- label="Month"
- value={`${dayjs(date).month()}`}
- options={MONTHS_FULL.map((month, index) => ({
- value: `${index}`,
- title: month
- }))}
- onSelectionChanged={(month) => {
- setDate((d) => d.month(parseInt(month)));
- }}
- />
- <LabeledSelect
- id="day"
- label="Day"
- value={`${dayjs(date).date()}`}
- options={new Array(dayjs(date).daysInMonth())
- .fill("0")
- .map((_, day) => ({
- value: `${day + 1}`,
- title: `${day + 1}`
- }))}
- onSelectionChanged={(day) => {
- setDate((d) => d.date(parseInt(day)));
- }}
- />
- </>
- ) : null}
- <Field
- id="time"
- label="Time"
- required
- data-test-id="time-input"
- helpText={`${
- db.settings.getTimeFormat() === "12-hour" ? "hh:mm AM/PM" : "hh:mm"
- }`}
- validate={(t) => {
- const format =
- db.settings.getTimeFormat() === "12-hour" ? "hh:mm a" : "HH:mm";
- return dayjs(t.toLowerCase(), format, true).isValid();
- }}
- defaultValue={date.format(getTimeFormat(db.settings.getTimeFormat()))}
- onChange={(e) => setDate((d) => setTimeOnly(e.target.value, d))}
- />
- </Flex>
- <Flex sx={{ gap: 2, mt: 2 }}>
- {priorities.map((p) => (
- <Label
- key={p.id}
- variant="text.body"
- data-test-id={`priority-${p.id}`}
- sx={{
- width: "auto",
- justifyContent: "center",
- alignItems: "center"
+ <LabeledSelect
+ id="day"
+ label="Day"
+ value={`${dayjs(date).date()}`}
+ options={new Array(dayjs(date).daysInMonth())
+ .fill("0")
+ .map((_, day) => ({
+ value: `${day + 1}`,
+ title: `${day + 1}`
+ }))}
+ onSelectionChanged={(day) => {
+ setDate((d) => d.date(parseInt(day)));
+ }}
+ />
+ </>
+ ) : null}
+ <Field
+ id="time"
+ label="Time"
+ required
+ data-test-id="time-input"
+ helpText={`${
+ db.settings.getTimeFormat() === "12-hour"
+ ? "hh:mm AM/PM"
+ : "hh:mm"
+ }`}
+ validate={(t) => {
+ const format =
+ db.settings.getTimeFormat() === "12-hour" ? "hh:mm a" : "HH:mm";
+ return dayjs(t.toLowerCase(), format, true).isValid();
}}
- >
- <Radio
- id="priority"
- name="priority"
- sx={{ color: p.id === priority ? "accent" : "icon" }}
- defaultChecked={p.id === Priorities.VIBRATE}
- checked={p.id === priority}
- onChange={() => setPriority(p.id)}
- />
- {p.title}
- </Label>
- ))}
- </Flex>
+ defaultValue={date.format(
+ getTimeFormat(db.settings.getTimeFormat())
+ )}
+ onChange={(e) => setDate((d) => setTimeOnly(e.target.value, d))}
+ />
+ </Flex>
+ <Flex sx={{ gap: 2, mt: 2 }}>
+ {priorities.map((p) => (
+ <Label
+ key={p.id}
+ variant="text.body"
+ data-test-id={`priority-${p.id}`}
+ sx={{
+ width: "auto",
+ justifyContent: "center",
+ alignItems: "center"
+ }}
+ >
+ <Radio
+ id="priority"
+ name="priority"
+ sx={{ color: p.id === priority ? "accent" : "icon" }}
+ defaultChecked={p.id === Priorities.VIBRATE}
+ checked={p.id === priority}
+ onChange={() => setPriority(p.id)}
+ />
+ {p.title}
+ </Label>
+ ))}
+ </Flex>
- {mode === Modes.REPEAT ? (
- <Text variant="subBody" sx={{ mt: 1 }}>
- {selectedDays.length === 0 && recurringMode !== RecurringModes.DAY
- ? recurringMode === RecurringModes.WEEK
- ? "Select day of the week to repeat the reminder."
- : "Select nth day(s) of the month to repeat the reminder."
- : repeatsDaily
- ? `Repeats daily at ${date.format(timeFormat())}.`
- : `Repeats every ${recurringMode} on ${getSelectedDaysText(
- selectedDays,
- recurringMode
- )} at ${date.format(timeFormat())}.`}
- </Text>
- ) : (
- <Text variant="subBody" sx={{ mt: 1 }}>
- {`The reminder will start on ${date} at ${date.format(
- timeFormat()
- )}.`}
- </Text>
- )}
- </Dialog>
- );
-}
+ {mode === Modes.REPEAT ? (
+ <Text variant="subBody" sx={{ mt: 1 }}>
+ {selectedDays.length === 0 && recurringMode !== RecurringModes.DAY
+ ? recurringMode === RecurringModes.WEEK
+ ? "Select day of the week to repeat the reminder."
+ : "Select nth day(s) of the month to repeat the reminder."
+ : repeatsDaily
+ ? `Repeats daily at ${date.format(timeFormat())}.`
+ : `Repeats every ${recurringMode} on ${getSelectedDaysText(
+ selectedDays,
+ recurringMode
+ )} at ${date.format(timeFormat())}.`}
+ </Text>
+ ) : (
+ <Text variant="subBody" sx={{ mt: 1 }}>
+ {`The reminder will start on ${date} at ${date.format(
+ timeFormat()
+ )}.`}
+ </Text>
+ )}
+ </Dialog>
+ );
+ }
+);
function setTimeOnly(str: string, date: dayjs.Dayjs) {
const value = dayjs(str, timeFormat(), true);
@@ -619,3 +624,12 @@ function LabeledSelect(props: LabeledSelectProps) {
</Label>
);
}
+
+type EditReminderDialogProps = { reminderId: string };
+export const EditReminderDialog = {
+ show: async (props: EditReminderDialogProps) => {
+ const reminder = await db.reminders.reminder(props.reminderId);
+ if (!reminder) return;
+ return AddReminderDialog.show({ reminder });
+ }
+};
diff --git a/apps/web/src/dialogs/add-tags-dialog.tsx b/apps/web/src/dialogs/add-tags-dialog.tsx
index df5c9640e..67b371fd8 100644
--- a/apps/web/src/dialogs/add-tags-dialog.tsx
+++ b/apps/web/src/dialogs/add-tags-dialog.tsx
@@ -29,12 +29,12 @@ import Dialog from "../components/dialog";
import { useStore, store } from "../stores/tag-store";
import { store as notestore } from "../stores/note-store";
import { useEditorStore } from "../stores/editor-store";
-import { Perform } from "../common/dialog-controller";
import { FilteredList } from "../components/filtered-list";
import { ItemReference, Tag } from "@notesnook/core/dist/types";
import { create } from "zustand";
import { VirtualizedGrouping } from "@notesnook/core";
import { ResolvedItem } from "@notesnook/common";
+import { BaseDialogProps, DialogManager } from "../common/dialog-manager";
type SelectedReference = {
id: string;
@@ -51,12 +51,10 @@ export const useSelectionStore = create<ISelectionStore>((set) => ({
setSelected: (selected) => set({ selected: selected.slice() })
}));
-export type AddTagsDialogProps = {
- onClose: Perform;
- noteIds: string[];
-};
-
-function AddTagsDialog(props: AddTagsDialogProps) {
+type AddTagsDialogProps = BaseDialogProps<boolean> & { noteIds: string[] };
+export const AddTagsDialog = DialogManager.register(function AddTagsDialog(
+ props: AddTagsDialogProps
+) {
const { onClose, noteIds } = props;
const [tags, setTags] = useState<VirtualizedGrouping<Tag> | undefined>(
@@ -101,7 +99,6 @@ function AddTagsDialog(props: AddTagsDialogProps) {
else await db.relations.unlink(tagRef, noteRef);
}
}
- await useEditorStore.getState().refreshTags();
await store.get().refresh();
await notestore.get().refresh();
onClose(true);
@@ -150,7 +147,7 @@ function AddTagsDialog(props: AddTagsDialogProps) {
)}
</Dialog>
);
-}
+});
function TagItem(props: { tag: Tag }) {
const { tag } = props;
@@ -201,8 +198,6 @@ function TagItem(props: { tag: Tag }) {
);
}
-export default AddTagsDialog;
-
function SelectedCheck({ id, size = 20 }: { id: string; size?: number }) {
const selected = useSelectionStore((store) => store.selected);
const selectedTag = selected.find((item) => item.id === id);
diff --git a/apps/web/src/dialogs/announcement-dialog.jsx b/apps/web/src/dialogs/announcement-dialog.tsx
similarity index 52%
rename from apps/web/src/dialogs/announcement-dialog.jsx
rename to apps/web/src/dialogs/announcement-dialog.tsx
index aa618e549..de65f041a 100644
--- a/apps/web/src/dialogs/announcement-dialog.jsx
+++ b/apps/web/src/dialogs/announcement-dialog.tsx
@@ -22,31 +22,36 @@ import AnnouncementBody from "../components/announcements/body";
import { store as announcementStore } from "../stores/announcement-store";
import { useCallback } from "react";
import BaseDialog from "../components/dialog";
-
-function AnnouncementDialog(props) {
- const { announcement, onClose } = props;
-
- const dismiss = useCallback(() => {
- announcementStore.get().dismiss(announcement.id);
- onClose(true);
- }, [announcement, onClose]);
-
- return (
- <BaseDialog isOpen onClose={props.onClose} width={"30%"}>
- <Flex
- bg="background"
- sx={{
- position: "relative",
- flexDirection: "column"
- }}
- >
- <AnnouncementBody
- dismiss={dismiss}
- components={announcement.body}
- type="dialog"
- />
- </Flex>
- </BaseDialog>
- );
-}
-export default AnnouncementDialog;
+import { BaseDialogProps, DialogManager } from "../common/dialog-manager";
+
+type AnnouncementDialogProps = BaseDialogProps<boolean> & {
+ announcement: any;
+};
+export const AnnouncementDialog = DialogManager.register(
+ function AnnouncementDialog(props: AnnouncementDialogProps) {
+ const { announcement, onClose } = props;
+
+ const dismiss = useCallback(() => {
+ announcementStore.get().dismiss(announcement.id);
+ onClose(true);
+ }, [announcement, onClose]);
+
+ return (
+ <BaseDialog isOpen onClose={() => onClose(false)} width={"30%"}>
+ <Flex
+ bg="background"
+ sx={{
+ position: "relative",
+ flexDirection: "column"
+ }}
+ >
+ <AnnouncementBody
+ dismiss={dismiss}
+ components={announcement.body}
+ type="dialog"
+ />
+ </Flex>
+ </BaseDialog>
+ );
+ }
+);
diff --git a/apps/web/src/dialogs/attachments-dialog.tsx b/apps/web/src/dialogs/attachments-dialog.tsx
index 3a2a7f293..ffd39f42e 100644
--- a/apps/web/src/dialogs/attachments-dialog.tsx
+++ b/apps/web/src/dialogs/attachments-dialog.tsx
@@ -50,7 +50,6 @@ import {
import NavigationItem from "../components/navigation-menu/navigation-item";
import { pluralize } from "@notesnook/common";
import { db } from "../common/db";
-import { Perform } from "../common/dialog-controller";
import { Attachment } from "../components/attachment";
import { ScopedThemeProvider } from "../components/theme-provider";
import {
@@ -63,6 +62,7 @@ import {
VirtualizedTableRowProps
} from "../components/virtualized-table";
import { FlexScrollContainer } from "../components/scroll-container";
+import { BaseDialogProps, DialogManager } from "../common/dialog-manager";
type ToolbarAction = {
title: string;
@@ -101,122 +101,123 @@ type SortOptions = {
id: "filename" | "size" | "dateUploaded";
direction: "asc" | "desc";
};
-type AttachmentsDialogProps = { onClose: Perform };
-function AttachmentsDialog({ onClose }: AttachmentsDialogProps) {
- const allAttachments = useStore((store) => store.attachments);
- const [attachments, setAttachments] =
- useState<VirtualizedGrouping<AttachmentType>>();
- const [counts, setCounts] = useState<Record<Route, number>>({
- all: 0,
- documents: 0,
- images: 0,
- orphaned: 0,
- uploads: 0,
- videos: 0,
- audio: 0
- });
- const [selected, setSelected] = useState<string[]>([]);
- const [sortBy, setSortBy] = useState<SortOptions>({
- id: "filename",
- direction: "asc"
- });
- const currentRoute = useRef<Route>("all");
- const refresh = useStore((store) => store.refresh);
- const download = useStore((store) => store.download);
+type AttachmentsDialogProps = BaseDialogProps<false>;
+export const AttachmentsDialog = DialogManager.register(
+ function AttachmentsDialog({ onClose }: AttachmentsDialogProps) {
+ const allAttachments = useStore((store) => store.attachments);
+ const [attachments, setAttachments] =
+ useState<VirtualizedGrouping<AttachmentType>>();
+ const [counts, setCounts] = useState<Record<Route, number>>({
+ all: 0,
+ documents: 0,
+ images: 0,
+ orphaned: 0,
+ uploads: 0,
+ videos: 0,
+ audio: 0
+ });
+ const [selected, setSelected] = useState<string[]>([]);
+ const [sortBy, setSortBy] = useState<SortOptions>({
+ id: "filename",
+ direction: "asc"
+ });
+ const currentRoute = useRef<Route>("all");
+ const refresh = useStore((store) => store.refresh);
+ const download = useStore((store) => store.download);
- useEffect(() => {
- refresh();
- }, [refresh]);
+ useEffect(() => {
+ refresh();
+ }, [refresh]);
- useEffect(() => {
- (async function () {
- setAttachments(
- await filterAttachments(currentRoute.current).sorted({
- sortBy: sortBy.id,
- sortDirection: sortBy.direction
- })
- );
- })();
- }, [sortBy, allAttachments]);
+ useEffect(() => {
+ (async function () {
+ setAttachments(
+ await filterAttachments(currentRoute.current).sorted({
+ sortBy: sortBy.id,
+ sortDirection: sortBy.direction
+ })
+ );
+ })();
+ }, [sortBy, allAttachments]);
- useEffect(() => {
- (async function () {
- setCounts(await getCounts());
- })();
- }, [allAttachments]);
+ useEffect(() => {
+ (async function () {
+ setCounts(await getCounts());
+ })();
+ }, [allAttachments]);
- return (
- <Dialog
- isOpen={true}
- width={"70%"}
- onClose={() => onClose(false)}
- noScroll
- sx={{ bg: "transparent" }}
- >
- <Flex
- sx={{
- height: "80vw",
- overflow: "hidden"
- }}
+ return (
+ <Dialog
+ isOpen={true}
+ width={"70%"}
+ onClose={() => onClose(false)}
+ noScroll
+ sx={{ bg: "transparent" }}
>
- <Sidebar
- onDownloadAll={async () =>
- download(
- await db.attachments.all.ids({
- sortBy: "dateCreated",
- sortDirection: "desc"
- })
- )
- }
- filter={async (query) => {
- setAttachments(await db.lookup.attachments(query).sorted());
- }}
- counts={counts}
- onRouteChange={async (route) => {
- currentRoute.current = route;
- setSelected([]);
- setAttachments(
- await filterAttachments(currentRoute.current).sorted({
- sortBy: sortBy.id,
- sortDirection: sortBy.direction
- })
- );
- }}
- />
<Flex
- variant="columnFill"
sx={{
- bg: "background",
- flexDirection: "column",
- pl: 4,
- pt: 2,
+ height: "80vw",
overflow: "hidden"
}}
>
- <FlexScrollContainer>
- <Flex sx={{ justifyContent: "space-between" }}>
- <Flex sx={{ gap: 1 }}>
- {TOOLBAR_ACTIONS.map((tool) => (
- <Button
- variant="secondary"
- key={tool.title}
- title={tool.title}
- onClick={() =>
- tool.onClick({
- selected
- // : attachments.filter(
- // (a) => selected.indexOf(a.id) > -1
- // )
- })
- }
- disabled={!selected.length}
- sx={{ bg: "transparent", p: 1 }}
- >
- <tool.icon size={18} />
- </Button>
- ))}
- </Flex>
- {/* <Button
+ <Sidebar
+ onDownloadAll={async () =>
+ download(
+ await db.attachments.all.ids({
+ sortBy: "dateCreated",
+ sortDirection: "desc"
+ })
+ )
+ }
+ filter={async (query) => {
+ setAttachments(await db.lookup.attachments(query).sorted());
+ }}
+ counts={counts}
+ onRouteChange={async (route) => {
+ currentRoute.current = route;
+ setSelected([]);
+ setAttachments(
+ await filterAttachments(currentRoute.current).sorted({
+ sortBy: sortBy.id,
+ sortDirection: sortBy.direction
+ })
+ );
+ }}
+ />
+ <Flex
+ variant="columnFill"
+ sx={{
+ bg: "background",
+ flexDirection: "column",
+ pl: 4,
+ pt: 2,
+ overflow: "hidden"
+ }}
+ >
+ <FlexScrollContainer>
+ <Flex sx={{ justifyContent: "space-between" }}>
+ <Flex sx={{ gap: 1 }}>
+ {TOOLBAR_ACTIONS.map((tool) => (
+ <Button
+ variant="secondary"
+ key={tool.title}
+ title={tool.title}
+ onClick={() =>
+ tool.onClick({
+ selected
+ // : attachments.filter(
+ // (a) => selected.indexOf(a.id) > -1
+ // )
+ })
+ }
+ disabled={!selected.length}
+ sx={{ bg: "transparent", p: 1 }}
+ >
+ <tool.icon size={18} />
+ </Button>
+ ))}
+ </Flex>
+ {/* <Button
variant="tool"
sx={{ p: 1, display: "flex" }}
onClick={async () => {
@@ -229,123 +230,122 @@ function AttachmentsDialog({ onClose }: AttachmentsDialogProps) {
Upload
</Text>
</Button> */}
- </Flex>
- {attachments && (
- <VirtualizedTable
- style={{ tableLayout: "fixed", borderCollapse: "collapse" }}
- header={
- <Box
- as="tr"
- sx={{
- height: 40,
- th: { borderBottom: "1px solid var(--separator)" },
- bg: "background"
- }}
- >
- <Text
- as="th"
- variant="body"
+ </Flex>
+ {attachments && (
+ <VirtualizedTable
+ style={{ tableLayout: "fixed", borderCollapse: "collapse" }}
+ header={
+ <Box
+ as="tr"
sx={{
- width: 24,
- textAlign: "left",
- fontWeight: "normal",
- mb: 2
+ height: 40,
+ th: { borderBottom: "1px solid var(--separator)" },
+ bg: "background"
}}
>
- <Label>
- <Checkbox
- sx={{ width: 18, height: 18 }}
- onChange={async (e) => {
- setSelected(
- e.currentTarget.checked
- ? await filterAttachments(
- currentRoute.current
- ).ids()
- : []
- );
- }}
- />
- </Label>
- </Text>
- {COLUMNS.map((column) =>
- !column.title ? (
- <th key={column.id} />
- ) : (
- <Box
- as="th"
- key={column.id}
- sx={{
- width: column.width,
- cursor: "pointer",
- px: 1,
- mb: 2,
- ":hover": { bg: "hover" }
- }}
- onClick={() => {
- setSortBy((sortBy) => ({
- direction:
- sortBy.id === column.id &&
- sortBy.direction === "asc"
- ? "desc"
- : "asc",
- id: column.id
- }));
- }}
- >
- <Flex
+ <Text
+ as="th"
+ variant="body"
+ sx={{
+ width: 24,
+ textAlign: "left",
+ fontWeight: "normal",
+ mb: 2
+ }}
+ >
+ <Label>
+ <Checkbox
+ sx={{ width: 18, height: 18 }}
+ onChange={async (e) => {
+ setSelected(
+ e.currentTarget.checked
+ ? await filterAttachments(
+ currentRoute.current
+ ).ids()
+ : []
+ );
+ }}
+ />
+ </Label>
+ </Text>
+ {COLUMNS.map((column) =>
+ !column.title ? (
+ <th key={column.id} />
+ ) : (
+ <Box
+ as="th"
+ key={column.id}
sx={{
- alignItems: "center",
- justifyContent: "space-between"
+ width: column.width,
+ cursor: "pointer",
+ px: 1,
+ mb: 2,
+ ":hover": { bg: "hover" }
+ }}
+ onClick={() => {
+ setSortBy((sortBy) => ({
+ direction:
+ sortBy.id === column.id &&
+ sortBy.direction === "asc"
+ ? "desc"
+ : "asc",
+ id: column.id
+ }));
}}
>
- <Text
- variant="body"
- sx={{ textAlign: "left", fontWeight: "normal" }}
+ <Flex
+ sx={{
+ alignItems: "center",
+ justifyContent: "space-between"
+ }}
>
- {column.title}
- </Text>
- {sortBy.id === column.id ? (
- sortBy.direction === "asc" ? (
- <ChevronUp size={16} />
- ) : (
- <ChevronDown size={16} />
- )
- ) : null}
- </Flex>
- </Box>
- )
- )}
- </Box>
- }
- mode="fixed"
- estimatedSize={30}
- headerSize={40}
- getItemKey={(index) => attachments.key(index)}
- items={attachments.placeholders}
- context={{
- isSelected: (id: string) => selected.indexOf(id) > -1,
- select: (id: string) => {
- setSelected((s) => {
- const copy = s.slice();
- const index = copy.indexOf(id);
- if (index > -1) copy.splice(index, 1);
- else copy.push(id);
- return copy;
- });
- },
- attachments
- }}
- renderRow={AttachmentRow}
- />
- )}
- </FlexScrollContainer>
+ <Text
+ variant="body"
+ sx={{ textAlign: "left", fontWeight: "normal" }}
+ >
+ {column.title}
+ </Text>
+ {sortBy.id === column.id ? (
+ sortBy.direction === "asc" ? (
+ <ChevronUp size={16} />
+ ) : (
+ <ChevronDown size={16} />
+ )
+ ) : null}
+ </Flex>
+ </Box>
+ )
+ )}
+ </Box>
+ }
+ mode="fixed"
+ estimatedSize={30}
+ headerSize={40}
+ getItemKey={(index) => attachments.key(index)}
+ items={attachments.placeholders}
+ context={{
+ isSelected: (id: string) => selected.indexOf(id) > -1,
+ select: (id: string) => {
+ setSelected((s) => {
+ const copy = s.slice();
+ const index = copy.indexOf(id);
+ if (index > -1) copy.splice(index, 1);
+ else copy.push(id);
+ return copy;
+ });
+ },
+ attachments
+ }}
+ renderRow={AttachmentRow}
+ />
+ )}
+ </FlexScrollContainer>
+ </Flex>
</Flex>
- </Flex>
- </Dialog>
- );
-}
-
-export default AttachmentsDialog;
+ </Dialog>
+ );
+ }
+);
function AttachmentRow(
props: VirtualizedTableRowProps<
diff --git a/apps/web/src/dialogs/backup-password-dialog.tsx b/apps/web/src/dialogs/backup-password-dialog.tsx
index ac8ec6506..5244a5a2f 100644
--- a/apps/web/src/dialogs/backup-password-dialog.tsx
+++ b/apps/web/src/dialogs/backup-password-dialog.tsx
@@ -18,105 +18,106 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import { useState } from "react";
-import { Perform } from "../common/dialog-controller";
import Field from "../components/field";
import Dialog from "../components/dialog";
import { Box, Button, Text } from "@theme-ui/components";
+import { BaseDialogProps, DialogManager } from "../common/dialog-manager";
-export type PromptDialogProps = {
- onClose: Perform;
+export type BackupPasswordDialogProps = BaseDialogProps<boolean> & {
validate: (outputs: {
password?: string;
key?: string;
}) => boolean | Promise<boolean>;
};
-export default function BackupPasswordDialog(props: PromptDialogProps) {
- const { onClose, validate } = props;
+export const BackupPasswordDialog = DialogManager.register(
+ function BackupPasswordDialog(props: BackupPasswordDialogProps) {
+ const { onClose, validate } = props;
- const [error, setError] = useState<string>();
- const [isLoading, setIsLoading] = useState(false);
- const [isEncryptionKey, setIsEncryptionKey] = useState(false);
+ const [error, setError] = useState<string>();
+ const [isLoading, setIsLoading] = useState(false);
+ const [isEncryptionKey, setIsEncryptionKey] = useState(false);
- return (
- <Dialog
- isOpen={true}
- testId="password-dialog"
- title={"Encrypted backup"}
- description={
- "Please enter the password to decrypt and restore this backup."
- }
- onClose={() => onClose(false)}
- positiveButton={{
- form: "backupPasswordForm",
- type: "submit",
- loading: isLoading,
- disabled: isLoading,
- text: "Restore"
- }}
- negativeButton={{ text: "Cancel", onClick: () => onClose(false) }}
- >
- <Box
- id="backupPasswordForm"
- as="form"
- onSubmit={async (e) => {
- e.preventDefault();
- const formData = new FormData(e.target as HTMLFormElement);
+ return (
+ <Dialog
+ isOpen={true}
+ testId="password-dialog"
+ title={"Encrypted backup"}
+ description={
+ "Please enter the password to decrypt and restore this backup."
+ }
+ onClose={() => onClose(false)}
+ positiveButton={{
+ form: "backupPasswordForm",
+ type: "submit",
+ loading: isLoading,
+ disabled: isLoading,
+ text: "Restore"
+ }}
+ negativeButton={{ text: "Cancel", onClick: () => onClose(false) }}
+ >
+ <Box
+ id="backupPasswordForm"
+ as="form"
+ onSubmit={async (e) => {
+ e.preventDefault();
+ const formData = new FormData(e.target as HTMLFormElement);
- try {
- setIsLoading(true);
- setError(undefined);
+ try {
+ setIsLoading(true);
+ setError(undefined);
- const key = formData.get("key") as string;
- const password = formData.get("password") as string;
- if (!key && !password) return;
+ const key = formData.get("key") as string;
+ const password = formData.get("password") as string;
+ if (!key && !password) return;
- if (await validate({ key, password })) {
- onClose(true);
- } else {
- setError("Wrong password.");
+ if (await validate({ key, password })) {
+ onClose(true);
+ } else {
+ setError("Wrong password.");
+ }
+ } catch (e) {
+ setError((e as Error).message);
+ } finally {
+ setIsLoading(false);
}
- } catch (e) {
- setError((e as Error).message);
- } finally {
- setIsLoading(false);
- }
- }}
- >
- {isEncryptionKey ? (
- <Field
- required
- autoFocus
- data-test-id="encryption-key"
- label="Encryption key"
- type="password"
- id="key"
- name="key"
- />
- ) : (
- <Field
- required
- autoFocus
- data-test-id="password"
- label="Password"
- type="password"
- autoComplete="current-password"
- id="password"
- name="password"
- />
- )}
- </Box>
- <Button variant="anchor" onClick={() => setIsEncryptionKey((s) => !s)}>
- {isEncryptionKey
- ? "Don't have encryption key? Use password."
- : "Forgot password? Use encryption key."}
- </Button>
+ }}
+ >
+ {isEncryptionKey ? (
+ <Field
+ required
+ autoFocus
+ data-test-id="encryption-key"
+ label="Encryption key"
+ type="password"
+ id="key"
+ name="key"
+ />
+ ) : (
+ <Field
+ required
+ autoFocus
+ data-test-id="password"
+ label="Password"
+ type="password"
+ autoComplete="current-password"
+ id="password"
+ name="password"
+ />
+ )}
+ </Box>
+ <Button variant="anchor" onClick={() => setIsEncryptionKey((s) => !s)}>
+ {isEncryptionKey
+ ? "Don't have encryption key? Use password."
+ : "Forgot password? Use encryption key."}
+ </Button>
- {error && (
- <Text as="div" mt={1} variant={"error"}>
- {error}
- </Text>
- )}
- </Dialog>
- );
-}
+ {error && (
+ <Text as="div" mt={1} variant={"error"}>
+ {error}
+ </Text>
+ )}
+ </Dialog>
+ );
+ }
+);
diff --git a/apps/web/src/dialogs/buy-dialog/buy-dialog.tsx b/apps/web/src/dialogs/buy-dialog/buy-dialog.tsx
index e04f1b5c9..6b0df6842 100644
--- a/apps/web/src/dialogs/buy-dialog/buy-dialog.tsx
+++ b/apps/web/src/dialogs/buy-dialog/buy-dialog.tsx
@@ -45,14 +45,16 @@ import { SUBSCRIPTION_STATUS } from "../../common/constants";
import BaseDialog from "../../components/dialog";
import { ScopedThemeProvider } from "../../components/theme-provider";
import { User } from "@notesnook/core";
+import { BaseDialogProps, DialogManager } from "../../common/dialog-manager";
-type BuyDialogProps = {
+type BuyDialogProps = BaseDialogProps<false> & {
couponCode?: string;
plan?: "monthly" | "yearly" | "education";
- onClose: () => void;
};
-export function BuyDialog(props: BuyDialogProps) {
+export const BuyDialog = DialogManager.register(function BuyDialog(
+ props: BuyDialogProps
+) {
const { onClose, couponCode, plan } = props;
const theme = useTheme() as Theme;
@@ -73,7 +75,7 @@ export function BuyDialog(props: BuyDialogProps) {
<BaseDialog
isOpen={true}
width={"868px"}
- onClose={() => props.onClose()}
+ onClose={() => props.onClose(false)}
noScroll
sx={{
bg: "transparent",
@@ -107,13 +109,13 @@ export function BuyDialog(props: BuyDialogProps) {
py: 50
}}
>
- <SideBar onClose={onClose} initialPlan={plan} />
+ <SideBar onClose={() => onClose(false)} initialPlan={plan} />
</ScopedThemeProvider>
<Details />
</Flex>
</BaseDialog>
);
-}
+});
type SideBarProps = {
initialPlan?: Period;
diff --git a/apps/web/src/dialogs/buy-dialog/index.ts b/apps/web/src/dialogs/buy-dialog/index.ts
index 54452d0c6..13b3cbd80 100644
--- a/apps/web/src/dialogs/buy-dialog/index.ts
+++ b/apps/web/src/dialogs/buy-dialog/index.ts
@@ -17,4 +17,4 @@ You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
-export { BuyDialog as default } from "./buy-dialog";
+export * from "./buy-dialog";
diff --git a/apps/web/src/dialogs/confirm.tsx b/apps/web/src/dialogs/confirm.tsx
index c82b5709f..e9601539d 100644
--- a/apps/web/src/dialogs/confirm.tsx
+++ b/apps/web/src/dialogs/confirm.tsx
@@ -19,15 +19,19 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.
import { Box, Checkbox, Label, Text } from "@theme-ui/components";
import { useRef } from "react";
-import { Perform } from "../common/dialog-controller";
import { mdToHtml } from "../utils/md";
import Dialog from "../components/dialog";
+import { BaseDialogProps, DialogManager } from "../common/dialog-manager";
+import { db } from "../common/db";
+import { AppVersion, getChangelog } from "../utils/version";
+import { downloadUpdate } from "../utils/updater";
type Check = { text: string; default?: boolean };
-export type ConfirmDialogProps<TCheckId extends string> = {
+export type ConfirmDialogProps<TCheckId extends string> = BaseDialogProps<
+ false | Record<TCheckId, boolean>
+> & {
title: string;
subtitle?: string;
- onClose: Perform<false | Record<TCheckId, boolean>>;
width?: number;
positiveButtonText?: string;
negativeButtonText?: string;
@@ -35,9 +39,9 @@ export type ConfirmDialogProps<TCheckId extends string> = {
checks?: Partial<Record<TCheckId, Check>>;
};
-function ConfirmDialog<TCheckId extends string>(
- props: ConfirmDialogProps<TCheckId>
-) {
+export const ConfirmDialog = DialogManager.register(function ConfirmDialog<
+ TCheckId extends string
+>(props: ConfirmDialogProps<TCheckId>) {
const {
onClose,
title,
@@ -116,6 +120,85 @@ function ConfirmDialog<TCheckId extends string>(
</Box>
</Dialog>
);
+});
+
+export function showMultiDeleteConfirmation(length: number) {
+ return ConfirmDialog.show({
+ title: `Delete ${length} items?`,
+ message: `These items will be **kept in your Trash for ${
+ db.settings.getTrashCleanupInterval() || 7
+ } days** after which they will be permanently deleted.`,
+ positiveButtonText: "Yes",
+ negativeButtonText: "No"
+ });
+}
+
+export function showMultiPermanentDeleteConfirmation(length: number) {
+ return ConfirmDialog.show({
+ title: `Permanently delete ${length} items?`,
+ message:
+ "These items will be **permanently deleted**. This is IRREVERSIBLE.",
+ positiveButtonText: "Yes",
+ negativeButtonText: "No"
+ });
+}
+
+export function showLogoutConfirmation() {
+ return ConfirmDialog.show({
+ title: `Logout?`,
+ message:
+ "Logging out will clear all data stored on THIS DEVICE. Make sure you have synced all your changes before logging out.",
+ positiveButtonText: "Yes",
+ negativeButtonText: "No"
+ });
+}
+
+export function showClearSessionsConfirmation() {
+ return ConfirmDialog.show({
+ title: `Logout from other devices?`,
+ message:
+ "All other logged-in devices will be forced to logout stopping sync. Use with care lest you lose important notes.",
+ positiveButtonText: "Yes",
+ negativeButtonText: "No"
+ });
}
-export default ConfirmDialog;
+export async function showUpdateAvailableNotice({
+ version
+}: {
+ version: string;
+}) {
+ const changelog = await getChangelog(version);
+
+ return showUpdateDialog({
+ title: `New version available`,
+ subtitle: `v${version} is available for download`,
+ changelog,
+ action: { text: `Update now`, onClick: () => downloadUpdate() }
+ });
+}
+
+type UpdateDialogProps = {
+ title: string;
+ subtitle: string;
+ changelog: string;
+ action: {
+ text: string;
+ onClick: () => void;
+ };
+};
+async function showUpdateDialog({
+ title,
+ subtitle,
+ changelog,
+ action
+}: UpdateDialogProps) {
+ const result = await ConfirmDialog.show({
+ title,
+ subtitle,
+ message: changelog,
+ width: 500,
+ positiveButtonText: action.text
+ });
+ if (result && action.onClick) action.onClick();
+}
diff --git a/apps/web/src/dialogs/create-color-dialog.tsx b/apps/web/src/dialogs/create-color-dialog.tsx
index e802cfd7b..84e34456f 100644
--- a/apps/web/src/dialogs/create-color-dialog.tsx
+++ b/apps/web/src/dialogs/create-color-dialog.tsx
@@ -20,91 +20,91 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.
import { Box, Flex } from "@theme-ui/components";
import Dialog from "../components/dialog";
import Field from "../components/field";
-import { Perform } from "../common/dialog-controller";
import { useRef } from "react";
import tinycolor from "tinycolor2";
import { db } from "../common/db";
import { showToast } from "../utils/toast";
+import { BaseDialogProps, DialogManager } from "../common/dialog-manager";
-type CreateColorDialogProps = {
- onClose: Perform;
- onDone: Perform<string>;
-};
-function CreateColorDialog(props: CreateColorDialogProps) {
- const colorRef = useRef<HTMLInputElement>(null);
- const colorPickerRef = useRef<HTMLInputElement>(null);
- return (
- <Dialog
- testId="new-color-dialog"
- isOpen={true}
- title={"Create a new color"}
- onClose={() => props.onClose(false)}
- positiveButton={{
- form: "colorForm",
- type: "submit",
- text: "Create"
- }}
- negativeButton={{ text: "Cancel", onClick: () => props.onClose(false) }}
- >
- <Box
- as="form"
- id="colorForm"
- onSubmit={async (e) => {
- e.preventDefault();
- const form = Object.fromEntries(
- new FormData(e.target as HTMLFormElement).entries()
- ) as { color: string; title: string };
- if (!tinycolor(form.color, { format: "hex" }).isValid()) {
- showToast("error", "Please enter a valid hex color (e.g. #ffffff)");
- return;
- }
- const colorId = await db.colors.add({
- colorCode: form.color,
- title: form.title
- });
- props.onDone(colorId);
+type CreateColorDialogProps = BaseDialogProps<string | false>;
+export const CreateColorDialog = DialogManager.register(
+ function CreateColorDialog(props: CreateColorDialogProps) {
+ const colorRef = useRef<HTMLInputElement>(null);
+ const colorPickerRef = useRef<HTMLInputElement>(null);
+ return (
+ <Dialog
+ testId="new-color-dialog"
+ isOpen={true}
+ title={"Create a new color"}
+ onClose={() => props.onClose(false)}
+ positiveButton={{
+ form: "colorForm",
+ type: "submit",
+ text: "Create"
}}
+ negativeButton={{ text: "Cancel", onClick: () => props.onClose(false) }}
>
- <Field
- required
- label="Title"
- id="title"
- name="title"
- autoFocus
- data-test-id="title-input"
- />
- <Flex sx={{ alignItems: "end" }}>
+ <Box
+ as="form"
+ id="colorForm"
+ onSubmit={async (e) => {
+ e.preventDefault();
+ const form = Object.fromEntries(
+ new FormData(e.target as HTMLFormElement).entries()
+ ) as { color: string; title: string };
+ if (!tinycolor(form.color, { format: "hex" }).isValid()) {
+ showToast(
+ "error",
+ "Please enter a valid hex color (e.g. #ffffff)"
+ );
+ return;
+ }
+ const colorId = await db.colors.add({
+ colorCode: form.color,
+ title: form.title
+ });
+ props.onClose(colorId);
+ }}
+ >
<Field
- inputRef={colorRef}
required
- label="Color"
- id="color"
- name="color"
- data-test-id="color-input"
- sx={{ flex: 1 }}
- onChange={(e) => {
- const color = tinycolor(e.target.value);
- if (colorPickerRef.current && color.isValid())
- colorPickerRef.current.value = color.toHexString();
- }}
+ label="Title"
+ id="title"
+ name="title"
+ autoFocus
+ data-test-id="title-input"
/>
- <input
- ref={colorPickerRef}
- type="color"
- style={{
- height: 41,
- backgroundColor: "transparent",
- border: "1px solid var(--border)",
- borderRadius: 5
- }}
- onChange={(e) => {
- if (colorRef.current) colorRef.current.value = e.target.value;
- }}
- />
- </Flex>
- </Box>
- </Dialog>
- );
-}
-
-export default CreateColorDialog;
+ <Flex sx={{ alignItems: "end" }}>
+ <Field
+ inputRef={colorRef}
+ required
+ label="Color"
+ id="color"
+ name="color"
+ data-test-id="color-input"
+ sx={{ flex: 1 }}
+ onChange={(e) => {
+ const color = tinycolor(e.target.value);
+ if (colorPickerRef.current && color.isValid())
+ colorPickerRef.current.value = color.toHexString();
+ }}
+ />
+ <input
+ ref={colorPickerRef}
+ type="color"
+ style={{
+ height: 41,
+ backgroundColor: "transparent",
+ border: "1px solid var(--border)",
+ borderRadius: 5
+ }}
+ onChange={(e) => {
+ if (colorRef.current) colorRef.current.value = e.target.value;
+ }}
+ />
+ </Flex>
+ </Box>
+ </Dialog>
+ );
+ }
+);
diff --git a/apps/web/src/dialogs/edit-profile-picture-dialog.tsx b/apps/web/src/dialogs/edit-profile-picture-dialog.tsx
index ffe6ceb68..ab3c6cf36 100644
--- a/apps/web/src/dialogs/edit-profile-picture-dialog.tsx
+++ b/apps/web/src/dialogs/edit-profile-picture-dialog.tsx
@@ -17,7 +17,6 @@ You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
-import { Perform } from "../common/dialog-controller";
import Dialog from "../components/dialog";
import { Profile } from "@notesnook/core";
import AvatarEditor from "react-avatar-editor";
@@ -28,139 +27,139 @@ import { showFilePicker } from "../utils/file-picker";
import { db } from "../common/db";
import { showToast } from "../utils/toast";
import { useStore as useSettingStore } from "../stores/setting-store";
+import { BaseDialogProps, DialogManager } from "../common/dialog-manager";
-export type EditProfilePictureDialogProps = {
- onClose: Perform;
+export type EditProfilePictureDialogProps = BaseDialogProps<boolean> & {
profile?: Profile;
};
-export default function EditProfilePictureDialog(
- props: EditProfilePictureDialogProps
-) {
- const { profile } = props;
- const [profilePicture, setProfilePicture] = useState<
- File | string | undefined
- >(profile?.profilePicture);
- const profileRef = useRef<AvatarEditor>(null);
- const [scale, setScale] = useState(1);
- const [isLoading, setIsLoading] = useState(false);
- const [clearProfilePicture, setClearProfilePicture] = useState(false);
+export const EditProfilePictureDialog = DialogManager.register(
+ function EditProfilePictureDialog(props: EditProfilePictureDialogProps) {
+ const { profile } = props;
+ const [profilePicture, setProfilePicture] = useState<
+ File | string | undefined
+ >(profile?.profilePicture);
+ const profileRef = useRef<AvatarEditor>(null);
+ const [scale, setScale] = useState(1);
+ const [isLoading, setIsLoading] = useState(false);
+ const [clearProfilePicture, setClearProfilePicture] = useState(false);
- return (
- <Dialog
- isOpen={true}
- title={"Edit profile picture"}
- description="Your profile data is stored 100% end-to-end encrypted."
- onClose={() => props.onClose(false)}
- positiveButton={{
- loading: isLoading,
- disabled: isLoading,
- text: "Save",
- onClick: async () => {
- setIsLoading(true);
- try {
- const pic = profileRef.current
- ? profileRef.current
- .getImageScaledToCanvas()
- .toDataURL("image/jpeg", 0.8)
- : clearProfilePicture
- ? undefined
- : profile?.profilePicture;
- await db.settings.setProfile({
- profilePicture: pic
- });
- await useSettingStore.getState().refresh();
- showToast("success", "Profile updated!");
- props.onClose(true);
- } catch (e) {
- console.error(e);
- showToast("error", (e as Error).message);
- } finally {
- setIsLoading(false);
+ return (
+ <Dialog
+ isOpen={true}
+ title={"Edit profile picture"}
+ description="Your profile data is stored 100% end-to-end encrypted."
+ onClose={() => props.onClose(false)}
+ positiveButton={{
+ loading: isLoading,
+ disabled: isLoading,
+ text: "Save",
+ onClick: async () => {
+ setIsLoading(true);
+ try {
+ const pic = profileRef.current
+ ? profileRef.current
+ .getImageScaledToCanvas()
+ .toDataURL("image/jpeg", 0.8)
+ : clearProfilePicture
+ ? undefined
+ : profile?.profilePicture;
+ await db.settings.setProfile({
+ profilePicture: pic
+ });
+ await useSettingStore.getState().refresh();
+ showToast("success", "Profile updated!");
+ props.onClose(true);
+ } catch (e) {
+ console.error(e);
+ showToast("error", (e as Error).message);
+ } finally {
+ setIsLoading(false);
+ }
}
- }
- }}
- negativeButton={{ text: "Cancel", onClick: () => props.onClose(false) }}
- >
- <Flex
- sx={{
- flexDirection: "column"
}}
+ negativeButton={{ text: "Cancel", onClick: () => props.onClose(false) }}
>
- {profilePicture ? (
- <AvatarEditor
- ref={profileRef}
- image={profilePicture}
- width={256}
- height={256}
- border={1}
- color={[255, 255, 255]}
- borderRadius={256}
- scale={scale}
- style={{
- width: 150,
- height: 150,
- alignSelf: "center"
- }}
- />
- ) : (
- <Flex
- variant="columnCenter"
- sx={{
- bg: "shade",
- mr: 2,
- size: 150,
- borderRadius: 200,
- alignSelf: "center"
- }}
- >
- <User size={60} />
- </Flex>
- )}
- <Flex sx={{ gap: 1, alignItems: "center", mt: 2 }}>
- <Button
- sx={{ flex: 1 }}
- variant="secondary"
- onClick={async () => {
- const [file] = await showFilePicker({
- acceptedFileTypes: "image/*"
- });
- if (!file) return;
- setProfilePicture(file);
- setScale(1);
- }}
- >
- {profilePicture
- ? "Change profile picture"
- : "Select profile picture"}
- </Button>
+ <Flex
+ sx={{
+ flexDirection: "column"
+ }}
+ >
{profilePicture ? (
+ <AvatarEditor
+ ref={profileRef}
+ image={profilePicture}
+ width={256}
+ height={256}
+ border={1}
+ color={[255, 255, 255]}
+ borderRadius={256}
+ scale={scale}
+ style={{
+ width: 150,
+ height: 150,
+ alignSelf: "center"
+ }}
+ />
+ ) : (
+ <Flex
+ variant="columnCenter"
+ sx={{
+ bg: "shade",
+ mr: 2,
+ size: 150,
+ borderRadius: 200,
+ alignSelf: "center"
+ }}
+ >
+ <User size={60} />
+ </Flex>
+ )}
+ <Flex sx={{ gap: 1, alignItems: "center", mt: 2 }}>
<Button
sx={{ flex: 1 }}
variant="secondary"
onClick={async () => {
- if (typeof profilePicture === "string") {
- setClearProfilePicture(true);
- setProfilePicture(undefined);
- } else setProfilePicture(profile?.profilePicture);
+ const [file] = await showFilePicker({
+ acceptedFileTypes: "image/*"
+ });
+ if (!file) return;
+ setProfilePicture(file);
setScale(1);
}}
>
- {typeof profilePicture === "string" ? "Clear" : "Reset"}
+ {profilePicture
+ ? "Change profile picture"
+ : "Select profile picture"}
</Button>
+ {profilePicture ? (
+ <Button
+ sx={{ flex: 1 }}
+ variant="secondary"
+ onClick={async () => {
+ if (typeof profilePicture === "string") {
+ setClearProfilePicture(true);
+ setProfilePicture(undefined);
+ } else setProfilePicture(profile?.profilePicture);
+ setScale(1);
+ }}
+ >
+ {typeof profilePicture === "string" ? "Clear" : "Reset"}
+ </Button>
+ ) : null}
+ </Flex>
+ {profilePicture ? (
+ <Slider
+ max={5}
+ min={1}
+ step={0.1}
+ value={scale}
+ sx={{ color: "accent" }}
+ onChange={(e) => setScale(e.target.valueAsNumber)}
+ />
) : null}
</Flex>
- {profilePicture ? (
- <Slider
- max={5}
- min={1}
- step={0.1}
- value={scale}
- sx={{ color: "accent" }}
- onChange={(e) => setScale(e.target.valueAsNumber)}
- />
- ) : null}
- </Flex>
- </Dialog>
- );
-}
+ </Dialog>
+ );
+ }
+);
diff --git a/apps/web/src/dialogs/email-change-dialog.tsx b/apps/web/src/dialogs/email-change-dialog.tsx
index 01a0801b5..6369d2f74 100644
--- a/apps/web/src/dialogs/email-change-dialog.tsx
+++ b/apps/web/src/dialogs/email-change-dialog.tsx
@@ -20,162 +20,162 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.
import { Flex, Text } from "@theme-ui/components";
import { useCallback, useRef, useState } from "react";
import { db } from "../common/db";
-import { Perform } from "../common/dialog-controller";
import { useTimer } from "../hooks/use-timer";
import Field from "../components/field";
import { Loading } from "../components/icons";
import Dialog from "../components/dialog";
+import { BaseDialogProps, DialogManager } from "../common/dialog-manager";
type EmailChangeState = {
newEmail: string;
password: string;
};
-export type EmailChangeDialogProps = {
- onClose: Perform;
-};
+export type EmailChangeDialogProps = BaseDialogProps<boolean>;
+export const EmailChangeDialog = DialogManager.register(
+ function EmailChangeDialog(props: EmailChangeDialogProps) {
+ const [error, setError] = useState<string>();
+ const [isLoading, setIsLoading] = useState(false);
+ const [emailChangeState, setEmailChangeState] =
+ useState<EmailChangeState>();
+ const [isSending, setIsSending] = useState(false);
+ const { elapsed, enabled, setEnabled } = useTimer(`email_change_code`, 60);
+
+ const emailRef = useRef<HTMLInputElement>(null);
+ const passwordRef = useRef<HTMLInputElement>(null);
+ const codeRef = useRef<HTMLInputElement>(null);
+
+ const sendCode = useCallback(
+ async (emailChangeState: EmailChangeState) => {
+ setIsSending(true);
+ try {
+ await db.user.sendVerificationEmail(emailChangeState.newEmail);
+
+ setEnabled(false);
+ } catch (e) {
+ const error = e as Error;
+ setError(error.message);
+ } finally {
+ setIsSending(false);
+ }
+ },
+ [setEnabled]
+ );
+
+ return (
+ <Dialog
+ isOpen={true}
+ title={"Change account email"}
+ description={
+ "Your account email will be changed without affecting your subscription or any other settings."
+ }
+ onClose={() => props.onClose(false)}
+ positiveButton={{
+ text: "Next",
+ disabled: isLoading,
+ loading: isLoading,
+ form: "changeEmailForm"
+ }}
+ negativeButton={{ text: "Cancel", onClick: () => props.onClose(false) }}
+ >
+ <Flex
+ id="changeEmailForm"
+ as="form"
+ onSubmit={async (e) => {
+ e.preventDefault();
+ try {
+ setIsLoading(true);
+ setError(undefined);
+
+ const formData = new FormData(e.target as HTMLFormElement);
+ const { password, newEmail, code } = Object.fromEntries(
+ formData.entries() as IterableIterator<[string, string]>
+ );
-export default function EmailChangeDialog(props: EmailChangeDialogProps) {
- const [error, setError] = useState<string>();
- const [isLoading, setIsLoading] = useState(false);
- const [emailChangeState, setEmailChangeState] = useState<EmailChangeState>();
- const [isSending, setIsSending] = useState(false);
- const { elapsed, enabled, setEnabled } = useTimer(`email_change_code`, 60);
-
- const emailRef = useRef<HTMLInputElement>(null);
- const passwordRef = useRef<HTMLInputElement>(null);
- const codeRef = useRef<HTMLInputElement>(null);
-
- const sendCode = useCallback(
- async (emailChangeState: EmailChangeState) => {
- setIsSending(true);
- try {
- await db.user.sendVerificationEmail(emailChangeState.newEmail);
-
- setEnabled(false);
- } catch (e) {
- const error = e as Error;
- setError(error.message);
- } finally {
- setIsSending(false);
- }
- },
- [setEnabled]
- );
-
- return (
- <Dialog
- isOpen={true}
- title={"Change account email"}
- description={
- "Your account email will be changed without affecting your subscription or any other settings."
- }
- onClose={() => props.onClose(false)}
- positiveButton={{
- text: "Next",
- disabled: isLoading,
- loading: isLoading,
- form: "changeEmailForm"
- }}
- negativeButton={{ text: "Cancel", onClick: () => props.onClose(false) }}
- >
- <Flex
- id="changeEmailForm"
- as="form"
- onSubmit={async (e) => {
- e.preventDefault();
- try {
- setIsLoading(true);
- setError(undefined);
-
- const formData = new FormData(e.target as HTMLFormElement);
- const { password, newEmail, code } = Object.fromEntries(
- formData.entries() as IterableIterator<[string, string]>
- );
-
- if (emailChangeState) {
- if (!code || code.length < 6) {
- setError("Please enter a valid verification code.");
+ if (emailChangeState) {
+ if (!code || code.length < 6) {
+ setError("Please enter a valid verification code.");
+ return;
+ }
+
+ await db.user.changeEmail(
+ emailChangeState.newEmail,
+ emailChangeState.password,
+ code
+ );
+ props.onClose(true);
return;
}
- await db.user.changeEmail(
- emailChangeState.newEmail,
- emailChangeState.password,
- code
- );
- props.onClose(true);
- return;
- }
+ if (!newEmail.trim() || !password.trim()) return;
- if (!newEmail.trim() || !password.trim()) return;
+ if (!password || !(await db.user.verifyPassword(password))) {
+ setError("Password is not correct.");
+ return;
+ }
- if (!password || !(await db.user.verifyPassword(password))) {
- setError("Password is not correct.");
- return;
+ await db.user.sendVerificationEmail(newEmail);
+ setEmailChangeState({ newEmail, password });
+ } catch (e) {
+ if (e instanceof Error) setError(e.message);
+ } finally {
+ setIsLoading(false);
}
-
- await db.user.sendVerificationEmail(newEmail);
- setEmailChangeState({ newEmail, password });
- } catch (e) {
- if (e instanceof Error) setError(e.message);
- } finally {
- setIsLoading(false);
- }
- }}
- sx={{ flexDirection: "column" }}
- >
- {emailChangeState ? (
- <Field
- inputRef={codeRef}
- id="code"
- name="code"
- label="6-digit code"
- helpText={`Enter 6-digit code sent to ${emailChangeState.newEmail}`}
- type="text"
- required
- action={{
- disabled: isSending || !enabled,
- component: (
- <Text variant={"body"}>
- {isSending ? (
- <Loading size={18} />
- ) : enabled ? (
- `Resend code`
- ) : (
- `Resend in ${elapsed}`
- )}
- </Text>
- ),
- onClick: async () => {
- await sendCode(emailChangeState);
- }
- }}
- />
- ) : (
- <>
- <Field
- inputRef={emailRef}
- id="newEmail"
- name="newEmail"
- label="New email"
- type="email"
- required
- />
+ }}
+ sx={{ flexDirection: "column" }}
+ >
+ {emailChangeState ? (
<Field
- inputRef={passwordRef}
- id="password"
- name="password"
- label="Your account password"
- type="password"
+ inputRef={codeRef}
+ id="code"
+ name="code"
+ label="6-digit code"
+ helpText={`Enter 6-digit code sent to ${emailChangeState.newEmail}`}
+ type="text"
required
+ action={{
+ disabled: isSending || !enabled,
+ component: (
+ <Text variant={"body"}>
+ {isSending ? (
+ <Loading size={18} />
+ ) : enabled ? (
+ `Resend code`
+ ) : (
+ `Resend in ${elapsed}`
+ )}
+ </Text>
+ ),
+ onClick: async () => {
+ await sendCode(emailChangeState);
+ }
+ }}
/>
- <Text variant="subBody" sx={{ mt: 1 }}>
- You will be logged out from all your other devices.
- </Text>
- </>
- )}
- {error && <Text variant="error">{error}</Text>}
- </Flex>
- </Dialog>
- );
-}
+ ) : (
+ <>
+ <Field
+ inputRef={emailRef}
+ id="newEmail"
+ name="newEmail"
+ label="New email"
+ type="email"
+ required
+ />
+ <Field
+ inputRef={passwordRef}
+ id="password"
+ name="password"
+ label="Your account password"
+ type="password"
+ required
+ />
+ <Text variant="subBody" sx={{ mt: 1 }}>
+ You will be logged out from all your other devices.
+ </Text>
+ </>
+ )}
+ {error && <Text variant="error">{error}</Text>}
+ </Flex>
+ </Dialog>
+ );
+ }
+);
diff --git a/apps/web/src/dialogs/email-verification-dialog.jsx b/apps/web/src/dialogs/email-verification-dialog.jsx
deleted file mode 100644
index c19df23aa..000000000
--- a/apps/web/src/dialogs/email-verification-dialog.jsx
+++ /dev/null
@@ -1,120 +0,0 @@
-/*
-This file is part of the Notesnook project (https://notesnook.com/)
-
-Copyright (C) 2023 Streetwriters (Private) Limited
-
-This program is free software: you can redistribute it and/or modify
-it under the terms of the GNU General Public License as published by
-the Free Software Foundation, either version 3 of the License, or
-(at your option) any later version.
-
-This program is distributed in the hope that it will be useful,
-but WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-GNU General Public License for more details.
-
-You should have received a copy of the GNU General Public License
-along with this program. If not, see <http://www.gnu.org/licenses/>.
-*/
-
-import { useEffect } from "react";
-import { Flex, Text } from "@theme-ui/components";
-import Dialog from "../components/dialog";
-import { useStore as useUserStore } from "../stores/user-store";
-import { db } from "../common/db";
-import { useState } from "react";
-import { useSessionState } from "../hooks/use-session-state";
-import Accordion from "../components/accordion";
-
-var interval = 0;
-function EmailVerificationDialog(props) {
- const user = useUserStore((store) => store.user);
- const [isSending, setIsSending] = useState(false);
- const [canSendAgain, setCanSendAgain] = useSessionState("canSendAgain", true);
- const [resetTimer, setResetTimer] = useSessionState("resetTimer", 60);
-
- useEffect(() => {
- if (!canSendAgain) {
- interval = setInterval(() => {
- setResetTimer((s) => {
- --s;
- if (s <= 0) {
- setCanSendAgain(true);
- clearInterval(interval);
- return 60;
- }
- return s;
- });
- }, 1000);
- }
- return () => {
- clearInterval(interval);
- };
- }, [canSendAgain, setResetTimer, setCanSendAgain]);
-
- if (!user) {
- props.onCancel();
- return null;
- }
- return (
- <Dialog
- isOpen={true}
- title={"Confirm your email"}
- description={
- "Check your spam folder if you haven't received an email yet."
- }
- onClose={() => props.onCancel(false)}
- positiveButton={{
- text: canSendAgain || isSending ? "Resend" : `Resend (${resetTimer})`,
- onClick: async () => {
- setIsSending(true);
- try {
- await db.user.sendVerificationEmail();
- setCanSendAgain(false);
- } catch (e) {
- console.error(e);
- } finally {
- setIsSending(false);
- }
- },
- loading: isSending,
- disabled: isSending || !canSendAgain
- }}
- negativeButton={{
- text: "Cancel",
- onClick: () => props.onCancel(true),
- disabled: isSending
- }}
- >
- <Flex sx={{ flexDirection: "column" }}>
- <Text
- as="span"
- variant="body"
- sx={{ borderRadius: "default", alignSelf: "stretch" }}
- >
- We have sent the email confirmation link at{" "}
- <Text as="b" sx={{ color: "accent" }}>
- {user.email}
- </Text>
- .
- </Text>
- <Accordion
- title={"What do I do if I am not getting the email?"}
- sx={{
- mt: 2,
- bg: "var(--background-secondary)",
- borderRadius: "default"
- }}
- >
- <Text variant={"body"} px={1} pb={1}>
- {`If you didn't get an email from us or the confirmation link isn't
- working,`}{" "}
- <b>please send us an email from your registered email address</b>{" "}
- and we will manually confirm your account.
- </Text>
- </Accordion>
- </Flex>
- </Dialog>
- );
-}
-export default EmailVerificationDialog;
diff --git a/apps/web/src/dialogs/email-verification-dialog.tsx b/apps/web/src/dialogs/email-verification-dialog.tsx
new file mode 100644
index 000000000..8d2a20125
--- /dev/null
+++ b/apps/web/src/dialogs/email-verification-dialog.tsx
@@ -0,0 +1,127 @@
+/*
+This file is part of the Notesnook project (https://notesnook.com/)
+
+Copyright (C) 2023 Streetwriters (Private) Limited
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+import { useEffect } from "react";
+import { Flex, Text } from "@theme-ui/components";
+import Dialog from "../components/dialog";
+import { useStore as useUserStore } from "../stores/user-store";
+import { db } from "../common/db";
+import { useState } from "react";
+import { useSessionState } from "../hooks/use-session-state";
+import Accordion from "../components/accordion";
+import { BaseDialogProps, DialogManager } from "../common/dialog-manager";
+
+let interval = 0;
+type EmailVerificationDialogProps = BaseDialogProps<boolean>;
+export const EmailVerificationDialog = DialogManager.register(
+ function EmailVerificationDialog(props: EmailVerificationDialogProps) {
+ const user = useUserStore((store) => store.user);
+ const [isSending, setIsSending] = useState(false);
+ const [canSendAgain, setCanSendAgain] = useSessionState(
+ "canSendAgain",
+ true
+ );
+ const [resetTimer, setResetTimer] = useSessionState("resetTimer", 60);
+
+ useEffect(() => {
+ if (!canSendAgain) {
+ interval = setInterval(() => {
+ setResetTimer((s) => {
+ --s;
+ if (s <= 0) {
+ setCanSendAgain(true);
+ clearInterval(interval);
+ return 60;
+ }
+ return s;
+ });
+ }, 1000) as unknown as number;
+ }
+ return () => {
+ clearInterval(interval);
+ };
+ }, [canSendAgain, setResetTimer, setCanSendAgain]);
+
+ if (!user) {
+ props.onClose(false);
+ return null;
+ }
+ return (
+ <Dialog
+ isOpen={true}
+ title={"Confirm your email"}
+ description={
+ "Check your spam folder if you haven't received an email yet."
+ }
+ onClose={() => props.onClose(false)}
+ positiveButton={{
+ text: canSendAgain || isSending ? "Resend" : `Resend (${resetTimer})`,
+ onClick: async () => {
+ setIsSending(true);
+ try {
+ await db.user.sendVerificationEmail();
+ setCanSendAgain(false);
+ } catch (e) {
+ console.error(e);
+ } finally {
+ setIsSending(false);
+ }
+ },
+ loading: isSending,
+ disabled: isSending || !canSendAgain
+ }}
+ negativeButton={{
+ text: "Cancel",
+ onClick: () => props.onClose(true),
+ disabled: isSending
+ }}
+ >
+ <Flex sx={{ flexDirection: "column" }}>
+ <Text
+ as="span"
+ variant="body"
+ sx={{ borderRadius: "default", alignSelf: "stretch" }}
+ >
+ We have sent the email confirmation link at{" "}
+ <Text as="b" sx={{ color: "accent" }}>
+ {user.email}
+ </Text>
+ .
+ </Text>
+ <Accordion
+ isClosed
+ title={"What do I do if I am not getting the email?"}
+ sx={{
+ mt: 2,
+ bg: "var(--background-secondary)",
+ borderRadius: "default"
+ }}
+ >
+ <Text variant={"body"} px={1} pb={1}>
+ {`If you didn't get an email from us or the confirmation link isn't
+ working,`}{" "}
+ <b>please send us an email from your registered email address</b>{" "}
+ and we will manually confirm your account.
+ </Text>
+ </Accordion>
+ </Flex>
+ </Dialog>
+ );
+ }
+);
diff --git a/apps/web/src/dialogs/feature-dialog.tsx b/apps/web/src/dialogs/feature-dialog.tsx
index 822fff3a8..1fb4d082e 100644
--- a/apps/web/src/dialogs/feature-dialog.tsx
+++ b/apps/web/src/dialogs/feature-dialog.tsx
@@ -25,6 +25,7 @@ import Config from "../utils/config";
import { useEffect } from "react";
import { ArrowRight, Checkmark, Icon, Warn } from "../components/icons";
+import { BaseDialogProps, DialogManager } from "../common/dialog-manager";
type CallToAction = {
title: string;
@@ -113,12 +114,13 @@ const features: Record<FeatureKeys, Feature> = {
}
};
-type FeatureDialogProps = {
+type FeatureDialogProps = BaseDialogProps<boolean> & {
featureName: FeatureKeys;
- onClose: (result: boolean) => void;
};
-function FeatureDialog(props: FeatureDialogProps) {
+export const FeatureDialog = DialogManager.register(function FeatureDialog(
+ props: FeatureDialogProps
+) {
const { featureName, onClose } = props;
const feature = features[featureName];
@@ -178,8 +180,7 @@ function FeatureDialog(props: FeatureDialogProps) {
</Flex>
</Dialog>
);
-}
-export default FeatureDialog;
+});
type CodeProps = { text: string; href?: string };
export function Code(props: CodeProps) {
diff --git a/apps/web/src/dialogs/image-picker-dialog.tsx b/apps/web/src/dialogs/image-picker-dialog.tsx
index b502f4b13..953e1badf 100644
--- a/apps/web/src/dialogs/image-picker-dialog.tsx
+++ b/apps/web/src/dialogs/image-picker-dialog.tsx
@@ -18,15 +18,14 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import { useEffect, useState } from "react";
-import { Perform } from "../common/dialog-controller";
import Dialog from "../components/dialog";
import { ScrollContainer } from "@notesnook/ui";
import { Flex, Image, Label, Text } from "@theme-ui/components";
import { formatBytes } from "@notesnook/common";
import { compressImage } from "../utils/image-compressor";
+import { BaseDialogProps, DialogManager } from "../common/dialog-manager";
-export type ImagePickerDialogProps = {
- onClose: Perform<false | File[]>;
+export type ImagePickerDialogProps = BaseDialogProps<false | File[]> & {
images: File[];
};
class FileWithURI extends File {
@@ -41,106 +40,110 @@ class FileWithURI extends File {
}
}
-export default function ImagePickerDialog(props: ImagePickerDialogProps) {
- const [images, setImages] = useState<FileWithURI[]>([]);
- const [selectedIndex, setSelectedIndex] = useState(0);
- const [compress, setCompress] = useState(true);
- const selectedImage = images[selectedIndex];
+export const ImagePickerDialog = DialogManager.register(
+ function ImagePickerDialog(props: ImagePickerDialogProps) {
+ const [images, setImages] = useState<FileWithURI[]>([]);
+ const [selectedIndex, setSelectedIndex] = useState(0);
+ const [compress, setCompress] = useState(true);
+ const selectedImage = images[selectedIndex];
- useEffect(() => {
- (async function () {
- const images: FileWithURI[] = [];
- for (const image of props.images) {
- const compressed = compress
- ? await compressImage(image, {
- maxWidth: (naturalWidth) => Math.min(1920, naturalWidth * 0.7),
- width: (naturalWidth) => naturalWidth,
- height: (_, naturalHeight) => naturalHeight,
- resize: "contain",
- quality: 0.7
+ useEffect(() => {
+ (async function () {
+ const images: FileWithURI[] = [];
+ for (const image of props.images) {
+ const compressed = compress
+ ? await compressImage(image, {
+ maxWidth: (naturalWidth) => Math.min(1920, naturalWidth * 0.7),
+ width: (naturalWidth) => naturalWidth,
+ height: (_, naturalHeight) => naturalHeight,
+ resize: "contain",
+ quality: 0.7
+ })
+ : image;
+ images.push(
+ new FileWithURI([compressed], image.name, {
+ lastModified: image.lastModified,
+ type: image.type
})
- : image;
- images.push(
- new FileWithURI([compressed], image.name, {
- lastModified: image.lastModified,
- type: image.type
- })
- );
- }
- setImages(images);
- })();
- }, [props.images, compress]);
+ );
+ }
+ setImages(images);
+ })();
+ }, [props.images, compress]);
- useEffect(() => {
- return () => {
- images.forEach((i) => URL.revokeObjectURL(i.uri));
- };
- }, [images]);
+ useEffect(() => {
+ return () => {
+ images.forEach((i) => URL.revokeObjectURL(i.uri));
+ };
+ }, [images]);
- return (
- <Dialog
- isOpen={true}
- onClose={() => props.onClose(false)}
- positiveButton={{
- text: "Insert",
- onClick: () => props.onClose(images)
- }}
- negativeButton={{ text: "Cancel", onClick: () => props.onClose(false) }}
- >
- {selectedImage && (
- <Flex sx={{ flexDirection: "column", alignItems: "center", mt: 4 }}>
- <Image
- src={selectedImage.uri}
- sx={{
- maxHeight: 250,
- objectFit: "contain",
- alignSelf: "center",
- borderRadius: "default"
- }}
- />
- <Text variant="subBody" sx={{ my: 2 }}>
- {selectedImage.name} ({formatBytes(selectedImage.size)})
- </Text>
- </Flex>
- )}
- {images.length > 1 ? (
- <ScrollContainer style={{ display: "flex" }}>
- {images.map((image, index) => (
+ return (
+ <Dialog
+ isOpen={true}
+ onClose={() => props.onClose(false)}
+ positiveButton={{
+ text: "Insert",
+ onClick: () => props.onClose(images)
+ }}
+ negativeButton={{ text: "Cancel", onClick: () => props.onClose(false) }}
+ >
+ {selectedImage && (
+ <Flex sx={{ flexDirection: "column", alignItems: "center", mt: 4 }}>
<Image
- key={image.name + image.size}
- src={image.uri}
+ src={selectedImage.uri}
sx={{
- flexShrink: 0,
- height: "55px",
- width: "55px",
+ maxHeight: 250,
objectFit: "contain",
- border:
- selectedIndex === index
- ? "2px solid var(--accent)"
- : "2px solid transparent",
+ alignSelf: "center",
borderRadius: "default"
}}
- onClick={() => setSelectedIndex(index)}
/>
- ))}
- </ScrollContainer>
- ) : null}
+ <Text variant="subBody" sx={{ my: 2 }}>
+ {selectedImage.name} ({formatBytes(selectedImage.size)})
+ </Text>
+ </Flex>
+ )}
+ {images.length > 1 ? (
+ <ScrollContainer style={{ display: "flex" }}>
+ {images.map((image, index) => (
+ <Image
+ key={image.name + image.size}
+ src={image.uri}
+ sx={{
+ flexShrink: 0,
+ height: "55px",
+ width: "55px",
+ objectFit: "contain",
+ border:
+ selectedIndex === index
+ ? "2px solid var(--accent)"
+ : "2px solid transparent",
+ borderRadius: "default"
+ }}
+ onClick={() => setSelectedIndex(index)}
+ />
+ ))}
+ </ScrollContainer>
+ ) : null}
- <Label variant="text.body" sx={{ mt: 2 }}>
- <input
- type="checkbox"
- style={{
- accentColor: "var(--accent)",
- marginRight: 1,
- width: 14,
- height: 14
- }}
- defaultChecked={compress}
- checked={compress}
- onChange={() => setCompress((s) => !s)}
- />
- <span style={{ marginLeft: 5 }}>Enable compression (recommended)</span>
- </Label>
- </Dialog>
- );
-}
+ <Label variant="text.body" sx={{ mt: 2 }}>
+ <input
+ type="checkbox"
+ style={{
+ accentColor: "var(--accent)",
+ marginRight: 1,
+ width: 14,
+ height: 14
+ }}
+ defaultChecked={compress}
+ checked={compress}
+ onChange={() => setCompress((s) => !s)}
+ />
+ <span style={{ marginLeft: 5 }}>
+ Enable compression (recommended)
+ </span>
+ </Label>
+ </Dialog>
+ );
+ }
+);
diff --git a/apps/web/src/dialogs/index.ts b/apps/web/src/dialogs/index.ts
deleted file mode 100644
index 1a0472f3e..000000000
--- a/apps/web/src/dialogs/index.ts
+++ /dev/null
@@ -1,97 +0,0 @@
-/*
-This file is part of the Notesnook project (https://notesnook.com/)
-
-Copyright (C) 2023 Streetwriters (Private) Limited
-
-This program is free software: you can redistribute it and/or modify
-it under the terms of the GNU General Public License as published by
-the Free Software Foundation, either version 3 of the License, or
-(at your option) any later version.
-
-This program is distributed in the hope that it will be useful,
-but WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-GNU General Public License for more details.
-
-You should have received a copy of the GNU General Public License
-along with this program. If not, see <http://www.gnu.org/licenses/>.
-*/
-
-import React from "react";
-import SettingsDialog from "./settings";
-
-const AddNotebookDialog = React.lazy(() => import("./add-notebook-dialog"));
-const BuyDialog = React.lazy(() => import("./buy-dialog"));
-const Confirm = React.lazy(() => import("./confirm"));
-const EmailVerificationDialog = React.lazy(
- () => import("./email-verification-dialog")
-);
-const LoadingDialog = React.lazy(() => import("./loading-dialog"));
-const ProgressDialog = React.lazy(() => import("./progress-dialog"));
-const MoveDialog = React.lazy(() => import("./move-note-dialog"));
-const PasswordDialog = React.lazy(() => import("./password-dialog"));
-const RecoveryKeyDialog = React.lazy(() => import("./recovery-key-dialog"));
-const ItemDialog = React.lazy(() => import("./item-dialog"));
-const FeatureDialog = React.lazy(() => import("./feature-dialog"));
-const ReminderDialog = React.lazy(() => import("./reminder-dialog"));
-const AddReminderDialog = React.lazy(() => import("./add-reminder-dialog"));
-const ReminderPreviewDialog = React.lazy(
- () => import("./reminder-preview-dialog")
-);
-const AnnouncementDialog = React.lazy(() => import("./announcement-dialog"));
-const IssueDialog = React.lazy(() => import("./issue-dialog"));
-const MultifactorDialog = React.lazy(() => import("./mfa/multi-factor-dialog"));
-const RecoveryCodesDialog = React.lazy(
- () => import("./mfa/recovery-code-dialog")
-);
-// import { MultifactorDialog, RecoveryCodesDialog } from "./multi-factor-dialog";
-const OnboardingDialog = React.lazy(() => import("./onboarding-dialog"));
-const AttachmentsDialog = React.lazy(() => import("./attachments-dialog"));
-const Prompt = React.lazy(() => import("./prompt"));
-const MigrationDialog = React.lazy(() => import("./migration-dialog"));
-const EmailChangeDialog = React.lazy(() => import("./email-change-dialog"));
-const AddTagsDialog = React.lazy(() => import("./add-tags-dialog"));
-const ThemeDetailsDialog = React.lazy(() => import("./theme-details-dialog"));
-const BackupPasswordDialog = React.lazy(
- () => import("./backup-password-dialog")
-);
-const CreateColorDialog = React.lazy(() => import("./create-color-dialog"));
-const EditProfilePictureDialog = React.lazy(
- () => import("./edit-profile-picture-dialog")
-);
-const ImagePickerDialog = React.lazy(() => import("./image-picker-dialog"));
-const NoteLinkingDialog = React.lazy(() => import("./note-linking-dialog"));
-
-export const Dialogs = {
- AddNotebookDialog,
- BuyDialog,
- Confirm,
- Prompt,
- EmailVerificationDialog,
- LoadingDialog,
- MoveDialog,
- PasswordDialog,
- RecoveryKeyDialog,
- ItemDialog,
- FeatureDialog,
- ProgressDialog,
- ReminderDialog,
- AnnouncementDialog,
- IssueDialog,
- MultifactorDialog,
- RecoveryCodesDialog,
- OnboardingDialog,
- AttachmentsDialog,
- MigrationDialog,
- AddReminderDialog,
- ReminderPreviewDialog,
- EmailChangeDialog,
- AddTagsDialog,
- SettingsDialog,
- ThemeDetailsDialog,
- BackupPasswordDialog,
- CreateColorDialog,
- EditProfilePictureDialog,
- ImagePickerDialog,
- NoteLinkingDialog
-};
diff --git a/apps/web/src/dialogs/issue-dialog.tsx b/apps/web/src/dialogs/issue-dialog.tsx
index 3c77d71d2..2c234aab4 100644
--- a/apps/web/src/dialogs/issue-dialog.tsx
+++ b/apps/web/src/dialogs/issue-dialog.tsx
@@ -23,13 +23,14 @@ import Field from "../components/field";
import Dialog from "../components/dialog";
import platform from "platform";
import { useState } from "react";
-import { confirm, Perform } from "../common/dialog-controller";
import { isUserPremium } from "../hooks/use-is-user-premium";
import { writeText } from "clipboard-polyfill";
import { store as userstore } from "../stores/user-store";
import { ErrorText } from "../components/error-text";
import { Debug } from "@notesnook/core/dist/api/debug";
+import { ConfirmDialog } from "./confirm";
+import { BaseDialogProps, DialogManager } from "../common/dialog-manager";
const PLACEHOLDERS = {
title: "Briefly describe what happened",
@@ -43,10 +44,10 @@ For example things like:
This is all optional, of course.`
};
-type IssueDialogProps = {
- onClose: Perform;
-};
-function IssueDialog(props: IssueDialogProps) {
+type IssueDialogProps = BaseDialogProps<boolean>;
+export const IssueDialog = DialogManager.register(function IssueDialog(
+ props: IssueDialogProps
+) {
const [isSubmitting, setIsSubmitting] = useState(false);
const [error, setError] = useState<string>();
@@ -143,12 +144,10 @@ function IssueDialog(props: IssueDialogProps) {
</Flex>
</Dialog>
);
-}
-
-export default IssueDialog;
+});
function showIssueReportedDialog({ url }: { url: string }) {
- return confirm({
+ return ConfirmDialog.show({
title: "Thank you for reporting!",
positiveButtonText: "Copy link",
message: `You can track your bug report at [${url}](${url}).
diff --git a/apps/web/src/dialogs/item-dialog.tsx b/apps/web/src/dialogs/item-dialog.tsx
index 5bc1b2911..c0c6a1675 100644
--- a/apps/web/src/dialogs/item-dialog.tsx
+++ b/apps/web/src/dialogs/item-dialog.tsx
@@ -20,18 +20,24 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.
import { Box } from "@theme-ui/components";
import Dialog from "../components/dialog";
import Field from "../components/field";
-import { Perform } from "../common/dialog-controller";
import { useState } from "react";
import { ErrorText } from "../components/error-text";
+import { BaseDialogProps, DialogManager } from "../common/dialog-manager";
+import { db } from "../common/db";
+import { showToast } from "../utils/toast";
+import { useStore as useTagStore } from "../stores/tag-store";
+import { useStore as useNoteStore } from "../stores/note-store";
+import { useStore as useAppStore } from "../stores/app-store";
+import { Color, Tag } from "@notesnook/core";
-type ItemDialogProps = {
+type ItemDialogProps = BaseDialogProps<false | string> & {
title: string;
subtitle?: string;
- onClose: Perform;
- onAction: (title: string) => Promise<void>;
defaultValue?: string;
};
-function ItemDialog(props: ItemDialogProps) {
+export const ItemDialog = DialogManager.register(function ItemDialog(
+ props: ItemDialogProps
+) {
const [error, setError] = useState<Error>();
return (
@@ -58,7 +64,7 @@ function ItemDialog(props: ItemDialogProps) {
const title = formData.get("title");
if (!title) return;
try {
- await props.onAction(title as string);
+ await props.onClose(title as string);
} catch (e) {
if (e instanceof Error) {
setError(e);
@@ -79,6 +85,47 @@ function ItemDialog(props: ItemDialogProps) {
</Box>
</Dialog>
);
-}
+});
-export default ItemDialog;
+export const CreateTagDialog = {
+ show: () =>
+ ItemDialog.show({
+ title: "Create tag",
+ subtitle: "You can create as many tags as you want."
+ }).then(async (title) => {
+ if (!title) return;
+ await db.tags.add({ title });
+ showToast("success", "Tag created!");
+ useTagStore.getState().refresh();
+ })
+};
+
+export const EditTagDialog = {
+ show: (tag: Tag) =>
+ ItemDialog.show({
+ title: "Edit tag",
+ subtitle: `You are editing #${tag.title}.`,
+ defaultValue: tag.title
+ }).then(async (title) => {
+ if (!title) return;
+ await db.tags.add({ id: tag.id, title });
+ showToast("success", "Tag edited!");
+ await useTagStore.getState().refresh();
+ await useNoteStore.getState().refresh();
+ await useAppStore.getState().refreshNavItems();
+ })
+};
+
+export const RenameColorDialog = {
+ show: (color: Color) =>
+ ItemDialog.show({
+ title: "Rename color",
+ subtitle: `You are renaming color ${color.title}.`,
+ defaultValue: color.title
+ }).then(async (title) => {
+ if (!title) return;
+ await db.colors.add({ id: color.id, title });
+ showToast("success", "Color renamed!");
+ useAppStore.getState().refreshNavItems();
+ })
+};
diff --git a/apps/web/src/dialogs/mfa/multi-factor-dialog.tsx b/apps/web/src/dialogs/mfa/multi-factor-dialog.tsx
index c33ba9773..191e24593 100644
--- a/apps/web/src/dialogs/mfa/multi-factor-dialog.tsx
+++ b/apps/web/src/dialogs/mfa/multi-factor-dialog.tsx
@@ -18,7 +18,6 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import { useState } from "react";
-import { Perform } from "../../common/dialog-controller";
import Dialog from "../../components/dialog";
import {
AuthenticatorOnNext,
@@ -31,65 +30,67 @@ import {
import { Authenticator, OnNextFunction } from "./types";
import { ErrorText } from "../../components/error-text";
import { AuthenticatorType } from "@notesnook/core";
+import { BaseDialogProps, DialogManager } from "../../common/dialog-manager";
-type MultifactorDialogProps = {
- onClose: Perform;
+type MultifactorDialogProps = BaseDialogProps<boolean> & {
primaryMethod?: AuthenticatorType;
};
-export default function MultifactorDialog(props: MultifactorDialogProps) {
- const { onClose, primaryMethod } = props;
- const [step, setStep] = useState<
- | Step<AuthenticatorOnNext>
- | Step<AuthenticatorTypeOnNext>
- | FallbackStep<OnNextFunction>
- >(primaryMethod ? fallbackSteps.choose(primaryMethod) : steps.choose());
- const [error, setError] = useState<string>();
+export const MultifactorDialog = DialogManager.register(
+ function MultifactorDialog(props: MultifactorDialogProps) {
+ const { onClose, primaryMethod } = props;
+ const [step, setStep] = useState<
+ | Step<AuthenticatorOnNext>
+ | Step<AuthenticatorTypeOnNext>
+ | FallbackStep<OnNextFunction>
+ >(primaryMethod ? fallbackSteps.choose(primaryMethod) : steps.choose());
+ const [error, setError] = useState<string>();
- if (!step) return null;
- return (
- <Dialog
- isOpen={true}
- title={step.title}
- description={step.description}
- width={500}
- positiveButton={
- step.next
- ? {
- text: "Continue",
- form: "2faForm"
- }
- : null
- }
- negativeButton={
- step.cancellable
- ? {
- text: "Cancel",
- onClick: () => props.onClose(false)
- }
- : null
- }
- >
- {step.component && (
- <step.component
- onNext={(arg: AuthenticatorType | Authenticator) => {
- if (!step.next) return onClose(true);
+ if (!step) return null;
+ return (
+ <Dialog
+ isOpen={true}
+ title={step.title}
+ description={step.description}
+ width={500}
+ positiveButton={
+ step.next
+ ? {
+ text: "Continue",
+ form: "2faForm"
+ }
+ : null
+ }
+ negativeButton={
+ step.cancellable
+ ? {
+ text: "Cancel",
+ onClick: () => props.onClose(false)
+ }
+ : null
+ }
+ >
+ {step.component && (
+ <step.component
+ onNext={(arg: AuthenticatorType | Authenticator) => {
+ if (!step.next) return onClose(true);
- const nextStep =
- step.next !== "recoveryCodes" && primaryMethod
- ? fallbackSteps[step.next](
- arg as AuthenticatorType & Authenticator,
- primaryMethod
- )
- : steps[step.next](arg as AuthenticatorType & Authenticator);
+ const nextStep =
+ step.next !== "recoveryCodes" && primaryMethod
+ ? fallbackSteps[step.next](
+ arg as AuthenticatorType & Authenticator,
+ primaryMethod
+ )
+ : steps[step.next](arg as AuthenticatorType & Authenticator);
- setStep(nextStep);
- }}
- onError={setError}
- onClose={onClose}
- />
- )}
- <ErrorText error={error} />
- </Dialog>
- );
-}
+ setStep(nextStep);
+ }}
+ onError={setError}
+ onClose={onClose}
+ />
+ )}
+ <ErrorText error={error} />
+ </Dialog>
+ );
+ }
+);
diff --git a/apps/web/src/dialogs/mfa/recovery-code-dialog.tsx b/apps/web/src/dialogs/mfa/recovery-code-dialog.tsx
index 3dccfd3fa..82f14f0cf 100644
--- a/apps/web/src/dialogs/mfa/recovery-code-dialog.tsx
+++ b/apps/web/src/dialogs/mfa/recovery-code-dialog.tsx
@@ -18,37 +18,38 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import { useState } from "react";
-import { Perform } from "../../common/dialog-controller";
import Dialog from "../../components/dialog";
import { steps } from "./steps";
import { ErrorText } from "../../components/error-text";
import { AuthenticatorType } from "@notesnook/core";
+import { BaseDialogProps, DialogManager } from "../../common/dialog-manager";
-type RecoveryCodesDialogProps = {
- onClose: Perform;
+type RecoveryCodesDialogProps = BaseDialogProps<boolean> & {
primaryMethod: AuthenticatorType;
};
-export default function RecoveryCodesDialog(props: RecoveryCodesDialogProps) {
- const { onClose, primaryMethod } = props;
- const [error, setError] = useState<string>();
- const step = steps.recoveryCodes(primaryMethod);
-
- return (
- <Dialog
- isOpen={true}
- title={step.title}
- description={step.description}
- width={500}
- positiveButton={{
- text: "Okay",
- onClick: () => onClose(true)
- }}
- >
- {step.component && (
- <step.component onNext={() => {}} onError={setError} />
- )}
- <ErrorText error={error} />
- </Dialog>
- );
-}
+export const RecoveryCodesDialog = DialogManager.register(
+ function RecoveryCodesDialog(props: RecoveryCodesDialogProps) {
+ const { onClose, primaryMethod } = props;
+ const [error, setError] = useState<string>();
+ const step = steps.recoveryCodes(primaryMethod);
+
+ return (
+ <Dialog
+ isOpen={true}
+ title={step.title}
+ description={step.description}
+ width={500}
+ positiveButton={{
+ text: "Okay",
+ onClick: () => onClose(true)
+ }}
+ >
+ {step.component && (
+ <step.component onNext={() => {}} onError={setError} />
+ )}
+ <ErrorText error={error} />
+ </Dialog>
+ );
+ }
+);
diff --git a/apps/web/src/dialogs/mfa/steps.tsx b/apps/web/src/dialogs/mfa/steps.tsx
index 08d42ed93..df713f69b 100644
--- a/apps/web/src/dialogs/mfa/steps.tsx
+++ b/apps/web/src/dialogs/mfa/steps.tsx
@@ -55,9 +55,9 @@ import {
StepComponentProps,
OnNextFunction
} from "./types";
-import { showMultifactorDialog } from "../../common/dialog-controller";
import { ErrorText } from "../../components/error-text";
import { AuthenticatorType } from "@notesnook/core";
+import { MultifactorDialog } from "./multi-factor-dialog";
const QRCode = React.lazy(() => import("../../re-exports/react-qrcode-logo"));
@@ -734,7 +734,9 @@ function TwoFactorEnabled(props: TwoFactorEnabledProps) {
onClick={() => {
props.onClose && props.onClose(true);
setTimeout(async () => {
- await showMultifactorDialog(props.authenticatorType);
+ await MultifactorDialog.show({
+ primaryMethod: props.authenticatorType
+ });
}, 100);
}}
>
diff --git a/apps/web/src/dialogs/mfa/types.ts b/apps/web/src/dialogs/mfa/types.ts
index 46ff648f0..0a8dd95ca 100644
--- a/apps/web/src/dialogs/mfa/types.ts
+++ b/apps/web/src/dialogs/mfa/types.ts
@@ -18,7 +18,6 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import { AuthenticatorType } from "@notesnook/core";
-import { Perform } from "../../common/dialog-controller";
import { Icon } from "../../components/icons";
export type Authenticator = {
@@ -31,7 +30,7 @@ export type Authenticator = {
export type StepComponentProps<T extends OnNextFunction> = {
onNext: T;
- onClose?: Perform;
+ onClose?: (result: boolean) => void;
onError?: (error: string) => void;
};
diff --git a/apps/web/src/dialogs/migration-dialog.tsx b/apps/web/src/dialogs/migration-dialog.tsx
index f3a991483..c23d92948 100644
--- a/apps/web/src/dialogs/migration-dialog.tsx
+++ b/apps/web/src/dialogs/migration-dialog.tsx
@@ -22,11 +22,10 @@ import { Text } from "@theme-ui/components";
import { useCallback, useEffect, useState } from "react";
import { createBackup } from "../common";
import { db } from "../common/db";
-import { Perform } from "../common/dialog-controller";
import { TaskManager } from "../common/task-manager";
-
import Dialog from "../components/dialog";
import { ErrorText } from "../components/error-text";
+import { BaseDialogProps, DialogManager } from "../common/dialog-manager";
type MigrationProgressEvent = {
collection: string;
@@ -34,11 +33,10 @@ type MigrationProgressEvent = {
current: number;
};
-export type MigrationDialogProps = {
- onClose: Perform;
-};
-
-export default function MigrationDialog(props: MigrationDialogProps) {
+export type MigrationDialogProps = BaseDialogProps<boolean>;
+export const MigrationDialog = DialogManager.register(function MigrationDialog(
+ props: MigrationDialogProps
+) {
const [error, setError] = useState<Error>();
const [isProcessing, setIsProcessing] = useState(false);
@@ -133,4 +131,4 @@ export default function MigrationDialog(props: MigrationDialogProps) {
</Text>
</Dialog>
);
-}
+});
diff --git a/apps/web/src/dialogs/move-note-dialog.tsx b/apps/web/src/dialogs/move-note-dialog.tsx
index 6c42b0c14..ed00d7eab 100644
--- a/apps/web/src/dialogs/move-note-dialog.tsx
+++ b/apps/web/src/dialogs/move-note-dialog.tsx
@@ -34,7 +34,6 @@ import Dialog from "../components/dialog";
import { useStore } from "../stores/notebook-store";
import { store as noteStore } from "../stores/note-store";
import { store as notebookStore } from "../stores/notebook-store";
-import { Perform, showAddNotebookDialog } from "../common/dialog-controller";
import { showToast } from "../utils/toast";
import { isMac } from "../utils/platform";
import { create } from "zustand";
@@ -48,8 +47,10 @@ import {
import { FlexScrollContainer } from "../components/scroll-container";
import { pluralize } from "@notesnook/common";
import Field from "../components/field";
+import { AddNotebookDialog } from "./add-notebook-dialog";
+import { BaseDialogProps, DialogManager } from "../common/dialog-manager";
-type MoveDialogProps = { onClose: Perform; noteIds: string[] };
+type MoveNoteDialogProps = BaseDialogProps<boolean> & { noteIds: string[] };
type NotebookReference = {
id: string;
new: boolean;
@@ -69,7 +70,10 @@ export const useSelectionStore = create<ISelectionStore>((set) => ({
setIsMultiselect: (isMultiselect) => set({ isMultiselect })
}));
-function MoveDialog({ onClose, noteIds }: MoveDialogProps) {
+export const MoveNoteDialog = DialogManager.register(function MoveNoteDialog({
+ onClose,
+ noteIds
+}: MoveNoteDialogProps) {
const setSelected = useSelectionStore((store) => store.setSelected);
const setIsMultiselect = useSelectionStore((store) => store.setIsMultiselect);
const isMultiselect = useSelectionStore((store) => store.isMultiselect);
@@ -284,6 +288,7 @@ function MoveDialog({ onClose, noteIds }: MoveDialogProps) {
isExpanded={props.context.isExpanded || false}
toggle={props.context.toggleExpandedState}
onCreateItem={() => {
+ console.log([props.item.index]);
reloadItem.current?.([props.item.index]);
treeRef.current?.expandItem(
props.item.index,
@@ -318,10 +323,12 @@ function MoveDialog({ onClose, noteIds }: MoveDialogProps) {
variant="secondary"
sx={{ mt: 2 }}
onClick={() =>
- showAddNotebookDialog().then(() =>
- db.notebooks.roots
- .ids(db.settings.getGroupOptions("notebooks"))
- .then((ids) => setNotebooks(ids))
+ AddNotebookDialog.show({}).then((res) =>
+ res
+ ? db.notebooks.roots
+ .ids(db.settings.getGroupOptions("notebooks"))
+ .then((ids) => setNotebooks(ids))
+ : null
)
}
>
@@ -331,7 +338,8 @@ function MoveDialog({ onClose, noteIds }: MoveDialogProps) {
)}
</Dialog>
);
-}
+});
+
function calculateIndentation(
expandable: boolean,
depth: number,
@@ -443,7 +451,7 @@ function NotebookItem(props: {
title="New notebook"
onClick={async (e) => {
e.stopPropagation();
- await showAddNotebookDialog(notebook.id);
+ await AddNotebookDialog.show({ parentId: notebook.id });
onCreateItem();
}}
/>
@@ -462,8 +470,6 @@ function TopicSelectionIndicator({ notebook }: { notebook: Notebook }) {
return <Circle size={8} color="accent" sx={{ mr: 1 }} />;
}
-export default MoveDialog;
-
function SelectedCheck({
item,
size = 20,
diff --git a/apps/web/src/dialogs/note-linking-dialog.tsx b/apps/web/src/dialogs/note-linking-dialog.tsx
index e474af925..f4653f59a 100644
--- a/apps/web/src/dialogs/note-linking-dialog.tsx
+++ b/apps/web/src/dialogs/note-linking-dialog.tsx
@@ -17,7 +17,6 @@ You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
-import { Perform } from "../common/dialog-controller";
import Field from "../components/field";
import Dialog from "../components/dialog";
import { useState } from "react";
@@ -35,211 +34,212 @@ import { LinkAttributes } from "@notesnook/editor/dist/extensions/link";
import { NoteResolvedData, ResolvedItem } from "@notesnook/common";
import { Lock } from "../components/icons";
import { ellipsize } from "@notesnook/core/dist/utils/content-block";
+import { BaseDialogProps, DialogManager } from "../common/dialog-manager";
-export type NoteLinkingDialogProps = {
+export type NoteLinkingDialogProps = BaseDialogProps<LinkAttributes | false> & {
attributes?: LinkAttributes;
- onClose: Perform;
- onDone: Perform<LinkAttributes>;
};
const HEADING_TYPES = ["h1", "h2", "h3", "h4", "h5", "h6"];
-export default function NoteLinkingDialog(props: NoteLinkingDialogProps) {
- const { attributes } = props;
- const [notes, setNotes] = useState<VirtualizedGrouping<NoteType>>();
- const [selectedNote, setSelectedNote] = useState<NoteType>();
- const [isNoteLocked, setIsNoteLocked] = useState(false);
- const [blocks, setBlocks] = useState<ContentBlock[]>([]);
- const [filteredBlocks, setFilteredBlocks] = useState<
- ContentBlock[] | undefined
- >();
+export const NoteLinkingDialog = DialogManager.register(
+ function NoteLinkingDialog(props: NoteLinkingDialogProps) {
+ const { attributes } = props;
+ const [notes, setNotes] = useState<VirtualizedGrouping<NoteType>>();
+ const [selectedNote, setSelectedNote] = useState<NoteType>();
+ const [isNoteLocked, setIsNoteLocked] = useState(false);
+ const [blocks, setBlocks] = useState<ContentBlock[]>([]);
+ const [filteredBlocks, setFilteredBlocks] = useState<
+ ContentBlock[] | undefined
+ >();
- return (
- <Dialog
- isOpen={true}
- title={attributes ? "Edit internal link" : "Link to note"}
- width={500}
- onClose={() => props.onClose(false)}
- onOpen={async () => {
- setNotes(
- await db.notes.all.sorted(db.settings.getGroupOptions("home"))
- );
- }}
- positiveButton={{
- text: "Insert link",
- disabled: !selectedNote,
- onClick: () =>
- selectedNote
- ? props.onDone({
- title: selectedNote.title,
- href: createInternalLink("note", selectedNote.id)
- })
- : null
- }}
- negativeButton={{ text: "Cancel", onClick: () => props.onClose(false) }}
- noScroll
- >
- <Flex variant="columnFill" sx={{ mx: 3, overflow: "hidden" }}>
- {selectedNote ? (
- <>
- <Field
- autoFocus
- placeholder="Type # to only search headings"
- sx={{ mx: 0 }}
- onChange={async (e) => {
- const query = e.target.value.trim().toLowerCase();
- if (!query) {
- setFilteredBlocks(undefined);
- } else {
- setFilteredBlocks(
- query.startsWith("#")
- ? blocks.filter(
- (v) =>
- HEADING_TYPES.includes(v.type) &&
+ return (
+ <Dialog
+ isOpen={true}
+ title={attributes ? "Edit internal link" : "Link to note"}
+ width={500}
+ onClose={() => props.onClose(false)}
+ onOpen={async () => {
+ setNotes(
+ await db.notes.all.sorted(db.settings.getGroupOptions("home"))
+ );
+ }}
+ positiveButton={{
+ text: "Insert link",
+ disabled: !selectedNote,
+ onClick: () =>
+ selectedNote
+ ? props.onDone({
+ title: selectedNote.title,
+ href: createInternalLink("note", selectedNote.id)
+ })
+ : null
+ }}
+ negativeButton={{ text: "Cancel", onClick: () => props.onClose(false) }}
+ noScroll
+ >
+ <Flex variant="columnFill" sx={{ mx: 3, overflow: "hidden" }}>
+ {selectedNote ? (
+ <>
+ <Field
+ autoFocus
+ placeholder="Type # to only search headings"
+ sx={{ mx: 0 }}
+ onChange={async (e) => {
+ const query = e.target.value.trim().toLowerCase();
+ if (!query) {
+ setFilteredBlocks(undefined);
+ } else {
+ setFilteredBlocks(
+ query.startsWith("#")
+ ? blocks.filter(
+ (v) =>
+ HEADING_TYPES.includes(v.type) &&
+ v.content.toLowerCase().includes(query)
+ )
+ : blocks.filter((v) =>
v.content.toLowerCase().includes(query)
- )
- : blocks.filter((v) =>
- v.content.toLowerCase().includes(query)
- )
- );
- }
- }}
- />
- <Button
- variant="accentSecondary"
- sx={{ mt: 1, textAlign: "left" }}
- onClick={() => {
- setSelectedNote(undefined);
- setIsNoteLocked(false);
- setFilteredBlocks(undefined);
- setBlocks([]);
- }}
- >
- Selected note: {selectedNote.title} (click to deselect)
- </Button>
- {isNoteLocked ? (
- <Text variant="body" sx={{ mt: 1 }}>
- Linking to a specific block is not available for locked notes.
- </Text>
- ) : blocks.length <= 0 ? (
- <Text variant="body" sx={{ mt: 1 }}>
- There are no blocks in this note.
- </Text>
- ) : null}
- <ScrollContainer>
- <VirtualizedList
- items={filteredBlocks || blocks}
- estimatedSize={34}
- mode="dynamic"
- itemGap={5}
- getItemKey={(i) => blocks[i].id}
- mt={1}
- renderItem={({ item }) => (
- <Button
- variant="menuitem"
- sx={{
- p: 1,
- width: "100%",
- textAlign: "left",
- display: "flex",
- justifyContent: "space-between",
- alignItems: "center",
- borderBottom: "1px solid var(--border)"
- }}
- onClick={() => {
- props.onDone({
- title: selectedNote.title,
- href: createInternalLink("note", selectedNote.id, {
- blockId: item.id
- })
- });
- }}
- >
- <Text
- variant="body"
- sx={{ fontFamily: "monospace", whiteSpace: "pre-wrap" }}
- >
- {ellipsize(item.content, 200, "end").trim() ||
- "(empty block)"}
- </Text>
- <Text
- variant="subBody"
- sx={{
- bg: "background-secondary",
- flexShrink: 0,
- p: "small",
- px: 1,
- borderRadius: "default",
- alignSelf: "flex-start"
- }}
- >
- {item.type.toUpperCase()}
- </Text>
- </Button>
- )}
+ )
+ );
+ }
+ }}
/>
- </ScrollContainer>
- </>
- ) : (
- <>
- <Field
- autoFocus
- placeholder="Search for a note to link to..."
- sx={{ mx: 0 }}
- onChange={async (e) => {
- const query = e.target.value.trim();
- setNotes(
- query
- ? await db.lookup.notes(e.target.value).sorted()
- : await db.notes.all.sorted(
- db.settings.getGroupOptions("home")
- )
- );
- }}
- />
- {notes && (
+ <Button
+ variant="accentSecondary"
+ sx={{ mt: 1, textAlign: "left" }}
+ onClick={() => {
+ setSelectedNote(undefined);
+ setIsNoteLocked(false);
+ setFilteredBlocks(undefined);
+ setBlocks([]);
+ }}
+ >
+ Selected note: {selectedNote.title} (click to deselect)
+ </Button>
+ {isNoteLocked ? (
+ <Text variant="body" sx={{ mt: 1 }}>
+ Linking to a specific block is not available for locked notes.
+ </Text>
+ ) : blocks.length <= 0 ? (
+ <Text variant="body" sx={{ mt: 1 }}>
+ There are no blocks in this note.
+ </Text>
+ ) : null}
<ScrollContainer>
<VirtualizedList
- items={notes.placeholders}
- estimatedSize={28}
+ items={filteredBlocks || blocks}
+ estimatedSize={34}
+ mode="dynamic"
itemGap={5}
- getItemKey={notes.key}
+ getItemKey={(i) => blocks[i].id}
mt={1}
- renderItem={({ index }) => (
- <ResolvedItem items={notes} index={index} type="note">
- {({ item: note, data }) => (
- <Button
- variant="menuitem"
- sx={{
- p: 1,
- width: "100%",
- textAlign: "left",
- display: "flex",
- alignItems: "center",
- gap: 1,
- borderBottom: "1px solid var(--border)"
- }}
- onClick={async () => {
- setSelectedNote(note);
- setIsNoteLocked(
- !!(data as NoteResolvedData).locked
- );
- setBlocks(await db.notes.contentBlocks(note.id));
- }}
- >
- <Text variant="body">{note.title}</Text>
- {(data as NoteResolvedData).locked ? (
- <Lock size={14} />
- ) : null}
- </Button>
- )}
- </ResolvedItem>
+ renderItem={({ item }) => (
+ <Button
+ variant="menuitem"
+ sx={{
+ p: 1,
+ width: "100%",
+ textAlign: "left",
+ display: "flex",
+ justifyContent: "space-between",
+ alignItems: "center",
+ borderBottom: "1px solid var(--border)"
+ }}
+ onClick={() => {
+ props.onDone({
+ title: selectedNote.title,
+ href: createInternalLink("note", selectedNote.id, {
+ blockId: item.id
+ })
+ });
+ }}
+ >
+ <Text
+ variant="body"
+ sx={{ fontFamily: "monospace", whiteSpace: "pre-wrap" }}
+ >
+ {ellipsize(item.content, 200, "end").trim() ||
+ "(empty block)"}
+ </Text>
+ <Text
+ variant="subBody"
+ sx={{
+ bg: "background-secondary",
+ flexShrink: 0,
+ p: "small",
+ px: 1,
+ borderRadius: "default",
+ alignSelf: "flex-start"
+ }}
+ >
+ {item.type.toUpperCase()}
+ </Text>
+ </Button>
)}
/>
</ScrollContainer>
- )}
- </>
- )}
- </Flex>
- </Dialog>
- );
-}
+ </>
+ ) : (
+ <>
+ <Field
+ autoFocus
+ placeholder="Search for a note to link to..."
+ sx={{ mx: 0 }}
+ onChange={async (e) => {
+ const query = e.target.value.trim();
+ setNotes(
+ query
+ ? await db.lookup.notes(e.target.value).sorted()
+ : await db.notes.all.sorted(
+ db.settings.getGroupOptions("home")
+ )
+ );
+ }}
+ />
+ {notes && (
+ <ScrollContainer>
+ <VirtualizedList
+ items={notes.placeholders}
+ estimatedSize={28}
+ itemGap={5}
+ getItemKey={notes.key}
+ mt={1}
+ renderItem={({ index }) => (
+ <ResolvedItem items={notes} index={index} type="note">
+ {({ item: note, data }) => (
+ <Button
+ variant="menuitem"
+ sx={{
+ p: 1,
+ width: "100%",
+ textAlign: "left",
+ display: "flex",
+ alignItems: "center",
+ gap: 1,
+ borderBottom: "1px solid var(--border)"
+ }}
+ onClick={async () => {
+ setSelectedNote(note);
+ setIsNoteLocked(
+ !!(data as NoteResolvedData).locked
+ );
+ setBlocks(await db.notes.contentBlocks(note.id));
+ }}
+ >
+ <Text variant="body">{note.title}</Text>
+ {(data as NoteResolvedData).locked ? (
+ <Lock size={14} />
+ ) : null}
+ </Button>
+ )}
+ </ResolvedItem>
+ )}
+ />
+ </ScrollContainer>
+ )}
+ </>
+ )}
+ </Flex>
+ </Dialog>
+ );
+ }
+);
diff --git a/apps/web/src/dialogs/onboarding-dialog.jsx b/apps/web/src/dialogs/onboarding-dialog.tsx
similarity index 77%
rename from apps/web/src/dialogs/onboarding-dialog.jsx
rename to apps/web/src/dialogs/onboarding-dialog.tsx
index 2f2e1a9bd..662777e35 100644
--- a/apps/web/src/dialogs/onboarding-dialog.jsx
+++ b/apps/web/src/dialogs/onboarding-dialog.tsx
@@ -39,7 +39,6 @@ import AppleStore from "../assets/apple.png";
import { useStore as useThemeStore } from "../stores/theme-store";
import { Checkbox, Label } from "@theme-ui/components";
import { Features } from "../components/announcements/body";
-import { showBuyDialog } from "../common/dialog-controller";
import { TaskManager } from "../common/task-manager";
import { db } from "../common/db";
import { usePersistentState } from "../hooks/use-persistent-state";
@@ -47,8 +46,20 @@ import { useCallback, useState } from "react";
import Config from "../utils/config";
import { isMacStoreApp } from "../utils/platform";
import { ErrorText } from "../components/error-text";
+import { BuyDialog } from "./buy-dialog";
+import { BaseDialogProps, DialogManager } from "../common/dialog-manager";
-const newUserSteps = [
+type Step = {
+ title: string;
+ subtitle: string;
+ buttonText?: string;
+ image?: JSX.Element;
+ component?:
+ | (() => JSX.Element)
+ | ((props: { onNext: () => void }) => JSX.Element)
+ | ((props: { onClose: () => void }) => JSX.Element);
+};
+const newUserSteps: Step[] = [
{
title: "Safe & encrypted notes",
subtitle: "Write with freedom. Never compromise on privacy again.",
@@ -86,7 +97,7 @@ const newUserSteps = [
}
];
-const proUserSteps = [
+const proUserSteps: Step[] = [
{
title: "Welcome to Notesnook Pro",
subtitle: "Thank you. You are the proof that privacy always comes first.",
@@ -112,7 +123,7 @@ const proUserSteps = [
}
];
-const trialUserSteps = [
+const trialUserSteps: Step[] = [
{
title: "Congratulations!",
subtitle: "You 14-day free trial has been activated.",
@@ -125,93 +136,111 @@ const onboarding = {
new: newUserSteps,
pro: proUserSteps,
trial: trialUserSteps
-};
+} as const;
-export function interruptedOnboarding() {
- for (let key in onboarding) {
+export function interruptedOnboarding(): keyof typeof onboarding | undefined {
+ for (const key in onboarding) {
const index = Config.get(key, undefined);
if (index === null || index === undefined) continue;
- if (index >= 0 && index < onboarding[key].length - 1) return key;
+ if (
+ index >= 0 &&
+ index < onboarding[key as keyof typeof onboarding].length - 1
+ )
+ return key as keyof typeof onboarding;
}
}
-function OnboardingDialog({ onClose: _onClose, type }) {
- const [step, setStep] = usePersistentState(type, 0);
- const steps = onboarding[type];
+type OnboardingDialogProps = BaseDialogProps<boolean> & {
+ type: keyof typeof onboarding;
+};
+export const OnboardingDialog = DialogManager.register(
+ function OnboardingDialog({
+ onClose: _onClose,
+ type
+ }: OnboardingDialogProps) {
+ const [step, setStep] = usePersistentState(type, 0);
+ console.log("STEPS", type);
+ const steps = onboarding[type];
- const onClose = useCallback(() => {
- Config.set(type, steps.length);
- _onClose();
- }, [_onClose, type, steps]);
+ const onClose = useCallback(
+ (result: boolean) => {
+ Config.set(type, steps.length);
+ _onClose(result);
+ },
+ [_onClose, type, steps]
+ );
- const onNext = useCallback(() => {
- if (step === steps.length - 1) onClose();
- else setStep((s) => ++s);
- }, [onClose, setStep, step, steps.length]);
+ const onNext = useCallback(() => {
+ if (step === steps.length - 1) onClose(true);
+ else setStep((s) => ++s);
+ }, [onClose, setStep, step, steps.length]);
- if (!steps || !steps[step] || !type) {
- onClose();
- return null;
- }
+ if (!steps || !steps[step] || !type) {
+ onClose(false);
+ return null;
+ }
- const {
- title,
- subtitle,
- image,
- component: Component,
- buttonText
- } = steps[step];
+ const {
+ title,
+ subtitle,
+ image,
+ component: Component,
+ buttonText
+ } = steps[step];
- return (
- <Dialog isOpen={true} width={500}>
- <Flex
- sx={{
- flexDirection: "column",
- alignItems: "center",
- overflowY: "auto"
- }}
- >
- {image}
- <Text variant={"heading"} mt={2}>
- {title}
- </Text>
- <Text
- variant={"body"}
+ return (
+ <Dialog isOpen={true} width={500}>
+ <Flex
sx={{
- textAlign: "center",
- maxWidth: "70%",
- color: "var(--paragraph-secondary)"
+ flexDirection: "column",
+ alignItems: "center",
+ overflowY: "auto"
}}
>
- {subtitle}
- </Text>
- {Component && <Component onClose={onClose} onNext={onNext} />}
- {buttonText && (
- <Button
- variant="accent"
- sx={{ borderRadius: 50, px: 30, mb: 4, mt: Component ? 0 : 4 }}
- onClick={onNext}
+ {image}
+ <Text variant={"heading"} mt={2}>
+ {title}
+ </Text>
+ <Text
+ variant={"body"}
+ sx={{
+ textAlign: "center",
+ maxWidth: "70%",
+ color: "var(--paragraph-secondary)"
+ }}
>
- {buttonText}
- </Button>
- )}
- </Flex>
- </Dialog>
- );
-}
-export default OnboardingDialog;
+ {subtitle}
+ </Text>
+ {Component && (
+ <Component onClose={() => onClose(true)} onNext={onNext} />
+ )}
+ {buttonText && (
+ <Button
+ variant="accent"
+ sx={{ borderRadius: 50, px: 30, mb: 4, mt: Component ? 0 : 4 }}
+ onClick={onNext}
+ >
+ {buttonText}
+ </Button>
+ )}
+ </Flex>
+ </Dialog>
+ );
+ }
+);
-function JoinCause({ onNext }) {
+function JoinCause({ onNext }: { onNext: () => void }) {
return (
<Flex mb={4} sx={{ flexDirection: "column" }}>
<Button
as="a"
- href="https://discord.com/invite/zQBK97EE22"
- target="_blank"
mt={4}
variant="accent"
sx={{ borderRadius: 50, alignSelf: "center", px: 30 }}
- onClick={() => onNext()}
+ onClick={() => {
+ window.open("https://go.notesnook.com/discord", "_blank");
+ onNext();
+ }}
>
Join the community
</Button>
@@ -235,7 +264,7 @@ const importers = [
{ title: "Google Keep" },
{ title: "Standard Notes" }
];
-function Importer({ onClose }) {
+function Importer({ onClose }: { onClose: () => void }) {
return (
<Flex my={4} sx={{ flexDirection: "column" }}>
<Box sx={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 1 }}>
@@ -260,12 +289,13 @@ function Importer({ onClose }) {
</Box>
<Button
as="a"
- href="https://importer.notesnook.com/"
- target="_blank"
mt={4}
variant="accent"
sx={{ borderRadius: 50, alignSelf: "center", px: 30 }}
- onClick={() => onClose()}
+ onClick={() => {
+ window.open("https://importer.notesnook.com/", "_blank");
+ onClose();
+ }}
>
Start importing now
</Button>
@@ -315,7 +345,6 @@ function Support() {
<Button
key={channel.key}
as="a"
- href={channel.url}
variant={"icon"}
sx={{
display: "flex",
@@ -323,6 +352,7 @@ function Support() {
borderRadius: "default",
alignItems: "center"
}}
+ onClick={() => window.open(channel.url)}
>
<channel.icon size={16} />
<Text variant={"body"} ml={1}>
@@ -335,8 +365,8 @@ function Support() {
}
const themes = [
- { key: "light", name: "Light", image: LightUI },
- { key: "dark", name: "Dark", image: DarkUI }
+ { key: "light" as const, name: "Light", image: LightUI },
+ { key: "dark" as const, name: "Dark", image: DarkUI }
];
function ThemeSelector() {
@@ -436,9 +466,9 @@ function CrossPlatform() {
);
}
-function TrialOffer({ onClose }) {
- const [error, setError] = useState();
- const [loading, setLoading] = useState();
+function TrialOffer({ onClose }: { onClose: () => void }) {
+ const [error, setError] = useState<string>();
+ const [loading, setLoading] = useState<boolean>();
return (
<Flex
my={4}
@@ -469,7 +499,7 @@ function TrialOffer({ onClose }) {
sx={{ borderRadius: 50, alignSelf: "center", mr: 2, width: "40%" }}
onClick={() => {
onClose();
- showBuyDialog("monthly", "TRIAL2PRO");
+ BuyDialog.show({ plan: "monthly", couponCode: "TRIAL2PRO" });
}}
>
Upgrade now
@@ -493,7 +523,9 @@ function TrialOffer({ onClose }) {
if (result) onClose();
} catch (e) {
setError(
- `Could not activate trial. Please try again. Error: ${e.message}`
+ `Could not activate trial. Please try again. Error: ${
+ (e as Error).message
+ }`
);
} finally {
setLoading(false);
diff --git a/apps/web/src/dialogs/password-dialog.tsx b/apps/web/src/dialogs/password-dialog.tsx
index 7811fbad4..f13e12044 100644
--- a/apps/web/src/dialogs/password-dialog.tsx
+++ b/apps/web/src/dialogs/password-dialog.tsx
@@ -22,25 +22,25 @@ import { Box, Text } from "@theme-ui/components";
import Dialog from "../components/dialog";
import Field, { FieldProps } from "../components/field";
import { Checkbox, Label } from "@theme-ui/components";
-import { Perform } from "../common/dialog-controller";
import { mdToHtml } from "../utils/md";
+import { BaseDialogProps, DialogManager } from "../common/dialog-manager";
type Check = { text: string; default?: boolean };
export type PasswordDialogProps<
TInputId extends string,
TCheckId extends string
-> = {
+> = BaseDialogProps<boolean | Record<TCheckId, boolean>> & {
title: string;
subtitle?: string;
message?: string;
inputs: Record<TInputId, FieldProps>;
validate: (passwords: Record<TInputId, string>) => Promise<boolean>;
checks?: Record<TCheckId, Check>;
- onClose: Perform<boolean | Record<TCheckId, boolean>>;
};
-function PasswordDialog<TInputId extends string, TCheckId extends string>(
- props: PasswordDialogProps<TInputId, TCheckId>
-) {
+const PasswordDialog = DialogManager.register(function PasswordDialog<
+ TInputId extends string,
+ TCheckId extends string
+>(props: PasswordDialogProps<TInputId, TCheckId>) {
const { checks, inputs, message, validate, onClose } = props;
const [error, setError] = useState<string>();
const [isLoading, setIsLoading] = useState(false);
@@ -150,5 +150,13 @@ function PasswordDialog<TInputId extends string, TCheckId extends string>(
</Box>
</Dialog>
);
+});
+
+export function showPasswordDialog<
+ TInputId extends string,
+ TCheckId extends string
+>(props: Omit<PasswordDialogProps<TInputId, TCheckId>, "onClose">) {
+ return PasswordDialog.show(props) as Promise<
+ string extends TCheckId ? boolean : false | Record<TCheckId, boolean>
+ >;
}
-export default PasswordDialog;
diff --git a/apps/web/src/dialogs/progress-dialog.jsx b/apps/web/src/dialogs/progress-dialog.tsx
similarity index 74%
rename from apps/web/src/dialogs/progress-dialog.jsx
rename to apps/web/src/dialogs/progress-dialog.tsx
index 97abb4c95..ee793b95d 100644
--- a/apps/web/src/dialogs/progress-dialog.jsx
+++ b/apps/web/src/dialogs/progress-dialog.tsx
@@ -20,21 +20,32 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.
import { useEffect, useState } from "react";
import { Box, Flex, Text } from "@theme-ui/components";
import Dialog from "../components/dialog";
+import { BaseDialogProps, DialogManager } from "../common/dialog-manager";
-function ProgressDialog(props) {
- const [{ current, total, text }, setProgress] = useState({
- current: 0,
- total: 1,
+type Progress = {
+ total?: number;
+ current?: number;
+ text: string;
+};
+type ProgressDialogProps<T> = BaseDialogProps<T | Error> & {
+ title: string;
+ subtitle: string;
+ action: (report: (progress: Progress) => void) => T;
+};
+export const ProgressDialog = DialogManager.register(function ProgressDialog<T>(
+ props: ProgressDialogProps<T>
+) {
+ const [{ current = 0, total = 1, text }, setProgress] = useState<Progress>({
text: ""
});
useEffect(() => {
(async function () {
try {
- props.onDone(await props.action(setProgress));
+ props.onClose(await props.action(setProgress));
} catch (e) {
console.error(e);
- props.onDone(e);
+ props.onClose(e as Error);
}
})();
}, [props]);
@@ -69,5 +80,4 @@ function ProgressDialog(props) {
</Flex>
</Dialog>
);
-}
-export default ProgressDialog;
+});
diff --git a/apps/web/src/dialogs/prompt.tsx b/apps/web/src/dialogs/prompt.tsx
index 1b326ec18..6605e56fa 100644
--- a/apps/web/src/dialogs/prompt.tsx
+++ b/apps/web/src/dialogs/prompt.tsx
@@ -18,19 +18,19 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import { useRef } from "react";
-import { Perform } from "../common/dialog-controller";
import Field from "../components/field";
import Dialog from "../components/dialog";
+import { BaseDialogProps, DialogManager } from "../common/dialog-manager";
-export type PromptDialogProps = {
- onClose: Perform;
+export type PromptDialogProps = BaseDialogProps<false | string> & {
title: string;
- onSave: (text: string) => void;
description?: string;
defaultValue?: string;
};
-export default function Prompt(props: PromptDialogProps) {
+export const PromptDialog = DialogManager.register(function PromptDialog(
+ props: PromptDialogProps
+) {
const inputRef = useRef<HTMLInputElement>(null);
return (
<Dialog
@@ -40,7 +40,7 @@ export default function Prompt(props: PromptDialogProps) {
onClose={() => props.onClose(false)}
positiveButton={{
text: "Done",
- onClick: () => props.onSave(inputRef.current?.value || "")
+ onClick: () => props.onClose(inputRef.current?.value || "")
}}
negativeButton={{ text: "Cancel", onClick: () => props.onClose(false) }}
>
@@ -49,9 +49,9 @@ export default function Prompt(props: PromptDialogProps) {
defaultValue={props.defaultValue}
autoFocus
onKeyUp={(e) => {
- if (e.key == "Enter") props.onSave(inputRef.current?.value || "");
+ if (e.key == "Enter") props.onClose(inputRef.current?.value || "");
}}
/>
</Dialog>
);
-}
+});
diff --git a/apps/web/src/dialogs/recovery-key-dialog.jsx b/apps/web/src/dialogs/recovery-key-dialog.jsx
deleted file mode 100644
index 21dd9f296..000000000
--- a/apps/web/src/dialogs/recovery-key-dialog.jsx
+++ /dev/null
@@ -1,153 +0,0 @@
-/*
-This file is part of the Notesnook project (https://notesnook.com/)
-
-Copyright (C) 2023 Streetwriters (Private) Limited
-
-This program is free software: you can redistribute it and/or modify
-it under the terms of the GNU General Public License as published by
-the Free Software Foundation, either version 3 of the License, or
-(at your option) any later version.
-
-This program is distributed in the hope that it will be useful,
-but WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-GNU General Public License for more details.
-
-You should have received a copy of the GNU General Public License
-along with this program. If not, see <http://www.gnu.org/licenses/>.
-*/
-
-import React, { useEffect, useState } from "react";
-import { Text, Flex, Button } from "@theme-ui/components";
-import Dialog from "../components/dialog";
-import { db } from "../common/db";
-import Logo from "../assets/notesnook-logo.png";
-import { writeText } from "clipboard-polyfill";
-import { Suspense } from "react";
-import Config from "../utils/config";
-import FileSaver from "file-saver";
-import { ErrorText } from "../components/error-text";
-
-const QRCode = React.lazy(() => import("../re-exports/react-qrcode-logo"));
-
-function RecoveryKeyDialog(props) {
- const [key, setKey] = useState();
- const [email, setEmail] = useState();
- const [copyText, setCopyText] = useState("Copy to clipboard");
- useEffect(() => {
- (async () => {
- const { email } = await db.user.getUser();
- const { key } = await db.user.getEncryptionKey();
- setEmail(email);
- setKey(key);
- })();
- }, []);
-
- return (
- <Dialog
- testId="recovery-key-dialog"
- isOpen={true}
- title="Backup your recovery key"
- width={400}
- positiveButton={{
- text: "I have backed up my key",
- onClick: () => {
- Config.set("recoveryKeyBackupDate", Date.now());
- props.onDone();
- }
- }}
- >
- <Flex sx={{ overflow: "hidden", flex: 1, flexDirection: "column" }}>
- <Flex sx={{ overflowY: "auto", flexDirection: "column" }}>
- <ErrorText
- error="In case you forget your password, your recovery key is the only way to recover your data."
- mt={0}
- />
- <Text
- data-test-id="recovery-key"
- className="selectable"
- mt={2}
- bg="var(--background-secondary)"
- p={2}
- sx={{
- borderRadius: "default",
- overflowWrap: "anywhere",
- fontSize: "body",
- fontFamily: "monospace",
- color: "paragraph"
- }}
- >
- {key}
- </Text>
- <Flex
- mt={4}
- sx={{ alignItems: "center", justifyContent: "space-around" }}
- >
- <Suspense fallback={<div />}>
- <QRCode
- value={key}
- logoImage={Logo}
- logoWidth={40}
- logoHeight={40}
- ecLevel={"M"}
- />
- </Suspense>
-
- <Flex sx={{ flexDirection: "column" }}>
- <Button
- variant="secondary"
- mt={1}
- className="copyKey"
- onClick={async () => {
- writeText(key)
- .then(() => {
- setCopyText("Copied!");
- setTimeout(() => {
- setCopyText("Copy to clipboard");
- }, 2000);
- })
- .catch((e) => {
- console.error("Error while copying text.", e);
- });
- }}
- sx={{ fontSize: "body" }}
- >
- {copyText}
- </Button>
- <Button
- variant="secondary"
- mt={1}
- onClick={async () => {
- const qrcode = document.getElementById("react-qrcode-logo");
- qrcode.toBlob((blob) => {
- FileSaver.saveAs(
- blob,
- `${email}-notesnook-recoverykey.png`
- );
- });
- }}
- sx={{ fontSize: "body" }}
- >
- Download QR Code
- </Button>
- <Button
- variant="secondary"
- mt={1}
- onClick={() => {
- FileSaver.saveAs(
- new Blob([Buffer.from(key)]),
- `${email}-notesnook-recoverykey.txt`
- );
- }}
- sx={{ fontSize: "body" }}
- >
- Download file
- </Button>
- </Flex>
- </Flex>
- </Flex>
- </Flex>
- </Dialog>
- );
-}
-export default RecoveryKeyDialog;
diff --git a/apps/web/src/dialogs/recovery-key-dialog.tsx b/apps/web/src/dialogs/recovery-key-dialog.tsx
new file mode 100644
index 000000000..d2d23acc4
--- /dev/null
+++ b/apps/web/src/dialogs/recovery-key-dialog.tsx
@@ -0,0 +1,166 @@
+/*
+This file is part of the Notesnook project (https://notesnook.com/)
+
+Copyright (C) 2023 Streetwriters (Private) Limited
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+import React, { useState } from "react";
+import { Text, Flex, Button } from "@theme-ui/components";
+import Dialog from "../components/dialog";
+import { db } from "../common/db";
+import Logo from "../assets/notesnook-logo.png";
+import { writeText } from "clipboard-polyfill";
+import { Suspense } from "react";
+import Config from "../utils/config";
+import FileSaver from "file-saver";
+import { ErrorText } from "../components/error-text";
+import { BaseDialogProps, DialogManager } from "../common/dialog-manager";
+import { usePromise } from "@notesnook/common";
+import { Loader } from "../components/loader";
+import { showToast } from "../utils/toast";
+
+const QRCode = React.lazy(() => import("../re-exports/react-qrcode-logo"));
+type RecoveryKeyDialogProps = BaseDialogProps<false>;
+export const RecoveryKeyDialog = DialogManager.register(
+ function RecoveryKeyDialog(props: RecoveryKeyDialogProps) {
+ const email = usePromise(() =>
+ db.user.getUser().then((user) => user?.email)
+ );
+ const key = usePromise(() =>
+ db.user.getEncryptionKey().then((key) => key?.key)
+ );
+ const [copyText, setCopyText] = useState("Copy to clipboard");
+
+ return (
+ <Dialog
+ testId="recovery-key-dialog"
+ isOpen={true}
+ title="Backup your recovery key"
+ width={400}
+ positiveButton={{
+ text: "I have backed up my key",
+ onClick: () => {
+ Config.set("recoveryKeyBackupDate", Date.now());
+ props.onClose(false);
+ }
+ }}
+ >
+ {key.status !== "fulfilled" ? (
+ <Loader title="Getting your encryption key..." />
+ ) : (
+ <Flex sx={{ overflow: "hidden", flex: 1, flexDirection: "column" }}>
+ <Flex sx={{ overflowY: "auto", flexDirection: "column" }}>
+ <ErrorText
+ error="In case you forget your password, your recovery key is the only way to recover your data."
+ mt={0}
+ />
+ <Text
+ data-test-id="recovery-key"
+ className="selectable"
+ mt={2}
+ bg="var(--background-secondary)"
+ p={2}
+ sx={{
+ borderRadius: "default",
+ overflowWrap: "anywhere",
+ fontSize: "body",
+ fontFamily: "monospace",
+ color: "paragraph"
+ }}
+ >
+ {key.value}
+ </Text>
+ <Flex
+ mt={4}
+ sx={{ alignItems: "center", justifyContent: "space-around" }}
+ >
+ <Suspense fallback={<div />}>
+ <QRCode
+ value={key.value}
+ logoImage={Logo}
+ logoWidth={40}
+ logoHeight={40}
+ ecLevel={"M"}
+ />
+ </Suspense>
+ <Flex sx={{ flexDirection: "column" }}>
+ <Button
+ variant="secondary"
+ mt={1}
+ className="copyKey"
+ onClick={async () => {
+ if (!key.value)
+ return showToast("error", "No encryption key found.");
+
+ writeText(key.value)
+ .then(() => {
+ setCopyText("Copied!");
+ setTimeout(() => {
+ setCopyText("Copy to clipboard");
+ }, 2000);
+ })
+ .catch((e) => {
+ console.error("Error while copying text.", e);
+ });
+ }}
+ sx={{ fontSize: "body" }}
+ >
+ {copyText}
+ </Button>
+ <Button
+ variant="secondary"
+ mt={1}
+ onClick={async () => {
+ const qrcode = document.getElementById(
+ "react-qrcode-logo"
+ ) as HTMLCanvasElement | null;
+ qrcode?.toBlob((blob) => {
+ blob
+ ? FileSaver.saveAs(
+ blob,
+ `${email}-notesnook-recoverykey.png`
+ )
+ : null;
+ });
+ }}
+ sx={{ fontSize: "body" }}
+ >
+ Download QR Code
+ </Button>
+ <Button
+ variant="secondary"
+ mt={1}
+ onClick={() => {
+ if (!key.value)
+ return showToast("error", "No encryption key found.");
+ FileSaver.saveAs(
+ new Blob([Buffer.from(key.value)]),
+ `${email}-notesnook-recoverykey.txt`
+ );
+ }}
+ sx={{ fontSize: "body" }}
+ >
+ Download file
+ </Button>
+ </Flex>
+ </Flex>
+ </Flex>
+ </Flex>
+ )}
+ </Dialog>
+ );
+ }
+);
diff --git a/apps/web/src/dialogs/reminder-dialog.jsx b/apps/web/src/dialogs/reminder-dialog.tsx
similarity index 84%
rename from apps/web/src/dialogs/reminder-dialog.jsx
rename to apps/web/src/dialogs/reminder-dialog.tsx
index a199cd705..0736b79ce 100644
--- a/apps/web/src/dialogs/reminder-dialog.jsx
+++ b/apps/web/src/dialogs/reminder-dialog.tsx
@@ -27,9 +27,12 @@ import {
Backup,
Vault,
PDF,
- Edit
+ Edit,
+ Icon
} from "../components/icons";
-import { showBuyDialog } from "../common/dialog-controller";
+import { BuyDialog } from "./buy-dialog";
+import { BaseDialogProps, DialogManager } from "../common/dialog-manager";
+import Config from "../utils/config";
const features = [
{ icon: Sync, title: "Instant private sync" },
@@ -41,8 +44,22 @@ const features = [
{ icon: PDF, title: "Export to PDF" },
{ icon: Edit, title: "Rich text editor" }
];
+
+type Reminder = {
+ title: string;
+ description: string;
+ offer: {
+ title: JSX.Element;
+ subtitle?: string;
+ };
+ features: { icon: Icon; title: string }[];
+ cta: {
+ title: string;
+ action: () => Promise<void> | void;
+ };
+};
// TODO create trial expiry coupon codes
-const reminders = {
+const reminders: Record<string, Reminder> = {
trialexpired: {
title: "Your free trial has expired",
description: "But we have a special offer just for you!",
@@ -70,7 +87,7 @@ const reminders = {
title: "Subscribe now",
action: () => {
setTimeout(async () => {
- await showBuyDialog("yearly", "TRIAL2PRO");
+ await BuyDialog.show({ plan: "yearly", couponCode: "TRIAL2PRO" });
}, 0);
}
}
@@ -91,17 +108,23 @@ const reminders = {
title: "Upgrade now",
action: () => {
setTimeout(async () => {
- await showBuyDialog();
+ await BuyDialog.show({});
}, 0);
}
}
}
};
-function ReminderDialog(props) {
+type ReminderDialogProps = BaseDialogProps<boolean> & {
+ reminderKey: keyof typeof reminders;
+};
+export const ReminderDialog = DialogManager.register(function ReminderDialog(
+ props: ReminderDialogProps
+) {
const { reminderKey } = props;
const reminder = reminders[reminderKey];
if (!reminder) return null;
+ if (Config.get(reminderKey, false)) return null;
return (
<Dialog
@@ -111,7 +134,6 @@ function ReminderDialog(props) {
onClose={() => props.onClose(false)}
showCloseButton
description={reminder.description}
- alignment="center"
positiveButton={{
text: <Flex>{reminder.cta.title}</Flex>,
onClick: async () => {
@@ -120,7 +142,6 @@ function ReminderDialog(props) {
props.onClose(true);
}
}}
- footer={reminder.footer}
>
<Flex
mt={2}
@@ -175,5 +196,4 @@ function ReminderDialog(props) {
</Flex>
</Dialog>
);
-}
-export default ReminderDialog;
+});
diff --git a/apps/web/src/dialogs/reminder-preview-dialog.tsx b/apps/web/src/dialogs/reminder-preview-dialog.tsx
index 6b514b647..2adaf6647 100644
--- a/apps/web/src/dialogs/reminder-preview-dialog.tsx
+++ b/apps/web/src/dialogs/reminder-preview-dialog.tsx
@@ -17,7 +17,6 @@ You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
-import { Perform } from "../common/dialog-controller";
import Dialog from "../components/dialog";
import { Button, Flex, Text } from "@theme-ui/components";
import { db } from "../common/db";
@@ -26,9 +25,9 @@ import IconTag from "../components/icon-tag";
import { Clock, Refresh } from "../components/icons";
import Note from "../components/note";
import { getFormattedReminderTime, usePromise } from "@notesnook/common";
+import { BaseDialogProps, DialogManager } from "../common/dialog-manager";
-export type ReminderPreviewDialogProps = {
- onClose: Perform;
+export type ReminderPreviewDialogProps = BaseDialogProps<false> & {
reminder: Reminder;
};
@@ -54,82 +53,89 @@ const SNOOZE_TIMES = [
{ id: "1-hour", title: "1 hour", interval: 60 * 60 * 1000 }
];
-export default function ReminderPreviewDialog(
- props: ReminderPreviewDialogProps
-) {
- const { reminder } = props;
- const referencedNotes = usePromise(
- () =>
- db.relations.to({ id: reminder.id, type: "reminder" }, "note").resolve(),
- [reminder.id]
- );
+export const ReminderPreviewDialog = DialogManager.register(
+ function ReminderPreviewDialog(props: ReminderPreviewDialogProps) {
+ const { reminder } = props;
+ const referencedNotes = usePromise(
+ () =>
+ db.relations
+ .to({ id: reminder.id, type: "reminder" }, "note")
+ .resolve(),
+ [reminder.id]
+ );
- return (
- <Dialog
- isOpen={true}
- title={reminder.title}
- description={reminder.description}
- onClose={() => props.onClose(false)}
- negativeButton={{
- text: "Close",
- onClick: () => props.onClose(false)
- }}
- >
- <Flex
- sx={{
- alignItems: "center",
- mb: 2
+ return (
+ <Dialog
+ isOpen={true}
+ title={reminder.title}
+ description={reminder.description}
+ onClose={() => props.onClose(false)}
+ negativeButton={{
+ text: "Close",
+ onClick: () => props.onClose(false)
}}
>
- {reminder.mode === "repeat" && reminder.recurringMode && (
- <IconTag
- icon={Refresh}
- text={RECURRING_MODE_MAP[reminder.recurringMode]}
- />
- )}
- <IconTag icon={Clock} text={getFormattedReminderTime(reminder)} />
- </Flex>
+ <Flex
+ sx={{
+ alignItems: "center",
+ mb: 2
+ }}
+ >
+ {reminder.mode === "repeat" && reminder.recurringMode && (
+ <IconTag
+ icon={Refresh}
+ text={RECURRING_MODE_MAP[reminder.recurringMode]}
+ />
+ )}
+ <IconTag icon={Clock} text={getFormattedReminderTime(reminder)} />
+ </Flex>
- <Text variant="body">Remind me in:</Text>
- <Flex
- sx={{
- alignItems: "center",
- my: 1,
- gap: 1
- }}
- >
- {SNOOZE_TIMES.map((time) => (
- <Button
- key={time.id}
- variant="secondary"
- onClick={() => {
- db.reminders.add({
- id: reminder.id,
- snoozeUntil: Date.now() + time.interval
- });
- props.onClose(false);
- }}
- sx={{
- borderRadius: 100,
- py: 1,
- px: 2,
- flexShrink: 0
- }}
- >
- {time.title}
- </Button>
- ))}
- </Flex>
- {referencedNotes &&
- referencedNotes.status === "fulfilled" &&
- referencedNotes.value.length > 0 && (
- <>
- <Text variant="body">References:</Text>
- {referencedNotes.value.map((item, index) => (
- <Note key={item.id} item={item} date={item.dateCreated} compact />
- ))}
- </>
- )}
- </Dialog>
- );
-}
+ <Text variant="body">Remind me in:</Text>
+ <Flex
+ sx={{
+ alignItems: "center",
+ my: 1,
+ gap: 1
+ }}
+ >
+ {SNOOZE_TIMES.map((time) => (
+ <Button
+ key={time.id}
+ variant="secondary"
+ onClick={() => {
+ db.reminders.add({
+ id: reminder.id,
+ snoozeUntil: Date.now() + time.interval
+ });
+ props.onClose(false);
+ }}
+ sx={{
+ borderRadius: 100,
+ py: 1,
+ px: 2,
+ flexShrink: 0
+ }}
+ >
+ {time.title}
+ </Button>
+ ))}
+ </Flex>
+ {referencedNotes &&
+ referencedNotes.status === "fulfilled" &&
+ referencedNotes.value.length > 0 && (
+ <>
+ <Text variant="body">References:</Text>
+ {referencedNotes.value.map((item, index) => (
+ <Note
+ key={item.id}
+ item={item}
+ date={item.dateCreated}
+ compact
+ />
+ ))}
+ </>
+ )}
+ </Dialog>
+ );
+ }
+);
diff --git a/apps/web/src/dialogs/settings/app-lock-settings.ts b/apps/web/src/dialogs/settings/app-lock-settings.ts
index 94660cc32..d15d0d7d2 100644
--- a/apps/web/src/dialogs/settings/app-lock-settings.ts
+++ b/apps/web/src/dialogs/settings/app-lock-settings.ts
@@ -19,10 +19,7 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.
import { SettingComponent, SettingsGroup } from "./types";
import { useStore as useUserStore } from "../../stores/user-store";
-import {
- showPasswordDialog,
- showPromptDialog
-} from "../../common/dialog-controller";
+import { showPasswordDialog } from "../../dialogs/password-dialog";
import {
CredentialType,
CredentialWithSecret,
@@ -35,6 +32,7 @@ import { WebAuthn } from "../../utils/webauthn";
import { generatePassword } from "../../utils/password-generator";
import { verifyAccount } from "../../common";
import { Checkmark } from "../../components/icons";
+import { PromptDialog } from "../prompt";
export const AppLockSettings: SettingsGroup[] = [
{
@@ -318,7 +316,7 @@ async function registerCredential(type: CredentialType) {
const user = useUserStore.getState().user;
const username =
user?.email ||
- (await showPromptDialog({
+ (await PromptDialog.show({
title: "Enter your username",
description:
"This username will be used to distinguish between different credentials in your security key. Make sure it is unique."
diff --git a/apps/web/src/dialogs/settings/auth-settings.ts b/apps/web/src/dialogs/settings/auth-settings.ts
index 86bb8a416..b855f7d00 100644
--- a/apps/web/src/dialogs/settings/auth-settings.ts
+++ b/apps/web/src/dialogs/settings/auth-settings.ts
@@ -20,14 +20,12 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.
import { SettingsGroup } from "./types";
import { useStore as useUserStore } from "../../stores/user-store";
import { createBackup, verifyAccount } from "../../common";
-import {
- show2FARecoveryCodesDialog,
- showMultifactorDialog,
- showPasswordDialog,
- showRecoveryKeyDialog
-} from "../../common/dialog-controller";
+import { showPasswordDialog } from "../../dialogs/password-dialog";
import { db } from "../../common/db";
import { showToast } from "../../utils/toast";
+import { RecoveryCodesDialog } from "../mfa/recovery-code-dialog";
+import { MultifactorDialog } from "../mfa/multi-factor-dialog";
+import { RecoveryKeyDialog } from "../recovery-key-dialog";
export const AuthenticationSettings: SettingsGroup[] = [
{
@@ -74,7 +72,7 @@ If this process is interrupted, there is a high chance of data corruption so **p
});
if (result) {
showToast("success", "Account password changed!");
- await showRecoveryKeyDialog();
+ await RecoveryKeyDialog.show({});
}
}
}
@@ -110,7 +108,7 @@ If this process is interrupted, there is a high chance of data corruption so **p
title: "Change",
action: async () => {
if (await verifyAccount()) {
- await showMultifactorDialog();
+ await MultifactorDialog.show({});
await useUserStore.getState().refreshUser();
}
},
@@ -135,9 +133,10 @@ If this process is interrupted, there is a high chance of data corruption so **p
variant: "secondary",
action: async () => {
if (await verifyAccount()) {
- await showMultifactorDialog(
- useUserStore.getState().user?.mfa.primaryMethod || "email"
- );
+ await MultifactorDialog.show({
+ primaryMethod:
+ useUserStore.getState().user?.mfa.primaryMethod || "email"
+ });
await useUserStore.getState().refreshUser();
}
}
@@ -157,9 +156,10 @@ If this process is interrupted, there is a high chance of data corruption so **p
variant: "secondary",
action: async () => {
if (await verifyAccount()) {
- await show2FARecoveryCodesDialog(
- useUserStore.getState().user?.mfa.primaryMethod || "email"
- );
+ await RecoveryCodesDialog.show({
+ primaryMethod:
+ useUserStore.getState().user?.mfa.primaryMethod || "email"
+ });
await useUserStore.getState().refreshUser();
}
}
diff --git a/apps/web/src/dialogs/settings/components/subscription-status.tsx b/apps/web/src/dialogs/settings/components/subscription-status.tsx
index 13c47f3d4..4b11c260d 100644
--- a/apps/web/src/dialogs/settings/components/subscription-status.tsx
+++ b/apps/web/src/dialogs/settings/components/subscription-status.tsx
@@ -23,11 +23,12 @@ import { useCallback, useMemo, useState } from "react";
import dayjs from "dayjs";
import { SUBSCRIPTION_STATUS } from "../../../common/constants";
import { db } from "../../../common/db";
-import { confirm, showBuyDialog } from "../../../common/dialog-controller";
import { TaskManager } from "../../../common/task-manager";
import { showToast } from "../../../utils/toast";
import { Loading } from "../../../components/icons";
import { Features } from "../../buy-dialog/features";
+import { ConfirmDialog } from "../../confirm";
+import { BuyDialog } from "../../buy-dialog";
const PROVIDER_MAP = {
0: "Streetwriters",
@@ -139,7 +140,7 @@ export function SubscriptionStatus() {
<Button
variant="secondary"
onClick={async () => {
- const cancelSubscription = await confirm({
+ const cancelSubscription = await ConfirmDialog.show({
title: "Cancel subscription?",
message:
"Cancelling your subscription will automatically downgrade you to the Basic plan at the end of your billing period. You will have to resubscribe to continue using the Pro features.",
@@ -169,7 +170,7 @@ export function SubscriptionStatus() {
<Button
variant="secondary"
onClick={async () => {
- const refundSubscription = await confirm({
+ const refundSubscription = await ConfirmDialog.show({
title: "Request refund?",
message:
"You will only be issued a refund if you are eligible as per our refund policy. Your account will be immediately downgraded to Basic and your funds will be transferred to your account within 24 hours.",
@@ -199,7 +200,7 @@ export function SubscriptionStatus() {
) : null}
{!isPro && (
<>
- <Button variant="accent" onClick={() => showBuyDialog()}>
+ <Button variant="accent" onClick={() => BuyDialog.show({})}>
{isProCancelled ? "Resubscribe" : "Upgrade to Pro"}
</Button>
{isBasic && (
diff --git a/apps/web/src/dialogs/settings/components/themes-selector.tsx b/apps/web/src/dialogs/settings/components/themes-selector.tsx
index 2336b116e..56258f2c5 100644
--- a/apps/web/src/dialogs/settings/components/themes-selector.tsx
+++ b/apps/web/src/dialogs/settings/components/themes-selector.tsx
@@ -35,12 +35,12 @@ import {
ThemesTRPC
} from "../../../common/themes-router";
import { ThemeMetadata } from "@notesnook/themes-server";
-import { showThemeDetails } from "../../../common/dialog-controller";
import { ThemePreview } from "../../../components/theme-preview";
import { Loader } from "../../../components/loader";
import { showToast } from "../../../utils/toast";
import { showFilePicker, readFile } from "../../../utils/file-picker";
import { VirtualizedGrid } from "../../../components/virtualized-grid";
+import { ThemeDetailsDialog } from "../../theme-details-dialog";
const ThemesClient = ThemesTRPC.createClient({
links: [
@@ -189,7 +189,7 @@ function ThemesList() {
if (error) return showToast("error", error);
if (
- await showThemeDetails({
+ await ThemeDetailsDialog.show({
...theme,
totalInstalls: 0,
previewColors: getPreviewColors(theme)
@@ -266,7 +266,7 @@ function ThemeItem(props: ThemeItemProps) {
}
}}
onClick={async () => {
- if (await showThemeDetails(theme)) {
+ if (await ThemeDetailsDialog.show(theme)) {
await setTheme(theme);
}
}}
diff --git a/apps/web/src/dialogs/settings/components/user-profile.tsx b/apps/web/src/dialogs/settings/components/user-profile.tsx
index 361620ffc..d3d732ae9 100644
--- a/apps/web/src/dialogs/settings/components/user-profile.tsx
+++ b/apps/web/src/dialogs/settings/components/user-profile.tsx
@@ -26,12 +26,10 @@ import { getFormattedDate } from "@notesnook/common";
import { SUBSCRIPTION_STATUS } from "../../../common/constants";
import dayjs from "dayjs";
import { useMemo } from "react";
-import {
- showEditProfilePictureDialog,
- showPromptDialog
-} from "../../../common/dialog-controller";
import { db } from "../../../common/db";
import { showToast } from "../../../utils/toast";
+import { EditProfilePictureDialog } from "../../edit-profile-picture-dialog";
+import { PromptDialog } from "../../prompt";
export function UserProfile() {
const user = useUserStore((store) => store.user);
@@ -142,7 +140,7 @@ export function UserProfile() {
}}
title="Edit profile picture"
onClick={async () => {
- await showEditProfilePictureDialog(profile);
+ await EditProfilePictureDialog.show({ profile });
}}
>
<Text variant="body" sx={{ color: "white" }}>
@@ -173,7 +171,7 @@ export function UserProfile() {
size={12}
title="Edit full name"
onClick={async () => {
- const fullName = await showPromptDialog({
+ const fullName = await PromptDialog.show({
title: "Edit your full name",
description:
"Your profile data is 100% end-to-end encrypted.",
diff --git a/apps/web/src/dialogs/settings/index.tsx b/apps/web/src/dialogs/settings/index.tsx
index ef55f5c9e..1a12a9f78 100644
--- a/apps/web/src/dialogs/settings/index.tsx
+++ b/apps/web/src/dialogs/settings/index.tsx
@@ -39,7 +39,6 @@ import {
ShieldLock,
Sync
} from "../../components/icons";
-import { Perform } from "../../common/dialog-controller";
import NavigationItem from "../../components/navigation-menu/navigation-item";
import { FlexScrollContainer } from "../../components/scroll-container";
import { useCallback, useEffect, useState } from "react";
@@ -74,8 +73,9 @@ import { debounce, usePromise } from "@notesnook/common";
import { SubscriptionSettings } from "./subscription-settings";
import { ScopedThemeProvider } from "../../components/theme-provider";
import { AppLockSettings } from "./app-lock-settings";
+import { BaseDialogProps, DialogManager } from "../../common/dialog-manager";
-type SettingsDialogProps = { onClose: Perform };
+type SettingsDialogProps = BaseDialogProps<false>;
const sectionGroups: SectionGroup[] = [
{
@@ -179,7 +179,9 @@ const SettingsGroups = [
// 5. Settings will be stateful but independent such that any one setting
// can appear independent of others (e.g. as a search result)
-export default function SettingsDialog(props: SettingsDialogProps) {
+export const SettingsDialog = DialogManager.register(function SettingsDialog(
+ props: SettingsDialogProps
+) {
const [activeSettings, setActiveSettings] = useState<SettingsGroup[]>(
SettingsGroups.filter((g) => g.section === "profile")
);
@@ -225,7 +227,7 @@ export default function SettingsDialog(props: SettingsDialogProps) {
</Flex>
</Dialog>
);
-}
+});
type SettingsSideBarProps = { onNavigate: (settings: SettingsGroup[]) => void };
function SettingsSideBar(props: SettingsSideBarProps) {
diff --git a/apps/web/src/dialogs/settings/other-settings.ts b/apps/web/src/dialogs/settings/other-settings.ts
index bb64e23d7..4a96c8ca4 100644
--- a/apps/web/src/dialogs/settings/other-settings.ts
+++ b/apps/web/src/dialogs/settings/other-settings.ts
@@ -23,9 +23,9 @@ import { writeText } from "clipboard-polyfill";
import { showToast } from "../../utils/toast";
import { checkForUpdate, downloadUpdate } from "../../utils/updater";
import { isMacStoreApp } from "../../utils/platform";
-import { showIssueDialog } from "../../common/dialog-controller";
import { clearLogs, downloadLogs } from "../../utils/logger";
import { useAutoUpdateStore } from "../../hooks/use-auto-updater";
+import { IssueDialog } from "../issue-dialog";
export const AboutSettings: SettingsGroup[] = [
{
@@ -271,7 +271,7 @@ export const SupportSettings: SettingsGroup[] = [
components: [
{
type: "button",
- action: showIssueDialog,
+ action: () => IssueDialog.show({}),
title: "Send bug report",
variant: "secondary"
}
diff --git a/apps/web/src/dialogs/settings/privacy-settings.ts b/apps/web/src/dialogs/settings/privacy-settings.ts
index 2c897ca34..cd8b73715 100644
--- a/apps/web/src/dialogs/settings/privacy-settings.ts
+++ b/apps/web/src/dialogs/settings/privacy-settings.ts
@@ -22,10 +22,10 @@ import { useStore as useSettingStore } from "../../stores/setting-store";
import { useStore as useUserStore } from "../../stores/user-store";
import { getPlatform } from "../../utils/platform";
import { db } from "../../common/db";
-import { showPromptDialog } from "../../common/dialog-controller";
import Config from "../../utils/config";
import { showToast } from "../../utils/toast";
import { TrackingDetails } from "./components/tracking-details";
+import { PromptDialog } from "../prompt";
export const PrivacySettings: SettingsGroup[] = [
{
@@ -143,7 +143,7 @@ This can sometimes bypass local ISP blockages on Notesnook traffic. Disable this
type: "button",
title: "Change proxy",
action: async () => {
- const result = await showPromptDialog({
+ const result = await PromptDialog.show({
title: "CORS bypass proxy",
description:
"You can set a custom proxy URL to increase your privacy.",
diff --git a/apps/web/src/dialogs/settings/profile-settings.ts b/apps/web/src/dialogs/settings/profile-settings.ts
index 77462f97c..e5282e25e 100644
--- a/apps/web/src/dialogs/settings/profile-settings.ts
+++ b/apps/web/src/dialogs/settings/profile-settings.ts
@@ -17,24 +17,21 @@ You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
-import {
- useStore as useUserStore,
- store as userstore
-} from "../../stores/user-store";
+import { useStore as useUserStore } from "../../stores/user-store";
import { SettingsGroup } from "./types";
-import {
- showAttachmentsDialog,
- showClearSessionsConfirmation,
- showEmailChangeDialog,
- showLoadingDialog,
- showLogoutConfirmation,
- showPasswordDialog,
- showRecoveryKeyDialog
-} from "../../common/dialog-controller";
+import { showPasswordDialog } from "../../dialogs/password-dialog";
import { db } from "../../common/db";
import { showToast } from "../../utils/toast";
import { UserProfile } from "./components/user-profile";
import { verifyAccount } from "../../common";
+import { EmailChangeDialog } from "../email-change-dialog";
+import {
+ showClearSessionsConfirmation,
+ showLogoutConfirmation
+} from "../confirm";
+import { TaskManager } from "../../common/task-manager";
+import { AttachmentsDialog } from "../attachments-dialog";
+import { RecoveryKeyDialog } from "../recovery-key-dialog";
export const ProfileSettings: SettingsGroup[] = [
{
@@ -56,7 +53,7 @@ export const ProfileSettings: SettingsGroup[] = [
type: "button",
title: "Change email",
variant: "secondary",
- action: showEmailChangeDialog
+ action: () => EmailChangeDialog.show({})
}
]
},
@@ -69,7 +66,7 @@ export const ProfileSettings: SettingsGroup[] = [
type: "button",
title: "Open manager",
variant: "secondary",
- action: showAttachmentsDialog
+ action: () => AttachmentsDialog.show({})
}
]
},
@@ -86,7 +83,7 @@ export const ProfileSettings: SettingsGroup[] = [
title: "Backup your recovery key",
variant: "secondary",
action: async () => {
- if (await verifyAccount()) await showRecoveryKeyDialog();
+ if (await verifyAccount()) await RecoveryKeyDialog.show({});
}
}
]
@@ -145,7 +142,8 @@ export const ProfileSettings: SettingsGroup[] = [
title: "Logout",
action: async () => {
if (await showLogoutConfirmation()) {
- await showLoadingDialog({
+ await TaskManager.startTask({
+ type: "modal",
title: "You are being logged out",
subtitle: "Please wait...",
action: () => db.user.logout(true)
diff --git a/apps/web/src/dialogs/settings/sync-settings.ts b/apps/web/src/dialogs/settings/sync-settings.ts
index b6f6714ae..369f712d5 100644
--- a/apps/web/src/dialogs/settings/sync-settings.ts
+++ b/apps/web/src/dialogs/settings/sync-settings.ts
@@ -19,7 +19,7 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.
import { SettingsGroup } from "./types";
import { useStore as useAppStore } from "../../stores/app-store";
-import { confirm } from "../../common/dialog-controller";
+import { ConfirmDialog } from "../confirm";
export const SyncSettings: SettingsGroup[] = [
{
@@ -93,7 +93,7 @@ Use this if some changes are not appearing on this device from other devices. Th
title: "Force push",
variant: "error",
action: () =>
- confirm({
+ ConfirmDialog.show({
title: "Are you sure?",
message:
"This must only be used for troubleshooting. Using them regularly for sync is **not recommended** and will lead to **unexpected data loss** and other issues. If you are having persistent issues with sync, please report them to us at [email protected].",
@@ -114,7 +114,7 @@ Use this if some changes are not appearing on this device from other devices. Th
title: "Force pull",
variant: "error",
action: () =>
- confirm({
+ ConfirmDialog.show({
title: "Are you sure?",
message:
"This must only be used for troubleshooting. Using them regularly for sync is **not recommended** and will lead to **unexpected data loss** and other issues. If you are having persistent issues with sync, please report them to us at [email protected].",
diff --git a/apps/web/src/dialogs/settings/vault-settings.tsx b/apps/web/src/dialogs/settings/vault-settings.tsx
index da96eba52..879f0189c 100644
--- a/apps/web/src/dialogs/settings/vault-settings.tsx
+++ b/apps/web/src/dialogs/settings/vault-settings.tsx
@@ -24,7 +24,7 @@ import Vault from "../../common/vault";
import { showToast } from "../../utils/toast";
import { db } from "../../common/db";
import { isUserPremium } from "../../hooks/use-is-user-premium";
-import { showBuyDialog } from "../../common/dialog-controller";
+import { BuyDialog } from "../buy-dialog/buy-dialog";
export const VaultSettings: SettingsGroup[] = [
{
@@ -43,7 +43,7 @@ export const VaultSettings: SettingsGroup[] = [
type: "button",
title: "Create",
action: () => {
- if (!isUserPremium()) showBuyDialog();
+ if (!isUserPremium()) BuyDialog.show({});
else
Vault.createVault().then((res) => {
useAppStore.getState().setIsVaultCreated(res);
diff --git a/apps/web/src/dialogs/theme-details-dialog.tsx b/apps/web/src/dialogs/theme-details-dialog.tsx
index 1a6aaa9f8..4874f30bf 100644
--- a/apps/web/src/dialogs/theme-details-dialog.tsx
+++ b/apps/web/src/dialogs/theme-details-dialog.tsx
@@ -17,85 +17,84 @@ You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
-import { Perform } from "../common/dialog-controller";
import Dialog from "../components/dialog";
import { ThemeMetadata } from "@notesnook/themes-server";
import { ThemePreview } from "../components/theme-preview";
import { Flex, Link, Text } from "@theme-ui/components";
import { useStore as useThemeStore } from "../stores/theme-store";
+import { BaseDialogProps, DialogManager } from "../common/dialog-manager";
-export type ThemeDetailsDialogProps = {
- onClose: Perform<boolean>;
+export type ThemeDetailsDialogProps = BaseDialogProps<boolean> & {
theme: ThemeMetadata;
};
-function ThemeDetailsDialog(props: ThemeDetailsDialogProps) {
- const { onClose, theme } = props;
- const isThemeCurrentlyApplied = useThemeStore(
- (store) => store.isThemeCurrentlyApplied
- );
+export const ThemeDetailsDialog = DialogManager.register(
+ function ThemeDetailsDialog(props: ThemeDetailsDialogProps) {
+ const { onClose, theme } = props;
+ const isThemeCurrentlyApplied = useThemeStore(
+ (store) => store.isThemeCurrentlyApplied
+ );
- return (
- <Dialog
- isOpen={true}
- onClose={() => onClose(false)}
- positiveButton={{
- text: `Set as default`,
- onClick: () => onClose(true),
- disabled: isThemeCurrentlyApplied(theme.id)
- }}
- negativeButton={{
- text: "Close",
- onClick: () => onClose(false)
- }}
- >
- <ThemePreview theme={theme} />
- <Flex sx={{ flexDirection: "column", mt: 2 }}>
- <Text variant="heading">
- {theme.name}{" "}
+ return (
+ <Dialog
+ isOpen={true}
+ onClose={() => onClose(false)}
+ positiveButton={{
+ text: `Set as default`,
+ onClick: () => onClose(true),
+ disabled: isThemeCurrentlyApplied(theme.id)
+ }}
+ negativeButton={{
+ text: "Close",
+ onClick: () => onClose(false)
+ }}
+ >
+ <ThemePreview theme={theme} />
+ <Flex sx={{ flexDirection: "column", mt: 2 }}>
+ <Text variant="heading">
+ {theme.name}{" "}
+ <Text variant="subBody" sx={{ fontSize: "subtitle" }}>
+ v{theme.version}
+ </Text>
+ </Text>
+ <Text variant="body" sx={{ fontSize: "title" }}>
+ {theme.description}
+ </Text>
<Text variant="subBody" sx={{ fontSize: "subtitle" }}>
- v{theme.version}
+ {theme.authors.map((author) => author.name).join(", ")}
</Text>
- </Text>
- <Text variant="body" sx={{ fontSize: "title" }}>
- {theme.description}
- </Text>
- <Text variant="subBody" sx={{ fontSize: "subtitle" }}>
- {theme.authors.map((author) => author.name).join(", ")}
- </Text>
- {theme.totalInstalls && theme.totalInstalls > 0 ? (
+ {theme.totalInstalls && theme.totalInstalls > 0 ? (
+ <Text variant="subBody" sx={{ fontSize: "subtitle" }}>
+ {theme.totalInstalls} installs
+ </Text>
+ ) : null}
<Text variant="subBody" sx={{ fontSize: "subtitle" }}>
- {theme.totalInstalls} installs
+ Licensed under {theme.license}
</Text>
- ) : null}
- <Text variant="subBody" sx={{ fontSize: "subtitle" }}>
- Licensed under {theme.license}
- </Text>
- <Flex sx={{ gap: 1, mt: 1 }}>
- {theme.homepage && (
- <Link
- href={theme.homepage}
- target="_blank"
- variant="text.subBody"
- sx={{ fontSize: "subtitle", color: "accent" }}
- >
- Website
- </Link>
- )}
- {theme.sourceURL && (
- <Link
- href={theme.sourceURL}
- target="_blank"
- variant="text.subBody"
- sx={{ fontSize: "subtitle", color: "accent" }}
- >
- Source
- </Link>
- )}
+ <Flex sx={{ gap: 1, mt: 1 }}>
+ {theme.homepage && (
+ <Link
+ href={theme.homepage}
+ target="_blank"
+ variant="text.subBody"
+ sx={{ fontSize: "subtitle", color: "accent" }}
+ >
+ Website
+ </Link>
+ )}
+ {theme.sourceURL && (
+ <Link
+ href={theme.sourceURL}
+ target="_blank"
+ variant="text.subBody"
+ sx={{ fontSize: "subtitle", color: "accent" }}
+ >
+ Source
+ </Link>
+ )}
+ </Flex>
</Flex>
- </Flex>
- </Dialog>
- );
-}
-
-export default ThemeDetailsDialog;
+ </Dialog>
+ );
+ }
+);
diff --git a/apps/web/src/navigation/hash-routes.tsx b/apps/web/src/navigation/hash-routes.tsx
index 230f6b1c8..0c83aacd2 100644
--- a/apps/web/src/navigation/hash-routes.tsx
+++ b/apps/web/src/navigation/hash-routes.tsx
@@ -17,45 +17,45 @@ You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
-import {
- showAddReminderDialog,
- showBuyDialog,
- showCreateTagDialog,
- showEditReminderDialog,
- showEmailVerificationDialog,
- showFeatureDialog,
- showOnboardingDialog,
- showSettings
-} from "../common/dialog-controller";
-import {
- showAddNotebookDialog,
- showEditNotebookDialog
-} from "../common/dialog-controller";
import { hashNavigate } from ".";
import { defineRoutes } from "./types";
import { useEditorStore } from "../stores/editor-store";
+import {
+ AddNotebookDialog,
+ EditNotebookDialog
+} from "../dialogs/add-notebook-dialog";
+import { EmailVerificationDialog } from "../dialogs/email-verification-dialog";
+import { SettingsDialog } from "../dialogs/settings";
+import { BuyDialog } from "../dialogs/buy-dialog";
+import {
+ AddReminderDialog,
+ EditReminderDialog
+} from "../dialogs/add-reminder-dialog";
+import { FeatureDialog } from "../dialogs/feature-dialog";
+import { CreateTagDialog } from "../dialogs/item-dialog";
+import { OnboardingDialog } from "../dialogs/onboarding-dialog";
const hashroutes = defineRoutes({
"/": () => {
// return <Editor nonce={"-1"} />;
},
"/email/verify": () => {
- showEmailVerificationDialog().then(afterAction);
+ EmailVerificationDialog.show({}).then(afterAction);
},
"/notebooks/create": () => {
- showAddNotebookDialog().then(afterAction);
+ AddNotebookDialog.show({}).then(afterAction);
},
"/notebooks/:notebookId/edit": ({ notebookId }) => {
- showEditNotebookDialog(notebookId)?.then(afterAction);
+ EditNotebookDialog.show({ notebookId })?.then(afterAction);
},
"/reminders/create": () => {
- showAddReminderDialog().then(afterAction);
+ AddReminderDialog.show({}).then(afterAction);
},
"/reminders/:reminderId/edit": ({ reminderId }) => {
- showEditReminderDialog(reminderId).then(afterAction);
+ EditReminderDialog.show({ reminderId }).then(afterAction);
},
"/tags/create": () => {
- showCreateTagDialog().then(afterAction);
+ CreateTagDialog.show().then(afterAction);
},
"/notes/:noteId/create": ({ noteId }) => {
useEditorStore.getState().openSession(noteId);
@@ -64,24 +64,25 @@ const hashroutes = defineRoutes({
useEditorStore.getState().openSession(noteId);
},
"/buy": () => {
- showBuyDialog().then(afterAction);
+ BuyDialog.show({}).then(afterAction);
},
"/buy/:code": ({ code }: { code: string }) => {
- showBuyDialog("monthly", code).then(afterAction);
+ BuyDialog.show({ couponCode: code, plan: "monthly" }).then(afterAction);
},
"/buy/:plan/:code": ({ plan, code }) => {
- showBuyDialog(plan === "monthly" ? "monthly" : "yearly", code).then(
- afterAction
- );
+ BuyDialog.show({
+ plan: plan === "monthly" ? "monthly" : "yearly",
+ couponCode: code
+ }).then(afterAction);
},
"/welcome": () => {
- showOnboardingDialog("new")?.then(afterAction);
+ OnboardingDialog.show({ type: "new" })?.then(afterAction);
},
"/confirmed": () => {
- showFeatureDialog("confirmed").then(afterAction);
+ FeatureDialog.show({ featureName: "confirmed" }).then(afterAction);
},
"/settings": () => {
- showSettings().then(afterAction);
+ SettingsDialog.show({}).then(afterAction);
}
});
diff --git a/apps/web/src/stores/reminder-store.ts b/apps/web/src/stores/reminder-store.ts
index d0f6ca013..887819ff7 100644
--- a/apps/web/src/stores/reminder-store.ts
+++ b/apps/web/src/stores/reminder-store.ts
@@ -21,13 +21,13 @@ import createStore from "../common/store";
import { db } from "../common/db";
import BaseStore from "./index";
import { TaskScheduler } from "../utils/task-scheduler";
-import { showReminderPreviewDialog } from "../common/dialog-controller";
import dayjs from "dayjs";
import Config from "../utils/config";
import { desktop } from "../common/desktop-bridge";
import { Reminder, VirtualizedGrouping } from "@notesnook/core";
import { store as noteStore } from "./note-store";
import { FilteredSelector } from "@notesnook/core/dist/database/sql-collection";
+import { ReminderPreviewDialog } from "../dialogs/reminder-preview-dialog";
class ReminderStore extends BaseStore<ReminderStore> {
reminders: VirtualizedGrouping<Reminder> | undefined = undefined;
@@ -115,7 +115,7 @@ function scheduleReminder(id: string, reminder: Reminder, cron: string) {
if (tag) {
await desktop?.integration.bringToFront.query();
- showReminderPreviewDialog(reminder);
+ await ReminderPreviewDialog.show({ reminder });
}
} else {
const notification = new Notification(reminder.title, {
@@ -129,7 +129,7 @@ function scheduleReminder(id: string, reminder: Reminder, cron: string) {
notification.onclick = function () {
window.focus();
- showReminderPreviewDialog(reminder);
+ ReminderPreviewDialog.show({ reminder });
};
}
diff --git a/apps/web/src/stores/user-store.ts b/apps/web/src/stores/user-store.ts
index 74edb075a..ea83dc907 100644
--- a/apps/web/src/stores/user-store.ts
+++ b/apps/web/src/stores/user-store.ts
@@ -22,16 +22,14 @@ import { db } from "../common/db";
import BaseStore from "./index";
import config from "../utils/config";
import { EV, EVENTS } from "@notesnook/core/dist/common";
-import {
- showAccountLoggedOutNotice,
- showOnboardingDialog
-} from "../common/dialog-controller";
import Config from "../utils/config";
import { hashNavigate } from "../navigation";
import { isUserPremium } from "../hooks/use-is-user-premium";
import { SUBSCRIPTION_STATUS } from "../common/constants";
import { ANALYTICS_EVENTS, trackEvent } from "../utils/analytics";
import { AuthenticatorType, User } from "@notesnook/core";
+import { ConfirmDialog } from "../dialogs/confirm";
+import { OnboardingDialog } from "../dialogs/onboarding-dialog";
class UserStore extends BaseStore<UserStore> {
isLoggedIn?: boolean;
@@ -78,9 +76,10 @@ class UserStore extends BaseStore<UserStore> {
state.user.subscription = subscription;
});
if (!wasUserPremium && isUserPremium())
- showOnboardingDialog(
- subscription.type === SUBSCRIPTION_STATUS.TRIAL ? "trial" : "pro"
- );
+ OnboardingDialog.show({
+ type:
+ subscription.type === SUBSCRIPTION_STATUS.TRIAL ? "trial" : "pro"
+ });
});
EV.subscribe(EVENTS.userEmailConfirmed, () => {
@@ -94,7 +93,11 @@ class UserStore extends BaseStore<UserStore> {
});
config.clear();
if (reason) {
- await showAccountLoggedOutNotice(reason);
+ await ConfirmDialog.show({
+ title: "You were logged out",
+ message: reason,
+ negativeButtonText: "Okay"
+ });
}
});
diff --git a/apps/web/src/views/app-lock.tsx b/apps/web/src/views/app-lock.tsx
index a90def5f7..5dcac210c 100644
--- a/apps/web/src/views/app-lock.tsx
+++ b/apps/web/src/views/app-lock.tsx
@@ -32,7 +32,6 @@ import { ErrorText } from "../components/error-text";
import Field from "../components/field";
import { startIdleDetection } from "../utils/idle-detection";
import { onPageVisibilityChanged } from "../utils/page-visibility";
-import { closeOpenedDialog } from "../common/dialog-controller";
import { WebAuthn } from "../utils/webauthn";
import { getDocumentTitle, setDocumentTitle } from "../utils/dom";
import { CredentialWithoutSecret, useKeyStore } from "../interfaces/key-store";
@@ -90,7 +89,7 @@ export default function AppLock(props: PropsWithChildren<unknown>) {
useEffect(() => {
if (isLocked) {
windowTitle.current = getDocumentTitle();
- closeOpenedDialog();
+ // ../common/dialog-controller closeOpenedDialog();
document.title = `Notesnook 🔒`;
} else {
setDocumentTitle(windowTitle.current);
diff --git a/apps/web/src/views/auth.tsx b/apps/web/src/views/auth.tsx
index 0ae9a24ef..97f8e7696 100644
--- a/apps/web/src/views/auth.tsx
+++ b/apps/web/src/views/auth.tsx
@@ -38,12 +38,10 @@ import { Loader } from "../components/loader";
import { showToast } from "../utils/toast";
import AuthContainer from "../components/auth-container";
import { useTimer } from "../hooks/use-timer";
-import {
- showLoadingDialog,
- showLogoutConfirmation
-} from "../common/dialog-controller";
import { ErrorText } from "../components/error-text";
import { AuthenticatorType, User } from "@notesnook/core";
+import { showLogoutConfirmation } from "../dialogs/confirm";
+import { TaskManager } from "../common/task-manager";
type EmailFormData = {
email: string;
@@ -494,7 +492,8 @@ function SessionExpiry(props: BaseAuthComponentProps<"sessionExpiry">) {
}}
onClick={async () => {
if (await showLogoutConfirmation()) {
- await showLoadingDialog({
+ await TaskManager.startTask({
+ type: "modal",
title: "You are being logged out",
action: () => db.user.logout(true),
subtitle: "Please wait..."
diff --git a/apps/web/src/views/notebook.tsx b/apps/web/src/views/notebook.tsx
index d18699f3c..4876daa4b 100644
--- a/apps/web/src/views/notebook.tsx
+++ b/apps/web/src/views/notebook.tsx
@@ -42,7 +42,6 @@ import { useStore as useNotesStore } from "../stores/note-store";
import { useStore as useNotebookStore } from "../stores/notebook-store";
import { db } from "../common/db";
import { getFormattedDate } from "@notesnook/common";
-import { showAddNotebookDialog } from "../common/dialog-controller";
import {
UncontrolledTreeEnvironment,
Tree,
@@ -63,6 +62,7 @@ import {
PanelResizeHandle,
ImperativePanelHandle
} from "react-resizable-panels";
+import { AddNotebookDialog } from "../dialogs/add-notebook-dialog";
type NotebookProps = {
rootId: string;
@@ -260,9 +260,9 @@ function SubNotebooks({
}}
onClick={async (e) => {
e.stopPropagation();
- await showAddNotebookDialog(
- context?.type === "notebook" ? context.id : rootId
- );
+ await AddNotebookDialog.show({
+ parentId: context?.type === "notebook" ? context.id : rootId
+ });
}}
>
<Plus size={20} />
diff --git a/apps/web/src/views/recovery.tsx b/apps/web/src/views/recovery.tsx
index 117d7cbb8..341e91234 100644
--- a/apps/web/src/views/recovery.tsx
+++ b/apps/web/src/views/recovery.tsx
@@ -26,11 +26,11 @@ import { showToast } from "../utils/toast";
import AuthContainer from "../components/auth-container";
import { AuthField, SubmitButton } from "./auth";
import { createBackup, restoreBackupFile, selectBackupFile } from "../common";
-import { showRecoveryKeyDialog } from "../common/dialog-controller";
import Config from "../utils/config";
import { EVENTS } from "@notesnook/core/dist/common";
import { ErrorText } from "../components/error-text";
import { User } from "@notesnook/core";
+import { RecoveryKeyDialog } from "../dialogs/recovery-key-dialog";
type RecoveryMethodType = "key" | "backup" | "reset";
type RecoveryMethodsFormData = Record<string, unknown>;
@@ -537,7 +537,7 @@ function Final(_props: BaseRecoveryComponentProps<"final">) {
const [isReady, setIsReady] = useState(false);
useEffect(() => {
async function finalize() {
- await showRecoveryKeyDialog();
+ await RecoveryKeyDialog.show({});
if (!isSessionExpired()) {
await db.user.logout(true, "Password changed.");
await db.user.clearSessions(true);
diff --git a/apps/web/src/views/trash.tsx b/apps/web/src/views/trash.tsx
index e66edc2f9..f950e3114 100644
--- a/apps/web/src/views/trash.tsx
+++ b/apps/web/src/views/trash.tsx
@@ -18,7 +18,6 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import ListContainer from "../components/list-container";
-import { confirm } from "../common/dialog-controller";
import { useStore, store } from "../stores/trash-store";
import { showToast } from "../utils/toast";
import useNavigate from "../hooks/use-navigate";
@@ -26,6 +25,7 @@ import Placeholder from "../components/placeholders";
import { useSearch } from "../hooks/use-search";
import { db } from "../common/db";
import { ListLoader } from "../components/loaders/list-loader";
+import { ConfirmDialog } from "../dialogs/confirm";
function Trash() {
useNavigate("trash", store.refresh);
@@ -45,7 +45,7 @@ function Trash() {
items={filteredItems || items}
button={{
onClick: function () {
- confirm({
+ ConfirmDialog.show({
title: "Clear Trash",
subtitle: "Are you sure you want to clear all the trash?",
positiveButtonText: "Clear trash",