From 78abdab0a03d65f490317f1332c6f5f9d2eb7923 Mon Sep 17 00:00:00 2001 From: Marius Vollmer Date: Tue, 17 Dec 2024 14:36:48 +0200 Subject: [PATCH] lib: Add types to pkg/lib/notifications --- pkg/lib/cockpit.d.ts | 1 + .../{notifications.js => notifications.ts} | 30 +++++++++++-------- 2 files changed, 19 insertions(+), 12 deletions(-) rename pkg/lib/{notifications.js => notifications.ts} (89%) diff --git a/pkg/lib/cockpit.d.ts b/pkg/lib/cockpit.d.ts index 99524c268755..946b362bb1c3 100644 --- a/pkg/lib/cockpit.d.ts +++ b/pkg/lib/cockpit.d.ts @@ -44,6 +44,7 @@ declare module 'cockpit' { wait(callback: (transport: Transport) => void): void; close(problem?: string): void; application(): string; + control(command: string, options: JsonObject): void; } export const transport: Transport; diff --git a/pkg/lib/notifications.js b/pkg/lib/notifications.ts similarity index 89% rename from pkg/lib/notifications.js rename to pkg/lib/notifications.ts index ef150db4c766..d29286a00e0a 100644 --- a/pkg/lib/notifications.js +++ b/pkg/lib/notifications.ts @@ -115,28 +115,34 @@ Usage: */ -import cockpit from "cockpit"; +import cockpit, { JsonValue, JsonObject } from "cockpit"; import { dequal } from 'dequal/lite'; -class PageStatus { +export interface Status { + type?: string | null; + title?: string; + details?: JsonObject; +} + +class PageStatus extends EventTarget { + valid: boolean = false; + cur_own: Status | null = null; + constructor() { - cockpit.event_target(this); + super(); window.addEventListener("storage", event => { if (event.key == "cockpit:page_status") { - this.dispatchEvent("changed"); + this.dispatchEvent(new CustomEvent("changed")); } }); - this.cur_own = null; - - this.valid = false; cockpit.transport.wait(() => { this.valid = true; - this.dispatchEvent("changed"); + this.dispatchEvent(new CustomEvent("changed")); }); } - get(page, host) { + get(page: string, host?: string): Status | null | undefined { let page_status; if (!this.valid) @@ -146,7 +152,7 @@ class PageStatus { host = cockpit.transport.host; try { - page_status = JSON.parse(sessionStorage.getItem("cockpit:page_status")); + page_status = JSON.parse(sessionStorage.getItem("cockpit:page_status") || "{}"); } catch { return null; } @@ -156,10 +162,10 @@ class PageStatus { return null; } - set_own(status) { + set_own(status: Status | null) { if (!dequal(status, this.cur_own)) { this.cur_own = status; - cockpit.transport.control("notify", { page_status: status }); + cockpit.transport.control("notify", { page_status: status as JsonValue }); } } }