-
-
Notifications
You must be signed in to change notification settings - Fork 3.6k
/
subform-repeatable-uncompressed.js
293 lines (250 loc) · 8.63 KB
/
subform-repeatable-uncompressed.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
/**
* @copyright Copyright (C) 2005 - 2018 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
;(function($){
"use strict";
$.subformRepeatable = function(container, options){
this.$container = $(container);
// check if alredy exist
if(this.$container.data("subformRepeatable")){
return self;
}
// Add a reverse reference to the DOM object
this.$container.data("subformRepeatable", self);
// merge options
this.options = $.extend({}, $.subformRepeatable.defaults, options);
// template for the repeating group
this.template = '';
// prepare a row template, and find available field names
this.prepareTemplate();
// check rows container
this.$containerRows = this.options.rowsContainer ? this.$container.find(this.options.rowsContainer) : this.$container;
// last row number, help to avoid the name duplications
this.lastRowNum = this.$containerRows.find(this.options.repeatableElement).length;
// To avoid scope issues,
var self = this;
// bind add button
this.$container.on('click', this.options.btAdd, function (e) {
e.preventDefault();
var after = $(this).parents(self.options.repeatableElement);
if(!after.length){
after = null;
}
self.addRow(after);
});
// bind remove button
this.$container.on('click', this.options.btRemove, function (e) {
e.preventDefault();
var $row = $(this).parents(self.options.repeatableElement);
self.removeRow($row);
});
// bind move button
if(this.options.btMove){
this.$containerRows.sortable({
items: this.options.repeatableElement,
handle: this.options.btMove,
tolerance: 'pointer'
});
}
// tell all that we a ready
this.$container.trigger('subform-ready');
};
// prepare a template that we will use repeating
$.subformRepeatable.prototype.prepareTemplate = function(){
// create from template
if(this.options.rowTemplateSelector){
var tmplElement = this.$container.find(this.options.rowTemplateSelector)[0] || {};
this.template = $.trim(tmplElement.text || tmplElement.textContent); //(text || textContent) is IE8 fix
}
// create from existing rows
else {
//find first available
var row = this.$container.find(this.options.repeatableElement).get(0),
$row = $(row).clone();
// clear scripts that can be attached to the fields
try {
this.clearScripts($row);
} catch (e) {
if(window.console){
console.log(e);
}
}
this.template = $row.prop('outerHTML');
}
};
// add new row
$.subformRepeatable.prototype.addRow = function(after){
// count how much we already have
var count = this.$containerRows.find(this.options.repeatableElement).length;
if(count >= this.options.maximum){
return null;
}
// make new from template
var row = $.parseHTML(this.template);
//add to container
if(after){
$(after).after(row);
} else {
this.$containerRows.append(row);
}
var $row = $(row);
//add marker that it is new
$row.attr('data-new', 'true');
// fix names and id`s, and reset values
this.fixUniqueAttributes($row, count);
// try find out with related scripts,
// tricky thing, so be careful
try {
this.fixScripts($row);
} catch (e) {
if(window.console){
console.log(e);
}
}
// tell everyone about the new row
this.$container.trigger('subform-row-add', $row);
return $row;
};
// remove row
$.subformRepeatable.prototype.removeRow = function($row){
// count how much we have
var count = this.$containerRows.find(this.options.repeatableElement).length;
if(count <= this.options.minimum){
return;
}
// tell everyoune about the row will be removed
this.$container.trigger('subform-row-remove', $row);
$row.remove();
};
// fix names ind id`s for field that in $row
$.subformRepeatable.prototype.fixUniqueAttributes = function($row, count){
this.lastRowNum++;
var group = $row.attr('data-group'),// current group name
basename = $row.attr('data-base-name'), // group base name, without count
count = count || 0,
countnew = Math.max(this.lastRowNum, count + 1),
groupnew = basename + countnew; // new group name
this.lastRowNum = countnew;
$row.attr('data-group', groupnew);
// Fix inputs that have a "name" attribute
var haveName = $row.find('[name]'),
ids = {}; // Collect id for fix checkboxes and radio
for (var i = 0, l = haveName.length; i < l; i++) {
var $el = $(haveName[i]),
name = $el.attr('name'),
id = name.replace(/(\[\]$)/g, '').replace(/(\]\[)/g, '__').replace(/\[/g, '_').replace(/\]/g, ''), // id from name
nameNew = name.replace('[' + group + '][', '['+ groupnew +']['), // New name
idNew = id.replace(group, groupnew), // Count new id
countMulti = 0, // count for multiple radio/checkboxes
forOldAttr = id; // Fix "for" in the labels
if ($el.prop('type') === 'checkbox' && name.match(/\[\]$/)) { // <input type="checkbox" name="name[]"> fix
// Recount id
countMulti = ids[id] ? ids[id].length : 0;
if (!countMulti) {
// Set the id for fieldset and group label
$el.closest('fieldset.checkboxes').attr('id', idNew);
$row.find('label[for="' + id + '"]').attr('for', idNew).attr('id', idNew + '-lbl');
}
forOldAttr = forOldAttr + countMulti;
idNew = idNew + countMulti;
}
else if ($el.prop('type') === 'radio') { // <input type="radio"> fix
// Recount id
countMulti = ids[id] ? ids[id].length : 0;
if (!countMulti) {
// Set the id for fieldset and group label
$el.closest('fieldset.radio').attr('id', idNew);
$row.find('label[for="' + id + '"]').attr('for', idNew).attr('id', idNew + '-lbl');
}
forOldAttr = forOldAttr + countMulti;
idNew = idNew + countMulti;
}
// Cache already used id
if (ids[id]) {
ids[id].push(true);
} else {
ids[id] = [true];
}
// Replace the name to new one
$el.attr('name', nameNew);
// Set new id
$el.attr('id', idNew);
// Guess there a label for this input
$row.find('label[for="' + forOldAttr + '"]').attr('for', idNew).attr('id', idNew + '-lbl');
}
};
// remove scripts attached to fields
// @TODO: make thing better when something like that will be accepted https://github.com/joomla/joomla-cms/pull/6357
$.subformRepeatable.prototype.clearScripts = function($row){
// destroy chosen if any
if($.fn.chosen){
$row.find('select.chzn-done').each(function(){
var $el = $(this);
$el.next('.chzn-container').remove();
$el.show().addClass('fix-chosen');
});
}
};
// method for hack the scripts that can be related
// to the one of field that in given $row
$.subformRepeatable.prototype.fixScripts = function($row){
// fix media field
$row.find('a[onclick*="jInsertFieldValue"]').each(function(){
var $el = $(this),
inputId = $el.siblings('input[type="text"]').attr('id'),
$select = $el.prev(),
oldHref = $select.attr('href');
// update the clear button
$el.attr('onclick', "jInsertFieldValue('', '" + inputId + "');return false;")
// update select button
$select.attr('href', oldHref.replace(/&fieldid=(.+)&/, '&fieldid=' + inputId + '&'));
});
// bootstrap based Media field
if($.fn.fieldMedia){
$row.find('.field-media-wrapper').fieldMedia();
}
// bootstrap based User field
if($.fn.fieldUser){
$row.find('.field-user-wrapper').fieldUser();
}
// another modals
if(window.SqueezeBox && window.SqueezeBox.assign){
SqueezeBox.assign($row.find('a.modal').get(), {parse: 'rel'});
}
};
// defaults
$.subformRepeatable.defaults = {
btAdd: ".group-add", // button selector for "add" action
btRemove: ".group-remove",// button selector for "remove" action
btMove: ".group-move",// button selector for "move" action
minimum: 0, // minimum repeating
maximum: 10, // maximum repeating
repeatableElement: ".subform-repeatable-group",
rowTemplateSelector: 'script.subform-repeatable-template-section', // selector for the row template <script>
rowsContainer: null // container for rows, same as main container by default
};
$.fn.subformRepeatable = function(options){
return this.each(function(){
var options = options || {},
data = $(this).data();
if(data.subformRepeatable){
// Alredy initialized, nothing to do here
return;
}
for (var p in data) {
// check options in the element
if (data.hasOwnProperty(p)) {
options[p] = data[p];
}
}
var inst = new $.subformRepeatable(this, options);
$(this).data('subformRepeatable', inst);
});
};
// initialise all available
// wait when all will be loaded, important for scripts fix
$(window).on('load', function(){
$('div.subform-repeatable').subformRepeatable();
})
})(jQuery);