The Invisible Shape

· Soren Blank ·

19 min read Original article ↗
Back to craft

I believe everyone who has ever used a computer has interacted with a kind of component called a "menu", which is a list of options shown to the user.

Now there are many types of menus. Text based menus, Pull-down (or drop-down) menus, Vertical menus, Context menus and probably a few more that I can't think of at the moment.

I believe the most common type of menu we interact with is "context menu" or "pop-up menu". Context Menu can be seen everywhere in modern interfaces. It's heavily used in almost every modern day software you can think of.

While working on context menu components for the web myself, I discovered some problems that come with large context menus and sub-menus. I went down the rabbit hole.

Today we are going to explore some parts of that rabbit hole.

A bit of history

In 1976, the Xerox Alto's Smalltalk-76 system introduced the idea of very first functional pop-up context menu ( and many other things ).

Smalltalk-76 running on a Xerox Alto

The person who made it possible was Dan Ingalls. He invented BitBlt, an operation that copies a block of pixels from one place to another really fast. That's what let a menu pop up on top of whatever was on the screen and go away again without redrawing everything. Sounds boring today. Back then nobody had seen anything like it. When Dan showed it at PARC, L Peter Deutsch jumped to his feet and said: "Did you just do what I thought you did?"

In 1979, Steve Jobs negotiated a deal allowing Apple engineers to visit Xerox PARC in exchange for Apple stock. Steve was blown away by the GUI that Xerox had that time. It was an original idea.

And they showed me really, uh, three things, but I was so blinded by the first one that I didn't even really see the other two. [...] I was so blinded by the first thing they showed me, which was the graphical user interface. I thought it was the best thing I had ever seen in my life... and within, you know, 10 minutes, it was obvious to me that all computers would work like this someday.

Many of the concepts they saw at Xerox PARC heavily influenced the design and development of Apple's Lisa and Macintosh operating systems. Which eventually got adopted by the whole industry.

Fun fact, the first Mac in 1984 had no sub-menus at all. They showed up in 1987 with the Mac II and Mac SE. And that's where our problem begins.

The Why Problem

Nobody wants to see a menu with a list of 50 different items in it. Here is how it would look like.

A cursor slowly travels down a flat context menu of two dozen items — scrolling the menu along the way — to reach the last item, then travels all the way back up.Open⌘OOpen in New Tab⌘TOpen in New Window⌘NOpen With…Get Info⌘IQuick LookSpaceRename…⏎Duplicate⌘DMake Alias⌃⌘ACompressShare…Cut⌘XCopy⌘CPaste⌘VCopy Path⌥⌘CMove to…Add to FavoritesTags…Translate…Look UpSearch the WebSet as Wallpaper…Print…⌘PMove to Trash⌘⌫

The best approach to fix this clutter is to group items hierarchically and have nested menus / sub-menus. You can keep the interface clean by collapsing everything by default and only expanding sub-menus when the user actually wants to see them.

A tidy context menu for an image file. A cursor arcs in from above onto Open, then drops to Open With — which instantly reveals the sub-menu beside it, listing Preview as the default app, then Photos, TextEdit, and the App Store and Other escape hatches — waits, and retraces its way back out.OpenOpen WithMove to TrashGet InfoRenameCompress “IMG_0042.png”CopyShare…Tags…Quick ActionsPreview.app(default)Photos.appTextEdit.appApp Store…Other…

In early software to open a sub-menu, the user had to drag their cursor in an exact straight line from the main item. If your cursor slipped off the parent item for even a fraction of a second, the menu instantly collapsed. You couldn't move diagonally.

Here the shortest path from "Open With" to "Other" is when you move diagonally.

The same context menu with the Open With sub-menu open, and two routes to its last item, Other. First a cursor follows the green L — straight along the Open With row into the sub-menu, then square down it, highlighting each app in turn — reaches Other, and retraces it. Then the cursor tries the red diagonal aimed straight at the same item: moments after setting off it slips off the Open With row, the sub-menu vanishes, and the cursor carries on over Move to Trash and Get Info before arriving at empty space where the sub-menu used to be.OpenOpen WithMove to TrashGet InfoRenameCompress “IMG_0042.png”CopyShare…Tags…Quick ActionsPreview.app(default)Photos.appTextEdit.appApp Store…Other…

Trust me when I say this, you do not want to do this. It's slow, it's tiring and of course you will slip off the parent menu many times every single day and will end up collapsing the sub-menu every time.

Bruce Tognazzini ( Tog ), who started Apple's Human Interface Group, explained why better than I can:

The engineer who originally designed hierarchicals apparently had his forearm mounted on a track so that he could move it perfectly in a horizontal direction without any vertical component. Most of us, however, have our forearms mounted on a pivot we like to call our elbow.

Bruce Tognazzini, A Quiz Designed to Give You Fitts

Your hand moves in an arc, not a straight line. So you will slip down while trying to go sideways.

There's actually a law for this. The Steering law says the time it takes to move through a tunnel goes up with the tunnel's length and down with its width: T = a + b × (A / W). Going across a parent row to its sub-menu is a tunnel as long as the menu is wide and only one row tall. Long and narrow, the worst kind. Make the menu wider to fit longer labels and the tunnel only gets longer.

The How(s)

How can we make the cursor able to move diagonally? While making sure that the sub-menu doesn't collapse or the cursor doesn't end up focusing any other menu?

This is a solved problem in modern day software. But the mechanism behind is a bit different in every software. Which makes each solution behave a bit differently from each other.

And it was solved a long time ago. Here is Tog again, on the Mac:

When I specified the Mac hierarchical menu algorithm in the mid-'80s, I called for a buffer zone shaped like a <, so that users could make an increasingly-greater error as they neared the hierarchical without fear of jumping to an unwanted menu. As long as the user's pointer was moving a few pixels over for every one down, on average, the menu stayed open, no matter how slow they moved.

Bruce Tognazzini, A Quiz Designed to Give You Fitts

That < is the invisible shape. Almost everything below is some version of it.

The most common solutions that i've come across are:

  • using timeout
  • placing curved SVGs or hidden paths to bridge the gap
  • drawing an invisible "safe triangle" between the cursor and the sub-menu
  • predicting user intent based on cursor velocity and position
  • or a hybrid approach that mixes several of the methods above

We will explore some of the approaches here that we see on web. In no particular order

Note: means dom. And means not a dom.

1. The Timeout approach

One might think that the easiest fix is having a timeout. When the cursor leaves the parent row, wait 300ms before closing the sub-menu. But this approach isn't really a good one.

A short context menu whose last item, Open With, has its sub-menu open below and to the right, and below them a 300ms meter labelled “grace period”, running from “cursor leaves the row” to a line marked “sub-menu closes”. The cursor runs the same diagonal from that row down to the sub-menu's last item, Other, twice. The first time it moves quickly: the meter starts filling as it leaves the row, but the cursor makes it into the sub-menu with the meter just short of the line, and the sub-menu stays put. The second time it moves at an ordinary pace, the meter reaches the line while the cursor is still in mid-air, the sub-menu vanishes, and the cursor arrives at empty space where Other used to be.OpenGet InfoRenameOpen WithPreview.app(default)Photos.appTextEdit.appOther…grace period300mscursor leaves the rowsub-menu closes

You see the problem? A fixed timeout will be too slow for some users and too fast for others.

Tog called this out too. Windows used to keep the sub-menu open for around half a second after you slipped, hoping you'd be quick enough to make it:

Unfortunately, people's reactions to heightened chance of error is to slow down, rather than speed up, a well-established phenomenon. Therefore, few users will ever figure out that moving faster could solve their problem. Microsoft's solution is exactly wrong.

Bruce Tognazzini, A Quiz Designed to Give You Fitts

So the careful users are the ones who get punished. And everyone who actually wants the next row has to wait for the timeout too.

2. The Curved SVG approach

I discovered this technique while watching Hakim El Hattab's talk at CSS Day 2019. His approach was using curved svg. Instead of a fixed timeout, Hakim used a dynamic curved SVG to bridge the gap between the parent item and the sub-menu.

A short context menu whose last item, Open With, has its sub-menu open below and to the right. A blue shape with curved edges sweeps from that row down to the sub-menu's bottom corner, hugging the row as it leaves, and the cursor crosses it in one straight diagonal to the last item, Other — highlighting TextEdit on the way in and then Other as it arrives — waits there, and comes straight back. The sub-menu stays open the whole time.OpenGet InfoRenameOpen WithPreview.app(default)Photos.appTextEdit.appOther…

Here is the code for the curved svg path he shared in his talk.

const anchor = row.getBoundingClientRect();
const menu = submenu.getBoundingClientRect();

hitArea.setAttribute(
"d",
`M ${anchor.x} ${anchor.y}` +
` Q ${menu.x} ${anchor.y} ${menu.x} ${menu.y}` +
` v ${menu.height}` +
` Q ${menu.x} ${anchor.bottom} ${anchor.x} ${anchor.bottom}` +
` h ${anchor.width}` +
` v ${-anchor.height}` +
` z`,
);

The code here measures the row and the sub-menu and then he is drawing a closed path between them while cutting out the row itself. And using quadratic Bézier curve Q to curve the two path. Hakim chose to use a curved path so that it covers less of the top/bottom rows in the menu and more of the natural trajectory of the cursor to all the items in the sub-menu.

I really recommend watching the YouTube video yourself to understand his thoughts better.

3. The Safe Area approach

I read about this in Invisible details - Building contextual menus article by Andreas Eldh.

A short context menu whose last item, Open With, has its sub-menu open below and to the right. A blue triangle spans the gap between them, its point near the cursor and its base running the full height of the sub-menu's left edge. The cursor crosses to the sub-menu's last item, Other, and the triangle is redrawn in visible steps five times a second rather than continuously, so its point lags behind the cursor and jumps to catch up, narrowing as it goes and lingering for a moment after the cursor has already arrived. On the way back out the triangle does not reappear and the sub-menu closes behind the cursor, so it returns to the Open With row across empty space; the sub-menu re-opens when the cursor reaches that row again. Then the cursor runs a shallower line at the same item's label instead — a line that would have fallen outside the curved shape from the previous figure — and this one is inside the triangle too, whose point settles into a thin strip against the sub-menu's edge, as small as it gets, before the sub-menu closes behind it a second time.OpenGet InfoRenameOpen With

Here is the code for the safe area approach. Here Andreas is using a div element to create a safe area for the cursor to move in. First sub-menu's size gets measured, then we get mouse coordinates to dynamically draw a CSS clipPath polygon.

export function MouseSafeArea(props: { parentRef: React.RefObject<HTMLDivElement> }) {
  const { x = 0, y = 0, height: h = 0, width: w = 0 } = props.parentRef.current?.getBoundingClientRect() || {};
  const [mouseX, mouseY] = useMousePosition();
  const positions = { x, y, h, w, mouseX, mouseY };
  return (
    <div
      style={{
        position: "absolute",
        top: 0,
        right: getRight(positions),
        left: getLeft(positions),
        height: h,
        width: getWidth(positions),
        clipPath: getClipPath(positions),
      }}
    />
  );
}

const getLeft = ({ x, mouseX }: Positions) => (mouseX > x ? undefined : -Math.max(x - mouseX, 10) + "px");
const getRight = ({ x, w, mouseX }: Positions) => (mouseX > x ? -Math.max(mouseX - (x + w), 10) + "px" : undefined);
const getWidth = ({ x, w, mouseX }: Positions) => mouseX > x ? Math.max(mouseX - (x + w), 10) + "px" : Math.max(x - mouseX, 10) + "px";
const getClipPath = ({ x, y, h, mouseX, mouseY }: Positions) =>
  mouseX > x
    ? `polygon(0% 0%, 0% 100%, 100% ${(100 * (mouseY - y)) / h}%)`
    : `polygon(100% 0%, 0% ${(100 * (mouseY - y)) / h}%, 100% 100%)`;

This clip path creates an invisible safe triangular shape connecting your cursor's position directly to the top and bottom corners of the sub-menu. As long as your mouse moves inside this safe area towards the sub-menu, it will not collapse.

You'll see variations of this technique everywhere on the web now. John Phamous shared a great example on Twitter showing how he built out menus for Vercel.

There is a catch though. A real element has to be re-rendered every time the mouse moves, and a fast flick can get ahead of it. Adobe's React Aria team tried this approach and dropped it for exactly that reason. It's also sitting on top of the rows under it, so those rows can't be hovered or clicked until it goes away.

4. The Amazon approach

Most of the web learned about the safe triangle from Ben Kamens. In 2013 he got nerd sniped by how fast Amazon's "Shop by Department" menu felt, and figured out why. There's no delay. Amazon checks if your cursor is moving inside a triangle between where it was and the corners of the sub-menu. Inside, the sub-menu stays. Outside, it switches instantly.

He wrote about it in Breaking down Amazon's mega dropdown and turned it into jQuery-menu-aim. Sophie Alpert helped him understand the cross-product math Amazon was using, but he went with a simpler slope comparison in the end. No dom here, just math on every mouse move.

He also wrote this in his post:

I'm sure this problem was solved years and years ago, forgotten, rediscovered, solved again, forgotten, rediscovered, solved again.

Ben Kamens, Breaking down Amazon's mega dropdown

He was more right than he knew. When I posted about this, Michael Brundage replied:

Michael, Gareth Farrington and Drew Stamps built that menu at Amazon. Their patent, US9733783B1, was filed on November 1, 2012. Four months before Ben's post.

And the patent doesn't draw one triangle. It draws three triangles and a circle.

  • The main triangle, from the cursor to a bit past the top and bottom corners of the sub-menu. Almost the same as everyone else.
  • Two more triangles, one above and one below. They step M pixels from the cursor towards the sub-menu, then N pixels up and P pixels down. Those two points become the tips of the new triangles, which makes the shape wider near the cursor, right where the main triangle is the thinnest.
  • A tiny circle around the cursor, so small jitters don't count as leaving.

If the cursor lands on another item, they check it right away. If not, they wait a moment and then check. If it's inside any of these shapes, the sub-menu stays and the whole thing gets redrawn from the new position. If it's outside, or if the cursor hasn't moved at all, the sub-menu switches.

The part I like the most is where M, N and P come from. The patent describes recording how lots of users move their cursor between two points and picking the values from that data. It even mentions tuning them per user.

Those two extra triangles do the same job as Hakim's curves. Just with math instead of an SVG, seven years earlier.

5. Predicting User Intent

I've found this method being used in Base UI ( and observed in MacOS menus ). It's the most overengineered solution out there, and probably the best one.

A short context menu whose last item, Open With, has its sub-menu open below and to the right, and below them a meter labelled “cursor speed” whose lowest third is tinted red and marked 0.1 px/ms. The cursor runs the same diagonal from that row toward the sub-menu's last item, Other, twice. The first time it moves at a steady pace: an amber quadrilateral with a dashed outline appears as it leaves the row, marked “no dom” along its lower edge, spanning the gap with its point at the place the cursor left rather than following it, the speed bar sits well clear of the red zone, and the cursor reaches the sub-menu — at which point the shape disappears, having done its job. The second time it starts at the same speed on the same line and then eases off; the bar shortens step by step and, while the cursor is still inside the very same shape and some distance short of the panel, drops into the red zone, and the sub-menu closes at that instant. The cursor drifts to a halt in the empty gap and returns. Both times it crosses back over the Open With row without the sub-menu reopening, which only happens a moment after the cursor has come to rest at the start.OpenGet InfoRenameOpen Withno domcursor speed300 px/ssub-menu closes0.1 px/mssub-menu stays open

The Safe Triangle above isn't a DOM element in the real implementation. There is nothing to inspect, nothing to hover, nothing sitting on top of your menu. It's just math running inside a mousemove listener. We're only drawing it here so you can see it.

function hasIntersectingEdge(pointX, pointY, xi, yi, xj, yj) {
  return yi >= pointY !== yj >= pointY && pointX <= ((xj - xi) * (pointY - yi)) / (yj - yi) + xi;
}

The interesting part is, it measures how fast you're moving.

const CURSOR_SPEED_THRESHOLD = 0.1; // px/ms
const CURSOR_SPEED_THRESHOLD_SQUARED = CURSOR_SPEED_THRESHOLD * CURSOR_SPEED_THRESHOLD;

const distanceSquared = deltaX * deltaX + deltaY * deltaY;
const thresholdSquared = elapsedTime * elapsedTime * CURSOR_SPEED_THRESHOLD_SQUARED;
return distanceSquared < thresholdSquared;

IMO a fixed timeout is the wrong tool. It's a guess about how long the trip takes and that depends on distance.

The fix isn't speed by itself. It's checking again on every move instead of guessing once. Base UI checks how fast you're moving (and still keeps a tiny 40ms timer for a hand that stops). React Aria uses a timer that restarts every time you move. Either way, nothing has to know how far away the sub-menu is.

One thing to keep in mind though. Tog's < kept the menu open "no matter how slow they moved". A speed check does the opposite, it closes the sub-menu when you're too slow. That's great for most people, but not for someone who moves slowly because they have to.

The safe area shape is just a bridge based on the guess that the cursor is travelling toward the sub-menu. The speed check makes sure it's still travelling at all.

These get checked on every mousemove:

  • is a deeper sub-menu open ( if yes, nothing else runs )
  • has the cursor already reached the sub-menu
  • has it stopped ( a stopped cursor fires no event, so a 40ms timer covers that )
  • is it moving too slowly
  • is it still inside the safe area

Adobe's React Aria team thought about this a lot while building their sub-menus. Instead of a triangle they compare angles with Math.atan2, and they went with a longer timeout over a speed check because people with motor impairments may take longer to get there. They also:

  • widen the allowed angle by 15° on the top and bottom
  • only close after two wrong movements in a row, because people with tremors can jerk the cursor the wrong way without meaning to
  • skip all of this for touch and pen, since there's no cursor to aim

One more detail from macOS that Costa Alexoglou noticed. The triangle only works one way. It protects you on the way into the sub-menu, but when you come back to the parent menu it's gone, so the rows light up right away.

Playground

Here is an interactive version with every approach from this post. Pick one, hover Open With, then cut diagonally toward Other.

What's next

Right now every library ships its own version of this. Base UI, Floating UI, Radix, React Aria and probably the one you're using. I've seen an open discussion in Open UI about native menu elements, and one suggestion there is to let browsers handle the hover delay and the safe triangle themselves. If that happens, none of us will have to write this ever again.

Resources