Pastebin PRO Accounts 2016 NEW YEARS SPECIAL! For a limited time only get 40% discount on a LIFETIME PRO account!
SHARE
TWEET
Untitled
a guest
Jun 25th, 2014
13
Never
- /**
- * jQuery plugin for getting position of cursor in textarea
- * @license under Apache license
- * @author Bevis Zhao (i@bevis.me, http://bevis.me)
- */
- (function($, window, document, undefined) {
- $(function() {
- var calculator = {
- // key styles
- primaryStyles: ['fontFamily', 'fontSize', 'fontWeight', 'fontVariant', 'fontStyle',
- 'paddingLeft', 'paddingTop', 'paddingBottom', 'paddingRight',
- 'marginLeft', 'marginTop', 'marginBottom', 'marginRight',
- 'borderLeftColor', 'borderTopColor', 'borderBottomColor', 'borderRightColor',
- 'borderLeftStyle', 'borderTopStyle', 'borderBottomStyle', 'borderRightStyle',
- 'borderLeftWidth', 'borderTopWidth', 'borderBottomWidth', 'borderRightWidth',
- 'line-height', 'outline'],
- specificStyle: {
- 'word-wrap': 'break-word',
- 'overflow-x': 'hidden',
- 'overflow-y': 'auto'
- },
- simulator : $('<div id="textarea_simulator" contenteditable="true"/>').css({
- position: 'absolute',
- top: 0,
- left: 0,
- visibility: 'hidden'
- }).appendTo(document.body),
- toHtml : function(text) {
- return text.replace(/</g,'<').replace(/>/g,'>').replace(/\n/g, '<br>')
- .replace(/(\s)/g,'<span style="white-space:pre-wrap;">$1</span>');
- },
- // calculate position
- getCaretPosition: function() {
- var cal = calculator, self = this, element = self[0], elementOffset = self.offset();
- // IE has easy way to get caret offset position
- if ($.browser.msie) {
- // must get focus first
- element.focus();
- var range = document.selection.createRange();
- return {
- left: range.boundingLeft - elementOffset.left,
- top: parseInt(range.boundingTop) - elementOffset.top + element.scrollTop
- + document.documentElement.scrollTop + parseInt(self.getComputedStyle("fontSize"))
- };
- }
- cal.simulator.empty();
- // clone primary styles to imitate textarea
- $.each(cal.primaryStyles, function(index, styleName) {
- self.cloneStyle(cal.simulator, styleName);
- });
- // caculate width and height
- cal.simulator.css($.extend({
- 'width': self.width(),
- 'height': self.height()
- }, cal.specificStyle));
- var value = self.val(), cursorPosition = self.getCursorPosition();
- var beforeText = value.substring(0, cursorPosition),
- afterText = value.substring(cursorPosition);
- var before = $('<span class="before"/>').html(cal.toHtml(beforeText)),
- focus = $('<span class="focus"/>'),
- after = $('<span class="after"/>').html(cal.toHtml(afterText));
- cal.simulator.append(before).append(focus).append(after);
- var focusOffset = focus.offset(), simulatorOffset = cal.simulator.offset();
- // alert(focusOffset.left + ',' + simulatorOffset.left + ',' + element.scrollLeft);
- return {
- top: focusOffset.top - simulatorOffset.top - element.scrollTop
- // calculate and add the font height except Firefox
- + ($.browser.mozilla ? 0 : parseInt(self.getComputedStyle("fontSize"))),
- left: focus[0].offsetLeft - cal.simulator[0].offsetLeft - element.scrollLeft
- };
- }
- };
- $.fn.extend({
- getComputedStyle: function(styleName) {
- if (this.length == 0) return;
- var thiz = this[0];
- var result = this.css(styleName);
- result = result || ($.browser.msie ?
- thiz.currentStyle[styleName]:
- document.defaultView.getComputedStyle(thiz, null)[styleName]);
- return result;
- },
- // easy clone method
- cloneStyle: function(target, styleName) {
- var styleVal = this.getComputedStyle(styleName);
- if (!!styleVal) {
- $(target).css(styleName, styleVal);
- }
- },
- cloneAllStyle: function(target, style) {
- var thiz = this[0];
- for (var styleName in thiz.style) {
- var val = thiz.style[styleName];
- typeof val == 'string' || typeof val == 'number'
- ? this.cloneStyle(target, styleName)
- : NaN;
- }
- },
- getCursorPosition : function() {
- var thiz = this[0], result = 0;
- if ('selectionStart' in thiz) {
- result = thiz.selectionStart;
- } else if('selection' in document) {
- var range = document.selection.createRange();
- if (parseInt($.browser.version) > 6) {
- thiz.focus();
- var length = document.selection.createRange().text.length;
- range.moveStart('character', - thiz.value.length);
- result = range.text.length - length;
- } else {
- var bodyRange = document.body.createTextRange();
- bodyRange.moveToElementText(thiz);
- for (; bodyRange.compareEndPoints("StartToStart", range) < 0; result++)
- bodyRange.moveStart('character', 1);
- for (var i = 0; i <= result; i ++){
- if (thiz.value.charAt(i) == '\n')
- result++;
- }
- var enterCount = thiz.value.split('\n').length - 1;
- result -= enterCount;
- return result;
- }
- }
- return result;
- },
- getCaretPosition: calculator.getCaretPosition
- });
- });
- })(jQuery, window, document);
- /*
- * AUTOSUGGEST 2.0
- */
- AutoSuggest = {
- timerId: 0,
- ul: undefined,
- cachedString: '', // if last string is the same string as the word to match
- cachedField: '', // if last field is the same as current field, e.g. only caretmovement
- locale: '', // language for Ajax
- init: function(){
- // Get current language from the page
- var ej = jQuery(".lang-select").find("a");
- if(ej.eq(0).hasClass("active")){ // if english
- AutoSuggest.locale = "en";
- }
- else{
- AutoSuggest.locale = "ja";
- }
- // Create hidden suggestion ul box and append it to the body
- jQuery(document.body).append('<ul id="autosuggest"></ul>');
- AutoSuggest.ul = jQuery("#autosuggest");
- AutoSuggest.ul.mouseover(function(e){
- if($('focussedLi')){
- $(focussedLi).removeAttribute('id');
- }
- });
- // Get all Elements where it should be applied on
- var tagfields = jQuery(".autosuggest, #post_tags, #tags");
- tagfields.each(function(index, tagfield){ // for all tagfields
- AutoSuggest.add(tagfield);
- });
- },
- add: function(tagfield){
- tagfield = jQuery(tagfield);
- tagfield.blur(function(){
- setTimeout(function(){
- AutoSuggest.ul.hide()
- }, 500);
- });
- tagfield.attr("autocomplete", "off");
- tagfield.keyup(function(e){
- var tagfield = this;
- var tf = false;
- if(tagfield.tagName === 'INPUT'){
- tf = e.keyCode !== Event.KEY_UP && e.keyCode !== Event.KEY_DOWN && e.keyCode !== Event.KEY_PAGEUP && e.keyCode !== Event.KEY_PAGEDOWN;
- }
- else if(tagfield.tagName === 'TEXTAREA'){
- tf = e.keyCode !== Event.KEY_PAGEUP && e.keyCode !== Event.KEY_PAGEDOWN;
- }
- if(tf){ // if not up or down key and or not pagedown or pageup
- var pos = AutoSuggest.getWordStartAndEnd(this);
- var wordToMatch = this.value.substring(pos['start'], pos['end']);
- var cachedString = AutoSuggest.cachedString;
- var cachedField = AutoSuggest.cachedField;
- if(wordToMatch !== cachedString && tagfield.value !== cachedField && wordToMatch !== ''){
- clearTimeout(AutoSuggest.timerId);
- timerId = setTimeout(function(){
- AutoSuggest.sendTagSuggestRequest(wordToMatch, tagfield);
- }, 380);
- }
- else{
- AutoSuggest.ul.html('').hide();
- }
- AutoSuggest.cachedString = wordToMatch;
- AutoSuggest.cachedField = tagfield.value;
- console.log(cachedString + " !== " + wordToMatch);
- }
- });
- tagfield.keydown(function(e){
- var tagfield = this;
- if(e.keyCode === Event.KEY_RETURN && AutoSuggest.ul.children().length > 0){
- AutoSuggest.addLiAsText($('focussedLi'), tagfield);
- e.preventDefault();
- }
- if(AutoSuggest.ul.is(":visible")){
- var lis = AutoSuggest.ul.find("li");
- var cur = -1;
- for(var i = 0; i < lis.length; i++){
- if(lis[i].id && lis[i].id === 'focussedLi'){
- cur = i;
- lis[i].removeAttribute('id');
- break;
- }
- }
- if(e.keyCode === Event.KEY_PAGEUP || (e.keyCode === Event.KEY_UP && tagfield.tagName === 'INPUT')){
- if(cur > 0){
- lis[cur-1].id = 'focussedLi';
- }
- else{
- lis[lis.length-1].id = 'focussedLi';
- }
- e.preventDefault();
- }
- else if(e.keyCode === Event.KEY_PAGEDOWN || (e.keyCode === Event.KEY_DOWN && tagfield.tagName === 'INPUT')){
- if(cur < lis.length - 1 && cur >= 0){
- lis[cur+1].id = 'focussedLi';
- }
- else{
- lis[0].id = 'focussedLi';
- }
- e.preventDefault();
- }
- }
- });
- },
- getWordStartAndEnd: function(inp){
- var rtrn = {
- 'start': 0,
- 'end': 0,
- };
- offsetStart = false;
- orStart = AutoSuggest.doGetCaretPosition(inp);
- while(orStart > 0 && inp.value[orStart - 1] !== ' '){
- orStart--;
- }
- rtrn['start'] = orStart;
- rtrn['end'] = rtrn['start'];
- while(inp.value[rtrn['end']] !== ' ' && rtrn['end'] <= inp.value.length){
- rtrn['end']++;
- }
- return rtrn;
- },
- doGetCaretPosition: function(oField){
- var iCaretPos = 0;
- if(document.selection){
- oField.focus();
- var oSel = document.selection.createRange();
- oSel.moveStart('character', - oField.value.length);
- iCaretPos = oSel.text.length;
- }
- else if(oField.selectionStart || oField.selectionStart === '0'){
- iCaretPos = oField.selectionStart;
- }
- return iCaretPos;
- },
- sendTagSuggestRequest: function(wordToMatch, tagfield){
- var locale;
- if($('locale')){ // if undefined
- $('locale').readAttribute('rel');
- }
- else{
- locale = AutoSuggest.locale;
- }
- new Ajax.Request('http://chan.sankakucomplex.com/tag/autosuggest?tag=' + wordToMatch + '&locale=' + locale, {
- method: 'get',
- onSuccess: function(transport){
- AutoSuggest.displayResults(transport.responseText || "{}", tagfield);
- },
- onFailure: function() {
- console.log("Ajax tag-suggest failure");
- }
- });
- },
- displayResults: function(results, tagfield){
- // Get tagfield position + caret position if Textarea
- var left = 0;
- var top = 0;
- var offset = 10;
- var jtagfield = jQuery(tagfield);
- if(tagfield.tagName === 'INPUT'){
- top = jtagfield.offset().top + jtagfield.height() + offset;
- left = jtagfield.offset().left;
- }
- else if(tagfield.tagName === 'TEXTAREA'){
- var caret = jtagfield.getCaretPosition();
- top = jtagfield.offset().top + caret.top + offset;
- left = jtagfield.offset().left + caret.left;
- }
- AutoSuggest.ul.html('').css({
- "top": top + "px",
- "left": left + "px",
- });
- var res = eval('(' + results + ')');
- var pos = AutoSuggest.getWordStartAndEnd(tagfield);
- var wordToMatch = tagfield.value.substring(pos['start'], pos['end']);
- if(res[1] && res[0] === wordToMatch){
- if(res[1].length > 0) {
- for(var i = 0; i < res[1].length; i++){
- var li = new Element('li');
- li.appendChild(new Element('span').update(res[1][i]));
- if(res[i+2]){
- li.appendChild(new Element('span').update(res[i+2]));
- }
- li.appendChild(document.createElement('br'));
- li.observe('click', function(e){
- AutoSuggest.addLiAsText(this, tagfield);
- e.preventDefault();
- });
- AutoSuggest.ul.append(jQuery(li));
- }
- AutoSuggest.ul.show();
- // add PUPD note
- if(tagfield.tagName === 'TEXTAREA'){
- AutoSuggest.ul.append('<div id="autosuggestPUPD">^ Pg Up / Pg Down v</div>');
- }
- }
- else{
- AutoSuggest.ul.hide();
- }
- }
- },
- addLiAsText: function(li, srch){
- var str = li.firstDescendant().firstChild.nodeValue;
- var pos = AutoSuggest.getWordStartAndEnd(srch);
- var prefix = srch.value.substring(0, pos['start']);
- var postfix = srch.value.substring(pos['end']);
- srch.value = prefix + str + postfix;
- srch.focus();
- AutoSuggest.cachedString = str;
- AutoSuggest.setCaretToPos(srch, prefix.length+str.length);
- if(srch.createTextRange){
- var range = srch.createTextRange();
- range.collapse(true);
- range.moveEnd('character', srch.value.length);
- range.moveStart('character', srch.value.length);
- range.select();
- }
- AutoSuggest.ul.html('').hide();
- },
- setCaretToPos:function(input, pos) {
- AutoSuggest.setSelectionRange(input, pos, pos);
- },
- setSelectionRange: function(input, selectionStart, selectionEnd) {
- if (input.setSelectionRange) {
- input.focus();
- input.setSelectionRange(selectionStart, selectionEnd);
- }
- else if (input.createTextRange) {
- var range = input.createTextRange();
- range.collapse(true);
- range.moveEnd('character', selectionEnd);
- range.moveStart('character', selectionStart);
- range.select();
- }
- },
- };
- jQuery(document).ready(function(){
- AutoSuggest.init();
- });
RAW Paste Data
