-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathmeta-box.js
2010 lines (1717 loc) · 64.9 KB
/
meta-box.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
/**
* @package PublishPress
* @author PublishPress
*
* Copyright (C) 2018 PublishPress
*
* ------------------------------------------------------------------------------
* Based on Edit Flow
* Author: Daniel Bachhuber, Scott Bressler, Mohammad Jangda, Automattic, and
* others
* Copyright (c) 2009-2016 Mohammad Jangda, Daniel Bachhuber, et al.
* ------------------------------------------------------------------------------
*
* This file is part of PublishPress
*
* PublishPress is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* PublishPress is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with PublishPress. If not, see <http://www.gnu.org/licenses/>.
*/
(function ($, window, document, counter) {
'use strict';
/**
* This variable is deprecated. Use ppChecklists instead.
* Added here just for backward compatibility with other
* plugins.
*
* @deprecated 1.4.0
*/
window.objectL10n_checklist_requirements = ppChecklists;
/*---------- Handler ----------*/
/**
* Object for handling the requirements in the post form.
* @type {Object}
*/
var PP_Checklists = {
/**
* Constant for the event validate_requirements
* @type {String}
*/
EVENT_VALIDATE_REQUIREMENTS: 'pp-checklists:validate_requirements',
/**
* Constant for the event tick. Triggered by a setInterval
* @type {String}
*/
EVENT_TIC: 'pp-checklists:tic',
/**
* Constant for the event update_requirement_state
* @type {String}
*/
EVENT_UPDATE_REQUIREMENT_STATE: 'pp-checklists:update_requirement_state',
/**
* Constant for the event toggle_custom_item
* @type {String}
*/
EVENT_TOGGLE_CUSTOM_ITEM: 'pp-checklists:toggle_custom_item',
/**
* Constant for the event tinymce_loaded
* @type {String}
*/
EVENT_TINYMCE_LOADED: 'pp-checklists:tinymce_loaded',
/**
* Constant for the interval of the tic event
* @type {Number}
*/
TIC_INTERVAL: 300,
/**
* List of interface elements
* @type {Object}
*/
elems: {
original_post_status: $('#original_post_status'),
post_status: $('#post_status'),
publish_button: $('#publish'),
document: $(document),
},
/**
* Stores the states for the object.
* @type {Object}
*/
state: {
/**
* Flag for the publishing state
* @type {boolean}
*/
is_publishing: false,
/**
* Flag for the confirmed state
* @type {boolean}
*/
is_confirmed: false,
/**
* Flag for the should_block state
* @type {boolean}
*/
should_block: false,
/**
* Flag to say the validate method is already being executed.
* @type {boolean}
*/
is_validating: false,
},
/**
* Initialize the object and events
* @return {void}
*/
init: function () {
// Create a custom event
this.elems.document.on(
this.EVENT_VALIDATE_REQUIREMENTS,
function (event) {
this.validate_requirements(event);
}.bind(this),
);
// On clicking the submit button
this.elems.publish_button.click(
function () {
this.state.is_publishing = true;
}.bind(this),
);
// On clicking the confirmation button in the modal window
this.elems.document.on(
'confirmation',
'.remodal',
function () {
this.state.is_confirmed = true;
// Trigger the publish button
this.elems.publish_button.trigger('click');
// For some reason, adding this again after the click is trigged solved the acf conflict issue https://github.com/publishpress/PublishPress-Checklists/issues/506
this.state.is_confirmed = true;
}.bind(this),
);
if (!this.is_gutenberg_active()) {
// Hook to the submit button
$('form#post').submit(
function (event) {
//do not trigger for preview action
if ($('input#wp-preview').val() === 'dopreview') {
return true;
}
// Reset the should_block state
this.state.should_block = false;
this.elems.document.trigger(this.EVENT_VALIDATE_REQUIREMENTS);
return !this.state.should_block;
}.bind(this),
);
} else {
$(document).on(
this.EVENT_TIC,
function (event) {
if (this.state.is_validating !== false) {
return;
}
var isSidebarOpened = wp.data.select('core/edit-post').isPublishSidebarOpened();
if (isSidebarOpened) {
this.elems.document.trigger(this.EVENT_VALIDATE_REQUIREMENTS);
} else {
// We need this as validate requirement is not been triggered for publish post. I'll leave the condition for now till i study this very well.
this.elems.document.trigger(this.EVENT_VALIDATE_REQUIREMENTS);
}
}.bind(this),
);
}
// Hook to the requirement items
$('[id^=pp-checklists-req]').on(
this.EVENT_UPDATE_REQUIREMENT_STATE,
function (event, state) {
this.update_requirement_icon(state, $(event.target));
}.bind(this),
);
// Add event to the custom items
$('.pp-checklists-custom-item').click(
function (event) {
var target = event.target;
if ('LI' !== target.nodeNAME) {
target = $(target).parent('li')[0];
}
if (typeof target !== 'undefined') {
this.elems.document.trigger(this.EVENT_TOGGLE_CUSTOM_ITEM, $(target));
}
}.bind(this),
);
// Add event to the button custom items
this.elems.document.on(
'click',
'.pp-checklists-req .pp-checklists-check-item',
function (event) {
event.preventDefault();
var target = $(event.target);
var target_li = target.closest('li');
var global_this = this;
$('.pp-checklists-req').find('.request-response').html('');
if (typeof target_li !== 'undefined') {
target_li.find('.pp-checklists-check-item').prop('disabled', true);
target_li.find('.spinner').addClass('is-active');
var data = {
action: 'pp_checklists_' + target_li.attr('data-source') + '_requirement',
requirement: ppChecklists.requirements[target_li.attr('data-id')],
content: PP_Checklists.get_editor_content(),
nonce: ppChecklists.nonce,
};
$.post(ajaxurl, data, function (response) {
var response_raw_content = response.content;
var response_content = response_raw_content.replace(/\n/g, '<br>');
if (response.yes_no == 'yes') {
$('#pp-checklists-req-' + target_li.attr('data-id'))
.find('.dashicons')
.removeClass('dashicons-yes');
global_this.elems.document.trigger(
global_this.EVENT_TOGGLE_CUSTOM_ITEM,
$('#pp-checklists-req-' + target_li.attr('data-id')),
);
} else if (response.yes_no == 'no') {
$('#pp-checklists-req-' + target_li.attr('data-id'))
.find('.dashicons')
.addClass('dashicons-yes');
global_this.elems.document.trigger(
global_this.EVENT_TOGGLE_CUSTOM_ITEM,
$('#pp-checklists-req-' + target_li.attr('data-id')),
);
}
target_li
.find('.request-response')
.html(
'<div id="message" class="ppch-message notice is-dismissible updated published"><p>' +
response_content +
'</p><button type="button" class="notice-dismiss" onclick="this.closest(\'#message\').remove();"><span class="screen-reader-text">Dismiss this notice.</span></button></div>',
);
target_li.find('.pp-checklists-check-item').prop('disabled', false);
target_li.find('.spinner').removeClass('is-active');
}).fail(function (jqXHR, textStatus, errorThrown) {
target_li
.find('.request-response')
.html(
'<div id="message" class="ppch-message notice is-dismissible updated published"><p>' +
errorThrown +
' ' +
textStatus +
'</p><button type="button" class="notice-dismiss" onclick="this.closest(\'#message\').remove();"><span class="screen-reader-text">Dismiss this notice.</span></button></div>',
);
target_li.find('.pp-checklists-check-item').prop('disabled', false);
target_li.find('.spinner').removeClass('is-active');
});
}
}.bind(this),
);
// On clicking the confirmation button in the modal window
this.elems.document.on(
this.EVENT_TOGGLE_CUSTOM_ITEM,
function (event, item) {
var $item = $(item),
$icon = $item.children('.dashicons'),
checked = $icon.hasClass('dashicons-yes');
$icon.removeClass('dashicons-no');
if (checked) {
$icon.removeClass('dashicons-yes');
$item.removeClass('status-yes');
$item.addClass('status-no');
$item.find('.ppch_item_requirement').val('no');
wp.hooks.doAction('pp-checklists.requirements-updated', $item);
} else {
$icon.addClass('dashicons-yes');
$item.addClass('status-yes');
$item.removeClass('status-no');
$item.find('.ppch_item_requirement').val('yes');
wp.hooks.doAction('pp-checklists.requirements-updated', $item);
}
$item.children('input[type="hidden"]').val($item.hasClass('status-yes') ? 'yes' : 'no');
}.bind(this),
);
// Start the tic event
setInterval(
function () {
$(document).trigger(this.EVENT_TIC);
}.bind(this),
this.TIC_INTERVAL,
);
},
/**
* Check if the current post is already published
* @return {Boolean} True if published.
*/
is_published: function () {
return 'publish' === this.elems.original_post_status.val();
},
/**
* Check if the current post status is pending
* @return {Boolean} True if pending.
*/
is_pending: function () {
return 'pending' === this.elems.original_post_status.val();
},
/**
* Check if the current post status is draft
* @return {Boolean} True if draft.
*/
is_draft: function () {
return (
'draft' === this.elems.original_post_status.val() || 'auto-draft' === this.elems.original_post_status.val()
);
},
/**
* Validates the requirements and show the warning, blocking or not the
* submission, according to the config. Returns false if the submission
* should be blocked.
*
* @param {[type]} event
* @return {Boolean}
*/
validate_requirements: function (event) {
this.state.is_validating = true;
this.state.should_block = false;
// Bypass all checks because the confirmation button was clicked.
if (this.state.is_confirmed) {
this.state.is_confirmed = false;
this.state.is_validating = false;
return;
}
var uncheckedItems = {
block: [],
warning: [],
};
/**
* Check the element of the requirement, to see if it is marked
* as incomplete.
*
* @param {Object} $req The DOM element
* @param {Array} list The list to inject the requirement, if incomplete
* @return {void}
*/
var checkRequirement = function ($reqElem, list) {
if ($reqElem.hasClass('status-no')) {
// Check if the requirement is not ok
var $uncheckedRequirements = $reqElem.find('.status-label');
if ($uncheckedRequirements.length > 0) {
list.push($uncheckedRequirements.html().trim());
}
}
}.bind(this);
var checkRequirementAction = function (actionType) {
var $elems = $('.pp-checklists-req.metabox-req.pp-checklists-' + actionType);
for (var i = 0; i < $elems.length; i++) {
checkRequirement($($elems[i]), uncheckedItems[actionType]);
}
}.bind(this);
// Check if any of the requirements is set to trigger warnings
checkRequirementAction('warning');
checkRequirementAction('block');
if (this.is_gutenberg_active()) {
this.state.is_publishing = wp.data.select('core/edit-post').isPublishSidebarOpened();
}
var originalPostStatus = this.elems.original_post_status.val(),
isPublishingThePost = this.state.is_publishing,
isUpdatingPublishedPost = this.getCurrentPostStatus() === 'publish' && originalPostStatus === 'publish';
if (isPublishingThePost || isUpdatingPublishedPost) {
var showBlockMessage = uncheckedItems.block.length > 0,
showWarning = uncheckedItems.warning.length > 0,
gutenbergLockName = 'pp-checklists';
if (showWarning || showBlockMessage) {
this.state.should_block = true;
var message = '';
if (showBlockMessage) {
if (PP_Checklists.is_gutenberg_active()) {
wp.data.dispatch('core/editor').lockPostSaving(gutenbergLockName);
wp.hooks.doAction('pp-checklists.update-failed-requirements', uncheckedItems);
} else {
if (isUpdatingPublishedPost) {
message = ppChecklists.msg_missed_required_updating;
} else {
message = ppChecklists.msg_missed_required_publishing;
}
message +=
'<div class="pp-checklists-modal-list"><ul><li>' +
uncheckedItems.block.join('</li><li>') +
'</li></ul></div>';
if (uncheckedItems.warning.length > 0) {
if (isUpdatingPublishedPost) {
message += ppChecklists.msg_missed_important_updating;
} else {
message += ppChecklists.msg_missed_important_publishing;
}
message +=
'<div class="pp-checklists-modal-list"><ul><li>' +
uncheckedItems.warning.join('</li><li>') +
'</li></ul></div>';
}
// Display the alert
$('#pp-checklists-modal-alert-content').html(message);
$('[data-remodal-id=pp-checklists-modal-alert]').remodal().open();
}
} else if (showWarning) {
if (PP_Checklists.is_gutenberg_active()) {
wp.data.dispatch('core/editor').unlockPostSaving(gutenbergLockName);
wp.hooks.doAction('pp-checklists.update-failed-requirements', uncheckedItems);
} else {
// Only display a warning
if (isUpdatingPublishedPost) {
message = ppChecklists.msg_missed_optional_updating;
} else {
message = ppChecklists.msg_missed_optional_publishing;
}
message +=
'<div class="pp-checklists-modal-list"><ul><li>' +
uncheckedItems.warning.join('</li><li>') +
'</li></ul></div>';
if (uncheckedItems.block.length > 0) {
message +=
ppChecklists.msg_missed_required +
'<div class="pp-checklists-modal-list"><ul><li>' +
uncheckedItems.block.join('</li><li>') +
'</li></ul></div>';
}
// Display the confirm
$('#pp-checklists-modal-confirm-content').html(message);
$('[data-remodal-id=pp-checklists-modal-confirm]').remodal().open();
}
}
} else {
if (PP_Checklists.is_gutenberg_active()) {
wp.data.dispatch('core/editor').unlockPostSaving(gutenbergLockName);
wp.hooks.doAction('pp-checklists.update-failed-requirements', uncheckedItems);
}
this.state.is_publishing = false;
this.state.is_validating = false;
return;
}
} else {
// we only need the failed counts to be triggered for panel validation
wp.hooks.doAction('pp-checklists.update-failed-requirements', uncheckedItems);
}
this.state.is_publishing = false;
this.state.is_validating = false;
},
getCurrentPostStatus: function () {
if (PP_Checklists.is_gutenberg_active()) {
return wp.data.select('core/editor').getEditedPostAttribute('status');
} else {
return this.elems.post_status.val();
}
},
/**
* Updates the icon in the requirement checklist according to the
* current state.
*
* @param {Boolean} is_completed
* @param {Object} $element
* @return {void}
*/
update_requirement_icon: function (is_completed, $element) {
var $icon_element = $element.find('.dashicons');
if (is_completed) {
// Ok
$icon_element.removeClass('dashicons-no');
$icon_element.addClass('dashicons-yes');
$icon_element.parent().removeClass('status-no');
$icon_element.parent().addClass('status-yes');
$element.find('.ppch_item_requirement').val('yes');
wp.hooks.doAction('pp-checklists.requirements-updated', $element);
} else {
// Not ok
$icon_element.removeClass('dashicons-yes');
$icon_element.addClass('dashicons-no');
$icon_element.parent().removeClass('status-yes');
$icon_element.parent().addClass('status-no');
$element.find('.ppch_item_requirement').val('no');
wp.hooks.doAction('pp-checklists.requirements-updated', $element);
}
},
/**
* Check if the value is valid, based on the min and max values.
* It makes a smarty check based on the following:
*
* - Both same value = exact
* - Min not empty, max empty or < min = only min
* - Min not empty, max not empty and > min = both min and max
* - Min empty, max not empty and > min = only max
*
* @param {Float} count
* @param {Float} min_value
* @param {Float} max_value
*
* @return {Bool}
*/
check_valid_quantity: function (count, min_value, max_value) {
var is_valid = false;
// Both same value = exact
if (min_value === max_value) {
is_valid = count === min_value;
}
// Min not empty, max empty or < min = only min
if (min_value > 0 && max_value < min_value) {
is_valid = count >= min_value;
}
// Min not empty, max not empty and > min = both min and max
if (min_value > 0 && max_value > min_value) {
is_valid = count >= min_value && count <= max_value;
}
// Min empty, max not empty and > min = only max
if (min_value === 0 && max_value > min_value) {
is_valid = count <= max_value;
}
return is_valid;
},
/**
* Check for internal link from content and return result as array
*
* - remove image inside tags so we don't count them as link
* - remove element inside <a href></a> to avoid double counting for one link in case of <a href="Link">Link</a>
* - check for every valid link and return array
* - loop array and return only valid internal links excluding other images url
*
* @param {String} content
* @param {Array} links
* @param {String} website
*
* @return {Array}
*/
extract_internal_links: function (content, links = [], website = window.location.host) {
var link;
if (content) {
//remove image inside tags so we don't count them as link
content = content.replace(/<img[^>]*>/g, '');
//remove element inside <a href></a> to avoid double counting for one link in case of <a href="Link">Link</a>
content = content.replace(/<a .*? *href="([^\'\"]+).*?<\/a>/g, '$1');
//check for every valid link and return array
content = content.match(/(https?:\/\/(?:www\.|(?!www))[^\s\.]+\.[^\s]{2,}|www\.[^\s]+\.[^\s]{2,})/gi);
//loop array and return only valid internal links excluding other images url
if (content) {
for (link of content) {
//skip if link is image
if (link.match(/\.(jpeg|jpg|gif|png|svg)$/)) continue;
//skip if link has different host than current website
if (link.indexOf(website) < 0) continue;
//add valid link to array
links.push(link);
}
}
}
return links;
},
/**
* Check for external link from content and return result as array
*
* - remove image inside tags so we don't count them as link
* - remove element inside <a href></a> to avoid double counting for one link in case of <a href="Link">Link</a>
* - check for every valid link and return array
* - loop array and return only valid external links excluding other images url
*
* @param {String} content
* @param {Array} links
* @param {String} website
*
* @return {Array}
*/
extract_external_links: function (content, links = [], website = window.location.host) {
var link,
match,
regex = /<a.*?href=["\']([^"\']+)["\'].*?\>(.*?)\<\/a\>/gi;
if (content) {
//check for external link and return array excluding other images url
while ((match = regex.exec(content)) !== null) {
link = match[1];
//skip if link is image
if (link.match(/\.(jpeg|jpg|gif|png|svg)$/)) continue;
//skip if link point to the current website host
if (link.indexOf(website) > 0) continue;
//add valid link to array
links.push(link);
}
}
return links;
},
/**
* Check for images without alt text from content and return result as array
*
* @param {String} content
* @param {Array} missing_alt
*
* @return {Array}
*/
missing_alt_images: function (content, missing_alt = []) {
var alt,
regex = /<img[^>]*>/g;
if (content) {
var imgTags = content.match(regex) || [];
imgTags.forEach(function (imgTag) {
alt = imgTag.match(/alt="([^"]*)"/);
if (!alt || !alt[1].replace(/\s/g, '').length) {
missing_alt.push(imgTag);
}
});
}
return missing_alt;
},
get_image_alt_lengths: function (content) {
var lengths = [];
var regex = /<img[^>]+alt=(['"])(.*?)\1[^>]*>/gi;
var match;
while ((match = regex.exec(content)) !== null) {
lengths.push(match[2].trim().length);
}
return lengths;
},
extract_links_from_content: function (content) {
let linksIterator = content.matchAll(/(?:<a[^>]+href=['"])([^'"]+)(?:['"][^>]*>)/gi);
let linkResult = linksIterator.next();
let linksList = [];
while (!linkResult.done) {
linksList.push(linkResult.value[1]);
linkResult = linksIterator.next();
}
return linksList;
},
is_valid_link: function (link) {
if (link.startsWith('#')) {
return true;
}
const linkWithoutFragment = link.split('#')[0];
return linkWithoutFragment.match(
/^(?:(#[-a-zA-Z0-9@:%._\+~#=]{0,256})|https?:\/\/(?:www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b(?:[-a-zA-Z0-9()@;:%_\+.~#?&\/\/=!*'(),]*)|tel:\+?[0-9\-]+|mailto:[a-z0-9\-_\.]+@[a-z0-9\-_\.]+?[a-z0-9@\.\?=\s\%,\-&_;*]+)$/i,
);
},
/**
* Check for links without http(s)
*
* @param {String} content
* @param {Array} invalid_links
*
* @return {Array}
*/
validate_links_format: function (content, invalid_links = []) {
if (!content) {
return [];
}
// Extract links from the href attribute.
let linksList = PP_Checklists.extract_links_from_content(content);
for (let i = 0; i < linksList.length; i++) {
if (!PP_Checklists.is_valid_link(linksList[i])) {
invalid_links.push(linksList[i]);
}
}
return invalid_links;
},
/**
* Returns true if the Gutenberg editor is active on the page.
*
* @returns {boolean}
*/
is_gutenberg_active: function () {
let gutenbergActive = false;
if (
typeof wp.data !== 'undefined' &&
typeof wp.data.select('core') !== 'undefined' &&
typeof wp.data.select('core/edit-post') !== 'undefined' &&
typeof wp.data.select('core/editor') !== 'undefined'
) {
gutenbergActive = true;
}
return gutenbergActive;
},
/**
* Returns editor content.
*
* @returns {boolean}
*/
get_editor_content: function () {
let data = '';
try {
// Gutenberg
data = PP_Checklists.getEditor().getEditedPostAttribute('content');
} catch (error) {
try {
// TinyMCE
let ed = tinyMCE.activeEditor;
if ('mce_fullscreen' == ed.id) {
tinyMCE.get('content').setContent(
ed.getContent({
format: 'raw',
}),
{
format: 'raw',
},
);
}
tinyMCE.get('content').save();
data = jQuery('#content').val();
} catch (error) {
try {
// Quick Tags
data = jQuery('#content').val();
} catch (error) {}
}
}
// Trim data
data = data.replace(/^\s+/, '').replace(/\s+$/, '');
return data;
},
/**
* Add a style tag.
*
* @param id
* @param css
*/
add_style_tag: function (id, css) {
var $head = $('head');
if ($head.find('#' + id).length === 0) {
var $style = $('<style>');
$style.attr('type', 'text/css');
$style.text(css);
$style.attr('id', id);
$head.append($style);
}
},
/**
*
* @param id
*/
remove_style_tag: function (id) {
$('#' + id).remove();
},
/**
* Return the editor
*
* @returns {object}
*/
getEditor: function () {
return wp.data.select('core/editor');
},
/**
* This function checks whether a post has a featured image or not.
*
* - For Gutenberg, it checks the featured_media attribute of the post.
* - For the Classic Editor, it checks the set-post-thumbnail element.
* @returns {boolean}
*/
hasFeaturedImage: function () {
var has_image = false;
if (PP_Checklists.is_gutenberg_active()) {
has_image = PP_Checklists.getEditor().getEditedPostAttribute('featured_media') > 0;
} else {
has_image = $('#postimagediv').find('#set-post-thumbnail').find('img').length > 0;
}
return has_image;
},
};
// Exposes and initialize the object
window.PP_Checklists = PP_Checklists;
if (typeof rankMath !== 'undefined' && typeof YoastSEO !== 'undefined') {
setTimeout(function () {
PP_Checklists.init();
}, 4000);
} else if (typeof rankMath !== 'undefined') {
setTimeout(function () {
PP_Checklists.init();
}, 3000);
} else if (typeof YoastSEO !== 'undefined') {
setTimeout(function () {
PP_Checklists.init();
}, 3000);
} else {
PP_Checklists.init();
}
/*---------- Warning icon in submit button ----------*/
if (ppChecklists.show_warning_icon_submit) {
$(document).on(PP_Checklists.EVENT_TIC, function (event) {
var has_unchecked = $('#pp-checklists-req-box').children('.status-no');
if (has_unchecked.length > 0) {
$('body').addClass('ppch-show-publishing-warning-icon');
} else {
$('body').removeClass('ppch-show-publishing-warning-icon');
}
});
}
/*---------- Disable publish button ----------*/
// Disable first save button until requirements are meet when "Include pre-publish checklist" is disabled
// @TODO Figure out how to get the status of "Include pre-publish checklist" and add it to the if() below
if (ppChecklists.disable_publish_button) {
$(window).on('load', function () {
if (
PP_Checklists.is_gutenberg_active() &&
((PP_Checklists.is_published() !== true && PP_Checklists.is_pending() !== true) ||
!ppChecklists.disable_published_block_feature)
) {
$(document).on(PP_Checklists.EVENT_TIC, function (event) {
var has_unchecked_block = $('#pp-checklists-req-box').children('.status-no.pp-checklists-block');
if (has_unchecked_block.length > 0) {
wp.data.dispatch('core/editor').lockPostSaving('ppcPublishButton');
} else {
wp.data.dispatch('core/editor').unlockPostSaving('ppcPublishButton');
}
});
}
});
}
/*---------- Featured Image ----------*/
if ($('#pp-checklists-req-featured_image').length > 0) {
$(document).on(PP_Checklists.EVENT_TIC, function (event) {
var has_image = PP_Checklists.hasFeaturedImage();
$('#pp-checklists-req-featured_image').trigger(PP_Checklists.EVENT_UPDATE_REQUIREMENT_STATE, has_image);
});
}
/*---------- Featured Image Alt ----------*/
// Check if the featured image is set or not
if ($('#pp-checklists-req-featured_image_alt').length > 0) {
let loaded = false,
meta_id = 0,
meta_alt = '';
let featured_image_alt = {};
const updateFeaturedImageAlt = (id, alt) => {
meta_id = Number(id);
meta_alt = alt;
featured_image_alt = { [meta_id]: meta_alt };
loaded = true;
};
if (PP_Checklists.is_gutenberg_active()) {
wp.data.subscribe(function () {
if (loaded) return;
const mediaId = PP_Checklists.getEditor().getEditedPostAttribute('featured_media');
if (mediaId) {
const dataMedia = wp.data.select('core').getMedia(mediaId);
if (typeof dataMedia === 'object' && dataMedia) {
updateFeaturedImageAlt(mediaId, dataMedia.alt_text);
}
}
});
} else {
updateFeaturedImageAlt(
$('#_thumbnail_id').val(),
$('#postimagediv').find('#set-post-thumbnail').find('img').attr('alt'),
);
}
$(document).on(PP_Checklists.EVENT_TIC, function (event) {
if (!loaded) return;
let has_alt = true,
has_image = PP_Checklists.hasFeaturedImage();
if (has_image) {
has_alt = Boolean(featured_image_alt[meta_id]);
}
if ($('#attachment-details-alt-text').length > 0) {
const callableFunc = function () {
const current_alt = $('#attachment-details-alt-text').val();
const previous_alt = featured_image_alt[meta_id] ?? '';
if (current_alt !== previous_alt) {
featured_image_alt[meta_id] = current_alt;
}
};
$('#attachment-details-alt-text')
.ready(function () {
$('.attachments-wrapper li').each(function () {
if ($(this).attr('aria-checked') === 'true') {
meta_id = Number($(this).attr('data-id'));
callableFunc();
}
});
})
.on('change', callableFunc);
}
$('#pp-checklists-req-featured_image_alt').trigger(PP_Checklists.EVENT_UPDATE_REQUIREMENT_STATE, has_alt);
});
}
/*---------- Tags Number ----------*/
if ($('#pp-checklists-req-tags_count').length > 0) {
$(document).on(PP_Checklists.EVENT_TIC, function (event) {
var count = 0,
min_value = parseInt(ppChecklists.requirements.tags_count.value[0]),