From dcfbce9593626854c72a8d91e5f4194f9231d910 Mon Sep 17 00:00:00 2001 From: Jasper Meggitt Date: Thu, 9 Sep 2021 10:48:30 -0400 Subject: [PATCH 1/4] Do primary tasks in assignment --- .gitignore | 3 + package-lock.json | 30 ++++++ package.json | 8 +- public/css/style.css | 74 +++++++++++++- public/index.html | 63 ++++++------ public/js/scripts.js | 106 +++++++++++++++++++- server.improved.js | 228 +++++++++++++++++++++++++++++++++---------- 7 files changed, 420 insertions(+), 92 deletions(-) create mode 100644 .gitignore create mode 100644 package-lock.json diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..c2669b88 --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +node_modules/ +.idea/ +*.iml diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 00000000..362f2195 --- /dev/null +++ b/package-lock.json @@ -0,0 +1,30 @@ +{ + "name": "a2-shortstack", + "lockfileVersion": 2, + "requires": true, + "packages": { + "": { + "dependencies": { + "mime": "^2.4.4" + } + }, + "node_modules/mime": { + "version": "2.5.2", + "resolved": "https://registry.npmjs.org/mime/-/mime-2.5.2.tgz", + "integrity": "sha512-tqkh47FzKeCPD2PUiPB6pkbMzsCasjxAfC62/Wap5qrUWcb+sFasXUC5I3gYM5iBM8v/Qpn4UK0x+j0iHyFPDg==", + "bin": { + "mime": "cli.js" + }, + "engines": { + "node": ">=4.0.0" + } + } + }, + "dependencies": { + "mime": { + "version": "2.5.2", + "resolved": "https://registry.npmjs.org/mime/-/mime-2.5.2.tgz", + "integrity": "sha512-tqkh47FzKeCPD2PUiPB6pkbMzsCasjxAfC62/Wap5qrUWcb+sFasXUC5I3gYM5iBM8v/Qpn4UK0x+j0iHyFPDg==" + } + } +} diff --git a/package.json b/package.json index 988f135f..63b9281c 100644 --- a/package.json +++ b/package.json @@ -1,8 +1,8 @@ { - "name": "", - "version": "", - "description": "", - "author": "", + "name": "a2-jmeggitt-Jasper-Meggit", + "version": "1.0.0", + "description": "Project 2 submission for CS 4241", + "author": "Jasper Meggitt", "scripts": { "start": "node server.improved.js" }, diff --git a/public/css/style.css b/public/css/style.css index d5f842ab..bf5deebf 100644 --- a/public/css/style.css +++ b/public/css/style.css @@ -1 +1,73 @@ -/*Style your own assignment! This is fun! */ \ No newline at end of file +body { + font-family: 'Open Sans', sans-serif; + display: flex; + flex-direction: column; + align-items: center; + flex-basis: 0; +} + +table { + margin-top: 1em; + border-collapse: collapse; + text-align: center; +} + +table tr:nth-child(even) { + background-color: #E3E3E3; +} + +th { + background-color: #4ECDC4; +} + +td, th { + padding: 8px; +} + +/* Rounded Table Corners https://stackoverflow.com/a/47318412/5987669 */ +th:first-of-type { + border-top-left-radius: 1em; +} +th:last-of-type { + border-top-right-radius: 1em; +} +tr:last-of-type td:first-of-type { + border-bottom-left-radius: 1em; +} +tr:last-of-type td:last-of-type { + border-bottom-right-radius: 1em; +} + +button { + border-radius: 0.5em; + border: 0; + transition-duration: 0.3s; +} + +button.edit { + background-color: #4A8FE7; +} + +button.edit:hover { + background-color: #175CB5; +} + +button.remove { + background-color: #D33F49; +} + +button.remove:hover { + background-color: #96222A; +} + +div.gray-box { + display: flex; + flex-direction: column; + background-color: #E3E3E3; + border-radius: 1em; + padding: 1em; +} + +div.gray-box h2 { + margin: 0; +} diff --git a/public/index.html b/public/index.html index c56d620e..8cb5bb9c 100644 --- a/public/index.html +++ b/public/index.html @@ -1,41 +1,42 @@ - + CS4241 Assignment 2 - - + + + + + + + +

User Leaderboard

+
+

Add Score

+
- - + + +
- - - fetch( '/submit', { - method:'POST', - body - }) - .then( function( response ) { - // do something with the reponse - console.log( response ) - }) - - return false - } - - window.onload = function() { - const button = document.querySelector( 'button' ) - button.onclick = submit - } - - diff --git a/public/js/scripts.js b/public/js/scripts.js index de052eae..2bbb80c7 100644 --- a/public/js/scripts.js +++ b/public/js/scripts.js @@ -1,3 +1,105 @@ -// Add some Javascript code here, to run on the front end. -console.log("Welcome to assignment 2!") \ No newline at end of file + +function updateLeaderboard(values) { + const elements = Object.entries(values) + .sort(([, a], [, b]) => b.score - a.score) + .map(([id, x], index) => ` + ${index + 1} + ${x.username} + ${x.score} + ${x.date} + + + + + `) + .join("\n"); + + const table = document.querySelector("#leaderboard") + table.tBodies[0].innerHTML = table.rows[0].innerHTML + table.tBodies[0].innerHTML += elements + + document.querySelectorAll(".remove").forEach(x => x.onclick = removeButton) + document.querySelectorAll(".edit").forEach(x => x.onclick = editButton) +} + +function removeButton(e) { + // Not necessary, but do anyway just to be safe + e.preventDefault() + + const targetID = e.path[2].id; + const id = parseInt(targetID.substring(5)) + console.log("Removing row of id " + id) + + const body = JSON.stringify({ + "id": id, + }) + + fetch('/api/remove', { + method: 'POST', + body + }) + .then(x => x.json()) + .then(updateLeaderboard) + + return false +} + +function editButton(e) { + if (e.path[0].innerHTML === "Edit") { + e.path[0].innerHTML = "Save" + + console.log(e.path) + const user = e.path[2].children[1] + const score = e.path[2].children[2] + + user.innerHTML = `` + score.innerHTML = `` + } else { + e.path[0].innerHTML = "Edit" + + const body = JSON.stringify({ + "id": parseInt(e.path[2].id.substring(5)), + "username": e.path[2].children[1].children[0].value, + "score": parseInt(e.path[2].children[2].children[0].value), + }) + + fetch('/api/edit', { + method: 'POST', + body + }) + .then(x => x.json()) + .then(updateLeaderboard) + } + + return false +} + +function fetchValues() { + fetch('/api/values', {method: 'GET'}) + .then(x => x.json()) + .then(updateLeaderboard) +} + + +function addUser(e) { + // prevent default form action from being carried out + e.preventDefault() + + const username = document.querySelector('#username') + const score = document.querySelector('#score') + + const body = JSON.stringify({ + "username": username.value, + "score": score.value, + }) + + fetch('/api/add', { + method: 'POST', + body + }) + .then(x => x.json()) + .then(updateLeaderboard) + + return false +} diff --git a/server.improved.js b/server.improved.js index 26673fc0..d24f9fad 100644 --- a/server.improved.js +++ b/server.improved.js @@ -1,72 +1,192 @@ -const http = require( 'http' ), - fs = require( 'fs' ), - // IMPORTANT: you must run `npm install` in the directory for this assignment - // to install the mime library used in the following line of code - mime = require( 'mime' ), - dir = 'public/', - port = 3000 - -const appdata = [ - { 'model': 'toyota', 'year': 1999, 'mpg': 23 }, - { 'model': 'honda', 'year': 2004, 'mpg': 30 }, - { 'model': 'ford', 'year': 1987, 'mpg': 14} -] - -const server = http.createServer( function( request,response ) { - if( request.method === 'GET' ) { - handleGet( request, response ) - }else if( request.method === 'POST' ){ - handlePost( request, response ) - } -}) +const http = require('http'), + fs = require('fs'), + // IMPORTANT: you must run `npm install` in the directory for this assignment + // to install the mime library used in the following line of code + mime = require('mime'), + dir = 'public/', + port = 3000 + +let dataCounter = 6; +const appdata = { + 0: {"rank": 1, "username": "Dave23", "score": 342, "date": new Date().toISOString()}, + 3: {"rank": 2, "username": "Legend69", "score": 235, "date": new Date().toISOString()}, + 5: {"rank": 3, "username": "bob", "score": 111, "date": new Date().toISOString()}, + 4: {"rank": 4, "username": "Dave23", "score": 29, "date": new Date().toISOString()}, +} -const handleGet = function( request, response ) { - const filename = dir + request.url.slice( 1 ) - if( request.url === '/' ) { - sendFile( response, 'public/index.html' ) - }else{ - sendFile( response, filename ) - } +function apiGetValues(request, response) { + response.writeHead(200, "OK", {'Content-Type': 'text/json'}) + response.end(JSON.stringify(appdata)) } -const handlePost = function( request, response ) { - let dataString = '' +function collectPost(request, callback) { + let dataString = '' + request.on('data', data => dataString += data) + request.on('end', () => callback(dataString)) +} - request.on( 'data', function( data ) { - dataString += data - }) +function apiPostAddition(request, response) { + collectPost(request, function (data) { + const field = JSON.parse(data); + + if (!(field.hasOwnProperty("username") && field.hasOwnProperty("score"))) { + response.writeHead(400, "Bad Request") + response.end("Missing username and/or score from request") + return + } + + if (!(typeof field.score === "number" && (field.score | 0) === field.score)) { + response.writeHead(400, "Bad Request") + response.end("Score must be an integer value") + return + } + + if (!(typeof field.username === "string" && field.username.length > 0)) { + response.writeHead(400, "Bad Request") + response.end("Username must be a non-empty string value") + return + } + + appdata[dataCounter] = { + "username": field.username, + "score": field.score, + "date": new Date().toISOString(), + } + + dataCounter += 1; + apiGetValues(request, response) + }) +} - request.on( 'end', function() { - console.log( JSON.parse( dataString ) ) +function apiPostRemove(request, response) { + collectPost(request, function (data) { + const field = JSON.parse(data); + + if (!(field.hasOwnProperty("id"))) { + response.writeHead(400, "Bad Request") + response.end("Missing id from request") + return + } + + if (!appdata.hasOwnProperty(field.id)) { + response.writeHead(400, "Bad Request") + response.end("Row ID not found") + return + } + + delete appdata[field.id] + apiGetValues(request, response) + }) +} - // ... do something with the data here!!! +function apiPostEdit(request, response) { + collectPost(request, function (data) { + const field = JSON.parse(data); + + if (!(field.hasOwnProperty("id") && field.hasOwnProperty("username") && field.hasOwnProperty("score"))) { + response.writeHead(400, "Bad Request") + response.end("Missing username, score and/or id from request") + return + } + + if (!(typeof field.score === "number" && (field.score | 0) === field.score)) { + response.writeHead(400, "Bad Request") + response.end("Score must be an integer value") + return + } + + if (!(typeof field.username === "string" && field.username.length > 0)) { + response.writeHead(400, "Bad Request") + response.end("Username must be a non-empty string value") + return + } + + if (!appdata.hasOwnProperty(field.id)) { + response.writeHead(400, "Bad Request") + response.end("Row ID not found") + return + } + + appdata[field.id] = { + "username": field.username, + "score": field.score, + "date": new Date().toISOString(), + } + apiGetValues(request, response) + }) +} - response.writeHead( 200, "OK", {'Content-Type': 'text/plain' }) - response.end() - }) +const handleGet = function (request, response) { + if (request.url === '/') { + sendFile(response, 'public/index.html') + } else { + sendFile(response, "public" + request.url) + } } -const sendFile = function( response, filename ) { - const type = mime.getType( filename ) +const sendFile = function (response, filename) { + const type = mime.getType(filename) - fs.readFile( filename, function( err, content ) { + fs.readFile(filename, function (err, content) { - // if the error = null, then we've loaded the file successfully - if( err === null ) { + // if the error = null, then we've loaded the file successfully + if (err === null) { - // status code: https://httpstatuses.com - response.writeHeader( 200, { 'Content-Type': type }) - response.end( content ) + // status code: https://httpstatuses.com + response.writeHeader(200, {'Content-Type': type}) + response.end(content) - }else{ + } else { + // file not found, error code 404 + response.writeHeader(404) + response.end('404 Error: File Not Found') + } + }) +} - // file not found, error code 404 - response.writeHeader( 404 ) - response.end( '404 Error: File Not Found' ) +function unknownRoute(request, response) { + response.writeHead(400, "Bad Request") + response.end("Unknown route: " + request.method + ": " + request.url) +} - } - }) +const routes = { + "GET": { + "/api/values": apiGetValues, + "/api": unknownRoute, + "/": handleGet, + }, + "POST": { + "/api/add": apiPostAddition, + "/api/remove": apiPostRemove, + "/api/edit": apiPostEdit, + } } -server.listen( process.env.PORT || port ) +const server = http.createServer(function (request, response) { + if (!routes.hasOwnProperty(request.method)) { + unknownRoute(request, response) + return + } + + for (const [route, fn] of Object.entries(routes[request.method])) { + if (request.url.startsWith(route)) { + fn(request, response) + return + } + } + + unknownRoute(request, response) + + // if (request.url.startsWith("/api")) { + // handleAPI(request, response) + // } else { + // if (request.method === 'GET') { + // handleGet(request, response) + // } else if (request.method === 'POST') { + // handlePost(request, response) + // } + // } +}) + +server.listen(process.env.PORT || port) From 3fe5aca9de7609c728d45ba7f945528e286a2dbc Mon Sep 17 00:00:00 2001 From: Jasper Meggitt Date: Thu, 9 Sep 2021 11:25:50 -0400 Subject: [PATCH 2/4] Update readme --- README.md | 101 +++++-------------------------------------- public/css/style.css | 4 +- public/index.html | 4 +- 3 files changed, 14 insertions(+), 95 deletions(-) diff --git a/README.md b/README.md index 996cf12d..99ef15b5 100644 --- a/README.md +++ b/README.md @@ -1,97 +1,16 @@ -Assignment 2 - Short Stack: Basic Two-tier Web Application using HTML/CSS/JS and Node.js -=== +## Simple Scoreboard -Due: September 9th, by 11:59 AM. +I implemented a very simple scoreboard. Anyone can add a score in the "Add Score" section and it will get displayed +below to anyone who loads the page. For my derived field, I have the date which updates whenever a line is added or +changed. The ranking column is computed on the client side. With the edit button you can modify the name and sore for +any row. Changes are sent to the remote when the save button is pressed. -This assignment aims to introduce you to creating a prototype two-tiered web application. -Your application will include the use of HTML, CSS, JavaScript, and Node.js functionality, with active communication between the client and the server over the life of a user session. - -Baseline Requirements ---- - -There is a large range of application areas and possibilities that meet these baseline requirements. -Try to make your application do something useful! A todo list, storing / retrieving high scores for a very simple game... have a little fun with it. - -Your application is required to implement the following functionalities: - -- a `Server` which not only serves files, but also maintains a tabular dataset with 3 or more fields related to your application -- a `Results` functionality which shows the entire dataset residing in the server's memory -- a `Form/Entry` functionality which allows a user to add, modify, or delete data items residing in the server's memory -- a `Server Logic` which, upon receiving new or modified "incoming" data, includes and uses a function that adds at least one additional derived field to this incoming data before integrating it with the existing dataset -- the `Derived field` for a new row of data must be computed based on fields already existing in the row. -For example, a `todo` dataset with `task`, `priority`, and `creation_date` may generate a new field `deadline` by looking at `creation_date` and `priority` - -Your application is required to demonstrate the use of the following concepts: - -HTML: -- One or more [HTML Forms](https://developer.mozilla.org/en-US/docs/Learn/HTML/Forms), with any combination of form tags appropriate for the user input portion of the application -- A results page displaying all data currently available on the server. You will most likely use a `` tag for this, but `
    ` or `
      ` could also work and might be simpler to work with. -- All pages should [validate](https://validator.w3.org) - -CSS: -- CSS styling of the primary visual elements in the application -- Various CSS Selector functionality must be demonstrated: - - Element selectors - - ID selectors - - Class selectors -- CSS positioning and styling of the primary visual elements in the application: - - Use of either a CSS grid or flexbox for layout - - Rules defining fonts for all text used; no default fonts! Be sure to use a web safe font or a font from a web service like [Google Fonts](http://fonts.google.com/) - -- CSS defined in a maintainable, readable form, in external stylesheets - -JavaScript: -- At minimum, a small amount of front-end JavaScript to get / fetch data from the server; a sample is provided in this repository. - -Node.js: -- An HTTP Server that delivers all necessary files and data for the application, and also creates the required `Derived Fields` in your data. -A starting point is provided in this repository. - -Deliverables ---- - -Do the following to complete this assignment and acheive a base grade of 85%: - -1. Fork the starting project code (make sure to fork the 2021 repo!). This repo contains some starter code that may be used or discarded as needed. -2. Implement your project with the above requirements. -3. Test your project to make sure that when someone goes to your main page, it displays correctly. -4. Deploy your project to Glitch, and fill in the appropriate fields in your package.json file. -5. Ensure that your project has the proper naming scheme `a2-yourGithubUsername` so we can find it. -6. Modify the README to the specifications below, and delete all of the instructions originally found in this README. -7. Create and submit a Pull Request to the original repo. Label the pull request as follows: a2-gitusername-firstname-lastname - -Acheivements ---- - -Below are suggested technical and design achievements. You can use these to help boost your grade up to an A and customize the assignment to your personal interests. These are recommended acheivements, but feel free to create/implement your own... just make sure you thoroughly describe what you did in your README and why it was challenging. ALL ACHIEVEMENTS MUST BE DESCRIBED IN YOUR README IN ORDER TO GET CREDIT FOR THEM. - -*Technical* -- (10 points) Create a single-page app that both provides a form for users to submit data and always shows the current state of the server-side data. To put it another way, when the user submits data, the server should respond sending back the updated data (including the derived field calculated on the server) and the client should then update its data display. - -*Design/UX* -- (5 points per person, with a max of 10 points) Test your user interface with other students in the class. Define a specific task for them to complete (ideally something short that takes <10 minutes), and then use the [think-aloud protocol](https://en.wikipedia.org/wiki/Think_aloud_protocol) to obtain feedback on your design (talk-aloud is also find). Important considerations when designing your study: - -1. Make sure you start the study by clearly stating the task that you expect your user to accomplish. -2. You shouldn't provide any verbal instructions on how to use your interface / accomplish the task you give them. Make sure that your interface is clear enough that users can figure it out without any instruction, or provide text instructions from within the interface itself. -3. If users get stuck to the point where they give up, you can then provde instruction so that the study can continue, but make sure to discuss this in your README. You won't lose any points for this... all feedback is good feedback! - -You'll need to use sometype of collaborative software that will enable you both to see the test subject's screen and listen to their voice as they describe their thoughts. After completing each study, briefly (one to two sentences for each question) address the following in your README: - -1. Provide the last name of each student you conduct the evaluation with. -2. What problems did the user have with your design? -3. What comments did they make that surprised you? -4. What would you change about the interface based on their feedback? - -*You do not need to actually make changes based on their feedback*. This acheivement is designed to help gain experience testing user interfaces. If you run two user studies, you should answer two sets of questions. - -Sample Readme (delete the above when you're ready to submit, and modify the below so with your links and descriptions) ---- - -## Your Web Application Title -Include a very brief summary of your project here. Be sure to include the CSS positioning technique you used, and any required instructions to use your application. +For the graphics, I used [coolors.co](coolors.co) to generate the color scheme for the table and buttons. The page uses +a flex box for the layout of elements. The font I decided to use is the Open Sans font from Google Fonts. ## Technical Achievements -- **Tech Achievement 1**: Using a combination of... +- **Tech Achievement 1**: Single page web app. Adding, saving, or removing any row will return the new state of the +leaderboard. ### Design/Evaluation Achievements -- **Design Achievement 1**: +n/a diff --git a/public/css/style.css b/public/css/style.css index bf5deebf..e7c3ea2b 100644 --- a/public/css/style.css +++ b/public/css/style.css @@ -60,7 +60,7 @@ button.remove:hover { background-color: #96222A; } -div.gray-box { +div.container { display: flex; flex-direction: column; background-color: #E3E3E3; @@ -68,6 +68,6 @@ div.gray-box { padding: 1em; } -div.gray-box h2 { +div.container h2 { margin: 0; } diff --git a/public/index.html b/public/index.html index 8cb5bb9c..4ad9cc93 100644 --- a/public/index.html +++ b/public/index.html @@ -11,7 +11,8 @@

      User Leaderboard

      -
      + +

      Add Score


      @@ -38,5 +39,4 @@

      Add Score

      fetchValues(); } - From 705d8f9dc7f193b5be912395b94a9e58cc710e22 Mon Sep 17 00:00:00 2001 From: Jasper Meggitt Date: Thu, 9 Sep 2021 11:29:01 -0400 Subject: [PATCH 3/4] Minor code cleanup --- public/js/scripts.js | 2 -- server.improved.js | 12 +----------- 2 files changed, 1 insertion(+), 13 deletions(-) diff --git a/public/js/scripts.js b/public/js/scripts.js index 2bbb80c7..5cb626bc 100644 --- a/public/js/scripts.js +++ b/public/js/scripts.js @@ -1,5 +1,3 @@ - - function updateLeaderboard(values) { const elements = Object.entries(values) .sort(([, a], [, b]) => b.score - a.score) diff --git a/server.improved.js b/server.improved.js index d24f9fad..cef2113f 100644 --- a/server.improved.js +++ b/server.improved.js @@ -3,7 +3,6 @@ const http = require('http'), // IMPORTANT: you must run `npm install` in the directory for this assignment // to install the mime library used in the following line of code mime = require('mime'), - dir = 'public/', port = 3000 let dataCounter = 6; @@ -150,6 +149,7 @@ function unknownRoute(request, response) { response.end("Unknown route: " + request.method + ": " + request.url) } +// DIY route handling const routes = { "GET": { "/api/values": apiGetValues, @@ -177,16 +177,6 @@ const server = http.createServer(function (request, response) { } unknownRoute(request, response) - - // if (request.url.startsWith("/api")) { - // handleAPI(request, response) - // } else { - // if (request.method === 'GET') { - // handleGet(request, response) - // } else if (request.method === 'POST') { - // handlePost(request, response) - // } - // } }) server.listen(process.env.PORT || port) From 9a48ba474c5e9854011fbb458096f19533259501 Mon Sep 17 00:00:00 2001 From: Jasper Meggitt Date: Thu, 9 Sep 2021 11:32:15 -0400 Subject: [PATCH 4/4] Add glitch link --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 99ef15b5..12e8b87e 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,5 @@ ## Simple Scoreboard +[https://a2-jmeggitt.glitch.me](https://a2-jmeggitt.glitch.me) I implemented a very simple scoreboard. Anyone can add a score in the "Add Score" section and it will get displayed below to anyone who loads the page. For my derived field, I have the date which updates whenever a line is added or