Skip to content
Open
Show file tree
Hide file tree
Changes from 14 commits
Commits
Show all changes
33 commits
Select commit Hold shift + click to select a range
ad2404b
update
ThokozaniNqwili Aug 11, 2023
575b160
update
ThokozaniNqwili Aug 11, 2023
038f93e
update
ThokozaniNqwili Aug 15, 2023
30785ac
update
ThokozaniNqwili Aug 18, 2023
96682be
update
ThokozaniNqwili Aug 23, 2023
e287191
update
ThokozaniNqwili Aug 25, 2023
b4e7f57
format change
ThokozaniNqwili Aug 28, 2023
1f6c3a3
review changes
ThokozaniNqwili Aug 28, 2023
eef44e5
update requested changes
ThokozaniNqwili Aug 29, 2023
097c7c1
update requested changes, index and style
ThokozaniNqwili Aug 29, 2023
3e38dff
update search
ThokozaniNqwili Aug 29, 2023
3c23cb2
first push 30/08
ThokozaniNqwili Aug 30, 2023
d8792ca
onclick
ThokozaniNqwili Aug 30, 2023
55837eb
last push 30/08
ThokozaniNqwili Aug 30, 2023
10b0d40
09/05
ThokozaniNqwili Sep 5, 2023
11ea6c4
update
ThokozaniNqwili Sep 5, 2023
2b53415
update
ThokozaniNqwili Sep 5, 2023
c15fe4c
09/06
ThokozaniNqwili Sep 6, 2023
90d744b
09/08
ThokozaniNqwili Sep 8, 2023
2361a84
11/09
ThokozaniNqwili Sep 11, 2023
eeb1c81
12/09
ThokozaniNqwili Sep 12, 2023
9580c60
15/09
ThokozaniNqwili Sep 15, 2023
cc6a0dd
15/09
ThokozaniNqwili Sep 15, 2023
f18872b
18/09
ThokozaniNqwili Sep 18, 2023
24aba76
18/09
ThokozaniNqwili Sep 18, 2023
2e7e23d
26/09
ThokozaniNqwili Sep 26, 2023
0d8a9d4
update
ThokozaniNqwili Sep 26, 2023
2313df4
update
ThokozaniNqwili Sep 27, 2023
817249c
09/28
ThokozaniNqwili Sep 28, 2023
cb7c3ea
10/02
ThokozaniNqwili Oct 2, 2023
f8204e9
updates
ThokozaniNqwili Oct 2, 2023
249611b
03/10
ThokozaniNqwili Oct 3, 2023
7a4b0e2
04/10
ThokozaniNqwili Oct 5, 2023
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
218 changes: 218 additions & 0 deletions app.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,218 @@
import { ajax, css } from "jquery";
let firstNumber = 0;
let lastNumber = 0;
let backend: string = "http://localhost:2050";

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Try for 2 global variables


window.onload = () => {
createTable();
displayRecords();
$('#btnSearch').on("click", async (event) => {
event.preventDefault();
let inputValue = $('#searchInput').val() as number;
await updateRecordsAndResize(inputValue); // calls to calculate the range once button is clicked
});
$('#closeModalBtn').on("click", () => {
$('.content').empty()
$('.modal').css('display', 'none') // closes modal
});
$('.arrow-right').on('click', () => {
rightArrow();
});
$('.arrow-left').on('click', () => {
leftArrow();
});
$('#searchInput').on('keydown', (event) => {
if (event.key === 'e' || event.key === 'E') {
event.preventDefault();
};
});
$('#searchInput').on('input', (event) => {
const inputValue = $('#searchInput').val() as string;
if (inputValue.includes('.')) {
$('#searchInput').val(inputValue.replace('.', ' '));
};
});
};

async function fetchRecordCount(): Promise<number> {
try {
const response = await fetch(`${backend}/recordCount`);
if (!response.ok) {
throw new Error('Failed to fetch record count');
}
return response.json()
} catch (error) {
throw new Error('Error fetching the record count')
};
};

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No need for ; after declaring a function


async function fetchColumns(): Promise<string[]> {
try {
const response = await fetch(`${backend}/columns`);
if (!response.ok) {
throw new Error('Failed to fetch columns');
}
const jsonText = await response.text();
const columns: string[] = await JSON.parse(jsonText);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
const jsonText = await response.text();
const columns: string[] = await JSON.parse(jsonText);
const columns: string[] = JSON.parse(response.text());

return columns
} catch (error) {
throw new Error('Error fetching columns')
};
};

async function createTable() {
try {
const columns = await fetchColumns();
for (const col of columns) {
$(".head").append(`<th>${col}</th>`);
};
} catch (error) {
throw new Error('Error creating table');
};
};

function adjustRowsByScreenHeight() {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

no need to use the function keyword and provide a return type

const screenHeight = window.innerHeight;
const availableHeight = screenHeight - 105; // subtracts the space used from the screeen
let rowHeight = 35;
if (availableHeight <= 0) {
return 0;
} else {
let maxRows = Math.floor(availableHeight / rowHeight);
return maxRows;
};
};

$(window).on('resize', async () => {
let resizeTimeout: number;
resizeTimeout = setTimeout(async () => {
$('#loader').show()
await displayRecords()
let inputValue = $('#searchInput').val(); // priotizes the search input value if available
if (inputValue !== '') {
await updateRecordsAndResize(Number(inputValue))
}
$('#loader').hide();
}, 500);
});

async function fetchRecords(from: number, to: number): Promise<any[]> {
try {
const response = await fetch(`${backend}/records?from=${from}&to=${to}`);
if (!response.ok) {
throw new Error("Sorry, there's a problem with the network");
}
return response.json();
} catch (error) {
throw new Error('Error fetching records from server');
};

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No need for the async anymore, and can remove the try and catch

Suggested change
try {
const response = await fetch(`${backend}/records?from=${from}&to=${to}`);
if (!response.ok) {
throw new Error("Sorry, there's a problem with the network");
}
return response.json();
} catch (error) {
throw new Error('Error fetching records from server');
};
return fetch(`${backend}/records?from=${from}&to=${to}`)
.then(res => {
if (!res.ok) {
throw "Sorry, there's a problem with the network";
}
return res.json();
}).catch(err => {
throw 'Error fetching records from server ' + err;
});

};

async function displayRecords(): Promise<void> {
try {
$('#loader').show();
let count = await fetchRecordCount() - 1;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You shouldn't have to make the backend calls the whole time, call once and save then in variables to be reused

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

still not done

let calculatedRows = adjustRowsByScreenHeight();
const inputValue = $('#searchInput').val() as number;
if (calculatedRows === 0) {
lastNumber = firstNumber
} else if (firstNumber < 0) {
firstNumber = 0;
lastNumber = firstNumber + (calculatedRows - 1);
} else {
lastNumber = firstNumber + (calculatedRows - 1);
};
let records;
if (lastNumber <= count && lastNumber >= 0) {
records = await fetchRecords(firstNumber, lastNumber);
$('#page').empty();
$('#page').append(`Showing record: ${firstNumber} - ${lastNumber}`); // changes the record range showing
$('#loader').hide();
} else {
firstNumber = count - (calculatedRows - 1);
lastNumber = count;
records = await fetchRecords(firstNumber, count);
$('#page').empty();
$('#page').append(`Showing record: ${firstNumber} - ${count}`);
$('#loader').hide();
};
const tbody = $("tbody");
tbody.empty();
for (const record of records) {
$("tbody").append(`<tr class="row"></tr>`); // creates row for each record
const lastRow = $(".row:last");
for (const value of record) {
lastRow.append(`<td>${value}</td>`); // assign each record to their column in a specified row
}
if (record.includes(inputValue)) {
lastRow.css('background-color', '#DDC0B4'); // highlights the searched row
}
$("tbody").append(lastRow);
}
} catch (error) {
throw new Error('Error displaying records');
};
};

async function updateRecordsAndResize(inputValue: number) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please add a return type to this function.

let count = await fetchRecordCount() - 1;
if (inputValue < 0 || inputValue > count) { // check if the search input
$('.modal').css('display', 'block');//opens modal if search input is not within range
$('.content').append(`<p>${inputValue} is not a number within the range.Please try a different number</p>`);
$('#searchInput').val(''); // empties search bar
return;
};
let calculatedRows = adjustRowsByScreenHeight();
const halfRange = Math.floor(calculatedRows / 2); // divides the calculated max rows in half
firstNumber = Math.max(0, inputValue - halfRange);
lastNumber = Math.min(count, firstNumber + (calculatedRows - 1));
await displayRecords();
};

async function rightArrow(): Promise<void> {
$('.arrow-right').css('display', 'none')
$('#searchInput').val('');
const lastRow = document.querySelector("#recordsTable tbody .row:last-child"); // retrieves the last row
let count = await fetchRecordCount() - 1;
if (lastRow) { // checks if the last row exists
const cells = lastRow.querySelectorAll("td");
const lastRecord = [];
for (const cell of Array.from(cells)) {
lastRecord.push(cell.textContent || "");
};
const lastID = parseFloat(lastRecord[0]); // determines te value in the last row
if (0 <= lastID && lastID <= (count)) { // checks if the last value is within range
const tbody = $("tbody");
tbody.empty(); // empties the table
firstNumber = lastID + 1; // calculates the first number of the page
let calculatedRows = adjustRowsByScreenHeight();
lastNumber = firstNumber + (calculatedRows - 1);// calculates the first number of the page
await displayRecords(); // display the new records
$('.arrow-right').css('display', 'inline-block')
};
};
};

async function leftArrow(): Promise<void> {
$('.arrow-left').css('display', 'none')
$('#searchInput').val('');
let count = await fetchRecordCount() - 1;
const firstRow = document.querySelector("#recordsTable tbody .row:first-child"); // retrieves the first row
if (firstRow) { // checks if the first row exists
const cells = firstRow.querySelectorAll("td");
const firstRecord = [];
for (const cell of Array.from(cells)) {
firstRecord.push(cell.textContent || "");
};
const firstID = parseFloat(firstRecord[0]); // determines te value in the first row
if (0 <= firstID && firstID <= (count)) { // checks if the first value is within range
const tbody = $("tbody");
tbody.empty(); // empties the table
const calculatedRows = adjustRowsByScreenHeight();
lastNumber = firstID - 1; // calculates the last number of the page
firstNumber = lastNumber - (calculatedRows - 1); // uses the last number to calculate
await displayRecords();
$('.arrow-left').css('display', 'inline-block')
};
};
};
32 changes: 30 additions & 2 deletions index.html
Original file line number Diff line number Diff line change
@@ -1,13 +1,41 @@
<!DOCTYPE html>
<html>

<head>
<title>JS Onboard Project</title>
<script type="text/javascript" charset="utf-8" src="third_party/jquery-2.0.3.min.js"></script>
<link rel="stylesheet" href="style.css">
<script src="/app.js" ></script>
</head>

<body>
<p>Hello</p>
<div id="loader"></div>
<h1 class="heading">OnBoard-Javascript</h1>
<div id="modal" class="modal">
<div class="modal-content">
<span id="closeModalBtn" class="close">&times;</span>
<p class="content"></p>
</div>
</div>
<div class="search-container">
<form id="searchForm">
<input type="number" id="searchInput" placeholder="Search.." name="search" autocomplete="off">
<button id="btnSearch" class="btnSearch" type="submit" >Submit</button>
</form>
</div>
<div class="showRecords">
<button class="arrow-right"></button>
<div id="page"></div>
<button class="arrow-left"></button>
</div>
<table id="recordsTable">
<thead>
<tr class="head">
</tr>
</thead>
<tbody>
</tbody>
</table>
</body>

</html>

27 changes: 27 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

27 changes: 27 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
{
"name": "onboard-javascript",
"version": "1.0.0",
"description": "This is a JavaScript project for all new developers to complete before venturing into our web frontend codebase.",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "tsc -p .",
"start": "npm run build -- -w"
},
"repository": {
"type": "git",
"url": "git+https://github.com/ThokozaniNqwili/onboard-javascript.git"
},
"author": "",
"license": "ISC",
"bugs": {
"url": "https://github.com/ThokozaniNqwili/onboard-javascript/issues"
},
"homepage": "https://github.com/ThokozaniNqwili/onboard-javascript#readme",
"devDependencies": {
"typescript": "^3.8.3"
},
"dependencies": {
"@types/jquery": "^3.5.16"
}
}
Loading