Files
plugi/plugi-core/dist/PageBuilderBody.js
T

1175 lines
44 KiB
JavaScript

$(".gjs-editor").append($("#toggle-sidebar"));
$(".gjs-pn-panels").prepend($("#sidebar-header"));
$(".gjs-pn-panels").append($("#sidebar-bottom-buttons"));
$("#toggle-sidebar").click(function() {
$("#gjs").toggleClass("sidebar-collapsed");
triggerEditorResize();
});
autoCollapseSidebar();
window.editor.on("run:open-sm", function(editor2) {
$(".gjs-trt-traits").parent().parent().css("display", "none");
$(".gjs-sm-sectors").parent().parent().css("display", "block");
$("#gjs-sm-advanced .gjs-sm-properties").append($(".gjs-clm-tags"));
});
window.editor.on("run:open-tm", function(editor2) {
$(".gjs-sm-sectors").parent().parent().css("display", "none");
$(".gjs-trt-traits").parent().parent().css("display", "block");
});
window.editor.on("block:drag:start", function(block) {
autoCollapseSidebar();
});
window.editor.on("rteToolbarPosUpdate", function(toolbarPosition) {
if (!window.editor || !window.editor.getSelected())
return;
let selectedDomComponent = window.editor.getSelected().getEl();
if (!selectedDomComponent)
return;
setTimeout(function() {
let $toolbar = $(".gjs-rte-toolbar").first();
let toolbarInUpperHalf = $toolbar.offset().top < toolbarPosition.elementTop + 0.5 * toolbarPosition.elementHeight;
if (toolbarInUpperHalf) {
let newTop = toolbarPosition.elementTop - $toolbar.height();
if (newTop > 0) {
$toolbar.css("top", newTop + "px");
}
}
}, 0);
});
function autoCollapseSidebar() {
if ($(window).width() < 1e3) {
$("#gjs").addClass("sidebar-collapsed");
triggerEditorResize();
}
}
function triggerEditorResize() {
window.editor.trigger("change:canvasOffset canvasScroll");
}
let backspaceIsPressed = false;
$(document).keydown(function(event) {
if (event.which === 8)
backspaceIsPressed = true;
}).keyup(function(event) {
if (event.which === 8)
backspaceIsPressed = false;
});
$(window).on("beforeunload", function(event) {
if (backspaceIsPressed)
event.preventDefault();
});
function addBlockSearch() {
$(".gjs-blocks-cs").prepend($("#block-search"));
}
window.addEventListener("message", onMessage, false);
function onMessage(event) {
if (event.data === "page-loaded") {
$("#phpb-loading").addClass("loaded");
addBlockSearch();
window.isLoaded = true;
$(window).trigger("pagebuilder-page-loaded");
} else if (event.data === "touch-start") {
window.touchStart();
}
}
$(document).on("input", "#block-search input", function() {
let term = $(this).val().toLowerCase();
$(".gjs-block-category").each(function() {
let atLeastOneMatch = false;
$(this).find(".gjs-block").each(function() {
if (!$(this).data("original-html")) {
$(this).data("original-html", $(this).html());
}
let label = $(this).text();
if (label.toLowerCase().includes(term)) {
$(this).removeClass("d-none");
atLeastOneMatch = true;
let regEx = new RegExp("(" + term + ")", "gi");
let highlightedText = label.replace(regEx, "<b>$1</b>");
$(this).find(".gjs-block-label").html(
$(this).data("original-html").replace(label.trim(), highlightedText)
);
} else {
$(this).addClass("d-none");
}
});
$(this).removeClass("d-none");
if (!atLeastOneMatch) {
$(this).addClass("d-none");
}
});
});
window.customBuilderScripts = {};
window.editor.on("component:create", (component) => {
if (component.components().length) {
let lastChild = component.components().models[component.components().length - 1];
if (lastChild.attributes.type === "script") {
let blockId = component.attributes.attributes["block-id"];
if (blockId === void 0) {
blockId = component.attributes.attributes["id"];
}
let rootComponent = lastChild;
let insideEditablePartOfPage = false;
while (rootComponent.parent()) {
rootComponent = rootComponent.parent();
if (rootComponent.attributes.attributes["phpb-content-container"]) {
insideEditablePartOfPage = true;
break;
}
}
if (insideEditablePartOfPage) {
window.customBuilderScripts[blockId] = lastChild.toHTML();
lastChild.remove();
}
}
}
});
window.editor.on("component:add", function(component) {
if (component.attributes["run-builder-script"] !== void 0) {
let originalCustomBuilderScripts = customBuilderScripts;
window.customBuilderScripts[component.attributes["block-id"]] = customBuilderScripts[component.attributes["run-builder-script"]];
runScriptsOfComponentAndChildren(component);
window.customBuilderScripts = originalCustomBuilderScripts;
delete component.attributes["run-builder-script"];
}
});
window.editor.on("sorter:drag:end", function(event) {
let component = event.modelToDrop;
if (component && component.attributes && (component.attributes["block-id"] || component.attributes["id"])) {
window.runScriptsOfComponentAndChildren(component);
}
for (let instanceName in CKEDITOR.instances) {
CKEDITOR.instances[instanceName].destroy(true);
}
});
window.runScriptsOfComponentAndChildren = function(component) {
runComponentScript(component);
component.components().each(function(child) {
runScriptsOfComponentAndChildren(child);
});
};
function runComponentScript(component) {
let blockId = component.attributes["block-id"];
if (blockId === void 0) {
blockId = component.attributes.attributes["id"];
}
if (blockId && window.customBuilderScripts[blockId] !== void 0) {
let styleIdentifier = component.attributes["style-identifier"];
let $scriptTag = $("<container>").append(window.customBuilderScripts[blockId]);
$scriptTag.find("script").prepend("let inPageBuilder = true;");
$scriptTag.find("script").prepend('let blockSelector = ".' + styleIdentifier + '";');
$scriptTag.find("script").prepend('let block = document.getElementsByClassName("' + styleIdentifier + '")[0];');
$scriptTag.find("script").prepend("(function(){");
$scriptTag.find("script").append("})();");
let scriptTag = document.createElement("script");
scriptTag.type = "text/javascript";
scriptTag.innerHTML = $scriptTag.find("script").html();
window.editor.Canvas.getDocument().body.appendChild(scriptTag);
}
}
function afterGrapesJSLoaded() {
addThemeBlocks();
let scriptTag = document.createElement("script");
scriptTag.type = "text/javascript";
scriptTag.src = window.injectionScriptUrl;
let fullScript = scriptTag.outerHTML + "<script>" + startFirstScript.toString() + startFirstScript.name + "()<\/script>";
window.initialComponents = window.initialComponents.replace("</body>", fullScript + "</body>");
$.each(window.languages, (languageCode, languageTranslation) => {
if (window.pageBlocks[languageCode] === null) {
window.pageBlocks[languageCode] = {};
}
});
activateLanguage(window.currentLanguage);
}
function startFirstScript() {
let scriptTags = document.querySelectorAll("script");
for (let i = 0; i < scriptTags.length; i++) {
let node = scriptTags[i];
if (node.innerHTML.startsWith("var script")) {
let beforeEquals = node.innerHTML.split("=")[0];
let scriptNumber = parseInt(beforeEquals.replace("var script", ""));
if (Number.isInteger(scriptNumber)) {
let startScriptMethodName = "script" + scriptNumber + "Start";
if (typeof window[startScriptMethodName] === "function") {
if (scriptNumber !== 0) {
window[startScriptMethodName]();
}
return false;
}
}
}
}
}
function addThemeBlocks() {
for (let blockSlug in window.themeBlocks) {
let block = window.themeBlocks[blockSlug];
let $blockHtml = $("<container>").append(block.content);
$blockHtml.find("[phpb-blocks-container]").each(function() {
if ($(this).html() !== "" && $(this).html().trim() === "") {
$(this).html("");
}
});
window.themeBlocks[blockSlug].content = $blockHtml.html();
block.content = $blockHtml.html();
editor.BlockManager.add(blockSlug, block);
}
}
$("#language-selector select").on("change", function() {
let selectedLanguage = $(this).find("option:selected").val();
window.switchLanguage(selectedLanguage, function() {
activateLanguage(selectedLanguage);
});
});
window.activateLanguage = function(newLanguage) {
window.currentLanguage = newLanguage;
window.editor.select();
window.editor.DomComponents.clear();
window.editor.DomComponents.componentsById = [];
window.editor.UndoManager.clear();
window.editor.Canvas.getDocument().querySelectorAll("script").forEach(function(node) {
node.remove();
});
window.editor.setComponents(window.initialComponents);
denyAccessToLayoutElements(editor.getWrapper());
window.editor.getWrapper().find("[phpb-content-container]").forEach((container, index) => {
container.set("custom-name", window.translations["page-content"]);
container.components(window.contentContainerComponents[index]);
replacePlaceholdersForRenderedBlocks(container);
applyBlockAttributesToComponents(container);
});
};
$(window).on("pagebuilder-page-loaded", function(event) {
window.editor.getWrapper().find("[phpb-content-container]").forEach((container) => {
restrictEditAccess(container);
window.runScriptsOfComponentAndChildren(container);
});
window.setWaiting(false);
setTimeout(function() {
window.changesOffset = window.editor.getModel().get("changesCount");
window.afterInitialRendering = true;
}, 250);
});
function replacePlaceholdersForRenderedBlocks(component) {
let newComponent = component;
if (component.get("tagName") === "phpb-block") {
let id = component.attributes.attributes.id;
if (window.pageBlocks[window.currentLanguage][id] !== void 0 && window.pageBlocks[window.currentLanguage][id]["html"] !== void 0) {
newComponent = component.replaceWith(window.pageBlocks[window.currentLanguage][id]["html"]);
window.pageBlocks[window.currentLanguage][id]["html"] = "";
}
}
newComponent.get("components").each((childComponent) => replacePlaceholdersForRenderedBlocks(childComponent));
}
function denyAccessToLayoutElements(component) {
if ("phpb-content-container" in component.attributes.attributes)
return;
disableAllEditFunctionality(component);
component.get("components").each((component2) => denyAccessToLayoutElements(component2));
}
window.editor.on("component:selected", function(component) {
if (componentHasBlockSettings(component)) {
$(".gjs-pn-buttons .gjs-pn-btn:nth-of-type(2)").click();
} else if (component.get("type") === "" && componentHasBackground(component)) {
$(".gjs-pn-buttons .gjs-pn-btn:nth-of-type(3)").click();
if ($("#gjs-sm-position").hasClass("gjs-sm-open")) {
$("#gjs-sm-position").find(".gjs-sm-title").click();
}
if (!$("#gjs-sm-background").hasClass("gjs-sm-open")) {
$("#gjs-sm-background").find(".gjs-sm-title").click();
}
}
if (!componentHasBlockSettings(component)) {
setTimeout(function() {
$(".gjs-trt-traits").html('<p class="no-settings">' + window.translations["trait-manager"]["no-settings"] + "</p>");
}, 0);
}
setTimeout(function() {
if (!component.attributes.removable) {
$(".gjs-toolbar .fa-trash-o.gjs-toolbar-item").hide();
}
if (!component.attributes.copyable) {
$(".gjs-toolbar .fa-clone.gjs-toolbar-item").hide();
}
if (!component.attributes.draggable) {
$(".gjs-toolbar .fa-arrows.gjs-toolbar-item").hide();
}
if (!component.attributes.removable && !component.attributes.copyable && !component.attributes.draggable) {
window.editor.select(component.parent());
}
let blockSlug = component.attributes["block-slug"];
if (blockSlug) {
let labelHtml = window.themeBlocks[blockSlug]["label"];
let labelTextParts = labelHtml.split("</div>");
if (labelTextParts.length > 1) {
$(".gjs-toolbar").attr("title", "Bloknaam: " + labelTextParts[1]);
}
}
}, 0);
});
window.editor.on("component:clone", function(component) {
if (!isCloningFromScript) {
let originalComponent = window.editor.getWrapper().find("." + component.attributes["style-identifier"])[0];
if (component.attributes["style-identifier"] !== void 0 && component.attributes["style-identifier"] !== "") {
component.removeClass(component.attributes["style-identifier"]);
delete component.attributes["style-identifier"];
addUniqueClass(component);
}
component.attributes["block-id"] = component.attributes["block-slug"];
if (originalComponent && window.customBuilderScripts[originalComponent.attributes["block-id"]] !== void 0) {
component.attributes["run-builder-script"] = originalComponent.attributes["block-id"];
}
}
});
function componentHasBackground(component) {
let hasBackground = false;
let componentElement = component.getEl();
if (componentElement && componentElement.style) {
let componentStyle = window.getComputedStyle(componentElement);
["background", "background-image", "background-color"].forEach((property) => {
let value = componentStyle.getPropertyValue(property);
if (value !== void 0 && value !== "" && !value.includes("none") && !value.includes("rgba(0, 0, 0, 0)")) {
hasBackground = true;
}
});
}
return hasBackground;
}
function componentHasBlockSettings(component) {
return component.attributes.traits.length > 0;
}
window.editor.on("block:drag:stop", function(droppedComponent) {
if (!droppedComponent || !droppedComponent.attributes || !droppedComponent.attributes.attributes)
return;
let draggedBlockId = generateId$1();
droppedComponent.attributes.attributes["dropped-component-id"] = draggedBlockId;
let parent = droppedComponent.parent();
applyBlockAttributesToComponents(droppedComponent);
parent.components().each(function(child) {
if (child.attributes["dropped-component-id"] === draggedBlockId) {
delete child.attributes["dropped-component-id"];
droppedComponent = child;
}
});
restrictEditAccess(droppedComponent);
window.runScriptsOfComponentAndChildren(droppedComponent);
});
function applyBlockAttributesToComponents(component) {
if (component.attributes.tagName === "phpb-block") {
let container = component.parent();
let clone = cloneComponent(component);
let blockRootComponent;
if (component.attributes.attributes["is-html"] === "false") {
container.components().each(function(componentSibling) {
if (componentSibling.cid === component.cid) {
let wrapperElement = "wrapper" in component.attributes.attributes ? component.attributes.attributes["wrapper"] : "div";
blockRootComponent = component.replaceWith({ tagName: wrapperElement });
blockRootComponent.attributes["is-style-wrapper"] = true;
clone.components().each(function(componentChild) {
blockRootComponent.append(cloneComponent(componentChild));
});
}
});
} else {
container.components().each(function(componentSibling) {
if (componentSibling.cid === component.cid) {
if (clone.components().length === 1) {
let firstChild = cloneComponent(clone.components().models[0]);
blockRootComponent = component.replaceWith(firstChild);
} else {
blockRootComponent = component.replaceWith({ tagName: "div" });
blockRootComponent.attributes["is-style-wrapper"] = true;
clone.components().each(function(componentChild) {
blockRootComponent.append(cloneComponent(componentChild));
});
}
}
});
}
component.remove();
copyAttributes(clone, blockRootComponent, true, false);
addSettingsToSidebar(blockRootComponent);
applyBlockAttributesToComponents(blockRootComponent);
} else {
component.components().each(function(childComponent) {
applyBlockAttributesToComponents(childComponent);
});
}
}
function getCurrentSettingValues(component) {
let relativeIds = [];
let rootComponent = component;
let hasDynamicAncestor = false;
while (rootComponent.parent() && rootComponent.parent().attributes.attributes["phpb-blocks-container"] === void 0 && rootComponent.parent().attributes["is-html"] !== "true" && rootComponent.parent().attributes.attributes["phpb-content-container"] === void 0) {
if (rootComponent.parent().attributes["is-html"] === "false") {
hasDynamicAncestor = true;
}
if (rootComponent.attributes["block-id"] !== void 0) {
relativeIds.push(rootComponent.attributes["block-id"]);
}
rootComponent = rootComponent.parent();
}
let rootId = component.attributes["block-id"];
if (hasDynamicAncestor) {
rootId = rootComponent.attributes["block-id"];
} else {
relativeIds = [];
}
let settings = window.pageBlocks[window.currentLanguage][rootId];
relativeIds.reverse().forEach(function(relativeId) {
if (settings === void 0 || settings.blocks === void 0 || settings.blocks[relativeId] === void 0) {
settings = {};
} else {
settings = settings.blocks[relativeId];
}
});
let settingsValues = {};
if (settings !== void 0 && settings.settings !== void 0 && settings.settings.attributes !== void 0) {
settingsValues = settings.settings.attributes;
}
return settingsValues;
}
function addSettingsToSidebar(component) {
if (window.blockSettings[component.attributes["block-slug"]] === void 0) {
return;
}
component.attributes.settings = {};
let settingValues = getCurrentSettingValues(component);
if (settingValues["style-identifier"] !== void 0) {
component.addClass(settingValues["style-identifier"]);
}
component.attributes["is-updating"] = true;
let settings = window.blockSettings[component.attributes["block-slug"]];
settings.forEach(function(setting) {
let trait = component.addTrait(setting);
if (settingValues[setting["name"]] !== void 0) {
trait[0].setTargetValue(settingValues[setting["name"]]);
} else if (setting["default-value"] !== void 0) {
trait[0].setTargetValue(setting["default-value"]);
}
});
component.attributes["is-updating"] = false;
}
window.editor.on("component:update", function(component) {
if (window.isLoaded !== true || component.attributes["block-slug"] === void 0 || component.attributes["is-updating"] || component.changed["attributes"] === void 0 || $(".gjs-frame").contents().find("#" + component.ccid).length === 0) {
return;
}
let relativeIds = [];
let ancestorToUpdate = component;
let hasDynamicAncestor = false;
while (ancestorToUpdate.parent() && ancestorToUpdate.parent().attributes.attributes["phpb-blocks-container"] === void 0 && ancestorToUpdate.parent().attributes["is-html"] !== "true" && ancestorToUpdate.parent().attributes.attributes["phpb-content-container"] === void 0) {
if (ancestorToUpdate.parent().attributes["is-html"] === "false") {
hasDynamicAncestor = true;
}
if (ancestorToUpdate.attributes["block-id"] !== void 0) {
relativeIds.push(ancestorToUpdate.attributes["block-id"]);
}
ancestorToUpdate = ancestorToUpdate.parent();
}
if (hasDynamicAncestor) {
component = ancestorToUpdate;
} else {
relativeIds = [];
}
component.attributes["is-updating"] = true;
$(".gjs-frame").contents().find("#" + component.ccid).addClass("gjs-freezed");
let container = window.editor.getWrapper().find("#" + component.ccid)[0].parent();
let data = window.getComponentDataInStorageFormat(component);
$.ajax({
type: "POST",
url: window.renderBlockUrl,
data: {
data: JSON.stringify(data),
language: window.currentLanguage
},
success: function(blockHtml) {
let blockId = $(blockHtml).attr("block-id");
window.pageBlocks[window.currentLanguage][blockId] = data.blocks[blockId] === void 0 ? {} : data.blocks[blockId];
component.replaceWith(blockHtml);
replacePlaceholdersForRenderedBlocks(container);
applyBlockAttributesToComponents(container);
restrictEditAccess(container, false, false);
let replacedComponent = findChildViaBlockIdsPath(container, [blockId]);
runScriptsOfComponentAndChildren(replacedComponent);
relativeIds.push(blockId);
let componentToSelect = findChildViaBlockIdsPath(container, relativeIds.reverse());
window.editor.select(componentToSelect);
},
error: function() {
$(".gjs-frame").contents().find("#" + component.ccid).removeClass("gjs-freezed");
component.attributes["is-updating"] = false;
window.toastr.error(window.translations["toastr-component-update-failed"]);
}
});
});
function findChildViaBlockIdsPath(component, blockIds) {
if (blockIds.length === 0) {
return component;
}
let result = null;
component.forEachChild(function(child) {
if (child.attributes["block-id"] === blockIds[0]) {
result = findChildViaBlockIdsPath(child, blockIds.slice(1));
return false;
}
});
component.forEachChild(function(child) {
let childResult = findChildViaBlockIdsPath(child, blockIds);
if (childResult !== null) {
result = childResult;
return false;
}
});
return result;
}
let isCloningFromScript = false;
window.cloneComponent = function(component) {
isCloningFromScript = true;
let clone = component.clone();
deepCopyAttributes(component, clone);
isCloningFromScript = false;
return clone;
};
function deepCopyAttributes(component, clone) {
copyAttributes(component, clone, false, true);
for (let index = 0; index < component.components().length; index++) {
let componentChild = component.components().models[index];
let cloneChild = clone.components().models[index];
deepCopyAttributes(componentChild, cloneChild);
}
}
function copyAttributes(component, targetComponent, copyGrapesAttributes, copyHtmlElementAttributes) {
let componentAttributes = component.attributes.attributes;
for (let attribute in componentAttributes) {
if (copyHtmlElementAttributes) {
targetComponent.attributes.attributes[attribute] = componentAttributes[attribute];
}
if (copyGrapesAttributes) {
targetComponent.attributes[attribute] = componentAttributes[attribute];
}
}
}
function restrictEditAccess(component, directlyInsideDynamicBlock = false, allowEditableComponents = true) {
disableAllEditFunctionality(component);
if (component.attributes.attributes["phpb-content-container"] !== void 0) {
component.set({
droppable: true,
hoverable: true
});
} else if (component.attributes["block-slug"] !== void 0) {
component.find("[phpb-hide-if-not-editable]").forEach((element) => {
if (allowEditableComponents || window.afterInitialRendering) {
element.addClass("editable");
} else {
element.removeClass("editable");
}
});
let permissions = {
selectable: true,
hoverable: true
};
if (!directlyInsideDynamicBlock) {
permissions = {
removable: true,
draggable: true,
copyable: true,
selectable: true,
hoverable: true,
stylable: true
};
addUniqueClass(component);
}
if (component.attributes["is-html"] === "true") {
directlyInsideDynamicBlock = false;
allowEditableComponents = true;
} else {
directlyInsideDynamicBlock = true;
allowEditableComponents = false;
component.getEl().setAttribute("data-cursor", "default");
}
component.set(permissions);
}
if (component.attributes.attributes["data-raw-content"] !== void 0) {
component.set({ editable: true });
return;
}
if (allowEditableComponents) {
allowEditBasedOnComponentAttributes(component);
if (component.attributes["made-text-editable"] === "true") {
component.attributes.attributes["data-raw-content"] = "true";
let newComponent = component.replaceWith(component.toHTML());
["block-id", "block-slug", "is-html", "style-identifier"].forEach((attribute) => {
newComponent.attributes[attribute] = component.attributes[attribute];
});
restrictEditAccess(newComponent);
return;
}
}
component.get("components").each((component2) => restrictEditAccess(component2, directlyInsideDynamicBlock, allowEditableComponents));
}
function allowEditBasedOnComponentAttributes(component) {
let htmlTag = component.get("tagName");
let textEditableTags = [
//'div','span', // needed for editable bootstrap alert, but cannot be used since divs (block containers) then cannot be removed
"h1",
"h2",
"h3",
"h4",
"h5",
"h6",
"h7",
"p",
"small",
"b",
"strong",
"i",
"em",
"label",
"button",
"ol",
"ul",
"li",
"table"
];
let otherEditableTags = [
"img"
];
let settings = {};
if ("phpb-blocks-container" in component.attributes.attributes) {
settings.hoverable = true;
settings.selectable = true;
settings.droppable = true;
}
if (textEditableTags.includes(htmlTag) || "phpb-editable" in component.attributes.attributes) {
settings.editable = true;
component.attributes["made-text-editable"] = "true";
} else if (otherEditableTags.includes(htmlTag)) {
settings.editable = true;
}
if (componentHasBackground(component)) {
settings.hoverable = true;
settings.selectable = true;
settings.stylable = true;
}
if (htmlTag === "a") {
settings.hoverable = true;
settings.selectable = true;
settings.stylable = true;
settings.removable = true;
}
if (!$.isEmptyObject(settings)) {
component.set(settings);
if (settings.stylable !== void 0 && settings.stylable) {
addUniqueClass(component);
}
}
}
function addUniqueClass(component) {
let componentIdentifier = false;
component.getClasses().forEach((componentClass) => {
if (componentClass.startsWith("ID") && componentClass.length >= 16) {
componentIdentifier = componentClass;
}
});
if (component.attributes["style-identifier"] === void 0) {
component.attributes["style-identifier"] = componentIdentifier ? componentIdentifier : generateId$1();
}
component.addClass(component.attributes["style-identifier"]);
}
function disableAllEditFunctionality(component) {
component.set({
removable: false,
draggable: false,
droppable: false,
badgable: false,
stylable: false,
highlightable: false,
copyable: false,
resizable: false,
editable: false,
layerable: false,
selectable: false,
hoverable: false
});
}
let counter$1 = 0;
function generateId$1() {
return "ID" + (Date.now().toString(36) + Math.random().toString(36).substr(2, 5) + counter$1++).toUpperCase();
}
function waitForGrapesToLoad() {
if (window.grapesJSLoaded) {
afterGrapesJSLoaded();
} else {
setTimeout(waitForGrapesToLoad, 100);
}
}
waitForGrapesToLoad();
window.pageData = {};
window.changesOffset = 0;
window.onbeforeunload = confirmExit;
function confirmExit() {
let changesCount = window.editor.getModel().get("changesCount") - window.changesOffset;
if (changesCount > 0) {
return "Are you sure? There are unsaved changes.";
}
}
$("#save-page").click(function() {
saveAllTranslationsToServer();
});
$(document).bind("keydown", function(e) {
if (e.ctrlKey && e.which === 83) {
window.editor.store();
saveAllTranslationsToServer();
e.preventDefault();
return false;
}
});
window.switchLanguage = function(newLanguage, callback) {
window.setWaiting(true);
saveCurrentTranslationLocally(function() {
applyChangesFromCurrentLanguageToNewLanguage(newLanguage);
let data = window.pageData;
data.blocks = { [newLanguage]: window.pageBlocks[newLanguage] };
$.ajax({
type: "POST",
url: window.renderLanguageVariantUrl,
data: {
data: JSON.stringify(data),
language: newLanguage
},
success: function(response) {
response = JSON.parse(response);
window.pageBlocks[newLanguage] = response.dynamicBlocks ? response.dynamicBlocks : {};
callback();
window.setWaiting(false);
},
error: function(error) {
callback();
console.log(error);
let errorMessage = error.statusText + " " + error.status;
errorMessage = error.responseJSON.message ? errorMessage + ': "' + error.responseJSON.message + '"' : errorMessage;
window.toastr.error(errorMessage);
window.toastr.error(window.translations["toastr-switching-language-failed"]);
}
});
});
};
function applyChangesFromCurrentLanguageToNewLanguage(newLanguage) {
let newLanguageBlocks = window.pageBlocks[newLanguage];
let currentLanguageBlocks = window.pageBlocks[window.currentLanguage];
if (newLanguageBlocks === void 0) {
newLanguageBlocks = currentLanguageBlocks;
} else {
updateNestedBlocks(currentLanguageBlocks, newLanguageBlocks);
for (let blockId in currentLanguageBlocks) {
if (newLanguageBlocks[blockId] === void 0) {
newLanguageBlocks[blockId] = currentLanguageBlocks[blockId];
}
}
}
for (let blockId in currentLanguageBlocks) {
let $currentLanguageBlockHtmlDom = $("<container>" + currentLanguageBlocks[blockId]["html"] + "</container>");
let $newLanguageBlockHtmlDom = $("<container>" + newLanguageBlocks[blockId]["html"] + "</container>");
$currentLanguageBlockHtmlDom.find("[phpb-blocks-container]").each(function(index) {
let currentLanguageBlockContainerHtml = $(this).html();
$newLanguageBlockHtmlDom.find("[phpb-blocks-container]").eq(index).html(currentLanguageBlockContainerHtml);
});
newLanguageBlocks[blockId]["html"] = $newLanguageBlockHtmlDom.html();
}
window.pageBlocks[newLanguage] = newLanguageBlocks;
}
function updateNestedBlocks(currentLanguageBlocks, newLanguageBlocks) {
for (let blockId in currentLanguageBlocks) {
if (newLanguageBlocks[blockId] === void 0) {
continue;
}
for (let subBlockId in currentLanguageBlocks[blockId].blocks) {
let updatedSubBlock = currentLanguageBlocks[blockId].blocks[subBlockId];
let oldSubBlock = newLanguageBlocks[blockId].blocks[subBlockId];
if (!updatedSubBlock || !oldSubBlock) {
continue;
}
let updatedSubBlockMatches = updatedSubBlock.html.match(/phpb-blocks-container(.*)>(.*)</g);
let oldSubBlockMatches = oldSubBlock.html.match(/phpb-blocks-container(.*)>(.*)</g);
if (!updatedSubBlockMatches || !oldSubBlockMatches) {
continue;
}
for (let i = 0; i < updatedSubBlockMatches.length; i++) {
newLanguageBlocks[blockId].blocks[subBlockId].html = newLanguageBlocks[blockId].blocks[subBlockId].html.replace(oldSubBlockMatches[i], updatedSubBlockMatches[i]);
}
}
}
}
function saveCurrentTranslationLocally(callback) {
setTimeout(function() {
let existingCss = window.pageData["css"] ? window.pageData["css"] : window.initialCss;
window.pageData = {
html: [],
components: [],
css: null,
style: null
};
window.pageBlocks[window.currentLanguage] = [];
window.editor.getWrapper().find("[phpb-content-container]").forEach((container, index) => {
let data = getContainerContentInStorageFormat(container);
window.pageData["css"] = mergeCss(existingCss, data.css);
window.pageData["style"] = data.style;
window.pageData["html"][index] = data.html;
window.pageData["components"][index] = data.components;
window.pageBlocks[window.currentLanguage] = { ...window.pageBlocks[window.currentLanguage], ...data.blocks };
window.contentContainerComponents[index] = data.components;
});
if (callback) {
callback();
}
}, 200);
}
function mergeCss(existingCss, newCss) {
if (!existingCss) {
return newCss;
}
let pageBlocksString = JSON.stringify(window.pageBlocks);
let regex = "\\.ID(.*?){(.*?)}";
let matches = existingCss.match(new RegExp(regex, "g"));
if (!matches) {
return newCss;
}
matches.forEach(function(css) {
let selector = css.split("{")[0];
let pageBlocksStringSelector = selector.replace(".", " ").trim();
if (newCss.indexOf(selector) === -1 && pageBlocksString.indexOf(pageBlocksStringSelector) >= 0) {
newCss += css;
}
});
return newCss;
}
function removeOldStyleSelectors(styleComponents) {
let pageBlocksString = JSON.stringify(window.pageBlocks);
let updatedStyleComponents = [];
styleComponents.forEach((styleComponent) => {
if (styleComponent.attributes.selectors.models.length) {
let selector = styleComponent.attributes.selectors.models[0].id;
if (pageBlocksString.includes(selector)) {
updatedStyleComponents.push(styleComponent);
}
}
});
return updatedStyleComponents;
}
function saveAllTranslationsToServer() {
toggleSaving();
saveCurrentTranslationLocally(function() {
$.each(window.languages, (languageCode, languageTranslation) => {
if (languageCode !== window.currentLanguage) {
applyChangesFromCurrentLanguageToNewLanguage(languageCode);
}
});
let data = window.pageData;
data.style = removeOldStyleSelectors(data.style);
data.blocks = window.pageBlocks;
$.ajax({
type: "POST",
url: $("#save-page").data("url"),
data: {
data: JSON.stringify(data)
},
success: function() {
toggleSaving();
window.toastr.success(window.translations["toastr-changes-saved"]);
setTimeout(function() {
window.changesOffset = window.editor.getModel().get("changesCount");
}, 250);
},
error: function(error) {
toggleSaving();
console.log(error);
let errorMessage = error.statusText + " " + error.status;
errorMessage = error.responseJSON.message ? errorMessage + ': "' + error.responseJSON.message + '"' : errorMessage;
window.toastr.error(errorMessage);
window.toastr.error(window.translations["toastr-saving-failed"]);
}
});
});
}
window.getComponentDataInStorageFormat = function(component) {
let container = window.cloneComponent(component.parent());
console.log({
container,
componentParent: component.parent()
});
const componentId = component.attributes["block-id"];
console.log(component.attributes["block-id"]);
container.components().forEach((c) => {
console.log({ c });
if ((c == null ? void 0 : c.attributes["block-id"]) !== componentId) {
c == null ? void 0 : c.remove();
}
});
console.log({
containerL: container.get("components").length,
componentParentL: component.parent().get("components").length
});
return getContainerContentInStorageFormat(container);
};
function getContainerContentInStorageFormat(container) {
let componentReferences = window.editor.DomComponents.componentsById;
window.editor.DomComponents.componentsById = [];
container = window.cloneComponent(container);
let blocksData = replaceDynamicBlocksWithPlaceholders(container).blocks;
let html = window.html_beautify(getContainerHtml(container));
let css = window.editor.getCss();
let style = window.editor.getStyle();
let components = JSON.parse(JSON.stringify(container.get("components")));
window.editor.DomComponents.componentsById = componentReferences;
return {
html,
css,
components,
blocks: blocksData,
style
};
}
function getContainerHtml(container) {
let html = "";
container.get("components").forEach((component) => html += component.toHTML());
let htmlDom = $("<container>" + html + "</container>");
htmlDom.find("phpb-block").each(function() {
$(this).replaceWith('[block slug="' + $(this).attr("slug") + '" id="' + $(this).attr("id") + '"]');
});
return htmlDom.html();
}
function getComponentHtml(component) {
let htmlDom = $("<container>" + component.toHTML() + "</container>");
htmlDom.find("phpb-block").each(function() {
$(this).replaceWith('[block slug="' + $(this).attr("slug") + '" id="' + $(this).attr("id") + '"]');
});
return htmlDom.html();
}
function replaceDynamicBlocksWithPlaceholders(component, parentIsDynamic = false, parentIsHtmlInsideDynamic = false) {
let data = {
current_block: { settings: {}, blocks: {}, html: "", is_html: false },
blocks: {}
};
let newParentIsDynamic = parentIsDynamic;
let newParentIsHtmlInsideDynamic = parentIsHtmlInsideDynamic;
if (component.attributes["block-id"] !== void 0) {
if (component.attributes["is-html"] === "false") {
newParentIsDynamic = true;
newParentIsHtmlInsideDynamic = false;
} else if (parentIsDynamic) {
newParentIsDynamic = false;
newParentIsHtmlInsideDynamic = true;
}
}
component.get("components").forEach(function(childComponent) {
let childData = replaceDynamicBlocksWithPlaceholders(childComponent, newParentIsDynamic, newParentIsHtmlInsideDynamic);
for (let key in childData.current_block.blocks) {
data.current_block.blocks[key] = childData.current_block.blocks[key];
}
for (let key in childData.blocks) {
data.blocks[key] = childData.blocks[key];
}
});
if (!component.parent()) {
return data;
}
if (component.attributes["block-id"] === void 0) {
return data;
}
if (component.attributes["is-html"] === "true") {
if (parentIsDynamic) {
data.current_block["blocks"][component.attributes["block-id"]] = { settings: {}, blocks: {}, html: window.html_beautify(getComponentHtml(component)), is_html: true };
} else {
if (component.attributes["style-identifier"] !== void 0) {
data.current_block["settings"]["attributes"] = { "style-identifier": component.attributes["style-identifier"] };
}
let instanceId = component.attributes["block-id"];
if (!component.attributes["block-id"].startsWith("ID")) {
instanceId = generateId();
}
component.replaceWith({
tagName: "phpb-block",
attributes: {
slug: component.attributes["block-slug"],
id: instanceId
}
});
data.blocks[instanceId] = { settings: data.current_block["settings"], blocks: {}, html: window.html_beautify(getComponentHtml(component)), is_html: true };
data.current_block = { settings: {}, blocks: {}, html: "", is_html: false };
}
} else {
let attributes = {};
component.get("traits").each(function(trait) {
attributes[trait.get("name")] = trait.getTargetValue();
});
data.current_block["settings"]["attributes"] = attributes;
if (component.attributes["style-identifier"] !== void 0) {
data.current_block["settings"]["attributes"]["style-identifier"] = component.attributes["style-identifier"];
}
let instanceId = component.attributes["block-id"];
if (!component.attributes["block-id"].startsWith("ID")) {
instanceId = generateId();
}
component.replaceWith({
tagName: "phpb-block",
attributes: {
slug: component.attributes["block-slug"],
id: instanceId
}
});
if (parentIsDynamic) {
let currentBlockForParent = { settings: {}, blocks: {}, html: "", is_html: false };
currentBlockForParent["blocks"][component.attributes["block-id"]] = data.current_block;
data.current_block = currentBlockForParent;
} else {
data.blocks[instanceId] = data.current_block;
data.current_block = { settings: {}, blocks: {}, html: "", is_html: false };
}
}
return data;
}
let counter = 0;
function generateId() {
return "ID" + (Date.now().toString(36) + Math.random().toString(36).substr(2, 5) + counter++).toUpperCase();
}
window.setWaiting = function(value) {
let wrapper = window.editor.DomComponents.getWrapper();
if (value) {
wrapper.addClass("gjs-waiting");
} else {
wrapper.removeClass("gjs-waiting");
}
};
function toggleSaving() {
let button = $("#save-page");
button.blur();
if (button.hasClass("waiting")) {
button.attr("disabled", false);
button.removeClass("waiting");
button.find(".spinner-border").addClass("d-none");
} else {
button.attr("disabled", true);
button.addClass("waiting");
button.find(".spinner-border").removeClass("d-none");
}
}
window.CKEDITOR.on("instanceReady", function(event) {
event.editor.on("paste", function(event2) {
let result = event2.data.dataValue;
result = result.replace(/<(?!\/?(?:a|table|tr|td|th|thead|tbody|tfoot|caption|col|colgroup|p|ul|ol|li|br|strong|em|b|i|u|strike|sub|sup|h1|h2|h3|h4|h5|h6|blockquote|pre|hr)\b)[^>]+>/gm, "");
result = result.replace(/<(a|table|tr|td|th|thead|tbody|tfoot|caption|col|colgroup|p|ul|ol|li|br|strong|em|b|i|u|strike|sub|sup|h1|h2|h3|h4|h5|h6|blockquote|pre|hr)\b[^>]*>/gm, function(match, tag) {
if (tag === "a") {
let href = match.match(/href="([^"]*)"/);
if (!href) {
return match;
}
return '<a href="' + href[1] + '">';
}
if ("|table|tr|td|th|thead|tbody|tfoot|".includes("|" + tag + "|")) {
let style = match.match(/style="([^"]*)"/);
if (!style) {
return match;
}
return "<" + tag + ' style="' + style[1] + '">';
}
return "<" + tag + ">";
});
event2.data.dataValue = result;
});
});
window.CKEDITOR.on("dialogDefinition", function(event) {
let dialogName = event.data.name;
let dialogDefinition = event.data.definition;
if (dialogName === "link") {
let infoTab = dialogDefinition.getContents("info");
dialogDefinition.onLoad = function() {
let dialog = CKEDITOR.dialog.getCurrent();
dialog.getContentElement("info", "linkType").getElement().hide();
dialog.getContentElement("info", "protocol").getElement().hide();
dialog.getContentElement("info", "url").getElement().hide();
};
infoTab.add({
type: "select",
id: "linktype-selector",
label: "Linktype",
"default": "",
items: [
[window.translations["page"], "page"],
["URL", "url"]
],
onChange: function(obj) {
let dialog = CKEDITOR.dialog.getCurrent();
if (obj.data.value === "page") {
dialog.getContentElement("info", "page-selector").getElement().show();
dialog.getContentElement("info", "url-field").getElement().hide();
} else {
dialog.getContentElement("info", "page-selector").getElement().hide();
dialog.getContentElement("info", "url-field").getElement().show();
dialog.getContentElement("info", "url-field").setValue("");
}
},
setup: function(data) {
if (data.type === void 0) {
this.setValue("page");
} else if (data.type === "url" && data.url.url.startsWith("[page id=")) {
this.setValue("page");
} else {
this.setValue(data.type);
}
}
});
infoTab.add({
type: "select",
id: "page-selector",
label: window.translations["page"],
"default": "",
items: window.pages,
onChange: function() {
let dialog = CKEDITOR.dialog.getCurrent();
let page = "[page id=" + this.getValue() + "]";
dialog.setValueOf("info", "url", page);
dialog.setValueOf("info", "protocol", "");
},
setup: function(dialog) {
this.allowOnChange = false;
let pageId = "";
if (dialog.url) {
pageId = dialog.url.url.substr(9, dialog.url.url.length - 10);
}
this.setValue(pageId);
this.allowOnChange = true;
}
});
infoTab.add({
type: "text",
id: "url-field",
label: "URL",
"default": "",
onChange: function() {
let dialog = CKEDITOR.dialog.getCurrent();
let url = this.getValue();
dialog.setValueOf("info", "url", url);
},
setup: function(dialog) {
this.allowOnChange = false;
let url = "";
if (dialog.url) {
url = dialog.url.url;
}
this.setValue(url);
this.allowOnChange = true;
}
});
}
});
window.touchStart = function() {
$("#gjs").addClass("sidebar-collapsed");
};
window.addEventListener("keydown", function(e) {
if (e.ctrlKey && e.key === "s") {
e.preventDefault();
return false;
}
});
window.parent.postMessage("page-loaded", "*");
document.addEventListener("touchstart", (e) => {
window.parent.postMessage("touch-start", "*");
});