Powerful and easy to use cms to build websites, blogs or ecommerce stores.
HTML backendblogblog-engineblog-platformbloggingcmscontent-managementcontent-management-systemecommerceecommerce-platformno-codepage-builderphpphp-cmsphp7php8self-hostedshopping-cartweb-applicationwebsite-builder
Javascript refactoring
Givan932ade7d2276
diff --git a/public/js/admin.js b/public/js/admin.jsindex ac6c148..da8f866 100755--- a/public/js/admin.js+++ b/public/js/admin.js@@ -56,9 +56,21 @@ class AjaxStack {if (this.start = this.stack.length) {let self = this;let call = this.stack.shift();- let ajax = call();+ let ajax;- ajax.then(function() {+ try {+ ajax = call();+ } catch (error) {+ console.error(error);+ self.execute();+ return;+ }++ Promise.resolve(ajax).then(function() {+ self.execute();+ }).catch(function(error) {+ //a failed request must not block the rest of the queue+ console.error(error);self.execute();});}@@ -77,16 +89,40 @@ function displayToast(type, title, message, position = 'bottom', id = null) {if (!id) {id = position + "-toast";}-++ type = String(type ?? 'success').replace(/^bg-/, '');+let toast = document.getElementById(id);+ if (!toast) {+ console.warn("displayToast: missing toast element", id);+ return;+ }+let header = toast.querySelector(".toast-header");toast.classList.remove("bottom-0", "top-0");toast.classList.add(position + "-0");- toast.querySelector(".toast-body .message").innerHTML = message;- header.classList.remove("bg-danger", "bg-success");- header.classList.add("bg-" + type);- header.querySelector("strong").textContent = title;++ //messages are plain text from the server, never render them as html+ let body = toast.querySelector(".toast-body .message");+ if (body) {+ body.textContent = message ?? "";+ }++ if (header) {+ header.classList.remove("bg-danger", "bg-success", "bg-warning", "bg-info");+ header.classList.add("bg-" + type);+ const strong = header.querySelector("strong");+ if (strong) {+ strong.textContent = title ?? "";+ }+ }++ if (!toast.parentNode) {+ return;+ }+let toastDisplay = toast.cloneNode(true);+ toastDisplay.removeAttribute("id");toast.parentNode.appendChild(toastDisplay);let delay = 3000;diff --git a/public/js/admin/functions.js b/public/js/admin/functions.jsindex fd18d28..dbaf8d8 100644--- a/public/js/admin/functions.js+++ b/public/js/admin/functions.js@@ -1,32 +1,67 @@//Tables-function addTemplate(id, name, parent, element = false, parentElement = "table", container = "tbody", callback) {+var elementIdCounter = 0;+function newId() {+ elementIdCounter++;+ return (Date.now() % 1000000000) * 1000 + elementIdCounter;+}++function adminEscapeHtml(value) {+ return String(value ?? '').replace(/[&<>"']/g, function (char) {+ return {'&': '&', '<': '<', '>': '>', '"': '"', "'": '''}[char];+ });+}++function addDataTemplate(element, template) {+ const targetText = template;+ const reg = /#([\w_-]+)#/g;+ let result;+ while ((result = reg.exec(targetText)) !== null) {+ let attr = element.closest("[data-" + result[1] + "]");+ //values come from the page data and must not be able to inject markup+ let value = attr ? attr.getAttribute("data-" + result[1]) : 0;+ template = template.replaceAll("#" + result[1] + "#", () => adminEscapeHtml(value));+ }++ return template;+}++function addTemplate(templateSelector, name, parent, element = false, parentElement = "table", container = "tbody", callback) {// id = attribute-template// name = product_attribute// parent = attributelet template;- let tbody;if (element) {element = element.closest(parentElement);} else {element = document;}- template = document.querySelector(id).cloneNode(true);++ template = element.querySelector(templateSelector);+ if (!template) {+ template = document.querySelector(templateSelector);+ }++ template = template.cloneNode(true)+ template.classList.remove("d-none");- template.querySelectorAll('[type="date"]', template).forEach(e => e.setAttribute("value", date()));+ template.querySelectorAll('[type="date"]').forEach(e => e.setAttribute("value", date()));template.querySelectorAll('[type="datetime-local"]').forEach(e => e.setAttribute("value", datetime()));template.querySelectorAll("input,select").forEach(e => e.removeAttribute("disabled"));- template =template.outerHTML;- let newId = Math.floor(Math.random() * 10000);- template = template.replaceAll(name + '[0]', name + '[' + newId + ']').- replaceAll(name + '[#]', name + '[' + newId + ']').- replaceAll(name + '#', name + newId ).- replaceAll("[" + name +"][#]", "[" + name +"][" + newId + "]").- replace('d-none', '').- replace('id="' + id + '"', '');+ template = template.outerHTML;+ let rowId = newId();+ template = template.replaceAll(name + "[#" + name + "#]", name + "[" + rowId + "]").+ replaceAll("#" + name + "#", rowId).+ replaceAll(name + "#", name + rowId);++ template = addDataTemplate(element, template);let row = generateElements(template)[0];row.removeAttribute("id");+ if (templateSelector[0] === ".") {+ row.classList.remove(templateSelector.slice(1));+ }+element.querySelector(parent + " " + container).append(row);if (callback) {@@ -39,10 +74,19 @@ function addTemplate(id, name, parent, element = false, parentElement = "table",function removeRow(element, elementName = false) {let row = element.closest("tr");if (row && elementName) {- let form = element.closest("form");- form.append(generateElements('<input type="hidden" name="delete[' + elementName + '][]" value="' + row.dataset.id + '">')[0]);+ let id = row.dataset.id;+ if (id && id !== "#") {+ let form = element.closest("form");+ if (form) {+ let input = document.createElement("input");+ input.type = "hidden";+ input.name = "delete[" + elementName + "][]";+ input.value = id;+ form.append(input);+ }+ }}- return row.remove();+ return row ? row.remove() : undefined;}function slugify(str) {@@ -63,32 +107,42 @@ function addTab(element, callback) {let navTemplate = nav.querySelector(".tab-nav-template");let contentTemplate = content.querySelector(".tab-content-template");- let newId = Math.floor(Math.random() * 10000);+ if (!navTemplate || !contentTemplate) {+ return;+ }+ let id = newId();navTemplate = navTemplate.cloneNode(true);navTemplate.classList.remove("tab-nav-template", "d-none");contentTemplate = contentTemplate.cloneNode(true);contentTemplate.classList.remove("tab-content-template", "d-none");- navTemplate.querySelector("a").setAttribute("href", "#tab-" + newId);- contentTemplate.setAttribute("id", "tab-" + newId);+ navTemplate.querySelector("a")?.setAttribute("href", "#tab-" + id);+ contentTemplate.setAttribute("id", "tab-" + id);contentTemplate = contentTemplate.outerHTML;- contentTemplate = contentTemplate.replaceAll('[0]', '[' + newId + ']').replaceAll('-0-', '-' + newId + '-').replaceAll('disabled', '');+ contentTemplate = contentTemplate.replaceAll('[0]', '[' + id + ']').replaceAll('[#tab#]', '[' + id + ']').replaceAll('#tab#', id).replaceAll('-0-', '-' + id + '-');nav.append(navTemplate);++ //contentTemplate = addDataTemplate(content, contentTemplate);let contentElement = generateElements(contentTemplate)[0];+ contentElement.querySelectorAll("[disabled]").forEach(e => e.removeAttribute("disabled"));+content.append(contentElement);if (callback) {callback(navTemplate, contentElement);}- document.querySelectorAll("#tab-" + newId +" .product_option_id").forEach(e => {+ //keep hidden inputs disabled+ document.querySelectorAll(".d-none input, .d-none select").forEach(e => e.setAttribute("disabled", "true"));++ document.querySelectorAll("#tab-" + id + " .product_option_id").forEach(e => {e.dispatchEvent(new Event("change"));});- navTemplate.querySelector("a").click();+ navTemplate.querySelector("a")?.click();}function removeTab(element, elementName) {@@ -96,23 +150,36 @@ function removeTab(element, elementName) {let nav = element.closest(".nav");if (elementName) {- let form = element.closest("form");- form.append(generateElements('<input type="hidden" name="delete[' + elementName + '][]" value="' + link.dataset.id + '">')[0]);+ let id = link.dataset.id;+ if (id && id !== "#") {+ let form = element.closest("form");+ if (form) {+ let input = document.createElement("input");+ input.type = "hidden";+ input.name = "delete[" + elementName + "][]";+ input.value = id;+ form.append(input);+ }+ }}- const bsTab = bootstrap.Tab.getOrCreateInstance(nav.querySelector(".nav-item:not(.d-none) a"));- bsTab.show();- document.querySelector(link.getAttribute("href")).remove();+ let nextTab = nav.querySelector(".nav-item:not(.d-none) a");+ if (nextTab && window.bootstrap?.Tab) {+ bootstrap.Tab.getOrCreateInstance(nextTab).show();+ }+ let target = link.getAttribute("href");+ if (target) {+ document.querySelector(target)?.remove();+ }return link.parentNode.remove();- return false;}function datetime() {let now = new Date();now.setMinutes(now.getMinutes() - now.getTimezoneOffset());- now.setMilliseconds(null)- now.setSeconds(null)+ now.setMilliseconds(0)+ now.setSeconds(0)return now.toISOString().slice(0, 19).replace('T', ' ');}@@ -120,8 +187,8 @@ function datetime() {function date() {let now = new Date();now.setMinutes(now.getMinutes() - now.getTimezoneOffset());- now.setMilliseconds(null)- now.setSeconds(null)+ now.setMilliseconds(0)+ now.setSeconds(0)return now.toISOString().slice(0, 10);}@@ -133,21 +200,28 @@ function addRow(element) {let table = element.closest("table");let template = table.querySelector("tr.template").cloneNode(true);template.classList.remove("template", "d-none");- let newId = Math.floor(Math.random() * 10000);+ let id = newId();- template.querySelectorAll("input,select", template).forEach(e => e.removeAttribute("disabled"));+ template.querySelectorAll("input,select").forEach(e => e.removeAttribute("disabled"));template = template.outerHTML;- template = template.replaceAll('[0]', '[' + newId + ']').- replaceAll('[#]', '[' + newId + ']');+ template = template.replaceAll('[0]', '[' + id + ']').+ replaceAll('[#]', '[' + id + ']');- table.querySelector("tbody").append(generateElements(template)[0]);- return element;+ let newEl = generateElements(template)[0];+ table.querySelector("tbody")?.append(newEl);+ return newEl;}let optionValues = [];function optionTypeChange(element) {+ if (typeof productOption === "undefined" || !productOption[element.value]) {+ return;+ }let tab = element.closest(".tab-pane");+ if (!tab) {+ return;+ }let optionValueId = element.value;let option = productOption[element.value];let optionType = option['type'];@@ -164,17 +238,23 @@ function optionTypeChange(element) {}function setValues(values){- let options = "";- for (id in values) {- options += "<option value='"+ id +"'>" + values[id] + "</option>";- }- tab.querySelector(".values select.option_value", tab).innerHTML = options;+ let select = tab.querySelector(".values select.option_value");+ if (!select) {+ return;+ }+ select.innerHTML = "";+ Object.entries(values).forEach(([valueId, valueName]) => {+ let option = generateElements("<option></option>")[0];+ option.value = valueId;+ option.textContent = valueName;+ select.append(option);+ });}if (!optionValues[optionValueId]) {- fetch(window.location.pathname + '?module=product/product&action=optionValuesAutocomplete&option_id=' + optionValueId)+ fetch(window.location.pathname + '?module=product/product&action=optionValuesAutocomplete&option_id=' + encodeURIComponent(optionValueId)).then((response) => {- if (!response.ok) { throw new Error(response) }+ if (!response.ok) { throw new Error(response.statusText || response.status) }return response.json()}).then((values) => {@@ -182,14 +262,29 @@ function optionTypeChange(element) {setValues(values);}).catch(error => {- console.log(error.statusText);- displayToast("danger", "Error", "Error saving!");+ console.error(error);+ displayToast("danger", "Error", "Error loading options!");});} else {setValues(optionValues[optionValueId]);}}++function addAllOptionsValues(element) {+ let table = element.closest(".tab-pane ").querySelector("table");+ let row = addRow(table);+ let dropdown = row.querySelector("[data-v-option-value-option_value_id]");+ dropdown.selectedIndex = 0;++ for (let i = 1;i < dropdown.childElementCount;i++) {+ row = addRow(table);+ dropdown = row.querySelector("[data-v-option-value-option_value_id]");+ dropdown.selectedIndex = i;+ console.log(row, dropdown, i);+ }++}// Datelet datepicker = function (e) {let element = e.target.closest('input.date, input[type="date"]');@@ -199,6 +294,11 @@ let datepicker = function (e) {singleDatePicker: true,autoApply: true,autoUpdateInput: false,+ /*+ ranges: {+ 'Today': [moment().startOf('day'), moment().endOf('day')],+ 'Yesterday': [moment().subtract(1, 'days').startOf('day'), moment().subtract(1, 'days').endOf('day')],+ },*/locale: {format: 'YYYY-MM-DD'}@@ -228,9 +328,12 @@ let daterangepicker = function (e) {'This Year': [moment().startOf('year').startOf('month').startOf('day'), moment().endOf('year').endOf('month').endOf('day')],},locale: {+ //format: "YYYY-MM-DD HH:mm:ss",format: "YYYY-MM-DD",}- });+ }/*, function (start, end) {+ this.element.value = start.format('YYYY-MM-DD') + " - " + end.format('YYYY-MM-DD');+ }*/);}}@@ -293,16 +396,27 @@ function generateElements(html) {}function togglePasswordInput(element, input) {- let password = document.getElementById(input) || element.parentNode.querySelector("[type=text],[type=password]");+ let password = (input && document.getElementById(input)) || element.parentNode?.querySelector("[type=text],[type=password]");+ if (!password) {+ return;+ }+ let use = element.querySelector("use");+ if (use) {+ let base = (use.getAttribute("href") || "").split("#")[0];+ use.setAttribute("href", base + (password.type == "password" ? "#eye" : "#eye-off"));+ } else {+ let icon = element.querySelector("i");+ if (password.type == "password") {+ icon?.classList.add("icon-eye-outline");+ icon?.classList.remove("icon-eye-off-outline");+ } else {+ icon?.classList.remove("icon-eye-outline");+ icon?.classList.add("icon-eye-off-outline");+ }+ }if (password.type == "password") {- password.type = "text";- let i = element.querySelector("i")- i.classList.add("icon-eye-outline")- i.classList.remove("icon-eye-off-outline");+ password.type = "text";} else {password.type = "password";- let i = element.querySelector("i")- i.classList.remove("icon-eye-outline")- i.classList.add("icon-eye-off-outline");}}diff --git a/public/js/admin/heartbeat.js b/public/js/admin/heartbeat.jsindex 3b4791b..a478cc8 100755--- a/public/js/admin/heartbeat.js+++ b/public/js/admin/heartbeat.js@@ -1,76 +1,115 @@/** Keep session open to avoid seeing login screen if not active for a few minutes, if session still expires login modal is shown.-*/+ */++function bindHeartbeatLogin(modalEl) {+ if (modalEl.dataset.loginBound) {+ return;+ }++ modalEl.dataset.loginBound = "1";++ modalEl.addEventListener("submit", function (e) {+ let form = e.target.closest("form");+ if (!form) {+ return;+ }++ e.preventDefault();++ let loginButton = modalEl.querySelector('.btn-login');+ let loading = loginButton?.querySelector('.loading');+ let text = loginButton?.querySelector('.button-text');++ if (loading) loading.classList.remove('d-none');+ if (text) text.classList.add('d-none');++ fetch(window.location.pathname + '?module=user/login&modal=true', {+ method: "POST",+ headers: {+ "X-Requested-With": "XMLHttpRequest",+ "Content-Type": "application/x-www-form-urlencoded",+ },+ body: new URLSearchParams(new FormData(form))+ })+ .then((response) => {+ if (!response.ok) {+ throw new Error(response.statusText || response.status);+ }+ return response.text();+ })+ .then(data => {+ //if no error message shown then hide login modal+ if (data.indexOf("data-v-notification-error") == -1) {+ bootstrap.Modal.getOrCreateInstance(modalEl).hide();+ } else {+ //if there are errors show login form with error message+ modalEl.querySelector(".modal-body").innerHTML = data;+ }+ })+ .catch(error => {+ console.error(error);+ if (typeof displayToast === "function") {+ displayToast("danger", "Login", "Error!");+ }+ })+ .finally(() => {+ if (loading) loading.classList.add('d-none');+ if (text) text.classList.remove('d-none');+ });++ return false;+ });+}++function heartbeatLogin(modalEl) {+ let modal = bootstrap.Modal.getOrCreateInstance(modalEl);+ let body = modalEl.querySelector(".modal-body");++ if (!body) {+ return;+ }++ //the form is already loaded, simply show the modal again+ if (body.querySelector("form")) {+ modal.show();+ return;+ }++ fetch(window.location.pathname + '?module=user/login&modal=true')+ .then((response) => {+ if (!response.ok) {+ throw new Error(response.statusText || response.status);+ }+ return response.text();+ })+ .then(formHtml => {+ body.innerHTML = formHtml;+ bindHeartbeatLogin(modalEl);+ modal.show();+ })+ .catch(error => console.error(error));+}let HeartBeat = setInterval(function () {fetch(window.location.pathname + '?action=heartbeat').then((response) => {- if (!response.ok) { throw new Error(response) }- return response.text()- })+ if (!response.ok) {+ throw new Error(response.statusText || response.status);+ }+ return response.text();+ }).then(sessionStatus => {- if (sessionStatus != "ok") {- if (!document.getElementById("login")) {- fetch(window.location.pathname + '?module=user/login&modal=true')- .then(response => {- if (!response.ok) { throw new Error(response) }- return response.text();- })- .then(formHtml => {- document.querySelector("#heartBeatLogin .modal-body").innerHTML = formHtml;- let login = document.getElementById('heartBeatLogin');- const heartBeatLogin = bootstrap.Modal.getOrCreateInstance(login);- heartBeatLogin.style.display = "";- login.addEventListener("submit", function(e) {- let form = e.target.closest("form");- if (form) {- //$("#heartBeatLogin [data-v-notifications]").remove();-- document.querySelector('.btn-login .loading').classList.remove('d-none');- document.querySelector('.btn-login .button-text').classList.add('d-none');-- fetch(window.location.pathname + '?module=user/login&modal=true', { method: "POST",- headers: {- //"Content-Type": "application/json",- 'Content-Type': 'application/x-www-form-urlencoded',- },- body: new URLSearchParams(new FormData(form))})- .then((response) => {- if (!response.ok) { throw new Error(response) }- return response.text()- })- .then(data => {- //if no error message shown then hide login modal- if (data.indexOf("data-v-notification-error") == -1) {- heartBeatLogin.style.display = "none";- } else {- //if there are errors show login form with error message- document.querySelector("#heartBeatLogin .modal-body").innerHTML = data;- }+ if (sessionStatus.trim() === "ok") {+ return;+ }- document.querySelector('.btn-login .loading').classList.add('d-none');- document.querySelector('.btn-login .button-text').classList.remove('d-none');- })- .catch(error => {- document.querySelector('.btn-login .loading').classList.add('d-none');- document.querySelector('.btn-login .button-text').classList.remove('d-none');- console.log(error.statusText);- displayToast("danger", "Login", "Error!");- });--- e.preventDefault();- return false;- }- });- }).catch(error => {- console.log(error.statusText);- });- }+ let modalEl = document.getElementById("heartBeatLogin");+ if (modalEl) {+ heartbeatLogin(modalEl);}- }).catch(error => {- console.log(error.statusText);- });+ })+ .catch(error => console.error(error));}, 3 * 60 * 1000);//3 minutesexport {HeartBeat};diff --git a/public/js/admin/revisions.js b/public/js/admin/revisions.jsindex 106a2c8..976d7cd 100644--- a/public/js/admin/revisions.js+++ b/public/js/admin/revisions.js@@ -1,12 +1,25 @@-function revisionAction(action, data, callback) {- fetch(window.location.pathname + "?module=content/revisions&action=" + action + "&" + (new URLSearchParams(data)).toString())+function revisionAction(action, data, callback, method = "GET") {+ let url = window.location.pathname + "?module=content/revisions&action=" + encodeURIComponent(action) + "&" + (new URLSearchParams(data)).toString();+ let options = {+ method,+ headers: {+ "X-Requested-With": "XMLHttpRequest",+ },+ };++ if (method === "POST") {+ options.headers["Content-Type"] = "application/x-www-form-urlencoded";+ options.body = new URLSearchParams({csrf: document.querySelector('[name=csrf]')?.value ?? ""});+ }++ fetch(url, options).then((response) => {if (!response.ok) { throw new Error(response) }return response.json()}).then(callback).catch(error => {- console.log(error.statusText);+ console.log(error?.statusText ?? error);displayToast("danger", "Revision", "Error!");});}@@ -22,15 +35,15 @@ function revision(childElement) {document.querySelector(".revisions")?.addEventListener("click", function (e) {let element = e.target.closest(".btn-load");if (element) {+ e.preventDefault();let data = revision(element);let contentEditor = tinymce.get( element.closest(".tab-pane").querySelector("[data-v-" + data.type + "-content-content]").id );revisionAction("revision", data, function (data) {- if (data.content) {+ if (data.content && contentEditor) {contentEditor.setContent(data["content"]);displayToast("success", "Revision", data["created_at"] + " Revision loaded!");}});- //e.preventDefault();return false;}});@@ -54,19 +67,24 @@ document.querySelector(".revisions").addEventListener("click", function (e) {document.querySelector(".revisions")?.addEventListener("click", function (e) {let element = e.target.closest(".btn-delete");if (element) {+ e.preventDefault();let data = revision(element);let item = element.closest("[data-v-revision]");let tab = element.closest(".tab-pane");- let count = tab.querySelector("[data-v-" + data.type + "-content-revision_count]");+ let count = tab?.querySelector("[data-v-" + data.type + "-content-revision_count]");if (confirm('Are you sure?')) {revisionAction("delete", data, function (data) {displayToast("success", "Revision", "Revision deleted!");- item.remove();- count.html(Math.max(count.html() - 1, 0));- });+ item?.remove();+ if (count) {+ let current = parseInt(count.textContent, 10);+ if (!isNaN(current)) {+ count.textContent = Math.max(current - 1, 0);+ }+ }+ }, "POST");}- //e.preventDefault()return false;}});diff --git a/public/js/app.js b/public/js/app.jsindex ae103ae..38e097f 100755--- a/public/js/app.js+++ b/public/js/app.js@@ -23,6 +23,14 @@ window.VvvebTheme = window.VvvebTheme || {ajax:{}};window.VvvebApp = window.VvvebApp || {};window.VvvebApp.path = document.currentScript.src.replace(/\/public.+$|assets-cache.+$|\/js.+$/, '');+function escapeHtml(value) {+ return String(value ?? '').replace(/[&<>"']/g, function (char) {+ return {'&': '&', '<': '<', '>': '>', '"': '"', "'": '''}[char];+ });+}++window.VvvebApp.escapeHtml = escapeHtml;+VvvebTheme.Ajax = {call: function(url, parameters, element, selector, callback, requestType = "POST") {if (!url) {@@ -31,18 +39,18 @@ VvvebTheme.Ajax = {}if (!selector) {- url += '&_component_ajax=' + parameters["component"] + '&_component_id=' + parameters["component_id"];+ url += (url.indexOf('?') > -1 ? '&' : '?') + '_component_ajax=' + encodeURIComponent(parameters["component"] ?? '') + '&_component_id=' + encodeURIComponent(parameters["component_id"] ?? '');}let loading = element?.querySelector('.loading');let btn = element?.querySelector('.button-text');- if (loading && loading.classList.contains("d-none")) {+ if (loading && btn && loading.classList.contains("d-none")) {loading.classList.remove('d-none');btn.classList.add('d-none');}- if (element?.hasAttribute("button")) {+ if (element?.matches?.("button, input[type=submit]")) {element.setAttribute("disabled", "true");}@@ -115,12 +123,12 @@ VvvebTheme.Ajax = {let loading = element?.querySelector('.loading');let btn = element?.querySelector('.button-text');- if (loading && btn.classList.contains("d-none")) {+ if (loading && btn && btn.classList.contains("d-none")) {loading.classList.add('d-none');btn.classList.remove('d-none');}- if (element.hasAttribute("button")) {+ if (element?.matches?.("button, input[type=submit]")) {element.removeAttribute("disabled");}})@@ -324,7 +332,15 @@ VvvebTheme.Alert = {show: function(message) {let alertTop = document.querySelector('.alert-top');- alertTop.querySelector(".message").innerHTML = message;+ if (!alertTop) {+ return;+ }++ let messageElement = alertTop.querySelector(".message");+ if (messageElement) {+ messageElement.innerHTML = message;+ }+alertTop.classList.add("show");alertTop.style.display = "block";@@ -414,9 +430,13 @@ VvvebTheme.Gui = {addToCart: function(e) {let element = this.closest("[data-v-vvveb-action]") ?? this;let product = elementProduct(this);+ if (!product) {+ e.preventDefault();+ return false;+ }let img = product.querySelector("img[data-v-product-image], img[data-v-product-image-src], img[data-v-product-image], img[data-v-product-main-image]");- let name = product.querySelector("[data-v-product-name]").textContent ?? "";+ let name = product.querySelector("[data-v-product-name]")?.textContent ?? "";let quantity = product.querySelector('[name="quantity"]')?.value ?? 1;let id = this.dataset.product_id ?? product.dataset.product_id;let options = {quantity};@@ -424,7 +444,7 @@ VvvebTheme.Gui = {if (!id) {id = product.dataset.product_id;if (!id) {- id = product.querySelector('input[name="product_id"]').value;+ id = product.querySelector('input[name="product_id"]')?.value;}}@@ -440,11 +460,11 @@ VvvebTheme.Gui = {}VvvebTheme.Cart.add(id, options, element, ['[data-v-component-cart]', '[data-v-notifications]'], function() {- let src = img.getAttribute("src");+ let src = img?.getAttribute("src") ?? "";VvvebTheme.Alert.show(`<div class="clearfix">- <img class="float-start me-2" height="80" src="${src}">  - <div class="float-start"><a href="#">${name}<a><br> <span class="text-muted">${cart_add_text}<span></span></div>+ <img class="float-start me-2" height="80" src="${escapeHtml(src)}">  + <div class="float-start"><a href="#">${escapeHtml(name)}<a><br> <span class="text-muted">${cart_add_text}<span></span></div></div><div class="row mt-2 g-2 " data-v-if="cart.total_items"><div class="col-6">@@ -476,6 +496,10 @@ VvvebTheme.Gui = {if (!product) {product = this.closest("[data-v-cart-product]");}+ if (!product) {+ e.preventDefault();+ return false;+ }let img = product.querySelector("[data-v-product-image],[data-v-product-image], [data-v-cart-product-image]")?.getAttribute("src") ?? "";let name = product.querySelector("[data-v-product-name]")?.textContent ?? "";let key = this.dataset.key;@@ -484,7 +508,7 @@ VvvebTheme.Gui = {if (!key) {key = product.dataset.key;if (!key) {- key = product.querySelector('input[name="key"]').value;+ key = product.querySelector('input[name="key"]')?.value;}}@@ -507,7 +531,7 @@ VvvebTheme.Gui = {location.reload();}- VvvebTheme.Alert.show('<img height=50 src="' + img + '">   <strong>' + name +'</strong> was removed from cart');+ VvvebTheme.Alert.show('<img height=50 src="' + escapeHtml(img) + '">   <strong>' + escapeHtml(name) + '</strong> was removed from cart');});e.preventDefault();@@ -517,18 +541,23 @@ VvvebTheme.Gui = {addToWishlist: function(e) {let element = this.closest("[data-v-vvveb-action]") ?? this;let product = elementProduct(this);+ if (!product) {+ e.preventDefault();+ return false;+ }let id = this.dataset.product_id ?? product.dataset.product_id;+ let name = product.querySelector("[data-v-product-name]")?.textContent ?? "";let img = product.querySelector("img[data-v-product-image], img[data-v-product-image], img[data-v-cart-product-image], img[data-v-product-main-image]")?.getAttribute("src") ?? "";if (!id) {id = product.dataset.product_id;if (!id) {- id = product.querySelector('input[name="product_id"]').value;+ id = product.querySelector('input[name="product_id"]')?.value;}}VvvebTheme.Wishlist.add(id, element, false, function(data) {- VvvebTheme.Alert.show('<img height=50 src="' + img + '">   <strong>' + name +'</strong> was added to wishlist');+ VvvebTheme.Alert.show('<img height=50 src="' + escapeHtml(img) + '">   <strong>' + escapeHtml(name) + '</strong> was added to wishlist');});e.preventDefault();@@ -538,7 +567,12 @@ VvvebTheme.Gui = {addToCompare: function(e) {let element = this.closest("[data-v-vvveb-action]") ?? this;let product = elementProduct(this);+ if (!product) {+ e.preventDefault();+ return false;+ }let id = this.dataset.product_id ?? product.dataset.product_id;+ let name = product.querySelector("[data-v-product-name]")?.textContent ?? "";let img = product.querySelector("img[data-v-product-image], img[data-v-product-image], img[data-v-cart-product-image], img[data-v-product-main-image]")?.getAttribute("src") ?? "";if (!id) {@@ -550,7 +584,7 @@ VvvebTheme.Gui = {}VvvebTheme.Compare.add(id, element, false, function(data) {- VvvebTheme.Alert.show('<img height=50 src="' + img + '">   <strong>' + name +'</strong> was added to compare');+ VvvebTheme.Alert.show('<img height=50 src="' + escapeHtml(img) + '">   <strong>' + escapeHtml(name) + '</strong> was added to compare');});e.preventDefault();@@ -641,7 +675,10 @@ VvvebTheme.Gui = {loading.classList.remove('d-none');}- document.querySelector(selector).replaceChildren();+ let results = document.querySelector(selector);+ if (results) {+ results.replaceChildren();+ }window.searchDebounce = setTimeout(function () {VvvebTheme.Search.query(parameters, element, selector, function(data) {if (loading) {@@ -722,37 +759,53 @@ function preloadUrl(e) {//ajax urlfunction loadAjax(url, selector, callback = null, params = {}, method = "get") {+ method = String(method || "get").toLowerCase();++ if (!url) url = window.location.href;++ let query = params ? new URLSearchParams(params).toString() : "";let options = {method,withCredentials: true,credentials: 'include'};- if (method == "post" && params) {- options.body = new URLSearchParams(params);+ if (query) {+ if (method === "post") {+ options.headers = {'Content-Type': 'application/x-www-form-urlencoded'};+ options.body = query;+ } else {+ url += (url.indexOf('?') > -1 ? '&' : '?') + query;+ }}- if (!url) url = window.location.href;let progressPercent = 10;- let progressTimer;+ let progressTimer = null;if (VvvebTheme.ajax.progressStatus) {- let progressTimer = () => {+ let tick = () => {if (progressPercent >= 95 || progressPercent == 0) {clearTimeout(progressTimer);+ progressTimer = null;+ return;} else {progressPercent += 5;- setTimeout(progressTimer, 100);+ progressTimer = setTimeout(tick, 100);}VvvebTheme.ajax.progressStatus(progressPercent);}//show progress bar only if takes longer than 1 sec- setTimeout(progressTimer, 1000);+ progressTimer = setTimeout(tick, 1000);}fetch(url, options).then((response) => {//if (!response.ok) { throw new Error(response) }+ if (progressTimer) {+ clearTimeout(progressTimer);+ progressTimer = null;+ }+if (VvvebTheme.ajax.progressStatus && progressPercent > 10) {progressPercent = 100;VvvebTheme.ajax.progressStatus(progressPercent);@@ -823,6 +876,16 @@ function loadAjax(url, selector, callback = null, params = {}, method = "get") {window.dispatchEvent(new CustomEvent("vvveb.loadUrl", {detail: {url, selector}}));}).catch(error => {+ if (progressTimer) {+ clearTimeout(progressTimer);+ progressTimer = null;+ }++ if (VvvebTheme.ajax.progressStatus) {+ progressPercent = 0;+ VvvebTheme.ajax.progressStatus(0);+ }+console.log(error);});}diff --git a/public/js/app/cart.js b/public/js/app/cart.jsindex 836a62c..8cdc336 100644--- a/public/js/app/cart.js+++ b/public/js/app/cart.js@@ -6,7 +6,8 @@ document.addEventListener('change', function (e) {let key = product.dataset.key;let product_id = product.dataset.product_id;let quantity = element.value;- let updateElements = ['#cart-container [data-key="' + key + '"] .price', '#cart-container [data-key="' + key + '"] .total', ".cart-right-column", ".mini-cart"];+ //let updateElements = ['#cart-container [data-key="' + key + '"] .price', '#cart-container [data-key="' + key + '"] .total', ".cart-right-column", ".mini-cart"];+ let updateElements = [".cart-table", ".mini-cart"];delay(() => VvvebTheme.Cart.update(key ?? product_id, {quantity}, element, updateElements), 1000);}@@ -18,7 +19,7 @@ document.addEventListener('click', function (e) {if (element) {let updateElements = [".cart-right-column", ".mini-cart"];if (element.classList.contains("btn-remove-coupon")) {- let coupon = element.parentNode.querySelector(".code").innerHTML;+ let coupon = element.parentNode.querySelector(".code")?.textContent?.trim() ?? "";let container = e.target.closest("[data-v-cart-coupon]");VvvebTheme.Cart.removeCoupon({coupon}, element, updateElements);diff --git a/public/js/app/checkout.js b/public/js/app/checkout.jsindex d089b53..653e4c4 100644--- a/public/js/app/checkout.js+++ b/public/js/app/checkout.js@@ -77,7 +77,7 @@ window.addEventListener('DOMContentLoaded', (e) => {}//if shipping or payment method is selected collapse the accordion- document.querySelector('.accordion-item input[type="radio"]:checked')?.closest("label").dispatchEvent(new MouseEvent('click'));+ document.querySelector('.accordion-item input[type="radio"]:checked')?.closest("label")?.dispatchEvent(new MouseEvent('click'));document.addEventListener("click", function(e) {let element = e.target.closest(".accordion-header label");@@ -147,7 +147,7 @@ document.addEventListener("change", function (e) {addRegionsToSelect(regionSelect, regions[country_id], region_id, self);reloadRegions(element);} else {- fetch(regionsUrl + "&country_id=" + country_id)+ fetch(regionsUrl + "&country_id=" + encodeURIComponent(country_id)).then(response => {if (!response.ok) { throw new Error(response) }return response.json()@@ -176,6 +176,10 @@ document.addEventListener("change", function (e) {function togglePasswordInput(element, input) {let password = document.getElementById(input);+ if (!password) {+ return;+ }+if (password.type == "password") {password.type = "text";let i = element.querySelector("i")@@ -196,7 +200,7 @@ document.addEventListener('click', function (e) {let updateElements = [".cart-right-column", ".mini-cart", ".cart-summary"];VvvebTheme.Cart.module= 'checkout/checkout';if (element.classList.contains("btn-remove-coupon")) {- let coupon = element.parentNode.querySelector(".code").innerHTML;+ let coupon = element.parentNode.querySelector(".code")?.textContent?.trim() ?? "";let container = e.target.closest("[data-v-cart-coupon]");VvvebTheme.Cart.removeCoupon({coupon}, element, updateElements);container.remove();diff --git a/public/js/app/filter.js b/public/js/app/filter.jsindex 4b72297..52b567f 100644--- a/public/js/app/filter.js+++ b/public/js/app/filter.js@@ -46,7 +46,7 @@ function filterChange() {for(const filterName in filters) {for (const filter in filters[filterName]) {- filterText += (filterText ? '&' : '?') + "filter[" + filterName + "][]=" + filters[filterName][filter];+ filterText += (filterText ? '&' : '?') + "filter[" + encodeURIComponent(filterName) + "][]=" + encodeURIComponent(filters[filterName][filter]);}}diff --git a/public/js/app/theme.js b/public/js/app/theme.jsindex cbf6073..e7606e9 100644--- a/public/js/app/theme.js+++ b/public/js/app/theme.js@@ -46,16 +46,25 @@ function navbarSticky(isSticky) {}function setCookie(name, value) {- document.cookie = name + "=" + value + ";";- //try to set cookie to all subdomains- document.cookie = name + "=" + value + ";path=/;domain=." + window.location.host.replace(/^.*?\./, '') + ";";+ value = encodeURIComponent(value);+ document.cookie = name + "=" + value + ";path=/;SameSite=Lax";++ //share the preference between www.example.com and example.com only+ let hostname = window.location.hostname;+ if (hostname.startsWith('www.') && hostname.length > 4) {+ document.cookie = name + "=" + value + ";path=/;domain=." + hostname.slice(4) + ";SameSite=Lax";+ }}let themeSwitch = document.querySelector("#color-theme-switch i");let theme = document.documentElement.dataset.bsTheme;-let themeCookie = document.cookie.match(/theme=(.*?);/);+let themeCookie = document.cookie.match(/(?:^|;\s*)theme=([^;]*)/);if (themeCookie && themeCookie[1]) {- theme = themeCookie[1];+ try {+ theme = decodeURIComponent(themeCookie[1]);+ } catch (error) {+ theme = themeCookie[1];+ }}if (theme && themeSwitch) {@@ -229,7 +238,8 @@ function productPage() {}});- document.querySelector("[data-v-product-price_tax_formatted]").innerText = variant.price_formatted;+ let price = document.querySelector("[data-v-product-price_tax_formatted]");+ if (price) price.innerText = variant.price_formatted;}}@@ -398,9 +408,9 @@ if (!isEditor()) document.addEventListener("click", function(event) {elements = [el];}- if (title) Object.assign(el , title);- if (description) Object.assign(el , title);- if (descPosition) Object.assign(el , title);+ if (title) el.title = title.innerHTML;+ if (description) el.description = description.innerHTML;+ if (descPosition) el.descPosition = descPosition;} else {//elements = [{"href": element.src}];diff --git a/public/js/libs/oembed.js b/public/js/libs/oembed.jsold mode 100644new mode 100755index 7132984..91baa49--- a/public/js/libs/oembed.js+++ b/public/js/libs/oembed.js@@ -214,9 +214,13 @@ const oEmbedProviders = [{regex: /https?:\/\/((play|www)\.)?anghami\.com\/.*/,url: "https://api.anghami.com/rest/v1/oembed.view"- }+ }];+/**+ * Fallback url -> embeddable iframe src transforms for providers without an+ * oEmbed endpoint. $1..$n are replaced with the regex capture groups.+ */const urlTransforms = [{regex: /youtu\.be\/([\w\-_\?&=.]+)/i,@@ -236,7 +240,7 @@ const urlTransforms = [},{regex: /vimeo\.com\/(.*)\/([0-9]+)\?h=(\w+)/,- url: 'player.vimeo.com/video/$2?h=$3&title=0&byline=0',+ url: 'player.vimeo.com/video/$2?h=$3&title=0&byline=0',},{regex: /vimeo\.com\/([0-9]+)/,@@ -244,16 +248,16 @@ const urlTransforms = [},{regex: /vimeo\.com\/(.*)\/([0-9]+)/,- url: 'player.vimeo.com/video/$2?title=0&byline=0',+ url: 'player.vimeo.com/video/$2?title=0&byline=0',},{regex: /(maps|www)\.google\.([a-z]{2,3})\/maps\/(.+)msid=(.+)/,- url: '$2.google.com/maps/ms?msid=$3&output=embed"',- },+ url: '$2.google.com/maps/ms?msid=$3&output=embed',+ },{regex: /(maps|www)\.google\.([a-z]{2,3})\/maps\/@(.+)/,- url: '$1.google.com/maps/embed?center=$3"',- },+ url: '$1.google.com/maps/embed?center=$3',+ },{regex: /dailymotion\.com\/video\/([^_]+)/,url: 'www.dailymotion.com/embed/video/$1',@@ -264,74 +268,96 @@ const urlTransforms = [}];+function notifyError(message) {+ if (typeof displayToast === "function") {+ displayToast("danger", "Error", message);+ } else {+ console.warn(message);+ }+}+async function getOembed(url, maxwidth = 800, maxheight = 600, silent = false) {- let oembedUrl;+ maxwidth = Number.parseInt(maxwidth, 10) || 800;+ maxheight = Number.parseInt(maxheight, 10) || 600;+ const matchTransform = () => {+ for (const transform of urlTransforms) {+ const matches = transform.regex.exec(url);+ if (matches) {+ let newUrl = transform.url;+ for (let i = 0; i < matches.length; i++) {+ newUrl = newUrl.replace('$' + i, () => matches[i] ? matches[i] : '');+ }+ //build the iframe through the DOM so a crafted embed url cannot+ //break out of the src attribute+ const iframe = document.createElement('iframe');+ iframe.src = 'https://' + newUrl;+ iframe.width = String(maxwidth);+ iframe.height = String(maxheight);+ iframe.style.border = '0';+ iframe.loading = 'lazy';+ return iframe.outerHTML;+ }+ }+ };++ //find the first matching provider endpoint+ let oembedUrl;for (const service of oEmbedProviders) {if (service.regex.exec(url)) {- let eurl = encodeURIComponent(url);- oembedUrl = service.url + `?url=${eurl}&maxwidth=${maxwidth}&maxheight=${maxheight}&format=json`;+ oembedUrl = service.url + `?url=${encodeURIComponent(url)}&maxwidth=${maxwidth}&maxheight=${maxheight}&format=json`;+ break;}}+ //no provider matched, try local url transformsif (oembedUrl === undefined) {-- const matchTransform = (url, maxwidth, maxheight) => {- for (const transforms of urlTransforms) {- let matches = transforms.regex.exec(url);- if (matches) {- let newUrl = transforms.url;- for (let i = 0; i < matches.length; i++) {- newUrl = newUrl.replace('$' + i, () => matches[i] ? matches[i] : '');- }- return `<iframe src="https://${newUrl}" width="${maxwidth}" height="${maxheight}" style="border:0;" loading="lazy" ></iframe>`;- }- }- };-- let transform = matchTransform(url, maxwidth, maxheight);- if (transform) {- return {html: transform};- }-- if (!silent) {- let message = 'Embed error: URL did not match any provider.';- displayToast("danger", "Error", message);- }-- return;- }+ const html = matchTransform();- let remoteResponse;- //try to fetch directly, if CORS error use proxy- for (url of [oembedUrl,oEmbedProxyUrl + "&url=" + encodeURIComponent(oembedUrl)]) {+ if (html) {+ return {html};+ }- try {- remoteResponse = await window.fetch(url);+ if (!silent) {+ notifyError('Embed error: URL did not match any provider.');+ }- if (remoteResponse && remoteResponse.status == 200) {- break;+ return null;+ }++ //try to fetch directly, if CORS error use proxy (when configured)+ const urls = [oembedUrl];+ if (typeof oEmbedProxyUrl !== "undefined" && oEmbedProxyUrl) {+ urls.push(oEmbedProxyUrl + "&url=" + encodeURIComponent(oembedUrl));+ }++ let remoteResponse = null;+ for (const fetchUrl of urls) {+ try {+ remoteResponse = await window.fetch(fetchUrl);+ if (remoteResponse?.ok) {+ break;}} catch (error) {- console.log(error);+ console.warn(`Vvveb: could not fetch ${fetchUrl}`, error);}- }+ }- if (!remoteResponse || remoteResponse.status !== 200) {- let message = `Embed error: Could not fetch embed URL.`;- displayToast("danger", "Error", message);- }+ if (!remoteResponse || !remoteResponse.ok) {+ if (!silent) {+ notifyError('Embed error: Could not fetch embed URL.');+ }+ return null;+ }- const json = await remoteResponse.json();+ const json = await remoteResponse.json();- if (json.html === undefined) {- const message = `Eembed error: ${message}`;- displayToast("danger", "Error", message);- return;- }-- //response = { url: url, html: json.html, poster: json.thumbnail_url };- response = json;+ if (!json || json.html === undefined) {+ if (!silent) {+ notifyError('Embed error: invalid oEmbed response.');+ }+ return null;+ }- return response;+ return json;}diff --git a/public/js/libs/tinymce-dist b/public/js/libs/tinymce-distindex 3d62192..2389164 160000--- a/public/js/libs/tinymce-dist+++ b/public/js/libs/tinymce-dist@@ -1 +1 @@-Subproject commit 3d6219296c9a92c87337bb38fb502a469ac1167f+Subproject commit 2389164632e1b6e23cc8a9322fc16776d6985192diff --git a/public/js/libs/tinymce-options.js b/public/js/libs/tinymce-options.jsindex 038db79..1e54a5c 100644--- a/public/js/libs/tinymce-options.js+++ b/public/js/libs/tinymce-options.js@@ -1,6 +1,12 @@var noWrapNodes = "p > img, p > video, p > figure, p > iframe";var wrapNodes = ['B','I','SPAN', 'TABLE', 'P', 'H1', 'H2', 'H3', 'H4'];+function escapeHtmlAttribute(value) {+ return String(value ?? '').replace(/[&<>"']/g, function (char) {+ return {'&': '&', '<': '<', '>': '>', '"': '"', "'": '''}[char];+ });+}+function fixWrapper(doc){let body = doc.body;@@ -68,9 +74,15 @@ const tinymce_image_upload_handler = (blobInfo, progress) => new Promise((resolvreturn;}- const json = JSON.parse(xhr.responseText);+ let json;+ try {+ json = JSON.parse(xhr.responseText);+ } catch (err) {+ reject('Invalid JSON: ' + xhr.responseText);+ return;+ }- if (!json || typeof json[0].file != 'string') {+ if (!Array.isArray(json) || !json[0] || typeof json[0].file != 'string') {reject('Invalid JSON: ' + xhr.responseText);return;}@@ -112,21 +124,26 @@ var tinyMceOptions = {args.content = '';getOembed(url, 800, 600, true).then(response => {if (response && response.html) {- editor.insertContent( '<div class="iframe" data-url="' + url + '" data-component-iframe>' + response.html.replace('<iframe ','<iframe class="align-center" ') + '</div>' );+ editor.insertContent( '<div class="iframe" data-url="' + escapeHtmlAttribute(url) + '" data-component-iframe>' + response.html.replace('<iframe ','<iframe class="align-center" ') + '</div>' );let arr = editor.contentDocument.getElementsByTagName('script');for (let n = 0; n < arr.length; n++) {let script = arr[n];- if (!script.hasAttribute("type")) continue;//process only new scripts that have the tinymce attribute+ //process only new scripts that have the tinymce sanitized src attribute+ let src = script.getAttribute("data-mce-src");+ //only allow http(s) and relative script urls from embeds+ if (!src || !/^(https?:\/\/|\/\/|\/)/i.test(src)) continue;let newScript = editor.contentDocument.createElement("script");- newScript.src = script.src;+ newScript.src = src;script.replaceWith(newScript);}} else {editor.insertContent(url);}}).catch(error => {- //editor.insertContent(url);+ //insert the raw url if oembed fails so the pasted content is not lost+ editor.insertContent(url);+ console.error('oEmbed failed:', error);});}},@@ -187,20 +204,21 @@ var tinyMceOptions = {editor.insertContent(galleryHTML);let node = editor.selection.getNode();let gallery = node.closest('[data-component-gallery]');+ if (gallery) {gallery.setAttribute( 'data-mce-selected', '2' );let img = gallery.querySelector("img");- editor.selection.select(img);-+ if (img) editor.selection.select(img);+ }if (!Vvveb.MediaModal) {Vvveb.MediaModal = new MediaModal(true);Vvveb.MediaModal.mediaPath = mediaPath;}- Vvveb.MediaModal.type = "multitple";+ Vvveb.MediaModal.type = "multiple";Vvveb.MediaModal.open(null, function (src, file, files) {if (src) {let imgs = "";- for (img of src.split(",")) if (img) {+ for (let img of src.split(",")) if (img) {imgs +='<div class="item"><a href="' + img + '">' + editor.dom.createHTML('img', {src: img,@@ -222,7 +240,10 @@ var tinyMceOptions = {//editor.fire( 'cut' );let node = editor.selection.getNode();let gallery = node.closest('[data-component-gallery]');- editor.selection.setNode(gallery.prevElementSibling);+ if (!gallery) return;+ if (gallery.previousElementSibling) {+ editor.selection.setNode(gallery.previousElementSibling);+ }gallery.remove();}} );@@ -245,7 +266,7 @@ var tinyMceOptions = {Vvveb.MediaModal.open(null, function (src, file, files) {if (src) {let imgs = "";- for (img of src.split(",")) if (img) {+ for (let img of src.split(",")) if (img) {imgs +='<div class="item"><a href="' + img + '">' + editor.dom.createHTML('img', {src: img,@@ -463,7 +484,7 @@ var tinyMceOptions = {Vvveb.MediaModal.open(null, function (src, file, files) {if (src) {let imgs = "";- for (img of src.split(",")) if (img) {+ for (let img of src.split(",")) if (img) {imgs +='<div><a href="' + img + '">' + editor.dom.createHTML('img', {src: img,@@ -473,7 +494,6 @@ var tinyMceOptions = {editor.insertContent(imgs);}});- //editor.fire("blur");editor.dispatch("blur");}});