2 lines
24 KiB
JavaScript
2 lines
24 KiB
JavaScript
import{j as e,M as le,a as q,T as f,B as w,b as P,c as C,A as Ce,d as re,L as T,C as L,I as O,e as be,f as D,P as $,g as we,u as Se,h as ce,i as X,k as Z,D as Q,l as W,m as F,n as K,o as ue,p as Pe,q as de,r as he,s as Fe,S as M,t as Ae,G as v,v as J,w as Ee,x as ke,y as De,z as $e,F as Ie,E as Te,H as Ue}from"./mui-CxHUbSMi.js";import{u as Y,a as R,b as H,c as Oe,d as qe,L as E,e as Me,O as Le,f as Re,r as N,g as B,h as z,q as ee,i as te,j as ne,Q as Be,k as ze,l as Ne,R as Qe,m as We}from"./tanstack-xmxrKlZO.js";import{c as Ke,r as y}from"./react-DXd9vB-a.js";import{i as U,B as He,a as Ve,b as _e,u as A,t as m}from"./i18n-DJgSTqOl.js";(function(){const n=document.createElement("link").relList;if(n&&n.supports&&n.supports("modulepreload"))return;for(const r of document.querySelectorAll('link[rel="modulepreload"]'))o(r);new MutationObserver(r=>{for(const i of r)if(i.type==="childList")for(const s of i.addedNodes)s.tagName==="LINK"&&s.rel==="modulepreload"&&o(s)}).observe(document,{childList:!0,subtree:!0});function a(r){const i={};return r.integrity&&(i.integrity=r.integrity),r.referrerPolicy&&(i.referrerPolicy=r.referrerPolicy),r.crossOrigin==="use-credentials"?i.credentials="include":r.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function o(r){if(r.ep)return;r.ep=!0;const i=a(r);fetch(r.href,i)}})();var G={},ae=Ke;G.createRoot=ae.createRoot,G.hydrateRoot=ae.hydrateRoot;const _=15,S="https://khofmann.userpage.fu-berlin.de/phpCourse/exam/api/";let oe;class Ge{constructor(){if(this.hasAuth=()=>this.token!==void 0,this.isAdmin=()=>{var n;return this.hasAuth()&&((n=this.self)==null?void 0:n.isAdmin)},this.getAuthenticatedUser=()=>this.self,this.getCurrentSession=()=>[this.token,this.refreshToken],this.logIn=async(n,a)=>{const{user:o,token:r}=await(await this.post("login",{email:n,password:a})).json();this.self=o,this.token=r},this.logOut=async()=>{try{return await(await this.postAuth("logout")).json()}catch{return!1}finally{this.self=void 0,this.token=void 0}},this.posts=async n=>{const a=`posts?p=${n??0}&l=${_}`;return this.token?await(await this.getAuth(a)).json():await(await this.get(a)).json()},this.deletePost=async n=>await(await this.delete(`posts/${n}?l=${_}`)).json(),this.user=async n=>{var a;return await(await this.getAuth(`users/${n??((a=this.self)==null?void 0:a.id)}`)).json()},this.updateUser=async(n,a)=>await(await this.patch(`users/${a??"self"}`,n)).json(),this.updateUserImage=async(n,a)=>{const o=new FormData;return n.image&&o.append("image",n.image),!n.image&&n.predefined&&o.append("predefined",n.predefined),await(await this.postAuthRaw(`users/${a??"self"}/image`,o)).json()},this.newPost=async n=>await(await this.postAuth(`posts?l=${_}`,{...n})).json(),this.updatePost=async(n,a)=>await(await this.patch(`posts/${a}`,n)).json(),this.post=async(n,a,o)=>{const r=await fetch(`${S}${n}`,{mode:"cors",method:"post",headers:o,body:JSON.stringify(a)});if(r.ok)return r;throw await r.json()},this.postAuth=async(n,a,o)=>{const r=await fetch(`${S}${n}`,{mode:"cors",method:"post",headers:{token:this.token??"",...o},body:JSON.stringify(a)});if(r.ok)return r;throw await r.json()},this.postAuthRaw=async(n,a,o)=>{const r=await fetch(`${S}${n}`,{mode:"cors",method:"post",headers:{token:this.token??"",...o},body:a});if(r.ok)return r;throw await r.json()},this.get=async(n,a)=>{const o=await fetch(`${S}${n}`,{mode:"cors",method:"get",headers:a});if(o.ok)return o;throw await o.json()},this.getAuth=async(n,a)=>{const o=await fetch(`${S}${n}`,{mode:"cors",method:"get",headers:{token:this.token??"",...a}});if(o.ok)return o;throw await o.json()},this.delete=async(n,a)=>{const o=await fetch(`${S}${n}`,{mode:"cors",method:"delete",headers:{token:this.token??"",...a}});if(o.ok)return o;throw await o.json()},this.patch=async(n,a,o)=>{const r=await fetch(`${S}${n}`,{mode:"cors",method:"patch",headers:{token:this.token??"",...o},body:JSON.stringify(a)});if(r.ok)return r;throw await r.json()},oe)throw new Error("New instance cannot be created!!");oe=this}}const g=new Ge;var k=(t=>(t.NOT_FOUND="NotFound",t.UNAUTHORIZED="Unauthorized",t.FAILED_UPDATE="FailedUpdate",t.MISSING_FIELD="MissingField",t))(k||{});U.use(He).use(Ve).use(_e).init({fallbackLng:"en",debug:!1,interpolation:{escapeValue:!1},backend:{loadPath:"/phpCourse/exam/dist/locales/{{lng}}/{{ns}}.json"}});const Xe=({anchorEl:t,handleClose:n})=>e.jsxs(le,{anchorEl:t,anchorOrigin:{vertical:"bottom",horizontal:"right"},keepMounted:!0,transformOrigin:{vertical:"top",horizontal:"right"},open:!!t,onClose:n,sx:{"& .MuiMenu-paper":{minWidth:"240px"}},children:[e.jsx(q,{selected:U.language==="en",onClick:()=>{U.changeLanguage("en"),n()},children:"English"},"de"),e.jsx(q,{selected:U.language==="de",onClick:()=>{U.changeLanguage("de"),n()},children:"Deutsch"},"en")]});var b=(t=>(t.INDEX="/",t.PROFILE="/profile",t))(b||{});const I=({error:t,context:n,color:a="error.main"})=>{const{t:o}=A();if(console.log(t,n),!t)return null;if(t.code)switch(t.code){case k.NOT_FOUND:return e.jsx(f,{color:a,children:o(t.code,{context:`${t.entity}:${n}`})});case k.UNAUTHORIZED:return e.jsx(f,{color:a,children:o(t.code,{context:n})});case k.FAILED_UPDATE:return t.fields.map((r,i)=>e.jsx(f,{color:a,children:o(t.code,{context:`${t.reasons[i]}:${r}:${n}`})},`error_${r}`));case k.MISSING_FIELD:return t.fields.map(r=>e.jsx(f,{color:a,children:o(t.code,{context:`${r}:${n}`})},`error_${r}`))}return e.jsx(f,{color:a,children:o((t==null?void 0:t.message)??"Unknown",{context:n})})},Ze=({handleClose:t})=>{const[n,a]=y.useState(),{t:o}=A(),r=Y(),i=R({defaultValues:{email:"",password:""},onSubmit:async({value:s})=>{try{await g.logIn(s.email,s.password),r.invalidate(),t()}catch(p){a(p)}}});return e.jsx("form",{onSubmit:s=>{s.preventDefault(),s.stopPropagation(),i.handleSubmit()},onKeyDown:s=>{s.key==="Tab"&&s.stopPropagation()},noValidate:!0,children:e.jsxs(w,{sx:{display:"grid",gap:2,padding:1},children:[e.jsx(i.Field,{name:"email",validators:{onChange:({value:s})=>s?void 0:o("Email required"),onChangeAsyncDebounceMs:250,onChangeAsync:async({value:s})=>!s&&o("Email required")},children:s=>e.jsx(e.Fragment,{children:e.jsx(P,{variant:"outlined",name:s.name,value:s.state.value,onBlur:s.handleBlur,onChange:p=>s.handleChange(p.target.value),size:"small",label:o("Email"),required:!0,error:s.state.meta.isTouched&&s.state.meta.errors.length>0,helperText:s.state.meta.isTouched?s.state.meta.errors.join(","):"",type:"email",autoComplete:"username",inputMode:"email",fullWidth:!0})})}),e.jsx(i.Field,{name:"password",validators:{onChange:({value:s})=>s?void 0:o("Password required"),onChangeAsyncDebounceMs:250,onChangeAsync:async({value:s})=>!s&&o("Password required")},children:s=>e.jsx(e.Fragment,{children:e.jsx(P,{variant:"outlined",name:s.name,value:s.state.value,onBlur:s.handleBlur,onChange:p=>s.handleChange(p.target.value),size:"small",label:o("Password"),required:!0,error:s.state.meta.isTouched&&s.state.meta.errors.length>0,helperText:s.state.meta.isTouched?s.state.meta.errors.join(","):"",type:"password",autoComplete:"password",fullWidth:!0})})}),e.jsx(i.Subscribe,{selector:s=>[s.canSubmit,s.isSubmitting],children:([s])=>e.jsx(e.Fragment,{children:e.jsx(C,{type:"submit",disabled:!s,variant:"contained",children:o("Log in")})})}),n&&e.jsx(I,{error:n,context:"login"})]})})},Je=({anchorEl:t,handleClose:n})=>{const a=H(),o=Y(),r=Oe({from:"/profile/",strict:!0,shouldThrow:!1}),i=g.getAuthenticatedUser();return e.jsx(le,{anchorEl:t,anchorOrigin:{vertical:"bottom",horizontal:"right"},keepMounted:!0,transformOrigin:{vertical:"top",horizontal:"right"},open:!!t,onClose:n,sx:{"& .MuiMenu-paper":{minWidth:"240px"}},children:i?[e.jsx(q,{selected:!!r,onClick:()=>{a({to:b.PROFILE}),n()},children:m("Profile")},"profile"),e.jsx(q,{onClick:async()=>{await g.logOut(),o.invalidate(),n()},children:m("Log out")},"logout")]:e.jsx(Ze,{handleClose:n})})},Ye=({children:t})=>{const n=Se({disableHysteresis:!0,threshold:0});return y.cloneElement(t,{elevation:n?4:0})},et=()=>{const[t,n]=y.useState(null),[a,o]=y.useState(null),{t:r}=A(),i=qe({select:h=>h.status==="pending"}),s=g.getAuthenticatedUser(),p=()=>{o(null),n(null)};return e.jsx(Ye,{children:e.jsxs(e.Fragment,{children:[e.jsx(Ce,{children:e.jsxs(re,{children:[e.jsxs(w,{sx:{flexGrow:1,alignItems:"center",display:"flex",gap:1},children:[e.jsx(T,{component:E,to:"/",color:"#FFF",variant:"h6",underline:"none",children:r("GuestBook")}),i&&e.jsx(L,{size:16,thickness:10,sx:{color:"white"}})]}),e.jsx(O,{size:"large",onClick:h=>o(h.currentTarget),children:e.jsx(be,{sx:{color:"white"}})}),s?e.jsx(O,{onClick:h=>n(h.currentTarget),sx:{p:0},children:e.jsx(D,{alt:s.username,src:`storage/${s.image}`,children:e.jsx($,{})})}):e.jsx(O,{size:"large",onClick:h=>n(h.currentTarget),color:"inherit",children:e.jsx(we,{})}),e.jsx(Xe,{anchorEl:a,handleClose:p}),e.jsx(Je,{anchorEl:t,handleClose:p})]})}),e.jsx(re,{})]})})},tt=()=>e.jsxs(e.Fragment,{children:[e.jsx(et,{}),e.jsx(w,{sx:{display:"flex",justifyContent:"center"},children:e.jsx(w,{sx:{maxWidth:"800px",flexGrow:1},children:e.jsx(Le,{})})}),!1]}),nt=({error:t})=>{const n=Y(),a=Re();return y.useEffect(()=>{a.reset()},[a]),"code"in t&&t.code===k.UNAUTHORIZED&&(g.logOut(),N({to:b.INDEX})),e.jsxs("div",{children:[t.message,e.jsx("button",{onClick:()=>{n.invalidate()},children:"retry"})]})},V=Me()({component:tt,errorComponent:nt}),st=()=>{const[t,n]=y.useState(),[a,o]=y.useState(0),{t:r}=A(),i=B(),s=H(),p=z({mutationFn:({data:d})=>g.newPost(d)}),h=R({defaultValues:{content:""},onSubmit:async({value:d})=>{try{p.mutate({data:d},{onSuccess:async x=>{h.reset(),await i.invalidateQueries({queryKey:["posts"]}),s({to:"/",search:{page:x.pages-1}})},onError:n})}catch(x){n(x)}}});return e.jsx("form",{onSubmit:d=>{d.preventDefault(),d.stopPropagation(),h.handleSubmit()},onKeyDown:d=>{d.key==="Tab"&&d.stopPropagation()},noValidate:!0,children:e.jsxs(w,{sx:{display:"grid",gap:2,padding:1},children:[e.jsx(h.Field,{name:"content",validators:{onChange:({value:d})=>d?void 0:r("Content required"),onChangeAsyncDebounceMs:250,onChangeAsync:async({value:d})=>!d&&r("Content required")},children:d=>e.jsxs(e.Fragment,{children:[e.jsx(P,{variant:"outlined",multiline:!0,minRows:3,name:d.name,value:d.state.value,onBlur:d.handleBlur,onChange:x=>{x.target.value.length<=250&&(o(x.target.value.length),d.handleChange(x.target.value))},size:"small",label:r("Comment"),required:!0,error:d.state.meta.isTouched&&d.state.meta.errors.length>0,helperText:d.state.meta.isTouched?d.state.meta.errors.join(","):"",autoComplete:"off",fullWidth:!0}),e.jsx(ce,{variant:"determinate",value:a/250*100,color:a===250?"error":a>=200?"warning":"primary"})]})}),e.jsx(h.Subscribe,{selector:d=>[d.canSubmit,d.isSubmitting],children:([d])=>e.jsx(e.Fragment,{children:e.jsx(C,{type:"submit",disabled:!d||p.isPending,variant:"contained",endIcon:p.isPending&&e.jsx(L,{color:"inherit",size:"20px"}),children:r("Post comment")})})}),t&&e.jsx(I,{error:t,context:"newPost"})]})})},me=t=>new Date(t.date).toLocaleString(navigator.languages[0]??"de-DE",{timeZone:t.timezone,day:"2-digit",month:"2-digit",year:"numeric",hour:"2-digit",hour12:!1,minute:"2-digit"}),rt=({post:t,open:n,onClose:a})=>{const[o,r]=y.useState(),[i,s]=y.useState(t.content.length),p=z({mutationFn:({data:c,id:j})=>g.updatePost(c,j)}),h=R({defaultValues:{content:t.content.replaceAll("<br />","")},onSubmit:async({value:c})=>{try{p.mutate({data:c,id:t.id},{onSuccess:()=>{u(),l.invalidateQueries({queryKey:["posts"]})},onError:r})}catch(j){r(j)}}}),d=X(),x=Z(d.breakpoints.only("xs"),{noSsr:!0}),l=B(),u=()=>{h.reset(),r(void 0),a()};return e.jsxs(Q,{open:n,onClose:u,fullWidth:!0,fullScreen:x,PaperProps:{component:"form",onSubmit:c=>{c.preventDefault(),c.stopPropagation(),h.handleSubmit()},onKeyDown:c=>{c.key==="Tab"&&c.stopPropagation()},noValidate:!0},children:[e.jsx(W,{children:m("Edit post")}),e.jsx(F,{children:e.jsx(h.Field,{name:"content",validators:{onChange:({value:c})=>c?void 0:m("Content required"),onChangeAsyncDebounceMs:250,onChangeAsync:async({value:c})=>!c&&m("Content required")},children:c=>e.jsxs(e.Fragment,{children:[e.jsx(P,{variant:"outlined",multiline:!0,minRows:3,name:c.name,value:c.state.value,onBlur:c.handleBlur,onChange:j=>{j.target.value.length<=250&&(s(j.target.value.length),c.handleChange(j.target.value))},size:"small",label:m("Comment"),required:!0,error:c.state.meta.isTouched&&c.state.meta.errors.length>0,helperText:c.state.meta.isTouched?c.state.meta.errors.join(","):"",autoComplete:"off",margin:"dense",fullWidth:!0}),e.jsx(ce,{variant:"determinate",value:i/250*100,color:i===250?"error":i>=200?"warning":"primary"})]})})}),e.jsx(K,{children:e.jsx(h.Subscribe,{selector:c=>[c.canSubmit,c.isSubmitting],children:([c])=>e.jsxs(e.Fragment,{children:[e.jsx(C,{variant:"outlined",onClick:()=>{u()},children:m("Cancel")}),e.jsx(C,{type:"submit",disabled:!c||p.isPending,autoFocus:!0,variant:"contained",endIcon:p.isPending&&e.jsx(L,{color:"inherit",size:"20px"}),children:m("Save")})]})})}),o&&e.jsx(F,{children:e.jsx(I,{error:o,context:"postUpdate"})})]})},at=({post:t})=>{var l,u,c;const[n,a]=y.useState(!1),[o,r]=y.useState(!1),[i,s]=y.useState(),p=z({mutationFn:j=>g.deletePost(j)}),{t:h}=A(),d=B(),x=H();return e.jsxs(ue,{children:[e.jsx(Pe,{avatar:"id"in t.user?t.user.id!==((l=g.getAuthenticatedUser())==null?void 0:l.id)?e.jsx(T,{component:E,to:"/profile/$id",params:{id:t.user.id},children:e.jsx(D,{alt:t.user.username,src:`storage/${t.user.image}`,children:e.jsx($,{})})}):e.jsx(T,{component:E,to:"/profile",children:e.jsx(D,{alt:t.user.username,src:`storage/${t.user.image}`,children:e.jsx($,{})})}):e.jsx(D,{alt:t.user.username,src:`storage/${t.user.image}`,children:e.jsx($,{})}),title:"id"in t.user?t.user.id!==((u=g.getAuthenticatedUser())==null?void 0:u.id)?e.jsx(T,{component:E,to:"/profile/$id",params:{id:t.user.id},children:t.user.username}):e.jsx(T,{component:E,to:"/profile",children:t.user.username}):t.user.username,subheader:me(t.postedAt)}),e.jsx(de,{children:e.jsx(f,{children:e.jsx("span",{dangerouslySetInnerHTML:{__html:t.content}})})}),e.jsxs(he,{children:[(g.isAdmin()||"id"in t.user&&t.user.id===((c=g.getAuthenticatedUser())==null?void 0:c.id))&&e.jsxs(e.Fragment,{children:[e.jsx(C,{size:"small",onClick:()=>r(!0),children:h("Edit")}),e.jsx(rt,{post:t,open:o,onClose:()=>r(!1)})]}),g.isAdmin()&&e.jsxs(e.Fragment,{children:[e.jsx(C,{size:"small",color:"error",onClick:()=>a(!0),children:h("Delete")}),e.jsxs(Q,{open:n,onClose:()=>a(!1),children:[e.jsx(W,{children:h("Confirm post delete title")}),e.jsx(F,{children:e.jsx(Fe,{children:h("Confirm post delete body",{name:t.user.username})})}),e.jsxs(K,{children:[e.jsx(C,{onClick:()=>a(!1),autoFocus:!0,variant:"contained",children:h("No")}),e.jsx(C,{variant:"outlined",color:"error",onClick:()=>{p.mutate(t.id,{onSuccess:async j=>{await d.invalidateQueries({queryKey:["posts"]}),x({to:"/",search:{page:j.pages-1}})},onError:s}),a(!1)},children:h("Yes")})]})]})]})]}),e.jsx(M,{open:p.isError,autoHideDuration:2e3,onClose:()=>{p.reset()},TransitionProps:{onExited:()=>s(void 0)},children:e.jsx(Ae,{severity:"error",variant:"filled",sx:{width:"100%"},children:i&&e.jsx(I,{error:i,context:"delete",color:"white"})})}),e.jsx(M,{open:p.isPending,message:h("Deleting")})]})},ge=t=>ee({queryKey:["posts",{page:t??0,hasAuth:g.hasAuth()}],queryFn:()=>g.posts(t)}),ot=()=>{const{page:t}=pe.useSearch(),{data:n,isFetching:a}=ne(ge(t)),{t:o}=A(),r=H();return y.useEffect(()=>{(t??0)>=n.pages&&r({to:"/",search:{page:n.pages-1}})},[t]),e.jsxs(e.Fragment,{children:[e.jsx(M,{open:a,message:o("Updating")}),e.jsxs(v,{container:!0,spacing:2,children:[n.data.map(i=>e.jsx(v,{item:!0,xs:12,children:e.jsx(at,{post:i})},i.id)),e.jsx(v,{item:!0,xs:12,children:e.jsx(J,{variant:"middle"})}),g.hasAuth()&&e.jsx(v,{item:!0,xs:12,children:e.jsx(st,{})}),e.jsx(v,{item:!0,xs:12,sx:{display:"flex",justifyContent:"center"},children:e.jsx(Ee,{page:(t??0)+1,count:n.pages,color:"primary",renderItem:i=>e.jsx(ke,{...i,component:E,to:"/",search:{page:(i.page??0)>0?(i.page??1)-1:void 0},onClick:s=>i.onClick(s)})})})]})]})},pe=te(b.INDEX)({loaderDeps:({search:{page:t}})=>({page:t}),loader:({context:{queryClient:t},deps:{page:n}})=>t.ensureQueryData(ge(n)),validateSearch:t=>({page:(t==null?void 0:t.page)!==void 0?Number((t==null?void 0:t.page)??0):void 0}),component:ot}),it=({user:t,open:n,onClose:a})=>{const[o,r]=y.useState(),i=z({mutationFn:({data:l,id:u})=>g.updateUser(l,u)}),s=R({defaultValues:{username:t.username,email:t.email},onSubmit:async({value:l})=>{var u;try{i.mutate({data:l,id:((u=g.getAuthenticatedUser())==null?void 0:u.id)===t.id?void 0:t.id},{onSuccess:()=>{var j;x();const c=((j=g.getAuthenticatedUser())==null?void 0:j.id)===t.id?["profile"]:["profile",{id:t.id}];d.invalidateQueries({queryKey:c})},onError:r})}catch(c){r(c)}}}),p=X(),h=Z(p.breakpoints.only("xs"),{noSsr:!0}),d=B(),x=()=>{s.reset(),r(void 0),a()};return e.jsxs(Q,{open:n,onClose:x,fullWidth:!0,fullScreen:h,PaperProps:{component:"form",onSubmit:l=>{l.preventDefault(),l.stopPropagation(),s.handleSubmit()},onKeyDown:l=>{l.key==="Tab"&&l.stopPropagation()},noValidate:!0},children:[e.jsx(W,{children:m("Edit data")}),e.jsxs(F,{children:[e.jsx(s.Field,{name:"username",validators:{onChange:({value:l})=>l?void 0:m("Username required"),onChangeAsyncDebounceMs:250,onChangeAsync:async({value:l})=>!l&&m("Username required")},children:l=>e.jsx(e.Fragment,{children:e.jsx(P,{name:l.name,value:l.state.value,onBlur:l.handleBlur,onChange:u=>l.handleChange(u.target.value),size:"small",label:m("Username"),required:!0,margin:"dense",autoComplete:"new-username",fullWidth:!0,error:l.state.meta.isTouched&&l.state.meta.errors.length>0,helperText:l.state.meta.isTouched?l.state.meta.errors.join(","):""})})}),e.jsx(s.Field,{name:"email",validators:{onChange:({value:l})=>l?void 0:m("Email required"),onChangeAsyncDebounceMs:250,onChangeAsync:async({value:l})=>!l&&m("Email required")},children:l=>e.jsx(e.Fragment,{children:e.jsx(P,{name:l.name,value:l.state.value,onBlur:l.handleBlur,onChange:u=>l.handleChange(u.target.value),size:"small",label:m("Email"),required:!0,margin:"dense",autoComplete:"new-username",fullWidth:!0,error:l.state.meta.isTouched&&l.state.meta.errors.length>0,helperText:l.state.meta.isTouched?l.state.meta.errors.join(","):""})})})]}),e.jsx(K,{children:e.jsx(s.Subscribe,{selector:l=>[l.canSubmit,l.isSubmitting],children:([l])=>e.jsxs(e.Fragment,{children:[e.jsx(C,{variant:"outlined",onClick:()=>{x()},children:m("Cancel")}),e.jsx(C,{type:"submit",disabled:!l||i.isPending,autoFocus:!0,variant:"contained",endIcon:i.isPending&&e.jsx(L,{color:"inherit",size:"20px"}),children:m("Save")})]})})}),o&&e.jsx(F,{children:e.jsx(I,{error:o,context:"userUpdate"})})]})},lt=({user:t,open:n,onClose:a})=>{const[o,r]=y.useState(),i=z({mutationFn:({data:u,id:c})=>g.updateUserImage(u,c)}),s=R({onSubmit:async({value:u})=>{var c;try{i.mutate({data:u,id:((c=g.getAuthenticatedUser())==null?void 0:c.id)===t.id?void 0:t.id},{onSuccess:()=>{var se;l();const j=((se=g.getAuthenticatedUser())==null?void 0:se.id)===t.id?["profile"]:["profile",{id:t.id}];d.invalidateQueries({queryKey:j})},onError:r})}catch(j){r(j)}}}),p=X(),h=Z(p.breakpoints.only("xs"),{noSsr:!0}),d=B(),x=s.useStore(u=>({image:u.values.image,predefined:u.values.predefined})),l=()=>{s.reset(),r(void 0),a()};return e.jsxs(Q,{open:n,onClose:l,fullWidth:!0,fullScreen:h,PaperProps:{component:"form",encType:"multipart/form-data",onSubmit:u=>{u.preventDefault(),u.stopPropagation(),s.handleSubmit()},onKeyDown:u=>{u.key==="Tab"&&u.stopPropagation()},noValidate:!0},children:[e.jsx(W,{children:m("Edit image")}),e.jsx(F,{sx:{gap:2},children:e.jsxs(v,{container:!0,spacing:2,children:[e.jsx(v,{item:!0,xs:12,sx:{display:"flex",justifyContent:"center"},children:e.jsx(D,{alt:t.username,src:x.image?URL.createObjectURL(x.image):x.predefined?`storage/profilbilder/default/${x.predefined}.svg`:`storage/${t.image}`,sx:{width:"100px",height:"100px"},children:e.jsx($,{sx:{width:"60px",height:"60px"}})})}),e.jsx(v,{item:!0,xs:12,children:e.jsxs(w,{sx:{display:"flex",gap:2},children:[e.jsx(C,{component:"label",role:void 0,variant:"contained",tabIndex:-1,startIcon:e.jsx(De,{}),fullWidth:!0,children:e.jsx(s.Field,{name:"image",children:u=>{var c;return e.jsxs(e.Fragment,{children:[e.jsx(w,{sx:{textOverflow:"ellipsis",textWrap:"nowrap",overflow:"hidden"},children:u.state.value?m("Upload named",{name:(c=u.state.value)==null?void 0:c.name}):m("Upload image")}),e.jsx(P,{name:u.name,onBlur:u.handleBlur,value:u.state.value?void 0:"",onChange:j=>u.handleChange(j.target.files[0]),size:"small",type:"file",required:!0,sx:{display:"none"},autoComplete:"off"})]})}})}),e.jsx(O,{color:"error",onClick:()=>s.setFieldValue("image",void 0),children:e.jsx($e,{})})]})}),e.jsx(v,{item:!0,xs:12,children:e.jsx(J,{variant:"middle",children:e.jsx(f,{sx:{opacity:.36},children:m("or")})})}),e.jsx(v,{item:!0,xs:12,children:e.jsx(s.Field,{name:"predefined",children:u=>e.jsxs(Ie,{fullWidth:!0,children:[e.jsx(Te,{size:"small",children:m("Predefined")}),e.jsx(Ue,{name:u.name,value:u.state.value,onBlur:u.handleBlur,onChange:c=>u.handleChange(c.target.value),size:"small",label:m("Predefined"),autoComplete:"off",fullWidth:!0,children:[...Array(10).keys()].map(c=>e.jsx(q,{value:`avatar-${c+1}`,children:m("Avatar",{name:c+1})},`avatar-${c+1}`))})]})})})]})}),e.jsx(K,{children:e.jsx(s.Subscribe,{selector:u=>[u.canSubmit,u.isSubmitting],children:([u])=>e.jsxs(e.Fragment,{children:[e.jsx(C,{variant:"outlined",onClick:()=>{l()},children:m("Cancel")}),e.jsx(C,{type:"submit",disabled:!u||i.isPending,autoFocus:!0,variant:"contained",endIcon:i.isPending&&e.jsx(L,{color:"inherit",size:"20px"}),children:m("Save")})]})})}),o&&e.jsx(F,{children:e.jsx(I,{error:o,context:"userUpdate"})})]})},xe=({user:t,canEdit:n})=>{const[a,o]=y.useState(!1),[r,i]=y.useState(!1),{t:s}=A();return e.jsxs(v,{container:!0,sx:{justifyContent:"center"},spacing:2,children:[e.jsx(v,{item:!0,children:e.jsxs(ue,{children:[e.jsx(de,{children:e.jsxs(v,{container:!0,spacing:2,children:[e.jsx(v,{item:!0,sx:{display:"flex",flexGrow:1,justifyContent:"center"},children:e.jsx(O,{onClick:()=>i(!0),children:e.jsx(D,{alt:t.username,src:`storage/>${t.image}`,sx:{width:"100px",height:"100px"},children:e.jsx($,{sx:{width:"60px",height:"60px"}})})})}),e.jsx(v,{item:!0,sx:{display:"flex",alignItems:"center"},children:e.jsxs(w,{sx:{display:"grid",gridTemplateColumns:"120px 1fr",columnGap:1},children:[e.jsxs(f,{fontWeight:"bold",children:[s("Username"),":"]}),e.jsx(f,{children:t.username}),e.jsxs(f,{fontWeight:"bold",children:[s("Email"),":"]}),e.jsx(f,{children:t.email}),e.jsxs(f,{fontWeight:"bold",children:[s("Member since"),":"]}),e.jsx(f,{children:me(t.memberSince)}),e.jsxs(f,{fontWeight:"bold",children:[s("Post count"),":"]}),e.jsx(f,{children:t.postCount})]})})]})}),e.jsx(he,{children:n&&e.jsxs(e.Fragment,{children:[e.jsx(C,{size:"small",onClick:()=>o(!0),children:s("Edit")}),e.jsx(it,{user:t,open:a,onClose:()=>o(!1)}),e.jsx(lt,{user:t,open:r,onClose:()=>i(!1)})]})})]})}),e.jsx(v,{item:!0,xs:12,children:e.jsx(J,{variant:"middle",children:e.jsx(f,{sx:{opacity:.36},children:s("Recent posts")})})})]})},je=ee({queryKey:["profile"],queryFn:()=>g.user()}),ye=t=>ee({queryKey:["profile",{id:t}],queryFn:()=>g.user(t)}),ct=()=>{const{data:t,isFetching:n}=ne(je);return e.jsxs(e.Fragment,{children:[e.jsx(M,{open:n,message:m("Updating")}),e.jsx(xe,{user:t,canEdit:!0})]})},ut=te(`${b.PROFILE}/`)({loader:({context:{queryClient:t}})=>t.ensureQueryData(je),beforeLoad:()=>{if(!g.hasAuth())throw N({to:b.INDEX})},component:ct}),dt=()=>{const{id:t}=fe.useParams(),{data:n,isFetching:a}=ne(ye(t));return e.jsxs(e.Fragment,{children:[e.jsx(M,{open:a,message:m("Updating")}),e.jsx(xe,{user:n,canEdit:g.isAdmin()})]})},fe=te(`${b.PROFILE}/$id`)({params:{parse:({id:t})=>({id:parseInt(t)}),stringify:({id:t})=>({id:t.toString()})},loader:({context:{queryClient:t},params:{id:n}})=>t.ensureQueryData(ye(n)),beforeLoad:({params:{id:t}})=>{var n;if(!g.hasAuth())throw N({to:b.INDEX});if(t===((n=g.getAuthenticatedUser())==null?void 0:n.id))throw N({to:b.PROFILE})},component:dt}),ht=pe.update({path:"/",getParentRoute:()=>V}),mt=ut.update({path:"/profile/",getParentRoute:()=>V}),gt=fe.update({path:"/profile/$id",getParentRoute:()=>V}),pt=V.addChildren({IndexRoute:ht,ProfileIdRoute:gt,ProfileIndexRoute:mt}),ve=new Be,xt=ze({routeTree:pt,context:{queryClient:ve},defaultPreload:"intent",defaultPreloadStaleTime:0,basepath:"/phpCourse/exam"}),ie=document.getElementById("root");ie.innerHTML||G.createRoot(ie).render(e.jsx(y.StrictMode,{children:e.jsxs(Ne,{client:ve,children:[e.jsx(Qe,{router:xt}),e.jsx(We,{initialIsOpen:!1})]})}));
|