For the context menus, we can’t assume there will always be space below the mouse cursor. That would make the menu go off-screen when the mouse is close to the bottom of the screen.
So we need some logic to determine placement.
A simple algorithm is to check where the most space is for each dimension (vertical & horizontal), and then place it there.
For example, if there is more space to the right than the left, and more space above than below, then the menu should be placed North-East of the mouse cursor.