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