- #if c.text.length is 1
- # definitely no linebreak in it
- #if loc
- #
- # for inline elements, this can include text in other tags on
- # the first or last lines.
- #
- # they clicked on text. now determine where in the text
- tries = {}
- cur = Math.floor(c.text.length / 2)
- #loop
- # xy = tries[cur] = cursor_to_loc c, cur
- return [c, cur]
+ before_i = 0
+ before = cursor_to_xyh c, before_i
+ after_i = c.text.length
+ after = cursor_to_xyh c, after_i
+ if loc.y < before.y + before.h and loc.x < before.x
+ continue # before first char on first line
+ if loc.y > after.y and loc.x > after.x
+ continue # after last char on last line
+ while after_i - before_i > 1
+ cur_i = Math.round((before_i + after_i) / 2)
+ cur = cursor_to_xyh c, cur_i
+ if loc.y < cur.y or (loc.y <= cur.y + cur.h and loc.x < cur.x)
+ after_i = cur_i
+ after = cur
+ else
+ before_i = cur_i
+ before = cur
+ # which one is closest?
+ if Math.abs(before.x - loc.x) < Math.abs(after.x - loc.x)
+ return [c, before_i]
+ else
+ return [c, after_i]