there is three area to take in count:
![enter image description here](https://cdn.statically.io/img/i.sstatic.net/uutOo.png)
For $P1$ the distance is $|P1-B|$
For $P3$ the distance is $|P3-A|$
to summarise, it juste the distance between two point when the point P is not between the two perpendicular line passing trough A and B.
the hardest part is P2 :
since it between the two point, the distance to the segment is the distance to the point $C$ on the segment $AB$. We can know where the point C is located with a parameter $h$ (the doted line) because of how a segment is parameterised.
$$(A,B) = (hx_B + (1-h)x_A,hy_B + (1-h)y_A)$$
if C is on B then $h=1$ and $h=0$ if C is on A, in the exemple h might be equal to 0,75 or 0,8.
To find h we need to do :
$$h = \frac{<P_2-A, B-A>}{|B-A|^2}$$
this is a projection of the length of the vector $\overrightarrow{P_2A}$ on to $\overrightarrow{BA}$ we use a dot product for that, then devide it to the length of $\overrightarrow{BA}$ then normalise it ench the power of 2.
then to find the distance $|P2-C|$ we do :
$$|P_2 - (A +h*(B-A))|$$
to finish we can compute the 3 expression at the same time wich lead us to :
$$h = min(1,max(0,\frac{<P_2-A, B-A>}{|B-A|^2}))$$
$$d = |P - A - h*(B-A)|$$