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