-
Notifications
You must be signed in to change notification settings - Fork 0
/
cmb2.js
1163 lines (949 loc) · 35.1 KB
/
cmb2.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
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Controls the behaviours of custom metabox fields.
*
* @author CMB2 team
* @see https://github.com/CMB2/CMB2
*/
/**
* Custom jQuery for Custom Metaboxes and Fields
*/
window.CMB2 = window.CMB2 || {};
(function(window, document, $, cmb, undefined){
'use strict';
// localization strings
var l10n = window.cmb2_l10;
var setTimeout = window.setTimeout;
var $document;
var $id = function( selector ) {
return $( document.getElementById( selector ) );
};
var defaults = {
idNumber : false,
repeatEls : 'input:not([type="button"],[id^=filelist]),select,textarea,.cmb2-media-status',
noEmpty : 'input:not([type="button"]):not([type="radio"]):not([type="checkbox"]),textarea',
repeatUpdate : 'input:not([type="button"]),select,textarea,label',
styleBreakPoint : 450,
mediaHandlers : {},
defaults : {
time_picker : l10n.defaults.time_picker,
date_picker : l10n.defaults.date_picker,
color_picker : l10n.defaults.color_picker || {},
code_editor : l10n.defaults.code_editor,
},
media : {
frames : {},
},
};
cmb.metabox = function() {
if ( cmb.$metabox ) {
return cmb.$metabox;
}
cmb.$metabox = $('.cmb2-wrap > .cmb2-metabox');
return cmb.$metabox;
};
cmb.init = function() {
$document = $( document );
// Setup the CMB2 object defaults.
$.extend( cmb, defaults );
cmb.trigger( 'cmb_pre_init' );
var $metabox = cmb.metabox();
var $repeatGroup = $metabox.find('.cmb-repeatable-group');
// Init time/date/color pickers
cmb.initPickers( $metabox.find('input[type="text"].cmb2-timepicker'), $metabox.find('input[type="text"].cmb2-datepicker'), $metabox.find('input[type="text"].cmb2-colorpicker') );
// Init code editors.
cmb.initCodeEditors( $metabox.find( '.cmb2-textarea-code:not(.disable-codemirror)' ) );
// Insert toggle button into DOM wherever there is multicheck. credit: Genesis Framework
$( '<p><span class="button-secondary cmb-multicheck-toggle">' + l10n.strings.check_toggle + '</span></p>' ).insertBefore( '.cmb2-checkbox-list:not(.no-select-all)' );
// Make File List drag/drop sortable:
cmb.makeListSortable();
$metabox
.on( 'change', '.cmb2_upload_file', function() {
cmb.media.field = $( this ).attr( 'id' );
$id( cmb.media.field + '_id' ).val('');
})
// Media/file management
.on( 'click', '.cmb-multicheck-toggle', cmb.toggleCheckBoxes )
.on( 'click', '.cmb2-upload-button', cmb.handleMedia )
.on( 'click', '.cmb-attach-list li, .cmb2-media-status .img-status img, .cmb2-media-status .file-status > span', cmb.handleFileClick )
.on( 'click', '.cmb2-remove-file-button', cmb.handleRemoveMedia )
// Repeatable content
.on( 'click', '.cmb-add-group-row', cmb.addGroupRow )
.on( 'click', '.cmb-add-row-button', cmb.addAjaxRow )
.on( 'click', '.cmb-remove-group-row', cmb.removeGroupRow )
.on( 'click', '.cmb-remove-row-button', cmb.removeAjaxRow )
// Ajax oEmbed display
.on( 'keyup paste focusout', '.cmb2-oembed', cmb.maybeOembed )
// Reset titles when removing a row
.on( 'cmb2_remove_row', '.cmb-repeatable-group', cmb.resetTitlesAndIterator )
.on( 'click', '.cmbhandle, .cmbhandle + .cmbhandle-title', cmb.toggleHandle );
if ( $repeatGroup.length ) {
$repeatGroup
.on( 'cmb2_add_row', cmb.emptyValue )
.on( 'cmb2_add_row', cmb.setDefaults )
.filter('.sortable').each( function() {
// Add sorting arrows
$( this ).find( '.cmb-remove-group-row-button' ).before( '<a class="button-secondary cmb-shift-rows move-up alignleft" href="#"><span class="'+ l10n.up_arrow_class +'"></span></a> <a class="button-secondary cmb-shift-rows move-down alignleft" href="#"><span class="'+ l10n.down_arrow_class +'"></span></a>' );
})
.on( 'click', '.cmb-shift-rows', cmb.shiftRows );
}
// on pageload
setTimeout( cmb.resizeoEmbeds, 500);
// and on window resize
$( window ).on( 'resize', cmb.resizeoEmbeds );
if ( $id( 'addtag' ).length ) {
cmb.listenTagAdd();
}
cmb.trigger( 'cmb_init' );
};
cmb.listenTagAdd = function() {
$document.ajaxSuccess( function( evt, xhr, settings ) {
if ( settings.data && settings.data.length && -1 !== settings.data.indexOf( 'action=add-tag' ) ) {
cmb.resetBoxes( $id( 'addtag' ).find( '.cmb2-wrap > .cmb2-metabox' ) );
}
});
};
cmb.resetBoxes = function( $boxes ) {
$.each( $boxes, function() {
cmb.resetBox( $( this ) );
});
};
cmb.resetBox = function( $box ) {
$box.find( '.wp-picker-clear' ).trigger( 'click' );
$box.find( '.cmb2-remove-file-button' ).trigger( 'click' );
$box.find( '.cmb-row.cmb-repeatable-grouping:not(:first-of-type) .cmb-remove-group-row' ).click();
$box.find( '.cmb-repeat-row:not(:first-child)' ).remove();
$box.find( 'input:not([type="button"]),select,textarea' ).each( function() {
var $element = $( this );
var tagName = $element.prop('tagName');
if ( 'INPUT' === tagName ) {
var elType = $element.attr( 'type' );
if ( 'checkbox' === elType || 'radio' === elType ) {
$element.prop( 'checked', false );
} else {
$element.val( '' );
}
}
if ( 'SELECT' === tagName ) {
$( 'option:selected', this ).prop( 'selected', false );
}
if ( 'TEXTAREA' === tagName ) {
$element.html( '' );
}
});
};
cmb.resetTitlesAndIterator = function( evt ) {
if ( ! evt.group ) {
return;
}
// Loop repeatable group tables
$( '.cmb-repeatable-group.repeatable' ).each( function() {
var $table = $( this );
var groupTitle = $table.find( '.cmb-add-group-row' ).data( 'grouptitle' );
// Loop repeatable group table rows
$table.find( '.cmb-repeatable-grouping' ).each( function( rowindex ) {
var $row = $( this );
var $rowTitle = $row.find( 'h3.cmb-group-title' );
// Reset rows iterator
$row.data( 'iterator', rowindex );
// Reset rows title
if ( $rowTitle.length ) {
$rowTitle.text( groupTitle.replace( '{#}', ( rowindex + 1 ) ) );
}
});
});
};
cmb.toggleHandle = function( evt ) {
evt.preventDefault();
cmb.trigger( 'postbox-toggled', $( this ).parent('.postbox').toggleClass('closed') );
};
cmb.toggleCheckBoxes = function( evt ) {
evt.preventDefault();
var $this = $( this );
var $multicheck = $this.closest( '.cmb-td' ).find( 'input[type=checkbox]:not([disabled])' );
// If the button has already been clicked once...
if ( $this.data( 'checked' ) ) {
// clear the checkboxes and remove the flag
$multicheck.prop( 'checked', false );
$this.data( 'checked', false );
}
// Otherwise mark the checkboxes and add a flag
else {
$multicheck.prop( 'checked', true );
$this.data( 'checked', true );
}
};
cmb.handleMedia = function( evt ) {
evt.preventDefault();
var $el = $( this );
cmb.attach_id = ! $el.hasClass( 'cmb2-upload-list' ) ? $el.closest( '.cmb-td' ).find( '.cmb2-upload-file-id' ).val() : false;
// Clean up default 0 value
cmb.attach_id = '0' !== cmb.attach_id ? cmb.attach_id : false;
cmb._handleMedia( $el.prev('input.cmb2-upload-file').attr('id'), $el.hasClass( 'cmb2-upload-list' ) );
};
cmb.handleFileClick = function( evt ) {
if ( $( evt.target ).is( 'a' ) ) {
return;
}
evt.preventDefault();
var $el = $( this );
var $td = $el.closest( '.cmb-td' );
var isList = $td.find( '.cmb2-upload-button' ).hasClass( 'cmb2-upload-list' );
cmb.attach_id = isList ? $el.find( 'input[type="hidden"]' ).data( 'id' ) : $td.find( '.cmb2-upload-file-id' ).val();
if ( cmb.attach_id ) {
cmb._handleMedia( $td.find( 'input.cmb2-upload-file' ).attr( 'id' ), isList, cmb.attach_id );
}
};
cmb._handleMedia = function( id, isList ) {
if ( ! wp ) {
return;
}
var media, handlers;
handlers = cmb.mediaHandlers;
media = cmb.media;
media.field = id;
media.$field = $id( media.field );
media.fieldData = media.$field.data();
media.previewSize = media.fieldData.previewsize;
media.sizeName = media.fieldData.sizename;
media.fieldName = media.$field.attr('name');
media.isList = isList;
// If this field's media frame already exists, reopen it.
if ( id in media.frames ) {
return media.frames[ id ].open();
}
// Create the media frame.
media.frames[ id ] = wp.media( {
title: cmb.metabox().find('label[for="' + id + '"]').text(),
library : media.fieldData.queryargs || {},
button: {
text: l10n.strings[ isList ? 'upload_files' : 'upload_file' ]
},
multiple: isList ? 'add' : false
} );
// Enable the additional media filters: https://github.com/CMB2/CMB2/issues/873
media.frames[ id ].states.first().set( 'filterable', 'all' );
cmb.trigger( 'cmb_media_modal_init', media );
handlers.list = function( selection, returnIt ) {
// Setup our fileGroup array
var fileGroup = [];
var attachmentHtml;
if ( ! handlers.list.templates ) {
handlers.list.templates = {
image : wp.template( 'cmb2-list-image' ),
file : wp.template( 'cmb2-list-file' ),
};
}
// Loop through each attachment
selection.each( function( attachment ) {
// Image preview or standard generic output if it's not an image.
attachmentHtml = handlers.getAttachmentHtml( attachment, 'list' );
// Add our file to our fileGroup array
fileGroup.push( attachmentHtml );
});
if ( ! returnIt ) {
// Append each item from our fileGroup array to .cmb2-media-status
media.$field.siblings( '.cmb2-media-status' ).append( fileGroup );
} else {
return fileGroup;
}
};
handlers.single = function( selection ) {
if ( ! handlers.single.templates ) {
handlers.single.templates = {
image : wp.template( 'cmb2-single-image' ),
file : wp.template( 'cmb2-single-file' ),
};
}
// Only get one file from the uploader
var attachment = selection.first();
media.$field.val( attachment.get( 'url' ) );
$id( media.field +'_id' ).val( attachment.get( 'id' ) );
// Image preview or standard generic output if it's not an image.
var attachmentHtml = handlers.getAttachmentHtml( attachment, 'single' );
// add/display our output
media.$field.siblings( '.cmb2-media-status' ).slideDown().html( attachmentHtml );
};
handlers.getAttachmentHtml = function( attachment, templatesId ) {
var isImage = 'image' === attachment.get( 'type' );
var data = handlers.prepareData( attachment, isImage );
// Image preview or standard generic output if it's not an image.
return handlers[ templatesId ].templates[ isImage ? 'image' : 'file' ]( data );
};
handlers.prepareData = function( data, image ) {
if ( image ) {
// Set the correct image size data
handlers.getImageData.call( data, 50 );
}
data = data.toJSON();
data.mediaField = media.field;
data.mediaFieldName = media.fieldName;
data.stringRemoveImage = l10n.strings.remove_image;
data.stringFile = l10n.strings.file;
data.stringDownload = l10n.strings.download;
data.stringRemoveFile = l10n.strings.remove_file;
return data;
};
handlers.getImageData = function( fallbackSize ) {
// Preview size dimensions
var previewW = media.previewSize[0] || fallbackSize;
var previewH = media.previewSize[1] || fallbackSize;
// Image dimensions and url
var url = this.get( 'url' );
var width = this.get( 'width' );
var height = this.get( 'height' );
var sizes = this.get( 'sizes' );
// Get the correct dimensions and url if a named size is set and exists
// fallback to the 'large' size
if ( sizes ) {
if ( sizes[ media.sizeName ] ) {
url = sizes[ media.sizeName ].url;
width = sizes[ media.sizeName ].width;
height = sizes[ media.sizeName ].height;
} else if ( sizes.large ) {
url = sizes.large.url;
width = sizes.large.width;
height = sizes.large.height;
}
}
// Fit the image in to the preview size, keeping the correct aspect ratio
if ( width > previewW ) {
height = Math.floor( previewW * height / width );
width = previewW;
}
if ( height > previewH ) {
width = Math.floor( previewH * width / height );
height = previewH;
}
if ( ! width ) {
width = previewW;
}
if ( ! height ) {
height = 'svg' === this.get( 'filename' ).split( '.' ).pop() ? '100%' : previewH;
}
this.set( 'sizeUrl', url );
this.set( 'sizeWidth', width );
this.set( 'sizeHeight', height );
return this;
};
handlers.selectFile = function() {
var selection = media.frames[ id ].state().get( 'selection' );
var type = isList ? 'list' : 'single';
if ( cmb.attach_id && isList ) {
$( '[data-id="'+ cmb.attach_id +'"]' ).parents( 'li' ).replaceWith( handlers.list( selection, true ) );
} else {
handlers[type]( selection );
}
cmb.trigger( 'cmb_media_modal_select', selection, media );
};
handlers.openModal = function() {
var selection = media.frames[ id ].state().get( 'selection' );
var attach;
if ( ! cmb.attach_id ) {
selection.reset();
} else {
attach = wp.media.attachment( cmb.attach_id );
attach.fetch();
selection.set( attach ? [ attach ] : [] );
}
cmb.trigger( 'cmb_media_modal_open', selection, media );
};
// When a file is selected, run a callback.
media.frames[ id ]
.on( 'select', handlers.selectFile )
.on( 'open', handlers.openModal );
// Finally, open the modal
media.frames[ id ].open();
};
cmb.handleRemoveMedia = function( evt ) {
evt.preventDefault();
var $this = $( this );
if ( $this.is( '.cmb-attach-list .cmb2-remove-file-button' ) ) {
$this.parents( '.cmb2-media-item' ).remove();
return false;
}
cmb.media.field = $this.attr('rel');
cmb.metabox().find( document.getElementById( cmb.media.field ) ).val('');
cmb.metabox().find( document.getElementById( cmb.media.field + '_id' ) ).val('');
$this.parents('.cmb2-media-status').html('');
return false;
};
cmb.cleanRow = function( $row, prevNum, group ) {
var $elements = $row.find( cmb.repeatUpdate );
if ( group ) {
var $other = $row.find( '[id]' ).not( cmb.repeatUpdate );
// Remove extra ajaxed rows
$row.find('.cmb-repeat-table .cmb-repeat-row:not(:first-child)').remove();
// Update all elements w/ an ID
if ( $other.length ) {
$other.each( function() {
var $_this = $( this );
var oldID = $_this.attr( 'id' );
var newID = oldID.replace( '_'+ prevNum, '_'+ cmb.idNumber );
var $buttons = $row.find('[data-selector="'+ oldID +'"]');
$_this.attr( 'id', newID );
// Replace data-selector vars
if ( $buttons.length ) {
$buttons.attr( 'data-selector', newID ).data( 'selector', newID );
}
});
}
}
$elements.filter( ':checked' ).removeAttr( 'checked' );
$elements.find( ':checked' ).removeAttr( 'checked' );
$elements.filter( ':selected' ).removeAttr( 'selected' );
$elements.find( ':selected' ).removeAttr( 'selected', false );
if ( $row.find('h3.cmb-group-title').length ) {
$row.find( 'h3.cmb-group-title' ).text( $row.data( 'title' ).replace( '{#}', ( cmb.idNumber + 1 ) ) );
}
$elements.each( function() {
cmb.elReplacements( $( this ), prevNum, group );
} );
return cmb;
};
cmb.elReplacements = function( $newInput, prevNum, group ) {
var oldFor = $newInput.attr( 'for' );
var oldVal = $newInput.val();
var type = $newInput.prop( 'type' );
var defVal = cmb.getFieldArg( $newInput, 'default' );
var newVal = 'undefined' !== typeof defVal ? defVal : '';
var tagName = $newInput.prop('tagName');
var checkable = 'radio' === type || 'checkbox' === type ? oldVal : false;
var attrs = {};
var newID, oldID;
if ( oldFor ) {
attrs = { 'for' : oldFor.replace( '_'+ prevNum, '_'+ cmb.idNumber ) };
} else {
var oldName = $newInput.attr( 'name' );
var newName;
oldID = $newInput.attr( 'id' );
// Handle adding groups vs rows.
if ( group ) {
// Expect another bracket after group's index closing bracket.
newName = oldName ? oldName.replace( '['+ prevNum +'][', '['+ cmb.idNumber +'][' ) : '';
// Expect another underscore after group's index trailing underscore.
newID = oldID ? oldID.replace( '_' + prevNum + '_', '_' + cmb.idNumber + '_' ) : '';
}
else {
// Row indexes are at the very end of the string.
newName = oldName ? cmb.replaceLast( oldName, '[' + prevNum + ']', '[' + cmb.idNumber + ']' ) : '';
newID = oldID ? cmb.replaceLast( oldID, '_' + prevNum, '_' + cmb.idNumber ) : '';
}
attrs = {
id: newID,
name: newName
};
}
// Clear out textarea values
if ( 'TEXTAREA' === tagName ) {
$newInput.html( newVal );
}
if ( 'SELECT' === tagName && undefined !== typeof defVal ) {
var $toSelect = $newInput.find( '[value="'+ defVal + '"]' );
if ( $toSelect.length ) {
$toSelect.attr( 'selected', 'selected' ).prop( 'selected', 'selected' );
}
}
if ( checkable ) {
$newInput.removeAttr( 'checked' );
if ( undefined !== typeof defVal && oldVal === defVal ) {
$newInput.attr( 'checked', 'checked' ).prop( 'checked', 'checked' );
}
}
if ( ! group && $newInput[0].hasAttribute( 'data-iterator' ) ) {
attrs['data-iterator'] = cmb.idNumber;
}
$newInput
.removeClass( 'hasDatepicker' )
.val( checkable ? checkable : newVal ).attr( attrs );
return $newInput;
};
cmb.newRowHousekeeping = function( $row ) {
var $colorPicker = $row.find( '.wp-picker-container' );
var $list = $row.find( '.cmb2-media-status' );
if ( $colorPicker.length ) {
// Need to clean-up colorpicker before appending
$colorPicker.each( function() {
var $td = $( this ).parent();
$td.html( $td.find( 'input[type="text"].cmb2-colorpicker' ).attr('style', '') );
});
}
// Need to clean-up colorpicker before appending
if ( $list.length ) {
$list.empty();
}
return cmb;
};
cmb.afterRowInsert = function( $row ) {
// Init pickers from new row
cmb.initPickers( $row.find('input[type="text"].cmb2-timepicker'), $row.find('input[type="text"].cmb2-datepicker'), $row.find('input[type="text"].cmb2-colorpicker') );
};
cmb.updateNameAttr = function () {
var $this = $( this );
var name = $this.attr( 'name' ); // get current name
// If name is defined
if ( typeof name !== 'undefined' ) {
var prevNum = parseInt( $this.parents( '.cmb-repeatable-grouping' ).data( 'iterator' ), 10 );
var newNum = prevNum - 1; // Subtract 1 to get new iterator number
// Update field name attributes so data is not orphaned when a row is removed and post is saved
var $newName = name.replace( '[' + prevNum + ']', '[' + newNum + ']' );
// New name with replaced iterator
$this.attr( 'name', $newName );
}
};
cmb.emptyValue = function( evt, row ) {
$( cmb.noEmpty, row ).val( '' );
};
cmb.setDefaults = function( evt, row ) {
$( cmb.noEmpty, row ).each( function() {
var $el = $(this);
var defVal = cmb.getFieldArg( $el, 'default' );
if ( false !== defVal ) {
$el.val( defVal );
}
});
};
cmb.addGroupRow = function( evt ) {
evt.preventDefault();
var $this = $( this );
// before anything significant happens
cmb.triggerElement( $this, 'cmb2_add_group_row_start', $this );
var $table = $id( $this.data('selector') );
var $oldRow = $table.find('.cmb-repeatable-grouping').last();
var prevNum = parseInt( $oldRow.data('iterator'), 10 );
cmb.idNumber = parseInt( prevNum, 10 ) + 1;
var $row = $oldRow.clone();
// Make sure the next number doesn't exist.
while ( $table.find( '.cmb-repeatable-grouping[data-iterator="'+ cmb.idNumber +'"]' ).length > 0 ) {
cmb.idNumber++;
}
cmb.newRowHousekeeping( $row.data( 'title', $this.data( 'grouptitle' ) ) ).cleanRow( $row, prevNum, true );
$row.find( '.cmb-add-row-button' ).prop( 'disabled', false );
var $newRow = $( '<div class="postbox cmb-row cmb-repeatable-grouping" data-iterator="'+ cmb.idNumber +'">'+ $row.html() +'</div>' );
$oldRow.after( $newRow );
cmb.afterRowInsert( $newRow );
cmb.triggerElement( $table, { type: 'cmb2_add_row', group: true }, $newRow );
};
cmb.addAjaxRow = function( evt ) {
evt.preventDefault();
var $this = $( this );
var $table = $id( $this.data('selector') );
var $emptyrow = $table.find('.empty-row');
var prevNum = parseInt( $emptyrow.find('[data-iterator]').data('iterator'), 10 );
cmb.idNumber = parseInt( prevNum, 10 ) + 1;
var $row = $emptyrow.clone();
cmb.newRowHousekeeping( $row ).cleanRow( $row, prevNum );
$emptyrow.removeClass('empty-row hidden').addClass('cmb-repeat-row');
$emptyrow.after( $row );
cmb.afterRowInsert( $row );
cmb.triggerElement( $table, { type: 'cmb2_add_row', group: false }, $row );
};
cmb.removeGroupRow = function( evt ) {
evt.preventDefault();
var $this = $( this );
var $table = $id( $this.data('selector') );
var $parent = $this.parents('.cmb-repeatable-grouping');
var number = $table.find('.cmb-repeatable-grouping').length;
if ( number < 2 ) {
return cmb.resetRow( $parent.parents('.cmb-repeatable-group').find( '.cmb-add-group-row' ), $this );
}
cmb.triggerElement( $table, 'cmb2_remove_group_row_start', $this );
// when a group is removed loop through all next groups and update fields names
$parent.nextAll( '.cmb-repeatable-grouping' ).find( cmb.repeatEls ).each( cmb.updateNameAttr );
$parent.remove();
cmb.triggerElement( $table, { type: 'cmb2_remove_row', group: true } );
};
cmb.removeAjaxRow = function( evt ) {
evt.preventDefault();
var $this = $( this );
// Check if disabled
if ( $this.hasClass( 'button-disabled' ) ) {
return;
}
var $parent = $this.parents('.cmb-row');
var $table = $this.parents('.cmb-repeat-table');
var number = $table.find('.cmb-row').length;
if ( number <= 2 ) {
return cmb.resetRow( $parent.find( '.cmb-add-row-button' ), $this );
}
if ( $parent.hasClass('empty-row') ) {
$parent.prev().addClass( 'empty-row' ).removeClass('cmb-repeat-row');
}
$this.parents('.cmb-repeat-table .cmb-row').remove();
cmb.triggerElement( $table, { type: 'cmb2_remove_row', group: false } );
};
cmb.resetRow = function( $addNewBtn, $removeBtn ) {
// Click the "add new" button followed by the "remove this" button
// in order to reset the repeat row to empty values.
$addNewBtn.trigger( 'click' );
$removeBtn.trigger( 'click' );
};
cmb.shiftRows = function( evt ) {
evt.preventDefault();
var $this = $( this );
var $from = $this.parents( '.cmb-repeatable-grouping' );
var $goto = $this.hasClass( 'move-up' ) ? $from.prev( '.cmb-repeatable-grouping' ) : $from.next( '.cmb-repeatable-grouping' );
// Before shift occurs.
cmb.triggerElement( $this, 'cmb2_shift_rows_enter', $this, $from, $goto );
if ( ! $goto.length ) {
return;
}
// About to shift
cmb.triggerElement( $this, 'cmb2_shift_rows_start', $this, $from, $goto );
var inputVals = [];
// Loop this item's fields
$from.find( cmb.repeatEls ).each( function() {
var $element = $( this );
var elType = $element.attr( 'type' );
var val;
if ( $element.hasClass('cmb2-media-status') ) {
// special case for image previews
val = $element.html();
} else if ( 'checkbox' === elType || 'radio' === elType ) {
val = $element.is(':checked');
} else if ( 'select' === $element.prop('tagName') ) {
val = $element.is(':selected');
} else {
val = $element.val();
}
// Get all the current values per element
inputVals.push( { val: val, $: $element } );
});
// And swap them all
$goto.find( cmb.repeatEls ).each( function( index ) {
var $element = $( this );
var elType = $element.attr( 'type' );
var val;
if ( $element.hasClass('cmb2-media-status') ) {
var toRowId = $element.closest('.cmb-repeatable-grouping').attr('data-iterator');
var fromRowId = inputVals[ index ].$.closest('.cmb-repeatable-grouping').attr('data-iterator');
// special case for image previews
val = $element.html();
$element.html( inputVals[ index ].val );
inputVals[ index ].$.html( val );
inputVals[ index ].$.find( 'input' ).each(function() {
var name = $( this ).attr( 'name' );
name = name.replace( '['+toRowId+']', '['+fromRowId+']' );
$( this ).attr( 'name', name );
});
$element.find('input').each(function() {
var name = $( this ).attr('name');
name = name.replace('['+fromRowId+']', '['+toRowId+']');
$( this ).attr('name', name);
});
}
// handle checkbox swapping
else if ( 'checkbox' === elType ) {
inputVals[ index ].$.prop( 'checked', $element.is(':checked') );
$element.prop( 'checked', inputVals[ index ].val );
}
// handle radio swapping
else if ( 'radio' === elType ) {
if ( $element.is( ':checked' ) ) {
inputVals[ index ].$.attr( 'data-checked', 'true' );
}
if ( inputVals[ index ].$.is( ':checked' ) ) {
$element.attr( 'data-checked', 'true' );
}
}
// handle select swapping
else if ( 'select' === $element.prop('tagName') ) {
inputVals[ index ].$.prop( 'selected', $element.is(':selected') );
$element.prop( 'selected', inputVals[ index ].val );
}
// handle normal input swapping
else {
inputVals[ index ].$.val( $element.val() );
$element.val( inputVals[ index ].val );
}
});
$from.find( 'input[data-checked=true]' ).prop( 'checked', true ).removeAttr( 'data-checked' );
$goto.find( 'input[data-checked=true]' ).prop( 'checked', true ).removeAttr( 'data-checked' );
// trigger color picker change event
$from.find( 'input[type="text"].cmb2-colorpicker' ).trigger( 'change' );
$goto.find( 'input[type="text"].cmb2-colorpicker' ).trigger( 'change' );
// shift done
cmb.triggerElement( $this, 'cmb2_shift_rows_complete', $this, $from, $goto );
};
cmb.initPickers = function( $timePickers, $datePickers, $colorPickers ) {
// Initialize jQuery UI timepickers
cmb.initDateTimePickers( $timePickers, 'timepicker', 'time_picker' );
// Initialize jQuery UI datepickers
cmb.initDateTimePickers( $datePickers, 'datepicker', 'date_picker' );
// Initialize color picker
cmb.initColorPickers( $colorPickers );
};
cmb.initDateTimePickers = function( $selector, method, defaultKey ) {
if ( $selector.length ) {
$selector[ method ]( 'destroy' ).each( function() {
var $this = $( this );
var fieldOpts = $this.data( method ) || {};
var options = $.extend( {}, cmb.defaults[ defaultKey ], fieldOpts );
$this[ method ]( cmb.datePickerSetupOpts( fieldOpts, options, method ) );
} );
}
};
cmb.datePickerSetupOpts = function( fieldOpts, options, method ) {
var existing = $.extend( {}, options );
options.beforeShow = function( input, inst ) {
if ( 'timepicker' === method ) {
cmb.addTimePickerClasses( inst.dpDiv );
}
// Wrap datepicker w/ class to narrow the scope of jQuery UI CSS and prevent conflicts
$id( 'ui-datepicker-div' ).addClass( 'cmb2-element' );
// Let's be sure to call beforeShow if it was added
if ( 'function' === typeof existing.beforeShow ) {
existing.beforeShow( input, inst );
}
};
if ( 'timepicker' === method ) {
options.onChangeMonthYear = function( year, month, inst, picker ) {
cmb.addTimePickerClasses( inst.dpDiv );
// Let's be sure to call onChangeMonthYear if it was added
if ( 'function' === typeof existing.onChangeMonthYear ) {
existing.onChangeMonthYear( year, month, inst, picker );
}
};
}
options.onClose = function( dateText, inst ) {
// Remove the class when we're done with it (and hide to remove FOUC).
var $picker = $id( 'ui-datepicker-div' ).removeClass( 'cmb2-element' ).hide();
if ( 'timepicker' === method && ! $( inst.input ).val() ) {
// Set the timepicker field value if it's empty.
inst.input.val( $picker.find( '.ui_tpicker_time' ).text() );
}
// Let's be sure to call onClose if it was added
if ( 'function' === typeof existing.onClose ) {
existing.onClose( dateText, inst );
}
};
return options;
};
// Adds classes to timepicker buttons.
cmb.addTimePickerClasses = function( $picker ) {
var func = cmb.addTimePickerClasses;
func.count = func.count || 0;
// Wait a bit to let the timepicker render, since these are pre-render events.
setTimeout( function() {
if ( $picker.find( '.ui-priority-secondary' ).length ) {
$picker.find( '.ui-priority-secondary' ).addClass( 'button-secondary' );
$picker.find( '.ui-priority-primary' ).addClass( 'button-primary' );
func.count = 0;
} else if ( func.count < 5 ) {
func.count++;
func( $picker );
}
}, 10 );
};
cmb.initColorPickers = function( $selector ) {
if ( ! $selector.length ) {
return;
}
if ( typeof jQuery.wp === 'object' && typeof jQuery.wp.wpColorPicker === 'function' ) {
$selector.each( function() {
var $this = $( this );
var fieldOpts = $this.data( 'colorpicker' ) || {};
$this.wpColorPicker( $.extend( {}, cmb.defaults.color_picker, fieldOpts ) );
} );
} else {
$selector.each( function( i ) {
$( this ).after( '<div id="picker-' + i + '" style="z-index: 1000; background: #EEE; border: 1px solid #CCC; position: absolute; display: block;"></div>' );
$id( 'picker-' + i ).hide().farbtastic( $( this ) );
} )
.focus( function() {
$( this ).next().show();
} )
.blur( function() {
$( this ).next().hide();
} );
}
};
cmb.initCodeEditors = function( $selector ) {
if ( ! cmb.defaults.code_editor || ! wp || ! wp.codeEditor || ! $selector.length ) {
return;
}
$selector.each( function() {
wp.codeEditor.initialize(
this.id,
cmb.codeEditorArgs( $( this ).data( 'codeeditor' ) )
);
} );
};
cmb.codeEditorArgs = function( overrides ) {
var props = [ 'codemirror', 'csslint', 'jshint', 'htmlhint' ];
var args = $.extend( {}, cmb.defaults.code_editor );
overrides = overrides || {};
for ( var i = props.length - 1; i >= 0; i-- ) {
if ( overrides.hasOwnProperty( props[i] ) ) {
args[ props[i] ] = $.extend( {}, args[ props[i] ] || {}, overrides[ props[i] ] );
}
}
return args;
};
cmb.makeListSortable = function() {
var $filelist = cmb.metabox().find( '.cmb2-media-status.cmb-attach-list' );
if ( $filelist.length ) {
$filelist.sortable({ cursor: 'move' }).disableSelection();
}
};
cmb.maybeOembed = function( evt ) {
var $this = $( this );
var m = {
focusout : function() {
setTimeout( function() {
// if it's been 2 seconds, hide our spinner
cmb.spinner( '.cmb2-metabox', true );
}, 2000);
},
keyup : function() {
var betw = function( min, max ) {
return ( evt.which <= max && evt.which >= min );
};
// Only Ajax on normal keystrokes
if ( betw( 48, 90 ) || betw( 96, 111 ) || betw( 8, 9 ) || evt.which === 187 || evt.which === 190 ) {
// fire our ajax function
cmb.doAjax( $this, evt );
}
},
paste : function() {
// paste event is fired before the value is filled, so wait a bit
setTimeout( function() { cmb.doAjax( $this ); }, 100);
}