mirror of
https://github.com/ether/etherpad-lite.git
synced 2025-02-01 03:12:42 +01:00
updating sendkeys, this version will be broken
This commit is contained in:
parent
e051f2f2f7
commit
aad7f679a7
1 changed files with 587 additions and 386 deletions
|
@ -1,199 +1,416 @@
|
||||||
// Cross-broswer implementation of text ranges and selections
|
'use strict';
|
||||||
// documentation: http://bililite.com/blog/2011/01/11/cross-browser-.and-selections/
|
|
||||||
// Version: 1.1
|
|
||||||
// Copyright (c) 2010 Daniel Wachsstock
|
|
||||||
// MIT license:
|
|
||||||
// Permission is hereby granted, free of charge, to any person
|
|
||||||
// obtaining a copy of this software and associated documentation
|
|
||||||
// files (the "Software"), to deal in the Software without
|
|
||||||
// restriction, including without limitation the rights to use,
|
|
||||||
// copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
||||||
// copies of the Software, and to permit persons to whom the
|
|
||||||
// Software is furnished to do so, subject to the following
|
|
||||||
// conditions:
|
|
||||||
|
|
||||||
// The above copyright notice and this permission notice shall be
|
let bililiteRange; // create one global variable
|
||||||
// included in all copies or substantial portions of the Software.
|
|
||||||
|
|
||||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
(function(){
|
||||||
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
|
|
||||||
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
|
||||||
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
|
|
||||||
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
|
||||||
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
|
||||||
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
|
|
||||||
// OTHER DEALINGS IN THE SOFTWARE.
|
|
||||||
|
|
||||||
(function($){
|
const datakey = Symbol(); // use as the key to modify elements.
|
||||||
|
|
||||||
bililiteRange = function(el, debug){
|
bililiteRange = function(el){
|
||||||
var ret;
|
var ret;
|
||||||
if (debug){
|
if (el.setSelectionRange){
|
||||||
ret = new NothingRange(); // Easier to force it to use the no-selection type than to try to find an old browser
|
// Element is an input or textarea
|
||||||
}else if (document.selection && !document.addEventListener){
|
// note that some input elements do not allow selections
|
||||||
// Internet Explorer 8 and lower
|
try{
|
||||||
ret = new IERange();
|
el.selectionStart = el.selectionStart;
|
||||||
}else if (window.getSelection && el.setSelectionRange){
|
|
||||||
// Standards. Element is an input or textarea
|
|
||||||
ret = new InputRange();
|
ret = new InputRange();
|
||||||
}else if (window.getSelection){
|
}catch(e){
|
||||||
// Standards, with any other kind of element
|
|
||||||
ret = new W3CRange()
|
|
||||||
}else{
|
|
||||||
// doesn't support selection
|
|
||||||
ret = new NothingRange();
|
ret = new NothingRange();
|
||||||
}
|
}
|
||||||
|
}else{
|
||||||
|
// Standards, with any other kind of element
|
||||||
|
ret = new W3CRange();
|
||||||
|
}
|
||||||
ret._el = el;
|
ret._el = el;
|
||||||
|
// determine parent document, as implemented by John McLear <john@mclear.co.uk>
|
||||||
ret._doc = el.ownerDocument;
|
ret._doc = el.ownerDocument;
|
||||||
ret._win = 'defaultView' in ret._doc ? ret._doc.defaultView : ret._doc.parentWindow;
|
ret._win = ret._doc.defaultView;
|
||||||
ret._textProp = textProp(el);
|
ret._bounds = [0, ret.length];
|
||||||
ret._bounds = [0, ret.length()];
|
|
||||||
|
// selection tracking. We want clicks to set the selection to the clicked location but tabbing in or element.focus() should restore
|
||||||
|
// the selection to what it was.
|
||||||
|
// There's no good way to do this. I just assume that a mousedown (or a drag and drop
|
||||||
|
// into the element) within 100 ms of the focus event must have caused the focus, and
|
||||||
|
// therefore we should not restore the selection.
|
||||||
|
if (!(el[datakey])){ // we haven't processed this element yet
|
||||||
|
const data = createDataObject (el);
|
||||||
|
startupHooks.forEach ( hook => hook (el, ret, data) );
|
||||||
|
}
|
||||||
return ret;
|
return ret;
|
||||||
}
|
}
|
||||||
|
|
||||||
function textProp(el){
|
bililiteRange.version = 3.2;
|
||||||
// returns the property that contains the text of the element
|
|
||||||
if (typeof el.value != 'undefined') return 'value';
|
const startupHooks = new Set();
|
||||||
if (typeof el.text != 'undefined') return 'text';
|
bililiteRange.addStartupHook = fn => startupHooks.add(fn);
|
||||||
if (typeof el.textContent != 'undefined') return 'textContent';
|
startupHooks.add (trackSelection);
|
||||||
return 'innerText';
|
startupHooks.add (fixInputEvents);
|
||||||
|
startupHooks.add (correctNewlines);
|
||||||
|
|
||||||
|
function trackSelection (element, range, data){
|
||||||
|
data.selection = [0,0];
|
||||||
|
range.listen('focusout', evt => data.selection = range._nativeSelection() );
|
||||||
|
range.listen('mousedown', evt => data.mousetime = evt.timeStamp );
|
||||||
|
range.listen('drop', evt => data.mousetime = evt.timeStamp );
|
||||||
|
range.listen('focus', evt => {
|
||||||
|
if ('mousetime' in data && evt.timeStamp - data.mousetime < 100) return;
|
||||||
|
range._nativeSelect(range._nativeRange(data.selection))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
function fixInputEvents (element, range, data){
|
||||||
|
// DOM 3 input events, https://www.w3.org/TR/input-events-1/
|
||||||
|
// have a data field with the text inserted, but thatisn't enough to fully describe the change;
|
||||||
|
// we need to know the old text (or at least its length)
|
||||||
|
// and *where* the new text was inserted.
|
||||||
|
// So we enhance input events with that information.
|
||||||
|
// the "newText" should always be the same as the 'data' field, if it is defined
|
||||||
|
data.oldText = range.all();
|
||||||
|
data.liveRanges = new Set();
|
||||||
|
range.listen('input', evt => {
|
||||||
|
const newText = range.all();
|
||||||
|
if (!evt.bililiteRange){
|
||||||
|
evt.bililiteRange = diff (data.oldText, newText);
|
||||||
|
if (evt.bililiteRange.unchanged){
|
||||||
|
// no change. Assume that whatever happened, happened at the selection point (and use whatever data the browser gives us).
|
||||||
|
evt.bililiteRange.start = range.clone().bounds('selection')[1] - (evt.data || '').length;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
data.oldText = newText;
|
||||||
|
|
||||||
|
// Also update live ranges on this element
|
||||||
|
data.liveRanges.forEach( rng => {
|
||||||
|
const start = evt.bililiteRange.start;
|
||||||
|
const oldend = start + evt.bililiteRange.oldText.length;
|
||||||
|
const newend = start + evt.bililiteRange.newText.length;
|
||||||
|
// adjust bounds; this tries to emulate the algorithm that Microsoft Word uses for bookmarks
|
||||||
|
let [b0, b1] = rng.bounds();
|
||||||
|
if (b0 <= start){
|
||||||
|
// no change
|
||||||
|
}else if (b0 > oldend){
|
||||||
|
b0 += newend - oldend;
|
||||||
|
}else{
|
||||||
|
b0 = newend;
|
||||||
|
}
|
||||||
|
if (b1 < start){
|
||||||
|
// no change
|
||||||
|
}else if (b1 >= oldend){
|
||||||
|
b1 += newend - oldend;
|
||||||
|
}else{
|
||||||
|
b1 = start;
|
||||||
|
}
|
||||||
|
rng.bounds([b0, b1]);
|
||||||
|
})
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function diff (oldText, newText){
|
||||||
|
// Try to find the changed text, assuming it was a continuous change
|
||||||
|
if (oldText == newText){
|
||||||
|
return {
|
||||||
|
unchanged: true,
|
||||||
|
start: 0,
|
||||||
|
oldText,
|
||||||
|
newText
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const oldlen = oldText.length;
|
||||||
|
const newlen = newText.length;
|
||||||
|
for (var i = 0; i < newlen && i < oldlen; ++i){
|
||||||
|
if (newText.charAt(i) != oldText.charAt(i)) break;
|
||||||
|
}
|
||||||
|
const start = i;
|
||||||
|
for (i = 0; i < newlen && i < oldlen; ++i){
|
||||||
|
let newpos = newlen-i-1, oldpos = oldlen-i-1;
|
||||||
|
if (newpos < start || oldpos < start) break;
|
||||||
|
if (newText.charAt(newpos) != oldText.charAt(oldpos)) break;
|
||||||
|
}
|
||||||
|
const oldend = oldlen-i;
|
||||||
|
const newend = newlen-i;
|
||||||
|
return {
|
||||||
|
start,
|
||||||
|
oldText: oldText.slice(start, oldend),
|
||||||
|
newText: newText.slice(start, newend)
|
||||||
|
}
|
||||||
|
};
|
||||||
|
bililiteRange.diff = diff; // expose
|
||||||
|
|
||||||
|
function correctNewlines (element, range, data){
|
||||||
|
// we need to insert newlines rather than create new elements, so character-based calculations work
|
||||||
|
range.listen('paste', evt => {
|
||||||
|
if (evt.defaultPrevented) return;
|
||||||
|
// windows adds \r's to clipboard!
|
||||||
|
range.clone().bounds('selection').
|
||||||
|
text(evt.clipboardData.getData("text/plain").replace(/\r/g,''), {inputType: 'insertFromPaste'}).
|
||||||
|
bounds('endbounds').
|
||||||
|
select().
|
||||||
|
scrollIntoView();
|
||||||
|
evt.preventDefault();
|
||||||
|
});
|
||||||
|
range.listen('keydown', function(evt){
|
||||||
|
if (evt.ctrlKey || evt.altKey || evt.shiftKey || evt.metaKey) return;
|
||||||
|
if (evt.defaultPrevented) return;
|
||||||
|
if (evt.key == 'Enter'){
|
||||||
|
range.clone().bounds('selection').
|
||||||
|
text('\n', {inputType: 'insertLineBreak'}).
|
||||||
|
bounds('endbounds').
|
||||||
|
select().
|
||||||
|
scrollIntoView();
|
||||||
|
evt.preventDefault();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// convenience function for defining input events
|
||||||
|
function inputEventInit(type, oldText, newText, start, inputType){
|
||||||
|
return {
|
||||||
|
type,
|
||||||
|
inputType,
|
||||||
|
data: newText,
|
||||||
|
bubbles: true,
|
||||||
|
bililiteRange: {
|
||||||
|
unchanged: (oldText == newText),
|
||||||
|
start,
|
||||||
|
oldText,
|
||||||
|
newText
|
||||||
|
}
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
// base class
|
// base class
|
||||||
function Range(){}
|
function Range(){}
|
||||||
Range.prototype = {
|
Range.prototype = {
|
||||||
length: function() {
|
// allow use of range[0] and range[1] for start and end of bounds
|
||||||
return this._el[this._textProp].replace(/\r/g, '').length; // need to correct for IE's CrLf weirdness
|
get 0(){
|
||||||
|
return this.bounds()[0];
|
||||||
|
},
|
||||||
|
set 0(x){
|
||||||
|
this.bounds([x, this[1]]);
|
||||||
|
return x;
|
||||||
|
},
|
||||||
|
get 1(){
|
||||||
|
return this.bounds()[1];
|
||||||
|
},
|
||||||
|
set 1(x){
|
||||||
|
this.bounds([this[0], x]);
|
||||||
|
return x;
|
||||||
|
},
|
||||||
|
all: function(text){
|
||||||
|
if (arguments.length){
|
||||||
|
return this.bounds('all').text(text, {inputType: 'insertReplacementText'});
|
||||||
|
}else{
|
||||||
|
return this._el[this._textProp];
|
||||||
|
}
|
||||||
},
|
},
|
||||||
bounds: function(s){
|
bounds: function(s){
|
||||||
if (s === 'all'){
|
if (typeof s === 'number'){
|
||||||
this._bounds = [0, this.length()];
|
this._bounds = [s,s];
|
||||||
}else if (s === 'start'){
|
}else if (bililiteRange.bounds[s]){
|
||||||
this._bounds = [0, 0];
|
this.bounds(bililiteRange.bounds[s].apply(this, arguments));
|
||||||
}else if (s === 'end'){
|
}else if (s && s.bounds){
|
||||||
this._bounds = [this.length(), this.length()];
|
this._bounds = s.bounds(); // copy bounds from an existing range
|
||||||
}else if (s === 'selection'){
|
|
||||||
this.bounds ('all'); // first select the whole thing for constraining
|
|
||||||
this._bounds = this._nativeSelection();
|
|
||||||
}else if (s){
|
}else if (s){
|
||||||
this._bounds = s; // don't error check now; the element may change at any moment, so constrain it when we need it.
|
this._bounds = s; // don't do error checking now; things may change at a moment's notice
|
||||||
}else{
|
}else{
|
||||||
|
// constrain bounds now
|
||||||
var b = [
|
var b = [
|
||||||
Math.max(0, Math.min (this.length(), this._bounds[0])),
|
Math.max(0, Math.min (this.length, this._bounds[0])),
|
||||||
Math.max(0, Math.min (this.length(), this._bounds[1]))
|
Math.max(0, Math.min (this.length, this._bounds[1]))
|
||||||
];
|
];
|
||||||
return b; // need to constrain it to fit
|
b[1] = Math.max(b[0], b[1]);
|
||||||
|
return b;
|
||||||
}
|
}
|
||||||
return this; // allow for chaining
|
return this; // allow for chaining
|
||||||
},
|
},
|
||||||
|
clone: function(){
|
||||||
|
return bililiteRange(this._el).bounds(this.bounds());
|
||||||
|
},
|
||||||
|
get data(){
|
||||||
|
return this._el[datakey];
|
||||||
|
},
|
||||||
|
dispatch: function(opts = {}){
|
||||||
|
var event = new Event (opts.type, opts);
|
||||||
|
event.view = this._win;
|
||||||
|
for (let prop in opts) try { event[prop] = opts[prop] } catch(e){}; // ignore read-only errors for properties that were copied in the previous line
|
||||||
|
this._el.dispatchEvent(event); // note that the event handlers will be called synchronously, before the "return this;"
|
||||||
|
return this;
|
||||||
|
},
|
||||||
|
get document() {
|
||||||
|
return this._doc;
|
||||||
|
},
|
||||||
|
dontlisten: function (type, func = console.log){
|
||||||
|
this._el.removeEventListener(type, func);
|
||||||
|
return this;
|
||||||
|
},
|
||||||
|
get element() {
|
||||||
|
return this._el
|
||||||
|
},
|
||||||
|
get length() {
|
||||||
|
return this._el[this._textProp].length;
|
||||||
|
},
|
||||||
|
live (on = true){
|
||||||
|
this.data.liveRanges[on ? 'add' : 'delete'](this);
|
||||||
|
return this;
|
||||||
|
},
|
||||||
|
listen: function (type, func = console.log){
|
||||||
|
this._el.addEventListener(type, func);
|
||||||
|
return this;
|
||||||
|
},
|
||||||
|
scrollIntoView: function(scroller = (top => this._el.scrollTop = top) ){
|
||||||
|
var top = this.top();
|
||||||
|
// scroll into position if necessary
|
||||||
|
if (this._el.scrollTop > top || this._el.scrollTop+this._el.clientHeight < top){
|
||||||
|
scroller.call(this._el, top);
|
||||||
|
}
|
||||||
|
return this;
|
||||||
|
},
|
||||||
select: function(){
|
select: function(){
|
||||||
this._nativeSelect(this._nativeRange(this.bounds()));
|
var b = this.data.selection = this.bounds();
|
||||||
|
if (this._el === this._doc.activeElement){
|
||||||
|
// only actually select if this element is active!
|
||||||
|
this._nativeSelect(this._nativeRange(b));
|
||||||
|
}
|
||||||
|
this.dispatch({type: 'select', bubbles: true});
|
||||||
return this; // allow for chaining
|
return this; // allow for chaining
|
||||||
},
|
},
|
||||||
text: function(text, select){
|
selection: function(text){
|
||||||
if (arguments.length){
|
if (arguments.length){
|
||||||
this._nativeSetText(text, this._nativeRange(this.bounds()));
|
return this.bounds('selection').text(text).bounds('endbounds').select();
|
||||||
if (select == 'start'){
|
}else{
|
||||||
this.bounds ([this._bounds[0], this._bounds[0]]);
|
return this.bounds('selection').text();
|
||||||
this.select();
|
|
||||||
}else if (select == 'end'){
|
|
||||||
this.bounds ([this._bounds[0]+text.length, this._bounds[0]+text.length]);
|
|
||||||
this.select();
|
|
||||||
}else if (select == 'all'){
|
|
||||||
this.bounds ([this._bounds[0], this._bounds[0]+text.length]);
|
|
||||||
this.select();
|
|
||||||
}
|
}
|
||||||
|
},
|
||||||
|
sendkeys: function (text){
|
||||||
|
this.data.sendkeysOriginalText = this.text();
|
||||||
|
this.data.sendkeysBounds = undefined;
|
||||||
|
function simplechar (rng, c){
|
||||||
|
if (/^{[^}]*}$/.test(c)) c = c.slice(1,-1); // deal with unknown {key}s
|
||||||
|
rng.text(c).bounds('endbounds');
|
||||||
|
}
|
||||||
|
text.replace(/{[^}]*}|[^{]+|{/g, part => (bililiteRange.sendkeys[part] || simplechar)(this, part, simplechar) );
|
||||||
|
this.bounds(this.data.sendkeysBounds);
|
||||||
|
this.dispatch({type: 'sendkeys', detail: text});
|
||||||
|
return this;
|
||||||
|
},
|
||||||
|
text: function(text, {inputType = 'insertText'} = {}){
|
||||||
|
if ( text !== undefined ){
|
||||||
|
let eventparams = [this.text(), text, this[0], inputType];
|
||||||
|
this.dispatch (inputEventInit('beforeinput',...eventparams));
|
||||||
|
this._nativeSetText(text, this._nativeRange(this.bounds()));
|
||||||
|
this[1] = this[0]+text.length;
|
||||||
|
this.dispatch (inputEventInit('input',...eventparams));
|
||||||
return this; // allow for chaining
|
return this; // allow for chaining
|
||||||
}else{
|
}else{
|
||||||
return this._nativeGetText(this._nativeRange(this.bounds()));
|
return this._nativeGetText(this._nativeRange(this.bounds()));
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
insertEOL: function (){
|
top: function(){
|
||||||
this._nativeEOL();
|
return this._nativeTop(this._nativeRange(this.bounds()));
|
||||||
this._bounds = [this._bounds[0]+1, this._bounds[0]+1]; // move past the EOL marker
|
},
|
||||||
|
get window() {
|
||||||
|
return this._win;
|
||||||
|
},
|
||||||
|
wrap: function (n){
|
||||||
|
this._nativeWrap(n, this._nativeRange(this.bounds()));
|
||||||
return this;
|
return this;
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
// allow extensions ala jQuery
|
||||||
|
bililiteRange.prototype = Range.prototype;
|
||||||
|
bililiteRange.extend = function(fns){
|
||||||
|
Object.assign(bililiteRange.prototype, fns);
|
||||||
|
};
|
||||||
|
|
||||||
|
bililiteRange.override = (name, fn) => {
|
||||||
|
const oldfn = bililiteRange.prototype[name];
|
||||||
|
bililiteRange.prototype[name] = function(){
|
||||||
|
const oldsuper = this.super;
|
||||||
|
this.super = oldfn;
|
||||||
|
const ret = fn.apply(this, arguments);
|
||||||
|
this.super = oldsuper;
|
||||||
|
return ret;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
//bounds functions
|
||||||
|
bililiteRange.bounds = {
|
||||||
|
all: function() { return [0, this.length] },
|
||||||
|
start: function() { return 0 },
|
||||||
|
end: function() { return this.length },
|
||||||
|
selection: function() {
|
||||||
|
if (this._el === this._doc.activeElement){
|
||||||
|
this.bounds ('all'); // first select the whole thing for constraining
|
||||||
|
return this._nativeSelection();
|
||||||
|
}else{
|
||||||
|
return this.data.selection;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
startbounds: function() { return this[0] },
|
||||||
|
endbounds: function() { return this[1] },
|
||||||
|
union: function (name,...rest) {
|
||||||
|
const b = this.clone().bounds(...rest);
|
||||||
|
return [ Math.min(this[0], b[0]), Math.max(this[1], b[1]) ];
|
||||||
|
},
|
||||||
|
intersection: function (name,...rest) {
|
||||||
|
const b = this.clone().bounds(...rest);
|
||||||
|
return [ Math.max(this[0], b[0]), Math.min(this[1], b[1]) ];
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// sendkeys functions
|
||||||
function IERange(){}
|
bililiteRange.sendkeys = {
|
||||||
IERange.prototype = new Range();
|
'{tab}': function (rng, c, simplechar){
|
||||||
IERange.prototype._nativeRange = function (bounds){
|
simplechar(rng, '\t'); // useful for inserting what would be whitespace
|
||||||
var rng;
|
},
|
||||||
if (this._el.tagName == 'INPUT'){
|
'{newline}': function (rng){
|
||||||
// IE 8 is very inconsistent; textareas have createTextRange but it doesn't work
|
rng.text('\n', {inputType: 'insertLineBreak'}).bounds('endbounds');
|
||||||
rng = this._el.createTextRange();
|
},
|
||||||
}else{
|
'{backspace}': function (rng){
|
||||||
rng = this._doc.body.createTextRange ();
|
var b = rng.bounds();
|
||||||
rng.moveToElementText(this._el);
|
if (b[0] == b[1]) rng.bounds([b[0]-1, b[0]]); // no characters selected; it's just an insertion point. Remove the previous character
|
||||||
}
|
rng.text('', {inputType: 'deleteContentBackward'}); // delete the characters and update the selection
|
||||||
if (bounds){
|
},
|
||||||
if (bounds[1] < 0) bounds[1] = 0; // IE tends to run elements out of bounds
|
'{del}': function (rng){
|
||||||
if (bounds[0] > this.length()) bounds[0] = this.length();
|
var b = rng.bounds();
|
||||||
if (bounds[1] < rng.text.replace(/\r/g, '').length){ // correct for IE's CrLf wierdness
|
if (b[0] == b[1]) rng.bounds([b[0], b[0]+1]); // no characters selected; it's just an insertion point. Remove the next character
|
||||||
// block-display elements have an invisible, uncounted end of element marker, so we move an extra one and use the current length of the range
|
rng.text('', {inputType: 'deleteContentForward'}).bounds('endbounds'); // delete the characters and update the selection
|
||||||
rng.moveEnd ('character', -1);
|
},
|
||||||
rng.moveEnd ('character', bounds[1]-rng.text.replace(/\r/g, '').length);
|
'{rightarrow}': function (rng){
|
||||||
}
|
var b = rng.bounds();
|
||||||
if (bounds[0] > 0) rng.moveStart('character', bounds[0]);
|
if (b[0] == b[1]) ++b[1]; // no characters selected; it's just an insertion point. Move to the right
|
||||||
}
|
rng.bounds([b[1], b[1]]);
|
||||||
return rng;
|
},
|
||||||
};
|
'{leftarrow}': function (rng){
|
||||||
IERange.prototype._nativeSelect = function (rng){
|
var b = rng.bounds();
|
||||||
rng.select();
|
if (b[0] == b[1]) --b[0]; // no characters selected; it's just an insertion point. Move to the left
|
||||||
};
|
rng.bounds([b[0], b[0]]);
|
||||||
IERange.prototype._nativeSelection = function (){
|
},
|
||||||
// returns [start, end] for the selection constrained to be in element
|
'{selectall}': function (rng){
|
||||||
var rng = this._nativeRange(); // range of the element to constrain to
|
rng.bounds('all');
|
||||||
var len = this.length();
|
},
|
||||||
if (this._doc.selection.type != 'Text') return [0,0]; // append to the end
|
'{selection}': function (rng){
|
||||||
var sel = this._doc.selection.createRange();
|
// insert the characters without the sendkeys processing
|
||||||
try{
|
rng.text(rng.data.sendkeysOriginalText).bounds('endbounds');
|
||||||
return [
|
},
|
||||||
iestart(sel, rng),
|
'{mark}': function (rng){
|
||||||
ieend (sel, rng)
|
rng.data.sendkeysBounds = rng.bounds();
|
||||||
];
|
|
||||||
}catch (e){
|
|
||||||
// IE gets upset sometimes about comparing text to input elements, but the selections cannot overlap, so make a best guess
|
|
||||||
return (sel.parentElement().sourceIndex < this._el.sourceIndex) ? [0,0] : [len, len];
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
IERange.prototype._nativeGetText = function (rng){
|
// Synonyms from the DOM standard (http://www.w3.org/TR/DOM-Level-3-Events-key/)
|
||||||
return rng.text.replace(/\r/g, ''); // correct for IE's CrLf weirdness
|
bililiteRange.sendkeys['{Enter}'] = bililiteRange.sendkeys['{enter}'] = bililiteRange.sendkeys['{newline}'];
|
||||||
};
|
bililiteRange.sendkeys['{Backspace}'] = bililiteRange.sendkeys['{backspace}'];
|
||||||
IERange.prototype._nativeSetText = function (text, rng){
|
bililiteRange.sendkeys['{Delete}'] = bililiteRange.sendkeys['{del}'];
|
||||||
rng.text = text;
|
bililiteRange.sendkeys['{ArrowRight}'] = bililiteRange.sendkeys['{rightarrow}'];
|
||||||
};
|
bililiteRange.sendkeys['{ArrowLeft}'] = bililiteRange.sendkeys['{leftarrow}'];
|
||||||
IERange.prototype._nativeEOL = function(){
|
|
||||||
if (typeof this._el.value != 'undefined'){
|
|
||||||
this.text('\n'); // for input and textarea, insert it straight
|
|
||||||
}else{
|
|
||||||
this._nativeRange(this.bounds()).pasteHTML('<br/>');
|
|
||||||
}
|
|
||||||
};
|
|
||||||
// IE internals
|
|
||||||
function iestart(rng, constraint){
|
|
||||||
// returns the position (in character) of the start of rng within constraint. If it's not in constraint, returns 0 if it's before, length if it's after
|
|
||||||
var len = constraint.text.replace(/\r/g, '').length; // correct for IE's CrLf wierdness
|
|
||||||
if (rng.compareEndPoints ('StartToStart', constraint) <= 0) return 0; // at or before the beginning
|
|
||||||
if (rng.compareEndPoints ('StartToEnd', constraint) >= 0) return len;
|
|
||||||
for (var i = 0; rng.compareEndPoints ('StartToStart', constraint) > 0; ++i, rng.moveStart('character', -1));
|
|
||||||
return i;
|
|
||||||
}
|
|
||||||
function ieend (rng, constraint){
|
|
||||||
// returns the position (in character) of the end of rng within constraint. If it's not in constraint, returns 0 if it's before, length if it's after
|
|
||||||
var len = constraint.text.replace(/\r/g, '').length; // correct for IE's CrLf wierdness
|
|
||||||
if (rng.compareEndPoints ('EndToEnd', constraint) >= 0) return len; // at or after the end
|
|
||||||
if (rng.compareEndPoints ('EndToStart', constraint) <= 0) return 0;
|
|
||||||
for (var i = 0; rng.compareEndPoints ('EndToStart', constraint) > 0; ++i, rng.moveEnd('character', -1));
|
|
||||||
return i;
|
|
||||||
}
|
|
||||||
|
|
||||||
// an input element in a standards document. "Native Range" is just the bounds array
|
// an input element in a standards document. "Native Range" is just the bounds array
|
||||||
function InputRange(){}
|
function InputRange(){}
|
||||||
InputRange.prototype = new Range();
|
InputRange.prototype = new Range();
|
||||||
|
InputRange.prototype._textProp = 'value';
|
||||||
InputRange.prototype._nativeRange = function(bounds) {
|
InputRange.prototype._nativeRange = function(bounds) {
|
||||||
return bounds || [0, this.length()];
|
return bounds || [0, this.length];
|
||||||
};
|
};
|
||||||
InputRange.prototype._nativeSelect = function (rng){
|
InputRange.prototype._nativeSelect = function (rng){
|
||||||
this._el.setSelectionRange(rng[0], rng[1]);
|
this._el.setSelectionRange(rng[0], rng[1]);
|
||||||
|
@ -211,9 +428,27 @@ InputRange.prototype._nativeSetText = function(text, rng){
|
||||||
InputRange.prototype._nativeEOL = function(){
|
InputRange.prototype._nativeEOL = function(){
|
||||||
this.text('\n');
|
this.text('\n');
|
||||||
};
|
};
|
||||||
|
InputRange.prototype._nativeTop = function(rng){
|
||||||
|
if (rng[0] == 0) return 0; // the range starts at the top
|
||||||
|
// I can't remember where I found this clever hack to find the location of text in a text area
|
||||||
|
var clone = this._el.cloneNode(true);
|
||||||
|
clone.style.visibility = 'hidden';
|
||||||
|
clone.style.position = 'absolute';
|
||||||
|
this._el.parentNode.insertBefore(clone, this._el);
|
||||||
|
clone.style.height = '1px';
|
||||||
|
clone.value = this._el.value.slice(0, rng[0]);
|
||||||
|
var top = clone.scrollHeight;
|
||||||
|
// this gives the bottom of the text, so we have to subtract the height of a single line
|
||||||
|
clone.value = 'X';
|
||||||
|
top -= clone.scrollHeight;
|
||||||
|
clone.parentNode.removeChild(clone);
|
||||||
|
return top;
|
||||||
|
}
|
||||||
|
InputRange.prototype._nativeWrap = function() {throw new Error("Cannot wrap in a text element")};
|
||||||
|
|
||||||
function W3CRange(){}
|
function W3CRange(){}
|
||||||
W3CRange.prototype = new Range();
|
W3CRange.prototype = new Range();
|
||||||
|
W3CRange.prototype._textProp = 'textContent';
|
||||||
W3CRange.prototype._nativeRange = function (bounds){
|
W3CRange.prototype._nativeRange = function (bounds){
|
||||||
var rng = this._doc.createRange();
|
var rng = this._doc.createRange();
|
||||||
rng.selectNodeContents(this._el);
|
rng.selectNodeContents(this._el);
|
||||||
|
@ -231,13 +466,13 @@ W3CRange.prototype._nativeSelect = function (rng){
|
||||||
W3CRange.prototype._nativeSelection = function (){
|
W3CRange.prototype._nativeSelection = function (){
|
||||||
// returns [start, end] for the selection constrained to be in element
|
// returns [start, end] for the selection constrained to be in element
|
||||||
var rng = this._nativeRange(); // range of the element to constrain to
|
var rng = this._nativeRange(); // range of the element to constrain to
|
||||||
if (this._win.getSelection().rangeCount == 0) return [this.length(), this.length()]; // append to the end
|
if (this._win.getSelection().rangeCount == 0) return [this.length, this.length]; // append to the end
|
||||||
var sel = this._win.getSelection().getRangeAt(0);
|
var sel = this._win.getSelection().getRangeAt(0);
|
||||||
return [
|
return [
|
||||||
w3cstart(sel, rng),
|
w3cstart(sel, rng),
|
||||||
w3cend (sel, rng)
|
w3cend (sel, rng)
|
||||||
];
|
];
|
||||||
}
|
};
|
||||||
W3CRange.prototype._nativeGetText = function (rng){
|
W3CRange.prototype._nativeGetText = function (rng){
|
||||||
return rng.toString();
|
return rng.toString();
|
||||||
};
|
};
|
||||||
|
@ -255,6 +490,21 @@ W3CRange.prototype._nativeEOL = function(){
|
||||||
rng.insertNode (this._doc.createTextNode('\n'));
|
rng.insertNode (this._doc.createTextNode('\n'));
|
||||||
rng.collapse (false);
|
rng.collapse (false);
|
||||||
};
|
};
|
||||||
|
W3CRange.prototype._nativeTop = function(rng){
|
||||||
|
if (this.length == 0) return 0; // no text, no scrolling
|
||||||
|
if (rng.toString() == ''){
|
||||||
|
var textnode = this._doc.createTextNode('X');
|
||||||
|
rng.insertNode (textnode);
|
||||||
|
}
|
||||||
|
var startrng = this._nativeRange([0,1]);
|
||||||
|
var top = rng.getBoundingClientRect().top - startrng.getBoundingClientRect().top;
|
||||||
|
if (textnode) textnode.parentNode.removeChild(textnode);
|
||||||
|
return top;
|
||||||
|
}
|
||||||
|
W3CRange.prototype._nativeWrap = function(n, rng) {
|
||||||
|
rng.surroundContents(n);
|
||||||
|
};
|
||||||
|
|
||||||
// W3C internals
|
// W3C internals
|
||||||
function nextnode (node, root){
|
function nextnode (node, root){
|
||||||
// in-order traversal
|
// in-order traversal
|
||||||
|
@ -281,10 +531,11 @@ function w3cmoveBoundary (rng, n, bStart, el){
|
||||||
}
|
}
|
||||||
while (node){
|
while (node){
|
||||||
if (node.nodeType == 3){
|
if (node.nodeType == 3){
|
||||||
if (n <= node.nodeValue.length){
|
var length = node.nodeValue.length;
|
||||||
|
if (n <= length){
|
||||||
rng[bStart ? 'setStart' : 'setEnd'](node, n);
|
rng[bStart ? 'setStart' : 'setEnd'](node, n);
|
||||||
// special case: if we end next to a <br>, include that node.
|
// special case: if we end next to a <br>, include that node.
|
||||||
if (n == node.nodeValue.length){
|
if (n == length){
|
||||||
// skip past zero-length text nodes
|
// skip past zero-length text nodes
|
||||||
for (var next = nextnode (node, el); next && next.nodeType==3 && next.nodeValue.length == 0; next = nextnode(next, el)){
|
for (var next = nextnode (node, el); next && next.nodeType==3 && next.nodeValue.length == 0; next = nextnode(next, el)){
|
||||||
rng[bStart ? 'setStartAfter' : 'setEndAfter'](next);
|
rng[bStart ? 'setStartAfter' : 'setEndAfter'](next);
|
||||||
|
@ -294,7 +545,7 @@ function w3cmoveBoundary (rng, n, bStart, el){
|
||||||
return;
|
return;
|
||||||
}else{
|
}else{
|
||||||
rng[bStart ? 'setStartAfter' : 'setEndAfter'](node); // skip past this one
|
rng[bStart ? 'setStartAfter' : 'setEndAfter'](node); // skip past this one
|
||||||
n -= node.nodeValue.length; // and eat these characters
|
n -= length; // and eat these characters
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
node = nextnode (node, el);
|
node = nextnode (node, el);
|
||||||
|
@ -327,8 +578,9 @@ function w3cend (rng, constraint){
|
||||||
|
|
||||||
function NothingRange(){}
|
function NothingRange(){}
|
||||||
NothingRange.prototype = new Range();
|
NothingRange.prototype = new Range();
|
||||||
|
NothingRange.prototype._textProp = 'value';
|
||||||
NothingRange.prototype._nativeRange = function(bounds) {
|
NothingRange.prototype._nativeRange = function(bounds) {
|
||||||
return bounds || [0,this.length()];
|
return bounds || [0,this.length];
|
||||||
};
|
};
|
||||||
NothingRange.prototype._nativeSelect = function (rng){ // do nothing
|
NothingRange.prototype._nativeSelect = function (rng){ // do nothing
|
||||||
};
|
};
|
||||||
|
@ -345,123 +597,72 @@ NothingRange.prototype._nativeSetText = function (text, rng){
|
||||||
NothingRange.prototype._nativeEOL = function(){
|
NothingRange.prototype._nativeEOL = function(){
|
||||||
this.text('\n');
|
this.text('\n');
|
||||||
};
|
};
|
||||||
|
NothingRange.prototype._nativeTop = function(){
|
||||||
})(jQuery);
|
return 0;
|
||||||
|
|
||||||
// insert characters in a textarea or text input field
|
|
||||||
// special characters are enclosed in {}; use {{} for the { character itself
|
|
||||||
// documentation: http://bililite.com/blog/2008/08/20/the-fnsendkeys-plugin/
|
|
||||||
// Version: 2.0
|
|
||||||
// Copyright (c) 2010 Daniel Wachsstock
|
|
||||||
// MIT license:
|
|
||||||
// Permission is hereby granted, free of charge, to any person
|
|
||||||
// obtaining a copy of this software and associated documentation
|
|
||||||
// files (the "Software"), to deal in the Software without
|
|
||||||
// restriction, including without limitation the rights to use,
|
|
||||||
// copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
||||||
// copies of the Software, and to permit persons to whom the
|
|
||||||
// Software is furnished to do so, subject to the following
|
|
||||||
// conditions:
|
|
||||||
|
|
||||||
// The above copyright notice and this permission notice shall be
|
|
||||||
// included in all copies or substantial portions of the Software.
|
|
||||||
|
|
||||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
|
||||||
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
|
|
||||||
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
|
||||||
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
|
|
||||||
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
|
||||||
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
|
||||||
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
|
|
||||||
// OTHER DEALINGS IN THE SOFTWARE.
|
|
||||||
|
|
||||||
(function($){
|
|
||||||
|
|
||||||
$.fn.sendkeys = function (x, opts){
|
|
||||||
return this.each( function(){
|
|
||||||
var localkeys = $.extend({}, opts, $(this).data('sendkeys')); // allow for element-specific key functions
|
|
||||||
// most elements to not keep track of their selection when they lose focus, so we have to do it for them
|
|
||||||
var rng = $.data (this, 'sendkeys.selection');
|
|
||||||
if (!rng){
|
|
||||||
rng = bililiteRange(this).bounds('selection');
|
|
||||||
$.data(this, 'sendkeys.selection', rng);
|
|
||||||
$(this).bind('mouseup.sendkeys', function(){
|
|
||||||
// we have to update the saved range. The routines here update the bounds with each press, but actual keypresses and mouseclicks do not
|
|
||||||
$.data(this, 'sendkeys.selection').bounds('selection');
|
|
||||||
}).bind('keyup.sendkeys', function(evt){
|
|
||||||
// restore the selection if we got here with a tab (a click should select what was clicked on)
|
|
||||||
if (evt.which == 9){
|
|
||||||
// there's a flash of selection when we restore the focus, but I don't know how to avoid that
|
|
||||||
$.data(this, 'sendkeys.selection').select();
|
|
||||||
}else{
|
|
||||||
$.data(this, 'sendkeys.selection').bounds('selection');
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
this.focus();
|
|
||||||
if (typeof x === 'undefined') return; // no string, so we just set up the event handlers
|
|
||||||
$.data(this, 'sendkeys.originalText', rng.text());
|
|
||||||
x.replace(/\n/g, '{enter}'). // turn line feeds into explicit break insertions
|
|
||||||
replace(/{[^}]*}|[^{]+/g, function(s){
|
|
||||||
(localkeys[s] || $.fn.sendkeys.defaults[s] || $.fn.sendkeys.defaults.simplechar)(rng, s);
|
|
||||||
});
|
|
||||||
$(this).trigger({type: 'sendkeys', which: x});
|
|
||||||
});
|
|
||||||
}; // sendkeys
|
|
||||||
|
|
||||||
|
|
||||||
// add the functions publicly so they can be overridden
|
|
||||||
$.fn.sendkeys.defaults = {
|
|
||||||
simplechar: function (rng, s){
|
|
||||||
rng.text(s, 'end');
|
|
||||||
for (var i =0; i < s.length; ++i){
|
|
||||||
var x = s.charCodeAt(i);
|
|
||||||
// a bit of cheating: rng._el is the element associated with rng.
|
|
||||||
$(rng._el).trigger({type: 'keypress', keyCode: x, which: x, charCode: x});
|
|
||||||
}
|
|
||||||
},
|
|
||||||
'{{}': function (rng){
|
|
||||||
$.fn.sendkeys.defaults.simplechar (rng, '{')
|
|
||||||
},
|
|
||||||
'{enter}': function (rng){
|
|
||||||
rng.insertEOL();
|
|
||||||
rng.select();
|
|
||||||
var x = '\n'.charCodeAt(0);
|
|
||||||
$(rng._el).trigger({type: 'keypress', keyCode: x, which: x, charCode: x});
|
|
||||||
},
|
|
||||||
'{backspace}': function (rng){
|
|
||||||
var b = rng.bounds();
|
|
||||||
if (b[0] == b[1]) rng.bounds([b[0]-1, b[0]]); // no characters selected; it's just an insertion point. Remove the previous character
|
|
||||||
rng.text('', 'end'); // delete the characters and update the selection
|
|
||||||
},
|
|
||||||
'{del}': function (rng){
|
|
||||||
var b = rng.bounds();
|
|
||||||
if (b[0] == b[1]) rng.bounds([b[0], b[0]+1]); // no characters selected; it's just an insertion point. Remove the next character
|
|
||||||
rng.text('', 'end'); // delete the characters and update the selection
|
|
||||||
},
|
|
||||||
'{rightarrow}': function (rng){
|
|
||||||
var b = rng.bounds();
|
|
||||||
if (b[0] == b[1]) ++b[1]; // no characters selected; it's just an insertion point. Move to the right
|
|
||||||
rng.bounds([b[1], b[1]]).select();
|
|
||||||
},
|
|
||||||
'{leftarrow}': function (rng){
|
|
||||||
var b = rng.bounds();
|
|
||||||
if (b[0] == b[1]) --b[0]; // no characters selected; it's just an insertion point. Move to the left
|
|
||||||
rng.bounds([b[0], b[0]]).select();
|
|
||||||
},
|
|
||||||
'{selectall}' : function (rng){
|
|
||||||
rng.bounds('all').select();
|
|
||||||
},
|
|
||||||
'{selection}': function (rng){
|
|
||||||
$.fn.sendkeys.defaults.simplechar(rng, $.data(rng._el, 'sendkeys.originalText'));
|
|
||||||
},
|
|
||||||
'{mark}' : function (rng){
|
|
||||||
var bounds = rng.bounds();
|
|
||||||
$(rng._el).one('sendkeys', function(){
|
|
||||||
// set up the event listener to change the selection after the sendkeys is done
|
|
||||||
rng.bounds(bounds).select();
|
|
||||||
});
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
|
NothingRange.prototype._nativeWrap = function() {throw new Error("Wrapping not implemented")};
|
||||||
|
|
||||||
})(jQuery)
|
|
||||||
|
// data for elements, similar to jQuery data, but allows for monitoring with custom events
|
||||||
|
const monitored = new Set();
|
||||||
|
|
||||||
|
function signalMonitor(prop, value, element){
|
||||||
|
const attr = `data-${prop}`;
|
||||||
|
element.dispatchEvent(new CustomEvent(attr, {bubbles: true, detail: value}));
|
||||||
|
try{
|
||||||
|
element.setAttribute (attr, value); // illegal attribute names will throw. Ignore it
|
||||||
|
} finally { /* ignore */ }
|
||||||
|
}
|
||||||
|
|
||||||
|
function createDataObject (el){
|
||||||
|
return el[datakey] = new Proxy(new Data(el), {
|
||||||
|
set(obj, prop, value) {
|
||||||
|
obj[prop] = value;
|
||||||
|
if (monitored.has(prop)) signalMonitor(prop, value, obj.sourceElement);
|
||||||
|
return true; // in strict mode, 'set' returns a success flag
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
var Data = function(el) {
|
||||||
|
Object.defineProperty(this, 'sourceElement', {
|
||||||
|
value: el
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
Data.prototype = {};
|
||||||
|
// for use with ex options. JSON.stringify(range.data) should return only the options that were
|
||||||
|
// both defined with bililiteRange.option() *and* actually had a value set on this particular data object.
|
||||||
|
// JSON.stringify (range.data.all) should return all the options that were defined.
|
||||||
|
Object.defineProperty(Data.prototype, 'toJSON', {
|
||||||
|
value: function(){
|
||||||
|
let ret = {};
|
||||||
|
for (let key in Data.prototype) if (this.hasOwnProperty(key)) ret[key] = this[key];
|
||||||
|
return ret;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
Object.defineProperty(Data.prototype, 'all', {
|
||||||
|
get: function(){
|
||||||
|
let ret = {};
|
||||||
|
for (let key in Data.prototype) ret[key] = this[key];
|
||||||
|
return ret;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
Object.defineProperty(Data.prototype, 'trigger', {
|
||||||
|
value: function(){
|
||||||
|
monitored.forEach(prop => signalMonitor (prop, this[prop], this.sourceElement));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
bililiteRange.createOption = function (name, desc = {}){
|
||||||
|
desc = Object.assign({
|
||||||
|
enumerable: true, // use these as the defaults
|
||||||
|
writable: true,
|
||||||
|
configurable: true
|
||||||
|
}, Object.getOwnPropertyDescriptor(Data.prototype, name), desc);
|
||||||
|
if ('monitored' in desc) monitored[desc.monitored ? 'add' : 'delete'](name);
|
||||||
|
Object.defineProperty(Data.prototype, name, desc);
|
||||||
|
return Data.prototype[name]; // return the default value
|
||||||
|
}
|
||||||
|
|
||||||
|
})();
|
||||||
|
|
Loading…
Reference in a new issue