Compare commits
42 Commits
5c7d36403f
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| 77b60ba073 | |||
| f213a9455b | |||
| 009ab50b47 | |||
| b1db439dda | |||
| e4abe61781 | |||
| cef8f10990 | |||
| 3f51d2f869 | |||
| 692d907ca5 | |||
| 15c2cce263 | |||
| 3704bd0c23 | |||
| 69c9fd6bef | |||
| 00c8da629c | |||
| ce0c34d014 | |||
| 6c305e0cdd | |||
| b587f8aeb6 | |||
| 6602d29299 | |||
| f4e5979c00 | |||
| e6c7778c08 | |||
| f320f6ff31 | |||
| fc88703a38 | |||
| 787324260c | |||
| 8a866566ba | |||
| 5f0fa91075 | |||
| 6f1547dde7 | |||
| 234f86d6b9 | |||
| 2979634033 | |||
| b07de2b03c | |||
| 4eca3b7124 | |||
| 6abed4e72a | |||
| 214c0be44e | |||
| 68337ba312 | |||
| 84059a84b5 | |||
| ffa41825dd | |||
| 86e5bc6429 | |||
| 3771eb7dca | |||
| 47fa309342 | |||
| 3e3d7686f6 | |||
| eb05cd264d | |||
| c3d233c41a | |||
| 177cc976b4 | |||
| 0749060b1f | |||
| 8a6b438e93 |
@@ -1,32 +0,0 @@
|
||||
import { createApiClient } from "./axios";
|
||||
import { tokenStore } from "./token";
|
||||
|
||||
// @ts-ignore
|
||||
const authApi = createApiClient(import.meta.env.VITE_AUTH_BASE_URL);
|
||||
|
||||
export const authClient = {
|
||||
async login(username: string, password: string) {
|
||||
const res = await authApi.post("/login", { username, password });
|
||||
const { access_token } = res.data;
|
||||
|
||||
if (!access_token) {
|
||||
throw new Error("No access token returned");
|
||||
}
|
||||
|
||||
tokenStore.set(access_token);
|
||||
return this.getIdentity();
|
||||
},
|
||||
|
||||
logout() {
|
||||
tokenStore.clear();
|
||||
},
|
||||
|
||||
async getIdentity() {
|
||||
const res = await authApi.get("/me");
|
||||
return res.data;
|
||||
},
|
||||
|
||||
isAuthenticated() {
|
||||
return !!tokenStore.get();
|
||||
},
|
||||
};
|
||||
@@ -1,5 +1,4 @@
|
||||
import * as React from "react";
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { useAuth, AuthPage } from "../react-auth";
|
||||
import { UploadProvider } from "./providers/UploadProvider";
|
||||
import AdminLayout from "./components/AdminLayout";
|
||||
@@ -8,23 +7,22 @@ import { getAppConfig } from "./config";
|
||||
import { initializeApiClients } from "./api/client";
|
||||
import { AppConfig } from "./types/config";
|
||||
import { Box, Typography, Paper, CircularProgress } from "@mui/material";
|
||||
import AppTheme from "./shared-theme/AppTheme";
|
||||
import {
|
||||
Routes,
|
||||
Route,
|
||||
useNavigate,
|
||||
useParams,
|
||||
Navigate,
|
||||
} from "react-router-dom";
|
||||
|
||||
const queryClient = new QueryClient();
|
||||
|
||||
// Create a context for the app config
|
||||
export const ConfigContext = React.createContext<AppConfig | null>(null);
|
||||
import { ConfigContext } from "./providers/ConfigContext";
|
||||
|
||||
function Dashboard({ basePath }: { basePath: string }) {
|
||||
const config = React.useContext(ConfigContext);
|
||||
const navigate = useNavigate();
|
||||
|
||||
const resources = config?.resources || [];
|
||||
const visibleResources = resources.filter((res) => !res.hidden);
|
||||
|
||||
return (
|
||||
<Box>
|
||||
<Typography variant="h4" gutterBottom>
|
||||
@@ -42,7 +40,7 @@ function Dashboard({ basePath }: { basePath: string }) {
|
||||
mt: 4,
|
||||
}}
|
||||
>
|
||||
{config?.resources.map((res) => (
|
||||
{visibleResources.map((res) => (
|
||||
<Paper
|
||||
key={res.name}
|
||||
sx={{
|
||||
@@ -52,7 +50,7 @@ function Dashboard({ basePath }: { basePath: string }) {
|
||||
transition: 'transform 0.2s',
|
||||
'&:hover': { transform: 'translateY(-4px)', boxShadow: 4 }
|
||||
}}
|
||||
onClick={() => navigate(`${basePath}/${res.name}`)}
|
||||
onClick={() => navigate(`/admin/${res.name}`)}
|
||||
>
|
||||
<Typography variant="h6" color="primary">{res.pluralLabel}</Typography>
|
||||
<Typography variant="body2" color="text.secondary">Manage {res.pluralLabel.toLowerCase()}</Typography>
|
||||
@@ -70,6 +68,9 @@ function AdminApp({ basePath }: { basePath: string }) {
|
||||
const config = React.useContext(ConfigContext);
|
||||
const navigate = useNavigate();
|
||||
|
||||
const resources = config?.resources || [];
|
||||
const visibleResources = resources.filter((res) => !res.hidden);
|
||||
|
||||
if (!currentUser) {
|
||||
return (
|
||||
<AuthPage
|
||||
@@ -89,8 +90,8 @@ function AdminApp({ basePath }: { basePath: string }) {
|
||||
<AdminLayout
|
||||
username={currentUser.username}
|
||||
onLogout={logout}
|
||||
onSelectResource={(name) => navigate(`${basePath}/${name}`)}
|
||||
resources={config?.resources || []}
|
||||
onSelectResource={(name) => navigate(`/admin/${name}`)}
|
||||
resources={visibleResources}
|
||||
>
|
||||
<Routes>
|
||||
<Route path="/" element={<Dashboard basePath={basePath} />} />
|
||||
@@ -114,19 +115,27 @@ function ResourceRouteWrapper() {
|
||||
return <ResourceView config={selectedResource} />;
|
||||
}
|
||||
|
||||
export default function Admin({ basePath = "/admin" }: { basePath?: string }) {
|
||||
const [config, setConfig] = React.useState<AppConfig | null>(null);
|
||||
interface AdminProps {
|
||||
basePath?: string;
|
||||
resourceOverrides?: Record<string, any>;
|
||||
profileConfig?: any;
|
||||
}
|
||||
|
||||
export default function Admin({ basePath = "/admin", resourceOverrides = {}, profileConfig = {} }: AdminProps) {
|
||||
const existingConfig = React.useContext(ConfigContext);
|
||||
const [config, setConfig] = React.useState<AppConfig | null>(existingConfig);
|
||||
|
||||
React.useEffect(() => {
|
||||
getAppConfig().then((cfg) => {
|
||||
if (!existingConfig) {
|
||||
getAppConfig(resourceOverrides, profileConfig).then((cfg) => {
|
||||
initializeApiClients(cfg.baseUrl, cfg.authBaseUrl);
|
||||
setConfig(cfg);
|
||||
});
|
||||
}, []);
|
||||
}
|
||||
}, [resourceOverrides, profileConfig, existingConfig]);
|
||||
|
||||
if (!config) {
|
||||
return (
|
||||
<AppTheme>
|
||||
<Box
|
||||
sx={{
|
||||
display: "flex",
|
||||
@@ -137,19 +146,24 @@ export default function Admin({ basePath = "/admin" }: { basePath?: string }) {
|
||||
>
|
||||
<CircularProgress />
|
||||
</Box>
|
||||
</AppTheme>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<AppTheme>
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<ConfigContext.Provider value={config}>
|
||||
const content = (
|
||||
<UploadProvider>
|
||||
<AdminApp basePath={basePath} />
|
||||
</UploadProvider>
|
||||
);
|
||||
|
||||
// If we have an existing config, we are already inside a Provider and QueryClient
|
||||
if (existingConfig) {
|
||||
return content;
|
||||
}
|
||||
|
||||
// Fallback for standalone usage
|
||||
return (
|
||||
<ConfigContext.Provider value={config}>
|
||||
{content}
|
||||
</ConfigContext.Provider>
|
||||
</QueryClientProvider>
|
||||
</AppTheme>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -7,6 +7,28 @@ import { createApiClient } from "../../react-auth";
|
||||
let _api: AxiosInstance | null = null;
|
||||
let _auth: AxiosInstance | null = null;
|
||||
|
||||
function withParamsSerializer(instance: AxiosInstance): AxiosInstance {
|
||||
instance.defaults.paramsSerializer = {
|
||||
serialize: (params) => {
|
||||
const searchParams = new URLSearchParams();
|
||||
|
||||
Object.entries(params).forEach(([key, value]) => {
|
||||
if (Array.isArray(value)) {
|
||||
value.forEach((v) => {
|
||||
searchParams.append(key, String(v)); // NO []
|
||||
});
|
||||
} else if (value !== undefined && value !== null) {
|
||||
searchParams.append(key, String(value));
|
||||
}
|
||||
});
|
||||
|
||||
return searchParams.toString();
|
||||
},
|
||||
};
|
||||
|
||||
return instance;
|
||||
}
|
||||
|
||||
export const api = {
|
||||
get: (...args: Parameters<AxiosInstance["get"]>) => {
|
||||
if (!_api) throw new Error("API client not initialized");
|
||||
@@ -38,6 +60,6 @@ export const auth = {
|
||||
};
|
||||
|
||||
export function initializeApiClients(baseUrl: string, authBaseUrl: string) {
|
||||
_api = createApiClient(baseUrl);
|
||||
_auth = createApiClient(authBaseUrl);
|
||||
_api = withParamsSerializer(createApiClient(baseUrl));
|
||||
_auth = withParamsSerializer(createApiClient(authBaseUrl));
|
||||
}
|
||||
|
||||
@@ -2,17 +2,12 @@ import * as React from 'react';
|
||||
import {
|
||||
Box,
|
||||
Drawer,
|
||||
AppBar,
|
||||
Toolbar,
|
||||
List,
|
||||
Typography,
|
||||
Divider,
|
||||
ListItem,
|
||||
ListItemButton,
|
||||
ListItemIcon,
|
||||
ListItemText,
|
||||
CssBaseline,
|
||||
Button,
|
||||
IconButton,
|
||||
Tooltip,
|
||||
useMediaQuery,
|
||||
@@ -20,7 +15,6 @@ import {
|
||||
} from '@mui/material';
|
||||
import TableViewIcon from '@mui/icons-material/TableView';
|
||||
import DashboardIcon from '@mui/icons-material/Dashboard';
|
||||
import LogoutIcon from '@mui/icons-material/Logout';
|
||||
import MenuIcon from '@mui/icons-material/Menu';
|
||||
import ChevronLeftIcon from '@mui/icons-material/ChevronLeft';
|
||||
import ChevronRightIcon from '@mui/icons-material/ChevronRight';
|
||||
@@ -41,8 +35,6 @@ interface AdminLayoutProps {
|
||||
export default function AdminLayout({
|
||||
children,
|
||||
onSelectResource,
|
||||
onLogout,
|
||||
username,
|
||||
resources,
|
||||
}: AdminLayoutProps) {
|
||||
const theme = useTheme();
|
||||
@@ -53,15 +45,15 @@ export default function AdminLayout({
|
||||
const [isCollapsed, setIsCollapsed] = React.useState(false);
|
||||
const [mobileOpen, setMobileOpen] = React.useState(false);
|
||||
|
||||
const activeResourceName = location.pathname.split('/')[1] || null;
|
||||
const activeResourceName = location.pathname.split('/admin')[1] || null;
|
||||
|
||||
// AUTO-TOGGLE LOGIC
|
||||
// AUTO-TOGGLE LOGIC (unchanged)
|
||||
React.useEffect(() => {
|
||||
if (isMobile) {
|
||||
setIsCollapsed(false); // Mobile drawer is never "mini"
|
||||
setMobileOpen(false); // Close on navigation
|
||||
setIsCollapsed(false);
|
||||
setMobileOpen(false);
|
||||
} else {
|
||||
if (location.pathname === '/' || location.pathname === '') {
|
||||
if (location.pathname === '/admin' || location.pathname === '') {
|
||||
setIsCollapsed(false);
|
||||
} else {
|
||||
setIsCollapsed(true);
|
||||
@@ -69,21 +61,31 @@ export default function AdminLayout({
|
||||
}
|
||||
}, [location.pathname, isMobile]);
|
||||
|
||||
const currentWidth = isMobile ? drawerWidth : (isCollapsed ? collapsedWidth : drawerWidth);
|
||||
const currentWidth = isMobile
|
||||
? drawerWidth
|
||||
: isCollapsed
|
||||
? collapsedWidth
|
||||
: drawerWidth;
|
||||
|
||||
const handleDrawerToggle = () => {
|
||||
setMobileOpen(!mobileOpen);
|
||||
setMobileOpen((prev) => !prev);
|
||||
};
|
||||
|
||||
const handleSidebarToggle = () => {
|
||||
setIsCollapsed(!isCollapsed);
|
||||
setIsCollapsed((prev) => !prev);
|
||||
};
|
||||
|
||||
const drawerContent = (
|
||||
<Box sx={{ overflow: 'hidden', display: 'flex', flexDirection: 'column', height: '100%' }}>
|
||||
<Box sx={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
|
||||
{!isMobile && (
|
||||
<>
|
||||
<Box sx={{ display: 'flex', justifyContent: isCollapsed ? 'center' : 'flex-end', p: 1 }}>
|
||||
<Box
|
||||
sx={{
|
||||
display: 'flex',
|
||||
justifyContent: isCollapsed ? 'center' : 'flex-end',
|
||||
p: 1,
|
||||
}}
|
||||
>
|
||||
<IconButton onClick={handleSidebarToggle}>
|
||||
{isCollapsed ? <ChevronRightIcon /> : <ChevronLeftIcon />}
|
||||
</IconButton>
|
||||
@@ -91,54 +93,92 @@ export default function AdminLayout({
|
||||
<Divider />
|
||||
</>
|
||||
)}
|
||||
{isMobile && <Toolbar />}
|
||||
|
||||
{/* Mobile spacing (replaces Toolbar) */}
|
||||
{isMobile && (
|
||||
<Box sx={{ height: (theme) => theme.spacing(7) }} />
|
||||
)}
|
||||
|
||||
<List>
|
||||
<ListItem disablePadding>
|
||||
<Tooltip title={(isCollapsed && !isMobile) ? "Dashboard" : ""} placement="right">
|
||||
<Tooltip
|
||||
title={isCollapsed && !isMobile ? 'Dashboard' : ''}
|
||||
placement="right"
|
||||
>
|
||||
<ListItemButton
|
||||
selected={location.pathname === '/'}
|
||||
onClick={() => navigate('/')}
|
||||
selected={location.pathname === '/admin'}
|
||||
onClick={() => navigate('/admin')}
|
||||
sx={{
|
||||
minHeight: 48,
|
||||
justifyContent: (isCollapsed && !isMobile) ? 'center' : 'initial',
|
||||
justifyContent:
|
||||
isCollapsed && !isMobile ? 'center' : 'initial',
|
||||
px: 2.5,
|
||||
}}
|
||||
>
|
||||
<ListItemIcon sx={{
|
||||
<ListItemIcon
|
||||
sx={{
|
||||
minWidth: 0,
|
||||
mr: (isCollapsed && !isMobile) ? 0 : 3,
|
||||
mr: isCollapsed && !isMobile ? 0 : 3,
|
||||
justifyContent: 'center',
|
||||
}}>
|
||||
<DashboardIcon color={location.pathname === '/' ? 'primary' : 'inherit'} />
|
||||
}}
|
||||
>
|
||||
<DashboardIcon
|
||||
color={
|
||||
location.pathname === '/admin'
|
||||
? 'primary'
|
||||
: 'inherit'
|
||||
}
|
||||
/>
|
||||
</ListItemIcon>
|
||||
{(!isCollapsed || isMobile) && <ListItemText primary="Dashboard" />}
|
||||
{(!isCollapsed || isMobile) && (
|
||||
<ListItemText primary="Dashboard" />
|
||||
)}
|
||||
</ListItemButton>
|
||||
</Tooltip>
|
||||
</ListItem>
|
||||
</List>
|
||||
|
||||
<Divider />
|
||||
|
||||
<List sx={{ flexGrow: 1 }}>
|
||||
{resources.map((res) => (
|
||||
<ListItem key={res.name} disablePadding>
|
||||
<Tooltip title={(isCollapsed && !isMobile) ? res.pluralLabel : ""} placement="right">
|
||||
<Tooltip
|
||||
title={
|
||||
isCollapsed && !isMobile ? res.pluralLabel : ''
|
||||
}
|
||||
placement="right"
|
||||
>
|
||||
<ListItemButton
|
||||
selected={activeResourceName === res.name}
|
||||
onClick={() => onSelectResource(res.name)}
|
||||
sx={{
|
||||
minHeight: 48,
|
||||
justifyContent: (isCollapsed && !isMobile) ? 'center' : 'initial',
|
||||
justifyContent:
|
||||
isCollapsed && !isMobile
|
||||
? 'center'
|
||||
: 'initial',
|
||||
px: 2.5,
|
||||
}}
|
||||
>
|
||||
<ListItemIcon sx={{
|
||||
<ListItemIcon
|
||||
sx={{
|
||||
minWidth: 0,
|
||||
mr: (isCollapsed && !isMobile) ? 0 : 3,
|
||||
mr: isCollapsed && !isMobile ? 0 : 3,
|
||||
justifyContent: 'center',
|
||||
}}>
|
||||
<TableViewIcon color={activeResourceName === res.name ? 'primary' : 'inherit'} />
|
||||
}}
|
||||
>
|
||||
<TableViewIcon
|
||||
color={
|
||||
activeResourceName === res.name
|
||||
? 'primary'
|
||||
: 'inherit'
|
||||
}
|
||||
/>
|
||||
</ListItemIcon>
|
||||
{(!isCollapsed || isMobile) && <ListItemText primary={res.pluralLabel} />}
|
||||
{(!isCollapsed || isMobile) && (
|
||||
<ListItemText primary={res.pluralLabel} />
|
||||
)}
|
||||
</ListItemButton>
|
||||
</Tooltip>
|
||||
</ListItem>
|
||||
@@ -149,51 +189,7 @@ export default function AdminLayout({
|
||||
|
||||
return (
|
||||
<Box sx={{ display: 'flex' }}>
|
||||
<CssBaseline />
|
||||
<AppBar
|
||||
position="fixed"
|
||||
sx={{
|
||||
zIndex: (theme) => theme.zIndex.drawer + 1,
|
||||
backdropFilter: 'blur(8px)',
|
||||
backgroundColor: 'rgba(255, 255, 255, 0.8)',
|
||||
color: 'text.primary',
|
||||
boxShadow: 'none',
|
||||
borderBottom: '1px solid',
|
||||
borderColor: 'divider',
|
||||
}}
|
||||
>
|
||||
<Toolbar>
|
||||
{isMobile && (
|
||||
<IconButton
|
||||
color="inherit"
|
||||
aria-label="open drawer"
|
||||
edge="start"
|
||||
onClick={handleDrawerToggle}
|
||||
sx={{ mr: 2 }}
|
||||
>
|
||||
<MenuIcon />
|
||||
</IconButton>
|
||||
)}
|
||||
<Typography variant="h6" noWrap component="div" sx={{ flexGrow: 1, fontWeight: 'bold' }}>
|
||||
Admin Panel
|
||||
</Typography>
|
||||
<Box sx={{ display: { xs: 'none', sm: 'flex' }, alignItems: 'center', mr: 2 }}>
|
||||
<Button
|
||||
color="inherit"
|
||||
onClick={() => navigate('/profile')}
|
||||
sx={{ textTransform: 'none', fontWeight: 500 }}
|
||||
>
|
||||
{username}
|
||||
</Button>
|
||||
</Box>
|
||||
<Tooltip title="Logout">
|
||||
<IconButton color="inherit" onClick={onLogout}>
|
||||
<LogoutIcon />
|
||||
</IconButton>
|
||||
</Tooltip>
|
||||
</Toolbar>
|
||||
</AppBar>
|
||||
|
||||
{/* NAV */}
|
||||
<Box
|
||||
component="nav"
|
||||
sx={{ width: { md: currentWidth }, flexShrink: { md: 0 } }}
|
||||
@@ -206,7 +202,9 @@ export default function AdminLayout({
|
||||
ModalProps={{ keepMounted: true }}
|
||||
sx={{
|
||||
display: { xs: 'block', md: 'none' },
|
||||
'& .MuiDrawer-paper': { boxSizing: 'border-box', width: drawerWidth },
|
||||
'& .MuiDrawer-paper': {
|
||||
width: drawerWidth,
|
||||
},
|
||||
}}
|
||||
>
|
||||
{drawerContent}
|
||||
@@ -214,46 +212,52 @@ export default function AdminLayout({
|
||||
) : (
|
||||
<Drawer
|
||||
variant="permanent"
|
||||
open
|
||||
sx={{
|
||||
display: { xs: 'none', md: 'block' },
|
||||
width: currentWidth,
|
||||
flexShrink: 0,
|
||||
whiteSpace: 'nowrap',
|
||||
boxSizing: 'border-box',
|
||||
transition: (theme) => theme.transitions.create('width', {
|
||||
easing: theme.transitions.easing.sharp,
|
||||
duration: theme.transitions.duration.enteringScreen,
|
||||
}),
|
||||
[`& .MuiDrawer-paper`]: {
|
||||
width: currentWidth,
|
||||
boxSizing: 'border-box',
|
||||
overflowX: 'hidden',
|
||||
transition: (theme) => theme.transitions.create('width', {
|
||||
easing: theme.transitions.easing.sharp,
|
||||
duration: theme.transitions.duration.enteringScreen,
|
||||
}),
|
||||
transition: theme.transitions.create('width'),
|
||||
},
|
||||
}}
|
||||
open
|
||||
>
|
||||
{drawerContent}
|
||||
</Drawer>
|
||||
)}
|
||||
</Box>
|
||||
|
||||
{/* MAIN */}
|
||||
<Box
|
||||
component="main"
|
||||
sx={{
|
||||
flexGrow: 1,
|
||||
p: { xs: 2, md: 3 },
|
||||
width: { xs: '100%', md: `calc(100% - ${currentWidth}px)` },
|
||||
transition: (theme) => theme.transitions.create(['margin', 'width'], {
|
||||
easing: theme.transitions.easing.sharp,
|
||||
duration: theme.transitions.duration.enteringScreen,
|
||||
}),
|
||||
width: {
|
||||
xs: '100%',
|
||||
md: `calc(100% - ${currentWidth}px)`,
|
||||
},
|
||||
}}
|
||||
>
|
||||
<Toolbar />
|
||||
{/* Control row (replaces AppBar) */}
|
||||
{isMobile && (
|
||||
<Box
|
||||
sx={{
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
mb: 2,
|
||||
height: (theme) => theme.spacing(7),
|
||||
}}
|
||||
>
|
||||
<IconButton onClick={handleDrawerToggle}>
|
||||
<MenuIcon />
|
||||
</IconButton>
|
||||
</Box>
|
||||
)}
|
||||
|
||||
{children}
|
||||
</Box>
|
||||
</Box>
|
||||
|
||||
@@ -104,12 +104,12 @@ export default function EnhancedTable({
|
||||
<GridActionsCellItem
|
||||
icon={<VisibilityIcon />}
|
||||
label="View"
|
||||
onClick={() => navigate(`/${config.name}/${params.id}`)}
|
||||
onClick={() => navigate(`/admin/${config.name}/${params.id}`)}
|
||||
/>,
|
||||
<GridActionsCellItem
|
||||
icon={<EditIcon />}
|
||||
label="Edit"
|
||||
onClick={() => navigate(`/${config.name}/edit/${params.id}`)}
|
||||
onClick={() => navigate(`/admin/${config.name}/edit/${params.id}`)}
|
||||
/>,
|
||||
<GridActionsCellItem
|
||||
icon={<DeleteIcon />}
|
||||
@@ -222,8 +222,8 @@ function MobileCardRow({ row, config, onDelete, onNavigate, navigate }: any) {
|
||||
<MoreVertIcon fontSize="small" />
|
||||
</IconButton>
|
||||
<Menu anchorEl={anchorEl} open={open} onClose={handleClose}>
|
||||
<MenuItem onClick={() => { handleClose(); navigate(`/${config.name}/${id}`); }}>View</MenuItem>
|
||||
<MenuItem onClick={() => { handleClose(); navigate(`/${config.name}/edit/${id}`); }}>Edit</MenuItem>
|
||||
<MenuItem onClick={() => { handleClose(); navigate(`/admin/${config.name}/${id}`); }}>View</MenuItem>
|
||||
<MenuItem onClick={() => { handleClose(); navigate(`/admin/${config.name}/edit/${id}`); }}>Edit</MenuItem>
|
||||
<MenuItem onClick={() => { handleClose(); onDelete(id); }} sx={{ color: 'error.main' }}>Delete</MenuItem>
|
||||
</Menu>
|
||||
</Box>
|
||||
@@ -242,7 +242,7 @@ function MobileCardRow({ row, config, onDelete, onNavigate, navigate }: any) {
|
||||
</Box>
|
||||
</CardContent>
|
||||
<CardActions sx={{ justifyContent: 'flex-end', px: 2, pb: 2 }}>
|
||||
<Button size="small" onClick={() => navigate(`/${config.name}/${id}`)}>View Details</Button>
|
||||
<Button size="small" onClick={() => navigate(`/admin/${config.name}/${id}`)}>View Details</Button>
|
||||
</CardActions>
|
||||
</Card>
|
||||
);
|
||||
@@ -359,7 +359,7 @@ function FieldRenderer({ params, field, fieldKey, config, onNavigate, navigate,
|
||||
label={value}
|
||||
size="small"
|
||||
color="primary"
|
||||
onClick={(e) => { e.stopPropagation(); navigate(`/${config.name}/${params.row[config.primaryKey]}`); }}
|
||||
onClick={(e) => { e.stopPropagation(); navigate(`/admin/${config.name}/${params.row[config.primaryKey]}`); }}
|
||||
sx={{ cursor: 'pointer', fontWeight: 'bold' }}
|
||||
/>
|
||||
);
|
||||
|
||||
@@ -11,7 +11,7 @@ import { useUpload } from '../providers/UploadProvider';
|
||||
import { useQueries } from '@tanstack/react-query';
|
||||
import { useResource } from '../hooks/useResource';
|
||||
import FormField from './fields/FormField';
|
||||
import { ConfigContext } from '../Admin';
|
||||
import { ConfigContext } from '../providers/ConfigContext';
|
||||
|
||||
interface GenericFormProps {
|
||||
config: ResourceConfig;
|
||||
@@ -67,6 +67,7 @@ export default function GenericForm({
|
||||
const relationDataMap = React.useMemo(() => {
|
||||
const map: Record<string, any[]> = {};
|
||||
allRelations.forEach((relName, index) => {
|
||||
// @ts-ignore
|
||||
map[relName] = queries[index].data || [];
|
||||
});
|
||||
return map;
|
||||
|
||||
@@ -2,7 +2,7 @@ import * as React from 'react';
|
||||
import { Box, Typography, Paper, CircularProgress, Alert } from '@mui/material';
|
||||
import { useResource } from '../hooks/useResource';
|
||||
import GenericForm from './GenericForm';
|
||||
import { ConfigContext } from '../Admin';
|
||||
import { ConfigContext } from '../providers/ConfigContext';
|
||||
|
||||
export default function ProfileView() {
|
||||
const appConfig = React.useContext(ConfigContext);
|
||||
|
||||
@@ -48,11 +48,11 @@ export default function ResourceView({ config, onNavigateToResource }: ResourceV
|
||||
const deleteMutation = useDelete();
|
||||
|
||||
const handleEdit = (item: any) => {
|
||||
navigate(`/${config.name}/edit/${item[config.primaryKey]}`);
|
||||
navigate(`/admin/${config.name}/edit/${item[config.primaryKey]}`);
|
||||
};
|
||||
|
||||
const handleCreate = () => {
|
||||
navigate(`/${config.name}/create`);
|
||||
navigate(`/admin/${config.name}/create`);
|
||||
};
|
||||
|
||||
const handleSave = async (formData: any) => {
|
||||
@@ -62,7 +62,7 @@ export default function ResourceView({ config, onNavigateToResource }: ResourceV
|
||||
} else {
|
||||
await createMutation.mutateAsync(formData);
|
||||
}
|
||||
navigate(`/${config.name}`);
|
||||
navigate(`/admin/${config.name}`);
|
||||
} catch (err) {
|
||||
console.error('Save failed:', err);
|
||||
}
|
||||
@@ -90,7 +90,7 @@ export default function ResourceView({ config, onNavigateToResource }: ResourceV
|
||||
onEdit={handleEdit}
|
||||
onDelete={handleDelete}
|
||||
onCreate={handleCreate}
|
||||
onNavigateToResource={(res, id) => navigate(`/${res}/${id}`)}
|
||||
onNavigateToResource={(res, id) => navigate(`/admin/${res}/${id}`)}
|
||||
/>
|
||||
) : (
|
||||
<Paper sx={{ p: 4 }}>
|
||||
@@ -98,10 +98,10 @@ export default function ResourceView({ config, onNavigateToResource }: ResourceV
|
||||
config={config}
|
||||
initialData={isCreate ? null : itemQuery.data}
|
||||
onSave={handleSave}
|
||||
onCancel={() => navigate(`/${config.name}`)}
|
||||
onCancel={() => navigate(`/admin/${config.name}`)}
|
||||
loading={createMutation.isPending || updateMutation.isPending}
|
||||
readOnly={isView}
|
||||
onEditClick={() => navigate(`/${config.name}/edit/${id}`)}
|
||||
onEditClick={() => navigate(`/admin/${config.name}/edit/${id}`)}
|
||||
/>
|
||||
</Paper>
|
||||
)}
|
||||
|
||||
@@ -71,7 +71,7 @@ export default function FormField({
|
||||
|
||||
// 2. Relation Handling (Select / Multi-Select)
|
||||
if (field.relation && relationDataMap[field.relation]) {
|
||||
const relationData = relationDataMap[field.relation];
|
||||
const relationData = relationDataMap[field.relation].data;
|
||||
const isArrayRelation = field.type === 'array';
|
||||
|
||||
// Determine how to display the related item
|
||||
|
||||
@@ -1,13 +1,16 @@
|
||||
import { AppConfig } from "./types/config";
|
||||
import { loadConfigFromOpenApi } from "./utils/openapi_loader";
|
||||
|
||||
export async function getAppConfig(): Promise<AppConfig> {
|
||||
export async function getAppConfig(
|
||||
resourceOverrides: Record<string, any> = {},
|
||||
profileConfig: any = {}
|
||||
): Promise<AppConfig> {
|
||||
// @ts-ignore
|
||||
const baseUrl = import.meta.env.VITE_API_BASE_URL
|
||||
|
||||
// @ts-ignore
|
||||
const authBaseUrl = import.meta.env.VITE_AUTH_BASE_URL
|
||||
const config = await loadConfigFromOpenApi(baseUrl);
|
||||
const config = await loadConfigFromOpenApi(baseUrl, resourceOverrides, profileConfig);
|
||||
|
||||
// You can still apply overrides here
|
||||
return {
|
||||
|
||||
@@ -1,16 +1,22 @@
|
||||
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
|
||||
import { api } from "../api/client";
|
||||
import { ResourceConfig } from "../types/config";
|
||||
import { ConfigContext } from "../providers/ConfigContext";
|
||||
import * as React from "react";
|
||||
|
||||
export function useResource<T = any>(config: ResourceConfig) {
|
||||
export function useResource<T = any>(config: ResourceConfig | undefined) {
|
||||
const queryClient = useQueryClient();
|
||||
const { name, endpoint, primaryKey } = config;
|
||||
|
||||
// Return empty/disabled hooks if config is missing
|
||||
const { name = '', endpoint = '', primaryKey = 'id' } = config || {};
|
||||
|
||||
// --- READ ALL ---
|
||||
const useList = (params?: any) =>
|
||||
useQuery({
|
||||
queryKey: [name, "list", params],
|
||||
queryFn: async () => {
|
||||
if (!endpoint) return { data: [], total: 0 };
|
||||
console.log('params:', params);
|
||||
// @ts-ignore
|
||||
const res = await api.get<T[]>(endpoint, { params });
|
||||
const total = res.headers ? parseInt(res.headers['x-total-count'] || res.headers['X-Total-Count']) : undefined;
|
||||
@@ -18,7 +24,8 @@ export function useResource<T = any>(config: ResourceConfig) {
|
||||
data: res.data,
|
||||
total: isNaN(total as any) ? undefined : total
|
||||
};
|
||||
}
|
||||
},
|
||||
enabled: !!endpoint,
|
||||
});
|
||||
|
||||
// --- READ ONE ---
|
||||
@@ -26,18 +33,19 @@ export function useResource<T = any>(config: ResourceConfig) {
|
||||
useQuery({
|
||||
queryKey: [name, "detail", id],
|
||||
queryFn: async () => {
|
||||
if (!id) return null;
|
||||
if (!id || !endpoint) return null;
|
||||
// @ts-ignore
|
||||
const res = await api.get<T>(`${endpoint}/${id}`);
|
||||
return res.data;
|
||||
},
|
||||
enabled: !!id,
|
||||
enabled: !!id && !!endpoint,
|
||||
});
|
||||
|
||||
// --- CREATE ---
|
||||
const useCreate = () =>
|
||||
useMutation({
|
||||
mutationFn: async (data: Partial<T>) => {
|
||||
if (!endpoint) throw new Error("Endpoint not defined");
|
||||
// @ts-ignore
|
||||
const res = await api.post<T>(endpoint, data);
|
||||
return res.data;
|
||||
@@ -51,6 +59,7 @@ export function useResource<T = any>(config: ResourceConfig) {
|
||||
const useUpdate = () =>
|
||||
useMutation({
|
||||
mutationFn: async ({ id, data }: { id: string; data: Partial<T> }) => {
|
||||
if (!endpoint) throw new Error("Endpoint not defined");
|
||||
// @ts-ignore
|
||||
const res = await api.put<T>(`${endpoint}/${id}`, data);
|
||||
return res.data;
|
||||
@@ -67,6 +76,7 @@ export function useResource<T = any>(config: ResourceConfig) {
|
||||
const useDelete = () =>
|
||||
useMutation({
|
||||
mutationFn: async (id: string) => {
|
||||
if (!endpoint) throw new Error("Endpoint not defined");
|
||||
await api.delete(`${endpoint}/${id}`);
|
||||
return id;
|
||||
},
|
||||
@@ -79,6 +89,7 @@ export function useResource<T = any>(config: ResourceConfig) {
|
||||
const getListQueryOptions = (params?: any) => ({
|
||||
queryKey: [name, "list", params],
|
||||
queryFn: async () => {
|
||||
if (!endpoint) return { data: [], total: 0 };
|
||||
// @ts-ignore
|
||||
const res = await api.get<T[]>(endpoint, { params });
|
||||
const total = res.headers ? parseInt(res.headers['x-total-count'] || res.headers['X-Total-Count']) : undefined;
|
||||
@@ -87,6 +98,7 @@ export function useResource<T = any>(config: ResourceConfig) {
|
||||
total: isNaN(total as any) ? undefined : total
|
||||
};
|
||||
},
|
||||
enabled: !!endpoint,
|
||||
});
|
||||
|
||||
// --- READ ME ---
|
||||
@@ -94,16 +106,19 @@ export function useResource<T = any>(config: ResourceConfig) {
|
||||
useQuery({
|
||||
queryKey: [name, "me"],
|
||||
queryFn: async () => {
|
||||
if (!endpoint) return null;
|
||||
// @ts-ignore
|
||||
const res = await api.get<T>(`${endpoint}/me`);
|
||||
return res.data;
|
||||
},
|
||||
enabled: !!endpoint,
|
||||
});
|
||||
|
||||
// --- UPDATE ME ---
|
||||
const useUpdateMe = () =>
|
||||
useMutation({
|
||||
mutationFn: async (data: Partial<T>) => {
|
||||
if (!endpoint) throw new Error("Endpoint not defined");
|
||||
// @ts-ignore
|
||||
const res = await api.put<T>(`${endpoint}/me`, data);
|
||||
return res.data;
|
||||
@@ -125,3 +140,10 @@ export function useResource<T = any>(config: ResourceConfig) {
|
||||
getListQueryOptions,
|
||||
};
|
||||
}
|
||||
|
||||
export function useResourceByName<T = any>(name: string) {
|
||||
const config = React.useContext(ConfigContext);
|
||||
const resourceConfig = config?.resources.find((r) => r.name === name);
|
||||
return useResource<T>(resourceConfig);
|
||||
}
|
||||
|
||||
|
||||
7
react-openapi/index.ts
Normal file
7
react-openapi/index.ts
Normal file
@@ -0,0 +1,7 @@
|
||||
export { default as Admin } from "./Admin";
|
||||
export { api, auth, initializeApiClients } from "./api/client";
|
||||
export { getAppConfig } from "./config";
|
||||
export type { AppConfig, ResourceConfig, ResourceField } from "./types/config";
|
||||
export { AppProvider } from "./providers/AppProvider";
|
||||
export { ConfigContext, useConfig } from "./providers/ConfigContext";
|
||||
export { useResource, useResourceByName } from "./hooks/useResource";
|
||||
70
react-openapi/providers/AppProvider.tsx
Normal file
70
react-openapi/providers/AppProvider.tsx
Normal file
@@ -0,0 +1,70 @@
|
||||
import * as React from "react";
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { ConfigContext } from "./ConfigContext";
|
||||
import { getAppConfig } from "../config";
|
||||
import { initializeApiClients } from "../api/client";
|
||||
import { AppConfig } from "../types/config";
|
||||
import { Box, CircularProgress } from "@mui/material";
|
||||
|
||||
const defaultQueryClient = new QueryClient({
|
||||
defaultOptions: {
|
||||
queries: {
|
||||
staleTime: 5 * 60 * 1000,
|
||||
retry: 1,
|
||||
refetchOnWindowFocus: false,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
interface AppProviderProps {
|
||||
children: React.ReactNode;
|
||||
resourceOverrides?: Record<string, any>;
|
||||
profileConfig?: any;
|
||||
queryClient?: QueryClient;
|
||||
}
|
||||
|
||||
export function AppProvider({
|
||||
children,
|
||||
resourceOverrides = {},
|
||||
profileConfig = {},
|
||||
queryClient = defaultQueryClient,
|
||||
}: AppProviderProps) {
|
||||
const [config, setConfig] = React.useState<AppConfig | null>(null);
|
||||
const [loading, setLoading] = React.useState(true);
|
||||
|
||||
React.useEffect(() => {
|
||||
getAppConfig(resourceOverrides, profileConfig)
|
||||
.then((cfg) => {
|
||||
initializeApiClients(cfg.baseUrl, cfg.authBaseUrl);
|
||||
setConfig(cfg);
|
||||
setLoading(false);
|
||||
})
|
||||
.catch((err) => {
|
||||
console.error("Failed to load OpenAPI configuration:", err);
|
||||
setLoading(false);
|
||||
});
|
||||
}, [resourceOverrides, profileConfig]);
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<Box
|
||||
sx={{
|
||||
display: "flex",
|
||||
justifyContent: "center",
|
||||
alignItems: "center",
|
||||
height: "100vh",
|
||||
}}
|
||||
>
|
||||
<CircularProgress />
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<ConfigContext.Provider value={config}>
|
||||
{children}
|
||||
</ConfigContext.Provider>
|
||||
</QueryClientProvider>
|
||||
);
|
||||
}
|
||||
12
react-openapi/providers/ConfigContext.tsx
Normal file
12
react-openapi/providers/ConfigContext.tsx
Normal file
@@ -0,0 +1,12 @@
|
||||
import * as React from "react";
|
||||
import { AppConfig } from "../types/config";
|
||||
|
||||
export const ConfigContext = React.createContext<AppConfig | null>(null);
|
||||
|
||||
export function useConfig() {
|
||||
const context = React.useContext(ConfigContext);
|
||||
if (context === undefined) {
|
||||
throw new Error("useConfig must be used within a ConfigProvider");
|
||||
}
|
||||
return context;
|
||||
}
|
||||
@@ -1,53 +0,0 @@
|
||||
import * as React from 'react';
|
||||
import { ThemeProvider, createTheme } from '@mui/material/styles';
|
||||
import type { ThemeOptions } from '@mui/material/styles';
|
||||
import { inputsCustomizations } from './customizations/inputs';
|
||||
import { dataDisplayCustomizations } from './customizations/dataDisplay';
|
||||
import { feedbackCustomizations } from './customizations/feedback';
|
||||
import { navigationCustomizations } from './customizations/navigation';
|
||||
import { surfacesCustomizations } from './customizations/surfaces';
|
||||
import { colorSchemes, typography, shadows, shape } from './themePrimitives';
|
||||
|
||||
interface AppThemeProps {
|
||||
children: React.ReactNode;
|
||||
/**
|
||||
* This is for the docs site. You can ignore it or remove it.
|
||||
*/
|
||||
disableCustomTheme?: boolean;
|
||||
themeComponents?: ThemeOptions['components'];
|
||||
}
|
||||
|
||||
export default function AppTheme(props: AppThemeProps) {
|
||||
const { children, disableCustomTheme, themeComponents } = props;
|
||||
const theme = React.useMemo(() => {
|
||||
return disableCustomTheme
|
||||
? {}
|
||||
: createTheme({
|
||||
// For more details about CSS variables configuration, see https://mui.com/material-ui/customization/css-theme-variables/configuration/
|
||||
cssVariables: {
|
||||
colorSchemeSelector: 'data-mui-color-scheme',
|
||||
cssVarPrefix: 'template',
|
||||
},
|
||||
colorSchemes, // Recently added in v6 for building light & dark mode app, see https://mui.com/material-ui/customization/palette/#color-schemes
|
||||
typography,
|
||||
shadows,
|
||||
shape,
|
||||
components: {
|
||||
...inputsCustomizations,
|
||||
...dataDisplayCustomizations,
|
||||
...feedbackCustomizations,
|
||||
...navigationCustomizations,
|
||||
...surfacesCustomizations,
|
||||
...themeComponents,
|
||||
},
|
||||
});
|
||||
}, [disableCustomTheme, themeComponents]);
|
||||
if (disableCustomTheme) {
|
||||
return <React.Fragment>{children}</React.Fragment>;
|
||||
}
|
||||
return (
|
||||
<ThemeProvider theme={theme} disableTransitionOnChange>
|
||||
{children}
|
||||
</ThemeProvider>
|
||||
);
|
||||
}
|
||||
@@ -1,89 +0,0 @@
|
||||
import * as React from 'react';
|
||||
import DarkModeIcon from '@mui/icons-material/DarkModeRounded';
|
||||
import LightModeIcon from '@mui/icons-material/LightModeRounded';
|
||||
import Box from '@mui/material/Box';
|
||||
import IconButton, { IconButtonOwnProps } from '@mui/material/IconButton';
|
||||
import Menu from '@mui/material/Menu';
|
||||
import MenuItem from '@mui/material/MenuItem';
|
||||
import { useColorScheme } from '@mui/material/styles';
|
||||
|
||||
export default function ColorModeIconDropdown(props: IconButtonOwnProps) {
|
||||
const { mode, systemMode, setMode } = useColorScheme();
|
||||
const [anchorEl, setAnchorEl] = React.useState<null | HTMLElement>(null);
|
||||
const open = Boolean(anchorEl);
|
||||
const handleClick = (event: React.MouseEvent<HTMLElement>) => {
|
||||
setAnchorEl(event.currentTarget);
|
||||
};
|
||||
const handleClose = () => {
|
||||
setAnchorEl(null);
|
||||
};
|
||||
const handleMode = (targetMode: 'system' | 'light' | 'dark') => () => {
|
||||
setMode(targetMode);
|
||||
handleClose();
|
||||
};
|
||||
if (!mode) {
|
||||
return (
|
||||
<Box
|
||||
data-screenshot="toggle-mode"
|
||||
sx={(theme) => ({
|
||||
verticalAlign: 'bottom',
|
||||
display: 'inline-flex',
|
||||
width: '2.25rem',
|
||||
height: '2.25rem',
|
||||
borderRadius: (theme.vars || theme).shape.borderRadius,
|
||||
border: '1px solid',
|
||||
borderColor: (theme.vars || theme).palette.divider,
|
||||
})}
|
||||
/>
|
||||
);
|
||||
}
|
||||
const resolvedMode = (systemMode || mode) as 'light' | 'dark';
|
||||
const icon = {
|
||||
light: <LightModeIcon />,
|
||||
dark: <DarkModeIcon />,
|
||||
}[resolvedMode];
|
||||
return (
|
||||
<React.Fragment>
|
||||
<IconButton
|
||||
data-screenshot="toggle-mode"
|
||||
onClick={handleClick}
|
||||
disableRipple
|
||||
size="small"
|
||||
aria-controls={open ? 'color-scheme-menu' : undefined}
|
||||
aria-haspopup="true"
|
||||
aria-expanded={open ? 'true' : undefined}
|
||||
{...props}
|
||||
>
|
||||
{icon}
|
||||
</IconButton>
|
||||
<Menu
|
||||
anchorEl={anchorEl}
|
||||
id="account-menu"
|
||||
open={open}
|
||||
onClose={handleClose}
|
||||
onClick={handleClose}
|
||||
slotProps={{
|
||||
paper: {
|
||||
variant: 'outlined',
|
||||
elevation: 0,
|
||||
sx: {
|
||||
my: '4px',
|
||||
},
|
||||
},
|
||||
}}
|
||||
transformOrigin={{ horizontal: 'right', vertical: 'top' }}
|
||||
anchorOrigin={{ horizontal: 'right', vertical: 'bottom' }}
|
||||
>
|
||||
<MenuItem selected={mode === 'system'} onClick={handleMode('system')}>
|
||||
System
|
||||
</MenuItem>
|
||||
<MenuItem selected={mode === 'light'} onClick={handleMode('light')}>
|
||||
Light
|
||||
</MenuItem>
|
||||
<MenuItem selected={mode === 'dark'} onClick={handleMode('dark')}>
|
||||
Dark
|
||||
</MenuItem>
|
||||
</Menu>
|
||||
</React.Fragment>
|
||||
);
|
||||
}
|
||||
@@ -1,28 +0,0 @@
|
||||
import * as React from 'react';
|
||||
import { useColorScheme } from '@mui/material/styles';
|
||||
import MenuItem from '@mui/material/MenuItem';
|
||||
import Select, { SelectProps } from '@mui/material/Select';
|
||||
|
||||
export default function ColorModeSelect(props: SelectProps) {
|
||||
const { mode, setMode } = useColorScheme();
|
||||
if (!mode) {
|
||||
return null;
|
||||
}
|
||||
return (
|
||||
<Select
|
||||
value={mode}
|
||||
onChange={(event) =>
|
||||
setMode(event.target.value as 'system' | 'light' | 'dark')
|
||||
}
|
||||
SelectDisplayProps={{
|
||||
// @ts-ignore
|
||||
'data-screenshot': 'toggle-mode',
|
||||
}}
|
||||
{...props}
|
||||
>
|
||||
<MenuItem value="system">System</MenuItem>
|
||||
<MenuItem value="light">Light</MenuItem>
|
||||
<MenuItem value="dark">Dark</MenuItem>
|
||||
</Select>
|
||||
);
|
||||
}
|
||||
@@ -1,233 +0,0 @@
|
||||
import { Theme, alpha, Components } from '@mui/material/styles';
|
||||
import { svgIconClasses } from '@mui/material/SvgIcon';
|
||||
import { typographyClasses } from '@mui/material/Typography';
|
||||
import { buttonBaseClasses } from '@mui/material/ButtonBase';
|
||||
import { chipClasses } from '@mui/material/Chip';
|
||||
import { iconButtonClasses } from '@mui/material/IconButton';
|
||||
import { gray, red, green } from '../themePrimitives';
|
||||
|
||||
/* eslint-disable import/prefer-default-export */
|
||||
export const dataDisplayCustomizations: Components<Theme> = {
|
||||
MuiList: {
|
||||
styleOverrides: {
|
||||
root: {
|
||||
padding: '8px',
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
gap: 0,
|
||||
},
|
||||
},
|
||||
},
|
||||
MuiListItem: {
|
||||
styleOverrides: {
|
||||
root: ({ theme }) => ({
|
||||
[`& .${svgIconClasses.root}`]: {
|
||||
width: '1rem',
|
||||
height: '1rem',
|
||||
color: (theme.vars || theme).palette.text.secondary,
|
||||
},
|
||||
[`& .${typographyClasses.root}`]: {
|
||||
fontWeight: 500,
|
||||
},
|
||||
[`& .${buttonBaseClasses.root}`]: {
|
||||
display: 'flex',
|
||||
gap: 8,
|
||||
padding: '2px 8px',
|
||||
borderRadius: (theme.vars || theme).shape.borderRadius,
|
||||
opacity: 0.7,
|
||||
'&.Mui-selected': {
|
||||
opacity: 1,
|
||||
backgroundColor: alpha(theme.palette.action.selected, 0.3),
|
||||
[`& .${svgIconClasses.root}`]: {
|
||||
color: (theme.vars || theme).palette.text.primary,
|
||||
},
|
||||
'&:focus-visible': {
|
||||
backgroundColor: alpha(theme.palette.action.selected, 0.3),
|
||||
},
|
||||
'&:hover': {
|
||||
backgroundColor: alpha(theme.palette.action.selected, 0.5),
|
||||
},
|
||||
},
|
||||
'&:focus-visible': {
|
||||
backgroundColor: 'transparent',
|
||||
},
|
||||
},
|
||||
}),
|
||||
},
|
||||
},
|
||||
MuiListItemText: {
|
||||
styleOverrides: {
|
||||
primary: ({ theme }) => ({
|
||||
fontSize: theme.typography.body2.fontSize,
|
||||
fontWeight: 500,
|
||||
lineHeight: theme.typography.body2.lineHeight,
|
||||
}),
|
||||
secondary: ({ theme }) => ({
|
||||
fontSize: theme.typography.caption.fontSize,
|
||||
lineHeight: theme.typography.caption.lineHeight,
|
||||
}),
|
||||
},
|
||||
},
|
||||
MuiListSubheader: {
|
||||
styleOverrides: {
|
||||
root: ({ theme }) => ({
|
||||
backgroundColor: 'transparent',
|
||||
padding: '4px 8px',
|
||||
fontSize: theme.typography.caption.fontSize,
|
||||
fontWeight: 500,
|
||||
lineHeight: theme.typography.caption.lineHeight,
|
||||
}),
|
||||
},
|
||||
},
|
||||
MuiListItemIcon: {
|
||||
styleOverrides: {
|
||||
root: {
|
||||
minWidth: 0,
|
||||
},
|
||||
},
|
||||
},
|
||||
MuiChip: {
|
||||
defaultProps: {
|
||||
size: 'small',
|
||||
},
|
||||
styleOverrides: {
|
||||
root: ({ theme }) => ({
|
||||
border: '1px solid',
|
||||
borderRadius: '999px',
|
||||
[`& .${chipClasses.label}`]: {
|
||||
fontWeight: 600,
|
||||
},
|
||||
variants: [
|
||||
{
|
||||
props: {
|
||||
color: 'default',
|
||||
},
|
||||
style: {
|
||||
borderColor: gray[200],
|
||||
backgroundColor: gray[100],
|
||||
[`& .${chipClasses.label}`]: {
|
||||
color: gray[500],
|
||||
},
|
||||
[`& .${chipClasses.icon}`]: {
|
||||
color: gray[500],
|
||||
},
|
||||
...theme.applyStyles('dark', {
|
||||
borderColor: gray[700],
|
||||
backgroundColor: gray[800],
|
||||
[`& .${chipClasses.label}`]: {
|
||||
color: gray[300],
|
||||
},
|
||||
[`& .${chipClasses.icon}`]: {
|
||||
color: gray[300],
|
||||
},
|
||||
}),
|
||||
},
|
||||
},
|
||||
{
|
||||
props: {
|
||||
color: 'success',
|
||||
},
|
||||
style: {
|
||||
borderColor: green[200],
|
||||
backgroundColor: green[50],
|
||||
[`& .${chipClasses.label}`]: {
|
||||
color: green[500],
|
||||
},
|
||||
[`& .${chipClasses.icon}`]: {
|
||||
color: green[500],
|
||||
},
|
||||
...theme.applyStyles('dark', {
|
||||
borderColor: green[800],
|
||||
backgroundColor: green[900],
|
||||
[`& .${chipClasses.label}`]: {
|
||||
color: green[300],
|
||||
},
|
||||
[`& .${chipClasses.icon}`]: {
|
||||
color: green[300],
|
||||
},
|
||||
}),
|
||||
},
|
||||
},
|
||||
{
|
||||
props: {
|
||||
color: 'error',
|
||||
},
|
||||
style: {
|
||||
borderColor: red[100],
|
||||
backgroundColor: red[50],
|
||||
[`& .${chipClasses.label}`]: {
|
||||
color: red[500],
|
||||
},
|
||||
[`& .${chipClasses.icon}`]: {
|
||||
color: red[500],
|
||||
},
|
||||
...theme.applyStyles('dark', {
|
||||
borderColor: red[800],
|
||||
backgroundColor: red[900],
|
||||
[`& .${chipClasses.label}`]: {
|
||||
color: red[200],
|
||||
},
|
||||
[`& .${chipClasses.icon}`]: {
|
||||
color: red[300],
|
||||
},
|
||||
}),
|
||||
},
|
||||
},
|
||||
{
|
||||
props: { size: 'small' },
|
||||
style: {
|
||||
maxHeight: 20,
|
||||
[`& .${chipClasses.label}`]: {
|
||||
fontSize: theme.typography.caption.fontSize,
|
||||
},
|
||||
[`& .${svgIconClasses.root}`]: {
|
||||
fontSize: theme.typography.caption.fontSize,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
props: { size: 'medium' },
|
||||
style: {
|
||||
[`& .${chipClasses.label}`]: {
|
||||
fontSize: theme.typography.caption.fontSize,
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
}),
|
||||
},
|
||||
},
|
||||
MuiTablePagination: {
|
||||
styleOverrides: {
|
||||
actions: {
|
||||
display: 'flex',
|
||||
gap: 8,
|
||||
marginRight: 6,
|
||||
[`& .${iconButtonClasses.root}`]: {
|
||||
minWidth: 0,
|
||||
width: 36,
|
||||
height: 36,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
MuiIcon: {
|
||||
defaultProps: {
|
||||
fontSize: 'small',
|
||||
},
|
||||
styleOverrides: {
|
||||
root: {
|
||||
variants: [
|
||||
{
|
||||
props: {
|
||||
fontSize: 'small',
|
||||
},
|
||||
style: {
|
||||
fontSize: '1rem',
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
@@ -1,46 +0,0 @@
|
||||
import { Theme, alpha, Components } from '@mui/material/styles';
|
||||
import { gray, orange } from '../themePrimitives';
|
||||
|
||||
/* eslint-disable import/prefer-default-export */
|
||||
export const feedbackCustomizations: Components<Theme> = {
|
||||
MuiAlert: {
|
||||
styleOverrides: {
|
||||
root: ({ theme }) => ({
|
||||
borderRadius: 10,
|
||||
backgroundColor: orange[100],
|
||||
color: (theme.vars || theme).palette.text.primary,
|
||||
border: `1px solid ${alpha(orange[300], 0.5)}`,
|
||||
'& .MuiAlert-icon': {
|
||||
color: orange[500],
|
||||
},
|
||||
...theme.applyStyles('dark', {
|
||||
backgroundColor: `${alpha(orange[900], 0.5)}`,
|
||||
border: `1px solid ${alpha(orange[800], 0.5)}`,
|
||||
}),
|
||||
}),
|
||||
},
|
||||
},
|
||||
MuiDialog: {
|
||||
styleOverrides: {
|
||||
root: ({ theme }) => ({
|
||||
'& .MuiDialog-paper': {
|
||||
borderRadius: '10px',
|
||||
border: '1px solid',
|
||||
borderColor: (theme.vars || theme).palette.divider,
|
||||
},
|
||||
}),
|
||||
},
|
||||
},
|
||||
MuiLinearProgress: {
|
||||
styleOverrides: {
|
||||
root: ({ theme }) => ({
|
||||
height: 8,
|
||||
borderRadius: 8,
|
||||
backgroundColor: gray[200],
|
||||
...theme.applyStyles('dark', {
|
||||
backgroundColor: gray[800],
|
||||
}),
|
||||
}),
|
||||
},
|
||||
},
|
||||
};
|
||||
@@ -1,445 +0,0 @@
|
||||
import * as React from 'react';
|
||||
import { alpha, Theme, Components } from '@mui/material/styles';
|
||||
import { outlinedInputClasses } from '@mui/material/OutlinedInput';
|
||||
import { svgIconClasses } from '@mui/material/SvgIcon';
|
||||
import { toggleButtonGroupClasses } from '@mui/material/ToggleButtonGroup';
|
||||
import { toggleButtonClasses } from '@mui/material/ToggleButton';
|
||||
import CheckBoxOutlineBlankRoundedIcon from '@mui/icons-material/CheckBoxOutlineBlankRounded';
|
||||
import CheckRoundedIcon from '@mui/icons-material/CheckRounded';
|
||||
import RemoveRoundedIcon from '@mui/icons-material/RemoveRounded';
|
||||
import { gray, brand } from '../themePrimitives';
|
||||
|
||||
/* eslint-disable import/prefer-default-export */
|
||||
export const inputsCustomizations: Components<Theme> = {
|
||||
MuiButtonBase: {
|
||||
defaultProps: {
|
||||
disableTouchRipple: true,
|
||||
disableRipple: true,
|
||||
},
|
||||
styleOverrides: {
|
||||
root: ({ theme }) => ({
|
||||
boxSizing: 'border-box',
|
||||
transition: 'all 100ms ease-in',
|
||||
'&:focus-visible': {
|
||||
outline: `3px solid ${alpha(theme.palette.primary.main, 0.5)}`,
|
||||
outlineOffset: '2px',
|
||||
},
|
||||
}),
|
||||
},
|
||||
},
|
||||
MuiButton: {
|
||||
styleOverrides: {
|
||||
root: ({ theme }) => ({
|
||||
boxShadow: 'none',
|
||||
borderRadius: (theme.vars || theme).shape.borderRadius,
|
||||
textTransform: 'none',
|
||||
variants: [
|
||||
{
|
||||
props: {
|
||||
size: 'small',
|
||||
},
|
||||
style: {
|
||||
height: '2.25rem',
|
||||
padding: '8px 12px',
|
||||
},
|
||||
},
|
||||
{
|
||||
props: {
|
||||
size: 'medium',
|
||||
},
|
||||
style: {
|
||||
height: '2.5rem', // 40px
|
||||
},
|
||||
},
|
||||
{
|
||||
props: {
|
||||
color: 'primary',
|
||||
variant: 'contained',
|
||||
},
|
||||
style: {
|
||||
color: 'white',
|
||||
backgroundColor: gray[900],
|
||||
backgroundImage: `linear-gradient(to bottom, ${gray[700]}, ${gray[800]})`,
|
||||
boxShadow: `inset 0 1px 0 ${gray[600]}, inset 0 -1px 0 1px hsl(220, 0%, 0%)`,
|
||||
border: `1px solid ${gray[700]}`,
|
||||
'&:hover': {
|
||||
backgroundImage: 'none',
|
||||
backgroundColor: gray[700],
|
||||
boxShadow: 'none',
|
||||
},
|
||||
'&:active': {
|
||||
backgroundColor: gray[800],
|
||||
},
|
||||
...theme.applyStyles('dark', {
|
||||
color: 'black',
|
||||
backgroundColor: gray[50],
|
||||
backgroundImage: `linear-gradient(to bottom, ${gray[100]}, ${gray[50]})`,
|
||||
boxShadow: 'inset 0 -1px 0 hsl(220, 30%, 80%)',
|
||||
border: `1px solid ${gray[50]}`,
|
||||
'&:hover': {
|
||||
backgroundImage: 'none',
|
||||
backgroundColor: gray[300],
|
||||
boxShadow: 'none',
|
||||
},
|
||||
'&:active': {
|
||||
backgroundColor: gray[400],
|
||||
},
|
||||
}),
|
||||
},
|
||||
},
|
||||
{
|
||||
props: {
|
||||
color: 'secondary',
|
||||
variant: 'contained',
|
||||
},
|
||||
style: {
|
||||
color: 'white',
|
||||
backgroundColor: brand[300],
|
||||
backgroundImage: `linear-gradient(to bottom, ${alpha(brand[400], 0.8)}, ${brand[500]})`,
|
||||
boxShadow: `inset 0 2px 0 ${alpha(brand[200], 0.2)}, inset 0 -2px 0 ${alpha(brand[700], 0.4)}`,
|
||||
border: `1px solid ${brand[500]}`,
|
||||
'&:hover': {
|
||||
backgroundColor: brand[700],
|
||||
boxShadow: 'none',
|
||||
},
|
||||
'&:active': {
|
||||
backgroundColor: brand[700],
|
||||
backgroundImage: 'none',
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
props: {
|
||||
variant: 'outlined',
|
||||
},
|
||||
style: {
|
||||
color: (theme.vars || theme).palette.text.primary,
|
||||
border: '1px solid',
|
||||
borderColor: gray[200],
|
||||
backgroundColor: alpha(gray[50], 0.3),
|
||||
'&:hover': {
|
||||
backgroundColor: gray[100],
|
||||
borderColor: gray[300],
|
||||
},
|
||||
'&:active': {
|
||||
backgroundColor: gray[200],
|
||||
},
|
||||
...theme.applyStyles('dark', {
|
||||
backgroundColor: gray[800],
|
||||
borderColor: gray[700],
|
||||
|
||||
'&:hover': {
|
||||
backgroundColor: gray[900],
|
||||
borderColor: gray[600],
|
||||
},
|
||||
'&:active': {
|
||||
backgroundColor: gray[900],
|
||||
},
|
||||
}),
|
||||
},
|
||||
},
|
||||
{
|
||||
props: {
|
||||
color: 'secondary',
|
||||
variant: 'outlined',
|
||||
},
|
||||
style: {
|
||||
color: brand[700],
|
||||
border: '1px solid',
|
||||
borderColor: brand[200],
|
||||
backgroundColor: brand[50],
|
||||
'&:hover': {
|
||||
backgroundColor: brand[100],
|
||||
borderColor: brand[400],
|
||||
},
|
||||
'&:active': {
|
||||
backgroundColor: alpha(brand[200], 0.7),
|
||||
},
|
||||
...theme.applyStyles('dark', {
|
||||
color: brand[50],
|
||||
border: '1px solid',
|
||||
borderColor: brand[900],
|
||||
backgroundColor: alpha(brand[900], 0.3),
|
||||
'&:hover': {
|
||||
borderColor: brand[700],
|
||||
backgroundColor: alpha(brand[900], 0.6),
|
||||
},
|
||||
'&:active': {
|
||||
backgroundColor: alpha(brand[900], 0.5),
|
||||
},
|
||||
}),
|
||||
},
|
||||
},
|
||||
{
|
||||
props: {
|
||||
variant: 'text',
|
||||
},
|
||||
style: {
|
||||
color: gray[600],
|
||||
'&:hover': {
|
||||
backgroundColor: gray[100],
|
||||
},
|
||||
'&:active': {
|
||||
backgroundColor: gray[200],
|
||||
},
|
||||
...theme.applyStyles('dark', {
|
||||
color: gray[50],
|
||||
'&:hover': {
|
||||
backgroundColor: gray[700],
|
||||
},
|
||||
'&:active': {
|
||||
backgroundColor: alpha(gray[700], 0.7),
|
||||
},
|
||||
}),
|
||||
},
|
||||
},
|
||||
{
|
||||
props: {
|
||||
color: 'secondary',
|
||||
variant: 'text',
|
||||
},
|
||||
style: {
|
||||
color: brand[700],
|
||||
'&:hover': {
|
||||
backgroundColor: alpha(brand[100], 0.5),
|
||||
},
|
||||
'&:active': {
|
||||
backgroundColor: alpha(brand[200], 0.7),
|
||||
},
|
||||
...theme.applyStyles('dark', {
|
||||
color: brand[100],
|
||||
'&:hover': {
|
||||
backgroundColor: alpha(brand[900], 0.5),
|
||||
},
|
||||
'&:active': {
|
||||
backgroundColor: alpha(brand[900], 0.3),
|
||||
},
|
||||
}),
|
||||
},
|
||||
},
|
||||
],
|
||||
}),
|
||||
},
|
||||
},
|
||||
MuiIconButton: {
|
||||
styleOverrides: {
|
||||
root: ({ theme }) => ({
|
||||
boxShadow: 'none',
|
||||
borderRadius: (theme.vars || theme).shape.borderRadius,
|
||||
textTransform: 'none',
|
||||
fontWeight: theme.typography.fontWeightMedium,
|
||||
letterSpacing: 0,
|
||||
color: (theme.vars || theme).palette.text.primary,
|
||||
border: '1px solid ',
|
||||
borderColor: gray[200],
|
||||
backgroundColor: alpha(gray[50], 0.3),
|
||||
'&:hover': {
|
||||
backgroundColor: gray[100],
|
||||
borderColor: gray[300],
|
||||
},
|
||||
'&:active': {
|
||||
backgroundColor: gray[200],
|
||||
},
|
||||
...theme.applyStyles('dark', {
|
||||
backgroundColor: gray[800],
|
||||
borderColor: gray[700],
|
||||
'&:hover': {
|
||||
backgroundColor: gray[900],
|
||||
borderColor: gray[600],
|
||||
},
|
||||
'&:active': {
|
||||
backgroundColor: gray[900],
|
||||
},
|
||||
}),
|
||||
variants: [
|
||||
{
|
||||
props: {
|
||||
size: 'small',
|
||||
},
|
||||
style: {
|
||||
width: '2.25rem',
|
||||
height: '2.25rem',
|
||||
padding: '0.25rem',
|
||||
[`& .${svgIconClasses.root}`]: { fontSize: '1rem' },
|
||||
},
|
||||
},
|
||||
{
|
||||
props: {
|
||||
size: 'medium',
|
||||
},
|
||||
style: {
|
||||
width: '2.5rem',
|
||||
height: '2.5rem',
|
||||
},
|
||||
},
|
||||
],
|
||||
}),
|
||||
},
|
||||
},
|
||||
MuiToggleButtonGroup: {
|
||||
styleOverrides: {
|
||||
root: ({ theme }) => ({
|
||||
borderRadius: '10px',
|
||||
boxShadow: `0 4px 16px ${alpha(gray[400], 0.2)}`,
|
||||
[`& .${toggleButtonGroupClasses.selected}`]: {
|
||||
color: brand[500],
|
||||
},
|
||||
...theme.applyStyles('dark', {
|
||||
[`& .${toggleButtonGroupClasses.selected}`]: {
|
||||
color: '#fff',
|
||||
},
|
||||
boxShadow: `0 4px 16px ${alpha(brand[700], 0.5)}`,
|
||||
}),
|
||||
}),
|
||||
},
|
||||
},
|
||||
MuiToggleButton: {
|
||||
styleOverrides: {
|
||||
root: ({ theme }) => ({
|
||||
padding: '12px 16px',
|
||||
textTransform: 'none',
|
||||
borderRadius: '10px',
|
||||
fontWeight: 500,
|
||||
...theme.applyStyles('dark', {
|
||||
color: gray[400],
|
||||
boxShadow: '0 4px 16px rgba(0, 0, 0, 0.5)',
|
||||
[`&.${toggleButtonClasses.selected}`]: {
|
||||
color: brand[300],
|
||||
},
|
||||
}),
|
||||
}),
|
||||
},
|
||||
},
|
||||
MuiCheckbox: {
|
||||
defaultProps: {
|
||||
disableRipple: true,
|
||||
icon: (
|
||||
<CheckBoxOutlineBlankRoundedIcon sx={{ color: 'hsla(210, 0%, 0%, 0.0)' }} />
|
||||
),
|
||||
checkedIcon: <CheckRoundedIcon sx={{ height: 14, width: 14 }} />,
|
||||
indeterminateIcon: <RemoveRoundedIcon sx={{ height: 14, width: 14 }} />,
|
||||
},
|
||||
styleOverrides: {
|
||||
root: ({ theme }) => ({
|
||||
margin: 10,
|
||||
height: 16,
|
||||
width: 16,
|
||||
borderRadius: 5,
|
||||
border: '1px solid ',
|
||||
borderColor: alpha(gray[300], 0.8),
|
||||
boxShadow: '0 0 0 1.5px hsla(210, 0%, 0%, 0.04) inset',
|
||||
backgroundColor: alpha(gray[100], 0.4),
|
||||
transition: 'border-color, background-color, 120ms ease-in',
|
||||
'&:hover': {
|
||||
borderColor: brand[300],
|
||||
},
|
||||
'&.Mui-focusVisible': {
|
||||
outline: `3px solid ${alpha(brand[500], 0.5)}`,
|
||||
outlineOffset: '2px',
|
||||
borderColor: brand[400],
|
||||
},
|
||||
'&.Mui-checked': {
|
||||
color: 'white',
|
||||
backgroundColor: brand[500],
|
||||
borderColor: brand[500],
|
||||
boxShadow: `none`,
|
||||
'&:hover': {
|
||||
backgroundColor: brand[600],
|
||||
},
|
||||
},
|
||||
...theme.applyStyles('dark', {
|
||||
borderColor: alpha(gray[700], 0.8),
|
||||
boxShadow: '0 0 0 1.5px hsl(210, 0%, 0%) inset',
|
||||
backgroundColor: alpha(gray[900], 0.8),
|
||||
'&:hover': {
|
||||
borderColor: brand[300],
|
||||
},
|
||||
'&.Mui-focusVisible': {
|
||||
borderColor: brand[400],
|
||||
outline: `3px solid ${alpha(brand[500], 0.5)}`,
|
||||
outlineOffset: '2px',
|
||||
},
|
||||
}),
|
||||
}),
|
||||
},
|
||||
},
|
||||
MuiInputBase: {
|
||||
styleOverrides: {
|
||||
root: {
|
||||
border: 'none',
|
||||
},
|
||||
input: {
|
||||
'&::placeholder': {
|
||||
opacity: 0.7,
|
||||
color: gray[500],
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
MuiOutlinedInput: {
|
||||
styleOverrides: {
|
||||
input: {
|
||||
padding: 0,
|
||||
},
|
||||
root: ({ theme }) => ({
|
||||
padding: '8px 12px',
|
||||
color: (theme.vars || theme).palette.text.primary,
|
||||
borderRadius: (theme.vars || theme).shape.borderRadius,
|
||||
border: `1px solid ${(theme.vars || theme).palette.divider}`,
|
||||
backgroundColor: (theme.vars || theme).palette.background.default,
|
||||
transition: 'border 120ms ease-in',
|
||||
'&:hover': {
|
||||
borderColor: gray[400],
|
||||
},
|
||||
[`&.${outlinedInputClasses.focused}`]: {
|
||||
outline: `3px solid ${alpha(brand[500], 0.5)}`,
|
||||
borderColor: brand[400],
|
||||
},
|
||||
...theme.applyStyles('dark', {
|
||||
'&:hover': {
|
||||
borderColor: gray[500],
|
||||
},
|
||||
}),
|
||||
variants: [
|
||||
{
|
||||
props: {
|
||||
size: 'small',
|
||||
},
|
||||
style: {
|
||||
height: '2.25rem',
|
||||
},
|
||||
},
|
||||
{
|
||||
props: {
|
||||
size: 'medium',
|
||||
},
|
||||
style: {
|
||||
height: '2.5rem',
|
||||
},
|
||||
},
|
||||
],
|
||||
}),
|
||||
notchedOutline: {
|
||||
border: 'none',
|
||||
},
|
||||
},
|
||||
},
|
||||
MuiInputAdornment: {
|
||||
styleOverrides: {
|
||||
root: ({ theme }) => ({
|
||||
color: (theme.vars || theme).palette.grey[500],
|
||||
...theme.applyStyles('dark', {
|
||||
color: (theme.vars || theme).palette.grey[400],
|
||||
}),
|
||||
}),
|
||||
},
|
||||
},
|
||||
MuiFormLabel: {
|
||||
styleOverrides: {
|
||||
root: ({ theme }) => ({
|
||||
typography: theme.typography.caption,
|
||||
marginBottom: 8,
|
||||
}),
|
||||
},
|
||||
},
|
||||
};
|
||||
@@ -1,279 +0,0 @@
|
||||
import * as React from 'react';
|
||||
import { Theme, alpha, Components } from '@mui/material/styles';
|
||||
import { SvgIconProps } from '@mui/material/SvgIcon';
|
||||
import { buttonBaseClasses } from '@mui/material/ButtonBase';
|
||||
import { dividerClasses } from '@mui/material/Divider';
|
||||
import { menuItemClasses } from '@mui/material/MenuItem';
|
||||
import { selectClasses } from '@mui/material/Select';
|
||||
import { tabClasses } from '@mui/material/Tab';
|
||||
import UnfoldMoreRoundedIcon from '@mui/icons-material/UnfoldMoreRounded';
|
||||
import { gray, brand } from '../themePrimitives';
|
||||
|
||||
/* eslint-disable import/prefer-default-export */
|
||||
export const navigationCustomizations: Components<Theme> = {
|
||||
MuiMenuItem: {
|
||||
styleOverrides: {
|
||||
root: ({ theme }) => ({
|
||||
borderRadius: (theme.vars || theme).shape.borderRadius,
|
||||
padding: '6px 8px',
|
||||
[`&.${menuItemClasses.focusVisible}`]: {
|
||||
backgroundColor: 'transparent',
|
||||
},
|
||||
[`&.${menuItemClasses.selected}`]: {
|
||||
[`&.${menuItemClasses.focusVisible}`]: {
|
||||
backgroundColor: alpha(theme.palette.action.selected, 0.3),
|
||||
},
|
||||
},
|
||||
}),
|
||||
},
|
||||
},
|
||||
MuiMenu: {
|
||||
styleOverrides: {
|
||||
list: {
|
||||
gap: '0px',
|
||||
[`&.${dividerClasses.root}`]: {
|
||||
margin: '0 -8px',
|
||||
},
|
||||
},
|
||||
paper: ({ theme }) => ({
|
||||
marginTop: '4px',
|
||||
borderRadius: (theme.vars || theme).shape.borderRadius,
|
||||
border: `1px solid ${(theme.vars || theme).palette.divider}`,
|
||||
backgroundImage: 'none',
|
||||
background: 'hsl(0, 0%, 100%)',
|
||||
boxShadow:
|
||||
'hsla(220, 30%, 5%, 0.07) 0px 4px 16px 0px, hsla(220, 25%, 10%, 0.07) 0px 8px 16px -5px',
|
||||
[`& .${buttonBaseClasses.root}`]: {
|
||||
'&.Mui-selected': {
|
||||
backgroundColor: alpha(theme.palette.action.selected, 0.3),
|
||||
},
|
||||
},
|
||||
...theme.applyStyles('dark', {
|
||||
background: gray[900],
|
||||
boxShadow:
|
||||
'hsla(220, 30%, 5%, 0.7) 0px 4px 16px 0px, hsla(220, 25%, 10%, 0.8) 0px 8px 16px -5px',
|
||||
}),
|
||||
}),
|
||||
},
|
||||
},
|
||||
MuiSelect: {
|
||||
defaultProps: {
|
||||
IconComponent: React.forwardRef<SVGSVGElement, SvgIconProps>((props, ref) => (
|
||||
<UnfoldMoreRoundedIcon fontSize="small" {...props} ref={ref} />
|
||||
)),
|
||||
},
|
||||
styleOverrides: {
|
||||
root: ({ theme }) => ({
|
||||
borderRadius: (theme.vars || theme).shape.borderRadius,
|
||||
border: '1px solid',
|
||||
borderColor: gray[200],
|
||||
backgroundColor: (theme.vars || theme).palette.background.paper,
|
||||
boxShadow: `inset 0 1px 0 1px hsla(220, 0%, 100%, 0.6), inset 0 -1px 0 1px hsla(220, 35%, 90%, 0.5)`,
|
||||
'&:hover': {
|
||||
borderColor: gray[300],
|
||||
backgroundColor: (theme.vars || theme).palette.background.paper,
|
||||
boxShadow: 'none',
|
||||
},
|
||||
[`&.${selectClasses.focused}`]: {
|
||||
outlineOffset: 0,
|
||||
borderColor: gray[400],
|
||||
},
|
||||
'&:before, &:after': {
|
||||
display: 'none',
|
||||
},
|
||||
|
||||
...theme.applyStyles('dark', {
|
||||
borderRadius: (theme.vars || theme).shape.borderRadius,
|
||||
borderColor: gray[700],
|
||||
backgroundColor: (theme.vars || theme).palette.background.paper,
|
||||
boxShadow: `inset 0 1px 0 1px ${alpha(gray[700], 0.15)}, inset 0 -1px 0 1px hsla(220, 0%, 0%, 0.7)`,
|
||||
'&:hover': {
|
||||
borderColor: alpha(gray[700], 0.7),
|
||||
backgroundColor: (theme.vars || theme).palette.background.paper,
|
||||
boxShadow: 'none',
|
||||
},
|
||||
[`&.${selectClasses.focused}`]: {
|
||||
outlineOffset: 0,
|
||||
borderColor: gray[900],
|
||||
},
|
||||
'&:before, &:after': {
|
||||
display: 'none',
|
||||
},
|
||||
}),
|
||||
}),
|
||||
select: ({ theme }) => ({
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
...theme.applyStyles('dark', {
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
'&:focus-visible': {
|
||||
backgroundColor: gray[900],
|
||||
},
|
||||
}),
|
||||
}),
|
||||
},
|
||||
},
|
||||
MuiLink: {
|
||||
defaultProps: {
|
||||
underline: 'none',
|
||||
},
|
||||
styleOverrides: {
|
||||
root: ({ theme }) => ({
|
||||
color: (theme.vars || theme).palette.text.primary,
|
||||
fontWeight: 500,
|
||||
position: 'relative',
|
||||
textDecoration: 'none',
|
||||
width: 'fit-content',
|
||||
'&::before': {
|
||||
content: '""',
|
||||
position: 'absolute',
|
||||
width: '100%',
|
||||
height: '1px',
|
||||
bottom: 0,
|
||||
left: 0,
|
||||
backgroundColor: (theme.vars || theme).palette.text.secondary,
|
||||
opacity: 0.3,
|
||||
transition: 'width 0.3s ease, opacity 0.3s ease',
|
||||
},
|
||||
'&:hover::before': {
|
||||
width: 0,
|
||||
},
|
||||
'&:focus-visible': {
|
||||
outline: `3px solid ${alpha(brand[500], 0.5)}`,
|
||||
outlineOffset: '4px',
|
||||
borderRadius: '2px',
|
||||
},
|
||||
}),
|
||||
},
|
||||
},
|
||||
MuiDrawer: {
|
||||
styleOverrides: {
|
||||
paper: ({ theme }) => ({
|
||||
backgroundColor: (theme.vars || theme).palette.background.default,
|
||||
}),
|
||||
},
|
||||
},
|
||||
MuiPaginationItem: {
|
||||
styleOverrides: {
|
||||
root: ({ theme }) => ({
|
||||
'&.Mui-selected': {
|
||||
color: 'white',
|
||||
backgroundColor: (theme.vars || theme).palette.grey[900],
|
||||
},
|
||||
...theme.applyStyles('dark', {
|
||||
'&.Mui-selected': {
|
||||
color: 'black',
|
||||
backgroundColor: (theme.vars || theme).palette.grey[50],
|
||||
},
|
||||
}),
|
||||
}),
|
||||
},
|
||||
},
|
||||
MuiTabs: {
|
||||
styleOverrides: {
|
||||
root: { minHeight: 'fit-content' },
|
||||
indicator: ({ theme }) => ({
|
||||
backgroundColor: (theme.vars || theme).palette.grey[800],
|
||||
...theme.applyStyles('dark', {
|
||||
backgroundColor: (theme.vars || theme).palette.grey[200],
|
||||
}),
|
||||
}),
|
||||
},
|
||||
},
|
||||
MuiTab: {
|
||||
styleOverrides: {
|
||||
root: ({ theme }) => ({
|
||||
padding: '6px 8px',
|
||||
marginBottom: '8px',
|
||||
textTransform: 'none',
|
||||
minWidth: 'fit-content',
|
||||
minHeight: 'fit-content',
|
||||
color: (theme.vars || theme).palette.text.secondary,
|
||||
borderRadius: (theme.vars || theme).shape.borderRadius,
|
||||
border: '1px solid',
|
||||
borderColor: 'transparent',
|
||||
':hover': {
|
||||
color: (theme.vars || theme).palette.text.primary,
|
||||
backgroundColor: gray[100],
|
||||
borderColor: gray[200],
|
||||
},
|
||||
[`&.${tabClasses.selected}`]: {
|
||||
color: gray[900],
|
||||
},
|
||||
...theme.applyStyles('dark', {
|
||||
':hover': {
|
||||
color: (theme.vars || theme).palette.text.primary,
|
||||
backgroundColor: gray[800],
|
||||
borderColor: gray[700],
|
||||
},
|
||||
[`&.${tabClasses.selected}`]: {
|
||||
color: '#fff',
|
||||
},
|
||||
}),
|
||||
}),
|
||||
},
|
||||
},
|
||||
MuiStepConnector: {
|
||||
styleOverrides: {
|
||||
line: ({ theme }) => ({
|
||||
borderTop: '1px solid',
|
||||
borderColor: (theme.vars || theme).palette.divider,
|
||||
flex: 1,
|
||||
borderRadius: '99px',
|
||||
}),
|
||||
},
|
||||
},
|
||||
MuiStepIcon: {
|
||||
styleOverrides: {
|
||||
root: ({ theme }) => ({
|
||||
color: 'transparent',
|
||||
border: `1px solid ${gray[400]}`,
|
||||
width: 12,
|
||||
height: 12,
|
||||
borderRadius: '50%',
|
||||
'& text': {
|
||||
display: 'none',
|
||||
},
|
||||
'&.Mui-active': {
|
||||
border: 'none',
|
||||
color: (theme.vars || theme).palette.primary.main,
|
||||
},
|
||||
'&.Mui-completed': {
|
||||
border: 'none',
|
||||
color: (theme.vars || theme).palette.success.main,
|
||||
},
|
||||
...theme.applyStyles('dark', {
|
||||
border: `1px solid ${gray[700]}`,
|
||||
'&.Mui-active': {
|
||||
border: 'none',
|
||||
color: (theme.vars || theme).palette.primary.light,
|
||||
},
|
||||
'&.Mui-completed': {
|
||||
border: 'none',
|
||||
color: (theme.vars || theme).palette.success.light,
|
||||
},
|
||||
}),
|
||||
variants: [
|
||||
{
|
||||
props: { completed: true },
|
||||
style: {
|
||||
width: 12,
|
||||
height: 12,
|
||||
},
|
||||
},
|
||||
],
|
||||
}),
|
||||
},
|
||||
},
|
||||
MuiStepLabel: {
|
||||
styleOverrides: {
|
||||
label: ({ theme }) => ({
|
||||
'&.Mui-completed': {
|
||||
opacity: 0.6,
|
||||
...theme.applyStyles('dark', { opacity: 0.5 }),
|
||||
},
|
||||
}),
|
||||
},
|
||||
},
|
||||
};
|
||||
@@ -1,113 +0,0 @@
|
||||
import { alpha, Theme, Components } from '@mui/material/styles';
|
||||
import { gray } from '../themePrimitives';
|
||||
|
||||
/* eslint-disable import/prefer-default-export */
|
||||
export const surfacesCustomizations: Components<Theme> = {
|
||||
MuiAccordion: {
|
||||
defaultProps: {
|
||||
elevation: 0,
|
||||
disableGutters: true,
|
||||
},
|
||||
styleOverrides: {
|
||||
root: ({ theme }) => ({
|
||||
padding: 4,
|
||||
overflow: 'clip',
|
||||
backgroundColor: (theme.vars || theme).palette.background.default,
|
||||
border: '1px solid',
|
||||
borderColor: (theme.vars || theme).palette.divider,
|
||||
':before': {
|
||||
backgroundColor: 'transparent',
|
||||
},
|
||||
'&:not(:last-of-type)': {
|
||||
borderBottom: 'none',
|
||||
},
|
||||
'&:first-of-type': {
|
||||
borderTopLeftRadius: (theme.vars || theme).shape.borderRadius,
|
||||
borderTopRightRadius: (theme.vars || theme).shape.borderRadius,
|
||||
},
|
||||
'&:last-of-type': {
|
||||
borderBottomLeftRadius: (theme.vars || theme).shape.borderRadius,
|
||||
borderBottomRightRadius: (theme.vars || theme).shape.borderRadius,
|
||||
},
|
||||
}),
|
||||
},
|
||||
},
|
||||
MuiAccordionSummary: {
|
||||
styleOverrides: {
|
||||
root: ({ theme }) => ({
|
||||
border: 'none',
|
||||
borderRadius: 8,
|
||||
'&:hover': { backgroundColor: gray[50] },
|
||||
'&:focus-visible': { backgroundColor: 'transparent' },
|
||||
...theme.applyStyles('dark', {
|
||||
'&:hover': { backgroundColor: gray[800] },
|
||||
}),
|
||||
}),
|
||||
},
|
||||
},
|
||||
MuiAccordionDetails: {
|
||||
styleOverrides: {
|
||||
root: { mb: 20, border: 'none' },
|
||||
},
|
||||
},
|
||||
MuiPaper: {
|
||||
defaultProps: {
|
||||
elevation: 0,
|
||||
},
|
||||
},
|
||||
MuiCard: {
|
||||
styleOverrides: {
|
||||
root: ({ theme }) => {
|
||||
return {
|
||||
padding: 16,
|
||||
gap: 16,
|
||||
transition: 'all 100ms ease',
|
||||
backgroundColor: gray[50],
|
||||
borderRadius: (theme.vars || theme).shape.borderRadius,
|
||||
border: `1px solid ${(theme.vars || theme).palette.divider}`,
|
||||
boxShadow: 'none',
|
||||
...theme.applyStyles('dark', {
|
||||
backgroundColor: gray[800],
|
||||
}),
|
||||
variants: [
|
||||
{
|
||||
props: {
|
||||
variant: 'outlined',
|
||||
},
|
||||
style: {
|
||||
border: `1px solid ${(theme.vars || theme).palette.divider}`,
|
||||
boxShadow: 'none',
|
||||
background: 'hsl(0, 0%, 100%)',
|
||||
...theme.applyStyles('dark', {
|
||||
background: alpha(gray[900], 0.4),
|
||||
}),
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
},
|
||||
},
|
||||
},
|
||||
MuiCardContent: {
|
||||
styleOverrides: {
|
||||
root: {
|
||||
padding: 0,
|
||||
'&:last-child': { paddingBottom: 0 },
|
||||
},
|
||||
},
|
||||
},
|
||||
MuiCardHeader: {
|
||||
styleOverrides: {
|
||||
root: {
|
||||
padding: 0,
|
||||
},
|
||||
},
|
||||
},
|
||||
MuiCardActions: {
|
||||
styleOverrides: {
|
||||
root: {
|
||||
padding: 0,
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
@@ -1,403 +0,0 @@
|
||||
import { createTheme, alpha, PaletteMode, Shadows } from '@mui/material/styles';
|
||||
|
||||
declare module '@mui/material/Paper' {
|
||||
interface PaperPropsVariantOverrides {
|
||||
highlighted: true;
|
||||
}
|
||||
}
|
||||
declare module '@mui/material/styles' {
|
||||
interface ColorRange {
|
||||
50: string;
|
||||
100: string;
|
||||
200: string;
|
||||
300: string;
|
||||
400: string;
|
||||
500: string;
|
||||
600: string;
|
||||
700: string;
|
||||
800: string;
|
||||
900: string;
|
||||
}
|
||||
|
||||
interface PaletteColor extends ColorRange {}
|
||||
|
||||
interface Palette {
|
||||
baseShadow: string;
|
||||
}
|
||||
}
|
||||
|
||||
const defaultTheme = createTheme();
|
||||
|
||||
const customShadows: Shadows = [...defaultTheme.shadows];
|
||||
|
||||
export const brand = {
|
||||
50: 'hsl(210, 100%, 95%)',
|
||||
100: 'hsl(210, 100%, 92%)',
|
||||
200: 'hsl(210, 100%, 80%)',
|
||||
300: 'hsl(210, 100%, 65%)',
|
||||
400: 'hsl(210, 98%, 48%)',
|
||||
500: 'hsl(210, 98%, 42%)',
|
||||
600: 'hsl(210, 98%, 55%)',
|
||||
700: 'hsl(210, 100%, 35%)',
|
||||
800: 'hsl(210, 100%, 16%)',
|
||||
900: 'hsl(210, 100%, 21%)',
|
||||
};
|
||||
|
||||
export const gray = {
|
||||
50: 'hsl(220, 35%, 97%)',
|
||||
100: 'hsl(220, 30%, 94%)',
|
||||
200: 'hsl(220, 20%, 88%)',
|
||||
300: 'hsl(220, 20%, 80%)',
|
||||
400: 'hsl(220, 20%, 65%)',
|
||||
500: 'hsl(220, 20%, 42%)',
|
||||
600: 'hsl(220, 20%, 35%)',
|
||||
700: 'hsl(220, 20%, 25%)',
|
||||
800: 'hsl(220, 30%, 6%)',
|
||||
900: 'hsl(220, 35%, 3%)',
|
||||
};
|
||||
|
||||
export const green = {
|
||||
50: 'hsl(120, 80%, 98%)',
|
||||
100: 'hsl(120, 75%, 94%)',
|
||||
200: 'hsl(120, 75%, 87%)',
|
||||
300: 'hsl(120, 61%, 77%)',
|
||||
400: 'hsl(120, 44%, 53%)',
|
||||
500: 'hsl(120, 59%, 30%)',
|
||||
600: 'hsl(120, 70%, 25%)',
|
||||
700: 'hsl(120, 75%, 16%)',
|
||||
800: 'hsl(120, 84%, 10%)',
|
||||
900: 'hsl(120, 87%, 6%)',
|
||||
};
|
||||
|
||||
export const orange = {
|
||||
50: 'hsl(45, 100%, 97%)',
|
||||
100: 'hsl(45, 92%, 90%)',
|
||||
200: 'hsl(45, 94%, 80%)',
|
||||
300: 'hsl(45, 90%, 65%)',
|
||||
400: 'hsl(45, 90%, 40%)',
|
||||
500: 'hsl(45, 90%, 35%)',
|
||||
600: 'hsl(45, 91%, 25%)',
|
||||
700: 'hsl(45, 94%, 20%)',
|
||||
800: 'hsl(45, 95%, 16%)',
|
||||
900: 'hsl(45, 93%, 12%)',
|
||||
};
|
||||
|
||||
export const red = {
|
||||
50: 'hsl(0, 100%, 97%)',
|
||||
100: 'hsl(0, 92%, 90%)',
|
||||
200: 'hsl(0, 94%, 80%)',
|
||||
300: 'hsl(0, 90%, 65%)',
|
||||
400: 'hsl(0, 90%, 40%)',
|
||||
500: 'hsl(0, 90%, 30%)',
|
||||
600: 'hsl(0, 91%, 25%)',
|
||||
700: 'hsl(0, 94%, 18%)',
|
||||
800: 'hsl(0, 95%, 12%)',
|
||||
900: 'hsl(0, 93%, 6%)',
|
||||
};
|
||||
|
||||
export const getDesignTokens = (mode: PaletteMode) => {
|
||||
customShadows[1] =
|
||||
mode === 'dark'
|
||||
? 'hsla(220, 30%, 5%, 0.7) 0px 4px 16px 0px, hsla(220, 25%, 10%, 0.8) 0px 8px 16px -5px'
|
||||
: 'hsla(220, 30%, 5%, 0.07) 0px 4px 16px 0px, hsla(220, 25%, 10%, 0.07) 0px 8px 16px -5px';
|
||||
|
||||
return {
|
||||
palette: {
|
||||
mode,
|
||||
primary: {
|
||||
light: brand[200],
|
||||
main: brand[400],
|
||||
dark: brand[700],
|
||||
contrastText: brand[50],
|
||||
...(mode === 'dark' && {
|
||||
contrastText: brand[50],
|
||||
light: brand[300],
|
||||
main: brand[400],
|
||||
dark: brand[700],
|
||||
}),
|
||||
},
|
||||
info: {
|
||||
light: brand[100],
|
||||
main: brand[300],
|
||||
dark: brand[600],
|
||||
contrastText: gray[50],
|
||||
...(mode === 'dark' && {
|
||||
contrastText: brand[300],
|
||||
light: brand[500],
|
||||
main: brand[700],
|
||||
dark: brand[900],
|
||||
}),
|
||||
},
|
||||
warning: {
|
||||
light: orange[300],
|
||||
main: orange[400],
|
||||
dark: orange[800],
|
||||
...(mode === 'dark' && {
|
||||
light: orange[400],
|
||||
main: orange[500],
|
||||
dark: orange[700],
|
||||
}),
|
||||
},
|
||||
error: {
|
||||
light: red[300],
|
||||
main: red[400],
|
||||
dark: red[800],
|
||||
...(mode === 'dark' && {
|
||||
light: red[400],
|
||||
main: red[500],
|
||||
dark: red[700],
|
||||
}),
|
||||
},
|
||||
success: {
|
||||
light: green[300],
|
||||
main: green[400],
|
||||
dark: green[800],
|
||||
...(mode === 'dark' && {
|
||||
light: green[400],
|
||||
main: green[500],
|
||||
dark: green[700],
|
||||
}),
|
||||
},
|
||||
grey: {
|
||||
...gray,
|
||||
},
|
||||
divider: mode === 'dark' ? alpha(gray[700], 0.6) : alpha(gray[300], 0.4),
|
||||
background: {
|
||||
default: 'hsl(0, 0%, 99%)',
|
||||
paper: 'hsl(220, 35%, 97%)',
|
||||
...(mode === 'dark' && { default: gray[900], paper: 'hsl(220, 30%, 7%)' }),
|
||||
},
|
||||
text: {
|
||||
primary: gray[800],
|
||||
secondary: gray[600],
|
||||
warning: orange[400],
|
||||
...(mode === 'dark' && { primary: 'hsl(0, 0%, 100%)', secondary: gray[400] }),
|
||||
},
|
||||
action: {
|
||||
hover: alpha(gray[200], 0.2),
|
||||
selected: `${alpha(gray[200], 0.3)}`,
|
||||
...(mode === 'dark' && {
|
||||
hover: alpha(gray[600], 0.2),
|
||||
selected: alpha(gray[600], 0.3),
|
||||
}),
|
||||
},
|
||||
},
|
||||
typography: {
|
||||
fontFamily: 'Inter, sans-serif',
|
||||
h1: {
|
||||
fontSize: defaultTheme.typography.pxToRem(48),
|
||||
fontWeight: 600,
|
||||
lineHeight: 1.2,
|
||||
letterSpacing: -0.5,
|
||||
},
|
||||
h2: {
|
||||
fontSize: defaultTheme.typography.pxToRem(36),
|
||||
fontWeight: 600,
|
||||
lineHeight: 1.2,
|
||||
},
|
||||
h3: {
|
||||
fontSize: defaultTheme.typography.pxToRem(30),
|
||||
lineHeight: 1.2,
|
||||
},
|
||||
h4: {
|
||||
fontSize: defaultTheme.typography.pxToRem(24),
|
||||
fontWeight: 600,
|
||||
lineHeight: 1.5,
|
||||
},
|
||||
h5: {
|
||||
fontSize: defaultTheme.typography.pxToRem(20),
|
||||
fontWeight: 600,
|
||||
},
|
||||
h6: {
|
||||
fontSize: defaultTheme.typography.pxToRem(18),
|
||||
fontWeight: 600,
|
||||
},
|
||||
subtitle1: {
|
||||
fontSize: defaultTheme.typography.pxToRem(18),
|
||||
},
|
||||
subtitle2: {
|
||||
fontSize: defaultTheme.typography.pxToRem(14),
|
||||
fontWeight: 500,
|
||||
},
|
||||
body1: {
|
||||
fontSize: defaultTheme.typography.pxToRem(14),
|
||||
},
|
||||
body2: {
|
||||
fontSize: defaultTheme.typography.pxToRem(14),
|
||||
fontWeight: 400,
|
||||
},
|
||||
caption: {
|
||||
fontSize: defaultTheme.typography.pxToRem(12),
|
||||
fontWeight: 400,
|
||||
},
|
||||
},
|
||||
shape: {
|
||||
borderRadius: 8,
|
||||
},
|
||||
shadows: customShadows,
|
||||
};
|
||||
};
|
||||
|
||||
export const colorSchemes = {
|
||||
light: {
|
||||
palette: {
|
||||
primary: {
|
||||
light: brand[200],
|
||||
main: brand[400],
|
||||
dark: brand[700],
|
||||
contrastText: brand[50],
|
||||
},
|
||||
info: {
|
||||
light: brand[100],
|
||||
main: brand[300],
|
||||
dark: brand[600],
|
||||
contrastText: gray[50],
|
||||
},
|
||||
warning: {
|
||||
light: orange[300],
|
||||
main: orange[400],
|
||||
dark: orange[800],
|
||||
},
|
||||
error: {
|
||||
light: red[300],
|
||||
main: red[400],
|
||||
dark: red[800],
|
||||
},
|
||||
success: {
|
||||
light: green[300],
|
||||
main: green[400],
|
||||
dark: green[800],
|
||||
},
|
||||
grey: {
|
||||
...gray,
|
||||
},
|
||||
divider: alpha(gray[300], 0.4),
|
||||
background: {
|
||||
default: 'hsl(0, 0%, 99%)',
|
||||
paper: 'hsl(220, 35%, 97%)',
|
||||
},
|
||||
text: {
|
||||
primary: gray[800],
|
||||
secondary: gray[600],
|
||||
warning: orange[400],
|
||||
},
|
||||
action: {
|
||||
hover: alpha(gray[200], 0.2),
|
||||
selected: `${alpha(gray[200], 0.3)}`,
|
||||
},
|
||||
baseShadow:
|
||||
'hsla(220, 30%, 5%, 0.07) 0px 4px 16px 0px, hsla(220, 25%, 10%, 0.07) 0px 8px 16px -5px',
|
||||
},
|
||||
},
|
||||
dark: {
|
||||
palette: {
|
||||
primary: {
|
||||
contrastText: brand[50],
|
||||
light: brand[300],
|
||||
main: brand[400],
|
||||
dark: brand[700],
|
||||
},
|
||||
info: {
|
||||
contrastText: brand[300],
|
||||
light: brand[500],
|
||||
main: brand[700],
|
||||
dark: brand[900],
|
||||
},
|
||||
warning: {
|
||||
light: orange[400],
|
||||
main: orange[500],
|
||||
dark: orange[700],
|
||||
},
|
||||
error: {
|
||||
light: red[400],
|
||||
main: red[500],
|
||||
dark: red[700],
|
||||
},
|
||||
success: {
|
||||
light: green[400],
|
||||
main: green[500],
|
||||
dark: green[700],
|
||||
},
|
||||
grey: {
|
||||
...gray,
|
||||
},
|
||||
divider: alpha(gray[700], 0.6),
|
||||
background: {
|
||||
default: gray[900],
|
||||
paper: 'hsl(220, 30%, 7%)',
|
||||
},
|
||||
text: {
|
||||
primary: 'hsl(0, 0%, 100%)',
|
||||
secondary: gray[400],
|
||||
},
|
||||
action: {
|
||||
hover: alpha(gray[600], 0.2),
|
||||
selected: alpha(gray[600], 0.3),
|
||||
},
|
||||
baseShadow:
|
||||
'hsla(220, 30%, 5%, 0.7) 0px 4px 16px 0px, hsla(220, 25%, 10%, 0.8) 0px 8px 16px -5px',
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
export const typography = {
|
||||
fontFamily: 'Inter, sans-serif',
|
||||
h1: {
|
||||
fontSize: defaultTheme.typography.pxToRem(48),
|
||||
fontWeight: 600,
|
||||
lineHeight: 1.2,
|
||||
letterSpacing: -0.5,
|
||||
},
|
||||
h2: {
|
||||
fontSize: defaultTheme.typography.pxToRem(36),
|
||||
fontWeight: 600,
|
||||
lineHeight: 1.2,
|
||||
},
|
||||
h3: {
|
||||
fontSize: defaultTheme.typography.pxToRem(30),
|
||||
lineHeight: 1.2,
|
||||
},
|
||||
h4: {
|
||||
fontSize: defaultTheme.typography.pxToRem(24),
|
||||
fontWeight: 600,
|
||||
lineHeight: 1.5,
|
||||
},
|
||||
h5: {
|
||||
fontSize: defaultTheme.typography.pxToRem(20),
|
||||
fontWeight: 600,
|
||||
},
|
||||
h6: {
|
||||
fontSize: defaultTheme.typography.pxToRem(18),
|
||||
fontWeight: 600,
|
||||
},
|
||||
subtitle1: {
|
||||
fontSize: defaultTheme.typography.pxToRem(18),
|
||||
},
|
||||
subtitle2: {
|
||||
fontSize: defaultTheme.typography.pxToRem(14),
|
||||
fontWeight: 500,
|
||||
},
|
||||
body1: {
|
||||
fontSize: defaultTheme.typography.pxToRem(14),
|
||||
},
|
||||
body2: {
|
||||
fontSize: defaultTheme.typography.pxToRem(14),
|
||||
fontWeight: 400,
|
||||
},
|
||||
caption: {
|
||||
fontSize: defaultTheme.typography.pxToRem(12),
|
||||
fontWeight: 400,
|
||||
},
|
||||
};
|
||||
|
||||
export const shape = {
|
||||
borderRadius: 8,
|
||||
};
|
||||
|
||||
// @ts-ignore
|
||||
const defaultShadows: Shadows = [
|
||||
'none',
|
||||
'var(--template-palette-baseShadow)',
|
||||
...defaultTheme.shadows.slice(2),
|
||||
];
|
||||
export const shadows = defaultShadows;
|
||||
@@ -30,6 +30,7 @@ export interface ResourceConfig {
|
||||
primaryKey: string;
|
||||
fields: Record<string, ResourceField>;
|
||||
pagination?: boolean;
|
||||
hidden?: boolean;
|
||||
}
|
||||
|
||||
export interface AppConfig {
|
||||
|
||||
@@ -12,4 +12,5 @@ export interface FieldOverride {
|
||||
export interface ResourceOverride {
|
||||
fields?: Record<string, FieldOverride>;
|
||||
pagination?: boolean;
|
||||
hidden?: boolean;
|
||||
}
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import SwaggerParser from "@apidevtools/swagger-parser";
|
||||
import { AppConfig, ResourceConfig, ResourceField, FieldType } from "../types/config";
|
||||
import { configuration, profileConfiguration } from "../../src/openapi-config";
|
||||
|
||||
/**
|
||||
* Maps OpenAPI property types to our internal FieldType
|
||||
@@ -40,7 +39,8 @@ function mapOpenApiType(prop: any): FieldType {
|
||||
function parseSchemaFields(
|
||||
schema: any,
|
||||
resourceName: string,
|
||||
schemaToResourceMap: Map<any, string>
|
||||
schemaToResourceMap: Map<any, string>,
|
||||
configuration: Record<string, any> = {}
|
||||
): Record<string, ResourceField> {
|
||||
const fields: Record<string, ResourceField> = {};
|
||||
const properties = schema.properties || {};
|
||||
@@ -84,7 +84,7 @@ function parseSchemaFields(
|
||||
|
||||
// Recursively parse nested objects (only if not a relation)
|
||||
if (fields[key].type === "object" && prop.properties && !relation) {
|
||||
fields[key].schema = parseSchemaFields(prop, resourceName, schemaToResourceMap);
|
||||
fields[key].schema = parseSchemaFields(prop, resourceName, schemaToResourceMap, configuration);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -94,7 +94,7 @@ function parseSchemaFields(
|
||||
/**
|
||||
* Scans paths to identify resources and their basic configuration
|
||||
*/
|
||||
export async function loadConfigFromOpenApi(baseUrl: string): Promise<AppConfig> {
|
||||
export async function loadConfigFromOpenApi(baseUrl: string, configuration: Record<string, any> = {}, profileConfiguration: any = {}): Promise<AppConfig> {
|
||||
// Use SwaggerParser to dereference the spec.
|
||||
// Dereferencing preserves object identity for $ref targets.
|
||||
const api = await SwaggerParser.dereference(
|
||||
@@ -150,7 +150,7 @@ export async function loadConfigFromOpenApi(baseUrl: string): Promise<AppConfig>
|
||||
const label = name.charAt(0).toUpperCase() + name.slice(1, -1);
|
||||
const pluralLabel = name.charAt(0).toUpperCase() + name.slice(1);
|
||||
|
||||
const fields = parseSchemaFields(schema, name, schemaToResourceMap);
|
||||
const fields = parseSchemaFields(schema, name, schemaToResourceMap, configuration);
|
||||
|
||||
const resourceOverride = configuration[name] || {};
|
||||
|
||||
@@ -162,6 +162,7 @@ export async function loadConfigFromOpenApi(baseUrl: string): Promise<AppConfig>
|
||||
primaryKey: "id", // Strict default, no heuristics
|
||||
fields,
|
||||
pagination: resourceOverride.pagination,
|
||||
hidden: resourceOverride.hidden,
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
48
src/AppTheme.tsx
Normal file
48
src/AppTheme.tsx
Normal file
@@ -0,0 +1,48 @@
|
||||
import * as React from "react";
|
||||
import { ThemeProvider, createTheme } from "@mui/material/styles";
|
||||
import { getDesignTokens } from "./shared-theme/themePrimitives";
|
||||
import { inputsCustomizations } from "./shared-theme/customizations/inputs";
|
||||
import { dataDisplayCustomizations } from "./shared-theme/customizations/dataDisplay";
|
||||
import { feedbackCustomizations } from "./shared-theme/customizations/feedback";
|
||||
import { navigationCustomizations } from "./shared-theme/customizations/navigation";
|
||||
import { surfacesCustomizations } from "./shared-theme/customizations/surfaces";
|
||||
|
||||
export const ColorModeContext = React.createContext({
|
||||
toggleColorMode: () => {},
|
||||
mode: "light" as "light" | "dark",
|
||||
});
|
||||
|
||||
export default function AppTheme({ children }: { children: React.ReactNode }) {
|
||||
const [mode, setMode] = React.useState<"light" | "dark">("light");
|
||||
|
||||
const colorMode = React.useMemo(
|
||||
() => ({
|
||||
toggleColorMode: () => {
|
||||
setMode((prevMode) => (prevMode === "light" ? "dark" : "light"));
|
||||
},
|
||||
mode,
|
||||
}),
|
||||
[mode]
|
||||
);
|
||||
|
||||
const theme = React.useMemo(
|
||||
() =>
|
||||
createTheme({
|
||||
...getDesignTokens(mode),
|
||||
components: {
|
||||
...inputsCustomizations,
|
||||
...dataDisplayCustomizations,
|
||||
...feedbackCustomizations,
|
||||
...navigationCustomizations,
|
||||
...surfacesCustomizations,
|
||||
},
|
||||
}),
|
||||
[mode]
|
||||
);
|
||||
|
||||
return (
|
||||
<ColorModeContext.Provider value={colorMode}>
|
||||
<ThemeProvider theme={theme}>{children}</ThemeProvider>
|
||||
</ColorModeContext.Provider>
|
||||
);
|
||||
}
|
||||
55
src/Dashboard.tsx
Normal file
55
src/Dashboard.tsx
Normal file
@@ -0,0 +1,55 @@
|
||||
import * as React from "react";
|
||||
import {
|
||||
Box,
|
||||
Container,
|
||||
CircularProgress,
|
||||
Alert
|
||||
} from "@mui/material";
|
||||
|
||||
import ConfigurableDashboard from "./components/Dashboard";
|
||||
import { configuration } from "./dashboard-config";
|
||||
import {
|
||||
useReport,
|
||||
prepareReport,
|
||||
} from "./features/report";
|
||||
|
||||
export default function Dashboard() {
|
||||
const report = useReport({
|
||||
periods: ["weekly", "monthly", "full"],
|
||||
rolling: true,
|
||||
include_transactions: true,
|
||||
group_by: ["tags"],
|
||||
})
|
||||
|
||||
const isLoading = report.isLoading;
|
||||
const error = report.error;
|
||||
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<Box sx={{ display: "flex", justifyContent: "center", alignItems: "center", height: "60vh" }}>
|
||||
<CircularProgress />
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<Container sx={{ mt: 4 }}>
|
||||
<Alert severity="error">{String(error)}</Alert>
|
||||
</Container>
|
||||
);
|
||||
}
|
||||
|
||||
if (!report) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const data = prepareReport(report.data?.data);
|
||||
return (
|
||||
<ConfigurableDashboard
|
||||
config={configuration}
|
||||
data={data}
|
||||
/>
|
||||
);
|
||||
}
|
||||
52
src/Footer.tsx
Normal file
52
src/Footer.tsx
Normal file
@@ -0,0 +1,52 @@
|
||||
import * as React from 'react';
|
||||
import Container from '@mui/material/Container';
|
||||
import Link from '@mui/material/Link';
|
||||
import Typography from '@mui/material/Typography';
|
||||
import {AppBar, Box, Button, IconButton, Toolbar, Tooltip} from "@mui/material";
|
||||
import MenuIcon from "@mui/icons-material/Menu";
|
||||
import LogoutIcon from "@mui/icons-material/Logout";
|
||||
|
||||
function Copyright() {
|
||||
return (
|
||||
<Typography variant="body2" sx={{ color: 'text.secondary' }}>
|
||||
<Link color="text.secondary" href="https://www.aetoskia.com/">
|
||||
{'Copyright © Aetoskia Internal Infrastructure — All rights reserved.'}
|
||||
</Link>
|
||||
|
||||
{new Date().getFullYear()}
|
||||
</Typography>
|
||||
);
|
||||
}
|
||||
|
||||
export default function Footer() {
|
||||
return (
|
||||
<AppBar
|
||||
position="fixed"
|
||||
color="default"
|
||||
sx={{
|
||||
top: 'auto',
|
||||
bottom: 0,
|
||||
backdropFilter: 'blur(8px)',
|
||||
boxShadow: 'none',
|
||||
borderTop: '1px solid',
|
||||
borderColor: 'divider',
|
||||
}}
|
||||
>
|
||||
<Toolbar>
|
||||
<React.Fragment>
|
||||
<Container
|
||||
sx={{
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
alignItems: 'center',
|
||||
gap: { xs: 2, sm: 4 },
|
||||
textAlign: { sm: 'center', md: 'left' },
|
||||
}}
|
||||
>
|
||||
<Copyright />
|
||||
</Container>
|
||||
</React.Fragment>
|
||||
</Toolbar>
|
||||
</AppBar>
|
||||
);
|
||||
}
|
||||
139
src/Header.tsx
Normal file
139
src/Header.tsx
Normal file
@@ -0,0 +1,139 @@
|
||||
import * as React from "react";
|
||||
import {
|
||||
useLocation,
|
||||
matchPath
|
||||
} from "react-router-dom";
|
||||
import {
|
||||
AppBar,
|
||||
Toolbar,
|
||||
Typography,
|
||||
IconButton,
|
||||
Tooltip,
|
||||
Button,
|
||||
Box,
|
||||
useMediaQuery,
|
||||
useTheme,
|
||||
} from "@mui/material";
|
||||
import MenuIcon from "@mui/icons-material/Menu";
|
||||
import LogoutIcon from "@mui/icons-material/Logout";
|
||||
import DarkModeIcon from "@mui/icons-material/DarkMode";
|
||||
import LightModeIcon from "@mui/icons-material/LightMode";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { useAuth } from "../react-auth";
|
||||
import { ColorModeContext } from "./AppTheme";
|
||||
|
||||
interface HeaderProps {
|
||||
routerMapping: {
|
||||
path: string;
|
||||
headerTitle: string;
|
||||
}[];
|
||||
onDrawerToggle?: () => void;
|
||||
}
|
||||
|
||||
export default function Header({
|
||||
routerMapping,
|
||||
onDrawerToggle,
|
||||
}: HeaderProps) {
|
||||
const location = useLocation();
|
||||
const matchedRoute = routerMapping.find((route) =>
|
||||
matchPath({ path: route.path, end: false }, location.pathname)
|
||||
);
|
||||
const headerTitle = matchedRoute?.headerTitle ?? "Khata";
|
||||
|
||||
const navigate = useNavigate();
|
||||
const { currentUser, logout } = useAuth();
|
||||
const { mode, toggleColorMode } = React.useContext(ColorModeContext);
|
||||
|
||||
const theme = useTheme();
|
||||
const isMobile = useMediaQuery(theme.breakpoints.down("md"));
|
||||
|
||||
const isAuthenticated = !!currentUser;
|
||||
|
||||
return (
|
||||
<AppBar
|
||||
position="fixed"
|
||||
color="default"
|
||||
sx={{
|
||||
zIndex: (theme) => theme.zIndex.drawer + 1,
|
||||
backdropFilter: "blur(8px)",
|
||||
boxShadow: "none",
|
||||
borderBottom: "1px solid",
|
||||
borderColor: "divider",
|
||||
}}
|
||||
>
|
||||
<Toolbar>
|
||||
{/* MOBILE MENU BUTTON */}
|
||||
{isMobile && onDrawerToggle && (
|
||||
<IconButton
|
||||
color="inherit"
|
||||
edge="start"
|
||||
onClick={onDrawerToggle}
|
||||
sx={{ mr: 2 }}
|
||||
>
|
||||
<MenuIcon />
|
||||
</IconButton>
|
||||
)}
|
||||
|
||||
{/* THEME TOGGLE */}
|
||||
<IconButton onClick={toggleColorMode} color="inherit" sx={{ mr: 2 }}>
|
||||
{mode === 'dark' ? <LightModeIcon /> : <DarkModeIcon />}
|
||||
</IconButton>
|
||||
|
||||
{/* TITLE */}
|
||||
<Typography
|
||||
variant="h6"
|
||||
noWrap
|
||||
sx={{ fontWeight: "bold", cursor: "pointer" }}
|
||||
onClick={() => navigate("/")}
|
||||
>
|
||||
{headerTitle}
|
||||
</Typography>
|
||||
|
||||
<span style={{ flexGrow: 1 }} />
|
||||
|
||||
{/* AUTH SECTION */}
|
||||
{isAuthenticated ? (
|
||||
<>
|
||||
<Box
|
||||
sx={{
|
||||
display: { xs: "none", sm: "flex" },
|
||||
alignItems: "center",
|
||||
mr: 2,
|
||||
}}
|
||||
>
|
||||
<Button
|
||||
color="inherit"
|
||||
onClick={() => navigate("/admin")}
|
||||
sx={{ textTransform: "none", fontWeight: 500 }}
|
||||
>
|
||||
Admin
|
||||
</Button>
|
||||
<Button
|
||||
color="inherit"
|
||||
onClick={() => navigate("/admin/profile")}
|
||||
sx={{ textTransform: "none", fontWeight: 500 }}
|
||||
>
|
||||
{currentUser.username}
|
||||
</Button>
|
||||
</Box>
|
||||
|
||||
<Tooltip title="Logout">
|
||||
<IconButton color="inherit" onClick={logout}>
|
||||
<LogoutIcon />
|
||||
</IconButton>
|
||||
</Tooltip>
|
||||
</>
|
||||
) : (
|
||||
<Button
|
||||
color="inherit"
|
||||
variant="outlined"
|
||||
onClick={() => navigate("/admin")}
|
||||
sx={{ textTransform: "none" }}
|
||||
>
|
||||
Login
|
||||
</Button>
|
||||
)}
|
||||
</Toolbar>
|
||||
</AppBar>
|
||||
);
|
||||
}
|
||||
116
src/Home.tsx
116
src/Home.tsx
@@ -1,26 +1,108 @@
|
||||
import * as React from "react";
|
||||
import { Box, Typography, Button, Container, Stack } from "@mui/material";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import ArrowForwardIcon from "@mui/icons-material/ArrowForward";
|
||||
|
||||
export default function Home() {
|
||||
const navigate = useNavigate();
|
||||
|
||||
const Home: React.FC = () => {
|
||||
return (
|
||||
<div style={styles.container}>
|
||||
<h1 style={styles.title}>Welcome to Khata</h1>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
const styles: { [key: string]: React.CSSProperties } = {
|
||||
container: {
|
||||
height: "100vh",
|
||||
<Box
|
||||
sx={{
|
||||
width: "100%",
|
||||
minHeight: "calc(100vh - 64px)", // accounting for header
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
backgroundColor: "#0f172a",
|
||||
position: "relative",
|
||||
overflow: "hidden",
|
||||
"&::before": {
|
||||
content: '""',
|
||||
position: "absolute",
|
||||
top: "-20%",
|
||||
left: "-10%",
|
||||
width: "50%",
|
||||
height: "60%",
|
||||
background: "radial-gradient(circle, rgba(99,102,241,0.15) 0%, rgba(0,0,0,0) 70%)",
|
||||
zIndex: 0,
|
||||
},
|
||||
title: {
|
||||
color: "#ffffff",
|
||||
fontSize: "2rem",
|
||||
fontWeight: 600,
|
||||
"&::after": {
|
||||
content: '""',
|
||||
position: "absolute",
|
||||
bottom: "-20%",
|
||||
right: "-10%",
|
||||
width: "50%",
|
||||
height: "60%",
|
||||
background: "radial-gradient(circle, rgba(236,72,153,0.15) 0%, rgba(0,0,0,0) 70%)",
|
||||
zIndex: 0,
|
||||
},
|
||||
};
|
||||
}}
|
||||
>
|
||||
<Container maxWidth="lg" sx={{ position: "relative", zIndex: 1 }}>
|
||||
<Stack
|
||||
spacing={4}
|
||||
alignItems="center"
|
||||
textAlign="center"
|
||||
sx={{
|
||||
p: { xs: 4, md: 8 },
|
||||
backdropFilter: "blur(20px)",
|
||||
backgroundColor: (theme) =>
|
||||
theme.palette.mode === "dark" ? "rgba(255, 255, 255, 0.03)" : "rgba(255, 255, 255, 0.6)",
|
||||
border: "1px solid",
|
||||
borderColor: "divider",
|
||||
borderRadius: 4,
|
||||
boxShadow: (theme) =>
|
||||
theme.palette.mode === "dark"
|
||||
? "0 8px 32px 0 rgba(0, 0, 0, 0.37)"
|
||||
: "0 8px 32px 0 rgba(31, 38, 135, 0.07)",
|
||||
}}
|
||||
>
|
||||
<Typography
|
||||
variant="h1"
|
||||
sx={{
|
||||
fontWeight: 800,
|
||||
fontSize: { xs: "3rem", md: "5rem" },
|
||||
background: "linear-gradient(45deg, #6366f1 30%, #ec4899 90%)",
|
||||
WebkitBackgroundClip: "text",
|
||||
WebkitTextFillColor: "transparent",
|
||||
mb: 2,
|
||||
}}
|
||||
>
|
||||
Welcome to Khata
|
||||
</Typography>
|
||||
|
||||
export default Home;
|
||||
<Typography
|
||||
variant="h5"
|
||||
color="text.secondary"
|
||||
sx={{ maxWidth: "600px", lineHeight: 1.6 }}
|
||||
>
|
||||
Your intelligent, extensible financial ledger. Control accounts, manage transactions, and track your data dynamically with our OpenAPI-driven architecture.
|
||||
</Typography>
|
||||
|
||||
<Box mt={4}>
|
||||
<Button
|
||||
variant="contained"
|
||||
size="large"
|
||||
endIcon={<ArrowForwardIcon />}
|
||||
onClick={() => navigate("/dashboard")}
|
||||
sx={{
|
||||
px: 4,
|
||||
py: 1.5,
|
||||
borderRadius: "50px",
|
||||
fontWeight: "bold",
|
||||
background: "linear-gradient(45deg, #6366f1 30%, #ec4899 90%)",
|
||||
transition: "transform 0.2s ease-in-out, box-shadow 0.2s",
|
||||
"&:hover": {
|
||||
transform: "translateY(-3px)",
|
||||
boxShadow: "0 8px 20px rgba(236,72,153,0.4)",
|
||||
},
|
||||
}}
|
||||
>
|
||||
Enter Dashboard
|
||||
</Button>
|
||||
</Box>
|
||||
</Stack>
|
||||
</Container>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
53
src/components/Dashboard/Dashboard.models.ts
Normal file
53
src/components/Dashboard/Dashboard.models.ts
Normal file
@@ -0,0 +1,53 @@
|
||||
import * as React from "react";
|
||||
import {
|
||||
ReportData,
|
||||
GroupKey,
|
||||
} from "../../features/report";
|
||||
|
||||
export type DashboardMode = "expense" | "income";
|
||||
export type DashboardPeriodType = "rolling" | "calendar";
|
||||
export type DashboardSelectedPeriodId = string | null;
|
||||
|
||||
export interface DashboardState {
|
||||
mode: DashboardMode;
|
||||
periodType: DashboardPeriodType;
|
||||
selectedPeriodId: DashboardSelectedPeriodId;
|
||||
selectedGroupKey: GroupKey | null;
|
||||
comparison: boolean;
|
||||
}
|
||||
|
||||
export interface DashboardSection {
|
||||
id: string;
|
||||
title?: string;
|
||||
summary?: string;
|
||||
component: React.ComponentType<any>;
|
||||
settings?: Record<string, any>;
|
||||
isList?: boolean;
|
||||
style?: {
|
||||
size?: number;
|
||||
[key: string]: any;
|
||||
};
|
||||
}
|
||||
|
||||
export interface ColorDefinition {
|
||||
primary: string;
|
||||
background?: string;
|
||||
text?: string;
|
||||
}
|
||||
|
||||
export interface ThemeAwarePalette {
|
||||
light: ColorDefinition;
|
||||
dark: ColorDefinition;
|
||||
}
|
||||
|
||||
export interface DashboardConfig {
|
||||
sections: DashboardSection[];
|
||||
style?: {
|
||||
palette?: Record<DashboardMode, ThemeAwarePalette>;
|
||||
};
|
||||
}
|
||||
|
||||
export interface DashboardProps {
|
||||
config: DashboardConfig;
|
||||
data: ReportData;
|
||||
}
|
||||
55
src/components/Dashboard/Dashboard.tsx
Normal file
55
src/components/Dashboard/Dashboard.tsx
Normal file
@@ -0,0 +1,55 @@
|
||||
import * as React from "react";
|
||||
import DashboardView from "./Dashboard.view";
|
||||
import { DashboardProps, DashboardState } from "./Dashboard.models";
|
||||
|
||||
export default function Dashboard(props: DashboardProps) {
|
||||
const [state, setState] = React.useState<DashboardState>({
|
||||
mode: "expense",
|
||||
periodType: "rolling",
|
||||
selectedPeriodId: null,
|
||||
selectedGroupKey: null,
|
||||
comparison: false,
|
||||
});
|
||||
|
||||
const toggleMode = () => {
|
||||
setState(prev => ({
|
||||
...prev,
|
||||
mode: prev.mode === "expense" ? "income" : "expense",
|
||||
}));
|
||||
};
|
||||
|
||||
const togglePeriodType = () => {
|
||||
setState(prev => ({
|
||||
...prev,
|
||||
periodType: prev.periodType === "rolling" ? "calendar" : "rolling",
|
||||
}));
|
||||
};
|
||||
|
||||
const toggleComparison = () => {
|
||||
setState(prev => ({
|
||||
...prev,
|
||||
comparison: !prev.comparison,
|
||||
}));
|
||||
};
|
||||
|
||||
const setSelectedPeriodId = (selectedPeriodId: typeof state.selectedPeriodId) => {
|
||||
setState(prev => ({ ...prev, selectedPeriodId }));
|
||||
};
|
||||
|
||||
const setSelectedGroupKey = (groupKey: typeof state.selectedGroupKey) => {
|
||||
setState(prev => ({ ...prev, selectedGroupKey: groupKey }));
|
||||
};
|
||||
|
||||
return (
|
||||
<DashboardView
|
||||
{...props}
|
||||
state={state}
|
||||
setState={setState}
|
||||
toggleMode={toggleMode}
|
||||
togglePeriodType={togglePeriodType}
|
||||
toggleComparison={toggleComparison}
|
||||
setSelectedPeriodId={setSelectedPeriodId}
|
||||
setSelectedGroupKey={setSelectedGroupKey}
|
||||
/>
|
||||
);
|
||||
}
|
||||
139
src/components/Dashboard/Dashboard.view.tsx
Normal file
139
src/components/Dashboard/Dashboard.view.tsx
Normal file
@@ -0,0 +1,139 @@
|
||||
import * as React from "react";
|
||||
import {
|
||||
Box,
|
||||
Container,
|
||||
Grid,
|
||||
Typography,
|
||||
ToggleButton,
|
||||
ToggleButtonGroup
|
||||
} from "@mui/material";
|
||||
import { useTheme, alpha } from "@mui/material/styles";
|
||||
import { GroupKey } from "../../features/report";
|
||||
import { DashboardProps, DashboardState } from "./Dashboard.models";
|
||||
|
||||
interface ViewProps extends DashboardProps {
|
||||
state: DashboardState;
|
||||
setState: React.Dispatch<React.SetStateAction<DashboardState>>;
|
||||
toggleMode: () => void;
|
||||
togglePeriodType: () => void;
|
||||
setSelectedPeriodId: (id: string | null) => void;
|
||||
setSelectedGroupKey: (groupKey: GroupKey | null) => void;
|
||||
toggleComparison: () => void;
|
||||
}
|
||||
|
||||
export default function DashboardView({
|
||||
config,
|
||||
data,
|
||||
state,
|
||||
setState,
|
||||
toggleMode,
|
||||
togglePeriodType,
|
||||
toggleComparison,
|
||||
setSelectedPeriodId,
|
||||
setSelectedGroupKey,
|
||||
}: ViewProps) {
|
||||
const theme = useTheme();
|
||||
const themeMode = theme.palette.mode;
|
||||
const { mode, periodType, comparison, selectedPeriodId, selectedGroupKey } = state;
|
||||
|
||||
// Resolve colors with fallbacks
|
||||
const colors = React.useMemo(() => {
|
||||
const palette = config.style?.palette?.[mode];
|
||||
const modeColors = palette ? palette[themeMode] : null;
|
||||
|
||||
if (modeColors) {
|
||||
return {
|
||||
primary: modeColors.primary,
|
||||
light: modeColors.background || alpha(modeColors.primary, 0.1),
|
||||
text: modeColors.text || (themeMode === 'light' ? theme.palette.text.primary : '#fff')
|
||||
};
|
||||
}
|
||||
|
||||
// Fallback to standard theme colors
|
||||
const themeColor = mode === 'expense' ? theme.palette.error : theme.palette.success;
|
||||
return {
|
||||
primary: themeColor.main,
|
||||
light: alpha(themeColor.main, themeMode === 'light' ? 0.08 : 0.15),
|
||||
text: themeColor.main
|
||||
};
|
||||
}, [config.style?.palette, mode, themeMode, theme.palette]);
|
||||
|
||||
return (
|
||||
<Container
|
||||
sx={{
|
||||
mt: 4,
|
||||
mb: 4,
|
||||
background: `linear-gradient(180deg, ${colors.light} 0%, transparent 100%)`,
|
||||
borderRadius: 4,
|
||||
p: 2,
|
||||
transition: 'background 0.3s ease'
|
||||
}}
|
||||
>
|
||||
<Box sx={{ display: "flex", justifyContent: "center", mb: 3 }}>
|
||||
<ToggleButtonGroup
|
||||
value={mode}
|
||||
exclusive
|
||||
onChange={toggleMode}
|
||||
sx={{
|
||||
borderRadius: 3,
|
||||
overflow: "hidden",
|
||||
"& .MuiToggleButton-root": {
|
||||
px: 3,
|
||||
textTransform: "none",
|
||||
color: "text.secondary"
|
||||
},
|
||||
"&.Mui-selected": {
|
||||
bgcolor: colors.primary,
|
||||
color: "white",
|
||||
borderColor: colors.primary
|
||||
},
|
||||
}}
|
||||
>
|
||||
<ToggleButton value="expense">Expenses</ToggleButton>
|
||||
<ToggleButton value="income">Income</ToggleButton>
|
||||
</ToggleButtonGroup>
|
||||
</Box>
|
||||
|
||||
<Grid container spacing={4}>
|
||||
{config.sections.map((section) => {
|
||||
const Component = section.component;
|
||||
|
||||
return (
|
||||
<Grid key={section.id} size={section.style?.size || 12 as any}>
|
||||
{section.title && !section.isList && (
|
||||
<Box sx={{ mb: 2 }}>
|
||||
<Typography variant="h6" fontWeight={700}>
|
||||
{section.title}
|
||||
</Typography>
|
||||
</Box>
|
||||
)}
|
||||
|
||||
<Component
|
||||
{...section.settings}
|
||||
header={section.title}
|
||||
summary={section.summary}
|
||||
reportData={data}
|
||||
title={section.title}
|
||||
accentColor={colors.primary}
|
||||
colorScheme={colors}
|
||||
|
||||
// State management
|
||||
mode={mode}
|
||||
|
||||
periodType={periodType}
|
||||
comparison={comparison}
|
||||
selectedPeriodId={selectedPeriodId}
|
||||
selectedGroupKey={selectedGroupKey}
|
||||
|
||||
togglePeriodType={togglePeriodType}
|
||||
toggleComparison={toggleComparison}
|
||||
setSelectedPeriodId={setSelectedPeriodId}
|
||||
setSelectedGroupKey={setSelectedGroupKey}
|
||||
/>
|
||||
</Grid>
|
||||
);
|
||||
})}
|
||||
</Grid>
|
||||
</Container>
|
||||
);
|
||||
}
|
||||
2
src/components/Dashboard/index.ts
Normal file
2
src/components/Dashboard/index.ts
Normal file
@@ -0,0 +1,2 @@
|
||||
export { default } from "./Dashboard";
|
||||
export * from "./Dashboard.models";
|
||||
75
src/components/HistoryChart/HistoryChart.adapter.ts
Normal file
75
src/components/HistoryChart/HistoryChart.adapter.ts
Normal file
@@ -0,0 +1,75 @@
|
||||
import { ReportData } from "../../features/report";
|
||||
import {
|
||||
mergeBucketPeriods,
|
||||
getAmount,
|
||||
PeriodKey,
|
||||
} from "../report.helpers";
|
||||
import { ChartDataPoint } from "./HistoryChart.models";
|
||||
|
||||
// ─── Tab → PeriodKey ─────────────────────────────────────────
|
||||
|
||||
const TAB_TO_KEY: Record<string, PeriodKey> = {
|
||||
Weekly: "weekly",
|
||||
Monthly: "monthly",
|
||||
Yearly: "yearly",
|
||||
"Financial Year": "fyly",
|
||||
"All Time": "full",
|
||||
};
|
||||
|
||||
export function tabToKey(tab: string): PeriodKey {
|
||||
return TAB_TO_KEY[tab] ?? "full";
|
||||
}
|
||||
|
||||
// ─── Comparison ──────────────────────────────────────────────
|
||||
|
||||
function attachComparison(
|
||||
points: ChartDataPoint[],
|
||||
key: PeriodKey
|
||||
): ChartDataPoint[] {
|
||||
const getCompareIndex = (i: number) => {
|
||||
if (key === "weekly") return i - 4;
|
||||
if (key === "monthly") return i - 12;
|
||||
if (key === "yearly") return i - 1;
|
||||
if (key === "fyly") return i - 1;
|
||||
return -1;
|
||||
};
|
||||
|
||||
return points.map((p, i) => {
|
||||
const ci = getCompareIndex(i);
|
||||
|
||||
return {
|
||||
...p,
|
||||
compare:
|
||||
ci >= 0 && points[ci]
|
||||
? {
|
||||
id: points[ci].id,
|
||||
label: points[ci].label,
|
||||
amount: points[ci].amount,
|
||||
}
|
||||
: undefined,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
// ─── Main adapter ────────────────────────────────────────────
|
||||
|
||||
export function buildChartData(
|
||||
reportData: ReportData,
|
||||
key: PeriodKey,
|
||||
mode: "expense" | "income",
|
||||
comparison: boolean
|
||||
): ChartDataPoint[] {
|
||||
const merged = mergeBucketPeriods(reportData.buckets, key);
|
||||
|
||||
let points: ChartDataPoint[] = merged.map((p) => ({
|
||||
id: p.id,
|
||||
label: p.label,
|
||||
amount: getAmount(p, mode),
|
||||
}));
|
||||
|
||||
if (comparison) {
|
||||
points = attachComparison(points, key);
|
||||
}
|
||||
|
||||
return points;
|
||||
}
|
||||
40
src/components/HistoryChart/HistoryChart.models.ts
Normal file
40
src/components/HistoryChart/HistoryChart.models.ts
Normal file
@@ -0,0 +1,40 @@
|
||||
import {
|
||||
DashboardMode,
|
||||
DashboardPeriodType,
|
||||
DashboardSelectedPeriodId
|
||||
} from "../Dashboard";
|
||||
import { ReportData } from "../../features/report";
|
||||
|
||||
export interface _ChartDataPoint {
|
||||
id: string;
|
||||
label: string;
|
||||
amount: number;
|
||||
highlighted?: boolean;
|
||||
}
|
||||
|
||||
export interface ChartDataPoint extends _ChartDataPoint {
|
||||
compare?: _ChartDataPoint;
|
||||
}
|
||||
|
||||
export interface HistoryChartProps {
|
||||
header: string;
|
||||
summary?: string;
|
||||
tabs: string[];
|
||||
|
||||
reportData: ReportData;
|
||||
|
||||
colorScheme: {
|
||||
primary: string;
|
||||
light: string;
|
||||
text: string;
|
||||
};
|
||||
|
||||
mode: DashboardMode;
|
||||
periodType: DashboardPeriodType;
|
||||
selectedPeriodId: DashboardSelectedPeriodId;
|
||||
comparison: boolean;
|
||||
|
||||
togglePeriodType: () => void;
|
||||
setSelectedPeriodId: (id: string | null) => void;
|
||||
toggleComparison: () => void;
|
||||
}
|
||||
92
src/components/HistoryChart/HistoryChart.tsx
Normal file
92
src/components/HistoryChart/HistoryChart.tsx
Normal file
@@ -0,0 +1,92 @@
|
||||
import * as React from "react";
|
||||
import { HistoryChartProps } from "./HistoryChart.models";
|
||||
import HistoryChartView from "./HistoryChart.view";
|
||||
import { buildChartData, tabToKey } from "./HistoryChart.adapter";
|
||||
|
||||
export default function HistoryChart(props: HistoryChartProps) {
|
||||
const {
|
||||
tabs,
|
||||
reportData,
|
||||
mode,
|
||||
comparison,
|
||||
selectedPeriodId,
|
||||
setSelectedPeriodId
|
||||
} = props;
|
||||
|
||||
const [activeTab, setActiveTab] = React.useState<string>(tabs[0] || "");
|
||||
const [startIndex, setStartIndex] = React.useState(0);
|
||||
|
||||
const activeDataKey = tabToKey(activeTab);
|
||||
|
||||
const currentData = React.useMemo(() => {
|
||||
return buildChartData(reportData, activeDataKey, mode, comparison);
|
||||
}, [reportData, activeDataKey, mode, comparison]);
|
||||
|
||||
const maxAmount =
|
||||
currentData.length > 0
|
||||
? Math.max(
|
||||
...currentData.flatMap((d) =>
|
||||
comparison
|
||||
? [d.amount, ...(d.compare ? [d.compare.amount] : [])]
|
||||
: [d.amount]
|
||||
),
|
||||
1
|
||||
)
|
||||
: 1;
|
||||
|
||||
const visibleCountMap = {
|
||||
weekly: 6,
|
||||
monthly: 4,
|
||||
yearly: 4,
|
||||
fyly: 4,
|
||||
full: 4,
|
||||
};
|
||||
|
||||
const visibleCount = visibleCountMap[activeDataKey] ?? 4;
|
||||
|
||||
const total = currentData.length;
|
||||
|
||||
const clampedStartIndex = Math.min(
|
||||
startIndex,
|
||||
Math.max(total - visibleCount, 0)
|
||||
);
|
||||
|
||||
React.useEffect(() => {
|
||||
if (startIndex !== clampedStartIndex) {
|
||||
setStartIndex(clampedStartIndex);
|
||||
}
|
||||
}, [startIndex, clampedStartIndex]);
|
||||
|
||||
const visibleData = currentData.slice(
|
||||
clampedStartIndex,
|
||||
clampedStartIndex + visibleCount
|
||||
);
|
||||
|
||||
React.useEffect(() => {
|
||||
setSelectedPeriodId(null);
|
||||
}, [activeTab]);
|
||||
|
||||
React.useEffect(() => {
|
||||
if (
|
||||
selectedPeriodId &&
|
||||
!visibleData.some((p) => p.id === selectedPeriodId)
|
||||
) {
|
||||
setSelectedPeriodId(null);
|
||||
}
|
||||
}, [visibleData, selectedPeriodId]);
|
||||
|
||||
return (
|
||||
<HistoryChartView
|
||||
{...props}
|
||||
activeTab={activeTab}
|
||||
setActiveTab={setActiveTab}
|
||||
currentData={currentData}
|
||||
visibleData={visibleData}
|
||||
maxAmount={maxAmount}
|
||||
visibleCount={visibleCount}
|
||||
startIndex={clampedStartIndex}
|
||||
setStartIndex={setStartIndex}
|
||||
activeDataKey={activeDataKey}
|
||||
/>
|
||||
);
|
||||
}
|
||||
27
src/components/HistoryChart/HistoryChart.utils.ts
Normal file
27
src/components/HistoryChart/HistoryChart.utils.ts
Normal file
@@ -0,0 +1,27 @@
|
||||
import { ChartDataPoint } from "./HistoryChart.models";
|
||||
|
||||
export const formatDisplay = (
|
||||
point: ChartDataPoint,
|
||||
tab: string,
|
||||
comparison: boolean
|
||||
) => {
|
||||
const base = point.amount;
|
||||
const cmp = point.compare?.amount ?? 0;
|
||||
|
||||
const formatShort = (val: number) => {
|
||||
if (tab === "monthly" && val >= 100000) {
|
||||
return `${(val / 100000).toFixed(2)}L`;
|
||||
}
|
||||
if (tab === "weekly" && val >= 1000) {
|
||||
return `${(val / 1000).toFixed(1)}K`;
|
||||
}
|
||||
return val.toLocaleString("en-IN");
|
||||
};
|
||||
|
||||
if (!comparison) return `₹ ${formatShort(base)}`;
|
||||
|
||||
const diff = base - cmp;
|
||||
const sign = diff >= 0 ? "+" : "-";
|
||||
|
||||
return `₹ ${formatShort(base)} (${sign}${formatShort(Math.abs(diff))})`;
|
||||
};
|
||||
217
src/components/HistoryChart/HistoryChart.view.tsx
Normal file
217
src/components/HistoryChart/HistoryChart.view.tsx
Normal file
@@ -0,0 +1,217 @@
|
||||
import * as React from "react";
|
||||
import {
|
||||
Box,
|
||||
Typography,
|
||||
ToggleButtonGroup,
|
||||
ToggleButton,
|
||||
Paper
|
||||
} from "@mui/material";
|
||||
import { useTheme, alpha } from "@mui/material/styles";
|
||||
import IconButton from "@mui/material/IconButton";
|
||||
import ChevronLeftIcon from "@mui/icons-material/ChevronLeft";
|
||||
import ChevronRightIcon from "@mui/icons-material/ChevronRight";
|
||||
import {
|
||||
ChartDataPoint,
|
||||
HistoryChartProps,
|
||||
} from "./HistoryChart.models";
|
||||
import { formatDisplay } from "./HistoryChart.utils";
|
||||
|
||||
interface ViewProps extends HistoryChartProps {
|
||||
activeTab: string;
|
||||
setActiveTab: (v: string) => void;
|
||||
currentData: ChartDataPoint[];
|
||||
visibleData: ChartDataPoint[];
|
||||
maxAmount: number;
|
||||
visibleCount: number;
|
||||
startIndex: number;
|
||||
setStartIndex: React.Dispatch<React.SetStateAction<number>>;
|
||||
activeDataKey: string;
|
||||
}
|
||||
|
||||
export default function HistoryChartView(props: ViewProps) {
|
||||
const {
|
||||
header,
|
||||
summary,
|
||||
tabs,
|
||||
colorScheme,
|
||||
|
||||
mode,
|
||||
periodType,
|
||||
selectedPeriodId,
|
||||
comparison,
|
||||
|
||||
togglePeriodType,
|
||||
setSelectedPeriodId,
|
||||
toggleComparison,
|
||||
|
||||
activeTab,
|
||||
setActiveTab,
|
||||
currentData,
|
||||
visibleData,
|
||||
maxAmount,
|
||||
visibleCount,
|
||||
startIndex,
|
||||
setStartIndex,
|
||||
activeDataKey,
|
||||
} = props;
|
||||
|
||||
const theme = useTheme();
|
||||
const isDark = theme.palette.mode === "dark";
|
||||
|
||||
const total = currentData.length;
|
||||
const maxStartIndex = Math.max(total - visibleCount, 0);
|
||||
const clampedStartIndex = Math.min(startIndex, maxStartIndex);
|
||||
|
||||
const handleTabChange = (_: React.MouseEvent<HTMLElement>, newTab: string | null) => {
|
||||
if (newTab !== null) setActiveTab(newTab);
|
||||
};
|
||||
|
||||
const canGoLeft = clampedStartIndex > 0;
|
||||
const canGoRight = clampedStartIndex < maxStartIndex;
|
||||
|
||||
const handlePrev = () => {
|
||||
if (!canGoLeft) return;
|
||||
setStartIndex((prev) => Math.max(prev - visibleCount, 0));
|
||||
};
|
||||
|
||||
const handleNext = () => {
|
||||
if (!canGoRight) return;
|
||||
setStartIndex((prev) => {
|
||||
const next = prev + visibleCount;
|
||||
return Math.min(next, maxStartIndex);
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<Paper
|
||||
sx={{
|
||||
p: { xs: 2.5, sm: 4 },
|
||||
borderRadius: 4,
|
||||
width: "100%",
|
||||
boxShadow: "none",
|
||||
border: "1px solid",
|
||||
borderColor: "divider",
|
||||
bgcolor: isDark ? "background.paper" : colorScheme.light,
|
||||
}}
|
||||
>
|
||||
<Typography variant="h6" fontWeight={700} gutterBottom>
|
||||
{header}
|
||||
</Typography>
|
||||
|
||||
{summary && (
|
||||
<Typography variant="body2" color="text.secondary" sx={{ mb: 3 }}>
|
||||
{summary}
|
||||
</Typography>
|
||||
)}
|
||||
|
||||
<ToggleButtonGroup value={activeTab} exclusive onChange={handleTabChange} fullWidth sx={{ mb: 4 }}>
|
||||
{tabs.map((tab) => (
|
||||
<ToggleButton key={tab} value={tab}>
|
||||
{tab}
|
||||
</ToggleButton>
|
||||
))}
|
||||
</ToggleButtonGroup>
|
||||
|
||||
<Box sx={{ display: "flex", justifyContent: "space-between", mb: 3 }}>
|
||||
<ToggleButtonGroup value={periodType} exclusive onChange={togglePeriodType} size="small">
|
||||
<ToggleButton value="rolling">Rolling</ToggleButton>
|
||||
<ToggleButton value="calendar">Calendar</ToggleButton>
|
||||
</ToggleButtonGroup>
|
||||
|
||||
<ToggleButton
|
||||
value="compare"
|
||||
selected={comparison}
|
||||
onChange={toggleComparison}
|
||||
size="small"
|
||||
>
|
||||
Compare
|
||||
</ToggleButton>
|
||||
</Box>
|
||||
|
||||
{currentData.length > 0 ? (
|
||||
<Box sx={{ position: "relative", mt: 4 }}>
|
||||
{canGoLeft && (
|
||||
<IconButton onClick={handlePrev} size="small" sx={{ position: "absolute", left: 0, top: "50%" }}>
|
||||
<ChevronLeftIcon fontSize="small" />
|
||||
</IconButton>
|
||||
)}
|
||||
|
||||
<Box sx={{ display: "flex", alignItems: "flex-end", height: 220, mt: 4 }}>
|
||||
{visibleData.map((point) => {
|
||||
const currentHeight = (point.amount / maxAmount) * 100;
|
||||
const compareHeight = comparison
|
||||
? ((point.compare?.amount ?? 0) / maxAmount) * 100
|
||||
: 0;
|
||||
|
||||
const isSelected = selectedPeriodId === point.id;
|
||||
const display = formatDisplay(point, activeDataKey, comparison);
|
||||
|
||||
return (
|
||||
<Box
|
||||
key={point.id}
|
||||
onClick={() =>
|
||||
setSelectedPeriodId(isSelected ? null : point.id)
|
||||
}
|
||||
sx={{
|
||||
flex: 1,
|
||||
display: "flex",
|
||||
flexDirection: "column",
|
||||
alignItems: "center",
|
||||
cursor: "pointer",
|
||||
height: "100%"
|
||||
}}
|
||||
>
|
||||
<Box sx={{ display: "flex", alignItems: "flex-end", gap: 1, height: "100%" }}>
|
||||
{comparison && (
|
||||
<Box
|
||||
sx={{
|
||||
width: 8,
|
||||
height: `${compareHeight}%`,
|
||||
bgcolor: alpha(colorScheme.primary, 0.4),
|
||||
borderRadius: "4px 4px 0 0"
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
|
||||
<Box
|
||||
sx={{
|
||||
width: 12,
|
||||
height: `${currentHeight}%`,
|
||||
bgcolor: isSelected ? "warning.main" : colorScheme.primary,
|
||||
borderRadius: "4px 4px 0 0"
|
||||
}}
|
||||
/>
|
||||
</Box>
|
||||
|
||||
<Typography variant="caption">
|
||||
{point.label}
|
||||
</Typography>
|
||||
|
||||
{comparison && point.compare && (
|
||||
<Typography variant="caption" color="text.secondary">
|
||||
{point.compare.label}
|
||||
</Typography>
|
||||
)}
|
||||
|
||||
<Typography variant="caption">
|
||||
{display}
|
||||
</Typography>
|
||||
</Box>
|
||||
);
|
||||
})}
|
||||
</Box>
|
||||
|
||||
{canGoRight && (
|
||||
<IconButton onClick={handleNext} size="small" sx={{ position: "absolute", right: 0, top: "50%" }}>
|
||||
<ChevronRightIcon fontSize="small" />
|
||||
</IconButton>
|
||||
)}
|
||||
</Box>
|
||||
) : (
|
||||
<Box sx={{ height: 200, display: "flex", alignItems: "center", justifyContent: "center" }}>
|
||||
<Typography color="text.secondary">No Data Available</Typography>
|
||||
</Box>
|
||||
)}
|
||||
</Paper>
|
||||
);
|
||||
}
|
||||
2
src/components/HistoryChart/index.ts
Normal file
2
src/components/HistoryChart/index.ts
Normal file
@@ -0,0 +1,2 @@
|
||||
export { default } from "./HistoryChart";
|
||||
export * from "./HistoryChart.models";
|
||||
66
src/components/LatestItems/LatestItems.adapter.ts
Normal file
66
src/components/LatestItems/LatestItems.adapter.ts
Normal file
@@ -0,0 +1,66 @@
|
||||
import { ReportData, Transaction, GroupKey } from "../../features/report";
|
||||
import {
|
||||
mergeBucketPeriods,
|
||||
periodIdToKey,
|
||||
formatCurrency,
|
||||
filterBuckets,
|
||||
} from "../report.helpers";
|
||||
import { LatestItem } from "./LatestItems.models";
|
||||
|
||||
// ─── Transaction extraction ─────────────────────────────────
|
||||
|
||||
function extractTransactions(
|
||||
reportData: ReportData,
|
||||
selectedPeriodId: string | null,
|
||||
selectedGroupKey: GroupKey | null,
|
||||
mode: "expense" | "income"
|
||||
): Transaction[] {
|
||||
const buckets = filterBuckets(reportData.buckets, selectedGroupKey);
|
||||
if (selectedPeriodId) {
|
||||
const key = periodIdToKey(selectedPeriodId);
|
||||
const periods = mergeBucketPeriods(buckets, key);
|
||||
const selected = periods.find((p) => p.id === selectedPeriodId);
|
||||
|
||||
if (!selected) return [];
|
||||
|
||||
return mode === "expense"
|
||||
? (selected.expenses.transactions || [])
|
||||
: (selected.incomes.transactions || []);
|
||||
}
|
||||
|
||||
const periods = mergeBucketPeriods(buckets, "full");
|
||||
|
||||
if (!periods.length) return [];
|
||||
|
||||
const full = periods[0];
|
||||
|
||||
return mode === "expense"
|
||||
? (full.expenses.transactions || [])
|
||||
: (full.incomes.transactions || []);
|
||||
}
|
||||
|
||||
// ─── Main adapter ────────────────────────────────────────────
|
||||
|
||||
export function buildLatestItems(
|
||||
reportData: ReportData,
|
||||
selectedPeriodId: string | null,
|
||||
selectedGroupKey: GroupKey | null,
|
||||
mode: "expense" | "income"
|
||||
): LatestItem[] {
|
||||
const txns = extractTransactions(reportData, selectedPeriodId, selectedGroupKey, mode);
|
||||
|
||||
return txns
|
||||
.filter((t) => (mode === "expense" ? t.amount < 0 : t.amount >= 0))
|
||||
.sort(
|
||||
(a, b) =>
|
||||
new Date(b.occurred_at).getTime() -
|
||||
new Date(a.occurred_at).getTime()
|
||||
)
|
||||
.map((t, index) => ({
|
||||
id: index + 1,
|
||||
title: t.payee.name,
|
||||
subtitle: t.tags.map((tag) => tag.name).join(", "),
|
||||
amount: formatCurrency(t.amount),
|
||||
timeAgo: new Date(t.occurred_at).toLocaleDateString("en-IN"),
|
||||
}));
|
||||
}
|
||||
14
src/components/LatestItems/LatestItems.models.ts
Normal file
14
src/components/LatestItems/LatestItems.models.ts
Normal file
@@ -0,0 +1,14 @@
|
||||
export interface LatestItem {
|
||||
id: string | number;
|
||||
title: string;
|
||||
subtitle: string;
|
||||
amount: string;
|
||||
timeAgo: string;
|
||||
}
|
||||
|
||||
export interface LatestItemsViewProps {
|
||||
items: LatestItem[];
|
||||
accentColor: string;
|
||||
canExpand: boolean;
|
||||
onExpand: () => void;
|
||||
}
|
||||
44
src/components/LatestItems/LatestItems.tsx
Normal file
44
src/components/LatestItems/LatestItems.tsx
Normal file
@@ -0,0 +1,44 @@
|
||||
import * as React from "react";
|
||||
import { ReportData, GroupKey } from "../../features/report";
|
||||
import { buildLatestItems } from "./LatestItems.adapter";
|
||||
import LatestItemsView from "./LatestItems.view";
|
||||
|
||||
type Props = {
|
||||
reportData: ReportData;
|
||||
mode: "expense" | "income";
|
||||
selectedPeriodId: string | null;
|
||||
selectedGroupKey?: GroupKey | null;
|
||||
accentColor: string;
|
||||
};
|
||||
|
||||
export default function LatestItems({
|
||||
reportData,
|
||||
mode,
|
||||
selectedPeriodId,
|
||||
selectedGroupKey = null,
|
||||
accentColor,
|
||||
}: Props) {
|
||||
const [visibleCount, setVisibleCount] = React.useState(5);
|
||||
|
||||
const allItems = React.useMemo(() => {
|
||||
return buildLatestItems(reportData, selectedPeriodId, selectedGroupKey, mode);
|
||||
}, [reportData, selectedPeriodId, selectedGroupKey, mode]);
|
||||
|
||||
const hasSelection = Boolean(selectedPeriodId) || Boolean(selectedGroupKey);
|
||||
|
||||
const visibleItems = React.useMemo(() => {
|
||||
if (!hasSelection) return allItems.slice(0, 5);
|
||||
return allItems.slice(0, visibleCount);
|
||||
}, [allItems, hasSelection, visibleCount]);
|
||||
|
||||
const canExpand = hasSelection && visibleCount < allItems.length;
|
||||
|
||||
return (
|
||||
<LatestItemsView
|
||||
items={visibleItems}
|
||||
accentColor={accentColor}
|
||||
canExpand={canExpand}
|
||||
onExpand={() => setVisibleCount((prev) => prev + 5)}
|
||||
/>
|
||||
);
|
||||
}
|
||||
88
src/components/LatestItems/LatestItems.view.tsx
Normal file
88
src/components/LatestItems/LatestItems.view.tsx
Normal file
@@ -0,0 +1,88 @@
|
||||
import * as React from "react";
|
||||
import {
|
||||
List,
|
||||
ListItem,
|
||||
ListItemAvatar,
|
||||
ListItemText,
|
||||
Avatar,
|
||||
Typography,
|
||||
Box,
|
||||
IconButton,
|
||||
} from "@mui/material";
|
||||
import ExpandMoreIcon from "@mui/icons-material/ExpandMore";
|
||||
import { LatestItemsViewProps } from "./LatestItems.models";
|
||||
|
||||
export default function LatestItemsView({
|
||||
items,
|
||||
accentColor,
|
||||
canExpand,
|
||||
onExpand,
|
||||
}: LatestItemsViewProps) {
|
||||
return (
|
||||
<Box sx={{ width: "100%", bgcolor: "background.paper", borderRadius: 4, p: 2 }}>
|
||||
<Box sx={{ mb: 2, px: 2 }}>
|
||||
<Typography variant="h6" fontWeight="bold">
|
||||
Recent Transactions
|
||||
</Typography>
|
||||
</Box>
|
||||
|
||||
<List disablePadding>
|
||||
{items.map((item, index) => (
|
||||
<ListItem
|
||||
key={item.id}
|
||||
sx={{
|
||||
px: { xs: 1, sm: 2 },
|
||||
py: 2,
|
||||
mb: index !== items.length - 1 ? 1 : 0,
|
||||
borderRadius: 3,
|
||||
"&:hover": { bgcolor: "action.hover" },
|
||||
}}
|
||||
>
|
||||
<ListItemAvatar>
|
||||
<Avatar
|
||||
variant="rounded"
|
||||
sx={{
|
||||
bgcolor: `${accentColor}22`,
|
||||
width: 48,
|
||||
height: 48,
|
||||
borderRadius: 3,
|
||||
mr: 2,
|
||||
}}
|
||||
/>
|
||||
</ListItemAvatar>
|
||||
|
||||
<ListItemText
|
||||
primary={
|
||||
<Typography variant="subtitle1" fontWeight={600}>
|
||||
{item.title}
|
||||
</Typography>
|
||||
}
|
||||
secondary={
|
||||
<Typography variant="body2" color="text.secondary">
|
||||
{item.subtitle}
|
||||
</Typography>
|
||||
}
|
||||
/>
|
||||
|
||||
<Box sx={{ textAlign: "right" }}>
|
||||
<Typography variant="subtitle1" fontWeight={700}>
|
||||
{item.amount}
|
||||
</Typography>
|
||||
<Typography variant="caption" color="text.secondary">
|
||||
{item.timeAgo}
|
||||
</Typography>
|
||||
</Box>
|
||||
</ListItem>
|
||||
))}
|
||||
|
||||
{canExpand && (
|
||||
<Box sx={{ display: "flex", justifyContent: "center", mt: 2 }}>
|
||||
<IconButton size="small" onClick={onExpand}>
|
||||
<ExpandMoreIcon />
|
||||
</IconButton>
|
||||
</Box>
|
||||
)}
|
||||
</List>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
2
src/components/LatestItems/index.ts
Normal file
2
src/components/LatestItems/index.ts
Normal file
@@ -0,0 +1,2 @@
|
||||
export { default } from "./LatestItems";
|
||||
export * from "./LatestItems.models";
|
||||
10
src/components/ProgressCard/ProgressCard.models.ts
Normal file
10
src/components/ProgressCard/ProgressCard.models.ts
Normal file
@@ -0,0 +1,10 @@
|
||||
export interface ProgressCardProps {
|
||||
header: string;
|
||||
summary?: string;
|
||||
progressAmount: number;
|
||||
totalAmount: number;
|
||||
colorTheme?: "primary" | "secondary" | "error" | "info" | "success" | "warning";
|
||||
compact?: boolean;
|
||||
selected?: boolean;
|
||||
onClick?: () => void;
|
||||
}
|
||||
25
src/components/ProgressCard/ProgressCard.tsx
Normal file
25
src/components/ProgressCard/ProgressCard.tsx
Normal file
@@ -0,0 +1,25 @@
|
||||
import * as React from "react";
|
||||
import ProgressCardView from "./ProgressCard.view";
|
||||
import { ProgressCardProps } from "./ProgressCard.models";
|
||||
import { getPercentage, formatCurrency } from "../report.helpers";
|
||||
|
||||
export default function ProgressCard(props: ProgressCardProps) {
|
||||
const { progressAmount, totalAmount, compact = false } = props;
|
||||
|
||||
const percentage = getPercentage(progressAmount, totalAmount);
|
||||
|
||||
const formattedProgress = formatCurrency(progressAmount);
|
||||
const formattedTotal = formatCurrency(totalAmount);
|
||||
|
||||
return (
|
||||
<ProgressCardView
|
||||
{...props}
|
||||
percentage={percentage}
|
||||
formattedProgress={formattedProgress}
|
||||
formattedTotal={formattedTotal}
|
||||
compact={compact}
|
||||
selected={props.selected}
|
||||
onClick={props.onClick}
|
||||
/>
|
||||
);
|
||||
}
|
||||
141
src/components/ProgressCard/ProgressCard.view.tsx
Normal file
141
src/components/ProgressCard/ProgressCard.view.tsx
Normal file
@@ -0,0 +1,141 @@
|
||||
import * as React from "react";
|
||||
import {
|
||||
Box,
|
||||
Typography,
|
||||
Paper,
|
||||
LinearProgress,
|
||||
Divider,
|
||||
linearProgressClasses
|
||||
} from "@mui/material";
|
||||
import { useTheme, alpha } from "@mui/material/styles";
|
||||
import { ProgressCardProps } from "./ProgressCard.models";
|
||||
|
||||
interface ViewProps extends ProgressCardProps {
|
||||
percentage: number;
|
||||
formattedProgress: string;
|
||||
formattedTotal: string;
|
||||
selected?: boolean;
|
||||
onClick?: () => void;
|
||||
}
|
||||
|
||||
export default function ProgressCardView({
|
||||
header,
|
||||
colorTheme = "info",
|
||||
percentage,
|
||||
formattedProgress,
|
||||
formattedTotal,
|
||||
compact = false,
|
||||
selected,
|
||||
onClick,
|
||||
}: ViewProps) {
|
||||
const theme = useTheme();
|
||||
const isDark = theme.palette.mode === "dark";
|
||||
|
||||
return (
|
||||
<Paper
|
||||
elevation={compact ? 2 : 4}
|
||||
onClick={onClick}
|
||||
sx={{
|
||||
width: "100%",
|
||||
p: compact ? { xs: 2.5, md: 3 } : { xs: 3, md: 4 },
|
||||
borderRadius: compact ? 3 : 4,
|
||||
cursor: onClick ? "pointer" : "default",
|
||||
transform: selected ? "scale(1.02)" : "scale(1)",
|
||||
transition: "transform 0.2s ease, box-shadow 0.2s ease",
|
||||
background: (theme) => {
|
||||
const baseColor = theme.palette[colorTheme]?.main || theme.palette.primary.main;
|
||||
const lightColor = theme.palette[colorTheme]?.light || theme.palette.primary.light;
|
||||
return isDark
|
||||
? `linear-gradient(135deg, ${alpha(baseColor, 0.9)} 0%, ${alpha(baseColor, 0.3)} 100%)`
|
||||
: `linear-gradient(135deg, ${baseColor} 0%, ${lightColor} 100%)`;
|
||||
},
|
||||
color: "#fff",
|
||||
display: "flex",
|
||||
flexDirection: "column",
|
||||
alignItems: compact ? "flex-start" : "center",
|
||||
justifyContent: "center",
|
||||
position: "relative",
|
||||
overflow: "hidden",
|
||||
border: selected
|
||||
? `2px solid #fff`
|
||||
: isDark ? "1px solid rgba(255,255,255,0.1)" : "none",
|
||||
boxShadow: (theme) => {
|
||||
const baseShadow = `0 ${compact ? 6 : 12}px ${compact ? 12 : 24}px -10px ${
|
||||
isDark
|
||||
? "rgba(0,0,0,0.5)"
|
||||
: theme.palette[colorTheme]?.main || theme.palette.primary.main
|
||||
}`;
|
||||
return selected
|
||||
? `${baseShadow}, 0 0 0 2px ${theme.palette.background.paper}, 0 0 0 4px ${theme.palette[colorTheme]?.main || theme.palette.primary.main}`
|
||||
: baseShadow;
|
||||
},
|
||||
}}
|
||||
>
|
||||
<Typography
|
||||
variant={compact ? "body2" : "subtitle1"}
|
||||
fontWeight={700}
|
||||
sx={{
|
||||
opacity: 0.95,
|
||||
mb: compact ? 1.5 : 2,
|
||||
width: '100%',
|
||||
overflow: 'hidden',
|
||||
textOverflow: 'ellipsis',
|
||||
whiteSpace: 'nowrap',
|
||||
letterSpacing: 0.5,
|
||||
textShadow: isDark ? '0 1px 2px rgba(0,0,0,0.3)' : 'none'
|
||||
}}
|
||||
>
|
||||
{header}
|
||||
</Typography>
|
||||
|
||||
<Box sx={{ mb: compact ? 2 : 3, width: '100%' }}>
|
||||
<Typography
|
||||
variant={compact ? "h5" : "h3"}
|
||||
fontWeight={900}
|
||||
sx={{ mb: 0.5, lineHeight: 1.2, textShadow: isDark ? '0 2px 4px rgba(0,0,0,0.3)' : 'none' }}
|
||||
>
|
||||
{formattedProgress}
|
||||
</Typography>
|
||||
|
||||
<Divider
|
||||
sx={{
|
||||
my: 1,
|
||||
borderColor: "rgba(255,255,255,0.25)",
|
||||
width: "100%",
|
||||
}}
|
||||
/>
|
||||
|
||||
<Typography
|
||||
variant={compact ? "caption" : "body2"}
|
||||
sx={{
|
||||
opacity: 0.85,
|
||||
fontWeight: 500,
|
||||
display: "block",
|
||||
color: "rgba(255,255,255,0.9)"
|
||||
}}
|
||||
>
|
||||
of {formattedTotal}
|
||||
</Typography>
|
||||
</Box>
|
||||
|
||||
<Box sx={{ width: "100%", mt: 'auto' }}>
|
||||
<LinearProgress
|
||||
variant="determinate"
|
||||
value={percentage}
|
||||
sx={{
|
||||
height: compact ? 6 : 10,
|
||||
borderRadius: 5,
|
||||
[`&.${linearProgressClasses.colorPrimary}`]: {
|
||||
backgroundColor: "rgba(0, 0, 0, 0.25)",
|
||||
},
|
||||
[`& .${linearProgressClasses.bar}`]: {
|
||||
borderRadius: 5,
|
||||
backgroundColor: "#fff",
|
||||
boxShadow: '0 0 8px rgba(255,255,255,0.4)'
|
||||
},
|
||||
}}
|
||||
/>
|
||||
</Box>
|
||||
</Paper>
|
||||
);
|
||||
}
|
||||
74
src/components/ProgressCard/TopTags.adapter.ts
Normal file
74
src/components/ProgressCard/TopTags.adapter.ts
Normal file
@@ -0,0 +1,74 @@
|
||||
import { ReportData } from "../../features/report";
|
||||
import {
|
||||
getAmount,
|
||||
DecoratedPeriod,
|
||||
} from "../report.helpers";
|
||||
|
||||
// ─── Helpers ─────────────────────────────────────────────────
|
||||
|
||||
function findPeriod(
|
||||
periods: DecoratedPeriod[],
|
||||
selectedPeriodId?: string | null
|
||||
) {
|
||||
if (!periods.length) return null;
|
||||
|
||||
if (selectedPeriodId) {
|
||||
const match = periods.find((p) => p.id === selectedPeriodId);
|
||||
if (match) return match;
|
||||
}
|
||||
|
||||
// fallback → latest
|
||||
return periods.reduce((latest, p) =>
|
||||
new Date(p.start).getTime() > new Date(latest.start).getTime()
|
||||
? p
|
||||
: latest
|
||||
);
|
||||
}
|
||||
|
||||
// ─── Main adapter ────────────────────────────────────────────
|
||||
|
||||
export interface TagItem {
|
||||
tag: string;
|
||||
amount: number;
|
||||
}
|
||||
|
||||
export function extractTopTags(
|
||||
reportData: ReportData,
|
||||
mode: "expense" | "income",
|
||||
selectedPeriodId?: string | null
|
||||
): { items: TagItem[]; total: number } {
|
||||
const tagMap = new Map<string, number>();
|
||||
|
||||
for (const bucket of reportData.buckets) {
|
||||
const tags = bucket.group_key.tags;
|
||||
if (!tags || tags.length === 0) continue;
|
||||
|
||||
// Prefer FULL if available
|
||||
const fullPeriods = (bucket.periods.full || []) as DecoratedPeriod[];
|
||||
|
||||
const periodsToUse = selectedPeriodId
|
||||
? (Object.values(bucket.periods).flat() as DecoratedPeriod[])
|
||||
: fullPeriods;
|
||||
|
||||
const period = findPeriod(periodsToUse, selectedPeriodId);
|
||||
if (!period) continue;
|
||||
|
||||
const amount = getAmount(period, mode);
|
||||
|
||||
for (const tag of tags) {
|
||||
tagMap.set(tag, (tagMap.get(tag) || 0) + amount);
|
||||
}
|
||||
}
|
||||
|
||||
const arr = Array.from(tagMap.entries()).map(([tag, amount]) => ({
|
||||
tag,
|
||||
amount,
|
||||
}));
|
||||
|
||||
arr.sort((a, b) => b.amount - a.amount);
|
||||
|
||||
const top = arr.slice(0, 4);
|
||||
const total = top.reduce((sum, t) => sum + t.amount, 0);
|
||||
|
||||
return { items: top, total };
|
||||
}
|
||||
61
src/components/ProgressCard/TopTags.tsx
Normal file
61
src/components/ProgressCard/TopTags.tsx
Normal file
@@ -0,0 +1,61 @@
|
||||
import * as React from "react";
|
||||
import { Box } from "@mui/material";
|
||||
import { ReportData, GroupKey } from "../../features/report";
|
||||
import ProgressCard from "./ProgressCard";
|
||||
import { extractTopTags } from "./TopTags.adapter";
|
||||
|
||||
type Props = {
|
||||
reportData: ReportData;
|
||||
mode: "expense" | "income";
|
||||
selectedPeriodId?: string | null;
|
||||
selectedGroupKey?: GroupKey | null;
|
||||
setSelectedGroupKey?: (key: GroupKey | null) => void;
|
||||
compact?: boolean;
|
||||
};
|
||||
|
||||
export default function TopTags({
|
||||
reportData,
|
||||
mode,
|
||||
selectedPeriodId,
|
||||
selectedGroupKey,
|
||||
setSelectedGroupKey,
|
||||
compact = true,
|
||||
}: Props) {
|
||||
const { items, total } = React.useMemo(() => {
|
||||
return extractTopTags(reportData, mode, selectedPeriodId);
|
||||
}, [reportData, mode, selectedPeriodId]);
|
||||
|
||||
return (
|
||||
<Box
|
||||
sx={{
|
||||
display: "grid",
|
||||
gridTemplateColumns: {
|
||||
xs: "1fr",
|
||||
sm: "repeat(2, 1fr)",
|
||||
md: "repeat(4, 1fr)",
|
||||
},
|
||||
gap: 2,
|
||||
}}
|
||||
>
|
||||
{items.map((item) => {
|
||||
const isSelected = selectedGroupKey?.tags?.includes(item.tag);
|
||||
return (
|
||||
<ProgressCard
|
||||
key={item.tag}
|
||||
header={item.tag}
|
||||
progressAmount={item.amount}
|
||||
totalAmount={total}
|
||||
compact={compact}
|
||||
colorTheme={mode === "expense" ? "error" : "success"}
|
||||
selected={isSelected}
|
||||
onClick={() => {
|
||||
if (setSelectedGroupKey) {
|
||||
setSelectedGroupKey(isSelected ? null : { tags: [item.tag] });
|
||||
}
|
||||
}}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
2
src/components/ProgressCard/index.ts
Normal file
2
src/components/ProgressCard/index.ts
Normal file
@@ -0,0 +1,2 @@
|
||||
export { default } from "./ProgressCard";
|
||||
export * from "./ProgressCard.models";
|
||||
147
src/components/report.helpers.ts
Normal file
147
src/components/report.helpers.ts
Normal file
@@ -0,0 +1,147 @@
|
||||
import {
|
||||
ReportPeriod,
|
||||
ReportBucket,
|
||||
GroupKey,
|
||||
} from "../features/report";
|
||||
|
||||
// ─── Types ────────────────────────────────────────────────────
|
||||
|
||||
export type PeriodKey = "weekly" | "monthly" | "yearly" | "fyly" | "full";
|
||||
|
||||
export type DecoratedPeriod = ReportPeriod & {
|
||||
id: string;
|
||||
label: string;
|
||||
};
|
||||
|
||||
// ─── Period helpers ───────────────────────────────────────────
|
||||
|
||||
const PREFIX_TO_KEY: Record<string, PeriodKey> = {
|
||||
W: "weekly",
|
||||
M: "monthly",
|
||||
Y: "yearly",
|
||||
FY: "fyly",
|
||||
FULL: "full",
|
||||
};
|
||||
|
||||
/**
|
||||
* Derive the period key from a decorated-period id.
|
||||
* E.g. `"W:2026-04-28_2026-05-04"` → `"weekly"`
|
||||
*/
|
||||
export function periodIdToKey(periodId: string): PeriodKey {
|
||||
const prefix = periodId.split(":")[0];
|
||||
return PREFIX_TO_KEY[prefix] ?? "full";
|
||||
}
|
||||
|
||||
// ─── Metric helpers ───────────────────────────────────────────
|
||||
|
||||
export function getAmount(
|
||||
period: ReportPeriod,
|
||||
mode: "expense" | "income"
|
||||
): number {
|
||||
return mode === "expense" ? period.expenses.sum : period.incomes.sum;
|
||||
}
|
||||
|
||||
function mergeMetric(a: ReportPeriod["expenses"], b: ReportPeriod["expenses"]) {
|
||||
const sum = a.sum + b.sum;
|
||||
const count = a.count + b.count;
|
||||
|
||||
return {
|
||||
...a,
|
||||
sum,
|
||||
count,
|
||||
average: count > 0 ? sum / count : 0,
|
||||
transactions:
|
||||
a.transactions || b.transactions
|
||||
? [...(a.transactions || []), ...(b.transactions || [])]
|
||||
: undefined,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Merge periods with the same id across all buckets, summing
|
||||
* their metrics and concatenating transactions.
|
||||
*
|
||||
* Returns sorted by start date ascending.
|
||||
*/
|
||||
export function mergeBucketPeriods(
|
||||
buckets: ReportBucket[],
|
||||
key: PeriodKey
|
||||
): DecoratedPeriod[] {
|
||||
const map = new Map<string, DecoratedPeriod>();
|
||||
|
||||
for (const bucket of buckets) {
|
||||
const periods = (bucket.periods[key] || []) as DecoratedPeriod[];
|
||||
|
||||
for (const p of periods) {
|
||||
const existing = map.get(p.id);
|
||||
|
||||
if (!existing) {
|
||||
map.set(p.id, {
|
||||
...p,
|
||||
expenses: { ...p.expenses },
|
||||
incomes: { ...p.incomes },
|
||||
});
|
||||
} else {
|
||||
map.set(p.id, {
|
||||
...existing,
|
||||
expenses: mergeMetric(existing.expenses, p.expenses),
|
||||
incomes: mergeMetric(existing.incomes, p.incomes),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return Array.from(map.values()).sort(
|
||||
(a, b) => new Date(a.start).getTime() - new Date(b.start).getTime()
|
||||
);
|
||||
}
|
||||
|
||||
// ─── Formatting ───────────────────────────────────────────────
|
||||
|
||||
export const formatCurrency = (val: number) => {
|
||||
const absVal = Math.abs(val);
|
||||
if (absVal >= 100000) {
|
||||
return `₹ ${(val / 100000).toFixed(2)}L`;
|
||||
}
|
||||
if (absVal >= 1000) {
|
||||
return `₹ ${(val / 1000).toFixed(2)}k`;
|
||||
}
|
||||
return `₹ ${val.toFixed(2)}`;
|
||||
};
|
||||
|
||||
export const getPercentage = (progressAmount: number, totalAmount: number) => {
|
||||
if (!totalAmount) return 0;
|
||||
return Math.min(100, Math.max(0, (progressAmount / totalAmount) * 100));
|
||||
};
|
||||
|
||||
// ─── Group filtering ──────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Check if a bucket's group_key matches the selected GroupKey.
|
||||
* Every dimension present in `selected` must exist in the bucket
|
||||
* and contain all the selected values.
|
||||
*/
|
||||
export function matchesGroupKey(
|
||||
bucket: ReportBucket,
|
||||
selected: GroupKey
|
||||
): boolean {
|
||||
for (const [dim, values] of Object.entries(selected)) {
|
||||
const bucketValues = bucket.group_key[dim as keyof GroupKey];
|
||||
if (!bucketValues) return false;
|
||||
if (!(values as string[]).every((v) => bucketValues.includes(v)))
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return only buckets matching the selected group key,
|
||||
* or all buckets if no selection.
|
||||
*/
|
||||
export function filterBuckets(
|
||||
buckets: ReportBucket[],
|
||||
selectedGroupKey: GroupKey | null
|
||||
): ReportBucket[] {
|
||||
if (!selectedGroupKey) return buckets;
|
||||
return buckets.filter((b) => matchesGroupKey(b, selectedGroupKey));
|
||||
}
|
||||
68
src/dashboard-config.ts
Normal file
68
src/dashboard-config.ts
Normal file
@@ -0,0 +1,68 @@
|
||||
import HistoryChart from "./components/HistoryChart";
|
||||
import LatestItems from "./components/LatestItems";
|
||||
import { DashboardConfig } from "./components/Dashboard";
|
||||
import TopTags from "./components/ProgressCard/TopTags";
|
||||
|
||||
export const configuration: DashboardConfig = {
|
||||
sections: [
|
||||
{
|
||||
id: "breakdown",
|
||||
title: "Breakdown",
|
||||
summary: "Interactive chronological tracking",
|
||||
component: HistoryChart,
|
||||
settings: {
|
||||
tabs: ["Weekly", "Monthly"],
|
||||
// tabs: ["Weekly", "Monthly", "Yearly", "Financial Year", "All Time"],
|
||||
},
|
||||
style: {
|
||||
size: 12,
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "top-categories",
|
||||
title: 'Top Categories',
|
||||
component: TopTags,
|
||||
settings: {
|
||||
compact: true,
|
||||
},
|
||||
style: {
|
||||
size: 12,
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "items",
|
||||
component: LatestItems,
|
||||
style: {
|
||||
size: 12,
|
||||
},
|
||||
},
|
||||
],
|
||||
style: {
|
||||
palette: {
|
||||
expense: {
|
||||
light: {
|
||||
primary: "#d32f2f",
|
||||
background: "#fdecea",
|
||||
text: "#b71c1c"
|
||||
},
|
||||
dark: {
|
||||
primary: "#f44336",
|
||||
background: "rgba(244, 67, 54, 0.15)",
|
||||
text: "#ffcdd2"
|
||||
}
|
||||
},
|
||||
income: {
|
||||
light: {
|
||||
primary: "#2e7d32",
|
||||
background: "#e8f5e9",
|
||||
text: "#1b5e20"
|
||||
},
|
||||
dark: {
|
||||
primary: "#4caf50",
|
||||
background: "rgba(76, 175, 80, 0.15)",
|
||||
text: "#c8e6c9"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
13
src/features/report/index.ts
Normal file
13
src/features/report/index.ts
Normal file
@@ -0,0 +1,13 @@
|
||||
export {
|
||||
useReport
|
||||
} from './useReport'
|
||||
export type {
|
||||
Transaction,
|
||||
ReportData,
|
||||
ReportBucket,
|
||||
ReportPeriod,
|
||||
GroupKey,
|
||||
} from './report.models'
|
||||
export {
|
||||
prepareReport
|
||||
} from './report.utils'
|
||||
90
src/features/report/report.models.ts
Normal file
90
src/features/report/report.models.ts
Normal file
@@ -0,0 +1,90 @@
|
||||
export interface Payor {
|
||||
name: string;
|
||||
}
|
||||
|
||||
export interface Payee {
|
||||
name: string;
|
||||
}
|
||||
|
||||
export interface Account {
|
||||
name: string;
|
||||
number: string;
|
||||
}
|
||||
|
||||
export interface Tag {
|
||||
name: string;
|
||||
icon: string;
|
||||
description: string;
|
||||
}
|
||||
|
||||
export interface Transaction {
|
||||
payor: Payor;
|
||||
payee: Payee;
|
||||
amount: number;
|
||||
account: Account;
|
||||
tags: Tag[];
|
||||
occurred_at: Date;
|
||||
}
|
||||
|
||||
// -----------------------------
|
||||
// Metrics
|
||||
// -----------------------------
|
||||
|
||||
export interface ReportMetric {
|
||||
sum: number;
|
||||
count: number;
|
||||
average: number;
|
||||
transactions?: Transaction[];
|
||||
}
|
||||
|
||||
// -----------------------------
|
||||
// Period
|
||||
// -----------------------------
|
||||
|
||||
export interface ReportPeriod {
|
||||
start: Date;
|
||||
end: Date;
|
||||
|
||||
expenses: ReportMetric;
|
||||
incomes: ReportMetric;
|
||||
}
|
||||
|
||||
// -----------------------------
|
||||
// Group (bucket)
|
||||
// -----------------------------
|
||||
|
||||
export type GroupKey = {
|
||||
payee?: string[];
|
||||
tags?: string[];
|
||||
flow?: string[];
|
||||
};
|
||||
|
||||
export interface ReportBucket {
|
||||
group_key: GroupKey;
|
||||
|
||||
periods: {
|
||||
weekly?: ReportPeriod[];
|
||||
monthly?: ReportPeriod[];
|
||||
yearly?: ReportPeriod[];
|
||||
fyly?: ReportPeriod[];
|
||||
full?: ReportPeriod[];
|
||||
};
|
||||
}
|
||||
|
||||
// -----------------------------
|
||||
// Final Report
|
||||
// -----------------------------
|
||||
|
||||
export interface ReportData {
|
||||
periods: ("weekly" | "monthly" | "yearly" | "fyly" | "full")[];
|
||||
|
||||
rolling: boolean;
|
||||
report_date?: string;
|
||||
|
||||
group_by: ("payee" | "tags")[];
|
||||
|
||||
ignore_self: boolean;
|
||||
include_transactions: boolean;
|
||||
|
||||
buckets: ReportBucket[];
|
||||
}
|
||||
131
src/features/report/report.utils.ts
Normal file
131
src/features/report/report.utils.ts
Normal file
@@ -0,0 +1,131 @@
|
||||
import {
|
||||
ReportData,
|
||||
ReportPeriod
|
||||
} from "./report.models";
|
||||
|
||||
/* ---------- ID BUILDING ---------- */
|
||||
|
||||
function formatDate(d: Date): string {
|
||||
const y = d.getUTCFullYear();
|
||||
const m = String(d.getUTCMonth() + 1).padStart(2, "0");
|
||||
const day = String(d.getUTCDate()).padStart(2, "0");
|
||||
return `${y}-${m}-${day}`;
|
||||
}
|
||||
|
||||
function buildPeriodId(
|
||||
type: "weekly" | "monthly" | "yearly" | "fyly" | "full",
|
||||
start: Date,
|
||||
end: Date
|
||||
): string {
|
||||
const s = formatDate(start);
|
||||
const e = formatDate(end);
|
||||
|
||||
switch (type) {
|
||||
case "weekly":
|
||||
return `W:${s}_${e}`;
|
||||
case "monthly":
|
||||
return `M:${s}_${e}`;
|
||||
case "yearly":
|
||||
return `Y:${s}_${e}`;
|
||||
case "fyly":
|
||||
return `FY:${s}_${e}`;
|
||||
case "full":
|
||||
return `FULL:${s}_${e}`;
|
||||
default:
|
||||
return `${s}_${e}`;
|
||||
}
|
||||
}
|
||||
|
||||
/* ---------- LABEL BUILDING ---------- */
|
||||
|
||||
const dayFmt = new Intl.DateTimeFormat("en-GB", {
|
||||
day: "numeric",
|
||||
month: "short",
|
||||
timeZone: "UTC",
|
||||
});
|
||||
|
||||
const monthDayFmt = new Intl.DateTimeFormat("en-GB", {
|
||||
month: "short",
|
||||
day: "numeric",
|
||||
timeZone: "UTC",
|
||||
});
|
||||
|
||||
const monthFmt = new Intl.DateTimeFormat("en-GB", {
|
||||
month: "short",
|
||||
timeZone: "UTC",
|
||||
});
|
||||
|
||||
const yearFmt = new Intl.DateTimeFormat("en-GB", {
|
||||
year: "numeric",
|
||||
timeZone: "UTC",
|
||||
});
|
||||
|
||||
function sameMonth(a: Date, b: Date) {
|
||||
return (
|
||||
a.getUTCFullYear() === b.getUTCFullYear() &&
|
||||
a.getUTCMonth() === b.getUTCMonth()
|
||||
);
|
||||
}
|
||||
|
||||
function buildLabel(
|
||||
type: "weekly" | "monthly" | "yearly" | "fyly" | "full",
|
||||
start: Date,
|
||||
end: Date
|
||||
): string {
|
||||
switch (type) {
|
||||
case "weekly": {
|
||||
const sDay = start.getUTCDate();
|
||||
const m = monthFmt.format(start);
|
||||
return `${sDay} ${m}`;
|
||||
}
|
||||
|
||||
case "monthly":
|
||||
return `${monthFmt.format(start)} ${yearFmt.format(start)}`;
|
||||
|
||||
case "yearly":
|
||||
return yearFmt.format(start);
|
||||
|
||||
case "fyly": {
|
||||
const startY = start.getUTCFullYear();
|
||||
const endY = end.getUTCFullYear();
|
||||
return `FY ${startY}–${String(endY).slice(-2)}`;
|
||||
}
|
||||
|
||||
default:
|
||||
return `${monthDayFmt.format(start)} - ${monthDayFmt.format(end)}`;
|
||||
}
|
||||
}
|
||||
|
||||
/* ---------- MAIN ---------- */
|
||||
|
||||
function decoratePeriods(
|
||||
type: "weekly" | "monthly" | "yearly" | "fyly" | "full",
|
||||
periods: ReportPeriod[]
|
||||
): (ReportPeriod & { id: string; label: string })[] {
|
||||
return periods.map((p) => ({
|
||||
...p,
|
||||
id: buildPeriodId(type, new Date(p.start + "Z"), new Date(p.end + "Z")),
|
||||
label: buildLabel(type, new Date(p.start + "Z"), new Date(p.end + "Z")),
|
||||
}));
|
||||
}
|
||||
|
||||
export function prepareReport(reportData: ReportData): ReportData {
|
||||
return {
|
||||
...reportData,
|
||||
buckets: reportData.buckets.map((bucket) => {
|
||||
const newPeriods: typeof bucket.periods = {};
|
||||
|
||||
for (const type of reportData.periods) {
|
||||
const arr = bucket.periods[type];
|
||||
if (arr) {
|
||||
newPeriods[type] = decoratePeriods(type, arr);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
...bucket,
|
||||
periods: newPeriods,
|
||||
};
|
||||
}),
|
||||
};
|
||||
}
|
||||
20
src/features/report/useReport.ts
Normal file
20
src/features/report/useReport.ts
Normal file
@@ -0,0 +1,20 @@
|
||||
import { useResourceByName } from "../../../react-openapi";
|
||||
|
||||
export interface ReportParams {
|
||||
periods?: ("weekly" | "monthly" | "yearly" | "fyly" | "full")[];
|
||||
rolling?: boolean;
|
||||
report_date?: string;
|
||||
group_by?: ("payee" | "tags")[];
|
||||
ignore_self?: boolean;
|
||||
include_transactions?: boolean;
|
||||
}
|
||||
|
||||
export function useReport(params: ReportParams) {
|
||||
const { useList } = useResourceByName("reports");
|
||||
|
||||
return useList({
|
||||
...params,
|
||||
periods: params.periods,
|
||||
group_by: params.group_by,
|
||||
});
|
||||
}
|
||||
60
src/main.jsx
60
src/main.jsx
@@ -1,22 +1,72 @@
|
||||
import * as React from 'react';
|
||||
import { createRoot } from 'react-dom/client';
|
||||
import { BrowserRouter, Routes, Route } from "react-router-dom";
|
||||
import {
|
||||
BrowserRouter,
|
||||
Routes,
|
||||
Route
|
||||
} from "react-router-dom";
|
||||
import {
|
||||
Box,
|
||||
CssBaseline,
|
||||
Toolbar
|
||||
} from "@mui/material";
|
||||
import Home from './Home';
|
||||
import Admin from '../react-openapi/Admin';
|
||||
import Dashboard from './Dashboard';
|
||||
import { Admin, AppProvider } from '../react-openapi';
|
||||
import { configuration, profileConfiguration } from './openapi-config';
|
||||
import { Buffer } from 'buffer';
|
||||
import process from 'process';
|
||||
import { AuthProvider } from "../react-auth";
|
||||
import Header from './Header';
|
||||
import Footer from './Footer';
|
||||
import AppTheme from './AppTheme';
|
||||
|
||||
window.Buffer = Buffer;
|
||||
window.process = process;
|
||||
|
||||
const rootElement = document.getElementById('root');
|
||||
const root = createRoot(rootElement);
|
||||
|
||||
const AUTH_BASE = import.meta.env.VITE_AUTH_BASE_URL;
|
||||
|
||||
const routerMapping = [
|
||||
{ path: "/", component: Home, headerTitle: "Home" },
|
||||
{ path: "/home", component: Home, headerTitle: "Home" },
|
||||
{ path: "/dashboard", component: Dashboard, headerTitle: "Dashboard" },
|
||||
{ path: "/admin/*", component: Admin, headerTitle: "Admin" },
|
||||
];
|
||||
|
||||
root.render(
|
||||
<AppProvider resourceOverrides={configuration} profileConfig={profileConfiguration}>
|
||||
<BrowserRouter>
|
||||
<AuthProvider authBaseUrl={AUTH_BASE}>
|
||||
<AppTheme>
|
||||
<CssBaseline enableColorScheme />
|
||||
<Header routerMapping={routerMapping} />
|
||||
|
||||
<Box sx={{ pb: 8 }}>
|
||||
<Toolbar />
|
||||
|
||||
<Routes>
|
||||
<Route path="/" element={<Home />} />
|
||||
<Route path="/home" element={<Home />} />
|
||||
<Route path="/admin/*" element={<Admin basePath="/admin" />} />
|
||||
{routerMapping.map(({ path, component: Component }) => (
|
||||
<Route
|
||||
key={path}
|
||||
path={path}
|
||||
element={
|
||||
path.startsWith("/admin") ? (
|
||||
<Component basePath="/admin" />
|
||||
) : (
|
||||
<Component />
|
||||
)
|
||||
}
|
||||
/>
|
||||
))}
|
||||
</Routes>
|
||||
</Box>
|
||||
|
||||
<Footer />
|
||||
</AppTheme>
|
||||
</AuthProvider>
|
||||
</BrowserRouter>
|
||||
</AppProvider>
|
||||
);
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { ResourceOverride } from "./types/overrides";
|
||||
import { ResourceOverride } from "../react-openapi/types/overrides";
|
||||
|
||||
export const configuration: Record<string, ResourceOverride> = {
|
||||
expenses: {
|
||||
@@ -40,6 +40,9 @@ export const configuration: Record<string, ResourceOverride> = {
|
||||
},
|
||||
pagination: true,
|
||||
},
|
||||
reports: {
|
||||
hidden: true
|
||||
}
|
||||
};
|
||||
|
||||
export const profileConfiguration = {
|
||||
|
||||
Reference in New Issue
Block a user