Skip to content

Commit

Permalink
lib: Add types to pkg/lib/notifications
Browse files Browse the repository at this point in the history
  • Loading branch information
mvollmer committed Dec 18, 2024
1 parent 6cb171d commit 78abdab
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 12 deletions.
1 change: 1 addition & 0 deletions pkg/lib/cockpit.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
30 changes: 18 additions & 12 deletions pkg/lib/notifications.js → pkg/lib/notifications.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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;
}
Expand All @@ -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 });
}
}
}
Expand Down

0 comments on commit 78abdab

Please sign in to comment.