refactor: migrate account-menu to react - implement functionality

- implement different handlers, such as set/change/remove passcode, etc.
- setup correct initial values
- rename React component
This commit is contained in:
VardanHakobyan
2021-05-31 22:15:49 +04:00
parent 1194c73c49
commit 09f62b68ae
10 changed files with 149 additions and 82 deletions

View File

@@ -1,7 +1,5 @@
'use strict';
// import { AccountMenu2 } from '@/components/AccountMenu';
declare const __VERSION__: string;
declare const __WEB__: boolean;
@@ -61,7 +59,7 @@ import { SessionsModalDirective } from './components/SessionsModal';
import { NoAccountWarningDirective } from './components/NoAccountWarning';
import { NoProtectionsdNoteWarningDirective } from './components/NoProtectionsNoteWarning';
import { SearchOptionsDirective } from './components/SearchOptions';
import { AccountMenu2 } from './components/AccountMenu2';
import { AccountMenuReact } from './components/AccountMenuReact';
import { ConfirmSignoutDirective } from './components/ConfirmSignoutModal';
import { MultipleSelectedNotesDirective } from './components/MultipleSelectedNotes';
import { NotesContextMenuDirective } from './components/NotesContextMenu';
@@ -153,7 +151,7 @@ const startApplication: StartApplication = async function startApplication(
.directive('historyMenu', () => new HistoryMenu())
.directive('syncResolutionMenu', () => new SyncResolutionMenu())
.directive('sessionsModal', SessionsModalDirective)
.directive('accountMenu2', AccountMenu2)
.directive('accountMenuReact', AccountMenuReact)
.directive('noAccountWarning', NoAccountWarningDirective)
.directive('protectedNotePanel', NoProtectionsdNoteWarningDirective)
.directive('searchOptions', SearchOptionsDirective)

View File

@@ -4,22 +4,32 @@ import { AppState } from '@/ui_models/app_state';
import { WebApplication } from '@/ui_models/application';
import { useCallback, useEffect, useRef, useState } from 'preact/hooks';
import { isDesktopApplication, isSameDay } from '@/utils';
import { isDesktopApplication, isSameDay, preventRefreshing } from '@/utils';
import { storage, StorageKey } from '@Services/localStorage';
import { disableErrorReporting, enableErrorReporting, errorReportingId } from '@Services/errorReporting';
import { STRING_E2E_ENABLED, STRING_ENC_NOT_ENABLED, STRING_LOCAL_ENC_ENABLED, StringUtils } from '@/strings';
import {
STRING_CONFIRM_APP_QUIT_DURING_PASSCODE_CHANGE,
STRING_CONFIRM_APP_QUIT_DURING_PASSCODE_REMOVAL,
STRING_E2E_ENABLED,
STRING_ENC_NOT_ENABLED,
STRING_LOCAL_ENC_ENABLED,
STRING_NON_MATCHING_PASSCODES,
StringUtils
} from '@/strings';
import { ContentType } from '@node_modules/@standardnotes/snjs';
import { PasswordWizardType } from '@/types';
import { JSXInternal } from '@node_modules/preact/src/jsx';
import TargetedEvent = JSXInternal.TargetedEvent;
import { alertDialog } from '@Services/alertService';
import TargetedMouseEvent = JSXInternal.TargetedMouseEvent;
// eslint-disable-next-line @typescript-eslint/no-empty-interface
// interface Props {} // TODO: Vardan: implement props and remove `eslint-disable`
type Props = {
appState: AppState;
application: WebApplication;
closeAccountMenu: () => void;
};
// const HistoryMenu = observer((props: Props) => {
// const AccountMenu = observer((props) => {
const AccountMenu = observer(({ appState, application }: Props) => {
const AccountMenu = observer(({ application, appState, closeAccountMenu }: Props) => {
const getProtectionsDisabledUntil = (): string | null => {
const protectionExpiry = application.getProtectionSessionExpiryDate();
const now = new Date();
@@ -57,26 +67,24 @@ const AccountMenu = observer(({ appState, application }: Props) => {
const [status, setStatus] = useState('');
const [syncError, setSyncError] = useState<string | undefined>(undefined);
const [passcode, setPasscode] = useState<string | undefined>(undefined);
const [passcodeConfirmation, setPasscodeConfirmation] = useState<string | undefined>(undefined);
const [encryptionStatusString, setEncryptionStatusString] = useState<string | undefined>(undefined);
const [isEncryptionEnabled, setIsEncryptionEnabled] = useState(false);
const [server, setServer] = useState<string | undefined>(undefined);
const [showPasscodeForm, setShowPasscodeForm] = useState(false);
const [selectedAutoLockInterval, setSelectedAutoLockInterval] = useState<unknown>(null);
const [isLoading, setIsLoading] = useState<unknown>(false);
const [isErrorReportingEnabled, setIsErrorReportingEnabled] = useState(false);
const [appVersion, setAppVersion] = useState(''); // TODO: Vardan: figure out how to get `appVersion` similar to original code
const user = application.getUser();
const hasUser = application.hasAccount();
const hasPasscode = application.hasPasscode();
const isEncryptionEnabled = hasUser || hasPasscode;
const encryptionStatusString = hasUser
? STRING_E2E_ENABLED : hasPasscode
? STRING_LOCAL_ENC_ENABLED : STRING_ENC_NOT_ENABLED;
// TODO: Vardan: in original code initial value of `backupEncrypted` is `hasUser || hasPasscode` -
// once I have those values here, set them as initial value
const [hasPasscode, setHasPasscode] = useState(application.hasPasscode());
const [isBackupEncrypted, setIsBackupEncrypted] = useState(isEncryptionEnabled);
const [isSyncInProgress, setIsSyncInProgress] = useState(false);
const [protectionsDisabledUntil, setProtectionsDisabledUntil] = useState(getProtectionsDisabledUntil());
const user = application.getUser();
const reloadAutoLockInterval = useCallback(async () => {
const interval = await application.getAutolockService().getAutoLockInterval();
@@ -85,7 +93,6 @@ const AccountMenu = observer(({ appState, application }: Props) => {
const errorReportingIdValue = errorReportingId();
const protectionsDisabledUntil = getProtectionsDisabledUntil();
const canAddPasscode = !application.isEphemeralSession();
const keyStorageInfo = StringUtils.keyStorageInfo(application);
const passcodeAutoLockOptions = application.getAutolockService().getAutoLockIntervalOptions();
@@ -133,11 +140,13 @@ const AccountMenu = observer(({ appState, application }: Props) => {
};
const openPasswordWizard = () => {
console.log('openPasswordWizard');
closeAccountMenu();
application.presentPasswordWizard(PasswordWizardType.ChangePassword);
};
const openSessionsModal = () => {
console.log('openSessionsModal');
closeAccountMenu();
appState.openSessionsModal();
};
const getEncryptionStatusForNotes = () => {
@@ -146,27 +155,85 @@ const AccountMenu = observer(({ appState, application }: Props) => {
};
const enableProtections = () => {
console.log('enableProtections');
application.clearProtectionSession();
// Get the latest the protection status
setProtectionsDisabledUntil(getProtectionsDisabledUntil());
};
const refreshEncryptionStatus = () => {
const hasUser = application.hasAccount();
const hasPasscode = application.hasPasscode();
setHasPasscode(hasPasscode);
const encryptionEnabled = hasUser || hasPasscode;
const newEncryptionStatusString = hasUser
? STRING_E2E_ENABLED
: hasPasscode
? STRING_LOCAL_ENC_ENABLED
: STRING_ENC_NOT_ENABLED;
setEncryptionStatusString(newEncryptionStatusString);
setIsEncryptionEnabled(encryptionEnabled);
setIsBackupEncrypted(encryptionEnabled);
};
const handleAddPassCode = () => {
console.log('handleAddPassCode');
setShowPasscodeForm(true);
};
const submitPasscodeForm = () => {
console.log('submitPasscodeForm');
const submitPasscodeForm = async (event: TargetedEvent<HTMLFormElement> | TargetedMouseEvent<HTMLButtonElement>) => {
event.preventDefault();
if (passcode !== passcodeConfirmation) {
await alertDialog({
text: STRING_NON_MATCHING_PASSCODES,
});
passcodeInput.current.focus();
return;
}
await preventRefreshing(
STRING_CONFIRM_APP_QUIT_DURING_PASSCODE_CHANGE,
async () => {
const successful = application.hasPasscode()
? await application.changePasscode(passcode as string)
: await application.addPasscode(passcode as string);
if (!successful) {
passcodeInput.current.focus();
}
}
);
setPasscode(undefined);
setPasscodeConfirmation(undefined);
setShowPasscodeForm(false);
setProtectionsDisabledUntil(getProtectionsDisabledUntil());
refreshEncryptionStatus();
};
const handlePasscodeChange = () => {
console.log('handlePasscodeChange');
// TODO: Vardan: check whether this (and `handleConfirmPasscodeChange`) method is required in the end
const handlePasscodeChange = (event: TargetedEvent<HTMLInputElement>) => {
const { value } = event.target as HTMLInputElement;
setPasscode(value);
};
const handleConfirmPasscodeChange = () => {
console.log('handleConfirmPasscodeChange');
const handleConfirmPasscodeChange = (event: TargetedEvent<HTMLInputElement>) => {
const { value } = event.target as HTMLInputElement;
setPasscodeConfirmation(value);
};
const selectAutoLockInterval = (interval: number) => {
console.log('selectAutoLockInterval', interval);
const selectAutoLockInterval = async (interval: number) => {
if (!(await application.authorizeAutolockIntervalChange())) {
return;
}
await application.getAutolockService().setAutoLockInterval(interval);
reloadAutoLockInterval();
};
const disableBetaWarning = () => {
@@ -187,13 +254,26 @@ const AccountMenu = observer(({ appState, application }: Props) => {
// TODO: Vardan: the name `changePasscodePressed` comes from original code; it is very similar to my `handlePasscodeChange`.
// Check if `handlePasscodeChange` is not required, remove it and rename `changePasscodePressed` to `handlePasscodeChange`
const changePasscodePressed = () => {
console.log('changePasscodePressed');
handleAddPassCode();
};
// TODO: Vardan: the name `removePasscodePressed` comes from original code;
// Check if I rename`changePasscodePressed` to `handlePasscodeChange`, also rename `removePasscodePressed` to `handleRemovePasscode`
const removePasscodePressed = () => {
console.log('removePasscodePressed');
const removePasscodePressed = async () => {
await preventRefreshing(
STRING_CONFIRM_APP_QUIT_DURING_PASSCODE_REMOVAL,
async () => {
if (await application.removePasscode()) {
await application
.getAutolockService()
.deleteAutolockPreference();
await reloadAutoLockInterval();
refreshEncryptionStatus();
}
}
);
setProtectionsDisabledUntil(getProtectionsDisabledUntil());
};
const downloadDataArchive = () => {
@@ -219,10 +299,6 @@ const AccountMenu = observer(({ appState, application }: Props) => {
console.log('openErrorReportingDialog');
};
const handleClose = () => {
console.log('close this');
};
// TODO: check whether this works fine (e.g. remove all tags and notes and then add one and check whether UI behaves appropriately)
const notesAndTagsCount = application.getItems([ContentType.Note, ContentType.Tag]).length;
const hasProtections = application.hasProtectionSources();
@@ -262,16 +338,9 @@ const AccountMenu = observer(({ appState, application }: Props) => {
setServer(host);
}, [application]);
/*
const { searchOptions } = appState;
const {
includeProtectedContents,
includeArchived,
includeTrashed,
} = searchOptions;
*/
useEffect(() => {
refreshEncryptionStatus();
}, [refreshEncryptionStatus]);
return (
<div style={{
@@ -284,10 +353,10 @@ const AccountMenu = observer(({ appState, application }: Props) => {
position: 'absolute'
}}>
<div className='sn-component'>
<div id='account-panel-vardan' className='sk-panel'>
<div id='account-panel-react' className='sk-panel'>
<div className='sk-panel-header'>
<div className='sk-panel-header-title'>Account</div>
<a className='sk-a info close-button' onClick={handleClose}>Close</a>
<a className='sk-a info close-button' onClick={closeAccountMenu}>Close</a>
</div>
<div className='sk-panel-content'>
{!user && !showLogin && !showRegister && (
@@ -514,7 +583,7 @@ const AccountMenu = observer(({ appState, application }: Props) => {
</p>
{protectionsDisabledUntil && (
<div className='sk-panel-row'>
<button className='sn-button small.info' onClick={enableProtections}>
<button className='sn-button small info' onClick={enableProtections}>
Enable protections
</button>
</div>
@@ -554,17 +623,19 @@ const AccountMenu = observer(({ appState, application }: Props) => {
{showPasscodeForm && (
<form className='sk-panel-form' onSubmit={submitPasscodeForm}>
<div className='sk-panel-row' />
{/* TODO: Vardan: there are `should-focus` and `sn-autofocus`, implement them */}
<input
className='sk-input contrast'
type='password'
ref={passcodeInput}
value={passcode}
onChange={handlePasscodeChange}
placeholder='Passcode'
autoFocus
/>
<input
className='sk-input contrast'
type='password'
value={passcodeConfirmation}
onChange={handleConfirmPasscodeChange}
placeholder='Confirm Passcode'
/>
@@ -588,7 +659,7 @@ const AccountMenu = observer(({ appState, application }: Props) => {
{passcodeAutoLockOptions.map(option => {
return (
<a
className={option.value === selectedAutoLockInterval ? 'boxed' : ''}
className={`sk-a info ${option.value === selectedAutoLockInterval ? 'boxed' : ''}`}
onClick={() => selectAutoLockInterval(option.value)}>
{option.label}
</a>
@@ -720,6 +791,7 @@ const AccountMenu = observer(({ appState, application }: Props) => {
);
});
export const AccountMenu2 = toDirective<Props>(
AccountMenu
export const AccountMenuReact = toDirective<Props>(
AccountMenu,
{ closeAccountMenu: '&'}
);

View File

@@ -19,7 +19,7 @@ const ConfirmSignoutContainer = observer((props: Props) => {
if (!props.appState.accountMenu.signingOut) {
return null;
}
if (!props.appState.accountMenu2.signingOut) {
if (!props.appState.accountMenuReact.signingOut) {
return null;
}
return <ConfirmSignoutModal {...props} />;
@@ -33,15 +33,14 @@ const ConfirmSignoutModal = observer(({ application, appState }: Props) => {
const cancelRef = useRef<HTMLButtonElement>();
function close() {
appState.accountMenu.setSigningOut(false);
appState.accountMenu2.setSigningOut(false);
appState.accountMenuReact.setSigningOut(false);
}
const [localBackupsCount, setLocalBackupsCount] = useState(0);
useEffect(() => {
application.bridge.localBackupsCount().then(setLocalBackupsCount);
// }, [appState.accountMenu.signingOut, application.bridge]);
}, [appState.accountMenu.signingOut, appState.accountMenu2.signingOut, application.bridge]);
}, [appState.accountMenu.signingOut, appState.accountMenuReact.signingOut, application.bridge]);
return (
<AlertDialog onDismiss={close} leastDestructiveRef={cancelRef}>

View File

@@ -21,7 +21,7 @@ const NoAccountWarning = observer(({ appState }: Props) => {
onClick={(event) => {
event.stopPropagation();
appState.accountMenu.setShow(true);
appState.accountMenu2.setShow(true);
appState.accountMenuReact.setShow(true);
}}
>
Open Account menu

View File

@@ -16,7 +16,7 @@ function NoProtectionsNoteWarning({ appState, onViewNote }: Props) {
className="sn-button small info"
onClick={() => {
appState.accountMenu.setShow(true);
appState.accountMenu2.setShow(true);
appState.accountMenuReact.setShow(true);
}}
>
Open account menu

View File

@@ -1,7 +1,7 @@
import { action, makeObservable, observable } from "mobx";
import { WebApplication } from '@/ui_models/application';
export class AccountMenuState2 {
export class AccountMenuStateReact {
show = false;
signingOut = false;

View File

@@ -21,7 +21,7 @@ import { SyncState } from './sync_state';
import { SearchOptionsState } from './search_options_state';
import { NotesState } from './notes_state';
import { TagsState } from './tags_state';
import { AccountMenuState2 } from '@/ui_models/app_state/account_menu_2_state';
import { AccountMenuStateReact } from '@/ui_models/app_state/account_menu_react_state';
export enum AppStateEvent {
TagChanged,
@@ -62,8 +62,7 @@ export class AppState {
selectedTag?: SNTag;
showBetaWarning: boolean;
readonly accountMenu = new AccountMenuState();
// readonly accountMenu2 = new AccountMenu_2_State();
readonly accountMenu2: AccountMenuState2;
readonly accountMenuReact: AccountMenuStateReact;
readonly actionsMenu = new ActionsMenuState();
readonly noAccountWarning: NoAccountWarningState;
readonly sync = new SyncState();
@@ -99,10 +98,7 @@ export class AppState {
application,
this.appEventObserverRemovers
);
this.accountMenu2 = new AccountMenuState2(
// application,
// this.appEventObserverRemovers
);
this.accountMenuReact = new AccountMenuStateReact();
this.searchOptions = new SearchOptionsState(
application,
this.appEventObserverRemovers

View File

@@ -18,10 +18,12 @@
ng-if='ctrl.showAccountMenu',
application='ctrl.application'
)
account-menu2(
account-menu-react(
ng-click='$event.stopPropagation()',
app-state='ctrl.appState'
application='ctrl.application'
ng-if='ctrl.showAccountMenu',
close-account-menu='ctrl.closeAccountMenu()',
)
.sk-app-bar-item
a.no-decoration.sk-label.title(

View File

@@ -62,7 +62,7 @@ class FooterViewCtrl extends PureViewCtrl<unknown, {
public user?: any
private offline = true
public showAccountMenu = false
public showAccountMenu2 = false
public showAccountMenuReact = false
private didCheckForOffline = false
private queueExtReload = false
private reloadInProgress = false
@@ -116,7 +116,7 @@ class FooterViewCtrl extends PureViewCtrl<unknown, {
this.autorun(() => {
const showBetaWarning = this.appState.showBetaWarning;
this.showAccountMenu = this.appState.accountMenu.show;
this.showAccountMenu2 = this.appState.accountMenu2.show;
this.showAccountMenuReact = this.appState.accountMenuReact.show;
this.setState({
showBetaWarning: showBetaWarning,
showDataUpgrade: !showBetaWarning
@@ -256,7 +256,7 @@ class FooterViewCtrl extends PureViewCtrl<unknown, {
this.didCheckForOffline = true;
if (this.offline && this.application.getNoteCount() === 0) {
this.appState.accountMenu.setShow(true);
this.appState.accountMenu2.setShow(true);
this.appState.accountMenuReact.setShow(true);
}
}
this.syncUpdated();
@@ -439,7 +439,7 @@ class FooterViewCtrl extends PureViewCtrl<unknown, {
accountMenuPressed() {
this.appState.accountMenu.toggleShow();
this.appState.accountMenu2.toggleShow();
this.appState.accountMenuReact.toggleShow();
this.closeAllRooms();
}
@@ -449,7 +449,7 @@ class FooterViewCtrl extends PureViewCtrl<unknown, {
closeAccountMenu() {
this.appState.accountMenu.setShow(false);
this.appState.accountMenu2.setShow(false);
this.appState.accountMenuReact.setShow(false);
}
lockApp() {
@@ -567,7 +567,7 @@ class FooterViewCtrl extends PureViewCtrl<unknown, {
return;
}
this.appState.accountMenu.setShow(false);
this.appState.accountMenu2.setShow(false);
this.appState.accountMenuReact.setShow(false);
}
}

View File

@@ -56,7 +56,7 @@
}
#account-panel,
#account-panel-vardan,
#account-panel-react,
#sync-resolution-menu {
width: 400px;
}