ts migration: Convert `favicon.js` to `favicon.ts`.

Added type annotations to function parameters, function return
values and local variables. Added neccessary `if` statements to
enforce the objects having proper type before executing the later
operations.

An error type check in the catch block in `update_favicon`
function is added because the statement in the catch block requires
error to be a type `Error` in order to access `error.stack`.
This commit is contained in:
AcKindle3 2023-03-24 17:02:09 -04:00 committed by Tim Abbott
parent c575d62d5a
commit ac4ec8888a
3 changed files with 19 additions and 7 deletions

View File

@ -84,7 +84,7 @@ EXEMPT_FILES = make_set(
"web/src/echo.js",
"web/src/emoji_picker.js",
"web/src/emojisets.js",
"web/src/favicon.js",
"web/src/favicon.ts",
"web/src/feature_flags.ts",
"web/src/feedback_widget.js",
"web/src/flatpickr.js",

5
web/src/assets.d.ts vendored
View File

@ -2,3 +2,8 @@ declare module "*.svg" {
const url: string;
export default url;
}
declare module "*.ttf" {
const url: string;
export default url;
}

View File

@ -6,9 +6,9 @@ import render_favicon_svg from "../templates/favicon.svg.hbs";
import * as blueslip from "./blueslip";
import favicon_font_url from "./favicon_font_url!=!url-loader!font-subset-loader2?glyphs=0123456789KMGT∞!source-sans/TTF/SourceSans3-Bold.ttf";
let favicon_state;
let favicon_state: {image: HTMLImageElement; url: string} | undefined;
function load_and_set_favicon(rendered_favicon) {
function load_and_set_favicon(rendered_favicon: string): void {
favicon_state = {
url: URL.createObjectURL(new Blob([rendered_favicon], {type: "image/svg+xml"})),
image: new Image(),
@ -19,12 +19,13 @@ function load_and_set_favicon(rendered_favicon) {
favicon_state.image.src = favicon_state.url;
favicon_state.image.addEventListener("load", set_favicon);
}
function set_favicon() {
function set_favicon(): void {
if (favicon_state === undefined) {
throw new Error("Programming error: favicon_state must be set.");
}
$("#favicon").attr("href", favicon_state.url);
}
export function update_favicon(new_message_count, pm_count) {
export function update_favicon(new_message_count: number, pm_count: number): void {
try {
if (favicon_state !== undefined) {
favicon_state.image.removeEventListener("load", set_favicon);
@ -62,6 +63,12 @@ export function update_favicon(new_message_count, pm_count) {
load_and_set_favicon(rendered_favicon);
} catch (error) {
// Error must be a type of Error in order to access error.stack
// The undetermined error was mentioned in this issue:
// https://github.com/zulip/zulip/issues/18374
if (!(error instanceof Error)) {
throw error;
}
blueslip.error("Failed to update favicon", undefined, error.stack);
}
}