/
scaffolds.sections.js
346 lines (291 loc) · 10.1 KB
/
scaffolds.sections.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
(function($) {
$(document).ready(function() {
Symphony.Language.add({
'<code>{$file}</code> does not appear to be JSON.': false,
'An error occuring parsing the definition, ensure it is valid JSON.': false,
'Imported {$num} fields from definition.': false
});
var $scaffolds = $('#scaffolds-area'),
$fields = $('#fields-duplicator'),
$sectionEssentials = $scaffolds.next('fieldset.settings');
// Add a dummy upload field so we can use the FileReader API
// Add a dummy iframe so that when exporting the definition
// can be prompted for download
$scaffolds
.append($('<input type="file" id="file" />'))
.append($('<iframe id="iframe" />'));
var $file = $('#file').bind('change', function() {
// If no file was uploaded, abort.
if(this.files.length !== 1) return;
Scaffolds.parseFiles(this.files);
$(this).val('');
});
// Add event handlers for the Import/Export button in the Section Editor
$scaffolds.find('ul').delegate('a', 'click', function(event) {
var $self = $(this);
if($self.data('action') === 'import') {
$file.trigger('click');
}
else if($self.data('action') === 'export') {
Scaffolds.export();
}
event.preventDefault();
});
// When the 'dropdown' arrow is clicked, toggle the 'dropdown' to close
// (or open)
$scaffolds.delegate('ul + a', 'click', function(event) {
$scaffolds.find('ul').toggleClass('target');
event.preventDefault();
});
// Base extension object that does the (majority) of the logic
var Scaffolds = {
// The only accepted file at the moment is one with a .json extension
acceptedFiles: /json$/i,
// Given a FileList object, this will make sure the uploaded
// file is one Scaffolds cares about (or rather can use) and if
// so will call Scaffolds.import
parseFiles: function(files) {
var reader = new FileReader();
// Listen for the onload event of the FileReader API
// Tries to parse the file as JSON, if it's malformed, just
// return (for now)
reader.onload = function(event) {
try {
Scaffolds.import(
$.parseJSON(event.target.result)
);
}
catch(e) {
Symphony.Message.post(
Symphony.Language.get('An error occuring parsing the definition, ensure it is valid JSON.'),
'error'
);
Scaffolds.applyMessage();
Scaffolds.closeDropDown();
}
};
// If the file isn't one of our valid types, abort.
if(Scaffolds.acceptedFiles.test(files[0].name)) {
// Load the file as text, we'll convert to JSON in onload.
reader.readAsText(files[0]);
}
else {
Symphony.Message.post(
Symphony.Language.get('<code>{$file}</code> does not appear to be JSON.', {
'file': files[0].name
}),
'error'
);
Scaffolds.applyMessage();
Scaffolds.closeDropDown();
}
},
// Called with a JSON object as a parameter, this will trigger the
// Section Editor duplicator
import: function(def) {
var $controls = $fields.find('.controls'),
imported = 0,
fields_definition = {},
section_definition = {};
// New versions of Scaffolds have section and field objects.
// Old ones just output the fields.
if(def.fields !== undefined && def.section !== undefined) {
section_definition = def.section;
fields_definition = def.fields;
}
else {
fields_definition = def;
}
// Loop over section definition
for(var setting in section_definition) {
if(!section_definition.hasOwnProperty(setting)) continue;
Scaffolds.set(
$sectionEssentials.find(':input[name*=' + setting + ']').closest('label'),
setting,
section_definition[setting]
);
}
// Loop over the fields definition and trigger the duplicators
for(var label in fields_definition) {
if(!fields_definition.hasOwnProperty(label)) continue;
var definition = fields_definition[label];
// Check to make sure we aren't overriding an existing field
// definition with the same name
if(
$fields.find('li.instance input[name*=label]').filter(function() {
return $(this).val() === label;
}).length !== 1
) {
$controls.find('option[data-type = ' + definition.type + ']').attr('selected', 'selected');
$controls.find('a.constructor').trigger('click');
var $field = $fields.find('li.instance:last-of-type div.content');
$field.find('input[name*=label]').val(label);
// Loop over our 'el' and set the values
for(var k in definition) {
if(!definition.hasOwnProperty(k) || k === 'type') continue;
Scaffolds.set($field, k, definition[k]);
}
imported++;
}
}
Symphony.Message.post(
Symphony.Language.get('Imported {$num} fields from definition.', {
'num': imported
}),
'success'
);
Scaffolds.applyMessage();
Scaffolds.closeDropDown();
},
// This iterates over all the instances and generates a JSON schema
// for the user to download. The JSON filename is the Section handle.
export: function() {
var def = {
section: {},
fields: {}
};
// Export the Section metadata
$sectionEssentials.find('input:not(:hidden)').each(function() {
var $setting = $(this),
label = $setting.attr('name').replace(/(meta\[|\])/g, ''),
data = Scaffolds.get($setting);
if(data !== false) def.section[label] = data;
});
// Export the Fields
$fields.find('li.instance div.content').each(function() {
var $field = $(this),
schema = {},
// The key for def needs to the value of 'Label'
label = $field.find('input[name*=label]').val();
if(label === "") return;
// Get the type for this field instance
schema.type = $field.find('input[name*=type]:hidden').val();
// Parse the rest as usual I guess
$field.find(':input').filter(':not(:hidden)').each(function() {
var $instance = $(this),
// For each of the fields in the setting, we need to serialize
// the field information, then convert it to the JSON format
// we are expecting..
name = $instance.attr('name').match(/\[([a-z_]+)\](\[\])?$/);
// Get fields that have a name, aren't the label (we already got that)
// and have a field that actually has a value.
if(name.length >= 2 && name[1] !== 'label' && $instance.val() !== '') {
var data = Scaffolds.get($instance);
if(data !== false) schema[name[1]] = data;
}
});
def.fields[label] = schema;
});
Scaffolds.closeDropDown();
// Get the current Section Name
var section_name = $('input[name*=meta]:first').val();
// Populate the iframe with the GET request so that the definition will downloaded
$('#iframe').attr(
'src',
Symphony.WEBSITE + '/extensions/scaffolds/lib/class.spit.php?section=' + section_name + '&schema=' + encodeURIComponent(JSON.stringify(def, null, " "))
);
},
// Returns the value of a given field, approtiate for Symphony.
get: function($field) {
// Custom logic for Checkbox
if($field.is(':checkbox')) {
return $field.is(':checked') ? 'yes' : 'no';
}
// Custom logic for Select Box
else if($field.is('select')) {
var $selected = $field.find('option:selected'),
tmp = [];
for(var i = 0, l = $selected.length; i < l; i++) {
var $v = $($selected[i]);
// If `v` is a number, we'll assume that's referencing an ID
// This isn't useful to export across environments, but exporting
// the Name might be
if($v.val().search(/^[0-9]+$/) !== -1) {
var t = {
'value': $v.text()
};
if($v.closest('optgroup').length) {
t.optgroup = $v.closest('optgroup').attr('label');
}
tmp.push(t);
}
// It's fine, normal Select Box value
else {
tmp.push({'value': $v.val()});
}
}
return tmp;
}
// jQuery's val() will handle alot of the suck for us
else {
return $field.val();
}
},
// Given the field context and a key/value pair, this will set the
// approtiate values in the Field's settings.
set: function(field, key, value) {
var $field = field.find(':input[name*=' + key + ']');
if($field.length === 0) return false;
// Select
if($field.is('select')) {
if($.isArray(value)) {
for(var i = 0, l = value.length; i < l; i++) {
var v = value[i];
// Select has optgroup
if($field.find('optgroup').length) {
Scaffolds.setSelectBox(
$field.find('optgroup[label = ' + v.optgroup + ']'),
v.value
);
}
// Select doesn't have an optgroup
else {
Scaffolds.setSelectBox($field, v.value);
}
}
}
else {
Scaffolds.setSelectBox($field, value);
}
}
// Checkbox
// Symphony adds a hidden field before a checkbox, so field
// may be an area with two elements. The first element will be a
// hidden field, the second will be a checkbox.
else if(
$field.length === 2 && $field.eq(1).is(':checkbox')
) {
$field.eq(1).attr('checked', (value !== 'no'));
}
// Not all Checkbox fields have the hidden field, so handle that
// case as well
else if($field.is(':checkbox')) {
$field.attr('checked', (value !== 'no'));
}
// Input
else {
$field.val(value);
}
},
// Given an element (<select> or <optgroup>) and a value, this will search
// all the options and add the selected attribute where the option's
// text() or @value matches the given value.
setSelectBox: function(el, value) {
return el.find('option').filter(function() {
var $option = $(this);
return $option.text() === value || $option.attr('value') === value;
}).attr('selected', 'selected');
},
// Removes the toggle class. Can be done with :target selector,
// but we don't want the 'snap to element' effect, so no bingo.
closeDropDown: function() {
$scaffolds.find('ul').removeClass('target');
},
// Used to animate the Symphony Message's for consistency
applyMessage: function() {
// Dim system messages
Symphony.Message.fade('silence', 10000);
}
};
});
})(jQuery.noConflict());