/**
*
* newsiteeditor.js - gestion de l'interface de NewSiteEditor
*
* Modifications:
* - 2022/07/12 - V.1.0 0 - B.Bouaphakeo - création
* - 2025/04/14 - V1.0.1 - E.Podvin - fix hover when siteeditor is activated with tinymce
* - 2025/05/06 - V.1.1.0 H.Malezet & C.Nelhomme - Added newFileEditor to edit image and video.
* - 2025/05/09 - V.1.2.0 C.Nelhomme - Added compressorJS and add request to mistralAI
* - 2025/05/31 - V1.3.0 - E.Podvin - add redirections to dashboard and help pages
* - 2025/06/02 - V1.3.1 - E.Podvin - call newsiteeditor/image POST
* - 2025/06/02 - V1.3.2 - E.Podvin - fix toggle on hover when we leave nse
* - 2025/06/03 - V1.4.0 - C.NELHOMME - Added videoEditor, posterEditor, refactor upload function, implements Kserver
* - 2025/06/04 - V1.4.1 - C.NELHOMME - Refactor fntManager using Modal class, add some commentary, renaming fntManager to newDeleteManager, renaming variable startingWith RG_ to normal variable
* - 2025/06/04 - V1.5.0 - C.NELHOMME - Implement SmartButton and abstract class BaseHoverManager and Refactor newDeleteManager and newTranslateManager and moving her into NewSiteEditor function()
* - 2025/06/11 - V1.5.1 - C.NELHOMME - Implement setCreateError to show error in modal, added page smartButton for selecting id of the currznt page
* - 2025/06/12 - V.1.5.2 - C.NELHOMME (Stable test with Hugo) - Fix multiple request to mistral now one by one, when translate/delete is open all the tinymce is now closed, remove poster from video
* @copyright Intersel 2022-2025
*
*
*/
//debugger;
/**
* Todo :
* - Faire en sorte que la poubelle et la traduction puisse pas etre fait au mm moment sinon confliiit
* - Préseletionner le parent si y'a une erreur
* - Afficher erreur si Mistral bug
*/
//Configuration
const { Uppy: UppyConstructor, Dashboard, ImageEditor } = window.Uppy;
const availableLang = Uppy.locales;
const lang = `${document.documentElement.lang.toLowerCase()}_${document.documentElement.lang.toUpperCase()}`;
const baseURL = window.location.origin;
const acceptedImageTypes = [".jpg", ".jpeg", ".png", ".gif", ".webp"];
const acceptedVideoTypes = [".mp4", ".webm"];
const imageTypesWithoutDots = extensionWODot(acceptedImageTypes);
const videoTypesWithoutDots = extensionWODot(acceptedVideoTypes);
function extensionWODot(extension) {
return extension.map((v) => v.replace(".", ""));
}
const managerURL = window.customerManagerUrl; //set in NewSiteEditor plugin
const managerHelpURL = window.helpManagerUrl; //set in NewSiteEditor plugin
/**
* @class Modal
* @description Modal is a class that enable to control easily a modal
*/
class Modal {
/**
*
* @param {string} modalId - The ID of the element where the modal should appear.
*/
constructor(modalId) {
this.modal = document.getElementById(modalId);
this.isOpen = this.modal ? this.modal.classList.contains("open") : false;
}
open() {
if (!this.modal) return;
this.modal.classList.add("open");
document.body.style.overflow = "hidden";
this.isOpen = true;
}
setError(text) {
const nseHeader = this.modal.querySelector('.nseHeader');
const nseError = nseHeader?.querySelector('.alert');
if (!nseHeader || !nseError) return;
nseHeader.style.display = "block";
nseError.textContent = text;
}
close() {
if (!this.modal) return;
this.modal.classList.remove("open");
document.body.style.overflow = "auto";
this.isOpen = false;
}
/**
* Sets the visibility of the modal.
*
* @param {boolean} visible - If true, the modal is opened; if false, it is closed.
*/
setVisible(visible) {
visible ? this.open() : this.close();
}
isVisible() {
return this.isOpen;
}
getModal() {
return this.modal;
}
onBackgroundClick(callback) {
this.modal.addEventListener("click", (e) => {
if (e.target === this.modal) callback();
});
}
onValidate(callback, selector = ".validateBtn") {
const btn = this.modal.querySelector(selector);
if (btn) {
btn.addEventListener("click", () => callback());
}
}
onCloseButtonClick(selector = ".closeBtn") {
const btn = this.modal.querySelector(selector);
if (btn) {
btn.addEventListener("click", () => this.setVisible(false));
}
}
}
/**
* @class SmartButton
* @description SmartButton is a class that enables the creation of a movable button.
*/
class SmartButton {
constructor(buttonId) {
this.button = document.getElementById(buttonId);
if (!this.button) throw new Error("SmartButton not found");
this.isVisible = false;
}
moveTo(x, y) {
Object.assign(this.button.style, {
left: `${x}px`,
top: `${y}px`,
position: "absolute",
});
this.show();
}
show() {
this.button.style.display = "block";
this.isVisible = true;
}
hide() {
this.button.style.display = "none";
this.isVisible = false;
}
setPosition(x, y) {
this.moveTo(x, y);
}
getElement() {
return this.button;
}
onClick(callback) {
this.button.addEventListener("click", () => {
callback();
});
}
}
var NEWSITEEDITOR = (function () {
let version = "1.5.2";
//set data-data for content and title
function dataData(who) {
let obj = {};
//let title;
let field = $(who).attr("field");
let dirty = $(who).attr("dirty");
let editModeOn = $("#edit").css("visibility") != "visible";
const sync = { syncsite: 1 };
//if(field === 'content') ...
if (!editModeOn || dirty == undefined)
{
$(who).attr("dirty", "0");
}
else
{
obj = JSON.parse($(who).attr("data-data"));
if (obj)
{
dirty = (obj[field] == who.innerHTML) ? "0" : "1";
$(who).attr("dirty", dirty);
}
}
if (field == "pagetitle") {
field = "longtitle";
}
if (editModeOn &&
(
who.innerText.trim() === "" ||
who.innerHTML.includes('
')
)
)
{
if (editModeOn) who.innerHTML = " ";
}
obj[field] = who.innerHTML;
Object.assign(obj, sync);
return $(who).attr("data-data", JSON.stringify(obj));
}
// REST : PUT method to put the content of the website in the manager
function saveContent() {
$(".siteeditor").blur(function () {
dataData(this);
if ($(this).attr("dirty") == "1")
{
blapyTools.ajaxSimpleAction(this);
$(this).attr("dirty", "0");
}
});
}
// Settings available for the richtext editor
function TinyMCE() {
$.doTimeout("startTinyMCE", 200, function () {
tinymce.init({
selector: ".siteeditor",
suffix: ".min",
inline: true,
plugins: "link textcolor table preview paste",
menubar: false,
toolbar: [
"undo redo | bold italic underline | link unlink | fontselect fontsizeselect",
// "forecolor backcolor | alignjustify alignleft aligncenter alignright alignfull | numlist bullist outdent indent | table | styleselect",
"forecolor backcolor | alignjustify alignleft aligncenter alignright alignfull | styleselect",
],
powerpaste_word_import: "clean",
powerpaste_html_import: "clean",
paste_auto_cleanup_on_paste: true,
setup: function (editor) {
editor.on("focus", function (event) {
toggleClosestButton(event.target);
});
editor.on("blur", function (event) {
toggleClosestButton(event.target);
});
editor.on("keydown", function (event) {
if (
["ArrowRight", "ArrowLeft", "ArrowUp", "ArrowDown"].includes(
event.code
)
) {
event.stopPropagation();
}
});
},
});
});
}
/**
* @abstract
* @class BaseHoverManager
* An abstract class that provides hover and click state management for a group of DOM elements.
* Extend this class to build custom managers with specific behaviors.
*/
class BaseHoverManager {
/**
*
* @param {string} selector - CSS selector for targeting DOM elements.
* @param {string} [hoverClass="hovered"] - CSS class applied on hover.
* @param {string} [clickedClass="clicked"] - CSS class applied on click.
*/
constructor(selector, hoverClass = "hovered", clickedClass = "clicked") {
this.selector = selector;
this.hoverClass = hoverClass;
this.clickedClass = clickedClass;
this.hoverActive = false;
this.addHoverClass = this.addHoverClass.bind(this);
this.removeHoverClass = this.removeHoverClass.bind(this);
this.toggleHover = this.toggleHover.bind(this);
}
/**
* Use the data-newmanager with value attribute to exclude from the selected elements
*/
getElements() {
return Array.from(document.querySelectorAll(this.selector)).filter(
(el) => el.getAttribute("data-newmanager") !== "false"
);
}
disableHover() {
if (this.hoverActive) {
this.hoverActive = false;
this.onHoverDisabled();
}
}
toggleHover() {
this.hoverActive = !this.hoverActive;
this.getElements().forEach((el) => {
if (this.hoverActive) {
//On supprime chaque instance de TinyMce sinon il s'active lors des clics
tinymce.editors.forEach((ed) => {
try {
ed.remove();
} catch (e) {
console.warn("Erreur suppression éditeur :", ed.id, e);
}
});
el.addEventListener("mouseenter", this.addHoverClass);
el.addEventListener("mouseleave", this.removeHoverClass);
} else {
TinyMCE();
el.removeEventListener("mouseenter", this.addHoverClass);
el.removeEventListener("mouseleave", this.removeHoverClass);
}
this.clearElementState(el);
});
if (!this.hoverActive) {
this.onHoverDisabled?.();
}
}
addHoverClass(e) {
e.currentTarget.classList.add(this.hoverClass);
}
removeHoverClass(e) {
e.currentTarget.classList.remove(this.hoverClass);
}
clearElementState(el) {
}
init() {
}
destroy() {
this.getElements().forEach((e) => e.classList.remove(this.hoverClass, this.clickedClass))
this.smartButton.hide();
}
}
class newDeleteManager extends BaseHoverManager {
constructor(toggleButtonId = "delete", bgModalId = "modalDelete", deleteButtonId = "btnDelete") {
super("[data-deleteid]", "deletable", "inDelete");
this.deleteID = null;
this.bgModal = new Modal(bgModalId);
this.smartButton = new SmartButton("btnDelete");
this.toggleButton = document.getElementById(toggleButtonId);
this.type = "data-deleteType";
this.storeData = this.storeData.bind(this);
this.removeResource = this.removeResource.bind(this);
this.onHoverDisabled = () => {
this.bgModal.setVisible(false);
this.smartButton.hide();
this.deleteID = null;
};
if (this.smartButton.getElement()) {
this.smartButton.onClick(() => {
this.bgModal.setVisible(true);
this.smartButton.hide();
})
this.bgModal.onBackgroundClick(() => this.bgModal.setVisible(false));
this.bgModal.onCloseButtonClick(".cancelBtn");
this.bgModal.onValidate(() => this.removeResource());
}
}
storeData(e) {
const id = e.currentTarget.getAttribute("data-deleteid");
if (id) {
this.deleteID = id;
}
}
init() {
this.getElements().forEach((el) => {
el.addEventListener("click", (e) => {
this.storeData(e);
if (el.classList.contains(this.hoverClass)) {
this.getElements().forEach((otherEl) => {
if (otherEl !== el) {
otherEl.classList.remove(this.hoverClass, this.clickedClass);
}
});
el.classList.add(this.clickedClass);
this.smartButton.setPosition(e.pageX, e.pageY - 20);
}
});
});
if (this.toggleButton) {
this.toggleButton.addEventListener("click", this.toggleHover);
}
}
getType() {
if (!this.deleteID) return null;
const el = document.querySelector(`[data-deleteid="${this.deleteID}"]`);
return el?.getAttribute(this.type) ?? null;
}
clearElementState(el) {
el.classList.remove(this.hoverClass, this.clickedClass);
}
async removeResource() {
try {
if (!this.getType()) {
console.error("No type define in [data-deleteType]");
this.bgModal.setVisible(false);
return;
}
const response = await fetch(
`${baseURL}/rest/dashboard/${this.getType()}/${this.deleteID}`,
{
method: "DELETE",
}
);
if (!response.ok) {
throw new Error(
`Erreur ${response.status} : la ressource n'a pas pu être supprimée.`
);
}
const data = await response.json();
if (data.code === "200") {
document
.querySelector('[data-deleteid="' + this.deleteID + '"]')
.remove();
this.bgModal.setVisible(false);
}
return data;
} catch (error) {
console.error("Erreur lors de la suppression :", error);
throw error;
}
}
}
class newTranslateManager extends BaseHoverManager {
constructor(openModalButtonId = "btnTranslate", bgModalId = "modalTranslateTemplate", toggleButtonId = "translate") {
super("[data-resourceid]", "clicked", "veryclicked");
this.resourceId = null;
this.modal = new Modal(bgModalId);
this.smartButton = new SmartButton(openModalButtonId);
this.pageSmartButton = new SmartButton("btnTranslatePage");
this.toggleButton = document.getElementById(toggleButtonId);
this.getSelector = this.getSelector.bind(this);
this.getElementWithSameId = this.getElementWithSameId.bind(this);
this.switchResourceId = "id_switchResourceId";
this.onHoverDisabled = () => {
this.modal.setVisible(false);
this.smartButton.hide();
this.resourceId = null;
this.getElements().forEach((element) => {
element.classList.remove(this.hoverClass, this.clickedClass);
})
};
if (this.smartButton.getElement()) {
this.modal.onBackgroundClick(() => this.modal.setVisible(false));
this.modal.onCloseButtonClick();
this.smartButton.onClick(() => {
this.modal.setVisible(true);
this.smartButton.hide();
document.getElementById(this.switchResourceId).value = this.resourceId;
});
}
this.pageSmartButton.onClick(() => {
this.modal.setVisible(true);
document.getElementById(this.switchResourceId).value = document.body.getAttribute('data-pageid');
document.getElementById('checkbox_children').checked = true;
document.getElementById('checkbox_hidden_children').value = 1;
})
}
init() {
this.pageSmartButton[document.body.hasAttribute('data-pageid') ? 'show' : 'hide']();
this.getElements().forEach((el) => {
el.addEventListener("click", (e) => {
e.stopPropagation();
if (!this.hoverActive) return;
this.getElements().forEach((otherEl) => {
if (otherEl !== el) {
otherEl.classList.remove(this.hoverClass, this.clickedClass);
}
})
let elements = this.getElementWithSameId(this.getSelector(el));
const rect = elements[0].getBoundingClientRect();
const scrollTop = window.pageYOffset || document.documentElement.scrollTop;
const scrollLeft = window.pageXOffset || document.documentElement.scrollLeft;
const button = this.smartButton.getElement();
const buttonWidth = button.offsetWidth;
const buttonHeight = button.offsetHeight;
const x = rect.left + scrollLeft + rect.width / 2 - buttonWidth / 2;
const y = rect.top + scrollTop - buttonHeight - 8;
this.smartButton.setPosition(x, y);
this.resourceId = this.getSelector(el);
elements.forEach((el) => el.classList.add(this.clickedClass))
})
})
if (this.toggleButton) {
this.toggleButton.addEventListener("click", this.toggleHover);
}
}
destroy() {
super.destroy();
this.pageSmartButton.hide();
}
getSelector(e) {
return e.getAttribute(this.selector.replace(/\[|\]/g, ""))
}
addHoverClass(e) {
this.getElements().forEach((el) => el.classList.remove(this.hoverClass));
this.getElementWithSameId(this.getSelector(e.target)).forEach((el) => el.classList.add(this.hoverClass));
}
removeHoverClass(e) {
this.getElementWithSameId(this.getSelector(e.target)).forEach((el) => el.classList.remove(this.hoverClass));
}
getElementWithSameId(id) {
return Array.from(document.querySelectorAll(this.selector)).filter(
(el) => this.getSelector(el) === id
);
}
}
const fnt = new newDeleteManager();
const translate = new newTranslateManager();
//REST : Get method to get the title of the resource in sidebar
function getTitle(who) {
var transform = $("h2").css("text-transform");
$(who).prepend(
'
'
);
hrefRestNse("#resourceName", "longtitle");
blapyTools.ajaxSimpleAction($("#resourceName"), function (data0) {
var title = data0.data.title;
if (title === "" || title == "--") {
hrefRestNse("#resourceName", "pagetitle");
blapyTools.ajaxSimpleAction($("#resourceName"), function (data1) {
var title1 = data1.data.title;
$("#resourceName").html(title1);
//console.log(title1+' '+3);
});
} else {
$("#resourceName").html(title);
}
});
}
function toggleClosestButton(element) {
const subElement = element.bodyElement;
const button = subElement.closest("button");
if (button) {
button.disabled = !button.disabled;
}
}
// to put href attribut in 'who' element, with 'what' tv and the element id in the url
function hrefRestNse(who, what) {
/*var pos1 = $('[status="selected"]').attr("class").indexOf("_", $('[status="selected"]').attr("class").indexOf("_") + 1)+1;
var pos2 = $('[status="selected"]').attr("class").indexOf(" ") ;
var currentId = $('[status="selected"]').attr("class").substring(pos1, pos2);*/
var currentId = $('[status="selected"]').attr("data-resourceid");
$(who).attr("href", "/rest/newsiteeditor/" + what + "/" + currentId);
}
// toggle from edit mode to view mode
function view() {
$("#view").click(function () {
//remove attr conteneditable sinon bug avec tinyMCE
tinymce.remove();
$(".mce-item-table").removeClass("mce-item-table");
$(
"#undo, #redo, #sidebarToggle, #customerManagerPage, #helpManagerPage, #manager, #view, #delete, #translate"
).css("visibility", "hidden");
$("#wrapper").addClass("no-sidebar");
$("#edit").css("visibility", "");
$('[data-managerButton="true"]')
.removeClass("selected")
.removeAttr("status")
.attr("data-managerbutton", "false");
onClickManager(false);
sidebar(false);
linkEnabled(true);
nseVideoEditor(false);
nseImageEditor(false);
fnt.destroy();
translate.destroy();
});
}
//désactiver les liens href sur sections
function linkEnabled(enableLink) {
if (enableLink) {
$(".siteeditor")
.parents("[data-hrefSave]")
.each(function () {
$(this).attr("href", $(this).attr("data-hrefSave"));
$(this).removeAttr("data-hrefSave");
});
} else {
$(".siteeditor")
.parents("[href]")
.each(function () {
//console.log($(this));
$(this).attr("data-hrefSave", $(this).attr("href"));
$(this).removeAttr("href");
});
}
}
// toggle from view to edit mode
function edit() {
$("#edit").click(function () {
TinyMCE();
$(this).css("visibility", "hidden");
$(
"#undo, #redo, #sidebarToggle, #customerManagerPage, #helpManagerPage, #view, #manager, #delete, #translate"
).css("visibility", "");
/*$('section').each(function(){
if ( $(this).attr("data-info") === "" ){
var pos1 = this.getAttribute("class").indexOf("_", this.getAttribute("class").indexOf("_") + 1)+1;
var pos2 = this.getAttribute("class").indexOf(" ") ;
var currentId = this.getAttribute("class").substring(pos1, pos2);
$(this).attr("data-info","managerButton_"+currentId);
}
});*/
$('[data-resourceid!=""][data-resourceid]').attr(
"data-managerbutton",
"true"
);
onClickManager(true);
sidebar(true);
linkEnabled(false);
nseVideoEditor(true);
nseImageEditor(true);
fnt.init();
translate.init();
});
}
// to set data-data after clicking undo button
function undo() {
$("#undo").click(function () {
$.doTimeout("TimeOut", 500, function () {
$(".siteeditor").each(function () {
var field = $(this).attr("field");
if (
$(this).attr("data-data") !=
'{"' + field + '":"' + this.innerHTML + '","syncsite":1}'
) {
dataData(this);
blapyTools.ajaxSimpleAction(this);
}
});
});
});
}
// to set data-data after clicking redo button
function redo() {
$("#redo").click(function () {
$.doTimeout("TimeOut", 500, function () {
$(".siteeditor").each(function () {
var field = $(this).attr("field");
if (
$(this).attr("data-data") !=
'{"' + field + '":"' + this.innerHTML + '","syncsite":1}'
) {
dataData(this);
blapyTools.ajaxSimpleAction(this);
}
});
});
});
}
// onHover on content you can edit
function onHover() {
$(".siteeditor").hover(
function () {
//debugger;
if (
$(this).attr("contenteditable") ==
"true" /*&& !($(this).is(":focus")) */
) {
$(this)[0].style.setProperty(
"background-color",
"rgb(0, 0, 255, 0.1)",
"important"
);
}
},
function () {
if ($(this).attr("contenteditable") == "true") {
$(this).css("background-color", "");
}
}
);
}
// onHover on resource you can edit
function onHoverManager() {
$("section").hover(
function () {
if (
this.getAttribute("data-managerbutton") &&
this.getAttribute("data-managerbutton") == "true"
) {
$(this).addClass("selected");
}
},
function () {
if (
this.getAttribute("data-managerbutton") &&
this.getAttribute("data-managerbutton") == "true" &&
!this.getAttribute("status")
) {
$(this).removeClass("selected");
}
}
);
}
// display a manager button when clicking on a resource which redirected on the resource clicked manager
function onClickManager(mode) {
//debugger;
if (mode) {
$("#body").on("click.siteeditor", function () {
$('[status="selected"]').removeClass("selected").removeAttr("status");
$("#manager").css("visibility", "hidden").removeAttr("onclick");
});
$("section").on("click.siteeditor", function () {
//debugger;
event.stopPropagation();
$('[status="selected"]').removeClass("selected").removeAttr("status");
$("#manager").css("visibility", "hidden").attr("onclick", "");
if (
this.getAttribute("data-managerbutton") &&
this.getAttribute("data-managerbutton") == "true"
) {
$(this).addClass("selected");
$(this).attr("status", "selected");
var currentId = this.getAttribute("data-resourceid");
$("#manager").attr(
"onclick",
"window.open('/manager/?a=resource/update&id=" + currentId + "');"
);
$("#manager").css("visibility", "visible");
}
});
} else {
$("#body").off("click.siteeditor");
$("section").off("click.siteeditor");
}
}
//toggle between sidebar and nosidebar
function sidebarDisplay(boolean) {
if (boolean) {
$("#noResourceSelected").css("display", "none");
$("#resourceSelected").css("display", "");
} else {
$("#noResourceSelected").css("display", "");
$("#resourceSelected").css("display", "none");
}
}
//When sidebar is open, display the info of the resource selected or "selectionner une ressource" if no resource selected
function sidebar(mode) {
if (mode) {
$("#body").on("click.sidebar", function () {
$("#resourceName").remove();
if ($("#wrapper").attr("class") !== "no-sidebar") {
sidebarDisplay(false);
}
});
$("section").on("click.sidebar", function (e) {
//debugger;
e.stopPropagation();
$("#resourceName").remove();
if (
$("#wrapper").attr("class") !== "no-sidebar" &&
this.getAttribute("data-resourceid")
) {
getTitle("#resourceSelected");
sidebarDisplay(true);
} else {
sidebarDisplay(false);
}
});
} else {
$("#body").off("click.sidebar");
$("section").off("click.sidebar");
}
}
//Open the sidebar when clicking on the parameter button with the information of the current selected resource or "selectionner une resssource" if no selected resource
function sidebarToggle() {
$("#sidebarToggle").on("click", function () {
const isNoSidebar = $("#wrapper").hasClass("no-sidebar");
console.log(isNoSidebar);
if (isNoSidebar) {
var compt = 0;
$("#resourceName").remove();
const styles = {
width: "calc(100% - 250px)",
marginLeft: "250px",
};
Object.assign(
document.querySelector(".teq-body-content").style,
styles
);
Object.assign(
document.querySelector("body > #wrapper > header").style,
styles
);
$("section").each(function () {
if ($(this).attr("status") == "selected") {
compt += 1;
}
});
if (compt > 0) {
getTitle("#resourceSelected");
sidebarDisplay(true);
} else {
sidebarDisplay(false);
}
} else {
document
.querySelectorAll(".teq-body-content, body > #wrapper > header")
.forEach((el) => {
el.style.width = "";
el.style.marginLeft = "";
});
}
$("#wrapper").toggleClass("no-sidebar");
});
}
//Open the customer manager page
function loadCustomerManager() {
$("#customerManagerPage").on("click", function () {
if (managerURL) location.assign(managerURL);
});
}
//Open the Help page
function loadHelpManager() {
$("#helpManagerPage").on("click", function () {
if (managerHelpURL) location.assign(managerHelpURL);
});
}
// REST : get method to know how many column the resource already occupied
function getNbColumn() {
hrefRestNse("#column-select", "nbcolumn");
blapyTools.ajaxSimpleAction($("#column-select"), function (data) {
var bootstrap = data.data.nb;
var nbColumn;
if (bootstrap === null) {
nbColumn = 12;
} else {
pos3 = bootstrap.lastIndexOf("-");
nbColumn = bootstrap.substr(pos3 + 1);
}
$("#column-select").prop("value", nbColumn);
});
}
//REST : Method PUT when a new number of column is selected in sidebar
// Change instantly the number of column on page
function putNbColumn() {
$("#column-select").change(function () {
var valueSelected = $("#column-select").val();
var bootstrap;
//version input number
if (valueSelected < 1) {
valueSelected = 1;
$("#column-select").attr("value", valueSelected);
bootstrap = "col-sm-1";
} else if (valueSelected >= 12) {
valueSelected = 12;
$("#column-select").attr("value", valueSelected);
bootstrap = null;
} else {
$("#column-select").attr("value", valueSelected);
bootstrap = "col-sm-" + valueSelected;
}
//envoyer le nombre de colonne au manager version number
hrefRestNse('[for="column-select"]', "nbcolumn");
if (bootstrap === null) {
$('[for="column-select"]').attr(
"data-data",
'{"tv_nbBootstrapColumn":' + bootstrap + ',"syncsite":1}'
);
} else {
$('[for="column-select"]').attr(
"data-data",
'{"tv_nbBootstrapColumn":"' + bootstrap + '","syncsite":1}'
);
}
blapyTools.ajaxSimpleAction($('[for="column-select"]'));
//dynamique sur la page
var pos3 = $('[status="selected"]').attr("class").indexOf("col-sm");
var pos4 = $('[status="selected"]')
.attr("class")
.indexOf(" ", pos3 + 1);
var currentBootstrap = $('[status="selected"]')
.attr("class")
.substr(pos3, pos4 - pos3);
if (currentBootstrap.startsWith("col-sm")) {
$('[status="selected"]')
.removeClass(currentBootstrap)
.removeClass("selected");
} else {
$('[status="selected"]').removeClass("selected");
}
$('[status="selected"]').addClass(bootstrap).addClass("selected");
if (bootstrap === null) {
$('[status="selected"]').css("clear", "");
} else {
$('[status="selected"]').css("clear", "none");
}
});
}
//REST : get method to get the managers width in the sidebar
function getWidth() {
hrefRestNse("#width", "width");
blapyTools.ajaxSimpleAction($("#width"), function (data) {
var percentage = data.data.width;
//console.log(percentage);
var width;
if (percentage === null) {
width = 100;
} else {
pos3 = percentage.indexOf("%");
width = percentage.substr(0, pos3);
//console.log(width);
}
$("#width").prop("value", width);
});
}
//REST : Method PUT when a new number of column is selected in sidebar
// Change instantly the number of column on page
function putWidth() {
$("#width").change(function () {
var valueSelected = $("#width").val();
var percentage;
//version input
if (valueSelected < 10) {
valueSelected = 10;
$("#width").prop("value", valueSelected);
percentage = "10%";
} else if (valueSelected > 100) {
valueSelected = 100;
$("#width").prop("value", valueSelected);
percentage = "100%";
} else {
$("#width").prop("value", valueSelected);
percentage = valueSelected + "%";
}
//envoyer le nombre de colonne au manager version number
hrefRestNse('[for="width"]', "width");
if (percentage === "100%") {
$('[for="width"]').attr(
"data-data",
'{"tv_sectionWidth":' + null + ',"syncsite":1}'
);
} else {
$('[for="width"]').attr(
"data-data",
'{"tv_sectionWidth":"' + percentage + '","syncsite":1}'
);
}
blapyTools.ajaxSimpleAction($('[for="width"]'));
//dynamique sur la page
$('[status="selected"]').find("div:first").css("width", percentage);
});
}
//REST : get method to get the manager padding in the sidebar
function getPadding() {
hrefRestNse("#paddingTop", "padding");
blapyTools.ajaxSimpleAction($("#paddingTop"), function (data) {
var css = data.data.CSS;
//console.log(css);
var posTop1;
var posTop2;
var posTop3;
var paddingTop;
if (css !== null && css.includes("padding-top")) {
css = css.replace(/ /g, "");
posTop1 = css.indexOf("padding-top");
posTop2 = css.indexOf(":", posTop1 + 1);
posTop3 = css.indexOf(";", posTop1 + 1);
paddingTop = css.substr(posTop2 + 1, posTop3 - posTop2 - 1);
//console.log(paddingTop);
//$('#paddingTop').prop('value',paddingTop);
var paddingTop2;
if (paddingTop.includes("px")) {
$("#paddingTopUnit").prop("value", "px");
posTop4 = paddingTop.indexOf("px");
paddingTop2 = paddingTop.substr(0, posTop4);
//console.log(paddingTop2);
} else if (paddingTop.includes("%")) {
$("#paddingTopUnit").prop("value", "%");
posTop4 = paddingTop.indexOf("%");
paddingTop2 = paddingTop.substr(0, posTop4);
}
$("#paddingTop").prop("value", paddingTop2);
//console.log(paddingTop2);
} else {
$("#paddingTopUnit").prop("value", "px");
$("#paddingTop").prop("value", "");
}
});
hrefRestNse("#paddingBottom", "padding");
blapyTools.ajaxSimpleAction($("#paddingBottom"), function (data) {
var css = data.data.CSS;
//console.log(css);
var posBot1;
var posBot2;
var posBot3;
var paddingBottom;
if (css !== null && css.includes("padding-bottom")) {
css = css.replace(/ /g, "");
posBot1 = css.indexOf("padding-bottom");
posBot2 = css.indexOf(":", posBot1 + 1);
posBot3 = css.indexOf(";", posBot1 + 1);
paddingBottom = css.substr(posBot2 + 1, posBot3 - posBot2 - 1);
var paddingBottom2;
if (paddingBottom.includes("px")) {
posBot4 = paddingBottom.indexOf("px");
paddingBottom2 = paddingBottom.substr(0, posBot4);
$("#paddingBottomUnit").prop("value", "px");
//console.log(paddingTop2);
} else if (paddingBottom.includes("%")) {
posBot4 = paddingBottom.indexOf("%");
paddingBottom2 = paddingBottom.substr(0, posBot4);
$("#paddingBottomUnit").prop("value", "%");
}
$("#paddingBottom").prop("value", paddingBottom2);
} else {
$("#paddingBottomUnit").prop("value", "px");
$("#paddingBottom").prop("value", "");
}
});
}
/**
* Converts a File or Blob object to a Base64-encoded data URL.
*
* @param {File|Blob} blob - The file or blob to convert.
* @returns {Promise} A promise that resolves to the Base64-encoded string.
*/
function blobToBase64(blob) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onloadend = () => {
resolve(reader.result);
};
reader.onerror = reject;
reader.readAsDataURL(blob);
});
}
// REST : put method to put the sidebar value in the manager
function putPadding() {
$(
"#paddingTop, #paddingBottom, #paddingTopUnit, #paddingBottomUnit"
).change(function () {
let paddingTop = parseInt($("#paddingTop").val());
if (isNaN(paddingTop)) paddingTop = 0;
let unitTop = $("#paddingTopUnit").val();
let paddingBottom = parseInt($("#paddingBottom").val());
if (isNaN(paddingBottom)) paddingBottom = 0;
let unitBottom = $("#paddingBottomUnit").val();
if (paddingTop > 999) {
paddingTop = 999;
$("#paddingTop").prop("value", paddingTop);
} else if (paddingTop < 0) {
paddingTop = 0;
$("#paddingTop").prop("value", paddingTop);
}
if (paddingBottom > 999) {
paddingBottom = 999;
$("#paddingBottom").prop("value", paddingBottom);
} else if (paddingBottom < 0) {
paddingBottom = 0;
$("#paddingBottom").prop("value", paddingBottom);
}
//envoyer le nombre de colonne au manager version number
hrefRestNse('[for="padding"]', "padding");
$('[for="padding"]').attr(
"data-data",
'{"tv_sectionCSS":"padding-top:' +
paddingTop +
unitTop +
";padding-bottom:" +
paddingBottom +
unitBottom +
';","syncsite":1}'
);
if (paddingTop === 0 && paddingBottom === 0) {
$('[for="padding"]').attr(
"data-data",
'{"tv_sectionCSS":"","syncsite":1}'
);
} else if (paddingTop === 0) {
$('[for="padding"]').attr(
"data-data",
'{"tv_sectionCSS":"padding-bottom:' +
paddingBottom +
unitBottom +
';","syncsite":1}'
);
}
blapyTools.ajaxSimpleAction($('[for="padding"]'));
//dynamique sur la page
if (
(paddingTop === 0 || paddingTop === "") &&
(paddingBottom === 0 || paddingBottom === "")
) {
$('[status="selected"]').css("padding-top", "");
$('[status="selected"]').css("padding-bottom", "");
} else if (paddingTop === 0 || paddingTop === "") {
$('[status="selected"]').css("padding-top", "");
$('[status="selected"]').css(
"padding-bottom",
paddingBottom + unitBottom
);
} else if (paddingBottom === 0 || paddingBottom === "") {
$('[status="selected"]').css("padding-top", paddingTop + unitTop);
$('[status="selected"]').css("padding-bottom", "");
} else {
$('[status="selected"]').css("padding-top", paddingTop + unitTop);
$('[status="selected"]').css(
"padding-bottom",
paddingBottom + unitBottom
);
}
});
}
let imageUppy = null;
let current = {};
let cropper = null;
let pendingFile = null;
let customButton = document.getElementById("editImageBtn");
async function handleImageEditor(e) {
const el = e.currentTarget;
const prev = document.querySelector(".imageeditor.selected-img");
if (prev) prev.classList.remove("selected-img");
el.classList.add("selected-img");
if (el.naturalHeight === 0) {
current.aspectRatio = 1;
} else {
current.aspectRatio = el.naturalWidth / el.naturalHeight;
}
current.element = el;
current.lang = el.getAttribute("data-lang");
current.dataRessourceId = el.getAttribute("data-resource-id");
current.customFields = {
src: el.getAttribute("data-img-src"),
alt: el.getAttribute("data-alt"),
};
uppyReset(imageUppy);
const blob = await fetch(el.src).then((res) => res.blob());
const ts = new Date().toISOString().replace(/[-:.]/g, "").replace("Z", "");
imageUppy.addFile({
name: ts + ".png",
type: blob.type,
data: blob,
meta: {
isCropped: true,
fromServer: true,
},
});
document.getElementById("altText").value = current.element.alt;
customButton.style.top = e.pageY + 10 + "px";
customButton.style.left = e.pageX + 10 + "px";
customButton.style.display = "block";
}
function nseImageEditor(active) {
if (!active) {
destroyUppy();
customButton.style.display = "none";
document.querySelectorAll(".imageeditor").forEach((el) => {
el.removeEventListener("click", handleImageEditor);
el.style.cursor = "";
});
return;
}
imageUppy = initializeUppy();
initializeEventListener();
customButton.addEventListener("click", () => {
openModal();
});
function initializeUppy() {
//console.log(Uppy.locales);
//console.log(current);
const uppy = new UppyConstructor({
locale: availableLang[lang],
restrictions: {
maxNumberOfFiles: 1,
allowedFileTypes: acceptedImageTypes,
autoProceed: true,
},
});
uppy.use(Dashboard, {
inline: true,
target: "#uppy",
showAddFilesButton: false,
hideUploadButton: true,
height: 400,
});
uppy.use(ImageEditor, {
target: Dashboard,
cropperOptions: {
viewMode: 1,
autoCropArea: 0.8,
},
actions: {
revert: false,
rotate: false,
flip: false,
granularRotate: false,
cropSquare: false,
cropWidescreen: false,
cropWidescreenVertical: false,
},
});
uppy.on("file-added", (file) => {
//console.log(file.type);
if (file.meta.isCropped) return;
pendingFile = file;
openCropper(file);
return false;
});
uppy.on("file-editor:complete", (file) => {
file.meta.fromServer = false;
});
return uppy;
}
function destroyUppy() {
if (imageUppy) {
imageUppy.cancelAll();
imageUppy.destroy();
}
}
function initializeEventListener() {
const modal = document.getElementById("modalNseBackground");
modal.addEventListener("click", (e) => {
if (e.target === modal) closeModal();
});
document.getElementById("generateByAi").addEventListener("click", () => {
const [file] = imageUppy.getFiles();
if (file) {
console.log("%c[Mitral AI] - Starting", "color: #f57842");
new Compressor(file.data, {
quality: 0.7,
width: 1000,
async success(result) {
//console.log(result.size / (1024 * 1024) + " mo");
const base64 = await blobToBase64(result);
var formData = new FormData();
formData.append("imageURL", base64);
formData.append("lang", current.lang);
document.getElementById("generateByAi").disabled = true;
const response = await fetch(
baseURL + "/rest/mistral/image-alt/",
{
method: "POST",
body: formData,
}
);
const json = await response.json();
if (json.code === "200") {
document.getElementById("altText").value =
json.data.content.choices[0].message.content;
console.log("%cSuccess - Alt updated", "color: #63f542");
} else {
console.error("No description :'(");
}
document.getElementById("generateByAi").disabled = false;
},
error(err) {
console.error("Une erreur est survenue");
document.getElementById("generateByAi").disabled = false;
},
});
}
});
document
.getElementById("assetsManagerImage")
.addEventListener("click", async () => {
registerFileBrowserHandler({
modalId: "modalImageFileBrowser",
fileBrowserId: "imageFileBrowser",
acceptedTypes: imageTypesWithoutDots,
fileType: "image",
uppyInstance: imageUppy,
})
});
document
.getElementById("saveImage")
.addEventListener("click", async () => {
const [file] = imageUppy.getFiles();
const params = new URLSearchParams();
params.append("urlvalue", current.dataRessourceId);
params.append("alt", document.getElementById("altText").value);
if (current.customFields?.alt) {
params.append("altField", current.customFields.alt);
}
if (current.customFields?.src) {
params.append("srcField", current.customFields.src);
}
if (file && !file.meta.fromServer) {
try {
document.getElementById("saveImage").innerText =
"Uploading document";
const uploadResult = await uploadFile(file, current.lang);
if (uploadResult.code === "200") {
params.append(
"imageSrc",
uploadResult.data.fullname.replace(/^(images)\//, "")
);
} else {
console.error("Upload failed", uploadResult);
return;
}
} catch (err) {
console.error("Upload error", err);
return;
}
}
if (file && file.meta.updateImage && file.meta.dir) {
params.append("imageSrc", file.meta.dir + "/" + file.name);
}
try {
document.getElementById("saveImage").innerText = "Updating data";
const response = await sendRequest(
`/rest/newsiteeditor/image/${current.dataRessourceId}`,
"PUT",
params
);
if (response.code === "200") {
closeModal();
window.location.reload();
}
} catch (err) {
console.error("Save error", err);
}
});
document
.getElementById("closeImageModal")
.addEventListener("click", () => {
closeModal();
});
document.getElementById("uploadFile").addEventListener("click", (e) => {
openFileSelectorAndReplace(
imageUppy,
"image/webp,image/png,image/jpeg"
);
});
document.addEventListener("click", (event) => {
if (!event.target.classList.contains("imageeditor")) {
customButton.style.display = "none";
document.querySelectorAll(".imageeditor").forEach((el) => {
el.classList.remove("selected-img");
});
}
});
document.querySelectorAll(".imageeditor").forEach((el) => {
el.style.cursor = "pointer";
el.removeEventListener("click", handleImageEditor);
el.addEventListener("click", handleImageEditor);
});
document
.getElementById("cropper-cancel")
.addEventListener("click", () => {
document.getElementById("cropper-modal").classList.remove("active");
if (cropper) {
cropper.destroy();
cropper = null;
}
pendingFile = null;
uppyReset(imageUppy);
});
document
.getElementById("cropper-confirm")
.addEventListener("click", () => {
if (!cropper || !pendingFile) return;
cropper.getCroppedCanvas().toBlob((blob) => {
imageUppy.removeFile(pendingFile.id);
const ts = new Date()
.toISOString()
.replace(/[-:.]/g, "")
.replace("Z", "");
imageUppy.addFile({
name: ts + ".png",
type: pendingFile.type,
data: blob,
meta: {
isCropped: true,
},
});
document.getElementById("cropper-modal").classList.remove("active");
cropper.destroy();
cropper = null;
pendingFile = null;
}, pendingFile.type);
});
}
/**
*
* @param {Blob} file - File you want to upload
* @returns {Response} - Response from the server with the image location
*/
async function uploadFile(file) {
//console.log(current);
const formData = new FormData();
formData.append("file", file.data, file.name);
formData.append("inputFileFieldName", "file");
formData.append("context_key", current.lang);
const response = await sendRequest(
"/rest/newsiteeditor/image/",
"POST",
formData
);
return response;
}
function openCropper(file) {
const reader = new FileReader();
reader.onload = (e) => {
const cropperImage = document.getElementById("cropper-image");
cropperImage.src = e.target.result;
document.getElementById("cropper-modal").classList.add("active");
if (cropper) {
cropper.destroy();
}
cropper = new Cropper(cropperImage, {
viewMode: 1,
aspectRatio: current.aspectRatio,
autoCropArea: 0.8,
});
};
reader.readAsDataURL(file.data);
}
function openModal() {
document.getElementById("modalNseBackground").style.display = "flex";
const imageEditor = imageUppy.getPlugin("ImageEditor");
imageEditor.setOptions({
cropperOptions: {
viewMode: 1,
aspectRatio: current.aspectRatio,
autoCropArea: 1,
},
});
}
function closeModal() {
document.getElementById("modalNseBackground").style.display = "none";
current = {};
destroyUppy();
imageUppy = initializeUppy();
}
}
let posterUppy = null;
let videoUppy = null;
let isVideoEditorSetup = false;
/**
* Editeur vidéo du newSiteEditor, permet de modifier la source, le poster, le titre et l'ariaLabel
* @param {boolean} enable - Active ou désactive l'éditeur vidéo.
*/
function nseVideoEditor(enable) {
//C'est un truc plus ou moins comme les records en typescript
const videoInfos = new Map();
const buttonId = "videoEditorButton";
const videoBackgroundID = "modalNseVideoBackground";
const nextToVideo = "nextToVideo";
const backToPoster = "backToPoster";
const videoTitleInput = "videoTitle";
const closeButtonID = "closeVideoModal";
const ariaLabelInput = "ariaLabel";
const submitVideoEditorID = "submitVideoEditor";
const videoPreview = document.getElementById("videoPreview");
/**
* Affiche la modal à l'écran
*/
function showModal() {
document.body.style.overflow = "hidden";
document.getElementById(videoBackgroundID).style.display = "flex";
if (!posterUppy || !videoUppy) {
[posterUppy, videoUppy] = initializeUppy();
}
loadPosterToUppy();
}
/**
* Cache la modal et réinitialise tout les uppys
*/
function hideModal() {
document.getElementById(videoBackgroundID).style.display = "none";
closeUppy();
showPosterStep();
}
/**
* Affiche l'étape du poster
*/
function showPosterStep() {
document.querySelector("#modalPosterNse").style.display = "block";
document.querySelector("#modalVideoNse").style.display = "none";
}
/**
* Affiche l'étape d'édition de vidéo avec les infos actuelles.
* @param {Object} info - Informations sur la vidéo.
* @param {string} info.title - Titre de la vidéo.
* @param {string} info.aria - Aria-label de la vidéo.
*/
function showVideoStep(info) {
document.querySelector("#modalPosterNse").style.display = "none";
document.querySelector("#modalVideoNse").style.display = "block";
document.getElementById("videoTitle").value = info.title;
document.getElementById("ariaLabel").value = info.aria;
}
/**
* Initialise les écouteurs d'évenements nécessaires à l'éditeur.
*/
function setupEventListeners() {
document.getElementById(buttonId).addEventListener("click", () => {
const button = document.getElementById(buttonId);
button.style.display = "none";
const currentId = button.getAttribute("data-currentId");
const info = videoInfos.get(currentId);
showModal();
document.body.addEventListener("keyup", (e) => {
if (e.code === "Escape") {
hideModal();
}
});
videoPreview.src = info.src;
});
document
.getElementById(videoBackgroundID)
.addEventListener("click", (event) => {
if (event.target.id === videoBackgroundID) {
hideModal();
}
});
document.getElementById(closeButtonID).addEventListener("click", () => {
hideModal();
});
document
.getElementById("uploadPosterFile")
.addEventListener("click", (e) => {
openFileSelectorAndReplace(posterUppy, "image/webp,image/png,image/jpeg");
});
document
.getElementById("assetsManagerPoster")
.addEventListener("click", async () => {
registerFileBrowserHandler({
modalId: "modalPosterFileBrowser",
fileBrowserId: "posterFileBrowser",
acceptedTypes: imageTypesWithoutDots,
fileType: "image",
uppyInstance: posterUppy,
});
});
document
.getElementById("assetsVideoManager")
.addEventListener("click", async () => {
registerFileBrowserHandler({
modalId: "modalVideoFileBrowser",
fileBrowserId: "videoFileBrowser",
acceptedTypes: videoTypesWithoutDots,
fileType: "video",
uppyInstance: videoUppy,
preview: videoPreview,
});
});
document.getElementById(nextToVideo).addEventListener("click", () => {
const info = getCurrentButtonInfo();
showVideoStep(info);
});
document.getElementById(backToPoster).addEventListener("click", () => {
showPosterStep();
});
document.querySelectorAll(".videoeditor").forEach((el) => {
const videoInfo = extractVideoInfo(videojs(el.id));
videoInfos.set(el.id, videoInfo);
el.addEventListener("click", (event) => {
event.stopPropagation();
event.stopImmediatePropagation();
updateReplaceButtonPositionAndDataId(event.pageX, event.pageY, el.id);
});
});
document
.getElementById("uploadVideoFile")
.addEventListener("click", (e) => {
openFileSelectorAndReplace(videoUppy, "video/mp4, video/webm");
});
document
.getElementById(submitVideoEditorID)
.addEventListener("click", () => {
submitModal();
});
}
/**
* Supprime les écouteurs d'évement
/**
* Extrait les informations d'une vidéo à partir du player video.js.
* @param {Object} player - Instance du lecteur video.js.
* @returns {{poster: string, title: string, aria: string, src: string}} - Informations extraites.
*/
function extractVideoInfo(player) {
const sources = Array.from(player.el().querySelectorAll("source")).map(
(s) => ({
src: s.src,
type: s.type,
})
);
return {
id: player.el().id,
resourceId: player.el().getAttribute("data-resource-id"),
context_key: player.el().getAttribute("data-lang"),
poster: player.poster(),
title: player.el().title,
aria: player.tech().el().getAttribute("aria-label"),
src: sources[0]?.src,
};
}
/**
* Met à jour la position du bouton "Edit video" et le data-id courant.
* @param {number} x - Position X du clic.
* @param {number} y - Position Y du clic.
* @param {string} videoId - ID de la vidéo cliquée.
*/
function updateReplaceButtonPositionAndDataId(x, y, videoId) {
const replaceButton = document.getElementById(buttonId);
if (replaceButton.getAttribute("data-movable") !== "true") return;
Object.assign(replaceButton.style, {
display: "block",
left: x + "px",
top: y + "px",
});
replaceButton.setAttribute("data-currentId", videoId);
}
/**
* Initialise les instances Uppy pour le poster et la vidéo.
* @returns {[UppyConstructor, UppyConstructor]} - Instances Uppy pour le poster et la vidéo.
*/
function initializeUppy() {
const poster = createPosterUppy();
const video = createVideoUppy();
return [poster, video];
}
function loadPosterToUppy() {
const info = getCurrentButtonInfo();
if (!info?.poster) return;
fetch(info.poster)
.then((res) => res.blob())
.then((blob) => {
const file = new File([blob], "poster.jpg", {
type: blob.type || "image/jpeg",
});
posterUppy.addFile({
name: file.name,
type: file.type,
data: file,
source: "Server",
meta: {
fromServer: true,
},
});
})
.catch(console.error);
if (!info.id) return;
videojs(info.id).pause();
}
/**
* Détruit les instances Uppy existantes (poster et vidéo).
*/
function closeUppy() {
document.body.style.overflow = "auto";
if (posterUppy) {
const posterDash = posterUppy.getPlugin("Dashboard");
if (posterDash && typeof posterDash.destroy === "function") {
posterDash.destroy();
}
posterUppy = null;
const posterContainer = document.querySelector("#uppy-poster");
if (posterContainer) posterContainer.innerHTML = "";
}
if (videoUppy) {
const videoDash = videoUppy.getPlugin("Dashboard");
if (videoDash && typeof videoDash.destroy === "function") {
videoDash.destroy();
}
videoUppy = null;
const videoContainer = document.querySelector("#uppy-video");
if (videoContainer) videoContainer.innerHTML = "";
}
}
/**
* Crée l'instance Uppy pour le poster.
* @returns {Uppy} - Instance Uppy configurée pour les images.
*/
function createPosterUppy() {
const uppy = new UppyConstructor({
locale: availableLang[lang],
restrictions: {
maxNumberOfFiles: 1,
allowedFileTypes: acceptedImageTypes,
},
});
uppy.use(Dashboard, {
inline: true,
target: "#uppy-poster",
showAddFilesButton: false,
hideUploadButton: true,
height: 450,
});
uppy.use(ImageEditor, {
target: Dashboard,
cropperOptions: {
viewMode: 1,
autoCropArea: 1,
aspectRatio: 25 / 14,
},
actions: {
revert: false,
rotate: false,
flip: false,
granularRotate: false,
cropSquare: false,
cropWidescreen: false,
cropWidescreenVertical: false,
},
});
uppy.on("file-added", (file) => {
//console.log(file);
if (file.meta.fromServer) {
return;
}
uppy.getPlugin("Dashboard").openFileEditor(file);
return false;
});
uppy.on("file-editor:complete", (file) => {
file.meta.fromServer = false;
});
/*uppy.on("file-removed", () => {
const info = getCurrentButtonInfo();
posterPreview.src = info?.poster;
});*/
uppy.on("file-editor:cancel", () => {
uppy.cancelAll();
});
/*uppy.on("cancel-all", () => {
if (!enable) return;
const info = getCurrentButtonInfo();
posterPreview.src = info?.poster;
});*/
return uppy;
}
/**
* Crée l'instance Uppy pour la vidéo.
* @returns {Uppy} - Instance Uppy configurée pour les vidéos.
*/
function createVideoUppy() {
const uppy = new UppyConstructor({
locale: availableLang[lang],
restrictions: {
maxNumberOfFiles: 1,
allowedFileTypes: acceptedVideoTypes,
},
});
uppy.use(Dashboard, {
inline: true,
target: "#uppy-video",
showAddFilesButton: false,
hideUploadButton: true,
height: 200,
});
uppy.on("file-added", (file) => {
videoPreview.src = URL.createObjectURL(file.data);
});
uppy.on("file-removed", () => {
const info = getCurrentButtonInfo();
videoPreview.src = info.src;
});
uppy.on("cancel-all", () => {
if (!enable) return;
const info = getCurrentButtonInfo();
videoPreview.src = info.src;
});
return uppy;
}
/**
* Récupère les informations de la vidéo actuellement sélectionnée.
* @returns {{poster: string, title: string, aria: string, src: string}} - Infos vidéo actuelle.
*/
function getCurrentButtonInfo() {
const button = document.getElementById(buttonId);
const currentId = button.getAttribute("data-currentId");
const info = videoInfos.get(currentId);
return info;
}
/**
* Soumet les données modifiées du modal au serveur.
* Met à jour les infos de la Map et le player video.js en conséquence.
*/
async function submitModal() {
const poster = posterUppy.getFiles()[0];
const video = videoUppy.getFiles()[0];
const title = document.getElementById(videoTitleInput)?.value?.trim();
const ariaLabel = document.getElementById(ariaLabelInput)?.value?.trim();
const buttonInfo = getCurrentButtonInfo();
const resourceId = buttonInfo.resourceId;
if (!poster && !video && !title && !ariaLabel) {
hideModal();
return;
}
const uploadFileIfNeeded = async (file, type) => {
if (file && !file.meta.fromServer) {
const formData = new FormData();
formData.append("file", file.data, file.name);
formData.append("inputFileFieldName", "file");
formData.append("context_key", buttonInfo.context_key);
try {
const response = await sendRequest(
"/rest/newsiteeditor/" + type,
"POST",
formData
);
document.getElementById(submitVideoEditorID).textContent =
"Uploading document...";
return response?.data?.fullname.replace(/^(images)\//, "");
} catch (error) {
console.error("Erreur upload fichier :", file.name, error);
}
}
if (
file &&
file.meta.fromServer &&
file.meta.updateImage &&
file.meta.dir
) {
return file.meta.dir + "/" + file.name;
}
};
const videoInfoParams = new URLSearchParams();
const posterLocation = await uploadFileIfNeeded(poster, "image");
const videoLocation = await uploadFileIfNeeded(video, "video");
document.getElementById(submitVideoEditorID).textContent =
"Updating data..";
videoInfoParams.append("urlvalue", resourceId);
videoInfoParams.append("ariaLabel", ariaLabel);
videoInfoParams.append("title", title);
if (posterLocation) {
videoInfoParams.append("poster", posterLocation);
}
if (videoLocation) {
videoInfoParams.append("video", videoLocation);
}
const updateInfo = await sendRequest(
"/rest/newsiteeditor/video/" + resourceId,
"PUT",
videoInfoParams
).then(() => {
window.location.reload();
});
}
if (!enable) {
closeUppy();
hideModal();
document.getElementById(buttonId).style.display = "none";
document.getElementById(buttonId).setAttribute("data-movable", false);
return;
}
if (!isVideoEditorSetup) {
setupEventListeners();
//console.log("setup");
isVideoEditorSetup = true;
}
document.getElementById(buttonId).setAttribute("data-movable", true);
if (!posterUppy || !videoUppy) {
[posterUppy, videoUppy] = initializeUppy();
}
}
/**
* @param {Uppy} uppyInstance Instance of Uppy that you should update
* @param {string} acceptedType A comma-separated string of MIME types (e.g., "image/png,image/jpeg")
*/
function openFileSelectorAndReplace(uppyInstance, acceptedType = "image/*") {
const tempInput = document.createElement("input");
tempInput.type = "file";
tempInput.accept = acceptedType;
tempInput.style.display = "none";
const acceptedMimeTypes = acceptedType
.split(",")
.map((type) => type.trim().toLowerCase());
//console.log(acceptedMimeTypes);
tempInput.addEventListener("change", (e) => {
const file = e.target.files[0];
if (file) {
const fileType = file.type.toLowerCase();
const isAccepted = acceptedMimeTypes.some((type) => {
if (type.endsWith("/*")) {
return fileType.startsWith(type.slice(0, -1));
}
return fileType === type;
});
if (!isAccepted) {
//Get the error from uppy and inform the user the valid fileTypes.
uppyInstance.info(uppyInstance.i18n('youCanOnlyUploadFileTypes',
{types: acceptedMimeTypes.map((type) => {
const parts = type.split('/');
return parts[1] ? ` .${parts[1]}` : null;
}).filter(Boolean)}), 'error', 5000);
console.warn(`Type de fichier non autorisé : ${fileType}`);
tempInput.remove();
return;
}
uppyReset(uppyInstance);
uppyInstance.addFile({
name: file.name,
type: file.type,
data: file,
source: "Local",
});
}
tempInput.remove();
});
document.body.appendChild(tempInput);
tempInput.click();
}
async function openFileBrowser(
containerId,
acceptedFileType,
fileDirectory
) {
return new Promise((resolve) => {
const explorer = new Karibsen.ServerBrowser({
containerId: containerId,
theme: "primary",
acceptedTypeFiles: acceptedFileType,
lang: document.documentElement.lang.toLowerCase(),
onValidate(file) {
//console.log(file);
resolve(file);
explorer.destroy();
},
dataSource:
baseURL + "/rest/newsiteeditor/dir?fileDirectory=" + fileDirectory,
autoHideEmptyFolders: true,
});
explorer.open();
});
}
async function uppyReset(uppyInstance) {
uppyInstance.getFiles().forEach((f) => uppyInstance.removeFile(f.id));
}
async function updateUppyInstance(
uppyInstance,
file,
folder,
videoPreview = null
) {
try {
let blob;
const mimeType = await getMimeTypeFromUrl(file.url);
if (mimeType && mimeType.startsWith("video/")) {
if (videoPreview) {
blob = "videoInfo";
blob.type = mimeType;
videoPreview.src = file.url;
}
} else {
const response = await fetch(file.url);
blob = await response.blob();
}
uppyReset(uppyInstance);
uppyInstance.addFile({
name: file.name,
type: blob.type,
data: blob,
meta: {
fromServer: true,
isCropped: true,
updateImage: true,
dir: folder,
},
});
return true;
} catch (err) {}
}
async function getMimeTypeFromUrl(url) {
try {
const response = await fetch(url, { method: "HEAD" });
if (!response.ok) {
throw new Error("Échec de la requête HEAD");
}
return response.headers.get("Content-Type");
} catch (e) {
console.error("Erreur HEAD fetch:", e);
return null;
}
}
/**
*
* @param {string} requestURL URL to request
* @param {string} method Type of method "POST, GET, PUT, DELETE"
* @param {FormData} Data Body of the request
* @returns
*/
async function sendRequest(requestURL, method, Data) {
if (!requestURL.startsWith("http")) {
requestURL = baseURL + requestURL;
}
const response = await fetch(requestURL, {
method: method,
body: Data,
});
const contentType = response.headers.get("content-type");
let result;
if (contentType && contentType.includes("application/json")) {
result = await response.json();
} else {
result = await response.blob();
}
return result;
}
/**
*
* @param {string} triggerId - Id of the trigger
* @param {string} modalId - Id of the modal
* @param {string} fileBrowserId - Id of Kserver container
* @param {string[]} acceptedTypes - Accepted files in Kserver
* @param {string} fileType -
* @param {Uppy} uppyInstance - Uppy instance to update
* @param {HTMLElement} [preview] - Element HTML pour mise à jour d’un aperçu vidéo ou image
*/
async function registerFileBrowserHandler({
modalId,
fileBrowserId,
acceptedTypes,
fileType,
uppyInstance,
preview = null,
}) {
const modal = new Modal(modalId);
modal.setVisible(true);
document.addEventListener('kserverbrowser:closed', (e) => {
console.log(e.detail.containerId, fileBrowserId)
if(e.detail.containerId === fileBrowserId) {
modal.setVisible(false)
return
}
}, {once: true});
modal.onBackgroundClick(() => modal.setVisible(false));
modal.onCloseButtonClick();
try {
const selectedFile = await openFileBrowser(
fileBrowserId,
acceptedTypes,
fileType
);
await updateUppyInstance(
uppyInstance,
selectedFile.file,
selectedFile.folder,
preview
);
modal.setVisible(false);
} catch (error) {
console.error(`Erreur lors de la sélection de fichier :`, error);
modal.setVisible(false);
}
}
// to set data-data for every element when opening the page
$(".siteeditor").each(function () {
dataData(this);
});
//window.addEventListener('DOMContentLoaded', newsiteeditor, false);
view();
edit();
onHover();
saveContent();
undo();
redo();
onHoverManager();
//onClickManager();
//sidebar();
//sidebarToggle();//activate sidebar
loadCustomerManager();
loadHelpManager();
putNbColumn();
putWidth();
putPadding();
//$('#body').off('click');
//$('section').off('click');
// define the public API
var API = {};
API.version = version;
// API.add = add;
// API.get_array = get_array;
return API;
})();