How do i have a widget adjust position on screen without exceeding screen bounds?

I am making an RTS game and Iwant to have a stats widget appear on screen to the upper right of the click point on screen when the player clicks on an NPC. But also not exceed the bounds on the screen. I would also like it so that the widget remains adjusts location on screen as the NPC moves.

Check viewport size, deduct widget size (desired size works most of the time here), clamp the position by the offset. If the widget alignment is [.5, .5], you’d need to adjust for that too - use half the desired side instead.