/
symphony.tags.js
111 lines (90 loc) · 2.57 KB
/
symphony.tags.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
/**
* @package assets
*/
(function($, Symphony) {
/**
* Insert tags from a list into an input field based on three modes:
* singular - allowing only one tag at a time (add a class of .singular)
* multiple - allowing multiple tags, comma separated
* inline - which adds tags at the current cursor position (add a class of .inline)
*
* @name $.symphonyTags
* @class
*
* @param {Object} custom_settings An object specifying containing the attributes specified below
* @param {String} [custom_settings.items='li'] Selector to find collapsible items within the container
*
* @example
$('.tags').symphonyTags();
*/
$.fn.symphonyTags = function(options) {
var objects = this,
settings = {
items: 'li'
};
$.extend(settings, options);
/*-------------------------------------------------------------------------
Events
-------------------------------------------------------------------------*/
objects.on('click.tags', settings.items, function tagging(event) {
var item = $(this),
object = item.parent(),
input = object.prev().find('input, textarea'),
value = input.val(),
tag = item.attr('class') || item.data('value') || item.text();
// Singular
if(object.is('.singular')) {
input.val(tag);
}
// Inline
else if(object.is('.inline')) {
var start = input[0].selectionStart,
end = input[0].selectionEnd,
position = 0;
// Insert tag
if(start > 0) {
input.val(value.substring(0, start) + tag + value.substring(end, value.length));
position = start + tag.length;
}
// Append tag
else {
input.val(value + tag);
position = value.length + tag.length;
}
// Reset cursor position
input[0].selectionStart = position;
input[0].selectionEnd = position;
}
// Multiple
else {
var exp = new RegExp('^' + tag.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&") + '$', 'i'),
tags = value.split(/,\s*/),
removed = false;
// Check existing tags
for(var index in tags) {
// Remove existing tag
if(tags[index] == tag) {
tags.splice(index, 1);
removed = true;
}
// Remove empty tags
else if(tags[index] == '') {
tags.splice(index, 1);
}
}
// Add new tag
if(removed === false) {
tags.push(tag);
}
// Save tags
input.val(tags.join(', '));
}
// Include the tag that was just triggered.
input.trigger('change', {
'tag': item
});
});
/*-----------------------------------------------------------------------*/
return objects;
};
})(window.jQuery, window.Symphony);