Very nice viz! BTW, a way to do this faster would be to employ a kNN algorithm (such as the one in https://github.com/mourner/rbush-knn), traversing the tree with a priority queue but replacing the distance measure against leaf child nodes with point-to-segment distance. This will find the closest segment with one traversal through the tree, with less candidates to test and without adaptive heuristics.
Excellent suggestion, thanks! I've implemented it here https://observablehq.com/d/5725c30c464e3614 , will clean up tomorrow. Much better to have a deterministic algo, but it doesn't seem faster (maybe because it yields more candidates to test with the more expensive distance, or maybe because I botched it somehow, I don't know).
@mourner it's much harder than I thought… we want to visit nodes where there might be a solution, but nothing guarantees that the first leaf from those nodes is the right one. I've outlined a case in which the traversal fails. I'm giving up for now.
@Fil sent you a PR with a fix — the issue was in calculating point to box distance squared (as opposed to non-squared point to segment distance). The number of candidates might be bigger but not always, e.g. compare when querying the middle rightmost point of the viz. Overall the performance should be faster if you optimize it carefully — this mostly comes down to avoiding any unnecessary allocations (so e.g. don't create objects/arrays when calculating point to segment distance, just return a number), and maybe also using squared distances for both. Keeping track of candidates also adds an overhead.