Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feat/lazy load discord groups page #852

Open
wants to merge 5 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
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
102 changes: 82 additions & 20 deletions __tests__/groups/group.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ const PAGE_URL = 'http://localhost:8000';
describe('Discord Groups Page', () => {
let browser;
let page;
jest.setTimeout(60000);
jest.setTimeout(120000);

beforeAll(async () => {
browser = await puppeteer.launch({
Expand Down Expand Up @@ -49,7 +49,10 @@ describe('Discord Groups Page', () => {
},
body: JSON.stringify(allUsersData.users[0]),
});
} else if (url === `${BASE_URL}/discord-actions/groups`) {
} else if (url.startsWith(`${BASE_URL}/discord-actions/groups`)) {
const urlParams = new URLSearchParams(url.split('?')[1]);
const latestDoc = urlParams.get('latestDoc');
const paginatedGroups = getPaginatedGroups(latestDoc);
interceptedRequest.respond({
status: 200,
contentType: 'application/json',
Expand All @@ -58,18 +61,7 @@ describe('Discord Groups Page', () => {
'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type, Authorization',
},
body: JSON.stringify(discordGroups),
});
} else if (url === `${BASE_URL}/discord-actions/groups?dev=true`) {
interceptedRequest.respond({
status: 200,
contentType: 'application/json',
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type, Authorization',
},
body: JSON.stringify(discordGroups),
body: JSON.stringify(paginatedGroups),
});
} else if (url === `${BASE_URL}/discord-actions/roles`) {
interceptedRequest.respond({
Expand All @@ -89,7 +81,6 @@ describe('Discord Groups Page', () => {
if (url === `${BASE_URL}/discord-actions/groups`) {
const postData = interceptedRequest.postData();
const groupData = JSON.parse(postData);
// discordGroups.push(groupData);
interceptedRequest.respond({
status: 201,
contentType: 'application/json',
Expand Down Expand Up @@ -134,7 +125,7 @@ describe('Discord Groups Page', () => {
}
});
await page.goto(`${PAGE_URL}/groups`);
await page.waitForNetworkIdle();
await page.waitForSelector('.card', { timeout: 5000 }); // Wait for the first batch of cards to load
});

afterAll(async () => {
Expand All @@ -147,7 +138,6 @@ describe('Discord Groups Page', () => {
});

test('Should display cards', async () => {
await page.waitForSelector('.card');
const cards = await page.$$('.card');

expect(cards.length).toBeGreaterThan(0);
Expand Down Expand Up @@ -239,11 +229,66 @@ describe('Discord Groups Page', () => {
const closeBtn = await groupCreationModal.$('#close-button');

await closeBtn.click();
await page.waitForTimeout(500); // Wait for modal to close
const groupCreationModalClosed = await page.$('.group-creation-modal');

expect(groupCreationModalClosed).toBeFalsy();
});

test('Should load more groups on scroll', async () => {
await page.goto(`${PAGE_URL}/groups`);
await page.waitForSelector('.card', { timeout: 10000 });

const initialGroupCount = await page.$$eval(
'.card',
(cards) => cards.length,
);

await page.evaluate(() => {
window.scrollTo(0, document.body.scrollHeight);
});

await page.waitForFunction(
(initialCount) => {
return document.querySelectorAll('.card').length > initialCount;
},
{ timeout: 60000 },
initialGroupCount,
);

const newGroupCount = await page.$$eval('.card', (cards) => cards.length);

expect(newGroupCount).toBeGreaterThan(initialGroupCount);
}, 120000);

test('Should stop loading more groups when all groups are loaded', async () => {
await page.goto(`${PAGE_URL}/groups`);
await page.waitForSelector('.card', { timeout: 5000 });

// Scroll to the bottom multiple times
for (let i = 0; i < 5; i++) {
await page.evaluate(() => {
window.scrollTo(0, document.body.scrollHeight);
});
await page.waitForTimeout(1000);
}

const finalGroupCount = await page.$$eval('.card', (cards) => cards.length);

// Scroll one more time
await page.evaluate(() => {
window.scrollTo(0, document.body.scrollHeight);
});
await page.waitForTimeout(1000);

const newFinalGroupCount = await page.$$eval(
'.card',
(cards) => cards.length,
);

expect(newFinalGroupCount).toBe(finalGroupCount);
});

test('Should display only specified groups when dev=true and name=<group-name> with different case', async () => {
const groupNames = 'fIrSt,DSA+COdInG';
await page.goto(`${PAGE_URL}/groups?dev=true&name=${groupNames}`);
Expand All @@ -255,15 +300,32 @@ describe('Discord Groups Page', () => {
);
});

expect(displayedGroups).toEqual(['First Daaa', 'DSA Coding Group']);
expect(displayedGroups).toContain('First Daaa');
expect(displayedGroups).toContain('DSA Coding Group');
});

test('Should display no group found div when no group is present', async () => {
await page.goto(`${PAGE_URL}/groups?dev=true&name=no-group-present`);
await page.waitForNetworkIdle();
await page.waitForSelector('.no-group-container', { timeout: 5000 });

const noGroupDiv = await page.$('.no-group-container');

expect(noGroupDiv).toBeTruthy();
});
});

// Helper function to simulate paginated data
function getPaginatedGroups(latestDoc) {
const pageSize = 18;
const startIndex = latestDoc
? discordGroups.groups.findIndex((g) => g.id === latestDoc) + 1
: 0;
const endIndex = startIndex + pageSize;
const groups = discordGroups.groups.slice(startIndex, endIndex);
const newLatestDoc = groups.length > 0 ? groups[groups.length - 1].id : null;

return {
message: 'Roles fetched successfully!',
groups,
newLatestDoc,
};
}
11 changes: 11 additions & 0 deletions groups/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,17 @@
</section>
<div class="group-container"></div>
</main>
<footer>
<p class="info-repo">
The contents of this website are deployed from this
<a
href="https://github.com/Real-Dev-Squad/website-dashboard"
target="_blank"
rel="noopener noreferrer"
>open sourced repo</a
>
</p>
</footer>
</body>
<div class="toast">
<div class="toast__message"></div>
Expand Down
149 changes: 121 additions & 28 deletions groups/script.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import {
addGroupRoleToMember,
createDiscordGroupRole,
getDiscordGroups,
getPaginatedDiscordGroups,
getUserGroupRoles,
getUserSelf,
removeRoleFromMember,
Expand Down Expand Up @@ -110,6 +111,8 @@ const handler = {
obj[prop] = value;
break;
case 'discordId':
case 'isLoading':
case 'hasMoreGroups':
obj[prop] = value;
break;
default:
Expand All @@ -123,10 +126,12 @@ const dataStore = new Proxy(
{
userSelf: null,
groups: null,
filteredGroupsIds: null,
filteredGroupsIds: isDev ? [] : null,
search: isDev ? getParamValueFromURL(QUERY_PARAM_KEY.GROUP_SEARCH) : '',
discordId: null,
isCreateGroupModalOpen: false,
isGroupCreationModalOpen: false,
isLoading: false,
hasMoreGroups: true,
},
handler,
);
Expand All @@ -147,6 +152,7 @@ const onCreate = () => {
throw new Error(data);
}
dataStore.userSelf = data;
isDev ? removeLoadingCards() : null;
removeLoadingNavbarProfile();
await afterAuthentication();
})
Expand All @@ -165,42 +171,129 @@ const onCreate = () => {
bindSearchInput();
bindSearchFocus();
bindGroupCreationButton();
isDev ? bindInfiniteScroll() : null;
};
const afterAuthentication = async () => {
renderNavbarProfile({ profile: dataStore.userSelf });
await Promise.all([getDiscordGroups(), getUserGroupRoles()]).then(
([groups, roleData]) => {
dataStore.filteredGroupsIds = groups.map((group) => group.id);
dataStore.groups = groups.reduce((acc, group) => {
let title = group.rolename
if (isDev) {
await Promise.all([loadMoreGroups(), getUserGroupRoles()]).then(
([groups, roleData]) => {
dataStore.filteredGroupsIds = groups.map((group) => group.id);
dataStore.groups = groups.reduce((acc, group) => {
let title = group.rolename
.replace('group-', '')
.split('-')
.map((word) => word.charAt(0).toUpperCase() + word.slice(1))
.join(' ');
acc[group.id] = {
id: group.id,
title: title,
count: group.memberCount,
isMember: group.isMember,
roleId: group.roleid,
description: group.description,
isUpdating: false,
};
return acc;
}, {});
if (isDev) {
dataStore.filteredGroupsIds = getDiscordGroupIdsFromSearch(
Object.values(dataStore.groups),
dataStore.search,
);
}
dataStore.discordId = roleData.userId;
},
);
} else {
await Promise.all([getDiscordGroups(), getUserGroupRoles()]).then(
([groups, roleData]) => {
dataStore.filteredGroupsIds = groups.map((group) => group.id);
dataStore.groups = groups.reduce((acc, group) => {
let title = group.rolename
.replace('group-', '')
.split('-')
.map((word) => word.charAt(0).toUpperCase() + word.slice(1))
.join(' ');
acc[group.id] = {
id: group.id,
title: title,
count: group.memberCount,
isMember: group.isMember,
roleId: group.roleid,
description: group.description,
isUpdating: false,
};
return acc;
}, {});
if (isDev) {
dataStore.filteredGroupsIds = getDiscordGroupIdsFromSearch(
Object.values(dataStore.groups),
dataStore.search,
);
}
dataStore.discordId = roleData.userId;
},
);
}
};
const loadMoreGroups = async () => {
if (dataStore.isLoading || !dataStore.hasMoreGroups) return;

dataStore.isLoading = true;
renderLoadingCards();

const newGroups = await getPaginatedDiscordGroups();

removeLoadingCards();
dataStore.isLoading = false;

if (newGroups.length === 0) {
dataStore.hasMoreGroups = false;
return;
}

dataStore.groups = {
...dataStore.groups,
...newGroups.reduce((acc, group) => {
acc[group.id] = {
id: group.id,
title: group.rolename
.replace('group-', '')
.split('-')
.map((word) => word.charAt(0).toUpperCase() + word.slice(1))
.join(' ');
acc[group.id] = {
id: group.id,
title: title,
count: group.memberCount,
isMember: group.isMember,
roleId: group.roleid,
description: group.description,
isUpdating: false,
};
return acc;
}, {});
if (isDev) {
dataStore.filteredGroupsIds = getDiscordGroupIdsFromSearch(
Object.values(dataStore.groups),
dataStore.search,
);
}
dataStore.discordId = roleData.userId;
},
);
.join(' '),
count: group.memberCount,
isMember: group.isMember,
roleId: group.roleid,
description: group.description,
isUpdating: false,
};
return acc;
}, {}),
};

dataStore.filteredGroupsIds = [
...dataStore.filteredGroupsIds,
...newGroups.map((group) => group.id),
];

return newGroups;
};

// Bind Functions

const bindInfiniteScroll = () => {
window.addEventListener('scroll', () => {
if (
window.innerHeight + window.scrollY >=
document.body.offsetHeight - 100
) {
loadMoreGroups();
}
});
};

const bindGroupCreationButton = () => {
const groupCreationBtn = document.querySelector('.create-group');

Expand Down
Loading