From 33e6ebd9c5e54e069cc1d5b695beae48463ce34c Mon Sep 17 00:00:00 2001 From: Gordon Wang <97267381+GHWang28@users.noreply.github.com> Date: Wed, 11 Oct 2023 20:20:26 +1100 Subject: [PATCH] Style Guide Updates from Ass1 and Ass2 feedback (#13) * Added Image Examples * Added style example assets * Updated universal CSS selector style guide * Fixed bolded sentences * Fixed wrong example title * Added margin and padding exception to universal selector * Moved title tag into head tag in html structure guide * Added a clearer disclaimer that the style guide is not exhaustive * Fixed formatting of existing examples * Stylised example accordions * Added new HTML points based on feedback * Added unmount on exit for quicker load times * Added note on refering marking criteria * Edited example accordion * Added more guidelines * Added disclaimer * Added missing example for !important * Added example of good use case for
* Changed 3.7. Arrow function to be less absolute * Added max-width * Reverted max-width * Removed unformatted markdown syntax * Fixed typo in example * Extracted similar code into own component * Fixed validateDomNesting errors * Reverted file to test checks * Revert "Reverted file to test checks" This reverts commit 077cdb72cb0c4409e1389a43671a767bab506162. --- frontend/src/component/StyleComponents.jsx | 102 +++--- frontend/src/page/Style/StyleCSS.jsx | 250 +++++++++++-- frontend/src/page/Style/StyleHtml.jsx | 372 +++++++++++++++++--- frontend/src/page/Style/StyleJavascript.jsx | 188 ++++++---- frontend/src/page/Style/StyleReact.jsx | 131 +++---- 5 files changed, 784 insertions(+), 259 deletions(-) diff --git a/frontend/src/component/StyleComponents.jsx b/frontend/src/component/StyleComponents.jsx index e97be38..c21823a 100644 --- a/frontend/src/component/StyleComponents.jsx +++ b/frontend/src/component/StyleComponents.jsx @@ -2,8 +2,10 @@ import React from 'react'; import Typography from '@mui/material/Typography'; import Divider from '@mui/material/Divider'; import Box from '@mui/material/Box'; +import Collapse from '@mui/material/Collapse'; import SyntaxHighlighter from 'react-syntax-highlighter'; import { a11yDark } from 'react-syntax-highlighter/dist/esm/styles/hljs'; +import ExpandLessIcon from '@mui/icons-material/ExpandLess'; export const Body = (props) => { return ( @@ -34,7 +36,7 @@ export const HR = () => { } export const Code = (props) => { - {/*
*/} + /*
*/ return (
{ ) } -export const Example = (props) => { - const [expand, setExpand] = React.useState(true); - return ( - <> - setExpand(!expand)}> - - {expand ? '⬇️' : '⬆️'} 💡 {`${(props.title ?? 'Example')}:`} - - - {expand ? ( -
- {props.bads && props.bads.map((bad, idx) => { - return ( - <> - 🔴 Bad - {bad} - - ) - })} - {props.goods && props.goods.map((good, idx) => { - return ( - <> - 🟢 Good - {good} - - ) - })} -
- ) : ( -
...
- )} - - ) -} +export const Example = (props) => ( + + {props.bads && props.bads.map((bad, idx) => { + return ( + + 🔴 Bad + {bad} + + ) + })} + {props.goods && props.goods.map((good, idx) => { + return ( + + 🟢 Good + {good} + + ) + })} + +) + +export const ExampleImages = ({ title, srcArray = [] }) => ( + + {srcArray.map((asset, idx) => ( + + ))} + +) -export const ExampleImages = ({ title, srcArray = [] }) => { - const [expand, setExpand] = React.useState(true); +const ExampleAccordionWrapper = ({ children, title = 'Example' }) => { + const [expand, setExpand] = React.useState(false); return ( - <> - setExpand(!expand)}> - - {expand ? '⬇️' : '⬆️'} 💡 {`${(title ?? 'Example')}:`} - - - {expand ? ( - srcArray.map((asset, idx) => ( - - )) - ) : ( -
...
- )} - + + setExpand(!expand)}> + + + {`${(title)}:`} + + + + + + {children} + + + ) } const CaptionedImage = ({ src, alt, caption }) => ( - + ( maxWidth='700px' width='100%' /> - {caption ?? ''} + {caption ?? ''} ) diff --git a/frontend/src/page/Style/StyleCSS.jsx b/frontend/src/page/Style/StyleCSS.jsx index d7c4415..9003eb3 100644 --- a/frontend/src/page/Style/StyleCSS.jsx +++ b/frontend/src/page/Style/StyleCSS.jsx @@ -3,34 +3,42 @@ import React from 'react'; import makePage from '../../component/makePage'; -import { Body, H3, H5, HR, Code, Example } from '../../component/StyleComponents'; +import { Body, H3, H5, HR, Example } from '../../component/StyleComponents'; const StyleCSS = ({}) => { + const emoji = '🎨'; + return ( <> +

{emoji} 2. CSS Style Guide

-

🎨 2. CSS Style Guide

- - The assignments in COMP6080 all have a portion of their marks allocated to code style. As such, it is **highly** recommended for students to have a read through this style guide. - This page outlines the conventions we will be following throughout the course. It incorporates guidelines derived from standard style guides plus feedback and inquiries accumulated from previous cohorts. - We follow the MDN style guide for CSS as a base. Here are a few notable guidelines that are often asked about or forgotten. + The assignments in COMP6080 all have a portion of their marks allocated to code style. As such, it is highly recommended for students to have a read through this style guide. - + Below is our style guide for COMP6080 for writing good CSS. For anything not mentioned here, refer to the MDN style guide for CSS. + + + Please also note that you should refer to the marking criteria too that's attached with each Assignment. + +
-
🎨 2.1. Casing & Quotation
+
{emoji} 2.1. Casing & Quotation
You should stick to kebab-casing when creating Classes/IDs and other things like keyframes. We won't be strict about this however - as long as you're consistent. @@ -82,7 +90,7 @@ const StyleCSS = ({}) => {
-
🎨 2.2. Indentation
+
{emoji} 2.2. Indentation
As long as you're consistent, you may use 2-space or 4-space indentation in CSS files. We increase the indentation level everytime we use an opening brace {'{'} and decrease it when we use a closing brace {'}'}. We also go to a new line with each semicolon ;. @@ -113,7 +121,7 @@ transition: background-color 0.3s ease;
-
🎨 2.3. Avoid Repetition
+
{emoji} 2.3. Avoid Repetition
Like coding languages, you should try and follow the DRY principle here - Don't Repeat Yourself. If two classes are very similar, then you should break it up into smaller pieces. @@ -238,7 +246,7 @@ css
-
🎨 2.4. CSS Colors
+
{emoji} 2.4. CSS Colors
You may use any method when picking/defining CSS colors. @@ -260,7 +268,7 @@ css
-
2.5. Universal Selectors
+
{emoji} 2.5. Universal Selectors
Avoid the * selector to prevent unintended side effects, such as unintentionally overriding the margin property of an element that you want a different margin set. However, an exception will be made if they are solely used to modify the default settings for box-sizing, margin or padding. @@ -286,15 +294,14 @@ css
-
🎨 2.6. Use External Spreadsheet
+
{emoji} 2.6. Use External Spreadsheet
- Keep all CSS separate from the HTML file. This is for the following reasons: -
    -
  • Separation of Concerns: Mixing CSS and HTML together makes it harder to maintain and update the code.
  • -
  • Code Reusability: Can reuse the same CSS file across multiple web pages.
  • -
  • Prevents Cascading issues: Inline styles take priority over external stylesheets and other CSS rules. This means as your codebase grows, it becomes more difficult to understand the styling hierarchy of your element.
  • -
- + Keep all CSS separate from the HTML file. This is for the following reasons: +
    +
  • Separation of Concerns: Mixing CSS and HTML together makes it harder to maintain and update the code.
  • +
  • Code Reusability: Can reuse the same CSS file across multiple web pages.
  • +
  • Prevents Cascading issues: Inline styles take priority over external stylesheets and other CSS rules. This means as your codebase grows, it becomes more difficult to understand the styling hierarchy of your element.
  • +
Do not be afraid to create multiple stylesheets to keep things more organised. @@ -306,7 +313,7 @@ css `, `/* in */ /* in */ - - -` + + +` ]} goods={[ `/* in style.css */ -.blue-card { +.primary-btn { background-color: blue; color: white; text-transform: capitalize; @@ -335,15 +342,15 @@ css /* in index.html in */ - - -` + + +` ]} />
-
🎨 2.7. Class/ID naming conventions
+
{emoji} 2.7. Class/ID naming conventions
Make sure your Classes/IDs have meaningful names that describes what styles it has or what it's used for. It will make your code more accessible to your group mate. Also in the event of forgetting what a Class/ID is for, the name will remind you. @@ -355,6 +362,16 @@ css } .img-b { filter: grayscale(100%); +} +.bg-1 { + background-color: salmon; +} +.bg-2 { + background-color: forestgreen; +} +.zsbd { + display: grid; + place-items: center; }` ]} goods={[ @@ -363,9 +380,168 @@ css } .grayscale-img { filter: grayscale(100%); +} +.red-bg { + background-color: salmon; +} +.green-bg { + background-color: forestgreen; +} +.container { + display: grid; + place-items: center; }` ]} /> + +
+
{emoji} 2.8. Overuse of !important
+ Using !important in CSS should be avoided or used sparingly as last resort because it can cause the following problems: +
    +
  • Limited flexibility: It will be harder to change styles of elements easily in the future as you'll need to figure out that the style you're trying to change is being overridden by an !important and then subsequently you need to hunt down that specific !important.
  • +
  • Specificity Confusion: !important overrides the natural cascading behaviour of Cascading Stylesheets (CSS), which can lead to confusion in understanding what styles are being applied to your elements.
  • +
+ + + +
+
{emoji} 2.9. Avoid negative margins
+ Overusing negative margins makes it difficult to debug, maintain or understand your CSS. Instead, if you want elements to overlap, you can use other methods like relative positioning. + +.offset { + margin-top: -10px; +} + + +
+

Hello world!

+
` + ]} + goods={[ + ` +.offset { + position: relative; + top: -10px; +} + + +
+

Hello world!

+
` + ]} + /> + If you're trying to get elements closer, remove the margins that are in the way. For example, it's better to get rid of the margin on the body rather than setting negative margins to the children to close the gap. + +.container { + margin-top: -8px; + margin-left: -8px; + + background-color: salmon; +} + + + +
Hello world!
+` + ]} + goods={[ + ` +body { + margin: 0; +} + +.container { + background-color: salmon; +} + + + +
Hello world!
+` + ]} + /> + +
+
{emoji} 2.10. Remove empty rulesets
+ You should not have any empty rulesets in your CSS files. They don't do anything. + +
+
{emoji} 2.11. Remove blocks of commented out code
+ While it may be useful during debugging, having a bunch of commented out code around will make your code less readable. + + ); }; diff --git a/frontend/src/page/Style/StyleHtml.jsx b/frontend/src/page/Style/StyleHtml.jsx index 2dae063..c916313 100644 --- a/frontend/src/page/Style/StyleHtml.jsx +++ b/frontend/src/page/Style/StyleHtml.jsx @@ -11,33 +11,40 @@ import EcklesImg from '../../asset/style/eckles-img-example.png'; const StyleHtml = ({}) => { - return ( - <> + const emoji = '📜'; -

📜 1. HTML Style Guide

+ return ( +
+

{emoji} 1. HTML Style Guide

The assignments in COMP6080 all have a portion of their marks allocated to code style. As such, it is highly recommended for students to have a read through this style guide. - This page outlines the conventions we will be following throughout the course. It incorporates guidelines derived from standard style guides plus feedback and inquiries accumulated from previous cohorts. - We follow the W3 schools style guide for HTML as a base. Here are a few notable guidelines that are often asked about or forgotten. - - + Below is our style guide for COMP6080 for writing good HTML. For anything not mentioned here, refer to the W3 schools style guide. + + Please also note that you should refer to the marking criteria too that's attached with each Assignment. + + +
-
📜 1.1. Casing & Quotation
+
{emoji} 1.1. Casing & Quotation
Unless specified otherwise, all tags and its attributes should be written in lowercase. The attribute values should always be in quotation marks, as well as no spaces between the equal sign and the value. {
-
📜 1.2. Indentation
+
{emoji} 1.2. Indentation
As long as you are consistent, you can use 2 or 4 space indentation. However, as there will be many levels of indentation, you should indent with 2 spaces in HTML as opposed to the usual 4 spaces. Each HTML tag should be indented with respect to its parent tag, with the opening and closing tag being on the same level of indentation (unless it is on the same line).

Hello @@ -73,8 +81,8 @@ const StyleHtml = ({}) => {

` ]} /> - @@ -127,7 +135,7 @@ const StyleHtml = ({}) => {
-
📜 1.3. Repetition
+
{emoji} 1.3. Repetition
Some repetitions are okay when writing HTML for the first assignment. For example, this is okay: @@ -143,11 +151,9 @@ const StyleHtml = ({}) => {
`} - In future assignments in the course when you are introduced to better methodologies, you should not repeat your code (See the [JavaScript Modularisation](#js-modularisation) and [ReactJS Modularisation](#jsx-modularisation) section). -
-
📜 1.4. General HTML Structure
+
{emoji} 1.4. General HTML Structure
All HTML files should not be missing the following starting code @@ -191,11 +197,12 @@ const StyleHtml = ({}) => {
-
📜 1.5. Use Appropriate Semantic Tags
+
{emoji} 1.5. Use Appropriate Semantic Tags
When deciding on which tag to use to contain your page elements, you should use the appropriate tag whenever you can. Not only will this provide clearer structural meaning to your page, but it will make your file less complicated and give screen readers an easier time. Reserve div tags for grouping related page elements or for styling purposes. Welcome to my page!
@@ -208,6 +215,7 @@ const StyleHtml = ({}) => { /> @@ -231,11 +239,89 @@ const StyleHtml = ({}) => { ]} /> -
+ +
Welcome to my Awesome Website!
+
+
+ + + + +
+
+ -
📜 1.6. The Style Attribute
- You should always try and avoid inline/internal styling and keep all CSS styles in a separate .css file - stick to external styling. See below under the [CSS section](#css-external-spreadsheet) for reasons why. +
+
+
About Us
+
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
+
+
+
+
Our Services
+ +
+
Service 1
+
We can paint your car
+
+
+
Service 2
+
We can repair your car
+
+
+
+
+
© 2023 Awesome Website. Do not steal!
+
` + ]} + goods={[ +`
+

Welcome to my Awesome Website!

+ +
+ +
+
+

About Us

+

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

+
+
+
+

Our Services

+ +
+

Service 1

+

We can paint your car

+
+
+

Service 2

+

We can repair your car

+
+
+
+ +
+

© 2023 Awesome Website. Do not steal!

+
` + ]} + /> + +
+ +
{emoji} 1.6. The Style Attribute
+ You should always try and avoid inline/internal styling and keep all CSS styles in a separate .css file - stick to external styling. Refer to the CSS section for reasons why. {
-
📜 1.7. The Script Tag
+
{emoji} 1.7. The Script Tag
Likewise to the previous guideline, you should not be writing internal JavaScript code - keep them separate. This is to keep your code modularised and prevent your html file from being extraordinarily large. @@ -322,21 +408,32 @@ document.getElementById('main-btn').addEventListener('click', changeText);
-
📜 1.8. Image Attributes
+
{emoji} 1.8. Image Attributes
All images should have alt attributes for accessibility/screen readers, search engine optimization and in case the image does not load properly. + You also need to give good alt tags. Good alt tags have the following traits: +
    +
  • Descriptive: Should accurately describe the content of the image.
  • +
  • Concise: All alt tags should be to the point. You also don't need to say that the image is an image since that's a given.
  • +
+ Regarding images used for decoration and do not convey anything meaningful, you can just leave the alt tag empty so it doesn't get picked up by SEO/assistive technology. i.e., alt="" can be used for an image of a tiny arrow used to decorate text. +Object` + ]} goods={[ -`Team of people discussing` +`Red apple +Aluminium can of soda` ]} medium />
-
📜 1.9. img tag VS. background-image
+
{emoji} 1.9. img tag VS. background-image
Do not mix up the img tag and background-image. @@ -358,13 +455,12 @@ document.getElementById('main-btn').addEventListener('click', changeText); On the other hand, a {''} tag is for setting an image in the foreground and is used for salient images (i.e., nothing is obscuring it and is part of the website flow/layout). These are used for displaying content that is to be consumed by users. - Getting these mixed up will impact: -
    -
  • Accessibility - Screen readers can not detect background images and background images do not have alt text.
  • -
  • Search Engine Optimisation - Search Engines use alt tags to detect images and display it in searches.
  • -
  • Interactions - Users can not interact with background images (i.e., copy or download the image).
  • -
- + Getting these mixed up will impact: +
    +
  • Accessibility - Screen readers can not detect background images and background images do not have alt text.
  • +
  • Search Engine Optimisation - Search Engines use alt tags to detect images and display it in searches.
  • +
  • Interactions - Users can not interact with background images (i.e., copy or download the image).
  • +
-
📜 1.10. Unique IDs
+
{emoji} 1.10. Unique IDs
Do not use the same ID on multiple HTML tags. IDs are meant to be unique identifiers and by using it on multiple tags, the behaviour would be undefined and is up to the browser you are using. Shrine Map` ]} /> - + +
+
{emoji} 1.11. Spamming line break tags and {' '}
+ Rather than using a bunch of {'
'}
tags to create spacing, you should use margins instead. This also includes to spamming {' '}. + + +

Welcome!

+
+
+
+

🎨       Art never finishes, it only stops moving...

+` + ]} + goods={[ + ` +.art-title { + margin-bottom: 40px; +} + +.sub-heading-container { + display: flex; + justify-content: space-between; + width: 100%; +} + + +

Welcome!

+
+

🎨

+

Art never finishes, it only stops moving...

+
+` + ]} + /> + {'
'}
tags are okay if you need something to start on a new line. + Enter your street: +
+` + ]} + /> + +
+
{emoji} 1.12. No redundant attributes on tags
+ Don't have attributes attached to tags that don't serve a purpose. + + +
+ +` + ]} + /> + +
+
{emoji} 1.13. Avoid having multiple separate versions of a webpage component
+ A lot of students for Assignment 1 Task 3 would create two or more separate variations of a webpage's component and hide/show them depending on the viewport. This is not good practice because of the following: + +
    +
  • Hard to maintain: If you wanted to make an edit to that part of the website, you'd need to make changes to multiple separate places in your code.
  • +
  • Bloats DOM: {'Even if one of the version\'s display is set to '}none{', it still exists on the DOM. As such, the DOM will have unnecessary elements in it, which can lead to several performance and memory-related issues that can negatively impact the user experience (such as longer First Contentful Paint (FCP) times).'}
  • +
+ + For the example below, we want to create two versions of a layout, one vertical and one horizontal. The layout will be vertical if the viewport becomes small enough and becomes horizontal if the viewport is big enough. + + + +.small-display { + display: initial; +} + +.big-display { + display: none; +} + +.small-article { + width: 100%; + display: block; +} + +.big-article { + width: 250px; + display: inline-block; +} + +@media (min-width: 640px) { + .small-display { + display: none; + } + + .big-display { + display: initial; + } +} + + +
+ + +
+ +
+ + +
+` + ]} + goods={[ + ` + +.flex-container { + display: flex; + flex-wrap: wrap +} + +.article-card { + width: 250px; +} + + +
+ + +
+` + ]} + /> + +
+
{emoji} 1.14. Remove blocks of commented out code
+ While it may be useful during debugging, having a bunch of commented out code around will make your code less readable. + + +

+ Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse sed enim mollis, consectetur mauris vel, auctor sem. Nulla aliquam maximus elit vel hendrerit. +

+ +
+

I am trying out different layouts...

+

+ Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec eu odio eu lacus scelerisque ultrices ut quis eros. Maecenas dictum fermentum mi eget congue. +

+
--> + +
+

Hello!

+

I have gained sentience

+
+` + ]} + goods={[ + `
+

Hello!

+

I have gained sentience

+
+` + ]} + /> + + ); }; diff --git a/frontend/src/page/Style/StyleJavascript.jsx b/frontend/src/page/Style/StyleJavascript.jsx index 55d7aba..0e2f49d 100644 --- a/frontend/src/page/Style/StyleJavascript.jsx +++ b/frontend/src/page/Style/StyleJavascript.jsx @@ -6,37 +6,42 @@ import { Body, H3, H5, HR, Code, Example } from '../../component/StyleComponents const StyleJavascript = ({}) => { + const emoji = '🔧'; + return ( <> +

{emoji} 3. JavaScript

-

🔧 3. JavaScript

- - The assignments in COMP6080 all have a portion of their marks allocated to code style. As such, it is **highly** recommended for students to have a read through this style guide. - This page outlines the conventions we will be following throughout the course. It incorporates guidelines derived from standard style guides plus feedback and inquiries accumulated from previous cohorts. - JavaScript shares a lot of the style principles found in other languages. We follow the [W3 schools style guide for JavaScript](https://www.w3schools.com/js/js_conventions.asp) as a base. Here are a few notable guidelines that are often asked about or forgotten. - + The assignments in COMP6080 all have a portion of their marks allocated to code style. As such, it is highly recommended for students to have a read through this style guide. + + + Below is our style guide for COMP6080 for writing good Javascript. For anything not mentioned here, refer to the W3 schools style guide. + - + Please also note that you should refer to the marking criteria too that's attached with each Assignment. + +
-
🔧 3.1. Casing & Quotation
+
{emoji} 3.1. Casing & Quotation
- You may use camelCase, snake_case etc. As long as you are **consistent**. camelCase is what most JavaScript developers use. Do not use PascalCase, as that is normally reserved for React components. + You may use camelCase, snake_case etc. As long as you are consistent. camelCase is what most JavaScript developers use. Do not use PascalCase, as that is normally reserved for React components. { const Range = maxInt - minInt + 1; // Generate a random number within the range - return Math.floor(Math.random() * Range) + minInt;` + return Math.floor(Math.random() * Range) + minInt; +}` ]} goods={[ `const randomNumberGenerator = (minInt, maxInt) => { @@ -69,11 +75,11 @@ const StyleJavascript = ({}) => { ]} /> - You may use either single (') or double (") quotations as long as you're **consistent** with which you choose. + You may use either single (') or double (") quotations as long as you're consistent with which you choose.
-
🔧 3.2. Indentation
+
{emoji} 3.2. Indentation
As long as you're consistent, you may use 2-space or 4-space indentation in JavaScript files. We recommend 2-space. Generally, we increase the indentation level everytime we use an opening brace {'{'} and decrease it when we use a closing brace {'}'}. @@ -100,7 +106,7 @@ dude.age++;
-
🔧 3.3. Comments
+
{emoji} 3.3. Comments
Include comments to explain the purpose, functionality, and important details of your code. Comments help you and others understand your code easily, which is especially important in the pair assignments. @@ -140,11 +146,11 @@ const groupArrayElements = (array, size) => {
-
🔧 3.4. Modularisation
+
{emoji} 3.4. Modularisation
If you have a function that is becoming very bloated and has multiple levels of indentation, chances are that it is not modular enough. Break down your code into smaller, modular functions to promote reusability, DRY principle and makes code maintenance more manageable. - In the below example, it is better to extract the fetch into separate module named appropriately named api.js or another appropriate name of your choosing. This module would be dedicated to handling API requests. The sendReq function then encapsulates the logic for making a fetch request, handling the response, and returning the parsed JSON data. This way, the logic of making API calls can be reused again and again without needing to write fetch and all the other logic multiple times. + In the below example, it is better to extract the fetch into separate module named api.js or another appropriate name of your choosing. This module would be dedicated to handling API requests. The sendReq function then encapsulates the logic for making a fetch request, handling the response, and returning the parsed JSON data. This way, the logic of making API calls can be reused again and again without needing to write fetch and all the other logic multiple times. {
-
🔧 3.5. Use External Files
+
{emoji} 3.5. Use External Files
You should not be writing JavaScript in a html file. This is to keep your code modularised and prevent your html file from being extraordinarily large. @@ -296,7 +302,7 @@ document.getElementById('main-btn').addEventListener('click', changeText);
-
🔧 3.6. Avoid converting Text to DOM Nodes (innerHTML, outerHTML, DOMParser etc.)
+
{emoji} 3.6. Avoid converting Text to DOM Nodes (innerHTML, outerHTML, DOMParser etc.)
Do not use methods that convert text to DOM nodes (such as innerHTML, outerHTML, DOMParser etc.). (Please see this blog post as to why these methods are highly discouraged). @@ -325,40 +331,66 @@ container.appendChild(buttonElement);`
-
🔧 3.7. Arrow functions over Regular functions
+
{emoji} 3.7. Arrow functions over Regular functions
- From week 4 and onwards, you should use a = () => {} function definitions over function a() {} in all instances. This is mainly because modern online sample code uses arrow functions instead and also looks much neater and less verbose as seen in the below examples. + You should use {'() => {}'} function definitions over {'function () {}'} in most cases, especially with callbacks. This is mainly because it's syntax is shorter and sweeter than regular functions. + However, if you need a dynamic execution context, then you may use a traditional function. { -if (arr.length === 0) return 0; + if (arr.length === 0) return 0; -return arr.reduce((accumulator, currVal) => (accumulator + currVal), 0) / arr.length; + return arr.reduce((accumulator, currVal) => (accumulator + currVal), 0) / arr.length; }` ]} /> - As a side note, there is a subtle difference between the two. Regular functions has a dynamic this whereas Arrow functions has a lexical this. This distinction falls outside the scope of this course, and you should not need to worry about it in the assignments. (In other words, stick to Arrow Functions for this course). + { + // 'this' is inherited from the lexical context (in this case it's the global context) + // rather than the superhero object. Thus, this will print undefined + console.log(this.catchphrase); + }, +} + +superhero.shout();` + ]} + goods={[ +`const superhero = { + catchphrase: 'Hello!', + shout: function () { + // 'this' will now refer to 'superhero' and so will log 'Hello!' + console.log(this.catchphrase); + }, +} - If you wish, you may read more about it here. +superhero.shout();` + ]} + />
-
🔧 3.8. Variable naming convention
+
{emoji} 3.8. Variable naming convention
All variables and function names should be named appropriately. The name should be meaningful enough that it is "self-documenting" (i.e., explains what it is used for). @@ -376,7 +408,7 @@ let clickCounter = 0;`
-
🔧 3.9. Variable declaration
+
{emoji} 3.9. Variable declaration
Never use var - stick to either let or const. In most cases, const is enough for what you need to do in JavaScript/React web development. @@ -390,25 +422,26 @@ let clickCounter = 0;` lang="javascript" bads={[ `var fooFunction = () => { -var loopAmount = 10; + var loopAmount = 10; -for (var i = 0; i < loopAmount; i++) { - console.log(i); -} + for (var i = 0; i < loopAmount; i++) { + console.log(i); + } }` ]} goods={[ `const fooFunction = () => { -const loopAmount = 10; + const loopAmount = 10; -for (let i = 0; i < loopAmount; i++) { - console.log(i); -} + for (let i = 0; i < loopAmount; i++) { + console.log(i); + } }` ]} /> -
🔧 3.10. Strict Equality
+
+
{emoji} 3.10. Strict Equality
Stick to using === (strict equality) over == (loose/abstract equality) in almost all instances. @@ -418,15 +451,15 @@ for (let i = 0; i < loopAmount; i++) { lang="javascript" bads={[ `console.log(0 == false); // Will print true, which might not be what you need - console.log(1 == '1'); // true - console.log(0 == ''); // true - console.log(42 == [42]); // true` +console.log(1 == '1'); // true +console.log(0 == ''); // true +console.log(42 == [42]); // true` ]} goods={[ `console.log(0 === false); // Will print false, which is correct since 0 and false are not the same. - console.log(1 === '1'); // false - console.log(0 === ''); // false - console.log(42 === [42]); // false` +console.log(1 === '1'); // false +console.log(0 === ''); // false +console.log(42 === [42]); // false` ]} /> @@ -436,19 +469,19 @@ for (let i = 0; i < loopAmount; i++) { lang="javascript" bads={[ `const foo = null; - console.log(foo === null) // Prints true - console.log(foo === undefined) // Prints false` +console.log(foo === null) // Prints true +console.log(foo === undefined) // Prints false` ]} goods={[ `const foo = null; - console.log(foo == null) // Prints true - console.log(foo == undefined) // Prints true` +console.log(foo == null) // Prints true +console.log(foo == undefined) // Prints true` ]} />
-
🔧 3.11. Semicolons
+
{emoji} 3.11. Semicolons
While JavaScript does not need ; at the end of each simple statement, it is still considered the batter practice to include them for code clarity. This guideline won't be enforced strictly. @@ -474,7 +507,7 @@ const fooObj = {
-
🔧 3.12. Whitespace
+
{emoji} 3.12. Whitespace
Using whitespace effectively will improve your code's readability, which is especially important when working in a team. This means leaving space around operators, after commas, and between logical sections of code. @@ -491,6 +524,33 @@ const fooObj = { let bar = 0; bar += x + y + z; +}` + ]} + /> + +
+
{emoji} 3.13. Remove blocks of commented out code
+ While it may be useful during debugging, having a bunch of commented out code around will make your code less readable. + + { + /* + if (target < lowerBound) { + return false; + } else if (target > upperBound) { + return false; + } else { + return true; + } + */ + return (target > lowerBound) && (target < upperBound); +}` + ]} + goods={[ + `const isWithinBounds = (lowerBound, upperBound, target) => { + return (target > lowerBound) && (target < upperBound); }` ]} /> diff --git a/frontend/src/page/Style/StyleReact.jsx b/frontend/src/page/Style/StyleReact.jsx index 567bff9..1c14437 100644 --- a/frontend/src/page/Style/StyleReact.jsx +++ b/frontend/src/page/Style/StyleReact.jsx @@ -3,33 +3,42 @@ import React from 'react'; import makePage from '../../component/makePage'; import { Body, H3, H5, HR, Code, Example } from '../../component/StyleComponents'; - +import EslintError from '../../asset/style/eslint-error.png'; +import EslintSuccess from '../../asset/style/eslint-success.png'; +import Box from '@mui/material/Box'; const StyleReact = ({}) => { + const emoji = '⚛️'; + return ( <> - -

⚛️ 4. ReactJS

+

{emoji} 4. ReactJS

The assignments in COMP6080 all have a portion of their marks allocated to code style. As such, it is highly recommended for students to have a read through this style guide. - This page outlines the conventions we will be following throughout the course. It incorporates guidelines derived from standard style guides plus feedback and inquiries accumulated from previous cohorts. - We follow the Airbnb style guide for ReactJS as a guideline. It is a very strict style guide so we don't enforce every principle, but do take it's guidance generally. - + Below is our style guide for COMP6080 for writing good React code. For anything not mentioned here, refer to the Airbnb style guide for ReactJS. It is a very strict style guide so we don't enforce every principle, but do take it's guidance generally. + + + All guidelines mentioned in the Javascript section also applies here. + + + Please also note that you should refer to the marking criteria too that's attached with each Assignment. + +
-
⚛️ 4.1. Casing & Quotation
+
{emoji} 4.1. Casing & Quotation
Components that you have made should follow PascalCasing. @@ -55,15 +64,16 @@ const my-component = () => { You may use either single (') or double (") quotations as long as you're consistent with which you choose. - JavaScript casing rules applies to other variables. See the above [JavaScript section](#js-casing) for more information. + Javascript casing rules applies to other variables.
-
⚛️ 4.2. Comments (And examples of E2E/Component testing)
+
{emoji} 4.2. Comments (And examples of E2E/Component testing)
Use comments to explain what your components are for and what they do. This is not only for you, but also for your group partner. Additionally, they are also very important when describing the test cases you have written for component and E2E testing. - Note that you do not need to follow the above verbatim - It is to just give a guide of good commenting habits. - { @@ -164,9 +173,8 @@ describe('Login functionality', () => { ]} /> - Note that you do not need to follow the above verbatim - It is to just give a guide of good commenting habits. - {
-
⚛️ 4.3. Modularisation
+
{emoji} 4.3. Modularisation
Modularisation is an essential part of building scalable React applications (or any project). If you find your components becoming extremely bloated with loads of hooks in it with deep nesting (i.e., not shallow), chances are that it can be broken into smaller components. Each component should ideally have a single responsibility so it is much easier to perform component testing. - It is also best practice to limit it to **one component per file** when possible, with the filename being the component's name. This is for easier readability and easier time locating where a component is written. If you find a file housing many components and those components are being used by other components, then that is a sign to split it up. + It is also best practice to limit it to one component per file when possible, with the filename being the component's name. This is for easier readability and easier time locating where a component is written. If you find a file housing many components and those components are being used by other components, then that is a sign to split it up. {
-
⚛️ 4.4. ESLint
+
{emoji} 4.4. ESLint
- You'll be given a pre-setup ESLint with your React Assignment. Do not ignore the errors and warnings it outputs, as it will point out little style rules you have not followed. + You'll be given a pre-setup ESLint with your React Assignment. Do not ignore the errors and warnings it outputs, as it will point out little practices you haven't followed. 🔴Bad - ESLint Error - + +
🟢Good - ESLint Success + Note that the ESLint compiler errors shown above was using the configuration from 22T3. Please use the configuration given to you in your Assignment.
-
⚛️ 4.5. The Document Keyword
+
{emoji} 4.5. The Document Keyword
When you're working on a React project, it's highly recommended avoid the `document` keyword, which you may have used in previous assignments. This is because React already manages DOM manipulation for you through its virtual DOM. Using this keyword also hinders your components reusability (as seen below). By relying on the `document` keyword, you're overlooking the innovative features that make React so widely used. @@ -376,15 +384,14 @@ const HoverTest = () => {
-
⚛️ 4.6. Functional VS. Class Components
+
{emoji} 4.6. Functional VS. Class Components
- Stick to Functional components rather than Class components. This is because, but not limited to: -
    -
  • Simplicity - It is easier to test and understand Functional components as you won't need to worry about complex concepts such as lifecycle methods or `this` keyword.
  • -
  • Modernity - With Functional components being the most popular, there is more resources online to help you out. There are also a lot more libraries available for Functional components compared to Class components.
  • -
  • Hooks - These simplify state management, handling side effects and the lifecycle functionalities in components without the need of classes.
  • -
- + Stick to Functional components rather than Class components. This is because, but not limited to: +
    +
  • Simplicity - It is easier to test and understand Functional components as you won't need to worry about complex concepts such as lifecycle methods or `this` keyword.
  • +
  • Modernity - With Functional components being the most popular, there is more resources online to help you out. There are also a lot more libraries available for Functional components compared to Class components.
  • +
  • Hooks - These simplify state management, handling side effects and the lifecycle functionalities in components without the need of classes.
  • +
-
⚛️ 4.7. CSS and React
- - When it comes to CSS, do not use universal CSS (i.e., importing a `.css` file into a React component). Likewise, you should also avoid inline styling. See the following lectures for more information: - - - - The better practices include: -
    -
  • CSS Modules (generally not recommended, but still OK)
  • -
  • Using utility class frameworks including but not limited to: -
      -
    • Tailwind CSS
    • -
    • Bootstrap/React-Bootstrap
    • -
    -
  • -
  • CSS-in-JS methods including but not limited to: -
      -
    • Styled Components to create your own custom CSS
    • -
    • Material UI (MUI) sx and styling options
    • -
    -
  • -
- +
{emoji} 4.7. CSS and React
+ + When it comes to CSS, do not use universal CSS (i.e., importing a `.css` file into a React component). Likewise, you should also avoid inline styling. See the following lectures for more information: + + + The better practices include: +
    +
  • CSS Modules (generally not recommended, but still OK)
  • +
  • Using utility class frameworks including but not limited to: +
      +
    • Tailwind CSS
    • +
    • Bootstrap/React-Bootstrap
    • +
    +
  • +
  • CSS-in-JS methods including but not limited to: +
      +
    • Styled Components to create your own custom CSS
    • +
    • Material UI (MUI) sx and styling options
    • +
    +
  • +
The following examples uses MUI v5. We highly recommend exploring [MUI's documentation](https://mui.com/material-ui/getting-started/overview/) to maximise the utility of these practices. Also, you are not just restricted to MUI; feel free to explore other libraries that offer similar functionality.