| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213 |
- /**
- *
- * 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/04/24 - V1.0.2 - C.Nelhomme - Fix prevent click problem and unclickable button + update Tinymce settings
- *
- * @copyright Intersel 2022
- */
- //debugger;
- import {
- Uppy,
- Dashboard,
- XHRUpload,
- } from "https://releases.transloadit.com/uppy/v4.13.3/uppy.min.mjs";
- let current = {};
- let NEWSITEEDITOR = (function () {
- let version = "1.0.2";
- //set data-data for content and title
- function dataData(who) {
- var obj = {};
- var title;
- var field = $(who).attr("field");
- const sync = { syncsite: 1 };
- //if(field === 'content'){
- if (field !== "pagetitle" && field !== "longtitle") {
- if (
- who.innerHTML === "" ||
- who.innerHTML.includes('<br data-mce-bogus="1">')
- ) {
- obj[field] = who.innerHTML;
- //$(who).parents('.textcontent:first').hide(); //EPO: Why do we need to do that?
- } else {
- obj[field] = who.innerHTML;
- }
- } else {
- if (
- who.innerHTML === "" ||
- who.innerHTML.includes('<br data-mce-bogus="1">')
- ) {
- title = { longtitle: "--" };
- $(who).parents(".equalHeight:first").hide();
- } else {
- title = { longtitle: who.innerHTML };
- }
- }
- Object.assign(obj, title);
- 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);
- blapyTools.ajaxSimpleAction(this);
- });
- }
- // Settings available for the richtext editor
- function TinyMCE() {
- // debugger;
- $.doTimeout("startTinyMCE", 200, function () {
- tinymce.init({
- selector: ".siteeditor",
- inline: true,
- plugins: "link, textcolor, table, preview",
- 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",
- ],
- fontsize_formats: "8px 10px 12px 14px 18px 24px 26px 34px",
- //, valid_elements: 'p[style],strong,em,span[style],a[href],ul,ol,li'
- //, valid_styles: {'*': 'font-size,font-family,color,text-decoration,text-align'}
- powerpaste_word_import: "clean",
- powerpaste_html_import: "clean",
- setup: function (editor) {
- editor.on("click", function (el) {
- el.preventDefault();
- el.stopImmediatePropagation();
- });
- editor.on("keydown", function (el) {
- if (
- el.code === "ArrowRight" ||
- el.code === "ArrowLeft" ||
- el.code === "ArrowUp" ||
- el.code === "ArrowDown"
- ) {
- el.stopPropagation();
- }
- });
- },
- }); //end init
- }); //end dotimeout
- }
- //REST : Get method to get the title of the resource in sidebar
- function getTitle(who) {
- var transform = $("h2").css("text-transform");
- $(who).prepend(
- '<p id="resourceName" method="GET" style="text-transform:' +
- transform +
- ';"></p>'
- );
- 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);
- }
- });
- }
- // 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();
- tinymce.activeEditor.remove();
- $(".mce-item-table").removeClass("mce-item-table");
- $("#undo, #redo, #sidebarToggle, #manager, #view").css(
- "visibility",
- "hidden"
- );
- $("#wrapper").addClass("no-sidebar");
- $("#edit").css("visibility", "");
- $('[data-managerButton="true"]')
- .removeClass("selected")
- .removeAttr("status")
- .attr("data-managerbutton", "false");
- //Disable all contentEditable added by tinyMce
- document.querySelectorAll("[contenteditable=true]").forEach((e) => {
- e.removeAttribute("contenteditable");
- });
- onClickManager(false);
- sidebar(false);
- linkEnabled(true);
- nseImageEditor(false);
- });
- }
- //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 () {
- $(this).attr("data-hrefSave", $(this).attr("href"));
- $(this).removeAttr("href");
- });
- }
- }
- function preventClickEnabled(enableClick) {
- let pointerEventsNoneClasses = document.getElementsByClassName(
- enableClick ? "pointer-events-none" : "edit-pointer-event"
- );
- if (pointerEventsNoneClasses.length > 0) {
- if (enableClick) {
- Array.from(
- document.getElementsByClassName("pointer-events-none")
- ).forEach((e) => {
- e.classList.remove("pointer-events-none");
- e.classList.add("edit-pointer-event");
- });
- } else {
- Array.from(
- document.getElementsByClassName("edit-pointer-event")
- ).forEach((e) => {
- e.classList.add("pointer-events-none");
- e.classList.remove("edit-pointer-event");
- });
- }
- }
- }
- // toggle from view to edit mode
- function edit() {
- $("#edit").click(function () {
- TinyMCE();
- $(this).css("visibility", "hidden");
- $("#undo, #redo, #sidebarToggle, #view, #manager").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);
- preventClickEnabled(true);
- sidebar(true);
- linkEnabled(false);
- nseImageEditor(true);
- });
- }
- // 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 (event) {
- event.stopPropagation();
- $('[status="selected"]').removeClass("selected").removeAttr("status");
- $("#manager").css("visibility", "hidden").removeAttr("onclick");
- });
- $("section").on("click.siteeditor", function (event) {
- //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");
- getNbColumn();
- getWidth();
- getPadding();
- 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 () {
- if ($("#wrapper").attr("class") == "no-sidebar") {
- var compt = 0;
- $("#resourceName").remove();
- $("section").each(function () {
- if ($(this).attr("status") == "selected") {
- compt += 1;
- }
- });
- if (compt > 0) {
- getNbColumn();
- getWidth();
- getPadding();
- getTitle("#resourceSelected");
- sidebarDisplay(true);
- } else {
- sidebarDisplay(false);
- }
- }
- $("#wrapper").toggleClass("no-sidebar");
- });
- }
- // 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", "");
- }
- });
- }
- // 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
- );
- }
- });
- }
- //nseImageEditor
- let cropper = null;
- let pendingFile = null;
- let aspectRatio;
- function nseImageEditor(active) {
- if (!active) {
- return;
- }
- const uppy = new Uppy({
- restrictions: {
- maxNumberOfFiles: 1,
- allowedFileTypes: [".jpg", ".jpeg", ".png", ".gif", ".webp"],
- },
- });
- uppy.use(Dashboard, {
- inline: true,
- target: "#uppy",
- showAddFilesButton: false,
- });
- uppy.on("file-added", (file) => {
- if (file.meta.isCropped) {
- return;
- }
- pendingFile = file;
- openCropper(file);
- return false;
- });
- uppy.on("complete", (file) => {
- showNseModal(false);
- uppy.cancelAll();
- console.log(file);
- current.element.src =
- "http://localhost/php/uploads/" + file.successful[0].meta.name;
- });
- //Initialiser l'endpoint pour l'upload des fichiers
- uppy.use(XHRUpload, { endpoint: "http://localhost/php/index.php" });
- const customButton = document.createElement("button");
- customButton.innerText = "Edit";
- customButton.style.position = "absolute";
- customButton.style.display = "none";
- customButton.id = "editImageBtn";
- document.body.append(customButton);
- customButton.onclick = () => showNseModal(true);
- const modal = document.getElementById("modalNseBackground");
- modal.addEventListener("click", (e) => {
- if (e.target === modal) {
- showNseModal(false);
- }
- });
- 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.addEventListener("click", (e) => {
- 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;
- customButton.style.top = e.pageY + 10 + "px";
- customButton.style.left = e.pageX + 10 + "px";
- customButton.style.display = "block";
- });
- });
- document.getElementById("cropper-cancel").addEventListener("click", () => {
- document.getElementById("cropper-modal").classList.remove("active");
- if (cropper) {
- cropper.destroy();
- cropper = null;
- }
- pendingFile = null;
- });
- document.getElementById("cropper-confirm").addEventListener("click", () => {
- if (!cropper || !pendingFile) return;
- cropper.getCroppedCanvas().toBlob((blob) => {
- uppy.removeFile(pendingFile.id);
- const ts = new Date()
- .toISOString()
- .replace(/[-:.]/g, "")
- .replace("Z", "");
- uppy.addFile({
- name: ts + ".png",
- type: pendingFile.type,
- data: blob,
- meta: {
- isCropped: true,
- },
- });
- // Nettoyage
- document.getElementById("cropper-modal").classList.remove("active");
- cropper.destroy();
- cropper = null;
- pendingFile = null;
- }, pendingFile.type);
- });
- }
- 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: 1,
- });
- };
- reader.readAsDataURL(file.data);
- }
- function showNseModal(shouldShow) {
- const modal = document.getElementById("modalNseBackground");
- modal.style.display = shouldShow ? "flex" : "none";
- }
- //Fin du nseImageEditor
- //nseBgImageEditor
-
- /**
- * Background Image Editor
- * Cette fonction permet d'éditer les images de fond des éléments avec la classe .bgimageeditor
- * - Déplacement vertical de l'image
- * - Changement de source via Uppy
- */
- function nseBgImageEditor() {
- // Sélection de tous les éléments avec la classe .bgimageeditor
- const editorElements = document.querySelectorAll(".bgimageeditor");
- let selectedElement = null;
- // Configuration et initialisation d'Uppy
- const uppy = initializeUppy();
-
- //Si une image est déjà en cours d'édition
- let isEditing = false;
- //Permet de ne mettre qu'un listener sur l'extérieur du site de l'image (Voir le document.addEventListener)
- let oneListener = false;
- // Configuration des événements pour le modal
- setupModalEvents();
- // Ajout des écouteurs d'événements à chaque élément éditeur
- editorElements.forEach(setupEditorElement);
- /**
- * Initialise Uppy pour la gestion d'upload d'images
- * @returns {Object} Instance Uppy configurée
- */
- function initializeUppy() {
- // Initialisation de Uppy avec restrictions
- const uppy = new Uppy({
- restrictions: {
- maxNumberOfFiles: 1,
- allowedFileTypes: [".jpg", ".jpeg", ".png", ".gif", ".webp"],
- },
- });
- // Configuration du dashboard
- uppy.use(Dashboard, {
- inline: true,
- target: "#uppyBgImageEditor",
- showAddFilesButton: false,
- });
- // Gestion de l'événement de fin d'upload
- uppy.on("complete", (file) => {
- showBgNseModal(false);
-
- // Mise à jour de l'image de fond de l'élément sélectionné
- if (selectedElement) {
- selectedElement.style.backgroundImage = `url('http://livinweb/nseTestPhp/uploads/${file.successful[0].meta.name}')`;
- selectedElement.style.backgroundPositionY = `0px`;
- }
-
- resetSelection();
- uppy.cancelAll();
- });
- // Configuration de l'endpoint pour l'upload
- uppy.use(XHRUpload, { endpoint: "http://livinweb/nseTestPhp/" });
- return uppy;
- }
- /**
- * Configure les événements pour le modal
- */
- function setupModalEvents() {
- const modal = document.getElementById("modalBgImageEditorBackground");
-
- // Fermer le modal lors d'un clic en dehors du contenu
- modal.addEventListener("click", (e) => {
- if (e.target === modal) {
- showBgNseModal(false);
- }
- });
- }
- /**
- * Affiche ou masque le modal d'édition d'image
- * @param {boolean} shouldShow - Indique si le modal doit être affiché ou masqué
- */
- function showBgNseModal(shouldShow) {
- const modal = document.getElementById("modalBgImageEditorBackground");
- modal.style.display = shouldShow ? "flex" : "none";
- }
- /**
- * Affiche le sous-menu d'édition d'image
- */
- function showBgImageEditorMenu() {
- const menuElements = document.querySelectorAll(".bgImageEditorMenu");
- if (menuElements.length > 0) {
- menuElements[0].style.display = "block";
- // Configuration du bouton de changement de source
- const sourceButtons = document.querySelectorAll(".bgimageeditorsrc");
- if (sourceButtons.length > 0) {
- sourceButtons[0].addEventListener('click', () => {
- showBgNseModal(true);
- });
- }
- }
- }
- /**
- * Récupère la position actuelle du background
- * @param {Element} element - L'élément dont on veut récupérer la position du background
- * @returns {Array} - Tableau contenant les positions X et Y en pixels
- */
- function getBgPosition(element) {
- const [x, y] = getComputedStyle(element).backgroundPosition.split(" ");
- return [parseFloat(x) || 0, parseFloat(y) || 0];
- }
- /**
- * Configure un élément éditeur avec les événements nécessaires
- * @param {Element} element - L'élément à configurer
- */
- function setupEditorElement(element) {
- // Variables pour le drag and drop
- let isDragging = false;
- let startX, startY;
- let origX = 0, origY = 0;
- let imageWidth, imageHeight;
- // Ajout de l'événement click (une seule fois) pour initialiser l'édition
- element.addEventListener("click", (el)=>{
- initEditor(el.target);
- });
-
- function initEditor(e) {
-
- /**
- * Valide l'image de fond
- */
- document.querySelectorAll('.bgimageeditorvalidate')[0].addEventListener('click', validate);
-
- if(isEditing) return;
- isEditing = true;
- // On retire l'écouteur initial pour éviter les doubles initialisations
- //element.removeEventListener("click", initEditor);
-
- // Marquer l'élément comme sélectionné
- resetSelection();
- element.classList.add("nsebgimageselected");
- selectedElement = element;
- // Afficher le menu d'édition
- showBgImageEditorMenu();
- // 1) Extraction de l'URL du background
- let backgroundStyle = getComputedStyle(element).backgroundImage;
- let urlMatch = backgroundStyle.match(/url\(["']?(.*?)["']?\)/);
- if (!urlMatch) return; // Pas d'image, on arrête
-
- let imageUrl = urlMatch[1];
- // 2) Chargement de l'image pour connaître ses dimensions naturelles
- uppy.on("complete", (file) => {
- img = new Image();
- img.onload = () => {
- imageWidth = img.naturalWidth;
- imageHeight = img.naturalHeight;
- };
- imageUrl = `http://livinweb/nseTestPhp/uploads/${file.successful[0].meta.name}`;
-
- uninitEditor(element);
- initEditor(element);
- })
- let img = new Image();
- img.onload = () => {
- imageWidth = img.naturalWidth;
- imageHeight = img.naturalHeight;
- };
- img.src = imageUrl;
-
- // 3) Configuration des événements de drag
- element.addEventListener("mousedown", startDragging);
-
- // Empêcher le drag natif du navigateur
- element.addEventListener("dragstart", e => e.preventDefault());
- };
- /**
- * Commence le drag de l'image de fond
- * @param {MouseEvent} e - L'événement mousedown
- */
- function startDragging(e) {
- e.preventDefault();
- isDragging = true;
- [origX, origY] = getBgPosition(element);
- startX = e.clientX;
- startY = e.clientY;
- element.style.cursor = "grabbing";
- element.style.backgroundRepeat = "no-repeat";
- // Ajouter les écouteurs temporaires pour le mouvement et la fin du drag
- document.addEventListener("mousemove", handleDragging);
- document.addEventListener("mouseup", stopDragging);
- }
- /**
- * Gère le déplacement pendant le drag
- * @param {MouseEvent} e - L'événement mousemove
- */
- function handleDragging(e) {
- if (!isDragging) return;
-
- let dy = e.clientY - startY;
- let newY = origY + dy;
- // 4) Contraintes sur le déplacement vertical
- if (imageWidth && imageHeight) {
- let containerWidth = element.clientWidth;
- let containerHeight = element.clientHeight;
- /*
- * imageHeight et imageWidth : Hauteur et largeur de l'image d'origine (source)
- * containerHeight et containerWidth : Hauteur et largeur du conteneur (canvas)
- * minY : Position minimale du background-position sur l'axe vertical en px
- * maxY : Position maximale du background-position sur l'axe vertical en px
- */
-
- // On borne verticalement
- let minY = Math.min(containerHeight - (containerWidth * (imageHeight / imageWidth)), 0);
- let maxY = 0;
-
- // Application des limites
- newY = Math.max(minY, Math.min(maxY, newY));
- }
- // Application de la nouvelle position
- element.style.backgroundPositionY = `${newY}px`;
- console.log(newY);
- }
- /**
- * Arrête le drag
- */
- function stopDragging() {
- if (!isDragging) return;
- isDragging = false;
- element.style.cursor = "";
-
- // Supprimer les écouteurs temporaires
- document.removeEventListener("mousemove", handleDragging);
- document.removeEventListener("mouseup", stopDragging);
- }
- /**
- * On déselectionne l'élément
- */
- function uninitEditor(e){
- e.removeEventListener("mousemove", handleDragging);
- e.removeEventListener("mouseup", stopDragging);
- e.removeEventListener("mousedown", startDragging);
- e.classList.remove("nsebgimageselected");
-
-
- let menu = document.querySelector(".bgImageEditorMenu");
- menu.style.display = "none";
- e.addEventListener("click", initEditor);
- //fin de l'édition
- isEditing = false;
- }
- function validate(){
- document.querySelectorAll('.bgimageeditorvalidate')[0].removeEventListener('click', validate);
- console.log("Nouvelle Source :" + element.style.backgroundImage, "Nouvelle Position :" + element.style.backgroundPositionY);
- uninitEditor(element);
- }
- /**
- * Ajoute un listener sur le document pour détecter si l'utilisateur clique autre part.
- */
- if(!oneListener){
- oneListener = true;
- document.addEventListener('click', function (e) {
- // Si pas en édition, on ne fait rien
- if (!isEditing || !selectedElement) return;
-
- // Si le clic est dans l'élément en cours ou dans le menu, on ignore
- const editorMenu = document.querySelector('.bgImageEditorMenu');
- const bgImageModal = document.querySelector('#modalBgImageEditorBackground');
-
- if (selectedElement.contains(e.target) || editorMenu.contains(e.target) || bgImageModal.contains(e.target)) return;
-
- console.log(selectedElement);
- // Sinon, on annule l'édition
- if(confirm("Voulez-vous vraiment annuler l'édition ?")){
- uninitEditor(selectedElement)
- };
- return;
- });
- }
- }
- /**
- * Réinitialise la sélection actuelle
- */
- function resetSelection() {
- let selectedElements = document.querySelectorAll('.nsebgimageselected');
- selectedElements.forEach(el => el.classList.remove('nsebgimageselected'));
- selectedElement = null;
- }
- }
- // 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();
- putNbColumn();
- putWidth();
- putPadding();
- //$('#body').off('click');
- //$('section').off('click');
- //nseFileEditor
- //nseImageEditor(false);
- nseBgImageEditor();
- // define the public API
- var API = {};
- API.version = version;
- // API.add = add;
- // API.get_array = get_array;
- return API;
- })();
|