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