Engineering a better menu with Reactive Streams
Search
Eat Play Code
A blog by Ameya Karve
Note: The position of the mouse on this page is predictive. The rest of the page is about the implementation.
I read Guillermo Rauch’s excellent writeup recently about rich web applications; I was particularly fascinated by the mouse prediction section. This can be implemented in a number of ways, but using Observable streams makes it a piece of cake. The code is also very clean, modular and surprisingly intuitive. RxJS and Immutable.js were the only external dependencies I used. There is no jQuery anywhere, no framework, and the whole script weighs in at 29kb gzipped. Here is how I went about things:
Table of Contents
1. Generate the input streams
2. Map the input streams to state streams
Putting it all together
Here, the only inputs I need are the mouse position and the time. We get the individual streams and merge them.
This is the most important part of the code. Here, I try to map the combined stream to meaningful data. Here, we need to get the predicted position of the mouse. To do this, I have used a simple PID contoller on the mouse events. In addition to this, the mouse will also converge towards the position of the cursor as time passes on. In the map function, I can choose to return whatever parts of the state that I wish to return. In this example, I store the previous ten mouse positions, but decide to expose only the latest predicted position.
This is the easiest part of them all.
Further, If I have a menu element of arbitrary shape defined by f(x, y) = true for points on the element, we can see if the predicted mouse position is over this element by using
Using this, we can very easily support elements of varied shapes. For instance, f(x, y) for a donut would look like
Yum
Close
Home
About
Contact
My name is Ameya Karve. I am a software engineer; I mostly prefer to write in Javascript, Scala and Python. I graduated from IIT Madras in Engineering Design. I currently work for LinkedIn, and live in Bangalore, India