A fully open source & end-to-end encrypted note taking alternative to Evernote.
TypeScript asp-net-coredotnet-coreelectronfosshacktoberfestnote-managmentnote-takingnote-taking-appnotebooknotesnotes-appopen-sourceopensourceprivacyproductivityreactreact-nativereactjsself-hosted
refactor: migrate dialogcontroller to typescript
thecodrrf8189f882c3d
diff --git a/apps/web/package.json b/apps/web/package.jsonindex c9ae53b29..ea4acd790 100644--- a/apps/web/package.json+++ b/apps/web/package.json@@ -72,6 +72,7 @@"@types/hookrouter": "^2.2.5","@types/node-fetch": "^2.5.10","@types/quill": "^2.0.5",+ "@types/react-dom": "^18.0.0","@types/react-modal": "^3.13.1","@types/rebass": "^4.0.10","@types/rebass__forms": "^4.0.6",diff --git a/apps/web/src/common/dialogcontroller.js b/apps/web/src/common/dialog-controller.tsxsimilarity index 60%rename from apps/web/src/common/dialogcontroller.jsrename to apps/web/src/common/dialog-controller.tsxindex 4ee30e8ab..b1d9deb3d 100644--- a/apps/web/src/common/dialogcontroller.js+++ b/apps/web/src/common/dialog-controller.tsx@@ -1,5 +1,5 @@-import React from "react";import ReactDOM from "react-dom";+import Dialogs from "../components/dialogs";import { hardNavigate, hashNavigate } from "../navigation";import ThemeProvider from "../components/theme-provider";import { qclone } from "qclone";@@ -13,24 +13,48 @@ import { showToast } from "../utils/toast";import { Box, Flex, Text } from "rebass";import * as Icon from "../components/icons";import Config from "../utils/config";-import Dialogs from "../components/dialogs";+import { formatDate } from "notes-core/utils/date";import downloadUpdate from "../commands/download-update";import installUpdate from "../commands/install-update";-import { getChangelog } from "../utils/version";+import { AppVersion, getChangelog } from "../utils/version";import { isDesktop } from "../utils/platform";-import { pluralize } from "../utils/string";--function showDialog(dialog) {+import { Period } from "../components/dialogs/buy-dialog/types";+import { AuthenticatorType } from "../components/dialogs/multi-factor-dialog";+import { FeatureKeys } from "../components/dialogs/feature-dialog";++type DialogIds = keyof DialogTypes;+type DialogTypes = typeof Dialogs;+export type Perform = (result: boolean) => void;+type RenderDialog<TId extends DialogIds, TReturnType> = (+ dialog: DialogTypes[TId],+ perform: (result: TReturnType) => void+) => JSX.Element;++const openDialogs: Partial<Record<DialogIds, boolean>> = {};+function showDialog<TId extends DialogIds, TReturnType>(+ id: TId,+ render: RenderDialog<TId, TReturnType>+): Promise<TReturnType> {return new Promise((resolve, reject) => {+ if (openDialogs[id]) return false;+const container = document.createElement("div");- const perform = (result) => {+ container.id = id;++ const perform = (result: TReturnType) => {+ openDialogs[id] = false;ReactDOM.unmountComponentAtNode(container);+ container.remove();hashNavigate("/", { replace: true, notify: false });resolve(result);};- const PropDialog = dialog(Dialogs, perform);- ReactDOM.render(<ThemeProvider>{PropDialog}</ThemeProvider>, container);+ const PropDialog = render(Dialogs[id], perform);+ ReactDOM.render(+ <ThemeProvider>{PropDialog}</ThemeProvider>,+ container,+ () => (openDialogs[id] = true)+ );});}@@ -39,26 +63,47 @@ export function closeOpenedDialog() {dialogs.forEach((elem) => elem.remove());}-export function showEditNotebookDialog(notebookId) {- const notebook = db.notebooks.notebook(notebookId)?.data;+export function showAddNotebookDialog() {+ return showDialog("AddNotebookDialog", (Dialog, perform) => (+ <Dialog+ isOpen={true}+ onDone={async (nb: any) => {+ // add the notebook to db+ await db.notebooks?.add({ ...nb });+ notebookStore.refresh();++ showToast("success", "Notebook added successfully!");+ perform(true);+ }}+ onClose={() => {+ perform(false);+ }}+ />+ ));+}++export function showEditNotebookDialog(notebookId: string) {+ const notebook = db.notebooks?.notebook(notebookId)?.data;if (!notebook) return false;- return showDialog((Dialogs, perform) => (- <Dialogs.AddNotebookDialog+ return showDialog("AddNotebookDialog", (Dialog, perform) => (+ <DialogisOpen={true}notebook={notebook}edit={true}- onDone={async (nb, deletedTopics) => {+ onDone={async (nb: any, deletedTopics: string[]) => {// we remove the topics from notebook// beforehand so we can add them manually, laterconst topics = qclone(nb.topics);nb.topics = [];- let notebookId = await db.notebooks.add(nb);+ let notebookId = await db.notebooks?.add(nb);// add or delete topics as required- const notebookTopics = db.notebooks.notebook(notebookId).topics;- await notebookTopics.add(...topics);- await notebookTopics.delete(...deletedTopics);+ const notebookTopics = db.notebooks?.notebook(notebookId).topics;+ if (notebookTopics) {+ await notebookTopics.add(...topics);+ await notebookTopics.delete(...deletedTopics);+ }notebookStore.refresh();noteStore.refresh();@@ -74,28 +119,9 @@ export function showEditNotebookDialog(notebookId) {));}-export function showAddNotebookDialog() {- return showDialog((Dialogs, perform) => (- <Dialogs.AddNotebookDialog- isOpen={true}- onDone={async (nb) => {- // add the notebook to db- await db.notebooks.add({ ...nb });- notebookStore.refresh();-- showToast("success", "Notebook added successfully!");- perform(true);- }}- onClose={() => {- perform(false);- }}- />- ));-}--export function showBuyDialog(plan, couponCode) {- return showDialog((Dialogs, perform) => (- <Dialogs.BuyDialog+export function showBuyDialog(plan?: Period, couponCode?: string) {+ return showDialog("BuyDialog", (Dialog, perform) => (+ <Dialogplan={plan}couponCode={couponCode}onClose={() => perform(false)}@@ -103,43 +129,33 @@ export function showBuyDialog(plan, couponCode) {));}-export function showBackupDialog() {- return showDialog((Dialogs, perform) => (- <Dialogs.BackupDialog onClose={() => perform(false)} />- ));-}--export function confirm({- title,- subtitle,- message,- yesText,- noText,- yesAction,- width,-}) {- return showDialog((Dialogs, perform) => (- <Dialogs.Confirm- title={title}- subtitle={subtitle}- message={message}- yesText={yesText}- width={width}- noText={noText}+type ConfirmDialogProps = {+ title?: string;+ subtitle?: string;+ message?: string | JSX.Element;+ yesText?: string;+ noText?: string;+ yesAction?: () => void;+ width?: string;+};+export function confirm(props: ConfirmDialogProps) {+ return showDialog("Confirm", (Dialog, perform) => (+ <Dialog+ {...props}onNo={() => perform(false)}onYes={() => {- if (yesAction) yesAction();+ if (props.yesAction) props.yesAction();perform(true);}}/>));}-export function showError(title, message) {+export function showError(title: string, message: string) {return confirm({ title, message, yesText: "Okay" });}-export function showMultiDeleteConfirmation(length) {+export function showMultiDeleteConfirmation(length: number) {return confirm({title: `Delete ${length} items?`,message: (@@ -156,7 +172,7 @@ export function showMultiDeleteConfirmation(length) {});}-export function showMultiPermanentDeleteConfirmation(length) {+export function showMultiPermanentDeleteConfirmation(length: number) {return confirm({title: `Permanently delete ${length} items?`,message: (@@ -194,25 +210,7 @@ export function showClearSessionsConfirmation() {});}-// export function showAccountDeletedNotice() {-// return confirm(Icon.Logout, {-// title: `Account deleted`,-// message:-// "You deleted your account from another device. You have been logged out.",-// yesText: `Okay`,-// });-// }--// export function showPasswordChangedNotice() {-// return confirm(Icon.Logout, {-// title: `Account password changed`,-// message:-// "Your account password was changed, please login again using the new password.",-// yesText: `Okay`,-// });-// }--export function showAccountLoggedOutNotice(reason) {+export function showAccountLoggedOutNotice(reason?: string) {return confirm({title: "You were logged out",message: reason,@@ -222,7 +220,9 @@ export function showAccountLoggedOutNotice(reason) {});}-export function showAppUpdatedNotice(version) {+export function showAppUpdatedNotice(+ version: AppVersion & { changelog?: string }+) {return confirm({title: `Welcome to v${version.formatted}`,message: (@@ -249,68 +249,57 @@ export function showAppUpdatedNotice(version) {}export function showEmailVerificationDialog() {- return showDialog((Dialogs, perform) => (- <Dialogs.EmailVerificationDialog onCancel={() => perform(false)} />+ return showDialog("EmailVerificationDialog", (Dialog, perform) => (+ <Dialog onCancel={() => perform(false)} />));}-export function showExportDialog(noteIds) {- return showDialog((Dialogs, perform) => (- <Dialogs.ExportDialog- noteIds={noteIds}- title={`Export ${noteIds.length} ${pluralize(- noteIds.length,- "note",- "notes"- )}`}- icon={Icon.Export}- onClose={() => perform(false)}- onDone={() => perform(true)}- />- ));-}--export function showLoadingDialog(dialogData) {+type LoadingDialogProps = {+ title: string;+ message?: string;+ subtitle: string;+ action: () => void;+};+export function showLoadingDialog(dialogData: LoadingDialogProps) {const { title, message, subtitle, action } = dialogData;- return showDialog((Dialogs, perform) => (- <Dialogs.LoadingDialog+ return showDialog("LoadingDialog", (Dialog, perform) => (+ <Dialogtitle={title}subtitle={subtitle}message={message}action={action}- onDone={(e) => perform(e)}+ onDone={(e: boolean) => perform(e)}/>));}-/**- *- * @param {{title: string, subtitle?: string, action: Function}} dialogData- * @returns- */-export function showProgressDialog(dialogData) {+type ProgressDialogProps = {+ title: string;+ subtitle: string;+ action: any;+};+export function showProgressDialog<T>(dialogData: ProgressDialogProps) {const { title, subtitle, action } = dialogData;- return showDialog((Dialogs, perform) => (- <Dialogs.ProgressDialog- title={title}- subtitle={subtitle}- action={action}- onDone={(e) => perform(e)}- />+ return showDialog<"ProgressDialog", T>(+ "ProgressDialog",+ (Dialog, perform) => (+ <Dialog+ title={title}+ subtitle={subtitle}+ action={action}+ onDone={(e: T) => perform(e)}+ />+ )+ );+}++export function showMoveNoteDialog(noteIds: string[]) {+ return showDialog("MoveDialog", (Dialog, perform) => (+ <Dialog noteIds={noteIds} onClose={(res: boolean) => perform(res)} />));}-export function showMoveNoteDialog(noteIds) {- return showDialog((Dialogs, perform) => (- <Dialogs.MoveDialog- noteIds={noteIds}- onClose={() => perform(false)}- onMove={() => perform(true)}- />- ));-}--function getDialogData(type) {+function getDialogData(type: string) {switch (type) {case "create_vault":return {@@ -412,14 +401,17 @@ function getDialogData(type) {positiveButtonText: "Delete Account",};default:- return;+ return {};}}-export function showPasswordDialog(type, validate) {+export function showPasswordDialog(+ type: string,+ validate: (password: string) => boolean+) {const { title, subtitle, positiveButtonText, checks } = getDialogData(type);- return showDialog((Dialogs, perform) => (- <Dialogs.PasswordDialog+ return showDialog("PasswordDialog", (Dialog, perform) => (+ <Dialogtype={type}title={title}subtitle={subtitle}@@ -433,23 +425,23 @@ export function showPasswordDialog(type, validate) {}export function showRecoveryKeyDialog() {- return showDialog((Dialogs, perform) => (- <Dialogs.RecoveryKeyDialog onDone={() => perform(true)} />+ return showDialog("RecoveryKeyDialog", (Dialog, perform) => (+ <Dialog onDone={() => perform(true)} />));}export function showCreateTopicDialog() {- return showDialog((Dialogs, perform) => (- <Dialogs.ItemDialog+ return showDialog("ItemDialog", (Dialog, perform) => (+ <Dialogtitle={"Create topic"}subtitle={"You can create as many topics as you want."}onClose={() => {perform(false);}}- onAction={async (topic) => {+ onAction={async (topic: any) => {if (!topic) return;const notebookId = notebookStore.get().selectedNotebookId;- await db.notebooks.notebook(notebookId).topics.add(topic);+ await db.notebooks?.notebook(notebookId).topics.add(topic);notebookStore.setSelectedNotebook(notebookId);showToast("success", "Topic created!");perform(true);@@ -458,22 +450,22 @@ export function showCreateTopicDialog() {));}-export function showEditTopicDialog(notebookId, topicId) {- const topic = db.notebooks- .notebook(notebookId)+export function showEditTopicDialog(notebookId: string, topicId: string) {+ const topic: any = db.notebooks+ ?.notebook(notebookId)?.topics?.topic(topicId)?._topic;if (!topic) return;- return showDialog((Dialogs, perform) => (- <Dialogs.ItemDialog+ return showDialog("ItemDialog", (Dialog, perform) => (+ <Dialogtitle={"Edit topic"}subtitle={`You are editing "${topic.title}" topic.`}defaultValue={topic.title}icon={Icon.Topic}item={topic}onClose={() => perform(false)}- onAction={async (t) => {+ onAction={async (t: string) => {await db.notebooks- .notebook(topic.notebookId)+ ?.notebook(topic.notebookId).topics.add({ ...topic, title: t });notebookStore.setSelectedNotebook(topic.notebookId);appStore.refreshNavItems();@@ -485,41 +477,41 @@ export function showEditTopicDialog(notebookId, topicId) {}export function showCreateTagDialog() {- return showDialog((Dialogs, perform) => (- <Dialogs.ItemDialog+ return showDialog("ItemDialog", (Dialog, perform) => (+ <Dialogtitle={"Create tag"}subtitle={"You can create as many tags as you want."}onClose={() => {perform(false);}}- onAction={async (title) => {+ onAction={async (title: string) => {if (!title) return showToast("error", "Tag title cannot be empty.");try {- await db.tags.add(title);+ await db.tags?.add(title);showToast("success", "Tag created!");tagStore.refresh();perform(true);} catch (e) {- showToast("error", e.message);+ if (e instanceof Error) showToast("error", e.message);}}}/>));}-export function showEditTagDialog(tagId) {- const tag = db.tags.tag(tagId);+export function showEditTagDialog(tagId: string) {+ const tag = db.tags?.tag(tagId);if (!tag) return;- return showDialog((Dialogs, perform) => (- <Dialogs.ItemDialog+ return showDialog("ItemDialog", (Dialog, perform) => (+ <Dialogtitle={"Edit tag"}- subtitle={`You are editing #${db.tags.alias(tag.id)}.`}- defaultValue={db.tags.alias(tag.id)}+ subtitle={`You are editing #${db.tags?.alias(tag.id)}.`}+ defaultValue={db.tags?.alias(tag.id)}item={tag}onClose={() => perform(false)}- onAction={async (title) => {+ onAction={async (title: string) => {if (!title) return;- await db.tags.rename(tagId, title);+ await db.tags?.rename(tagId, title);showToast("success", "Tag edited!");tagStore.refresh();editorStore.refreshTags();@@ -531,19 +523,19 @@ export function showEditTagDialog(tagId) {));}-export function showRenameColorDialog(colorId) {- const color = db.colors.tag(colorId);+export function showRenameColorDialog(colorId: string) {+ const color = db.colors?.tag(colorId);if (!color) return;- return showDialog((Dialogs, perform) => (- <Dialogs.ItemDialog+ return showDialog("ItemDialog", (Dialog, perform) => (+ <Dialogtitle={"Rename color"}- subtitle={`You are renaming color ${db.colors.alias(color.id)}.`}+ subtitle={`You are renaming color ${db.colors?.alias(color.id)}.`}item={color}- defaultValue={db.colors.alias(color.id)}+ defaultValue={db.colors?.alias(color.id)}onClose={() => perform(false)}- onAction={async (title) => {+ onAction={async (title: string) => {if (!title) return;- await db.colors.rename(colorId, title);+ await db.colors?.rename(colorId, title);showToast("success", "Color renamed!");appStore.refreshNavItems();perform(true);@@ -552,22 +544,19 @@ export function showRenameColorDialog(colorId) {));}-export function showFeatureDialog(featureName) {- return showDialog((Dialogs, perform) => (- <Dialogs.FeatureDialog- featureName={featureName}- onClose={(res) => perform(res)}- />+export function showFeatureDialog(featureName: FeatureKeys) {+ return showDialog("FeatureDialog", (Dialog, perform) => (+ <Dialog featureName={featureName} onClose={(res) => perform(res)} />));}-export function showReminderDialog(reminderKey) {+export function showReminderDialog(reminderKey: string) {if (Config.get(reminderKey, false)) return;- return showDialog((Dialogs, perform) => (- <Dialogs.ReminderDialog+ return showDialog("ReminderDialog", (Dialog, perform) => (+ <DialogreminderKey={reminderKey}- onClose={(res) => {+ onClose={(res: boolean) => {Config.set(reminderKey, true);perform(res);}}@@ -576,16 +565,19 @@ export function showReminderDialog(reminderKey) {}export function showTrackingDetailsDialog() {- return showDialog((Dialogs, perform) => (- <Dialogs.TrackingDetailsDialog onClose={(res) => perform(res)} />+ return showDialog("TrackingDetailsDialog", (Dialog, perform) => (+ <Dialog onClose={(res: boolean) => perform(res)} />));}-export function showAnnouncementDialog(announcement, remove) {- return showDialog((Dialogs, perform) => (- <Dialogs.AnnouncementDialog+export function showAnnouncementDialog(+ announcement: any,+ remove: (id: string) => void+) {+ return showDialog("AnnouncementDialog", (Dialog, perform) => (+ <Dialogannouncement={announcement}- onClose={(res) => {+ onClose={(res: boolean) => {remove(announcement.id);perform(res);}}@@ -594,9 +586,9 @@ export function showAnnouncementDialog(announcement, remove) {}export function showIssueDialog() {- return showDialog((Dialogs, perform) => (- <Dialogs.IssueDialog- onClose={(res) => {+ return showDialog("IssueDialog", (Dialog, perform) => (+ <Dialog+ onClose={(res: boolean) => {perform(res);}}/>@@ -604,69 +596,71 @@ export function showIssueDialog() {}export function showImportDialog() {- return showDialog((Dialogs, perform) => (- <Dialogs.ImportDialog onClose={(res) => perform(res)} />+ return showDialog("ImportDialog", (Dialog, perform) => (+ <Dialog onClose={(res: boolean) => perform(res)} />));}-export function showMultifactorDialog(primaryMethod = "") {- return showDialog((Dialogs, perform) => (- <Dialogs.MultifactorDialog- onClose={(res) => perform(res)}- primaryMethod={primaryMethod}- />+export function showMultifactorDialog(primaryMethod?: AuthenticatorType) {+ return showDialog("MultifactorDialog", (Dialog, perform) => (+ <Dialog onClose={(res) => perform(res)} primaryMethod={primaryMethod} />));}-export function show2FARecoveryCodesDialog(primaryMethod) {- return showDialog((Dialogs, perform) => (- <Dialogs.RecoveryCodesDialog- 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((Dialogs, perform) => (- <Dialogs.AttachmentsDialog onClose={(res) => perform(res)} />+ return showDialog("AttachmentsDialog", (Dialog, perform) => (+ <Dialog onClose={(res: boolean) => perform(res)} />));}-export function showOnboardingDialog(type) {+export function showOnboardingDialog(type: string) {if (!type) return;-- return showDialog((Dialogs, perform) => (- <Dialogs.OnboardingDialog type={type} onClose={(res) => perform(res)} />+ return showDialog("OnboardingDialog", (Dialog, perform) => (+ <Dialog type={type} onClose={(res: boolean) => perform(res)} />));}-export function showInvalidSystemTimeDialog({ serverTime, localTime }) {- return showDialog((Dialogs) => (- <Dialogs.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:{" "}- {formatDate(serverTime, { dateStyle: "medium", timeStyle: "medium" })}- <br />- Local time:{" "}- {formatDate(localTime, { dateStyle: "medium", timeStyle: "medium" })}- <br />- Please sync your system time with{" "}- <a href="https://time.is">https://time.is/</a>.- </>- }- yesText="Reload app"- onYes={() => window.location.reload()}- />- ));+export function showInvalidSystemTimeDialog({+ serverTime,+ localTime,+}: {+ serverTime: number;+ localTime: number;+}) {+ return 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:{" "}+ {formatDate(serverTime, { dateStyle: "medium", timeStyle: "medium" })}+ <br />+ Local time:{" "}+ {formatDate(localTime, { dateStyle: "medium", timeStyle: "medium" })}+ <br />+ Please sync your system time with{" "}+ <a href="https://time.is">https://time.is/</a>.+ </>+ ),+ yesText: "Reload app",+ yesAction: () => window.location.reload(),+ });}-export function showUpdateAvailableNotice({ changelog, version }) {+export function showUpdateAvailableNotice({+ changelog,+ version,+}: {+ changelog: string;+ version: string;+}) {return showUpdateDialog({title: `New version available`,subtitle: `v${version} is available for download`,@@ -675,7 +669,7 @@ export function showUpdateAvailableNotice({ changelog, version }) {});}-export async function showUpdateReadyNotice({ version }) {+export async function showUpdateReadyNotice({ version }: { version: string }) {const changelog = isDesktop() ? null : await getChangelog(version);return await showUpdateDialog({title: `Update ready for installation`,@@ -688,7 +682,21 @@ export async function showUpdateReadyNotice({ version }) {});}-function showUpdateDialog({ title, subtitle, changelog, action }) {+type UpdateDialogProps = {+ title: string;+ subtitle: string;+ changelog: string;+ action: {+ text: string;+ onClick: () => void;+ };+};+function showUpdateDialog({+ title,+ subtitle,+ changelog,+ action,+}: UpdateDialogProps) {return confirm({title,subtitle,diff --git a/apps/web/src/common/task-manager.ts b/apps/web/src/common/task-manager.tsindex 904779f4b..a00dfa336 100644--- a/apps/web/src/common/task-manager.ts+++ b/apps/web/src/common/task-manager.ts@@ -55,7 +55,7 @@ export class TaskManager {removeStatus(statusTask.id);return result;case "modal":- return await showProgressDialog({+ return await showProgressDialog<T>({title: task.title,subtitle: task.subtitle,action: task.action,diff --git a/apps/web/src/components/dialogs/feature-dialog.tsx b/apps/web/src/components/dialogs/feature-dialog.tsxindex 5ac3af9e1..3c4c5812b 100644--- a/apps/web/src/components/dialogs/feature-dialog.tsx+++ b/apps/web/src/components/dialogs/feature-dialog.tsx@@ -24,7 +24,7 @@ type Feature = {subFeatures?: SubFeature[];};-type FeatureKeys = "confirmed" | "highlights";+export type FeatureKeys = "confirmed" | "highlights";const features: Record<FeatureKeys, Feature> = {confirmed: {title: "Email confirmed!",@@ -63,11 +63,11 @@ const features: Record<FeatureKeys, Feature> = {},},shouldShow: () => {- const hasShown = Config.get(- `${appVersion.numerical}:highlights`,- false- ) as boolean;- return !isTesting() && !hasShown;+ const key = `${appVersion.numerical}:highlights`;+ const hasShownBefore = Config.get(key, false) as boolean;+ const hasShownAny = Config.has((k) => k.endsWith(":highlights"));+ if (!hasShownAny) Config.set(key, true);+ return hasShownAny && !isTesting() && !hasShownBefore;},},};diff --git a/apps/web/src/components/dialogs/multifactordialog.tsx b/apps/web/src/components/dialogs/multifactordialog.tsxindex 6c5450ecd..f5d55c348 100644--- a/apps/web/src/components/dialogs/multifactordialog.tsx+++ b/apps/web/src/components/dialogs/multifactordialog.tsx@@ -29,7 +29,7 @@ import { useSessionState } from "../../utils/hooks";import { exportToPDF } from "../../common/export";import { useTimer } from "../../hooks/use-timer";import { phone } from "phone";-import { showMultifactorDialog } from "../../common/dialog-controller";+import { Perform, showMultifactorDialog } from "../../common/dialog-controller";const QRCode = React.lazy(() => import("../../re-exports/react-qrcode-logo"));export type AuthenticatorType = "app" | "sms" | "email";@@ -48,7 +48,7 @@ type Authenticator = {type StepComponentProps = {onNext: (...args: any[]) => void;- onClose?: () => void;+ onClose?: Perform;onError?: (error: string) => void;};@@ -80,12 +80,12 @@ type VerifyAuthenticatorFormProps = PropsWithChildren<{type SetupAuthenticatorProps = { onSubmitCode: SubmitCodeFunction };type MultifactorDialogProps = {- onClose: () => void;+ onClose: Perform;primaryMethod?: AuthenticatorType;};type RecoveryCodesDialogProps = {- onClose: () => void;+ onClose: Perform;primaryMethod: AuthenticatorType;};@@ -245,7 +245,7 @@ export function MultifactorDialog(props: MultifactorDialogProps) {{step.component && (<step.componentonNext={(...args) => {- if (!step.next) return onClose();+ if (!step.next) return onClose(true);const nextStepCreator: Function =step.next !== "recoveryCodes" && primaryMethod@@ -750,7 +750,11 @@ function TwoFactorEnabled(props: TwoFactorEnabledProps) {<Text variant={"body"} color="fontTertiary" mt={1} textAlign="center">Your account is now 100% secure against unauthorized logins.</Text>- <Button mt={2} sx={{ borderRadius: 100, px: 6 }} onClick={props.onClose}>+ <Button+ mt={2}+ sx={{ borderRadius: 100, px: 6 }}+ onClick={() => props.onClose?.(true)}+ >Done</Button>@@ -758,7 +762,7 @@ function TwoFactorEnabled(props: TwoFactorEnabledProps) {variant={"anchor"}mt={2}onClick={() => {- props.onClose && props.onClose();+ props.onClose && props.onClose(true);setTimeout(async () => {await showMultifactorDialog(props.authenticatorType);}, 100);@@ -792,7 +796,11 @@ function Fallback2FAEnabled(props: Fallback2FAEnabledProps) {{mfaMethodToPhrase(fallbackMethod)} in case you lose access to your{" "}{mfaMethodToPhrase(primaryMethod)}.</Text>- <Button mt={2} sx={{ borderRadius: 100, px: 6 }} onClick={onClose}>+ <Button+ mt={2}+ sx={{ borderRadius: 100, px: 6 }}+ onClick={() => onClose?.(true)}+ >Done</Button></Flex>diff --git a/apps/web/src/components/dialogs/reminder-dialog.js b/apps/web/src/components/dialogs/reminder-dialog.jsindex 783367d80..94e1c45ff 100644--- a/apps/web/src/components/dialogs/reminder-dialog.js+++ b/apps/web/src/components/dialogs/reminder-dialog.js@@ -73,7 +73,7 @@ const reminders = {function ReminderDialog(props) {const { reminderKey } = props;const reminder = reminders[reminderKey];- if (!reminder) return;+ if (!reminder) return null;return (<Dialogdiff --git a/apps/web/src/utils/config.js b/apps/web/src/utils/config.jsdeleted file mode 100644index 2c1991c62..000000000--- a/apps/web/src/utils/config.js+++ /dev/null@@ -1,19 +0,0 @@-import { tryParse } from "./parse";--function set(key, value) {- window.localStorage.setItem(key, JSON.stringify(value));-}--function get(key, def) {- const value = window.localStorage.getItem(key);- if (!value) return def;-- return tryParse(value);-}--function clear() {- window.localStorage.clear();-}--const Config = { set, get, clear };-export default Config;diff --git a/apps/web/src/utils/config.ts b/apps/web/src/utils/config.tsnew file mode 100644index 000000000..276d83e7d--- /dev/null+++ b/apps/web/src/utils/config.ts@@ -0,0 +1,38 @@+import { tryParse } from "./parse";++function set<T>(key: string, value: T) {+ window.localStorage.setItem(key, JSON.stringify(value));+}++function get<T>(key: string, def?: T) {+ const value = window.localStorage.getItem(key);+ if (!value) return def;++ return tryParse(value);+}++function clear() {+ window.localStorage.clear();+}++function all(): Record<string, any> {+ const data: Record<string, any> = {};+ for (let i = 0; i < window.localStorage.length; ++i) {+ const key = window.localStorage.key(i);+ if (!key) continue;+ data[key] = get(key);+ }+ return data;+}++function has(predicate: (key: string) => boolean) {+ for (let i = 0; i < window.localStorage.length; ++i) {+ const key = window.localStorage.key(i);+ if (!key) continue;+ if (predicate(key)) return true;+ }+ return false;+}++const Config = { set, get, clear, all, has };+export default Config;diff --git a/apps/web/src/utils/version.js b/apps/web/src/utils/version.tssimilarity index 65%rename from apps/web/src/utils/version.jsrename to apps/web/src/utils/version.tsindex b786188fb..59ba2c571 100644--- a/apps/web/src/utils/version.js+++ b/apps/web/src/utils/version.ts@@ -1,41 +1,28 @@+export type Platforms = "web" | "desktop";+export type AppVersion = typeof appVersion;export const appVersion = {formatted: format(process.env.REACT_APP_VERSION,process.env.REACT_APP_GIT_HASH,- process.env.REACT_APP_PLATFORM+ process.env.REACT_APP_PLATFORM as Platforms),clean: formatVersion(process.env.REACT_APP_VERSION),- numerical: parseInt(process.env.REACT_APP_VERSION),+ numerical: parseInt(process.env.REACT_APP_VERSION || "0"),};-/**- *- * @param {number} version- * @param {string} hash- * @param {"web"|"desktop"} type- */-function format(version, hash, type) {+function format(version?: string, hash?: string, type?: "web" | "desktop") {return `${formatVersion(version)}-${hash}-${type}`;}-/**- *- * @param {number} version- * @param {string} hash- * @param {"web"|"desktop"} type- */-function formatVersion(version) {+function formatVersion(version?: string) {if (!version) return "";const [major, minor, bugfix0, bugfix1] = version.toString().split("");return `${major}.${minor}.${bugfix0}${bugfix1 || ""}`;}-/**- *- * @param {ServiceWorker} serviceWorker- * @returns {Promise<{formatted: string, numerical: number}>}- */-export function getServiceWorkerVersion(serviceWorker) {+export function getServiceWorkerVersion(+ serviceWorker: ServiceWorker+): Promise<AppVersion> {return new Promise((resolve, reject) => {const timeout = setTimeout(() => reject("Service worker did not respond."),@@ -50,6 +37,7 @@ export function getServiceWorkerVersion(serviceWorker) {resolve({formatted: formatVersion(version),numerical: parseInt(version),+ clean: formatVersion(version),});});serviceWorker.postMessage({ type: "GET_VERSION" });