refactor, redesign, multiple rooms

This commit is contained in:
mdr 2020-05-08 17:55:57 +02:00
parent 509bea9468
commit 714c63271e
31 changed files with 16462 additions and 488 deletions

1
.env Normal file
View file

@ -0,0 +1 @@
REACT_APP_API_URL=backend/api/

1
.env.development Normal file
View file

@ -0,0 +1 @@
REACT_APP_API_URL=http://localhost/sdbs/sermon3/backend/api/

25
.gitignore vendored
View file

@ -1,2 +1,23 @@
outchat.db # See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
api_extra.php
# dependencies
/node_modules
/.pnp
.pnp.js
# testing
/coverage
# production
/build
# misc
.DS_Store
.env.local
.env.development.local
.env.test.local
.env.production.local
npm-debug.log*
yarn-debug.log*
yarn-error.log*

3
.htaccess Normal file
View file

@ -0,0 +1,3 @@
<IfModule mod_headers.c>
Header set Access-Control-Allow-Origin "*"
</IfModule>

21
LICENSE
View file

@ -1,21 +0,0 @@
MIT License
Copyright (c) 2018 sdbs
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

78
README.md Normal file
View file

@ -0,0 +1,78 @@
## Installing SERMON
Put contents of the `build` folder into the root of your server.
Put the `backend` folder into the root of your server.
That's it.
See below for building the project and other tasks.
---
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
## Available Scripts
In the project directory, you can run:
### `npm start`
Runs the app in the development mode.<br />
Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
The page will reload if you make edits.<br />
You will also see any lint errors in the console.
### `npm test`
Launches the test runner in the interactive watch mode.<br />
See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.
### `npm run build`
Builds the app for production to the `build` folder.<br />
It correctly bundles React in production mode and optimizes the build for the best performance.
The build is minified and the filenames include the hashes.<br />
Your app is ready to be deployed!
See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.
### `npm run eject`
**Note: this is a one-way operation. Once you `eject`, you cant go back!**
If you arent satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.
Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point youre on your own.
You dont have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldnt feel obligated to use this feature. However we understand that this tool wouldnt be useful if you couldnt customize it when you are ready for it.
## Learn More
You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).
To learn React, check out the [React documentation](https://reactjs.org/).
### Code Splitting
This section has moved here: https://facebook.github.io/create-react-app/docs/code-splitting
### Analyzing the Bundle Size
This section has moved here: https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size
### Making a Progressive Web App
This section has moved here: https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app
### Advanced Configuration
This section has moved here: https://facebook.github.io/create-react-app/docs/advanced-configuration
### Deployment
This section has moved here: https://facebook.github.io/create-react-app/docs/deployment
### `npm run build` fails to minify
This section has moved here: https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify

60
api.php
View file

@ -1,60 +0,0 @@
<?php
$initialized = file_exists('outchat.db');
try {
$database = new SQLite3('outchat.db');
} catch (Exception $exception) {
http_response_code(500);
echo $exception;
die(-1);
}
if (!$initialized) {
$database->exec(file_get_contents("outchat-ddl.sql"));
}
$action = $_GET['action'];
if ($action === 'getMessages') {
$timestamp = $database->escapeString(htmlspecialchars($_GET['timestamp']));
$timestamp = ($timestamp == 0) ? strtotime('-6 hours') : $timestamp;
$statement = $database->prepare('SELECT * FROM messages WHERE timestamp > :timestamp');
$statement->bindValue('timestamp', $timestamp);
$results = $statement->execute();
$messageArray = [];
while ($row = $results->fetchArray(SQLITE3_ASSOC)) {
$row['datetime'] = date('d/m H:i', $row['timestamp']);
$image_search = preg_match('/(http|https):\/\/[^ ]+(\.gif|\.jpg|\.jpeg|\.png)/', $row['text'], $out);
if ($image_search > 0) {
$row['text_processed'] = str_replace($out[0], '<p><img src="' . $out[0] . '" /></p>', $row['text']);
} else {
$row['text_processed'] = $row['text'];
}
$messageArray[] = $row;
}
echo json_encode($messageArray);
}
if ($action === 'createMessage') {
$timestamp = time();
$name = $database->escapeString(htmlspecialchars($_POST['name']));
$text = $database->escapeString(htmlspecialchars($_POST['text']));
$statement = $database->prepare('INSERT INTO messages (name, text, extra, timestamp) VALUES (:name, :text, :extra, :timestamp)');
$statement->bindValue(':name', $name, SQLITE3_TEXT);
$statement->bindValue(':text', $text, SQLITE3_TEXT);
if (file_exists('api_extra.php')) {
$extra_content = require 'api_extra.php';
$statement->bindValue(':extra', $extra_content(), SQLITE3_TEXT);
}
$statement->bindValue(':timestamp', $timestamp, SQLITE3_INTEGER);
$statement->execute();
}
?>

View file

@ -0,0 +1,17 @@
<?php
$timestamp = time();
$name = $database->escapeString(htmlspecialchars($_POST['name']));
$text = $database->escapeString(htmlspecialchars($_POST['text']));
$room_id = intval($database->escapeString(htmlspecialchars($_POST['room_id'])));
$statement = $database->prepare('INSERT INTO messages (name, text, timestamp, room_id) VALUES (:name, :text, :timestamp, :room_id)');
$statement->bindValue(':name', $name, SQLITE3_TEXT);
$statement->bindValue(':text', $text, SQLITE3_TEXT);
$statement->bindValue(':timestamp', $timestamp, SQLITE3_INTEGER);
$statement->bindValue(':room_id', $room_id, SQLITE3_INTEGER);
$statement->execute();
?>

View file

@ -0,0 +1,27 @@
<?php
$statement = $database->prepare('
SELECT messages.id, messages.room_id, messages.name, messages.text, messages.timestamp
FROM messages
JOIN rooms ON messages.room_id = rooms.id
WHERE rooms.is_active = 1
')->execute();
$messageArray = [];
while ($row = $statement->fetchArray(SQLITE3_ASSOC)) {
$row['datetime'] = date('d/m/Y H:i', $row['timestamp']);
$image_search = preg_match('/(http|https):\/\/[^ ]+(\.gif|\.jpg|\.jpeg|\.png)/', $row['text'], $out);
if ($image_search > 0) {
$row['text'] = str_replace($out[0], '<p><img src="' . $out[0] . '" /></p>', $row['text']);
} else {
$row['text'] = $row['text'];
}
$messageArray[] = $row;
}
echo json_encode($messageArray);
?>

16
backend/api/getRooms.php Normal file
View file

@ -0,0 +1,16 @@
<?php
$statement = $database->prepare('
SELECT *
FROM rooms
WHERE is_active = 1
')->execute();
$rooms = [];
while ($row = $statement->fetchArray(SQLITE3_ASSOC)) {
$rooms[] = $row;
}
echo json_encode($rooms);
?>

29
backend/api/index.php Normal file
View file

@ -0,0 +1,29 @@
<?php
include_once('../constants.php');
$action = $_GET['action'];
/*
$i = 1;
while($i <= 500) {
$name = substr(md5(rand()), 0, 7);
$text = md5(rand());
$room = rand(1,2);
$timestamp = time();
echo 'INSERT INTO messages (name, text, room_id, timestamp) VALUES ("'.$name.'", "'.$text.'", '.$room.', "'.$timestamp.'");<br>';
$i++;
}
exit;
*/
if($_GET['action'] && file_exists($_GET['action'].'.php')) {
include_once(BASE_PATH . '/db.php');
include_once(BASE_PATH . '/api/' . $_GET['action'].'.php');
} else {
http_response_code(500);
exit;
}
?>

5
backend/constants.php Normal file
View file

@ -0,0 +1,5 @@
<?php
define('BASE_PATH', dirname(__FILE__));
?>

15
backend/db.php Normal file
View file

@ -0,0 +1,15 @@
<?php
try {
$database = new SQLite3(BASE_PATH . '/db/sermon.db');
} catch (Exception $exception) {
http_response_code(500);
echo $exception;
exit;
}
if (!file_exists(BASE_PATH . '/db/sermon.db')) {
$database->exec(file_get_contents(BASE_PATH . '/db/sermon-ddl.sql'));
}
?>

16
backend/db/sermon-ddl.sql Normal file
View file

@ -0,0 +1,16 @@
CREATE TABLE `messages`
(
`id` INTEGER PRIMARY KEY AUTOINCREMENT,
`room_id` INTEGER,
`name` TEXT,
`text` TEXT,
`timestamp` INTEGER
);
CREATE TABLE `rooms`
(
`id` INTEGER PRIMARY KEY AUTOINCREMENT,
`name` TEXT
);
INSERT INTO `rooms` (`name`) VALUES (`default`)

BIN
backend/db/sermon.db Normal file

Binary file not shown.

View file

@ -1,47 +0,0 @@
function htmlToElements(html) {
const template = document.createElement('template')
template.innerHTML = html
return template.content.childNodes
}
function hashCode(str) { // java String#hashCode
var hash = 0;
for (var i = 0; i < str.length; i++) {
hash = str.charCodeAt(i) + ((hash << 5) - hash);
}
return hash;
}
function intToRGB(i) {
const c = (i & 0x00FFFFFF)
.toString(16)
.toUpperCase();
return "00000".substring(0, 6 - c.length) + c;
}
function getCookie(name) {
const value = "; " + document.cookie;
const parts = value.split("; " + name + "=");
if (parts.length == 2) return parts.pop().split(";").shift();
}
function nl2br(str, is_xhtml) {
if (typeof str === 'undefined' || str === null) {
return '';
}
var breakTag = (is_xhtml || typeof is_xhtml === 'undefined') ? '<br />' : '<br>';
return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1' + breakTag + '$2');
}
function scrollWindowDown() {
window.scrollTo(0, document.body.scrollHeight)
}
function inIframe() {
try {
return window.self !== window.top;
} catch (e) {
return true;
}
}

View file

@ -1,38 +0,0 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>sermon</title>
<meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1">
<link rel="stylesheet" href="main.css">
</head>
<body <?= empty($_REQUEST['observer']) ? '' : 'class="observer"' ?>>
<?php if (!isset($_COOKIE['outchat_name']) && empty($_REQUEST['observer'])) { ?>
<div class="modal">
<form action="" method="post" class="modal__form">
<input type="text" name="name" placeholder="name" minLength="3" maxLength="20" class="modal__form-input">
<input type="submit" value="»" class="modal__form-submit">
</form>
<div class="modal__info_url">
to only see chat, go <a href="https://live.sdbs.cz/sermon" target="_top">https://live.sdbs.cz/sermon</a>
</div>
</div>
<?php } ?>
<div class="chat">
</div>
<form method="post" action="api.php?action=createMessage" class="form">
<textarea name="text" class="form__input-message" placeholder="message"></textarea>
<input type="hidden" name="name" value="kent">
<input type="submit" value="»" class="form__input-submit">
</form>
<script src="helpers.js"></script>
<script src="main.js"></script>
</body>
</html>

186
main.css
View file

@ -1,186 +0,0 @@
* {
box-sizing: border-box;
}
html {
color: #fff;
background-color: #111;
font-family: Courier, Verdana, serif;
font-size: 14px;
}
body {
margin: 0;
}
.chat {
width: 100%;
padding: 30px 30px 80px 30px;
position: relative;
overflow: auto;
}
.message {
width: 100%;
margin-bottom: 40px;
}
.message__info {
width: 100%;
margin-bottom: 5px;
line-height: 1;
display: flex;
align-items: flex-end;
}
.message__info-name {
font-weight: 700;
margin-right: 10px;
font-size: 18px;
line-height: .8;
}
.message__info-extra {
color: #969696;
margin-right: 10px;
}
.message__info-extra:before {
content: "(";
}
.message__info-extra:after {
content: ")";
}
.message__text {
position: relative;
white-space: pre-line;
}
.message__text p {
margin: 0;
}
.message__text img {
margin: 10px 0 0 0;
width: 100%;
max-width: 320px;
display: block;
height: auto;
}
.form {
left: 15px;
bottom: 15px;
width: calc(100% - 30px);
height: 60px;
background-color: #fff;
position: fixed;
display: flex;
}
.form__input-message {
padding: 20px;
width: calc(100% - 60px);
height: 100%;
border: 0;
outline: 0;
margin: 0;
font-size: 16px;
resize: none;
white-space: pre-line;
}
.form__input-submit {
right: 0;
top: 0;
width: 60px;
height: 60px;
font-size: 30px;
font-weight: 700;
outline: 0;
border: 0;
cursor: pointer;
position: absolute;
background: none;
}
.modal {
left: 0;
top: 0;
width: 100%;
height: 100%;
z-index: 100;
background-color: #000;
position: fixed;
}
.modal__form {
width: 100%;
max-width: 600px;
height: 60px;
margin: 50px auto;
position: relative;
padding: 0 .5rem;
}
.modal__form-input {
padding: 0 90px 0 30px;
width: 100%;
height: 100%;
border: 0;
outline: 0;
font-size: 16px;
}
.modal__form-submit {
right: 0;
top: 0;
width: 60px;
height: 60px;
font-size: 30px;
font-weight: 700;
outline: 0;
border: 0;
cursor: pointer;
position: absolute;
background: none;
}
.modal__info_url {
text-align: center;
visibility: hidden;
}
.modal__info_url a {
color: white;
}
@media (max-width: 640px) {
.chat {
padding: 10px 10px 50px 10px;
}
.form {
left: 10px;
bottom: 10px;
width: calc(100% - 20px);
}
.message {
margin-bottom: 25px;
}
}
.observer .chat {
padding: 30px;
}
.observer .form {
visibility: hidden;
}
.observer .message:last-child {
margin-bottom: 0;
}

125
main.js
View file

@ -1,125 +0,0 @@
// modal form handle
if (document.querySelector('.modal__form-submit')) {
document.querySelector('.modal__form-submit').addEventListener('click', function (e) {
e.preventDefault();
const value = document.querySelector('.modal__form-input').value;
if (value.length >= 3) {
let date = new Date(Date.now());
date = date.setTime(date.getTime() + (90 * 24 * 60 * 60 * 1000));
date = new Date(date);
const expires = '; expires=' + date.toUTCString();
document.cookie = 'outchat_name=' + (value || '') + expires + '; path=/';
window.location.href = '';
}
});
}
document.querySelector('.form__input-message').addEventListener('keydown', function (e) {
if (!e.ctrlKey && e.keyCode === 13) {
e.preventDefault();
document.querySelector('.form__input-submit').click();
}
});
document.querySelector('.form__input-submit').addEventListener('click', function (e) {
e.preventDefault();
const name = getCookie('outchat_name');
const text = document.querySelector('.form__input-message').value;
document.querySelector('.form__input-message').value = '';
let formData = new FormData();
formData.append(name, text);
fetch('api.php?action=createMessage', {
method: 'post',
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
body: 'name=' + name + '&text=' + text,
}).then(() => {
getMessages();
}).catch((error) => {
console.log(error);
});
});
function getMessages() {
const timestamp = (document.querySelector('.chat').lastElementChild) ? document.querySelector('.chat').lastElementChild.getAttribute('data-timestamp') : 0;
return fetch('api.php?action=getMessages&timestamp=' + timestamp)
.then(function (data) {
return data.json();
})
.then(function (data) {
if (data.length > 0) {
if ((window.scrollY + window.innerHeight) === document.body.scrollHeight) {
setTimeout(function () {
scrollWindowDown();
}, 100);
}
for (let message of data) {
createMessageNode(message.name, message.text_processed, message.extra, message.timestamp, message.datetime);
}
}
})
.catch(function (error) {
console.log(error);
});
}
function createMessageNode(name, text, extra, timestamp, datetime) {
const elementMain = document.createElement('div', {class: 'message'});
const elementText = document.createElement('div', {class: 'message__text'});
const elementInfo = document.createElement('div', {class: 'message__info'});
const elementName = document.createElement('div', {id: 'message__info-name'});
const elementExtra = document.createElement('div', {class: 'message__info-extra'});
const elementDatetime = document.createElement('div', {id: 'message__info-datetime'});
const contentName = document.createTextNode(name);
const contentExtra = document.createTextNode(extra);
const contentDatetime = document.createTextNode('[' + datetime + ']');
//const contentText = document.createTextNode(text)
// element creation
elementMain.classList.add('message');
elementText.classList.add('message__text');
elementInfo.classList.add('message__info');
elementDatetime.classList.add('message__info-datetime');
elementName.classList.add('message__info-name');
elementExtra.classList.add('message__info-extra');
// "hash" name color
elementName.style.color = "#" + intToRGB(hashCode(name));
// append everything to chat
elementName.appendChild(contentName);
elementExtra.appendChild(contentExtra);
elementDatetime.appendChild(contentDatetime);
elementText.innerHTML = text;
elementInfo.appendChild(elementName);
if (extra) {
elementInfo.appendChild(elementExtra);
}
elementInfo.appendChild(elementDatetime);
elementMain.appendChild(elementInfo);
elementMain.appendChild(elementText);
elementMain.setAttribute('data-timestamp', timestamp);
document.querySelector('.chat').appendChild(elementMain);
return true;
}
getMessages().then(() => {
scrollWindowDown();
});
setInterval(function () {
getMessages();
}, 2000);
if (inIframe()) {
document.querySelector('.modal__info_url').style.visibility = 'visible';
}

View file

@ -1,9 +0,0 @@
CREATE TABLE `messages`
(
`id` INTEGER PRIMARY KEY AUTOINCREMENT,
`name` TEXT,
`text` TEXT,
`extra` TEXT,
`timestamp` INTEGER
);

15393
package-lock.json generated Normal file

File diff suppressed because it is too large Load diff

37
package.json Normal file
View file

@ -0,0 +1,37 @@
{
"name": "sermon3",
"version": "0.1.0",
"homepage": ".",
"private": true,
"dependencies": {
"@testing-library/jest-dom": "^4.2.4",
"@testing-library/react": "^9.5.0",
"@testing-library/user-event": "^7.2.1",
"react": "^16.13.1",
"react-dom": "^16.13.1",
"react-scripts": "3.4.1"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"devDependencies": {
"react-router-dom": "^5.1.2"
}
}

19
public/index.html Normal file
View file

@ -0,0 +1,19 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>/-\ SERMON</title>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
</body>
</html>

269
src/App.css Normal file
View file

@ -0,0 +1,269 @@
* {
box-sizing: border-box;
}
html {
font-size: 14px;
height: 100%;
color: #A59F6F;
background-color: #000;
overflow: hidden;
}
body {
margin: 0;
height: 100%;
overflow: hidden;
font-family: monospace, sans-serif;
}
a {
color: #60BB2D;
}
/* ### ROOM LIST ### */
.chat {
left: 0;
top: 3rem;
width: 100%;
height: calc(100% - 6rem);
position: absolute;
}
.chat--large {
top: 0;
height: calc(100% - 3rem);
}
.chat__room {
left: 0;
top: 0;
width: 100%;
height: 100%;
padding: 1rem;
overflow: auto;
position: absolute;
display: none;
}
.chat__room.is-active {
display: block;
}
/* ### ROOM LIST ### */
.room-list {
height: 3rem;
display: flex;
overflow: auto;
border-bottom: 1px solid #60BB2D;
}
.room-list__item {
padding: 0 1rem;
height: 3rem;
line-height: 3rem;
opacity: .6;
color: #60BB2D;
}
.room-list__item:before {
content: attr(title);
font-weight: 700;
opacity: 0;
height: 0;
display: block;
overflow: hidden;
visibility: hidden;
}
.room-list__item:hover,
.room-list__item.is-active {
opacity: 1;
font-weight: 700;
cursor: pointer;
}
/* ### MESSAGE ### */
.message {
width: 100%;
margin-bottom: 2rem;
}
.message:last-child {
margin-bottom: 1rem;
}
.message__info {
width: 100%;
margin-bottom: .5rem;
display: flex;
align-items: center;
flex-wrap: wrap;
}
.message__info-name {
font-weight: 700;
}
.message__info-datetime {
font-size: .8rem;
margin-left: .5rem;
}
.message__info-extra {
color: #969696;
margin-top: .5rem;
width: 100%;
font-size: .8rem;
}
.message__info-extra:before {
content: "(";
}
.message__info-extra:after {
content: ")";
}
.message__text {
position: relative;
white-space: pre-line;
}
.message__text p {
margin: 0;
}
.message__text img {
margin: 1rem 0 0 0;
width: 100%;
max-width: 320px;
display: block;
height: auto;
vertical-align: top;
}
/* FORM */
.form {
bottom: 0;
left: 0;
padding: 1rem;
width: 100%;
background: none;
position: fixed;
display: flex;
}
.form--modal {
bottom: 50%;
}
.form--message {
height: 3rem;
border-top: 1px solid #60BB2D;
}
.form__input-message {
padding: 0 2rem 0 0;
height: 1.8rem;
width: 100%;
border: 0;
outline: 0;
margin: 0;
font-size: 1rem;
background: none;
white-space: pre-line;
resize: none;
font-family: monospace;
color: #60BB2D;
border-bottom: 1px solid #60BB2D;
}
.form--message .form__input-message {
border: 0;
}
.form__input-submit {
right: 0;
top: 0;
padding: 0 1rem;
height: 100%;
font-size: 1.2rem;
font-weight: 700;
color: #60BB2D;
outline: 0;
border: 0;
cursor: pointer;
position: absolute;
background: none;
}
/* ### MODAL ### */
.modal {
left: 0;
top: 0;
padding: 1rem;
width: 100%;
height: 100%;
z-index: 100;
background-color: #20201E;
position: fixed;
}
.modal__form {
width: 100%;
max-width: 40rem;
margin: 5rem auto;
position: relative;
}
.modal__form-input {
padding: 0 2rem 0 0;
width: 100%;
height: 1.6rem;
border: 0;
outline: 0;
font-size: 1rem;
border-bottom: 1px solid #60BB2D;
color: #60BB2D;
font-family: monospace, sans-serif;
background: none;
}
.modal__form-submit {
right: 0;
top: 0;
height: 100%;
padding: 0 0 0 1rem;
font-size: 1.2rem;
font-weight: 700;
outline: 0;
border: 0;
color: #60BB2D;
cursor: pointer;
position: absolute;
background: none;
}
.modal__info-url {
padding: 0 1rem;
text-align: center;
visibility: hidden;
}
.modal__info_url a {
color: white;
}
.observer .chat {
padding: 2rem;
}
.observer .form {
visibility: hidden;
}
.observer .message:last-child {
margin-bottom: 0;
}

211
src/App.js Normal file
View file

@ -0,0 +1,211 @@
import './App.css'
import React, { useState, useEffect } from 'react'
import Modal from './components/Modal'
import MessageForm from './components/MessageForm'
import Messages from './components/Messages'
import useInterval from './helpers/useInterval'
export default function App(props) {
const [username, setUsername] = useState(``)
const [modalActive, setModalActive] = useState(true)
const [rooms, setRooms] = useState([])
const [roomActive, setRoomActive] = useState(0)
const [message, setMessage] = useState(``)
const [messages, setMessages] = useState([])
const [chatScrollStatus, setChatScrollStatus] = useState(`bottom`)
/*
###
### USERNAME (MODAL)
###
*/
/* username change */
const handleUsernameChange = (username) => {
setUsername(username)
}
/* username submit */
const handleUsernameSubmit = () => {
if(username.length >= 3) {
localStorage.setItem(`sdbs-sermon-username`, username)
setModalActive(false)
}
}
/* submit username, write into local storage and close modal */
useEffect(() => {
if(localStorage.getItem(`sdbs-sermon-username`)) {
setUsername(localStorage.getItem(`sdbs-sermon-username`))
setModalActive(false)
}
}, [username, modalActive])
/*
###
### ROOMS
###
*/
const fetchRooms = (roomActive) => {
fetch(`${process.env.REACT_APP_API_URL}?action=getRooms`)
.then(response => response.json())
.then(data => {
if (!roomActive) {
setRoomActive(data[0].id)
}
setRooms(data)
})
}
useEffect(() => {
fetchRooms()
}, [])
useInterval(() => {
fetchRooms(roomActive)
}, 10000)
const handleRoomChange = (id) => {
setRoomActive(id)
setChatScrollStatus(`bottom`)
}
/*
###
### CHAT ROOM SCROLLING
###
*/
const handleChatScrollStatus = (chat) => {
if((chat.scrollTop + chat.offsetHeight) < (chat.scrollHeight - 50)) {
setChatScrollStatus(`scrolling`)
} else {
setChatScrollStatus(`bottom`)
}
}
const handleChatScroll = () => {
const chats = document.querySelectorAll(`.chat__room`)
if(chatScrollStatus === `bottom`) {
chats.forEach(item => {
item.scrollTop = item.scrollHeight
})
}
}
/*
###
### MESSAGES
###
*/
useEffect(() => {
handleChatScroll()
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [roomActive])
const fetchMessages = () => {
fetch(`${process.env.REACT_APP_API_URL}?action=getMessages`)
.then(response => response.json())
.then(data => {
setMessages(data)
handleChatScroll()
})
}
useEffect(() => {
fetchMessages()
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [])
useInterval(() => {
fetchMessages()
}, 5000)
/*
###
### MESSAGE FORM
###
*/
/* message change */
const handleMessageChange = (message) => {
setMessage(message)
}
/* message change */
const handleMessageSubmit = (e) => {
e.preventDefault()
if(message.length > 0) {
fetch(`${process.env.REACT_APP_API_URL}?action=createMessage`, {
method: `POST`,
headers: {
'Content-Type': `application/x-www-form-urlencoded`,
},
body: `name=${username}&text=${message}&room_id=${roomActive}`,
}).then(response => {
console.log(response)
setMessage(``)
fetchMessages()
}).catch(error => {
console.log(error)
})
}
}
/* ### RENDER ### */
return (
<div className={`wrapper`}>
{modalActive && <Modal usernameChange={handleUsernameChange} usernameSubmit={handleUsernameSubmit} />}
{rooms.length > 1 &&
<div className={`room-list`}>
{rooms.map(room =>
<div
className={`room-list__item ${(roomActive === room.id) && `is-active`}`}
key={room.id}
title={room.name}
onClick={e => handleRoomChange(room.id)}
>
{room.name}
</div>
)}
</div>
}
<div className={rooms.length <= 1 ? `chat chat--large` : `chat`}>
{rooms.map(room =>
<div
className={`chat__room ${(roomActive === room.id) && `is-active`}`}
key={room.id}
onScroll={e => handleChatScrollStatus(e.target)}
data-id={room.id}
>
<Messages messages={messages.filter(m => m.room_id === room.id)} />
</div>
)}
</div>
<MessageForm messageChange={handleMessageChange} messageSubmit={handleMessageSubmit} message={message} />
</div>
)
}

View file

@ -0,0 +1,33 @@
import React from 'react'
export default function MessageForm(props) {
return (
<form
method={`post`}
className={`form form--message`}
>
<textarea
name={`text`}
className={`form__input-message`}
placeholder={`message`}
value={props.message}
onChange={e => props.messageChange(e.target.value)}
>
</textarea>
<input
type={`submit`}
value={``}
className={`form__input-submit`}
onClick={e => {
e.preventDefault()
props.messageSubmit(e)
}}
/>
</form>
)
}

View file

@ -0,0 +1,49 @@
import React from 'react'
export default function Messages(props) {
const formatDate = (timestamp) => {
const d = new Date(timestamp * 1000)
const day = (d.getDay() < 10 && `0`) + d.getDay()
const month = ((d.getMonth() + 1) < 10 && `0`) + d.getMonth()
const year = d.getFullYear()
const hours = (d.getHours() < 10 && `0`) + d.getHours()
const minutes = (d.getMinutes() < 10 && `0`) + d.getMinutes()
return `${day}/${month}/${year} ${hours}:${minutes}`
}
const nameToRGB = (str) => {
let hash = 0
for (var i = 0; i < str.length; i++) {
hash = str.charCodeAt(i) + ((hash << 5) - hash)
}
const c = (hash & 0x00FFFFFF).toString(16).toUpperCase()
return `#` + (`00000`.substring(0, 6 - c.length) + c)
}
return (
<div>
{props.messages.map(item =>
<div
className={`message`}
key={item.id}
>
<div className={`message__info`}>
<div className={`message__info-name`} style={{ color: nameToRGB(item.name) }}>
{item.name}
</div>
<div className={`message__info-datetime`}>[{formatDate(item.timestamp)}]</div>
</div>
<div className={`message__text`} dangerouslySetInnerHTML={{__html: item.text}}>
</div>
</div>
)}
</div>
)
}

39
src/components/Modal.js Normal file
View file

@ -0,0 +1,39 @@
import React from 'react'
export default function Modal(props) {
const handleUsernameChange = (e) => {
props.usernameChange(e.target.value)
}
const handleUsernameSubmit = (e) => {
e.preventDefault()
props.usernameSubmit()
}
return (
<div className={`modal`}>
<form method={`post`} className={`form form--modal`}>
<input
type={`text`}
name={`name`}
placeholder={`enter your nickname`}
minLength={`3`}
maxLength={`20`}
className={`form__input-message`}
onChange={e => handleUsernameChange(e)}
/>
<input
type={`submit`}
value={``}
className={`form__input-submit`}
onClick={e => handleUsernameSubmit(e)}
/>
</form>
</div>
)
}

View file

@ -0,0 +1,24 @@
import { useEffect, useRef } from 'react'
export default function useInterval(callback, delay) {
const savedCallback = useRef()
// Remember the latest callback.
useEffect(() => {
savedCallback.current = callback
}, [callback])
// Set up the interval.
useEffect(() => {
function tick() {
savedCallback.current()
}
if (delay !== null) {
let id = setInterval(tick, delay)
return () => clearInterval(id)
}
}, [delay])
}

16
src/index.js Normal file
View file

@ -0,0 +1,16 @@
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import * as serviceWorker from './serviceWorker';
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);
// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
serviceWorker.unregister();

141
src/serviceWorker.js Normal file
View file

@ -0,0 +1,141 @@
// This optional code is used to register a service worker.
// register() is not called by default.
// This lets the app load faster on subsequent visits in production, and gives
// it offline capabilities. However, it also means that developers (and users)
// will only see deployed updates on subsequent visits to a page, after all the
// existing tabs open on the page have been closed, since previously cached
// resources are updated in the background.
// To learn more about the benefits of this model and instructions on how to
// opt-in, read https://bit.ly/CRA-PWA
const isLocalhost = Boolean(
window.location.hostname === 'localhost' ||
// [::1] is the IPv6 localhost address.
window.location.hostname === '[::1]' ||
// 127.0.0.0/8 are considered localhost for IPv4.
window.location.hostname.match(
/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
)
);
export function register(config) {
if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
// The URL constructor is available in all browsers that support SW.
const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href);
if (publicUrl.origin !== window.location.origin) {
// Our service worker won't work if PUBLIC_URL is on a different origin
// from what our page is served on. This might happen if a CDN is used to
// serve assets; see https://github.com/facebook/create-react-app/issues/2374
return;
}
window.addEventListener('load', () => {
const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;
if (isLocalhost) {
// This is running on localhost. Let's check if a service worker still exists or not.
checkValidServiceWorker(swUrl, config);
// Add some additional logging to localhost, pointing developers to the
// service worker/PWA documentation.
navigator.serviceWorker.ready.then(() => {
console.log(
'This web app is being served cache-first by a service ' +
'worker. To learn more, visit https://bit.ly/CRA-PWA'
);
});
} else {
// Is not localhost. Just register service worker
registerValidSW(swUrl, config);
}
});
}
}
function registerValidSW(swUrl, config) {
navigator.serviceWorker
.register(swUrl)
.then(registration => {
registration.onupdatefound = () => {
const installingWorker = registration.installing;
if (installingWorker == null) {
return;
}
installingWorker.onstatechange = () => {
if (installingWorker.state === 'installed') {
if (navigator.serviceWorker.controller) {
// At this point, the updated precached content has been fetched,
// but the previous service worker will still serve the older
// content until all client tabs are closed.
console.log(
'New content is available and will be used when all ' +
'tabs for this page are closed. See https://bit.ly/CRA-PWA.'
);
// Execute callback
if (config && config.onUpdate) {
config.onUpdate(registration);
}
} else {
// At this point, everything has been precached.
// It's the perfect time to display a
// "Content is cached for offline use." message.
console.log('Content is cached for offline use.');
// Execute callback
if (config && config.onSuccess) {
config.onSuccess(registration);
}
}
}
};
};
})
.catch(error => {
console.error('Error during service worker registration:', error);
});
}
function checkValidServiceWorker(swUrl, config) {
// Check if the service worker can be found. If it can't reload the page.
fetch(swUrl, {
headers: { 'Service-Worker': 'script' },
})
.then(response => {
// Ensure service worker exists, and that we really are getting a JS file.
const contentType = response.headers.get('content-type');
if (
response.status === 404 ||
(contentType != null && contentType.indexOf('javascript') === -1)
) {
// No service worker found. Probably a different app. Reload the page.
navigator.serviceWorker.ready.then(registration => {
registration.unregister().then(() => {
window.location.reload();
});
});
} else {
// Service worker found. Proceed as normal.
registerValidSW(swUrl, config);
}
})
.catch(() => {
console.log(
'No internet connection found. App is running in offline mode.'
);
});
}
export function unregister() {
if ('serviceWorker' in navigator) {
navigator.serviceWorker.ready
.then(registration => {
registration.unregister();
})
.catch(error => {
console.error(error.message);
});
}
}