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
intl: centralize locale selection and initialization, automate locale loaders
kashaf-ansari-dev7a2446594ee5
diff --git a/apps/desktop/src/api/os-integration.ts b/apps/desktop/src/api/os-integration.tsindex 395a6e3d6..692bf47f0 100644--- a/apps/desktop/src/api/os-integration.ts+++ b/apps/desktop/src/api/os-integration.ts@@ -30,7 +30,6 @@ import {} from "electron";import { AutoLaunch } from "../utils/autolaunch";import { config, DesktopIntegration } from "../utils/config";-import { JSONStorage } from "../utils/json-storage";import { bringToFront } from "../utils/bring-to-front";import { getTheme, setTheme, Theme } from "../utils/theme";import { existsSync } from "fs";@@ -140,7 +139,7 @@ export const osIntegrationRouter = t.router({setAppLanguage: t.procedure.input(z.string()).mutation(({ input: language }) => {- JSONStorage.set("appLanguage", language);+ config.appLanguage = language;app.relaunch();app.exit();}),diff --git a/apps/desktop/src/utils/config.ts b/apps/desktop/src/utils/config.tsindex 744b1cd0e..f752e33c8 100644--- a/apps/desktop/src/utils/config.ts+++ b/apps/desktop/src/utils/config.ts@@ -55,7 +55,8 @@ export const config = {backgroundColor: nativeTheme.themeSource === "dark" ? "#0f0f0f" : "#ffffff",windowControlsIconColor:nativeTheme.themeSource === "dark" ? "#ffffff" : "#000000",- backupDirectory: PATHS.backupsDirectory+ backupDirectory: PATHS.backupsDirectory,+ appLanguage: ""};type ConfigKey = keyof typeof config;diff --git a/apps/desktop/src/utils/locale.ts b/apps/desktop/src/utils/locale.tsindex a5e4e704d..32009ef16 100644--- a/apps/desktop/src/utils/locale.ts+++ b/apps/desktop/src/utils/locale.ts@@ -18,57 +18,16 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.*/import { app } from "electron";-import { JSONStorage } from "./json-storage";-import {- setI18nGlobal,- AVAILABLE_LANGUAGES,- getSupportedLocale-} from "@notesnook/intl";-import { i18n, type Messages } from "@lingui/core";--const localeMap: Record<- string,- () => Promise<{ default: { messages: unknown } }>-> = {- en: () => import("@notesnook/intl/locales/$en.json"),- de: () => import("@notesnook/intl/locales/$de.json"),- es: () => import("@notesnook/intl/locales/$es.json"),- fr: () => import("@notesnook/intl/locales/$fr.json"),- it: () => import("@notesnook/intl/locales/$it.json"),- nl: () => import("@notesnook/intl/locales/$nl.json"),- pl: () => import("@notesnook/intl/locales/$pl.json"),- "pt-BR": () => import("@notesnook/intl/locales/$pt-BR.json"),- ru: () => import("@notesnook/intl/locales/$ru.json"),- tr: () => import("@notesnook/intl/locales/$tr.json"),- uk: () => import("@notesnook/intl/locales/$uk.json")-};--function resolveTargetLang(): string {- const savedLanguage = JSONStorage.get<string>("appLanguage", "");- if (- savedLanguage &&- AVAILABLE_LANGUAGES.some((l) => l.code === savedLanguage)- ) {- return savedLanguage;- }-- const systemLocale = app.getLocale() || "en";- const detected = getSupportedLocale(systemLocale);- JSONStorage.set("appLanguage", detected);- return detected;-}--async function getLocaleMessages(lang: string): Promise<Messages> {- const loader = localeMap[lang] || localeMap.en;- const mod = await loader();- return mod.default.messages as unknown as Messages;-}+import { config } from "./config";+import { initLocale as initIntlLocale } from "@notesnook/intl";export async function initLocale() {- const targetLang = resolveTargetLang();- const messages = await getLocaleMessages(targetLang);- i18n.load({ [targetLang]: messages });- i18n.activate(targetLang);- setI18nGlobal(i18n as any);- return targetLang;+ return initIntlLocale({+ getSavedLocale: () => config.appLanguage,+ onSaveLocale: (locale) => {+ config.appLanguage = locale;+ },+ systemLocale: app.getLocale() || "en"+ });}+diff --git a/apps/mobile/app/common/locale/index.js b/apps/mobile/app/common/locale/index.jsindex e9cb019cd..b726e4056 100644--- a/apps/mobile/app/common/locale/index.js+++ b/apps/mobile/app/common/locale/index.js@@ -17,27 +17,17 @@ You should have received a copy of the GNU General Public Licensealong with this program. If not, see <http://www.gnu.org/licenses/>.*/-import { setI18nGlobal, getSupportedLocale } from "@notesnook/intl";import { i18n } from "@lingui/core";+import {+ setI18nGlobal,+ resolveTargetLocale,+ LOCALE_LOADERS+} from "@notesnook/intl";import SettingsService from "../../services/settings";const localeCache = {};const localeCatalogs = {};-const LOCALE_LOADERS = {- en: () => require("@notesnook/intl/dist/locales/$en.json").messages,- de: () => require("@notesnook/intl/dist/locales/$de.json").messages,- es: () => require("@notesnook/intl/dist/locales/$es.json").messages,- fr: () => require("@notesnook/intl/dist/locales/$fr.json").messages,- it: () => require("@notesnook/intl/dist/locales/$it.json").messages,- nl: () => require("@notesnook/intl/dist/locales/$nl.json").messages,- pl: () => require("@notesnook/intl/dist/locales/$pl.json").messages,- "pt-BR": () => require("@notesnook/intl/dist/locales/$pt-BR.json").messages,- ru: () => require("@notesnook/intl/dist/locales/$ru.json").messages,- tr: () => require("@notesnook/intl/dist/locales/$tr.json").messages,- uk: () => require("@notesnook/intl/dist/locales/$uk.json").messages-};-for (const locale of Object.keys(LOCALE_LOADERS)) {Object.defineProperty(localeCatalogs, locale, {enumerable: true,@@ -51,17 +41,11 @@ for (const locale of Object.keys(LOCALE_LOADERS)) {}export function initLocale() {- const savedLanguage = SettingsService.getProperty("appLanguage");- let targetLang;+ const saved = SettingsService.getProperty("appLanguage");+ const targetLang = resolveTargetLocale(saved);- if (savedLanguage && localeCatalogs[savedLanguage]) {- targetLang = savedLanguage;- } else {- let systemLocale = "en";- try {- systemLocale = Intl.DateTimeFormat().resolvedOptions().locale;- } catch (e) {}- targetLang = getSupportedLocale(systemLocale);+ if (!saved) {+ SettingsService.setProperty("appLanguage", targetLang);}i18n.load(localeCatalogs);@@ -69,3 +53,4 @@ export function initLocale() {setI18nGlobal(i18n);return targetLang;}+diff --git a/apps/mobile/app/components/list/card.tsx b/apps/mobile/app/components/list/card.tsxindex 5b6dcf349..a6fdcf6f3 100644--- a/apps/mobile/app/components/list/card.tsx+++ b/apps/mobile/app/components/list/card.tsx@@ -22,7 +22,7 @@ import React from "react";import { Dimensions, View } from "react-native";import Icon from "react-native-vector-icons/MaterialCommunityIcons";import { Message, useMessageStore } from "../../stores/use-message-store";-import { getLocalizedMessageStrings } from "../../services/message";+import { getMessageById } from "../../services/message";import { AppFontSize } from "../../utils/size";import { DefaultAppStyles } from "../../utils/styles";import { Pressable } from "../ui/pressable";@@ -42,9 +42,12 @@ export const Card = ({);const announcements = useMessageStore((state) => state.announcements);const fontScale = Dimensions.get("window").fontScale;- const freshStrings = getLocalizedMessageStrings(messageBoardState.id);+ const localizedMessage =+ customMessage ||+ getMessageById(messageBoardState.id, (messageBoardState as Message).data);return !messageBoardState.visible ||+ !localizedMessage ||(announcements && announcements.length) ? null : (<Viewstyle={{@@ -54,7 +57,7 @@ export const Card = ({}}><Pressable- onPress={messageBoardState.onPress}+ onPress={localizedMessage.onPress}type="plain"style={{paddingVertical: DefaultAppStyles.GAP_VERTICAL,@@ -83,10 +86,10 @@ export const Card = ({<Iconsize={AppFontSize.xxxl}color={- messageBoardState.type === "error" ? colors.error.icon : color+ localizedMessage.type === "error" ? colors.error.icon : color}allowFontScaling- name={messageBoardState.icon}+ name={localizedMessage.icon}/></View>@@ -105,10 +108,10 @@ export const Card = ({size={AppFontSize.sm}color={colors.primary.heading}>- {freshStrings?.actionText || messageBoardState.actionText}+ {localizedMessage.actionText}</Paragraph><Paragraph color={colors.secondary.paragraph} size={AppFontSize.xs}>- {freshStrings?.message || messageBoardState.message}+ {localizedMessage.message}</Paragraph></View></View>diff --git a/apps/mobile/app/components/side-menu/side-menu-home.tsx b/apps/mobile/app/components/side-menu/side-menu-home.tsxindex 49cf7a6ab..fdbefbebe 100644--- a/apps/mobile/app/components/side-menu/side-menu-home.tsx+++ b/apps/mobile/app/components/side-menu/side-menu-home.tsx@@ -39,19 +39,7 @@ import { MenuItem } from "./menu-item";import { PinnedSection } from "./pinned-section";import { SideMenuHeader } from "./side-menu-header";-const getProItem = () => ({- title: strings.upgradePlan(),- icon: "crown",- id: "pro",- onPress: () => {- Navigation.navigate("PayWall", {- context: "logged-in"- });- }-});-export function SideMenuHome() {- const pro = getProItem();const { colors } = useThemeColors();const [isAppLoading, introCompleted] = useSettingStore((state) => [state.isAppLoading,@@ -150,12 +138,16 @@ export function SideMenuHome() {!user) &&!SettingsService.getProperty("serverUrls") ? (<Button- title={pro.title}+ title={strings.upgradePlan()}style={{width: "100%"}}type="accent"- onPress={pro.onPress}+ onPress={() => {+ Navigation.navigate("PayWall", {+ context: "logged-in"+ });+ }}/>) : null}</>diff --git a/apps/mobile/app/screens/settings/home.tsx b/apps/mobile/app/screens/settings/home.tsxindex b142f3b37..2ed2d6b80 100644--- a/apps/mobile/app/screens/settings/home.tsx+++ b/apps/mobile/app/screens/settings/home.tsx@@ -45,12 +45,15 @@ const Home = ({focusOnInit: true});- const renderItem = ({ item }: { item: SettingSection; index: number }) =>- item.id === "account" ? (- <SettingsUserSection item={item} />- ) : (- <SectionGroup item={item} />- );+ const renderItem = React.useCallback(+ ({ item }: { item: SettingSection; index: number }) =>+ item.id === "account" ? (+ <SettingsUserSection item={item} />+ ) : (+ <SectionGroup item={item} />+ ),+ []+ );return (<>diff --git a/apps/mobile/app/screens/settings/picker/pickers.tsx b/apps/mobile/app/screens/settings/picker/pickers.tsxindex ca4958b2c..ca4a1ce40 100644--- a/apps/mobile/app/screens/settings/picker/pickers.tsx+++ b/apps/mobile/app/screens/settings/picker/pickers.tsx@@ -36,7 +36,12 @@ import { useUserStore } from "../../../stores/use-user-store";import { MenuItemsList } from "../../../utils/menu-items";import { verifyUserWithApplock } from "../functions";import PaywallSheet from "../../../components/sheets/paywall";-import { AVAILABLE_LANGUAGES, getSupportedLocale, setI18nGlobal, strings } from "@notesnook/intl";+import {+ AVAILABLE_LANGUAGES,+ getSupportedLocale,+ setI18nGlobal,+ strings+} from "@notesnook/intl";import { isFeatureAvailable } from "@notesnook/common";import { i18n } from "@lingui/core";import RNRestart from "react-native-restart";@@ -68,7 +73,7 @@ export const LanguagePicker = createSettingsPicker<let systemLocale = "en";try {systemLocale = Intl.DateTimeFormat().resolvedOptions().locale;- } catch (e) { }+ } catch (e) {}return saved || getSupportedLocale(systemLocale);},updateValue: async (item) => {@@ -76,21 +81,23 @@ export const LanguagePicker = createSettingsPicker<const currentLang = useSettingStore.getState().settings.appLanguage;if (lang === currentLang) return;- presentDialog({- title: strings.changeLanguage ? strings.changeLanguage() : "Change language",- paragraph: strings.restartAppToApplyChanges- ? strings.restartAppToApplyChanges()- : "Restart the app to apply the changes.",- positiveText: strings.restartNow ? strings.restartNow() : "Restart now",- negativeText: strings.cancel ? strings.cancel() : "Cancel",- positivePress: async () => {- eSendEvent(eCloseSimpleDialog);- i18n.activate(lang);- setI18nGlobal(i18n);- SettingsService.setProperty("appLanguage", lang);- RNRestart.restart();- }- });+ setTimeout(() => {+ presentDialog({+ title: strings.changeLanguage(),+ paragraph: strings.restartAppToApplyChanges(),+ positiveText: strings.restartNow(),+ negativeText: strings.cancel(),+ positivePress: async () => {+ eSendEvent(eCloseSimpleDialog);+ i18n.activate(lang);+ setI18nGlobal(i18n);+ SettingsService.setProperty("appLanguage", lang);+ // restarting early causes appLanguage value to not get saved.+ setTimeout(() => RNRestart.restart(), 100);+ return true;+ }+ });+ }, 300);},formatValue: (item) => {const code = typeof item === "object" ? item.code : item;@@ -99,7 +106,8 @@ export const LanguagePicker = createSettingsPicker<},getItemKey: (item) => (typeof item === "object" ? item.code : item),options: AVAILABLE_LANGUAGES,- compareValue: (current, item) => current === (typeof item === "object" ? item.code : item),+ compareValue: (current, item) =>+ current === (typeof item === "object" ? item.code : item),isFeatureAvailable: async () => true,isOptionAvailable: async () => true});diff --git a/apps/mobile/app/screens/settings/settings-data.tsx b/apps/mobile/app/screens/settings/settings-data.tsxindex e4c91e518..8dca25b18 100644--- a/apps/mobile/app/screens/settings/settings-data.tsx+++ b/apps/mobile/app/screens/settings/settings-data.tsx@@ -86,1787 +86,1788 @@ import { getTimeLeft } from "./user-section";export function getSettingsGroups(): SettingSection[] {return [- {- id: "account-local",- name: strings.account(),- useHook: () => useUserStore((state) => state.user),- hidden: (current) => !!current,- sections: [- {- id: "delete-data",- name: strings.deleteData(),- icon: "delete",- description: strings.deleteAccountDesc(),- modifer: () => {- presentDialog({- title: strings.deleteData(),- paragraph: strings.irreverisibleAction(),- positiveType: "errorShade",- positiveText: "Delete data",- positivePress: async () => {- await PremiumService.setPremiumStatus();- await BiometricService.resetCredentials();- MMKV.clearStore();- resetTabStore();- clearAllStores();- Navigation.queueRoutesForUpdate();- SettingsService.resetSettings();- db.reset();+ {+ id: "account-local",+ name: strings.account(),+ useHook: () => useUserStore((state) => state.user),+ hidden: (current) => !!current,+ sections: [+ {+ id: "delete-data",+ name: strings.deleteData(),+ icon: "delete",+ description: strings.deleteAccountDesc(),+ modifer: () => {+ presentDialog({+ title: strings.deleteData(),+ paragraph: strings.irreverisibleAction(),+ positiveType: "errorShade",+ positiveText: "Delete data",+ positivePress: async () => {+ await PremiumService.setPremiumStatus();+ await BiometricService.resetCredentials();+ MMKV.clearStore();+ resetTabStore();+ clearAllStores();+ Navigation.queueRoutesForUpdate();+ SettingsService.resetSettings();+ db.reset();- setImmediate(() => {- refreshAllStores();- eSendEvent(eAfterSync);- });- return true;- }- });+ setImmediate(() => {+ refreshAllStores();+ eSendEvent(eAfterSync);+ });+ return true;+ }+ });+ }}- }- ]- },- {- id: "account",- name: strings.account(),- useHook: () => useUserStore((state) => state.user),- hidden: (current) => !current,- sections: [- {- id: "subscription-status",- useHook: () => useUserStore((state) => state.user),- hidden: (current) => {- const user = current as User;- return (- !user ||- !user.subscription ||- user.subscription.provider === undefined ||- !strings.subscriptionProviderInfo[user?.subscription?.provider] ||- user.subscription?.plan === SubscriptionPlan.FREE- );- },- name: (current) => {- const user = (current as User) || useUserStore.getState().user;- return (- strings.subscriptionProviderInfo[- user?.subscription?.provider- ]?.title() || `Unknown provider id: ${user?.subscription?.provider}`- );- },- icon: "credit-card",- modifer: () => {- const user = useUserStore.getState().user;- if (!user) return;- const subscriptionProviderInfo =- strings.subscriptionProviderInfo[user?.subscription?.provider];+ ]+ },+ {+ id: "account",+ name: strings.account(),+ useHook: () => useUserStore((state) => state.user),+ hidden: (current) => !current,+ sections: [+ {+ id: "subscription-status",+ useHook: () => useUserStore((state) => state.user),+ hidden: (current) => {+ const user = current as User;+ return (+ !user ||+ !user.subscription ||+ user.subscription.provider === undefined ||+ !strings.subscriptionProviderInfo[user?.subscription?.provider] ||+ user.subscription?.plan === SubscriptionPlan.FREE+ );+ },+ name: (current) => {+ const user = (current as User) || useUserStore.getState().user;+ return (+ strings.subscriptionProviderInfo[+ user?.subscription?.provider+ ]?.title() || `Unknown provider id: ${user?.subscription?.provider}`+ );+ },+ icon: "credit-card",+ modifer: () => {+ const user = useUserStore.getState().user;+ if (!user) return;+ const subscriptionProviderInfo =+ strings.subscriptionProviderInfo[user?.subscription?.provider];- if (!subscriptionProviderInfo) return;+ if (!subscriptionProviderInfo) return;- const isCurrentPlatform =- (user.subscription?.provider === SubscriptionProvider.APPLE &&- Platform.OS === "ios") ||- (user.subscription?.provider === SubscriptionProvider.GOOGLE &&- Platform.OS === "android");+ const isCurrentPlatform =+ (user.subscription?.provider === SubscriptionProvider.APPLE &&+ Platform.OS === "ios") ||+ (user.subscription?.provider === SubscriptionProvider.GOOGLE &&+ Platform.OS === "android");- if (- (user.subscription?.provider === SubscriptionProvider.GOOGLE ||- user.subscription?.provider === SubscriptionProvider.APPLE) &&- isCurrentPlatform &&- user?.subscription?.productId- ) {- RNIap.deepLinkToSubscriptions({- sku: user?.subscription.productId- });- } else {- presentSheet({- title: subscriptionProviderInfo.title(),- paragraph: subscriptionProviderInfo.desc()- });- }- },- description: (current) => {- const user = current as User;- if (!user) return strings.neverHesitate();- const subscriptionDaysLeft =- user && getTimeLeft(user.subscription?.expiry);- const expiryDate = dayjs(user?.subscription?.expiry).format(- "dddd, MMMM D, YYYY h:mm A"- );- const startDate = dayjs(user?.subscription?.start).format(- "dddd, MMMM D, YYYY h:mm A"- );+ if (+ (user.subscription?.provider === SubscriptionProvider.GOOGLE ||+ user.subscription?.provider === SubscriptionProvider.APPLE) &&+ isCurrentPlatform &&+ user?.subscription?.productId+ ) {+ RNIap.deepLinkToSubscriptions({+ sku: user?.subscription.productId+ });+ } else {+ presentSheet({+ title: subscriptionProviderInfo.title(),+ paragraph: subscriptionProviderInfo.desc()+ });+ }+ },+ description: (current) => {+ const user = current as User;+ if (!user) return strings.neverHesitate();+ const subscriptionDaysLeft =+ user && getTimeLeft(user.subscription?.expiry);+ const expiryDate = dayjs(user?.subscription?.expiry).format(+ "dddd, MMMM D, YYYY h:mm A"+ );+ const startDate = dayjs(user?.subscription?.start).format(+ "dddd, MMMM D, YYYY h:mm A"+ );- const trialEndDate = dayjs(user?.subscription?.start)- .add(- user?.subscription?.productId?.includes("monthly") ? 7 : 14,- "day"- )- .format("dddd, MMMM D, YYYY h:mm A");+ const trialEndDate = dayjs(user?.subscription?.start)+ .add(+ user?.subscription?.productId?.includes("monthly") ? 7 : 14,+ "day"+ )+ .format("dddd, MMMM D, YYYY h:mm A");- if (- user.subscription?.plan !== SubscriptionPlan.FREE &&- user.subscription?.productId- ) {- const status = user.subscription?.status;- return status === SubscriptionStatus.TRIAL- ? strings.trialOnGoing(trialEndDate)- : status === SubscriptionStatus.ACTIVE- ? strings.subRenewOn(expiryDate)- : status === SubscriptionStatus.CANCELED ||- status === SubscriptionStatus.PAUSED- ? strings.subEndsOn(expiryDate)- : status === SubscriptionStatus.EXPIRED- ? subscriptionDaysLeft.time < -3- ? strings.subEnded()- : strings.accountDowngradedIn(3)- : strings.neverHesitate();- }+ if (+ user.subscription?.plan !== SubscriptionPlan.FREE &&+ user.subscription?.productId+ ) {+ const status = user.subscription?.status;+ return status === SubscriptionStatus.TRIAL+ ? strings.trialOnGoing(trialEndDate)+ : status === SubscriptionStatus.ACTIVE+ ? strings.subRenewOn(expiryDate)+ : status === SubscriptionStatus.CANCELED ||+ status === SubscriptionStatus.PAUSED+ ? strings.subEndsOn(expiryDate)+ : status === SubscriptionStatus.EXPIRED+ ? subscriptionDaysLeft.time < -3+ ? strings.subEnded()+ : strings.accountDowngradedIn(3)+ : strings.neverHesitate();+ }- return strings.neverHesitate();- }- },- {- id: "redeem-gift-code",- name: strings.redeemGiftCode(),- description: strings.redeemGiftCodeDesc(),- hidden: (current) => {- return !current as boolean;+ return strings.neverHesitate();+ }},- useHook: () =>- useUserStore(- (state) => state.user?.subscription?.plan === SubscriptionPlan.FREE- ),- icon: "gift",- modifer: () => {- presentDialog({- title: strings.redeemGiftCode(),- paragraph: strings.redeemGiftCodeDesc(),- form: {- formRef: createFormRef({- code: ""- }),- items: [- {- name: "code",- placeholder: strings.code(),- ref: React.createRef<TextInput | null>(),- validators: [validators.required(strings.giftCodeRequired())]- }- ],- onFormSubmit: async (form) => {- try {- await db.subscriptions.redeemCode(form.getValue("code"));- return true;- } catch (e) {- form.setError("code", (e as Error).message);- return false;+ {+ id: "redeem-gift-code",+ name: strings.redeemGiftCode(),+ description: strings.redeemGiftCodeDesc(),+ hidden: (current) => {+ return !current as boolean;+ },+ useHook: () =>+ useUserStore(+ (state) => state.user?.subscription?.plan === SubscriptionPlan.FREE+ ),+ icon: "gift",+ modifer: () => {+ presentDialog({+ title: strings.redeemGiftCode(),+ paragraph: strings.redeemGiftCodeDesc(),+ form: {+ formRef: createFormRef({+ code: ""+ }),+ items: [+ {+ name: "code",+ placeholder: strings.code(),+ ref: React.createRef<TextInput | null>(),+ validators: [validators.required(strings.giftCodeRequired())]+ }+ ],+ onFormSubmit: async (form) => {+ try {+ await db.subscriptions.redeemCode(form.getValue("code"));+ return true;+ } catch (e) {+ form.setError("code", (e as Error).message);+ return false;+ }}+ },+ positiveText: strings.redeem()+ });+ }+ },+ {+ id: "account-settings",+ type: "screen",+ name: strings.manageAccount(),+ icon: "account-cog",+ description: strings.manageAccountDesc(),+ sections: [+ {+ id: "remove-profile-picture",+ name: strings.removeProfilePicture(),+ description: strings.removeProfilePictureDesc(),+ useHook: () =>+ useUserStore((state) => state.profile?.profilePicture),+ hidden: () => !useUserStore.getState().profile?.profilePicture,+ modifer: () => {+ presentDialog({+ title: strings.removeProfilePicture(),+ paragraph: strings.removeProfilePictureConfirmation(),+ positiveText: strings.remove(),+ positivePress: async () => {+ db.settings+ .setProfile({+ profilePicture: undefined+ })+ .then(async () => {+ useUserStore.setState({+ profile: db.settings.getProfile()+ });+ });+ }+ });}},- positiveText: strings.redeem()- });- }- },- {- id: "account-settings",- type: "screen",- name: strings.manageAccount(),- icon: "account-cog",- description: strings.manageAccountDesc(),- sections: [- {- id: "remove-profile-picture",- name: strings.removeProfilePicture(),- description: strings.removeProfilePictureDesc(),- useHook: () =>- useUserStore((state) => state.profile?.profilePicture),- hidden: () => !useUserStore.getState().profile?.profilePicture,- modifer: () => {- presentDialog({- title: strings.removeProfilePicture(),- paragraph: strings.removeProfilePictureConfirmation(),- positiveText: strings.remove(),- positivePress: async () => {- db.settings- .setProfile({- profilePicture: undefined- })- .then(async () => {- useUserStore.setState({- profile: db.settings.getProfile()+ {+ id: "remove-name",+ name: strings.removeFullName(),+ description: strings.removeFullNameDesc(),+ useHook: () => useUserStore((state) => state.profile?.fullName),+ hidden: () => !useUserStore.getState().profile?.fullName,+ modifer: () => {+ presentDialog({+ title: strings.removeFullName(),+ paragraph: strings.removeFullNameConfirmation(),+ positiveText: strings.remove(),+ positivePress: async () => {+ db.settings+ .setProfile({+ fullName: undefined+ })+ .then(async () => {+ useUserStore.setState({+ profile: db.settings.getProfile()+ });});+ }+ });+ }+ },+ {+ id: "recovery-key",+ name: strings.saveDataRecoveryKey(),+ modifer: async () => {+ verifyUser(null, async () => {+ await sleep(300);+ eSendEvent(eOpenRecoveryKeyDialog);+ });+ },+ description: strings.saveDataRecoveryKeyDesc(),+ icon: "key"+ },+ {+ id: "manage-attachments",+ name: strings.manageAttachments(),+ icon: "attachment",+ type: "screen",+ component: "attachments-manager",+ description: strings.manageAttachmentsDesc(),+ hideHeader: true+ },+ {+ id: "change-password",+ name: strings.changePassword(),+ type: "screen",+ description: strings.changePasswordDesc(),+ component: "change-password",+ icon: "form-textbox-password"+ },+ {+ id: "change-email",+ name: strings.changeEmail(),+ type: "screen",+ component: "change-email",+ description: strings.changeEmailDesc(),+ icon: "at"+ },+ {+ id: "2fa-settings",+ type: "screen",+ name: strings.twoFactorAuth(),+ description: strings.twoFactorAuthDesc(),+ icon: "two-factor-authentication",+ sections: [+ {+ id: "enable-2fa",+ name: strings.change2faMethod(),+ modifer: () => {+ verifyUser("global", async () => {+ MFASheet.present();});- }- });- }- },- {- id: "remove-name",- name: strings.removeFullName(),- description: strings.removeFullNameDesc(),- useHook: () => useUserStore((state) => state.profile?.fullName),- hidden: () => !useUserStore.getState().profile?.fullName,- modifer: () => {- presentDialog({- title: strings.removeFullName(),- paragraph: strings.removeFullNameConfirmation(),- positiveText: strings.remove(),- positivePress: async () => {- db.settings- .setProfile({- fullName: undefined- })- .then(async () => {- useUserStore.setState({- profile: db.settings.getProfile()- });+ },+ useHook: () => useUserStore((state) => state.user),+ description: strings.change2faMethodDesc()+ },+ {+ id: "2fa-fallback",+ name: strings.addFallback2faMethod(),+ useHook: () => useUserStore((state) => state.user),+ hidden: (user) => {+ return (+ !!(user as User)?.mfa?.secondaryMethod ||+ !(user as User)?.mfa?.isEnabled+ );+ },+ modifer: () => {+ verifyUser("global", async () => {+ MFASheet.present(true);+ });+ },+ description: strings.addFallback2faMethodDesc()+ },+ {+ id: "change-2fa-method",+ name: strings.change2faFallbackMethod(),+ useHook: () => useUserStore((state) => state.user),+ hidden: (user) => {+ return (+ !(user as User)?.mfa?.secondaryMethod ||+ !(user as User)?.mfa?.isEnabled+ );+ },+ modifer: () => {+ verifyUser("global", async () => {+ MFASheet.present(true);});+ },+ description: strings.change2faFallbackMethod()+ },+ {+ id: "view-2fa-codes",+ name: strings.viewRecoveryCodes(),+ modifer: () => {+ verifyUser("global", async () => {+ MFARecoveryCodes.present("sms");+ });+ },+ useHook: () => useUserStore((state) => state.user),+ hidden: (user) => {+ return !(user as User)?.mfa?.isEnabled;+ },+ description: strings.viewRecoveryCodesDesc()}- });- }- },- {- id: "recovery-key",- name: strings.saveDataRecoveryKey(),- modifer: async () => {- verifyUser(null, async () => {- await sleep(300);- eSendEvent(eOpenRecoveryKeyDialog);- });+ ]},- description: strings.saveDataRecoveryKeyDesc(),- icon: "key"- },- {- id: "manage-attachments",- name: strings.manageAttachments(),- icon: "attachment",- type: "screen",- component: "attachments-manager",- description: strings.manageAttachmentsDesc(),- hideHeader: true- },- {- id: "change-password",- name: strings.changePassword(),- type: "screen",- description: strings.changePasswordDesc(),- component: "change-password",- icon: "form-textbox-password"- },- {- id: "change-email",- name: strings.changeEmail(),- type: "screen",- component: "change-email",- description: strings.changeEmailDesc(),- icon: "at"- },- {- id: "2fa-settings",- type: "screen",- name: strings.twoFactorAuth(),- description: strings.twoFactorAuthDesc(),- icon: "two-factor-authentication",- sections: [- {- id: "enable-2fa",- name: strings.change2faMethod(),- modifer: () => {- verifyUser("global", async () => {- MFASheet.present();+ {+ id: "subscription-not-active",+ name: strings.subscriptionNotActivated(),+ useHook: () => useUserStore((state) => state.user),+ hidden: (user) =>+ Platform.OS !== "ios" ||+ (user as User)?.subscription?.plan !== SubscriptionPlan.FREE,+ modifer: async () => {+ if (Platform.OS === "android") return;+ try {+ presentSheet({+ title: strings.loadingSubscription(),+ paragraph: strings.loadingSubscriptionDesc(),+ progress: true});- },- useHook: () => useUserStore((state) => state.user),- description: strings.change2faMethodDesc()- },- {- id: "2fa-fallback",- name: strings.addFallback2faMethod(),- useHook: () => useUserStore((state) => state.user),- hidden: (user) => {- return (- !!(user as User)?.mfa?.secondaryMethod ||- !(user as User)?.mfa?.isEnabled+ const subscriptions = await RNIap.getPurchaseHistory();+ subscriptions.sort(+ (a, b) => b.transactionDate - a.transactionDate);- },- modifer: () => {- verifyUser("global", async () => {- MFASheet.present(true);+ const currentSubscription = subscriptions[0];++ if (+ !currentSubscription ||+ dayjs(currentSubscription.transactionDate).isBefore(+ dayjs().subtract(30, "day")+ )+ ) {+ ToastManager.show({+ message: "No active subscription found",+ type: "info"+ });+ eSendEvent(eCloseSheet);+ return;+ }++ presentSheet({+ title: strings.notesnookPro(),+ paragraph: strings.subscribedOnVerify(+ new Date(+ currentSubscription.transactionDate+ ).toLocaleString()+ ),+ action: async () => {+ presentSheet({+ title: strings.verifySubscription(),+ paragraph: strings.subscriptionVerifyWait()+ });+ await PremiumService.subscriptions.verify(+ currentSubscription+ );+ eSendEvent(eCloseSheet);+ },+ icon: "information-outline",+ actionText: strings.verify()});- },- description: strings.addFallback2faMethodDesc()+ } catch (e) {+ eSendEvent(eCloseSheet);+ }},- {- id: "change-2fa-method",- name: strings.change2faFallbackMethod(),- useHook: () => useUserStore((state) => state.user),- hidden: (user) => {- return (- !(user as User)?.mfa?.secondaryMethod ||- !(user as User)?.mfa?.isEnabled- );- },- modifer: () => {- verifyUser("global", async () => {- MFASheet.present(true);- });- },- description: strings.change2faFallbackMethod()+ description: strings.verifySubDesc()+ },+ {+ id: "clear-cache",+ name: strings.clearCache(),+ icon: "delete",+ modifer: async () => {+ presentDialog({+ title: strings.clearCacheConfirm(),+ paragraph: strings.clearCacheConfirmDesc(),+ positiveText: strings.clear(),+ positivePress: async () => {+ filesystem.clearCache();+ ToastManager.show({+ heading: strings.cacheCleared(),+ message: strings.cacheClearedDesc(),+ type: "success"+ });+ }+ });},- {- id: "view-2fa-codes",- name: strings.viewRecoveryCodes(),- modifer: () => {- verifyUser("global", async () => {- MFARecoveryCodes.present("sms");+ description(current) {+ return strings.clearCacheDesc(current as number);+ },+ useHook: () => {+ const [cacheSize, setCacheSize] = React.useState(0);+ React.useEffect(() => {+ filesystem+ .getCacheSize()+ .then(setCacheSize)+ .catch(() => {+ /* empty */+ });+ const sub = eSubscribeEvent("cache-cleared", () => {+ setCacheSize(0);});- },- useHook: () => useUserStore((state) => state.user),- hidden: (user) => {- return !(user as User)?.mfa?.isEnabled;- },- description: strings.viewRecoveryCodesDesc()+ return () => {+ sub?.unsubscribe();+ };+ }, []);+ return formatBytes(cacheSize);}- ]- },- {- id: "subscription-not-active",- name: strings.subscriptionNotActivated(),- useHook: () => useUserStore((state) => state.user),- hidden: (user) =>- Platform.OS !== "ios" ||- (user as User)?.subscription?.plan !== SubscriptionPlan.FREE,- modifer: async () => {- if (Platform.OS === "android") return;- try {- presentSheet({- title: strings.loadingSubscription(),- paragraph: strings.loadingSubscriptionDesc(),- progress: true- });- const subscriptions = await RNIap.getPurchaseHistory();- subscriptions.sort(- (a, b) => b.transactionDate - a.transactionDate- );- const currentSubscription = subscriptions[0];+ },- if (- !currentSubscription ||- dayjs(currentSubscription.transactionDate).isBefore(- dayjs().subtract(30, "day")- )- ) {- ToastManager.show({- message: "No active subscription found",- type: "info"- });- eSendEvent(eCloseSheet);+ {+ id: "logout",+ name: strings.logout(),+ description: strings.logoutWarnin(),+ icon: "logout",+ modifer: logoutUser+ },+ {+ id: "delete-account",+ type: "danger",+ name: strings.deleteAccount(),+ icon: "alert",+ description: strings.deleteAccountDesc(),+ modifer: () => {+ presentDialog({+ title: strings.deleteAccount(),+ paragraphColor: "red",+ paragraph: strings.deleteAccountDesc(),+ positiveType: "errorShade",+ input: true,+ secureTextEntry: true,+ inputPlaceholder: strings.enterAccountPassword(),+ positiveText: strings.delete(),+ positivePress: async (value) => {+ try {+ if (!value || !value.trim()) {+ ToastManager.error(+ new Error(strings.passwordNotEntered()),+ undefined,+ "local"+ );+ return;+ }+ const verified = await db.user?.verifyPassword(value);+ if (verified) {+ setTimeout(async () => {+ try {+ startProgress({+ title: "Deleting account",+ paragraph:+ "Please wait while we delete your account"+ });+ await db.user?.deleteUser(value);+ DatabaseLogger.info("User account deleted");+ Navigation.navigate("Notes");+ await BiometricService.resetCredentials();+ SettingsService.set({+ introCompleted: true+ });+ } catch (e) {+ endProgress();+ DatabaseLogger.error(e);+ ToastManager.error(+ e as Error,+ strings.failedToDeleteAccount(),+ "global"+ );+ }+ }, 300);+ } else {+ ToastManager.show({+ heading: strings.passwordIncorrect(),+ type: "error",+ context: "global"+ });+ }+ } catch (e) {+ ToastManager.error(+ e as Error,+ strings.failedToDeleteAccount(),+ "global"+ );+ }+ }+ });+ }+ }+ ]+ },+ {+ id: "sync-settings",+ name: strings.syncSettings(),+ description: strings.syncSettingsDesc(),+ type: "screen",+ icon: "autorenew",+ component: "offline-mode-progress",+ sections: [+ {+ id: "offline-mode",+ icon: "download-multiple",+ name: strings.fullOfflineMode(),+ description: strings.fullOfflineModeDesc(),+ type: "switch",+ property: "offlineMode",+ featureId: "fullOfflineMode",+ modifer: () => {+ const current = SettingsService.get().offlineMode;+ if (current) {+ SettingsService.setProperty("offlineMode", false);+ db.fs().cancel("offline-mode");return;}-- presentSheet({- title: strings.notesnookPro(),- paragraph: strings.subscribedOnVerify(- new Date(- currentSubscription.transactionDate- ).toLocaleString()- ),- action: async () => {- presentSheet({- title: strings.verifySubscription(),- paragraph: strings.subscriptionVerifyWait()- });- await PremiumService.subscriptions.verify(- currentSubscription- );- eSendEvent(eCloseSheet);- },- icon: "information-outline",- actionText: strings.verify()+ SettingsService.setProperty("offlineMode", true);+ db.attachments.cacheAttachments().catch(() => {+ /* empty */});- } catch (e) {- eSendEvent(eCloseSheet);}},- description: strings.verifySubDesc()- },- {- id: "clear-cache",- name: strings.clearCache(),- icon: "delete",- modifer: async () => {- presentDialog({- title: strings.clearCacheConfirm(),- paragraph: strings.clearCacheConfirmDesc(),- positiveText: strings.clear(),- positivePress: async () => {- filesystem.clearCache();- ToastManager.show({- heading: strings.cacheCleared(),- message: strings.cacheClearedDesc(),- type: "success"- });+ {+ id: "auto-sync",+ name: strings.disableAutoSync(),+ description: strings.disableAutoSyncDesc(),+ type: "switch",+ property: "disableAutoSync",+ featureId: "syncControls",+ icon: "sync-off"+ },+ {+ id: "disable-realtime-sync",+ name: strings.disableRealtimeSync(),+ description: strings.disableRealtimeSyncDesc(),+ type: "switch",+ property: "disableRealtimeSync",+ featureId: "syncControls"+ },+ {+ id: "disable-sync",+ name: strings.disableSync(),+ description: strings.disableSyncDesc(),+ type: "switch",+ property: "disableSync",+ featureId: "syncControls",+ icon: "cloud-off-outline"+ },+ {+ id: "background-sync",+ name: strings.backgroundSync(),+ description: strings.backgroundSyncDesc(),+ type: "switch",+ property: "backgroundSync",+ icon: "cloud-upload-outline",+ onChange: (value) => {+ if (value) {+ BackgroundSync.start();+ } else {+ BackgroundSync.stop();}- });+ }},- description(current) {- return strings.clearCacheDesc(current as number);+ {+ id: "pull-sync",+ name: strings.forcePullChanges(),+ description: strings.forcePullChangesDesc(),+ icon: "download",+ modifer: () => {+ presentDialog({+ title: strings.forcePullChanges(),+ paragraph: strings.forceSyncNotice(),+ negativeText: strings.cancel(),+ positiveText: strings.start(),+ positivePress: async () => {+ eSendEvent(eCloseSheet);+ await sleep(300);+ Progress.present();+ Sync.run("global", true, "fetch", () => {+ eSendEvent(eCloseSheet);+ });+ }+ });+ }},- useHook: () => {- const [cacheSize, setCacheSize] = React.useState(0);- React.useEffect(() => {- filesystem- .getCacheSize()- .then(setCacheSize)- .catch(() => {- /* empty */- });- const sub = eSubscribeEvent("cache-cleared", () => {- setCacheSize(0);+ {+ id: "push-sync",+ name: strings.forcePushChanges(),+ description: strings.forcePushChangesDesc(),+ icon: "upload",+ modifer: () => {+ presentDialog({+ title: strings.forcePushChanges(),+ paragraph: strings.forceSyncNotice(),+ negativeText: strings.cancel(),+ positiveText: strings.start(),+ positivePress: async () => {+ eSendEvent(eCloseSheet);+ await sleep(300);+ Progress.present();+ Sync.run("global", true, "send", () => {+ eSendEvent(eCloseSheet);+ });+ }});- return () => {- sub?.unsubscribe();- };- }, []);- return formatBytes(cacheSize);+ }}- },-- {- id: "logout",- name: strings.logout(),- description: strings.logoutWarnin(),- icon: "logout",- modifer: logoutUser- },- {- id: "delete-account",- type: "danger",- name: strings.deleteAccount(),- icon: "alert",- description: strings.deleteAccountDesc(),- modifer: () => {- presentDialog({- title: strings.deleteAccount(),- paragraphColor: "red",- paragraph: strings.deleteAccountDesc(),- positiveType: "errorShade",- input: true,- secureTextEntry: true,- inputPlaceholder: strings.enterAccountPassword(),- positiveText: strings.delete(),- positivePress: async (value) => {- try {- if (!value || !value.trim()) {- ToastManager.error(- new Error(strings.passwordNotEntered()),- undefined,- "local"- );- return;- }- const verified = await db.user?.verifyPassword(value);- if (verified) {- setTimeout(async () => {+ ]+ },+ {+ id: "notesnook-circle",+ name: strings.notesnookCircle(),+ icon: "circle-outline",+ type: "screen",+ description: strings.notesnookCircleDesc(),+ component: "notesnook-circle"+ },+ {+ id: "inbox-api",+ name: strings.inboxAPI(),+ icon: "inbox",+ type: "screen",+ description: strings.inboxAPIDesc(),+ sections: [+ {+ id: "toggle-inbox-api",+ name: strings.enableInboxAPI(),+ description: strings.enableInboxAPIDesc(),+ type: "switch",+ useHook: () => {+ return useSettingStore((state) => state.inboxEnabled);+ },+ getter: (current) => current,+ modifer: async (current) => {+ if (current) {+ return new Promise((resolve) => {+ presentDialog({+ title: strings.disableInboxAPI(),+ paragraph: strings.disableInboxAPIDesc(),+ positiveText: strings.disable(),+ onClose: () => {+ resolve();+ },+ positivePress: async () => {try {- startProgress({- title: "Deleting account",- paragraph:- "Please wait while we delete your account"- });- await db.user?.deleteUser(value);- DatabaseLogger.info("User account deleted");- Navigation.navigate("Notes");- await BiometricService.resetCredentials();- SettingsService.set({- introCompleted: true+ await db.inboxItemsHistory.deleteFailed();+ await db.user.discardInboxKeys();+ useSettingStore.setState({+ inboxEnabled: false});+ resolve();+ return true;} catch (e) {- endProgress();+ ToastManager.show({+ message: (e as Error).message,+ context: "local"+ });DatabaseLogger.error(e);- ToastManager.error(- e as Error,- strings.failedToDeleteAccount(),- "global"- );+ return false;}- }, 300);- } else {- ToastManager.show({- heading: strings.passwordIncorrect(),- type: "error",- context: "global"- });- }- } catch (e) {- ToastManager.error(- e as Error,- strings.failedToDeleteAccount(),- "global"- );- }- }- });- }- }- ]- },- {- id: "sync-settings",- name: strings.syncSettings(),- description: strings.syncSettingsDesc(),- type: "screen",- icon: "autorenew",- component: "offline-mode-progress",- sections: [- {- id: "offline-mode",- icon: "download-multiple",- name: strings.fullOfflineMode(),- description: strings.fullOfflineModeDesc(),- type: "switch",- property: "offlineMode",- featureId: "fullOfflineMode",- modifer: () => {- const current = SettingsService.get().offlineMode;- if (current) {- SettingsService.setProperty("offlineMode", false);- db.fs().cancel("offline-mode");- return;- }- SettingsService.setProperty("offlineMode", true);- db.attachments.cacheAttachments().catch(() => {- /* empty */- });- }- },- {- id: "auto-sync",- name: strings.disableAutoSync(),- description: strings.disableAutoSyncDesc(),- type: "switch",- property: "disableAutoSync",- featureId: "syncControls",- icon: "sync-off"- },- {- id: "disable-realtime-sync",- name: strings.disableRealtimeSync(),- description: strings.disableRealtimeSyncDesc(),- type: "switch",- property: "disableRealtimeSync",- featureId: "syncControls"- },- {- id: "disable-sync",- name: strings.disableSync(),- description: strings.disableSyncDesc(),- type: "switch",- property: "disableSync",- featureId: "syncControls",- icon: "cloud-off-outline"- },- {- id: "background-sync",- name: strings.backgroundSync(),- description: strings.backgroundSyncDesc(),- type: "switch",- property: "backgroundSync",- icon: "cloud-upload-outline",- onChange: (value) => {- if (value) {- BackgroundSync.start();- } else {- BackgroundSync.stop();- }- }- },- {- id: "pull-sync",- name: strings.forcePullChanges(),- description: strings.forcePullChangesDesc(),- icon: "download",- modifer: () => {- presentDialog({- title: strings.forcePullChanges(),- paragraph: strings.forceSyncNotice(),- negativeText: strings.cancel(),- positiveText: strings.start(),- positivePress: async () => {- eSendEvent(eCloseSheet);- await sleep(300);- Progress.present();- Sync.run("global", true, "fetch", () => {- eSendEvent(eCloseSheet);+ }+ });});}- });- }- },- {- id: "push-sync",- name: strings.forcePushChanges(),- description: strings.forcePushChangesDesc(),- icon: "upload",- modifer: () => {- presentDialog({- title: strings.forcePushChanges(),- paragraph: strings.forceSyncNotice(),- negativeText: strings.cancel(),- positiveText: strings.start(),- positivePress: async () => {- eSendEvent(eCloseSheet);- await sleep(300);- Progress.present();- Sync.run("global", true, "send", () => {- eSendEvent(eCloseSheet);- });++ try {+ Navigation.push("SettingsGroup", {+ id: "setup-inbox-keys",+ name: strings.setupInboxKeys(),+ type: "screen",+ component: "setup-inbox-keys"+ } as any);+ } catch (e) {+ console.log(e);}- });- }- }- ]- },- {- id: "notesnook-circle",- name: strings.notesnookCircle(),- icon: "circle-outline",- type: "screen",- description: strings.notesnookCircleDesc(),- component: "notesnook-circle"- },- {- id: "inbox-api",- name: strings.inboxAPI(),- icon: "inbox",- type: "screen",- description: strings.inboxAPIDesc(),- sections: [- {- id: "toggle-inbox-api",- name: strings.enableInboxAPI(),- description: strings.enableInboxAPIDesc(),- type: "switch",- useHook: () => {- return useSettingStore((state) => state.inboxEnabled);+ }},- getter: (current) => current,- modifer: async (current) => {- if (current) {+ {+ id: "manage-inbox-keys",+ name: strings.manageInboxKeys(),+ useHook: () => useSettingStore((state) => state.inboxEnabled),+ hidden: (current) => !current,+ description: strings.manageInboxKeysDesc(),+ onVerify: async () => {return new Promise((resolve) => {- presentDialog({- title: strings.disableInboxAPI(),- paragraph: strings.disableInboxAPIDesc(),- positiveText: strings.disable(),- onClose: () => {- resolve();+ verifyUser(+ "global",+ () => {+ resolve(true);},- positivePress: async () => {- try {- await db.inboxItemsHistory.deleteFailed();- await db.user.discardInboxKeys();- useSettingStore.setState({- inboxEnabled: false- });- resolve();- return true;- } catch (e) {- ToastManager.show({- message: (e as Error).message,- context: "local"- });- DatabaseLogger.error(e);- return false;- }- }- });+ false,+ () => resolve(false)+ );});- }-- try {- Navigation.push("SettingsGroup", {- id: "setup-inbox-keys",- name: strings.setupInboxKeys(),- type: "screen",- component: "setup-inbox-keys"- } as any);- } catch (e) {- console.log(e);- }- }- },- {- id: "manage-inbox-keys",- name: strings.manageInboxKeys(),- useHook: () => useSettingStore((state) => state.inboxEnabled),- hidden: (current) => !current,- description: strings.manageInboxKeysDesc(),- onVerify: async () => {- return new Promise((resolve) => {- verifyUser(- "global",- () => {- resolve(true);- },- false,- () => resolve(false)- );- });+ },+ type: "screen",+ component: "manage-inbox-keys"},- type: "screen",- component: "manage-inbox-keys"- },- {- id: "inbox-keys",- name: strings.viewAPIKeys(),- description: strings.viewAPIKeysDesc(),- useHook: () => useSettingStore((state) => state.inboxEnabled),- hidden: (current) => !current,- type: "screen",- component: "inbox-keys"- },- {- id: "failed-inbox-items",- name: strings.failedInboxItems(),- description: strings.failedInboxItemsDesc(),- useHook: () => useSettingStore((state) => state.inboxEnabled),- hidden: (current) => !current,- type: "screen",- component: "failed-inbox-items",- hideHeader: true- }- ]- }- ]- },- {- id: "customize",- name: strings.customization(),- sections: [- {- id: "personalization",- type: "screen",- name: strings.appearance(),- description: strings.appearanceDesc(),- icon: "shape",- sections: [- {- id: "theme-picker",- type: "screen",- name: strings.themes(),- description: strings.themesDesc(),- component: "theme-selector",- icon: "shape"- },- {- id: "use-system-theme",- type: "switch",- name: strings.useSystemTheme(),- description: strings.useSystemThemeDesc(),- property: "useSystemTheme",- icon: "circle-half",- modifer: () => {- const current = SettingsService.get().useSystemTheme;- SettingsService.set({- useSystemTheme: !current- });- if (!current) {- useThemeStore- .getState()- .setColorScheme(Appearance.getColorScheme() as any);- }+ {+ id: "inbox-keys",+ name: strings.viewAPIKeys(),+ description: strings.viewAPIKeysDesc(),+ useHook: () => useSettingStore((state) => state.inboxEnabled),+ hidden: (current) => !current,+ type: "screen",+ component: "inbox-keys"+ },+ {+ id: "failed-inbox-items",+ name: strings.failedInboxItems(),+ description: strings.failedInboxItemsDesc(),+ useHook: () => useSettingStore((state) => state.inboxEnabled),+ hidden: (current) => !current,+ type: "screen",+ component: "failed-inbox-items",+ hideHeader: true}- },- {- id: "enable-dark-mode",- type: "switch",- name: strings.darkMode(),- description: strings.darkModeDesc(),- property: "colorScheme",- icon: "brightness-6",- modifer: () => {- useThemeStore.getState().setColorScheme();+ ]+ }+ ]+ },+ {+ id: "customize",+ name: strings.customization(),+ sections: [+ {+ id: "personalization",+ type: "screen",+ name: strings.appearance(),+ description: strings.appearanceDesc(),+ icon: "shape",+ sections: [+ {+ id: "theme-picker",+ type: "screen",+ name: strings.themes(),+ description: strings.themesDesc(),+ component: "theme-selector",+ icon: "shape"},- getter: () => useThemeStore.getState().colorScheme === "dark"- }- ]- },- {- id: "behaviour",- type: "screen",- icon: "brain",- name: strings.behavior(),- description: strings.behaviorDesc(),- sections: [- {- id: "app-language",- name: strings.selectLanguage(),- description: strings.changeLanguage(),- type: "component",- component: "language-selector",- property: "appLanguage",- icon: "google-translate"- },- {- id: "default-sidebar-view",- type: "component",- name: strings.defaultSidebarTab(),- description: strings.defaultSidebarTabDesc(),- component: "sidebar-tab-selector"- },- {- id: "date-format",- name: strings.dateFormat(),- description: strings.dateFormatDesc(),- type: "component",- component: "date-format-selector",- icon: "calendar-blank"- },- {- id: "day-format",- name: strings.dayFormat(),- description: strings.dayFormatDesc(),- type: "component",- component: "day-format-selector",- icon: "calendar-today"- },- {- id: "week-format",- name: strings.weekFormat(),- description: strings.weekFormatDesc(),- type: "component",- component: "week-format-selector",- icon: "calendar"- },- {- id: "time-format",- name: strings.timeFormat(),- description: strings.timeFormatDesc(),- type: "component",- component: "time-format-selector",- icon: "clock-digital"- },- {- id: "clear-trash-interval",- type: "component",- name: strings.clearTrashInterval(),- description: strings.clearTrashIntervalDesc(),- component: "trash-interval-selector",- icon: "delete"- },- {- id: "default-notebook",- name: strings.clearDefaultNotebook(),- description: strings.clearDefaultNotebookDesc(),- modifer: () => {- db.settings.setDefaultNotebook(undefined);- ToastManager.show({- heading: strings.defaultNotebookCleared(),- type: "success"- });+ {+ id: "use-system-theme",+ type: "switch",+ name: strings.useSystemTheme(),+ description: strings.useSystemThemeDesc(),+ property: "useSystemTheme",+ icon: "circle-half",+ modifer: () => {+ const current = SettingsService.get().useSystemTheme;+ SettingsService.set({+ useSystemTheme: !current+ });+ if (!current) {+ useThemeStore+ .getState()+ .setColorScheme(Appearance.getColorScheme() as any);+ }+ }},- disabled: () => !db.settings.getDefaultNotebook(),- icon: "notebook-minus"- },- {- id: "disable-update-check",- type: "switch",- name: strings.autoUpdateCheck(),- description: strings.autoUpdateCheckDesc(),- property: "checkForUpdates",- icon: "update"- },- {- id: "keep-screen-on",- type: "switch",- name: strings.keepScreenOn(),- description: strings.keepScreenOnDesc(),- property: "keepScreenOn",- icon: "cellphone-screenshot"- },- {- id: "image-compression",- type: "component",- name: strings.imageCompression(),- description: strings.imageCompressionDesc(),- component: "image-compression-picker",- icon: "image-area"- }- ]- },- {- id: "editor",- name: strings.editor(),- type: "screen",- icon: "note-edit-outline",- description: strings.editorDesc(),- sections: [- {- id: "configure-toolbar",- type: "screen",- name: strings.customizeToolbar(),- description: strings.customizeToolbarDesc(),- component: "configuretoolbar"- },- {- id: "reset-toolbar",- name: strings.resetToolbar(),- description: strings.resetToolbarDesc(),- modifer: () => {- useDragState.getState().setPreset("default");- ToastManager.show({- heading: strings.toolbarReset(),- type: "success"- });- }- },- {- id: "double-spaced-lines",- name: strings.doubleSpacedLines(),- description: strings.doubleSpacedLinesDesc(),- type: "switch",- property: "doubleSpacedLines",- icon: "format-line-spacing",- onChange: () => {- ToastManager.show({- heading: strings.lineSpacingChanged(),- type: "success"- });+ {+ id: "enable-dark-mode",+ type: "switch",+ name: strings.darkMode(),+ description: strings.darkModeDesc(),+ property: "colorScheme",+ icon: "brightness-6",+ modifer: () => {+ useThemeStore.getState().setColorScheme();+ },+ getter: () => useThemeStore.getState().colorScheme === "dark"}- },- {- id: "default-font-size",- name: strings.defaultFontSize(),- description: strings.defaultFontSizeDesc(),- type: "input-selector",- minInputValue: 8,- maxInputValue: 120,- icon: "format-size",- property: "defaultFontSize"- },- {- id: "default-font-family",- name: strings.defaultFontFamily(),- description: strings.defaultFontFamilyDesc(),- type: "component",- icon: "format-font",- property: "defaultFontFamily",- component: "font-selector"- },- {- id: "default-line-height",- name: strings.lineHeight(),- description: strings.lineHeightDesc(),- type: "input-selector",- property: "defaultLineHeight",- icon: "format-line-spacing",- minInputValue: EDITOR_LINE_HEIGHT.MIN,- maxInputValue: EDITOR_LINE_HEIGHT.MAX- },- {- id: "title-format",- name: strings.titleFormat(),- component: "title-format",- description: strings.titleFormatDesc(),- type: "component"- },- {- id: "toggle-markdown",- name: strings.mardownShortcuts(),- property: "markdownShortcuts",- description: strings.mardownShortcutsDesc(),- type: "switch",- featureId: "markdownShortcuts"- }- ]- },- {- id: "servers",- type: "screen",- name: strings.servers(),- description: strings.serversConfigurationDesc(),- icon: "server",- component: "server-config"- }- ]- },- {- id: "privacy-security",- name: strings.privacyAndSecurity(),- sections: [- {- id: "marketing-emails",- type: "switch",- icon: "email-newsletter",- name: strings.marketingEmails(),- description: strings.marketingEmailsDesc(),- modifer: async () => {- try {- await db.user?.changeMarketingConsent(- !useUserStore.getState().user?.marketingConsent- );- useUserStore.getState().setUser(await db.user?.fetchUser());- } catch (e) {- ToastManager.error(e as Error);- }+ ]},- getter: (current: any) => current?.marketingConsent,- useHook: () => useUserStore((state) => state.user),- hidden: (current) => !current- },- {- id: "cors-bypass",- type: "input",- name: strings.corsBypass(),- description: strings.corsBypassDesc(),- inputProperties: {- defaultValue: "https://cors.notesnook.com",- autoCorrect: false,- keyboardType: "url"- },- property: "corsProxy",- icon: "arrow-decision-outline"- },-- {- id: "vault",- type: "screen",- name: strings.vault(),- description: strings.vaultDesc(),- icon: "key",- sections: [- {- id: "create-vault",- name: strings.createVault(),- description: strings.createVaultDesc(),- icon: "key",- useHook: useVaultStatus,- hidden: (current) => (current as VaultStatusType)?.exists,- modifer: () => {- openVault({- requestType: VaultRequestType.CreateVault,- title: strings.createVault(),- buttonTitle: strings.create()- });- }- },- {- id: "lock-vault-after",- type: "component",- useHook: useVaultStatus,- name: strings.lockVaultAfter(),- description: strings.lockVaultAfterDesc(),- hidden: (current) => !(current as VaultStatusType)?.exists,- component: "vault-lock-timer",- icon: "clock-outline"- },- {- id: "change-vault-password",- useHook: useVaultStatus,- name: strings.changeVaultPassword(),- description: strings.changeVaultPasswordDesc(),- hidden: (current) => !(current as VaultStatusType)?.exists,- modifer: () =>- openVault({- requestType: VaultRequestType.ChangePassword,- title: strings.changeVaultPassword(),- buttonTitle: strings.change()- })- },- {- id: "clear-vault",- useHook: useVaultStatus,- description: strings.clearVaultDesc(),- name: strings.clearVault(),- hidden: (current) => !(current as VaultStatusType)?.exists,- modifer: () => {- openVault({- requestType: VaultRequestType.ClearVault,- title: strings.clearVault() + "?",- buttonTitle: strings.clear(),- positiveButtonType: "errorShade"- });- }- },- {- id: "delete-vault",- name: strings.deleteVault(),- description: strings.deleteVaultDesc(),- useHook: useVaultStatus,- hidden: (current) => !(current as VaultStatusType)?.exists,- modifer: () => {- openVault({- requestType: VaultRequestType.DeleteVault,- title: strings.deleteVault() + "?",- buttonTitle: strings.delete(),- positiveButtonType: "errorShade"- });- }- },- {- id: "biometric-unlock",- type: "switch",- name: strings.biometricUnlock(),- icon: "fingerprint",- useHook: useVaultStatus,- description: strings.biometricUnlockDesc(),- hidden: (current) => {- const _current = current as VaultStatusType;- return !_current?.exists || !_current?.isBiometryAvailable;+ {+ id: "behaviour",+ type: "screen",+ icon: "brain",+ name: strings.behavior(),+ description: strings.behaviorDesc(),+ sections: [+ {+ id: "app-language",+ name: strings.selectLanguage(),+ description: strings.changeLanguage(),+ type: "component",+ component: "language-selector",+ property: "appLanguage",+ icon: "google-translate"},- getter: (current) => (current as VaultStatusType)?.biometryEnrolled,- modifer: (current) => {- const _current = current as VaultStatusType;- const isRevoking = _current.biometryEnrolled;- openVault({- requestType: isRevoking- ? VaultRequestType.RevokeFingerprint- : VaultRequestType.EnableFingerprint,- title: isRevoking- ? strings.revokeBiometricUnlock()- : strings.vaultEnableBiometrics(),- buttonTitle: isRevoking ? strings.revoke() : strings.enable()- });+ {+ id: "default-sidebar-view",+ type: "component",+ name: strings.defaultSidebarTab(),+ description: strings.defaultSidebarTabDesc(),+ component: "sidebar-tab-selector"+ },+ {+ id: "date-format",+ name: strings.dateFormat(),+ description: strings.dateFormatDesc(),+ type: "component",+ component: "date-format-selector",+ icon: "calendar-blank"+ },+ {+ id: "day-format",+ name: strings.dayFormat(),+ description: strings.dayFormatDesc(),+ type: "component",+ component: "day-format-selector",+ icon: "calendar-today"+ },+ {+ id: "week-format",+ name: strings.weekFormat(),+ description: strings.weekFormatDesc(),+ type: "component",+ component: "week-format-selector",+ icon: "calendar"+ },+ {+ id: "time-format",+ name: strings.timeFormat(),+ description: strings.timeFormatDesc(),+ type: "component",+ component: "time-format-selector",+ icon: "clock-digital"+ },+ {+ id: "clear-trash-interval",+ type: "component",+ name: strings.clearTrashInterval(),+ description: strings.clearTrashIntervalDesc(),+ component: "trash-interval-selector",+ icon: "delete"+ },+ {+ id: "default-notebook",+ name: strings.clearDefaultNotebook(),+ description: strings.clearDefaultNotebookDesc(),+ modifer: () => {+ db.settings.setDefaultNotebook(undefined);+ ToastManager.show({+ heading: strings.defaultNotebookCleared(),+ type: "success"+ });+ },+ disabled: () => !db.settings.getDefaultNotebook(),+ icon: "notebook-minus"+ },+ {+ id: "disable-update-check",+ type: "switch",+ name: strings.autoUpdateCheck(),+ description: strings.autoUpdateCheckDesc(),+ property: "checkForUpdates",+ icon: "update"+ },+ {+ id: "keep-screen-on",+ type: "switch",+ name: strings.keepScreenOn(),+ description: strings.keepScreenOnDesc(),+ property: "keepScreenOn",+ icon: "cellphone-screenshot"+ },+ {+ id: "image-compression",+ type: "component",+ name: strings.imageCompression(),+ description: strings.imageCompressionDesc(),+ component: "image-compression-picker",+ icon: "image-area"}- }- ]- },- {- id: "privacy-mode",- type: "switch",- icon: "eye-off-outline",- name: strings.privacyMode(),- description: strings.privacyModeDesc(),- modifer: () => {- const settings = SettingsService.get();- SettingsService.setPrivacyScreen(!settings.privacyScreen);- SettingsService.set({ privacyScreen: !settings.privacyScreen });+ ]},- property: "privacyScreen"- },- {- id: "app-lock",- name: strings.appLock(),- type: "screen",- description: strings.appLockDesc(),- icon: "lock",- featureId: "appLock",- sections: [- {- id: "app-lock-mode",- name: strings.enableAppLock(),- description: strings.appLockDesc(),- icon: "lock",- type: "switch",- property: "appLockEnabled",- featureId: "appLock",- onChange: (property) => {- if (property) {- SettingsService.set({- privacyScreen: true+ {+ id: "editor",+ name: strings.editor(),+ type: "screen",+ icon: "note-edit-outline",+ description: strings.editorDesc(),+ sections: [+ {+ id: "configure-toolbar",+ type: "screen",+ name: strings.customizeToolbar(),+ description: strings.customizeToolbarDesc(),+ component: "configuretoolbar"+ },+ {+ id: "reset-toolbar",+ name: strings.resetToolbar(),+ description: strings.resetToolbarDesc(),+ modifer: () => {+ useDragState.getState().setPreset("default");+ ToastManager.show({+ heading: strings.toolbarReset(),+ type: "success"});- SettingsService.setPrivacyScreen(true);}},- onVerify: async () => {- const verified = await verifyUserWithApplock();- if (!verified) return false;-- if (!SettingsService.getProperty("appLockEnabled")) {- if (- !SettingsService.getProperty("appLockHasPasswordSecurity") &&- (await BiometricService.isBiometryAvailable())- ) {- SettingsService.setProperty("biometricsAuthEnabled", true);- }-- if (- !(await BiometricService.isBiometryAvailable()) &&- !SettingsService.getProperty("appLockHasPasswordSecurity")- ) {- ToastManager.show({- heading: strings.biometricsNotEnrolled(),- type: "error",- message: strings.biometricsNotEnrolledDesc()- });- return false;- }+ {+ id: "double-spaced-lines",+ name: strings.doubleSpacedLines(),+ description: strings.doubleSpacedLinesDesc(),+ type: "switch",+ property: "doubleSpacedLines",+ icon: "format-line-spacing",+ onChange: () => {+ ToastManager.show({+ heading: strings.lineSpacingChanged(),+ type: "success"+ });}-- return verified;+ },+ {+ id: "default-font-size",+ name: strings.defaultFontSize(),+ description: strings.defaultFontSizeDesc(),+ type: "input-selector",+ minInputValue: 8,+ maxInputValue: 120,+ icon: "format-size",+ property: "defaultFontSize"+ },+ {+ id: "default-font-family",+ name: strings.defaultFontFamily(),+ description: strings.defaultFontFamilyDesc(),+ type: "component",+ icon: "format-font",+ property: "defaultFontFamily",+ component: "font-selector"+ },+ {+ id: "default-line-height",+ name: strings.lineHeight(),+ description: strings.lineHeightDesc(),+ type: "input-selector",+ property: "defaultLineHeight",+ icon: "format-line-spacing",+ minInputValue: EDITOR_LINE_HEIGHT.MIN,+ maxInputValue: EDITOR_LINE_HEIGHT.MAX+ },+ {+ id: "title-format",+ name: strings.titleFormat(),+ component: "title-format",+ description: strings.titleFormatDesc(),+ type: "component"+ },+ {+ id: "toggle-markdown",+ name: strings.mardownShortcuts(),+ property: "markdownShortcuts",+ description: strings.mardownShortcutsDesc(),+ type: "switch",+ featureId: "markdownShortcuts"+ }+ ]+ },+ {+ id: "servers",+ type: "screen",+ name: strings.servers(),+ description: strings.serversConfigurationDesc(),+ icon: "server",+ component: "server-config"+ }+ ]+ },+ {+ id: "privacy-security",+ name: strings.privacyAndSecurity(),+ sections: [+ {+ id: "marketing-emails",+ type: "switch",+ icon: "email-newsletter",+ name: strings.marketingEmails(),+ description: strings.marketingEmailsDesc(),+ modifer: async () => {+ try {+ await db.user?.changeMarketingConsent(+ !useUserStore.getState().user?.marketingConsent+ );+ useUserStore.getState().setUser(await db.user?.fetchUser());+ } catch (e) {+ ToastManager.error(e as Error);}},- {- id: "app-lock-timer",- name: strings.appLockTimeout(),- description: strings.appLockTimeoutDesc(),- type: "component",- component: "applock-timer"+ getter: (current: any) => current?.marketingConsent,+ useHook: () => useUserStore((state) => state.user),+ hidden: (current) => !current+ },+ {+ id: "cors-bypass",+ type: "input",+ name: strings.corsBypass(),+ description: strings.corsBypassDesc(),+ inputProperties: {+ defaultValue: "https://cors.notesnook.com",+ autoCorrect: false,+ keyboardType: "url"},- {- id: "app-lock-pin",- name: () =>- SettingsService.getProperty("applockKeyboardType") === "numeric"- ? strings.setupAppLockPin()- : strings.setupAppLockPassword(),+ property: "corsProxy",+ icon: "arrow-decision-outline"+ },- description: () =>- SettingsService.getProperty("applockKeyboardType") === "numeric"- ? strings.setupAppLockPinDesc()- : strings.setupAppLockPasswordDesc(),- hidden: () => {- return !!SettingsService.getProperty(- "appLockHasPasswordSecurity"- );+ {+ id: "vault",+ type: "screen",+ name: strings.vault(),+ description: strings.vaultDesc(),+ icon: "key",+ sections: [+ {+ id: "create-vault",+ name: strings.createVault(),+ description: strings.createVaultDesc(),+ icon: "key",+ useHook: useVaultStatus,+ hidden: (current) => (current as VaultStatusType)?.exists,+ modifer: () => {+ openVault({+ requestType: VaultRequestType.CreateVault,+ title: strings.createVault(),+ buttonTitle: strings.create()+ });+ }},- onVerify: () => {- return verifyUserWithApplock();+ {+ id: "lock-vault-after",+ type: "component",+ useHook: useVaultStatus,+ name: strings.lockVaultAfter(),+ description: strings.lockVaultAfterDesc(),+ hidden: (current) => !(current as VaultStatusType)?.exists,+ component: "vault-lock-timer",+ icon: "clock-outline"},- property: "appLockHasPasswordSecurity",- modifer: () => {- AppLockPassword.present("create");- }- },- {- id: "app-lock-pin-change",- name: () =>- SettingsService.getProperty("applockKeyboardType") === "numeric"- ? strings.changeAppLockPin()- : strings.changeAppLockPassword(),- description: () =>- SettingsService.getProperty("applockKeyboardType") === "numeric"- ? strings.changeAppLockPinDesc()- : strings.changeAppLockPasswordDesc(),- hidden: () => {- return !SettingsService.getProperty("appLockHasPasswordSecurity");+ {+ id: "change-vault-password",+ useHook: useVaultStatus,+ name: strings.changeVaultPassword(),+ description: strings.changeVaultPasswordDesc(),+ hidden: (current) => !(current as VaultStatusType)?.exists,+ modifer: () =>+ openVault({+ requestType: VaultRequestType.ChangePassword,+ title: strings.changeVaultPassword(),+ buttonTitle: strings.change()+ })},- property: "appLockHasPasswordSecurity",- modifer: () => {- AppLockPassword.present("change");- }- },- {- id: "app-lock-pin-remove",- name: () =>- SettingsService.getProperty("applockKeyboardType") === "numeric"- ? strings.removeAppLockPin()- : strings.removeAppLockPassword(),- description: () =>- SettingsService.getProperty("applockKeyboardType") === "numeric"- ? strings.removeAppLockPinDesc()- : strings.removeAppLockPasswordDesc(),- hidden: () => {- return !SettingsService.getProperty("appLockHasPasswordSecurity");+ {+ id: "clear-vault",+ useHook: useVaultStatus,+ description: strings.clearVaultDesc(),+ name: strings.clearVault(),+ hidden: (current) => !(current as VaultStatusType)?.exists,+ modifer: () => {+ openVault({+ requestType: VaultRequestType.ClearVault,+ title: strings.clearVault() + "?",+ buttonTitle: strings.clear(),+ positiveButtonType: "errorShade"+ });+ }+ },+ {+ id: "delete-vault",+ name: strings.deleteVault(),+ description: strings.deleteVaultDesc(),+ useHook: useVaultStatus,+ hidden: (current) => !(current as VaultStatusType)?.exists,+ modifer: () => {+ openVault({+ requestType: VaultRequestType.DeleteVault,+ title: strings.deleteVault() + "?",+ buttonTitle: strings.delete(),+ positiveButtonType: "errorShade"+ });+ }},- property: "appLockHasPasswordSecurity",- modifer: () => {- AppLockPassword.present("remove");+ {+ id: "biometric-unlock",+ type: "switch",+ name: strings.biometricUnlock(),+ icon: "fingerprint",+ useHook: useVaultStatus,+ description: strings.biometricUnlockDesc(),+ hidden: (current) => {+ const _current = current as VaultStatusType;+ return !_current?.exists || !_current?.isBiometryAvailable;+ },+ getter: (current) => (current as VaultStatusType)?.biometryEnrolled,+ modifer: (current) => {+ const _current = current as VaultStatusType;+ const isRevoking = _current.biometryEnrolled;+ openVault({+ requestType: isRevoking+ ? VaultRequestType.RevokeFingerprint+ : VaultRequestType.EnableFingerprint,+ title: isRevoking+ ? strings.revokeBiometricUnlock()+ : strings.vaultEnableBiometrics(),+ buttonTitle: isRevoking ? strings.revoke() : strings.enable()+ });+ }}+ ]+ },+ {+ id: "privacy-mode",+ type: "switch",+ icon: "eye-off-outline",+ name: strings.privacyMode(),+ description: strings.privacyModeDesc(),+ modifer: () => {+ const settings = SettingsService.get();+ SettingsService.setPrivacyScreen(!settings.privacyScreen);+ SettingsService.set({ privacyScreen: !settings.privacyScreen });},- {- id: "app-lock-fingerprint",- name: strings.unlockWithBiometrics(),- description: strings.unlockWithBiometricsDesc(),- type: "switch",- property: "biometricsAuthEnabled",- onVerify: async () => {- const verified = await verifyUserWithApplock();- if (!verified) return false;-- if (SettingsService.getProperty("biometricsAuthEnabled")) {- if (- !SettingsService.getProperty("appLockHasPasswordSecurity")- ) {- SettingsService.setProperty("appLockEnabled", false);- ToastManager.show({- heading: strings.appLockDisabled(),- type: "success"+ property: "privacyScreen"+ },+ {+ id: "app-lock",+ name: strings.appLock(),+ type: "screen",+ description: strings.appLockDesc(),+ icon: "lock",+ featureId: "appLock",+ sections: [+ {+ id: "app-lock-mode",+ name: strings.enableAppLock(),+ description: strings.appLockDesc(),+ icon: "lock",+ type: "switch",+ property: "appLockEnabled",+ featureId: "appLock",+ onChange: (property) => {+ if (property) {+ SettingsService.set({+ privacyScreen: true});+ SettingsService.setPrivacyScreen(true);+ }+ },+ onVerify: async () => {+ const verified = await verifyUserWithApplock();+ if (!verified) return false;++ if (!SettingsService.getProperty("appLockEnabled")) {+ if (+ !SettingsService.getProperty("appLockHasPasswordSecurity") &&+ (await BiometricService.isBiometryAvailable())+ ) {+ SettingsService.setProperty("biometricsAuthEnabled", true);+ }++ if (+ !(await BiometricService.isBiometryAvailable()) &&+ !SettingsService.getProperty("appLockHasPasswordSecurity")+ ) {+ ToastManager.show({+ heading: strings.biometricsNotEnrolled(),+ type: "error",+ message: strings.biometricsNotEnrolledDesc()+ });+ return false;+ }}++ return verified;}+ },+ {+ id: "app-lock-timer",+ name: strings.appLockTimeout(),+ description: strings.appLockTimeoutDesc(),+ type: "component",+ component: "applock-timer"+ },+ {+ id: "app-lock-pin",+ name: () =>+ SettingsService.getProperty("applockKeyboardType") === "numeric"+ ? strings.setupAppLockPin()+ : strings.setupAppLockPassword(),- return verified;+ description: () =>+ SettingsService.getProperty("applockKeyboardType") === "numeric"+ ? strings.setupAppLockPinDesc()+ : strings.setupAppLockPasswordDesc(),+ hidden: () => {+ return !!SettingsService.getProperty(+ "appLockHasPasswordSecurity"+ );+ },+ onVerify: () => {+ return verifyUserWithApplock();+ },+ property: "appLockHasPasswordSecurity",+ modifer: () => {+ AppLockPassword.present("create");+ }},- icon: "fingerprint"- }- ]- }- ]- },- {- id: "back-restore",- name: strings.backupRestore(),- sections: [- {- id: "backups",- type: "screen",- name: strings.backups(),- icon: "backup-restore",- description: strings.backupsDesc(),- sections: [- {- id: "backup-now",- name: strings.backupNow(),- description: strings.backupNowDesc(),- modifer: async () => {- const user = useUserStore.getState().user;- if (!user || SettingsService.getProperty("encryptedBackup")) {- await BackupService.run(true);- return;+ {+ id: "app-lock-pin-change",+ name: () =>+ SettingsService.getProperty("applockKeyboardType") === "numeric"+ ? strings.changeAppLockPin()+ : strings.changeAppLockPassword(),+ description: () =>+ SettingsService.getProperty("applockKeyboardType") === "numeric"+ ? strings.changeAppLockPinDesc()+ : strings.changeAppLockPasswordDesc(),+ hidden: () => {+ return !SettingsService.getProperty("appLockHasPasswordSecurity");+ },+ property: "appLockHasPasswordSecurity",+ modifer: () => {+ AppLockPassword.present("change");+ }+ },+ {+ id: "app-lock-pin-remove",+ name: () =>+ SettingsService.getProperty("applockKeyboardType") === "numeric"+ ? strings.removeAppLockPin()+ : strings.removeAppLockPassword(),+ description: () =>+ SettingsService.getProperty("applockKeyboardType") === "numeric"+ ? strings.removeAppLockPinDesc()+ : strings.removeAppLockPasswordDesc(),+ hidden: () => {+ return !SettingsService.getProperty("appLockHasPasswordSecurity");+ },+ property: "appLockHasPasswordSecurity",+ modifer: () => {+ AppLockPassword.present("remove");}+ },+ {+ id: "app-lock-fingerprint",+ name: strings.unlockWithBiometrics(),+ description: strings.unlockWithBiometricsDesc(),+ type: "switch",+ property: "biometricsAuthEnabled",+ onVerify: async () => {+ const verified = await verifyUserWithApplock();+ if (!verified) return false;- verifyUser(null, () => BackupService.run(true));+ if (SettingsService.getProperty("biometricsAuthEnabled")) {+ if (+ !SettingsService.getProperty("appLockHasPasswordSecurity")+ ) {+ SettingsService.setProperty("appLockEnabled", false);+ ToastManager.show({+ heading: strings.appLockDisabled(),+ type: "success"+ });+ }+ }++ return verified;+ },+ icon: "fingerprint"}- },- {- id: "backup-now-with-attachments",- name: strings.backupNowWithAttachments(),- description: strings.backupNowWithAttachmentsDesc(),- hidden: () => !useUserStore.getState().user,- modifer: async () => {- const user = useUserStore.getState().user;- if (!user || SettingsService.getProperty("encryptedBackup")) {- await BackupService.run(true, undefined, "full");- return;+ ]+ }+ ]+ },+ {+ id: "back-restore",+ name: strings.backupRestore(),+ sections: [+ {+ id: "backups",+ type: "screen",+ name: strings.backups(),+ icon: "backup-restore",+ description: strings.backupsDesc(),+ sections: [+ {+ id: "backup-now",+ name: strings.backupNow(),+ description: strings.backupNowDesc(),+ modifer: async () => {+ const user = useUserStore.getState().user;+ if (!user || SettingsService.getProperty("encryptedBackup")) {+ await BackupService.run(true);+ return;+ }++ verifyUser(null, () => BackupService.run(true));}+ },+ {+ id: "backup-now-with-attachments",+ name: strings.backupNowWithAttachments(),+ description: strings.backupNowWithAttachmentsDesc(),+ hidden: () => !useUserStore.getState().user,+ modifer: async () => {+ const user = useUserStore.getState().user;+ if (!user || SettingsService.getProperty("encryptedBackup")) {+ await BackupService.run(true, undefined, "full");+ return;+ }- verifyUser(null, () =>- BackupService.run(true, undefined, "full")- );- }- },- {- id: "auto-backups",- type: "component",- name: strings.automaticBackups(),- description: strings.automaticBackupsDesc(),- component: "autobackups"- },- {- id: "auto-backups-with-attachments",- type: "component",- hidden: () => !useUserStore.getState().user,- name: strings.automaticBackupsWithAttachments(),- description: [- ...strings.automaticBackupsWithAttachmentsDesc()- ].join("\n"),- component: "autobackupsattachments"- },- {- id: "select-backup-dir",- name: strings.selectBackupDir(),- description: () => {- const desc = strings.selectBackupDirDesc(- SettingsService.get().backupDirectoryAndroid?.path || ""- );- return desc[0] + " " + desc[1];+ verifyUser(null, () =>+ BackupService.run(true, undefined, "full")+ );+ }},- icon: "folder",- hidden: () =>- !!SettingsService.get().backupDirectoryAndroid ||- Platform.OS !== "android",- property: "backupDirectoryAndroid",- modifer: async () => {- let dir;- try {- dir = await BackupService.checkBackupDirExists(true);- } catch (e) {- console.error(e);- } finally {- if (!dir) {- ToastManager.show({- heading: strings.noDirectorySelected(),- type: "error"- });+ {+ id: "auto-backups",+ type: "component",+ name: strings.automaticBackups(),+ description: strings.automaticBackupsDesc(),+ component: "autobackups"+ },+ {+ id: "auto-backups-with-attachments",+ type: "component",+ hidden: () => !useUserStore.getState().user,+ name: strings.automaticBackupsWithAttachments(),+ description: [+ ...strings.automaticBackupsWithAttachmentsDesc()+ ].join("\n"),+ component: "autobackupsattachments"+ },+ {+ id: "select-backup-dir",+ name: strings.selectBackupDir(),+ description: () => {+ const desc = strings.selectBackupDirDesc(+ SettingsService.get().backupDirectoryAndroid?.path || ""+ );+ return desc[0] + " " + desc[1];+ },+ icon: "folder",+ hidden: () =>+ !!SettingsService.get().backupDirectoryAndroid ||+ Platform.OS !== "android",+ property: "backupDirectoryAndroid",+ modifer: async () => {+ let dir;+ try {+ dir = await BackupService.checkBackupDirExists(true);+ } catch (e) {+ console.error(e);+ } finally {+ if (!dir) {+ ToastManager.show({+ heading: strings.noDirectorySelected(),+ type: "error"+ });+ }}}- }- },- {- id: "change-backup-dir",- name: strings.changeBackupDir(),- description: () =>- SettingsService.get().backupDirectoryAndroid?.name || "",- icon: "folder",- hidden: () =>- !SettingsService.get().backupDirectoryAndroid ||- Platform.OS !== "android",- property: "backupDirectoryAndroid",- modifer: async () => {- let dir;- try {- dir = await BackupService.checkBackupDirExists(true);- } catch (e) {- console.error(e);- } finally {- if (!dir) {+ },+ {+ id: "change-backup-dir",+ name: strings.changeBackupDir(),+ description: () =>+ SettingsService.get().backupDirectoryAndroid?.name || "",+ icon: "folder",+ hidden: () =>+ !SettingsService.get().backupDirectoryAndroid ||+ Platform.OS !== "android",+ property: "backupDirectoryAndroid",+ modifer: async () => {+ let dir;+ try {+ dir = await BackupService.checkBackupDirExists(true);+ } catch (e) {+ console.error(e);+ } finally {+ if (!dir) {+ ToastManager.show({+ heading: strings.noDirectorySelected(),+ type: "error"+ });+ }+ }+ }+ },+ {+ id: "enable-backup-encryption",+ type: "switch",+ name: strings.backupEncryption(),+ description: strings.backupEncryptionDesc(),+ icon: "lock",+ property: "encryptedBackup",+ modifer: async () => {+ const user = useUserStore.getState().user;+ const settings = SettingsService.get();+ if (!user) {ToastManager.show({- heading: strings.noDirectorySelected(),+ heading: strings.loginRequired(),type: "error"});+ return;}- }- }- },- {- id: "enable-backup-encryption",- type: "switch",- name: strings.backupEncryption(),- description: strings.backupEncryptionDesc(),- icon: "lock",- property: "encryptedBackup",- modifer: async () => {- const user = useUserStore.getState().user;- const settings = SettingsService.get();- if (!user) {- ToastManager.show({- heading: strings.loginRequired(),- type: "error"- });- return;- }- if (settings.encryptedBackup) {- await verifyUser(null, () => {+ if (settings.encryptedBackup) {+ await verifyUser(null, () => {+ SettingsService.set({+ encryptedBackup: false+ });+ });+ } else {SettingsService.set({- encryptedBackup: false+ encryptedBackup: true});- });- } else {- SettingsService.set({- encryptedBackup: true- });+ }}}+ ]+ },+ {+ id: "restore-backup",+ name: strings.restoreBackup(),+ description: strings.restoreBackupDesc(),+ icon: "restore",+ type: "screen",+ component: "backuprestore"+ },+ {+ id: "export-notes",+ name: strings.exportAllNotes(),+ icon: "export",+ description: strings.exportAllNotesDesc(),+ modifer: () => {+ verifyUser(null, () => {+ ExportNotesSheet.present(undefined, true);+ });}- ]- },- {- id: "restore-backup",- name: strings.restoreBackup(),- description: strings.restoreBackupDesc(),- icon: "restore",- type: "screen",- component: "backuprestore"- },- {- id: "export-notes",- name: strings.exportAllNotes(),- icon: "export",- description: strings.exportAllNotesDesc(),- modifer: () => {- verifyUser(null, () => {- ExportNotesSheet.present(undefined, true);- });}- }- ]- },- {- id: "productivity",- name: strings.productivity(),- sections: [- {- id: "notification-notes",- type: "switch",- name: strings.quickNoteNotification(),- description: strings.quickNoteNotificationDesc(),- property: "notifNotes",- icon: "form-textbox",- modifer: async () => {- const settings = SettingsService.get();- if (settings.notifNotes) {- Notifications.unpinQuickNote();- } else {- Notifications.pinQuickNote();- }- SettingsService.set({- notifNotes: !settings.notifNotes- });+ ]+ },+ {+ id: "productivity",+ name: strings.productivity(),+ sections: [+ {+ id: "notification-notes",+ type: "switch",+ name: strings.quickNoteNotification(),+ description: strings.quickNoteNotificationDesc(),+ property: "notifNotes",+ icon: "form-textbox",+ modifer: async () => {+ const settings = SettingsService.get();+ if (settings.notifNotes) {+ Notifications.unpinQuickNote();+ } else {+ Notifications.pinQuickNote();+ }+ SettingsService.set({+ notifNotes: !settings.notifNotes+ });+ },+ hidden: () => Platform.OS !== "android",+ featureId: "createNoteFromNotificationDrawer"},- hidden: () => Platform.OS !== "android",- featureId: "createNoteFromNotificationDrawer"- },- {- id: "reminders",- type: "screen",- name: strings.reminders(),- icon: "bell",- description: strings.remindersDesc(),- sections: [- {- id: "enable-reminders",- property: "reminderNotifications",- type: "switch",- name: strings.reminderNotification(),- icon: "bell-outline",- onChange: (property) => {- if (property) {- Notifications.setupReminders();- } else {- Notifications.clearAllTriggers();+ {+ id: "reminders",+ type: "screen",+ name: strings.reminders(),+ icon: "bell",+ description: strings.remindersDesc(),+ sections: [+ {+ id: "enable-reminders",+ property: "reminderNotifications",+ type: "switch",+ name: strings.reminderNotification(),+ icon: "bell-outline",+ onChange: (property) => {+ if (property) {+ Notifications.setupReminders();+ } else {+ Notifications.clearAllTriggers();+ }+ },+ description: strings.reminderNotificationDesc()+ },+ {+ id: "snooze-time",+ property: "defaultSnoozeTime",+ type: "input",+ name: strings.defaultSnoozeTime(),+ description: strings.defaultSnoozeTimeDesc(),+ inputProperties: {+ keyboardType: "decimal-pad",+ defaultValue: 5 + "",+ placeholder: strings.setSnoozeTimePlaceholder(),+ onSubmitEditing: () => {+ Notifications.setupReminders();+ }}},- description: strings.reminderNotificationDesc()- },- {- id: "snooze-time",- property: "defaultSnoozeTime",- type: "input",- name: strings.defaultSnoozeTime(),- description: strings.defaultSnoozeTimeDesc(),- inputProperties: {- keyboardType: "decimal-pad",- defaultValue: 5 + "",- placeholder: strings.setSnoozeTimePlaceholder(),- onSubmitEditing: () => {- Notifications.setupReminders();+ {+ id: "reminder-sound-ios",+ type: "screen",+ name: strings.changeNotificationSound(),+ description: strings.changeNotificationSoundDesc(),+ component: "sound-picker",+ icon: "bell-ring",+ hidden: () =>+ Platform.OS === "ios" ||+ (Platform.OS === "android" && Platform.Version > 25)+ },+ {+ id: "reminder-sound-android",+ name: strings.changeNotificationSound(),+ description: strings.changeNotificationSoundDesc(),+ icon: "bell-ring",+ hidden: () =>+ Platform.OS === "ios" ||+ (Platform.OS === "android" && Platform.Version < 26),+ modifer: async () => {+ const id = await Notifications.getChannelId("urgent");+ if (id) {+ await notifee.openNotificationSettings(id);+ }}}+ ]+ }+ ]+ },+ {+ id: "help-support",+ name: strings.helpAndSupport(),+ sections: [+ {+ id: "report-issue",+ name: strings.reportAnIssue(),+ icon: "bug",+ modifer: () => {+ presentSheet({+ //@ts-ignore Migrate to TS+ component: <Issue />+ });},- {- id: "reminder-sound-ios",- type: "screen",- name: strings.changeNotificationSound(),- description: strings.changeNotificationSoundDesc(),- component: "sound-picker",- icon: "bell-ring",- hidden: () =>- Platform.OS === "ios" ||- (Platform.OS === "android" && Platform.Version > 25)- },- {- id: "reminder-sound-android",- name: strings.changeNotificationSound(),- description: strings.changeNotificationSoundDesc(),- icon: "bell-ring",- hidden: () =>- Platform.OS === "ios" ||- (Platform.OS === "android" && Platform.Version < 26),- modifer: async () => {- const id = await Notifications.getChannelId("urgent");- if (id) {- await notifee.openNotificationSettings(id);- }- }- }- ]- }- ]- },- {- id: "help-support",- name: strings.helpAndSupport(),- sections: [- {- id: "report-issue",- name: strings.reportAnIssue(),- icon: "bug",- modifer: () => {- presentSheet({- //@ts-ignore Migrate to TS- component: <Issue />- });+ description: strings.reportAnIssueDesc()},- description: strings.reportAnIssueDesc()- },- {- id: "email-support",- name: strings.emailSupport(),- icon: "email",- modifer: () => {- Clipboard.setString("[email protected]");- ToastManager.show({- heading: strings.emailCopied(),- type: "success",- icon: "content-copy"- });- setTimeout(() => {- Linking.openURL("mailto:[email protected]");- }, 1000);+ {+ id: "email-support",+ name: strings.emailSupport(),+ icon: "email",+ modifer: () => {+ Clipboard.setString("[email protected]");+ ToastManager.show({+ heading: strings.emailCopied(),+ type: "success",+ icon: "content-copy"+ });+ setTimeout(() => {+ Linking.openURL("mailto:[email protected]");+ }, 1000);+ },+ description: strings.emailSupportDesc()},- description: strings.emailSupportDesc()- },- {- id: "docs-link",- name: strings.documentation(),- modifer: async () => {- Linking.openURL("https://notesnook.com/help/");+ {+ id: "docs-link",+ name: strings.documentation(),+ modifer: async () => {+ Linking.openURL("https://notesnook.com/help/");+ },+ description: strings.documentationDesc(),+ icon: "file-document"},- description: strings.documentationDesc(),- icon: "file-document"- },- {- id: "debugging",- name: strings.debugging(),- description: strings.debuggingDesc(),- type: "screen",- icon: "bug",- sections: [- {- id: "debug-logs",- type: "screen",- name: strings.debugLogs(),- description: strings.debugLogsDesc(),- component: "debug-logs"- }- ]- }- ]- },- {- id: "community",- name: strings.community(),- sections: [- {- id: "join-telegram",- name: strings.joinTelegram(),- description: strings.joinTelegramDesc(),- icon: "sc-telegram",- iconFamily: "evilicons",- iconSize: 35,- modifer: () => {- Linking.openURL("https://t.me/notesnook").catch(() => {- /* empty */- });- }- },- {- id: "join-mastodon",- name: strings.joinMastodon(),- description: strings.joinMastodonDesc(),- icon: "mastodon",- modifer: () => {- Linking.openURL("https://fosstodon.org/@notesnook").catch(- console.log- );- }- },- {- id: "join-twitter",- name: strings.followOnX(),- description: strings.followOnXDesc(),- icon: "twitter",- modifer: () => {- Linking.openURL("https://twitter.com/notesnook").catch(() => {- /* empty */- });+ {+ id: "debugging",+ name: strings.debugging(),+ description: strings.debuggingDesc(),+ type: "screen",+ icon: "bug",+ sections: [+ {+ id: "debug-logs",+ type: "screen",+ name: strings.debugLogs(),+ description: strings.debugLogsDesc(),+ component: "debug-logs"+ }+ ]}- },- {- id: "join-discord",- name: strings.joinDiscord(),- icon: "discord",- modifer: async () => {- Linking.openURL("https://discord.gg/zQBK97EE22").catch(() => {- /* empty */- });- },- description: strings.joinDiscordDesc()- }- ]- },- {- id: "legal",- name: strings.legal(),- sections: [- {- id: "tos",- name: strings.tos(),- icon: "briefcase-outline",- modifer: async () => {- try {- await Linking.openURL("https://notesnook.com/tos");- } catch (e) {- console.error(e);+ ]+ },+ {+ id: "community",+ name: strings.community(),+ sections: [+ {+ id: "join-telegram",+ name: strings.joinTelegram(),+ description: strings.joinTelegramDesc(),+ icon: "sc-telegram",+ iconFamily: "evilicons",+ iconSize: 35,+ modifer: () => {+ Linking.openURL("https://t.me/notesnook").catch(() => {+ /* empty */+ });}},- description: strings.tosDesc()- },- {- id: "privacy-policy",- name: strings.privacyPolicy(),- icon: "shield-outline",- modifer: async () => {- try {- await Linking.openURL("https://notesnook.com/privacy");- } catch (e) {- console.error(e);+ {+ id: "join-mastodon",+ name: strings.joinMastodon(),+ description: strings.joinMastodonDesc(),+ icon: "mastodon",+ modifer: () => {+ Linking.openURL("https://fosstodon.org/@notesnook").catch(+ console.log+ );}},- description: strings.privacyPolicyDesc()- },- {- id: "licenses",- name: strings.licenses(),- type: "screen",- component: "licenses",- description: strings.ossLibs(),- icon: "open-source-initiative"- }- ]- },- {- id: "about",- name: strings.about(),- sections: [- {- id: "download",- name: strings.downloadOnDesktop(),- icon: "monitor",- modifer: async () => {- try {- await Linking.openURL("https://notesnook.com/downloads");- } catch (e) {- console.error(e);+ {+ id: "join-twitter",+ name: strings.followOnX(),+ description: strings.followOnXDesc(),+ icon: "twitter",+ modifer: () => {+ Linking.openURL("https://twitter.com/notesnook").catch(() => {+ /* empty */+ });}},- description: strings.downloadOnDesktopDesc()- },- {- id: "roadmap",- name: strings.roadmap(),- icon: "chart-timeline",- modifer: async () => {- try {- await Linking.openURL("https://notesnook.com/roadmap/");- } catch (e) {- console.error(e);- }+ {+ id: "join-discord",+ name: strings.joinDiscord(),+ icon: "discord",+ modifer: async () => {+ Linking.openURL("https://discord.gg/zQBK97EE22").catch(() => {+ /* empty */+ });+ },+ description: strings.joinDiscordDesc()+ }+ ]+ },+ {+ id: "legal",+ name: strings.legal(),+ sections: [+ {+ id: "tos",+ name: strings.tos(),+ icon: "briefcase-outline",+ modifer: async () => {+ try {+ await Linking.openURL("https://notesnook.com/tos");+ } catch (e) {+ console.error(e);+ }+ },+ description: strings.tosDesc()},- description: strings.roadmapDesc()- },- {- id: "check-for-updates",- name: strings.checkForUpdates(),- icon: "cellphone-arrow-down",- description: strings.checkForUpdatesDesc(),- modifer: async () => {- presentSheet({- //@ts-ignore // Migrate to ts- component: (ref) => <Update fwdRef={ref} />- });+ {+ id: "privacy-policy",+ name: strings.privacyPolicy(),+ icon: "shield-outline",+ modifer: async () => {+ try {+ await Linking.openURL("https://notesnook.com/privacy");+ } catch (e) {+ console.error(e);+ }+ },+ description: strings.privacyPolicyDesc()+ },+ {+ id: "licenses",+ name: strings.licenses(),+ type: "screen",+ component: "licenses",+ description: strings.ossLibs(),+ icon: "open-source-initiative"}- },- {- id: "app-version",- name: strings.appVersion(),- icon: "alpha-v",- modifer: async () => {- try {- await Linking.openURL("https://notesnook.com");- } catch (e) {- console.error(e);+ ]+ },+ {+ id: "about",+ name: strings.about(),+ sections: [+ {+ id: "download",+ name: strings.downloadOnDesktop(),+ icon: "monitor",+ modifer: async () => {+ try {+ await Linking.openURL("https://notesnook.com/downloads");+ } catch (e) {+ console.error(e);+ }+ },+ description: strings.downloadOnDesktopDesc()+ },+ {+ id: "roadmap",+ name: strings.roadmap(),+ icon: "chart-timeline",+ modifer: async () => {+ try {+ await Linking.openURL("https://notesnook.com/roadmap/");+ } catch (e) {+ console.error(e);+ }+ },+ description: strings.roadmapDesc()+ },+ {+ id: "check-for-updates",+ name: strings.checkForUpdates(),+ icon: "cellphone-arrow-down",+ description: strings.checkForUpdatesDesc(),+ modifer: async () => {+ presentSheet({+ //@ts-ignore // Migrate to ts+ component: (ref) => <Update fwdRef={ref} />+ });}},- description: getVersion()- }- ]- }-];+ {+ id: "app-version",+ name: strings.appVersion(),+ icon: "alpha-v",+ modifer: async () => {+ try {+ await Linking.openURL("https://notesnook.com");+ } catch (e) {+ console.error(e);+ }+ },+ description: getVersion()+ }+ ]+ }+ ];}export function useSettingsGroups(): SettingSection[] {- useSettingStore((state) => state.settings.appLanguage);- return getSettingsGroups();+ const appLanguage = useSettingStore((state) => state.settings.appLanguage);++ return React.useMemo(() => getSettingsGroups(), [appLanguage]);}export const settingsGroups: SettingSection[] = new Proxy([] as SettingSection[], {diff --git a/apps/mobile/app/services/message.tsx b/apps/mobile/app/services/message.tsxindex a57d2c8a6..e553bdc70 100644--- a/apps/mobile/app/services/message.tsx+++ b/apps/mobile/app/services/message.tsx@@ -35,7 +35,10 @@ import { Update } from "../components/sheets/update";import { GithubVersionInfo } from "../utils/github-version";import { CheckVersionResponse } from "react-native-check-version";-const APP_MESSAGE_BUILDERS: Record<MessageId, () => Message> = {+const APP_MESSAGE_BUILDERS: Record<+ MessageId,+ (data?: object) => Message+> = {"rate-app": () => ({visible: true,message: strings.rateAppMessage(),@@ -99,48 +102,62 @@ const APP_MESSAGE_BUILDERS: Record<MessageId, () => Message> = {type: "error",id: "confirm-email"}),- "app-update": () => ({}) as Message,+ "app-update": (data) => {+ const version = (data as { version?: GithubVersionInfo | CheckVersionResponse } | undefined)?.version;+ return {+ visible: true,+ message: strings.newUpdateMessage(),+ actionText: strings.newUpdateActionText(),+ onPress: () => {+ if (version) {+ presentSheet({+ component: (ref) => <Update version={version} fwdRef={ref} />+ });+ }+ },+ data: data || {},+ icon: "update",+ type: "normal",+ id: "app-update"+ };+ },none: () => ({}) as Message};-function showMessageById(id: MessageId) {- if (APP_MESSAGE_BUILDERS[id]) {- useMessageStore.getState().setMessage(APP_MESSAGE_BUILDERS[id]());- }+export function setMessageById(id: MessageId, data?: object) {+ useMessageStore.getState().setMessage({+ ...useMessageStore.getState().message,+ visible: id !== "none",+ id,+ data: data || {}+ });}-export function getLocalizedMessageStrings(id: MessageId): { message: string; actionText: string } | null {- if (id === "app-update") {- return {- message: strings.newUpdateMessage(),- actionText: strings.newUpdateActionText()- };- }+export function getMessageById(+ id: MessageId,+ data?: object+): Message | null {const builder = APP_MESSAGE_BUILDERS[id];if (builder && id !== "none") {- const msg = builder();- return {- message: msg.message as string,- actionText: msg.actionText as string- };+ return builder(data);}return null;}export function setRateAppMessage() {- showMessageById("rate-app");+ setMessageById("rate-app");}export function setRecoveryKeyMessage() {- showMessageById("recovery-key");+ setMessageById("recovery-key");}export function setLoginMessage() {- showMessageById("log-in");+ setMessageById("log-in");}export function setEmailVerifyMessage() {- showMessageById("confirm-email");+ setMessageById("confirm-email");}export function clearMessage() {@@ -150,26 +167,9 @@ export function clearMessage() {});}-const updateAvailableMessage = (- version: GithubVersionInfo | CheckVersionResponse-) =>- ({- visible: true,- message: strings.newUpdateMessage(),- actionText: strings.newUpdateActionText(),- onPress: () => {- presentSheet({- component: (ref) => <Update version={version} fwdRef={ref} />- });- },- data: {},- icon: "update",- type: "normal",- id: "app-update"- }) as Message;-export function setUpdateAvailableMessage(version: GithubVersionInfo | CheckVersionResponse) {- useMessageStore.getState().setMessage(updateAvailableMessage(version));+ setMessageById("app-update", { version });}+diff --git a/apps/mobile/ios/Podfile.lock b/apps/mobile/ios/Podfile.lockindex 722aabed9..13176cb8e 100644--- a/apps/mobile/ios/Podfile.lock+++ b/apps/mobile/ios/Podfile.lock@@ -2204,6 +2204,8 @@ PODS:- ReactCommon/turbomodule/core- SocketRocket- Yoga+ - react-native-restart (0.0.28):+ - React-Core- react-native-safe-area-context (5.6.1):- boost- DoubleConversion@@ -3597,6 +3599,7 @@ DEPENDENCIES:- react-native-orientation-locker (from `../node_modules/react-native-orientation-locker`)- react-native-pdf (from `../node_modules/react-native-pdf`)- react-native-quick-sqlite (from `../node_modules/react-native-quick-sqlite`)+ - react-native-restart (from `../node_modules/react-native-restart`)- react-native-safe-area-context (from `../node_modules/react-native-safe-area-context`)- react-native-screenguard (from `../node_modules/react-native-screenguard`)- "react-native-share-extension (from `../node_modules/@ammarahmed/react-native-share-extension`)"@@ -3812,6 +3815,8 @@ EXTERNAL SOURCES::path: "../node_modules/react-native-pdf"react-native-quick-sqlite::path: "../node_modules/react-native-quick-sqlite"+ react-native-restart:+ :path: "../node_modules/react-native-restart"react-native-safe-area-context::path: "../node_modules/react-native-safe-area-context"react-native-screenguard:@@ -4022,6 +4027,7 @@ SPEC CHECKSUMS:react-native-orientation-locker: cc6f357b289a2e0dd2210fea0c52cb8e0727fdaareact-native-pdf: edc236298f13f1609e42d41e45b8b6ea88ed10f9react-native-quick-sqlite: 1ed8d3db1e22a8604d006be69f06053382e93bb0+ react-native-restart: f2a57ccec2e6481deb1f19958ac60c0813313784react-native-safe-area-context: c6e2edd1c1da07bdce287fa9d9e60c5f7b514616react-native-screenguard: 975d4612dce0c348b19b08a48aa23e9b68584d98react-native-share-extension: fdc6aaab51591a2d445df239c446aaa3a99658ecdiff --git a/apps/mobile/package-lock.json b/apps/mobile/package-lock.jsonindex 9eb73d3b4..c99b6935a 100644--- a/apps/mobile/package-lock.json+++ b/apps/mobile/package-lock.json@@ -1,12 +1,12 @@{"name": "@notesnook/mobile",- "version": "3.4.10",+ "version": "3.4.11","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "@notesnook/mobile",- "version": "3.4.10",+ "version": "3.4.11","hasInstallScript": true,"license": "GPL-3.0-or-later","dependencies": {diff --git a/apps/web/src/common/locale.ts b/apps/web/src/common/locale.tsindex aca0684ea..2a75be692 100644--- a/apps/web/src/common/locale.ts+++ b/apps/web/src/common/locale.ts@@ -18,59 +18,13 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.*/import Config from "../utils/config";-import {- setI18nGlobal,- AVAILABLE_LANGUAGES,- getSupportedLocale-} from "@notesnook/intl";-import { i18n, type Messages } from "@lingui/core";--const localeMap: Record<- string,- () => Promise<{ default: { messages: unknown } }>-> = {- en: () => import("@notesnook/intl/locales/$en.json"),- de: () => import("@notesnook/intl/locales/$de.json"),- es: () => import("@notesnook/intl/locales/$es.json"),- fr: () => import("@notesnook/intl/locales/$fr.json"),- it: () => import("@notesnook/intl/locales/$it.json"),- nl: () => import("@notesnook/intl/locales/$nl.json"),- pl: () => import("@notesnook/intl/locales/$pl.json"),- "pt-BR": () => import("@notesnook/intl/locales/$pt-BR.json"),- ru: () => import("@notesnook/intl/locales/$ru.json"),- tr: () => import("@notesnook/intl/locales/$tr.json"),- uk: () => import("@notesnook/intl/locales/$uk.json")-};--function resolveTargetLang(): string {- const savedLanguage = Config.get<string>("appLanguage", "");- if (- savedLanguage &&- AVAILABLE_LANGUAGES.some((l) => l.code === savedLanguage)- ) {- return savedLanguage;- }-- let systemLocale = "en";- try {- systemLocale = Intl.DateTimeFormat().resolvedOptions().locale;- } catch (e) {}- const detected = getSupportedLocale(systemLocale);- Config.set("appLanguage", detected);- return detected;-}--async function getLocaleMessages(lang: string): Promise<Messages> {- const loader = localeMap[lang] || localeMap.en;- const mod = await loader();- return mod.default.messages as unknown as Messages;-}+import { initLocale as initIntlLocale } from "@notesnook/intl";export async function initLocale() {- const targetLang = resolveTargetLang();- const messages = await getLocaleMessages(targetLang);- i18n.load({ [targetLang]: messages });- i18n.activate(targetLang);- setI18nGlobal(i18n);- return targetLang;+ return initIntlLocale({+ getSavedLocale: () => Config.get<string>("appLanguage", ""),+ onSaveLocale: (locale) => {+ Config.set("appLanguage", locale);+ }+ });}diff --git a/packages/intl/.gitignore b/packages/intl/.gitignoreindex d20050857..e4395bb51 100644--- a/packages/intl/.gitignore+++ b/packages/intl/.gitignore@@ -1,3 +1,4 @@.swclocales-generated/*.ts\ No newline at end of file+src/generated/+generated/\ No newline at end of filediff --git a/packages/intl/locale/pseudo-LOCALE.po b/packages/intl/locale/pseudo-LOCALE.poindex 8f3210622..faced3fea 100644--- a/packages/intl/locale/pseudo-LOCALE.po+++ b/packages/intl/locale/pseudo-LOCALE.po@@ -7513,8 +7513,6 @@ msgstr "User verification failed"msgid "Using {instance} (v{version})"msgstr "Using {instance} (v{version})"-#: src/strings.ts:2809-msgid "Using Notesnook without an account will NOT sync your notes across devices and could result in data loss if you lose access to your device or uninstall the app. Make sure to backup your notes regularly."#: src/strings.ts:2812msgid "Using Notesnook without an account will **NOT** sync your notes across devices and could result in data loss if you lose access to your device or uninstall the app. Make sure to backup your notes regularly."msgstr ""diff --git a/packages/intl/package.json b/packages/intl/package.jsonindex 8ecc78b55..a3647d9b4 100644--- a/packages/intl/package.json+++ b/packages/intl/package.json@@ -16,7 +16,8 @@"default": "./dist/index.mjs"}},- "./locales/*.json": "./dist/locales/*.json"+ "./locales/*.json": "./dist/locales/*.json",+ "./dist/locales/*.json": "./dist/locales/*.json"},"repository": {"type": "git",@@ -25,7 +26,7 @@"scripts": {"extract": "lingui extract --clean --overwrite","compile": "lingui compile --typescript",- "build-locale": "node scripts/generate-strings.mjs && npm run extract && npm run compile",+ "build-locale": "node scripts/generate-strings.mjs && node scripts/generate-locale-loaders.mjs && npm run extract && npm run compile","build": "npm run build-locale && npx vite build && node scripts/postbuild.mjs","watch": "nodemon --watch scripts/ --watch src --ext ts,mjs --exec \"npm run build\"","postinstall": "patch-package"diff --git a/packages/intl/scripts/generate-locale-loaders.mjs b/packages/intl/scripts/generate-locale-loaders.mjsnew file mode 100644index 000000000..766e71d0a--- /dev/null+++ b/packages/intl/scripts/generate-locale-loaders.mjs@@ -0,0 +1,97 @@+/*+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 { writeFileSync, mkdirSync, existsSync } from "fs";+import { createRequire } from "module";+import path from "path";+import { fileURLToPath } from "url";++const __filename = fileURLToPath(import.meta.url);+const __dirname = path.dirname(__filename);+const require = createRequire(import.meta.url);++const linguiConfig = require("../lingui.config.js");+const locales = linguiConfig.locales.filter((l) => l !== "pseudo-LOCALE");++const LICENSE_HEADER = `/*+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/>.+*/++// THIS FILE IS AUTO-GENERATED BY scripts/generate-locale-loaders.mjs. DO NOT EDIT.+`;++function generateWebLocaleMap() {+ const entries = locales.map((locale) => {+ const key = locale.includes("-") ? `"${locale}"` : locale;+ return ` ${key}: () => import("../../locales/$${locale}.json")`;+ });++ return `${LICENSE_HEADER}+export const localeMap: Record<+ string,+ () => Promise<{ default: { messages: unknown } } | { messages: unknown }>+> = {+${entries.join(",\n")}+};+`;+}++function generateMobileLocaleLoaders() {+ const entries = locales.map((locale) => {+ const key = locale.includes("-") ? `"${locale}"` : locale;+ return ` ${key}: () => require("@notesnook/intl/dist/locales/$${locale}.json").messages`;+ });++ return `${LICENSE_HEADER}+export const LOCALE_LOADERS = {+${entries.join(",\n")}+};+`;+}++// 1. Write Web/Desktop locale map+const generatedDir = path.join(__dirname, "../src/generated");+if (!existsSync(generatedDir)) {+ mkdirSync(generatedDir, { recursive: true });+}+writeFileSync(+ path.join(generatedDir, "locale-map.ts"),+ generateWebLocaleMap()+);++// 2. Write Mobile locale loaders+writeFileSync(+ path.join(generatedDir, "loaders.mobile.ts"),+ generateMobileLocaleLoaders()+);diff --git a/packages/intl/src/index.ts b/packages/intl/src/index.tsindex 3a1b43ca7..730dd783c 100644--- a/packages/intl/src/index.ts+++ b/packages/intl/src/index.ts@@ -22,4 +22,13 @@ export { strings } from "./strings";export { setI18nGlobal } from "./setup";export { AVAILABLE_LANGUAGES, getSupportedLocale } from "./languages";export type { Language } from "./languages";+export {+ initLocale,+ resolveTargetLocale,+ getLocaleMessages,+ localeMap,+ LOCALE_LOADERS+} from "./locale";+export type { InitLocaleOptions } from "./locale";+diff --git a/packages/intl/src/locale.ts b/packages/intl/src/locale.tsnew file mode 100644index 000000000..a759468b5--- /dev/null+++ b/packages/intl/src/locale.ts@@ -0,0 +1,80 @@+/*+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 { i18n as defaultI18n, type Messages } from "@lingui/core";+import { setI18nGlobal } from "./setup";+import { AVAILABLE_LANGUAGES, getSupportedLocale } from "./languages";++import { localeMap } from "./generated/locale-map";+import { LOCALE_LOADERS } from "./generated/loaders.mobile";+export { localeMap, LOCALE_LOADERS };++export function resolveTargetLocale(+ savedLanguage?: string | null,+ systemLocale?: string+): string {+ if (+ savedLanguage &&+ AVAILABLE_LANGUAGES.some((l) => l.code === savedLanguage)+ ) {+ return savedLanguage;+ }++ let sysLocale = systemLocale;+ if (!sysLocale) {+ try {+ sysLocale = Intl.DateTimeFormat().resolvedOptions().locale;+ } catch {+ sysLocale = "en";+ }+ }++ return getSupportedLocale(sysLocale);+}++export async function getLocaleMessages(lang: string): Promise<Messages> {+ const loader = localeMap[lang] || localeMap.en;+ const mod = await loader();+ const messages = "default" in mod ? mod.default.messages : (mod as { messages: unknown }).messages;+ return messages as unknown as Messages;+}++export type InitLocaleOptions = {+ getSavedLocale?: () => string | null | undefined;+ onSaveLocale?: (locale: string) => void;+ systemLocale?: string;+ getMessages?: (lang: string) => Promise<Messages> | Messages;+};++export async function initLocale(options?: InitLocaleOptions): Promise<string> {+ const saved = options?.getSavedLocale?.();+ const targetLang = resolveTargetLocale(saved, options?.systemLocale);+ if (!saved && options?.onSaveLocale) {+ options.onSaveLocale(targetLang);+ }++ const messages = options?.getMessages+ ? await options.getMessages(targetLang)+ : await getLocaleMessages(targetLang);++ defaultI18n.load({ [targetLang]: messages });+ defaultI18n.activate(targetLang);+ setI18nGlobal(defaultI18n);+ return targetLang;+}diff --git a/packages/intl/src/setup.ts b/packages/intl/src/setup.tsindex afe73c0a0..590e63ea0 100644--- a/packages/intl/src/setup.ts+++ b/packages/intl/src/setup.ts@@ -20,20 +20,18 @@ import { I18n, i18n as i18nn } from "@lingui/core";let i18nGlobal: I18n | undefined = undefined;-export const setI18nGlobal = (i18n: any) => {- i18nGlobal = i18n;+export const setI18nGlobal = (newI18n: any) => {+ if (newI18n === i18n) return;+ i18nGlobal = newI18n;};export function getI18nGlobal() {return i18nGlobal;}-export const i18n = new Proxy(- {},- {- get: (target, property) => {- return (- i18nGlobal?.[property as keyof I18n] || i18nn[property as keyof I18n]- );- }+export const i18n: I18n = new Proxy({} as I18n, {+ get: (target, property) => {+ return (+ i18nGlobal?.[property as keyof I18n] || i18nn[property as keyof I18n]+ );}-);+});