Compare commits

...

20 Commits

Author SHA1 Message Date
ValdiANS 8206f7de5f feat(FE-40): create MainUiSlice type 2025-10-01 13:45:25 +07:00
ValdiANS a5b392ae76 feat(FE-40): create main UI slice 2025-10-01 13:45:16 +07:00
ValdiANS 6cbdff5398 feat(FE-40): add main UI slice to useUiStore 2025-10-01 13:45:00 +07:00
ValdiANS 87ce1e50aa feat(FE-40): create MAIN_DRAWER_LINKS constant 2025-10-01 13:44:42 +07:00
ValdiANS 2456d64a68 feat(FE-40): create MainDrawer component 2025-10-01 13:44:26 +07:00
ValdiANS c068fe5166 feat(FE-40): redirect to /dashboard 2025-10-01 13:44:18 +07:00
ValdiANS 19b7c53ec2 feat(FE-40): use MainDrawer component in root layout 2025-10-01 13:44:02 +07:00
ValdiANS 037e4776a8 chore: run eslint command in dev command 2025-09-30 15:45:33 +07:00
ValdiANS 3be69eeff8 fix: error type 2025-09-30 15:44:48 +07:00
ValdiANS a364a860fa chore: update PasswordInput component 2025-09-30 15:43:48 +07:00
ValdiANS 8e23a805a9 chore: update Button component 2025-09-30 15:43:04 +07:00
ValdiANS e052166b3a chore: update Pagination component 2025-09-30 15:42:25 +07:00
ValdiANS 691b49a902 chore: update Table component 2025-09-30 15:42:03 +07:00
ValdiANS 33f5ca2a57 chore: update Table component 2025-09-30 15:33:57 +07:00
ValdiANS 02c44ced92 chore: update Collapse component 2025-09-30 11:25:38 +07:00
ValdiANS 978285021e feat: add Collapse component 2025-09-29 11:58:57 +07:00
ValdiANS 7e57debb98 chore: update MenuItem component 2025-09-29 11:58:19 +07:00
Adnan Zahir a5d8ac47fe Merge branch 'init' into 'development'
init

See merge request mbugroup/lti-web-client!1
2025-09-26 11:41:47 +07:00
ValdiANS f127e16c7c chore: change copywriting 2025-09-26 11:36:53 +07:00
ValdiANS 2e1b0fef2b init 2025-09-26 11:06:31 +07:00
39 changed files with 9215 additions and 79 deletions
+41
View File
@@ -0,0 +1,41 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.*
.yarn/*
!.yarn/patches
!.yarn/plugins
!.yarn/releases
!.yarn/versions
# testing
/coverage
# next.js
/.next/
/out/
# production
/build
# misc
.DS_Store
*.pem
# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*
.pnpm-debug.log*
# env files (can opt-in for committing if needed)
.env*
# vercel
.vercel
# typescript
*.tsbuildinfo
next-env.d.ts
+22 -79
View File
@@ -1,93 +1,36 @@
# LTI - Client This is a [Next.js](https://nextjs.org) project bootstrapped with [`create-next-app`](https://nextjs.org/docs/app/api-reference/cli/create-next-app).
## Getting Started
First, run the development server:
## Getting started ```bash
npm run dev
To make it easy for you to get started with GitLab, here's a list of recommended next steps. # or
yarn dev
Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)! # or
pnpm dev
## Add your files # or
bun dev
- [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files
- [ ] [Add files using the command line](https://docs.gitlab.com/topics/git/add_files/#add-files-to-a-git-repository) or push an existing Git repository with the following command:
```
cd existing_repo
git remote add origin https://gitlab.com/mbugroup/lti-client.git
git branch -M main
git push -uf origin main
``` ```
## Integrate with your tools Open [http://localhost:3000](http://localhost:3000) with your browser to see the result.
- [ ] [Set up project integrations](https://gitlab.com/mbugroup/lti-client/-/settings/integrations) You can start editing the page by modifying `app/page.tsx`. The page auto-updates as you edit the file.
## Collaborate with your team This project uses [`next/font`](https://nextjs.org/docs/app/building-your-application/optimizing/fonts) to automatically optimize and load [Geist](https://vercel.com/font), a new font family for Vercel.
- [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/) ## Learn More
- [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html)
- [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically)
- [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/)
- [ ] [Set auto-merge](https://docs.gitlab.com/user/project/merge_requests/auto_merge/)
## Test and Deploy To learn more about Next.js, take a look at the following resources:
Use the built-in continuous integration in GitLab. - [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API.
- [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial.
- [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/) You can check out [the Next.js GitHub repository](https://github.com/vercel/next.js) - your feedback and contributions are welcome!
- [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing (SAST)](https://docs.gitlab.com/ee/user/application_security/sast/)
- [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html)
- [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/)
- [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html)
*** ## Deploy on Vercel
# Editing this README The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js.
When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thanks to [makeareadme.com](https://www.makeareadme.com/) for this template. Check out our [Next.js deployment documentation](https://nextjs.org/docs/app/building-your-application/deploying) for more details.
## Suggestions for a good README
Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information.
## Name
Choose a self-explaining name for your project.
## Description
Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors.
## Badges
On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge.
## Visuals
Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method.
## Installation
Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection.
## Usage
Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README.
## Support
Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc.
## Roadmap
If you have ideas for releases in the future, it is a good idea to list them in the README.
## Contributing
State if you are open to contributions and what your requirements are for accepting them.
For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self.
You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser.
## Authors and acknowledgment
Show your appreciation to those who have contributed to the project.
## License
For open source projects, say how it is licensed.
## Project status
If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers.
+25
View File
@@ -0,0 +1,25 @@
import { dirname } from "path";
import { fileURLToPath } from "url";
import { FlatCompat } from "@eslint/eslintrc";
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const compat = new FlatCompat({
baseDirectory: __dirname,
});
const eslintConfig = [
...compat.extends("next/core-web-vitals", "next/typescript"),
{
ignores: [
"node_modules/**",
".next/**",
"out/**",
"build/**",
"next-env.d.ts",
],
},
];
export default eslintConfig;
+8
View File
@@ -0,0 +1,8 @@
import type { NextConfig } from 'next';
const nextConfig: NextConfig = {
output: 'export',
images: { unoptimized: true },
};
export default nextConfig;
+7007
View File
File diff suppressed because it is too large Load Diff
+40
View File
@@ -0,0 +1,40 @@
{
"name": "lti-web-client",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "eslint && next dev --turbopack",
"build": "next build --turbopack",
"start": "next start",
"lint": "eslint"
},
"dependencies": {
"@tanstack/match-sorter-utils": "^8.19.4",
"@tanstack/react-table": "^8.21.3",
"axios": "^1.12.2",
"clsx": "^2.1.1",
"formik": "^2.4.6",
"moment": "^2.30.1",
"next": "15.5.3",
"react": "19.1.0",
"react-dom": "19.1.0",
"react-select": "^5.10.2",
"swr": "^2.3.6",
"tailwind-merge": "^3.3.1",
"yup": "^1.7.0",
"zustand": "^5.0.8"
},
"devDependencies": {
"@eslint/eslintrc": "^3",
"@iconify/react": "^6.0.2",
"@tailwindcss/postcss": "^4",
"@types/node": "^20",
"@types/react": "^19",
"@types/react-dom": "^19",
"daisyui": "^5.1.12",
"eslint": "^9",
"eslint-config-next": "15.5.3",
"tailwindcss": "^4",
"typescript": "^5"
}
}
+5
View File
@@ -0,0 +1,5 @@
const config = {
plugins: ["@tailwindcss/postcss"],
};
export default config;
Binary file not shown.

After

Width:  |  Height:  |  Size: 316 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

+14
View File
@@ -0,0 +1,14 @@
@import 'tailwindcss';
@plugin "daisyui";
:root {
--color-primary: #1f74bf;
}
@theme {
--font-inter: var(--font-inter);
}
html {
scrollbar-gutter: initial;
}
+34
View File
@@ -0,0 +1,34 @@
import type { Metadata, Viewport } from 'next';
import { Inter } from 'next/font/google';
import '@/app/globals.css';
import MainDrawer from '@/components/MainDrawer';
const inter = Inter({
variable: '--font-inter',
subsets: ['latin'],
});
export const viewport: Viewport = {
themeColor: '#1f74bf',
colorScheme: 'light',
initialScale: 1,
};
export const metadata: Metadata = {
title: 'LTI',
description: 'PT. Lumbung Telur Indonesia',
};
export default function RootLayout({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
return (
<html lang='en'>
<body className={`${inter.variable} antialiased font-inter`}>
<MainDrawer>{children}</MainDrawer>
</body>
</html>
);
}
+11
View File
@@ -0,0 +1,11 @@
import { redirect } from 'next/navigation';
export default function Home() {
redirect('/dashboard');
return (
<main className='w-full h-full min-h-screen flex flex-row justify-center items-center'>
<h1>LTI ERP</h1>
</main>
);
}
+86
View File
@@ -0,0 +1,86 @@
import react from 'react';
import Link from 'next/link';
import { cn } from '@/lib/helper';
import { Color } from '@/types/theme';
interface ButtonProps extends react.ComponentProps<'button'> {
variant?: 'soft' | 'outline' | 'dash' | 'ghost' | 'link' | 'active';
color?: Color;
href?: string;
isLoading?: boolean;
}
const Button = ({
children,
type,
href,
variant,
color = 'primary',
isLoading,
className,
disabled,
onClick,
...props
}: ButtonProps) => {
const btnBaseClassName = cn(
'btn',
{
'btn-soft': variant === 'soft',
'btn-outline': variant === 'outline',
'btn-dash': variant === 'dash',
'btn-ghost': variant === 'ghost',
'btn-link': variant === 'link',
'btn-active': variant === 'active',
'btn-primary': color === 'primary',
'btn-secondary': color === 'secondary',
'btn-accent': color === 'accent',
'btn-neutral': color === 'neutral',
'btn-info': color === 'info',
'btn-success': color === 'success',
'btn-warning': color === 'warning',
'btn-error': color === 'error',
},
'h-fit justify-center items-center gap-2 rounded-xl p-2 text-base transition-all'
);
return (
<>
{!href && (
<button
{...props}
type={type}
onClick={onClick}
disabled={disabled}
className={cn(
btnBaseClassName,
'disabled:pointer-events-auto! disabled:cursor-not-allowed!',
className
)}
>
{!isLoading && children}
{isLoading && <span className='loading loading-dots loading-xl' />}
</button>
)}
{href && (
<Link
href={disabled ? '#' : href}
aria-disabled={disabled}
className={cn(
btnBaseClassName,
{ 'pointer-events-auto cursor-not-allowed': disabled },
className
)}
>
{!isLoading && children}
{isLoading && <span className='loading loading-dots loading-xl' />}
</Link>
)}
</>
);
};
export default Button;
+130
View File
@@ -0,0 +1,130 @@
import React, { useCallback, useId, useMemo, useState } from 'react';
import { cn } from '@/lib/helper';
export type CollapseVariant = 'default' | 'arrow' | 'plus';
export type CollapseProps = {
/** Unique name used when `asRadio` is true (Accordion single-open). */
name?: string;
/** If provided, component is controlled. */
open?: boolean;
/** Initial open state for uncontrolled usage. */
defaultOpen?: boolean;
/** Callback when open state changes. */
onOpenChange?: (open: boolean) => void;
/** Title row content. Accepts string or custom node. */
title?: React.ReactNode;
/** Optional secondary text displayed under/next to title. */
subtitle?: React.ReactNode;
/** Content of the panel. */
children?: React.ReactNode;
/** Visual variant: default / arrow / plus */
variant?: CollapseVariant;
/** Add a bordered look */
bordered?: boolean;
/** Disable interactions */
disabled?: boolean;
/** Allow only one open at a time by switching to radio input */
asRadio?: boolean;
/** Extra classnames */
className?: string;
titleClassName?: string;
contentClassName?: string;
};
export const Collapse = ({
name,
open,
defaultOpen,
onOpenChange,
title,
subtitle,
children,
variant = 'default',
bordered,
disabled,
asRadio = false,
className,
titleClassName,
contentClassName,
}: CollapseProps) => {
const inputId = useId();
const isControlled = typeof open === 'boolean';
const [internalOpen, setInternalOpen] = useState(!!defaultOpen);
const isOpen = isControlled ? !!open : internalOpen;
// Manage change from checkbox/radio
const handleChange = useCallback(
(next: boolean) => {
if (!isControlled) setInternalOpen(next);
onOpenChange?.(next);
},
[isControlled, onOpenChange]
);
const inputType = asRadio ? 'radio' : 'checkbox';
const rootClass = cn(
'collapse',
variant === 'arrow' && 'collapse-arrow',
variant === 'plus' && 'collapse-plus',
bordered && 'border base-content/20 border-opacity-20 rounded-box',
disabled && 'opacity-60 pointer-events-none',
className
);
const titleNode = useMemo(() => {
if (subtitle) {
return (
<div className='flex flex-col gap-0.5'>
<span>{title}</span>
<span className='text-sm opacity-70'>{subtitle}</span>
</div>
);
}
return <div>{title}</div>;
}, [title, subtitle]);
return (
<div className={rootClass} data-open={isOpen}>
<input
id={inputId}
type={inputType}
name={asRadio ? name : undefined}
className='peer p-0 hidden'
checked={isOpen}
onChange={(e) => handleChange(e.currentTarget.checked)}
aria-controls={`${inputId}-content`}
disabled={disabled}
/>
<div
role='button'
tabIndex={0}
className={cn(
'collapse-title p-0',
'focus:outline-none focus-visible:ring focus-visible:ring-primary/40',
titleClassName
)}
onKeyDown={(e) => {
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
handleChange(!isOpen);
}
}}
onClick={() => handleChange(!isOpen)}
>
{titleNode}
</div>
<div
id={`${inputId}-content`}
className={cn('collapse-content p-0!', contentClassName)}
>
{children}
</div>
</div>
);
};
export default Collapse;
+60
View File
@@ -0,0 +1,60 @@
'use client';
import { ReactNode } from 'react';
import { cn } from '@/lib/helper';
interface DrawerProps {
children?: ReactNode;
sidebarContent?: ReactNode;
open: boolean;
setOpen: (newOpenState: boolean) => void;
openOnLarge?: boolean;
}
const Drawer = ({
children,
sidebarContent,
open,
setOpen,
openOnLarge,
}: DrawerProps) => {
const toggleDrawer = () => {
setOpen(!open);
};
const closeDrawer = () => {
setOpen(false);
};
return (
<div
className={cn('drawer', {
'lg:drawer-open': openOnLarge,
})}
>
<input
type='checkbox'
checked={open}
onChange={toggleDrawer}
className='drawer-toggle'
/>
<div className='drawer-content'>{children}</div>
<div className='drawer-side border-r border-solid border-gray-200 z-20'>
<label
aria-label='close sidebar'
className='drawer-overlay'
onClick={closeDrawer}
/>
<div className='min-h-full w-full max-w-[300px] lg:w-[300px] bg-base-100'>
{sidebarContent}
</div>
</div>
</div>
);
};
export default Drawer;
+205
View File
@@ -0,0 +1,205 @@
'use client';
import { useState } from 'react';
import { usePathname } from 'next/navigation';
import Image from 'next/image';
import { Icon } from '@iconify/react';
import Drawer from '@/components/Drawer';
import Menu from '@/components/menu/Menu';
import MenuItem from '@/components/menu/MenuItem';
import Navbar from '@/components/Navbar';
import Collapse from '@/components/Collapse';
import { useUiStore } from '@/stores/ui/ui.store';
import { MAIN_DRAWER_LINKS } from '@/config/constant';
import { cn } from '@/lib/helper';
type CollapseMenuProps = {
title: string;
link: string;
icon: string;
submenu?: CollapseMenuProps[];
depth?: number;
};
const isPathActive = (pathname: string, link?: string) => {
if (!link) return false;
const splittedPathname = pathname.split('/');
const splittedLink = link.split('/');
return splittedPathname.every((pathnameChunk, idx) => {
return pathnameChunk === splittedLink[idx];
});
};
const isCollapseActive = (pathname: string, link?: string) => {
if (!link) return false;
return pathname === link || pathname.startsWith(link);
};
const CollapseMenu = ({
title,
link,
icon,
submenu,
depth = 0,
}: CollapseMenuProps) => {
const pathname = usePathname();
const [open, setOpen] = useState(isCollapseActive(pathname, link));
const menuCollapseTitle = (
<div
className={cn(
'w-full px-3 py-2 rounded-md text-base font-semibold transition-colors flex flex-row justify-between items-center gap-2 hover:bg-primary/10',
{
'bg-primary/10': open,
}
)}
>
<div className='flex flex-row items-center gap-2'>
<Icon icon={icon} width={20} height={20} />
<span>{title}</span>
</div>
<Icon
icon='cuida:caret-up-outline'
width={20}
height={20}
className={cn('transition-transform', {
'rotate-90': !open,
'rotate-180': open,
})}
/>
</div>
);
const paddingLeftDepth = `pl-${4 * (depth + 1)}`;
return (
<Collapse
open={open}
title={menuCollapseTitle}
onOpenChange={setOpen}
titleClassName='p-0!'
>
<Menu className={cn('py-0.5', paddingLeftDepth)}>
{submenu?.map((item, idx) => {
const hasSubmenu = item.submenu && item.submenu.length > 0;
if (!hasSubmenu) {
return (
<MenuItem
key={idx}
title={item.title}
href={item.link}
icon={item.icon}
active={isPathActive(pathname, item.link)}
/>
);
}
return (
<CollapseMenu
key={idx}
title={item.title}
link={item.link}
icon={item.icon}
submenu={item.submenu}
depth={depth + 1}
/>
);
})}
</Menu>
</Collapse>
);
};
const MainDrawerMenu = () => {
const pathname = usePathname();
return (
<Menu>
{MAIN_DRAWER_LINKS.map((item, idx) => {
const hasSubmenu = item.submenu && item.submenu.length > 0;
if (!hasSubmenu) {
return (
<MenuItem
key={idx}
title={item.title}
href={item.link}
icon={item.icon}
active={pathname.startsWith(item.link)}
/>
);
}
return (
<CollapseMenu
key={idx}
title={item.title}
link={item.link}
icon={item.icon}
submenu={item.submenu}
/>
);
})}
</Menu>
);
};
const MainDrawerContent = () => {
return (
<div className='w-full p-4 flex flex-col gap-4'>
<div className='flex items-center gap-4'>
<Image
src='/assets/img/lti-logo.png'
alt='MBU Logo'
width={256}
height={256}
className='w-full max-w-16 h-auto'
/>
<h1 className='text-xl font-bold'>LTI ERP</h1>
</div>
<MainDrawerMenu />
</div>
);
};
const MainDrawer = ({
children,
}: Readonly<{
children: React.ReactNode;
}>) => {
const { mainDrawerOpen, setMainDrawerOpen } = useUiStore();
const pathname = usePathname();
const pageTitle = MAIN_DRAWER_LINKS.find((item) =>
pathname.startsWith(item.link)
)?.title;
const toggleSidebar = () => {
setMainDrawerOpen(!mainDrawerOpen);
};
return (
<Drawer
open={mainDrawerOpen}
setOpen={setMainDrawerOpen}
openOnLarge
sidebarContent={<MainDrawerContent />}
>
<main className='w-full h-full flex flex-col gap-4'>
<Navbar title={pageTitle as string} toggleSidebar={toggleSidebar} />
{children}
</main>
</Drawer>
);
};
export default MainDrawer;
+54
View File
@@ -0,0 +1,54 @@
'use client';
import { Icon } from '@iconify/react';
import Menu from '@/components/menu/Menu';
import MenuItem from '@/components/menu/MenuItem';
import Button from '@/components/Button';
interface NavbarProps {
title: string;
toggleSidebar?: () => void;
}
const Navbar = ({ title, toggleSidebar }: NavbarProps) => {
return (
<div className='navbar px-4 bg-base-100 shadow-sm'>
<div className='flex-1'>
<div className='flex flex-row items-center gap-4'>
{toggleSidebar && (
<Button onClick={toggleSidebar} className='block lg:hidden'>
<Icon
icon='material-symbols:menu-rounded'
width={24}
height={24}
/>
</Button>
)}
<span className='font-bold text-xl text-primary'>{title}</span>
</div>
</div>
<div className='flex gap-2'>
<div className='dropdown dropdown-end'>
<div
tabIndex={0}
role='button'
className='btn btn-ghost btn-circle avatar'
>
<div className='w-10 rounded-full border grid place-items-center'>
<Icon icon='uil:user' width={40} height={40} />
</div>
</div>
<Menu className='dropdown-content w-52 mt-3 p-2 bg-base-100 shadow rounded-box menu-sm'>
<MenuItem title='Settings' href='#' />
<MenuItem title='Logout' href='#' />
</Menu>
</div>
</div>
</div>
);
};
export default Navbar;
+335
View File
@@ -0,0 +1,335 @@
'use client';
import { ReactNode } from 'react';
import { Icon } from '@iconify/react';
import { cn } from '@/lib/helper';
const range = (start: number, end: number) =>
Array.from({ length: end - start + 1 }, (_, i) => i + start);
const PaginationButton = ({
content = '',
disabled = false,
onClick = () => {},
}: {
content?: ReactNode;
disabled?: boolean;
onClick?: () => void;
}) => (
<button
className={cn(
'join-item btn btn-ghost p-2.5 rounded-lg text-sm font-medium text-gray-500 aspect-square',
'disabled:text-gray-700 disabled:pointer-events-auto! disabled:cursor-not-allowed! disabled:bg-gray-50 disabled:active:translate-y-0'
)}
disabled={disabled}
onClick={onClick}
>
{content}
</button>
);
const EtcPaginationButton = ({
startPage = 0,
endPage = 0,
onPageItemClick,
}: {
startPage: number;
endPage: number;
onPageItemClick: (a: number) => void;
}) => {
const pages = range(startPage, endPage);
return (
<>
{startPage > 0 && endPage >= startPage && (
<div className='dropdown dropdown-top dropdown-center'>
<button
tabIndex={0}
role='button'
className={cn(
'join-item btn btn-ghost p-2.5 rounded-lg text-sm font-medium text-gray-500 aspect-square'
)}
>
...
</button>
<div className='dropdown-content'>
<ul
tabIndex={0}
className='menu bg-base-100 rounded-lg z-1 w-fit min-w-max max-h-64 p-1 shadow-sm mb-2 overflow-y-auto flex-nowrap'
>
{pages.map((pageNumber) => (
<li key={pageNumber}>
<PaginationButton
content={pageNumber}
onClick={() => onPageItemClick(pageNumber)}
/>
</li>
))}
</ul>
</div>
</div>
)}
{(startPage === 0 || endPage < startPage) && (
<button
disabled
className={cn(
'join-item btn btn-ghost p-2.5 rounded-lg text-sm font-medium text-gray-500 aspect-square'
)}
>
...
</button>
)}
</>
);
};
const Pagination = ({
currentPage = 1,
totalItems = 0,
itemsPerPage = 10,
onPageChange,
onPrevPage = () => {},
onNextPage = () => {},
}: {
currentPage: number;
totalItems: number;
itemsPerPage: number;
onPageChange: (pageNumber: number) => void;
onPrevPage: () => void;
onNextPage: () => void;
}) => {
const totalPages =
Math.ceil(totalItems / itemsPerPage) === 0
? 1
: Math.ceil(totalItems / itemsPerPage);
const pageChangeHandler = (pageNumber: number) => onPageChange(pageNumber);
return (
<div>
<div className='join w-full justify-between items-center gap-3'>
<button
disabled={currentPage === 1}
onClick={onPrevPage}
className={cn(
'join-item btn btn-outline group px-3 py-2 text-sm font-semibold rounded-lg border border-gray-300 shadow-xs hidden sm:flex justify-center items-center gap-1.5',
'disabled:bg-[initial]! disabled:text-gray-400 disabled:pointer-events-auto! disabled:cursor-not-allowed disabled:active:translate-y-0'
)}
>
<Icon
icon='uil:arrow-left'
width={20}
height={20}
className='text-gray-400 group-disabled:text-gray-300'
/>{' '}
Previous
</button>
{totalPages <= 7 && (
<div className='join-item join gap-0.5'>
{range(1, totalPages).map((pageNumber) => (
<PaginationButton
key={pageNumber}
content={pageNumber}
disabled={currentPage === pageNumber}
onClick={() => pageChangeHandler(pageNumber)}
/>
))}
</div>
)}
{totalPages > 7 && (
<div className='join-item join gap-0.5'>
<PaginationButton
content={1}
disabled={currentPage === 1}
onClick={() => pageChangeHandler(1)}
/>
{totalPages >= 2 &&
(currentPage <= 3 || currentPage >= totalPages - 2) && (
<PaginationButton
content={2}
disabled={currentPage === 2}
onClick={() => pageChangeHandler(2)}
/>
)}
{totalPages >= 2 &&
currentPage > 3 &&
currentPage < totalPages - 2 && (
<EtcPaginationButton
startPage={2}
endPage={currentPage - 2}
onPageItemClick={pageChangeHandler}
/>
)}
{totalPages >= 3 &&
(currentPage <= 4 || currentPage >= totalPages - 2) &&
currentPage !== totalPages - 2 && (
<PaginationButton
content={3}
disabled={currentPage === 3}
onClick={() => pageChangeHandler(3)}
/>
)}
{totalPages >= 7 &&
(currentPage <= 2 || currentPage >= totalPages - 2) && (
<EtcPaginationButton
startPage={
currentPage <= 2
? currentPage + 2
: currentPage === totalPages - 2
? 3
: currentPage >= totalPages - 1
? 4
: 1
}
endPage={
currentPage <= 2 || currentPage >= totalPages - 1
? totalPages - 3
: currentPage === totalPages - 2
? totalPages - 4
: 2
}
onPageItemClick={pageChangeHandler}
/>
)}
{totalPages >= 3 &&
currentPage > 4 &&
currentPage < totalPages - 1 && (
<PaginationButton
content={currentPage - 1}
onClick={() => pageChangeHandler(currentPage - 1)}
/>
)}
{totalPages >= 7 &&
currentPage > 3 &&
currentPage < totalPages - 2 && (
<PaginationButton content={currentPage} disabled />
)}
{totalPages >= 5 &&
currentPage > 2 &&
currentPage < totalPages - 2 && (
<PaginationButton
content={currentPage + 1}
onClick={() => pageChangeHandler(currentPage + 1)}
/>
)}
{totalPages >= 5 &&
(currentPage <= 2 || currentPage >= totalPages - 2) && (
<PaginationButton
content={totalPages - 2}
disabled={currentPage === totalPages - 2}
onClick={() => pageChangeHandler(totalPages - 2)}
/>
)}
{totalPages >= 6 &&
currentPage > 2 &&
currentPage < totalPages - 3 && (
<EtcPaginationButton
startPage={
currentPage <= 3
? currentPage + 2
: currentPage >= 4
? currentPage + 2
: 1
}
endPage={
currentPage <= 3
? totalPages - 2
: currentPage >= 4
? totalPages - 1
: 0
}
onPageItemClick={pageChangeHandler}
/>
)}
{totalPages >= 6 &&
(currentPage <= 3 || currentPage >= totalPages - 3) && (
<PaginationButton
content={totalPages - 1}
disabled={currentPage === totalPages - 1}
onClick={() => pageChangeHandler(totalPages - 1)}
/>
)}
{totalPages >= 7 && (
<PaginationButton
content={totalPages}
disabled={currentPage === totalPages}
onClick={() => pageChangeHandler(totalPages)}
/>
)}
</div>
)}
<button
disabled={currentPage === totalPages}
onClick={onNextPage}
className={cn(
'join-item btn btn-outline group px-3 py-2 text-sm font-semibold rounded-lg border border-gray-300 shadow-xs hidden sm:flex justify-center items-center gap-1.5',
'disabled:bg-[initial]! disabled:text-gray-400 disabled:pointer-events-auto! disabled:cursor-not-allowed disabled:active:translate-y-0'
)}
>
Next{' '}
<Icon
icon='uil:arrow-right'
width={20}
height={20}
className='text-gray-400 group-disabled:text-gray-300'
/>
</button>
</div>
<div className='flex gap-2 mt-2 sm:hidden'>
<button
disabled={currentPage === 1}
onClick={onPrevPage}
className={cn(
'join-item btn btn-outline group px-3 py-2 text-sm font-semibold rounded-lg border border-gray-300 shadow-xs flex justify-center items-center gap-1.5',
'disabled:bg-[initial]! disabled:text-gray-400 disabled:pointer-events-auto! disabled:cursor-not-allowed disabled:active:translate-y-0'
)}
>
<Icon
icon='uil:arrow-left'
width={20}
height={20}
className='text-gray-400 group-disabled:text-gray-300'
/>{' '}
Previous
</button>
<button
disabled={currentPage === totalPages}
onClick={onNextPage}
className={cn(
'join-item btn btn-outline group px-3 py-2 text-sm font-semibold rounded-lg border border-gray-300 shadow-xs flex justify-center items-center gap-1.5',
'disabled:bg-[initial]! disabled:text-gray-400 disabled:pointer-events-auto! disabled:cursor-not-allowed disabled:active:translate-y-0'
)}
>
Next{' '}
<Icon
icon='uil:arrow-right'
width={20}
height={20}
className='text-gray-400 group-disabled:text-gray-300'
/>
</button>
</div>
</div>
);
};
export default Pagination;
+249
View File
@@ -0,0 +1,249 @@
'use client';
import { ReactNode, useCallback, useState } from 'react';
import {
flexRender,
getCoreRowModel,
getFilteredRowModel,
getPaginationRowModel,
getSortedRowModel,
TableOptions,
useReactTable,
ColumnDef,
FilterFn,
} from '@tanstack/react-table';
import { rankItem } from '@tanstack/match-sorter-utils';
import { Icon } from '@iconify/react';
import Pagination from '@/components/Pagination';
import { cn } from '@/lib/helper';
interface TableClassNames {
containerClassName?: string;
tableWrapperClassName?: string;
tableClassName?: string;
tableHeaderClassName?: string;
headerRowClassName?: string;
headerColumnClassName?: string;
tableBodyClassName?: string;
bodyRowClassName?: string;
bodyColumnClassName?: string;
paginationClassName?: string;
}
export interface TableProps<TData extends object> {
data: TData[];
columns: ColumnDef<TData, unknown>[];
pageSize?: number;
totalItems?: number;
page?: number;
onPageChange?: (page: number) => void;
isLoading?: boolean;
fuzzySearchValue?: string | null;
onFuzzySearchValueChange?: (value: string) => void;
className?: TableClassNames;
emptyContent?: ReactNode;
}
const DUMMY_SKELETON_DATA = [{}, {}, {}, {}, {}];
const emptyContentDefaultValue = (
<div className='w-full p-5 text-center'>
<span className='text-lg opacity-50'>
Tidak ada data yang dapat ditampilkan...
</span>
</div>
);
const Table = <TData extends object>({
data = [],
columns = [],
pageSize = 10,
totalItems,
page,
onPageChange,
isLoading = false,
fuzzySearchValue,
onFuzzySearchValueChange,
className = {
containerClassName: '',
tableWrapperClassName: '',
tableClassName: '',
tableHeaderClassName: '',
headerRowClassName: '',
headerColumnClassName: '',
tableBodyClassName: '',
bodyRowClassName: '',
bodyColumnClassName: '',
paginationClassName: '',
},
emptyContent = emptyContentDefaultValue,
}: TableProps<TData>) => {
const isServerSideTable =
totalItems !== undefined &&
page !== undefined &&
onPageChange !== undefined;
const [pagination, setPagination] = useState({
pageIndex: 0,
pageSize: pageSize,
});
const fuzzyFilter: FilterFn<TData> = useCallback(
(row, columnId, value, addMeta) => {
const itemRank = rankItem(row.getValue(columnId), value);
addMeta({ itemRank });
return itemRank.passed;
},
[]
);
const tableOptions: TableOptions<TData> = {
columns,
data: isLoading ? (DUMMY_SKELETON_DATA as TData[]) : data, // Type assertion
getCoreRowModel: getCoreRowModel(),
getSortedRowModel: getSortedRowModel(),
getPaginationRowModel: getPaginationRowModel(),
onPaginationChange: setPagination,
state: {
pagination,
globalFilter: fuzzySearchValue,
},
filterFns: {
fuzzy: fuzzyFilter,
},
globalFilterFn: fuzzyFilter,
};
if (fuzzySearchValue !== null) {
tableOptions.onGlobalFilterChange = onFuzzySearchValueChange;
tableOptions.getFilteredRowModel = getFilteredRowModel();
}
const table = useReactTable(tableOptions);
const prevPageClickHandler = () => {
table.previousPage();
if (isServerSideTable) {
onPageChange(page - 1);
}
};
const nextPageClickHandler = () => {
table.nextPage();
if (isServerSideTable) {
onPageChange(page + 1);
}
};
const pageChangeHandler = (pageNumber: number) => {
const currentPage = pageNumber - 1;
table.setPageIndex(pageNumber ? currentPage : 0);
if (isServerSideTable) {
onPageChange(pageNumber);
}
};
return (
<div className={className.containerClassName}>
<div className={className.tableWrapperClassName}>
<table className={className.tableClassName}>
<thead className={className.tableHeaderClassName}>
{table.getHeaderGroups().map((headerGroup) => (
<tr key={headerGroup.id} className={className.headerRowClassName}>
{headerGroup.headers.map((header) => (
<th
key={header.id}
colSpan={header.colSpan}
onClick={header.column.getToggleSortingHandler()}
className={cn(
header.column.getCanSort()
? 'cursor-pointer select-none'
: '',
className.headerColumnClassName
)}
>
<div className='flex items-center gap-1'>
{flexRender(
header.column.columnDef.header,
header.getContext()
)}
{header.column.getCanSort() && (
<div className='flex items-center'>
<Icon
icon='lucide:arrow-up'
width={12}
height={12}
className={cn(
'transition-all ease-in-out duration-200',
header.column.getIsSorted() === 'asc'
? 'text-black'
: 'text-black/30'
)}
/>
<Icon
icon='lucide:arrow-down'
width={12}
height={12}
className={cn(
'transition-all ease-in-out duration-200',
header.column.getIsSorted() === 'desc'
? 'text-black'
: 'text-black/30'
)}
/>
</div>
)}
</div>
</th>
))}
</tr>
))}
</thead>
<tbody className={className.tableBodyClassName}>
{table.getRowModel().rows.map((row) => (
<tr key={row.id} className={className.bodyRowClassName}>
{row.getVisibleCells().map((cell) => (
<td key={cell.id} className={className.bodyColumnClassName}>
{!isLoading &&
flexRender(cell.column.columnDef.cell, cell.getContext())}
{isLoading && <div className='skeleton w-full h-4' />}
</td>
))}
</tr>
))}
</tbody>
</table>
</div>
{(data.length === 0 || table.getRowModel().rows.length === 0) &&
emptyContent}
{data.length > 0 && table.getRowModel().rows.length > 0 && !isLoading && (
<div className={cn('mt-5', className.paginationClassName)}>
<Pagination
totalItems={isServerSideTable ? totalItems : table.getRowCount()}
itemsPerPage={table.getState().pagination.pageSize}
currentPage={
isServerSideTable
? page
: table.getState().pagination.pageIndex + 1
}
onPrevPage={prevPageClickHandler}
onNextPage={nextPageClickHandler}
onPageChange={pageChangeHandler}
/>
</div>
)}
</div>
);
};
export default Table;
+88
View File
@@ -0,0 +1,88 @@
import { Ref } from 'react';
import { cn } from '@/lib/helper';
import { TextInputProps } from '@/components/input/TextInput';
interface FileInputProps
extends Omit<
TextInputProps,
| 'type'
| 'value'
| 'isValid'
| 'startAdornment'
| 'endAdornment'
| 'isLoading'
> {
ref?: Ref<HTMLInputElement>;
accept?: string;
className?: {
wrapper?: string;
label?: string;
input?: string;
};
}
const FileInput = ({
ref,
label,
bottomLabel,
name,
placeholder,
accept = '*',
className,
isError,
errorMessage,
disabled = false,
onChange,
onBlur,
readOnly = false,
}: FileInputProps) => {
return (
<div
className={cn(
'w-full flex flex-col gap-2 text-start',
className?.wrapper
)}
>
{label && (
<label
htmlFor={name}
className={cn(
'w-full text-sm font-normal leading-5',
{
'text-error': isError,
},
className?.label
)}
>
{label}
</label>
)}
<input
ref={ref}
type='file'
accept={accept}
id={name}
name={name}
placeholder={placeholder}
onChange={onChange}
onBlur={onBlur}
disabled={disabled}
className={cn(
'grow file-input w-full h-12 rounded-lg!',
className?.input
)}
readOnly={readOnly}
/>
{bottomLabel && (
<p className='w-full text-sm opacity-60'>{bottomLabel}</p>
)}
{isError && <p className='w-full text-sm text-error'>{errorMessage}</p>}
</div>
);
};
export default FileInput;
+49
View File
@@ -0,0 +1,49 @@
'use client';
import { useState } from 'react';
import { Icon } from '@iconify/react';
import TextInput, { TextInputProps } from '@/components/input/TextInput';
import Button from '@/components/Button';
type PasswordInputProps = Omit<
TextInputProps,
'type' | 'startAdornment' | 'endAdornment'
>;
const PasswordInput = (props: PasswordInputProps) => {
const [type, setType] = useState('password');
const showPasswordHandler = () => {
setType((prevType) => {
if (prevType === 'password') return 'text';
return 'password';
});
};
return (
<TextInput
{...props}
type={type}
endAdornment={
<Button
tabIndex={-1}
type='button'
variant='ghost'
onClick={showPasswordHandler}
className='btn btn-ghost w-fit h-fit p-2 rounded-full'
disabled={props.disabled}
>
<Icon
icon={type === 'password' ? 'mdi:eye' : 'mdi:eye-off'}
width={16}
height={16}
/>
</Button>
}
/>
);
};
export default PasswordInput;
+203
View File
@@ -0,0 +1,203 @@
'use client';
import { ComponentType, ReactNode, useMemo } from 'react';
import Select, { OptionProps, GroupBase } from 'react-select';
import makeAnimated from 'react-select/animated';
import { cn } from '@/lib/helper';
export interface OptionType {
value: string | number;
label: string;
className?: string; // for multi select
labelClassName?: string; // for multi select
}
export type OptionComponent<T = OptionType> = ComponentType<
OptionProps<T, boolean, GroupBase<T>>
>;
interface SelectInputProps<T = OptionType> {
label?: ReactNode;
bottomLabel?: ReactNode;
value?: T | T[];
onChange?: (val: T | T[] | null) => void;
options: T[];
optionComponent?: OptionComponent<T>;
isDisabled?: boolean;
isLoading?: boolean;
isClearable?: boolean;
isRtl?: boolean;
isSearchable?: boolean;
isMulti?: boolean;
placeholder?: string;
required?: boolean;
className?: {
wrapper?: string;
label?: string;
select?: string;
};
isError?: boolean;
errorMessage?: string;
isAnimated?: boolean;
openMenu?: boolean;
}
const animatedComponents = makeAnimated();
const SelectInput = <T extends OptionType>({
label,
bottomLabel,
value,
onChange,
options,
optionComponent,
isDisabled,
isLoading,
isClearable,
isRtl,
isSearchable = true,
isMulti,
placeholder,
required,
className,
isError,
errorMessage,
isAnimated = true,
openMenu,
}: SelectInputProps) => {
const components = useMemo(() => {
const base = isAnimated ? animatedComponents : {};
return {
...base,
IndicatorSeparator: () => null,
};
}, [isAnimated]);
return (
<div
className={cn(
'w-full flex flex-col gap-2 text-start',
className?.wrapper
)}
>
{label && (
<span
className={cn(
'w-full text-sm font-normal leading-5',
{
'text-error': isError,
},
className?.label
)}
>
{label}
{required && (
<>
{' '}
<span className='tooltip tooltip-error' data-tip='required'>
<span className='text-error'> *</span>
</span>
</>
)}
</span>
)}
<Select
instanceId='select'
value={value}
onChange={(val) => onChange?.(val as T)}
options={options}
menuIsOpen={openMenu}
isMulti={isMulti}
isDisabled={isDisabled}
isLoading={isLoading}
isClearable={isClearable}
isRtl={isRtl}
isSearchable={isSearchable}
placeholder={placeholder}
className={cn('w-full', className)}
classNames={{
control: ({ isFocused, isDisabled }) =>
cn(
'w-full min-h-12! rounded-lg! border bg-white transition-shadow cursor-pointer!',
{
'border-red-500! focus-within:border-red-500 focus-within:ring-2 focus-within:ring-red-200':
isError,
'border-indigo-500 ring-2 ring-indigo-200': isFocused,
'border-gray-300': !isError && !isFocused,
'bg-gray-100 text-gray-400 cursor-not-allowed': isDisabled,
}
),
valueContainer: () => cn('flex-1 px-4! py-2! gap-1'),
placeholder: () =>
cn({ 'text-gray-400': !isError, 'text-red-300!': isError }),
singleValue: () =>
cn({ 'text-gray-900': !isError, 'text-error!': isError }),
input: () => cn('text-gray-900'),
indicatorsContainer: () => cn('flex items-center gap-1 pr-2'),
indicatorSeparator: () => cn('mx-1 h-4 w-px bg-gray-200'),
clearIndicator: () => cn('p-1 rounded-md hover:bg-gray-100'),
dropdownIndicator: ({ isFocused }) =>
cn('p-1 rounded-md hover:bg-gray-100', {
'text-gray-900': isFocused,
'text-gray-500': !isFocused,
'text-error!': isError,
}),
menu: () =>
cn(
'border border-gray-200 rounded-lg bg-white shadow-lg rounded-lg!'
),
menuList: () => cn('p-2! max-h-60 overflow-auto'),
groupHeading: () =>
cn('ml-2 mt-2 mb-1 text-xs font-medium text-gray-500'),
option: ({ isFocused, isSelected, isDisabled }) =>
cn('mt-1 px-3 py-2 rounded-md cursor-pointer! select-none', {
'text-gray-300': isDisabled,
'bg-indigo-600 text-white': isFocused,
'text-gray-700': !isDisabled && !isFocused,
'active:bg-indigo-50': !isDisabled,
'bg-blue-500!': isSelected,
}),
noOptionsMessage: () => cn('px-3 py-2 text-gray-500'),
loadingMessage: () => cn('px-3 py-2 text-gray-500'),
multiValue: ({ getValue, index }) => {
const selectedValues = getValue();
return cn(
'bg-indigo-50 rounded-md py-0.5 pl-2 pr-1 flex items-center gap-1 rounded-md!',
selectedValues[index]?.className
);
},
multiValueLabel: ({ getValue, index }) => {
const selectedValues = getValue();
return cn('text-indigo-700', selectedValues[index]?.labelClassName);
},
multiValueRemove: () =>
cn('p-1 rounded-sm! hover:bg-indigo-100 hover:text-indigo-800'),
}}
components={{
...components,
...(optionComponent ? { Option: optionComponent } : {}),
}}
// make the menu float above modals/etc.
menuPortalTarget={
typeof document !== 'undefined' ? document.body : undefined
}
styles={{
// Tailwind can't set inline z-index on a portal; use styles here:
menuPortal: (base) => ({ ...base, zIndex: 9999 }),
}}
/>
{isError && <p className='w-full text-sm text-error'>{errorMessage}</p>}
{!isError && bottomLabel && (
<p className='w-full text-sm opacity-60'>{bottomLabel}</p>
)}
</div>
);
};
export default SelectInput;
+130
View File
@@ -0,0 +1,130 @@
'use client';
import {
ChangeEventHandler,
FocusEventHandler,
HTMLInputTypeAttribute,
ReactNode,
} from 'react';
import { cn } from '@/lib/helper';
export interface TextInputProps {
type?: HTMLInputTypeAttribute;
label?: string;
bottomLabel?: string;
name: string;
value?: string | number;
placeholder?: string;
className?: {
wrapper?: string;
label?: string;
inputWrapper?: string;
input?: string;
};
isError?: boolean;
isValid?: boolean;
disabled?: boolean;
readOnly?: boolean;
required?: boolean;
isLoading?: boolean;
errorMessage?: string;
startAdornment?: ReactNode;
endAdornment?: ReactNode;
onChange?: ChangeEventHandler<HTMLInputElement>;
onBlur?: FocusEventHandler<HTMLInputElement>;
}
const TextInput = ({
type = 'text',
label,
bottomLabel,
name,
value,
placeholder,
className,
isError,
isValid,
errorMessage,
startAdornment,
endAdornment,
disabled = false,
required = false,
onChange,
onBlur,
readOnly = false,
isLoading = false,
}: TextInputProps) => {
return (
<div
className={cn(
'w-full flex flex-col gap-2 text-start',
className?.wrapper
)}
>
{label && (
<label
htmlFor={name}
className={cn(
'w-full text-sm font-normal leading-5',
{
'text-error': isError,
},
className?.label
)}
>
{label}
{required && (
<>
{' '}
<span className='tooltip tooltip-error' data-tip='required'>
<span className='text-error'> *</span>
</span>
</>
)}
</label>
)}
<div
className={cn(
'input h-12 px-4 py-2 text-base font-normal leading-6 w-full rounded-lg! outline-none! transition-all duration-200',
{
'border-error': isError,
'border-success!': isValid,
},
className?.inputWrapper
)}
>
{startAdornment && startAdornment}
<input
type={type}
id={name}
name={name}
placeholder={placeholder}
value={value}
onChange={onChange}
onBlur={onBlur}
disabled={disabled}
className={cn('grow', className?.input)}
readOnly={readOnly}
/>
{(isLoading || endAdornment) && (
<div className='flex flex-row gap-2'>
{isLoading && <span className='loading loading-spinner' />}
{endAdornment && endAdornment}
</div>
)}
</div>
{!isError && bottomLabel && (
<p className='w-full text-sm opacity-60'>{bottomLabel}</p>
)}
{isError && <p className='w-full text-sm text-error'>{errorMessage}</p>}
</div>
);
};
export default TextInput;
+16
View File
@@ -0,0 +1,16 @@
import { ReactNode } from 'react';
import { cn } from '@/lib/helper';
interface MenuProps {
children?: ReactNode;
className?: string;
}
const Menu = ({ children, className }: MenuProps) => {
return (
<ul className={cn('menu w-full p-0 gap-0.5', className)}>{children}</ul>
);
};
export default Menu;
+64
View File
@@ -0,0 +1,64 @@
import Link from 'next/link';
import { Icon } from '@iconify/react';
import { cn } from '@/lib/helper';
interface MenuItemProps {
title: string;
href?: string;
icon?: string;
active?: boolean;
onClick?: () => void;
className?: string;
}
const MenuItem = ({
title,
href,
icon,
active = false,
className,
onClick,
}: MenuItemProps) => {
const menuItemBaseClassName = cn(
'group px-3 py-2 text-base text-black font-semibold flex flex-row items-center rounded-md',
{ 'bg-gray-100 border-l-2 border-l-primary': active },
className
);
const menuItemContent = (
<>
{icon && (
<Icon
icon={icon}
width={20}
height={20}
className={cn('group-active:text-[inherit]', {
'text-gray-400': !active,
'text-black': active,
})}
/>
)}
<span
className={cn({ 'opacity-40': !active }, 'group-active:opacity-100')}
>
{title}
</span>
</>
);
return (
<li onClick={onClick}>
{href && (
<Link href={href} className={menuItemBaseClassName}>
{menuItemContent}
</Link>
)}
{!href && <a className={menuItemBaseClassName}>{menuItemContent}</a>}
</li>
);
};
export default MenuItem;
+75
View File
@@ -0,0 +1,75 @@
export const MAIN_DRAWER_LINKS = [
{
title: 'Dashboard',
link: '/dashboard',
icon: 'gg:chart',
},
{
title: 'Master Data',
link: '/master-data',
icon: 'majesticons:data-line',
submenu: [
{
title: 'Product',
link: '/master-data/product',
icon: 'fluent-mdl2:product-variant',
},
{
title: 'Product Category',
link: '/master-data/product-category',
icon: 'carbon:categories',
},
{
title: 'Bank',
link: '/master-data/Bank',
icon: 'mdi:bank-outline',
},
{
title: 'Area',
link: '/master-data/area',
icon: 'majesticons:map-marker-area-line',
},
{
title: 'Location',
link: '/master-data/location',
icon: 'mingcute:location-line',
},
{
title: 'Kandang',
link: '/master-data/kandang',
icon: 'mdi:farm-home-outline',
},
{
title: 'Warehouse',
link: '/master-data/warehouse',
icon: 'hugeicons:warehouse',
},
{
title: 'Customer',
link: '/master-data/customer',
icon: 'ix:customer',
},
{
title: 'UOM',
link: '/master-data/uom',
icon: 'lsicon:measure-outline',
},
{
title: 'Non-Stock',
link: '/master-data/nonstock',
icon: 'fluent:box-32-regular',
},
{
title: 'FCR',
link: '/master-data/FCR',
icon: 'fluent:food-chicken-leg-16-regular',
},
{
title: 'Supplier',
link: '/master-data/supplier',
icon: 'material-symbols:add-business-outline-rounded',
},
],
},
];
+7
View File
@@ -0,0 +1,7 @@
import { BaseApiResponse, SuccessApiResponse } from '@/types/api';
export const isResponseSuccess = <T>(
res?: BaseApiResponse<T>
): res is SuccessApiResponse<T> => {
return res?.status === 'success';
};
+29
View File
@@ -0,0 +1,29 @@
import moment from 'moment';
import { twMerge } from 'tailwind-merge';
import clsx, { ClassValue } from 'clsx';
export const sleep = (ms: number = 1000) =>
new Promise((resolve) => setTimeout(resolve, ms));
export const formatDate = (date: moment.MomentInput, format?: string) => {
return moment(date).format(format);
};
export const cn = (...inputs: ClassValue[]) => {
return twMerge(clsx(inputs));
};
export const formatCurrency = (
value: number | bigint | Intl.StringNumericLiteral,
currency = 'USD',
locale = 'en-US',
minimumFractionDigits = 0,
maximumFractionDigits = 2
) => {
return new Intl.NumberFormat(locale, {
style: 'currency',
currency,
minimumFractionDigits,
maximumFractionDigits,
}).format(value);
};
+13
View File
@@ -0,0 +1,13 @@
import * as Yup from 'yup';
export const EmailSchema = Yup.string().email('Format email invalid!');
export const PasswordSchema = Yup.string()
.min(8, 'Password harus setidaknya memiliki 8 karakter')
.matches(/[a-z]/, 'Harus memiliki setidaknya 1 huruf kecil')
.matches(/[A-Z]/, 'Harus memiliki setidaknya 1 huruf besar')
.matches(/\d/, 'Harus memiliki setidaknya 1 angka')
.matches(
/[@$!%*?&^#()_\-+={}[\]|:;"'<>,.\\/]/,
'Harus memiliki setidaknya 1 karakter spesial'
);
View File
+25
View File
@@ -0,0 +1,25 @@
import { create } from 'zustand';
import { UserWithRoles } from '@/types/api';
type AuthStore = {
user?: UserWithRoles;
isLoadingUser?: boolean;
setUser: (newUserData?: UserWithRoles) => void;
setIsLoadingUser: (isLoading?: boolean) => void;
};
const useAuthStore = create<AuthStore>()((set) => ({
user: undefined,
isLoadingUser: false,
setUser: (newUserData) => set({ user: newUserData }),
setIsLoadingUser: (isLoading) => set({ isLoadingUser: Boolean(isLoading) }),
}));
export const useAuth = () => {
const { user, setUser } = useAuthStore();
return {
user,
setUser,
};
};
+22
View File
@@ -0,0 +1,22 @@
export type HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
export type AuthMode = 'none' | 'cookie' | 'bearer';
export type RequestOptions<B = unknown> = {
method?: HttpMethod;
body?: B;
query?: Record<string, unknown>;
headers?: Record<string, string>;
auth?: AuthMode; // 'cookie' | 'bearer' | 'none'
token?: string; // required if auth === 'bearer'
timeoutMs?: number;
};
export class HttpError extends Error {
constructor(
public status: number,
public code?: string,
public data?: unknown
) {
super(`HTTP ${status}${code ? ` ${code}` : ''}`);
}
}
+59
View File
@@ -0,0 +1,59 @@
import axios from 'axios';
import type { AxiosRequestConfig } from 'axios';
import { RequestOptions } from '@/services/http/base';
const BASE_URL = process.env.NEXT_PUBLIC_API_BASE_URL ?? '';
const axiosClient = axios.create({ baseURL: BASE_URL, timeout: 10_000 });
export async function httpClient<T, B = unknown>(
path: string,
opts: RequestOptions<B> = {}
): Promise<T> {
const isCookieAuth = opts.auth === 'cookie';
const isBearerAuth = opts.auth === 'bearer' && !!opts.token;
const config: AxiosRequestConfig = {
url: path,
method: opts.method ?? 'GET',
params: opts.query,
data: opts.body,
timeout: opts.timeoutMs ?? 10_000,
withCredentials: isCookieAuth,
headers: {
'Content-Type': 'application/json',
...(opts.headers ?? {}),
...(isBearerAuth ? { Authorization: `Bearer ${opts.token}` } : {}),
},
};
try {
const res = await axiosClient.request<T>(config);
return res.data;
} catch (e: unknown) {
throw e;
}
}
type SWRHttpKey<B = unknown> =
| string
| [path: string, opts?: RequestOptions<B>]
| { path: string; opts?: RequestOptions<B> };
export async function httpClientFetcher<T = unknown, B = unknown>(
key: SWRHttpKey<B>
): Promise<T> {
if (!key) throw new Error('Invalid SWR key');
let path: string;
let opts: RequestOptions<B> | undefined;
if (typeof key === 'string') {
path = key;
} else if (Array.isArray(key)) {
[path, opts] = key;
} else {
({ path, opts } = key);
}
return httpClient<T, B>(path, opts);
}
+12
View File
@@ -0,0 +1,12 @@
import { StateCreator } from 'zustand';
import { MainUiSlice } from '@/types/stores';
export const createMainUiSlice: StateCreator<
MainUiSlice,
[],
[],
MainUiSlice
> = (set): MainUiSlice => ({
mainDrawerOpen: false,
setMainDrawerOpen: (open) => set(() => ({ mainDrawerOpen: open })),
});
+18
View File
@@ -0,0 +1,18 @@
'use client';
import { create } from 'zustand';
import { devtools } from 'zustand/middleware';
import { UIStore } from '@/types/stores';
import { createMainUiSlice } from './slices/main.slice';
export const useUiStore = create<UIStore>()(
devtools(
(...args) => ({
...createMainUiSlice(...args),
}),
{
name: 'UIStore',
}
)
);
+35
View File
@@ -0,0 +1,35 @@
type ErrorApiResponse = {
code: number;
status: 'error';
message: string;
errors?: { [key: string]: string };
};
type SuccessApiResponse<T = unknown> = {
code: number;
status: 'success';
message: string;
meta?: {
page: number;
limit: number;
total_pages: number;
total_results: number;
};
data: T;
};
type BaseApiResponse<T = unknown> = ErrorApiResponse | SuccessApiResponse<T>;
export type User = {
id: number;
email: string;
npk: string;
name: string;
image?: string | null;
created_at: string;
updated_at: string;
};
export type UserWithRoles = User & {
roles: RoleWithPermissions[];
};
+6
View File
@@ -0,0 +1,6 @@
type MainUiSlice = {
mainDrawerOpen: boolean;
setMainDrawerOpen: (open: boolean) => void;
};
export type UIStore = MainUiSlice;
+11
View File
@@ -0,0 +1,11 @@
type Color =
| 'primary'
| 'secondary'
| 'accent'
| 'neutral'
| 'info'
| 'success'
| 'warning'
| 'error';
export { Color };
+27
View File
@@ -0,0 +1,27 @@
{
"compilerOptions": {
"target": "ES2017",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"incremental": true,
"plugins": [
{
"name": "next"
}
],
"paths": {
"@/*": ["./src/*"]
}
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
"exclude": ["node_modules"]
}