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

Improve the storybook #110

Merged
merged 2 commits into from
Nov 25, 2024
Merged
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
66 changes: 66 additions & 0 deletions krait-ui/.storybook/mocker/actions.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
import { cats, tableStructure } from './db.js';
import { getLinks, getMeta, paginate } from './pagination.js';
import { sort } from './sorting.js';

export const getTableStructure = (req) => {
return new Response(JSON.stringify(tableStructure), {
headers: {
'content-type': 'application/json',
},
});
};

export const getTableData = (req) => {
const url = new URL(req.url);

const tableData = sort({ data: cats, url });
const currentPage = parseInt(url.searchParams.get('page') ?? 1);
const ipp = parseInt(url.searchParams.get('ipp') ?? 30);
const [paginatedData, totalPages] = paginate(tableData, ipp, currentPage);
const pageLinks = getLinks(currentPage, url, totalPages);
const pageMeta = getMeta({
url,
currentPage,
totalPages,
totalRecords: tableData.length,
ipp,
pageLinks,
});

const data = {
data: {
...paginatedData,
},
links: {
...pageLinks,
},
meta: {
...pageMeta,
},
};
return new Response(JSON.stringify(data), {
headers: {
'content-type': 'application/json',
},
});
};

export const setItemsPerPage = (req) => {
return new Response();
};

export const reorderColumns = (req) => {
return new Response();
};

export const resizeColumns = (req) => {
return new Response();
};

export const sortColumns = (req) => {
return new Response();
};

export const hideColumns = (req) => {
return new Response();
};
47 changes: 47 additions & 0 deletions krait-ui/.storybook/mocker/db.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import { createColumn, createRandomCat } from './mocks.js';
import { faker } from '@faker-js/faker';

// Creating 100 cats 🐱
const cats = faker.helpers.multiple(createRandomCat, {
count: 100,
});

// Creating the initial table structure
const tableStructure = {
data: {
preview_configuration: {
uuid: '3b8dbcca-ee7f-41b9-bc20-2a5ab4e855fe',
table_name: 'cats-table',
sort_column: null,
sort_direction: null,
columns_order: null,
columns_width: null,
visible_columns: [
'uuid',
'first_name',
'last_name',
'username',
'breed',
'email',
'avatar',
'birthdate',
'created_at',
],
},
columns: [
createColumn({ name: 'uuid', label: 'ID' }),
createColumn({ name: 'first_name', label: 'First Name' }),
createColumn({ name: 'last_name', label: 'Last Name' }),
createColumn({ name: 'username', label: 'Username' }),
createColumn({ name: 'breed', label: 'Breed' }),
createColumn({ name: 'email', label: 'Email' }),
createColumn({ name: 'avatar', label: 'Avatar' }),
createColumn({ name: 'birthdate', label: 'Birthdate' }),
createColumn({ name: 'created_at', label: 'Created on' }),
],
selectable_rows: false,
bulk_action_links: [],
},
};

export { cats, tableStructure };
36 changes: 36 additions & 0 deletions krait-ui/.storybook/mocker/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import Router from './router.js';
import { initRoutes } from './routes.js';

const initCsrf = () => {
const csrfMetaEl = document.createElement('meta');
csrfMetaEl.setAttribute('name', 'csrf-token');
csrfMetaEl.setAttribute('content', 'test-token');
document.head.appendChild(csrfMetaEl);
};

const init = () => {
initCsrf();
initRoutes();
console.info('Krait Sample Mocker initialized!🥳');
};

window.fetch = async (target, fetchInit) => {
// Parse all input types to a Request object
const incomingRequest = new Request(target, fetchInit);
console.info(
`Sending ${incomingRequest.method} request to `,
incomingRequest.url,
);

const route = Router.match(incomingRequest);
if (!route) {
console.error(`URL ${incomingRequest.url} is not mocked!`);
return new Response('Not Found!', { status: 404 });
}

return route['handler'](incomingRequest);
};

export default {
init,
};
77 changes: 0 additions & 77 deletions krait-ui/.storybook/mocker/mocker.js

This file was deleted.

37 changes: 37 additions & 0 deletions krait-ui/.storybook/mocker/mocks.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { faker } from '@faker-js/faker';

export const createRandomCat = () => {
return {
uuid: faker.string.uuid(),
first_name: faker.person.firstName(),
last_name: faker.person.lastName(),
username: faker.internet.username({
firstName: 'Awesome Cat',
}),
breed: faker.animal.cat(),
email: faker.internet.email(),
avatar: faker.image.avatar(),
birthdate: faker.date.birthdate(),
created_at: faker.date.past(),
};
};

export const createColumn = ({
name,
label,
hideLabel = false,
datetime = false,
sortable = true,
fixed = false,
classes = null,
}) => {
return {
name,
label,
hideLabel,
datetime,
sortable,
fixed,
classes,
};
};
81 changes: 81 additions & 0 deletions krait-ui/.storybook/mocker/pagination.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
export const paginate = (data, ipp, currentPage) => {
if (!data || data.length === 0) return [];

// Calculate total number of pages
const totalPages = Math.ceil(data.length / ipp);

const start = (currentPage - 1) * ipp;
return [data.slice(start, start + ipp), totalPages];
};

export const getLinks = (currentPage, url, totalPages) => {
const firstURL = new URL(url);
firstURL.searchParams.set('page', '1');
const lastURL = new URL(url);
lastURL.searchParams.set('page', String(totalPages));

let prevURL = null;
if (currentPage > 1) {
prevURL = new URL(url);
prevURL.searchParams.set('page', String(currentPage - 1));
}

let nextURL = null;
if (currentPage < totalPages) {
nextURL = new URL(url);
nextURL.searchParams.set('page', String(currentPage + 1));
}

return {
first: firstURL.toString(),
last: lastURL.toString(),
prev: prevURL ? prevURL.toString() : null,
next: nextURL ? nextURL.toString() : null,
};
};

export const getMeta = ({
url,
currentPage,
totalPages,
totalRecords,
ipp,
pageLinks,
}) => {
const pageButtons = [];

for (let i = 0; i < totalPages; i++) {
const pageURL = new URL(url);
pageURL.searchParams.set('page', String(i + 1));
pageButtons.push({
url: pageURL.toString(),
label: String(i + 1),
active: currentPage === i + 1,
});
}

const links = [
{
url: pageLinks['prev'],
label: '&laquo; Previous',
active: !!pageLinks['prev'],
},
...pageButtons,
{
url: pageLinks['next'],
label: 'Next &raquo;',
active: !!pageLinks['next'],
},
];

return {
current_page: currentPage,
last_page: totalPages,
path: `${url.origin}/${url.pathname}`,
per_page: ipp,
from: currentPage ? (currentPage - 1) * ipp : 1,
to: currentPage * ipp,
total: totalRecords,
links,
};
};
Loading