Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Update the counter over the fox to handle notifications #25093

Merged
merged 15 commits into from
Jun 18, 2024
Merged
Show file tree
Hide file tree
Changes from 10 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
120 changes: 102 additions & 18 deletions app/scripts/background.js
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,15 @@ import DesktopManager from '@metamask/desktop/dist/desktop-manager';
///: END:ONLY_INCLUDE_IF
/* eslint-enable import/order */

import { TRIGGER_TYPES } from './controllers/metamask-notifications/constants/notification-schema';

// eslint-disable-next-line @metamask/design-tokens/color-no-hex
const BADGE_COLOR_APPROVAL = '#0376C9';
// eslint-disable-next-line @metamask/design-tokens/color-no-hex
const BADGE_COLOR_NOTIFICATION = '#D73847';
const BADGE_LABEL_APPROVAL = '\u22EF'; // unicode ellipsis
const BADGE_MAX_NOTIFICATION_COUNT = 9;

// Setup global hook for improved Sentry state snapshots during initialization
const inTest = process.env.IN_TEST;
const localStore = inTest ? new ReadOnlyNetworkStore() : new LocalStore();
Expand Down Expand Up @@ -825,45 +834,120 @@ export function setupController(
updateBadge,
);

controller.controllerMessenger.subscribe(
METAMASK_CONTROLLER_EVENTS.METAMASK_NOTIFICATIONS_LIST_UPDATED,
updateBadge,
);

controller.controllerMessenger.subscribe(
METAMASK_CONTROLLER_EVENTS.METAMASK_NOTIFICATIONS_MARK_AS_READ,
updateBadge,
);

controller.controllerMessenger.subscribe(
METAMASK_CONTROLLER_EVENTS.NOTIFICATIONS_STATE_CHANGE,
matthewwalsh0 marked this conversation as resolved.
Show resolved Hide resolved
updateBadge,
);

controller.txController.initApprovals();

/**
* Updates the Web Extension's "badge" number, on the little fox in the toolbar.
* The number reflects the current number of pending transactions or message signatures needing user approval.
*/
function updateBadge() {
const pendingApprovalCount = getPendingApprovalCount();
const unreadNotificationsCount = getUnreadNotificationsCount();

let label = '';
const count = getUnapprovedTransactionCount();
if (count) {
label = String(count);
let badgeColor = BADGE_COLOR_APPROVAL;

if (pendingApprovalCount) {
label = BADGE_LABEL_APPROVAL;
} else if (unreadNotificationsCount > 0) {
label =
unreadNotificationsCount > BADGE_MAX_NOTIFICATION_COUNT
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

BADGE_MAX_NOTIFICATION_COUNT seems to be a string, seems a little odd to do string greater than here.

JS probably converts this to a number when doing this check.

Instead change BADGE_MAX_NOTIFICATION_COUNT to a number for valid conditional.

Copy link
Contributor

@Prithpal-Sooriya Prithpal-Sooriya Jun 7, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

(Prith note, this is just me rambling to myself) why don't we use // @ts-check in our JS files? I guess this will force JS files to be passed through our compiler and might give us false sense of security (since not true TS)... but I think it would still be handy to prevent type mismatch.

? `${BADGE_MAX_NOTIFICATION_COUNT}+`
: String(unreadNotificationsCount);
badgeColor = BADGE_COLOR_NOTIFICATION;
}
// browserAction has been replaced by action in MV3
if (isManifestV3) {
browser.action.setBadgeText({ text: label });
browser.action.setBadgeBackgroundColor({ color: '#037DD6' });
} else {
browser.browserAction.setBadgeText({ text: label });
browser.browserAction.setBadgeBackgroundColor({ color: '#037DD6' });

try {
const badgeText = { text: label };
const badgeBackgroundColor = { color: badgeColor };

if (isManifestV3) {
browser.action.setBadgeText(badgeText);
browser.action.setBadgeBackgroundColor(badgeBackgroundColor);
} else {
browser.browserAction.setBadgeText(badgeText);
browser.browserAction.setBadgeBackgroundColor(badgeBackgroundColor);
}
} catch (error) {
console.error('Error updating browser badge:', error);
}
matthewwalsh0 marked this conversation as resolved.
Show resolved Hide resolved
}

function getUnapprovedTransactionCount() {
let count =
controller.appStateController.waitingForUnlock.length +
controller.approvalController.getTotalApprovalCount();
function getPendingApprovalCount() {
try {
let pendingApprovalCount =
controller.appStateController.waitingForUnlock.length +
controller.approvalController.getTotalApprovalCount();

if (controller.preferencesController.getUseRequestQueue()) {
pendingApprovalCount +=
controller.queuedRequestController.state.queuedRequestCount;
}
return pendingApprovalCount;
} catch (error) {
console.error('Failed to get unapproved transaction count:', error);
matthewwalsh0 marked this conversation as resolved.
Show resolved Hide resolved
return 0;
}
}

if (controller.preferencesController.getUseRequestQueue()) {
count += controller.queuedRequestController.state.queuedRequestCount;
function getUnreadNotificationsCount() {
try {
const { isMetamaskNotificationsEnabled, isFeatureAnnouncementsEnabled } =
controller.metamaskNotificationsController.state;

const snapNotificationCount = Object.values(
controller.notificationController.state.notifications,
).filter((notification) => notification.readDate === null).length;

const featureAnnouncementCount = isFeatureAnnouncementsEnabled
? controller.metamaskNotificationsController.state.metamaskNotificationsList.filter(
(notification) =>
!notification.isRead &&
notification.type === TRIGGER_TYPES.FEATURES_ANNOUNCEMENT,
).length
: 0;

const walletNotificationCount = isMetamaskNotificationsEnabled
? controller.metamaskNotificationsController.state.metamaskNotificationsList.filter(
(notification) =>
!notification.isRead &&
notification.type !== TRIGGER_TYPES.FEATURES_ANNOUNCEMENT,
).length
: 0;

const unreadNotificationsCount =
snapNotificationCount +
featureAnnouncementCount +
walletNotificationCount;

return unreadNotificationsCount;
} catch (error) {
console.error('Failed to get unread notifications count:', error);
return 0;
}
return count;
}

notificationManager.on(
NOTIFICATION_MANAGER_EVENTS.POPUP_CLOSED,
({ automaticallyClosed }) => {
if (!automaticallyClosed) {
rejectUnapprovedNotifications();
} else if (getUnapprovedTransactionCount() > 0) {
} else if (getPendingApprovalCount() > 0) {
triggerUi();
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -175,6 +175,16 @@ export declare type MetamaskNotificationsControllerSelectIsMetamaskNotifications
handler: MetamaskNotificationsController['selectIsMetamaskNotificationsEnabled'];
};

export type MetamaskNotificationsControllerNotificationsListUpdatedEvent = {
type: `${typeof controllerName}:notificationsListUpdated`;
payload: [Notification[]];
};

export type MetamaskNotificationsControllerMarkNotificationsAsRead = {
type: `${typeof controllerName}:markNotificationsAsRead`;
payload: [Notification[]];
};

// Messenger Actions
export type Actions =
| MetamaskNotificationsControllerUpdateMetamaskNotificationsList
Expand Down Expand Up @@ -209,7 +219,9 @@ export type MetamaskNotificationsControllerMessengerEvents =
// Allowed Events
export type AllowedEvents =
| KeyringControllerStateChangeEvent
| PushPlatformNotificationsControllerOnNewNotificationEvent;
| PushPlatformNotificationsControllerOnNewNotificationEvent
| MetamaskNotificationsControllerNotificationsListUpdatedEvent
| MetamaskNotificationsControllerMarkNotificationsAsRead;

// Type for the messenger of MetamaskNotificationsController
export type MetamaskNotificationsControllerMessenger =
Expand Down Expand Up @@ -1004,6 +1016,11 @@ export class MetamaskNotificationsController extends BaseController<
state.metamaskNotificationsList = metamaskNotifications;
});

this.messagingSystem.publish(
`${controllerName}:notificationsListUpdated`,
this.state.metamaskNotificationsList,
);

this.#setIsFetchingMetamaskNotifications(false);
return metamaskNotifications;
} catch (err) {
Expand Down Expand Up @@ -1068,7 +1085,7 @@ export class MetamaskNotificationsController extends BaseController<
log.warn('Something failed when marking notifications as read', err);
}

// Update the state (state is also used on counter & badge)
// Update the state
this.update((state) => {
const currentReadList = state.metamaskNotificationsReadList;
const newReadIds = [...featureAnnouncementNotificationIds];
Expand All @@ -1088,6 +1105,12 @@ export class MetamaskNotificationsController extends BaseController<
},
);
});

// Publish the event
this.messagingSystem.publish(
`${controllerName}:markNotificationsAsRead`,
this.state.metamaskNotificationsList,
);
}

/**
Expand Down Expand Up @@ -1120,6 +1143,10 @@ export class MetamaskNotificationsController extends BaseController<
notification,
...state.metamaskNotificationsList,
];
this.messagingSystem.publish(
`${controllerName}:notificationsListUpdated`,
state.metamaskNotificationsList,
);
}
});
}
Expand Down
5 changes: 5 additions & 0 deletions app/scripts/metamask-controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -338,6 +338,11 @@ export const METAMASK_CONTROLLER_EVENTS = {
// TODO: Add this and similar enums to the `controllers` repo and export them
APPROVAL_STATE_CHANGE: 'ApprovalController:stateChange',
QUEUED_REQUEST_STATE_CHANGE: 'QueuedRequestController:stateChange',
METAMASK_NOTIFICATIONS_LIST_UPDATED:
'MetamaskNotificationsController:notificationsListUpdated',
METAMASK_NOTIFICATIONS_MARK_AS_READ:
'MetamaskNotificationsController:markNotificationsAsRead',
NOTIFICATIONS_STATE_CHANGE: 'NotificationController:stateChange',
};

// stream channels
Expand Down