0

I'd like to achieve etherpad UI effect when each user types in different colour. I use contenteditable div as a rich text editor.

What I've tried so far:

1) On any input change make a diff between original and changed text (using diff-match-patch, for example).

2) Look at the diff substring bounds and see if it lays inside user's text (defined by a couple of tags)

3) If true, do nothing. If false, insert two colour tags aside of that substring, and apply the change calling $(element).html(new_text)

There is a major problem - calling html() resets caret position to zero, which is kinda bad when you work in a text editor. I tried to extract caret position from contenteditable div and set it again with diff.length offset - that, too, doesn't work good, because I've got a lot of child nodes inside my div, and caret offset is relative to a parent.

UPDATE:

So, I can narrow down my problem a bit:

1) I know how to get caret position within TextNode element

2) I know how to set it within TextNode element (with Rangy or without)

3) The only question is how to find out which element is my caret on now?

rocknrollnerd
  • 2,564
  • 1
  • 16
  • 20
  • https://github.com/ichord/Caret.js/tree/master – David Fregoli Jan 06 '14 at 18:09
  • Looks good, but that allows only to get caret, not to set it. – rocknrollnerd Jan 06 '14 at 18:22
  • 1
    http://stackoverflow.com/a/16100733/96100 – Tim Down Jan 06 '14 at 22:09
  • Thanks, I've actually found a similar question solved with your library, Rangy, [here](http://stackoverflow.com/questions/11741156/rangy-restore-cursor-position-when-replacing-innerhtml). It works good, but it doesn't recognize paragraphs: when I type enter key, the caret is returned to its original position to the upper line (you can see the same behaviour in the liked post's jsbin). Is there any way to fix it? – rocknrollnerd Jan 07 '14 at 09:52
  • I thought that question might be coming. It's quite tricky since line breaks in HTML tend to come from `
    ` elements and block elements rather than text nodes. Rangy's TextRange module attempts to solve this. Demo: http://rangy.googlecode.com/svn/trunk/demos/textrange.html
    – Tim Down Jan 08 '14 at 00:45

1 Answers1

0

I end up using Rangy's saveSelection and restoreSelection functions. Big thanks to Tim Down, of course.

rocknrollnerd
  • 2,564
  • 1
  • 16
  • 20