April update

This commit is contained in:
mrfry 2022-03-30 12:15:39 +02:00
parent 4748c23769
commit ce63911b68
18 changed files with 1046 additions and 253 deletions

View file

@ -75,7 +75,7 @@
.commentAreaContainer > textarea { .commentAreaContainer > textarea {
width: 99%; width: 99%;
font-size: 18px; font-size: 12px;
} }
.commentAreaContainer > div { .commentAreaContainer > div {

View file

@ -3,11 +3,13 @@ import React, { useState } from 'react'
import Modal from './modal' import Modal from './modal'
import styles from './composer.module.css' import styles from './composer.module.css'
import constants from '../constants.json'
export default function Composer({ onSubmit }) { export default function Composer({ onSubmit, allowFile, fileOnly }) {
const [editorShowing, setEditorShowing] = useState(false) const [editorShowing, setEditorShowing] = useState(false)
const [val, setVal] = useState('') const [val, setVal] = useState('')
const [title, setTitle] = useState('') const [title, setTitle] = useState('')
const [file, setFile] = useState()
return ( return (
<> <>
@ -18,7 +20,7 @@ export default function Composer({ onSubmit }) {
}} }}
className={styles.new} className={styles.new}
> >
Bejegyzés írása... Új poszt ...
</div> </div>
</div> </div>
{editorShowing && ( {editorShowing && (
@ -37,27 +39,70 @@ export default function Composer({ onSubmit }) {
setTitle(e.target.value) setTitle(e.target.value)
}} }}
/> />
<textarea {!fileOnly && (
placeholder={'Írj ide valamit...'} <textarea
required placeholder={'Írj ide valamit...'}
value={val} required
onChange={(e) => { value={val}
setVal(e.target.value) onChange={(e) => {
}} setVal(e.target.value)
/> }}
/>
)}
{(allowFile || fileOnly) && (
<input
className={styles.fileInput}
type="file"
name="file"
accept={`${constants.imageExts
.map((x) => `.${x}`)
.join(',')},${constants.videoExts
.map((x) => `.${x}`)
.join(',')}`}
onChange={(e) => {
const selectedFile = e.target.files[0]
setFile(selectedFile)
if (!title) {
setTitle(
selectedFile.name.split('.').slice(0, -1).join('.')
)
}
}}
/>
)}
<div className={`actions ${styles.composerAction}`}> <div className={`actions ${styles.composerAction}`}>
<span <span
onClick={() => { onClick={() => {
if (!title) { if (!title) {
alert('Üres a tartalom!')
return
}
if (!val) {
alert('Üres a téma!') alert('Üres a téma!')
return return
} }
if (!val && !fileOnly) {
alert('Üres a tartalom!')
return
}
if (fileOnly && !file) {
alert('Kérlek tölts fel egy fájlt!')
return
}
onSubmit(title, val) const ext = file.name.split('.').reverse()[0]
if (
!constants.imageExts.includes(ext.toLowerCase()) &&
!constants.videoExts.includes(ext.toLowerCase())
) {
alert(
`Kérlek helyes formátum fájlt tölts fel! (${constants.imageExts.join(
', '
)}, ${constants.videoExts.join(', ')})`
)
return
}
onSubmit(title, val, file)
setTitle('')
setVal('')
setFile(undefined)
setEditorShowing(false) setEditorShowing(false)
}} }}
> >

View file

@ -189,6 +189,8 @@ function UserStatus({ userId, unreads, onClick }) {
className={styles.logout} className={styles.logout}
title="Kijelentkezés" title="Kijelentkezés"
onClick={() => { onClick={() => {
const res = window.confirm('Kijelentkezel?')
if (!res) return
fetch(constants.apiUrl + 'logout', { fetch(constants.apiUrl + 'logout', {
method: 'GET', method: 'GET',
credentials: 'include', credentials: 'include',

View file

@ -10,9 +10,9 @@
.modalContent { .modalContent {
display: flex; display: flex;
max-height: 80%; max-height: 90%;
height: auto; height: auto;
width: 50%; width: 60%;
position: fixed; position: fixed;
background: var(--background-color); background: var(--background-color);
top: 50%; top: 50%;

View file

@ -4,8 +4,56 @@ import ReactButton from './reactButton.js'
import Comments from './comments.js' import Comments from './comments.js'
import Link from 'next/link' import Link from 'next/link'
import constants from '../constants.json'
import styles from './newsEntry.module.css' import styles from './newsEntry.module.css'
const Media = ({ url, onClick }) => {
const ext = url.split('.').reverse()[0]
if (constants.imageExts.includes(ext.toLowerCase())) {
return (
<img
style={{ cursor: 'pointer' }}
onClick={() => {
if (onClick) onClick()
}}
src={url}
/>
)
} else if (constants.videoExts.includes(ext.toLowerCase())) {
return (
<video controls style={{ maxHeight: '700px' }}>
<source src={url} type={`video/${ext === 'mkv' ? 'mp4' : ext}`} />
</video>
)
} else {
return <div>Invalid media: {ext} :/</div>
}
}
const Content = ({ admin, content, mediaPath, onMediaClick }) => {
return (
<>
{mediaPath && (
<div className={styles.mediaContainer}>
<Media
onClick={onMediaClick}
url={`${constants.apiUrl}forumFiles/${mediaPath}`}
/>
</div>
)}
{admin ? (
<div
className={styles.newsBody}
dangerouslySetInnerHTML={{ __html: content }}
/>
) : (
<div className={styles.newsBody}>{content}</div>
)}
</>
)
}
export default function NewsEntry({ export default function NewsEntry({
newsItem, newsItem,
uid, uid,
@ -14,21 +62,35 @@ export default function NewsEntry({
onComment, onComment,
onDelete, onDelete,
onPostDelete, onPostDelete,
showUpDownVote,
hideAdminIndicator,
onTitleClick,
}) { }) {
const { reacts, title, content, user, comments, date, admin } = newsItem const { reacts, title, content, user, comments, date, admin, mediaPath } =
newsItem
const dateObj = new Date(date) const dateObj = new Date(date)
const isPostAdmin = !hideAdminIndicator && admin
return ( return (
<div className={styles.newsRoot}> <div className={styles.newsRoot}>
<div <div
className={`${styles.newsContainer} ${admin && styles.adminPost} ${ className={`${styles.newsContainer} ${
!admin && styles.userPost isPostAdmin && styles.adminPost
} ${uid === user && styles.ownPost} ${ } ${!isPostAdmin && styles.userPost} ${
uid === user && admin && styles.adminPost uid === user && styles.ownPost
}`} } ${uid === user && isPostAdmin && styles.adminPost}`}
> >
<div className={styles.newsHeader}> <div className={styles.newsHeader}>
<div className={styles.newsTitle}>{title}</div> <div
onClick={() => {
if (onTitleClick) onTitleClick()
}}
style={{ cursor: onTitleClick ? 'pointer' : 'default' }}
className={styles.newsTitle}
>
{title}
</div>
<div className={styles.userinfo}> <div className={styles.userinfo}>
<Link href={`/chat?user=${user}`}> <Link href={`/chat?user=${user}`}>
<a title={`Chat #${user}-el`} className={'userId'}> <a title={`Chat #${user}-el`} className={'userId'}>
@ -43,14 +105,12 @@ export default function NewsEntry({
</div> </div>
</div> </div>
</div> </div>
{admin ? ( <Content
<div onMediaClick={onTitleClick}
className={styles.newsBody} admin={admin}
dangerouslySetInnerHTML={{ __html: content }} content={content}
/> mediaPath={mediaPath}
) : ( />
<div className={styles.newsBody}>{content}</div>
)}
</div> </div>
<div className={'actions'}> <div className={'actions'}>
<Comments <Comments
@ -72,6 +132,7 @@ export default function NewsEntry({
</span> </span>
) : null} ) : null}
<ReactButton <ReactButton
showUpDownVote={showUpDownVote}
existingReacts={reacts} existingReacts={reacts}
uid={uid} uid={uid}
onClick={(reaction, isDelete) => { onClick={(reaction, isDelete) => {

View file

@ -39,12 +39,6 @@
border-left: 4px dotted azure; border-left: 4px dotted azure;
} }
.newsContainer img {
max-width: 100%;
min-width: 200px;
border: 2px solid white;
}
.newsHeader { .newsHeader {
display: flex; display: flex;
justify-content: space-between; justify-content: space-between;
@ -88,3 +82,17 @@
padding: 10px 2px; padding: 10px 2px;
} }
} }
.mediaContainer {
display: flex;
justify-content: center;
}
.newsContainer img {
max-height: 700px;
}
.newsContainer video {
max-width: 500px;
object-fit: fill;
}

View file

@ -5,6 +5,8 @@ import Tooltip from './tooltip.js'
import styles from './reactButton.module.css' import styles from './reactButton.module.css'
import reactions from '../data/reactions.json' import reactions from '../data/reactions.json'
const upDownVoteKeys = { 'thumbs up': [-1], 'thumbs down': [-1] }
function useOutsideAlerter(ref, action) { function useOutsideAlerter(ref, action) {
useEffect(() => { useEffect(() => {
function handleClickOutside(event) { function handleClickOutside(event) {
@ -20,12 +22,24 @@ function useOutsideAlerter(ref, action) {
}, [ref]) }, [ref])
} }
function ExistingReacts({ existingReacts, onClick, uid }) { function mergeEmptyUpDownVoteObjWithExisting(existingReacts) {
if (!existingReacts) return upDownVoteKeys
return Object.keys(existingReacts).reduce((acc, reactKey) => {
return { ...acc, [reactKey]: existingReacts[reactKey] }
}, upDownVoteKeys)
}
function ExistingReacts({ existingReacts, onClick, uid, showUpDownVote }) {
const mergedReactions = showUpDownVote
? mergeEmptyUpDownVoteObjWithExisting(existingReacts)
: existingReacts
return ( return (
<> <>
{existingReacts && {mergedReactions &&
Object.keys(existingReacts).map((key) => { Object.keys(mergedReactions).map((key) => {
const currReact = existingReacts[key] const currReact = mergedReactions[key]
const react = reactions[key] const react = reactions[key]
if (!react) { if (!react) {
return null return null
@ -40,7 +54,7 @@ function ExistingReacts({ existingReacts, onClick, uid }) {
onClick(key, currReact.includes(uid)) onClick(key, currReact.includes(uid))
}} }}
> >
{react.emoji} {currReact.length} {react.emoji} {currReact[0] === -1 ? 0 : currReact.length}
</span> </span>
) )
})} })}
@ -54,6 +68,7 @@ function RenderEmojis({ onClick }) {
return ( return (
<> <>
<input <input
autoFocus
type="text" type="text"
placeholder="Keresés..." placeholder="Keresés..."
onChange={(event) => { onChange={(event) => {
@ -81,7 +96,12 @@ function RenderEmojis({ onClick }) {
) )
} }
export default function ReactButton({ onClick, existingReacts, uid }) { export default function ReactButton({
onClick,
existingReacts,
uid,
showUpDownVote,
}) {
const [opened, setOpened] = useState(false) const [opened, setOpened] = useState(false)
const wrapperRef = useRef(null) const wrapperRef = useRef(null)
useOutsideAlerter(wrapperRef, () => { useOutsideAlerter(wrapperRef, () => {
@ -91,8 +111,8 @@ export default function ReactButton({ onClick, existingReacts, uid }) {
return ( return (
<> <>
<Tooltip <Tooltip
width={300} width={300}
height={250} height={250}
text={() => { text={() => {
return ( return (
<span <span
@ -116,6 +136,7 @@ export default function ReactButton({ onClick, existingReacts, uid }) {
</div> </div>
</Tooltip> </Tooltip>
<ExistingReacts <ExistingReacts
showUpDownVote={showUpDownVote}
uid={uid} uid={uid}
onClick={(key, isDelete) => { onClick={(key, isDelete) => {
onClick(key, isDelete) onClick(key, isDelete)

View file

@ -2,5 +2,7 @@
"siteUrl": "https://qmining.frylabs.net/", "siteUrl": "https://qmining.frylabs.net/",
"apiUrl": "https://api.frylabs.net/", "apiUrl": "https://api.frylabs.net/",
"mobileWindowWidth": 700, "mobileWindowWidth": 700,
"maxQuestionsToRender": 250 "maxQuestionsToRender": 250,
"imageExts" : ["gif", "png", "jpeg", "jpg"],
"videoExts" : ["mp4", "mkv", "webm"]
} }

View file

@ -1,7 +1,11 @@
{ {
"index": { "index": {
"href": "/", "href": "/",
"text": "Főoldal" "text": "Memes"
},
"main": {
"href": "/main",
"text": "(Fő)oldal"
}, },
"script": { "script": {
"href": "/script", "href": "/script",

View file

@ -7,7 +7,14 @@ import Layout from '../components/layout'
import '../defaultStyles.css' import '../defaultStyles.css'
import constants from '../constants.json' import constants from '../constants.json'
const queryClient = new QueryClient() const queryClient = new QueryClient({
defaultOptions: {
queries: {
staleTime: Infinity,
refetchOnWindowFocus: 'always',
},
},
})
const getGlobalProps = () => { const getGlobalProps = () => {
return new Promise((resolve) => { return new Promise((resolve) => {

View file

@ -357,7 +357,10 @@ export default function AllQuestions({ router, globalState, setGlobalState }) {
)} )}
</> </>
) : fetchingData ? ( ) : fetchingData ? (
<LoadingIndicator /> <div>
Kérdések betöltése, nagy adatbázisoknál ez sokáig tarthat ...
<LoadingIndicator />
</div>
) : null} ) : null}
</div> </div>
) )

View file

@ -12,12 +12,6 @@ const byDate = (a, b) => {
return a.date - b.date return a.date - b.date
} }
function countAllMessages(msgs) {
return Object.keys(msgs).reduce((acc, key) => {
return acc + msgs[key].length
}, 0)
}
function groupPrevMessages(msgs, currUser) { function groupPrevMessages(msgs, currUser) {
return msgs.reduce((acc, msg) => { return msgs.reduce((acc, msg) => {
const group = const group =
@ -152,7 +146,6 @@ export default class Chat extends React.Component {
} }
if ( if (
prevState.selectedUser &&
prevState.msgs && prevState.msgs &&
prevState.msgs[prevState.selectedUser] && prevState.msgs[prevState.selectedUser] &&
this.state.msgs && this.state.msgs &&
@ -164,6 +157,9 @@ export default class Chat extends React.Component {
if (prevLatest && newLatest && prevLatest.date !== newLatest.date) { if (prevLatest && newLatest && prevLatest.date !== newLatest.date) {
this.scrollToChatBottom() this.scrollToChatBottom()
} }
if (prevState.msgs[prevState.selectedUser].msgs.length === 1) {
this.scrollToChatBottom()
}
} }
} }

View file

@ -1,4 +1,5 @@
import React, { useState, useEffect } from 'react' import React, { useState, useEffect } from 'react'
import { useQuery } from 'react-query'
import fetch from 'unfetch' import fetch from 'unfetch'
import Head from 'next/head' import Head from 'next/head'
@ -6,12 +7,85 @@ import LoadingIndicator from '../components/LoadingIndicator'
import Sleep from '../components/sleep' import Sleep from '../components/sleep'
import NewsEntry from '../components/newsEntry' import NewsEntry from '../components/newsEntry'
import Composer from '../components/composer' import Composer from '../components/composer'
import Modal from '../components/modal'
import styles from './index.module.css' import styles from './index.module.css'
import constants from '../constants.json' import constants from '../constants.json'
const forumPostPerPage = 5 const forumPostPerPage = 5
const frontpageForumName = 'frontpage' const frontpageForumName = 'memes'
const LeaderBoard = ({ leaderBoard, userId }) => {
if (!leaderBoard) return <LoadingIndicator />
return (
<div className={styles.msg}>
<div style={{ padding: 8 }}>Ranglista</div>
<div className={styles.leaderBoard}>
<div></div>
<div>User #</div>
<div>Up</div>
<div>Down</div>
<div>Sum</div>
</div>
{leaderBoard &&
leaderBoard.map((x, i) => {
if (i > 9) return null
const { up, down, user, sum } = x
return (
<div
className={`${styles.leaderBoard} ${
userId === parseInt(user) && styles.selfRow
}`}
key={user}
>
<div>{`${i + 1}.`}</div>
<div>#{user}</div>
<div>{up}</div>
<div>{down}</div>
<div>{sum}</div>
</div>
)
})}
</div>
)
}
const Header = ({ leaderBoard, userId }) => {
return (
<div className={styles.header}>
<div className={styles.msg}>
Mivel mostanában elég népszerű lett az oldal, ezért egy új rész lett
hozzáadva: Memes
<p /> Ide lehet posztolni akármilyen vicces tartalmat, és upvoteolni /
downvoteolni lehet a többiek által feltöltötteket
<p />
Have fun! :)
</div>
<LeaderBoard leaderBoard={leaderBoard} userId={userId} />
</div>
)
}
function fetchLeaderboard() {
const { data } = useQuery('leaderBoard', () => {
return new Promise((resolve) => {
fetch(`${constants.apiUrl}forumRanklist?forumName=memes`, {
credentials: 'include',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
})
.then((res) => {
return res.json()
})
.then((res) => {
resolve(res)
})
})
})
return data || []
}
function fetchForum(from) { function fetchForum(from) {
return new Promise((resolve) => { return new Promise((resolve) => {
@ -34,7 +108,7 @@ function fetchForum(from) {
}) })
} }
function addPost(title, content) { function addPost(title, content, file) {
return new Promise((resolve) => { return new Promise((resolve) => {
fetch(constants.apiUrl + 'addPost', { fetch(constants.apiUrl + 'addPost', {
method: 'POST', method: 'POST',
@ -47,13 +121,27 @@ function addPost(title, content) {
forumName: frontpageForumName, forumName: frontpageForumName,
title: title, title: title,
content: content, content: content,
image: file.name,
}), }),
}) })
.then((res) => { .then((res) => {
return res.json() return res.json()
}) })
.then((res) => { .then((res) => {
resolve(res) const formData = new FormData() // eslint-disable-line
formData.append('file', file)
fetch(constants.apiUrl + 'postMeme', {
method: 'POST',
credentials: 'include',
headers: {
Accept: 'application/json',
},
body: formData,
}).then((imgPostRes) => {
console.info(imgPostRes)
resolve(res)
})
}) })
}) })
} }
@ -76,16 +164,185 @@ function updateForumPost(forum, postKey, postData) {
}, {}) }, {})
} }
export default function Index({ globalData, globalState, setGlobalState }) { const NewsEntryContainer = ({
postKey,
setNews,
news,
userId,
newsEntryData,
onTitleClick,
}) => {
return (
<NewsEntry
showUpDownVote
onTitleClick={onTitleClick}
onPostDelete={() => {
fetch(constants.apiUrl + 'rmPost', {
method: 'POST',
credentials: 'include',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
forumName: frontpageForumName,
postKey: postKey,
}),
})
.then((res) => {
return res.json()
})
.then((res) => {
const { success, msg } = res
if (success) {
setNews(
Object.keys(news).reduce((acc, key) => {
const entry = news[key]
if (key !== postKey) {
acc = {
...acc,
[key]: entry,
}
}
return acc
}, {})
)
} else {
alert(msg)
}
})
}}
onNewsReact={({ reaction, isDelete }) => {
fetch(constants.apiUrl + 'react', {
method: 'POST',
credentials: 'include',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
reaction: reaction,
postKey: postKey,
isDelete: isDelete,
forumName: frontpageForumName,
}),
})
.then((res) => {
return res.json()
})
.then((res) => {
setNews(updateForumPost(news, postKey, res.postData))
})
}}
onCommentReact={({ path, reaction, isDelete }) => {
fetch(constants.apiUrl + 'react', {
method: 'POST',
credentials: 'include',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
type: 'reaction',
postKey: postKey,
path: path,
reaction: reaction,
isDelete: isDelete,
forumName: frontpageForumName,
}),
})
.then((res) => {
return res.json()
})
.then((res) => {
const { success, postData, msg } = res
if (success) {
setNews(updateForumPost(news, postKey, postData))
} else {
alert(msg)
}
})
}}
onDelete={(path) => {
fetch(constants.apiUrl + 'comment', {
method: 'POST',
credentials: 'include',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
type: 'delete',
path: path,
postKey: postKey,
forumName: frontpageForumName,
}),
})
.then((res) => {
return res.json()
})
.then((res) => {
const { success, postData, msg } = res
if (success) {
setNews(updateForumPost(news, postKey, postData))
} else {
alert(msg)
}
})
}}
onComment={(path, content) => {
fetch(constants.apiUrl + 'comment', {
method: 'POST',
credentials: 'include',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
type: 'add',
path: path,
content: content,
postKey: postKey,
forumName: frontpageForumName,
}),
})
.then((res) => {
return res.json()
})
.then((res) => {
const { success, postData, msg } = res
if (success) {
setNews(updateForumPost(news, postKey, postData))
} else {
alert(msg)
}
})
}}
uid={userId}
key={postKey}
newsKey={postKey}
newsItem={newsEntryData}
/>
)
}
export default function Memes({
router,
globalData,
globalState,
setGlobalState,
}) {
const userId = globalData.userId const userId = globalData.userId
const motd = globalData.motd
const [news, setNews] = useState(null) const [news, setNews] = useState(null)
const [nextEntryKey, setNextEntryKey] = useState() const [nextEntryKey, setNextEntryKey] = useState()
const [fetchingForum, setFetchingForum] = useState(false) const [fetchingForum, setFetchingForum] = useState(false)
const [postInModalKey, setPostInModalKey] = useState()
const [isUploading, setIsUploading] = useState(false)
const { leaderBoard } = fetchLeaderboard()
useEffect(() => { useEffect(() => {
if (globalState.news) { if (globalState.memes) {
const { entries, nextKey } = globalState.news const { entries, nextKey } = globalState.memes
setNextEntryKey(nextKey) setNextEntryKey(nextKey)
setNews(entries) setNews(entries)
} else { } else {
@ -95,185 +352,78 @@ export default function Index({ globalData, globalState, setGlobalState }) {
const { entries, nextKey } = res const { entries, nextKey } = res
setNextEntryKey(nextKey) setNextEntryKey(nextKey)
setNews(entries) setNews(entries)
setGlobalState({ news: res }) setGlobalState({ memes: res })
}) })
} }
}, []) }, [])
useEffect(() => {
const postKey = router.query.postKey
? decodeURIComponent(router.query.postKey)
: ''
if (postKey) {
setPostInModalKey(postKey)
}
}, [router.query.postKey])
const renderNews = () => { const renderNews = () => {
if (news) { if (news) {
let newsItems = Object.keys(news).map((postKey) => { let newsItems = Object.keys(news).map((postKey) => {
let newsEntryData = news[postKey] let newsEntryData = news[postKey]
return ( return (
<NewsEntry <NewsEntryContainer
onPostDelete={() => { onTitleClick={() => {
fetch(constants.apiUrl + 'rmPost', { setPostInModalKey(postKey)
method: 'POST', router.push(
credentials: 'include', `${router.pathname}?postKey=${encodeURIComponent(postKey)}`,
headers: { undefined,
Accept: 'application/json', { shallow: true }
'Content-Type': 'application/json', )
},
body: JSON.stringify({
forumName: frontpageForumName,
postKey: postKey,
}),
})
.then((res) => {
return res.json()
})
.then((res) => {
const { success, msg } = res
if (success) {
setNews(
Object.keys(news).reduce((acc, key) => {
const entry = news[key]
if (key !== postKey) {
acc = {
...acc,
[key]: entry,
}
}
return acc
}, {})
)
} else {
alert(msg)
}
})
}} }}
onNewsReact={({ reaction, isDelete }) => {
fetch(constants.apiUrl + 'react', {
method: 'POST',
credentials: 'include',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
reaction: reaction,
postKey: postKey,
isDelete: isDelete,
forumName: frontpageForumName,
}),
})
.then((res) => {
return res.json()
})
.then((res) => {
setNews(updateForumPost(news, postKey, res.postData))
})
}}
onCommentReact={({ path, reaction, isDelete }) => {
fetch(constants.apiUrl + 'react', {
method: 'POST',
credentials: 'include',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
type: 'reaction',
postKey: postKey,
path: path,
reaction: reaction,
isDelete: isDelete,
forumName: frontpageForumName,
}),
})
.then((res) => {
return res.json()
})
.then((res) => {
const { success, postData, msg } = res
if (success) {
setNews(updateForumPost(news, postKey, postData))
} else {
alert(msg)
}
})
}}
onDelete={(path) => {
fetch(constants.apiUrl + 'comment', {
method: 'POST',
credentials: 'include',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
type: 'delete',
path: path,
postKey: postKey,
forumName: frontpageForumName,
}),
})
.then((res) => {
return res.json()
})
.then((res) => {
const { success, postData, msg } = res
if (success) {
setNews(updateForumPost(news, postKey, postData))
} else {
alert(msg)
}
})
}}
onComment={(path, content) => {
fetch(constants.apiUrl + 'comment', {
method: 'POST',
credentials: 'include',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
type: 'add',
path: path,
content: content,
postKey: postKey,
forumName: frontpageForumName,
}),
})
.then((res) => {
return res.json()
})
.then((res) => {
const { success, postData, msg } = res
if (success) {
setNews(updateForumPost(news, postKey, postData))
} else {
alert(msg)
}
})
}}
uid={userId}
key={postKey} key={postKey}
newsKey={postKey} postKey={postKey}
newsItem={newsEntryData} setNews={setNews}
news={news}
userId={userId}
newsEntryData={newsEntryData}
/> />
) )
}) })
return ( return (
<div> <div>
<div className={styles.title}>Fórum/Hírek</div>
<hr />
<Composer <Composer
onSubmit={(title, content) => { allowFile
addPost(title, content).then((res) => { fileOnly
onSubmit={(title, content, file) => {
if (!file) return
setIsUploading(true)
addPost(title, content, file).then((res) => {
const { success, newPostKey, newEntry, msg } = res const { success, newPostKey, newEntry, msg } = res
if (success) { if (success) {
setNews({ [newPostKey]: newEntry, ...news }) setNews({ [newPostKey]: newEntry, ...news })
} else { } else {
alert(msg) alert(msg)
} }
setIsUploading(false)
}) })
}} }}
/> />
{isUploading && (
<div
style={{
display: 'flex',
alignItems: 'center',
flexDirection: 'column',
}}
>
{'Feltöltés ...'}
<LoadingIndicator />
</div>
)}
<div>{newsItems}</div> <div>{newsItems}</div>
{nextEntryKey && ( {nextEntryKey ? (
<div <div
className={styles.loadMoreButton} className={styles.loadMoreButton}
onClick={() => { onClick={() => {
@ -303,6 +453,17 @@ export default function Index({ globalData, globalState, setGlobalState }) {
'Több bejegyzés betöltése' 'Több bejegyzés betöltése'
)} )}
</div> </div>
) : (
<div
style={{
padding: 16,
display: 'flex',
justifyContent: 'center',
fontStyle: 'italic',
}}
>
{'The end'}
</div>
)} )}
</div> </div>
) )
@ -311,31 +472,39 @@ export default function Index({ globalData, globalState, setGlobalState }) {
} }
} }
const renderMotd = () => {
if (motd) {
return (
<div className={styles.motd}>
<div className={styles.title}>MOTD</div>
{motd ? (
<div dangerouslySetInnerHTML={{ __html: motd }} />
) : (
<div>...</div>
)}
</div>
)
} else {
return null
}
}
return ( return (
<div> <div>
<Head> <Head>
<title>Qmining | Frylabs.net</title> <title>Qmining | Frylabs.net</title>
</Head> </Head>
{renderMotd()} <Header leaderBoard={leaderBoard} userId={userId} />
<div className={styles.description}>
{
'A "Memes" rész Április 8-ig lesz elérhető, vagy ha népszerű lesz, akkor véglegesen bekerülhet a menübe.'
}
</div>
<Sleep /> <Sleep />
{renderNews()} {renderNews()}
{postInModalKey && (
<Modal
closeClick={() => {
setPostInModalKey(undefined)
router.back({ shallow: true })
}}
>
{news ? (
<NewsEntryContainer
postKey={postInModalKey}
setNews={setNews}
news={news}
userId={userId}
newsEntryData={news[postInModalKey]}
/>
) : (
<LoadingIndicator />
)}
</Modal>
)}
</div> </div>
) )
} }

View file

@ -2,7 +2,7 @@
width: 100%; width: 100%;
} }
.motd { .msg {
text-align: center; text-align: center;
font-size: 20px; font-size: 20px;
@ -12,7 +12,6 @@
padding-left: 5px; padding-left: 5px;
padding-right: 5px; padding-right: 5px;
margin-top: 18px; margin-top: 18px;
margin-bottom: 30px;
margin-left: 5px; margin-left: 5px;
margin-right: 5px; margin-right: 5px;
} }
@ -95,3 +94,41 @@
.loadMoreButton:hover { .loadMoreButton:hover {
background-color: var(--hoover-color); background-color: var(--hoover-color);
} }
.header {
display: flex;
}
.header > * {
flex: 1;
}
.leaderBoard {
font-size: 16px;
padding: 2px;
display: flex;
justify-content: space-around;
}
.leaderBoard > div:first-child {
flex: 1;
}
.leaderBoard > div {
flex: 2;
}
.leaderBoard:hover {
background-color: var(--hoover-color);
}
.selfRow {
color: var(--text-color);
}
.description {
font-size: 12px;
padding: 4px;
display: flex;
justify-content: center;
}

353
src/pages/main.js Normal file
View file

@ -0,0 +1,353 @@
import React, { useState, useEffect } from 'react'
import fetch from 'unfetch'
import Head from 'next/head'
import LoadingIndicator from '../components/LoadingIndicator'
import Sleep from '../components/sleep'
import NewsEntry from '../components/newsEntry'
import Composer from '../components/composer'
import styles from './main.module.css'
import constants from '../constants.json'
const forumPostPerPage = 5
const frontpageForumName = 'frontpage'
function fetchForum(from) {
return new Promise((resolve) => {
fetch(
`${
constants.apiUrl
}forumEntries?forumName=${frontpageForumName}&getContent=true${
from ? `&from=${from}` : ''
}&count=${forumPostPerPage}`,
{
credentials: 'include',
}
)
.then((resp) => {
return resp.json()
})
.then((res) => {
resolve(res)
})
})
}
function addPost(title, content) {
return new Promise((resolve) => {
fetch(constants.apiUrl + 'addPost', {
method: 'POST',
credentials: 'include',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
forumName: frontpageForumName,
title: title,
content: content,
}),
})
.then((res) => {
return res.json()
})
.then((res) => {
resolve(res)
})
})
}
function updateForumPost(forum, postKey, postData) {
return Object.keys(forum).reduce((acc, key) => {
const entry = forum[key]
if (key === postKey) {
acc = {
...acc,
[key]: postData,
}
} else {
acc = {
...acc,
[key]: entry,
}
}
return acc
}, {})
}
export default function Main({ globalData, globalState, setGlobalState }) {
const userId = globalData.userId
const motd = globalData.motd
const [news, setNews] = useState(null)
const [nextEntryKey, setNextEntryKey] = useState()
const [fetchingForum, setFetchingForum] = useState(false)
useEffect(() => {
if (globalState.news) {
const { entries, nextKey } = globalState.news
setNextEntryKey(nextKey)
setNews(entries)
} else {
setFetchingForum(true)
fetchForum().then((res) => {
setFetchingForum(false)
const { entries, nextKey } = res
setNextEntryKey(nextKey)
setNews(entries)
setGlobalState({ news: res })
})
}
}, [])
const renderNews = () => {
if (news) {
let newsItems = Object.keys(news).map((postKey) => {
let newsEntryData = news[postKey]
return (
<NewsEntry
hideAdminIndicator
onPostDelete={() => {
fetch(constants.apiUrl + 'rmPost', {
method: 'POST',
credentials: 'include',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
forumName: frontpageForumName,
postKey: postKey,
}),
})
.then((res) => {
return res.json()
})
.then((res) => {
const { success, msg } = res
if (success) {
setNews(
Object.keys(news).reduce((acc, key) => {
const entry = news[key]
if (key !== postKey) {
acc = {
...acc,
[key]: entry,
}
}
return acc
}, {})
)
} else {
alert(msg)
}
})
}}
onNewsReact={({ reaction, isDelete }) => {
fetch(constants.apiUrl + 'react', {
method: 'POST',
credentials: 'include',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
reaction: reaction,
postKey: postKey,
isDelete: isDelete,
forumName: frontpageForumName,
}),
})
.then((res) => {
return res.json()
})
.then((res) => {
setNews(updateForumPost(news, postKey, res.postData))
})
}}
onCommentReact={({ path, reaction, isDelete }) => {
fetch(constants.apiUrl + 'react', {
method: 'POST',
credentials: 'include',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
type: 'reaction',
postKey: postKey,
path: path,
reaction: reaction,
isDelete: isDelete,
forumName: frontpageForumName,
}),
})
.then((res) => {
return res.json()
})
.then((res) => {
const { success, postData, msg } = res
if (success) {
setNews(updateForumPost(news, postKey, postData))
} else {
alert(msg)
}
})
}}
onDelete={(path) => {
fetch(constants.apiUrl + 'comment', {
method: 'POST',
credentials: 'include',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
type: 'delete',
path: path,
postKey: postKey,
forumName: frontpageForumName,
}),
})
.then((res) => {
return res.json()
})
.then((res) => {
const { success, postData, msg } = res
if (success) {
setNews(updateForumPost(news, postKey, postData))
} else {
alert(msg)
}
})
}}
onComment={(path, content) => {
fetch(constants.apiUrl + 'comment', {
method: 'POST',
credentials: 'include',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
type: 'add',
path: path,
content: content,
postKey: postKey,
forumName: frontpageForumName,
}),
})
.then((res) => {
return res.json()
})
.then((res) => {
const { success, postData, msg } = res
if (success) {
setNews(updateForumPost(news, postKey, postData))
} else {
alert(msg)
}
})
}}
uid={userId}
key={postKey}
newsKey={postKey}
newsItem={newsEntryData}
/>
)
})
return (
<div>
<div className={styles.title}>Fórum/Hírek</div>
<hr />
<Composer
onSubmit={(title, content) => {
addPost(title, content).then((res) => {
const { success, newPostKey, newEntry, msg } = res
if (success) {
setNews({ [newPostKey]: newEntry, ...news })
} else {
alert(msg)
}
})
}}
/>
<div>{newsItems}</div>
{nextEntryKey ? (
<div
className={styles.loadMoreButton}
onClick={() => {
if (fetchingForum) {
return
}
setFetchingForum(true)
fetchForum(nextEntryKey).then((res) => {
setFetchingForum(false)
const { entries, nextKey } = res
setNextEntryKey(nextKey)
setNews({ ...news, ...entries })
setGlobalState({
news: {
entries: { ...news, ...entries },
nextKey: nextKey,
},
})
})
}}
>
{fetchingForum ? (
<LoadingIndicator />
) : (
'Több bejegyzés betöltése'
)}
</div>
) : (
<div
style={{
padding: 16,
display: 'flex',
justifyContent: 'center',
fontStyle: 'italic',
}}
>
{'The end'}
</div>
)}
</div>
)
} else {
return <LoadingIndicator />
}
}
const renderMotd = () => {
if (motd) {
return (
<div className={styles.motd}>
<div className={styles.title}>MOTD</div>
{motd ? (
<div dangerouslySetInnerHTML={{ __html: motd }} />
) : (
<div>...</div>
)}
</div>
)
} else {
return null
}
}
return (
<div>
<Head>
<title>Qmining | Frylabs.net</title>
</Head>
{renderMotd()}
<Sleep />
{renderNews()}
</div>
)
}

97
src/pages/main.module.css Normal file
View file

@ -0,0 +1,97 @@
.hr {
width: 100%;
}
.motd {
text-align: center;
font-size: 20px;
border: 2px dashed var(--text-color);
padding-top: 13px;
padding-bottom: 15px;
padding-left: 5px;
padding-right: 5px;
margin-top: 18px;
margin-bottom: 30px;
margin-left: 5px;
margin-right: 5px;
}
.itemContainer {
width: 100%;
margin: 20px 5px;
background-color: var(--hoover-color);
}
.newsBody {
margin: 0px 5px;
padding: 10px 14px;
font-size: 17px;
color: #fff;
text-align: justify;
}
.title {
color: var(--text-color);
font-size: 32px;
text-align: center;
letter-spacing: 2.5px;
}
.subtitle {
color: var(--text-color);
font-size: 20px;
text-align: center;
}
.newsTitle {
color: var(--text-color);
font-size: 28px;
padding-left: 17px;
}
.question {
font-weight: bold;
font-size: 16px;
color: #fff;
margin: 0px 5px;
}
.answer {
margin: 0px 5px;
}
.itemNumber {
color: #a7a7a7;
margin: 0px 5px;
font-size: 22px;
padding-top: 12px;
padding-left: 13px;
padding-bottom: 3px;
}
.repos {
display: flex;
flex-direction: column;
}
.loadMoreButton {
display: flex;
justify-content: center;
align-items: center;
background-color: var(--dark-color);
margin-left: 8px;
margin-right: 8px;
margin-bottom: 16px;
margin-top: 16px;
padding: 10px;
height: 50px;
cursor: pointer;
}
.loadMoreButton:hover {
background-color: var(--hoover-color);
}

View file

@ -93,7 +93,6 @@ export default function RankList({ globalData, globalState, setGlobalState }) {
const [ownEntryOnTop, setOwnEntryOnTop] = useState(false) const [ownEntryOnTop, setOwnEntryOnTop] = useState(false)
const getList = () => { const getList = () => {
console.log(globalState)
setSum() setSum()
setRanklist(null) setRanklist(null)
if (globalState[`rankilst_${since}`]) { if (globalState[`rankilst_${since}`]) {
@ -106,7 +105,6 @@ export default function RankList({ globalData, globalState, setGlobalState }) {
} else { } else {
getListFromServer(since) getListFromServer(since)
.then((data) => { .then((data) => {
console.log(since)
const { list, sum, selfuserId } = data const { list, sum, selfuserId } = data
setRanklist(list || []) setRanklist(list || [])
setSum(sum) setSum(sum)

View file

@ -1,4 +1,5 @@
import React, { useState, useEffect } from 'react' import React, { useState, useEffect } from 'react'
import { useQuery } from 'react-query'
import Head from 'next/head' import Head from 'next/head'
import Link from 'next/link' import Link from 'next/link'
@ -22,21 +23,10 @@ function fetchSupportedSites() {
}) })
} }
export default function Script({ globalState, setGlobalState }) { export default function Script() {
const [supportedSites, setSupportedSites] = useState() const { data: supportedSites } = useQuery('leaderBoard', () =>
fetchSupportedSites()
useEffect(() => { )
if (globalState.supportedSites) {
setSupportedSites(globalState.supportedSites)
} else {
fetchSupportedSites().then((res) => {
setSupportedSites(res)
setGlobalState({
supportedSites: res,
})
})
}
}, [])
return ( return (
<div className={styles.content}> <div className={styles.content}>