Carets are a nightmare


Making caret position queries continues to be the hardest problem, and it continues to reveal my lack of knowledge about text layout. This wouldn’t matter if there were browser APIs for caret position queries but it seems to be an underdeveloped part of web tech. There just isn’t an API for things like

  • getting the closest caret position to some x/y coordinates (firefox lacks support for caretRangeFromPoint)
  • getting the x/y coordinates of a caret position
  • determining whether a caret position is wrapped along a particular line number
  • whether the caret position is along any edges of the textbox

So in the absence of proper browser APIs some workarounds are necessary, and these browser hacks end up relying a lot on my understanding of text layout. It turns out I don’t know much. The latest assumption that was proven wrong was that I could get the x/y caret position by truncating a text node (string) to the caret position, appending a span and getBoundingClientRect() to measure that element. But it turns out that truncation isn’t the correct technique because characters following can affect the preceding caret x/y position… long words are wrapped so truncating a string to remove them can pull a caret onto the preceding line, affecting its x/y. It makes sense but there are so many similar subtle bugs that don’t occur until you have the right tests, so it’ll need more workarounds.

good grief