actuel-inactuel/assets/front-comments/index.js

36 lines
15 KiB
JavaScript
Raw Normal View History

2024-04-06 10:08:45 +02:00
(function(){"use strict";const p={comments:[],suggestions:[],author:null,page:{id:null,uri:null},csrf:null,save(f){const t={};t[f]=this[f];const u={method:"PATCH",headers:{"X-CSRF":this.csrf},body:JSON.stringify(t).replaceAll("_","")};return fetch("/api/pages/"+this.page.id,u).then(c=>c.ok?c.json():Promise.reject("Front comments plugin - can't add comment: "+c.statusText)).then(c=>{console.log(c),console.log("Front comments plugin - comment successfully added.")}).catch(c=>Promise.reject(c))}};var R=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function G(f){return f&&f.__esModule&&Object.prototype.hasOwnProperty.call(f,"default")?f.default:f}var U={exports:{}};(function(f,t){(function(u,c){f.exports=c()})(R,function(){var u=1e3,c=6e4,b=36e5,P="millisecond",w="second",M="minute",C="hour",D="day",j="week",y="month",J="quarter",x="year",E="date",Z="Invalid Date",it=/^(\d{4})[-/]?(\d{1,2})?[-/]?(\d{0,2})[Tt\s]*(\d{1,2})?:?(\d{1,2})?:?(\d{1,2})?[.:]?(\d+)?$/,rt=/\[([^\]]+)]|Y{1,4}|M{1,4}|D{1,2}|d{1,4}|H{1,2}|h{1,2}|a|A|m{1,2}|s{1,2}|Z{1,2}|SSS/g,ot={name:"en",weekdays:"Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),months:"January_February_March_April_May_June_July_August_September_October_November_December".split("_"),ordinal:function(r){var s=["th","st","nd","rd"],e=r%100;return"["+r+(s[(e-20)%10]||s[e]||s[0])+"]"}},I=function(r,s,e){var i=String(r);return!i||i.length>=s?r:""+Array(s+1-i.length).join(e)+r},at={s:I,z:function(r){var s=-r.utcOffset(),e=Math.abs(s),i=Math.floor(e/60),n=e%60;return(s<=0?"+":"-")+I(i,2,"0")+":"+I(n,2,"0")},m:function r(s,e){if(s.date()<e.date())return-r(e,s);var i=12*(e.year()-s.year())+(e.month()-s.month()),n=s.clone().add(i,y),o=e-n<0,a=s.clone().add(i+(o?-1:1),y);return+(-(i+(e-n)/(o?n-a:a-n))||0)},a:function(r){return r<0?Math.ceil(r)||0:Math.floor(r)},p:function(r){return{M:y,y:x,w:j,d:D,D:E,h:C,m:M,s:w,ms:P,Q:J}[r]||String(r||"").toLowerCase().replace(/s$/,"")},u:function(r){return r===void 0}},W="en",L={};L[W]=ot;var V="$isDayjsObject",N=function(r){return r instanceof F||!(!r||!r[V])},H=function r(s,e,i){var n;if(!s)return W;if(typeof s=="string"){var o=s.toLowerCase();L[o]&&(n=o),e&&(L[o]=e,n=o);var a=s.split("-");if(!n&&a.length>1)return r(a[0])}else{var h=s.name;L[h]=s,n=h}return!i&&n&&(W=n),n||!i&&W},m=function(r,s){if(N(r))return r.clone();var e=typeof s=="object"?s:{};return e.date=r,e.args=arguments,new F(e)},d=at;d.l=H,d.i=N,d.w=function(r,s){return m(r,{locale:s.$L,utc:s.$u,x:s.$x,$offset:s.$offset})};var F=function(){function r(e){this.$L=H(e.locale,null,!0),this.parse(e),this.$x=this.$x||e.x||{},this[V]=!0}var s=r.prototype;return s.parse=function(e){this.$d=function(i){var n=i.date,o=i.utc;if(n===null)return new Date(NaN);if(d.u(n))return new Date;if(n instanceof Date)return new Date(n);if(typeof n=="string"&&!/Z$/i.test(n)){var a=n.match(it);if(a){var h=a[2]-1||0,l=(a[7]||"0").substring(0,3);return o?new Date(Date.UTC(a[1],h,a[3]||1,a[4]||0,a[5]||0,a[6]||0,l)):new Date(a[1],h,a[3]||1,a[4]||0,a[5]||0,a[6]||0,l)}}return new Date(n)}(e),this.init()},s.init=function(){var e=this.$d;this.$y=e.getFullYear(),this.$M=e.getMonth(),this.$D=e.getDate(),this.$W=e.getDay(),this.$H=e.getHours(),this.$m=e.getMinutes(),this.$s=e.getSeconds(),this.$ms=e.getMilliseconds()},s.$utils=function(){return d},s.isValid=function(){return this.$d.toString()!==Z},s.isSame=function(e,i){var n=m(e);return this.startOf(i)<=n&&n<=this.endOf(i)},s.isAfter=function(e,i){return m(e)<this.startOf(i)},s.isBefore=function(e,i){return this.endOf(i)<m(e)},s.$g=function(e,i,n){return d.u(e)?this[i]:this.set(n,e)},s.unix=function(){return Math.floor(this.valueOf()/1e3)},s.valueOf=function(){return this.$d.getTime()},s.startOf=function(e,i){var n=this,o=!!d.u(i)||i,a=d.p(e),h=function(A,$){var S=d.w(n.$u?Date.UTC(n.$y,$,A):new Date(n.$y,$,A),n);return o?S:S.endOf(D)},l=function(A,$){return d.w(n.toDate()[A].apply(n.toDate("s"),(o?[0,0,0,0]:[23,59,59,999]).slice($)),n)},_=this.$W,g=this.$M,v=this.$D,k="set"+(this.$u?"UTC":"");switch(a
id="${this.id}"
class="fc__bubble fc__btn"
style="left: ${this.position.left}; top: ${this.position.top};">
${this.author.slice(0,1)}
</button>`);return t.addEventListener("mouseenter",()=>{setTimeout(()=>{this.expand()},10)}),this.node=t,t}expand(){const t=this.windowWidth?`<li class="fc__context-item">
<b>Largeur fenêtre</b> : ${this.windowWidth}px <button class="fc__open-window" title="Ouvrir une fenêtre de cette largeur">voir</button>
</li>`:"",u=this.userAgent?`<li class="fc__context-item">
<b>Agent utilisateur</b> : <br>
${this.userAgent}
</li>`:"",c=this.userAgent||this.windowWidth?`
<div class="fc__context">
<input id="collapsible" class="fc__toggle" type="checkbox">
<label for="collapsible" class="fc__label-toggle" title="État du navigateur au moment de l'ajout du commentaire">Contexte</label>
<div class="fc__collapsible-content">
<ul class="fc__content-inner">
${t}
${u}
</ul>
</div>
</div>
`:"",b=this._injectNode(`<div
class="fc__comment"
style="left: ${this.position.left}; top: ${this.position.top};"
>
<button class="fc__btn fc__comment-delete" title="Remove comment">
<img class="fc__icon" src="${p.filesPath}/icons/delete.svg">
</button>
<span class="fc__author">${this.author}</span><br><span class="fc__datetime">${this.date} à ${this.time}</span><br>
<p>${this.message}</p>
${c}
</div>`);q.fixOffscreen(b),b.querySelector(".fc__comment-delete").addEventListener("click",()=>{this.remove()});const w=document.querySelector(".fc__open-window");return w&&w.addEventListener("click",()=>{window.open(window.location.href,"",`width=${this.windowWidth}, height=800`)}),b.addEventListener("mouseleave",()=>{setTimeout(()=>{this.toBubble()},10)}),this.node=b,b}_injectNode(t){this.node&&document.body.removeChild(this.node);const u=document.createElement("div");u.innerHTML=t;const c=u.firstChild;return document.body.appendChild(c),c}async remove(){const t={method:"PATCH"};fetch(`/comments/delete/${this.id}/${p.page.uri}.json`,t).then(u=>u.json()).then(u=>{p.comments=p.comments.filter(c=>c.id!=this.id),document.body.removeChild(this.node)}).catch(u=>{console.log(u)})}}class et{constructor(){this._panel,this._textArea}create(){this._panel=this._createPanel(),this._textArea=this._createTextArea();const t=this._createBtns();this._panel.appendChild(this._textArea),this._panel.appendChild(t),document.body.appendChild(this._panel),this._textArea.focus(),q.fixOffscreen(this._panel),document.querySelector(".fc__edition-panel__remove-btn").addEventListener("click",()=>{document.body.removeChild(this._panel)})}_createPanel(){const t=document.createElement("div");return t.classList.add("fc__edition-panel"),t.style.left=this._getMousePos().x+"px",t.style.top=this._getMousePos().y+window.scrollY+"px",t}_createBtns(){const t=document.createElement("div");t.classList.add("fc__edition-panel__btns");const u=document.createElement("button");u.classList.add("fc__edition-panel__remove-btn"),u.textContent="supprimer";const c=document.createElement("button");return c.classList.add("fc__edition-panel__save-btn"),c.textContent="enregistrer",t.appendChild(u),t.appendChild(c),t}_getMousePos(){return{x:event.clientX,y:event.clientY}}_createTextArea(){const t=document.createElement("textarea");return t.classList.add("fc__text"),t}_getPos(){const t=this._panel.offsetLeft/((window.innerWidth+window.pageXOffset)/100);return{top:this._panel.style.top,left:t+"vw"}}}class z{constructor(){this.position={},this.author="",this.message="",this.id=Date.now(),this.date=X().format("DD/MM/YY"),this.time=X().format("HH:mm"),this.windowWidth=window.innerWidth,this.userAgent=navigator.userAgent}setPosition(t){return this.position=t,this}setAuthor(t){return this.author=t,this}setMessage(t){return this.message=t,this}setId(t){return this.id=t,this}setDate(t){return this.date=t,this}setTime(t){return this.time=t,this}setWindowWidth(t){return this.windowWidth=t,this}setUserAgent(t){return this.userAgent=t,this}build(){return!this.position||!this.author||!this.message?(console.error("Missing required parameters for Comment: position, author, message",this),null):new tt(this.position,this.author,this.message,this.id,this.date,this.time,this.windowWidth,this.userAgent)}}class nt extends et{create(){super.create(),document.querySelector(".fc__edition-panel__save-btn").addEventListener("click",()=>{this._createComment()}),this._textArea.addEventListener("keydown",t=>{t.key==="Enter"&&this._createComment(),t.key==="Escape"&&document.body.removeChild(this._panel)})}async _createComment(){const t=new z().setAuthor(p.author).setMessage(this._textArea.value).setPosition({top:this._getPos().top,left:this._getPos().left}).build();try{p.comments.push(t),await p.save("comments"),t.toBubble(),document.body.removeChild(this._panel)}catch(u){p.comments=p.comments.filter(c=>c.id!==t.id),document.body.removeChild(t.node),console.error("Create comment failed:",u)}return t}}class st{constructor(t){this._button=this._createButton(t),this._initEventListeners()}_createButton(t){const u=document.createElement("div");u.innerHTML=`<button class="fc__btn fc__btn-add fc__btn-add--${t} fc__btn-add--free" title="New comment">
<img class="fc__icon fc__plus" src="${p.filesPath}/icons/chat-box-plus.svg">
</button>`;const c=u.firstChild;return document.body.appendChild(c),c}_initEventListeners(){this._button.addEventListener("click",this._handleClick.bind(this)),window.addEventListener("mousemove",this._handleMouseMove.bind(this)),window.addEventListener("keydown",this._handleKeyDown.bind(this))}_handleClick(t){this._button.classList.contains("fc__btn-add--move")&&(new nt().create(),this._resetPosition()),this._button.classList.toggle("fc__btn-add--move")}_handleMouseMove(t){this._button.classList.contains("fc__btn-add--move")&&(this._button.style.left=t.clientX-48/2+"px",this._button.style.top=t.clientY+window.scrollY-48/2+"px")}_handleKeyDown(t){t.key==="Escape"&&(this._button.classList.remove("fc__btn-add--move"),this._resetPosition())}_resetPosition(){this._button.style.left="",this._button.style.top=""}}document.addEventListener("DOMContentLoaded",()=>{p.author=FCAuthor,p.page.id=FCPageId,p.page.uri=FCPageUri,p.csrf=FCCsrf,p.filesPath=FCFilesPath;try{JSON.parse(FCComments).forEach(t=>{const u=new z().setPosition(t.position).setAuthor(t.author).setMessage(t.message).setId(t.id).setDate(t.date).setTime(t.time).setWindowWidth(t.windowWidth).setUserAgent(t.userAgent).build();u.toBubble(),p.comments.push(u)})}catch(f){console.error("Plugin Front Comments : can't parse comments : ",f),console.log("Comments : ",FCComments)}new st(FCPosition)})})();