From d337a46fd7ff571d090b37d675d54888456dadcd Mon Sep 17 00:00:00 2001 From: Kam Date: Wed, 30 Sep 2026 10:23:17 +0300 Subject: [PATCH 1/2] feat(overlay): add disposeOverlay and keep a single overlay per page Importing the overlay module starts it and discarded the dispose, so the auto-started overlay could not be stopped. disposeOverlay() now stops whichever overlay is running and removes the floating button, and initOverlay() stops the previous overlay before starting a new one. Dispose now also closes the devframe connection, forgets the page on the server, and aborts an overlay that is still connecting. The popup gains hideDevtools(), and showDevtools() can create it again after a destroy. Dispose removes window.__ngDevtoolsComponentOf only while it is still the lookup this overlay installed, so stopping a replaced overlay leaves the Elements-panel sync of the one that replaced it working. --- README.md | 16 +- .../src/__tests__/overlay-dispose.test.ts | 203 ++++++++++++++++++ packages/ng-devtools/src/overlay.ts | 100 ++++++--- packages/ng-devtools/src/popup.ts | 8 + 4 files changed, 299 insertions(+), 28 deletions(-) create mode 100644 packages/ng-devtools/src/__tests__/overlay-dispose.test.ts diff --git a/README.md b/README.md index c915f19f..1169ea17 100644 --- a/README.md +++ b/README.md @@ -300,9 +300,9 @@ button below; with the hub mounted, the button opens the whole hub (every dock in a side rail). `initOverlay` is exported for a devtools mounted somewhere else. Importing the -module has already started an overlay on the default URLs by then, so dispose of -that one before starting another, or the page ends up with two connections and -two polling intervals: +module has already started an overlay on the default URLs by then; calling +`initOverlay` stops that one and starts a new one, so only one runs at a time. +It resolves with a function that stops the overlay it started: ```ts import { initOverlay } from '@santoshyadavdev/ng-devtools/overlay'; @@ -310,6 +310,16 @@ import { initOverlay } from '@santoshyadavdev/ng-devtools/overlay'; const dispose = await initOverlay({ baseURL: '/__my-devtools/' }); ``` +To turn the overlay off entirely, call `disposeOverlay`. It stops whichever +overlay is running (the auto-started one included), closes its connection, +clears its timers, listeners and observers, and removes the floating button: + +```ts +import { disposeOverlay } from '@santoshyadavdev/ng-devtools/overlay'; + +await disposeOverlay(); +``` + ### In-Page Popup The devtools can appear as a floating popup directly on your page — no browser extension needed: diff --git a/packages/ng-devtools/src/__tests__/overlay-dispose.test.ts b/packages/ng-devtools/src/__tests__/overlay-dispose.test.ts new file mode 100644 index 00000000..8b6e1d18 --- /dev/null +++ b/packages/ng-devtools/src/__tests__/overlay-dispose.test.ts @@ -0,0 +1,203 @@ +// @vitest-environment jsdom +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +interface FakeClient { + close: ReturnType; + calls: string[]; +} + +const clients: FakeClient[] = []; +let connectGate: Promise = Promise.resolve(); + +vi.mock('devframe/client', () => ({ + connectDevframe: vi.fn(async () => { + const client: FakeClient = { close: vi.fn(), calls: [] }; + clients.push(client); + await connectGate; + return { + close: client.close, + scope: () => ({ + rpc: { + call: vi.fn(async (name: string) => { + client.calls.push(name); + return undefined; + }), + register: vi.fn(), + }, + }), + }; + }), +})); + +async function loadOverlay() { + vi.resetModules(); + return import('../overlay.ts'); +} + +const flush = async () => { + for (let i = 0; i < 10; i++) await Promise.resolve(); +}; + +describe.sequential('overlay dispose', () => { + beforeEach(() => { + clients.length = 0; + connectGate = Promise.resolve(); + document.body.innerHTML = ''; + delete window.__ngDevtoolsComponentOf; + vi.stubGlobal('BroadcastChannel', undefined); + vi.stubGlobal( + 'fetch', + vi.fn(async () => new Response('', { status: 404 })), + ); + vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'setInterval', 'clearInterval'] }); + }); + + afterEach(() => { + vi.useRealTimers(); + vi.unstubAllGlobals(); + vi.unstubAllEnvs(); + }); + + it('clears every timer, listener and observer and closes the connection', async () => { + const { initOverlay } = await loadOverlay(); + const added = vi.spyOn(window, 'addEventListener'); + const removed = vi.spyOn(window, 'removeEventListener'); + const docAdded = vi.spyOn(document, 'addEventListener'); + const docRemoved = vi.spyOn(document, 'removeEventListener'); + const disconnect = vi.spyOn(MutationObserver.prototype, 'disconnect'); + + const dispose = await initOverlay(); + await vi.advanceTimersByTimeAsync(0); + expect(vi.getTimerCount()).toBeGreaterThan(0); + dispose(); + + expect(vi.getTimerCount()).toBe(0); + expect(clients[0].close).toHaveBeenCalledTimes(1); + expect(disconnect).toHaveBeenCalled(); + const key = ([type, listener]: unknown[]) => `${type}:${String(listener)}`; + expect(removed.mock.calls.map(key).sort()).toEqual(added.mock.calls.map(key).sort()); + expect(docRemoved.mock.calls.map(key).sort()).toEqual(docAdded.mock.calls.map(key).sort()); + expect(clients[0].calls).toContain('forget-component-page'); + expect(window.__ngDevtoolsComponentOf).toBeUndefined(); + + const pushes = clients[0].calls.length; + await vi.advanceTimersByTimeAsync(10_000); + expect(clients[0].calls.length).toBe(pushes); + }); + + it('is safe to dispose twice', async () => { + const { initOverlay } = await loadOverlay(); + const dispose = await initOverlay(); + dispose(); + dispose(); + expect(clients[0].close).toHaveBeenCalledTimes(1); + }); + + it('removes the Elements-panel lookup it installed', async () => { + const { initOverlay } = await loadOverlay(); + const dispose = await initOverlay(); + expect(window.__ngDevtoolsComponentOf).toBeTypeOf('function'); + + dispose(); + expect(window.__ngDevtoolsComponentOf).toBeUndefined(); + }); + + it('leaves an Elements-panel lookup that is not its own', async () => { + const { initOverlay } = await loadOverlay(); + const dispose = await initOverlay(); + const other = () => null; + window.__ngDevtoolsComponentOf = other; + + dispose(); + expect(window.__ngDevtoolsComponentOf).toBe(other); + }); + + it('keeps the lookup of the overlay that replaced it', async () => { + const { initOverlay } = await loadOverlay(); + const first = await initOverlay(); + const firstLookup = window.__ngDevtoolsComponentOf; + const second = await initOverlay(); + const secondLookup = window.__ngDevtoolsComponentOf; + + expect(secondLookup).toBeTypeOf('function'); + expect(secondLookup).not.toBe(firstLookup); + first(); + expect(window.__ngDevtoolsComponentOf).toBe(secondLookup); + second(); + expect(window.__ngDevtoolsComponentOf).toBeUndefined(); + }); + + it('stops the running overlay when another one starts', async () => { + const { initOverlay } = await loadOverlay(); + const first = await initOverlay(); + const intervals = vi.getTimerCount(); + await initOverlay({ baseURL: '/__elsewhere/' }); + + expect(clients).toHaveLength(2); + expect(clients[0].close).toHaveBeenCalledTimes(1); + expect(clients[1].close).not.toHaveBeenCalled(); + expect(vi.getTimerCount()).toBe(intervals); + + first(); + expect(clients[1].close).not.toHaveBeenCalled(); + }); + + it('stops an overlay that is still connecting', async () => { + const { initOverlay, disposeOverlay } = await loadOverlay(); + let open = () => {}; + connectGate = new Promise((resolve) => (open = resolve)); + const started = initOverlay(); + await flush(); + await disposeOverlay(); + open(); + const dispose = await started; + + expect(clients[0].close).toHaveBeenCalledTimes(1); + expect(clients[0].calls).toEqual([]); + expect(vi.getTimerCount()).toBe(0); + expect(window.__ngDevtoolsComponentOf).toBeUndefined(); + dispose(); + }); + + it('stops the auto-started overlay and removes the floating button', async () => { + vi.stubEnv('VITEST', ''); + const { disposeOverlay } = await loadOverlay(); + await vi.waitFor(() => { + expect(clients).toHaveLength(1); + expect(document.getElementById('ng-devtools-popup-root')).not.toBeNull(); + }); + await flush(); + + await disposeOverlay(); + + expect(clients[0].close).toHaveBeenCalledTimes(1); + expect(document.getElementById('ng-devtools-popup-root')).toBeNull(); + expect(vi.getTimerCount()).toBe(0); + expect(window.__ngDevtoolsComponentOf).toBeUndefined(); + }); +}); + +describe.sequential('popup hide', () => { + beforeEach(() => { + document.body.innerHTML = ''; + vi.stubGlobal( + 'fetch', + vi.fn(async () => new Response('', { status: 404 })), + ); + }); + + afterEach(() => vi.unstubAllGlobals()); + + it('removes the popup and lets it be shown again', async () => { + vi.resetModules(); + const popup = await import('../popup.ts'); + await popup.showDevtools(); + expect(document.getElementById('ng-devtools-popup-root')).not.toBeNull(); + + await popup.hideDevtools(); + expect(document.getElementById('ng-devtools-popup-root')).toBeNull(); + + await popup.showDevtools(); + expect(document.getElementById('ng-devtools-popup-root')).not.toBeNull(); + }); +}); diff --git a/packages/ng-devtools/src/overlay.ts b/packages/ng-devtools/src/overlay.ts index 1bdc1c28..78699c2e 100644 --- a/packages/ng-devtools/src/overlay.ts +++ b/packages/ng-devtools/src/overlay.ts @@ -90,12 +90,64 @@ async function claimPageId(): Promise<{ id: string; release: () => void }> { return { id, release: () => channel.close() }; } -export async function initOverlay(options: { baseURL?: string | string[] } = {}) { +interface OverlayOptions { + baseURL?: string | string[]; +} + +let current: { stop: () => void } | null = null; +let popup: Promise | undefined; + +/** + * Starts the overlay and resolves with its dispose. Only one overlay runs per + * page: starting another stops the one before it, including the auto-started one. + */ +export function initOverlay(options: OverlayOptions = {}): Promise<() => void> { + current?.stop(); + const cleanups: (() => void)[] = []; + let stopped = false; + const instance = { + stop: () => { + if (stopped) return; + stopped = true; + if (current === instance) current = null; + for (const cleanup of cleanups.splice(0).reverse()) { + try { + cleanup(); + } catch { + continue; + } + } + }, + }; + current = instance; + const own = (cleanup: () => void) => { + if (stopped) cleanup(); + else cleanups.push(cleanup); + return !stopped; + }; + return startOverlay(options, own).then( + () => instance.stop, + (error) => { + instance.stop(); + throw error; + }, + ); +} + +/** Stops the running overlay and removes the floating devtools button. */ +export async function disposeOverlay(): Promise { + current?.stop(); + const loaded = await popup?.catch(() => undefined); + await loaded?.hideDevtools(); +} + +async function startOverlay(options: OverlayOptions, own: (cleanup: () => void) => boolean) { // `connectDevframe()` alone looks for the connection next to the page, which // misses the documented `/__ng-devtools/` mount in a host app. const rpc = await connectDevframe({ baseURL: options.baseURL ?? ['./', '/__ng-devtools/', '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/__devframes/ng-devtools/'], }); + if (!own(() => rpc.close?.())) return; const my = rpc.scope('ng-devtools'); let componentTarget: string | null = null; @@ -114,6 +166,7 @@ export async function initOverlay(options: { baseURL?: string | string[] } = {}) serializeNamed(name, value, { budget: 1000 }), ); const restoreSignalHook = await installSignalWriteHook(signalHistory.onWrite); + if (!own(restoreSignalHook)) return; let signalTarget: SignalTarget = null; let lastSignalKey = ''; @@ -152,6 +205,7 @@ export async function initOverlay(options: { baseURL?: string | string[] } = {}) } const { id: pageId, release: releasePageId } = await claimPageId(); + if (!own(releasePageId)) return; const stopAnalog = attachAnalog(my, pageId, getNg); const forms = attachForms(my, pageId, getNg, { show: showHighlight, clear: clearHighlight }); const pushForms = forms.push; @@ -294,25 +348,18 @@ export async function initOverlay(options: { baseURL?: string | string[] } = {}) routerPushTimer = setTimeout(() => void pushRouter(), 50); } - pushTree(); - pushSignalGraph(); - pushInjectorTree(); - pushNgrxState(); - pushForms(); - pushPipes(); - pushRouter(); - pushHttp(); - - const interval = setInterval(() => { - pushTree(); - pushSignalGraph(); - pushInjectorTree(); + const pushAll = () => { + pushTree().catch(() => {}); + pushSignalGraph().catch(() => {}); + pushInjectorTree().catch(() => {}); pushNgrxState(); pushForms(); pushPipes(); - pushRouter(); + void pushRouter(); pushHttp(); - }, 3000); + }; + pushAll(); + const interval = setInterval(pushAll, 3000); my.rpc.register({ name: 'highlight-in-page', @@ -381,10 +428,14 @@ export async function initOverlay(options: { baseURL?: string | string[] } = {}) }, }); - window.__ngDevtoolsComponentOf = (el) => { + const componentOf = (el: unknown) => { const host = el instanceof Element ? componentHostOf(getNg(), el) : null; return host ? elementId(host) : null; }; + window.__ngDevtoolsComponentOf = componentOf; + own(() => { + if (window.__ngDevtoolsComponentOf === componentOf) delete window.__ngDevtoolsComponentOf; + }); const leave = () => { pipes.pause(); @@ -405,25 +456,23 @@ export async function initOverlay(options: { baseURL?: string | string[] } = {}) }; addEventListener('pageshow', resendConfig); - return () => { + own(() => { clearInterval(interval); - restoreSignalHook(); removeEventListener('pagehide', leave); + removeEventListener('pageshow', resendConfig); + leave(); forms.stop(); pipes.stop(); - void my.rpc.call('forget-pipes-page', pageId).catch(() => {}); ngrx.stop(); stopAnalog(); - removeEventListener('pageshow', resendConfig); for (const cleanup of routerCleanup) cleanup(); routerCleanup = []; stopInstrument?.(); + stopInstrument = null; routerDomObserver?.disconnect(); clearTimeout(routerPushTimer); - releasePageId(); clearHighlight(); - delete window.__ngDevtoolsComponentOf; - }; + }); } function findAngularElements(): Element[] { @@ -523,5 +572,6 @@ if ( !(typeof process !== 'undefined' && process.env?.['VITEST']) ) { initOverlay().catch(console.error); - import('./popup.ts').then((m) => m.showDevtools()).catch(console.error); + popup = import('./popup.ts'); + popup.then((m) => m.showDevtools()).catch(console.error); } diff --git a/packages/ng-devtools/src/popup.ts b/packages/ng-devtools/src/popup.ts index 713a2b52..26e79604 100644 --- a/packages/ng-devtools/src/popup.ts +++ b/packages/ng-devtools/src/popup.ts @@ -74,6 +74,13 @@ export function showDevtools(): Promise { return shown; } +/** Removes the popup, waiting for one that is still being created. */ +export async function hideDevtools(): Promise { + await shown?.catch(() => {}); + handle?.destroy(); + shown = undefined; +} + function getBaseURL(): string { const paths = ['/__ng-devtools/', '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/__devframes/ng-devtools/', '/__devframe/', '/']; for (const base of paths) { @@ -578,6 +585,7 @@ export function createDevtoolsPopup(options: { src?: string } = {}) { popupRoot?.remove(); popupRoot = null; handle = undefined; + shown = undefined; isOpen = false; }, }; From 422a954c61089546dd46a13da43e096c50e0191b Mon Sep 17 00:00:00 2001 From: Kam Date: Wed, 30 Sep 2026 13:02:15 +0300 Subject: [PATCH 2/2] docs(overlay): document disposeOverlay and one overlay per page --- .../src/content/getting-started/overlay.md | 23 +++++++++++++++---- 1 file changed, 19 insertions(+), 4 deletions(-) diff --git a/apps/docs/src/content/getting-started/overlay.md b/apps/docs/src/content/getting-started/overlay.md index 70aa704c..fb051d0c 100644 --- a/apps/docs/src/content/getting-started/overlay.md +++ b/apps/docs/src/content/getting-started/overlay.md @@ -110,13 +110,28 @@ bootstrapApplication(App, appConfig).then(async () => { }); ``` -`baseURL` takes one path or a list of paths to try in order. `initOverlay` resolves to a function that stops the overlay and removes its hooks. +`baseURL` takes one path or a list of paths to try in order. `initOverlay` resolves to a function that stops the overlay it started and removes its hooks. -### Avoid two overlays +### One overlay per page -Importing the module already starts an overlay on the default URLs, and it does not hand you a function to stop it. When the devtools live only at your custom path, that overlay finds no connection, logs an error and stops. Your `initOverlay` call is then the only one running. +Only one overlay runs on a page. Importing the module already starts one on the default URLs. When you call `initOverlay`, it stops the running overlay first, the auto-started one included, and then starts yours. The page never ends up with two connections. -If the devtools also answer on a default URL, don't call `initOverlay`. Otherwise the page ends up with two connections and two polling intervals. +## Stop the overlay + +Call `disposeOverlay` to turn the overlay off: + +```ts +// src/app/devtools-toggle.ts +import {disposeOverlay} from '@santoshyadavdev/ng-devtools/overlay'; + +export async function stopDevtools() { + await disposeOverlay(); +} +``` + +`disposeOverlay` stops whichever overlay is running, including the one that importing the module started. It closes the connection, clears its timers, listeners and observers, and removes the floating button. + +To send data again, call `initOverlay`. It does not add the floating button back. ## NgRx signal stores