Show a message preview in web notifications

This commit is contained in:
Coracle-Bot 2026-09-09 01:31:37 +00:00 committed by hodlbod
parent 0b4bb849f3
commit f750bf8fd4

View file

@ -1,5 +1,6 @@
import type {Unsubscriber} from "svelte/store"
import {maybe} from "@welshman/lib"
import {parse, renderAsText} from "@welshman/content"
import {ellipsize, maybe} from "@welshman/lib"
import {hexTags, matchFilter, tagValues, type TrustedEvent} from "@welshman/util"
import {DM_KINDS} from "@app/content"
import {app} from "@app/core"
@ -8,6 +9,15 @@ import type {IPushAdapter} from "@app/push/adapters/common"
import {onNotification} from "@app/push/adapters/common"
import {goToEvent} from "@app/routes"
const PREVIEW_LENGTH = 120
const makePreview = (event: TrustedEvent) => {
const lines = renderAsText(parse(event)).toString().split("\n")
const line = lines.map(line => line.trim()).find(line => line.length > 0)
return line && ellipsize(line, PREVIEW_LENGTH, "…")
}
export class WebNotifications implements IPushAdapter {
_unsubscriber = maybe<Unsubscriber>()
@ -52,12 +62,22 @@ export class WebNotifications implements IPushAdapter {
const $pubkey = app.get().user?.pubkey
if (push && document.hidden && Notification?.permission === "granted") {
const preview = makePreview(event)
if (messages && matchFilter({kinds: DM_KINDS}, event)) {
this._notify(event, "New direct message", "Someone sent you a direct message.")
this._notify(
event,
"New direct message",
preview || "Someone sent you a direct message.",
)
} else if (mentions && $pubkey && tagValues(hexTags("p"), event.tags).includes($pubkey)) {
this._notify(event, "Someone mentioned you", "Someone tagged you in a message.")
this._notify(
event,
"Someone mentioned you",
preview || "Someone tagged you in a message.",
)
} else if (spaces) {
this._notify(event, "New activity", "Someone posted a new message.")
this._notify(event, "New activity", preview || "Someone posted a new message.")
}
}
})