import { AutoResizeOptions } from '../options/auto-resize-options'; import { resizeContainer } from './resize-container'; let activeCleanup: (() => void) | null = null; /** * Automatically adjusts the iframe container height to match the extension's content. * Uses a ResizeObserver on document.body to detect content size changes and reports * the height to the Struct PIM host application. * * Only supported for extension point types: Tab, Section, Property, and SidebarWidget. * For other types, the host will reject the underlying resize actions. * * Only one auto-resize observer can be active at a time. Calling this again * will disconnect the previous observer before creating a new one. * * @example * ```ts * // With defaults (no max height, 100ms debounce) * struct.actions.enableAutoResize(); * * // With options * struct.actions.enableAutoResize({ maxHeight: 800, debounceMs: 200 }); * ``` */ export function enableAutoResize(options?: AutoResizeOptions): () => void { if (activeCleanup) { activeCleanup(); activeCleanup = null; } const debounceMs = options?.debounceMs ?? 100; const maxHeight = options?.maxHeight; let lastHeight = -1; let timer: ReturnType | null = null; function postHeight(): void { let height = document.body.offsetHeight; if (maxHeight !== undefined && height > maxHeight) { height = maxHeight; } if (height !== lastHeight) { lastHeight = height; resizeContainer({ height }); } } // Send initial height immediately postHeight(); const observer = new ResizeObserver(() => { if (timer !== null) { clearTimeout(timer); } timer = setTimeout(postHeight, debounceMs); }); observer.observe(document.body); activeCleanup = () => { observer.disconnect(); if (timer !== null) { clearTimeout(timer); timer = null; } activeCleanup = null; }; return activeCleanup; }