refactor: migrate remaining angular components to react (#833)

* refactor: menuRow directive to MenuRow component

* refactor: migrate footer to react

* refactor: migrate actions menu to react

* refactor: migrate history menu to react

* fix: click outside handler use capture to trigger event before re-render occurs which would otherwise cause node.contains to return incorrect result (specifically for the account menu)

* refactor: migrate revision preview modal to react

* refactor: migrate permissions modal to react

* refactor: migrate password wizard to react

* refactor: remove unused input modal directive

* refactor: remove unused delay hide component

* refactor: remove unused filechange directive

* refactor: remove unused elemReady directive

* refactor: remove unused sn-enter directive

* refactor: remove unused lowercase directive

* refactor: remove unused autofocus directive

* refactor(wip): note view to react

* refactor: use mutation observer to deinit textarea listeners

* refactor: migrate challenge modal to react

* refactor: migrate note group view to react

* refactor(wip): migrate remaining classes

* fix: navigation parent ref

* refactor: fully remove angular assets

* fix: account switcher

* fix: application view state

* refactor: remove unused password wizard type

* fix: revision preview and permissions modal

* fix: remove angular comment

* refactor: react panel resizers for editor

* feat: simple panel resizer

* fix: use simple panel resizer everywhere

* fix: simplify panel resizer state

* chore: rename simple panel resizer to panel resizer

* refactor: simplify column layout

* fix: editor mount safety check

* fix: use inline onLoad callback for iframe, as setting onload after it loads will never call it

* chore: fix note view test

* chore(deps): upgrade snjs
This commit is contained in:
Mo
2022-01-30 19:01:30 -06:00
committed by GitHub
parent 0ecbde6bac
commit 50c92619ce
117 changed files with 4715 additions and 5309 deletions

View File

@@ -77,6 +77,7 @@ export class AccountMenuState {
runInAction(() => {
if (isDev && window._devAccountServer) {
this.setServer(window._devAccountServer);
this.application.setCustomHost(window._devAccountServer);
} else {
this.setServer(this.application.getHost());
}

View File

@@ -1,6 +1,6 @@
import { Bridge } from '@/services/bridge';
import { storage, StorageKey } from '@/services/localStorage';
import { WebApplication } from '@/ui_models/application';
import { WebApplication, WebAppEvent } from '@/ui_models/application';
import { AccountMenuState } from '@/ui_models/app_state/account_menu_state';
import { isDesktopApplication } from '@/utils';
import {
@@ -17,7 +17,6 @@ import {
ComponentViewer,
SNTag,
NoteViewController,
SNTheme,
} from '@standardnotes/snjs';
import pull from 'lodash/pull';
import {
@@ -68,14 +67,11 @@ export class AppState {
readonly enableUnfinishedFeatures: boolean =
window?._enable_unfinished_features;
$rootScope: ng.IRootScopeService;
$timeout: ng.ITimeoutService;
application: WebApplication;
observers: ObserverCallback[] = [];
locked = true;
unsubApp: any;
rootScopeCleanup1: any;
rootScopeCleanup2: any;
webAppEventDisposer?: () => void;
onVisibilityChange: any;
showBetaWarning: boolean;
@@ -105,14 +101,7 @@ export class AppState {
private readonly foldersComponentViewerDisposer: () => void;
/* @ngInject */
constructor(
$rootScope: ng.IRootScopeService,
$timeout: ng.ITimeoutService,
application: WebApplication,
private bridge: Bridge
) {
this.$timeout = $timeout;
this.$rootScope = $rootScope;
constructor(application: WebApplication, private bridge: Bridge) {
this.application = application;
this.notes = new NotesState(
application,
@@ -203,12 +192,8 @@ export class AppState {
this.appEventObserverRemovers.forEach((remover) => remover());
this.features.deinit();
this.appEventObserverRemovers.length = 0;
if (this.rootScopeCleanup1) {
this.rootScopeCleanup1();
this.rootScopeCleanup2();
this.rootScopeCleanup1 = undefined;
this.rootScopeCleanup2 = undefined;
}
this.webAppEventDisposer?.();
this.webAppEventDisposer = undefined;
document.removeEventListener('visibilitychange', this.onVisibilityChange);
this.onVisibilityChange = undefined;
this.tagChangedDisposer();
@@ -356,11 +341,7 @@ export class AppState {
.componentsForArea(ComponentArea.TagsList)
.find((component) => component.active);
this.application.performFunctionWithAngularDigestCycleAfterAsyncChange(
() => {
this.setFoldersComponent(componentViewer);
}
);
this.setFoldersComponent(componentViewer);
}
}
);
@@ -437,13 +418,13 @@ export class AppState {
registerVisibilityObservers() {
if (isDesktopApplication()) {
this.rootScopeCleanup1 = this.$rootScope.$on('window-lost-focus', () => {
this.notifyEvent(AppStateEvent.WindowDidBlur);
});
this.rootScopeCleanup2 = this.$rootScope.$on(
'window-gained-focus',
() => {
this.notifyEvent(AppStateEvent.WindowDidFocus);
this.webAppEventDisposer = this.application.addWebEventObserver(
(event) => {
if (event === WebAppEvent.DesktopWindowGainedFocus) {
this.notifyEvent(AppStateEvent.WindowDidFocus);
} else if (event === WebAppEvent.DesktopWindowLostFocus) {
this.notifyEvent(AppStateEvent.WindowDidBlur);
}
}
);
} else {
@@ -462,11 +443,11 @@ export class AppState {
async notifyEvent(eventName: AppStateEvent, data?: any) {
/**
* Timeout is particullary important so we can give all initial
* Timeout is particularly important so we can give all initial
* controllers a chance to construct before propogting any events *
*/
return new Promise<void>((resolve) => {
this.$timeout(async () => {
setTimeout(async () => {
for (const callback of this.observers) {
await callback(eventName, data);
}

View File

@@ -45,6 +45,7 @@ export class NotesViewState {
notesToDisplay = 0;
pageSize = 0;
panelTitle = 'All Notes';
panelWidth = 0;
renderedNotes: SNNote[] = [];
searchSubmitted = false;
selectedNotes: Record<UuidString, SNNote> = {};
@@ -324,7 +325,14 @@ export class NotesViewState {
if (displayOptionsChanged) {
this.reloadNotesDisplayOptions();
}
this.reloadNotes();
const width = this.application.getPreference(PrefKey.NotesPanelWidth);
if (width) {
this.panelWidth = width;
}
if (freshDisplayOptions.sortBy !== currentSortBy) {
this.selectFirstNote();
}
@@ -338,12 +346,9 @@ export class NotesViewState {
}
await this.appState.openNewNote(title);
this.application.performFunctionWithAngularDigestCycleAfterAsyncChange(
() => {
this.reloadNotes();
this.appState.noteTags.reloadTags();
}
);
this.reloadNotes();
this.appState.noteTags.reloadTags();
};
createPlaceholderNote = () => {

View File

@@ -1,5 +1,4 @@
import { WebCrypto } from '@/crypto';
import { InputModalScope } from '@/directives/views/inputModal';
import { AlertService } from '@/services/alertService';
import { ArchiveManager } from '@/services/archiveManager';
import { AutolockService } from '@/services/autolock_service';
@@ -8,18 +7,15 @@ import { DesktopManager } from '@/services/desktopManager';
import { IOService } from '@/services/ioService';
import { StatusManager } from '@/services/statusManager';
import { ThemeManager } from '@/services/themeManager';
import { PasswordWizardScope, PasswordWizardType } from '@/types';
import { AppState } from '@/ui_models/app_state';
import { WebDeviceInterface } from '@/web_device_interface';
import {
DeinitSource,
PermissionDialog,
Platform,
SNApplication,
NoteGroupController,
removeFromArray,
} from '@standardnotes/snjs';
import angular from 'angular';
import { AccountSwitcherScope, PermissionsModalScope } from './../types';
type WebServices = {
appState: AppState;
@@ -31,20 +27,23 @@ type WebServices = {
io: IOService;
};
export class WebApplication extends SNApplication {
private scope?: angular.IScope;
private webServices!: WebServices;
private currentAuthenticationElement?: angular.IRootElementService;
public noteControllerGroup: NoteGroupController;
export enum WebAppEvent {
NewUpdateAvailable = 'NewUpdateAvailable',
DesktopWindowGainedFocus = 'DesktopWindowGainedFocus',
DesktopWindowLostFocus = 'DesktopWindowLostFocus',
}
export type WebEventObserver = (event: WebAppEvent) => void;
export class WebApplication extends SNApplication {
private webServices!: WebServices;
public noteControllerGroup: NoteGroupController;
private webEventObservers: WebEventObserver[] = [];
/* @ngInject */
constructor(
deviceInterface: WebDeviceInterface,
platform: Platform,
identifier: string,
private $compile: angular.ICompileService,
private $timeout: angular.ITimeoutService,
scope: angular.IScope,
defaultSyncServerHost: string,
public bridge: Bridge,
enableUnfinishedFeatures: boolean,
@@ -63,11 +62,8 @@ export class WebApplication extends SNApplication {
enableUnfinishedFeatures,
webSocketUrl
);
this.$compile = $compile;
this.scope = scope;
deviceInterface.setApplication(this);
this.noteControllerGroup = new NoteGroupController(this);
this.presentPermissionsDialog = this.presentPermissionsDialog.bind(this);
}
/** @override */
@@ -79,14 +75,12 @@ export class WebApplication extends SNApplication {
(service as any).application = undefined;
}
this.webServices = {} as WebServices;
(this.$compile as unknown) = undefined;
this.noteControllerGroup.deinit();
(this.scope as any).application = undefined;
this.scope!.$destroy();
this.scope = undefined;
(this.presentPermissionsDialog as unknown) = undefined;
/** Allow our Angular directives to be destroyed and any pending digest cycles
* to complete before destroying the global application instance and all its services */
this.webEventObservers.length = 0;
/**
* Allow any pending renders to complete before destroying the global
* application instance and all its services
*/
setTimeout(() => {
super.deinit(source);
if (source === DeinitSource.SignOut) {
@@ -95,24 +89,21 @@ export class WebApplication extends SNApplication {
}, 0);
}
onStart(): void {
super.onStart();
this.componentManager.presentPermissionsDialog =
this.presentPermissionsDialog;
}
setWebServices(services: WebServices): void {
this.webServices = services;
}
/**
* If a UI change is made in an async function, Angular might not re-render the change.
* Use this function to force re-render the UI after an async function has made UI changes.
*/
public performFunctionWithAngularDigestCycleAfterAsyncChange(
func: () => void
) {
this.$timeout(func);
public addWebEventObserver(observer: WebEventObserver): () => void {
this.webEventObservers.push(observer);
return () => {
removeFromArray(this.webEventObservers, observer);
};
}
public notifyWebEvent(event: WebAppEvent): void {
for (const observer of this.webEventObservers) {
observer(event);
}
}
public getAppState(): AppState {
@@ -147,79 +138,12 @@ export class WebApplication extends SNApplication {
return this.protocolUpgradeAvailable();
}
presentPasswordWizard(type: PasswordWizardType) {
const scope = this.scope!.$new(true) as PasswordWizardScope;
scope.type = type;
scope.application = this;
const el = this.$compile!(
"<password-wizard application='application' type='type'></password-wizard>"
)(scope as any);
this.applicationElement.append(el);
}
downloadBackup(): void | Promise<void> {
return this.bridge.downloadBackup();
}
authenticationInProgress() {
return this.currentAuthenticationElement != null;
}
get applicationElement() {
return angular.element(document.getElementById(this.identifier)!);
}
async signOutAndDeleteLocalBackups(): Promise<void> {
await this.bridge.deleteLocalBackups();
return this.signOut();
}
presentPasswordModal(callback: () => void) {
const scope = this.scope!.$new(true) as InputModalScope;
scope.type = 'password';
scope.title = 'Decryption Assistance';
scope.message = `Unable to decrypt this item with your current keys.
Please enter your account password at the time of this revision.`;
scope.callback = callback;
const el = this.$compile!(
`<input-modal type='type' message='message'
title='title' callback='callback()'></input-modal>`
)(scope as any);
this.applicationElement.append(el);
}
presentRevisionPreviewModal(uuid: string, content: any, title?: string) {
const scope: any = this.scope!.$new(true);
scope.uuid = uuid;
scope.content = content;
scope.title = title;
scope.application = this;
const el = this.$compile!(
`<revision-preview-modal application='application' uuid='uuid' content='content' title='title'
class='sk-modal'></revision-preview-modal>`
)(scope);
this.applicationElement.append(el);
}
public openAccountSwitcher() {
const scope = this.scope!.$new(true) as Partial<AccountSwitcherScope>;
scope.application = this;
const el = this.$compile!(
"<account-switcher application='application' " +
"class='sk-modal'></account-switcher>"
)(scope as any);
this.applicationElement.append(el);
}
presentPermissionsDialog(dialog: PermissionDialog) {
const scope = this.scope!.$new(true) as PermissionsModalScope;
scope.permissionsString = dialog.permissionsString;
scope.component = dialog.component;
scope.callback = dialog.callback;
const el = this.$compile!(
"<permissions-modal component='component' permissions-string='permissionsString'" +
" callback='callback' class='sk-modal'></permissions-modal>"
)(scope as any);
this.applicationElement.append(el);
}
}

View File

@@ -17,24 +17,13 @@ import { StatusManager } from '@/services/statusManager';
import { ThemeManager } from '@/services/themeManager';
export class ApplicationGroup extends SNApplicationGroup {
$compile: ng.ICompileService;
$rootScope: ng.IRootScopeService;
$timeout: ng.ITimeoutService;
/* @ngInject */
constructor(
$compile: ng.ICompileService,
$rootScope: ng.IRootScopeService,
$timeout: ng.ITimeoutService,
private defaultSyncServerHost: string,
private bridge: Bridge,
private enableUnfinishedFeatures: boolean,
private webSocketUrl: string,
private webSocketUrl: string
) {
super(new WebDeviceInterface($timeout, bridge));
this.$compile = $compile;
this.$timeout = $timeout;
this.$rootScope = $rootScope;
super(new WebDeviceInterface(bridge));
}
async initialize(callback?: any): Promise<void> {
@@ -54,33 +43,19 @@ export class ApplicationGroup extends SNApplicationGroup {
descriptor: ApplicationDescriptor,
deviceInterface: DeviceInterface
) => {
const scope = this.$rootScope.$new(true);
const platform = getPlatform();
const application = new WebApplication(
deviceInterface as WebDeviceInterface,
platform,
descriptor.identifier,
this.$compile,
this.$timeout,
scope,
this.defaultSyncServerHost,
this.bridge,
this.enableUnfinishedFeatures,
this.webSocketUrl,
);
const appState = new AppState(
this.$rootScope,
this.$timeout,
application,
this.bridge
this.webSocketUrl
);
const appState = new AppState(application, this.bridge);
const archiveService = new ArchiveManager(application);
const desktopService = new DesktopManager(
this.$rootScope,
this.$timeout,
application,
this.bridge
);
const desktopService = new DesktopManager(application, this.bridge);
const io = new IOService(
platform === Platform.MacWeb || platform === Platform.MacDesktop
);

View File

@@ -1,326 +0,0 @@
import {
PanelSide,
ResizeFinishCallback,
} from '@/directives/views/panelResizer';
import { debounce } from '@/utils';
import { ApplicationEvent, PrefKey } from '@standardnotes/snjs';
import { action, computed, makeObservable, observable } from 'mobx';
import { WebApplication } from './application';
export type PanelResizerProps = {
alwaysVisible?: boolean;
application: WebApplication;
collapsable: boolean;
defaultWidth?: number;
hoverable?: boolean;
minWidth?: number;
panel: HTMLDivElement;
prefKey: PrefKey;
resizeFinishCallback?: ResizeFinishCallback;
side: PanelSide;
widthEventCallback?: () => void;
};
export class PanelResizerState {
private application: WebApplication;
alwaysVisible: boolean;
collapsable: boolean;
collapsed = false;
currentMinWidth = 0;
defaultWidth: number;
hoverable: boolean;
lastDownX = 0;
lastLeft = 0;
lastWidth = 0;
panel: HTMLDivElement;
pressed = false;
prefKey: PrefKey;
resizeFinishCallback?: ResizeFinishCallback;
side: PanelSide;
startLeft = 0;
startWidth = 0;
widthBeforeLastDblClick = 0;
widthEventCallback?: () => void;
overlay?: HTMLDivElement;
constructor({
alwaysVisible,
application,
defaultWidth,
hoverable,
collapsable,
minWidth,
panel,
prefKey,
resizeFinishCallback,
side,
widthEventCallback,
}: PanelResizerProps) {
const currentKnownPref =
(application.getPreference(prefKey) as number) ?? defaultWidth ?? 0;
this.panel = panel;
this.startLeft = this.panel.offsetLeft;
this.startWidth = this.panel.scrollWidth;
this.alwaysVisible = alwaysVisible ?? false;
this.application = application;
this.collapsable = collapsable ?? false;
this.collapsed = false;
this.currentMinWidth = minWidth ?? 0;
this.defaultWidth = defaultWidth ?? 0;
this.hoverable = hoverable ?? true;
this.lastDownX = 0;
this.lastLeft = this.startLeft;
this.lastWidth = this.startWidth;
this.prefKey = prefKey;
this.pressed = false;
this.side = side;
this.widthBeforeLastDblClick = 0;
this.widthEventCallback = widthEventCallback;
this.resizeFinishCallback = resizeFinishCallback;
this.setWidth(currentKnownPref, true);
application.addEventObserver(async () => {
const changedWidth = application.getPreference(prefKey) as number;
if (changedWidth !== this.lastWidth) this.setWidth(changedWidth, true);
}, ApplicationEvent.PreferencesChanged);
makeObservable(this, {
pressed: observable,
collapsed: observable,
addInvisibleOverlay: action,
finishSettingWidth: action,
handleLeftEvent: action,
handleWidthEvent: action,
onDblClick: action,
onMouseDown: action,
onMouseUp: action,
reloadDefaultValues: action,
removeInvisibleOverlay: action,
setLeft: action,
setMinWidth: action,
setWidth: action,
appFrame: computed,
});
document.addEventListener('mouseup', this.onMouseUp.bind(this));
document.addEventListener('mousemove', this.onMouseMove.bind(this));
if (this.side === PanelSide.Right) {
window.addEventListener(
'resize',
debounce(this.handleResize.bind(this), 250)
);
}
}
get appFrame() {
return document.getElementById('app')?.getBoundingClientRect() as DOMRect;
}
getParentRect() {
return (this.panel.parentNode as HTMLElement).getBoundingClientRect();
}
isAtMaxWidth = () => {
return (
Math.round(this.lastWidth + this.lastLeft) ===
Math.round(this.getParentRect().width)
);
};
isCollapsed() {
return this.lastWidth <= this.currentMinWidth;
}
reloadDefaultValues = () => {
this.startWidth = this.isAtMaxWidth()
? this.getParentRect().width
: this.panel.scrollWidth;
this.lastWidth = this.startWidth;
};
finishSettingWidth = () => {
if (!this.collapsable) {
return;
}
this.collapsed = this.isCollapsed();
};
setWidth = (width: number, finish = false) => {
if (width < this.currentMinWidth) {
width = this.currentMinWidth;
}
const parentRect = this.getParentRect();
if (width > parentRect.width) {
width = parentRect.width;
}
const maxWidth = this.appFrame.width - this.panel.getBoundingClientRect().x;
if (width > maxWidth) {
width = maxWidth;
}
if (Math.round(width + this.lastLeft) === Math.round(parentRect.width)) {
this.panel.style.width = `calc(100% - ${this.lastLeft}px)`;
} else {
this.panel.style.width = width + 'px';
}
this.lastWidth = width;
if (finish) {
this.finishSettingWidth();
if (this.resizeFinishCallback) {
this.resizeFinishCallback(
this.lastWidth,
this.lastLeft,
this.isAtMaxWidth(),
this.isCollapsed()
);
}
}
this.application.setPreference(this.prefKey, this.lastWidth);
};
setLeft = (left: number) => {
this.panel.style.left = left + 'px';
this.lastLeft = left;
};
onDblClick = () => {
const collapsed = this.isCollapsed();
if (collapsed) {
this.setWidth(this.widthBeforeLastDblClick || this.defaultWidth);
} else {
this.widthBeforeLastDblClick = this.lastWidth;
this.setWidth(this.currentMinWidth);
}
this.application.setPreference(this.prefKey, this.lastWidth);
this.finishSettingWidth();
if (this.resizeFinishCallback) {
this.resizeFinishCallback(
this.lastWidth,
this.lastLeft,
this.isAtMaxWidth(),
this.isCollapsed()
);
}
};
handleWidthEvent(event?: MouseEvent) {
if (this.widthEventCallback) {
this.widthEventCallback();
}
let x;
if (event) {
x = event.clientX;
} else {
/** Coming from resize event */
x = 0;
this.lastDownX = 0;
}
const deltaX = x - this.lastDownX;
const newWidth = this.startWidth + deltaX;
this.setWidth(newWidth, false);
}
handleLeftEvent(event: MouseEvent) {
const panelRect = this.panel.getBoundingClientRect();
const x = event.clientX || panelRect.x;
let deltaX = x - this.lastDownX;
let newLeft = this.startLeft + deltaX;
if (newLeft < 0) {
newLeft = 0;
deltaX = -this.startLeft;
}
const parentRect = this.getParentRect();
let newWidth = this.startWidth - deltaX;
if (newWidth < this.currentMinWidth) {
newWidth = this.currentMinWidth;
}
if (newWidth > parentRect.width) {
newWidth = parentRect.width;
}
if (newLeft + newWidth > parentRect.width) {
newLeft = parentRect.width - newWidth;
}
this.setLeft(newLeft);
this.setWidth(newWidth, false);
}
handleResize = () => {
this.reloadDefaultValues();
this.handleWidthEvent();
this.finishSettingWidth();
};
onMouseDown = (event: MouseEvent) => {
this.addInvisibleOverlay();
this.pressed = true;
this.lastDownX = event.clientX;
this.startWidth = this.panel.scrollWidth;
this.startLeft = this.panel.offsetLeft;
};
onMouseUp = () => {
this.removeInvisibleOverlay();
if (!this.pressed) {
return;
}
this.pressed = false;
const isMaxWidth = this.isAtMaxWidth();
if (this.resizeFinishCallback) {
this.resizeFinishCallback(
this.lastWidth,
this.lastLeft,
isMaxWidth,
this.isCollapsed()
);
}
this.finishSettingWidth();
};
onMouseMove(event: MouseEvent) {
if (!this.pressed) {
return;
}
event.preventDefault();
if (this.side === PanelSide.Left) {
this.handleLeftEvent(event);
} else {
this.handleWidthEvent(event);
}
}
setMinWidth = (minWidth?: number) => {
this.currentMinWidth = minWidth ?? this.currentMinWidth;
};
/**
* If an iframe is displayed adjacent to our panel, and the mouse exits over the iframe,
* document[onmouseup] is not triggered because the document is no longer the same over
* the iframe. We add an invisible overlay while resizing so that the mouse context
* remains in our main document.
*/
addInvisibleOverlay = () => {
if (this.overlay) {
return;
}
const overlayElement = document.createElement('div');
overlayElement.id = 'resizer-overlay';
this.overlay = overlayElement;
document.body.prepend(this.overlay);
};
removeInvisibleOverlay = () => {
if (this.overlay) {
this.overlay.remove();
this.overlay = undefined;
}
};
}