| 1 |
import { errorWithCauses } from "./lib/errors"; |
| 2 |
import { log_error } from "./log"; |
| 3 |
|
| 4 |
/** The notification list div, lazily created. */ |
| 5 |
const notificationList = (() => { |
| 6 |
let value: HTMLDivElement | null = null; |
| 7 |
return () => { |
| 8 |
if (value === null) { |
| 9 |
value = document.createElement("div"); |
| 10 |
value.className = "notifications"; |
| 11 |
value.style.right = "10px"; |
| 12 |
document.body.appendChild(value); |
| 13 |
} |
| 14 |
// always update the distance to top to account for the current header height |
| 15 |
const headerHeight = |
| 16 |
document.querySelector("header")?.getBoundingClientRect().height ?? 50; |
| 17 |
value.style.top = `${(headerHeight + 10).toString()}px`; |
| 18 |
return value; |
| 19 |
}; |
| 20 |
})(); |
| 21 |
|
| 22 |
type NotificationType = "info" | "warning" | "error"; |
| 23 |
|
| 24 |
/** |
| 25 |
* Show a notification containing the given `msg` text and having class `cls`. |
| 26 |
* The notification is automatically removed after 5 seconds and on click |
| 27 |
* `callback` is called. |
| 28 |
* |
| 29 |
* @param msg - The message to diplay |
| 30 |
* @param cls - The message type. |
| 31 |
* @param callback - The callback to execute on click.. |
| 32 |
*/ |
| 33 |
export function notify( |
| 34 |
msg: string, |
| 35 |
cls: NotificationType = "info", |
| 36 |
callback?: () => void, |
| 37 |
): void { |
| 38 |
const notification = document.createElement("li"); |
| 39 |
notification.classList.add(cls); |
| 40 |
notification.appendChild(document.createTextNode(msg)); |
| 41 |
notificationList().append(notification); |
| 42 |
notification.addEventListener("click", () => { |
| 43 |
notification.remove(); |
| 44 |
callback?.(); |
| 45 |
}); |
| 46 |
setTimeout(() => { |
| 47 |
notification.remove(); |
| 48 |
}, 5000); |
| 49 |
} |
| 50 |
|
| 51 |
/** |
| 52 |
* Notify the user about an warning and log to console. |
| 53 |
*/ |
| 54 |
export function notify_warn(msg: string): void { |
| 55 |
notify(msg, "warning"); |
| 56 |
|
| 57 |
console.warn(msg); |
| 58 |
} |
| 59 |
|
| 60 |
/** |
| 61 |
* Notify the user about an error and log to console. |
| 62 |
*/ |
| 63 |
export function notify_err( |
| 64 |
error: unknown, |
| 65 |
msg: (e: Error) => string = errorWithCauses, |
| 66 |
): void { |
| 67 |
if (error instanceof Error) { |
| 68 |
notify(msg(error), "error"); |
| 69 |
} |
| 70 |
log_error(error); |
| 71 |
} |