#
# implementation: insert a span tag where we want the cursor, and ask the
# browser where it put that span
-cursor_to_loc = (n, i) ->
+cursor_to_xyh = (n, i) ->
span = domify span: style: "height: 1em; border-left: 1px solid black; margin-left: -1px"
parent = n.el.parentNode
els = []
parent.insertBefore n.el, els[0]
for el in els
parent.removeChild el
- ret = x: bounds.x, y: bounds.y
+ ret = x: bounds.x, y: bounds.y, h: bounds.h
if plus_width
ret.x += bounds.w
# fudge case where bounds are BS because we're on non-significant whitespace
if i > 0
- first = cursor_to_loc n, 0
+ first = cursor_to_xyh n, 0
if ret.x <= first.x
# no need for a loop here, because recursion
- ret = cursor_to_loc n, i - 1
+ ret = cursor_to_xyh n, i - 1
return ret
# encode text so it can be safely placed inside an html attribute
return null
find_loc_cursor_position = (tree, loc) ->
- console.log tree, loc
for c in tree
if c.type is TYPE_TAG or c.type is TYPE_TEXT
bounds = get_el_bounds c.el
- console.log bounds
continue if loc.x < bounds.x
continue if loc.x > bounds.x + bounds.w
continue if loc.y < bounds.y
if c.type is TYPE_TEXT
# click is within bounding box that contains all text.
return [c, 0] if c.text.length is 0
- #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]
if c.children.length
- console.log "in"
ret = find_loc_cursor_position c.children, loc
- console.log 'found', ret if ret?
return ret if ret?
return null
@idoc.body.appendChild @cursor_el
@cursor_visible = true
# TODO figure out x,y coords for cursor
- loc = cursor_to_loc cursor[0], cursor[1]
+ loc = cursor_to_xyh cursor[0], cursor[1]
@cursor_el.style.left = "#{loc.x}px"
@cursor_el.style.top = "#{loc.y}px"