feat: search options (#540)

* feat: search options

* feat: sanitize folder names

* fix: add cursor: pointer to switch

* fix: explicitly make the search bar a text input

* refactor: remove magic number

* refactor: extract Switch component to its own file

* refactor: split AppState into multiple files

* refactor: review comments
This commit is contained in:
Baptiste Grob
2021-04-06 16:48:25 +02:00
committed by GitHub
parent 275c8cbd1f
commit ed69680295
24 changed files with 672 additions and 319 deletions

View File

@@ -58,6 +58,7 @@ import { Bridge } from './services/bridge';
import { SessionsModalDirective } from './components/SessionsModal';
import { NoAccountWarningDirective } from './components/NoAccountWarning';
import { NoProtectionsdNoteWarningDirective } from './components/NoProtectionsNoteWarning';
import { SearchOptionsDirective } from './components/SearchOptions';
function reloadHiddenFirefoxTab(): boolean {
/**
@@ -145,7 +146,8 @@ const startApplication: StartApplication = async function startApplication(
.directive('syncResolutionMenu', () => new SyncResolutionMenu())
.directive('sessionsModal', SessionsModalDirective)
.directive('noAccountWarning', NoAccountWarningDirective)
.directive('protectedNotePanel', NoProtectionsdNoteWarningDirective);
.directive('protectedNotePanel', NoProtectionsdNoteWarningDirective)
.directive('searchOptions', SearchOptionsDirective);
// Filters
angular.module('app').filter('trusted', ['$sce', trusted]);

View File

@@ -0,0 +1,112 @@
import { AppState } from '@/ui_models/app_state';
import { toDirective, useAutorunValue } from './utils';
import { useRef, useState } from 'preact/hooks';
import { WebApplication } from '@/ui_models/application';
import VisuallyHidden from '@reach/visually-hidden';
import {
Disclosure,
DisclosureButton,
DisclosurePanel,
} from '@reach/disclosure';
import { FocusEvent } from 'react';
import { Switch } from './Switch';
import TuneIcon from '../../icons/ic_tune.svg';
type Props = {
appState: AppState;
application: WebApplication;
};
function SearchOptions({ appState }: Props) {
const { searchOptions } = appState;
const {
includeProtectedContents,
includeArchived,
includeTrashed,
} = useAutorunValue(() => ({
includeProtectedContents: searchOptions.includeProtectedContents,
includeArchived: searchOptions.includeArchived,
includeTrashed: searchOptions.includeTrashed,
}));
const [
togglingIncludeProtectedContents,
setTogglingIncludeProtectedContents,
] = useState(false);
async function toggleIncludeProtectedContents() {
setTogglingIncludeProtectedContents(true);
try {
await searchOptions.toggleIncludeProtectedContents();
} finally {
setTogglingIncludeProtectedContents(false);
}
}
const [open, setOpen] = useState(false);
const [optionsPanelTop, setOptionsPanelTop] = useState(0);
const buttonRef = useRef<HTMLButtonElement>();
const panelRef = useRef<HTMLDivElement>();
function closeOnBlur(event: FocusEvent<HTMLElement>) {
if (
!togglingIncludeProtectedContents &&
!panelRef.current.contains(event.relatedTarget as Node)
) {
setOpen(false);
}
}
return (
<Disclosure
open={open}
onChange={() => {
const { height } = buttonRef.current.getBoundingClientRect();
const extraVerticalBreathingRoom = 4;
setOptionsPanelTop(height + extraVerticalBreathingRoom);
setOpen((prevIsOpen) => !prevIsOpen);
}}
>
<DisclosureButton
ref={buttonRef}
onBlur={closeOnBlur}
className="sn-icon-button color-neutral hover:color-info"
>
<VisuallyHidden>Search options</VisuallyHidden>
<TuneIcon className="fill-current block" />
</DisclosureButton>
<DisclosurePanel
ref={panelRef}
style={{
top: optionsPanelTop,
}}
className="sn-dropdown sn-dropdown-anchor-right grid gap-2 py-2"
>
<Switch
checked={includeProtectedContents}
onChange={toggleIncludeProtectedContents}
onBlur={closeOnBlur}
>
<p className="capitalize">Include protected contents</p>
</Switch>
<Switch
checked={includeArchived}
onChange={searchOptions.toggleIncludeArchived}
onBlur={closeOnBlur}
>
<p className="capitalize">Include archived notes</p>
</Switch>
<Switch
checked={includeTrashed}
onChange={searchOptions.toggleIncludeTrashed}
onBlur={closeOnBlur}
>
<p className="capitalize">Include trashed notes</p>
</Switch>
</DisclosurePanel>
</Disclosure>
);
}
export const SearchOptionsDirective = toDirective<Props>(SearchOptions);

View File

@@ -0,0 +1,48 @@
import { ComponentChildren, FunctionalComponent } from 'preact';
import { useState } from 'preact/hooks';
import { HTMLProps } from 'react';
import {
CustomCheckboxContainer,
CustomCheckboxInput,
CustomCheckboxInputProps,
} from '@reach/checkbox';
import '@reach/checkbox/styles.css';
export type SwitchProps = HTMLProps<HTMLInputElement> & {
checked?: boolean;
onChange: (checked: boolean) => void;
children: ComponentChildren;
};
export const Switch: FunctionalComponent<SwitchProps> = (
props: SwitchProps
) => {
const [checkedState, setChecked] = useState(props.checked || false);
const checked = props.checked ?? checkedState;
return (
<label className="sn-component flex justify-between items-center cursor-pointer hover:bg-contrast py-2 px-3">
{props.children}
<CustomCheckboxContainer
checked={checked}
onChange={(event) => {
setChecked(event.target.checked);
props.onChange(event.target.checked);
}}
className={`sn-switch ${checked ? 'bg-info' : 'bg-secondary-contrast'}`}
>
<CustomCheckboxInput
{...({
...props,
children: undefined,
} as CustomCheckboxInputProps)}
/>
<span
aria-hidden
className={`sn-switch-handle ${
checked ? 'sn-switch-handle-right' : ''
}`}
/>
</CustomCheckboxContainer>
</label>
);
};

View File

@@ -32,6 +32,9 @@ export function toDirective<Props>(
'$scope',
// eslint-disable-next-line @typescript-eslint/no-explicit-any
($element: JQLite, $scope: any) => {
if ($scope.class) {
$element.addClass($scope.class);
}
return {
$onChanges() {
render(

View File

@@ -2,7 +2,6 @@
// css
import '@reach/dialog/styles.css';
import 'sn-stylekit/dist/stylekit.css';
import '../stylesheets/index.css.scss';
// Vendor

View File

@@ -7,17 +7,20 @@ import {
PayloadContent,
} from '@standardnotes/snjs';
function zippableTxtName(name: string, suffix = ""): string {
const sanitizedName = name.trim().replace(/[.\\/:"?*|<>]/g, '_');
const nameEnd = suffix + ".txt";
function sanitizeFileName(name: string): string {
return name.trim().replace(/[.\\/:"?*|<>]/g, '_');
}
function zippableTxtName(name: string, suffix = ''): string {
const sanitizedName = sanitizeFileName(name);
const nameEnd = suffix + '.txt';
const maxFileNameLength = 100;
return sanitizedName.slice(0, maxFileNameLength - nameEnd.length) + nameEnd;
}
export class ArchiveManager {
private readonly application: WebApplication
private textFile?: string
private readonly application: WebApplication;
private textFile?: string;
constructor(application: WebApplication) {
this.application = application;
@@ -32,10 +35,9 @@ export class ArchiveManager {
if (!data) {
return;
}
const blobData = new Blob(
[JSON.stringify(data, null, 2)],
{ type: 'text/json' }
);
const blobData = new Blob([JSON.stringify(data, null, 2)], {
type: 'text/json',
});
if (encrypted) {
this.downloadData(
blobData,
@@ -81,19 +83,16 @@ export class ArchiveManager {
});
}
private async downloadZippedDecryptedItems(
data: BackupFile
) {
private async downloadZippedDecryptedItems(data: BackupFile) {
await this.loadZip();
const items = data.items;
this.zip.createWriter(
new this.zip.BlobWriter('application/zip'),
async (zipWriter: any) => {
await new Promise((resolve) => {
const blob = new Blob(
[JSON.stringify(data, null, 2)],
{ type: 'text/plain' }
);
const blob = new Blob([JSON.stringify(data, null, 2)], {
type: 'text/plain',
});
const fileName = zippableTxtName(
'Standard Notes Backup and Import File.txt'
);
@@ -116,7 +115,8 @@ export class ArchiveManager {
name = '';
}
const blob = new Blob([contents], { type: 'text/plain' });
const fileName = `Items/${item.content_type}/` +
const fileName =
`Items/${sanitizeFileName(item.content_type)}/` +
zippableTxtName(name, `-${item.uuid.split('-')[0]}`);
zipWriter.add(fileName, new this.zip.BlobReader(blob), () => {
index++;
@@ -134,7 +134,9 @@ export class ArchiveManager {
});
};
nextFile();
}, onerror);
},
onerror
);
}
private hrefForData(data: Blob) {

View File

@@ -0,0 +1,21 @@
import { action, makeObservable, observable } from "mobx";
export class AccountMenuState {
show = false;
constructor() {
makeObservable(this, {
show: observable,
setShow: action,
toggleShow: action,
});
}
setShow = (show: boolean): void => {
this.show = show;
}
toggleShow = (): void => {
this.show = !this.show;
}
}

View File

@@ -0,0 +1,22 @@
import { UuidString } from "@standardnotes/snjs";
import { action, makeObservable, observable } from "mobx";
export class ActionsMenuState {
hiddenExtensions: Record<UuidString, boolean> = {};
constructor() {
makeObservable(this, {
hiddenExtensions: observable,
toggleExtensionVisibility: action,
reset: action,
});
}
toggleExtensionVisibility = (uuid: UuidString): void => {
this.hiddenExtensions[uuid] = !this.hiddenExtensions[uuid];
}
reset = (): void => {
this.hiddenExtensions = {};
}
}

View File

@@ -7,16 +7,18 @@ import {
ContentType,
PayloadSource,
DeinitSource,
UuidString,
SyncOpStatus,
PrefKey,
SNApplication,
} from '@standardnotes/snjs';
import { WebApplication } from '@/ui_models/application';
import { Editor } from '@/ui_models/editor';
import { action, makeObservable, observable, runInAction } from 'mobx';
import { action, makeObservable, observable } from 'mobx';
import { Bridge } from '@/services/bridge';
import { storage, StorageKey } from '@/services/localStorage';
import { AccountMenuState } from './account_menu_state';
import { ActionsMenuState } from './actions_menu_state';
import { NoAccountWarningState } from './no_account_warning_state';
import { SyncState } from './sync_state';
import { SearchOptionsState } from './search_options_state';
export enum AppStateEvent {
TagChanged,
@@ -41,113 +43,6 @@ export enum EventSource {
type ObserverCallback = (event: AppStateEvent, data?: any) => Promise<void>;
class ActionsMenuState {
hiddenExtensions: Record<UuidString, boolean> = {};
constructor() {
makeObservable(this, {
hiddenExtensions: observable,
toggleExtensionVisibility: action,
reset: action,
});
}
toggleExtensionVisibility(uuid: UuidString) {
this.hiddenExtensions[uuid] = !this.hiddenExtensions[uuid];
}
reset() {
this.hiddenExtensions = {};
}
}
export class SyncState {
inProgress = false;
errorMessage?: string = undefined;
humanReadablePercentage?: string = undefined;
constructor() {
makeObservable(this, {
inProgress: observable,
errorMessage: observable,
humanReadablePercentage: observable,
update: action,
});
}
update(status: SyncOpStatus): void {
this.errorMessage = status.error?.message;
this.inProgress = status.syncInProgress;
const stats = status.getStats();
const completionPercentage =
stats.uploadCompletionCount === 0
? 0
: stats.uploadCompletionCount / stats.uploadTotalCount;
if (completionPercentage === 0) {
this.humanReadablePercentage = undefined;
} else {
this.humanReadablePercentage = completionPercentage.toLocaleString(
undefined,
{ style: 'percent' }
);
}
}
}
class AccountMenuState {
show = false;
constructor() {
makeObservable(this, {
show: observable,
setShow: action,
toggleShow: action,
});
}
setShow(show: boolean) {
this.show = show;
}
toggleShow() {
this.show = !this.show;
}
}
class NoAccountWarningState {
show: boolean;
constructor(application: SNApplication, appObservers: (() => void)[]) {
this.show = application.hasAccount()
? false
: storage.get(StorageKey.ShowNoAccountWarning) ?? true;
appObservers.push(
application.addEventObserver(async () => {
runInAction(() => {
this.show = false;
});
}, ApplicationEvent.SignedIn),
application.addEventObserver(async () => {
if (application.hasAccount()) {
runInAction(() => {
this.show = false;
});
}
}, ApplicationEvent.Started)
);
makeObservable(this, {
show: observable,
hide: action,
});
}
hide() {
this.show = false;
storage.set(StorageKey.ShowNoAccountWarning, false);
}
reset() {
storage.remove(StorageKey.ShowNoAccountWarning);
}
}
export class AppState {
readonly enableUnfinishedFeatures =
isDev || location.host.includes('app-dev.standardnotes.org');
@@ -167,8 +62,8 @@ export class AppState {
readonly actionsMenu = new ActionsMenuState();
readonly noAccountWarning: NoAccountWarningState;
readonly sync = new SyncState();
readonly searchOptions;
isSessionsModalVisible = false;
mouseUp = Promise.resolve();
private appEventObserverRemovers: (() => void)[] = [];
@@ -186,6 +81,10 @@ export class AppState {
application,
this.appEventObserverRemovers
);
this.searchOptions = new SearchOptionsState(
application,
this.appEventObserverRemovers
);
this.addAppEventObserver();
this.streamNotesAndTags();
this.onVisibilityChange = () => {
@@ -196,7 +95,6 @@ export class AppState {
this.notifyEvent(event);
};
this.registerVisibilityObservers();
document.addEventListener('mousedown', this.onMouseDown);
if (this.bridge.appVersion.includes('-beta')) {
this.showBetaWarning = storage.get(StorageKey.ShowBetaWarning) ?? true;
@@ -233,16 +131,9 @@ export class AppState {
this.rootScopeCleanup2 = undefined;
}
document.removeEventListener('visibilitychange', this.onVisibilityChange);
document.removeEventListener('mousedown', this.onMouseDown);
this.onVisibilityChange = undefined;
}
onMouseDown = (): void => {
this.mouseUp = new Promise((resolve) => {
document.addEventListener('mouseup', () => resolve(), { once: true });
});
};
openSessionsModal() {
this.isSessionsModalVisible = true;
}

View File

@@ -0,0 +1,6 @@
export {
AppState,
AppStateEvent,
EventSource,
PanelResizedData,
} from './app_state';

View File

@@ -0,0 +1,41 @@
import { storage, StorageKey } from "@/services/localStorage";
import { SNApplication, ApplicationEvent } from "@standardnotes/snjs";
import { runInAction, makeObservable, observable, action } from "mobx";
export class NoAccountWarningState {
show: boolean;
constructor(application: SNApplication, appObservers: (() => void)[]) {
this.show = application.hasAccount()
? false
: storage.get(StorageKey.ShowNoAccountWarning) ?? true;
appObservers.push(
application.addEventObserver(async () => {
runInAction(() => {
this.show = false;
});
}, ApplicationEvent.SignedIn),
application.addEventObserver(async () => {
if (application.hasAccount()) {
runInAction(() => {
this.show = false;
});
}
}, ApplicationEvent.Started)
);
makeObservable(this, {
show: observable,
hide: action,
});
}
hide = (): void => {
this.show = false;
storage.set(StorageKey.ShowNoAccountWarning, false);
}
reset = (): void => {
storage.remove(StorageKey.ShowNoAccountWarning);
}
}

View File

@@ -0,0 +1,59 @@
import { ApplicationEvent } from "@standardnotes/snjs";
import { makeObservable, observable, action, runInAction } from "mobx";
import { WebApplication } from "../application";
export class SearchOptionsState {
includeProtectedContents = false;
includeArchived = false;
includeTrashed = false;
constructor(
private application: WebApplication,
appObservers: (() => void)[]
) {
makeObservable(this, {
includeProtectedContents: observable,
includeTrashed: observable,
includeArchived: observable,
toggleIncludeArchived: action,
toggleIncludeTrashed: action,
toggleIncludeProtectedContents: action,
refreshIncludeProtectedContents: action,
});
appObservers.push(
this.application.addEventObserver(async () => {
this.refreshIncludeProtectedContents();
}, ApplicationEvent.ProtectionSessionExpiryDateChanged)
);
}
toggleIncludeArchived = (): void => {
this.includeArchived = !this.includeArchived;
};
toggleIncludeTrashed = (): void => {
this.includeTrashed = !this.includeTrashed;
};
refreshIncludeProtectedContents = (): void => {
if (
this.includeProtectedContents &&
this.application.areProtectionsEnabled()
) {
this.includeProtectedContents = false;
}
};
toggleIncludeProtectedContents = async (): Promise<void> => {
if (this.includeProtectedContents) {
this.includeProtectedContents = false;
} else {
const authorized = await this.application.authorizeSearchingProtectedNotesText();
runInAction(() => {
this.includeProtectedContents = authorized;
});
}
};
}

View File

@@ -0,0 +1,36 @@
import { SyncOpStatus } from "@standardnotes/snjs";
import { action, makeObservable, observable } from "mobx";
export class SyncState {
inProgress = false;
errorMessage?: string = undefined;
humanReadablePercentage?: string = undefined;
constructor() {
makeObservable(this, {
inProgress: observable,
errorMessage: observable,
humanReadablePercentage: observable,
update: action,
});
}
update = (status: SyncOpStatus): void => {
this.errorMessage = status.error?.message;
this.inProgress = status.syncInProgress;
const stats = status.getStats();
const completionPercentage =
stats.uploadCompletionCount === 0
? 0
: stats.uploadCompletionCount / stats.uploadTotalCount;
if (completionPercentage === 0) {
this.humanReadablePercentage = undefined;
} else {
this.humanReadablePercentage = completionPercentage.toLocaleString(
undefined,
{ style: 'percent' }
);
}
}
}

View File

@@ -12,6 +12,7 @@
i.icon.ion-plus.add-button
.filter-section(role='search')
input#search-bar.filter-bar(
type="text"
ng-ref='self.searchBarInput'
ng-focus='self.onSearchInputFocus()'
ng-blur='self.onSearchInputBlur()',
@@ -25,21 +26,12 @@
#search-clear-button(
ng-click='self.clearFilterText();',
ng-show='self.state.noteFilter.text'
aria-role="button"
) ✕
label.sk-panel-row.justify-left.mt-2.animate-slide-in-top(
ng-if='self.state.searchIsFocused || self.state.searchOptionsAreFocused || self.state.authorizingSearchOptions'
style="padding-bottom: 0"
)
.sk-horizontal-group.tight
input(
ng-ref='self.searchOptionsInput'
ng-focus="self.onSearchOptionsFocus()"
ng-blur="self.onSearchOptionsBlur()"
type="checkbox"
ng-checked="self.state.noteFilter.includeProtectedNoteText"
ng-on-click="self.onIncludeProtectedNoteTextChange($event)"
)
p.sk-p.capitalize Include protected contents
search-options(
class="ml-2 h-20px"
app-state='self.appState'
)
no-account-warning(
application='self.application'
app-state='self.appState'

View File

@@ -18,10 +18,11 @@ import { KeyboardModifier, KeyboardKey } from '@/services/keyboardManager';
import {
PANEL_NAME_NOTES
} from '@/views/constants';
import { autorun, IReactionDisposer } from 'mobx';
type NotesState = {
panelTitle: string
notes?: SNNote[]
notes: SNNote[]
renderedNotes: SNNote[]
renderedNotesTags: string[],
sortBy?: string
@@ -33,11 +34,12 @@ type NotesState = {
hideTags: boolean
noteFilter: {
text: string;
includeProtectedNoteText: boolean;
}
searchIsFocused: boolean;
searchOptionsAreFocused: boolean;
authorizingSearchOptions: boolean;
searchOptions: {
includeProtectedContents: boolean;
includeArchived: boolean;
includeTrashed: boolean;
}
mutable: { showMenu: boolean }
completedFullSync: boolean
[PrefKey.TagsPanelWidth]?: number
@@ -76,8 +78,7 @@ class NotesViewCtrl extends PureViewCtrl<unknown, NotesState> {
private searchKeyObserver: any
private noteFlags: Partial<Record<UuidString, NoteFlag[]>> = {}
private removeObservers: Array<() => void> = [];
private searchBarInput?: JQLite;
private searchOptionsInput?: JQLite;
private appStateObserver?: IReactionDisposer;
/* @ngInject */
constructor($timeout: ng.ITimeoutService,) {
@@ -94,6 +95,24 @@ class NotesViewCtrl extends PureViewCtrl<unknown, NotesState> {
this.onPanelResize = this.onPanelResize.bind(this);
window.addEventListener('resize', this.onWindowResize, true);
this.registerKeyboardShortcuts();
this.appStateObserver = autorun(async () => {
const {
includeProtectedContents,
includeArchived,
includeTrashed,
} = this.appState.searchOptions;
await this.setState({
searchOptions: {
includeProtectedContents,
includeArchived,
includeTrashed,
}
});
if (this.state.noteFilter.text) {
this.reloadNotesDisplayOptions();
this.reloadNotes();
}
});
}
onWindowResize() {
@@ -112,6 +131,7 @@ class NotesViewCtrl extends PureViewCtrl<unknown, NotesState> {
this.nextNoteKeyObserver();
this.previousNoteKeyObserver();
this.searchKeyObserver();
this.appStateObserver?.();
this.newNoteKeyObserver = undefined;
this.nextNoteKeyObserver = undefined;
this.previousNoteKeyObserver = undefined;
@@ -119,10 +139,6 @@ class NotesViewCtrl extends PureViewCtrl<unknown, NotesState> {
super.deinit();
}
getState() {
return this.state as NotesState;
}
async setNotesState(state: Partial<NotesState>) {
return this.setState(state);
}
@@ -135,14 +151,15 @@ class NotesViewCtrl extends PureViewCtrl<unknown, NotesState> {
mutable: { showMenu: false },
noteFilter: {
text: '',
includeProtectedNoteText: false
},
searchOptions: {
includeArchived: false,
includeProtectedContents: false,
includeTrashed: false,
},
panelTitle: '',
completedFullSync: false,
hideTags: true,
searchIsFocused: false,
searchOptionsAreFocused: false,
authorizingSearchOptions: false
hideTags: true
};
}
@@ -203,7 +220,7 @@ class NotesViewCtrl extends PureViewCtrl<unknown, NotesState> {
* that may be in progress. This is the sync alternative to `async getMostValidNotes`
*/
private getPossiblyStaleNotes() {
return this.getState().notes!;
return this.state.notes;
}
/**
@@ -230,7 +247,7 @@ class NotesViewCtrl extends PureViewCtrl<unknown, NotesState> {
}
streamNotesAndTags() {
this.removeObservers.push(this.application!.streamItems(
this.removeObservers.push(this.application.streamItems(
[ContentType.Note],
async (items) => {
const notes = items as SNNote[];
@@ -256,7 +273,7 @@ class NotesViewCtrl extends PureViewCtrl<unknown, NotesState> {
}
));
this.removeObservers.push(this.application!.streamItems(
this.removeObservers.push(this.application.streamItems(
[ContentType.Tag],
async (items) => {
const tags = items as SNTag[];
@@ -280,9 +297,9 @@ class NotesViewCtrl extends PureViewCtrl<unknown, NotesState> {
}
async createNewNote() {
let title = `Note ${this.getState().notes!.length + 1}`;
let title = `Note ${this.state.notes.length + 1}`;
if (this.isFiltering()) {
title = this.getState().noteFilter.text;
title = this.state.noteFilter.text;
}
await this.appState.createEditor(title);
await this.flushUI();
@@ -293,21 +310,21 @@ class NotesViewCtrl extends PureViewCtrl<unknown, NotesState> {
this.resetScrollPosition();
this.setShowMenuFalse();
await this.setNoteFilterText('');
this.application!.getDesktopService().searchText();
this.application.getDesktopService().searchText();
this.resetPagination();
/* Capture db load state before beginning reloadNotes,
since this status may change during reload */
const dbLoaded = this.application!.isDatabaseLoaded();
const dbLoaded = this.application.isDatabaseLoaded();
this.reloadNotesDisplayOptions();
await this.reloadNotes();
if (this.getState().notes!.length > 0) {
if (this.state.notes.length > 0) {
this.selectFirstNote();
} else if (dbLoaded) {
if (
this.activeEditorNote &&
!this.getState().notes!.includes(this.activeEditorNote!)
!this.state.notes.includes(this.activeEditorNote!)
) {
this.appState.closeActiveEditor();
}
@@ -323,7 +340,7 @@ class NotesViewCtrl extends PureViewCtrl<unknown, NotesState> {
}
async removeNoteFromList(note: SNNote) {
const notes = this.getState().notes!;
const notes = this.state.notes;
removeFromArray(notes, note);
await this.setNotesState({
notes: notes,
@@ -343,23 +360,37 @@ class NotesViewCtrl extends PureViewCtrl<unknown, NotesState> {
*/
private reloadNotesDisplayOptions() {
const tag = this.appState.selectedTag;
const searchText = this.getState().noteFilter.text.toLowerCase();
const searchText = this.state.noteFilter.text.toLowerCase();
const isSearching = searchText.length;
let includeArchived: boolean;
let includeTrashed: boolean;
if (isSearching) {
includeArchived = this.state.searchOptions.includeArchived;
includeTrashed = this.state.searchOptions.includeTrashed;
} else {
includeArchived = this.state.showArchived ?? false;
includeTrashed = false;
}
const criteria = NotesDisplayCriteria.Create({
sortProperty: this.state.sortBy! as CollectionSort,
sortDirection: this.state.sortReverse! ? 'asc' : 'dsc',
sortProperty: this.state.sortBy as CollectionSort,
sortDirection: this.state.sortReverse ? 'asc' : 'dsc',
tags: tag ? [tag] : [],
includeArchived: this.getState().showArchived!,
includePinned: !this.getState().hidePinned!,
includeArchived,
includeTrashed,
includePinned: !this.state.hidePinned,
searchQuery: {
query: searchText ?? '',
includeProtectedNoteText: this.state.noteFilter.includeProtectedNoteText
query: searchText,
includeProtectedNoteText: this.state.searchOptions.includeProtectedContents
}
});
this.application!.setNotesDisplayCriteria(criteria);
this.application.setNotesDisplayCriteria(criteria);
}
private get selectedTag() {
return this.application!.getAppState().getSelectedTag();
return this.application.getAppState().getSelectedTag();
}
private async performReloadNotes() {
@@ -411,7 +442,7 @@ class NotesViewCtrl extends PureViewCtrl<unknown, NotesState> {
setShowMenuFalse() {
this.setNotesState({
mutable: {
...this.getState().mutable,
...this.state.mutable,
showMenu: false
}
});
@@ -420,19 +451,19 @@ class NotesViewCtrl extends PureViewCtrl<unknown, NotesState> {
async handleEditorChange() {
const activeNote = this.appState.getActiveEditor()?.note;
if (activeNote && activeNote.conflictOf) {
this.application!.changeAndSaveItem(activeNote.uuid, (mutator) => {
this.application.changeAndSaveItem(activeNote.uuid, (mutator) => {
mutator.conflictOf = undefined;
});
}
if (this.isFiltering()) {
this.application!.getDesktopService().searchText(this.getState().noteFilter.text);
this.application.getDesktopService().searchText(this.state.noteFilter.text);
}
}
async reloadPreferences() {
const viewOptions = {} as NotesState;
const prevSortValue = this.getState().sortBy;
let sortBy = this.application!.getPreference(
const prevSortValue = this.state.sortBy;
let sortBy = this.application.getPreference(
PrefKey.SortNotesBy,
CollectionSort.CreatedAt
);
@@ -444,23 +475,23 @@ class NotesViewCtrl extends PureViewCtrl<unknown, NotesState> {
sortBy = CollectionSort.UpdatedAt;
}
viewOptions.sortBy = sortBy;
viewOptions.sortReverse = this.application!.getPreference(
viewOptions.sortReverse = this.application.getPreference(
PrefKey.SortNotesReverse,
false
);
viewOptions.showArchived = this.application!.getPreference(
viewOptions.showArchived = this.application.getPreference(
PrefKey.NotesShowArchived,
false
);
viewOptions.hidePinned = this.application!.getPreference(
viewOptions.hidePinned = this.application.getPreference(
PrefKey.NotesHidePinned,
false
);
viewOptions.hideNotePreview = this.application!.getPreference(
viewOptions.hideNotePreview = this.application.getPreference(
PrefKey.NotesHideNotePreview,
false
);
viewOptions.hideDate = this.application!.getPreference(
viewOptions.hideDate = this.application.getPreference(
PrefKey.NotesHideDate,
false
);
@@ -468,7 +499,7 @@ class NotesViewCtrl extends PureViewCtrl<unknown, NotesState> {
PrefKey.NotesHideTags,
true,
);
const state = this.getState();
const state = this.state;
const displayOptionsChanged = (
viewOptions.sortBy !== state.sortBy ||
viewOptions.sortReverse !== state.sortReverse ||
@@ -490,13 +521,13 @@ class NotesViewCtrl extends PureViewCtrl<unknown, NotesState> {
}
reloadPanelWidth() {
const width = this.application!.getPreference(
const width = this.application.getPreference(
PrefKey.NotesPanelWidth
);
if (width && this.panelPuppet!.ready) {
this.panelPuppet!.setWidth!(width);
if (this.panelPuppet!.isCollapsed!()) {
this.application!.getAppState().panelDidResize(
this.application.getAppState().panelDidResize(
PANEL_NAME_NOTES,
this.panelPuppet!.isCollapsed!()
);
@@ -510,11 +541,11 @@ class NotesViewCtrl extends PureViewCtrl<unknown, NotesState> {
__: boolean,
isCollapsed: boolean
) {
this.application!.setPreference(
this.application.setPreference(
PrefKey.NotesPanelWidth,
newWidth
);
this.application!.getAppState().panelDidResize(
this.application.getAppState().panelDidResize(
PANEL_NAME_NOTES,
isCollapsed
);
@@ -524,7 +555,7 @@ class NotesViewCtrl extends PureViewCtrl<unknown, NotesState> {
this.notesToDisplay += this.pageSize;
this.reloadNotes();
if (this.searchSubmitted) {
this.application!.getDesktopService().searchText(this.getState().noteFilter.text);
this.application.getDesktopService().searchText(this.state.noteFilter.text);
}
}
@@ -543,7 +574,7 @@ class NotesViewCtrl extends PureViewCtrl<unknown, NotesState> {
reloadPanelTitle() {
let title;
if (this.isFiltering()) {
const resultCount = this.getState().notes!.length;
const resultCount = this.state.notes.length;
title = `${resultCount} search results`;
} else if (this.appState.selectedTag) {
title = `${this.appState.selectedTag.title}`;
@@ -555,20 +586,20 @@ class NotesViewCtrl extends PureViewCtrl<unknown, NotesState> {
optionsSubtitle() {
let base = "";
if (this.getState().sortBy === CollectionSort.CreatedAt) {
if (this.state.sortBy === CollectionSort.CreatedAt) {
base += " Date Added";
} else if (this.getState().sortBy === CollectionSort.UpdatedAt) {
} else if (this.state.sortBy === CollectionSort.UpdatedAt) {
base += " Date Modified";
} else if (this.getState().sortBy === CollectionSort.Title) {
} else if (this.state.sortBy === CollectionSort.Title) {
base += " Title";
}
if (this.getState().showArchived) {
if (this.state.showArchived) {
base += " | + Archived";
}
if (this.getState().hidePinned) {
if (this.state.hidePinned) {
base += " | Pinned";
}
if (this.getState().sortReverse) {
if (this.state.sortReverse) {
base += " | Reversed";
}
return base;
@@ -628,13 +659,8 @@ class NotesViewCtrl extends PureViewCtrl<unknown, NotesState> {
this.noteFlags[note.uuid] = flags;
}
displayableNotes() {
return this.getState().notes!;
}
getFirstNonProtectedNote() {
const displayableNotes = this.displayableNotes();
return displayableNotes.find(note => !note.protected);
return this.state.notes.find(note => !note.protected);
}
selectFirstNote() {
@@ -645,9 +671,9 @@ class NotesViewCtrl extends PureViewCtrl<unknown, NotesState> {
}
selectNextNote() {
const displayableNotes = this.displayableNotes();
const displayableNotes = this.state.notes;
const currentIndex = displayableNotes.findIndex((candidate) => {
return candidate.uuid === this.activeEditorNote!.uuid;
return candidate.uuid === this.activeEditorNote.uuid;
});
if (currentIndex + 1 < displayableNotes.length) {
this.selectNote(displayableNotes[currentIndex + 1]);
@@ -664,7 +690,7 @@ class NotesViewCtrl extends PureViewCtrl<unknown, NotesState> {
}
selectPreviousNote() {
const displayableNotes = this.displayableNotes();
const displayableNotes = this.state.notes;
const currentIndex = displayableNotes.indexOf(this.activeEditorNote!);
if (currentIndex - 1 >= 0) {
this.selectNote(displayableNotes[currentIndex - 1]);
@@ -675,14 +701,14 @@ class NotesViewCtrl extends PureViewCtrl<unknown, NotesState> {
}
isFiltering() {
return this.getState().noteFilter.text &&
this.getState().noteFilter.text.length > 0;
return this.state.noteFilter.text &&
this.state.noteFilter.text.length > 0;
}
async setNoteFilterText(text: string) {
await this.setNotesState({
noteFilter: {
...this.getState().noteFilter,
...this.state.noteFilter,
text: text
}
});
@@ -703,72 +729,8 @@ class NotesViewCtrl extends PureViewCtrl<unknown, NotesState> {
await this.reloadNotes();
}
async onIncludeProtectedNoteTextChange(event: Event) {
this.searchBarInput?.[0].focus();
if (this.state.noteFilter.includeProtectedNoteText) {
await this.setState({
noteFilter: {
...this.state.noteFilter,
includeProtectedNoteText: false,
},
});
this.reloadNotesDisplayOptions();
await this.reloadNotes();
} else {
this.setState({
authorizingSearchOptions: true,
});
event.preventDefault();
if (await this.application.authorizeSearchingProtectedNotesText()) {
await this.setState({
noteFilter: {
...this.state.noteFilter,
includeProtectedNoteText: true,
},
});
this.reloadNotesDisplayOptions();
await this.reloadNotes();
}
await this.$timeout(50);
await this.setState({
authorizingSearchOptions: false,
});
}
}
onSearchInputFocus() {
this.setState({
searchIsFocused: true,
});
}
async onSearchInputBlur() {
await this.appState.mouseUp;
/**
* Wait a non-zero amount of time so the newly-focused element can have
* enough time to set its state
*/
await this.$timeout(50);
await this.setState({
searchIsFocused:
this.searchBarInput?.[0] === document.activeElement,
});
this.onFilterEnter();
}
onSearchOptionsFocus() {
this.setState({
searchOptionsAreFocused: true,
});
}
async onSearchOptionsBlur() {
await this.appState.mouseUp;
await this.$timeout(50);
this.setState({
searchOptionsAreFocused:
this.searchOptionsInput?.[0] === document.activeElement,
});
this.appState.searchOptions.refreshIncludeProtectedContents();
}
onFilterEnter() {
@@ -778,7 +740,7 @@ class NotesViewCtrl extends PureViewCtrl<unknown, NotesState> {
* enter before highlighting desktop search results.
*/
this.searchSubmitted = true;
this.application!.getDesktopService().searchText(this.getState().noteFilter.text);
this.application.getDesktopService().searchText(this.state.noteFilter.text);
}
selectedMenuItem() {
@@ -786,7 +748,7 @@ class NotesViewCtrl extends PureViewCtrl<unknown, NotesState> {
}
togglePrefKey(key: PrefKey) {
this.application!.setPreference(
this.application.setPreference(
key,
!this.state[key]
);
@@ -806,14 +768,14 @@ class NotesViewCtrl extends PureViewCtrl<unknown, NotesState> {
toggleReverseSort() {
this.selectedMenuItem();
this.application!.setPreference(
this.application.setPreference(
PrefKey.SortNotesReverse,
!this.getState().sortReverse
!this.state.sortReverse
);
}
setSortBy(type: CollectionSort) {
this.application!.setPreference(
this.application.setPreference(
PrefKey.SortNotesBy,
type
);
@@ -829,7 +791,7 @@ class NotesViewCtrl extends PureViewCtrl<unknown, NotesState> {
* use Control modifier as well. These rules don't apply to desktop, but
* probably better to be consistent.
*/
this.newNoteKeyObserver = this.application!.getKeyboardService().addKeyObserver({
this.newNoteKeyObserver = this.application.getKeyboardService().addKeyObserver({
key: 'n',
modifiers: [
KeyboardModifier.Meta,
@@ -841,7 +803,7 @@ class NotesViewCtrl extends PureViewCtrl<unknown, NotesState> {
}
});
this.nextNoteKeyObserver = this.application!.getKeyboardService().addKeyObserver({
this.nextNoteKeyObserver = this.application.getKeyboardService().addKeyObserver({
key: KeyboardKey.Down,
elements: [
document.body,
@@ -856,7 +818,7 @@ class NotesViewCtrl extends PureViewCtrl<unknown, NotesState> {
}
});
this.previousNoteKeyObserver = this.application!.getKeyboardService().addKeyObserver({
this.previousNoteKeyObserver = this.application.getKeyboardService().addKeyObserver({
key: KeyboardKey.Up,
element: document.body,
onKeyDown: () => {
@@ -864,7 +826,7 @@ class NotesViewCtrl extends PureViewCtrl<unknown, NotesState> {
}
});
this.searchKeyObserver = this.application!.getKeyboardService().addKeyObserver({
this.searchKeyObserver = this.application.getKeyboardService().addKeyObserver({
key: "f",
modifiers: [
KeyboardModifier.Meta,