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