xref: /plugin/struct/script.js (revision fa7b96aac3c296355e7757cc16519768d467d548)
1jQuery(function () {
2    'use strict';
3    /* globals JSINFO */
4
5    /** counter for copied multi templates */
6    var copycount = 0;
7
8    /**
9     * Simplyfies AJAX requests for types
10     *
11     * @param {string} column A configured column in the form schema.name
12     * @param {function} fn Callback on success
13     * @param {object} data Additional data to pass
14     */
15    function struct_ajax(column, fn, data) {
16        if (!data) data = {};
17
18        data['call'] = 'plugin_struct';
19        data['column'] = column;
20        data['id'] = JSINFO.id;
21        data['ns'] = JSINFO.namespace;
22
23        jQuery.post(DOKU_BASE + 'lib/exe/ajax.php', data, fn, 'json')
24            .fail(function (result) {
25                if(result.responseJSON) {
26                    if (result.responseJSON.stacktrace) {
27                        console.error(result.responseJSON.error + "\n" + result.responseJSON.stacktrace);
28                    }
29                    alert(result.responseJSON.error);
30                } else {
31                    // some fatal error occured, get a text only version of the response
32                    alert(jQuery(result.responseText).text());
33                }
34            });
35    }
36
37    /**
38     * @param {string} val
39     * @return {Array}
40     */
41    function split(val) {
42        return val.split(/,\s*/);
43    }
44
45    /**
46     * @param {string} term
47     * @returns {string}
48     */
49    function extractLast(term) {
50        return split(term).pop();
51    }
52
53
54    /**
55     * Replace numbered placeholders in a string with the given arguments
56     *
57     * Example formatString('{0} is dead, but {1} is alive! {0} {2}', 'ASP', 'ASP.NET');
58     *
59     * adapted from http://stackoverflow.com/a/4673436/3293343
60     * @param format
61     * @returns {*}
62     */
63    function formatString(format) {
64        var args = Array.prototype.slice.call(arguments, 1);
65        return format.replace(/{(\d+)}/g, function(match, number) {
66            return typeof args[number] != 'undefined'
67                ? args[number]
68                : match
69            ;
70        });
71    }
72
73
74    /**
75     * hints
76     */
77    jQuery('.struct .hashint').tooltip();
78
79    /**
80     * Attach datepicker to date types
81     */
82    jQuery('input.struct_date').datepicker({
83        dateFormat: 'yy-mm-dd'
84    });
85
86    /**
87     * Attach datepicker to datetype types, keeps time part
88     */
89    jQuery('input.struct_datetime').datepicker({
90        dateFormat: 'yy-mm-dd',
91        onSelect: function(date, inst){
92            var $input = jQuery(this);
93            var both = inst.lastVal.split(' ', 2);
94            if(both.length == 2) {
95                date += ' ' + both[1];
96            } else{
97                date += ' 00:00:00';
98            }
99            $input.val(date);
100        }
101    });
102
103    /**
104     * Attach image dialog to image types
105     */
106    jQuery('button.struct_media').click(function () {
107        var input_id = jQuery(this).siblings('input').attr('id');
108        window.open(
109            DOKU_BASE + 'lib/exe/mediamanager.php' +
110            '?ns=' + encodeURIComponent(JSINFO['namespace']) +
111            '&edid=' + encodeURIComponent(input_id) +
112            '&onselect=insertStructMedia',
113            'mediaselect',
114            'width=750,height=500,left=20,top=20,scrollbars=yes,resizable=yes'); //
115    });
116
117    /**
118     * Custom onSelect handler for struct img button
119     */
120    window.insertStructMedia = function (edid, mediaid, opts, align) {
121        jQuery('#' + edid).val(mediaid).change();
122    };
123
124    /**
125     * Autocomplete for single type
126     */
127    jQuery('input.struct_autocomplete').autocomplete({
128        ismulti: false,
129        source: function (request, cb) {
130            var name = jQuery(this.element[0]).closest('label').data('column');
131            var term = request.term;
132            if (this.options.ismulti) {
133                term = extractLast(term);
134            }
135            struct_ajax(name, cb, {search: term});
136        }
137    });
138
139    /**
140     * Autocomplete for multi type
141     */
142    jQuery('.multiwrap input.struct_autocomplete').autocomplete('option', {
143        ismulti: true,
144        focus: function () {
145            // prevent value inserted on focus
146            return false;
147        },
148        select: function (event, ui) {
149            var terms = split(this.value);
150            // remove the current input
151            terms.pop();
152            // add the selected item
153            terms.push(ui.item.value);
154            // add placeholder to get the comma-and-space at the end
155            terms.push("");
156            this.value = terms.join(", ");
157            return false;
158        }
159    });
160
161    /**
162     * Handle tabs in the Schema Editor
163     */
164    jQuery('#plugin__struct_json, #plugin__struct_delete').hide();
165    jQuery('#plugin__struct_tabs').find('a').click(function (e) {
166        e.preventDefault();
167        e.stopPropagation();
168        var $me = jQuery(this);
169        if($me.parent().hasClass('active')) return; // nothing to do
170
171        $me.parent().parent().find('li').removeClass('active');
172        $me.parent().addClass('active');
173        jQuery('#plugin__struct_json, #plugin__struct_editor, #plugin__struct_delete').hide();
174        jQuery($me.attr('href')).show();
175    });
176
177
178    /**
179     * Toggle the disabled class in the schema editor
180     */
181    jQuery('#plugin__struct_editor').find('td.isenabled input').change(function () {
182        var $checkbox = jQuery(this);
183        $checkbox.parents('tr').toggleClass('disabled', !$checkbox.prop('checked'));
184    });
185
186    var $dokuform = jQuery('#dw__editform');
187
188    /**
189     * Duplicate the elements in .newtemplate whenever any input in it changes
190     */
191    $dokuform.find('.struct .newtemplate').each(function () {
192        var $tplwrapper = jQuery(this);
193        var $tpl = $tplwrapper.children().clone(true, true);
194
195        $tplwrapper.on('change', 'input,textarea,select', function () {
196            if (jQuery(this).val() == '') return;
197
198            // prepare a new template and make sure all the IDs in it are unique
199            var $copy = $tpl.clone(true, true);
200            copycount++;
201            $copy.find('*[id]').each(function () {
202                this.id = this.id + '_' + copycount;
203            });
204
205            // append the template
206            $tplwrapper.append($copy);
207        });
208    });
209
210    /**
211     * Toggle fieldsets in edit form and remeber in cookie
212     */
213    $dokuform.find('.struct fieldset legend').each(function () {
214        var $legend = jQuery(this);
215        var $fset = $legend.parent();
216
217        // reinit saved state from cookie
218        if (DokuCookie.getValue($fset.data('schema'))) {
219            $fset.toggleClass('closed');
220        }
221
222        // attach click handler
223
224        $legend.click(function () {
225            $fset.toggleClass('closed');
226            // remember setting in preference cookie
227            if ($fset.hasClass('closed')) {
228                DokuCookie.setValue($fset.data('schema'), 1);
229            } else {
230                DokuCookie.setValue($fset.data('schema'), '');
231            }
232        });
233    });
234
235    jQuery('a.deleteSchema').click(function (event) {
236        var schema = jQuery(this).closest('tr').find('td:nth-child(2)').text();
237        var page = jQuery(this).closest('tr').find('td:nth-child(1)').text();
238        if(!window.confirm(formatString(LANG.plugins.struct['confirmAssignmentsDelete'], schema, page))) {
239            event.preventDefault();
240            event.stopPropagation();
241        }
242    })
243
244});
245