Skip to content

Conversation

himn1
Copy link
Collaborator

@himn1 himn1 commented Apr 11, 2025

No description provided.

</tr>
`;
const tbody = document.querySelector("#rooms_list tbody");
tbody.insertAdjacentHTML("beforeend", roomTmpl(room));

Check warning

Code scanning / CodeQL

DOM text reinterpreted as HTML Medium test

DOM text
is reinterpreted as HTML without escaping meta-characters.

Copilot Autofix

AI about 2 months ago

To fix this vulnerability, all user-controlled values that are interpolated into the HTML template (specifically, fields like id, name) should be properly escaped before being injected into HTML. Escaping will prevent HTML/script injection by ensuring any special characters (like <, >, &, etc) in these fields are replaced with their safe entity equivalents. The fix involves:

  • Introducing an HTML-escaping utility function (for example, escapeHtml).
  • Applying escapeHtml to all user-controlled variables before inserting them into the HTML template with ${...} in roomTmpl.
  • Update the relevant lines in roomTmpl for all possibly-tainted variables (id, name, etc).

No new imports are strictly required, but introducing a small well-tested escape function is advisable. All fixes can be implemented within test/dummy/frontend/js/views/user/rooms/List.js without changing external code.


Suggested changeset 1
test/dummy/frontend/js/views/user/rooms/List.js

Autofix patch

Autofix patch
Run the following command in your local git repository to apply this patch
cat << 'EOF' | git apply diff --git a/test/dummy/frontend/js/views/user/rooms/List.js b/test/dummy/frontend/js/views/user/rooms/List.js --- a/test/dummy/frontend/js/views/user/rooms/List.js +++ b/test/dummy/frontend/js/views/user/rooms/List.js @@ -5,25 +5,40 @@ let rooms = []; +// Function to escape user input to prevent XSS +function escapeHtml(unsafe) { + return String(unsafe) + .replace(/&/g, "&amp;") + .replace(/</g, "&lt;") + .replace(/>/g, "&gt;") + .replace(/"/g, "&quot;") + .replace(/'/g, "&#039;"); +} + const roomTmpl = ({ id, name, members_count, joined }) => { + // All variables interpolated into HTML must be escaped + const safeId = escapeHtml(id); + const safeName = escapeHtml(name); + const safeMembersCount = escapeHtml(members_count); + const safeJoined = !!joined; // Boolean - not user-supplied, safe return ` - <tr id="room_${id}"> - <td>${name}</td> - <td class="members">${members_count}</td> + <tr id="room_${safeId}"> + <td>${safeName}</td> + <td class="members">${safeMembersCount}</td> <td> <a rel="nofollow" data-turbo-method="patch" - href="${joined ? `/user/rooms/${id}/leave` : `/user/rooms/${id}/join`}" + href="${safeJoined ? `/user/rooms/${safeId}/leave` : `/user/rooms/${safeId}/join`}" > - ${joined ? "Leave" : "Join"} + ${safeJoined ? "Leave" : "Join"} </a> | <a rel="nofollow" data-turbo-method="delete" data-turbo-confirm="R U sure?" - href="/user/rooms/${id}" + href="/user/rooms/${safeId}" > Destroy </a> EOF
@@ -5,25 +5,40 @@

let rooms = [];

// Function to escape user input to prevent XSS
function escapeHtml(unsafe) {
return String(unsafe)
.replace(/&/g, "&amp;")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;")
.replace(/"/g, "&quot;")
.replace(/'/g, "&#039;");
}

const roomTmpl = ({ id, name, members_count, joined }) => {
// All variables interpolated into HTML must be escaped
const safeId = escapeHtml(id);
const safeName = escapeHtml(name);
const safeMembersCount = escapeHtml(members_count);
const safeJoined = !!joined; // Boolean - not user-supplied, safe
return `
<tr id="room_${id}">
<td>${name}</td>
<td class="members">${members_count}</td>
<tr id="room_${safeId}">
<td>${safeName}</td>
<td class="members">${safeMembersCount}</td>
<td>
<a
rel="nofollow"
data-turbo-method="patch"
href="${joined ? `/user/rooms/${id}/leave` : `/user/rooms/${id}/join`}"
href="${safeJoined ? `/user/rooms/${safeId}/leave` : `/user/rooms/${safeId}/join`}"
>
${joined ? "Leave" : "Join"}
${safeJoined ? "Leave" : "Join"}
</a>
|
<a
rel="nofollow"
data-turbo-method="delete"
data-turbo-confirm="R U sure?"
href="/user/rooms/${id}"
href="/user/rooms/${safeId}"
>
Destroy
</a>
Copilot is powered by AI and may make mistakes. Always verify output.
@@ -1,2 +1 @@
!function(){"use strict";var e,t={91520:function(e,t,r){r(64600),r(56844).c.start();var n=r(97320),a=r(20960),i=r(6640);const s="ADD_ARTICLES",o="PREPEND_ARTICLES",c="REMOVE_ARTICLE",l="SET_ARTICLES",d="UPDATE_ARTICLE",m="ADD_COMMENTS",u="REMOVE_COMMENT",p="SET_COMMENTS",f="UPDATE_COMMENT",y="PREPEND_USERS";function g(e){return{type:s,articles:e}}function h(e){return{type:l,articles:e}}function b(e,t){return{type:d,article:e,index:t}}function w(e,t){return{type:p,comments:e,articleId:t}}function v(e,t,r){return{type:f,comment:e,articleId:t,index:r}}var E=r(18928),_=r(524),I=(0,_.cp)(((e=[],t)=>{switch(t.type){case s:return e.concat(t.articles);case o:return t.articles.concat(e);case c:return e.filter((e=>e.id!==t.id));case l:return t.articles;case d:e[t.index]=t.article;break;default:return e}})),k=(0,_.cp)(((e={},t)=>{switch(t.type){case m:void 0===e[t.articleId]&&(e[t.articleId]=[]),e[t.articleId]=e[t.articleId].concat(t.comments);break;case u:if(null==e[t.articleId])return e;e[t.articleId]=e[t.articleId].filter((e=>e.id!==t.id));break;case p:e[t.articleId]=t.comments;break;case f:{const r=t.articleId;let n=t.index;if(!n){const a=e[r].find((e=>e.id===t.comment.id));n=e[r].indexOf(a)}e[r][n]=t.comment;break}default:return e}})),S=(0,_.cp)(((e=[],t)=>{switch(t.type){case"SET_USERS":return t.users;case y:return t.users.concat(e);default:return e}})),A=(0,E.TL)({articles:I,comments:k,users:S}),C=(0,E.eC)(A);const j=e=>function(t,r,n={}){let a=t[e];if(n.parentId&&(a=a[n.parentId]),void 0===a)return[null,null];const i=a.find((e=>e.id===r));return i?[i,a.indexOf(i)]:[null,null]},z=j("articles"),x=j("comments");function O(e,t,r){var n;return(t="symbol"==typeof(n=function(e,t){if("object"!=typeof e||!e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var n=r.call(e,"string");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(t))?n:String(n))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}class R extends n.Models.Base{constructor(e){super(e),this.published=null!=this.publishedAt}vulgarityLevel(){(null!=this.title&&/fuck/i.exec(this.title)||null!=this.content&&/fuck/i.exec(this.content))&&this.addErrorMessage("Article contains strong language.",{for:"base"})}setDefaultValuesForAdminReview(){this.adminRate=null==this.adminRate?3:this.adminRate,this.categoryId=null==this.categoryId?6:this.categoryId,this.adminReviewStartedAt=Date.now()}}O(R,"identity","Article"),O(R,"resources",{url:"/user/articles",paginate:{per:5},main:{url:"/articles",paginate:{per:3}},admin:{url:"/admin/articles",paginate:{per:4}}}),O(R,"attributes",{title:{validations:{presence:!0,length:{within:[3,255]}}},content:{validations:{presence:!0,length:{minimum:100}},remoteName:"text"},createdAt:{type:"Date",remoteName:"created_at"},updatedAt:{type:"Date",remoteName:"updated_at"},commentsCount:{type:"Int",remoteName:"comments_count"},publishedAt:{type:"Date",remoteName:"published_at"},published:{},adminReview:{remoteName:"admin_review"},adminRate:{type:"Int",remoteName:"admin_rate"},categoryId:{type:"Int",remoteName:"category_id"},adminReviewStartedAt:{remoteName:"admin_review_started_at"}}),O(R,"validate",["vulgarityLevel"]);var B=R;function T(e,t,r){var n;return(t="symbol"==typeof(n=function(e,t){if("object"!=typeof e||!e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var n=r.call(e,"string");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(t))?n:String(n))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}class $ extends n.Models.Base{constructor(e){super(e)}}T($,"identity","Article.Comment"),T($,"remoteName","Comment"),T($,"resources",{url:"/user/articles/:articleId/comments",paginate:{per:10},main:{url:"/articles/:articleId/comments",paginate:{per:5,param:"page-num"}},admin:{url:"/admin/articles/:articleId/comments",paginate:{per:5}}}),T($,"attributes",{author:{validations:{presence:!0}},text:{validations:{presence:!0,vulgarity:!0}},articleId:{type:"Int",validations:{presence:!0},remoteName:"article_id"},createdAt:{type:"Date",remoteName:"created_at"},updatedAt:{type:"Date",remoteName:"updated_at"},emotion:{type:"Int"},pinned:{type:"Boolean"},adminRate:{type:"Int",remoteName:"admin_rate"},approved:{type:"Boolean"}});var N=$;function M(e,t,r){var n;return(t="symbol"==typeof(n=function(e,t){if("object"!=typeof e||!e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var n=r.call(e,"string");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(t))?n:String(n))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}class D extends n.Models.Base{constructor(e){super(e)}}M(D,"identity","User"),M(D,"resources",{url:"/users",admin:{url:"/admin/users"}}),M(D,"paginate",{per:10}),M(D,"attributes",{email:{validations:{presence:!0,format:{with:/^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i}}},username:{validations:{presence:!0,format:{with:/^[a-z][a-z0-9_-]*$/i}}},password:{validations:{presence:{on:"create"},confirmation:!0}},passwordConfirmation:{remoteName:"password_confirmation"},confirmed:{},createdAt:{type:"Date",remoteName:"created_at"},updatedAt:{type:"Date",remoteName:"updated_at"}});var q=D,P=r(11504),L=r(97104),F=r(3268),U=r.n(F),H=class{constructor(e,t=(0,n.getLocale)()){this.date=e,this.skope=n.I18n[t].date}toString(e="default"){const t=this.skope.formats;switch(e){case"default":return this.strftime(t.default);case"short":return this.strftime(t.short);case"long":return this.strftime(t.long);default:console.log("Services.Date#toString: unknown format.")}}strftime(e){e=(e=e.replace("%Y",this.date.getFullYear())).replace("%y",this.date.getFullYear().toString().substr(-2,2));let t=this.date.getMonth()+1;return t=t>=10?t:`0${t}`,(e=(e=(e=(e=(e=(e=e.replace("%m",t)).replace("%b",this.skope.abbr_month_names[this.date.getMonth()])).replace("%B",this.skope.month_names[this.date.getMonth()])).replace("%d",this.date.getDate()>=10?this.date.getDate():`0${this.date.getDate()}`)).replace("%H",this.date.getHours()>=10?this.date.getHours():`0${this.date.getHours()}`)).replace("%M",this.date.getMinutes()>=10?this.date.getMinutes():`0${this.date.getMinutes()}`)).replace("%S",this.date.getSeconds()>=10?this.date.getSeconds():`0${this.date.getSeconds()}`)}};function V({comment:e}){const t=new H(e.createdAt).strftime("%d %b %y");return P.createElement("p",{id:`comment_${e.id}`},P.createElement("b",null,e.author)," on ",P.createElement("i",null,t)," (",P.createElement("a",{href:`/admin/articles/${e.articleId}/comments/${e.id}/edit`},"edit"),")",P.createElement("br",null),e.text)}V.propTypes={comment:U().instanceOf(N).isRequired};var W=V;function Y({comments:e}){return 0===e.length?P.createElement("p",null,"No comments"):P.createElement(P.Fragment,null,e.map((e=>P.createElement(W,{comment:e,key:e.id}))))}Y.propTypes={comments:U().arrayOf(U().instanceOf(N)).isRequired};var J=Y;const G=e=>{document.getElementById("article_author").textContent=e.author,document.getElementById("article_title").textContent=e.title,document.getElementById("article_text").textContent=e.content},K=e=>async function(t){if("updated"===t){const t=await e.reload();G(t)}};function Q({article:e}){const t=new H(e.publishedAt).toString("short");return P.createElement("article",{id:`article_${e.id}`},P.createElement("h2",null,e.title),P.createElement("p",null,P.createElement("i",null,e.author," wrote this on ",t," /"," ",P.createElement("span",{className:"comments_quantity"},e.commentsCount," comment",1===e.commentsCount?"":"s"))),P.createElement("p",null,e.content),P.createElement("p",null,P.createElement("a",{href:`/admin/articles/${e.id}/edit`},"Review")))}Q.propTypes={article:U().instanceOf(B).isRequired};var X=Q;function Z(e){const[t,r]=(0,P.useState)(e.articles);(0,P.useEffect)((()=>{const e=C.subscribe((()=>r(C.getState().articles)));return()=>{e()}}),[]);const n=t.map((e=>P.createElement(X,{key:e.id,article:e})));return P.createElement(P.Fragment,null,n)}Z.propTypes={articles:U().arrayOf(U().instanceOf(B)).isRequired};var ee=Z;const te=async()=>{const e=await B.find(n.helpers.params.id);(e=>{(0,n.subscribe)({to:e,with:K(e)}),G(e)})(e),(e=>{e.setDefaultValuesForAdminReview(),new a.UI.Form({id:"edit_article_form",for:e}).render()})(e)};const re=()=>window.location.href="/admin";const ne=({user:e})=>P.createElement("tr",{id:`user_${e.id}`},P.createElement("td",null,e.email),P.createElement("td",null,e.username),P.createElement("td",{className:"confirmed"},e.confirmed?"Yes":"No"),P.createElement("td",null,P.createElement("a",{href:`/admin/users/${e.id}`},"Show")," |"," ",P.createElement("a",{href:`/admin/users/${e.id}/edit`},"Edit")," |"," ",P.createElement("a",{href:`/admin/users/${e.id}`,"data-method":"delete","data-confirm":"Are you sure?"},"Delete")," ","|"," ",P.createElement("a",{href:"#",onClick:t=>((e,t)=>{e.preventDefault(),lt.emit({type:"PING",user_id:t})})(t,e.id)},"Ping")));ne.propTypes={user:U().instanceOf(q).isRequired};var ae=ne;function ie(e){const[t,r]=(0,P.useState)(e.users);(0,P.useEffect)((()=>{const e=C.subscribe((()=>r(C.getState().users)));return()=>{e()}}),[]);const n=t.map((e=>P.createElement(ae,{key:`user_${e.id}`,user:e})));return P.createElement(P.Fragment,null,n)}ie.propTypes={users:U().arrayOf(U().instanceOf(q)).isRequired};var se=ie;class oe extends n.Controllers.Base{initialize(){this.setScope("admin")}}oe.Articles=class{async published(){const e=await B.get("published");C.dispatch(h(e.resources)),(0,L.render)(P.createElement(ee,{articles:e.resources}),document.getElementById("articles"))}async edit(){te(),(async()=>{(e=>{(0,L.render)(P.createElement(J,{comments:e}),document.getElementById("comments"))})((await N.all({articleId:n.helpers.params.id})).resources)})()}},oe.Comments=class{edit(){((e={})=>{const t=new a.UI.Form({for:new N({id:e.commentId,resource:"admin"}),id:`edit_comment_${e.commentId}`,initObj:!0});t.render(),window.test={commentFormObj:t.getObj()}})({commentId:n.helpers.params.id})}},oe.Sessions=class{new(){new a.UI.Form({id:"sign_in_admin",callbackSuccess:re}).render()}},oe.Users=class{async index(){const e=await q.get("all");C.dispatch(function(e){return{type:y,users:e}}(e.resources)),(0,L.render)(P.createElement(se,{users:e.resources}),document.querySelector("table tbody"))}async show(){(e=>{document.getElementById("user_email").textContent=e.email,document.getElementById("user_username").textContent=e.username,document.getElementById("user_confirmed").textContent=e.confirmed?"Yes":"No",(e=>{const t=document.getElementById("edit_link"),r=t.getAttribute("href");t.setAttribute("href",r.replace("/0/",`/${e.id}/`))})(e)})(await q.find(n.helpers.params.id))}edit(){var e;e=new q({id:n.helpers.params.id}),new a.UI.Form({for:e,initObj:!0,id:"admin_user_form"}).render()}};var ce=oe;const le=(e,t)=>e.comments[t];function de({comment:e}){const t=new H(e.createdAt).strftime("%d %b %y");return P.createElement("p",{id:`comment_${e.id}`},P.createElement("b",null,e.author)," on ",P.createElement("i",null,t)," wrote:",P.createElement("br",null),e.text)}de.propTypes={comment:U().instanceOf(N).isRequired};var me=de;function ue(e){const t=e.articleId,[r,n]=(0,P.useState)(e.comments);(0,P.useEffect)((()=>{const e=C.subscribe((()=>{n(le(C.getState(),t))}));return()=>{e()}}),[]);const a=r.map((e=>P.createElement(me,{key:e.id,comment:e})));return 0===r.length?P.createElement("p",{id:"no_comments"},"No comments."):P.createElement(P.Fragment,null,a)}ue.propTypes={articleId:U().number.isRequired,comments:U().arrayOf(U().instanceOf(N)).isRequired};var pe=ue;function fe(e){const[t,r]=(0,P.useState)(e.comments);return(0,P.useEffect)((()=>{const t=C.subscribe((()=>{r(le(C.getState(),e.articleId))}));return()=>{t()}}),[]),P.createElement(P.Fragment,null,`${t.length} comment${1===t.length?"":"s"}`)}fe.propTypes={articleId:U().number.isRequired,comments:U().arrayOf(U().instanceOf(N)).isRequired};var ye=fe;const ge=(e,t,r)=>{null!=e[t]&&(r.classList.add(t),document.querySelector(".flash p").textContent=e[t])};var he=(e={})=>{const{hide:t}=e,r=document.querySelector(".flash");(e=>{e.classList.remove("notice"),e.classList.remove("alert"),e.classList.remove("warning")})(r),ge(e,"notice",r),ge(e,"alert",r),ge(e,"warning",r),r.classList.remove("none"),t&&((e=4e3)=>{setTimeout((()=>{document.querySelector(".flash").classList.add("none")}),e)})()};const be=e=>async function(t){switch(t){case"updating":he({warning:"Author is currently editing article. Be aware of possible changes."});break;case"updated":{const t=await e.reload();we(t,!0)}}},we=(e,t=!1)=>{!1===t&&(0,n.subscribe)({to:e,with:be(e)}),document.getElementById("title").textContent=e.title,document.getElementById("author").textContent=e.author;const r=new H(e.publishedAt);document.getElementById("pub_date").textContent=r.toString("short");const a=document.getElementById("text");a.innerHTML="";const i=((s=(s=(s=e.content).replace(/\r\n?/,"\n")).trim()).length>0&&(s="<p>"+(s=(s=s.replace(/\n\n+/g,"</p><p>")).replace(/\n/g,"<br>"))+"</p>"),s);var s;a.insertAdjacentHTML("beforeend",i)};var ve={renderArticle:we,renderForm:e=>{new a.UI.Form({for:e,initObj:!0,id:"new_comment"}).render()}};function Ee(){const[e,t]=(0,P.useState)(1),[r,n]=(0,P.useState)(!1);return r?P.createElement("span",null,"No more posts."):P.createElement("a",{href:"#",id:"load_more",onClick:async function(r){r.preventDefault();const a=e+1;t(a);let i=null;try{i=await B.get("all",{page:a})}catch(r){return void alert(`Invalid URL: ${r}`)}i.resources.length>0?C.dispatch(g(i.resources)):n(!0)}},"Load more…")}function _e({article:e}){const t=new H(e.publishedAt).toString("short");return P.createElement("article",{id:`article_${e.id}`},P.createElement("h2",null,e.title),P.createElement("p",null,P.createElement("i",null,e.author," wrote this on ",t," /"," ",P.createElement("a",{href:`/articles/${e.id}#comments`,className:"comments_quantity"},e.commentsCount," comment",1===e.commentsCount?"":"s"))),P.createElement("p",null,e.content),P.createElement("p",null,P.createElement("a",{href:`/articles/${e.id}`},"Continued…")))}_e.propTypes={article:U().instanceOf(B).isRequired};var Ie=_e;function ke(e){const[t,r]=(0,P.useState)(e.articles);(0,P.useEffect)((()=>{const e=C.subscribe((()=>r(C.getState().articles)));return()=>{e()}}),[]);const n=t.map((e=>P.createElement(Ie,{key:e.id,article:e})));return P.createElement(P.Fragment,null,n)}ke.propTypes={articles:U().arrayOf(U().instanceOf(B)).isRequired};var Se=ke;const Ae=e=>{switch(e){case"confirming":document.getElementById("verification_info").textContent=document.getElementById("verification_progress").textContent;break;case"confirmed":window.location.href="/user/sessions/new?event=confirmed"}},Ce=e=>{(0,n.subscribe)({to:new q({id:e.id}),with:Ae}),document.querySelector("form").style.display="none",document.getElementById("sign_in_paragraph").classList.remove("none"),document.getElementById("verification_info").classList.remove("none"),he({notice:e.notice})};class je extends n.Controllers.Base{initialize(){this.setScope("main")}}je.Articles=class{async show(){const e=new N({articleId:n.helpers.params.id});ve.renderForm(e),(async()=>{const e=await B.find(n.helpers.params.id);C.dispatch(h([e])),ve.renderArticle(e)})(),(async()=>{const e=await N.get("count",{articleId:n.helpers.params.id}),t=await N.all({articleId:n.helpers.params.id,total:e.total});C.dispatch(w(t,n.helpers.params.id)),(0,L.render)(P.createElement(pe,{articleId:n.helpers.params.id,comments:t}),document.getElementById("comments")),(0,L.render)(P.createElement(ye,{articleId:n.helpers.params.id,comments:t}),document.getElementById("comments_count"))})()}},je.Pages=class{async index(){(0,L.render)(P.createElement(Ee,null),document.getElementById("load_more_wrapper"));const e=await B.get("all",{page:1});C.dispatch(h(e.resources)),(0,L.render)(P.createElement(Se,{articles:e.resources}),document.getElementById("articles"))}},je.Users=class{new(){new a.UI.Form({for:new q,callbackSuccess:Ce}).render()}};var ze=je;function xe(e,t,r){var n;return(t="symbol"==typeof(n=function(e,t){if("object"!=typeof e||!e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var n=r.call(e,"string");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(t))?n:String(n))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}class Oe extends n.Models.Base{constructor(e){super(e)}}xe(Oe,"identity","Room.Member"),xe(Oe,"resources",{url:"/user/rooms/:roomId/members",paginate:{per:100}});var Re,Be,Te,$e,Ne=Oe;class Me extends n.Models.Base{constructor(e){super(e)}}Re=Me,Te="Room",(Be="symbol"==typeof($e=function(e,t){if("object"!=typeof e||!e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var n=r.call(e,"string");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(Be="identity"))?$e:String($e))in Re?Object.defineProperty(Re,Be,{value:Te,enumerable:!0,configurable:!0,writable:!0}):Re[Be]=Te;var De=Me;const qe=e=>{document.querySelector(`#room_${e} td.members`)},Pe=(e,t)=>{switch(e){case"Room member_joined":(e=>{const t=qe(e);t.textContent=parseInt(t.text())+1})(t.room_id);break;case"Room member_left":(e=>{const t=qe(e);t.textContent=parseInt(t.text())-1})(t.room_id);break;case"Room created":document.getElementById("rooms_list").insertAdjacentHTML("beforeend",((r=t.room).id,r.name,r.id,void r.id));break;case"Room destroyed":{const e=document.getElementById(`room_${t.room_id}`);e.parentNode.removeChild(e)}}var r},Le=e=>{const t=`<li id='user_${e.id}'>${e.username}</li>`;document.getElementById("members").insertAdjacentHTML("beforeend",t)},Fe=e=>function(t,r){switch(t){case"Room member_joined":if(r.room_id!==e)return;Le(r.member);break;case"Room member_left":if(r.room_id!==e)return;(e=>{const t=document.querySelector(`#members li#user_${e.id}`);t.parentNode.removeChild(t)})(r.member)}};var Ue=(e,t)=>{const r=`<p class="msg"><b>${t}</b>: ${e}</p>`;document.getElementById("messages").insertAdjacentHTML("beforeend",r)},He=class{constructor(){this.callbacks={}}index(){(0,n.subscribe)({to:De,with:Pe})}async show(){var e;this.callbacks.receivedMessage=Ue,e=n.helpers.params.id,(0,n.subscribe)({to:De,with:Fe(e)}),(e=>{document.querySelector("[data-behavior~=room-speaker]").addEventListener("keypress",(t=>{13===t.keyCode&&(t.preventDefault(),lt.emit({type:"NEW_MESSAGE",txt:t.target.value,room_id:e}),t.target.value="")}))})(e);(e=>{for(const t of e)Le(t)})((await Ne.all({roomId:n.helpers.params.id})).resources)}};const Ve=e=>{document.getElementById("article_title").textContent=e.title,document.getElementById("article_text").textContent=e.content;const t=document.getElementById("publish_article");t&&null!=e.publishedAt?t.style.display="none":t&&(t.style.display="")},We=e=>async function(t){switch(t){case"updated":await e.reload(),e.applyChanges(),Ve(e);break;case"destroyed":window.location.href="/user/articles?message=deleted"}};function Ye({comment:e,isAdmin:t=!1}){const[r,n]=(0,P.useState)(!1),a=new H(e.createdAt).strftime("%d %b %y"),i=async t=>{t.preventDefault(),n(!0),e.approved=!0,(await e.updateAttribute("approved")).ok&&C.dispatch(v(new N({...e,approved:!0}),e.articleId))};return P.createElement("p",{id:`comment_${e.id}`},P.createElement("b",null,e.author)," on ",P.createElement("i",null,a),t?(()=>{let t;return t=e.approved?P.createElement(P.Fragment,null,P.createElement("span",null,"approved")," |"," "):r?P.createElement(P.Fragment,null,P.createElement("span",null,"approving...")," |"," "):P.createElement(P.Fragment,null,P.createElement("a",{href:`/user/articles/${e.articleId}/comments/${e.id}/approve`,className:"approve",onClick:i},"approve")," ","|"," "),P.createElement(P.Fragment,null," ","(",t,P.createElement("a",{href:`/user/articles/${e.articleId}/comments/${e.id}/edit`},"edit")," ","|"," ",P.createElement("a",{href:`/user/articles/${e.articleId}/comments/${e.id}`,"data-method":"delete","data-confirm":"Are you sure?"},"delete"),")")})():"",P.createElement("br",null),e.text)}Ye.propTypes={comment:U().instanceOf(N).isRequired,isAdmin:U().bool};var Je=Ye;function Ge(e){const t=e.articleId,r=e.isAdmin||!1,[n,a]=(0,P.useState)(e.comments);if((0,P.useEffect)((()=>{const e=C.subscribe((()=>a(le(C.getState(),t))));return()=>{e()}}),[]),0===n.length)return P.createElement("p",null,"No comments.");const i=n.map((e=>P.createElement(Je,{key:e.id,comment:e,isAdmin:r})));return P.createElement(P.Fragment,null,i)}Ge.propTypes={articleId:U().number.isRequired,isAdmin:U().bool,comments:U().arrayOf(U().instanceOf(N)).isRequired};var Ke=Ge;const Qe=e=>async function(t,r){switch(t){case"updating":document.querySelector("h1").getAttribute("data-mark")!==r.mark&&he({warning:"Uuups someone else started editing this article."});break;case"updated":await e.reload(),(e=>{for(const[t]of Object.entries(e.changes())){const r=document.querySelector(`a.apply_changes[data-for=${e.getAttrRemoteName(t)}]`);r&&r.classList.remove("none")}})(e);break;case"destroyed":window.location.href="/user/articles?message=deleted"}};var Xe=e=>{C.dispatch(g([e])),(0,n.subscribe)({to:e,with:Qe(e)});const t=new a.UI.Form({for:e});t.render(),(e=>{for(const t of Array.from(document.querySelectorAll("a.apply_changes")))t.addEventListener("click",(t=>{t.preventDefault();const r=e.getObj(),n=r.getAttrName(t.target.getAttribute("data-for"));r[n]=r.changes()[n].is,e.fill(n),t.target.classList.add("none")}))})(t)};function Ze({article:e,onArticleDestroyed:t}){return P.createElement("tr",{id:`article_${e.id}`},P.createElement("td",null,e.title),P.createElement("td",null,e.content),P.createElement("td",{className:"comments_quantity"},e.commentsCount),P.createElement("td",{className:"published"},e.publishedAt?"yes":"no"),P.createElement("td",null,P.createElement("a",{href:`/user/articles/${e.id}`},"Show")," |",P.createElement("a",{href:`/user/articles/${e.id}/edit`},"Edit")," |",P.createElement("a",{href:`/user/articles/${e.id}`,className:"delete_article",onClick:async r=>{if(r.preventDefault(),!confirm("Are you sure?"))return;const n=await e.delete(null);var a;n.success&&C.dispatch((a=n.id,{type:c,id:a})),t(n)}},"Delete")))}Ze.propTypes={article:U().instanceOf(B).isRequired,onArticleDestroyed:U().func.isRequired};var et=Ze;function tt(e){const[t,r]=(0,P.useState)(e.articles);(0,P.useEffect)((()=>{const e=C.subscribe((()=>r(C.getState().articles)));return()=>{e()}}),[]);const n=t.map((t=>P.createElement(et,{key:t.id,article:t,onArticleDestroyed:e.onArticleDestroyed})));return P.createElement(P.Fragment,null,n)}tt.propTypes={articles:U().arrayOf(U().instanceOf(B)).isRequired,onArticleDestroyed:U().func.isRequired};var rt=tt;const nt=e=>{e.success?he({notice:e.notice}):he({alert:e.alert})};class at extends n.Controllers.Base{}at.Articles=class{async index(){"deleted"===n.helpers.params.message&&he({alert:"Article has been deleted."});const e=await B.get("all");C.dispatch(h(e.resources)),(0,L.render)(P.createElement(rt,{articles:e.resources,onArticleDestroyed:nt}),document.getElementById("article_list"))}show(){(async()=>{const e=await B.find(n.helpers.params.id);C.dispatch(h([e])),(e=>{null!==e&&((0,n.subscribe)({to:e,with:We(e)}),(e=>{document.getElementById("publish_article").addEventListener("click",(async t=>{t.preventDefault(),t.target.textContent="Publishing...";try{await e.put("publish"),document.getElementById("publish_article").outerHTML="<span>Published!</span>"}catch(e){document.getElementById("publish_article").textContent="Publish",he({alert:"Connection error!"})}}))})(e),(e=>{const t=document.getElementById("edit_link").getAttribute("href");document.getElementById("edit_link").setAttribute("href",t.replace("/0/",`/${e}/`))})(e.id),Ve(e))})(e)})(),(async()=>{const e=await N.all({articleId:n.helpers.params.id});C.dispatch(w(e.resources,n.helpers.params.id)),(0,L.render)(P.createElement(Ke,{articleId:n.helpers.params.id,comments:e.resources}),document.getElementById("comments"))})()}new(){Xe(new B)}async edit(){(async e=>{const t=await N.all({articleId:e});C.dispatch(w(t.resources,e)),(0,L.render)(P.createElement(Ke,{articleId:e,comments:t.resources,isAdmin:!0}),document.getElementById("comments"))})(n.helpers.params.id);const e=await B.find(n.helpers.params.id);Xe(e)}},at.Rooms=He;var it=at;const st=({article_id:e},t)=>{const[r,n]=z(C.getState(),e);if(!r)return;const a=new B({...r,commentsCount:r.commentsCount+t});C.dispatch(b(a,n))};B.Comment=N,De.Member=Ne;const ot=(0,n.init)({cable:(0,i.gF)(),controllers:{Admin:ce,Main:ze,User:it},models:{Article:B,Room:De,User:q},notificationCenter:async e=>{switch(e.type){case"PING":lt.getEnv().namespaceController.constructor===it&&alert("Ping!");break;case"NEW_MESSAGE":(lt.getEnv().namespaceController.constructor!==it||lt.getEnv().controller.constructor!==He||"show"!==lt.getEnv().action?()=>{}:lt.getEnv().controller.callbacks.receivedMessage)(e.message,e.author);break;case"Article created":(async({id:e})=>{if(lt.getEnv().namespaceController.constructor!==it)return;const t=await B.find({id:e,abbr:!0});C.dispatch(g([t]))})(e.payload);break;case"Article published":(async({id:e})=>{if(lt.getEnv().namespaceController.constructor===ce){const t=await B.find({id:e,abbr:!0,resource:"admin"});C.dispatch(function(e){return{type:o,articles:e}}([t]))}else{const t=await B.find({id:e,abbr:!0});C.dispatch(g([t]))}})(e.payload);break;case"Article updated":(async({id:e})=>{const t={id:e,abbr:!0};lt.getEnv().namespaceController.constructor===ce&&(t.resource="admin");let[r,n]=z(C.getState(),e);r&&(r=await B.find(t),C.dispatch(b(r,n)))})(e.payload);break;case"Article.Comment created":(async({article_id:e,id:t})=>{const r={articleId:e,id:t};lt.getEnv().namespaceController.constructor===ze&&(r.resource="main");const[n]=z(C.getState(),e);if(!n)return;const a=await N.find(r);null!==a&&(C.dispatch(function(e,t){return{type:m,articleId:t,comments:e}}([a],e)),st({article_id:e},1))})(e.payload);break;case"Article.Comment destroyed":st(e.payload,-1),(({article_id:e,id:t})=>{C.dispatch(function(e,t){return{type:u,id:e,articleId:t}}(t,e))})(e.payload);break;case"Article.Comment updated":(async({article_id:e,id:t})=>{const[r,n]=x(C.getState(),t,{parentId:e});if(!r)return;const a=await r.reload();C.dispatch(v(a,e,n))})(e.payload);break;case"User created":{const t=await q.find(e.payload.id);C.dispatch(function(e){return{type:y,users:e}}([t]));break}}},notifications:{log:!0,size:10,disconnectedForTooLong:()=>{he({alert:"You have been disconnected from the server for too long. Reload page!",hide:!1})}},postInit:()=>{"test"===document.querySelector("body").getAttribute("data-rails-env")&&ot.getWire().setPollingTime(1e3)}});(0,a.connect)((0,n.createConnector)(ot));var ct,lt=ot;n.Validators.Vulgarity=(function(e,t,r){t=function(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var n=r.call(e,"string");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==typeof t?t:String(t)}(t),t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r}(ct=class extends n.Validators.Base{constructor(){super()}validate(){if(null!=this.val)switch(typeof this.val){case"string":{const e=this._getVulgarWord();if(!new RegExp(`${e}`,["i"]).exec(this.val))return;this._addErrorMessage();break}default:throw new TypeError(`Vulgarity validator is applicable only for strings and ${this.attr} isn't.`)}}_addErrorMessage(){const e=n.I18n[(0,n.getLocale)()].errors.messages.vulgarity;this.obj.addErrorMessage(e,{for:this.attr})}_getVulgarWord(){switch((0,n.getLocale)()){case"pl":return"kurwa";case"en":return"fuck"}}},"identity","Vulgarity"),ct),n.I18n.pl={variants:{few(e){const t=parseInt((r=String(e))[r.length-1]);var r;-1!==[2,3,4].indexOf(t)&&(2!==String(e).length||String(e)[0])}},models:{},attributes:{},ui:{form:{sending:"Wysyłam...",success:"Sukces",errors:{connection:"Błąd z połączeniem",invalid_data:"Nieprawidłowe dane"}}},date:{formats:{default:"%d-%m-%Y",short:"%d %b",long:"%B %d, %Y"},day_names:["niedziela","poniedziałek","wtorek","środa","czwartek","piątek","sobota"],abbr_day_names:["nie","pon","wto","śro","czw","pią","sob"],month_names:["styczeń","luty","marzec","kwiecień","maj","czerwiec","lipiec","sierpień","wrzesień","październik","listopad","grudzień"],abbr_month_names:["sty","lut","mar","kwi","maj","cze","lip","sie","wrz","paź","lis","gru"]},errors:{messages:{accepted:"musi zostać zaakceptowane",blank:"nie może być puste",confirmation:"nie zgadza się z polem %{attribute}",empty:"nie może być puste",equal_to:"musi być równe %{count}",even:"musi być parzyste",exclusion:"jest zarezerwowane",greater_than:"musi być większe od %{count}",greater_than_or_equal_to:"musi być większe lub równe %{count}",inclusion:"nie znajduje się na liście dopuszczalnych wartości",invalid:"jest nieprawidłowe",less_than:"musi być mniejsze od %{count}",less_than_or_equal_to:"musi być mniejsze lub równe %{count}",not_a_number:"nie jest liczbą",not_an_integer:"musi być liczbą całkowitą",odd:"musi być nieparzyste",present:"musi być puste",too_long:{few:"jest za długie (maksymalnie %{count} znaki)",many:"jest za długie (maksymalnie %{count} znaków)",one:"jest za długie (maksymalnie jeden znak)",other:"jest za długie (maksymalnie %{count} znaków)"},too_short:{few:"jest za krótkie (przynajmniej %{count} znaki)",many:"jest za krótkie (przynajmniej %{count} znaków)",one:"jest za krótkie (przynajmniej jeden znak)",other:"jest za krótkie (przynajmniej %{count} znaków)"},wrong_length:{few:"ma nieprawidłową długość (powinna wynosić %{count} znaki)",many:"ma nieprawidłową długość (powinna wynosić %{count} znaków)",one:"ma nieprawidłową długość (powinna wynosić jeden znak)",other:"ma nieprawidłową długość (powinna wynosić %{count} znaków)"},other_than:"musi być inna niż %{count}"}}},n.I18n.pl.models.User="Użytkownik",n.I18n.pl.attributes.User={password:"Hasło",passwordConfirmation:"Powtórz hasło"},n.I18n.en.errors.messages.vulgarity="contains strong language.",n.I18n.pl.errors.messages.vulgarity="zawiera mocny język.",n.I18n.en.date={formats:{default:"%Y-%m-%d",short:"%b %d",long:"%B %d, %Y"},day_names:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],abbr_day_names:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],month_names:["January","February","March","April","May","June","July","August","September","October","November","December"],abbr_month_names:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]},window.test={getLine:()=>lt.getLine(),getWire:()=>lt.getWire()}}},r={};function n(e){var a=r[e];if(void 0!==a)return a.exports;var i=r[e]={exports:{}};return t[e].call(i.exports,i,i.exports,n),i.exports}n.m=t,e=[],n.O=function(t,r,a,i){if(!r){var s=1/0;for(d=0;d<e.length;d++){r=e[d][0],a=e[d][1],i=e[d][2];for(var o=!0,c=0;c<r.length;c++)(!1&i||s>=i)&&Object.keys(n.O).every((function(e){return n.O[e](r[c])}))?r.splice(c--,1):(o=!1,i<s&&(s=i));if(o){e.splice(d--,1);var l=a();void 0!==l&&(t=l)}}return t}i=i||0;for(var d=e.length;d>0&&e[d-1][2]>i;d--)e[d]=e[d-1];e[d]=[r,a,i]},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,{a:t}),t},n.d=function(e,t){for(var r in t)n.o(t,r)&&!n.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},n.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},function(){var e={72:0};n.O.j=function(t){return 0===e[t]};var t=function(t,r){var a,i,s=r[0],o=r[1],c=r[2],l=0;if(s.some((function(t){return 0!==e[t]}))){for(a in o)n.o(o,a)&&(n.m[a]=o[a]);if(c)var d=c(n)}for(t&&t(r);l<s.length;l++)i=s[l],n.o(e,i)&&e[i]&&e[i][0](),e[i]=0;return n.O(d)},r=self.webpackChunk=self.webpackChunk||[];r.forEach(t.bind(null,0)),r.push=t.bind(null,r.push.bind(r))}();var a=n.O(void 0,[968],(function(){return n(91520)}));a=n.O(a)}();
//# sourceMappingURL=application.js.map No newline at end of file
!function(){var e,t={278:function(e){window,e.exports=function(){"use strict";var e={d:function(t,n){for(var r in n)e.o(n,r)&&!e.o(t,r)&&Object.defineProperty(t,r,{enumerable:!0,get:n[r]})},o:function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},r:function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})}},t={};e.r(t),e.d(t,{Config:function(){return n},I18n:function(){return r},Models:function(){return $},Validators:function(){return j},connector:function(){return z}});var n=new class{constructor(){this.localeVar="en",this.protocolWithHostVar=null,this.scopeVar=null}get locale(){return this.localeVar}set locale(e){this.localeVar=e}get protocolWithHost(){return this.protocolWithHostVar}set protocolWithHost(e){e?"/"===e[e.length-1]?this.protocolWithHostVar=e.slice(0,e.length-1):this.protocolWithHostVar=e:this.protocolWithHostVar=null}get scope(){return this.scopeVar}set scope(e){this.scopeVar=e}},r={en:{variants:{},models:{},attributes:{},errors:{messages:{accepted:"must be accepted",blank:"can't be blank",confirmation:"doesn't match %{attribute}",empty:"can't be empty",equal_to:"must be equal to %{count}",even:"must be even",exclusion:"is reserved",greater_than:"must be greater than %{count}",greater_than_or_equal_to:"must be greater than or equal to %{count}",inclusion:"is not included in the list",invalid:"is invalid",less_than:"must be less than %{count}",less_than_or_equal_to:"must be less than or equal to %{count}",not_a_number:"is not a number",not_an_integer:"must be an integer",odd:"must be odd",present:"must be blank",too_long:{one:"is too long (maximum is 1 character)",other:"is too long (maximum is %{count} characters)"},too_short:{one:"is too short (minimum is 1 character)",other:"is too short (minimum is %{count} characters)"},wrong_length:{one:"is the wrong length (should be 1 character)",other:"is the wrong length (should be %{count} characters)"},other_than:"must be other than %{count}"}}}};let s={};const i=(e,t)=>{if(-1!==e.indexOf(t))return null;const n=(e=>{let t=e.length;return e.find((e,n)=>{if(null===e)return t=n,!0}),t})(e);return e[n]=t,n},o=(e,t,n)=>{void 0!==s?.[e]?.[t]?.[n]&&(s[e][t][n]=null)},a=e=>{const t=e.getIdentity();void 0===s[t]&&(s[t]={}),void 0===s[t][e.id]&&(s[t][e.id]=[]),s[t][e.id][0]=e};var c={get imap(){return s},clear:()=>s={},subscribe:e=>{const t=()=>{};if("object"==typeof e.to){const n=((e,t={})=>{const n=t.with;a(n);const r=s[n.getIdentity()][n.id];return i(r,e)})(e.with,{with:e.to});return null===n?t:()=>{o(e.to.getIdentity(),e.to.id,n)}}if("function"==typeof e.to){const n=((e,t={})=>{void 0===s[e]&&(s[e]={}),void 0===s[e].collection&&(s[e].collection=[]);const n=s[e].collection;return i(n,t.to)})(e.to.getIdentity(),{to:e.with});return null===n?t:()=>{o(e.to.getIdentity(),"collection",n)}}},unsubscribe:o,add:a,find:(e,t)=>void 0!==s[e]&&null!=s[e][t]?s[e][t][0]:null,findConnected:(e,t)=>void 0!==s[e]&&void 0!==s[e][t]&&s[e][t].length>1?s[e][t].slice(1):[]};class l{static instance(e,t,n){const r=this.identity;null==this.sharedInstances[r]&&(this.sharedInstances[r]=new j[r]);const s=this.sharedInstances[r];return s.assignAttribs(e,t,n),s}constructor(){this.obj=null,this.attr=null,this.val=null,this.opts=null}assignAttribs(e,t,n){this.obj=e,this.attr=t,this.val=this.obj[this.attr],this.opts=n}}var u=l;l.sharedInstances={};class d extends u{constructor(){super()}validate(){if("string"==typeof this.val){if(null!=this.val&&0===this.val.length)return}else if(null==this.val)return;this.#e()}#e(){const e=null!=this.opts.message?this.opts.message:r[n.locale].errors.messages.present;this.obj.addErrorMessage(e,{for:this.attr})}}var m=d;d.identity="Absence";class h extends u{constructor(){super()}validate(){const e=this.obj[this.#t()];null!=this.val&&null!=e&&this.val===e||this.#e()}#e(){const e=this.attr.charAt(0).toUpperCase()+this.attr.slice(1),t=r[n.locale].attributes[this.obj.getIdentity()],s=t&&t[this.attr]||e;let i=null!=this.opts.message?this.opts.message:r[n.locale].errors.messages.confirmation;i=i.replace("%{attribute}",s),this.obj.addErrorMessage(i,{for:this.#t()})}#t(){return`${this.attr}Confirmation`}}var p=h;h.identity="Confirmation";class f extends u{constructor(){super()}validate(){-1!==(this.opts.in||this.opts.within||[]).indexOf(this.val)&&this.#e()}#e(){const e=null!=this.opts.message?this.opts.message:r[n.locale].errors.messages.exclusion;this.obj.addErrorMessage(e,{for:this.attr})}}var g=f;f.identity="Exclusion";class y extends u{constructor(){super()}validate(){null==this.opts.with.exec(this.val||"")&&this.#e()}#e(){const e=null!=this.opts.message?this.opts.message:r[n.locale].errors.messages.invalid;this.obj.addErrorMessage(e,{for:this.attr})}}var b=y;y.identity="Format";class _ extends u{constructor(){super()}validate(){-1===(this.opts.in||this.opts.within||[]).indexOf(this.val)&&this.#e()}#e(){const e=null!=this.opts.message?this.opts.message:r[n.locale].errors.messages.inclusion;this.obj.addErrorMessage(e,{for:this.attr})}}var v=_;_.identity="Inclusion";class w extends u{constructor(){super()}validate(){if(null==this.val)return;let e=null;const[t,n]=this.#n();null!=t&&null!=n&&t===n&&this.val.length!==t?e=this.#r("wrong_length",t):null!=t&&this.val.length<t?e=this.#r("too_short",t):null!=n&&this.val.length>n&&(e=this.#r("too_long",n)),null!==e&&this.obj.addErrorMessage(e,{for:this.attr})}#n(){return[this.opts.minimum||this.opts.is||null!=this.opts.within&&this.opts.within[0]||null,this.opts.maximum||this.opts.is||null!=this.opts.within&&this.opts.within[1]||null]}#r(e,t){if(1===t)return r[n.locale].errors.messages[e].one;let s=null;for(const i of["few","many"])if(this.#s(i,t)){s=r[n.locale].errors.messages[e][i];break}return null==s&&(s=r[n.locale].errors.messages[e].other),null!=this.opts.message&&(s=this.opts.message),/%\{count\}/.exec(s)&&(s=s.replace("%{count}",t)),s}#s(e,t){if(null!=r[n.locale].variants[e])return r[n.locale].variants[e](t)}}var E=w;w.identity="Length";class I extends u{constructor(){super()}validate(){isNaN(this.val)?this.#i():null!=this.opts.only_integer&&Number(this.val)!==parseInt(this.val,10)?this.#o():null!=this.opts.greater_than&&Number(this.val)<=this.opts.greater_than?this.#a():null!=this.opts.greater_than_or_equal_to&&Number(this.val)<this.opts.greater_than_or_equal_to?this.#c():null!=this.opts.equal_to&&Number(this.val)!==this.opts.equal_to?this.#l():null!=this.opts.less_than&&Number(this.val)>=this.opts.less_than?this.#u():null!=this.opts.less_than_or_equal_to&&Number(this.val)>this.opts.less_than_or_equal_to?this.#d():null!=this.opts.other_than&&Number(this.val)===this.opts.other_than?this.#m():null!=this.opts.odd&&Number(this.val)%2!=1?this.#h():null!=this.opts.even&&Number(this.val)%2!=0&&this.#p()}#i(){const e=null!=this.opts.message?this.opts.message:r[n.locale].errors.messages.not_a_number;this.obj.addErrorMessage(e,{for:this.attr})}#o(){const e=r[n.locale].errors.messages.not_an_integer;this.obj.addErrorMessage(e,{for:this.attr})}#a(){let e=r[n.locale].errors.messages.greater_than;e=e.replace("%{count}",this.opts.greater_than),this.obj.addErrorMessage(e,{for:this.attr})}#c(){let e=r[n.locale].errors.messages.greater_than_or_equal_to;e=e.replace("%{count}",this.opts.greater_than_or_equal_to),this.obj.addErrorMessage(e,{for:this.attr})}#l(){let e=r[n.locale].errors.messages.equal_to;e=e.replace("%{count}",this.opts.equal_to),this.obj.addErrorMessage(e,{for:this.attr})}#u(){let e=r[n.locale].errors.messages.less_than;e=e.replace("%{count}",this.opts.less_than),this.obj.addErrorMessage(e,{for:this.attr})}#d(){let e=r[n.locale].errors.messages.less_than_or_equal_to;e=e.replace("%{count}",this.opts.less_than_or_equal_to),this.obj.addErrorMessage(e,{for:this.attr})}#m(){let e=r[n.locale].errors.messages.other_than;e=e.replace("%{count}",this.opts.other_than),this.obj.addErrorMessage(e,{for:this.attr})}#h(){const e=r[n.locale].errors.messages.odd;this.obj.addErrorMessage(e,{for:this.attr})}#p(){const e=r[n.locale].errors.messages.even;this.obj.addErrorMessage(e,{for:this.attr})}}var k=I;I.identity="Numericality";class S extends u{constructor(){super()}validate(){if("string"==typeof this.val){if(null!=this.val&&this.val.length>0)return}else if(null!=this.val)return;this.#e()}#e(){const e=null!=this.opts.message?this.opts.message:r[n.locale].errors.messages.blank;this.obj.addErrorMessage(e,{for:this.attr})}}var C=S;S.identity="Presence";class A extends u{constructor(){super()}validate(){return E.instance(this.obj,this.attr,this.opts).validate()}}var O=A;A.identity="Size";var j={Absence:m,Base:u,Confirmation:p,Exclusion:g,Format:b,Inclusion:v,Length:E,Numericality:k,Presence:C,Size:O};const R=(e,t,n,r={})=>{const s=(e=>{const t={};if(!e)return t;const n=["resource","total","count"];return Object.keys(e).forEach(r=>{-1===n.indexOf(r)&&(t[r]=e[r])}),t})(n),i="GET"===e?`${t}?${(e=>{let t="";return Object.keys(e).forEach(n=>{""!==t&&(t=`${t}&`),t=`${t}${n}=${encodeURIComponent(e[n])}`}),t})(s)}`:t,o=document.querySelector("meta[name='csrf-token']"),a=new XMLHttpRequest;return a.withCredentials=!0===r.cookiesByCORS,a.open(e,i),a.setRequestHeader("Accept","application/json"),a.setRequestHeader("Content-Type","application/json"),o&&a.setRequestHeader("X-CSRF-Token",o.content),null!=r.authorizationHeader&&a.setRequestHeader("Authorization",r.authorizationHeader),a.send(JSON.stringify(s)),a};var N=class{static getIdentity(){if(null!=this.identity)return this.identity;throw new Error("Specify Model's identity!")}static getRemoteName(){return null!=this.remoteName?this.remoteName:this.getIdentity()}static all(e={}){return this.get("all",e)}static get(e,t={}){return this.__send("GET",e,t)}static post(e,t={}){return this.__send("POST",e,t)}static put(e,t={}){return this.__send("PUT",e,t)}static patch(e,t={}){return this.__send("PATCH",e,t)}static delete(e,t={}){return this.__send("DELETE",e,t)}static find(e){let t,n={};"object"==typeof e?(n={...e},t=e.id,delete n.id):t=e;const r=`${this.__getResourcesUrl(n)}/${t}`,s=R("GET",r,n,this.__requestOpts());return new Promise((t,n)=>{s.onerror=e=>n(e),s.onload=n=>{if(404===n.target.status)return void t(null);const r=JSON.parse(n.target.response);t(this.__initFromJSON(r,e.resource))}})}static getAttribRemoteName(e){return null==this.attributes||null==this.attributes[e]?null:null==this.attributes[e].remoteName?e:this.attributes[e].remoteName}static getResourcesUrlParams(e){let t=this.__getResourcesUrl({resource:e.resource});const n=/:(\w+)\/?/,r=[];let s;for(;s=n.exec(t);)r.push(s[1]),t=t.replace(s[0],s[1]);return r}static __getResourcesUrl(e={}){let t;t=null==this.resources?`/${this.getRemoteName().toLowerCase()}s`:e.resource?this.resources[e.resource].url:null!=n.scope&&null!=this.resources&&null!=this.resources[n.scope]?this.resources[n.scope].url:this.resources.url,null!=this.protocolWithHost?t=`${this.protocolWithHost}${t}`:null!=n.protocolWithHost&&(t=`${n.protocolWithHost}${t}`);const r=/:([a-zA-Z]+)\/?/.exec(t);return null==r||(null!=e[r[1]]?(t=t.replace(`:${r[1]}`,e[r[1]]),delete e[r[1]]):null!=e.obj&&null!=e.obj[r[1]]&&(t=t.replace(`:${r[1]}`,e.obj[r[1]]))),t}static __requestOpts(){return{authorizationHeader:n.authorizationHeader||this.authorizationHeader,cookiesByCORS:null!=this.cookiesByCORS?this.cookiesByCORS:n.cookiesByCORS}}static __page(e,t,n){const r=t.url;t.params[t.pageParam]=e;const s=R(t.method,r,t.params,this.__requestOpts());return new Promise((e,r)=>{s.onerror=e=>r(e),s.onload=r=>{const s=JSON.parse(r.target.response);if(Array.isArray(s))for(const e of s){const r=this.__initFromJSON(e,t.resource);n.push(r)}else if(null!=s.resources){n.constructor===Array&&(n={resources:[],count:0});for(const e of s.resources){const r=this.__initFromJSON(e,t.resource);n.resources.push(r)}n.count=s.count}else for(const e in s)Object.prototype.hasOwnProperty.call(s,e)&&(n[e]=s[e]);e(n)}})}static __paginate(e){const t={method:e.method,url:e.url,params:e.params,pageParam:e.pageParam,resource:e.resource};return this.__page(e.pageNum||1,t,[]).then(n=>{const r=n.count||e.total;let s=Promise.resolve(n);if(null!=e.pageNum)return s;if(r<=e.perPage)return s;let i=parseInt(r/e.perPage,10);if(i!==r/e.perPage&&(i+=1),1===i)return s;for(let e=2;e<=i;e+=1)(e=>{s=s.then(()=>this.__page(e,t,n))})(e);return s})}static __getPaginationParam(e){const t="page";return null!=e&&null!=this.resources&&this.resources[e]?this.resources[e].paginate&&this.resources[e].paginate.param||t:null!=n.scope&&null!=this.resources&&null!=this.resources[n.scope]?this.resources[n.scope]&&this.resources[n.scope].paginate&&this.resources[n.scope].paginate.param||t:null!=this.resources&&null!=this.resources.paginate&&null!=this.resources.paginate.param?this.resources.paginate.param:t}static __getPaginationPer(e){return null!=e&&null!=this.resources&&this.resources[e]?this.resources[e].paginate&&this.resources[e].paginate.per:null!=n.scope&&null!=this.resources&&null!=this.resources[n.scope]?this.resources[n.scope]&&this.resources[n.scope].paginate&&this.resources[n.scope].paginate.per:null!=this.resources&&null!=this.resources.paginate&&null!=this.resources.paginate.per?this.resources.paginate.per:null}static __send(e,t,n){let r=this.__getResourcesUrl(n);"all"!==t&&(r=`${r}/${t}`);const s={method:e,url:r,params:n,resource:n.resource,perPage:this.__getPaginationPer(n.resource),pageNum:n.page,pageParam:this.__getPaginationParam(n.resource),total:n.total||n.count};return this.__paginate(s)}static __initFromJSON(e,t){const n=new this(e);return n.resource=t,c.add(n),n}constructor(e={}){this.id=null,this.errors=null,this.resource=e.resource,null!=this.constructor.attributes&&this.#f(),null!=e&&this.#g(e)}setResource(e){this.resource=e}getIdentity(){return this.constructor.getIdentity()}getAttrRemoteName(e){return null==this.constructor.attributes||null==this.constructor.attributes[e]?null:this.constructor.attributes[e].remoteName||e}getAttrName(e){if(null==this.constructor.attributes)return e;if(null!=this.constructor.attributes[e])return e;for(const t in this.constructor.attributes)if(this.constructor.attributes[t].remoteName===e)return t;return e}getAttrType(e){return null==this.constructor.attributes||null==this.constructor.attributes[e]?null:this.constructor.attributes[e].type}assignAttr(e,t){const n=this.getAttrType(e);if(null!=t){switch(n){case"Date":t=new Date(Date.parse(t));break;case"Integer":case"Int":t=parseInt(t,10);break;case"Float":t=parseFloat(t);break;case"Boolean":case"Bool":t="boolean"==typeof t?t:Boolean(parseInt(t,10));break;case"Number":t=Number(t);break;case"String":t=String(t)}this[e]=t}else this[e]=null}attributes(){const e={id:this.id};if(null==this.constructor.attributes)return e;for(const t in this.constructor.attributes)e[t]=this[t];return e}isValid(){if(null==this.constructor.attributes)return!0;this.errors=null;for(const e in this.constructor.attributes){const t=this.constructor.attributes[e];if(null!=t&&null!=t.validations)for(const n in t.validations){const r=t.validations[n];if(null!=this.id&&"create"===r.on)continue;if(null==this.id&&"update"===r.on)continue;if(null!=r.if&&!r.if(this))continue;const s=n.charAt(0).toUpperCase()+n.slice(1);if(null==j[s]){console.warn(`"${s}" validator is not implemented!`);continue}const i=this.#y(r);j[s].instance(this,e,i).validate()}}if(null!=this.constructor.validate)for(const e of this.constructor.validate)"function"==typeof this[e]&&this[e]();return null==this.errors}isInvalid(){return!this.isValid()}isEmpty(){const e=this.attributes();for(const t in e)if(null!==this[t])return!1;return!0}addErrorMessage(e,t={}){null==this.errors&&(this.errors={});const n=t.for;null==this.errors[n]&&(this.errors[n]=[]),this.errors[n].push(e)}save(){const e=null!=this.id?"PUT":"POST",t=R(e,this.#b(),this.serialize(),this.constructor.__requestOpts());return new Promise((e,n)=>{t.onerror=e=>n(e),t.onload=t=>{const n=JSON.parse(t.target.response);n.success||null!=n.errors&&this.#_(n.errors),e(n)}})}updateAttribute(e){const t=R("PUT",this.#b(),this.serialize(e),this.constructor.__requestOpts());return new Promise((e,n)=>{t.onerror=e=>n(e),t.onload=t=>{if(t.target.status>=200&&t.target.status<400){const n=JSON.parse(t.target.response);if(n.success)return void e(n);null!=n.errors&&this.#_(n.errors),e(n)}else t.target.status>=500&&n(t)}})}serialize(e=null){if(null==this.constructor.attributes)return{};const t={},n=this.constructor.getRemoteName().toLowerCase();t[n]={};let r={};null!=e?r[e]=null:r=this.constructor.attributes;for(const e in r){const r=this.getAttrRemoteName(e);t[n][r]=this[e]}return t}reload(){const e={id:this.id,resource:this.resource},t=this.constructor.getResourcesUrlParams({resource:this.resource});for(const n of t)e[n]=this[n];return this.constructor.find(e)}changes(){const e={},t=c.find(this.getIdentity(),this.id),n=this.attributes();for(const r in n){const s=n[r];if(s!==t[r]){if(null!=s&&s.constructor===Date&&t[r]-s===0)continue;s!==t[r]&&(e[r]={is:t[r],was:s})}}return e}applyChanges(){const e=this.changes();for(const t in e)this[t]=e[t].is}toKey(){return`${this.getIdentity().toLowerCase()}_${this.id}`}get(e,t={}){return this.#v("GET",e,t)}post(e,t={}){return this.#v("POST",e,t)}put(e,t={}){return this.#v("PUT",e,t)}patch(e,t={}){return this.#v("PATCH",e,t)}delete(e,t={}){return this.#v("DELETE",e,t)}#v(e,t,n){let r=this.#b();null!=t&&(r=`${r}/${t}`);const s=R(e,r,n,this.constructor.__requestOpts());return new Promise((e,t)=>{s.onerror=e=>t(e),s.onload=n=>{if(n.target.status>=200&&n.target.status<400){const t=JSON.parse(n.target.response);e(t)}else n.target.status>=500&&t(n)}})}#g(e){for(const t in e){const n=e[t],r=this.getAttrName(t);this.assignAttr(r,n)}}#f(){for(const e in this.constructor.attributes)this[e]=null}#_(e){for(const t in e){const n=e[t],r=this.getAttrName(t);for(const e of n)this.addErrorMessage(e,{for:r})}}#b(){const e=this.constructor.__getResourcesUrl({resource:this.resource,obj:this});return null==this.id?e:`${e}/${this.id}`}#y(e){const t={};for(const n in e){const r=e[n];t[n]="function"==typeof r?r(this):r}return t}};N.prototype.clone=function(){return new this.constructor({...this.attributes()})};var $={Base:N};const z={IdentityMap:c,Models:$};return t}()},728:function(e,t,n){"use strict";n(559),document.addEventListener("turbo:before-render",e=>{const{namespace:t,controller:n,action:r}=e.detail.newBody.dataset;document.body.dataset.namespace=t,document.body.dataset.controller=n,document.body.dataset.action=r});var r=n(916),s=n(278),i=class{setScope(e){s.Config.scope=e}},o=n(540),a=n(338);const c="ADD_ARTICLES",l="PREPEND_ARTICLES",u="REMOVE_ARTICLE",d="SET_ARTICLES",m="UPDATE_ARTICLE",h="ADD_COMMENTS",p="REMOVE_COMMENT",f="SET_COMMENTS",g="UPDATE_COMMENT",y="PREPEND_USERS";function b(e){return{type:c,articles:e}}function _(e){return{type:d,articles:e}}function v(e,t){return{type:m,article:e,index:t}}function w(e,t){return{type:f,comments:e,articleId:t}}function E(e,t,n){return{type:g,comment:e,articleId:t,index:n}}var I=n(644),k=n(932),S=(0,k.jM)((e=[],t)=>{switch(t.type){case c:{const n=t.articles.filter(t=>!e.some(e=>e.id===t.id));return void e.push(...n)}case l:return t.articles.concat(e);case u:return e.filter(e=>e.id!==t.id);case d:return t.articles;case m:e[t.index]=t.article;break;default:return e}}),C=(0,k.jM)((e={},t)=>{switch(t.type){case h:void 0===e[t.articleId]&&(e[t.articleId]=[]),e[t.articleId]=e[t.articleId].concat(t.comments);break;case p:if(null==e[t.articleId])return e;e[t.articleId]=e[t.articleId].filter(e=>e.id!==t.id);break;case f:e[t.articleId]=t.comments;break;case g:{const n=t.articleId;let r=t.index;if(!r){const s=e[n].find(e=>e.id===t.comment.id);r=e[n].indexOf(s)}e[n][r]=t.comment;break}default:return e}}),A=(0,k.jM)((e=[],t)=>{switch(t.type){case"SET_USERS":return t.users;case y:return t.users.concat(e);default:return e}}),O=(0,I.HY)({articles:S,comments:C,users:A}),j=(0,I.Yl)(O);class R extends s.Models.Base{static identity="Article";static resources={url:"/user/articles",paginate:{per:5},main:{url:"/articles",paginate:{per:3}},admin:{url:"/admin/articles",paginate:{per:4}}};static attributes={title:{validations:{presence:!0,length:{within:[3,255]}}},content:{validations:{presence:!0,length:{minimum:100}},remoteName:"text"},createdAt:{type:"Date",remoteName:"created_at"},updatedAt:{type:"Date",remoteName:"updated_at"},commentsCount:{type:"Int",remoteName:"comments_count"},publishedAt:{type:"Date",remoteName:"published_at"},published:{},adminReview:{remoteName:"admin_review"},adminRate:{type:"Int",remoteName:"admin_rate"},categoryId:{type:"Int",remoteName:"category_id"},adminReviewStartedAt:{remoteName:"admin_review_started_at"}};static validate=["vulgarityLevel"];constructor(e){super(e),this.published=null!=this.publishedAt}vulgarityLevel(){(null!=this.title&&/fuck/i.exec(this.title)||null!=this.content&&/fuck/i.exec(this.content))&&this.addErrorMessage("Article contains strong language.",{for:"base"})}setDefaultValuesForAdminReview(){this.adminRate=null==this.adminRate?3:this.adminRate,this.categoryId=null==this.categoryId?6:this.categoryId,this.adminReviewStartedAt=Date.now()}}var N=R;class $ extends s.Models.Base{static identity="Article.Comment";static remoteName="Comment";static resources={url:"/user/articles/:articleId/comments",paginate:{per:10},main:{url:"/articles/:articleId/comments",paginate:{per:5,param:"page-num"}},admin:{url:"/admin/articles/:articleId/comments",paginate:{per:5}}};static attributes={author:{validations:{presence:!0}},text:{validations:{presence:!0,vulgarity:!0}},articleId:{type:"Int",validations:{presence:!0},remoteName:"article_id"},createdAt:{type:"Date",remoteName:"created_at"},updatedAt:{type:"Date",remoteName:"updated_at"},emotion:{type:"Int"},pinned:{type:"Boolean"},adminRate:{type:"Int",remoteName:"admin_rate"},approved:{type:"Boolean"}};constructor(e){super(e)}}var z=$,M=n(874),T=n(556),x=n.n(T),q=class{constructor(e,t=s.Config.locale){this.date=e,this.skope=s.I18n[t].date}toString(e="default"){const t=this.skope.formats;switch(e){case"default":return this.strftime(t.default);case"short":return this.strftime(t.short);case"long":return this.strftime(t.long);default:console.log("Services.Date#toString: unknown format.")}}strftime(e){e=(e=e.replace("%Y",this.date.getFullYear())).replace("%y",this.date.getFullYear().toString().substr(-2,2));let t=this.date.getMonth()+1;return t=t>=10?t:`0${t}`,(e=(e=(e=(e=(e=(e=e.replace("%m",t)).replace("%b",this.skope.abbr_month_names[this.date.getMonth()])).replace("%B",this.skope.month_names[this.date.getMonth()])).replace("%d",this.date.getDate()>=10?this.date.getDate():`0${this.date.getDate()}`)).replace("%H",this.date.getHours()>=10?this.date.getHours():`0${this.date.getHours()}`)).replace("%M",this.date.getMinutes()>=10?this.date.getMinutes():`0${this.date.getMinutes()}`)).replace("%S",this.date.getSeconds()>=10?this.date.getSeconds():`0${this.date.getSeconds()}`)}};function P({comment:e}){const t=new q(e.createdAt).strftime("%d %b %y");return o.createElement("p",{id:`comment_${e.id}`},o.createElement("b",null,e.author)," on ",o.createElement("i",null,t)," (",o.createElement("a",{href:`/admin/articles/${e.articleId}/comments/${e.id}/edit`},"edit"),")",o.createElement("br",null),e.text)}P.propTypes={comment:x().instanceOf(z).isRequired};var B=P;function H({comments:e}){return 0===e.length?o.createElement("p",null,"No comments"):o.createElement(o.Fragment,null,e.map(e=>o.createElement(B,{comment:e,key:e.id})))}H.propTypes={comments:x().arrayOf(x().instanceOf(z)).isRequired};var L=H;const D=e=>{document.getElementById("article_author").textContent=e.author,document.getElementById("article_title").textContent=e.title,document.getElementById("article_text").textContent=e.content},U=e=>async function(t){if("updated"===t){const t=await e.reload();D(t)}};var F=n(228);function W({article:e}){const t=new q(e.publishedAt).toString("short");return o.createElement("article",{id:`article_${e.id}`},o.createElement("h2",null,e.title),o.createElement("p",null,o.createElement("i",null,e.author," wrote this on ",t," /"," ",o.createElement("span",{className:"comments_quantity"},e.commentsCount," comment",1===e.commentsCount?"":"s"))),o.createElement("p",null,e.content),o.createElement("p",null,o.createElement("a",{href:`/admin/articles/${e.id}/edit`},"Review")))}W.propTypes={article:x().instanceOf(N).isRequired};var V=W;function J(e){const[t,n]=(0,o.useState)(e.articles);(0,o.useEffect)(()=>{const e=j.subscribe(()=>n(j.getState().articles));return()=>{e()}},[]);const r=t.map(e=>o.createElement(V,{key:e.id,article:e}));return o.createElement(o.Fragment,null,r)}J.propTypes={articles:x().arrayOf(x().instanceOf(N)).isRequired};var Y=J;const G=async()=>{const e=await N.find(r.helpers.params.id);(e=>{(0,M.subscribe)({to:e,with:U(e)}),D(e)})(e),(e=>{e.setDefaultValuesForAdminReview(),new F.UI.Form({id:"edit_article_form",for:e}).render()})(e)};const X=()=>window.location.href="/admin";class Z extends s.Models.Base{static identity="User";static resources={url:"/users",admin:{url:"/admin/users"}};static paginate={per:10};static attributes={email:{validations:{presence:!0,format:{with:/^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i}}},username:{validations:{presence:!0,format:{with:/^[a-z][a-z0-9_-]*$/i}}},password:{validations:{presence:{on:"create"},confirmation:!0}},passwordConfirmation:{remoteName:"password_confirmation"},confirmed:{},createdAt:{type:"Date",remoteName:"created_at"},updatedAt:{type:"Date",remoteName:"updated_at"}};constructor(e){super(e)}}var K=Z,Q=n(997);const ee=e=>function(t,n,r={}){let s=t[e];if(r.parentId&&(s=s[r.parentId]),void 0===s)return[null,null];const i=s.find(e=>e.id===n);return i?[i,s.indexOf(i)]:[null,null]},te=ee("articles"),ne=ee("comments"),re=(e,t)=>e.comments[t];function se({comment:e}){const t=new q(e.createdAt).strftime("%d %b %y");return o.createElement("p",{id:`comment_${e.id}`},o.createElement("b",null,e.author)," on ",o.createElement("i",null,t)," wrote:",o.createElement("br",null),e.text)}se.propTypes={comment:x().instanceOf(z).isRequired};var ie=se;function oe(e){const t=e.articleId,[n,r]=(0,o.useState)(e.comments);(0,o.useEffect)(()=>{const e=j.subscribe(()=>{r(re(j.getState(),t))});return()=>{e()}},[]);const s=n.map(e=>o.createElement(ie,{key:e.id,comment:e}));return 0===n.length?o.createElement("p",{id:"no_comments"},"No comments."):o.createElement(o.Fragment,null,s)}oe.propTypes={articleId:x().number.isRequired,comments:x().arrayOf(x().instanceOf(z)).isRequired};var ae=oe;function ce(e){const[t,n]=(0,o.useState)(e.comments);return(0,o.useEffect)(()=>{const t=j.subscribe(()=>{n(re(j.getState(),e.articleId))});return()=>{t()}},[]),o.createElement(o.Fragment,null,`${t.length} comment${1===t.length?"":"s"}`)}ce.propTypes={articleId:x().number.isRequired,comments:x().arrayOf(x().instanceOf(z)).isRequired};var le=ce;const ue=(e,t,n)=>{null!=e[t]&&(n.classList.add(t),document.querySelector(".flash p").textContent=e[t])};var de=(e={})=>{const{hide:t}=e,n=document.querySelector(".flash");(e=>{e.classList.remove("notice"),e.classList.remove("alert"),e.classList.remove("warning")})(n),ue(e,"notice",n),ue(e,"alert",n),ue(e,"warning",n),n.classList.remove("none"),t&&((e=4e3)=>{setTimeout(()=>{document.querySelector(".flash").classList.add("none")},e)})()};const me=e=>async function(t){switch(t){case"updating":de({warning:"Author is currently editing article. Be aware of possible changes."});break;case"updated":{const t=await e.reload();he(t,!0)}}},he=(e,t=!1)=>{!1===t&&(0,M.subscribe)({to:e,with:me(e)}),document.getElementById("title").textContent=e.title,document.getElementById("author").textContent=e.author;const n=new q(e.publishedAt);document.getElementById("pub_date").textContent=n.toString("short");const r=document.getElementById("text");r.innerHTML="";const s=((i=(i=(i=e.content).replace(/\r\n?/,"\n")).trim()).length>0&&(i="<p>"+(i=(i=i.replace(/\n\n+/g,"</p><p>")).replace(/\n/g,"<br>"))+"</p>"),i);var i;r.insertAdjacentHTML("beforeend",s)};var pe={renderArticle:he,renderForm:e=>{new F.UI.Form({for:e,initObj:!0,id:"new_comment"}).render()}};function fe(){const[e,t]=(0,o.useState)(1),[n,r]=(0,o.useState)(!1);return n?o.createElement("span",null,"No more posts."):o.createElement("a",{href:"#",id:"load_more",onClick:async function(n){n.preventDefault();const s=e+1;t(s);let i=null;try{i=await N.get("all",{page:s})}catch(n){return void alert(`Invalid URL: ${n}`)}i.resources.length>0?j.dispatch(b(i.resources)):r(!0)}},"Load more…")}function ge({article:e}){const t=new q(e.publishedAt).toString("short");return o.createElement("article",{id:`article_${e.id}`},o.createElement("h2",null,e.title),o.createElement("p",null,o.createElement("i",null,e.author," wrote this on ",t," /"," ",o.createElement("a",{href:`/articles/${e.id}#comments`,className:"comments_quantity"},e.commentsCount," comment",1===e.commentsCount?"":"s"))),o.createElement("p",null,e.content),o.createElement("p",null,o.createElement("a",{href:`/articles/${e.id}`},"Continued…")))}ge.propTypes={article:x().instanceOf(N).isRequired};var ye=ge;function be(e){const[t,n]=(0,o.useState)(e.articles);(0,o.useEffect)(()=>{const e=j.subscribe(()=>n(j.getState().articles));return()=>{e()}},[]);const r=t.map(e=>o.createElement(ye,{key:e.id,article:e}));return o.createElement(o.Fragment,null,r)}be.propTypes={articles:x().arrayOf(x().instanceOf(N)).isRequired};var _e=be;const ve=e=>{switch(e){case"confirming":document.getElementById("verification_info").textContent=document.getElementById("verification_progress").textContent;break;case"confirmed":window.location.href="/user/sessions/new?event=confirmed"}},we=e=>{rt.getWire().token=e.access_token,(0,M.subscribe)({to:new K({id:e.id}),with:ve}),document.querySelector("form").style.display="none",document.getElementById("sign_in_paragraph").classList.remove("none"),document.getElementById("verification_info").classList.remove("none"),de({notice:e.notice})};class Ee extends i{initialize(){this.setScope("main")}}Ee.Articles=class{async show(){const e=new z({articleId:r.helpers.params.id});pe.renderForm(e),(async()=>{const e=await N.find(r.helpers.params.id);j.dispatch(_([e])),pe.renderArticle(e)})(),(async()=>{const e=await z.get("count",{articleId:r.helpers.params.id}),t=await z.all({articleId:r.helpers.params.id,total:e.total});j.dispatch(w(t,r.helpers.params.id)),(0,a.createRoot)(document.getElementById("comments")).render(o.createElement(ae,{articleId:r.helpers.params.id,comments:t})),(0,a.createRoot)(document.getElementById("comments_count")).render(o.createElement(le,{articleId:r.helpers.params.id,comments:t}))})()}},Ee.Pages=class{async index(){(0,a.createRoot)(document.getElementById("load_more_wrapper")).render(o.createElement(fe,null));const e=await N.get("all",{page:1});j.dispatch(_(e.resources)),(0,a.createRoot)(document.getElementById("articles")).render(o.createElement(_e,{articles:e.resources}))}},Ee.Users=class{new(){new F.UI.Form({for:new K,callbackSuccess:we}).render()}};var Ie=Ee;class ke extends s.Models.Base{static identity="Room.Member";static resources={url:"/user/rooms/:roomId/members",paginate:{per:100}};constructor(e){super(e)}}var Se=ke;class Ce extends s.Models.Base{static identity="Room";constructor(e){super(e)}}var Ae=Ce;let Oe=[];const je=({id:e,name:t,members_count:n,joined:r})=>`\n <tr id="room_${e}">\n <td>${t}</td>\n <td class="members">${n}</td>\n <td>\n <a\n rel="nofollow"\n data-turbo-method="patch"\n href="${r?`/user/rooms/${e}/leave`:`/user/rooms/${e}/join`}"\n >\n ${r?"Leave":"Join"}\n </a>\n |\n <a\n rel="nofollow"\n data-turbo-method="delete"\n data-turbo-confirm="R U sure?"\n href="/user/rooms/${e}"\n >\n Destroy\n </a>\n </td>\n </tr>\n `,Re=e=>{document.querySelector("#rooms_list tbody").insertAdjacentHTML("beforeend",je(e))},Ne=(e,t,n)=>{const r=Oe.find(t=>t.id===e);r.members_count+=t,n===(()=>{const e=document.getElementById("current-user-data");return JSON.parse(e.textContent)})().id&&(r.joined=t>0),(e=>{const t=Oe.find(t=>t.id===e);document.getElementById(`room_${e}`).innerHTML=je(t)})(e)},$e=(e,t)=>{switch(e){case"Room member_joined":Ne(t.room_id,1,t.member.id);break;case"Room member_left":Ne(t.room_id,-1,t.member.id);break;case"Room created":t.room.members_count=0,Oe.push(t.room),Re(t.room);break;case"Room destroyed":{const e=document.getElementById(`room_${t.room_id}`);e.parentNode.removeChild(e)}}};const ze=e=>{if(document.querySelector(`#members li#user_${e.id}`))return;const t=`<li id='user_${e.id}'>${e.username}</li>`;document.getElementById("members").insertAdjacentHTML("beforeend",t)},Me=e=>function(t,n){switch(t){case"Room member_joined":if(n.room_id!==e)return;ze(n.member);break;case"Room member_left":if(n.room_id!==e)return;(e=>{const t=document.querySelector(`#members li#user_${e.id}`);t.parentNode.removeChild(t)})(n.member)}};var Te={render:e=>{(e=>{document.querySelector("[data-behavior~=room-speaker]").addEventListener("keypress",t=>{13===t.keyCode&&(t.preventDefault(),rt.emit({type:"NEW_MESSAGE",txt:t.target.value,room_id:e,message_type:document.querySelector("[name='message_type']:checked").value}),t.target.value="")})})(e);const t=(e=>{const t=setInterval(()=>{rt.emit({type:"HEARTBEAT",room_id:e}),console.log("heartbeat",e)},3e3);return()=>clearInterval(t)})(e),n=(0,M.subscribe)({to:Ae,with:Me(e)});return()=>{t(),n()}},renderMembers:e=>{for(const t of e)ze(t)},receivedMessage:(e,t)=>{const n=`<p class="msg"><b>${t}</b>: ${e}</p>`;document.getElementById("messages").insertAdjacentHTML("beforeend",n)},disconnected:()=>{de({alert:"You have been disconnected from the server. You might have lost some ephemeral messages.",hide:!1})}},xe=class{constructor(){this.view=null,this.unsubscribe=null}deinitialize(){null!==this.unsubscribe&&(this.unsubscribe(),this.unsubscribe=null)}index(){this.unsubscribe=function(){let e=document.getElementById("rooms-data");return Oe=JSON.parse(e.textContent),Oe.forEach(e=>Re(e)),(0,M.subscribe)({to:Ae,with:$e})}()}async show(){this.view=Te,this.unsubscribe=Te.render(r.helpers.params.id);const e=await Se.all({roomId:r.helpers.params.id});Te.renderMembers(e.resources)}};const qe=e=>{document.getElementById("article_title").textContent=e.title,document.getElementById("article_text").textContent=e.content;const t=document.getElementById("publish_article");t&&null!=e.publishedAt?t.style.display="none":t&&(t.style.display="")},Pe=e=>async function(t){switch(t){case"updated":await e.reload(),e.applyChanges(),qe(e);break;case"destroyed":window.location.href="/user/articles?message=deleted"}};function Be({comment:e,isAdmin:t=!1}){const[n,r]=(0,o.useState)(!1),s=new q(e.createdAt).strftime("%d %b %y"),i=async t=>{t.preventDefault(),r(!0),e.approved=!0,(await e.updateAttribute("approved")).ok&&j.dispatch(E(new z({...e,approved:!0}),e.articleId))};return o.createElement("p",{id:`comment_${e.id}`},o.createElement("b",null,e.author)," on ",o.createElement("i",null,s),t?(()=>{let t;return t=e.approved?o.createElement(o.Fragment,null,o.createElement("span",null,"approved")," |"," "):n?o.createElement(o.Fragment,null,o.createElement("span",null,"approving...")," |"," "):o.createElement(o.Fragment,null,o.createElement("a",{href:`/user/articles/${e.articleId}/comments/${e.id}/approve`,className:"approve",onClick:i},"approve")," ","|"," "),o.createElement(o.Fragment,null," ","(",t,o.createElement("a",{href:`/user/articles/${e.articleId}/comments/${e.id}/edit`},"edit")," ","|"," ",o.createElement("a",{href:`/user/articles/${e.articleId}/comments/${e.id}`,"data-method":"delete","data-confirm":"Are you sure?"},"delete"),")")})():"",o.createElement("br",null),e.text)}Be.propTypes={comment:x().instanceOf(z).isRequired,isAdmin:x().bool};var He=Be;function Le(e){const t=e.articleId,n=e.isAdmin||!1,[r,s]=(0,o.useState)(e.comments);if((0,o.useEffect)(()=>{const e=j.subscribe(()=>s(re(j.getState(),t)));return()=>{e()}},[]),0===r.length)return o.createElement("p",null,"No comments.");const i=r.map(e=>o.createElement(He,{key:e.id,comment:e,isAdmin:n}));return o.createElement(o.Fragment,null,i)}Le.propTypes={articleId:x().number.isRequired,isAdmin:x().bool,comments:x().arrayOf(x().instanceOf(z)).isRequired};var De=Le;const Ue=e=>async function(t,n){switch(t){case"updating":document.querySelector("h1").getAttribute("data-mark")!==n.mark&&de({warning:"Uuups someone else started editing this article."});break;case"updated":await e.reload(),(e=>{for(const[t]of Object.entries(e.changes())){const n=document.querySelector(`a.apply_changes[data-for=${e.getAttrRemoteName(t)}]`);n&&n.classList.remove("none")}})(e);break;case"destroyed":window.location.href="/user/articles?message=deleted"}};var Fe=e=>{j.dispatch(b([e]));const t=(0,M.subscribe)({to:e,with:Ue(e)}),n=new F.UI.Form({for:e});return n.render(),(e=>{for(const t of Array.from(document.querySelectorAll("a.apply_changes")))t.addEventListener("click",t=>{t.preventDefault();const n=e.getObj(),r=n.getAttrName(t.target.getAttribute("data-for"));n[r]=n.changes()[r].is,e.fill(r),t.target.classList.add("none")})})(n),t};function We({article:e,onArticleDestroyed:t}){return o.createElement("tr",{id:`article_${e.id}`},o.createElement("td",{className:"title"},e.title),o.createElement("td",null,e.content),o.createElement("td",{className:"comments_quantity"},e.commentsCount),o.createElement("td",{className:"published"},e.publishedAt?"yes":"no"),o.createElement("td",null,o.createElement("a",{href:`/user/articles/${e.id}`},"Show")," |",o.createElement("a",{href:`/user/articles/${e.id}/edit`},"Edit")," |",o.createElement("a",{href:`/user/articles/${e.id}`,className:"delete_article",onClick:async n=>{if(n.preventDefault(),!confirm("Are you sure?"))return;const r=await e.delete(null);var s;r.success&&j.dispatch((s=r.id,{type:u,id:s})),t(r)}},"Delete")))}We.propTypes={article:x().instanceOf(N).isRequired,onArticleDestroyed:x().func.isRequired};var Ve=We;function Je(e){const[t,n]=(0,o.useState)(e.articles);(0,o.useEffect)(()=>{const e=j.subscribe(()=>n(j.getState().articles));return()=>{e()}},[]);const r=t.map(t=>o.createElement(Ve,{key:t.id,article:t,onArticleDestroyed:e.onArticleDestroyed}));return o.createElement(o.Fragment,null,r)}Je.propTypes={articles:x().arrayOf(x().instanceOf(N)).isRequired,onArticleDestroyed:x().func.isRequired};var Ye=Je;const Ge=e=>{e.success?de({notice:e.notice}):de({alert:e.alert})};class Xe extends i{initialize(){this.setScope(null)}}Xe.Articles=class{initialize(){this.unsubscribe=null}deinitialize(){null!==this.unsubscribe&&(this.unsubscribe(),this.unsubscribe=null)}async index(){"deleted"===r.helpers.params.message&&de({alert:"Article has been deleted."});const e=await N.get("all");j.dispatch(_(e.resources)),(0,a.createRoot)(document.getElementById("article_list")).render(o.createElement(Ye,{articles:e.resources,onArticleDestroyed:Ge}))}show(){(async()=>{const e=await N.find(r.helpers.params.id);j.dispatch(_([e])),(e=>{null!==e&&((0,M.subscribe)({to:e,with:Pe(e)}),(e=>{document.getElementById("publish_article").addEventListener("click",async t=>{t.preventDefault(),t.target.textContent="Publishing...";try{await e.put("publish"),document.getElementById("publish_article").outerHTML="<span>Published!</span>"}catch{document.getElementById("publish_article").textContent="Publish",de({alert:"Connection error!"})}})})(e),(e=>{const t=document.getElementById("edit_link").getAttribute("href");document.getElementById("edit_link").setAttribute("href",t.replace("/0/",`/${e}/`))})(e.id),qe(e))})(e)})(),(async()=>{const e=await z.all({articleId:r.helpers.params.id});j.dispatch(w(e.resources,r.helpers.params.id)),(0,a.createRoot)(document.getElementById("comments")).render(o.createElement(De,{articleId:r.helpers.params.id,comments:e.resources}))})()}new(){this.unsubscribe=Fe(new N)}async edit(){(async e=>{const t=await z.all({articleId:e});j.dispatch(w(t.resources,e)),(0,a.createRoot)(document.getElementById("comments")).render(o.createElement(De,{articleId:e,comments:t.resources,isAdmin:!0}))})(r.helpers.params.id);const e=await N.find(r.helpers.params.id);this.unsubscribe=Fe(e)}},Xe.Rooms=xe;var Ze=Xe;const Ke=()=>mt().namespaceController.constructor===Ze,Qe=()=>mt().namespaceController.constructor===lt,et=()=>Ke()&&null!==mt().controller&&mt().controller.constructor===xe&&"show"===mt().action,tt=({article_id:e},t)=>{const[n,r]=te(j.getState(),e);if(!n)return;const s=new N({...n,commentsCount:n.commentsCount+t});j.dispatch(v(s,r))};(0,M.connectWithModel)(s.connector),N.Comment=z,Ae.Member=Se;const nt=(0,M.init)({cable:(0,Q.Be)(),models:{Article:N,Room:Ae,User:K},notificationCenter:async e=>{switch(void 0!==e.loco&&"disconnected"===e.loco&&et()&&mt().controller.view.disconnected(),e.type){case"PING":Ke()&&alert("Ping!");break;case"NEW_MESSAGE":(et()?mt().controller.view.receivedMessage:()=>{})(e.message,e.author);break;case"Article created":(async({id:e})=>{if(!Ke())return;const t=await N.find({id:e,abbr:!0});j.dispatch(b([t]))})(e.payload);break;case"Article published":(async({id:e})=>{if(Qe()){const t=await N.find({id:e,abbr:!0,resource:"admin"});j.dispatch(function(e){return{type:l,articles:e}}([t]))}else{const t=await N.find({id:e,abbr:!0});j.dispatch(b([t]))}})(e.payload);break;case"Article updated":(async({id:e})=>{const t={id:e,abbr:!0};Qe()&&(t.resource="admin");let[n,r]=te(j.getState(),e);n&&(n=await N.find(t),j.dispatch(v(n,r)))})(e.payload);break;case"Article.Comment created":(async({article_id:e,id:t})=>{const n={articleId:e,id:t};mt().namespaceController.constructor===Ie&&(n.resource="main");const[r]=te(j.getState(),e);if(!r)return;const s=await z.find(n);null!==s&&(j.dispatch(function(e,t){return{type:h,articleId:t,comments:e}}([s],e)),tt({article_id:e},1))})(e.payload);break;case"Article.Comment destroyed":tt(e.payload,-1),(({article_id:e,id:t})=>{j.dispatch(function(e,t){return{type:p,id:e,articleId:t}}(t,e))})(e.payload);break;case"Article.Comment updated":(async({article_id:e,id:t})=>{const[n,r]=ne(j.getState(),t,{parentId:e});if(!n)return;const s=await n.reload();j.dispatch(E(s,e,r))})(e.payload);break;case"USER_CONFIRMED":window.location.href="/user/sessions/new?event=confirmed";break;case"User created":{const t=await K.find(e.payload.id);j.dispatch(function(e){return{type:y,users:e}}([t]));break}}},notifications:{log:!0,size:10},postInit:()=>{"test"===document.querySelector("body").getAttribute("data-rails-env")&&nt.getWire().setPollingTime(1e3)}});var rt=nt;const st=({user:e})=>o.createElement("tr",{id:`user_${e.id}`},o.createElement("td",null,e.email),o.createElement("td",null,e.username),o.createElement("td",{className:"confirmed"},e.confirmed?"Yes":"No"),o.createElement("td",null,o.createElement("a",{href:`/admin/users/${e.id}`},"Show")," |"," ",o.createElement("a",{href:`/admin/users/${e.id}/edit`},"Edit")," |"," ",o.createElement("a",{href:`/admin/users/${e.id}`,"data-method":"delete","data-confirm":"Are you sure?"},"Delete")," ","|"," ",o.createElement("a",{href:"#",onClick:t=>((e,t)=>{e.preventDefault(),rt.emit({type:"PING",user_id:t})})(t,e.id)},"Ping")));st.propTypes={user:x().instanceOf(K).isRequired};var it=st;function ot(e){const[t,n]=(0,o.useState)(e.users);(0,o.useEffect)(()=>{const e=j.subscribe(()=>n(j.getState().users));return()=>{e()}},[]);const r=t.map(e=>o.createElement(it,{key:`user_${e.id}`,user:e}));return o.createElement(o.Fragment,null,r)}ot.propTypes={users:x().arrayOf(x().instanceOf(K)).isRequired};var at=ot;class ct extends i{initialize(){this.setScope("admin")}}ct.Articles=class{async published(){const e=await N.get("published");j.dispatch(_(e.resources)),(0,a.createRoot)(document.getElementById("articles")).render(o.createElement(Y,{articles:e.resources}))}async edit(){G(),(async()=>{(e=>{(0,a.createRoot)(document.getElementById("comments")).render(o.createElement(L,{comments:e}))})((await z.all({articleId:r.helpers.params.id})).resources)})()}},ct.Comments=class{edit(){((e={})=>{const t=new F.UI.Form({for:new z({id:e.commentId,resource:"admin"}),id:`edit_comment_${e.commentId}`,initObj:!0});t.render(),window.test={commentFormObj:t.getObj()}})({commentId:r.helpers.params.id})}},ct.Sessions=class{new(){new F.UI.Form({id:"sign_in_admin",callbackSuccess:X}).render()}},ct.Users=class{async index(){const e=await K.get("all");j.dispatch(function(e){return{type:y,users:e}}(e.resources)),(0,a.createRoot)(document.querySelector("table tbody")).render(o.createElement(at,{users:e.resources}))}async show(){(e=>{document.getElementById("user_email").textContent=e.email,document.getElementById("user_username").textContent=e.username,document.getElementById("user_confirmed").textContent=e.confirmed?"Yes":"No",(e=>{const t=document.getElementById("edit_link"),n=t.getAttribute("href");t.setAttribute("href",n.replace("/0/",`/${e.id}/`))})(e)})(await K.find(r.helpers.params.id))}edit(){var e;e=new K({id:r.helpers.params.id}),new F.UI.Form({for:e,initObj:!0,id:"admin_user_form"}).render()}};var lt=ct;const ut={Admin:lt,Main:Ie,User:Ze};let dt=null;document.addEventListener("turbo:load",()=>{dt=(0,r.init)(ut)}),["turbo:click","turbo:submit-start"].forEach(e=>{document.addEventListener(e,()=>{null!==dt&&null!=dt.controller.cleanup&&(dt.controller.cleanup(),dt.controller.cleanup=null)})});var mt=()=>dt;(0,F.connect)({getLocale:()=>s.Config.locale,loco:rt,I18n:s.I18n}),s.Validators.Vulgarity=class extends s.Validators.Base{static identity="Vulgarity";constructor(){super()}validate(){if(null!=this.val)switch(typeof this.val){case"string":{const e=this._getVulgarWord();if(!new RegExp(`${e}`,["i"]).exec(this.val))return;this._addErrorMessage();break}default:throw new TypeError(`Vulgarity validator is applicable only for strings and ${this.attr} isn't.`)}}_addErrorMessage(){const e=s.I18n[s.Config.locale].errors.messages.vulgarity;this.obj.addErrorMessage(e,{for:this.attr})}_getVulgarWord(){switch(s.Config.locale){case"pl":return"kurwa";case"en":return"fuck"}}},s.I18n.pl={variants:{few(e){const t=parseInt((n=String(e))[n.length-1]);var n;-1!==[2,3,4].indexOf(t)&&(2!==String(e).length||String(e)[0])}},models:{},attributes:{},ui:{form:{sending:"Wysyłam...",success:"Sukces",errors:{connection:"Błąd z połączeniem",invalid_data:"Nieprawidłowe dane"}}},date:{formats:{default:"%d-%m-%Y",short:"%d %b",long:"%B %d, %Y"},day_names:["niedziela","poniedziałek","wtorek","środa","czwartek","piątek","sobota"],abbr_day_names:["nie","pon","wto","śro","czw","pią","sob"],month_names:["styczeń","luty","marzec","kwiecień","maj","czerwiec","lipiec","sierpień","wrzesień","październik","listopad","grudzień"],abbr_month_names:["sty","lut","mar","kwi","maj","cze","lip","sie","wrz","paź","lis","gru"]},errors:{messages:{accepted:"musi zostać zaakceptowane",blank:"nie może być puste",confirmation:"nie zgadza się z polem %{attribute}",empty:"nie może być puste",equal_to:"musi być równe %{count}",even:"musi być parzyste",exclusion:"jest zarezerwowane",greater_than:"musi być większe od %{count}",greater_than_or_equal_to:"musi być większe lub równe %{count}",inclusion:"nie znajduje się na liście dopuszczalnych wartości",invalid:"jest nieprawidłowe",less_than:"musi być mniejsze od %{count}",less_than_or_equal_to:"musi być mniejsze lub równe %{count}",not_a_number:"nie jest liczbą",not_an_integer:"musi być liczbą całkowitą",odd:"musi być nieparzyste",present:"musi być puste",too_long:{few:"jest za długie (maksymalnie %{count} znaki)",many:"jest za długie (maksymalnie %{count} znaków)",one:"jest za długie (maksymalnie jeden znak)",other:"jest za długie (maksymalnie %{count} znaków)"},too_short:{few:"jest za krótkie (przynajmniej %{count} znaki)",many:"jest za krótkie (przynajmniej %{count} znaków)",one:"jest za krótkie (przynajmniej jeden znak)",other:"jest za krótkie (przynajmniej %{count} znaków)"},wrong_length:{few:"ma nieprawidłową długość (powinna wynosić %{count} znaki)",many:"ma nieprawidłową długość (powinna wynosić %{count} znaków)",one:"ma nieprawidłową długość (powinna wynosić jeden znak)",other:"ma nieprawidłową długość (powinna wynosić %{count} znaków)"},other_than:"musi być inna niż %{count}"}}},s.I18n.pl.models.User="Użytkownik",s.I18n.pl.attributes.User={password:"Hasło",passwordConfirmation:"Powtórz hasło"},s.I18n.en.errors.messages.vulgarity="contains strong language.",s.I18n.pl.errors.messages.vulgarity="zawiera mocny język.",s.I18n.en.date={formats:{default:"%Y-%m-%d",short:"%b %d",long:"%B %d, %Y"},day_names:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],abbr_day_names:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],month_names:["January","February","March","April","May","June","July","August","September","October","November","December"],abbr_month_names:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]},window.test={getLine:()=>rt.getLine(),getWire:()=>rt.getWire()}},874:function(e){window,e.exports=function(){"use strict";var e={d:function(t,n){for(var r in n)e.o(n,r)&&!e.o(t,r)&&Object.defineProperty(t,r,{enumerable:!0,get:n[r]})},o:function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},r:function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})}},t={};e.r(t),e.d(t,{connectWithModel:function(){return f},init:function(){return h},subscribe:function(){return p}});var n=class{static toURIParams(e){let t="";for(const n in e)if(Object.prototype.hasOwnProperty.call(e,n)){const r=e[n];""!==t&&(t+="&"),t+=`${n}=${encodeURIComponent(r)}`}return t}};let r=null,s=null;const i=[];var o=e=>!!i.includes(e)||(i.unshift(e),i.length>100&&i.pop(),!1);const a=(e,t,n,r=null)=>{null!=e&&e(null==r?t:{type:r,payload:t},n)};var c=(e,t={})=>{t.log&&console.log(e);const[n,i,c,l]=e;if(o(l.loco.idempotency_key))return!1;if(delete l.loco,null==n&&null==c)return a(t.notificationCenter,l,t.emit),!0;const u=(e=>{for(const t of(()=>{if(!s||"object"!=typeof s)return[];const e=[],t=/^[A-Z]/;for(const n of Object.keys(s)){if(!t.test(n)||"Base"===n)continue;e.push(n);const r=s[n];for(const s of Object.keys(r))t.test(s)&&e.push(`${n}.${s}`)}return e})()){const n=t.split(".");if(1===n.length){const t=s[n[0]];if(t?.getRemoteName?.()===e)return t}else if(2===n.length){const t=s[n[0]]?.[n[1]];if(t?.getRemoteName?.()===e)return t}}})(n);return void 0===u?(a(t.notificationCenter,l,t.emit,`${n} ${c}`),!1):(((e,t,n,s,i,o)=>{const c=e.getIdentity();a(i,s,o,`${c} ${n}`),void 0!==r.imap[c]&&(void 0!==r.imap[c][t]&&((e,t,n,s,i,o=null)=>{null===o&&(o=new s({id:e}));for(const s of r.findConnected(i,e))s(t,n)})(t,n,s,e,c),void 0!==r.imap[c].collection&&0!==r.imap[c].collection.length&&((e,t,n)=>{for(const s of r.imap[n].collection.filter(e=>null!==e))s(`${n} ${e}`,t)})(n,s,c))})(u,i,c,l,t.notificationCenter,t.emit),!0)},l=class{constructor(e,t,n){this.pollingTime=e.pollingTime??3e3,this.log=!!e.log,this.ssl=e.ssl,this.location=e.location??"notification-center",this.size=e.size??100,this.protocolWithHost=e.protocolWithHost,this.notificationCenter=t,this.reqOpts=n,this.syncTime=null,this.token=null,this.pollingInterval=null,this.uuid=null,this.line=null}setLine(e){this.line=e}setPollingTime(e){this.pollingTime=e,this.line?.isConnected||(this.disconnect(),this.connect())}connect(){this.check(),this.pollingInterval=setInterval(()=>{this.line?.isConnected?this.disconnect():this.check()},this.pollingTime)}disconnect(){window.clearInterval(this.pollingInterval)}check(){const e=((e,t,n)=>{const r=document.querySelector("meta[name='csrf-token']"),s=new XMLHttpRequest;return s.withCredentials=!0===n.cookiesByCORS,s.open("GET",t),s.setRequestHeader("Accept","application/json"),r&&s.setRequestHeader("X-CSRF-Token",r.content),null!=n.authorizationHeader&&s.setRequestHeader("Authorization",n.authorizationHeader),s})(0,`${this._getURL()}?${n.toURIParams(this._requestParams())}`,this.reqOpts);e.onload=e=>{if(e.target.status>=200&&e.target.status<400){const t=JSON.parse(e.target.response);this.syncTime=t[1];const n=t[0];if(0===n.length)return;for(const e of n)c(e,{log:this.log,notificationCenter:this.notificationCenter,emit:e=>this.line?.send(e)});n.length===this.size&&this.check()}},e.send()}_requestParams(){const e={synced_at:this.syncTime};return null!=this.token&&(e.token=this.token),null!=this.uuid&&(e.uuid=this.uuid),e}_getURL(){let[e,,t]=window.location.href.split("/");return null!=this.protocolWithHost&&([e,t]=this.protocolWithHost.split("//")),null!=this.ssl&&(e=this.ssl?"https:":"http:"),`${e}//${t}/${this.location}`}},u=class{constructor(e,t,n){this.client=e,this.notificationCenter=t,this.wire=n,this.isConnected=!1,this.disconnectWire=!1}connect(){this.client.connect(this)}disconnect({all:e=!1}={}){return this.disconnectWire=e,this.client.disconnect()}send(e){return!!this.isConnected&&this.client.send(e)}pong(){setTimeout(()=>this.send({loco:{pong:!0}}),3e3)}connected(){console.log("WS connected"),this.isConnected=!0,null!==this.wire&&this.wire.check(),this.notificationCenter({loco:"connected"}),this.pong()}disconnected(){console.log("WS disconnected"),this.isConnected=!1,null!==this.wire&&(this.wire.uuid=null,this.disconnectWire||this.wire.connect()),this.disconnectWire=!1,this.notificationCenter({loco:"disconnected"})}rejected(){console.log("WS rejected"),this.notificationCenter({loco:"rejected"})}received(e){if(null!=e.loco){const t=((e,t)=>{if(!0===e.ping&&t.pong(),null!=t.wire)return"string"==typeof e.sync_time&&(t.wire.syncTime=e.sync_time),"string"==typeof e.uuid&&(console.log(`uuid: ${e.uuid}`),t.wire.uuid=e.uuid),"object"==typeof e.notification&&"Array"===e.notification.constructor.name&&c(e.notification,{log:t.wire.log,notificationCenter:t.notificationCenter,emit:t.send}),"string"!=typeof e.idempotency_key||!o(e.idempotency_key)})(e.loco,this);if(!0!==t)return;delete e.loco}0!==Object.keys(e).length&&this.notificationCenter(e)}},d=class{constructor(e){this.consumer=e,this.subscription=null}connect(e){this.subscription=this.consumer.subscriptions.create({channel:"Loco::NotificationCenterChannel"},{connected:()=>{e.connected()},disconnected:()=>{e.disconnected()},rejected:()=>{e.rejected()},received:t=>{e.received(t)}})}disconnect(){this.consumer.disconnect()}send(e){this.subscription.send(e)}},m=class{constructor(e){this.models=e,this.wire=null,this.line=null}getModels(){return this.models}getLine(){return this.line}getWire(){return this.wire}setAuthorizationHeader(e){for(const t in this.models)Object.prototype.hasOwnProperty.call(this.models,t)&&(this.models[t].authorizationHeader=e)}init(e){const t=e.notifications??{};if(t.protocolWithHost=e.protocolWithHost,!1!==t.enable){const n={cookiesByCORS:e.cookiesByCORS,authorizationHeader:e.authorizationHeader};this.wire=new l(t,e.notificationCenter,n),this.wire.connect()}const n=this.#e(e);null!=n&&(this.line=new u(n,e.notificationCenter,this.wire),this.line.connect(),this.wire&&this.wire.setLine(this.line)),this.#t(()=>{e.postInit?.()})}emit(e){return this.line.send(e)}#e(e){return null!=e.wsClient?e.wsClient:null!=e.cable?new d(e.cable):null}#t(e){(document.attachEvent?"complete"===document.readyState:"loading"!==document.readyState)?e():document.addEventListener("DOMContentLoaded",e)}};const h=e=>{const t=(e=>{const t=e.models||{};if(null===s)return t;for(const e of Object.keys(t))s[e]=t[e];return t})(e),n=new m(t);return n.init(e),n};let p=()=>{};const f=e=>{var t,n;t=e.IdentityMap,r=t,r.clear(),n=e.Models,s=n,p=e.IdentityMap.subscribe};return t}()},916:function(e){window,e.exports=function(){"use strict";var e={d:function(t,n){for(var r in n)e.o(n,r)&&!e.o(t,r)&&Object.defineProperty(t,r,{enumerable:!0,get:n[r]})},o:function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},r:function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})}},t={};e.r(t),e.d(t,{helpers:function(){return a},init:function(){return o}});let n=null,r=null;const s=(e,t)=>{"function"==typeof e.constructor[t]&&e.constructor[t](),"function"==typeof e[t]&&e[t]()},i=(e,t,n)=>{const r=void 0===n?e[t]:e[t][n];return"function"==typeof r?new r:"object"==typeof r?r:null};var o=e=>{const t=document.getElementsByTagName("body")[0],o=t.getAttribute("data-namespace"),a=t.getAttribute("data-controller"),c=t.getAttribute("data-action");return null!==r&&(s(r,"deinitialize"),r=null),null!==n&&(s(n,"deinitialize"),n=null),n=i(e,o),r=i(e,a),null!==n&&(r=i(e,o,a),n.controller=r,s(n,"initialize")),null!==r&&(r.namespaceController=n,s(r,"initialize"),s(r,c)),{namespaceController:n,controller:r,action:c}},a={get params(){return((e=window.location.href)=>{const t={},n=/https?:\/\/.+\/\w+\/(\d+)/.exec(e),r=null!==n?n[1]:null;null!==r&&(t.id=parseInt(r));const s=e.split("?");if(1===s.length)return t;const i=s[s.length-1].split("&").map(e=>e.split("="));for(const e of i){let n=decodeURIComponent(e[0]),r=decodeURIComponent(e[1]);"string"==typeof r&&(r=r.replace(/\+/g," ")),t[n]=r}return t})()}};return t}()}},n={};function r(e){var s=n[e];if(void 0!==s)return s.exports;var i=n[e]={exports:{}};return t[e](i,i.exports,r),i.exports}r.m=t,e=[],r.O=function(t,n,s,i){if(!n){var o=1/0;for(u=0;u<e.length;u++){n=e[u][0],s=e[u][1],i=e[u][2];for(var a=!0,c=0;c<n.length;c++)(!1&i||o>=i)&&Object.keys(r.O).every(function(e){return r.O[e](n[c])})?n.splice(c--,1):(a=!1,i<o&&(o=i));if(a){e.splice(u--,1);var l=s();void 0!==l&&(t=l)}}return t}i=i||0;for(var u=e.length;u>0&&e[u-1][2]>i;u--)e[u]=e[u-1];e[u]=[n,s,i]},r.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return r.d(t,{a:t}),t},r.d=function(e,t){for(var n in t)r.o(t,n)&&!r.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},r.e=function(){return Promise.resolve()},r.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},r.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},function(){var e={543:0};r.O.j=function(t){return 0===e[t]};var t=function(t,n){var s,i,o=n[0],a=n[1],c=n[2],l=0;if(o.some(function(t){return 0!==e[t]})){for(s in a)r.o(a,s)&&(r.m[s]=a[s]);if(c)var u=c(r)}for(t&&t(n);l<o.length;l++)i=o[l],r.o(e,i)&&e[i]&&e[i][0](),e[i]=0;return r.O(u)},n=self.webpackChunk=self.webpackChunk||[];n.forEach(t.bind(null,0)),n.push=t.bind(null,n.push.bind(n))}();var s=r.O(void 0,[121],function(){return r(728)});s=r.O(s)}(); No newline at end of file

Check warning

Code scanning / CodeQL

DOM text reinterpreted as HTML Medium test

DOM text
is reinterpreted as HTML without escaping meta-characters.

Copilot Autofix

AI about 2 months ago

Copilot could not generate an autofix suggestion

Copilot could not generate an autofix suggestion for this alert. Try pushing a new commit or if the problem persists contact support.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

2 participants