jakiestfu / Medium.js

A tiny JavaScript library for making contenteditable beautiful (Like Medium's editor)
http://jakiestfu.github.io/Medium.js/
4.39k stars 403 forks source link

Is it better to add position support to Cursor.js #209

Open haozhechen opened 6 years ago

haozhechen commented 6 years ago

The Cursor support for medium.js is good but not enough. Like it lacks some basic cursor position support, i.e. if the cursor is at the end of the element?

I tried to add two functions: isCaretAtBegin and isCaretAtEnd. which could support some basic cursor position support.

Medium.Cursor.prototype = {
    ......
    isCaretAtBegin: function (el) {
            var sel = rangy.getSelection();
            return sel.anchorOffset === 0;
        },
    isCaretAtEnd: function (el) {
            var sel = rangy.getSelection();
            return sel.anchorOffset === el.innerText.length;
        }
}

However, when using this two function upon nested elements, the

rangy.getSelection() 

will get the last inner element other than the very outer element. For example, use

rangy.getSelection() 

for element

<p>this is a test paragraph,<span>ho ho ho</span></p>,

the selection will be the inner span other than the p element, so even you place the cursor at the end of this paragraph, the

el.innerText.length 

will be 33 and

sel.anchorOffset

will be 8.

I just wonder if these kind of functions is needed, I could work on it to improve Medium.js since this is the best open source WYSIWYG editor I have met.

robertleeplummerjr commented 6 years ago

We welcome it!