Skip to content

Open source website builder and Webflow alternative. Webstudio is an advanced visual builder that connects to any headless CMS, supports all CSS properties, and can be hosted anywhere, including with us.

fix: Fix browser notification polling behavior (#5740)

Oleg Isonen34091b370d3d
diff --git a/apps/builder/app/shared/notifications/browser-notification.ts b/apps/builder/app/shared/notifications/browser-notification.ts
index de4b61a385..37062d2b37 100644
--- a/apps/builder/app/shared/notifications/browser-notification.ts
+++ b/apps/builder/app/shared/notifications/browser-notification.ts
@@ -36,11 +36,11 @@ export const requestNotificationPermission =
*
* Will silently no-op when:
* - Permission hasn't been granted.
- * - The tab is currently focused (the in-app toast is enough).
+ * - The tab is currently focused, unless `showWhenFocused` is true.
*/
export const showBrowserNotification = (
title: string,
- options?: NotificationOptions
+ options?: NotificationOptions & { showWhenFocused?: boolean }
) => {
if (typeof Notification === "undefined") {
return;
@@ -50,10 +50,12 @@ export const showBrowserNotification = (
}
// Skip when the user is already looking at the page — the in-app
// toast handles that case.
- if (document.hasFocus()) {
+ if (options?.showWhenFocused !== true && document.hasFocus()) {
return;
}
- const notification = new Notification(title, options);
+ const { showWhenFocused, ...notificationOptions } = options ?? {};
+ void showWhenFocused;
+ const notification = new Notification(title, notificationOptions);
notification.onclick = () => {
window.focus();
notification.close();
diff --git a/apps/builder/app/shared/notifications/subscription.tsx b/apps/builder/app/shared/notifications/subscription.tsx
index 4e4806884d..6c453d138e 100644
--- a/apps/builder/app/shared/notifications/subscription.tsx
+++ b/apps/builder/app/shared/notifications/subscription.tsx
@@ -20,11 +20,15 @@ import {
import { publicStaticEnv } from "~/env/env.static";
const knownNotificationTypes = new Set<string>(notificationTypes);
+const NEW_NOTIFICATIONS_TOAST_DURATION = 10_000;
export const $notifications = atom<Notifications>([]);
export const $shouldRevalidateProjects = atom(0);
let manager: ReturnType<typeof createCrossTabPollingManager> | undefined;
+const pendingBrowserNotificationTimeouts = new Set<
+ ReturnType<typeof setTimeout>
+>();
export const refreshNotifications = () => manager?.refresh();
@@ -49,6 +53,7 @@ export const startSubscription = () => {
nativeClient.polly.poll.query({
topics,
}) as Promise<SubscriptionResponse>,
+ pauseOnHidden: false,
onError: (error) => {
console.warn("[subscription] poll failed", error);
},
@@ -71,11 +76,32 @@ export const startSubscription = () => {
const hasNew = known.some((n) => prevIds.has(n.id) === false);
if (hasNew) {
- toast.info("You have new notifications");
- // Best-effort browser notification (may be silenced by the OS).
- showBrowserNotification("Webstudio", {
- body: "You have new notifications",
+ const newIds = new Set(
+ known.filter((n) => prevIds.has(n.id) === false).map((n) => n.id)
+ );
+ toast.info("You have new notifications", {
+ duration: NEW_NOTIFICATIONS_TOAST_DURATION,
});
+ // Best-effort browser notification (may be silenced by the OS).
+ if (document.hasFocus()) {
+ const timeoutId = setTimeout(() => {
+ pendingBrowserNotificationTimeouts.delete(timeoutId);
+ const hasUnresolvedNewNotification = $notifications
+ .get()
+ .some((n) => newIds.has(n.id));
+ if (hasUnresolvedNewNotification) {
+ showBrowserNotification("Webstudio", {
+ body: "You have new notifications",
+ showWhenFocused: true,
+ });
+ }
+ }, NEW_NOTIFICATIONS_TOAST_DURATION);
+ pendingBrowserNotificationTimeouts.add(timeoutId);
+ } else {
+ showBrowserNotification("Webstudio", {
+ body: "You have new notifications",
+ });
+ }
}
};
@@ -115,6 +141,10 @@ export const startSubscription = () => {
};
export const stopSubscription = () => {
+ for (const timeoutId of pendingBrowserNotificationTimeouts) {
+ clearTimeout(timeoutId);
+ }
+ pendingBrowserNotificationTimeouts.clear();
manager?.destroy();
manager = undefined;
};
diff --git a/apps/builder/app/shared/polly/polling-manager.test.ts b/apps/builder/app/shared/polly/polling-manager.test.ts
index 16a64d82d4..9fb07f7012 100644
--- a/apps/builder/app/shared/polly/polling-manager.test.ts
+++ b/apps/builder/app/shared/polly/polling-manager.test.ts
@@ -54,6 +54,40 @@ describe("createPollingManager", () => {
manager.destroy();
});
+ test("can keep polling when document is hidden", async () => {
+ const addSpy = vi.spyOn(document, "addEventListener");
+ const fetcher = createMockFetcher();
+ const manager = createPollingManager({
+ fetcher,
+ interval: 1_000,
+ pauseOnHidden: false,
+ });
+
+ manager.subscribe("notifications", vi.fn());
+ await flush();
+
+ expect(addSpy).not.toHaveBeenCalledWith(
+ "visibilitychange",
+ expect.any(Function)
+ );
+
+ Object.defineProperty(document, "visibilityState", {
+ value: "hidden",
+ writable: true,
+ configurable: true,
+ });
+
+ await vi.advanceTimersByTimeAsync(1_000);
+ expect(fetcher).toHaveBeenCalledTimes(2);
+
+ Object.defineProperty(document, "visibilityState", {
+ value: "visible",
+ writable: true,
+ configurable: true,
+ });
+ manager.destroy();
+ });
+
test("removing the last subscription stops polling", async () => {
const fetcher = createMockFetcher();
const manager = createPollingManager({ fetcher, interval: 1_000 });
diff --git a/apps/builder/app/shared/polly/polling-manager.ts b/apps/builder/app/shared/polly/polling-manager.ts
index da59f8dd21..ee7429ba93 100644
--- a/apps/builder/app/shared/polly/polling-manager.ts
+++ b/apps/builder/app/shared/polly/polling-manager.ts
@@ -38,6 +38,11 @@ export type PollingManagerOptions = {
* @default 30_000
*/
interval?: number;
+ /**
+ * Pause polling while the document is hidden.
+ * @default true
+ */
+ pauseOnHidden?: boolean;
/** Called when the fetcher throws. */
onError?: (error: unknown) => void;
};
@@ -68,7 +73,7 @@ export type PollingManager = {
export const createPollingManager = (
options: PollingManagerOptions
): PollingManager => {
- const { fetcher, interval, onError } = options;
+ const { fetcher, interval, pauseOnHidden, onError } = options;
// ── Subscription bookkeeping ───────────────────────────────────
@@ -121,6 +126,7 @@ export const createPollingManager = (
// Always reads the *current* set of topics at call time.
fetcher: () => fetcher(getActiveTopics()),
interval,
+ pauseOnHidden,
onData: dispatch,
onError,
});