PluginProbe
LearnPress – WordPress LMS Plugin for Create and Sell Online Courses / 4.4.1
LearnPress – WordPress LMS Plugin for Create and Sell Online Courses v4.4.1
4.4.9.1 4.4.9 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 All 141 releases
learnpress / assets / js / dist / frontend / checkout.js

checkout.js in LearnPress – WordPress LMS Plugin for Create and Sell Online Courses 4.4.1, at assets/js/dist/frontend/checkout.js

630 lines 18.7 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 /******/ const __webpack_module_cache__ = {};
370 /******/
371 /******/ // The require function
372 /******/ function __webpack_require__(moduleId) {
373 /******/ // Check if module is in cache
374 /******/ const 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 /******/ const 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 /******/ const 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/value functions for harmony exports
402 /******/ __webpack_require__.d = (exports, definition) => {
403 /******/ if(Array.isArray(definition)) {
404 /******/ var i = 0;
405 /******/ while(i < definition.length) {
406 /******/ var key = definition[i++];
407 /******/ var binding = definition[i++];
408 /******/ if(!__webpack_require__.o(exports, key)) {
409 /******/ if(binding === 0) {
410 /******/ Object.defineProperty(exports, key, { enumerable: true, value: definition[i++] });
411 /******/ } else {
412 /******/ Object.defineProperty(exports, key, { enumerable: true, get: binding });
413 /******/ }
414 /******/ } else if(binding === 0) { i++; }
415 /******/ }
416 /******/ } else {
417 /******/ for(var key in definition) {
418 /******/ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
419 /******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });
420 /******/ }
421 /******/ }
422 /******/ }
423 /******/ };
424 /******/ })();
425 /******/
426 /******/ /* webpack/runtime/hasOwnProperty shorthand */
427 /******/ (() => {
428 /******/ __webpack_require__.o = (obj, prop) => (Object.hasOwn(obj, prop))
429 /******/ })();
430 /******/
431 /******/ /* webpack/runtime/make namespace object */
432 /******/ (() => {
433 /******/ // define __esModule on exports
434 /******/ __webpack_require__.r = (exports) => {
435 /******/ if(Symbol.toStringTag) {
436 /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
437 /******/ }
438 /******/ Object.defineProperty(exports, '__esModule', { value: true });
439 /******/ };
440 /******/ })();
441 /******/
442 /************************************************************************/
443 let __webpack_exports__ = {};
444 // This entry needs to be wrapped in an IIFE because it needs to be isolated against other modules in the chunk.
445 (() => {
446 /*!********************************************!*\
447 !*** ./assets/src/js/frontend/checkout.js ***!
448 \********************************************/
449 __webpack_require__.r(__webpack_exports__);
450 /* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils.js */ "./assets/src/js/utils.js");
451 /**
452 * File JS handling checkout page.
453 */
454
455
456
457 // Events
458 document.addEventListener('submit', e => {
459 window.lpCheckout.submit(e);
460 });
461 document.addEventListener('change', e => {
462 window.lpCheckout.paymentSelect(e);
463 });
464 document.addEventListener('keyup', e => {
465 window.lpCheckout.checkEmailGuest(e);
466 });
467 window.lpCheckout = {
468 idFormCheckout: 'learn-press-checkout-form',
469 idBtnPlaceOrder: 'learn-press-checkout-place-order',
470 classPaymentMethod: 'lp-payment-method',
471 classPaymentMethodForm: 'payment-method-form',
472 timeOutCheckEmail: null,
473 fetchAPI: (url, params, callBack) => {
474 const option = {
475 headers: {}
476 };
477 if (0 !== parseInt(lpData.user_id)) {
478 option.headers['X-WP-Nonce'] = lpData.nonce;
479 }
480 const searchParams = new URLSearchParams();
481 Object.keys(params).forEach(key => {
482 searchParams.append(key, params[key]);
483 });
484 option.method = 'POST';
485 option.body = searchParams;
486 fetch(url, option).then(res => res.text()).then(data => {
487 data = (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.lpAjaxParseJsonOld)(data);
488 callBack.success(data);
489 }).finally(() => {
490 callBack.completed();
491 }).catch(err => callBack.error(err));
492 },
493 submit: e => {
494 const formCheckout = e.target;
495 if (formCheckout.id !== window.lpCheckout.idFormCheckout) {
496 return;
497 }
498 if (formCheckout.classList.contains('processing')) {
499 return;
500 }
501 e.preventDefault();
502 formCheckout.classList.add('processing');
503 const btnSubmit = formCheckout.querySelector('button[type="submit"]');
504 btnSubmit.disabled = true;
505 window.lpCheckout.removeMessage();
506 const elBtnPlaceOrder = document.getElementById(window.lpCheckout.idBtnPlaceOrder);
507 const urlHandle = new URL(lpCheckoutSettings.ajaxurl);
508 urlHandle.searchParams.set('lp-ajax', 'checkout');
509
510 // get values from FormData
511 const formData = new FormData(formCheckout);
512 const dataSend = Object.fromEntries(Array.from(formData.keys(), key => {
513 const val = formData.getAll(key);
514 return [key, val.length > 1 ? val : val.pop()];
515 }));
516 elBtnPlaceOrder.classList.add('loading');
517 const callBack = {
518 success: response => {
519 response = (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.lpAjaxParseJsonOld)(response);
520 const {
521 message,
522 result
523 } = response;
524 if (response.redirect) {
525 window.location.href = response.redirect;
526 } else if ('success' !== result) {
527 window.lpCheckout.showErrors(formCheckout, 'error', message);
528 }
529 },
530 error: error => {
531 window.lpCheckout.showErrors(formCheckout, 'error', error);
532 },
533 completed: () => {
534 elBtnPlaceOrder.classList.remove('loading');
535 formCheckout.classList.remove('processing');
536 btnSubmit.disabled = false;
537 }
538 };
539 window.lpCheckout.fetchAPI(urlHandle, dataSend, callBack);
540 },
541 paymentSelect: e => {
542 const target = e.target;
543 const elPaymentMethod = target.closest(`.${window.lpCheckout.classPaymentMethod}`);
544 if (!elPaymentMethod) {
545 return;
546 }
547 const elUlPaymentMethods = elPaymentMethod.closest('.payment-methods');
548 if (!elUlPaymentMethods) {
549 return;
550 }
551 const elPaymentMethods = elUlPaymentMethods.querySelectorAll(`.${window.lpCheckout.classPaymentMethod}`);
552 elPaymentMethods.forEach(el => {
553 const elPaymentMethodForm = el.querySelector(`.${window.lpCheckout.classPaymentMethodForm}`);
554 if (!elPaymentMethodForm) {
555 return;
556 }
557 if (elPaymentMethod !== el) {
558 elPaymentMethodForm.style.display = 'none';
559 } else {
560 elPaymentMethodForm.style.display = 'block';
561 }
562 });
563 },
564 checkEmailGuest: e => {
565 const target = e.target;
566 if (target.id !== 'guest_email') {
567 return;
568 }
569 if (!window.lpCheckout.isEmail(target.value)) {
570 return;
571 }
572 target.classList.add('loading');
573 if (window.lpCheckout.timeOutCheckEmail !== null) {
574 clearTimeout(window.lpCheckout.timeOutCheckEmail);
575 }
576 window.lpCheckout.timeOutCheckEmail = setTimeout(() => {
577 const callBack = {
578 success: response => {
579 const {
580 message,
581 data,
582 status
583 } = response;
584 if ('success' === status) {
585 const content = data.content || '';
586 const elGuestOutput = document.querySelector('.lp-guest-checkout-output');
587 if (elGuestOutput) {
588 elGuestOutput.remove();
589 }
590 target.insertAdjacentHTML('afterend', content);
591 } else {
592 window.lpCheckout.showErrors(target.closest('form'), status, message);
593 }
594 },
595 error: error => {
596 window.lpCheckout.showErrors(target.closest('form'), 'error', error);
597 },
598 completed: () => {
599 target.classList.remove('loading');
600 }
601 };
602 window.lpCheckout.fetchAPI(window.location.href, {
603 'lp-ajax': 'checkout-user-email-exists',
604 email: target.value
605 }, callBack);
606 }, 500);
607 },
608 removeMessage: () => {
609 const lpMessages = document.querySelectorAll('.learn-press-message');
610 if (!lpMessages) {
611 return;
612 }
613 lpMessages.forEach(el => {
614 el.remove();
615 });
616 },
617 showErrors: (form, status, message) => {
618 const mesHtml = `<div class="learn-press-message ${status}">${message}</div>`;
619 form.insertAdjacentHTML('afterbegin', mesHtml);
620 form.scrollIntoView();
621 },
622 isEmail: email => {
623 return new RegExp('^[-!#$%&\'*+\\./0-9=?A-Z^_`a-z{|}~]+@[-!#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+\.[-!#$%&\'*+\\./0-9=?A-Z^_`a-z{|}~]+$').test(email);
624 }
625 };
626 })();
627
628 /******/ })()
629 ;
630 //# sourceMappingURL=checkout.js.map