Skip to content

Commit

Permalink
feat: 优化通知功能,增加icon小红点,增加提示音,优化通知场景
Browse files Browse the repository at this point in the history
  • Loading branch information
moonrailgun committed Jan 10, 2023
1 parent 338af09 commit 350371d
Show file tree
Hide file tree
Showing 10 changed files with 160 additions and 37 deletions.
20 changes: 19 additions & 1 deletion client/shared/cache/cache.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
import { ChatConverseInfo, fetchConverseInfo } from '../model/converse';
import { findGroupInviteByCode, GroupInvite } from '../model/group';
import {
findGroupInviteByCode,
getGroupBasicInfo,
GroupBasicInfo,
GroupInvite,
} from '../model/group';
import {
fetchLocalStaticRegistryPlugins,
fetchRegistryPlugins,
Expand Down Expand Up @@ -41,6 +46,19 @@ export async function getCachedConverseInfo(
return data;
}

/**
* 获取缓存的邀请码信息
*/
export async function getCachedBaseGroupInfo(
groupId: string
): Promise<GroupBasicInfo | null> {
const data = await queryClient.fetchQuery(['baseGroupInfo', groupId], () =>
getGroupBasicInfo(groupId)
);

return data;
}

/**
* 获取缓存的邀请码信息
*/
Expand Down
1 change: 1 addition & 0 deletions client/shared/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ export type { AppSocket } from './api/socket';
export {
getCachedUserInfo,
getCachedConverseInfo,
getCachedBaseGroupInfo,
getCachedGroupInviteInfo,
getCachedRegistryPlugins,
} from './cache/cache';
Expand Down
Binary file not shown.
7 changes: 6 additions & 1 deletion client/web/plugins/com.msgbyte.notify/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,10 @@
"main": "src/index.tsx",
"version": "0.0.0",
"private": true,
"dependencies": {}
"dependencies": {
"tinycon": "^0.6.8"
},
"devDependencies": {
"@types/tinycon": "^0.6.3"
}
}
45 changes: 45 additions & 0 deletions client/web/plugins/com.msgbyte.notify/src/bubble.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import tinycon from 'tinycon';

/**
* 设置小红点
* @param num 小红点数
*/
let bubbleNum = 0;
export function setBubble(num: number) {
bubbleNum = num;
if (num < 0) {
num = 0;
}
tinycon.setBubble(num >= 100 ? 99 : num);
}

/**
* 增加小红点数量
*/
export function incBubble() {
setBubble(bubbleNum + 1);
}

const hiddenProperty =
'hidden' in document
? 'hidden'
: 'webkitHidden' in document
? 'webkitHidden'
: 'mozHidden' in document
? 'mozHidden'
: null;
const visibilityChangeEvent = hiddenProperty?.replace(
/hidden/i,
'visibilitychange'
);
const onVisibilityChange = function () {
if (!document[hiddenProperty ?? '']) {
// 显示标签页时清空
tinycon.setBubble(0);
} else {
// 隐藏标签页
}
};
if (typeof visibilityChangeEvent === 'string') {
document.addEventListener(visibilityChangeEvent, onVisibilityChange);
}
102 changes: 69 additions & 33 deletions client/web/plugins/com.msgbyte.notify/src/notify.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,16 @@ import {
regSocketEventListener,
getGlobalState,
getCachedUserInfo,
getCachedConverseInfo,
getCachedBaseGroupInfo,
getServiceWorkerRegistration,
navigate,
} from '@capital/common';
import { Translate } from './translate';
import { hasSilent } from './silent';
import { incBubble, setBubble } from './bubble';

const TAG = 'tailchat-message';

export function initNotify() {
if (Notification.permission === 'default') {
Expand All @@ -15,7 +20,6 @@ export function initNotify() {

const registration: ServiceWorkerRegistration | null =
getServiceWorkerRegistration();

if (registration) {
registration.addEventListener('notificationclick', (e: any) => {
const tag = e.notification.tag;
Expand All @@ -25,53 +29,73 @@ export function initNotify() {
});
}

let isBlur = false;
window.addEventListener('focus', () => {
setBubble(0); // 点击时清空
isBlur = false;
});
window.addEventListener('blur', () => (isBlur = true));

regSocketEventListener({
eventName: 'chat.message.add',
eventFn: (message) => {
const converseId = message.converseId;
const currentUserId = getGlobalState()?.user.info._id;

if (hasSilent(converseId)) {
// 免打扰
// 手动设置了当前会话免打扰
return;
}

if (currentUserId !== message.author) {
// 创建通知
if (currentUserId === message.author) {
// 忽略本人消息
return;
}

const hidden = window.document.hidden ?? false;
if (hidden || isBlur) {
// 如果当前不是活跃窗口或处于隐藏状态,则创建通知

// TODO: 需要增加所在群组
if (Notification.permission === 'granted') {
Promise.all([getCachedUserInfo(message.author)]).then(
([userInfo]) => {
const nickname = userInfo?.nickname ?? '';
const icon = userInfo?.avatar ?? undefined;
const content = message.content;

const title = `${Translate.from} ${nickname}`;
const options: NotificationOptions = {
body: content,
icon,
tag: 'tailchat-message',
renotify: true,
data: message,
};
// TODO: 需要增加显示所在群组
Promise.all([
getCachedUserInfo(message.author),
message.groupId
? getCachedBaseGroupInfo(message.groupId).then((d) => d.name)
: Promise.resolve(Translate.dm),
]).then(([userInfo, scopeName]) => {
const nickname = userInfo?.nickname ?? '';
const icon = userInfo?.avatar ?? undefined;
const content = message.content;

if (registration && registration.showNotification) {
registration.showNotification(title, options);
} else {
// fallback
const notification = new Notification(title, options);
notification.onclick = (e: any) => {
const tag = e.target.tag;
const data = e.target.data;

handleMessageNotifyClick(tag, data);
};
}
const title = `${Translate.from} [${scopeName}] ${nickname}`;
const options: NotificationOptions = {
body: content,
icon,
tag: TAG,
renotify: true,
data: message,
silent: true, // 因为有提示音了,所以禁音默认音
};

if (registration && registration.showNotification) {
registration.showNotification(title, options);
} else {
// fallback
const notification = new Notification(title, options);
notification.onclick = (e: any) => {
const tag = e.target.tag;
const data = e.target.data;

handleMessageNotifyClick(tag, data);
};
}
);
});
}

incBubble();
}
tryPlayNotificationSound(); // 不管当前是不是处于活跃状态,都发出提示音
},
});
}
Expand All @@ -97,6 +121,18 @@ function handleMessageNotifyClick(tag, data) {
navigate(`/main/personal/converse/${converseId}`);
}
}
}

console.log(tag, data);
/**
* 尝试播放通知声音
*/
function tryPlayNotificationSound() {
try {
const audio = new Audio(
'/plugins/com.msgbyte.notify/assets/sounds_bing.mp3'
);
audio.play();
} catch (err) {
console.error(err);
}
}
4 changes: 4 additions & 0 deletions client/web/plugins/com.msgbyte.notify/src/translate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,4 +10,8 @@ export const Translate = {
'zh-CN': '来自',
'en-US': 'From',
}),
dm: localTrans({
'zh-CN': '私信',
'en-US': 'DM',
}),
};
1 change: 0 additions & 1 deletion client/web/plugins/com.msgbyte.notify/tsconfig.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
{
"compilerOptions": {
"baseUrl": "./src",
"esModuleInterop": true,
"jsx": "react",
"paths": {
Expand Down
1 change: 1 addition & 0 deletions client/web/src/plugin/common/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ export {
getServiceUrl,
getCachedUserInfo,
getCachedConverseInfo,
getCachedBaseGroupInfo,
localTrans,
getLanguage,
sharedEvent,
Expand Down
16 changes: 15 additions & 1 deletion pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit 350371d

Please sign in to comment.