Probably 60% of the XSL is related to getting figures in the margin.
There are a few LaTeX packages that can accomplish it, but the one I'm using is called "xcoffins". The LaTeX preamble code is loaded on lines 149-193.
In the original LaTeX for APEX, Greg wrote a custom apex.sty file that created custom commands like 'mfigure' and 'mtable'.
These had an argument that was a number between 0 and 1, and this was an absolute position on the page. In any case, I never figured out how to implement something like this in PreTeXt.
The xcoffins package uses relative position, but of course you don't always get things automatically placed where you want them, so there is some adjusting that needs to be done.
Other considerations: the use of tcolorbox affects horizontal placement of margin figures. So I had to do a lot initially with guidelines turned on to figure out the horizontal shift in various cases: a figure that is a peer of <p> in the main text, a figure within an example, a figure within a list, a figure within a list within an example, etc. There is XSL logic to sort into the various cases and provide the right shift.
After several years of having to spend days building the PDF, adjusting placements (hand-editing the .tex file from PreTeXt), rebuilding, checking, adjusting some more, I decided to add some additional XSL to handle this for me.
So there are some additional attributes in APEX that are not part of PreTeXt, like "vshift" as an attribute on a figure, image, table, etc.
This attribute is the logic trigger in the XSL to place the object in the margin, and it also tries to put everything in the right place.
Of course, every year the text changes slightly, and some of these numbers have to be adjusted.
The rest of our XSL handles things like YouTube videos, exercise geometry, etc.