forked from max-favilli/tagmanager
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tagmanager.js
501 lines (421 loc) · 15.3 KB
/
tagmanager.js
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
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
/* ===================================================
* tagmanager.js v3.0.0
* http://welldonethings.com/tags/manager
* ===================================================
* Copyright 2012 Max Favilli
*
* Licensed under the Mozilla Public License, Version 2.0 You may not use this work except in compliance with the License.
*
* http://www.mozilla.org/MPL/2.0/
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ========================================================== */
(function ($) {
"use strict";
if (typeof console === "undefined" || typeof console.log === "undefined") {
console = {};
console.log = function () { };
}
$.fn.tagsManager = function (options, tagToManipulate) {
var obj = this;
var rndid = "";
var tagManagerOptions = {
prefilled: null,
CapitalizeFirstLetter: false,
preventSubmitOnEnter: true, // deprecated
isClearInputOnEsc: true, // deprecated
AjaxPush: null,
AjaxPushAllTags: null,
AjaxPushParameters: null,
delimiters: [9, 13, 44], // tab, enter, comma
backspace: [8],
maxTags: 0,
hiddenTagListName: null, // deprecated
hiddenTagListId: null, // deprecated
replace: true,
output: null,
deleteTagsOnBackspace: true, // deprecated
tagsContainer: null,
tagCloseIcon: 'x',
tagClass: '',
validator: null,
onlyTagList: false
};
// exit when no matched elements
if (!(0 in this)) {
return this;
}
if (typeof options == 'string') {
tagManagerOptions = obj.data("tm_options");
} else {
$.extend(tagManagerOptions, options);
obj.data("tm_options", tagManagerOptions);
}
if (typeof options == 'string') {
rndid = obj.data("tm_rndid");
} else {
var albet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
for (var i = 0; i < 5; i++)
rndid += albet.charAt(Math.floor(Math.random() * albet.length));
obj.data("tm_rndid", rndid);
}
if (tagManagerOptions.replace === true && tagManagerOptions.hiddenTagListName === null) {
var original_name = obj.attr('name');
tagManagerOptions.hiddenTagListName = original_name;
obj.attr('name', "display-" + rndid);
}
if (tagManagerOptions.hiddenTagListName === null) {
tagManagerOptions.hiddenTagListName = "hidden-" + rndid;
}
var delimiters = tagManagerOptions.delimeters || tagManagerOptions.delimiters; // 'delimeter' is deprecated
// delimiter values to be handled as key codes
var keyNums = [9, 13, 17, 18, 19, 37, 38, 39, 40];
var delimiterChars = [], delimiterKeys = [];
$.each(delimiters, function (i, v) {
if ($.inArray(v, keyNums) != -1) {
delimiterKeys.push(v);
} else {
delimiterChars.push(v);
}
});
var baseDelimiter = String.fromCharCode(delimiterChars[0] || 44);
var backspace = tagManagerOptions.backspace;
var tagBaseClass = 'tm-tag';
var inputBaseClass = 'tm-input';
if ($.isFunction(tagManagerOptions.validator)) obj.data('validator', tagManagerOptions.validator);
//var ajaxPolling = function (query, process) {
// if (typeof (tagManagerOptions.typeaheadAjaxSource) == "string") {
// $.ajax({
// cache: false,
// type: "POST",
// contentType: "application/json",
// dataType: "json",
// url: tagManagerOptions.typeaheadAjaxSource,
// data: JSON.stringify({ typeahead: query }),
// success: function (data) { onTypeaheadAjaxSuccess(data, false, process); }
// });
// }
//};
var tagClasses = function () {
// 1) default class (tm-tag)
var cl = tagBaseClass;
// 2) interpolate from input class: tm-input-xxx --> tm-tag-xxx
if (obj.attr('class')) {
$.each(obj.attr('class').split(' '), function (index, value) {
if (value.indexOf(inputBaseClass + '-') != -1) {
cl += ' ' + tagBaseClass + value.substring(inputBaseClass.length);
}
});
}
// 3) tags from tagClass option
cl += (tagManagerOptions.tagClass ? ' ' + tagManagerOptions.tagClass : '');
return cl;
};
var trimTag = function (tag) {
tag = $.trim(tag);
// truncate at the first delimiter char
var i = 0;
for (i; i < tag.length; i++) {
if ($.inArray(tag.charCodeAt(i), delimiterChars) != -1) break;
}
return tag.substring(0, i);
};
var showOrHide = function () {
var tlis = obj.data("tlis");
if (tagManagerOptions.maxTags > 0 && tlis.length < tagManagerOptions.maxTags) {
obj.show();
obj.trigger('tm:show');
}
if (tagManagerOptions.maxTags > 0 && tlis.length >= tagManagerOptions.maxTags) {
obj.hide();
obj.trigger('tm:hide');
}
};
var popTag = function () {
var tlis = obj.data("tlis");
var tlid = obj.data("tlid");
if (tlid.length > 0) {
var tagId = tlid.pop();
var tagBeingRemoved = tlis[tlis.length - 1];
obj.trigger('tm:popping', tagBeingRemoved);
tlis.pop();
// console.log("TagIdToRemove: " + tagId);
$("#" + rndid + "_" + tagId).remove();
refreshHiddenTagList();
obj.trigger('tm:popped', tagBeingRemoved);
// console.log(tlis);
}
showOrHide();
//if (tagManagerOptions.maxTags > 0 && tlis.length < tagManagerOptions.maxTags) {
// obj.show();
//}
};
var empty = function () {
var tlis = obj.data("tlis");
var tlid = obj.data("tlid");
while (tlid.length > 0) {
var tagId = tlid.pop();
tlis.pop();
// console.log("TagIdToRemove: " + tagId);
$("#" + rndid + "_" + tagId).remove();
refreshHiddenTagList();
// console.log(tlis);
}
obj.trigger('tm:emptied', null);
showOrHide();
//if (tagManagerOptions.maxTags > 0 && tlis.length < tagManagerOptions.maxTags) {
// obj.show();
//}
};
var refreshHiddenTagList = function () {
var tlis = obj.data("tlis");
var lhiddenTagList = obj.data("lhiddenTagList");
if (lhiddenTagList) {
$(lhiddenTagList).val(tlis.join(baseDelimiter)).change();
}
obj.trigger('tm:refresh', tlis.join(baseDelimiter));
};
var spliceTag = function (tagId) {
var tlis = obj.data("tlis");
var tlid = obj.data("tlid");
var p = $.inArray(tagId, tlid);
// console.log("TagIdToRemove: " + tagId);
// console.log("position: " + p);
if (-1 != p) {
var tagBeingRemoved = tlis[p];
obj.trigger('tm:splicing', tagBeingRemoved);
$("#" + rndid + "_" + tagId).remove();
tlis.splice(p, 1);
tlid.splice(p, 1);
refreshHiddenTagList();
obj.trigger('tm:spliced', tagBeingRemoved);
// console.log(tlis);
}
showOrHide();
//if (tagManagerOptions.maxTags > 0 && tlis.length < tagManagerOptions.maxTags) {
// obj.show();
//}
};
var pushAllTags = function (e, tag) {
if (tagManagerOptions.AjaxPushAllTags) {
if (e.type != 'tm:pushed' || $.inArray(tag, tagManagerOptions.prefilled) == -1) {
var tlis = obj.data("tlis");
$.post(tagManagerOptions.AjaxPush, { tags: tlis.join(baseDelimiter) });
}
}
};
var pushTag = function (tag, ignore_events) {
tag = trimTag(tag);
if (!tag || tag.length <= 0) return;
if (tagManagerOptions.CapitalizeFirstLetter && tag.length > 1) {
tag = tag.charAt(0).toUpperCase() + tag.slice(1).toLowerCase();
}
// call the validator (if any) and do not let the tag pass if invalid
if (obj.data('validator') && !obj.data('validator')(tag)) return;
var tlis = obj.data("tlis");
var tlid = obj.data("tlid");
// dont accept new tags beyond the defined maximum
if (tagManagerOptions.maxTags > 0 && tlis.length >= tagManagerOptions.maxTags) return;
var alreadyInList = false;
var tlisLowerCase = tlis.map(function (elem) { return elem.toLowerCase(); });
var p = $.inArray(tag.toLowerCase(), tlisLowerCase);
if (-1 != p) {
// console.log("tag:" + tag + " !!already in list!!");
alreadyInList = true;
}
if (alreadyInList) {
var pTagId = tlid[p];
$("#" + rndid + "_" + pTagId).stop()
.animate({ backgroundColor: tagManagerOptions.blinkBGColor_1 }, 100)
.animate({ backgroundColor: tagManagerOptions.blinkBGColor_2 }, 100)
.animate({ backgroundColor: tagManagerOptions.blinkBGColor_1 }, 100)
.animate({ backgroundColor: tagManagerOptions.blinkBGColor_2 }, 100)
.animate({ backgroundColor: tagManagerOptions.blinkBGColor_1 }, 100)
.animate({ backgroundColor: tagManagerOptions.blinkBGColor_2 }, 100);
} else {
if(!ignore_events)
obj.trigger('tm:pushing', tag);
var max = Math.max.apply(null, tlid);
max = max == -Infinity ? 0 : max;
var tagId = ++max;
tlis.push(tag);
tlid.push(tagId);
if (!ignore_events)
if (tagManagerOptions.AjaxPush != null) {
if ($.inArray(tag, tagManagerOptions.prefilled) == -1) {
$.post(tagManagerOptions.AjaxPush, $.extend({ tag: tag }, tagManagerOptions.AjaxPushParameters));
}
}
// console.log("tagList: " + tlis);
var newTagId = rndid + '_' + tagId;
var newTagRemoveId = rndid + '_Remover_' + tagId;
var escaped = $("<span></span>").text(tag).html();
var html = '<span class="' + tagClasses() + '" id="' + newTagId + '">';
html += '<span>' + escaped + '</span>';
html += '<a href="#" class="tm-tag-remove" id="' + newTagRemoveId + '" TagIdToRemove="' + tagId + '">';
html += tagManagerOptions.tagCloseIcon + '</a></span> ';
var $el = $(html);
if (tagManagerOptions.tagsContainer != null) {
$(tagManagerOptions.tagsContainer).append($el);
} else {
if (tagId > 1) {
var lastTagId = tagId - 1;
var lastTagObj = $("#" + rndid + "_" + lastTagId);
lastTagObj.after($el);
} else {
obj.before($el);
}
}
$el.find("#" + newTagRemoveId).on("click", obj, function (e) {
e.preventDefault();
var TagIdToRemove = parseInt($(this).attr("TagIdToRemove"));
spliceTag(TagIdToRemove, e.data);
});
refreshHiddenTagList();
if (!ignore_events)
obj.trigger('tm:pushed', tag);
showOrHide();
//if (tagManagerOptions.maxTags > 0 && tlis.length >= tagManagerOptions.maxTags) {
// obj.hide();
//}
}
obj.val("");
};
var prefill = function (pta) {
$.each(pta, function (key, val) {
pushTag(val,true);
});
};
var killEvent = function (e) {
e.cancelBubble = true;
e.returnValue = false;
e.stopPropagation();
e.preventDefault();
};
var keyInArray = function (e, ary) {
return $.inArray(e.which, ary) != -1
};
var applyDelimiter = function (e) {
pushTag(obj.val());
e.preventDefault();
};
var returnValue = null;
this.each(function () {
if (typeof options == 'string') {
switch (options) {
case "empty":
empty();
break;
case "popTag":
popTag();
break;
case "pushTag":
pushTag(tagToManipulate);
break;
case "tags":
returnValue = { tags: obj.data("tlis") };
break;
}
return;
}
// prevent double-initialization of TagManager
if ($(this).data('tagManager')) { return false; }
$(this).data('tagManager', true);
// store instance-specific data in the DOM object
var tlis = new Array();
var tlid = new Array();
obj.data("tlis", tlis); //list of string tags
obj.data("tlid", tlid); //list of ID of the string tags
if (tagManagerOptions.output == null) {
var hiddenObj = jQuery('<input/>', {
type: 'hidden',
name: tagManagerOptions.hiddenTagListName
});
obj.after(hiddenObj);
obj.data("lhiddenTagList", hiddenObj);
} else {
obj.data("lhiddenTagList", jQuery(tagManagerOptions.output))
}
if (tagManagerOptions.AjaxPushAllTags) {
obj.on('tm:spliced', pushAllTags);
obj.on('tm:popped', pushAllTags);
obj.on('tm:pushed', pushAllTags);
}
// hide popovers on focus and keypress events
obj.on('focus keypress', function (e) {
if ($(this).popover) {
$(this).popover('hide');
}
});
// handle ESC (keyup used for browser compatibility)
if (tagManagerOptions.isClearInputOnEsc) {
obj.on('keyup', function (e) {
if (e.which == 27) {
// console.log('esc detected');
$(this).val('');
killEvent(e);
}
});
}
obj.on('keypress', function (e) {
// push ASCII-based delimiters
if (keyInArray(e, delimiterChars)) {
applyDelimiter(e);
}
});
obj.on('keydown', function (e) {
// disable ENTER
if (e.which == 13) {
if (tagManagerOptions.preventSubmitOnEnter) {
killEvent(e);
}
}
// push key-based delimiters (includes <enter> by default)
if (keyInArray(e, delimiterKeys)) {
applyDelimiter(e);
}
});
// BACKSPACE (keydown used for browser compatibility)
if (tagManagerOptions.deleteTagsOnBackspace) {
obj.on('keydown', function (e) {
if (keyInArray(e, backspace)) {
// console.log("backspace detected");
if ($(this).val().length <= 0) {
popTag();
killEvent(e);
}
}
});
}
obj.change(function (e) {
if (!/webkit/.test(navigator.userAgent.toLowerCase())) { $(this).focus(); } // why?
/* unimplemented mode to push tag on blur
else if (tagManagerOptions.pushTagOnBlur) {
console.log('change: pushTagOnBlur ' + tag);
pushTag($(this).val());
} */
killEvent(e);
});
if (tagManagerOptions.prefilled != null) {
if (typeof (tagManagerOptions.prefilled) == "object") {
prefill(tagManagerOptions.prefilled);
} else if (typeof (tagManagerOptions.prefilled) == "string") {
prefill(tagManagerOptions.prefilled.split(baseDelimiter));
} else if (typeof (tagManagerOptions.prefilled) == "function") {
prefill(tagManagerOptions.prefilled());
}
} else if (tagManagerOptions.output != null) {
if (jQuery(tagManagerOptions.output) && jQuery(tagManagerOptions.output).val())
var existing_tags = jQuery(tagManagerOptions.output)
prefill(jQuery(tagManagerOptions.output).val().split(baseDelimiter));
}
});
if (!returnValue)
returnValue = this;
return returnValue;
}
})(jQuery);