The battery management monitors the individual and combined cell voltages during charge and discharge, mapping the changes against the amount of energy that has been pulled from the pack. This allows it to maintain in internal "Energy to empty" value it can calculate against at various states of charge.
Separate from that, it tracks recent energy use and combines those along with some environmental data to give an estimated range from that remaining energy. I don't think anyone has cracked the formula it uses to average your recent driving, but it seems like it's like a running tally of efficiency over the last 50 miles or something.
Doesn't really matter that much - once you have a handle on the efficiency of driving various routes and the energy that's available at a given state of charge, you can make decent estimates based on what you know your driving *will* be rather than what it was recently.
It's honestly weird to me that I can hyper-mile a 120 mile round trip, that COMPLETELY drains the battery, but it will show a 200 mile estimate after recharging because the latter half of the trip was mostly downhill and far more energy efficient.