chore: show invite count bubble on preferences button (#2458)

This commit is contained in:
Aman Harwara
2023-09-01 22:31:35 +05:30
committed by GitHub
parent 4ca291291c
commit be3b904f62
20 changed files with 158 additions and 54 deletions

View File

@@ -1,4 +1,4 @@
const PREFERENCE_IDS = [
const PREFERENCE_PANE_IDS = [
'general',
'account',
'security',
@@ -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]

View File

@@ -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[] = []

View File

@@ -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

View File

@@ -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
@@ -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,
@@ -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
@@ -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()
@@ -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> {
@@ -253,6 +273,7 @@ export class VaultInviteService
private async processInboundInvites(invites: SharedVaultInviteServerHash[]): Promise<void> {
if (invites.length === 0) {
this.updatePendingInviteCount()
return
}
@@ -274,11 +295,11 @@ export class VaultInviteService
})
if (!trustedMessage.isFailed()) {
this.pendingInvites[invite.uuid] = {
this.addPendingInvite({
invite,
message: trustedMessage.getValue(),
trusted: true,
}
})
continue
}
@@ -290,11 +311,11 @@ export class VaultInviteService
})
if (!untrustedMessage.isFailed()) {
this.pendingInvites[invite.uuid] = {
this.addPendingInvite({
invite,
message: untrustedMessage.getValue(),
trusted: false,
}
})
}
}

View File

@@ -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'

View File

@@ -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),

View File

@@ -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)) {

View File

@@ -1,5 +1,5 @@
import { PreferenceId } from '../../Preferences/PreferenceId'
import { PreferencePaneId } from '@standardnotes/services'
export type SettingsParams = {
panel: PreferenceId
panel: PreferencePaneId
}

View File

@@ -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'
@@ -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,
}
}

View File

@@ -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'

View File

@@ -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'
@@ -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)

View File

@@ -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,
@@ -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,
})

View File

@@ -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'
@@ -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>

View File

@@ -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
}

View File

@@ -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'
@@ -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())
@@ -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
})
@@ -81,7 +82,7 @@ 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
}
@@ -89,11 +90,11 @@ export class PreferencesSessionController {
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)
}

View File

@@ -80,24 +80,26 @@ const ContactInviteModal: FunctionComponent<Props> = ({ vault, onCloseDialog })
return (
<Modal title="Add New Contact" close={handleDialogClose} actions={modalActions}>
<div className={classNames('px-4.5 py-4 flex w-full flex-col gap-3', isLoadingContacts && 'items-center')}>
<div className={classNames('flex w-full flex-col gap-3 px-4.5 py-4', isLoadingContacts && 'items-center')}>
{isLoadingContacts ? (
<Spinner className="w-5 h-5" />
) : (
<Spinner className="h-5 w-5" />
) : contacts.length > 0 ? (
contacts.map((contact) => {
return (
<label className="grid grid-cols-[auto_1fr] gap-x-3 gap-y-0.5" key={contact.uuid}>
<input
className="accent-info w-4 h-4 self-center"
className="h-4 w-4 self-center accent-info"
type="checkbox"
checked={selectedContacts.includes(contact)}
onChange={() => toggleContact(contact)}
/>
<div className="col-start-2 font-semibold text-sm">{contact.name}</div>
<div className="col-start-2 text-sm font-semibold">{contact.name}</div>
<div className="col-start-2">{contact.contactUuid}</div>
</label>
)
})
) : (
<div className="text-sm">No contacts available to invite.</div>
)}
</div>
</Modal>

View File

@@ -158,11 +158,13 @@ const Vaults = () => {
<PreferencesGroup>
<PreferencesSegment>
<Title>Vaults</Title>
<div className="my-2 flex flex-col gap-3.5">
{vaults.map((vault) => {
return <VaultItem vault={vault} key={vault.uuid} />
})}
</div>
{vaults.length > 0 && (
<div className="my-2 flex flex-col gap-3.5">
{vaults.map((vault) => {
return <VaultItem vault={vault} key={vault.uuid} />
})}
</div>
)}
{canCreateMoreVaults ? (
<div className="mt-2.5 flex flex-row">
<Button label="Create New Vault" className={'mr-3 text-xs'} onClick={createNewVault} />
@@ -186,7 +188,7 @@ const Vaults = () => {
<Subtitle>Share your CollaborationID with collaborators to join their vaults.</Subtitle>
{contactService.isCollaborationEnabled() ? (
<>
<code className="mt-2.5 overflow-hidden whitespace-pre-wrap break-words p-3 border border-border rounded bg-contrast">
<code className="mt-2.5 overflow-hidden whitespace-pre-wrap break-words rounded border border-border bg-contrast p-3">
{contactService.getCollaborationID()}
</code>
<Button

View File

@@ -1,17 +1,25 @@
import Icon from '@/Components/Icon/Icon'
import { FunctionComponent } from 'react'
import { IconType } from '@standardnotes/snjs'
import { IconType, classNames } from '@standardnotes/snjs'
import { ErrorCircle } from '@/Components/UIElements/ErrorCircle'
interface Props {
iconType: IconType
label: string
selected: boolean
hasBubble?: boolean
bubbleCount?: number
hasErrorIndicator?: boolean
onClick: () => void
}
const PreferencesMenuItem: FunctionComponent<Props> = ({ iconType, label, selected, onClick, hasBubble }) => (
const PreferencesMenuItem: FunctionComponent<Props> = ({
iconType,
label,
selected,
onClick,
bubbleCount,
hasErrorIndicator,
}) => (
<div
className={`preferences-menu-item box-border flex h-auto w-auto min-w-42 cursor-pointer select-none flex-row items-center justify-start rounded border border-solid px-4 py-2 text-sm hover:border-border hover:bg-default ${
selected ? 'selected border-info font-bold text-info' : 'border-transparent'
@@ -21,10 +29,17 @@ const PreferencesMenuItem: FunctionComponent<Props> = ({ iconType, label, select
onClick()
}}
>
<Icon className={`icon text-base ${selected ? 'text-info' : 'text-neutral'}`} type={iconType} />
<div className="relative mr-1">
<Icon className={classNames('text-base', selected ? 'text-info' : 'text-neutral')} type={iconType} />
{bubbleCount ? (
<div className="absolute bottom-full right-full flex aspect-square h-4 w-4 translate-x-2 translate-y-2 items-center justify-center rounded-full border border-info-contrast bg-info text-[0.5rem] font-bold text-info-contrast">
{bubbleCount}
</div>
) : null}
</div>
<div className="min-w-1" />
{label}
{hasBubble && (
{hasErrorIndicator && (
<span className="ml-2">
<ErrorCircle />
</span>

View File

@@ -4,7 +4,7 @@ import Dropdown from '../Dropdown/Dropdown'
import { DropdownItem } from '../Dropdown/DropdownItem'
import PreferencesMenuItem from './PreferencesComponents/MenuItem'
import { PreferencesSessionController } from './Controller/PreferencesSessionController'
import { PreferenceId } from '@standardnotes/ui-services'
import { PreferencePaneId } from '@standardnotes/services'
type Props = {
menu: PreferencesSessionController
@@ -32,7 +32,8 @@ const PreferencesMenuView: FunctionComponent<Props> = ({ menu }) => {
iconType={pref.icon}
label={pref.label}
selected={pref.selected}
hasBubble={pref.hasBubble}
bubbleCount={pref.bubbleCount}
hasErrorIndicator={pref.hasErrorIndicator}
onClick={() => {
selectPane(pref.id)
}}
@@ -45,7 +46,7 @@ const PreferencesMenuView: FunctionComponent<Props> = ({ menu }) => {
label="Preferences Menu"
value={selectedPaneId}
onChange={(paneId) => {
selectPane(paneId as PreferenceId)
selectPane(paneId as PreferencePaneId)
}}
classNameOverride={{
wrapper: 'relative',

View File

@@ -1,13 +1,14 @@
import { InternalEventBusInterface } from '@standardnotes/snjs'
import { action, computed, makeObservable, observable } from 'mobx'
import { PreferenceId, RootQueryParam, RouteServiceInterface } from '@standardnotes/ui-services'
import { RootQueryParam, RouteServiceInterface } from '@standardnotes/ui-services'
import { AbstractViewController } from './Abstract/AbstractViewController'
import { PreferencePaneId } from '@standardnotes/services'
const DEFAULT_PANE: PreferenceId = 'account'
const DEFAULT_PANE: PreferencePaneId = 'account'
export class PreferencesController extends AbstractViewController {
private _open = false
currentPane: PreferenceId = DEFAULT_PANE
currentPane: PreferencePaneId = DEFAULT_PANE
constructor(
private routeService: RouteServiceInterface,
@@ -25,11 +26,11 @@ export class PreferencesController extends AbstractViewController {
})
}
setCurrentPane = (prefId: PreferenceId): void => {
setCurrentPane = (prefId: PreferencePaneId): void => {
this.currentPane = prefId
}
openPreferences = (prefId?: PreferenceId): void => {
openPreferences = (prefId?: PreferencePaneId): void => {
if (prefId) {
this.currentPane = prefId
}