Skip to content

Commit

Permalink
chore: show invite count bubble on preferences button (#2458)
Browse files Browse the repository at this point in the history
  • Loading branch information
amanharwara committed Sep 1, 2023
1 parent 4ca2912 commit be3b904
Show file tree
Hide file tree
Showing 20 changed files with 158 additions and 54 deletions.
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
const PREFERENCE_IDS = [
const PREFERENCE_PANE_IDS = [
'general',
'account',
'security',
Expand All @@ -14,4 +14,4 @@ const PREFERENCE_IDS = [
'whats-new',
] as const

export type PreferenceId = (typeof PREFERENCE_IDS)[number]
export type PreferencePaneId = (typeof PREFERENCE_PANE_IDS)[number]
34 changes: 34 additions & 0 deletions packages/services/src/Domain/Status/StatusService.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,44 @@
import { removeFromArray } from '@standardnotes/utils'
import { AbstractService } from '../Service/AbstractService'
import { StatusServiceEvent, StatusServiceInterface, StatusMessageIdentifier } from './StatusServiceInterface'
import { PreferencePaneId } from '../Preferences/PreferenceId'

/* istanbul ignore file */

export class StatusService extends AbstractService<StatusServiceEvent, string> implements StatusServiceInterface {
private preferencesBubbleCounts: Record<PreferencePaneId, number> = {
general: 0,
account: 0,
security: 0,
'home-server': 0,
vaults: 0,
appearance: 0,
backups: 0,
listed: 0,
shortcuts: 0,
accessibility: 0,
'get-free-month': 0,
'help-feedback': 0,
'whats-new': 0,
}

getPreferencesBubbleCount(preferencePaneId: PreferencePaneId): number {
return this.preferencesBubbleCounts[preferencePaneId]
}

setPreferencesBubbleCount(preferencePaneId: PreferencePaneId, count: number): void {
this.preferencesBubbleCounts[preferencePaneId] = count
const totalCount = this.totalPreferencesBubbleCount
void this.notifyEvent(
StatusServiceEvent.PreferencesBubbleCountChanged,
totalCount > 0 ? totalCount.toString() : undefined,
)
}

get totalPreferencesBubbleCount(): number {
return Object.values(this.preferencesBubbleCounts).reduce((total, count) => total + count, 0)
}

private _message = ''
private directSetMessage?: string
private dynamicMessages: string[] = []
Expand Down
6 changes: 6 additions & 0 deletions packages/services/src/Domain/Status/StatusServiceInterface.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,20 @@
import { PreferencePaneId } from '../Preferences/PreferenceId'
import { AbstractService } from '../Service/AbstractService'

/* istanbul ignore file */

export enum StatusServiceEvent {
MessageChanged = 'MessageChanged',
PreferencesBubbleCountChanged = 'PreferencesBubbleCountChanged',
}

export type StatusMessageIdentifier = string

export interface StatusServiceInterface extends AbstractService<StatusServiceEvent, string> {
getPreferencesBubbleCount(preferencePaneId: PreferencePaneId): number
setPreferencesBubbleCount(preferencePaneId: PreferencePaneId, count: number): void
get totalPreferencesBubbleCount(): number

get message(): string
setMessage(message: string | undefined): void
addMessage(message: string): StatusMessageIdentifier
Expand Down
33 changes: 27 additions & 6 deletions packages/services/src/Domain/VaultInvite/VaultInviteService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,8 @@ import { AbstractService } from './../Service/AbstractService'
import { VaultInviteServiceEvent } from './VaultInviteServiceEvent'
import { GetKeyPairs } from '../Encryption/UseCase/GetKeyPairs'
import { DecryptErroredPayloads } from '../Encryption/UseCase/DecryptErroredPayloads'
import { StatusServiceInterface } from '../Status/StatusServiceInterface'
import { ApplicationEvent } from '../Event/ApplicationEvent'
import { WebSocketsServiceEvent } from '../Api/WebSocketsServiceEvent'

export class VaultInviteService
Expand All @@ -51,6 +53,7 @@ export class VaultInviteService
private vaultUsers: VaultUserServiceInterface,
private sync: SyncServiceInterface,
private invitesServer: SharedVaultInvitesServer,
private status: StatusServiceInterface,
private _getAllContacts: GetAllContacts,
private _getVault: GetVault,
private _getVaultContacts: GetVaultContacts,
Expand Down Expand Up @@ -96,11 +99,28 @@ export class VaultInviteService
this.pendingInvites = {}
}

updatePendingInviteCount() {
this.status.setPreferencesBubbleCount('vaults', Object.keys(this.pendingInvites).length)
}

addPendingInvite(invite: InviteRecord): void {
this.pendingInvites[invite.invite.uuid] = invite
this.updatePendingInviteCount()
}

removePendingInvite(uuid: string): void {
delete this.pendingInvites[uuid]
this.updatePendingInviteCount()
}

async handleEvent(event: InternalEventInterface): Promise<void> {
switch (event.type) {
case SyncEvent.ReceivedSharedVaultInvites:
await this.processInboundInvites(event.payload as SyncEventReceivedSharedVaultInvitesData)
break
case ApplicationEvent.Launched:
void this.downloadInboundInvites()
break
case WebSocketsServiceEvent.UserInvitedToSharedVault:
await this.processInboundInvites([(event as UserInvitedToSharedVaultEvent).payload.invite])
break
Expand Down Expand Up @@ -154,7 +174,7 @@ export class VaultInviteService
return Result.fail(acceptResult.getError())
}

delete this.pendingInvites[pendingInvite.invite.uuid]
this.removePendingInvite(pendingInvite.invite.uuid)

void this.sync.sync()

Expand Down Expand Up @@ -242,7 +262,7 @@ export class VaultInviteService
return ClientDisplayableError.FromString(`Failed to delete invite ${JSON.stringify(response)}`)
}

delete this.pendingInvites[invite.uuid]
this.removePendingInvite(invite.uuid)
}

private async reprocessCachedInvitesTrustStatusAfterTrustedContactsChange(): Promise<void> {
Expand All @@ -253,6 +273,7 @@ export class VaultInviteService

private async processInboundInvites(invites: SharedVaultInviteServerHash[]): Promise<void> {
if (invites.length === 0) {
this.updatePendingInviteCount()
return
}

Expand All @@ -274,11 +295,11 @@ export class VaultInviteService
})

if (!trustedMessage.isFailed()) {
this.pendingInvites[invite.uuid] = {
this.addPendingInvite({
invite,
message: trustedMessage.getValue(),
trusted: true,
}
})

continue
}
Expand All @@ -290,11 +311,11 @@ export class VaultInviteService
})

if (!untrustedMessage.isFailed()) {
this.pendingInvites[invite.uuid] = {
this.addPendingInvite({
invite,
message: untrustedMessage.getValue(),
trusted: false,
}
})
}
}

Expand Down
1 change: 1 addition & 0 deletions packages/services/src/Domain/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,7 @@ export * from './KeySystem/KeySystemKeyManager'
export * from './Mfa/MfaServiceInterface'
export * from './Mutator/MutatorClientInterface'
export * from './Payloads/PayloadManagerInterface'
export * from './Preferences/PreferenceId'
export * from './Preferences/PreferenceServiceInterface'
export * from './Protection/MobileUnlockTiming'
export * from './Protection/ProtectionClientInterface'
Expand Down
1 change: 1 addition & 0 deletions packages/snjs/lib/Application/Dependencies/Dependencies.ts
Original file line number Diff line number Diff line change
Expand Up @@ -864,6 +864,7 @@ export class Dependencies {
this.get<VaultUserService>(TYPES.VaultUserService),
this.get<SyncService>(TYPES.SyncService),
this.get<SharedVaultInvitesServer>(TYPES.SharedVaultInvitesServer),
this.get<StatusService>(TYPES.StatusService),
this.get<GetAllContacts>(TYPES.GetAllContacts),
this.get<GetVault>(TYPES.GetVault),
this.get<GetVaultContacts>(TYPES.GetVaultContacts),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ export function RegisterApplicationServicesEvents(container: Dependencies, event
events.addEventHandler(container.get(TYPES.SubscriptionManager), SessionEvent.Restored)
events.addEventHandler(container.get(TYPES.SyncService), IntegrityEvent.IntegrityCheckCompleted)
events.addEventHandler(container.get(TYPES.UserService), AccountEvent.SignedInOrRegistered)
events.addEventHandler(container.get(TYPES.VaultInviteService), ApplicationEvent.Launched)
events.addEventHandler(container.get(TYPES.VaultInviteService), SyncEvent.ReceivedSharedVaultInvites)

if (container.get(TYPES.FilesBackupService)) {
Expand Down
4 changes: 2 additions & 2 deletions packages/ui-services/src/Route/Params/SettingsParams.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { PreferenceId } from '../../Preferences/PreferenceId'
import { PreferencePaneId } from '@standardnotes/services'

export type SettingsParams = {
panel: PreferenceId
panel: PreferencePaneId
}
4 changes: 2 additions & 2 deletions packages/ui-services/src/Route/RouteParser.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { UserRequestType } from '@standardnotes/common'
import { PreferenceId } from './../Preferences/PreferenceId'
import { PreferencePaneId } from '@standardnotes/services'
import { AppViewRouteParam, ValidAppViewRoutes } from './Params/AppViewRouteParams'
import { DemoParams } from './Params/DemoParams'
import { OnboardingParams } from './Params/OnboardingParams'
Expand Down Expand Up @@ -58,7 +58,7 @@ export class RouteParser implements RouteParserInterface {
this.checkForProperRouteType(RouteType.Settings)

return {
panel: this.searchParams.get(RootQueryParam.Settings) as PreferenceId,
panel: this.searchParams.get(RootQueryParam.Settings) as PreferencePaneId,
}
}

Expand Down
1 change: 0 additions & 1 deletion packages/ui-services/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ export * from './Keyboard/KeyboardKey'
export * from './Keyboard/KeyboardModifier'
export * from './Keyboard/keyboardCharacterForModifier'
export * from './Keyboard/keyboardStringForShortcut'
export * from './Preferences/PreferenceId'
export * from './Route/Params/DemoParams'
export * from './Route/Params/OnboardingParams'
export * from './Route/Params/PurchaseParams'
Expand Down
4 changes: 2 additions & 2 deletions packages/web/src/javascripts/Application/WebApplication.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,13 +37,13 @@ import {
IsNativeIOS,
IsNativeMobileWeb,
KeyboardService,
PreferenceId,
RouteServiceInterface,
ThemeManager,
VaultDisplayServiceInterface,
WebAlertService,
WebApplicationInterface,
} from '@standardnotes/ui-services'
import { PreferencePaneId } from '@standardnotes/services'
import { MobileWebReceiver, NativeMobileEventListener } from '../NativeMobileWeb/MobileWebReceiver'
import { setCustomViewportHeight } from '@/setViewportHeightWithFallback'
import { FeatureName } from '@/Controllers/FeatureName'
Expand Down Expand Up @@ -504,7 +504,7 @@ export class WebApplication extends SNApplication implements WebApplicationInter
return this.environment === Environment.Web
}

openPreferences(pane?: PreferenceId): void {
openPreferences(pane?: PreferencePaneId): void {
this.preferencesController.openPreferences()
if (pane) {
this.preferencesController.setCurrentPane(pane)
Expand Down
7 changes: 5 additions & 2 deletions packages/web/src/javascripts/Components/Footer/Footer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { WebApplication } from '@/Application/WebApplication'
import { WebApplicationGroup } from '@/Application/WebApplicationGroup'
import { AbstractComponent } from '@/Components/Abstract/PureComponent'
import { destroyAllObjectProperties, preventRefreshing } from '@/Utils'
import { ApplicationEvent, ApplicationDescriptor, WebAppEvent } from '@standardnotes/snjs'
import { ApplicationEvent, ApplicationDescriptor, WebAppEvent, StatusServiceEvent } from '@standardnotes/snjs'
import {
STRING_NEW_UPDATE_READY,
STRING_CONFIRM_APP_QUIT_DURING_UPGRADE,
Expand Down Expand Up @@ -112,7 +112,10 @@ class Footer extends AbstractComponent<Props, State> {
override componentDidMount(): void {
super.componentDidMount()

this.removeStatusObserver = this.application.status.addEventObserver((_event, message) => {
this.removeStatusObserver = this.application.status.addEventObserver((event, message) => {
if (event !== StatusServiceEvent.MessageChanged) {
return
}
this.setState({
arbitraryStatusMessage: message,
})
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { compareSemVersions } from '@standardnotes/snjs'
import { compareSemVersions, StatusServiceEvent } from '@standardnotes/snjs'
import { keyboardStringForShortcut, OPEN_PREFERENCES_COMMAND } from '@standardnotes/ui-services'
import { useCallback, useEffect, useMemo, useState } from 'react'
import { useApplication } from '../ApplicationProvider'
Expand Down Expand Up @@ -36,11 +36,26 @@ const PreferencesButton = ({ openPreferences }: Props) => {
openPreferences(isChangelogUnread)
}, [isChangelogUnread, openPreferences])

const [bubbleCount, setBubbleCount] = useState<string | undefined>()
useEffect(() => {
return application.status.addEventObserver((event, message) => {
if (event !== StatusServiceEvent.PreferencesBubbleCountChanged) {
return
}
setBubbleCount(message)
})
}, [application.status])

return (
<StyledTooltip label={`Open preferences (${shortcut})`}>
<button onClick={onClick} className="relative flex h-full w-8 cursor-pointer items-center justify-center">
<div className="h-5">
<Icon type="tune" className="rounded hover:text-info" />
<button onClick={onClick} className="group relative flex h-full w-8 cursor-pointer items-center justify-center">
<div className="relative h-5">
<Icon type="tune" className="rounded group-hover:text-info" />
{bubbleCount && (
<div className="absolute bottom-full left-full aspect-square -translate-x-1/2 translate-y-1/2 rounded-full border border-info-contrast bg-info px-1.5 py-px text-[0.575rem] font-bold text-info-contrast">
{bubbleCount}
</div>
)}
</div>
{isChangelogUnread && <div className="absolute right-0.5 top-0.5 h-2 w-2 rounded-full bg-info" />}
</button>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import { IconType } from '@standardnotes/snjs'
import { PreferenceId } from '@standardnotes/ui-services'
import { PreferencePaneId } from '@standardnotes/services'

export interface PreferencesMenuItem {
readonly id: PreferenceId
readonly id: PreferencePaneId
readonly icon: IconType
readonly label: string
readonly order: number
readonly hasBubble?: boolean
readonly bubbleCount?: number
readonly hasErrorIndicator?: boolean
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { action, makeAutoObservable, observable } from 'mobx'
import { WebApplication } from '@/Application/WebApplication'
import { PackageProvider } from '../Panes/General/Advanced/Packages/Provider/PackageProvider'
import { securityPrefsHasBubble } from '../Panes/Security/securityPrefsHasBubble'
import { PreferenceId } from '@standardnotes/ui-services'
import { PreferencePaneId } from '@standardnotes/services'
import { isDesktopApplication } from '@/Utils'
import { featureTrunkHomeServerEnabled, featureTrunkVaultsEnabled } from '@/FeatureTrunk'
import { PreferencesMenuItem } from './PreferencesMenuItem'
Expand All @@ -14,7 +14,7 @@ import { PREFERENCES_MENU_ITEMS, READY_PREFERENCES_MENU_ITEMS } from './MenuItem
* Preferences menu. It is created and destroyed each time the menu is opened and closed.
*/
export class PreferencesSessionController {
private _selectedPane: PreferenceId = 'account'
private _selectedPane: PreferencePaneId = 'account'
private _menu: PreferencesMenuItem[]
private _extensionLatestVersions: PackageProvider = new PackageProvider(new Map())

Expand Down Expand Up @@ -69,7 +69,8 @@ export class PreferencesSessionController {
const item: SelectableMenuItem = {
...preference,
selected: preference.id === this._selectedPane,
hasBubble: this.sectionHasBubble(preference.id),
bubbleCount: this.application.status.getPreferencesBubbleCount(preference.id),
hasErrorIndicator: this.sectionHasBubble(preference.id),
}
return item
})
Expand All @@ -81,19 +82,19 @@ export class PreferencesSessionController {
return this._menu.find((item) => item.id === this._selectedPane)
}

get selectedPaneId(): PreferenceId {
get selectedPaneId(): PreferencePaneId {
if (this.selectedMenuItem != undefined) {
return this.selectedMenuItem.id
}

return 'account'
}

selectPane = (key: PreferenceId) => {
selectPane = (key: PreferencePaneId) => {
this._selectedPane = key
}

sectionHasBubble(id: PreferenceId): boolean {
sectionHasBubble(id: PreferencePaneId): boolean {
if (id === 'security') {
return securityPrefsHasBubble(this.application)
}
Expand Down

0 comments on commit be3b904

Please sign in to comment.