()
| 16 | const TAG = 'tailchat-message'; |
| 17 | |
| 18 | export function initNotify() { |
| 19 | if (Notification.permission === 'default') { |
| 20 | Notification.requestPermission(); |
| 21 | } |
| 22 | |
| 23 | const registration: ServiceWorkerRegistration | null = |
| 24 | getServiceWorkerRegistration(); |
| 25 | if (registration) { |
| 26 | registration.addEventListener('notificationclick', (e: any) => { |
| 27 | const tag = e.notification.tag; |
| 28 | const data = e.notification.data; |
| 29 | |
| 30 | handleMessageNotifyClick(tag, data); |
| 31 | }); |
| 32 | } |
| 33 | |
| 34 | let isBlur = false; |
| 35 | window.addEventListener('focus', () => { |
| 36 | setBubble(0); // 点击时清空 |
| 37 | isBlur = false; |
| 38 | }); |
| 39 | window.addEventListener('blur', () => (isBlur = true)); |
| 40 | |
| 41 | sharedEvent.on('receiveUnmutedMessage', (message) => { |
| 42 | const currentUserId = getGlobalState()?.user.info._id; |
| 43 | |
| 44 | if (currentUserId === message.author) { |
| 45 | // 忽略本人消息 |
| 46 | return; |
| 47 | } |
| 48 | |
| 49 | const hidden = window.document.hidden ?? false; |
| 50 | if (hidden || isBlur) { |
| 51 | // 如果当前不是活跃窗口或处于隐藏状态,则创建通知 |
| 52 | |
| 53 | if (Notification.permission === 'granted') { |
| 54 | // TODO: 需要增加显示所在群组 |
| 55 | Promise.all([ |
| 56 | getCachedUserInfo(message.author), |
| 57 | message.groupId |
| 58 | ? getCachedBaseGroupInfo(message.groupId).then((d) => d.name) |
| 59 | : Promise.resolve(Translate.dm), |
| 60 | ]).then(([userInfo, scopeName]) => { |
| 61 | const nickname = userInfo?.nickname ?? ''; |
| 62 | const icon = userInfo?.avatar ?? undefined; |
| 63 | const content = getMessageTextDecorators().serialize(message.content); // 只显示无富文本形式的消息 |
| 64 | |
| 65 | const title = `${Translate.from} [${scopeName}] ${nickname}`; |
| 66 | const options: NotificationOptions = { |
| 67 | body: content, |
| 68 | icon, |
| 69 | tag: TAG, |
| 70 | renotify: true, |
| 71 | data: message, |
| 72 | silent: true, // 因为有提示音了,所以禁音默认音 |
| 73 | }; |
| 74 | |
| 75 | if (registration && registration.showNotification) { |
no test coverage detected