type Rect = { x: number; y: number; width: number; height: number }; function intersectionArea(a: Rect, b: Rect): number { const left = Math.max(a.x, b.x); const top = Math.max(a.y, b.y); const right = Math.min(a.x + a.width, b.x + b.width); const bottom = Math.min(a.y + a.height, b.y + b.height); if (right <= left || bottom <= top) return 0; return (right - left) * (bottom - top); } function pickArea(bounds: Rect, areas: Rect[]): Rect { let best = areas[0]; let bestArea = -1; for (const area of areas) { const overlap = intersectionArea(bounds, area); if (overlap > bestArea) { best = area; bestArea = overlap; } } return best ?? { x: 0, y: 0, width: 1920, height: 1080 }; } function clampToArea( bounds: Rect, area: Rect, minWidth = 320, minHeight = 240, ): Rect { const width = Math.min(Math.max(bounds.width, minWidth), area.width); const height = Math.min(Math.max(bounds.height, minHeight), area.height); return { x: Math.min(Math.max(bounds.x, area.x), area.x + area.width - width), y: Math.min(Math.max(bounds.y, area.y), area.y + area.height - height), width, height, }; } const primary: Rect = { x: 0, y: 0, width: 1920, height: 1000 }; const secondary: Rect = { x: -1280, y: 0, width: 1280, height: 800 }; const areas = [primary, secondary]; const pickedSecondary = pickArea( { x: -900, y: 100, width: 500, height: 400 }, areas, ); const pickedPrimary = pickArea( { x: 400, y: 100, width: 500, height: 400 }, areas, ); const negative = clampToArea( { x: -2000, y: -300, width: 900, height: 700 }, primary, ); const oversized = clampToArea( { x: 500, y: 500, width: 3000, height: 2000 }, primary, ); const tiny = clampToArea( { x: 100, y: 100, width: 100, height: 80 }, primary, 400, 300, ); const inside = (rect: Rect, area: Rect): boolean => rect.x >= area.x && rect.y >= area.y && rect.x + rect.width <= area.x + area.width && rect.y + rect.height <= area.y + area.height; console.log( JSON.stringify({ evt: "smoke", ok: pickedSecondary === secondary && pickedPrimary === primary && inside(negative, primary) && negative.x === 0 && negative.y === 0 && inside(oversized, primary) && oversized.width === primary.width && oversized.height === primary.height && tiny.width === 400 && tiny.height === 300, pickedSecondary, pickedPrimary, negative, oversized, tiny, }), );