Skip to content

v-editable-text directive, modeled after v-model #1

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: dev
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions component.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
"src/viewmodel.js",
"src/binding.js",
"src/observer.js",
"src/contenteditable-selection.js",
"src/directive.js",
"src/exp-parser.js",
"src/template-parser.js",
Expand Down
98 changes: 98 additions & 0 deletions src/contenteditable-selection.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
/**
* In order to get the cursor position / selection for a contenteditable HTML element, we need to do some
* fancy stuff. This is necessary for the editable-text directive (and possibly others in the future). This code comes
* from the following stack overflow post:
*
* http://stackoverflow.com/questions/13949059/persisting-the-changes-of-range-objects-after-selection-in-html/13950376#13950376
* Example here:
* http://jsfiddle.net/WeWy7/3/
*
*/
module.exports = {
/**
* Given an html element (with contenteditable="true"), returns the current cursor selection.
* @param containerEl
* @returns {{start: Number, end: number}}
*/
saveSelection: function saveSelection(containerEl) {
var start;
if (window.getSelection && document.createRange) {
var range = window.getSelection().getRangeAt(0);
var preSelectionRange = range.cloneRange();
preSelectionRange.selectNodeContents(containerEl);
preSelectionRange.setEnd(range.startContainer, range.startOffset);
start = preSelectionRange.toString().length;

return {
start: start,
end: start + range.toString().length
}
} else if (document.selection && document.body.createTextRange) {
// This is for IE...
var selectedTextRange = document.selection.createRange();
var preSelectionTextRange = document.body.createTextRange();
preSelectionTextRange.moveToElementText(containerEl);
preSelectionTextRange.setEndPoint("EndToStart", selectedTextRange);
start = preSelectionTextRange.text.length;

return {
start: start,
end: start + selectedTextRange.text.length
}
}
},

/**
* Given an html element, resets the selection to the start/end specified in savedSel. Expectation
* is that savedSel was generated by the saveSelection function.
*
* @param containerEl
* @param savedSel {{start: Number, end: number}}
*/
restoreSelection: function restoreSelection(containerEl, savedSel) {
if (window.getSelection && document.createRange) {
var charIndex = 0, range = document.createRange();
range.setStart(containerEl, 0);
range.collapse(true);
var nodeStack = [containerEl], node, foundStart = false, stop = false;

// This while loop is super confusing. This part of DOM exploration is greek to me though and
// I trust stack overflow more than trying to figure this out from first principles.
// Here's the w3 article on nodeType http://www.w3schools.com/jsref/prop_node_nodetype.asp
// nodeType == 3 is text. Basically it's taking the element and trying to find the text part of the element
// Once it has that, it moves one chunk of text at a time until it finds the beginning / end
// of the desired selection, and then creates that range.
while (!stop && (node = nodeStack.pop())) {
if (node.nodeType === 3) {
var nextCharIndex = charIndex + node.length;
if (!foundStart && savedSel.start >= charIndex && savedSel.start <= nextCharIndex) {
range.setStart(node, savedSel.start - charIndex);
foundStart = true;
}
if (foundStart && savedSel.end >= charIndex && savedSel.end <= nextCharIndex) {
range.setEnd(node, savedSel.end - charIndex);
stop = true;
}
charIndex = nextCharIndex;
} else {
var i = node.childNodes.length;
while (i--) {
nodeStack.push(node.childNodes[i]);
}
}
}

var sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
} else if (document.selection && document.body.createTextRange) {
// This is for IE...
var textRange = document.body.createTextRange();
textRange.moveToElementText(containerEl);
textRange.collapse(true);
textRange.moveEnd("character", savedSel.end);
textRange.moveStart("character", savedSel.start);
textRange.select();
}
}
}
92 changes: 92 additions & 0 deletions src/directives/editable_text.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
var utils = require('../utils'),
ESCAPE_KEY = 27,
ENTER_KEY = 13,
attrToChange = 'textContent'

/**
* Two-way binding for form input elements
*/
module.exports = {

_savedSelection: null, // Default Value

bind: function () {

var self = this,
el = self.el

// Make the content editable
el.setAttribute('contenteditable', true)

// On escape, reset to the initial value and deselect (blur)
self.onEsc = function(e) {
if (e.keyCode === ESCAPE_KEY) {
el[attrToChange] = self.initialValue || ''
self._set()
el.blur()
}
}
el.addEventListener('keyup', this.onEsc)

self.onEnter = function(e) {
if (e.keyCode === ENTER_KEY) {
e.preventDefault()
el.blur()
}
}
el.addEventListener('keydown', this.onEnter)

// On focus, store the initial value so it can be reset on escape
self.onFocus = function() {
self.initialValue = el[attrToChange]
}
el.addEventListener('focus', this.onFocus)

self.onInput = function () {
// if this directive has filters
// we need to let the vm.$set trigger
// update() so filters are applied.
// therefore we have to record cursor position (selection)
// so that after vm.$set changes the input
// value we can put the cursor back at where it is
this._savedSelection = utils.selectionHelper.saveSelection(el)

self._set()
}

el.addEventListener('input', self.onInput)

// FIXME: We don't support IE 9 so I never solved whatever issues exist with backspace / del / cut
},

_set: function () {
this.vm.$set(this.key, this.el[attrToChange])
},

update: function (value, init) {
// sync back inline value if initial data is undefined
if (init && value === undefined) {
return this._set()
}

this.el[attrToChange] = typeof value !== 'string' ? '' : value

// Since updates are async, we need to reset the position of the cursor after it fires
// v-model tries to do this with setTimeout(cb, 0) but if there's a filter and you type
// too fast, there's a race condition where the timeout can fire before
// update, moving the cursor back to the front. Having this here guarantees the cursor
// is reset after update.
// See the comment in self.set for additional context
if (this._savedSelection) {
utils.selectionHelper.restoreSelection(this.el, this._savedSelection)
}
},

unbind: function () {
var el = this.el
el.removeEventListener('input', this.onInput)
el.removeEventListener('keyup', this.onEsc)
el.removeEventListener('keydown', this.onEnter)
el.removeEventListener('focus', this.onFocus)
}
}
5 changes: 5 additions & 0 deletions src/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,11 @@ var utils = module.exports = {
*/
parseTemplateOption: require('./template-parser.js'),

/**
* Helper function for getting/restoring the cursor in contenteditable elements
*/
selectionHelper: require('./contenteditable-selection.js'),

/**
* get a value from an object keypath
*/
Expand Down
23 changes: 23 additions & 0 deletions test/unit/specs/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -488,6 +488,29 @@ describe('Utils', function () {

describe('objectToArray', function () {
// TODO
}),
describe('contenteditable-selection', function() {
var selectionHelper = utils.selectionHelper
it('Expect saving a restored cursor to match', function() {
var template = '<div id="selection-test-div" contenteditable="true">This text is at least 15 characters long.</div>',
el = document.createElement('template')
el.innerHTML = template
appendMock(el)
var expectedSelection = {start: 7, end: 7} // start == end means it's just the cursor
selectionHelper.restoreSelection(el, expectedSelection)
var selection = selectionHelper.saveSelection(el)
assert.deepEqual(selection, expectedSelection)
});
it('Expect saving a restored selection to match', function() {
var template = '<div id="selection-test-div" contenteditable="true">This text is at least 15 characters long.</div>',
el = document.createElement('template')
el.innerHTML = template
appendMock(el)
var expectedSelection = {start: 3, end: 15}
selectionHelper.restoreSelection(el, expectedSelection)
var selection = selectionHelper.saveSelection(el)
assert.deepEqual(selection, expectedSelection)
});
})

})