Files
ihasmail-inbuxa/web/src/lib/notify/notify.ts
T
jcoffey-dev bd6a605d61 Group six more clusters out of web/src/lib
Takes the flat module count from 66 to 42, continuing what admin/ and
calendar/ started.

  lib/mailbox/  archiveDate, emptyFolder, folderMove, labelTree,
                mailboxName, mailboxRoute
  lib/sieve/    sieve, sieveApply, sieveFolders
  lib/input/    keyboard, swipe, touch, listSelection, dropUpload
  lib/notify/   notify, webpush, webpushEnable
  lib/sw/       swCache, swFacts, staleBuild
  lib/text/     html, markdown, text, emlName

FOUR THINGS THE FILENAMES GET WRONG, each checked by reading the file
rather than trusting what it is called:

  - appFolder is not a mailbox. It is the `ihasmail` folder in JMAP
    *Files*, where the client keeps signature images and synced settings.
    It stays flat.
  - format holds no formatting of text. It re-exports the date and clock
    formatters, so it belongs with dates/datetime, not with text/.
  - preview is the file viewer deciding what it can show without
    downloading, and source is where to point someone asking for this
    instance's AGPL source. Neither is about text.
  - notify is not Web Push. It is the tab title, the favicon badge and
    the new-mail sound -- in-app notification, which is why it sits with
    webpush rather than under sw/ with the service worker's own concerns.

threadScroll stays flat too: it decides where a conversation opens, which
is view state rather than a gesture, and input/ is honest only if
everything in it interprets something the reader did.

No behavior change. Almost every reference was on the @/ alias; eight
relative imports in files that did not move, or that moved away from a
sibling, needed rewriting by hand.
2026-09-15 23:17:50 -07:00

122 lines
4.2 KiB
TypeScript

import { withBase } from "../basePath";
let baseTitle = "ihasmail";
let faviconCanvas: HTMLCanvasElement | null = null;
let baseFavicon: HTMLImageElement | null = null;
export function setBaseTitle(t: string) {
baseTitle = t;
}
/*
* The unread count on the installed app's icon.
*
* The title and the favicon below are the same idea for a tab, and an
* installed app has neither: in `display: standalone` there is no tab strip
* and no favicon anywhere on screen, so everything this file did for the
* unread count vanished at exactly the moment somebody put ihasmail on a home
* screen. The Badging API is where the count goes instead, and it is the one
* thing every phone user expects a mail icon to do.
*
* Silently nothing where it is unsupported, and silently nothing on iOS until
* notification permission has been granted, which is that platform's condition
* for showing a badge at all. Neither is worth reporting: a count that does not
* appear is not a failure anybody can act on.
*/
function setIconBadge(count: number): void {
if (!("setAppBadge" in navigator)) return;
const done = count > 0 ? navigator.setAppBadge(count) : navigator.clearAppBadge();
void done.catch(() => {
/* unsupported, or not permitted on this platform */
});
}
/** Update document title, favicon and app icon badge with unread count. */
export function setUnreadBadge(count: number): void {
document.title = count > 0 ? `(${count > 999 ? "999+" : count}) ${baseTitle}` : baseTitle;
setIconBadge(count);
try {
const link = document.querySelector<HTMLLinkElement>('link[rel="icon"][type="image/png"]');
if (!link) return;
if (!baseFavicon) {
baseFavicon = new Image();
baseFavicon.src = withBase("/img/favicon-64.png");
baseFavicon.onload = () => setUnreadBadge(count);
return;
}
if (!baseFavicon.complete) return;
if (count <= 0) {
link.href = withBase("/img/favicon-64.png");
return;
}
faviconCanvas ??= document.createElement("canvas");
const c = faviconCanvas;
c.width = 64;
c.height = 64;
const ctx = c.getContext("2d");
if (!ctx) return;
ctx.clearRect(0, 0, 64, 64);
ctx.drawImage(baseFavicon, 0, 0, 64, 64);
ctx.fillStyle = "#dc2626";
ctx.beginPath();
ctx.arc(46, 18, 16, 0, Math.PI * 2);
ctx.fill();
ctx.fillStyle = "#fff";
ctx.font = "bold 22px system-ui, sans-serif";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText(count > 99 ? "99" : String(count), 46, 19);
link.href = c.toDataURL("image/png");
} catch {
/* ignore */
}
}
export async function requestNotificationPermission(): Promise<NotificationPermission> {
if (!("Notification" in window)) return "denied";
if (Notification.permission !== "default") return Notification.permission;
try {
return await Notification.requestPermission();
} catch {
return "denied";
}
}
export function showNotification(title: string, opts: NotificationOptions & { onClick?: () => void } = {}): void {
if (!("Notification" in window) || Notification.permission !== "granted") return;
if (document.visibilityState === "visible" && document.hasFocus()) return;
try {
const n = new Notification(title, { icon: withBase("/img/icon-192.png"), badge: withBase("/img/favicon-64.png"), ...opts });
n.onclick = () => {
window.focus();
opts.onClick?.();
n.close();
};
setTimeout(() => n.close(), 8000);
} catch {
/* ignore */
}
}
let audioCtx: AudioContext | null = null;
/** Short, soft "ding" using WebAudio (no asset needed). */
export function playNewMailSound(): void {
try {
audioCtx ??= new AudioContext();
const ctx = audioCtx;
const o = ctx.createOscillator();
const g = ctx.createGain();
o.type = "sine";
o.frequency.setValueAtTime(880, ctx.currentTime);
o.frequency.exponentialRampToValueAtTime(1320, ctx.currentTime + 0.08);
g.gain.setValueAtTime(0.0001, ctx.currentTime);
g.gain.exponentialRampToValueAtTime(0.15, ctx.currentTime + 0.02);
g.gain.exponentialRampToValueAtTime(0.0001, ctx.currentTime + 0.4);
o.connect(g).connect(ctx.destination);
o.start();
o.stop(ctx.currentTime + 0.45);
} catch {
/* ignore */
}
}