refactor: new snjs support (#967)

This commit is contained in:
Mo
2022-04-11 12:48:19 -05:00
committed by GitHub
parent 3126d97dca
commit 3a2ff2f440
44 changed files with 569 additions and 799 deletions

View File

@@ -1,7 +1,7 @@
import { observer } from 'mobx-react-lite';
import { AppState } from '@/ui_models/app_state';
import { WebApplication } from '@/ui_models/application';
import { User as UserType } from '@standardnotes/responses';
import { User as UserType } from '@standardnotes/snjs';
type Props = {
appState: AppState;

View File

@@ -169,20 +169,18 @@ export const AttachedFilesPopover: FunctionComponent<Props> = observer(
</div>
) : null}
{filteredList.length > 0 ? (
filteredList
.filter((file) => !file.deleted)
.map((file: SNFile) => {
return (
<PopoverFileItem
key={file.uuid}
file={file}
isAttachedToNote={attachedFiles.includes(file)}
handleFileAction={handleFileAction}
getIconType={application.iconsController.getIconForFileType}
closeOnBlur={closeOnBlur}
/>
);
})
filteredList.map((file: SNFile) => {
return (
<PopoverFileItem
key={file.uuid}
file={file}
isAttachedToNote={attachedFiles.includes(file)}
handleFileAction={handleFileAction}
getIconType={application.iconsController.getIconForFileType}
closeOnBlur={closeOnBlur}
/>
);
})
) : (
<div className="flex flex-col items-center justify-center w-full py-8">
<div className="w-18 h-18 mb-2">

View File

@@ -226,10 +226,7 @@ export class Footer extends PureComponent<Props, State> {
this.application.items.setDisplayOptions(
ContentType.Theme,
CollectionSort.Title,
'asc',
(theme: ItemInterface) => {
return !theme.errorDecrypting;
}
'asc'
);
}

View File

@@ -281,7 +281,7 @@ export class NoteView extends PureComponent<Props, State> {
});
}
if (!note.deleted && note.locked !== this.state.noteLocked) {
if (note.locked !== this.state.noteLocked) {
this.setState({
noteLocked: note.locked,
});
@@ -421,7 +421,7 @@ export class NoteView extends PureComponent<Props, State> {
streamItems() {
this.removeComponentStreamObserver = this.application.streamItems(
ContentType.Component,
async (_items, source) => {
async ({ source }) => {
if (
isPayloadSourceInternalChange(source) ||
source === PayloadSource.InitialObserverRegistrationPush
@@ -1003,7 +1003,7 @@ export class NoteView extends PureComponent<Props, State> {
)}
</div>
{this.note && !this.note.errorDecrypting && (
{this.note && (
<div id="editor-title-bar" className="section-title-bar w-full">
<div className="flex items-center justify-between h-8">
<div
@@ -1089,165 +1089,127 @@ export class NoteView extends PureComponent<Props, State> {
</div>
)}
{!this.note.errorDecrypting && (
<div
id={ElementIds.EditorContent}
className={ElementIds.EditorContent}
ref={this.editorContentRef}
>
{this.state.marginResizersEnabled &&
this.editorContentRef.current ? (
<PanelResizer
minWidth={300}
hoverable={true}
collapsable={false}
panel={this.editorContentRef.current}
side={PanelSide.Left}
type={PanelResizeType.OffsetAndWidth}
left={this.state.leftResizerOffset}
width={this.state.leftResizerWidth}
resizeFinishCallback={this.onPanelResizeFinish}
/>
) : null}
<div
id={ElementIds.EditorContent}
className={ElementIds.EditorContent}
ref={this.editorContentRef}
>
{this.state.marginResizersEnabled &&
this.editorContentRef.current ? (
<PanelResizer
minWidth={300}
hoverable={true}
collapsable={false}
panel={this.editorContentRef.current}
side={PanelSide.Left}
type={PanelResizeType.OffsetAndWidth}
left={this.state.leftResizerOffset}
width={this.state.leftResizerWidth}
resizeFinishCallback={this.onPanelResizeFinish}
/>
) : null}
{this.state.editorComponentViewer && (
<div className="component-view">
<ComponentView
componentViewer={this.state.editorComponentViewer}
onLoad={this.onEditorComponentLoad}
requestReload={this.editorComponentViewerRequestsReload}
application={this.application}
appState={this.appState}
/>
</div>
{this.state.editorComponentViewer && (
<div className="component-view">
<ComponentView
componentViewer={this.state.editorComponentViewer}
onLoad={this.onEditorComponentLoad}
requestReload={this.editorComponentViewerRequestsReload}
application={this.application}
appState={this.appState}
/>
</div>
)}
{this.state.editorStateDidLoad &&
!this.state.editorComponentViewer &&
!this.state.textareaUnloading && (
<textarea
autocomplete="off"
className="editable font-editor"
dir="auto"
id={ElementIds.NoteTextEditor}
onChange={this.onTextAreaChange}
value={this.state.editorText}
readonly={this.state.noteLocked}
onFocus={this.onContentFocus}
spellcheck={this.state.spellcheck}
ref={(ref) => this.onSystemEditorLoad(ref)}
></textarea>
)}
{this.state.editorStateDidLoad &&
!this.state.editorComponentViewer &&
!this.state.textareaUnloading && (
<textarea
autocomplete="off"
className="editable font-editor"
dir="auto"
id={ElementIds.NoteTextEditor}
onChange={this.onTextAreaChange}
value={this.state.editorText}
readonly={this.state.noteLocked}
onFocus={this.onContentFocus}
spellcheck={this.state.spellcheck}
ref={(ref) => this.onSystemEditorLoad(ref)}
></textarea>
)}
{this.state.marginResizersEnabled &&
this.editorContentRef.current ? (
<PanelResizer
minWidth={300}
hoverable={true}
collapsable={false}
panel={this.editorContentRef.current}
side={PanelSide.Right}
type={PanelResizeType.OffsetAndWidth}
left={this.state.rightResizerOffset}
width={this.state.rightResizerWidth}
resizeFinishCallback={this.onPanelResizeFinish}
/>
) : null}
</div>
{this.state.marginResizersEnabled &&
this.editorContentRef.current ? (
<PanelResizer
minWidth={300}
hoverable={true}
collapsable={false}
panel={this.editorContentRef.current}
side={PanelSide.Right}
type={PanelResizeType.OffsetAndWidth}
left={this.state.rightResizerOffset}
width={this.state.rightResizerWidth}
resizeFinishCallback={this.onPanelResizeFinish}
/>
) : null}
</div>
)}
{this.note.errorDecrypting && (
<div className="section">
<div id="error-decrypting-container" className="sn-component">
<div id="error-decrypting-panel" className="sk-panel">
<div className="sk-panel-header">
<div className="sk-panel-header-title">
{this.note.waitingForKey
? 'Waiting for Key'
: 'Unable to Decrypt'}
</div>
</div>
<div className="sk-panel-content">
<div className="sk-panel-section">
{this.note.waitingForKey && (
<p className="sk-p">
This note is awaiting its encryption key to be ready.
Please wait for syncing to complete for this note to
be decrypted.
</p>
)}
{!this.note.waitingForKey && (
<p className="sk-p">
There was an error decrypting this item. Ensure you
are running the latest version of this app, then sign
out and sign back in to try again.
</p>
)}
</div>
</div>
</div>
</div>
</div>
)}
{!this.note.errorDecrypting && (
<div id="editor-pane-component-stack">
{this.state.availableStackComponents.length > 0 && (
<div
id="component-stack-menu-bar"
className="sk-app-bar no-edges"
>
<div className="left">
{this.state.availableStackComponents.map((component) => {
return (
<div
key={component.uuid}
onClick={() => {
this.toggleStackComponent(component);
}}
className="sk-app-bar-item"
>
<div className="sk-app-bar-item-column">
<div
className={
(this.stackComponentExpanded(component) &&
component.active
? 'info '
: '') +
(!this.stackComponentExpanded(component)
? 'neutral '
: '') +
' sk-circle small'
}
/>
</div>
<div className="sk-app-bar-item-column">
<div className="sk-label">{component.name}</div>
</div>
<div id="editor-pane-component-stack">
{this.state.availableStackComponents.length > 0 && (
<div
id="component-stack-menu-bar"
className="sk-app-bar no-edges"
>
<div className="left">
{this.state.availableStackComponents.map((component) => {
return (
<div
key={component.uuid}
onClick={() => {
this.toggleStackComponent(component);
}}
className="sk-app-bar-item"
>
<div className="sk-app-bar-item-column">
<div
className={
(this.stackComponentExpanded(component) &&
component.active
? 'info '
: '') +
(!this.stackComponentExpanded(component)
? 'neutral '
: '') +
' sk-circle small'
}
/>
</div>
);
})}
</div>
<div className="sk-app-bar-item-column">
<div className="sk-label">{component.name}</div>
</div>
</div>
);
})}
</div>
)}
<div className="sn-component">
{this.state.stackComponentViewers.map((viewer) => {
return (
<div className="component-view component-stack-item">
<ComponentView
key={viewer.identifier}
componentViewer={viewer}
manualDealloc={true}
application={this.application}
appState={this.appState}
/>
</div>
);
})}
</div>
)}
<div className="sn-component">
{this.state.stackComponentViewers.map((viewer) => {
return (
<div className="component-view component-stack-item">
<ComponentView
key={viewer.identifier}
componentViewer={viewer}
manualDealloc={true}
application={this.application}
appState={this.appState}
/>
</div>
);
})}
</div>
)}
</div>
</div>
</div>
);

View File

@@ -1,6 +1,7 @@
import { WebApplication } from '@/ui_models/application';
import {
CollectionSort,
CollectionSortProperty,
sanitizeHtmlString,
SNNote,
} from '@standardnotes/snjs';
@@ -18,7 +19,7 @@ type Props = {
onClick: () => void;
onContextMenu: (e: MouseEvent) => void;
selected: boolean;
sortedBy?: CollectionSort;
sortedBy?: CollectionSortProperty;
};
type NoteFlag = {
@@ -34,25 +35,7 @@ const flagsForNote = (note: SNNote) => {
class: 'danger',
});
}
if (note.errorDecrypting) {
if (note.waitingForKey) {
flags.push({
text: 'Waiting For Keys',
class: 'info',
});
} else {
flags.push({
text: 'Missing Keys',
class: 'danger',
});
}
}
if (note.deleted) {
flags.push({
text: 'Deletion Pending Sync',
class: 'danger',
});
}
return flags;
};

View File

@@ -1,5 +1,9 @@
import { WebApplication } from '@/ui_models/application';
import { CollectionSort, PrefKey } from '@standardnotes/snjs';
import {
CollectionSort,
CollectionSortProperty,
PrefKey,
} from '@standardnotes/snjs';
import { observer } from 'mobx-react-lite';
import { FunctionComponent } from 'preact';
import { useState } from 'preact/hooks';
@@ -52,7 +56,7 @@ export const NotesListOptionsMenu: FunctionComponent<Props> = observer(
setSortReverse(!sortReverse);
};
const toggleSortBy = (sort: CollectionSort) => {
const toggleSortBy = (sort: CollectionSortProperty) => {
if (sortBy === sort) {
toggleSortReverse();
} else {

View File

@@ -104,7 +104,7 @@ const ListedActionsMenu: FunctionComponent<ListedActionsMenuProps> = ({
const updatedGroup: ListedMenuGroup = {
name: updatedAccountInfo.display_name,
account: group.account,
actions: updatedAccountInfo.actions,
actions: updatedAccountInfo.actions as Action[],
};
const updatedGroups = menuGroups.map((group) => {
@@ -145,7 +145,7 @@ const ListedActionsMenu: FunctionComponent<ListedActionsMenuProps> = ({
menuGroups.push({
name: accountInfo.display_name,
account,
actions: accountInfo.actions,
actions: accountInfo.actions as Action[],
});
} else {
menuGroups.push({

View File

@@ -219,7 +219,6 @@ export const NotesOptions = observer(
const notTrashed = notes.some((note) => !note.trashed);
const pinned = notes.some((note) => note.pinned);
const unpinned = notes.some((note) => !note.pinned);
const errored = notes.some((note) => note.errorDecrypting);
useEffect(() => {
const removeAltKeyObserver = application.io.addKeyObserver({
@@ -278,26 +277,6 @@ export const NotesOptions = observer(
});
};
if (errored) {
return (
<>
{notes.length === 1 ? (
<div className="px-3 pt-1.5 pb-1 text-xs color-neutral font-medium">
<div>
<span className="font-semibold">Note ID:</span> {notes[0].uuid}
</div>
</div>
) : null}
<DeletePermanentlyButton
closeOnBlur={closeOnBlur}
onClick={async () => {
await appState.notes.deleteNotesPermanently();
}}
/>
</>
);
}
const openRevisionHistoryModal = () => {
appState.notes.setShowRevisionHistoryModal(true);
};

View File

@@ -86,7 +86,7 @@ export const ChangeEditorMenu: FunctionComponent<ChangeEditorMenuProps> = ({
) => {
if (component) {
if (component.conflictOf) {
application.mutator.changeAndSaveItem(component.uuid, (mutator) => {
application.mutator.changeAndSaveItem(component, (mutator) => {
mutator.conflictOf = undefined;
});
}

View File

@@ -1,11 +1,13 @@
import { WebApplication } from '@/ui_models/application';
import {
ContentType,
FeatureStatus,
SNComponent,
ComponentArea,
FeatureDescription,
GetFeatures,
NoteType,
} from '@standardnotes/features';
import { ContentType, FeatureStatus, SNComponent } from '@standardnotes/snjs';
} from '@standardnotes/snjs';
import { EditorMenuItem, EditorMenuGroup } from '../ChangeEditorOption';
export const PLAIN_EDITOR_NAME = 'Plain Editor';

View File

@@ -1,12 +1,6 @@
import { action, makeAutoObservable, observable } from 'mobx';
import { ExtensionsLatestVersions } from '@/components/Preferences/panes/extensions-segments';
import {
ComponentArea,
ContentType,
FeatureIdentifier,
SNComponent,
IconType,
} from '@standardnotes/snjs';
import { FeatureIdentifier, IconType } from '@standardnotes/snjs';
import { WebApplication } from '@/ui_models/application';
const PREFERENCE_IDS = [
@@ -61,7 +55,6 @@ const READY_PREFERENCES_MENU_ITEMS: PreferencesMenuItem[] = [
export class PreferencesMenu {
private _selectedPane: PreferenceId | FeatureIdentifier = 'account';
private _extensionPanes: SNComponent[] = [];
private _menu: PreferencesMenuItem[];
private _extensionLatestVersions: ExtensionsLatestVersions =
new ExtensionsLatestVersions(new Map());
@@ -74,7 +67,6 @@ export class PreferencesMenu {
? PREFERENCES_MENU_ITEMS
: READY_PREFERENCES_MENU_ITEMS;
this.loadExtensionsPanes();
this.loadLatestVersions();
makeAutoObservable<
@@ -105,64 +97,24 @@ export class PreferencesMenu {
return this._extensionLatestVersions;
}
loadExtensionsPanes(): void {
const excludedComponents = [
FeatureIdentifier.TwoFactorAuthManager,
'org.standardnotes.batch-manager',
'org.standardnotes.extensions-manager',
FeatureIdentifier.CloudLink,
];
this._extensionPanes = (
this.application.items.getItems([
ContentType.ActionsExtension,
ContentType.Component,
ContentType.Theme,
]) as SNComponent[]
).filter(
(extension) =>
extension.area === ComponentArea.Modal &&
!excludedComponents.includes(extension.package_info.identifier)
);
}
get menuItems(): SelectableMenuItem[] {
const menuItems = this._menu.map((preference) => ({
...preference,
selected: preference.id === this._selectedPane,
}));
const extensionsMenuItems: SelectableMenuItem[] = this._extensionPanes.map(
(extension) => {
return {
icon: 'window',
id: extension.package_info.identifier,
label: extension.name,
selected: extension.package_info.identifier === this._selectedPane,
};
}
);
return menuItems.concat(extensionsMenuItems);
return menuItems;
}
get selectedMenuItem(): PreferencesMenuItem | undefined {
return this._menu.find((item) => item.id === this._selectedPane);
}
get selectedExtension(): SNComponent | undefined {
return this._extensionPanes.find(
(extension) => extension.package_info.identifier === this._selectedPane
);
}
get selectedPaneId(): PreferenceId | FeatureIdentifier {
if (this.selectedMenuItem != undefined) {
return this.selectedMenuItem.id;
}
if (this.selectedExtension != undefined) {
return this.selectedExtension.package_info.identifier;
}
return 'account';
}

View File

@@ -1,6 +1,8 @@
import { RoundIconButton } from '@/components/RoundIconButton';
import { TitleBar, Title } from '@/components/TitleBar';
import { FunctionComponent } from 'preact';
import { observer } from 'mobx-react-lite';
import {
AccountPreferences,
HelpAndFeedback,
@@ -8,15 +10,12 @@ import {
General,
Security,
} from './panes';
import { observer } from 'mobx-react-lite';
import { PreferencesMenu } from './PreferencesMenu';
import { PreferencesMenuView } from './PreferencesMenuView';
import { WebApplication } from '@/ui_models/application';
import { MfaProps } from './panes/two-factor-auth/MfaProps';
import { AppState } from '@/ui_models/app_state';
import { useEffect, useMemo } from 'preact/hooks';
import { ExtensionPane } from './panes/ExtensionPane';
import { Backups } from '@/components/Preferences/panes/Backups';
import { Appearance } from './panes/Appearance';
@@ -66,24 +65,13 @@ const PaneSelector: FunctionComponent<
case 'help-feedback':
return <HelpAndFeedback />;
default:
if (menu.selectedExtension != undefined) {
return (
<ExtensionPane
application={application}
appState={appState}
extension={menu.selectedExtension}
preferencesMenu={menu}
/>
);
} else {
return (
<General
appState={appState}
application={application}
extensionsLatestVersions={menu.extensionsLatestVersions}
/>
);
}
return (
<General
appState={appState}
application={application}
extensionsLatestVersions={menu.extensionsLatestVersions}
/>
);
}
});

View File

@@ -4,12 +4,12 @@ import { sortThemes } from '@/components/QuickSettingsMenu/QuickSettingsMenu';
import { HorizontalSeparator } from '@/components/Shared/HorizontalSeparator';
import { Switch } from '@/components/Switch';
import { WebApplication } from '@/ui_models/application';
import { GetFeatures } from '@standardnotes/features';
import {
ContentType,
FeatureIdentifier,
FeatureStatus,
PrefKey,
GetFeatures,
SNTheme,
} from '@standardnotes/snjs';
import { observer } from 'mobx-react-lite';
@@ -61,9 +61,8 @@ export const Appearance: FunctionComponent<Props> = observer(
);
useEffect(() => {
const themesAsItems: DropdownItem[] = (
application.items.getDisplayableItems(ContentType.Theme) as SNTheme[]
)
const themesAsItems: DropdownItem[] = application.items
.getDisplayableItems<SNTheme>(ContentType.Theme)
.filter((theme) => !theme.isLayerable())
.sort(sortThemes)
.map((theme) => {

View File

@@ -1,79 +0,0 @@
import {
PreferencesGroup,
PreferencesSegment,
} from '@/components/Preferences/components';
import { WebApplication } from '@/ui_models/application';
import { ComponentViewer, SNComponent } from '@standardnotes/snjs';
import { FeatureIdentifier } from '@standardnotes/features';
import { observer } from 'mobx-react-lite';
import { FunctionComponent } from 'preact';
import { ExtensionItem } from './extensions-segments';
import { ComponentView } from '@/components/ComponentView';
import { AppState } from '@/ui_models/app_state';
import { PreferencesMenu } from '@/components/Preferences/PreferencesMenu';
import { useEffect, useState } from 'preact/hooks';
interface IProps {
application: WebApplication;
appState: AppState;
extension: SNComponent;
preferencesMenu: PreferencesMenu;
}
const urlOverrideForExtension = (extension: SNComponent) => {
if (extension.identifier === FeatureIdentifier.CloudLink) {
return 'https://extensions.standardnotes.org/components/cloudlink';
} else {
return undefined;
}
};
export const ExtensionPane: FunctionComponent<IProps> = observer(
({ extension, application, appState, preferencesMenu }) => {
const [componentViewer] = useState<ComponentViewer>(
application.componentManager.createComponentViewer(
extension,
undefined,
undefined,
urlOverrideForExtension(extension)
)
);
const latestVersion =
preferencesMenu.extensionsLatestVersions.getVersion(extension);
useEffect(() => {
return () => {
application.componentManager.destroyComponentViewer(componentViewer);
};
}, [application, componentViewer]);
return (
<div className="preferences-extension-pane color-foreground flex-grow flex flex-row overflow-y-auto min-h-0">
<div className="flex-grow flex flex-col py-6 items-center">
<div className="w-200 max-w-200 flex flex-col">
<PreferencesGroup>
<ExtensionItem
application={application}
extension={extension}
first={false}
uninstall={() =>
application.mutator
.deleteItem(extension)
.then(() => preferencesMenu.loadExtensionsPanes())
}
latestVersion={latestVersion}
/>
<PreferencesSegment>
<ComponentView
application={application}
appState={appState}
componentViewer={componentViewer}
/>
</PreferencesSegment>
</PreferencesGroup>
</div>
</div>
</div>
);
}
);

View File

@@ -13,10 +13,11 @@ import { useEffect, useRef, useState } from 'preact/hooks';
import { observer } from 'mobx-react-lite';
const loadExtensions = (application: WebApplication) =>
application.items.getItems(
[ContentType.ActionsExtension, ContentType.Component, ContentType.Theme],
true
) as SNComponent[];
application.items.getItems([
ContentType.ActionsExtension,
ContentType.Component,
ContentType.Theme,
]) as SNComponent[];
export const Extensions: FunctionComponent<{
application: WebApplication;

View File

@@ -13,16 +13,16 @@ import {
Text,
Title,
} from '../../components';
import {
EmailBackupFrequency,
MuteFailedBackupsEmailsOption,
SettingName,
} from '@standardnotes/settings';
import { Dropdown, DropdownItem } from '@/components/Dropdown';
import { Switch } from '@/components/Switch';
import { HorizontalSeparator } from '@/components/Shared/HorizontalSeparator';
import { FeatureIdentifier } from '@standardnotes/features';
import { FeatureStatus } from '@standardnotes/snjs';
import {
FeatureStatus,
FeatureIdentifier,
EmailBackupFrequency,
MuteFailedBackupsEmailsOption,
SettingName,
} from '@standardnotes/snjs';
type Props = {
application: WebApplication;

View File

@@ -1,11 +1,12 @@
import { useCallback, useEffect, useState } from 'preact/hooks';
import { ButtonType, SettingName } from '@standardnotes/snjs';
import {
ButtonType,
SettingName,
CloudProvider,
DropboxBackupFrequency,
GoogleDriveBackupFrequency,
OneDriveBackupFrequency,
} from '@standardnotes/settings';
} from '@standardnotes/snjs';
import { WebApplication } from '@/ui_models/application';
import { Button } from '@/components/Button';
import { isDev, openInNewTab } from '@/utils';

View File

@@ -9,14 +9,15 @@ import {
Title,
} from '@/components/Preferences/components';
import { HorizontalSeparator } from '@/components/Shared/HorizontalSeparator';
import { FeatureIdentifier } from '@standardnotes/features';
import { FeatureStatus } from '@standardnotes/snjs';
import { FunctionComponent } from 'preact';
import {
FeatureStatus,
FeatureIdentifier,
CloudProvider,
MuteFailedCloudBackupsEmailsOption,
SettingName,
} from '@standardnotes/settings';
} from '@standardnotes/snjs';
import { FunctionComponent } from 'preact';
import { Switch } from '@/components/Switch';
import { convertStringifiedBooleanToBoolean } from '@/utils';
import { STRING_FAILED_TO_UPDATE_USER_SETTING } from '@/strings';

View File

@@ -1,4 +1,4 @@
import { displayStringForContentType, SNComponent } from '@standardnotes/snjs';
import { DisplayStringForContentType, SNComponent } from '@standardnotes/snjs';
import { Button } from '@/components/Button';
import { FunctionComponent } from 'preact';
import { Title, Text, Subtitle, PreferencesSegment } from '../../components';
@@ -30,7 +30,7 @@ export const ConfirmCustomExtension: FunctionComponent<{
},
{
label: 'Extension Type',
value: displayStringForContentType(component.content_type),
value: DisplayStringForContentType(component.content_type),
},
];

View File

@@ -47,7 +47,7 @@ export const ExtensionItem: FunctionComponent<ExtensionItemProps> = ({
const newOfflineOnly = !offlineOnly;
setOfflineOnly(newOfflineOnly);
application.mutator
.changeAndSaveItem(extension.uuid, (m: any) => {
.changeAndSaveItem(extension, (m: any) => {
if (m.content == undefined) m.content = {};
m.content.offlineOnly = newOfflineOnly;
})
@@ -63,7 +63,7 @@ export const ExtensionItem: FunctionComponent<ExtensionItemProps> = ({
const changeExtensionName = (newName: string) => {
setExtensionName(newName);
application.mutator
.changeAndSaveItem(extension.uuid, (m: any) => {
.changeAndSaveItem(extension, (m: any) => {
if (m.content == undefined) m.content = {};
m.content.name = newName;
})

View File

@@ -1,6 +1,9 @@
import { WebApplication } from '@/ui_models/application';
import { FeatureDescription } from '@standardnotes/features';
import { SNComponent, ClientDisplayableError } from '@standardnotes/snjs';
import {
SNComponent,
ClientDisplayableError,
FeatureDescription,
} from '@standardnotes/snjs';
import { makeAutoObservable, observable } from 'mobx';
export class ExtensionsLatestVersions {

View File

@@ -34,7 +34,7 @@ const makeEditorDefault = (
if (currentDefault) {
removeEditorDefault(application, currentDefault);
}
application.mutator.changeAndSaveItem(component.uuid, (m) => {
application.mutator.changeAndSaveItem(component, (m) => {
const mutator = m as ComponentMutator;
mutator.defaultEditor = true;
});
@@ -44,7 +44,7 @@ const removeEditorDefault = (
application: WebApplication,
component: SNComponent
) => {
application.mutator.changeAndSaveItem(component.uuid, (m) => {
application.mutator.changeAndSaveItem(component, (m) => {
const mutator = m as ComponentMutator;
mutator.defaultEditor = false;
});

View File

@@ -1,4 +1,3 @@
import { FindNativeFeature } from '@standardnotes/features';
import { Switch } from '@/components/Switch';
import {
PreferencesGroup,
@@ -8,7 +7,11 @@ import {
Title,
} from '@/components/Preferences/components';
import { WebApplication } from '@/ui_models/application';
import { FeatureIdentifier, FeatureStatus } from '@standardnotes/snjs';
import {
FeatureIdentifier,
FeatureStatus,
FindNativeFeature,
} from '@standardnotes/snjs';
import { FunctionComponent } from 'preact';
import { useCallback, useEffect, useState } from 'preact/hooks';
import { usePremiumModal } from '@/components/Premium';

View File

@@ -12,7 +12,7 @@ import {
MuteSignInEmailsOption,
LogSessionUserAgentOption,
SettingName,
} from '@standardnotes/settings';
} from '@standardnotes/snjs';
import { observer } from 'mobx-react-lite';
import { FunctionalComponent } from 'preact';
import { useCallback, useEffect, useState } from 'preact/hooks';

View File

@@ -103,15 +103,15 @@ export const QuickSettingsMenu: FunctionComponent<MenuProps> = observer(
}, [focusModeEnabled]);
const reloadThemes = useCallback(() => {
const themes = (
application.items.getDisplayableItems(ContentType.Theme) as SNTheme[]
).map((item) => {
return {
name: item.name,
identifier: item.identifier,
component: item,
};
}) as ThemeItem[];
const themes = application.items
.getDisplayableItems<SNTheme>(ContentType.Theme)
.map((item) => {
return {
name: item.name,
identifier: item.identifier,
component: item,
};
}) as ThemeItem[];
GetFeatures()
.filter(
@@ -140,17 +140,15 @@ export const QuickSettingsMenu: FunctionComponent<MenuProps> = observer(
}, [application]);
const reloadToggleableComponents = useCallback(() => {
const toggleableComponents = (
application.items.getDisplayableItems(
ContentType.Component
) as SNComponent[]
).filter(
(component) =>
[ComponentArea.EditorStack, ComponentArea.TagsList].includes(
component.area
) &&
component.identifier !== FeatureIdentifier.DeprecatedFoldersComponent
);
const toggleableComponents = application.items
.getDisplayableItems<SNComponent>(ContentType.Component)
.filter(
(component) =>
[ComponentArea.EditorStack].includes(component.area) &&
component.identifier !==
FeatureIdentifier.DeprecatedFoldersComponent
);
setToggleableComponents(toggleableComponents);
}, [application]);

View File

@@ -134,7 +134,7 @@ export const HistoryListContainer: FunctionComponent<Props> = observer(
throw new Error('Could not fetch revision');
}
setSelectedRevision(response.item as HistoryEntry);
setSelectedRevision(response.item as unknown as HistoryEntry);
} catch (error) {
console.error(error);
setSelectedRevision(undefined);
@@ -165,7 +165,7 @@ export const HistoryListContainer: FunctionComponent<Props> = observer(
try {
const remoteRevision =
await application.historyManager.fetchRemoteRevision(
note.uuid,
note,
revisionListEntry
);
setSelectedRevision(remoteRevision);
@@ -182,7 +182,7 @@ export const HistoryListContainer: FunctionComponent<Props> = observer(
},
[
application,
note.uuid,
note,
setIsFetchingSelectedRevision,
setSelectedRemoteEntry,
setSelectedRevision,

View File

@@ -8,7 +8,6 @@ import {
ButtonType,
ContentType,
HistoryEntry,
PayloadContent,
PayloadSource,
RevisionListEntry,
SNNote,
@@ -148,7 +147,7 @@ export const RevisionHistoryModal: FunctionComponent<RevisionHistoryModalProps>
}).then((confirmed) => {
if (confirmed) {
application.mutator.changeAndSaveItem(
selectedRevision.payload.uuid,
originalNote,
(mutator) => {
mutator.unsafe_setCustomContent(
selectedRevision.payload.content
@@ -165,14 +164,14 @@ export const RevisionHistoryModal: FunctionComponent<RevisionHistoryModalProps>
const restoreAsCopy = async () => {
if (selectedRevision) {
const originalNote = application.items.findItem(
const originalNote = application.items.findSureItem<SNNote>(
selectedRevision.payload.uuid
) as SNNote;
);
const duplicatedItem = await application.mutator.duplicateItem(
originalNote,
{
...(selectedRevision.payload.content as PayloadContent),
...selectedRevision.payload.content,
title: selectedRevision.payload.content.title
? selectedRevision.payload.content.title + ' (copy)'
: undefined,
@@ -188,10 +187,10 @@ export const RevisionHistoryModal: FunctionComponent<RevisionHistoryModalProps>
useEffect(() => {
const fetchTemplateNote = async () => {
if (selectedRevision) {
const newTemplateNote = (await application.mutator.createTemplateItem(
const newTemplateNote = application.mutator.createTemplateItem(
ContentType.Note,
selectedRevision.payload.content
)) as SNNote;
) as SNNote;
setTemplateNoteForRevision(newTemplateNote);
}
@@ -218,7 +217,7 @@ export const RevisionHistoryModal: FunctionComponent<RevisionHistoryModalProps>
setIsDeletingRevision(true);
application.historyManager
.deleteRemoteRevision(note.uuid, selectedRemoteEntry)
.deleteRemoteRevision(note, selectedRemoteEntry)
.then((res) => {
if (res.error?.message) {
throw new Error(res.error.message);

View File

@@ -4,7 +4,7 @@ import {
PayloadSource,
SNNote,
ComponentViewer,
PayloadContent,
NoteContent,
} from '@standardnotes/snjs';
import { confirmDialog } from '@/services/alertService';
import { STRING_RESTORE_LOCKED_ATTEMPT } from '@/strings';
@@ -13,7 +13,7 @@ import { ComponentView } from './ComponentView';
interface Props {
application: WebApplication;
content: PayloadContent;
content: NoteContent;
title?: string;
uuid: string;
}
@@ -74,7 +74,7 @@ export class RevisionPreviewModal extends PureComponent<Props, State> {
});
} else {
this.application.mutator.changeAndSaveItem(
this.props.uuid,
this.originalNote,
(mutator) => {
mutator.unsafe_setCustomContent(this.props.content);
},

View File

@@ -110,30 +110,29 @@ export const SmartViewsListItem: FunctionComponent<Props> = observer(
paddingLeft: `${level * PADDING_PER_LEVEL_PX + PADDING_BASE_PX}px`,
}}
>
{!view.errorDecrypting ? (
<div className="tag-info">
<div className={`tag-icon mr-1`}>
<Icon
type={iconType}
className={`${isSelected ? 'color-info' : 'color-neutral'}`}
/>
</div>
<input
className={`title ${isEditing ? 'editing' : ''}`}
disabled={!isEditing}
id={`react-tag-${view.uuid}`}
onBlur={onBlur}
onInput={onInput}
value={title}
onKeyUp={onKeyUp}
spellCheck={false}
ref={inputRef}
<div className="tag-info">
<div className={`tag-icon mr-1`}>
<Icon
type={iconType}
className={`${isSelected ? 'color-info' : 'color-neutral'}`}
/>
<div className="count">
{view.uuid === SystemViewId.AllNotes && tagsState.allNotesCount}
</div>
</div>
) : null}
<input
className={`title ${isEditing ? 'editing' : ''}`}
disabled={!isEditing}
id={`react-tag-${view.uuid}`}
onBlur={onBlur}
onInput={onInput}
value={title}
onKeyUp={onKeyUp}
spellCheck={false}
ref={inputRef}
/>
<div className="count">
{view.uuid === SystemViewId.AllNotes && tagsState.allNotesCount}
</div>
</div>
{!isSystemView(view) && (
<div className="meta">
{view.conflictOf && (
@@ -141,14 +140,7 @@ export const SmartViewsListItem: FunctionComponent<Props> = observer(
Conflicted Copy {view.conflictOf}
</div>
)}
{view.errorDecrypting && !view.waitingForKey && (
<div className="danger small-text font-bold">Missing Keys</div>
)}
{view.errorDecrypting && view.waitingForKey && (
<div className="info small-text font-bold">
Waiting For Keys
</div>
)}
{isSelected && (
<div className="menu">
{!isEditing && (

View File

@@ -152,7 +152,7 @@ export const TagsListItem: FunctionComponent<Props> = observer(
() => ({
accept: ItemTypes.TAG,
canDrop: (item) => {
return tagsState.isValidTagParent(tag.uuid, item.uuid);
return tagsState.isValidTagParent(tag, item as SNTag);
},
drop: (item) => {
if (!hasFolders) {
@@ -202,70 +202,61 @@ export const TagsListItem: FunctionComponent<Props> = observer(
onContextMenu(tag, e.clientX, e.clientY);
}}
>
{!tag.errorDecrypting ? (
<div className="tag-info" title={title} ref={dropRef}>
{hasAtLeastOneFolder && (
<div className="tag-fold-container">
<button
className={`tag-fold focus:shadow-inner ${
showChildren ? 'opened' : 'closed'
} ${!hasChildren ? 'invisible' : ''}`}
onClick={hasChildren ? toggleChildren : undefined}
>
<Icon
className={`color-neutral`}
type={
showChildren
? 'menu-arrow-down-alt'
: 'menu-arrow-right'
}
/>
</button>
</div>
)}
<div className={`tag-icon draggable mr-1`} ref={dragRef}>
<Icon
type="hashtag"
className={`${isSelected ? 'color-info' : 'color-neutral'}`}
/>
</div>
<input
className={`title ${isEditing ? 'editing' : ''}`}
id={`react-tag-${tag.uuid}`}
disabled={!isEditing}
onBlur={onBlur}
onInput={onInput}
value={title}
onKeyDown={onKeyDown}
spellCheck={false}
ref={inputRef}
/>
<div className="flex items-center">
<div className="tag-info" title={title} ref={dropRef}>
{hasAtLeastOneFolder && (
<div className="tag-fold-container">
<button
className={`border-0 mr-2 bg-transparent hover:bg-contrast focus:shadow-inner cursor-pointer ${
isSelected ? 'visible' : 'invisible'
}`}
onClick={toggleContextMenu}
ref={menuButtonRef}
className={`tag-fold focus:shadow-inner ${
showChildren ? 'opened' : 'closed'
} ${!hasChildren ? 'invisible' : ''}`}
onClick={hasChildren ? toggleChildren : undefined}
>
<Icon type="more" className="color-neutral" />
<Icon
className={`color-neutral`}
type={
showChildren ? 'menu-arrow-down-alt' : 'menu-arrow-right'
}
/>
</button>
<div className="count">{noteCounts.get()}</div>
</div>
)}
<div className={`tag-icon draggable mr-1`} ref={dragRef}>
<Icon
type="hashtag"
className={`${isSelected ? 'color-info' : 'color-neutral'}`}
/>
</div>
) : null}
<input
className={`title ${isEditing ? 'editing' : ''}`}
id={`react-tag-${tag.uuid}`}
disabled={!isEditing}
onBlur={onBlur}
onInput={onInput}
value={title}
onKeyDown={onKeyDown}
spellCheck={false}
ref={inputRef}
/>
<div className="flex items-center">
<button
className={`border-0 mr-2 bg-transparent hover:bg-contrast focus:shadow-inner cursor-pointer ${
isSelected ? 'visible' : 'invisible'
}`}
onClick={toggleContextMenu}
ref={menuButtonRef}
>
<Icon type="more" className="color-neutral" />
</button>
<div className="count">{noteCounts.get()}</div>
</div>
</div>
<div className={`meta ${hasAtLeastOneFolder ? 'with-folders' : ''}`}>
{tag.conflictOf && (
<div className="danger small-text font-bold">
Conflicted Copy {tag.conflictOf}
</div>
)}
{tag.errorDecrypting && !tag.waitingForKey && (
<div className="danger small-text font-bold">Missing Keys</div>
)}
{tag.errorDecrypting && tag.waitingForKey && (
<div className="info small-text font-bold">Waiting For Keys</div>
)}
</div>
</button>
{isAddingSubtag && (

View File

@@ -1,11 +1,10 @@
import { WebApplication } from '@/ui_models/application';
import { parseFileName } from '@standardnotes/filepicker';
import {
EncryptionIntent,
ContentType,
SNNote,
BackupFile,
PayloadContent,
BackupFileDecryptedContextualPayload,
NoteContent,
} from '@standardnotes/snjs';
function sanitizeFileName(name: string): string {
@@ -79,6 +78,7 @@ export class ArchiveManager {
const blob = new Blob([JSON.stringify(data, null, 2)], {
type: 'text/plain',
});
const fileName = zippableFileName('Standard Notes Backup and Import File');
await zipWriter.add(fileName, new zip.BlobReader(blob));
@@ -88,9 +88,9 @@ export class ArchiveManager {
let name, contents;
if (item.content_type === ContentType.Note) {
const note = item as SNNote;
name = (note.content as PayloadContent).title;
contents = (note.content as PayloadContent).text;
const note = item as BackupFileDecryptedContextualPayload<NoteContent>;
name = note.content.title;
contents = note.content.text;
} else {
name = item.content_type;
contents = JSON.stringify(item.content, null, 2);

View File

@@ -8,13 +8,11 @@ import {
removeFromArray,
DesktopManagerInterface,
PayloadSource,
EncryptionIntent,
CreateIntentPayloadFromObject,
InternalEventBus,
} from '@standardnotes/snjs';
import { WebAppEvent, WebApplication } from '@/ui_models/application';
import { isDesktopApplication } from '@/utils';
import { Bridge, ElectronDesktopCallbacks } from './bridge';
import { InternalEventBus } from '@standardnotes/services';
/**
* An interface used by the Desktop application to interact with SN
@@ -68,10 +66,7 @@ export class DesktopManager
* Keys are not passed into ItemParams, so the result is not encrypted
*/
convertComponentForTransmission(component: SNComponent) {
return CreateIntentPayloadFromObject(
component.payloadRepresentation(),
EncryptionIntent.FileDecrypted
);
return component.payloadRepresentation().ejected();
}
// All `components` should be installed
@@ -84,11 +79,7 @@ export class DesktopManager
return this.convertComponentForTransmission(component);
})
).then((payloads) => {
this.bridge.syncComponents(
payloads.filter(
(payload) => !payload.errorDecrypting && !payload.waitingForKey
)
);
this.bridge.syncComponents(payloads);
});
}
@@ -137,7 +128,7 @@ export class DesktopManager
return;
}
const updatedComponent = await this.application.mutator.changeAndSaveItem(
component.uuid,
component,
(m) => {
const mutator = m as ComponentMutator;
if (error) {

View File

@@ -1,7 +1,6 @@
import { WebApplication } from '@/ui_models/application';
import {
StorageValueModes,
EncryptionIntent,
ApplicationService,
SNTheme,
removeFromArray,
@@ -11,9 +10,9 @@ import {
FeatureStatus,
PayloadSource,
PrefKey,
CreateIntentPayloadFromObject,
CreateDecryptedLocalStorageContextPayload,
InternalEventBus,
} from '@standardnotes/snjs';
import { InternalEventBus } from '@standardnotes/services';
const CACHED_THEMES_KEY = 'cachedThemes';
@@ -156,9 +155,9 @@ export class ThemeManager extends ApplicationService {
const preference = prefersDarkColorScheme
? PrefKey.AutoDarkThemeIdentifier
: PrefKey.AutoLightThemeIdentifier;
const themes = this.application.items.getDisplayableItems(
const themes = this.application.items.getDisplayableItems<SNTheme>(
ContentType.Theme
) as SNTheme[];
);
const enableDefaultTheme = () => {
const activeTheme = themes.find(
@@ -206,7 +205,8 @@ export class ThemeManager extends ApplicationService {
this.unregisterStream = this.application.streamItems(
ContentType.Theme,
(items, source) => {
({ changed, inserted, source }) => {
const items = changed.concat(inserted);
const themes = items as SNTheme[];
for (const theme of themes) {
if (theme.active) {
@@ -275,10 +275,7 @@ export class ThemeManager extends ApplicationService {
const mapped = themes.map((theme) => {
const payload = theme.payloadRepresentation();
return CreateIntentPayloadFromObject(
payload,
EncryptionIntent.LocalStorageDecrypted
);
return CreateDecryptedLocalStorageContextPayload(payload);
});
return this.application.setValue(

View File

@@ -6,7 +6,12 @@ import {
observable,
runInAction,
} from 'mobx';
import { ApplicationEvent, ContentType, SNItem } from '@standardnotes/snjs';
import {
ApplicationEvent,
ContentType,
SNNote,
SNTag,
} from '@standardnotes/snjs';
import { WebApplication } from '@/ui_models/application';
import { AccountMenuPane } from '@/components/AccountMenu';
@@ -23,7 +28,7 @@ export class AccountMenuState {
otherSessionsSignOut = false;
server: string | undefined = undefined;
enableServerOption = false;
notesAndTags: SNItem[] = [];
notesAndTags: (SNNote | SNTag)[] = [];
isEncryptionEnabled = false;
encryptionStatusString = '';
isBackupEncrypted = false;

View File

@@ -8,13 +8,14 @@ import {
ContentType,
DeinitSource,
NoteViewController,
PayloadSource,
PrefKey,
SNNote,
SmartView,
SNTag,
SystemViewId,
removeFromArray,
PayloadSource,
Uuid,
} from '@standardnotes/snjs';
import {
action,
@@ -276,9 +277,9 @@ export class AppState {
this.application.noteControllerGroup.closeAllNoteViews();
}
noteControllerForNote(note: SNNote) {
noteControllerForNote(uuid: Uuid) {
for (const controller of this.getNoteControllers()) {
if (controller.note.uuid === note.uuid) {
if (controller.note.uuid === uuid) {
return controller;
}
}
@@ -328,43 +329,61 @@ export class AppState {
}
streamNotesAndTags() {
this.application.streamItems(
this.application.streamItems<SNNote | SNTag>(
[ContentType.Note, ContentType.Tag],
async (items, source) => {
async ({ changed, inserted, removed, source }) => {
if (
![PayloadSource.PreSyncSave, PayloadSource.RemoteRetrieved].includes(
source
)
) {
return;
}
const removedNotes = removed.filter(
(i) => i.content_type === ContentType.Note
);
for (const removedNote of removedNotes) {
const noteController = this.noteControllerForNote(removedNote.uuid);
if (noteController) {
this.closeNoteController(noteController);
}
}
const changedOrInserted = [...changed, ...inserted].filter(
(i) => i.content_type === ContentType.Note
);
const selectedTag = this.tags.selected;
/** Close any note controllers for deleted/trashed/archived notes */
if (source === PayloadSource.PreSyncSave) {
const notes = items.filter(
(candidate) => candidate.content_type === ContentType.Note
) as SNNote[];
for (const note of notes) {
const noteController = this.noteControllerForNote(note);
if (!noteController) {
continue;
}
if (note.deleted) {
this.closeNoteController(noteController);
} else if (
note.trashed &&
!(
selectedTag instanceof SmartView &&
selectedTag.uuid === SystemViewId.TrashedNotes
) &&
!this.searchOptions.includeTrashed
) {
this.closeNoteController(noteController);
} else if (
note.archived &&
!(
selectedTag instanceof SmartView &&
selectedTag.uuid === SystemViewId.ArchivedNotes
) &&
!this.searchOptions.includeArchived &&
!this.application.getPreference(PrefKey.NotesShowArchived, false)
) {
this.closeNoteController(noteController);
}
for (const note of changedOrInserted) {
const noteController = this.noteControllerForNote(note.uuid);
if (!noteController) {
continue;
}
const isBrowswingTrashedNotes =
selectedTag instanceof SmartView &&
selectedTag.uuid === SystemViewId.TrashedNotes;
const isBrowsingArchivedNotes =
selectedTag instanceof SmartView &&
selectedTag.uuid === SystemViewId.ArchivedNotes;
if (
note.trashed &&
!isBrowswingTrashedNotes &&
!this.searchOptions.includeTrashed
) {
this.closeNoteController(noteController);
} else if (
note.archived &&
!isBrowsingArchivedNotes &&
!this.searchOptions.includeArchived &&
!this.application.getPreference(PrefKey.NotesShowArchived, false)
) {
this.closeNoteController(noteController);
}
}
}
@@ -436,11 +455,9 @@ export class AppState {
/** Returns the tags that are referncing this note */
public getNoteTags(note: SNNote) {
return this.application.items
.itemsReferencingItem(note.uuid)
.filter((ref) => {
return ref.content_type === ContentType.Tag;
}) as SNTag[];
return this.application.items.itemsReferencingItem(note).filter((ref) => {
return ref.content_type === ContentType.Tag;
}) as SNTag[];
}
panelDidResize(name: string, collapsed: boolean) {

View File

@@ -215,7 +215,7 @@ export class NoteTagsState {
async removeTagFromActiveNote(tag: SNTag): Promise<void> {
const { activeNote } = this;
if (activeNote) {
await this.application.mutator.changeItem(tag.uuid, (mutator) => {
await this.application.mutator.changeItem(tag, (mutator) => {
mutator.removeItemAsRelationship(activeNote);
});
this.application.sync.sync();

View File

@@ -60,15 +60,22 @@ export class NotesState {
});
appEventListeners.push(
application.streamItems(ContentType.Note, (notes) => {
runInAction(() => {
for (const note of notes) {
if (this.selectedNotes[note.uuid]) {
this.selectedNotes[note.uuid] = note as SNNote;
application.streamItems<SNNote>(
ContentType.Note,
({ changed, inserted, removed }) => {
runInAction(() => {
for (const removedNote of removed) {
delete this.selectedNotes[removedNote.uuid];
}
}
});
})
for (const note of [...changed, ...inserted]) {
if (this.selectedNotes[note.uuid]) {
this.selectedNotes[note.uuid] = note;
}
}
});
}
)
);
}
@@ -85,9 +92,8 @@ export class NotesState {
}
private async selectNotesRange(selectedNote: SNNote): Promise<void> {
const notes = this.application.items.getDisplayableItems(
ContentType.Note
) as SNNote[];
const notes = this.application.items.getDisplayableNotes();
const lastSelectedNoteIndex = notes.findIndex(
(note) => note.uuid == this.lastSelectedNote?.uuid
);
@@ -179,10 +185,6 @@ export class NotesState {
this.appState.noteTags.reloadTags();
await this.onActiveEditorChanged();
if (note.waitingForKey) {
this.application.presentKeyRecoveryWizard();
}
}
setContextMenuOpen(open: boolean): void {
@@ -263,7 +265,7 @@ export class NotesState {
mutate: (mutator: NoteMutator) => void
): Promise<void> {
await this.application.mutator.changeItems(
Object.keys(this.selectedNotes),
Object.values(this.selectedNotes),
mutate,
false
);
@@ -399,7 +401,7 @@ export class NotesState {
async toggleGlobalSpellcheckForNote(note: SNNote) {
await this.application.mutator.changeItem<NoteMutator>(
note.uuid,
note,
(mutator) => {
mutator.toggleSpellcheck();
},
@@ -410,11 +412,11 @@ export class NotesState {
async addTagToSelectedNotes(tag: SNTag): Promise<void> {
const selectedNotes = Object.values(this.selectedNotes);
const parentChainTags = this.application.items.getTagParentChain(tag.uuid);
const parentChainTags = this.application.items.getTagParentChain(tag);
const tagsToAdd = [...parentChainTags, tag];
await Promise.all(
tagsToAdd.map(async (tag) => {
await this.application.mutator.changeItem(tag.uuid, (mutator) => {
await this.application.mutator.changeItem(tag, (mutator) => {
for (const note of selectedNotes) {
mutator.addItemAsRelationship(note);
}
@@ -426,7 +428,7 @@ export class NotesState {
async removeTagFromSelectedNotes(tag: SNTag): Promise<void> {
const selectedNotes = Object.values(this.selectedNotes);
await this.application.mutator.changeItem(tag.uuid, (mutator) => {
await this.application.mutator.changeItem(tag, (mutator) => {
for (const note of selectedNotes) {
mutator.removeItemAsRelationship(note);
}

View File

@@ -1,6 +1,7 @@
import {
ApplicationEvent,
CollectionSort,
CollectionSortProperty,
ContentType,
findInArray,
NotesDisplayCriteria,
@@ -28,7 +29,7 @@ const ELEMENT_ID_SEARCH_BAR = 'search-bar';
const ELEMENT_ID_SCROLL_CONTAINER = 'notes-scrollable';
export type DisplayOptions = {
sortBy: CollectionSort;
sortBy: CollectionSortProperty;
sortReverse: boolean;
hidePinned: boolean;
showArchived: boolean;
@@ -73,18 +74,20 @@ export class NotesViewState {
this.resetPagination();
appObservers.push(
application.streamItems(ContentType.Note, () => {
application.streamItems<SNNote>(ContentType.Note, () => {
this.reloadNotes();
const activeNote = this.appState.notes.activeNoteController?.note;
if (this.application.getAppState().notes.selectedNotesCount < 2) {
if (activeNote) {
const discarded = activeNote.deleted || activeNote.trashed;
const browsingTrashedNotes =
this.appState.selectedTag instanceof SmartView &&
this.appState.selectedTag?.uuid === SystemViewId.TrashedNotes;
if (
discarded &&
!(
this.appState.selectedTag instanceof SmartView &&
this.appState.selectedTag?.uuid === SystemViewId.TrashedNotes
) &&
activeNote.trashed &&
!browsingTrashedNotes &&
!this.appState?.searchOptions.includeTrashed
) {
this.selectNextOrCreateNew();
@@ -96,19 +99,24 @@ export class NotesViewState {
}
}
}),
application.streamItems([ContentType.Tag], async (items) => {
const tags = items as SNTag[];
/** A tag could have changed its relationships, so we need to reload the filter */
this.reloadNotesDisplayOptions();
this.reloadNotes();
if (
this.appState.selectedTag &&
findInArray(tags, 'uuid', this.appState.selectedTag.uuid)
) {
/** Tag title could have changed */
this.reloadPanelTitle();
application.streamItems<SNTag>(
[ContentType.Tag],
async ({ changed, inserted }) => {
const tags = [...changed, ...inserted];
/** A tag could have changed its relationships, so we need to reload the filter */
this.reloadNotesDisplayOptions();
this.reloadNotes();
if (
this.appState.selectedTag &&
findInArray(tags, 'uuid', this.appState.selectedTag.uuid)
) {
/** Tag title could have changed */
this.reloadPanelTitle();
}
}
}),
),
application.addEventObserver(async () => {
this.reloadPreferences();
}, ApplicationEvent.PreferencesChanged),
@@ -223,9 +231,7 @@ export class NotesViewState {
if (!tag) {
return;
}
const notes = this.application.items.getDisplayableItems(
ContentType.Note
) as SNNote[];
const notes = this.application.items.getDisplayableNotes();
const renderedNotes = notes.slice(0, this.notesToDisplay);
this.notes = notes;
@@ -250,7 +256,7 @@ export class NotesViewState {
}
const criteria = NotesDisplayCriteria.Create({
sortProperty: this.displayOptions.sortBy as CollectionSort,
sortProperty: this.displayOptions.sortBy,
sortDirection: this.displayOptions.sortReverse ? 'asc' : 'dsc',
tags: tag instanceof SNTag ? [tag] : [],
views: tag instanceof SmartView ? [tag] : [],
@@ -498,7 +504,7 @@ export class NotesViewState {
handleEditorChange = async () => {
const activeNote = this.appState.getActiveNoteController()?.note;
if (activeNote && activeNote.conflictOf) {
this.application.mutator.changeAndSaveItem(activeNote.uuid, (mutator) => {
this.application.mutator.changeAndSaveItem(activeNote, (mutator) => {
mutator.conflictOf = undefined;
});
}

View File

@@ -14,6 +14,7 @@ import {
TagMutator,
UuidString,
isSystemView,
FindItem,
} from '@standardnotes/snjs';
import {
action,
@@ -29,11 +30,9 @@ import { FeaturesState, SMART_TAGS_FEATURE_NAME } from './features_state';
type AnyTag = SNTag | SmartView;
const rootTags = (application: SNApplication): SNTag[] => {
const hasNoParent = (tag: SNTag) => !application.items.getTagParent(tag.uuid);
const hasNoParent = (tag: SNTag) => !application.items.getTagParent(tag);
const allTags = application.items.getDisplayableItems(
ContentType.Tag
) as SNTag[];
const allTags = application.items.getDisplayableItems<SNTag>(ContentType.Tag);
const rootTags = allTags.filter(hasNoParent);
return rootTags;
@@ -44,10 +43,10 @@ const tagSiblings = (application: SNApplication, tag: SNTag): SNTag[] => {
tags.filter((other) => other.uuid !== tag.uuid);
const isTemplateTag = application.items.isTemplateItem(tag);
const parentTag = !isTemplateTag && application.items.getTagParent(tag.uuid);
const parentTag = !isTemplateTag && application.items.getTagParent(tag);
if (parentTag) {
const siblingsAndTag = application.items.getTagChildren(parentTag.uuid);
const siblingsAndTag = application.items.getTagChildren(parentTag);
return withoutCurrentTag(siblingsAndTag);
}
@@ -148,24 +147,24 @@ export class TagsState {
appEventListeners.push(
this.application.streamItems(
[ContentType.Tag, ContentType.SmartView],
(items) => {
({ changed, removed }) => {
runInAction(() => {
this.tags = this.application.items.getDisplayableItems<SNTag>(
ContentType.Tag
);
this.smartViews = this.application.items.getSmartViews();
const selectedTag = this.selected_;
if (selectedTag && !isSystemView(selectedTag as SmartView)) {
const matchingTag = items.find(
(candidate) => candidate.uuid === selectedTag.uuid
) as AnyTag;
if (matchingTag) {
if (matchingTag.deleted) {
this.selected_ = this.smartViews[0];
} else {
this.selected_ = matchingTag;
}
if (FindItem(removed, selectedTag.uuid)) {
this.selected_ = this.smartViews[0];
}
const updated = FindItem(changed, selectedTag.uuid);
if (updated) {
this.selected_ = updated as AnyTag;
}
} else {
this.selected_ = this.smartViews[0];
@@ -202,7 +201,7 @@ export class TagsState {
title
)) as SNTag;
const futureSiblings = this.application.items.getTagChildren(parent.uuid);
const futureSiblings = this.application.items.getTagChildren(parent);
if (!isValidFutureSiblings(this.application, futureSiblings, createdTag)) {
this.setAddingSubtagTo(undefined);
@@ -319,7 +318,7 @@ export class TagsState {
return [];
}
const children = this.application.items.getTagChildren(tag.uuid);
const children = this.application.items.getTagChildren(tag);
const childrenUuids = children.map((childTag) => childTag.uuid);
const childrenTags = this.tags.filter((tag) =>
@@ -328,8 +327,8 @@ export class TagsState {
return childrenTags;
}
isValidTagParent(parentUuid: UuidString, tagUuid: UuidString): boolean {
return this.application.items.isValidTagParent(parentUuid, tagUuid);
isValidTagParent(parent: SNTag, tag: SNTag): boolean {
return this.application.items.isValidTagParent(parent, tag);
}
public hasParent(tagUuid: UuidString): boolean {
@@ -343,7 +342,7 @@ export class TagsState {
): Promise<void> {
const tag = this.application.items.findItem(tagUuid) as SNTag;
const currentParent = this.application.items.getTagParent(tag.uuid);
const currentParent = this.application.items.getTagParent(tag);
const currentParentUuid = currentParent?.uuid;
if (currentParentUuid === futureParentUuid) {
@@ -361,9 +360,8 @@ export class TagsState {
}
await this.application.mutator.unsetTagParent(tag);
} else {
const futureSiblings = this.application.items.getTagChildren(
futureParent.uuid
);
const futureSiblings =
this.application.items.getTagChildren(futureParent);
if (!isValidFutureSiblings(this.application, futureSiblings, tag)) {
return;
}
@@ -374,9 +372,7 @@ export class TagsState {
}
get rootTags(): SNTag[] {
return this.tags.filter(
(tag) => !this.application.items.getTagParent(tag.uuid)
);
return this.tags.filter((tag) => !this.application.items.getTagParent(tag));
}
get tagsCount(): number {
@@ -401,7 +397,7 @@ export class TagsState {
public set selected(tag: AnyTag | undefined) {
if (tag && tag.conflictOf) {
this.application.mutator.changeAndSaveItem(tag.uuid, (mutator) => {
this.application.mutator.changeAndSaveItem(tag, (mutator) => {
mutator.conflictOf = undefined;
});
}
@@ -417,12 +413,9 @@ export class TagsState {
}
public setExpanded(tag: SNTag, expanded: boolean) {
this.application.mutator.changeAndSaveItem<TagMutator>(
tag.uuid,
(mutator) => {
mutator.expanded = expanded;
}
);
this.application.mutator.changeAndSaveItem<TagMutator>(tag, (mutator) => {
mutator.expanded = expanded;
});
}
public get selectedUuid(): UuidString | undefined {
@@ -527,7 +520,7 @@ export class TagsState {
});
} else {
await this.application.mutator.changeAndSaveItem<TagMutator>(
tag.uuid,
tag,
(mutator) => {
mutator.title = newTitle;
}
@@ -563,9 +556,7 @@ export class TagsState {
}
public get hasAtLeastOneFolder(): boolean {
return this.tags.some(
(tag) => !!this.application.items.getTagParent(tag.uuid)
);
return this.tags.some((tag) => !!this.application.items.getTagParent(tag));
}
}

View File

@@ -75,15 +75,16 @@ export class WebApplication extends SNApplication {
if (source === DeinitSource.AppGroupUnload) {
this.getThemeService().deactivateAllThemes();
}
for (const service of Object.values(this.webServices)) {
if ('deinit' in service) {
service.deinit?.(source);
}
(service as any).application = undefined;
}
this.webServices = {} as WebServices;
this.noteControllerGroup.deinit();
this.iconsController.deinit();
this.webEventObservers.length = 0;
if (source === DeinitSource.SignOut) {

View File

@@ -6,6 +6,7 @@ import {
DeviceInterface,
Platform,
Runtime,
InternalEventBus,
} from '@standardnotes/snjs';
import { AppState } from '@/ui_models/app_state';
import { Bridge } from '@/services/bridge';
@@ -16,7 +17,6 @@ import { IOService } from '@/services/ioService';
import { AutolockService } from '@/services/autolock_service';
import { StatusManager } from '@/services/statusManager';
import { ThemeManager } from '@/services/themeManager';
import { InternalEventBus } from '@standardnotes/services';
export class ApplicationGroup extends SNApplicationGroup {
constructor(