function get_best_coords_for_popup(_options) { const viewport_width = document.body.getBoundingClientRect().width; const viewport_height = document.body.getBoundingClientRect().height; const options = { offset: { x: 0, y: 0, }, popup: { width: 200, height: 200, }, ..._options, }; const target = options.target ?? { x: options.target_element?.getBoundingClientRect().left ?? viewport_width / 2 - options.popup.width / 2, y: options.target_element?.getBoundingClientRect().top ?? viewport_height / 2 - options.popup.height / 2, }; const best_coords = { x: target.x + options.offset.x, y: target.y + options.offset.y, }; if (target.x + options.offset.x + options.popup.width + options.offset.x > viewport_width) { best_coords.x = Math.max(0, target.x - options.popup.width + options.offset.x); } if (target.y + options.offset.y + options.popup.height + options.offset.y > viewport_height) { best_coords.y = Math.max(0, target.y - options.popup.height + options.offset.y); } return best_coords; }