initial commit
[emels.git] / emels / static / admin / js / inlines.js
1 /*global DateTimeShortcuts, SelectFilter*/
2 /**
3  * Django admin inlines
4  *
5  * Based on jQuery Formset 1.1
6  * @author Stanislaus Madueke (stan DOT madueke AT gmail DOT com)
7  * @requires jQuery 1.2.6 or later
8  *
9  * Copyright (c) 2009, Stanislaus Madueke
10  * All rights reserved.
11  *
12  * Spiced up with Code from Zain Memon's GSoC project 2009
13  * and modified for Django by Jannis Leidel, Travis Swicegood and Julien Phalip.
14  *
15  * Licensed under the New BSD License
16  * See: http://www.opensource.org/licenses/bsd-license.php
17  */
18 (function($) {
19     'use strict';
20     $.fn.formset = function(opts) {
21         var options = $.extend({}, $.fn.formset.defaults, opts);
22         var $this = $(this);
23         var $parent = $this.parent();
24         var updateElementIndex = function(el, prefix, ndx) {
25             var id_regex = new RegExp("(" + prefix + "-(\\d+|__prefix__))");
26             var replacement = prefix + "-" + ndx;
27             if ($(el).prop("for")) {
28                 $(el).prop("for", $(el).prop("for").replace(id_regex, replacement));
29             }
30             if (el.id) {
31                 el.id = el.id.replace(id_regex, replacement);
32             }
33             if (el.name) {
34                 el.name = el.name.replace(id_regex, replacement);
35             }
36         };
37         var totalForms = $("#id_" + options.prefix + "-TOTAL_FORMS").prop("autocomplete", "off");
38         var nextIndex = parseInt(totalForms.val(), 10);
39         var maxForms = $("#id_" + options.prefix + "-MAX_NUM_FORMS").prop("autocomplete", "off");
40         // only show the add button if we are allowed to add more items,
41         // note that max_num = None translates to a blank string.
42         var showAddButton = maxForms.val() === '' || (maxForms.val() - totalForms.val()) > 0;
43         $this.each(function(i) {
44             $(this).not("." + options.emptyCssClass).addClass(options.formCssClass);
45         });
46         if ($this.length && showAddButton) {
47             var addButton;
48             if ($this.prop("tagName") === "TR") {
49                 // If forms are laid out as table rows, insert the
50                 // "add" button in a new table row:
51                 var numCols = this.eq(-1).children().length;
52                 $parent.append('<tr class="' + options.addCssClass + '"><td colspan="' + numCols + '"><a href="#">' + options.addText + "</a></tr>");
53                 addButton = $parent.find("tr:last a");
54             } else {
55                 // Otherwise, insert it immediately after the last form:
56                 $this.filter(":last").after('<div class="' + options.addCssClass + '"><a href="#">' + options.addText + "</a></div>");
57                 addButton = $this.filter(":last").next().find("a");
58             }
59             addButton.click(function(e) {
60                 e.preventDefault();
61                 var template = $("#" + options.prefix + "-empty");
62                 var row = template.clone(true);
63                 row.removeClass(options.emptyCssClass)
64                 .addClass(options.formCssClass)
65                 .attr("id", options.prefix + "-" + nextIndex);
66                 if (row.is("tr")) {
67                     // If the forms are laid out in table rows, insert
68                     // the remove button into the last table cell:
69                     row.children(":last").append('<div><a class="' + options.deleteCssClass + '" href="#">' + options.deleteText + "</a></div>");
70                 } else if (row.is("ul") || row.is("ol")) {
71                     // If they're laid out as an ordered/unordered list,
72                     // insert an <li> after the last list item:
73                     row.append('<li><a class="' + options.deleteCssClass + '" href="#">' + options.deleteText + "</a></li>");
74                 } else {
75                     // Otherwise, just insert the remove button as the
76                     // last child element of the form's container:
77                     row.children(":first").append('<span><a class="' + options.deleteCssClass + '" href="#">' + options.deleteText + "</a></span>");
78                 }
79                 row.find("*").each(function() {
80                     updateElementIndex(this, options.prefix, totalForms.val());
81                 });
82                 // Insert the new form when it has been fully edited
83                 row.insertBefore($(template));
84                 // Update number of total forms
85                 $(totalForms).val(parseInt(totalForms.val(), 10) + 1);
86                 nextIndex += 1;
87                 // Hide add button in case we've hit the max, except we want to add infinitely
88                 if ((maxForms.val() !== '') && (maxForms.val() - totalForms.val()) <= 0) {
89                     addButton.parent().hide();
90                 }
91                 // The delete button of each row triggers a bunch of other things
92                 row.find("a." + options.deleteCssClass).click(function(e1) {
93                     e1.preventDefault();
94                     // Remove the parent form containing this button:
95                     row.remove();
96                     nextIndex -= 1;
97                     // If a post-delete callback was provided, call it with the deleted form:
98                     if (options.removed) {
99                         options.removed(row);
100                     }
101                     $(document).trigger('formset:removed', [row, options.prefix]);
102                     // Update the TOTAL_FORMS form count.
103                     var forms = $("." + options.formCssClass);
104                     $("#id_" + options.prefix + "-TOTAL_FORMS").val(forms.length);
105                     // Show add button again once we drop below max
106                     if ((maxForms.val() === '') || (maxForms.val() - forms.length) > 0) {
107                         addButton.parent().show();
108                     }
109                     // Also, update names and ids for all remaining form controls
110                     // so they remain in sequence:
111                     var i, formCount;
112                     var updateElementCallback = function() {
113                         updateElementIndex(this, options.prefix, i);
114                     };
115                     for (i = 0, formCount = forms.length; i < formCount; i++) {
116                         updateElementIndex($(forms).get(i), options.prefix, i);
117                         $(forms.get(i)).find("*").each(updateElementCallback);
118                     }
119                 });
120                 // If a post-add callback was supplied, call it with the added form:
121                 if (options.added) {
122                     options.added(row);
123                 }
124                 $(document).trigger('formset:added', [row, options.prefix]);
125             });
126         }
127         return this;
128     };
129
130     /* Setup plugin defaults */
131     $.fn.formset.defaults = {
132         prefix: "form",          // The form prefix for your django formset
133         addText: "add another",      // Text for the add link
134         deleteText: "remove",      // Text for the delete link
135         addCssClass: "add-row",      // CSS class applied to the add link
136         deleteCssClass: "delete-row",  // CSS class applied to the delete link
137         emptyCssClass: "empty-row",    // CSS class applied to the empty row
138         formCssClass: "dynamic-form",  // CSS class applied to each form in a formset
139         added: null,          // Function called each time a new form is added
140         removed: null          // Function called each time a form is deleted
141     };
142
143
144     // Tabular inlines ---------------------------------------------------------
145     $.fn.tabularFormset = function(options) {
146         var $rows = $(this);
147         var alternatingRows = function(row) {
148             $($rows.selector).not(".add-row").removeClass("row1 row2")
149             .filter(":even").addClass("row1").end()
150             .filter(":odd").addClass("row2");
151         };
152
153         var reinitDateTimeShortCuts = function() {
154             // Reinitialize the calendar and clock widgets by force
155             if (typeof DateTimeShortcuts !== "undefined") {
156                 $(".datetimeshortcuts").remove();
157                 DateTimeShortcuts.init();
158             }
159         };
160
161         var updateSelectFilter = function() {
162             // If any SelectFilter widgets are a part of the new form,
163             // instantiate a new SelectFilter instance for it.
164             if (typeof SelectFilter !== 'undefined') {
165                 $('.selectfilter').each(function(index, value) {
166                     var namearr = value.name.split('-');
167                     SelectFilter.init(value.id, namearr[namearr.length - 1], false);
168                 });
169                 $('.selectfilterstacked').each(function(index, value) {
170                     var namearr = value.name.split('-');
171                     SelectFilter.init(value.id, namearr[namearr.length - 1], true);
172                 });
173             }
174         };
175
176         var initPrepopulatedFields = function(row) {
177             row.find('.prepopulated_field').each(function() {
178                 var field = $(this),
179                     input = field.find('input, select, textarea'),
180                     dependency_list = input.data('dependency_list') || [],
181                     dependencies = [];
182                 $.each(dependency_list, function(i, field_name) {
183                     dependencies.push('#' + row.find('.field-' + field_name).find('input, select, textarea').attr('id'));
184                 });
185                 if (dependencies.length) {
186                     input.prepopulate(dependencies, input.attr('maxlength'));
187                 }
188             });
189         };
190
191         $rows.formset({
192             prefix: options.prefix,
193             addText: options.addText,
194             formCssClass: "dynamic-" + options.prefix,
195             deleteCssClass: "inline-deletelink",
196             deleteText: options.deleteText,
197             emptyCssClass: "empty-form",
198             removed: alternatingRows,
199             added: function(row) {
200                 initPrepopulatedFields(row);
201                 reinitDateTimeShortCuts();
202                 updateSelectFilter();
203                 alternatingRows(row);
204             }
205         });
206
207         return $rows;
208     };
209
210     // Stacked inlines ---------------------------------------------------------
211     $.fn.stackedFormset = function(options) {
212         var $rows = $(this);
213         var updateInlineLabel = function(row) {
214             $($rows.selector).find(".inline_label").each(function(i) {
215                 var count = i + 1;
216                 $(this).html($(this).html().replace(/(#\d+)/g, "#" + count));
217             });
218         };
219
220         var reinitDateTimeShortCuts = function() {
221             // Reinitialize the calendar and clock widgets by force, yuck.
222             if (typeof DateTimeShortcuts !== "undefined") {
223                 $(".datetimeshortcuts").remove();
224                 DateTimeShortcuts.init();
225             }
226         };
227
228         var updateSelectFilter = function() {
229             // If any SelectFilter widgets were added, instantiate a new instance.
230             if (typeof SelectFilter !== "undefined") {
231                 $(".selectfilter").each(function(index, value) {
232                     var namearr = value.name.split('-');
233                     SelectFilter.init(value.id, namearr[namearr.length - 1], false);
234                 });
235                 $(".selectfilterstacked").each(function(index, value) {
236                     var namearr = value.name.split('-');
237                     SelectFilter.init(value.id, namearr[namearr.length - 1], true);
238                 });
239             }
240         };
241
242         var initPrepopulatedFields = function(row) {
243             row.find('.prepopulated_field').each(function() {
244                 var field = $(this),
245                     input = field.find('input, select, textarea'),
246                     dependency_list = input.data('dependency_list') || [],
247                     dependencies = [];
248                 $.each(dependency_list, function(i, field_name) {
249                     dependencies.push('#' + row.find('.form-row .field-' + field_name).find('input, select, textarea').attr('id'));
250                 });
251                 if (dependencies.length) {
252                     input.prepopulate(dependencies, input.attr('maxlength'));
253                 }
254             });
255         };
256
257         $rows.formset({
258             prefix: options.prefix,
259             addText: options.addText,
260             formCssClass: "dynamic-" + options.prefix,
261             deleteCssClass: "inline-deletelink",
262             deleteText: options.deleteText,
263             emptyCssClass: "empty-form",
264             removed: updateInlineLabel,
265             added: function(row) {
266                 initPrepopulatedFields(row);
267                 reinitDateTimeShortCuts();
268                 updateSelectFilter();
269                 updateInlineLabel(row);
270             }
271         });
272
273         return $rows;
274     };
275
276     $(document).ready(function() {
277         $(".js-inline-admin-formset").each(function() {
278             var data = $(this).data(),
279                 inlineOptions = data.inlineFormset;
280             switch(data.inlineType) {
281             case "stacked":
282                 $(inlineOptions.name + "-group .inline-related").stackedFormset(inlineOptions.options);
283                 break;
284             case "tabular":
285                 $(inlineOptions.name + "-group .tabular.inline-related tbody tr").tabularFormset(inlineOptions.options);
286                 break;
287             }
288         });
289     });
290 })(django.jQuery);