summaryrefslogtreecommitdiff
path: root/site-media/js/jquery.tagInput.js
blob: d8dc682c0b1d4b65595764099c39a40ae55d391f (plain)
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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
/*
  Copyright (c) 2009 Open Lab, http://www.open-lab.com/
  Written by Roberto Bicchierai http://roberto.open-lab.com.
  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.
*/
/**
   * options.tags an object array [{tag:"tag1",freq:1},{tag:"tag2",freq:2}, {tag:"tag3",freq:3},{tag:"tag4",freq:4} ].
   * options.jsonUrl an url returning a json object array in the same format of options.tag. The url will be called with
   *                              "search" parameter to be used server side to filter results
   * option.autoFilter true/false  default=true when active show only matching tags, "false" should be used for server-side filtering
   * option.autoStart true/false  default=false when active dropdown will appear entering field, otherwise when typing
   * options.sortBy "frequency"|"tag"|"none"  default="tag"
   * options.tagSeparator default="," any separator char as space, comma, semicolumn
   * options.boldify true/false default trrue boldify the matching part of tag in dropdown
   *
   * options.suggestedTags callback an object array like ["sugtag1","sugtag2","sugtag3"]
   * options.suggestedTagsPlaceHolder  jquery proxy for suggested tag placeholder. When placeholder is supplied (hence unique), tagField should be applied on a single input
   *                          (something like  $("#myTagFiled").tagField(...) will works fine: $(":text").tagField(...) probably not!)
   */

if (typeof(String.prototype.trim)  == "undefined"){
    String.prototype.trim = function () {
      return this.replace(/^\s*(\S*(\s+\S+)*)\s*$/, "$1");
    };
}



jQuery.fn.tagInput = function(options) {
  // --------------------------  start default option values --------------------------
  if (!options.tags && !options.jsonUrl) {
    options.tags = [ { tag:"tag1", freq:1 }, { tag:"tag2", freq:2 }, { tag:"tag3", freq:3 }, { tag:"tag4", freq:4 } ];
  }

  if (typeof(options.tagSeparator) == "undefined")
    options.tagSeparator = ",";

  if (typeof(options.autoFilter) == "undefined")
    options.autoFilter = true;

  if (typeof(options.autoStart) == "undefined")
    options.autoStart = false;

  if (typeof(options.boldify) == "undefined")
    options.boldify = true;

  if (typeof(options.sortBy) == "undefined")
    options.sortBy = "tag";

  // --------------------------  end default option values --------------------------


  this.each(function() {

    var theInput = $(this);
    var theDiv;

    theInput.addClass("tagInput");
    theInput.tagOptions=options;

    var suggestedTagsPlaceHolder=options.suggestedTagsPlaceHolder;
    //create suggested tags place if the case
    if (options.suggestedTags){
      if (!suggestedTagsPlaceHolder){
        //create a placeholder
        var stl=$("<div class='tagInputSuggestedTags'><span class='label'>suggested tags: </span><span class='tagInputSuggestedTagList'></span></div>");
        suggestedTagsPlaceHolder=stl.find(".tagInputSuggestedTagList");
        theInput.after(stl);
      }

      //fill with suggestions
      for (var tag in options.suggestedTags) {
        suggestedTagsPlaceHolder.append($("<span class='tag'>" + options.suggestedTags[tag] + "</span>"));
      }

      // bind click on suggestion tags
      suggestedTagsPlaceHolder.find(".tag").click(function() {
        var element = $(this);
        var val = theInput.val();
        var tag = element.text();

        //check if already present
        var re = new RegExp(tag + "\\b","g");
        if (containsTag(val, tag)) {
          val = val.replace(re, ""); //remove all the tag
          element.removeClass("tagUsed");
        } else {
          val = val + options.tagSeparator + tag;
          element.addClass("tagUsed");
        }
        theInput.val(refurbishTags(val));
//        selectSuggTagFromInput();

      });

    }


    // --------------------------  INPUT FOCUS --------------------------
    var tagInputFocus = function () {
      theDiv = $("#__tagInputDiv");
      // check if the result box exists
      if (theDiv.size() <= 0) {
        //create the div
        theDiv = $("<div id='__tagInputDiv' class='tagInputDiv' style='width:" + theInput.get(0).clientWidth + ";display:none; '></div>");
        theInput.after(theDiv);
        theDiv.css({left:theInput.position().left});
      }
      if (options.autoStart)
        tagInputRefreshDiv(theInput, theDiv);
    };


    // --------------------------  INPUT BLUR --------------------------
    var tagInputBlur = function () {
      // reformat string
      theDiv = $("#__tagInputDiv");
      theInput.val(refurbishTags(theInput.val()));

      theDiv.fadeOut(200, function() {
        theDiv.remove();
      });
    };


    // --------------------------  INPUT KEYBOARD --------------------------
    var tagInputKey = function (e) {
      var rows = theDiv.find("div.tagInputLine");
      var rowNum = rows.index(theDiv.find("div.tagInputSel"));

      var ret = true;
      switch (e.which) {
        case 38: //up arrow
          rowNum = (rowNum < 1 ? 0 : rowNum - 1 );
          tagInputHLSCR(rows.eq(rowNum), true);
          break;

        case 40: //down arrow
          rowNum = (rowNum < rows.size() - 1 ? rowNum + 1 : rows.size() - 1 );
          tagInputHLSCR(rows.eq(rowNum), false);
          break;

        case 9: //tab
        case 13: //enter
          if (theDiv.is(":visible")){
            var theRow = rows.eq(rowNum);
            tagInputClickRow(theRow);
            ret = false;
          }
          break;

        case 27: //esc
          theDiv.fadeOut(200);
          break;

        default:
          $(document).stopTime("tagInputRefresh");
          $(document).oneTime(400, "tagInputRefresh", function() {
            tagInputRefreshDiv();
          });
          break;
      }
      return ret;
    };


    // --------------------------  TAG DIV HIGHLIGHT AND SCROLL --------------------------
    var tagInputHLSCR = function(theRowJQ, isUp) {
      if (theRowJQ.size() > 0) {
        var div = theDiv.get(0);
        var theRow = theRowJQ.get(0);
        if (isUp) {
          if (theDiv.scrollTop() > theRow.offsetTop) {
            theDiv.scrollTop(theRow.offsetTop);
          }
        } else {
          if ((theRow.offsetTop + theRow.offsetHeight) > (div.scrollTop + div.offsetHeight)) {
            div.scrollTop = theRow.offsetTop + theRow.offsetHeight - div.offsetHeight;
          }
        }
        theDiv.find("div.tagInputSel").removeClass("tagInputSel");
        theRowJQ.addClass("tagInputSel");
      }
    };


    // --------------------------  TAG LINE CLICK --------------------------
    var tagInputClickRow = function(theRow) {
      var lastComma = theInput.val().lastIndexOf(options.tagSeparator);
      var sep= lastComma<=0? (""):(options.tagSeparator+ (options.tagSeparator==" "?"":" "));
      var newVal = (theInput.val().substr(0, lastComma) + sep + theRow.find(".tagInputLineTag").text()).trim();
      theInput.val(newVal);
      theDiv.hide();
      $().oneTime(200, function() {
        theInput.focus();
      });
    };


    // --------------------------  REFILL TAG BOX --------------------------
    var tagInputRefreshDiv = function () {

      var lastComma = theInput.val().lastIndexOf(options.tagSeparator);
      var search = theInput.val().substr(lastComma + 1).trim();


      // --------------------------  FILLING THE DIV --------------------------
      var fillingCallbak = function(tags) {
        if (options.sortBy == "frequency") {
          tags = tags.sort(function (a, b) {
            if (a.freq < b.freq)
              return 1;
            if (a.freq > b.freq)
              return -1;
            return 0;
          });

        } else if (options.sortBy == "tag") {
          tags = tags.sort(function (a, b) {
            if (a.tag < b.tag)
              return -1;
            if (a.tag > b.tag)
              return 1;
            return 0;
          });
        }

        for (var i in tags) {
          var el = tags[i];
          var matches = el.tag.toLocaleLowerCase().indexOf(search.toLocaleLowerCase()) == 0;
          if (!options.autoFilter || matches) {
            var line = $("<div class='tagInputLine'></div>");
            var tag = el.tag;
            if (options.boldify && matches) {
              tag = "<b>" + tag.substring(0, search.length) + "</b>" + tag.substring(search.length);
            }

            line.append("<div class='tagInputLineTag'>" + tag + "</div>");
            if (el.freq)
              line.append("<div class='tagInputLineFreq'>" + el.freq + "</div>");
            theDiv.append(line);
          }
        }
        if (theDiv.html()!=""){
          theDiv.fadeIn();
        }

        theDiv.find("div:first").addClass("tagInputSel");
        theDiv.find("div.tagInputLine").bind("click", function() {
          tagInputClickRow($(this));
        });
      };


      if (search != "" || options.autoStart) {
        theDiv.html("");

        if (options.tags)
          fillingCallbak(options.tags);
        else{
          var data = {search:search};
          $.getJSON(options.jsonUrl, data, fillingCallbak );
        }
      } else {
        theDiv.fadeOut(200);
      }
    };

    // --------------------------  CLEAN THE TAG LIST FROM EXTRA SPACES, DOUBLE COMMAS ETC. --------------------------
    var refurbishTags = function (tagString) {
      var splitted = tagString.split(options.tagSeparator);
      var res = "";
      var first = true;
      for (var i = 0; i < splitted.length; i++) {
        if (splitted[i].trim() != "") {
          if (first) {
            first = false;
            res = res + splitted[i].trim();
          } else {
            res = res + options.tagSeparator+ (options.tagSeparator==" "?"":" ") + splitted[i].trim();
          }
        }
      }
      return( res);
    };

    // --------------------------  TEST IF TAG IS PRESENT --------------------------
    var containsTag=function (tagString,tag){
      var splitted = tagString.split(options.tagSeparator);
      var res="";
      var found=false;
      tag=tag.trim();
      for(i = 0; i < splitted.length; i++){
        var testTag=splitted[i].trim();
        if (testTag==tag){
          found=true;
          break;
        }
      }
      return found;
    };


    // --------------------------  SELECT TAGS BASING ON USER INPUT --------------------------
    var delayedSelectTagFromInput= function(){
      var element = $(this);
      $().stopTime("suggTagRefresh");
      $().oneTime(400, "suggTagRefresh", function() {
        selectSuggTagFromInput();
      });

    };

    var selectSuggTagFromInput = function () {
      var val = theInput.val();
      suggestedTagsPlaceHolder.find(".tag").each(function(){
        var el = $(this);
        var tag=el.text();

        //check if already present
        if (containsTag(val,tag)) {
          el.addClass("tagUsed");
        } else {
          el.removeClass("tagUsed");
        }
      });

    };




    // --------------------------  INPUT BINDINGS --------------------------
    $(this).bind("focus", tagInputFocus).bind("blur", tagInputBlur).bind("keydown", tagInputKey);
    if (options.suggestedTags)
      $(this).bind("keyup",delayedSelectTagFromInput) ;


  });
  return this;
};