index.js 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207
  1. /**
  2. *
  3. * newsiteeditor.js - gestion de l'interface de NewSiteEditor
  4. *
  5. * Modifications:
  6. * - 2022/07/12 - V.1.0 0 - B.Bouaphakeo - création
  7. * - 2025/04/14 - V1.0.1 - E.Podvin - fix hover when siteeditor is activated with tinymce
  8. * - 2025/04/24 - V1.0.2 - C.Nelhomme - Fix prevent click problem and unclickable button + update Tinymce settings
  9. *
  10. * @copyright Intersel 2022
  11. */
  12. //debugger;
  13. import {
  14. Uppy,
  15. Dashboard,
  16. XHRUpload,
  17. } from "https://releases.transloadit.com/uppy/v4.13.3/uppy.min.mjs";
  18. let current = {};
  19. let NEWSITEEDITOR = (function () {
  20. let version = "1.0.2";
  21. //set data-data for content and title
  22. function dataData(who) {
  23. var obj = {};
  24. var title;
  25. var field = $(who).attr("field");
  26. const sync = { syncsite: 1 };
  27. //if(field === 'content'){
  28. if (field !== "pagetitle" && field !== "longtitle") {
  29. if (
  30. who.innerHTML === "" ||
  31. who.innerHTML.includes('<br data-mce-bogus="1">')
  32. ) {
  33. obj[field] = who.innerHTML;
  34. //$(who).parents('.textcontent:first').hide(); //EPO: Why do we need to do that?
  35. } else {
  36. obj[field] = who.innerHTML;
  37. }
  38. } else {
  39. if (
  40. who.innerHTML === "" ||
  41. who.innerHTML.includes('<br data-mce-bogus="1">')
  42. ) {
  43. title = { longtitle: "--" };
  44. $(who).parents(".equalHeight:first").hide();
  45. } else {
  46. title = { longtitle: who.innerHTML };
  47. }
  48. }
  49. Object.assign(obj, title);
  50. Object.assign(obj, sync);
  51. return $(who).attr("data-data", JSON.stringify(obj));
  52. }
  53. // REST : PUT method to put the content of the website in the manager
  54. function saveContent() {
  55. $(".siteeditor").blur(function () {
  56. dataData(this);
  57. blapyTools.ajaxSimpleAction(this);
  58. });
  59. }
  60. // Settings available for the richtext editor
  61. function TinyMCE() {
  62. // debugger;
  63. $.doTimeout("startTinyMCE", 200, function () {
  64. tinymce.init({
  65. selector: ".siteeditor",
  66. inline: true,
  67. plugins: "link, textcolor, table, preview",
  68. menubar: false,
  69. toolbar: [
  70. "undo redo | bold italic underline | link unlink | fontselect fontsizeselect",
  71. "forecolor backcolor | alignjustify alignleft aligncenter alignright alignfull | numlist bullist outdent indent | table | styleselect",
  72. ],
  73. fontsize_formats: "8px 10px 12px 14px 18px 24px 26px 34px",
  74. //, valid_elements: 'p[style],strong,em,span[style],a[href],ul,ol,li'
  75. //, valid_styles: {'*': 'font-size,font-family,color,text-decoration,text-align'}
  76. powerpaste_word_import: "clean",
  77. powerpaste_html_import: "clean",
  78. setup: function (editor) {
  79. editor.on("click", function (el) {
  80. el.preventDefault();
  81. el.stopImmediatePropagation();
  82. });
  83. editor.on("keydown", function (el) {
  84. if (
  85. el.code === "ArrowRight" ||
  86. el.code === "ArrowLeft" ||
  87. el.code === "ArrowUp" ||
  88. el.code === "ArrowDown"
  89. ) {
  90. el.stopPropagation();
  91. }
  92. });
  93. },
  94. }); //end init
  95. }); //end dotimeout
  96. }
  97. //REST : Get method to get the title of the resource in sidebar
  98. function getTitle(who) {
  99. var transform = $("h2").css("text-transform");
  100. $(who).prepend(
  101. '<p id="resourceName" method="GET" style="text-transform:' +
  102. transform +
  103. ';"></p>'
  104. );
  105. hrefRestNse("#resourceName", "longtitle");
  106. blapyTools.ajaxSimpleAction($("#resourceName"), function (data0) {
  107. var title = data0.data.title;
  108. if (title === "" || title == "--") {
  109. hrefRestNse("#resourceName", "pagetitle");
  110. blapyTools.ajaxSimpleAction($("#resourceName"), function (data1) {
  111. var title1 = data1.data.title;
  112. $("#resourceName").html(title1);
  113. //console.log(title1+' '+3);
  114. });
  115. } else {
  116. $("#resourceName").html(title);
  117. }
  118. });
  119. }
  120. // to put href attribut in 'who' element, with 'what' tv and the element id in the url
  121. function hrefRestNse(who, what) {
  122. /*var pos1 = $('[status="selected"]').attr("class").indexOf("_", $('[status="selected"]').attr("class").indexOf("_") + 1)+1;
  123. var pos2 = $('[status="selected"]').attr("class").indexOf(" ") ;
  124. var currentId = $('[status="selected"]').attr("class").substring(pos1, pos2);*/
  125. var currentId = $('[status="selected"]').attr("data-resourceid");
  126. $(who).attr("href", "/rest/newsiteeditor/" + what + "/" + currentId);
  127. }
  128. // toggle from edit mode to view mode
  129. function view() {
  130. $("#view").click(function () {
  131. //remove attr conteneditable sinon bug avec tinyMCE
  132. tinymce.remove();
  133. tinymce.activeEditor.remove();
  134. $(".mce-item-table").removeClass("mce-item-table");
  135. $("#undo, #redo, #sidebarToggle, #manager, #view").css(
  136. "visibility",
  137. "hidden"
  138. );
  139. $("#wrapper").addClass("no-sidebar");
  140. $("#edit").css("visibility", "");
  141. $('[data-managerButton="true"]')
  142. .removeClass("selected")
  143. .removeAttr("status")
  144. .attr("data-managerbutton", "false");
  145. //Disable all contentEditable added by tinyMce
  146. document.querySelectorAll("[contenteditable=true]").forEach((e) => {
  147. e.removeAttribute("contenteditable");
  148. });
  149. onClickManager(false);
  150. sidebar(false);
  151. linkEnabled(true);
  152. nseImageEditor(false);
  153. });
  154. }
  155. //désactiver les liens href sur sections
  156. function linkEnabled(enableLink) {
  157. if (enableLink) {
  158. $(".siteeditor")
  159. .parents("[data-hrefSave]")
  160. .each(function () {
  161. $(this).attr("href", $(this).attr("data-hrefSave"));
  162. $(this).removeAttr("data-hrefSave");
  163. });
  164. } else {
  165. $(".siteeditor")
  166. .parents("[href]")
  167. .each(function () {
  168. $(this).attr("data-hrefSave", $(this).attr("href"));
  169. $(this).removeAttr("href");
  170. });
  171. }
  172. }
  173. function preventClickEnabled(enableClick) {
  174. let pointerEventsNoneClasses = document.getElementsByClassName(
  175. enableClick ? "pointer-events-none" : "edit-pointer-event"
  176. );
  177. if (pointerEventsNoneClasses.length > 0) {
  178. if (enableClick) {
  179. Array.from(
  180. document.getElementsByClassName("pointer-events-none")
  181. ).forEach((e) => {
  182. e.classList.remove("pointer-events-none");
  183. e.classList.add("edit-pointer-event");
  184. });
  185. } else {
  186. Array.from(
  187. document.getElementsByClassName("edit-pointer-event")
  188. ).forEach((e) => {
  189. e.classList.add("pointer-events-none");
  190. e.classList.remove("edit-pointer-event");
  191. });
  192. }
  193. }
  194. }
  195. // toggle from view to edit mode
  196. function edit() {
  197. $("#edit").click(function () {
  198. TinyMCE();
  199. $(this).css("visibility", "hidden");
  200. $("#undo, #redo, #sidebarToggle, #view, #manager").css("visibility", "");
  201. /*$('section').each(function(){
  202. if ( $(this).attr("data-info") === "" ){
  203. var pos1 = this.getAttribute("class").indexOf("_", this.getAttribute("class").indexOf("_") + 1)+1;
  204. var pos2 = this.getAttribute("class").indexOf(" ") ;
  205. var currentId = this.getAttribute("class").substring(pos1, pos2);
  206. $(this).attr("data-info","managerButton_"+currentId);
  207. }
  208. });*/
  209. $('[data-resourceid!=""][data-resourceid]').attr(
  210. "data-managerbutton",
  211. "true"
  212. );
  213. onClickManager(true);
  214. preventClickEnabled(true);
  215. sidebar(true);
  216. linkEnabled(false);
  217. nseImageEditor(true);
  218. });
  219. }
  220. // to set data-data after clicking undo button
  221. function undo() {
  222. $("#undo").click(function () {
  223. $.doTimeout("TimeOut", 500, function () {
  224. $(".siteeditor").each(function () {
  225. var field = $(this).attr("field");
  226. if (
  227. $(this).attr("data-data") !=
  228. '{"' + field + '":"' + this.innerHTML + '","syncsite":1}'
  229. ) {
  230. dataData(this);
  231. blapyTools.ajaxSimpleAction(this);
  232. }
  233. });
  234. });
  235. });
  236. }
  237. // to set data-data after clicking redo button
  238. function redo() {
  239. $("#redo").click(function () {
  240. $.doTimeout("TimeOut", 500, function () {
  241. $(".siteeditor").each(function () {
  242. var field = $(this).attr("field");
  243. if (
  244. $(this).attr("data-data") !=
  245. '{"' + field + '":"' + this.innerHTML + '","syncsite":1}'
  246. ) {
  247. dataData(this);
  248. blapyTools.ajaxSimpleAction(this);
  249. }
  250. });
  251. });
  252. });
  253. }
  254. // onHover on content you can edit
  255. function onHover() {
  256. $(".siteeditor").hover(
  257. function () {
  258. //debugger;
  259. if (
  260. $(this).attr("contenteditable") ==
  261. "true" /*&& !($(this).is(":focus")) */
  262. ) {
  263. $(this)[0].style.setProperty(
  264. "background-color",
  265. "rgb(0, 0, 255, 0.1)",
  266. "important"
  267. );
  268. }
  269. },
  270. function () {
  271. if ($(this).attr("contenteditable") == "true") {
  272. $(this).css("background-color", "");
  273. }
  274. }
  275. );
  276. }
  277. // onHover on resource you can edit
  278. function onHoverManager() {
  279. $("section").hover(
  280. function () {
  281. if (
  282. this.getAttribute("data-managerbutton") &&
  283. this.getAttribute("data-managerbutton") == "true"
  284. ) {
  285. $(this).addClass("selected");
  286. }
  287. },
  288. function () {
  289. if (
  290. this.getAttribute("data-managerbutton") &&
  291. this.getAttribute("data-managerbutton") == "true" &&
  292. !this.getAttribute("status")
  293. ) {
  294. $(this).removeClass("selected");
  295. }
  296. }
  297. );
  298. }
  299. // display a manager button when clicking on a resource which redirected on the resource clicked manager
  300. function onClickManager(mode) {
  301. //debugger;
  302. if (mode) {
  303. $("#body").on("click.siteeditor", function (event) {
  304. event.stopPropagation();
  305. $('[status="selected"]').removeClass("selected").removeAttr("status");
  306. $("#manager").css("visibility", "hidden").removeAttr("onclick");
  307. });
  308. $("section").on("click.siteeditor", function (event) {
  309. //debugger;
  310. event.stopPropagation();
  311. $('[status="selected"]').removeClass("selected").removeAttr("status");
  312. $("#manager").css("visibility", "hidden").attr("onclick", "");
  313. if (
  314. this.getAttribute("data-managerbutton") &&
  315. this.getAttribute("data-managerbutton") == "true"
  316. ) {
  317. $(this).addClass("selected");
  318. $(this).attr("status", "selected");
  319. var currentId = this.getAttribute("data-resourceid");
  320. $("#manager").attr(
  321. "onclick",
  322. "window.open('/manager/?a=resource/update&id=" + currentId + "');"
  323. );
  324. $("#manager").css("visibility", "visible");
  325. }
  326. });
  327. } else {
  328. $("#body").off("click.siteeditor");
  329. $("section").off("click.siteeditor");
  330. }
  331. }
  332. //toggle between sidebar and nosidebar
  333. function sidebarDisplay(boolean) {
  334. if (boolean) {
  335. $("#noResourceSelected").css("display", "none");
  336. $("#resourceSelected").css("display", "");
  337. } else {
  338. $("#noResourceSelected").css("display", "");
  339. $("#resourceSelected").css("display", "none");
  340. }
  341. }
  342. //When sidebar is open, display the info of the resource selected or "selectionner une ressource" if no resource selected
  343. function sidebar(mode) {
  344. if (mode) {
  345. $("#body").on("click.sidebar", function () {
  346. $("#resourceName").remove();
  347. if ($("#wrapper").attr("class") !== "no-sidebar") {
  348. sidebarDisplay(false);
  349. }
  350. });
  351. $("section").on("click.sidebar", function (e) {
  352. //debugger;
  353. e.stopPropagation();
  354. $("#resourceName").remove();
  355. if (
  356. $("#wrapper").attr("class") !== "no-sidebar" &&
  357. this.getAttribute("data-resourceid")
  358. ) {
  359. getTitle("#resourceSelected");
  360. getNbColumn();
  361. getWidth();
  362. getPadding();
  363. sidebarDisplay(true);
  364. } else {
  365. sidebarDisplay(false);
  366. }
  367. });
  368. } else {
  369. $("#body").off("click.sidebar");
  370. $("section").off("click.sidebar");
  371. }
  372. }
  373. //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
  374. function sidebarToggle() {
  375. $("#sidebarToggle").on("click", function () {
  376. if ($("#wrapper").attr("class") == "no-sidebar") {
  377. var compt = 0;
  378. $("#resourceName").remove();
  379. $("section").each(function () {
  380. if ($(this).attr("status") == "selected") {
  381. compt += 1;
  382. }
  383. });
  384. if (compt > 0) {
  385. getNbColumn();
  386. getWidth();
  387. getPadding();
  388. getTitle("#resourceSelected");
  389. sidebarDisplay(true);
  390. } else {
  391. sidebarDisplay(false);
  392. }
  393. }
  394. $("#wrapper").toggleClass("no-sidebar");
  395. });
  396. }
  397. // REST : get method to know how many column the resource already occupied
  398. function getNbColumn() {
  399. hrefRestNse("#column-select", "nbcolumn");
  400. blapyTools.ajaxSimpleAction($("#column-select"), function (data) {
  401. var bootstrap = data.data.nb;
  402. var nbColumn;
  403. if (bootstrap === null) {
  404. nbColumn = 12;
  405. } else {
  406. pos3 = bootstrap.lastIndexOf("-");
  407. nbColumn = bootstrap.substr(pos3 + 1);
  408. }
  409. $("#column-select").prop("value", nbColumn);
  410. });
  411. }
  412. //REST : Method PUT when a new number of column is selected in sidebar
  413. // Change instantly the number of column on page
  414. function putNbColumn() {
  415. $("#column-select").change(function () {
  416. var valueSelected = $("#column-select").val();
  417. var bootstrap;
  418. //version input number
  419. if (valueSelected < 1) {
  420. valueSelected = 1;
  421. $("#column-select").attr("value", valueSelected);
  422. bootstrap = "col-sm-1";
  423. } else if (valueSelected >= 12) {
  424. valueSelected = 12;
  425. $("#column-select").attr("value", valueSelected);
  426. bootstrap = null;
  427. } else {
  428. $("#column-select").attr("value", valueSelected);
  429. bootstrap = "col-sm-" + valueSelected;
  430. }
  431. //envoyer le nombre de colonne au manager version number
  432. hrefRestNse('[for="column-select"]', "nbcolumn");
  433. if (bootstrap === null) {
  434. $('[for="column-select"]').attr(
  435. "data-data",
  436. '{"tv_nbBootstrapColumn":' + bootstrap + ',"syncsite":1}'
  437. );
  438. } else {
  439. $('[for="column-select"]').attr(
  440. "data-data",
  441. '{"tv_nbBootstrapColumn":"' + bootstrap + '","syncsite":1}'
  442. );
  443. }
  444. blapyTools.ajaxSimpleAction($('[for="column-select"]'));
  445. //dynamique sur la page
  446. var pos3 = $('[status="selected"]').attr("class").indexOf("col-sm");
  447. var pos4 = $('[status="selected"]')
  448. .attr("class")
  449. .indexOf(" ", pos3 + 1);
  450. var currentBootstrap = $('[status="selected"]')
  451. .attr("class")
  452. .substr(pos3, pos4 - pos3);
  453. if (currentBootstrap.startsWith("col-sm")) {
  454. $('[status="selected"]')
  455. .removeClass(currentBootstrap)
  456. .removeClass("selected");
  457. } else {
  458. $('[status="selected"]').removeClass("selected");
  459. }
  460. $('[status="selected"]').addClass(bootstrap).addClass("selected");
  461. if (bootstrap === null) {
  462. $('[status="selected"]').css("clear", "");
  463. } else {
  464. $('[status="selected"]').css("clear", "none");
  465. }
  466. });
  467. }
  468. //REST : get method to get the managers width in the sidebar
  469. function getWidth() {
  470. hrefRestNse("#width", "width");
  471. blapyTools.ajaxSimpleAction($("#width"), function (data) {
  472. var percentage = data.data.width;
  473. //console.log(percentage);
  474. var width;
  475. if (percentage === null) {
  476. width = 100;
  477. } else {
  478. pos3 = percentage.indexOf("%");
  479. width = percentage.substr(0, pos3);
  480. //console.log(width);
  481. }
  482. $("#width").prop("value", width);
  483. });
  484. }
  485. //REST : Method PUT when a new number of column is selected in sidebar
  486. // Change instantly the number of column on page
  487. function putWidth() {
  488. $("#width").change(function () {
  489. var valueSelected = $("#width").val();
  490. var percentage;
  491. //version input
  492. if (valueSelected < 10) {
  493. valueSelected = 10;
  494. $("#width").prop("value", valueSelected);
  495. percentage = "10%";
  496. } else if (valueSelected > 100) {
  497. valueSelected = 100;
  498. $("#width").prop("value", valueSelected);
  499. percentage = "100%";
  500. } else {
  501. $("#width").prop("value", valueSelected);
  502. percentage = valueSelected + "%";
  503. }
  504. //envoyer le nombre de colonne au manager version number
  505. hrefRestNse('[for="width"]', "width");
  506. if (percentage === "100%") {
  507. $('[for="width"]').attr(
  508. "data-data",
  509. '{"tv_sectionWidth":' + null + ',"syncsite":1}'
  510. );
  511. } else {
  512. $('[for="width"]').attr(
  513. "data-data",
  514. '{"tv_sectionWidth":"' + percentage + '","syncsite":1}'
  515. );
  516. }
  517. blapyTools.ajaxSimpleAction($('[for="width"]'));
  518. //dynamique sur la page
  519. $('[status="selected"]').find("div:first").css("width", percentage);
  520. });
  521. }
  522. //REST : get method to get the manager padding in the sidebar
  523. function getPadding() {
  524. hrefRestNse("#paddingTop", "padding");
  525. blapyTools.ajaxSimpleAction($("#paddingTop"), function (data) {
  526. var css = data.data.CSS;
  527. //console.log(css);
  528. var posTop1;
  529. var posTop2;
  530. var posTop3;
  531. var paddingTop;
  532. if (css !== null && css.includes("padding-top")) {
  533. css = css.replace(/ /g, "");
  534. posTop1 = css.indexOf("padding-top");
  535. posTop2 = css.indexOf(":", posTop1 + 1);
  536. posTop3 = css.indexOf(";", posTop1 + 1);
  537. paddingTop = css.substr(posTop2 + 1, posTop3 - posTop2 - 1);
  538. //console.log(paddingTop);
  539. //$('#paddingTop').prop('value',paddingTop);
  540. var paddingTop2;
  541. if (paddingTop.includes("px")) {
  542. $("#paddingTopUnit").prop("value", "px");
  543. posTop4 = paddingTop.indexOf("px");
  544. paddingTop2 = paddingTop.substr(0, posTop4);
  545. //console.log(paddingTop2);
  546. } else if (paddingTop.includes("%")) {
  547. $("#paddingTopUnit").prop("value", "%");
  548. posTop4 = paddingTop.indexOf("%");
  549. paddingTop2 = paddingTop.substr(0, posTop4);
  550. }
  551. $("#paddingTop").prop("value", paddingTop2);
  552. //console.log(paddingTop2);
  553. } else {
  554. $("#paddingTopUnit").prop("value", "px");
  555. $("#paddingTop").prop("value", "");
  556. }
  557. });
  558. hrefRestNse("#paddingBottom", "padding");
  559. blapyTools.ajaxSimpleAction($("#paddingBottom"), function (data) {
  560. var css = data.data.CSS;
  561. //console.log(css);
  562. var posBot1;
  563. var posBot2;
  564. var posBot3;
  565. var paddingBottom;
  566. if (css !== null && css.includes("padding-bottom")) {
  567. css = css.replace(/ /g, "");
  568. posBot1 = css.indexOf("padding-bottom");
  569. posBot2 = css.indexOf(":", posBot1 + 1);
  570. posBot3 = css.indexOf(";", posBot1 + 1);
  571. paddingBottom = css.substr(posBot2 + 1, posBot3 - posBot2 - 1);
  572. var paddingBottom2;
  573. if (paddingBottom.includes("px")) {
  574. posBot4 = paddingBottom.indexOf("px");
  575. paddingBottom2 = paddingBottom.substr(0, posBot4);
  576. $("#paddingBottomUnit").prop("value", "px");
  577. //console.log(paddingTop2);
  578. } else if (paddingBottom.includes("%")) {
  579. posBot4 = paddingBottom.indexOf("%");
  580. paddingBottom2 = paddingBottom.substr(0, posBot4);
  581. $("#paddingBottomUnit").prop("value", "%");
  582. }
  583. $("#paddingBottom").prop("value", paddingBottom2);
  584. } else {
  585. $("#paddingBottomUnit").prop("value", "px");
  586. $("#paddingBottom").prop("value", "");
  587. }
  588. });
  589. }
  590. // REST : put method to put the sidebar value in the manager
  591. function putPadding() {
  592. $(
  593. "#paddingTop, #paddingBottom, #paddingTopUnit, #paddingBottomUnit"
  594. ).change(function () {
  595. let paddingTop = parseInt($("#paddingTop").val());
  596. if (isNaN(paddingTop)) paddingTop = 0;
  597. let unitTop = $("#paddingTopUnit").val();
  598. let paddingBottom = parseInt($("#paddingBottom").val());
  599. if (isNaN(paddingBottom)) paddingBottom = 0;
  600. let unitBottom = $("#paddingBottomUnit").val();
  601. if (paddingTop > 999) {
  602. paddingTop = 999;
  603. $("#paddingTop").prop("value", paddingTop);
  604. } else if (paddingTop < 0) {
  605. paddingTop = 0;
  606. $("#paddingTop").prop("value", paddingTop);
  607. }
  608. if (paddingBottom > 999) {
  609. paddingBottom = 999;
  610. $("#paddingBottom").prop("value", paddingBottom);
  611. } else if (paddingBottom < 0) {
  612. paddingBottom = 0;
  613. $("#paddingBottom").prop("value", paddingBottom);
  614. }
  615. //envoyer le nombre de colonne au manager version number
  616. hrefRestNse('[for="padding"]', "padding");
  617. $('[for="padding"]').attr(
  618. "data-data",
  619. '{"tv_sectionCSS":"padding-top:' +
  620. paddingTop +
  621. unitTop +
  622. ";padding-bottom:" +
  623. paddingBottom +
  624. unitBottom +
  625. ';","syncsite":1}'
  626. );
  627. if (paddingTop === 0 && paddingBottom === 0) {
  628. $('[for="padding"]').attr(
  629. "data-data",
  630. '{"tv_sectionCSS":"","syncsite":1}'
  631. );
  632. } else if (paddingTop === 0) {
  633. $('[for="padding"]').attr(
  634. "data-data",
  635. '{"tv_sectionCSS":"padding-bottom:' +
  636. paddingBottom +
  637. unitBottom +
  638. ';","syncsite":1}'
  639. );
  640. }
  641. blapyTools.ajaxSimpleAction($('[for="padding"]'));
  642. //dynamique sur la page
  643. if (
  644. (paddingTop === 0 || paddingTop === "") &&
  645. (paddingBottom === 0 || paddingBottom === "")
  646. ) {
  647. $('[status="selected"]').css("padding-top", "");
  648. $('[status="selected"]').css("padding-bottom", "");
  649. } else if (paddingTop === 0 || paddingTop === "") {
  650. $('[status="selected"]').css("padding-top", "");
  651. $('[status="selected"]').css(
  652. "padding-bottom",
  653. paddingBottom + unitBottom
  654. );
  655. } else if (paddingBottom === 0 || paddingBottom === "") {
  656. $('[status="selected"]').css("padding-top", paddingTop + unitTop);
  657. $('[status="selected"]').css("padding-bottom", "");
  658. } else {
  659. $('[status="selected"]').css("padding-top", paddingTop + unitTop);
  660. $('[status="selected"]').css(
  661. "padding-bottom",
  662. paddingBottom + unitBottom
  663. );
  664. }
  665. });
  666. }
  667. //nseImageEditor
  668. let cropper = null;
  669. let pendingFile = null;
  670. let aspectRatio;
  671. function nseImageEditor(active) {
  672. if (!active) {
  673. return;
  674. }
  675. const uppy = new Uppy({
  676. restrictions: {
  677. maxNumberOfFiles: 1,
  678. allowedFileTypes: [".jpg", ".jpeg", ".png", ".gif", ".webp"],
  679. },
  680. });
  681. uppy.use(Dashboard, {
  682. inline: true,
  683. target: "#uppy",
  684. showAddFilesButton: false,
  685. });
  686. uppy.on("file-added", (file) => {
  687. if (file.meta.isCropped) {
  688. return;
  689. }
  690. pendingFile = file;
  691. openCropper(file);
  692. return false;
  693. });
  694. uppy.on("complete", (file) => {
  695. showNseModal(false);
  696. uppy.cancelAll();
  697. console.log(file);
  698. current.element.src =
  699. "http://localhost/php/uploads/" + file.successful[0].meta.name;
  700. });
  701. //Initialiser l'endpoint pour l'upload des fichiers
  702. uppy.use(XHRUpload, { endpoint: "http://localhost/php/index.php" });
  703. const customButton = document.createElement("button");
  704. customButton.innerText = "Edit";
  705. customButton.style.position = "absolute";
  706. customButton.style.display = "none";
  707. customButton.id = "editImageBtn";
  708. document.body.append(customButton);
  709. customButton.onclick = () => showNseModal(true);
  710. const modal = document.getElementById("modalNseBackground");
  711. modal.addEventListener("click", (e) => {
  712. if (e.target === modal) {
  713. showNseModal(false);
  714. }
  715. });
  716. document.addEventListener("click", (event) => {
  717. if (!event.target.classList.contains("imageeditor")) {
  718. customButton.style.display = "none";
  719. document.querySelectorAll(".imageeditor").forEach((el) => {
  720. el.classList.remove("selected-img");
  721. });
  722. }
  723. });
  724. document.querySelectorAll(".imageeditor").forEach((el) => {
  725. el.style.cursor = "pointer";
  726. el.addEventListener("click", (e) => {
  727. const prev = document.querySelector(".imageeditor.selected-img");
  728. if (prev) prev.classList.remove("selected-img");
  729. el.classList.add("selected-img");
  730. if (el.naturalHeight === 0) {
  731. current.aspectRatio = 1;
  732. } else {
  733. current.aspectRatio = el.naturalWidth / el.naturalHeight;
  734. }
  735. current.element = el;
  736. customButton.style.top = e.pageY + 10 + "px";
  737. customButton.style.left = e.pageX + 10 + "px";
  738. customButton.style.display = "block";
  739. });
  740. });
  741. document.getElementById("cropper-cancel").addEventListener("click", () => {
  742. document.getElementById("cropper-modal").classList.remove("active");
  743. if (cropper) {
  744. cropper.destroy();
  745. cropper = null;
  746. }
  747. pendingFile = null;
  748. });
  749. document.getElementById("cropper-confirm").addEventListener("click", () => {
  750. if (!cropper || !pendingFile) return;
  751. cropper.getCroppedCanvas().toBlob((blob) => {
  752. uppy.removeFile(pendingFile.id);
  753. const ts = new Date()
  754. .toISOString()
  755. .replace(/[-:.]/g, "")
  756. .replace("Z", "");
  757. uppy.addFile({
  758. name: ts + ".png",
  759. type: pendingFile.type,
  760. data: blob,
  761. meta: {
  762. isCropped: true,
  763. },
  764. });
  765. // Nettoyage
  766. document.getElementById("cropper-modal").classList.remove("active");
  767. cropper.destroy();
  768. cropper = null;
  769. pendingFile = null;
  770. }, pendingFile.type);
  771. });
  772. }
  773. function openCropper(file) {
  774. const reader = new FileReader();
  775. reader.onload = (e) => {
  776. const cropperImage = document.getElementById("cropper-image");
  777. cropperImage.src = e.target.result;
  778. document.getElementById("cropper-modal").classList.add("active");
  779. if (cropper) {
  780. cropper.destroy();
  781. }
  782. cropper = new Cropper(cropperImage, {
  783. viewMode: 1,
  784. aspectRatio: current.aspectRatio,
  785. autoCropArea: 1,
  786. });
  787. };
  788. reader.readAsDataURL(file.data);
  789. }
  790. function showNseModal(shouldShow) {
  791. const modal = document.getElementById("modalNseBackground");
  792. modal.style.display = shouldShow ? "flex" : "none";
  793. }
  794. //Fin du nseImageEditor
  795. //nseBgImageEditor
  796. /**
  797. * Background Image Editor
  798. * Cette fonction permet d'éditer les images de fond des éléments avec la classe .bgimageeditor
  799. * - Déplacement vertical de l'image
  800. * - Changement de source via Uppy
  801. */
  802. function nseBgImageEditor() {
  803. // Sélection de tous les éléments avec la classe .bgimageeditor
  804. const editorElements = document.querySelectorAll(".bgimageeditor");
  805. let selectedElement = null;
  806. // Configuration et initialisation d'Uppy
  807. const uppy = initializeUppy();
  808. //Si une image est déjà en cours d'édition
  809. let isEditing = false;
  810. // Configuration des événements pour le modal
  811. setupModalEvents();
  812. // Ajout des écouteurs d'événements à chaque élément éditeur
  813. editorElements.forEach(setupEditorElement);
  814. /**
  815. * Initialise Uppy pour la gestion d'upload d'images
  816. * @returns {Object} Instance Uppy configurée
  817. */
  818. function initializeUppy() {
  819. // Initialisation de Uppy avec restrictions
  820. const uppy = new Uppy({
  821. restrictions: {
  822. maxNumberOfFiles: 1,
  823. allowedFileTypes: [".jpg", ".jpeg", ".png", ".gif", ".webp"],
  824. },
  825. });
  826. // Configuration du dashboard
  827. uppy.use(Dashboard, {
  828. inline: true,
  829. target: "#uppyBgImageEditor",
  830. showAddFilesButton: false,
  831. });
  832. // Gestion de l'événement de fin d'upload
  833. uppy.on("complete", (file) => {
  834. showBgNseModal(false);
  835. // Mise à jour de l'image de fond de l'élément sélectionné
  836. if (selectedElement) {
  837. selectedElement.style.backgroundImage = `url('http://livinweb/nseTestPhp/uploads/${file.successful[0].meta.name}')`;
  838. selectedElement.style.backgroundPositionY = `0px`;
  839. }
  840. resetSelection();
  841. uppy.cancelAll();
  842. });
  843. // Configuration de l'endpoint pour l'upload
  844. uppy.use(XHRUpload, { endpoint: "http://livinweb/nseTestPhp/" });
  845. return uppy;
  846. }
  847. /**
  848. * Configure les événements pour le modal
  849. */
  850. function setupModalEvents() {
  851. const modal = document.getElementById("modalBgImageEditorBackground");
  852. // Fermer le modal lors d'un clic en dehors du contenu
  853. modal.addEventListener("click", (e) => {
  854. if (e.target === modal) {
  855. showBgNseModal(false);
  856. }
  857. });
  858. }
  859. /**
  860. * Affiche ou masque le modal d'édition d'image
  861. * @param {boolean} shouldShow - Indique si le modal doit être affiché ou masqué
  862. */
  863. function showBgNseModal(shouldShow) {
  864. const modal = document.getElementById("modalBgImageEditorBackground");
  865. modal.style.display = shouldShow ? "flex" : "none";
  866. }
  867. /**
  868. * Affiche le sous-menu d'édition d'image
  869. */
  870. function showBgImageEditorMenu() {
  871. const menuElements = document.querySelectorAll(".bgImageEditorMenu");
  872. if (menuElements.length > 0) {
  873. menuElements[0].style.display = "block";
  874. // Configuration du bouton de changement de source
  875. const sourceButtons = document.querySelectorAll(".bgimageeditorsrc");
  876. if (sourceButtons.length > 0) {
  877. sourceButtons[0].addEventListener('click', () => {
  878. showBgNseModal(true);
  879. });
  880. }
  881. }
  882. }
  883. /**
  884. * Récupère la position actuelle du background
  885. * @param {Element} element - L'élément dont on veut récupérer la position du background
  886. * @returns {Array} - Tableau contenant les positions X et Y en pixels
  887. */
  888. function getBgPosition(element) {
  889. const [x, y] = getComputedStyle(element).backgroundPosition.split(" ");
  890. return [parseFloat(x) || 0, parseFloat(y) || 0];
  891. }
  892. /**
  893. * Configure un élément éditeur avec les événements nécessaires
  894. * @param {Element} element - L'élément à configurer
  895. */
  896. function setupEditorElement(element) {
  897. // Variables pour le drag and drop
  898. let isDragging = false;
  899. let startX, startY;
  900. let origX = 0, origY = 0;
  901. let imageWidth, imageHeight;
  902. // Ajout de l'événement click (une seule fois) pour initialiser l'édition
  903. element.addEventListener("click", (el)=>{
  904. initEditor(el.target);
  905. });
  906. function initEditor(e) {
  907. /**
  908. * Valide l'image de fond
  909. */
  910. document.querySelectorAll('.bgimageeditorvalidate')[0].addEventListener('click', validate);
  911. if(isEditing) return;
  912. isEditing = true;
  913. // On retire l'écouteur initial pour éviter les doubles initialisations
  914. //element.removeEventListener("click", initEditor);
  915. // Marquer l'élément comme sélectionné
  916. resetSelection();
  917. element.classList.add("nsebgimageselected");
  918. selectedElement = element;
  919. // Afficher le menu d'édition
  920. showBgImageEditorMenu();
  921. // 1) Extraction de l'URL du background
  922. let backgroundStyle = getComputedStyle(element).backgroundImage;
  923. let urlMatch = backgroundStyle.match(/url\(["']?(.*?)["']?\)/);
  924. if (!urlMatch) return; // Pas d'image, on arrête
  925. let imageUrl = urlMatch[1];
  926. // 2) Chargement de l'image pour connaître ses dimensions naturelles
  927. uppy.on("complete", (file) => {
  928. img = new Image();
  929. img.onload = () => {
  930. imageWidth = img.naturalWidth;
  931. imageHeight = img.naturalHeight;
  932. };
  933. imageUrl = `http://livinweb/nseTestPhp/uploads/${file.successful[0].meta.name}`;
  934. uninitEditor(element);
  935. initEditor(element);
  936. })
  937. let img = new Image();
  938. img.onload = () => {
  939. imageWidth = img.naturalWidth;
  940. imageHeight = img.naturalHeight;
  941. };
  942. img.src = imageUrl;
  943. // 3) Configuration des événements de drag
  944. element.addEventListener("mousedown", startDragging);
  945. // Empêcher le drag natif du navigateur
  946. element.addEventListener("dragstart", e => e.preventDefault());
  947. };
  948. /**
  949. * Commence le drag de l'image de fond
  950. * @param {MouseEvent} e - L'événement mousedown
  951. */
  952. function startDragging(e) {
  953. e.preventDefault();
  954. isDragging = true;
  955. [origX, origY] = getBgPosition(element);
  956. startX = e.clientX;
  957. startY = e.clientY;
  958. element.style.cursor = "grabbing";
  959. element.style.backgroundRepeat = "no-repeat";
  960. // Ajouter les écouteurs temporaires pour le mouvement et la fin du drag
  961. document.addEventListener("mousemove", handleDragging);
  962. document.addEventListener("mouseup", stopDragging);
  963. }
  964. /**
  965. * Gère le déplacement pendant le drag
  966. * @param {MouseEvent} e - L'événement mousemove
  967. */
  968. function handleDragging(e) {
  969. if (!isDragging) return;
  970. let dy = e.clientY - startY;
  971. let newY = origY + dy;
  972. // 4) Contraintes sur le déplacement vertical
  973. if (imageWidth && imageHeight) {
  974. let containerWidth = element.clientWidth;
  975. let containerHeight = element.clientHeight;
  976. /*
  977. * imageHeight et imageWidth : Hauteur et largeur de l'image d'origine (source)
  978. * containerHeight et containerWidth : Hauteur et largeur du conteneur (canvas)
  979. * minY : Position minimale du background-position sur l'axe vertical en px
  980. * maxY : Position maximale du background-position sur l'axe vertical en px
  981. */
  982. // On borne verticalement
  983. let minY = Math.min(containerHeight - (containerWidth * (imageHeight / imageWidth)), 0);
  984. let maxY = 0;
  985. // Application des limites
  986. newY = Math.max(minY, Math.min(maxY, newY));
  987. }
  988. // Application de la nouvelle position
  989. element.style.backgroundPositionY = `${newY}px`;
  990. console.log(newY);
  991. }
  992. /**
  993. * Arrête le drag
  994. */
  995. function stopDragging() {
  996. if (!isDragging) return;
  997. isDragging = false;
  998. element.style.cursor = "";
  999. // Supprimer les écouteurs temporaires
  1000. document.removeEventListener("mousemove", handleDragging);
  1001. document.removeEventListener("mouseup", stopDragging);
  1002. }
  1003. /**
  1004. * On déselectionne l'élément
  1005. */
  1006. function uninitEditor(e){
  1007. e.removeEventListener("mousemove", handleDragging);
  1008. e.removeEventListener("mouseup", stopDragging);
  1009. e.removeEventListener("mousedown", startDragging);
  1010. e.classList.remove("nsebgimageselected");
  1011. let menu = document.querySelector(".bgImageEditorMenu");
  1012. menu.style.display = "none";
  1013. e.addEventListener("click", initEditor);
  1014. //fin de l'édition
  1015. isEditing = false;
  1016. }
  1017. function validate(){
  1018. document.querySelectorAll('.bgimageeditorvalidate')[0].removeEventListener('click', validate);
  1019. console.log("Nouvelle Source :" + element.style.backgroundImage, "Nouvelle Position :" + element.style.backgroundPositionY);
  1020. uninitEditor(element);
  1021. }
  1022. /**
  1023. * Ajoute un listener sur le document pour détecter si l'utilisateur clique autre part.
  1024. */
  1025. document.addEventListener('click', function (e) {
  1026. // Si pas en édition, on ne fait rien
  1027. if (!isEditing || !selectedElement) return;
  1028. // Si le clic est dans l'élément en cours ou dans le menu, on ignore
  1029. const editorMenu = document.querySelector('.bgImageEditorMenu');
  1030. const bgImageModal = document.querySelector('#modalBgImageEditorBackground');
  1031. if (selectedElement.contains(e.target) || editorMenu.contains(e.target) || bgImageModal.contains(e.target)) return;
  1032. console.log(selectedElement);
  1033. // Sinon, on annule l'édition
  1034. if(confirm("Voulez-vous vraiment annuler l'édition ?")){
  1035. uninitEditor(selectedElement)
  1036. };
  1037. return;
  1038. },{once: true});
  1039. }
  1040. /**
  1041. * Réinitialise la sélection actuelle
  1042. */
  1043. function resetSelection() {
  1044. let selectedElements = document.querySelectorAll('.nsebgimageselected');
  1045. selectedElements.forEach(el => el.classList.remove('nsebgimageselected'));
  1046. selectedElement = null;
  1047. }
  1048. }
  1049. // to set data-data for every element when opening the page
  1050. $(".siteeditor").each(function () {
  1051. dataData(this);
  1052. });
  1053. //window.addEventListener('DOMContentLoaded', newsiteeditor, false);
  1054. view();
  1055. edit();
  1056. onHover();
  1057. saveContent();
  1058. undo();
  1059. redo();
  1060. onHoverManager();
  1061. //onClickManager();
  1062. //sidebar();
  1063. sidebarToggle();
  1064. putNbColumn();
  1065. putWidth();
  1066. putPadding();
  1067. //$('#body').off('click');
  1068. //$('section').off('click');
  1069. //nseFileEditor
  1070. //nseImageEditor(false);
  1071. nseBgImageEditor();
  1072. // define the public API
  1073. var API = {};
  1074. API.version = version;
  1075. // API.add = add;
  1076. // API.get_array = get_array;
  1077. return API;
  1078. })();