3 lines
11 KiB
JavaScript
3 lines
11 KiB
JavaScript
import{P as p,Q as W,S as X,U as K,C as t,a as m,V as b,X as y,Y as V}from"./vendor_1_react-CXEjNhpI.js";import{u as k,a as Z,b as J,c as Y,L as x,d as _,O as ee,e as te,r as F,f as $,q as E,g as I,Q as ne,h as se,i as re,R as oe,j as ae}from"./vendor_tanstack-BhPLOUa_.js";import{M as D,a as w,B as v,T as L,b as ie,c as l,A as ue,d as R,L as j,C as ce,I as A,e as le,f as C,g as de,u as he,h as ge,i as me,j as pe,S as O,G as g,P as xe,k as fe}from"./vendor_mui-lk1_op8u.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"]'))a(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"&&a(s)}).observe(document,{childList:!0,subtree:!0});function o(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 a(r){if(r.ep)return;r.ep=!0;const i=o(r);fetch(r.href,i)}})();const f="https://khofmann.userpage.fu-berlin.de/phpCourse/exam/api/";let S;class je{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,o)=>{const{user:a,token:r}=await(await this.post("login",{email:n,password:o})).json();this.self=a,this.isAdmin=a.isAdmin,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 o=`posts?p=${n??0}&l=9`;return this.token?await(await this.getAuth(o)).json():await(await this.get(o)).json()},this.user=async n=>{var o;return await(await this.getAuth(`users/${n??((o=this.self)==null?void 0:o.id)}`)).json()},this.post=async(n,o=void 0,a=void 0)=>{const r=await fetch(`${f}${n}`,{mode:"cors",method:"post",headers:a,body:JSON.stringify(o)});if(r.ok)return r;throw await r.json()},this.postAuth=async(n,o=void 0,a=void 0)=>{const r=await fetch(`${f}${n}`,{mode:"cors",method:"post",headers:{token:this.token??"",...a},body:JSON.stringify(o)});if(r.ok)return r;throw await r.json()},this.get=async(n,o=void 0)=>{const a=await fetch(`${f}${n}`,{mode:"cors",method:"get",headers:o});if(a.ok)return a;throw await a.json()},this.getAuth=async(n,o=void 0)=>{const a=await fetch(`${f}${n}`,{mode:"cors",method:"get",headers:{token:this.token??"",...o}});if(a.ok)return a;throw await a.json()},S)throw new Error("New instance cannot be created!!");S=this}}const c=new je;p.use(W).use(X).use(K).init({fallbackLng:"en",debug:!1,interpolation:{escapeValue:!1},backend:{loadPath:"/phpCourse/exam/dist/locales/{{lng}}/{{ns}}.json"}});const ye=({anchorEl:e,handleClose:n})=>t.jsxs(D,{anchorEl:e,anchorOrigin:{vertical:"bottom",horizontal:"right"},keepMounted:!0,transformOrigin:{vertical:"top",horizontal:"right"},open:!!e,onClose:n,sx:{"& .MuiMenu-paper":{minWidth:"240px"}},children:[t.jsx(w,{selected:p.language==="en",onClick:()=>{p.changeLanguage("en"),n()},children:"English"},"de"),t.jsx(w,{selected:p.language==="de",onClick:()=>{p.changeLanguage("de"),n()},children:"Deutsch"},"en")]});var d=(e=>(e.INDEX="/",e.PROFILE="/profile",e))(d||{}),M=(e=>(e.NOT_FOUND="NotFound",e.UNAUTHORIZED="Unauthorized",e))(M||{});const we=(e,n,o=(...a)=>a)=>{if(!e)return o("",{});if(e.code)switch(e.code){case"NotFound":return o(e.code,{context:`${e.entity}:${n}`});case"Unauthorized":return o(e.code,{context:n});default:return o("Unknown",{context:n})}return o((e==null?void 0:e.message)??"Unknown",{context:n})},ve=({handleClose:e})=>{const[n,o]=m.useState(),{t:a}=b(),r=k(),i=Z({defaultValues:{email:"",password:""},onSubmit:async({value:s})=>{try{await c.logIn(s.email,s.password),r.invalidate(),e()}catch(u){o(u)}}});return t.jsx("form",{onSubmit:s=>{s.preventDefault(),s.stopPropagation(),i.handleSubmit()},onKeyDown:s=>{s.key==="Tab"&&s.stopPropagation()},noValidate:!0,children:t.jsxs(v,{sx:{display:"grid",gap:2,padding:1},children:[t.jsx(i.Field,{name:"email",validators:{onChange:({value:s})=>s?void 0:a("Email required"),onChangeAsyncDebounceMs:500,onChangeAsync:async({value:s})=>(await new Promise(u=>setTimeout(u,1e3)),s.includes("error")&&'No "error" allowed in email')},children:s=>t.jsx(t.Fragment,{children:t.jsx(L,{variant:"outlined",name:s.name,value:s.state.value,onBlur:s.handleBlur,onChange:u=>s.handleChange(u.target.value),size:"small",label:a("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"})})}),t.jsx(i.Field,{name:"password",validators:{onChange:({value:s})=>s?void 0:a("Password required"),onChangeAsyncDebounceMs:500,onChangeAsync:async({value:s})=>(await new Promise(u=>setTimeout(u,1e3)),s.includes("error")&&'No "error" allowed in password')},children:s=>t.jsx(t.Fragment,{children:t.jsx(L,{variant:"outlined",name:s.name,value:s.state.value,onBlur:s.handleBlur,onChange:u=>s.handleChange(u.target.value),size:"small",label:a("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"})})}),t.jsx(i.Subscribe,{selector:s=>[s.canSubmit,s.isSubmitting],children:([s])=>t.jsx(t.Fragment,{children:t.jsx(ie,{type:"submit",disabled:!s,variant:"contained",children:a("Log in")})})}),n&&t.jsx(l,{color:"error.main",children:we(n,"login",a)})]})})},Ce=({anchorEl:e,handleClose:n})=>{const o=J(),a=k(),r=c.getAuthenticatedUser();return t.jsx(D,{anchorEl:e,anchorOrigin:{vertical:"bottom",horizontal:"right"},keepMounted:!0,transformOrigin:{vertical:"top",horizontal:"right"},open:!!e,onClose:n,sx:{"& .MuiMenu-paper":{minWidth:"240px"}},children:r?[t.jsx(w,{onClick:()=>{o({to:d.PROFILE}),n()},children:y("Profile")},"profile"),t.jsx(w,{onClick:()=>{c.logOut(),a.invalidate(),n()},children:y("Log out")},"logout")]:t.jsx(ve,{handleClose:n})})},be=({children:e})=>{const n=he({disableHysteresis:!0,threshold:0});return m.cloneElement(e,{elevation:n?4:0})},Pe=()=>{const[e,n]=m.useState(null),[o,a]=m.useState(null),{t:r}=b(),i=Y({select:h=>h.status==="pending"}),s=c.getAuthenticatedUser(),u=()=>{a(null),n(null)};return t.jsx(be,{children:t.jsxs(t.Fragment,{children:[t.jsx(ue,{children:t.jsxs(R,{children:[t.jsxs(v,{sx:{flexGrow:1,alignItems:"center",display:"flex",gap:1},children:[t.jsx(j,{component:x,to:"/",color:"#FFF",variant:"h6",underline:"none",children:r("GuestBook")}),i&&t.jsx(ce,{size:16,thickness:10,sx:{color:"white"}})]}),t.jsx(A,{size:"large",onClick:h=>a(h.currentTarget),children:t.jsx(le,{sx:{color:"white"}})}),s?t.jsx(A,{onClick:h=>n(h.currentTarget),sx:{p:0},children:t.jsx(C,{alt:s.username,src:`storage/${s.image}`})}):t.jsx(A,{size:"large",onClick:h=>n(h.currentTarget),color:"inherit",children:t.jsx(de,{})}),t.jsx(ye,{anchorEl:o,handleClose:u}),t.jsx(Ce,{anchorEl:e,handleClose:u})]})}),t.jsx(R,{})]})})},Ae=()=>t.jsxs(t.Fragment,{children:[t.jsx(Pe,{}),t.jsx(ee,{}),!1]}),ke=({error:e})=>{const n=k(),o=te();return m.useEffect(()=>{o.reset()},[o]),"code"in e&&e.code===M.UNAUTHORIZED&&(c.logOut(),F({to:d.INDEX})),t.jsxs("div",{children:[e.message,t.jsx("button",{onClick:()=>{n.invalidate()},children:"retry"})]})},P=_()({component:Ae,errorComponent:ke}),N=e=>new Date(e.date).toLocaleString(navigator.languages[0]??"de-DE",{timeZone:e.timezone,day:"2-digit",month:"2-digit",year:"numeric",hour:"2-digit",hour12:!1,minute:"2-digit"}),Fe=({post:e})=>{var n;return t.jsxs(ge,{sx:{display:"flex",flexDirection:"column",flexGrow:1},children:[t.jsx(me,{avatar:"id"in e.user?t.jsx(j,{component:x,to:"/profile/$id",params:{id:e.user.id},color:"#FFF",variant:"h6",underline:"none",children:t.jsx(C,{alt:e.user.username,src:`storage/${e.user.image}`})}):t.jsx(C,{alt:e.user.username,src:`storage/${e.user.image}`}),title:"id"in e.user?e.user.id!==((n=c.getAuthenticatedUser())==null?void 0:n.id)?t.jsx(j,{component:x,to:"/profile/$id",params:{id:e.user.id},children:e.user.username}):t.jsx(j,{component:x,to:"/profile",children:e.user.username}):e.user.username,subheader:N(e.postedAt)}),t.jsx(pe,{children:t.jsx(l,{children:e.content})})]})},U=e=>E({queryKey:["posts",{page:e??0,hasAuth:c.hasAuth()}],queryFn:()=>c.posts(e)}),$e=()=>{const{page:e}=B.useSearch(),{data:n,isFetching:o}=I(U(e)),{t:a}=b();return t.jsxs(t.Fragment,{children:[t.jsx(O,{open:o,message:a("Updating")}),t.jsxs(g,{container:!0,spacing:2,children:[n.data.map(r=>t.jsx(g,{item:!0,xs:12,md:6,lg:4,sx:{display:"flex"},children:t.jsx(Fe,{post:r})},r.id)),t.jsx(g,{item:!0,xs:12,sx:{display:"flex",justifyContent:"center"},children:t.jsx(xe,{page:(e??0)+1,count:n.pages,color:"primary",renderItem:r=>t.jsx(fe,{...r,component:x,to:"/",search:{page:(r.page??0)>0?(r.page??1)-1:void 0},onClick:i=>r.onClick(i)})})})]})]})},B=$(d.INDEX)({loaderDeps:({search:{page:e}})=>({page:e}),loader:({context:{queryClient:e},deps:{page:n}})=>e.ensureQueryData(U(n)),validateSearch:e=>({page:(e==null?void 0:e.page)!==void 0?Number((e==null?void 0:e.page)??0):void 0}),component:$e}),Q=({user:e})=>{const{t:n}=b();return t.jsx(v,{children:t.jsxs(g,{container:!0,spacing:2,children:[t.jsxs(g,{item:!0,sx:{display:"grid",gridTemplateColumns:"fit-content(100%) 1fr",columnGap:2,rowGap:1},children:[t.jsx(v,{sx:{gridColumn:"1/3",display:"flex",justifyContent:"center"},children:t.jsx(C,{alt:e.username,src:`storage/${e.image}`,sx:{width:100,height:100}})}),t.jsxs(l,{fontWeight:"bold",children:[n("Username"),":"]}),t.jsx(l,{children:e.username}),t.jsxs(l,{fontWeight:"bold",children:[n("Member since"),":"]}),t.jsx(l,{children:N(e.memberSince)}),t.jsxs(l,{fontWeight:"bold",children:[n("Post count"),":"]}),t.jsx(l,{children:e.postCount})]}),t.jsx(g,{item:!0})]})})},q=E({queryKey:["profile"],queryFn:()=>c.user()}),Ee=()=>{const{data:e,isFetching:n}=I(q);return t.jsxs(t.Fragment,{children:[t.jsx(O,{open:n,message:y("Updating")}),t.jsx(Q,{user:e})]})},Ie=$(`${d.PROFILE}/`)({loader:({context:{queryClient:e}})=>e.ensureQueryData(q),beforeLoad:()=>{if(!c.hasAuth())throw F({to:d.INDEX})},component:Ee}),z=e=>E({queryKey:["profile",{id:e}],queryFn:()=>c.user(e)}),Oe=()=>{const{id:e}=G.useParams(),{data:n,isFetching:o}=I(z(e));return t.jsxs(t.Fragment,{children:[t.jsx(O,{open:o,message:y("Updating")}),t.jsx(Q,{user:n})]})},G=$(`${d.PROFILE}/$id`)({params:{parse:({id:e})=>({id:parseInt(e)}),stringify:({id:e})=>({id:e.toString()})},loader:({context:{queryClient:e},params:{id:n}})=>e.ensureQueryData(z(n)),beforeLoad:()=>{if(!c.hasAuth())throw F({to:d.INDEX})},component:Oe}),Le=B.update({path:"/",getParentRoute:()=>P}),Re=Ie.update({path:"/profile/",getParentRoute:()=>P}),Se=G.update({path:"/profile/$id",getParentRoute:()=>P}),Te=P.addChildren({IndexRoute:Le,ProfileIdRoute:Se,ProfileIndexRoute:Re}),H=new ne,De=se({routeTree:Te,context:{queryClient:H},defaultPreload:"intent",defaultPreloadStaleTime:0,basepath:"/phpCourse/exam"}),T=document.getElementById("root");T.innerHTML||V.createRoot(T).render(t.jsx(m.StrictMode,{children:t.jsxs(re,{client:H,children:[t.jsx(oe,{router:De}),t.jsx(ae,{initialIsOpen:!1})]})}));
|
|
//# sourceMappingURL=index-_R7ZZc23.js.map
|