File: category_autocomplete.js

package info (click to toggle)
tdiary 5.0.11-1
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 2,852 kB
  • sloc: ruby: 22,925; xml: 325; makefile: 16; sh: 10
file content (96 lines) | stat: -rw-r--r-- 2,390 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
/*
 * category_autocomplete.js : Support the automatic input of the category,
 *                            using jQuery UI autocomplete.
 *
 * Copyright (C) 2012 by tamoot <tamoot+tdiary@gmail.com>
 * You can distribute it under GPL2 or any later version.
 */

$(function() {
  var config = $tDiary.plugin.category_autocomplete;
  var support = false;
  var regrep  = ""
  
  if ( $tDiary.style == "tdiary" ){
    support = true;
    regrep  = "^ *\\[.*";
  } else if ( $tDiary.style == 'gfm' ) {
    support = true;
    regrep  = "^# *\\[.*";
  } else if ( $tDiary.style == "wiki" ){
    support = true;
    regrep  = "^! *\\[.*";
  }
  
  function widgetPosition(){
     var caretPosition = Measurement.caretPos($("#body"));
     return {left: caretPosition.left + "px",
             top:  caretPosition.top + 20 + "px",
             width: "auto"};
  }
  
  function matchedCategory(val){
    if(support == false){
      return false;
    }
    
    terms = val.split("\n");
    term  = terms[ terms.length - 1];
    var matched = term.match(regrep);
    if( matched == null ){
      return false;
    }
    
    return true;
    
  }
  
  function typedCategory( term ) {
    var array = term.split("[");
    return array[ array.length - 1 ];
  }
  
  $( "#body" )
    .on( "keydown", function( event ) {
      if ( event.keyCode === $.ui.keyCode.TAB &&
           $( this ).data( "autocomplete" ).menu.active ) {
        event.preventDefault();
      }
    })
    .autocomplete({
      
      delay: 500,
      
      //filtering
      source: function( request, response ) {
        if(matchedCategory(request.term)){
          response( $.ui.autocomplete.filter(
            config.candidates, typedCategory( request.term ) ) );
        }
      },
      
      // prevent value inserted on focus
      focus: function() {
        return false;
      },
      
      // replace textarea
      select: function( event, ui ) {
        var terms = this.value.split("[");
        // remove the current typed category
        terms.pop();
        // add the selected item
        terms.push( ui.item.value );
        this.value = terms.join( "[" ) + "]";
        return false;
      },
      
      // re-positioning supports excluding IE. 
      open: function(){
         if (! document.uniqueID) {
            $(".ui-autocomplete").css(widgetPosition())
         }
      }
   });
});