perf: notification supports clicking to open the source website

This commit is contained in:
molvqingtai 2024-10-13 06:13:45 +08:00
parent aa3c0703dc
commit 653229c8fa
3 changed files with 37 additions and 10 deletions

View file

@ -1,14 +1,16 @@
import { EVENT } from '@/constants/event'
import { messenger } from '@/messenger'
import { browser } from 'wxt/browser'
import { browser, Tabs } from 'wxt/browser'
import { defineBackground } from 'wxt/sandbox'
export default defineBackground({
type: 'module',
main() {
const historyNotificationTabs = new Map<string, Tabs.Tab>()
messenger.onMessage(EVENT.OPTIONS_PAGE_OPEN, () => {
browser.runtime.openOptionsPage()
})
messenger.onMessage(EVENT.NOTIFICATION_PUSH, async ({ data: message, sender }) => {
// Check if there is an active tab on the same site
const tabs = await browser.tabs.query({ active: true })
@ -17,15 +19,46 @@ export default defineBackground({
})
if (hasActiveSomeSiteTab) return
browser.notifications.create(message.id, {
type: 'basic',
iconUrl: message.userAvatar,
title: message.username,
message: message.body
message: message.body,
contextMessage: sender.tab!.url!
})
historyNotificationTabs.set(message.id, sender.tab!)
})
messenger.onMessage(EVENT.NOTIFICATION_CLEAR, async ({ data: id }) => {
browser.notifications.clear(id)
})
browser.notifications.onButtonClicked.addListener(async (id) => {
const fromTab = historyNotificationTabs.get(id)
if (fromTab?.id) {
try {
const tab = await browser.tabs.get(fromTab.id)
browser.tabs.update(tab.id, { active: true })
} catch {
browser.tabs.create({ url: fromTab.url })
}
}
})
browser.notifications.onClicked.addListener(async (id) => {
const fromTab = historyNotificationTabs.get(id)
if (fromTab?.id) {
try {
const tab = await browser.tabs.get(fromTab.id)
browser.tabs.update(tab.id, { active: true })
} catch {
browser.tabs.create({ url: fromTab.url })
}
}
})
browser.notifications.onClosed.addListener(async (id) => {
historyNotificationTabs.delete(id)
})
}
})

View file

@ -3,16 +3,12 @@ import { TextMessage } from '../Room'
export interface Notification {
push: (message: TextMessage) => Promise<string>
clear: (id: string) => Promise<boolean>
}
export const NotificationExtern = Remesh.extern<Notification>({
default: {
push: () => {
throw new Error('"push" not implemented.')
},
clear: () => {
throw new Error('"clear" not implemented.')
}
}
})

View file

@ -4,14 +4,12 @@ import { EVENT } from '@/constants/event'
import { messenger } from '@/messenger'
class Notification {
messages: TextMessage[] = []
async push(message: TextMessage) {
await messenger.sendMessage(EVENT.NOTIFICATION_PUSH, message)
this.messages.push(message)
return message.id
}
async clear(id: string) {
await messenger.sendMessage(EVENT.NOTIFICATION_CLEAR, id)
return true
}
}
export const NotificationImpl = NotificationExtern.impl(new Notification())