Skip to content

armgit / zulip

Public Imported from GitHub
0

Zulip server and web application. Open-source team chat that helps teams stay productive and focused.

6.4 KB
Raw Blame
import {$} from "jquery";
import assert from "minimalistic-assert";

import {electron_bridge} from "./electron_bridge.ts";

export type NotificationData = {type: "message"; message_id: number; msg_count: number};

type NoticeMemory = Map<
    string,
    {
        obj: Notification | ElectronBridgeNotification;
        data: NotificationData;
    }
>;

export const notice_memory: NoticeMemory = new Map();

export let NotificationAPI: typeof ElectronBridgeNotification | typeof Notification | undefined;

// Used for testing
export function set_notification_api(n: typeof NotificationAPI): void {
    NotificationAPI = n;
}

export class ElectronBridgeNotification extends EventTarget {
    title: string;
    dir: NotificationDirection;
    lang: string;
    body: string;
    tag: string;
    icon: string;
    data: unknown;
    close: () => void;

    constructor(title: string, options: NotificationOptions) {
        super();
        assert(electron_bridge?.new_notification !== undefined);
        const notification_data = electron_bridge.new_notification(
            title,
            options,
            (type, eventInit) => this.dispatchEvent(new Event(type, eventInit)),
        );
        this.title = notification_data.title;
        this.dir = notification_data.dir;
        this.lang = notification_data.lang;
        this.body = notification_data.body;
        this.tag = notification_data.tag;
        this.icon = notification_data.icon;
        this.data = notification_data.data;
        this.close = notification_data.close;
    }

    static get permission(): NotificationPermission {
        return Notification.permission;
    }

    static async requestPermission(
        callback?: (permission: NotificationPermission) => void,
    ): Promise<NotificationPermission> {
        if (callback) {
            callback(await Promise.resolve(Notification.permission));
        }
        return Notification.permission;
    }
}

// Most mobile browsers expose the Notification interface, but
// support only persistent notifications, which are created via
// ServiceWorkerRegistration.showNotification().
// The Notification() constructor throws a TypeError there, so until
// we register a service worker, treat them as having no support.
// See https://developer.mozilla.org/en-US/docs/Web/API/Notifications_API#persistent_and_non-persistent_notifications
function maybe_construct_notification(
    title: string,
    options: NotificationOptions,
): ElectronBridgeNotification | Notification | undefined {
    if (NotificationAPI === undefined) {
        return undefined;
    }
    try {
        return new NotificationAPI(title, options);
    } catch (error) {
        if (!(error instanceof TypeError)) {
            throw error;
        }
        NotificationAPI = undefined;
        return undefined;
    }
}

if (electron_bridge?.new_notification) {
    NotificationAPI = ElectronBridgeNotification;
} else if (window.Notification) {
    NotificationAPI = window.Notification;
    if (Notification.permission !== "granted") {
        // A notification constructed without permission is never
        // displayed, which lets us check the constructor without
        // bothering the user. Once permission has been granted we
        // cannot make this check, so we treat the browser as supported
        // until a notification first fails to be constructed.
        maybe_construct_notification("", {})?.close();
    }
}

export function create_notification(opts: {
    notification_options: NotificationOptions;
    key: string;
    title: string;
    data: NotificationData;
    on_click?: (() => void) | undefined;
}): void {
    const {notification_options, key, title, data, on_click} = opts;
    const existing_notification = notice_memory.get(key);
    if (existing_notification) {
        existing_notification.obj.close();
    }

    if (!granted_desktop_notifications_permission()) {
        return;
    }

    const notification_object = maybe_construct_notification(title, notification_options);
    if (notification_object === undefined) {
        return;
    }
    notice_memory.set(key, {
        obj: notification_object,
        data,
    });

    if (typeof notification_object.addEventListener === "function") {
        // Sadly, some third-party Electron apps like Franz/Ferdi
        // misimplement the Notification API not inheriting from
        // EventTarget.  This results in addEventListener being
        // unavailable for them.
        notification_object.addEventListener("click", () => {
            notification_object.close();
            on_click?.();
            window.focus();
        });
        notification_object.addEventListener("close", () => {
            const current_notice_memory = notice_memory.get(key);
            // This check helps avoid race between close event for current notification
            // object and the previous notification_object close handler.
            if (current_notice_memory?.obj === notification_object) {
                notice_memory.delete(key);
            }
        });
    }
}

export function get_notifications(): NoticeMemory {
    return notice_memory;
}

export function initialize(): void {
    $(window).on("focus", () => {
        for (const notice_mem_entry of notice_memory.values()) {
            notice_mem_entry.obj.close();
        }
        notice_memory.clear();
    });
}

// Utility function for testing support for the Notifications API
export function has_notification_support(): boolean {
    return NotificationAPI !== undefined;
}

export function permission_state(): string {
    if (NotificationAPI) {
        return NotificationAPI.permission;
    }
    // Act like notifications are blocked if a UA
    // has no access to the notification API.
    return "denied";
}

export function close_notification(message_id: number): void {
    for (const [key, notice_mem_entry] of notice_memory) {
        if (notice_mem_entry.data.message_id === message_id) {
            notice_mem_entry.obj.close();
            notice_memory.delete(key);
        }
    }
}

export function granted_desktop_notifications_permission(): boolean {
    return NotificationAPI?.permission === "granted";
}

export async function request_desktop_notifications_permission(): Promise<NotificationPermission> {
    if (NotificationAPI) {
        return await NotificationAPI.requestPermission();
    }
    // Act like notifications are blocked if a UA
    // has no access to the notification API.
    return "denied";
}