It's preplanned and done using "Orbital Mechanics". Here's a link:
Orbital mechanics - Wikipedia
And here's the quick excerpt from Wikipedia:
Orbital mechanics or
astrodynamics is the application of
ballistics and
celestial mechanics to the practical problems concerning the motion of
rockets and other
spacecraft. The motion of these objects is usually calculated from
Newton's laws of motion and
law of universal gravitation. Orbital mechanics is a core discipline within
space-mission design and control.
Celestial mechanics treats more broadly the
orbital dynamics of systems under the influence of
gravity, including both spacecraft and natural
astronomical bodies such as
star systems,
planets,
moons, and
comets.
Orbital mechanics focuses on spacecraft trajectories, including orbital maneuvers, orbital plane changes, and interplanetary transfers, and is used by mission planners to predict the results of propulsive maneuvers. General relativity is a more exact theory than Newton's laws for calculating orbits, and is sometimes necessary for greater accuracy or in high-gravity situations (e.g. orbits near the Sun).
******
If you saw the movie "Hidden Figures", that's what those ladies were doing.