import {
configEventName,
configRequestEventName,
defaultOptions,
} from "./config";
import modalCSS from "./gentle-alerts.css?raw";
import notificationAudio from "./notification.ogg";
// HTML to show the modal
export const modalHTML = "\
";
// Global Modal value so that modal messages can be queued
let modal: Modal | undefined = undefined;
// User configs, sent over a DOM event by bootstrap.ts. This script is injected
// into the page's main world, so it has neither the chrome.* APIs to read them
// itself nor a currentScript to hang a dataset off of. The page can forge the
// event, but the options only choose a timeout and a notification sound.
const config: Record = {};
// Interval to wait within a double flash
export const flashInterval = 1250;
// Interval to wait between double flashes
const flashWaitMultiple = 6;
// Time to wait until notification disappears
// A value of 0 disables auto-closing, as documented in options.htm
export let modalTimeout = defaultOptions.modalTimeout;
// Set the time to wait until the notification disappears. Exported because ES
// module bindings are read-only for importers, so callers outside this module
// need a setter rather than assigning to the binding directly. Config values
// arrive as strings, so normalize to a number here.
export function setModalTimeout(value: number | string): void {
modalTimeout = Number(value);
}
// Keys to close modals
const enterCode = "Enter";
const escapeCode = "Escape";
const spaceCode = "Space";
const closeModalCodes = [enterCode, escapeCode, spaceCode];
// The window properties that are hijacked to detect a modal-closing interaction
type WindowEventName = "onclick" | "onkeyup";
// window.onclick and window.onkeyup are declared with different event types, so
// assigning one shared handler to either needs an indexable view of window
type WindowEventHandlers = Record;
// getConfig function to read a user config, falling back to a default
function getConfig(property: string, defaultValue: T): string | T {
const value = config[property];
if (value) {
return value;
}
return defaultValue;
}
// Track whether the CSS has already been injected
let cssInjected = false;
// Add the modal's styles to the page. The stylesheet is bundled into this
// script as text rather than fetched over a chrome-extension:// URL, which
// would show up in the page's DevTools Network list. It stays deferred until
// the first alert so that pages without alerts are left untouched.
function injectCSS(): void {
if (cssInjected) {
return;
}
const style = document.createElement("style");
style.textContent = modalCSS;
(document.head||document.documentElement).appendChild(style);
cssInjected = true;
}
// Store the options carried by a config event. Exported for testing; the
// listener below is what bootstrap.ts actually reaches.
export function receiveConfig(event: Event): void {
const detail = (event as CustomEvent).detail;
if (typeof detail !== "string") {
return;
}
let options: unknown;
try {
options = JSON.parse(detail);
} catch {
return;
}
if (typeof options !== "object" || options === null) {
return;
}
Object.entries(options).forEach(function([key, value]) {
config[key] = String(value);
});
}
// Frequency at which the audio notification sounds
type AudioNotificationFrequency = "none" | "once" | "repeating";
let audioNotificationFrequency = defaultOptions.audioNotificationFrequency as AudioNotificationFrequency;
// Audio played during a notification, inlined into the bundle as a data URI
let audioNotificationFile: string | undefined = notificationAudio;
// Set the audio file played during a notification. Exported for the same
// reason as setModalTimeout: ES module bindings are read-only for importers.
export function setAudioNotificationFile(value: string | undefined): void {
audioNotificationFile = value;
}
export class Modal {
msgQueue: string[] = [];
modalElement: HTMLElement | undefined = undefined;
notification: ReturnType | undefined = undefined;
originalTitle: string | undefined = undefined;
// Add messages to the Modal queue
queueMsg(msg: string): void {
this.msgQueue.push(msg);
this.generateModal();
}
// Create a modal from modalHTML and append to the bottom of the document
createModal(msg: string): void {
const span = document.createElement("span");
span.id = "gentle-alerts-modal";
span.innerHTML = modalHTML;
document.documentElement.appendChild(span);
const modalContent = span.querySelector("#gentle-alerts-modal-content-text");
if (modalContent) {
modalContent.textContent = msg;
}
this.modalElement = span;
this.modalElement.style.display = "block";
this.notify();
}
// Find and delete the modal
deleteModal(): void {
if (this.modalElement === undefined) {
return;
}
this.modalElement.remove();
this.modalElement = undefined;
this.stopFlashTab();
}
// Create, set the modal content, and show it
generateModal(): void {
if (this.modalElement) {
return;
}
const msg = this.msgQueue.shift();
if (msg === undefined) {
return;
}
this.createModal(msg);
this.registerModalClose();
}
// Set up an event to process closing the modal
registerModalClose(): void {
const originalCallbacks: Partial = {};
let timeoutTimer: ReturnType | undefined = undefined;
const isOnclick = (onClickEvent: Event): boolean => {
return onClickEvent.target === this.modalElement;
};
const isOnKeyUp = (onKeyUpEvent: Event): boolean => {
return closeModalCodes.indexOf((onKeyUpEvent as KeyboardEvent).code) >= 0;
};
const generateEvent = (onClickCorrect: (event: Event) => boolean, windowEvent: WindowEventName) => {
const windowHandlers = window as unknown as WindowEventHandlers;
originalCallbacks[windowEvent] = windowHandlers[windowEvent];
const callback = (eventObject: Event) => {
if (!onClickCorrect(eventObject)) {
return;
}
this.deleteModal();
(Object.keys(originalCallbacks) as WindowEventName[]).forEach(function (key) {
windowHandlers[key] = originalCallbacks[key];
});
clearTimeout(timeoutTimer);
this.generateModal();
eventObject.preventDefault();
return false;
};
windowHandlers[windowEvent] = callback;
};
// When the user clicks anywhere outside of the modal, close it
generateEvent(isOnclick, "onclick");
generateEvent(isOnKeyUp, "onkeyup");
// When the modal times out, close it. A timeout of 0 means "never
// auto-close" rather than setTimeout's "fire on the next tick".
if (modalTimeout > 0) {
timeoutTimer = setTimeout(function callback() {
const keyUpEvent = new KeyboardEvent("keyup", {code: escapeCode});
window.onkeyup?.(keyUpEvent);
}, modalTimeout);
}
}
// Start flashing the tab and sounding the audio notification. The first
// notification fires immediately rather than on the first setInterval tick:
// waiting for the tick delayed it by a whole flash cycle, and browsers
// throttle or freeze timers in hidden tabs, which is exactly where an alert
// most needs announcing.
notify(): void {
const originalTitle = document.title;
this.originalTitle = originalTitle;
let notified = false;
const flashOn = () => {
const playAudio = (audioNotificationFrequency === "once" && !notified)
|| audioNotificationFrequency === "repeating";
if (audioNotificationFile && playAudio) {
const audio = new Audio(audioNotificationFile);
audio.play().catch(() => {});
}
notified = true;
document.title = originalTitle + " - Alert";
setTimeout(() => {
// Skip the restore if the modal is already gone: stopFlashTab has
// restored the title and the page may have set its own since
if (this.originalTitle !== undefined) {
document.title = originalTitle;
}
}, flashInterval);
};
flashOn();
this.notification = setInterval(flashOn, flashInterval * flashWaitMultiple);
}
// Stop flashing tab and restore the title the page had before flashing
stopFlashTab(): void {
clearInterval(this.notification);
if (this.originalTitle !== undefined) {
document.title = this.originalTitle;
this.originalTitle = undefined;
}
}
}
function gentleAlert(msg: string): void {
injectCSS();
// The config value is unvalidated; an unrecognized frequency
// simply matches none of the comparisons in notify() and plays no audio
audioNotificationFrequency = getConfig(
"audioNotificationFrequency",
audioNotificationFrequency,
) as AudioNotificationFrequency;
setModalTimeout(getConfig("modalTimeout", modalTimeout));
if (modal === undefined) {
modal = new Modal();
}
modal.queueMsg(msg);
}
if (typeof window !== "undefined" && typeof window.alert !== "undefined") {
window.alert = gentleAlert;
document.addEventListener(configEventName, receiveConfig);
// bootstrap.ts may have already sent the options before this script was
// injected, so ask rather than wait
document.dispatchEvent(new Event(configRequestEventName));
}