PluginProbe
LearnPress – WordPress LMS Plugin for Create and Sell Online Courses / 4.4.2
LearnPress – WordPress LMS Plugin for Create and Sell Online Courses v4.4.2
4.4.8 4.4.7 4.4.6 4.4.5 4.4.4 4.4.3 4.4.2 4.4.1 4.4.0 4.3.9.1 4.3.9 4.3.8 4.3.7 4.1.6.9 4.1.6.9.1 4.1.6.9.2 4.1.6.9.3 4.1.6.9.4 4.1.7 4.1.7.1 4.1.7.2 4.1.7.3 4.1.7.3.1 4.1.7.3.2 4.2.0 All 139 releases
learnpress / assets / js / dist / admin / learnpress.js

learnpress.js in LearnPress – WordPress LMS Plugin for Create and Sell Online Courses 4.4.2, at assets/js/dist/admin/learnpress.js

1,181 lines 37.4 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 /******/ (() => { // webpackBootstrap
2 /******/ "use strict";
3 /******/ var __webpack_modules__ = ({
4
5 /***/ "./assets/src/js/utils.js"
6 /*!********************************!*\
7 !*** ./assets/src/js/utils.js ***!
8 \********************************/
9 (__unused_webpack_module, __webpack_exports__, __webpack_require__) {
10
11 __webpack_require__.r(__webpack_exports__);
12 /* harmony export */ __webpack_require__.d(__webpack_exports__, {
13 /* harmony export */ debounce: () => (/* binding */ debounce),
14 /* harmony export */ eventHandlers: () => (/* binding */ eventHandlers),
15 /* harmony export */ getDataOfForm: () => (/* binding */ getDataOfForm),
16 /* harmony export */ getFieldKeysOfForm: () => (/* binding */ getFieldKeysOfForm),
17 /* harmony export */ listenElementCreated: () => (/* binding */ listenElementCreated),
18 /* harmony export */ listenElementViewed: () => (/* binding */ listenElementViewed),
19 /* harmony export */ lpAddQueryArgs: () => (/* binding */ lpAddQueryArgs),
20 /* harmony export */ lpAjaxParseJsonOld: () => (/* binding */ lpAjaxParseJsonOld),
21 /* harmony export */ lpClassName: () => (/* binding */ lpClassName),
22 /* harmony export */ lpFetchAPI: () => (/* binding */ lpFetchAPI),
23 /* harmony export */ lpGetCurrentURLNoParam: () => (/* binding */ lpGetCurrentURLNoParam),
24 /* harmony export */ lpOnElementReady: () => (/* binding */ lpOnElementReady),
25 /* harmony export */ lpSetLoadingEl: () => (/* binding */ lpSetLoadingEl),
26 /* harmony export */ lpShowHideEl: () => (/* binding */ lpShowHideEl),
27 /* harmony export */ mergeDataWithDatForm: () => (/* binding */ mergeDataWithDatForm),
28 /* harmony export */ toggleCollapse: () => (/* binding */ toggleCollapse)
29 /* harmony export */ });
30 /**
31 * Utils functions
32 *
33 * @param url
34 * @param data
35 * @param functions
36 * @since 4.2.5.1
37 * @version 1.0.6
38 */
39 const lpClassName = {
40 hidden: 'lp-hidden',
41 loading: 'loading',
42 elCollapse: 'lp-collapse',
43 elSectionToggle: '.lp-section-toggle',
44 elTriggerToggle: '.lp-trigger-toggle'
45 };
46 const lpFetchAPI = (url, data = {}, functions = {}) => {
47 if ('function' === typeof functions.before) {
48 functions.before();
49 }
50 fetch(url, {
51 method: 'GET',
52 ...data
53 }).then(response => response.json()).then(response => {
54 if ('function' === typeof functions.success) {
55 functions.success(response);
56 }
57 }).catch(err => {
58 if ('function' === typeof functions.error) {
59 functions.error(err);
60 }
61 }).finally(() => {
62 if ('function' === typeof functions.completed) {
63 functions.completed();
64 }
65 });
66 };
67
68 /**
69 * Get current URL without params.
70 *
71 * @since 4.2.5.1
72 */
73 const lpGetCurrentURLNoParam = () => {
74 let currentUrl = window.location.href;
75 const hasParams = currentUrl.includes('?');
76 if (hasParams) {
77 currentUrl = currentUrl.split('?')[0];
78 }
79 return currentUrl;
80 };
81 const lpAddQueryArgs = (endpoint, args) => {
82 const url = new URL(endpoint);
83 Object.keys(args).forEach(arg => {
84 url.searchParams.set(arg, args[arg]);
85 });
86 return url;
87 };
88
89 /**
90 * Listen element viewed.
91 *
92 * @param el
93 * @param callback
94 * @since 4.2.5.8
95 */
96 const listenElementViewed = (el, callback) => {
97 const observerSeeItem = new IntersectionObserver(function (entries) {
98 for (const entry of entries) {
99 if (entry.isIntersecting) {
100 callback(entry);
101 }
102 }
103 });
104 observerSeeItem.observe(el);
105 };
106
107 /**
108 * Listen element created.
109 *
110 * @param callback
111 * @since 4.2.5.8
112 */
113 const listenElementCreated = callback => {
114 const observerCreateItem = new MutationObserver(function (mutations) {
115 mutations.forEach(function (mutation) {
116 if (mutation.addedNodes) {
117 mutation.addedNodes.forEach(function (node) {
118 if (node.nodeType === 1) {
119 callback(node);
120 }
121 });
122 }
123 });
124 });
125 observerCreateItem.observe(document, {
126 childList: true,
127 subtree: true
128 });
129 // End.
130 };
131
132 /**
133 * Listen element created.
134 *
135 * @param selector
136 * @param callback
137 * @since 4.2.7.1
138 */
139 const lpOnElementReady = (selector, callback) => {
140 const element = document.querySelector(selector);
141 if (element) {
142 callback(element);
143 return;
144 }
145 const observer = new MutationObserver((mutations, obs) => {
146 const element = document.querySelector(selector);
147 if (element) {
148 obs.disconnect();
149 callback(element);
150 }
151 });
152 observer.observe(document.documentElement, {
153 childList: true,
154 subtree: true
155 });
156 };
157
158 // Parse JSON from string with content include LP_AJAX_START.
159 const lpAjaxParseJsonOld = data => {
160 if (typeof data !== 'string') {
161 return data;
162 }
163 const m = String.raw({
164 raw: data
165 }).match(/<-- LP_AJAX_START -->(.*)<-- LP_AJAX_END -->/s);
166 try {
167 if (m) {
168 data = JSON.parse(m[1].replace(/(?:\r\n|\r|\n)/g, ''));
169 } else {
170 data = JSON.parse(data);
171 }
172 } catch (e) {
173 data = {};
174 }
175 return data;
176 };
177
178 // status 0: hide, 1: show
179 const lpShowHideEl = (el, status = 0) => {
180 if (!el) {
181 return;
182 }
183 if (!status) {
184 el.classList.add(lpClassName.hidden);
185 } else {
186 el.classList.remove(lpClassName.hidden);
187 }
188 };
189
190 // status 0: hide, 1: show
191 const lpSetLoadingEl = (el, status) => {
192 if (!el) {
193 return;
194 }
195 if (!status) {
196 el.classList.remove(lpClassName.loading);
197 } else {
198 el.classList.add(lpClassName.loading);
199 }
200 };
201
202 // Toggle collapse section
203 const toggleCollapse = (e, target, elTriggerClassName = '', elsExclude = [], callback) => {
204 if (!elTriggerClassName) {
205 elTriggerClassName = lpClassName.elTriggerToggle;
206 }
207
208 // Exclude elements, which should not trigger the collapse toggle
209 if (elsExclude && elsExclude.length > 0) {
210 for (const elExclude of elsExclude) {
211 if (target.closest(elExclude)) {
212 return;
213 }
214 }
215 }
216 const elTrigger = target.closest(elTriggerClassName);
217 if (!elTrigger) {
218 return;
219 }
220
221 //console.log( 'elTrigger', elTrigger );
222
223 const elSectionToggle = elTrigger.closest(`${lpClassName.elSectionToggle}`);
224 if (!elSectionToggle) {
225 return;
226 }
227 elSectionToggle.classList.toggle(`${lpClassName.elCollapse}`);
228 if ('function' === typeof callback) {
229 callback(elSectionToggle);
230 }
231 };
232
233 // Get data of form
234 const getDataOfForm = form => {
235 const dataSend = {};
236 const formData = new FormData(form);
237 for (const pair of formData.entries()) {
238 const key = pair[0];
239 const value = formData.getAll(key);
240 if (!dataSend.hasOwnProperty(key)) {
241 // Convert value array to string.
242 dataSend[key] = value.join(',');
243 }
244 }
245 return dataSend;
246 };
247
248 // Get field keys of form
249 const getFieldKeysOfForm = form => {
250 const keys = [];
251 const elements = form.elements;
252 for (let i = 0; i < elements.length; i++) {
253 const name = elements[i].name;
254 if (name && !keys.includes(name)) {
255 keys.push(name);
256 }
257 }
258 return keys;
259 };
260
261 // Merge data handle with data form.
262 const mergeDataWithDatForm = (elForm, dataHandle) => {
263 const dataForm = getDataOfForm(elForm);
264 const keys = getFieldKeysOfForm(elForm);
265 keys.forEach(key => {
266 if (!dataForm.hasOwnProperty(key)) {
267 delete dataHandle[key];
268 } else if (dataForm[key][0] === '') {
269 delete dataForm[key];
270 delete dataHandle[key];
271 }
272 });
273 dataHandle = {
274 ...dataHandle,
275 ...dataForm
276 };
277 return dataHandle;
278 };
279
280 /**
281 * Event trigger
282 * For each list of event handlers, listen event on document.
283 *
284 * eventName: 'click', 'change', ...
285 * eventHandlers = [ { selector: '.lp-button', callBack: function(){}, class: object } ]
286 *
287 * @param eventName
288 * @param eventHandlers
289 */
290 const eventHandlers = (eventName, eventHandlers) => {
291 document.addEventListener(eventName, e => {
292 const target = e.target;
293 let args = {
294 e,
295 target
296 };
297 eventHandlers.forEach(eventHandler => {
298 args = {
299 ...args,
300 ...eventHandler
301 };
302
303 //console.log( args );
304
305 // Check condition before call back
306 if (eventHandler.conditionBeforeCallBack) {
307 if (eventHandler.conditionBeforeCallBack(args) !== true) {
308 return;
309 }
310 }
311
312 // Special check for keydown event with checkIsEventEnter = true
313 if (eventName === 'keydown' && eventHandler.checkIsEventEnter) {
314 if (e.key !== 'Enter') {
315 return;
316 }
317 }
318 if (target.closest(eventHandler.selector)) {
319 if (eventHandler.class) {
320 // Call method of class, function callBack will understand exactly {this} is class object.
321 eventHandler.class[eventHandler.callBack](args);
322 } else {
323 // For send args is objected, {this} is eventHandler object, not class object.
324 eventHandler.callBack(args);
325 }
326 }
327 });
328 });
329 };
330
331 /**
332 * Debounce - delays function execution until after `wait` ms of inactivity.
333 *
334 * Each call resets the timer. Only the last call in a burst executes.
335 *
336 * USE CASES:
337 * - Search inputs, form validation, window resize
338 * - Multiple elements need independent timers
339 * - When you need to call with different arguments
340 *
341 * EXAMPLES:
342 * const debouncedSearch = debounce( (query) => fetchResults(query), 300 );
343 * searchInput.addEventListener('input', (e) => debouncedSearch(e.target.value));
344 *
345 * const debouncedResize = debounce( recalculateLayout, 250 );
346 * window.addEventListener('resize', debouncedResize);
347 *
348 * ⚠️ Create ONCE outside event handlers, not inside.
349 *
350 * @param {Function} func - Function to debounce (can be anonymous)
351 * @param {number} wait - Milliseconds to wait (default: 500)
352 * @return {Function} Debounced wrapper function
353 * @since 4.3.7
354 * @version 1.0.0
355 */
356 const debounce = (func, wait = 500) => {
357 let timer;
358 return args => {
359 clearTimeout(timer);
360 timer = setTimeout(() => func(args), wait);
361 };
362 };
363
364 /***/ }
365
366 /******/ });
367 /************************************************************************/
368 /******/ // The module cache
369 /******/ var __webpack_module_cache__ = {};
370 /******/
371 /******/ // The require function
372 /******/ function __webpack_require__(moduleId) {
373 /******/ // Check if module is in cache
374 /******/ var cachedModule = __webpack_module_cache__[moduleId];
375 /******/ if (cachedModule !== undefined) {
376 /******/ return cachedModule.exports;
377 /******/ }
378 /******/ // Create a new module (and put it into the cache)
379 /******/ var module = __webpack_module_cache__[moduleId] = {
380 /******/ // no module.id needed
381 /******/ // no module.loaded needed
382 /******/ exports: {}
383 /******/ };
384 /******/
385 /******/ // Execute the module function
386 /******/ if (!(moduleId in __webpack_modules__)) {
387 /******/ delete __webpack_module_cache__[moduleId];
388 /******/ var e = new Error("Cannot find module '" + moduleId + "'");
389 /******/ e.code = 'MODULE_NOT_FOUND';
390 /******/ throw e;
391 /******/ }
392 /******/ __webpack_modules__[moduleId](module, module.exports, __webpack_require__);
393 /******/
394 /******/ // Return the exports of the module
395 /******/ return module.exports;
396 /******/ }
397 /******/
398 /************************************************************************/
399 /******/ /* webpack/runtime/define property getters */
400 /******/ (() => {
401 /******/ // define getter functions for harmony exports
402 /******/ __webpack_require__.d = (exports, definition) => {
403 /******/ for(var key in definition) {
404 /******/ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
405 /******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });
406 /******/ }
407 /******/ }
408 /******/ };
409 /******/ })();
410 /******/
411 /******/ /* webpack/runtime/hasOwnProperty shorthand */
412 /******/ (() => {
413 /******/ __webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))
414 /******/ })();
415 /******/
416 /******/ /* webpack/runtime/make namespace object */
417 /******/ (() => {
418 /******/ // define __esModule on exports
419 /******/ __webpack_require__.r = (exports) => {
420 /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
421 /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
422 /******/ }
423 /******/ Object.defineProperty(exports, '__esModule', { value: true });
424 /******/ };
425 /******/ })();
426 /******/
427 /************************************************************************/
428 var __webpack_exports__ = {};
429 // This entry needs to be wrapped in an IIFE because it needs to be isolated against other modules in the chunk.
430 (() => {
431 /*!*******************************************!*\
432 !*** ./assets/src/js/admin/learnpress.js ***!
433 \*******************************************/
434 __webpack_require__.r(__webpack_exports__);
435 /* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils */ "./assets/src/js/utils.js");
436
437 const $ = jQuery;
438 const $doc = $(document);
439 const makePaymentsSortable = function makePaymentsSortable() {
440 // Make payments sortable
441 $('.learn-press-payments.sortable tbody').sortable({
442 handle: '.dashicons-menu',
443 helper(e, ui) {
444 ui.children().each(function () {
445 $(this).width($(this).width());
446 });
447 return ui;
448 },
449 axis: 'y',
450 start(event, ui) {},
451 stop(event, ui) {},
452 update(event, ui) {
453 const order = $(this).children().map(function () {
454 return $(this).find('input[name="payment-order"]').val();
455 }).get();
456 $.post({
457 url: '',
458 data: {
459 'lp-ajax': 'update-payment-order',
460 order,
461 nonce: $('input[name=lp-settings-nonce]').val()
462 },
463 success(response) {}
464 });
465 }
466 });
467 };
468
469 /** Start Nhamdv code */
470
471 const lpMetaboxCustomFields = () => {
472 $('.lp-metabox__custom-fields').on('click', '.lp-metabox-custom-field-button', function () {
473 const row = $(this).data('row').replace(/lp_metabox_custom_fields_key/gi, Math.floor(Math.random() * 1000) + 1);
474 $(this).closest('table').find('tbody').append(row);
475 updateSort($(this).closest('.lp-metabox__custom-fields'));
476 return false;
477 });
478 $('.lp-metabox__custom-fields').on('click', 'a.delete', function () {
479 $(this).closest('tr').remove();
480 updateSort($(this).closest('.lp-metabox__custom-fields'));
481 return false;
482 });
483 $('.lp-metabox__custom-fields tbody').sortable({
484 items: 'tr',
485 cursor: 'move',
486 axis: 'y',
487 handle: 'td.sort',
488 scrollSensitivity: 40,
489 forcePlaceholderSize: true,
490 helper: 'clone',
491 opacity: 0.65,
492 update(event, ui) {
493 updateSort($(this).closest('.lp-metabox__custom-fields'));
494 }
495 });
496 const updateSort = element => {
497 const items = element.find('tbody tr');
498 items.each(function (i, item) {
499 $(this).find('.sort .count').val(i);
500 });
501 };
502 };
503 const lpMetaboxRepeaterField = () => {
504 const updateSort = element => {
505 const items = element.find('.lp_repeater_meta_box__field');
506 items.each(function (i, item) {
507 $(this).find('.lp_repeater_meta_box__field__count').val(i);
508 $(this).find('.lp_repeater_meta_box__title__title > span').text(i + 1);
509 });
510 };
511 $('.lp_repeater_meta_box__add').on('click', function () {
512 const row = $(this).data('add').replace(/lp_metabox_repeater_key/gi, Math.floor(Math.random() * 1000) + 1);
513 $(this).closest('.lp_repeater_meta_box__wrapper').find('.lp_repeater_meta_box__fields').append(row);
514 updateSort($(this).closest('.lp_repeater_meta_box__wrapper'));
515 $(this).closest('.lp_repeater_meta_box__wrapper').find('.lp_repeater_meta_box__fields').last().find('input').trigger('focus');
516 return false;
517 });
518 $('.lp_repeater_meta_box__wrapper').on('click', 'a.lp_repeater_meta_box__title__delete', function () {
519 $(this).closest('.lp_repeater_meta_box__field').remove();
520 updateSort($(this).closest('.lp_repeater_meta_box__wrapper'));
521 return false;
522 });
523 $('.lp_repeater_meta_box__fields').on('click', '.lp_repeater_meta_box__title__toggle, .lp_repeater_meta_box__title__title', function () {
524 const field = $(this).closest('.lp_repeater_meta_box__field');
525 if (field.hasClass('lp_repeater_meta_box__field_active')) {
526 field.removeClass('lp_repeater_meta_box__field_active');
527 } else {
528 field.addClass('lp_repeater_meta_box__field_active');
529 }
530 return false;
531 });
532 $('.lp_repeater_meta_box__fields').sortable({
533 items: '.lp_repeater_meta_box__field',
534 cursor: 'grab',
535 axis: 'y',
536 handle: '.lp_repeater_meta_box__title__sort',
537 scrollSensitivity: 40,
538 forcePlaceholderSize: true,
539 helper: 'clone',
540 opacity: 0.65,
541 update(event, ui) {
542 updateSort($(this).closest('.lp_repeater_meta_box__wrapper'));
543 }
544 });
545 };
546 const lpMetaboxExtraInfo = () => {
547 $('.lp_course_extra_meta_box__add').on('click', function () {
548 $(this).closest('.lp_course_extra_meta_box__content').find('.lp_course_extra_meta_box__fields').append($(this).data('add'));
549 $(this).closest('.lp_course_extra_meta_box__content').find('.lp_course_extra_meta_box__field').last().find('input').trigger('focus');
550 return false;
551 });
552
553 /*document.querySelectorAll( '.lp_course_extra_meta_box__fields' ).forEach( ( ele ) => {
554 ele.addEventListener( 'keydown', ( e ) => {
555 const inputs = ele.querySelectorAll( '.lp_course_extra_meta_box__input' );
556 if ( e.keyCode === 13 ) {
557 e.preventDefault();
558 inputs.forEach( ( input ) => {
559 input.blur();
560 } );
561 return false;
562 }
563 } );
564 } );*/
565
566 $('.lp_course_extra_meta_box__fields').on('click', 'a.delete', function () {
567 $(this).closest('.lp_course_extra_meta_box__field').remove();
568 return false;
569 });
570 $('.lp_course_extra_meta_box__fields').sortable({
571 items: '.lp_course_extra_meta_box__field',
572 cursor: 'grab',
573 axis: 'y',
574 handle: '.sort',
575 scrollSensitivity: 40,
576 forcePlaceholderSize: true,
577 helper: 'clone',
578 opacity: 0.65
579 });
580
581 // FAQs metabox.
582 $('.lp_course_faq_meta_box__add').on('click', function () {
583 $(this).closest('.lp_course_faq_meta_box__content').find('.lp_course_faq_meta_box__fields').append($(this).data('add'));
584 return false;
585 });
586
587 /*document.querySelectorAll( '.lp_course_faq_meta_box__fields' ).forEach( ( ele ) => {
588 ele.addEventListener( 'keydown', ( e ) => {
589 const inputs = ele.querySelectorAll( '.lp_course_faq_meta_box__field input' );
590 const textareas = ele.querySelectorAll( '.lp_course_faq_meta_box__field textarea' );
591 if ( e.keyCode === 13 ) {
592 e.preventDefault();
593 [ ...inputs, ...textareas ].forEach( ( input ) => {
594 input.blur();
595 } );
596 return false;
597 }
598 } );
599 } );*/
600
601 $('.lp_course_faq_meta_box__fields').on('click', 'a.delete', function () {
602 $(this).closest('.lp_course_faq_meta_box__field').remove();
603 return false;
604 });
605 $('.lp_course_faq_meta_box__fields').sortable({
606 items: '.lp_course_faq_meta_box__field',
607 cursor: 'grab',
608 axis: 'y',
609 handle: '.sort',
610 scrollSensitivity: 40,
611 forcePlaceholderSize: true,
612 helper: 'clone',
613 opacity: 0.65
614 });
615 };
616
617 // Nhamdv.
618 const lpGetFinalQuiz = () => {
619 const btns = document.querySelectorAll('.lp-metabox-get-final-quiz');
620 [...btns].map(btn => {
621 btn.addEventListener('click', e => {
622 e.preventDefault();
623 const text = btn.textContent,
624 loading = btn.dataset.loading,
625 message = document.querySelector('.lp-metabox-evaluate-final_quiz');
626 if (message) {
627 message.remove();
628 }
629 btn.textContent = loading;
630 getResponse(btn).then(data => {
631 const {
632 message,
633 data: responseData
634 } = data;
635 btn.textContent = text;
636 const newNode = document.createElement('div');
637 newNode.className = 'lp-metabox-evaluate-final_quiz';
638 newNode.innerHTML = responseData || message;
639 btn.parentNode.insertBefore(newNode, btn.nextSibling);
640 });
641 });
642 });
643 const getResponse = async btn => {
644 const response = await wp.apiFetch({
645 path: 'lp/v1/admin/course/get_final_quiz',
646 method: 'POST',
647 data: {
648 courseId: btn.dataset.postid || ''
649 }
650 });
651 return response;
652 };
653 };
654 const lpMetaboxColorPicker = () => {
655 $('.lp-metabox__colorpick').iris({
656 change(event, ui) {
657 $(this).parent().find('.colorpickpreview').css({
658 backgroundColor: ui.color.toString()
659 });
660 },
661 hide: true,
662 border: true
663 }).on('click focus', function (event) {
664 event.stopPropagation();
665 $('.iris-picker').hide();
666 $(this).closest('td').find('.iris-picker').show();
667 $(this).data('original-value', $(this).val());
668 }).on('change', function () {
669 if ($(this).is('.iris-error')) {
670 const originalValue = $(this).data('original-value');
671 if (originalValue.match(/^\#([a-fA-F0-9]{6}|[a-fA-F0-9]{3})$/)) {
672 $(this).val($(this).data('original-value')).trigger('change');
673 } else {
674 $(this).val('').trigger('change');
675 }
676 }
677 });
678 $('body').on('click', function () {
679 $('.iris-picker').hide();
680 });
681 };
682 const lpMetaboxImage = () => {
683 $('.lp-metabox-field__image').each((i, ele) => {
684 let lpImageFrame;
685 const addImage = $(ele).find('.lp-metabox-field__image--add');
686 const delImage = $(ele).find('.lp-metabox-field__image--delete');
687 const image = $(ele).find('.lp-metabox-field__image--image');
688 const inputVal = $(ele).find('.lp-metabox-field__image--id');
689 if (!inputVal.val()) {
690 addImage.show();
691 delImage.hide();
692 } else {
693 addImage.hide();
694 delImage.show();
695 }
696 addImage.on('click', event => {
697 event.preventDefault();
698 if (lpImageFrame) {
699 lpImageFrame.open();
700 return;
701 }
702 lpImageFrame = wp.media({
703 title: addImage.data('choose'),
704 button: {
705 text: addImage.data('update')
706 },
707 multiple: false
708 });
709 lpImageFrame.on('select', function () {
710 const attachment = lpImageFrame.state().get('selection').first().toJSON();
711 const attachmentImage = attachment.sizes && attachment.sizes.thumbnail ? attachment.sizes.thumbnail.url : attachment.url;
712 image.append('<div class="lp-metabox-field__image--inner"><img src="' + attachmentImage + '" alt="" style="max-width:100%;"/></div>');
713 inputVal.val(attachment.id);
714 addImage.hide();
715 delImage.show();
716 });
717 lpImageFrame.open();
718 });
719 delImage.on('click', event => {
720 event.preventDefault();
721 image.html('');
722 addImage.show();
723 delImage.hide();
724 inputVal.val('');
725 });
726 });
727 };
728 const lpMetaboxImageAdvanced = () => {
729 $('.lp-metabox-field__image-advanced').each((i, element) => {
730 let lpImageFrame;
731 const imageGalleryIds = $(element).find('#lp-gallery-images-ids');
732 const listImages = $(element).find('.lp-metabox-field__image-advanced-images');
733 const btnUpload = $(element).find('.lp-metabox-field__image-advanced-upload > a');
734 $(btnUpload).on('click', event => {
735 event.preventDefault();
736 if (lpImageFrame) {
737 lpImageFrame.open();
738 return;
739 }
740 lpImageFrame = wp.media({
741 title: btnUpload.data('choose'),
742 button: {
743 text: btnUpload.data('update')
744 },
745 states: [new wp.media.controller.Library({
746 title: btnUpload.data('choose'),
747 filterable: 'all',
748 multiple: true
749 })]
750 });
751 lpImageFrame.on('select', function () {
752 const selection = lpImageFrame.state().get('selection');
753 let attachmentIds = imageGalleryIds.val();
754 selection.forEach(function (attachment) {
755 attachment = attachment.toJSON();
756 if (attachment.id) {
757 attachmentIds = attachmentIds ? attachmentIds + ',' + attachment.id : attachment.id;
758 const attachmentImage = attachment.sizes && attachment.sizes.thumbnail ? attachment.sizes.thumbnail.url : attachment.url;
759 listImages.append('<li class="image" data-attachment_id="' + attachment.id + '"><img src="' + attachmentImage + '" /><ul class="actions"><li><a href="#" class="delete" title="' + btnUpload.data('delete') + '">' + btnUpload.data('text') + '</a></li></ul></li>');
760 }
761 });
762 imageGalleryIds.val(attachmentIds);
763 });
764 lpImageFrame.open();
765 });
766 listImages.sortable({
767 items: 'li.image',
768 cursor: 'move',
769 scrollSensitivity: 40,
770 forcePlaceholderSize: true,
771 forceHelperSize: false,
772 helper: 'clone',
773 opacity: 0.65,
774 placeholder: 'lp-metabox-sortable-placeholder',
775 start(event, ui) {
776 ui.item.css('background-color', '#f6f6f6');
777 },
778 stop(event, ui) {
779 ui.item.removeAttr('style');
780 },
781 update() {
782 let attachmentIds = '';
783 listImages.find('li.image').css('cursor', 'default').each(function () {
784 const attachmentId = $(this).attr('data-attachment_id');
785 attachmentIds = attachmentIds + attachmentId + ',';
786 });
787 imageGalleryIds.val(attachmentIds);
788 }
789 });
790 $(listImages).find('li.image').each((i, ele) => {
791 const del = $(ele).find('a.delete');
792 del.on('click', () => {
793 $(ele).remove();
794 let attachmentIds = '';
795 $(listImages).find('li.image').css('cursor', 'default').each(function () {
796 const attachmentId = $(this).attr('data-attachment_id');
797 attachmentIds = attachmentIds + attachmentId + ',';
798 });
799 imageGalleryIds.val(attachmentIds);
800 return false;
801 });
802 });
803 });
804 };
805 const lpMetaboxCourseTabs = () => {
806 $(document.body).on('lp-metabox-course-tab-panels', function () {
807 $('ul.lp-meta-box__course-tab__tabs').show();
808 $('ul.lp-meta-box__course-tab__tabs a').on('click', function (e) {
809 e.preventDefault();
810 const panelWrap = $(this).closest('div.lp-meta-box__course-tab');
811 $('ul.lp-meta-box__course-tab__tabs li', panelWrap).removeClass('active');
812 $(this).parent().addClass('active');
813 $('div.lp-meta-box-course-panels', panelWrap).hide();
814 $($(this).attr('href')).show();
815 });
816 $('div.lp-meta-box__course-tab').each(function () {
817 $(this).find('ul.lp-meta-box__course-tab__tabs li').eq(0).find('a').trigger('click');
818 });
819 }).trigger('lp-metabox-course-tab-panels');
820 };
821
822 // use to show and hide field condition logic metabox.
823 /*const lpMetaboxCondition = () => {
824 const fields = document.querySelectorAll( '.lp-meta-box .form-field' );
825
826 fields.forEach( ( field ) => {
827 if ( field.hasAttribute( 'data-show' ) && field.dataset.show ) {
828 lpMetaboxConditionType( field, field.dataset.show, 'show' );
829 } else if ( field.hasAttribute( 'data-hide' ) && field.dataset.hide ) {
830 lpMetaboxConditionType( field, field.dataset.hide, 'hide' );
831 }
832 } );
833 };*/
834
835 /*const lpMetaboxConditionType = ( field, conditions, typeCondition = 'show' ) => {
836 const condition = JSON.parse( conditions ),
837 eles = document.querySelectorAll( `input[id^="${ condition[ 0 ] }"]` ),
838 logic = condition[ 1 ] === '=' ? '=' : '!=',
839 dataLogic = condition[ 2 ];
840
841 const switchCase = ( type, ele, target ) => {
842 switch ( type ) {
843 case 'checkbox':
844 let val = dataLogic;
845
846 if ( dataLogic === 'yes' || dataLogic === '1' || dataLogic === 1 || dataLogic === 'true' ) {
847 val = true;
848 } else if ( dataLogic === 'no' || dataLogic === '0' || dataLogic === 0 || dataLogic === 'false' ) {
849 val = false;
850 }
851
852 if ( logic == '!=' && val !== Boolean( target ? target.checked : ele.checked ) ) {
853 field.style.display = typeCondition === 'show' ? '' : 'none';
854 } else if ( logic == '=' && val == Boolean( target ? target.checked : ele.checked ) ) {
855 field.style.display = typeCondition === 'show' ? '' : 'none';
856 } else {
857 field.style.display = typeCondition === 'show' ? 'none' : '';
858 }
859 break;
860 }
861 };
862
863 eles.forEach( ( ele ) => {
864 const type = ele.getAttribute( 'type' );
865
866 switchCase( type, ele );
867
868 ele.addEventListener( 'change', ( e ) => {
869 const target = e.target;
870
871 switchCase( type, ele, target );
872 } );
873 } );
874 };*/
875
876 /** End Nhamdv code */
877
878 const initTooltips = function initTooltips() {
879 $('.learn-press-tooltip').each(function () {
880 const $el = $(this),
881 args = $.extend({
882 title: 'data-tooltip',
883 offset: 10,
884 gravity: 's'
885 }, $el.data());
886 $el.tipsy(args);
887 });
888 };
889 const initSelect2 = function initSelect2() {
890 if ($.fn.select2) {
891 const elSelect2 = $('.lp-select-2 select');
892 elSelect2.select2({
893 placeholder: 'Select a value'
894 });
895 elSelect2.on('change.select2', function (e) {
896 const el = $(e.target);
897 const val = el.val();
898 if (!val.length) {
899 el.val(null);
900 }
901 });
902 $('.lp_autocomplete_metabox_field').each(function () {
903 const dataAtts = $(this).data('atts');
904 let action = dataAtts.action;
905 if (!action) {
906 switch (dataAtts.data) {
907 case 'users':
908 action = dataAtts.rest_url + 'wp/v2/users';
909 break;
910 default:
911 action = dataAtts.rest_url + 'wp/v2/' + dataAtts.data;
912 break;
913 }
914 }
915 $(this).find('select').select2({
916 placeholder: dataAtts.placeholder ? dataAtts.placeholder : 'Select',
917 ajax: {
918 url: action,
919 dataType: 'json',
920 delay: 250,
921 beforeSend(xhr) {
922 xhr.setRequestHeader('X-WP-Nonce', dataAtts.nonce);
923 },
924 data(params) {
925 return {
926 search: params.term
927 };
928 },
929 processResults(data) {
930 return {
931 results: data.map(item => {
932 return {
933 id: item.id,
934 text: item.title && item.title.rendered ? item.title.rendered : item.name
935 };
936 })
937 };
938 },
939 cache: true
940 },
941 minimumInputLength: 2
942 });
943 });
944 }
945 };
946 const initSingleCoursePermalink = function initSingleCoursePermalink() {
947 $doc.on('change', '.learn-press-single-course-permalink input[type="radio"]', function () {
948 const $check = $(this),
949 $row = $check.closest('.learn-press-single-course-permalink');
950 if ($row.hasClass('custom-base')) {
951 $row.find('input[type="text"]').prop('readonly', false);
952 } else {
953 $row.siblings('.custom-base').find('input[type="text"]').prop('readonly', true);
954 }
955 }).on('change', 'input.learn-press-course-base', function () {
956 $('#course_permalink_structure').val($(this).val());
957 }).on('focus', '#course_permalink_structure', function () {
958 $('#learn_press_custom_permalink').click();
959 }).on('change', '#learn_press_courses_page_id', function () {
960 $('tr.learn-press-courses-page-id').toggleClass('hide-if-js', !parseInt(this.value));
961 });
962 };
963 const togglePaymentStatus = function togglePaymentStatus(e) {
964 e.preventDefault();
965 const $row = $(this).closest('tr'),
966 $button = $(this),
967 status = $row.find('.status').hasClass('enabled') ? 'no' : 'yes';
968 $.ajax({
969 url: '',
970 data: {
971 'lp-ajax': 'update-payment-status',
972 status,
973 id: $row.data('payment'),
974 nonce: $('input[name=lp-settings-nonce]').val()
975 },
976 success(response) {
977 response = (0,_utils__WEBPACK_IMPORTED_MODULE_0__.lpAjaxParseJsonOld)(response);
978 for (const i in response) {
979 $('#payment-' + i + ' .status').toggleClass('enabled', response[i]);
980 }
981 }
982 });
983 };
984 const updateEmailStatus = function updateEmailStatus() {
985 (function () {
986 $.post({
987 url: window.location.href,
988 data: {
989 'lp-ajax': 'update_email_status',
990 status: $(this).parent().hasClass('enabled') ? 'no' : 'yes',
991 id: $(this).data('id'),
992 nonce: $('input[name=lp-settings-nonce]').val()
993 },
994 dataType: 'text',
995 success: $.proxy(function (res) {
996 res = (0,_utils__WEBPACK_IMPORTED_MODULE_0__.lpAjaxParseJsonOld)(res);
997 for (const i in res) {
998 $('#email-' + i + ' .status').toggleClass('enabled', res[i]);
999 }
1000 }, this)
1001 });
1002 }).apply(this);
1003 };
1004 const lpMetaboxsalePriceDate = () => {
1005 // Don't run in LearnPress Frontend Editor Add-on.
1006 if (!$('#course-settings').length) {
1007 return;
1008 }
1009 $('.lp_sale_dates_fields').each(function () {
1010 const wrap = $(this).closest('#price_course_data');
1011 let saleScheduleSet = false;
1012 $(this).find('input').each(function () {
1013 if ('' !== $(this).val()) {
1014 saleScheduleSet = true;
1015 }
1016 });
1017 if (saleScheduleSet) {
1018 wrap.find('.lp_sale_price_schedule').hide();
1019 wrap.find('.lp_sale_dates_fields').show();
1020 } else {
1021 wrap.find('.lp_sale_price_schedule').show();
1022 wrap.find('.lp_sale_dates_fields').hide();
1023 }
1024 });
1025 $('.lp-meta-box-course-panels').on('click', '.lp_sale_price_schedule', function () {
1026 const wrap = $(this).closest('#price_course_data');
1027 $(this).hide();
1028 wrap.find('.lp_cancel_sale_schedule').show();
1029 wrap.find('.lp_sale_dates_fields').show();
1030 return false;
1031 });
1032 $('.lp-meta-box-course-panels').on('click', '.lp_cancel_sale_schedule', function () {
1033 const wrap = $(this).closest('div.lp-meta-box-course-panels');
1034 $(this).hide();
1035 wrap.find('.lp_sale_price_schedule').show();
1036 wrap.find('.lp_sale_dates_fields').hide();
1037 wrap.find('.lp_sale_dates_fields').find('input').val('');
1038 return false;
1039 });
1040 $(document).on('input', '#price_course_data', function (e) {
1041 const $this = $(this),
1042 regularPrice = $('.lp_meta_box_regular_price'),
1043 salePrice = $('.lp_meta_box_sale_price'),
1044 $target = $(e.target).attr('id');
1045 $this.find('.learn-press-tip-floating').remove();
1046 if (parseInt(salePrice.val()) > parseInt(regularPrice.val())) {
1047 if ($target === '_lp_price') {
1048 regularPrice.parent('.form-field').append('<div class="learn-press-tip-floating">' + lpAdminCourseEditorSettings.i18n.notice_price + '</div>');
1049 } else if ($target === '_lp_sale_price') {
1050 salePrice.parent('.form-field').append('<div class="learn-press-tip-floating">' + lpAdminCourseEditorSettings.i18n.notice_sale_price + '</div>');
1051 }
1052 }
1053 });
1054
1055 /*const datePickerSelect = function( datepicker ) {
1056 const option = $( datepicker ).is( '#_lp_sale_start' ) ? 'minDate' : 'maxDate',
1057 otherDateField = 'minDate' === option ? $( '#_lp_sale_end' ) : $( '#_lp_sale_start' ),
1058 date = $( datepicker ).datetimepicker( 'getDate' );
1059 $( otherDateField ).datetimepicker( 'option', option, date );
1060 $( datepicker ).trigger( 'change' );
1061 };
1062 $( '.lp_sale_dates_fields' ).each( function() {
1063 $( this ).find( 'input' ).datetimepicker( {
1064 timeFormat: 'HH:mm',
1065 separator: ' ',
1066 dateFormat: 'yy-mm-dd',
1067 showButtonPanel: true,
1068 onSelect() {
1069 datePickerSelect( $( this ) );
1070 },
1071 } );
1072 $( this ).find( 'input' ).each( function() {
1073 datePickerSelect( $( this ) );
1074 } );
1075 } );*/
1076 };
1077 const lpHidePassingGrade = () => {
1078 const listHides = ['evaluate_final_quiz', 'evaluate_final_assignment'];
1079 const inputLists = document.querySelectorAll('input[type=radio][name=_lp_course_result]');
1080 [...inputLists].map((ele, i) => {
1081 if (ele.checked && listHides.includes(ele.value)) {
1082 $('._lp_passing_condition_field').hide();
1083 }
1084 return null;
1085 });
1086 $('input[type=radio][name=_lp_course_result]').on('change', function (e) {
1087 if (listHides.includes(e.target.value)) {
1088 $('._lp_passing_condition_field').hide();
1089 } else {
1090 $('._lp_passing_condition_field').show();
1091 }
1092 });
1093 };
1094 const callbackFilterTemplates = function callbackFilterTemplates() {
1095 const $link = $(this);
1096 if ($link.hasClass('current')) {
1097 return false;
1098 }
1099 const $templatesList = $('#learn-press-template-files'),
1100 $templates = $templatesList.find('tr[data-template]'),
1101 template = $link.data('template'),
1102 filter = $link.data('filter');
1103 $link.addClass('current').siblings('a').removeClass('current');
1104 if (!template) {
1105 if (!filter) {
1106 $templates.removeClass('hide-if-js');
1107 } else {
1108 $templates.map(function () {
1109 $(this).toggleClass('hide-if-js', $(this).data('filter-' + filter) !== 'yes');
1110 });
1111 }
1112 } else {
1113 $templates.map(function () {
1114 $(this).toggleClass('hide-if-js', $(this).data('template') !== template);
1115 });
1116 }
1117 $('#learn-press-no-templates').toggleClass('hide-if-js', !!$templatesList.find('tr.template-row:not(.hide-if-js):first').length);
1118 return false;
1119 };
1120 const toggleEmails = function toggleEmails(e) {
1121 e.preventDefault();
1122 const $button = $(this),
1123 status = $button.data('status');
1124 $.ajax({
1125 url: '',
1126 data: {
1127 'lp-ajax': 'update_email_status',
1128 nonce: $('input[name=lp-settings-nonce]').val(),
1129 status
1130 },
1131 success(response) {
1132 response = (0,_utils__WEBPACK_IMPORTED_MODULE_0__.lpAjaxParseJsonOld)(response);
1133 for (const i in response) {
1134 $('#email-' + i + ' .status').toggleClass('enabled', response[i]);
1135 }
1136 }
1137 });
1138 };
1139 const onReady = function onReady() {
1140 makePaymentsSortable();
1141 initSelect2();
1142 initTooltips();
1143 initSingleCoursePermalink();
1144
1145 // lp Metabox in LP4.
1146 lpMetaboxCourseTabs();
1147 lpMetaboxCustomFields();
1148 lpMetaboxColorPicker();
1149 lpMetaboxImageAdvanced();
1150 lpMetaboxImage();
1151 lpMetaboxsalePriceDate();
1152 lpMetaboxExtraInfo();
1153 lpHidePassingGrade();
1154 lpGetFinalQuiz();
1155 //lpMetaboxCondition();
1156 lpMetaboxRepeaterField();
1157 $(document).on('click', '.learn-press-payments .status .dashicons', togglePaymentStatus).on('click', '.change-email-status', updateEmailStatus).on('click', '.learn-press-filter-template', callbackFilterTemplates).on('click', '#learn-press-enable-emails, #learn-press-disable-emails', toggleEmails);
1158 };
1159 $(document).ready(onReady);
1160
1161 // Events
1162 document.addEventListener('keydown', function (e) {
1163 const target = e.target;
1164 if (e.key === 'Enter' || e.keyCode === 13) {
1165 // When enter on input on Extra information Options, blur it.
1166 if (target.classList.contains('lp_course_extra_meta_box__input')) {
1167 e.preventDefault();
1168 target.blur();
1169 } else if (target.tagName === 'INPUT') {
1170 if (target.closest('.lp_course_faq_meta_box__field')) {
1171 e.preventDefault();
1172 target.blur();
1173 }
1174 }
1175 }
1176 });
1177 })();
1178
1179 /******/ })()
1180 ;
1181 //# sourceMappingURL=learnpress.js.map