style: run prettier

This commit is contained in:
Baptiste Grob
2021-03-22 18:32:50 +01:00
parent 9f5c640bcd
commit ac634333cf

View File

@@ -1,4 +1,9 @@
import { Strings, STRING_ARCHIVE_LOCKED_ATTEMPT, STRING_SAVING_WHILE_DOCUMENT_HIDDEN, STRING_UNARCHIVE_LOCKED_ATTEMPT } from './../../strings'; import {
Strings,
STRING_ARCHIVE_LOCKED_ATTEMPT,
STRING_SAVING_WHILE_DOCUMENT_HIDDEN,
STRING_UNARCHIVE_LOCKED_ATTEMPT,
} from './../../strings';
import { Editor } from '@/ui_models/editor'; import { Editor } from '@/ui_models/editor';
import { WebApplication } from '@/ui_models/application'; import { WebApplication } from '@/ui_models/application';
import { PanelPuppet, WebDirective } from '@/types'; import { PanelPuppet, WebDirective } from '@/types';
@@ -31,7 +36,7 @@ import {
STRING_DELETE_PLACEHOLDER_ATTEMPT, STRING_DELETE_PLACEHOLDER_ATTEMPT,
STRING_DELETE_LOCKED_ATTEMPT, STRING_DELETE_LOCKED_ATTEMPT,
StringDeleteNote, StringDeleteNote,
StringEmptyTrash StringEmptyTrash,
} from '@/strings'; } from '@/strings';
import { alertDialog, confirmDialog } from '@/services/alertService'; import { alertDialog, confirmDialog } from '@/services/alertService';
@@ -45,89 +50,91 @@ const ElementIds = {
NoteTextEditor: 'note-text-editor', NoteTextEditor: 'note-text-editor',
NoteTitleEditor: 'note-title-editor', NoteTitleEditor: 'note-title-editor',
EditorContent: 'editor-content', EditorContent: 'editor-content',
NoteTagsComponentContainer: 'note-tags-component-container' NoteTagsComponentContainer: 'note-tags-component-container',
}; };
type NoteStatus = { type NoteStatus = {
message?: string message?: string;
date?: Date date?: Date;
} };
type EditorState = { type EditorState = {
stackComponents: SNComponent[] stackComponents: SNComponent[];
editorComponent?: SNComponent editorComponent?: SNComponent;
tagsComponent?: SNComponent tagsComponent?: SNComponent;
saveError?: any saveError?: any;
noteStatus?: NoteStatus noteStatus?: NoteStatus;
tagsAsStrings?: string tagsAsStrings?: string;
marginResizersEnabled?: boolean marginResizersEnabled?: boolean;
monospaceFont?: boolean monospaceFont?: boolean;
isDesktop?: boolean isDesktop?: boolean;
syncTakingTooLong: boolean syncTakingTooLong: boolean;
showActionsMenu: boolean showActionsMenu: boolean;
showOptionsMenu: boolean showOptionsMenu: boolean;
showEditorMenu: boolean showEditorMenu: boolean;
showHistoryMenu: boolean showHistoryMenu: boolean;
altKeyDown: boolean altKeyDown: boolean;
spellcheck: boolean spellcheck: boolean;
/** /**
* Setting to false then true will allow the current editor component-view to be destroyed * Setting to false then true will allow the current editor component-view to be destroyed
* then re-initialized. Used when changing between component editors. * then re-initialized. Used when changing between component editors.
*/ */
editorUnloading: boolean editorUnloading: boolean;
/** Setting to true then false will allow the main content textarea to be destroyed /** Setting to true then false will allow the main content textarea to be destroyed
* then re-initialized. Used when reloading spellcheck status. */ * then re-initialized. Used when reloading spellcheck status. */
textareaUnloading: boolean textareaUnloading: boolean;
/** Fields that can be directly mutated by the template */ /** Fields that can be directly mutated by the template */
mutable: any mutable: any;
showProtectedWarning: boolean showProtectedWarning: boolean;
} };
type EditorValues = { type EditorValues = {
title?: string title?: string;
text?: string text?: string;
tagsInputValue?: string tagsInputValue?: string;
} };
function sortAlphabetically(array: SNComponent[]): SNComponent[] { function sortAlphabetically(array: SNComponent[]): SNComponent[] {
return array.sort((a, b) => a.name.toLowerCase() < b.name.toLowerCase() ? -1 : 1); return array.sort((a, b) =>
a.name.toLowerCase() < b.name.toLowerCase() ? -1 : 1
);
} }
class EditorViewCtrl extends PureViewCtrl<unknown, EditorState> { class EditorViewCtrl extends PureViewCtrl<unknown, EditorState> {
/** Passed through template */ /** Passed through template */
readonly application!: WebApplication readonly application!: WebApplication;
readonly editor!: Editor readonly editor!: Editor;
private leftPanelPuppet?: PanelPuppet private leftPanelPuppet?: PanelPuppet;
private rightPanelPuppet?: PanelPuppet private rightPanelPuppet?: PanelPuppet;
private unregisterComponent: any private unregisterComponent: any;
private saveTimeout?: ng.IPromise<void> private saveTimeout?: ng.IPromise<void>;
private statusTimeout?: ng.IPromise<void> private statusTimeout?: ng.IPromise<void>;
private lastEditorFocusEventSource?: EventSource private lastEditorFocusEventSource?: EventSource;
public editorValues: EditorValues = {} public editorValues: EditorValues = {};
onEditorLoad?: () => void onEditorLoad?: () => void;
private tags: SNTag[] = []; private tags: SNTag[] = [];
private removeAltKeyObserver?: any private removeAltKeyObserver?: any;
private removeTrashKeyObserver?: any private removeTrashKeyObserver?: any;
private removeTabObserver?: any private removeTabObserver?: any;
private removeTagsObserver!: () => void private removeTagsObserver!: () => void;
private removeComponentsObserver!: () => void private removeComponentsObserver!: () => void;
prefKeyMonospace: string prefKeyMonospace: string;
prefKeySpellcheck: string prefKeySpellcheck: string;
prefKeyMarginResizers: string prefKeyMarginResizers: string;
/* @ngInject */ /* @ngInject */
constructor($timeout: ng.ITimeoutService) { constructor($timeout: ng.ITimeoutService) {
super($timeout); super($timeout);
this.leftPanelPuppet = { this.leftPanelPuppet = {
onReady: () => this.reloadPreferences() onReady: () => this.reloadPreferences(),
}; };
this.rightPanelPuppet = { this.rightPanelPuppet = {
onReady: () => this.reloadPreferences() onReady: () => this.reloadPreferences(),
}; };
/** Used by .pug template */ /** Used by .pug template */
this.prefKeyMonospace = PrefKey.EditorMonospaceEnabled; this.prefKeyMonospace = PrefKey.EditorMonospaceEnabled;
@@ -196,7 +203,9 @@ class EditorViewCtrl extends PureViewCtrl<unknown, EditorState> {
if (note.lastSyncEnd) { if (note.lastSyncEnd) {
if (note.lastSyncBegan!.getTime() > note.lastSyncEnd!.getTime()) { if (note.lastSyncBegan!.getTime() > note.lastSyncEnd!.getTime()) {
this.showSavingStatus(); this.showSavingStatus();
} else if (note.lastSyncEnd!.getTime() > note.lastSyncBegan!.getTime()) { } else if (
note.lastSyncEnd!.getTime() > note.lastSyncBegan!.getTime()
) {
this.showAllChangesSavedStatus(); this.showAllChangesSavedStatus();
} }
} else { } else {
@@ -223,7 +232,7 @@ class EditorViewCtrl extends PureViewCtrl<unknown, EditorState> {
editorUnloading: false, editorUnloading: false,
textareaUnloading: false, textareaUnloading: false,
mutable: { mutable: {
tagsString: '' tagsString: '',
}, },
showProtectedWarning: false, showProtectedWarning: false,
} as EditorState; } as EditorState;
@@ -265,8 +274,8 @@ class EditorViewCtrl extends PureViewCtrl<unknown, EditorState> {
break; break;
case ApplicationEvent.LocalDatabaseWriteError: case ApplicationEvent.LocalDatabaseWriteError:
this.showErrorStatus({ this.showErrorStatus({
message: "Offline Saving Issue", message: 'Offline Saving Issue',
desc: "Changes not saved" desc: 'Changes not saved',
}); });
break; break;
} }
@@ -275,7 +284,8 @@ class EditorViewCtrl extends PureViewCtrl<unknown, EditorState> {
async handleEditorNoteChange() { async handleEditorNoteChange() {
this.cancelPendingSetStatus(); this.cancelPendingSetStatus();
const note = this.editor.note; const note = this.editor.note;
const showProtectedWarning = note.protected && !this.application.hasProtectionSources(); const showProtectedWarning =
note.protected && !this.application.hasProtectionSources();
await this.setState({ await this.setState({
showActionsMenu: false, showActionsMenu: false,
showOptionsMenu: false, showOptionsMenu: false,
@@ -299,7 +309,7 @@ class EditorViewCtrl extends PureViewCtrl<unknown, EditorState> {
async dismissProtectedWarning() { async dismissProtectedWarning() {
await this.setState({ await this.setState({
showProtectedWarning: false showProtectedWarning: false,
}); });
this.focusTitle(); this.focusTitle();
} }
@@ -342,7 +352,9 @@ class EditorViewCtrl extends PureViewCtrl<unknown, EditorState> {
} }
private async reloadEditor() { private async reloadEditor() {
const newEditor = this.application.componentManager!.editorForNote(this.note); const newEditor = this.application.componentManager!.editorForNote(
this.note
);
/** Editors cannot interact with template notes so the note must be inserted */ /** Editors cannot interact with template notes so the note must be inserted */
if (newEditor && this.editor.isTemplateNote) { if (newEditor && this.editor.isTemplateNote) {
await this.editor.insertTemplatedNote(); await this.editor.insertTemplatedNote();
@@ -351,7 +363,7 @@ class EditorViewCtrl extends PureViewCtrl<unknown, EditorState> {
if (currentEditor?.uuid !== newEditor?.uuid) { if (currentEditor?.uuid !== newEditor?.uuid) {
await this.setState({ await this.setState({
/** Unload current component view so that we create a new one */ /** Unload current component view so that we create a new one */
editorUnloading: true editorUnloading: true,
}); });
await this.setState({ await this.setState({
/** Reload component view */ /** Reload component view */
@@ -360,12 +372,14 @@ class EditorViewCtrl extends PureViewCtrl<unknown, EditorState> {
}); });
this.reloadFont(); this.reloadFont();
} }
this.application.componentManager!.contextItemDidChangeInArea(ComponentArea.Editor); this.application.componentManager!.contextItemDidChangeInArea(
ComponentArea.Editor
);
} }
setMenuState(menu: string, state: boolean) { setMenuState(menu: string, state: boolean) {
this.setState({ this.setState({
[menu]: state [menu]: state,
}); });
this.closeAllMenus(menu); this.closeAllMenus(menu);
} }
@@ -403,12 +417,15 @@ class EditorViewCtrl extends PureViewCtrl<unknown, EditorState> {
}); });
this.reloadEditor(); this.reloadEditor();
} }
if (this.state.editorComponent?.isExplicitlyEnabledForItem(this.note.uuid)) { if (
await this.disassociateComponentWithCurrentNote(this.state.editorComponent); this.state.editorComponent?.isExplicitlyEnabledForItem(this.note.uuid)
) {
await this.disassociateComponentWithCurrentNote(
this.state.editorComponent
);
} }
this.reloadFont(); this.reloadFont();
} } else if (component.area === ComponentArea.Editor) {
else if (component.area === ComponentArea.Editor) {
const currentEditor = this.state.editorComponent; const currentEditor = this.state.editorComponent;
if (currentEditor && component !== currentEditor) { if (currentEditor && component !== currentEditor) {
await this.disassociateComponentWithCurrentNote(currentEditor); await this.disassociateComponentWithCurrentNote(currentEditor);
@@ -421,8 +438,7 @@ class EditorViewCtrl extends PureViewCtrl<unknown, EditorState> {
}); });
} }
await this.associateComponentWithCurrentNote(component); await this.associateComponentWithCurrentNote(component);
} } else if (component.area === ComponentArea.EditorStack) {
else if (component.area === ComponentArea.EditorStack) {
await this.toggleStackComponentForCurrentItem(component); await this.toggleStackComponentForCurrentItem(component);
} }
/** Dirtying can happen above */ /** Dirtying can happen above */
@@ -430,8 +446,10 @@ class EditorViewCtrl extends PureViewCtrl<unknown, EditorState> {
} }
hasAvailableExtensions() { hasAvailableExtensions() {
return this.application.actionsManager!. return (
extensionsInContextOfItem(this.note).length > 0; this.application.actionsManager!.extensionsInContextOfItem(this.note)
.length > 0
);
} }
/** /**
@@ -455,37 +473,33 @@ class EditorViewCtrl extends PureViewCtrl<unknown, EditorState> {
closeAfterSync = false closeAfterSync = false
) { ) {
if (document.hidden) { if (document.hidden) {
this.application.alertService!.alert( this.application.alertService!.alert(STRING_SAVING_WHILE_DOCUMENT_HIDDEN);
STRING_SAVING_WHILE_DOCUMENT_HIDDEN
);
return; return;
} }
const note = this.note; const note = this.note;
if (note.deleted) { if (note.deleted) {
this.application.alertService!.alert( this.application.alertService!.alert(STRING_DELETED_NOTE);
STRING_DELETED_NOTE
);
return; return;
} }
if (this.editor.isTemplateNote) { if (this.editor.isTemplateNote) {
await this.editor.insertTemplatedNote(); await this.editor.insertTemplatedNote();
} }
const selectedTag = this.appState.selectedTag; const selectedTag = this.appState.selectedTag;
if (!selectedTag?.isSmartTag && !selectedTag?.hasRelationshipWithItem(note)) { if (
await this.application.changeItem( !selectedTag?.isSmartTag &&
selectedTag!.uuid, !selectedTag?.hasRelationshipWithItem(note)
(mutator) => { ) {
await this.application.changeItem(selectedTag!.uuid, (mutator) => {
mutator.addItemAsRelationship(note); mutator.addItemAsRelationship(note);
} });
);
} }
if (!this.application.findItem(note.uuid)) { if (!this.application.findItem(note.uuid)) {
this.application.alertService!.alert( this.application.alertService!.alert(STRING_INVALID_NOTE);
STRING_INVALID_NOTE
);
return; return;
} }
await this.application.changeItem(note.uuid, (mutator) => { await this.application.changeItem(
note.uuid,
(mutator) => {
const noteMutator = mutator as NoteMutator; const noteMutator = mutator as NoteMutator;
if (customMutate) { if (customMutate) {
customMutate(noteMutator); customMutate(noteMutator);
@@ -500,7 +514,9 @@ class EditorViewCtrl extends PureViewCtrl<unknown, EditorState> {
noteMutator.preview_plain = previewPlain; noteMutator.preview_plain = previewPlain;
noteMutator.preview_html = undefined; noteMutator.preview_html = undefined;
} }
}, isUserModified); },
isUserModified
);
if (this.saveTimeout) { if (this.saveTimeout) {
this.$timeout.cancel(this.saveTimeout); this.$timeout.cancel(this.saveTimeout);
} }
@@ -517,16 +533,13 @@ class EditorViewCtrl extends PureViewCtrl<unknown, EditorState> {
} }
showSavingStatus() { showSavingStatus() {
this.setStatus( this.setStatus({ message: 'Saving…' }, false);
{ message: "Saving…" },
false
);
} }
showAllChangesSavedStatus() { showAllChangesSavedStatus() {
this.setState({ this.setState({
saveError: false, saveError: false,
syncTakingTooLong: false syncTakingTooLong: false,
}); });
this.setStatus({ this.setStatus({
message: 'All changes saved', message: 'All changes saved',
@@ -536,13 +549,13 @@ class EditorViewCtrl extends PureViewCtrl<unknown, EditorState> {
showErrorStatus(error?: any) { showErrorStatus(error?: any) {
if (!error) { if (!error) {
error = { error = {
message: "Sync Unreachable", message: 'Sync Unreachable',
desc: "Changes saved offline" desc: 'Changes saved offline',
}; };
} }
this.setState({ this.setState({
saveError: true, saveError: true,
syncTakingTooLong: false syncTakingTooLong: false,
}); });
this.setStatus(error); this.setStatus(error);
} }
@@ -554,12 +567,12 @@ class EditorViewCtrl extends PureViewCtrl<unknown, EditorState> {
if (wait) { if (wait) {
this.statusTimeout = this.$timeout(() => { this.statusTimeout = this.$timeout(() => {
this.setState({ this.setState({
noteStatus: status noteStatus: status,
}); });
}, MINIMUM_STATUS_DURATION); }, MINIMUM_STATUS_DURATION);
} else { } else {
this.setState({ this.setState({
noteStatus: status noteStatus: status,
}); });
} }
} }
@@ -571,10 +584,7 @@ class EditorViewCtrl extends PureViewCtrl<unknown, EditorState> {
} }
contentChanged() { contentChanged() {
this.saveNote( this.saveNote(false, true);
false,
true
);
} }
onTitleEnter($event: Event) { onTitleEnter($event: Event) {
@@ -584,11 +594,7 @@ class EditorViewCtrl extends PureViewCtrl<unknown, EditorState> {
} }
onTitleChange() { onTitleChange() {
this.saveNote( this.saveNote(false, true, true);
false,
true,
true,
);
} }
focusEditor() { focusEditor() {
@@ -608,17 +614,15 @@ class EditorViewCtrl extends PureViewCtrl<unknown, EditorState> {
} }
// eslint-disable-next-line @typescript-eslint/no-empty-function // eslint-disable-next-line @typescript-eslint/no-empty-function
onTitleFocus() { onTitleFocus() {}
}
// eslint-disable-next-line @typescript-eslint/no-empty-function // eslint-disable-next-line @typescript-eslint/no-empty-function
onTitleBlur() { onTitleBlur() {}
}
onContentFocus() { onContentFocus() {
this.application.getAppState().editorDidFocus(this.lastEditorFocusEventSource!); this.application
.getAppState()
.editorDidFocus(this.lastEditorFocusEventSource!);
this.lastEditorFocusEventSource = undefined; this.lastEditorFocusEventSource = undefined;
} }
@@ -630,39 +634,29 @@ class EditorViewCtrl extends PureViewCtrl<unknown, EditorState> {
async deleteNote(permanently: boolean) { async deleteNote(permanently: boolean) {
if (this.editor.isTemplateNote) { if (this.editor.isTemplateNote) {
this.application.alertService!.alert( this.application.alertService!.alert(STRING_DELETE_PLACEHOLDER_ATTEMPT);
STRING_DELETE_PLACEHOLDER_ATTEMPT
);
return; return;
} }
if (this.note.locked) { if (this.note.locked) {
this.application.alertService!.alert( this.application.alertService!.alert(STRING_DELETE_LOCKED_ATTEMPT);
STRING_DELETE_LOCKED_ATTEMPT
);
return; return;
} }
const title = this.note.safeTitle().length const title = this.note.safeTitle().length
? `'${this.note.title}'` ? `'${this.note.title}'`
: "this note"; : 'this note';
const text = StringDeleteNote( const text = StringDeleteNote(title, permanently);
title, if (
permanently await confirmDialog({
);
if (await confirmDialog({
text, text,
confirmButtonStyle: 'danger' confirmButtonStyle: 'danger',
})) { })
) {
if (permanently) { if (permanently) {
this.performNoteDeletion(this.note); this.performNoteDeletion(this.note);
} else { } else {
this.saveNote( this.saveNote(true, false, true, (mutator) => {
true,
false,
true,
(mutator) => {
mutator.trashed = true; mutator.trashed = true;
} });
);
} }
} }
} }
@@ -693,35 +687,27 @@ class EditorViewCtrl extends PureViewCtrl<unknown, EditorState> {
async emptyTrash() { async emptyTrash() {
const count = this.getTrashCount(); const count = this.getTrashCount();
if (await confirmDialog({ if (
await confirmDialog({
text: StringEmptyTrash(count), text: StringEmptyTrash(count),
confirmButtonStyle: 'danger' confirmButtonStyle: 'danger',
})) { })
) {
this.application.emptyTrash(); this.application.emptyTrash();
this.application.sync(); this.application.sync();
} }
} }
togglePin() { togglePin() {
this.saveNote( this.saveNote(true, false, true, (mutator) => {
true,
false,
true,
(mutator) => {
mutator.pinned = !this.note.pinned; mutator.pinned = !this.note.pinned;
} });
);
} }
toggleLockNote() { toggleLockNote() {
this.saveNote( this.saveNote(true, false, true, (mutator) => {
true,
false,
true,
(mutator) => {
mutator.locked = !this.note.locked; mutator.locked = !this.note.locked;
} });
);
} }
async toggleProtectNote() { async toggleProtectNote() {
@@ -731,29 +717,24 @@ class EditorViewCtrl extends PureViewCtrl<unknown, EditorState> {
const note = await this.application.protectNote(this.note); const note = await this.application.protectNote(this.note);
if (note?.protected && !this.application.hasProtectionSources()) { if (note?.protected && !this.application.hasProtectionSources()) {
this.setState({ this.setState({
showProtectedWarning: true showProtectedWarning: true,
}); });
} }
} }
} }
toggleNotePreview() { toggleNotePreview() {
this.saveNote( this.saveNote(true, false, true, (mutator) => {
true,
false,
true,
(mutator) => {
mutator.hidePreview = !this.note.hidePreview; mutator.hidePreview = !this.note.hidePreview;
} });
);
} }
toggleArchiveNote() { toggleArchiveNote() {
if (this.note.locked) { if (this.note.locked) {
alertDialog({ alertDialog({
text: this.note.archived ? text: this.note.archived
STRING_UNARCHIVE_LOCKED_ATTEMPT : ? STRING_UNARCHIVE_LOCKED_ATTEMPT
STRING_ARCHIVE_LOCKED_ATTEMPT, : STRING_ARCHIVE_LOCKED_ATTEMPT,
}); });
return; return;
} }
@@ -781,10 +762,7 @@ class EditorViewCtrl extends PureViewCtrl<unknown, EditorState> {
for (let i = 0; i < tags.length; i++) { for (let i = 0; i < tags.length; i++) {
const localTag = this.tags[i]; const localTag = this.tags[i];
const tag = tags[i]; const tag = tags[i];
if ( if (tag.title !== localTag.title || tag.uuid !== localTag.uuid) {
tag.title !== localTag.title ||
tag.uuid !== localTag.uuid
) {
this.reloadTagsString(tags); this.reloadTagsString(tags);
break; break;
} }
@@ -810,9 +788,11 @@ class EditorViewCtrl extends PureViewCtrl<unknown, EditorState> {
removeTag(tag: SNTag) { removeTag(tag: SNTag) {
const tags = this.appState.getNoteTags(this.note); const tags = this.appState.getNoteTags(this.note);
const strings = tags.map((currentTag) => { const strings = tags
.map((currentTag) => {
return currentTag.title; return currentTag.title;
}).filter((title) => { })
.filter((title) => {
return title !== tag.title; return title !== tag.title;
}); });
this.saveTagsFromStrings(strings); this.saveTagsFromStrings(strings);
@@ -825,14 +805,14 @@ class EditorViewCtrl extends PureViewCtrl<unknown, EditorState> {
public async saveTagsFromStrings(strings?: string[]) { public async saveTagsFromStrings(strings?: string[]) {
if ( if (
!strings !strings &&
&& this.editorValues.tagsInputValue === this.state.tagsAsStrings this.editorValues.tagsInputValue === this.state.tagsAsStrings
) { ) {
return; return;
} }
if (!strings) { if (!strings) {
strings = this.editorValues.tagsInputValue! strings = this.editorValues
.split('#') .tagsInputValue!.split('#')
.filter((string) => { .filter((string) => {
return string.length > 0; return string.length > 0;
}) })
@@ -855,23 +835,15 @@ class EditorViewCtrl extends PureViewCtrl<unknown, EditorState> {
} }
const newRelationships: SNTag[] = []; const newRelationships: SNTag[] = [];
for (const title of strings) { for (const title of strings) {
const existingRelationship = find( const existingRelationship = find(currentTags, { title: title });
currentTags,
{ title: title }
);
if (!existingRelationship) { if (!existingRelationship) {
newRelationships.push( newRelationships.push(await this.application.findOrCreateTag(title));
await this.application.findOrCreateTag(title)
);
} }
} }
if (newRelationships.length > 0) { if (newRelationships.length > 0) {
await this.application.changeItems( await this.application.changeItems(Uuids(newRelationships), (mutator) => {
Uuids(newRelationships),
(mutator) => {
mutator.addItemAsRelationship(note); mutator.addItemAsRelationship(note);
} });
);
} }
this.application.sync(); this.application.sync();
this.reloadTags(); this.reloadTags();
@@ -879,24 +851,15 @@ class EditorViewCtrl extends PureViewCtrl<unknown, EditorState> {
async onPanelResizeFinish(width: number, left: number, isMaxWidth: boolean) { async onPanelResizeFinish(width: number, left: number, isMaxWidth: boolean) {
if (isMaxWidth) { if (isMaxWidth) {
await this.application.setPreference( await this.application.setPreference(PrefKey.EditorWidth, null);
PrefKey.EditorWidth,
null
);
} else { } else {
if (width !== undefined && width !== null) { if (width !== undefined && width !== null) {
await this.application.setPreference( await this.application.setPreference(PrefKey.EditorWidth, width);
PrefKey.EditorWidth,
width
);
this.leftPanelPuppet!.setWidth!(width); this.leftPanelPuppet!.setWidth!(width);
} }
} }
if (left !== undefined && left !== null) { if (left !== undefined && left !== null) {
await this.application.setPreference( await this.application.setPreference(PrefKey.EditorLeft, left);
PrefKey.EditorLeft,
left
);
this.rightPanelPuppet!.setLeft!(left); this.rightPanelPuppet!.setLeft!(left);
} }
this.application.sync(); this.application.sync();
@@ -918,7 +881,7 @@ class EditorViewCtrl extends PureViewCtrl<unknown, EditorState> {
await this.setState({ await this.setState({
monospaceFont, monospaceFont,
spellcheck, spellcheck,
marginResizersEnabled marginResizersEnabled,
}); });
if (!document.getElementById(ElementIds.EditorContent)) { if (!document.getElementById(ElementIds.EditorContent)) {
@@ -933,18 +896,12 @@ class EditorViewCtrl extends PureViewCtrl<unknown, EditorState> {
this.leftPanelPuppet?.ready && this.leftPanelPuppet?.ready &&
this.rightPanelPuppet?.ready this.rightPanelPuppet?.ready
) { ) {
const width = this.application.getPreference( const width = this.application.getPreference(PrefKey.EditorWidth, null);
PrefKey.EditorWidth,
null
);
if (width != null) { if (width != null) {
this.leftPanelPuppet!.setWidth!(width); this.leftPanelPuppet!.setWidth!(width);
this.rightPanelPuppet!.setWidth!(width); this.rightPanelPuppet!.setWidth!(width);
} }
const left = this.application.getPreference( const left = this.application.getPreference(PrefKey.EditorLeft, null);
PrefKey.EditorLeft,
null
);
if (left != null) { if (left != null) {
this.leftPanelPuppet!.setLeft!(left); this.leftPanelPuppet!.setLeft!(left);
this.rightPanelPuppet!.setLeft!(left); this.rightPanelPuppet!.setLeft!(left);
@@ -956,10 +913,7 @@ class EditorViewCtrl extends PureViewCtrl<unknown, EditorState> {
const root = document.querySelector(':root') as HTMLElement; const root = document.querySelector(':root') as HTMLElement;
const propertyName = '--sn-stylekit-editor-font-family'; const propertyName = '--sn-stylekit-editor-font-family';
if (this.state.monospaceFont) { if (this.state.monospaceFont) {
root.style.setProperty( root.style.setProperty(propertyName, 'var(--sn-stylekit-monospace-font)');
propertyName,
'var(--sn-stylekit-monospace-font)'
);
} else { } else {
root.style.setProperty( root.style.setProperty(
propertyName, propertyName,
@@ -970,12 +924,9 @@ class EditorViewCtrl extends PureViewCtrl<unknown, EditorState> {
async toggleWebPrefKey(key: PrefKey) { async toggleWebPrefKey(key: PrefKey) {
const currentValue = (this.state as any)[key]; const currentValue = (this.state as any)[key];
await this.application.setPreference( await this.application.setPreference(key, !currentValue);
key,
!currentValue,
);
await this.setState({ await this.setState({
[key]: !currentValue [key]: !currentValue,
}); });
this.reloadFont(); this.reloadFont();
@@ -984,7 +935,10 @@ class EditorViewCtrl extends PureViewCtrl<unknown, EditorState> {
await this.setState({ textareaUnloading: true }); await this.setState({ textareaUnloading: true });
await this.setState({ textareaUnloading: false }); await this.setState({ textareaUnloading: false });
this.reloadFont(); this.reloadFont();
} else if (key === PrefKey.EditorResizersEnabled && this.state[key] === true) { } else if (
key === PrefKey.EditorResizersEnabled &&
this.state[key] === true
) {
this.$timeout(() => { this.$timeout(() => {
this.leftPanelPuppet!.flash!(); this.leftPanelPuppet!.flash!();
this.rightPanelPuppet!.flash!(); this.rightPanelPuppet!.flash!();
@@ -995,12 +949,13 @@ class EditorViewCtrl extends PureViewCtrl<unknown, EditorState> {
/** @components */ /** @components */
registerComponentHandler() { registerComponentHandler() {
this.unregisterComponent = this.application.componentManager!.registerHandler({ this.unregisterComponent = this.application.componentManager!.registerHandler(
{
identifier: 'editor', identifier: 'editor',
areas: [ areas: [
ComponentArea.NoteTags, ComponentArea.NoteTags,
ComponentArea.EditorStack, ComponentArea.EditorStack,
ComponentArea.Editor ComponentArea.Editor,
], ],
contextRequestHandler: (componentUuid) => { contextRequestHandler: (componentUuid) => {
const currentEditor = this.state.editorComponent; const currentEditor = this.state.editorComponent;
@@ -1021,12 +976,12 @@ class EditorViewCtrl extends PureViewCtrl<unknown, EditorState> {
if (action === ComponentAction.SetSize) { if (action === ComponentAction.SetSize) {
const setSize = ( const setSize = (
element: HTMLElement, element: HTMLElement,
size: { width: string | number, height: string | number } size: { width: string | number; height: string | number }
) => { ) => {
const widthString = typeof size.width === 'string' const widthString =
? size.width typeof size.width === 'string' ? size.width : `${data.width}px`;
: `${data.width}px`; const heightString =
const heightString = typeof size.height === 'string' typeof size.height === 'string'
? size.height ? size.height
: `${data.height}px`; : `${data.height}px`;
element.setAttribute( element.setAttribute(
@@ -1039,22 +994,21 @@ class EditorViewCtrl extends PureViewCtrl<unknown, EditorState> {
const container = document.getElementById( const container = document.getElementById(
ElementIds.NoteTagsComponentContainer ElementIds.NoteTagsComponentContainer
); );
setSize(container!, { width: data.width!, height: data.height! }); setSize(container!, {
width: data.width!,
height: data.height!,
});
} }
} }
} } else if (action === ComponentAction.AssociateItem) {
else if (action === ComponentAction.AssociateItem) {
if (data.item!.content_type === ContentType.Tag) { if (data.item!.content_type === ContentType.Tag) {
const tag = this.application.findItem(data.item!.uuid) as SNTag; const tag = this.application.findItem(data.item!.uuid) as SNTag;
this.addTag(tag); this.addTag(tag);
} }
} } else if (action === ComponentAction.DeassociateItem) {
else if (action === ComponentAction.DeassociateItem) {
const tag = this.application.findItem(data.item!.uuid) as SNTag; const tag = this.application.findItem(data.item!.uuid) as SNTag;
this.removeTag(tag); this.removeTag(tag);
} else if ( } else if (action === ComponentAction.SaveSuccess) {
action === ComponentAction.SaveSuccess
) {
const savedUuid = data.item ? data.item.uuid : data.items![0].uuid; const savedUuid = data.item ? data.item.uuid : data.items![0].uuid;
if (savedUuid === this.note.uuid) { if (savedUuid === this.note.uuid) {
const selectedTag = this.appState.selectedTag; const selectedTag = this.appState.selectedTag;
@@ -1071,23 +1025,30 @@ class EditorViewCtrl extends PureViewCtrl<unknown, EditorState> {
} }
} }
} }
},
} }
}); );
} }
async reloadNoteTagsComponent() { async reloadNoteTagsComponent() {
const [tagsComponent] = const [
this.application.componentManager!.componentsForArea(ComponentArea.NoteTags); tagsComponent,
] = this.application.componentManager!.componentsForArea(
ComponentArea.NoteTags
);
await this.setState({ await this.setState({
tagsComponent: tagsComponent?.active ? tagsComponent : undefined tagsComponent: tagsComponent?.active ? tagsComponent : undefined,
}); });
this.application.componentManager!.contextItemDidChangeInArea(ComponentArea.NoteTags); this.application.componentManager!.contextItemDidChangeInArea(
ComponentArea.NoteTags
);
} }
async reloadStackComponents() { async reloadStackComponents() {
const stackComponents = sortAlphabetically( const stackComponents = sortAlphabetically(
this.application.componentManager!.componentsForArea(ComponentArea.EditorStack) this.application
.filter(component => component.active) .componentManager!.componentsForArea(ComponentArea.EditorStack)
.filter((component) => component.active)
); );
if (this.note) { if (this.note) {
for (const component of stackComponents) { for (const component of stackComponents) {
@@ -1100,7 +1061,9 @@ class EditorViewCtrl extends PureViewCtrl<unknown, EditorState> {
} }
} }
await this.setState({ stackComponents }); await this.setState({ stackComponents });
this.application.componentManager!.contextItemDidChangeInArea(ComponentArea.EditorStack); this.application.componentManager!.contextItemDidChangeInArea(
ComponentArea.EditorStack
);
} }
stackComponentHidden(component: SNComponent) { stackComponentHidden(component: SNComponent) {
@@ -1108,11 +1071,15 @@ class EditorViewCtrl extends PureViewCtrl<unknown, EditorState> {
} }
async toggleStackComponentForCurrentItem(component: SNComponent) { async toggleStackComponentForCurrentItem(component: SNComponent) {
const hidden = this.application.componentManager!.isComponentHidden(component); const hidden = this.application.componentManager!.isComponentHidden(
component
);
if (hidden || !component.active) { if (hidden || !component.active) {
this.application.componentManager!.setComponentHidden(component, false); this.application.componentManager!.setComponentHidden(component, false);
await this.associateComponentWithCurrentNote(component); await this.associateComponentWithCurrentNote(component);
this.application.componentManager!.contextItemDidChangeInArea(ComponentArea.EditorStack); this.application.componentManager!.contextItemDidChangeInArea(
ComponentArea.EditorStack
);
} else { } else {
this.application.componentManager!.setComponentHidden(component, true); this.application.componentManager!.setComponentHidden(component, true);
await this.disassociateComponentWithCurrentNote(component); await this.disassociateComponentWithCurrentNote(component);
@@ -1139,28 +1106,27 @@ class EditorViewCtrl extends PureViewCtrl<unknown, EditorState> {
} }
registerKeyboardShortcuts() { registerKeyboardShortcuts() {
this.removeAltKeyObserver = this.application.getKeyboardService().addKeyObserver({ this.removeAltKeyObserver = this.application
modifiers: [ .getKeyboardService()
KeyboardModifier.Alt .addKeyObserver({
], modifiers: [KeyboardModifier.Alt],
onKeyDown: () => { onKeyDown: () => {
this.setState({ this.setState({
altKeyDown: true altKeyDown: true,
}); });
}, },
onKeyUp: () => { onKeyUp: () => {
this.setState({ this.setState({
altKeyDown: false altKeyDown: false,
}); });
} },
}); });
this.removeTrashKeyObserver = this.application.getKeyboardService().addKeyObserver({ this.removeTrashKeyObserver = this.application
.getKeyboardService()
.addKeyObserver({
key: KeyboardKey.Backspace, key: KeyboardKey.Backspace,
notElementIds: [ notElementIds: [ElementIds.NoteTextEditor, ElementIds.NoteTitleEditor],
ElementIds.NoteTextEditor,
ElementIds.NoteTitleEditor
],
modifiers: [KeyboardModifier.Meta], modifiers: [KeyboardModifier.Meta],
onKeyDown: () => { onKeyDown: () => {
this.deleteNote(false); this.deleteNote(false);
@@ -1178,8 +1144,12 @@ class EditorViewCtrl extends PureViewCtrl<unknown, EditorState> {
* If the shift key is pressed first, this event is * If the shift key is pressed first, this event is
* not fired. * not fired.
*/ */
const editor = document.getElementById(ElementIds.NoteTextEditor)! as HTMLInputElement; const editor = document.getElementById(
this.removeTabObserver = this.application.getKeyboardService().addKeyObserver({ ElementIds.NoteTextEditor
)! as HTMLInputElement;
this.removeTabObserver = this.application
.getKeyboardService()
.addKeyObserver({
element: editor, element: editor,
key: KeyboardKey.Tab, key: KeyboardKey.Tab,
onKeyDown: (event) => { onKeyDown: (event) => {
@@ -1199,8 +1169,10 @@ class EditorViewCtrl extends PureViewCtrl<unknown, EditorState> {
const end = editor.selectionEnd!; const end = editor.selectionEnd!;
const spaces = ' '; const spaces = ' ';
/** Insert 4 spaces */ /** Insert 4 spaces */
editor.value = editor.value.substring(0, start) editor.value =
+ spaces + editor.value.substring(end); editor.value.substring(0, start) +
spaces +
editor.value.substring(end);
/** Place cursor 4 spaces away from where the tab key was pressed */ /** Place cursor 4 spaces away from where the tab key was pressed */
editor.selectionStart = editor.selectionEnd = start + 4; editor.selectionStart = editor.selectionEnd = start + 4;
} }
@@ -1226,7 +1198,7 @@ export class EditorView extends WebDirective {
this.restrict = 'E'; this.restrict = 'E';
this.scope = { this.scope = {
editor: '=', editor: '=',
application: '=' application: '=',
}; };
this.template = template; this.template = template;
this.replace = true; this.replace = true;