7 Commits
0.1.0 ... 0.1.1

Author SHA1 Message Date
5fb810bd5a common themeConfig.ts 2026-05-23 01:47:38 +05:30
2a12e33e22 Dashboard.view.tsx to handle rendering and Dashboard.tsx to handle state 2026-05-19 18:51:59 +05:30
7dd685ae49 remove unused 2026-05-19 12:55:41 +05:30
86bb9ab222 default light 2026-05-19 12:55:33 +05:30
de59ef1f7d AppTheme.tsx fixes 2026-05-19 12:45:58 +05:30
16d164b92a Dashboard Refactor (#5)
# Dashboard Refactor

## Overview

This merge request performs a major cleanup and architectural refactor of the dashboard component system.

The primary goals were:

* Consolidate dashboard state handling
* Standardize component contracts
* Remove duplicated transaction aggregation logic
* Simplify theming
* Eliminate unnecessary wrapper/view layers
* Improve maintainability and type safety

---

# Major Changes

## Dashboard Architecture Refactor

### Consolidated State API

Introduced a centralized `DashboardStateSetters` interface:

```ts
export interface DashboardStateSetters {
  setSelectedPeriodId: (id: DashboardSelectedPeriodId) => void;
  setSelectedGroupKey: (groupKey: GroupKey | null) => void;
  toggleFlow: () => void;
  togglePeriodType: () => void;
  toggleComparison: () => void;
}
```

This removes scattered prop drilling and standardizes dashboard interaction handling.

---

### Introduced Shared `ComponentProps`

All dashboard widgets now consume a unified contract:

```ts
export interface ComponentProps extends DashboardSection {
  reportData: ReportData;

  state: DashboardState;
  stateSetters: DashboardStateSetters;
  isFetching: boolean;

  colorScheme: {
    primary: string;
    light: string;
    text: string;
  };
}
```

Benefits:

* Consistent widget APIs
* Reduced repetitive prop definitions
* Easier extensibility
* Cleaner component composition

---

### Removed `Dashboard.view.tsx`

The view/container split was removed.

Dashboard rendering now lives directly inside:

```ts
Dashboard.tsx
```

Benefits:

* Reduced indirection
* Easier navigation
* Lower cognitive overhead
* Simpler state flow

---

## Dashboard Config Cleanup

Removed legacy `style.size` configuration from dashboard sections.

Before:

```ts
style: {
  size: 12,
}
```

Now:

```ts
{
  id: "items",
  title: "Recent Transactions",
  component: LatestItems,
}
```

This simplifies section configuration and removes unnecessary abstraction.

---

# Shared Transaction Utilities

## Added `extractFilteredTransactions`

Created a reusable transaction extraction helper:

```ts
extractFilteredTransactions(
  reportData,
  selectedPeriodId,
  selectedGroupKey
)
```

This centralizes:

* Period resolution
* Group filtering
* Tag filtering
* Payee filtering

Previously duplicated across:

* LatestItems
* TopTags
* TopPayees

---

## Added `aggregateTransactions`

Created a reusable aggregation utility:

```ts
aggregateTransactions(
  transactions,
  keyExtractor,
  limit
)
```

Benefits:

* Removes repeated Map aggregation logic
* Standardizes sorting and totals
* Simplifies adapters significantly

---

# HistoryChart Refactor

## Split Models vs Props

Separated:

* data models
* component props
* view props

into dedicated files.

New:

```txt
HistoryChart.models.ts
HistoryChart.props.ts
```

Benefits:

* Cleaner typing boundaries
* Better maintainability
* Reduced coupling

---

## Migrated to Shared Dashboard State

HistoryChart now consumes:

```ts
state
stateSetters
```

instead of individual props.

This aligns it with the new dashboard architecture.

---

# LatestItems Refactor

## Simplified Component Contract

Removed duplicated props:

* flow
* header
* accentColor
* selectedPeriodId
* selectedGroupKey

Now inherited from shared `ComponentProps`.

---

## Added Auto Reset on Flow Change

```ts
React.useEffect(() => {
  setVisibleCount(5);
}, [flow]);
```

Improves UX when switching inflow/outflow views.

---

# ProgressCard Refactor

## Removed `ProgressCard.tsx`

Deleted unnecessary wrapper component.

Rendering logic now lives directly in:

```txt
ProgressCard.view.tsx
```

---

## Introduced `ProgressCard.props.ts`

Separated props into dedicated interfaces:

```ts
ProgressCardProps
ProgressCardViewProps
```

---

## Reworked Styling System

Removed dependency on:

```ts
colorTheme
```

Now fully driven by:

```ts
colorScheme
```

Benefits:

* Consistent dashboard-wide theming
* Better dark mode behavior
* Reduced MUI palette coupling

---

## Improved Visual Consistency

Updated:

* borders
* shadows
* progress bar styling
* dark mode surfaces
* selection state styling

to use standardized dashboard colors.

---

# TopTags & TopPayees Refactor

## Removed Duplicated Aggregation Logic

Both adapters now use:

```ts
extractFilteredTransactions()
aggregateTransactions()
```

instead of maintaining separate filtering/aggregation implementations.

Benefits:

* Less code duplication
* Consistent behavior
* Easier future maintenance

---

## Migrated to Shared Component Props

Both components now consume:

```ts
ComponentProps
```

via:

```ts
ProgressCardProps
```

This aligns all dashboard widgets under the same architecture.

---

# Theme System Cleanup

## Consolidated AppTheme

Moved to:

```txt
src/shared-theme/AppTheme.tsx
```

and removed unused duplicate implementations.

---

## Added Explicit Color Mode Context

Introduced:

```ts
ColorModeContext
```

with:

* `mode`
* `setMode`
* `toggleColorMode`

This provides a cleaner foundation for future theme controls.

---

## Simplified Theme Creation

Replaced older MUI experimental color scheme setup with:

```ts
getDesignTokens(mode)
```

Benefits:

* Easier to reason about
* Cleaner light/dark handling
* Less framework complexity

---

## Added Global CssBaseline

```tsx
<CssBaseline />
```

is now applied centrally inside `AppTheme`.

---

# Type Safety Improvements

## Removed Optional Fields Where Invalid

Several previously optional fields are now required:

```ts
title: string
background: string
text: string
isFetching: boolean
style.palette
```

Benefits:

* Stronger guarantees
* Fewer runtime fallbacks
* Simpler rendering logic

---

# Cleanup Summary

## Removed

* `Dashboard.view.tsx`
* `ProgressCard.tsx`
* legacy prop duplication
* repeated transaction extraction logic
* repeated aggregation logic
* unused style configuration
* legacy theme configuration complexity

---

## Added

* centralized dashboard state setters
* reusable transaction helpers
* reusable aggregation helper
* unified component props
* dedicated prop definition files
* explicit color mode context
* consolidated theme provider

---

# Result

The dashboard system is now:

* significantly more maintainable
* easier to extend
* more type-safe
* less repetitive
* more consistent across widgets
* cleaner in terms of state ownership
* simpler to theme and customize

Reviewed-on: #5
Co-authored-by: Vishesh 'ironeagle' Bangotra <aetoskia@gmail.com>
Co-committed-by: Vishesh 'ironeagle' Bangotra <aetoskia@gmail.com>
2026-05-19 07:11:46 +00:00
8bea3d06f6 Dashboard Refactor: Flow-based Metrics + Unified Data Model (#4)
# Dashboard Refactor: Flow-based Metrics + Unified Data Model

## Summary

This MR transforms the dashboard into a **flow-driven, backend-powered analytics system** with a significantly cleaner architecture and improved UX.

## Overview

This MR introduces a **major refactor of the dashboard and report data model**, transitioning from separate `expense/income` handling to a unified **flow-based (`outflows` / `inflows`) system** backed by a single `metric` structure.

It simplifies data handling, improves UI consistency, and enables better extensibility for future analytics.

---

## Key Changes

### 1. Data Model Simplification

* Replaced:

  * `expenses` / `incomes`
* With:

  * `metric`

```ts
ReportPeriod {
  start: string;
  end: string;
  metric: {
    sum: number;
    count: number;
    transactions: Transaction[];
  }
}
```

* Eliminates duplication across logic paths
* Flow is now controlled at query level instead of data shape

---

### 2. Flow-based System (Core Change)

* Introduced:

  ```ts
  type DashboardFlow = "outflows" | "inflows";
  ```

* Replaced all references of:

  * `expense` → `outflows`
  * `income` → `inflows`

* Flow is now:

  * Controlled at **Dashboard level**
  * Propagated to **API query (`useReport`)**

---

### 3. API Changes

#### `useReport`

* Removed legacy params:

  * `group_by`, `rolling`, `include_transactions`, etc.

* New structure:

```ts
useReport({
  periods: ["daily", "weekly", "monthly", "all"],
  flow,
  payee,
  tags
})
```

* Backend now handles:

  * Flow filtering
  * Aggregation

---

### 4. Period System Update

* Removed:

  * yearly, fyly, full

* Added:

  * `daily`
  * `all`

```ts
type PeriodType = "daily" | "weekly" | "monthly" | "all";
```

* Updated helpers:

  * `periodIdToKey`
  * `buildPeriodId`
  * `buildLabel`

---

### 5. React Query UX Improvement

* Added:

```ts
placeholderData: keepPreviousData
```

* Prevents UI flicker on filter/flow changes
* Enables smooth transitions

---

### 6. Dashboard State Refactor

#### Before

```ts
mode: "expense" | "income"
```

#### After

```ts
flow: "outflows" | "inflows"
```

* Introduced `onFlowChange` callback
* Lifted flow state to parent (`Dashboard.tsx`)
* Flow change triggers API refetch

---

### 7. UI Improvements

#### Flow Toggle

* Replaced mode toggle with:

  * Outflows / Inflows switch

#### Loading State Handling

* Added `isFetching` across components
* UI behavior during fetch:

  * Reduced opacity
  * Disabled interactions

#### Drill-down UX

* Added:

  * "Clear Drill-down" button

---

### 8. New Components

#### TopPayees

* New analytics card

* Shows top payees based on:

  * Selected period
  * Drill-down filters

* Supports:

  * Click-to-filter (drill-down)

---

### 9. Adapter Layer Simplification

#### Removed mode branching everywhere

Examples:

* `getAmount(period)` now uses:

  ```ts
  period.metric.sum
  ```

* `LatestItems`, `TopTags`, `HistoryChart`:

  * No longer split logic by expense/income
  * Work on unified transaction stream

---

### 10. GroupKey Generalization

#### Before

```ts
{
  payee?: string[];
  tags?: string[];
}
```

#### After

```ts
{
  [dimension: string]: string[];
}
```

* Enables future dimensions without refactor

---

## Behavioral Changes

* Flow selection now **controls backend query**
* All components consume **filtered data only**
* No client-side filtering for expense/income

---

## Benefits

* Single source of truth (`metric`)
* Cleaner adapters (no branching explosion)
* Easier feature additions (new dimensions, filters)
* Better UX (no flicker, smoother transitions)
* Backend-driven correctness

---

## Migration Notes

* Replace all `mode` usages with `flow`
* Update adapters to use `metric`
* Remove assumptions about:

  * `expenses`
  * `incomes`
* Ensure API supports:

  * `flow`
  * new period types

---

## Future Scope

* Add more dimensions (account, category hierarchy)
* Multi-flow comparison (inflows vs outflows together)
* Snapshot-based caching (already partially supported)

---

## Testing Notes

Verify:

* Flow toggle updates API calls
* No UI flicker on filter change
* Drill-down works across:

  * tags
  * payees
* Daily / Weekly / Monthly / All tabs behave correctly
* Loading state disables interaction properly

---

Reviewed-on: #4
Co-authored-by: Vishesh 'ironeagle' Bangotra <aetoskia@gmail.com>
Co-committed-by: Vishesh 'ironeagle' Bangotra <aetoskia@gmail.com>
2026-05-18 05:37:51 +00:00
44 changed files with 1074 additions and 971 deletions

View File

@@ -1,4 +1,4 @@
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { useQuery, useMutation, useQueryClient, keepPreviousData } from "@tanstack/react-query";
import { api } from "../api/client";
import { ResourceConfig } from "../types/config";
import { ConfigContext } from "../providers/ConfigContext";
@@ -26,6 +26,7 @@ export function useResource<T = any>(config: ResourceConfig | undefined) {
};
},
enabled: !!endpoint,
placeholderData: keepPreviousData,
});
// --- READ ONE ---

View File

@@ -1,48 +0,0 @@
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>
);
}

View File

@@ -10,7 +10,14 @@ import {
Button
} from "@mui/material";
import ConfigurableDashboard from "./components/Dashboard";
import DashboardView from "./components/Dashboard";
import {
DashboardState,
DashboardStateSetters,
DashboardFlow,
} from "./components/Dashboard";
import { configuration } from "./dashboard-config";
import {
useReport,
@@ -18,6 +25,14 @@ import {
} from "./features/report";
export default function Dashboard() {
const [state, setState] = React.useState<DashboardState>({
flow: "outflows",
periodType: "rolling",
selectedPeriodId: null,
selectedGroupKey: null,
comparison: false,
});
const [appliedPayees, setAppliedPayees] = React.useState<string[]>([]);
const [appliedTags, setAppliedTags] = React.useState<string[]>([]);
@@ -28,10 +43,8 @@ export default function Dashboard() {
const [loadedTags, setLoadedTags] = React.useState<string[]>([]);
const report = useReport({
periods: ["weekly", "monthly", "full"],
rolling: true,
include_transactions: true,
group_by: ["tags"],
periods: ["daily", "weekly", "monthly", "all"],
flow: state.flow,
payee: appliedPayees.length > 0 ? appliedPayees : undefined,
tags: appliedTags.length > 0 ? appliedTags : undefined,
});
@@ -43,10 +56,7 @@ export default function Dashboard() {
report.data.data.buckets.forEach((b: any) => {
Object.values(b.periods).forEach((periodArray: any) => {
periodArray?.forEach((p: any) => {
p.expenses?.transactions?.forEach((t: any) => {
if (t.payee?.name) pSet.add(t.payee.name);
});
p.incomes?.transactions?.forEach((t: any) => {
p.metric?.transactions?.forEach((t: any) => {
if (t.payee?.name) pSet.add(t.payee.name);
});
});
@@ -60,10 +70,7 @@ export default function Dashboard() {
report.data.data.buckets.forEach((b: any) => {
Object.values(b.periods).forEach((periodArray: any) => {
periodArray?.forEach((p: any) => {
p.expenses?.transactions?.forEach((t: any) => {
t.tags?.forEach((tag: any) => tSet.add(tag.name || tag));
});
p.incomes?.transactions?.forEach((t: any) => {
p.metric?.transactions?.forEach((t: any) => {
t.tags?.forEach((tag: any) => tSet.add(tag.name || tag));
});
});
@@ -74,10 +81,124 @@ export default function Dashboard() {
}
}, [report.data?.data]);
const toggleFlow =
React.useCallback(() => {
setState((prev) => ({
...prev,
flow:
prev.flow ===
"outflows"
? "inflows"
: "outflows",
selectedGroupKey:
null,
selectedPeriodId:
null,
}));
}, []);
const setFlow =
React.useCallback(
(
flow: DashboardFlow
) => {
setState((prev) => ({
...prev,
flow,
selectedGroupKey:
null,
selectedPeriodId:
null,
}));
},
[]
);
const togglePeriodType =
React.useCallback(() => {
setState((prev) => ({
...prev,
periodType:
prev.periodType ===
"rolling"
? "calendar"
: "rolling",
}));
}, []);
const toggleComparison =
React.useCallback(() => {
setState((prev) => ({
...prev,
comparison:
!prev.comparison,
}));
}, []);
const setSelectedPeriodId =
React.useCallback(
(
selectedPeriodId: DashboardState["selectedPeriodId"]
) => {
setState((prev) => ({
...prev,
selectedPeriodId,
}));
},
[]
);
const setSelectedGroupKey =
React.useCallback(
(
selectedGroupKey: DashboardState["selectedGroupKey"]
) => {
setState((prev) => ({
...prev,
selectedGroupKey,
}));
},
[]
);
const stateSetters: DashboardStateSetters =
React.useMemo(
() => ({
toggleFlow,
setFlow,
togglePeriodType,
toggleComparison,
setSelectedPeriodId,
setSelectedGroupKey,
}),
[
toggleFlow,
setFlow,
togglePeriodType,
toggleComparison,
setSelectedPeriodId,
setSelectedGroupKey,
]
);
const isLoading = report.isLoading;
const error = report.error;
if (isLoading && !report.data) {
return (
<Box sx={{ display: "flex", justifyContent: "center", alignItems: "center", height: "60vh" }}>
@@ -144,23 +265,26 @@ export default function Dashboard() {
sx={{ '& .MuiOutlinedInput-root': { height: 'auto', minHeight: '2.5rem', py: 0.5 } }}
/>
</Box>
<Button
variant="contained"
<Button
variant="contained"
size="large"
onClick={() => {
setAppliedPayees(payeeInput);
setAppliedTags(tagsInput);
}}
disabled={isLoading}
sx={{ height: 40, borderRadius: 2 }} // Changed from 56 to 40 to match minHeight of inputs
sx={{ height: 40, borderRadius: 2 }}
>
Apply
</Button>
</Paper>
</Container>
<ConfigurableDashboard
<DashboardView
config={configuration}
data={data}
state={state}
stateSetters={stateSetters}
isFetching={report.isFetching}
/>
</Box>
);

View File

@@ -20,7 +20,7 @@ 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";
import { ColorModeContext } from "./shared-theme/AppTheme";
interface HeaderProps {
routerMapping: {

View File

@@ -1,10 +1,12 @@
import * as React from "react";
import { Box, Typography, Button, Container, Stack } from "@mui/material";
import { useTheme, alpha } from "@mui/material/styles";
import { useNavigate } from "react-router-dom";
import ArrowForwardIcon from "@mui/icons-material/ArrowForward";
export default function Home() {
const navigate = useNavigate();
const theme = useTheme();
return (
<Box
@@ -46,14 +48,13 @@ export default function Home() {
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)",
backgroundColor: (t) => alpha(t.palette.common.white, t.palette.mode === "dark" ? 0.04 : 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)"
boxShadow: (t) =>
t.palette.mode === "dark"
? "0 8px 32px 0 rgba(0, 0, 0, 0.5)"
: "0 8px 32px 0 rgba(31, 38, 135, 0.07)",
}}
>
@@ -94,7 +95,7 @@ export default function Home() {
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)",
boxShadow: (t) => `0 8px 20px ${alpha(t.palette.primary.main, 0.4)}`,
},
}}
>

View File

@@ -4,50 +4,58 @@ import {
GroupKey,
} from "../../features/report";
export type DashboardMode = "expense" | "income";
export type DashboardFlow = "outflows" | "inflows";
export type DashboardPeriodType = "rolling" | "calendar";
export type DashboardSelectedPeriodId = string | null;
export interface DashboardState {
mode: DashboardMode;
flow: DashboardFlow;
periodType: DashboardPeriodType;
selectedPeriodId: DashboardSelectedPeriodId;
selectedGroupKey: GroupKey | null;
comparison: boolean;
}
export interface DashboardStateSetters {
setSelectedPeriodId: (id: DashboardSelectedPeriodId) => void;
setSelectedGroupKey: (groupKey: GroupKey | null) => void;
toggleFlow: () => void;
togglePeriodType: () => void;
toggleComparison: () => void;
}
export interface DashboardSection {
id: string;
title?: string;
summary?: string;
title: string;
component: React.ComponentType<any>;
summary?: string;
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 {
export interface DashboardViewProps {
config: DashboardConfig;
data: ReportData;
state: DashboardState;
stateSetters: DashboardStateSetters;
isFetching: boolean;
}
export interface ColorScheme {
primary: string;
surface: string;
text: string;
}
export interface ComponentProps extends DashboardSection {
reportData: ReportData;
state: DashboardState;
stateSetters: DashboardStateSetters;
isFetching: boolean;
colorScheme: ColorScheme;
}

View File

@@ -1,55 +0,0 @@
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}
/>
);
}

View File

@@ -3,132 +3,98 @@ import {
Box,
Container,
Grid,
Typography,
ToggleButton,
ToggleButtonGroup
ToggleButtonGroup,
Button
} 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;
}
import { DashboardViewProps } from "./Dashboard.models";
export default function DashboardView({
config,
data,
state,
setState,
toggleMode,
togglePeriodType,
toggleComparison,
setSelectedPeriodId,
setSelectedGroupKey,
}: ViewProps) {
stateSetters,
isFetching,
}: DashboardViewProps) {
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;
const {
flow,
selectedGroupKey,
} = state;
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]);
const colorScheme = flow === "outflows" ? theme.palette.flows.outflows : theme.palette.flows.inflows;
return (
<Container
sx={{
mt: 4,
mb: 4,
background: `linear-gradient(180deg, ${colors.light} 0%, transparent 100%)`,
background: `linear-gradient(180deg, ${alpha(colorScheme.primary, theme.palette.mode === "dark" ? 0.06 : 0.04)} 0%, transparent 100%)`,
borderRadius: 4,
p: 2,
transition: 'background 0.3s ease'
transition: "background 0.3s ease",
}}
>
<Box sx={{ display: "flex", justifyContent: "center", mb: 3 }}>
<Box
sx={{
display: "flex",
flexDirection: "column",
alignItems: "center",
mb: 3,
}}
>
<ToggleButtonGroup
value={mode}
value={flow}
exclusive
onChange={toggleMode}
onChange={stateSetters.toggleFlow}
sx={{
borderRadius: 3,
overflow: "hidden",
"& .MuiToggleButton-root": {
px: 3,
textTransform: "none",
color: "text.secondary"
color: "text.secondary",
},
"&.Mui-selected": {
bgcolor: colors.primary,
bgcolor: colorScheme.primary,
color: "white",
borderColor: colors.primary
borderColor: colorScheme.primary,
},
}}
>
<ToggleButton value="expense">Expenses</ToggleButton>
<ToggleButton value="income">Income</ToggleButton>
<ToggleButton value="outflows">Outflows</ToggleButton>
<ToggleButton value="inflows">Inflows</ToggleButton>
</ToggleButtonGroup>
{selectedGroupKey && Object.keys(selectedGroupKey).length > 0 && (
<Button
size="small"
sx={{ mt: 1, textTransform: "none" }}
onClick={() => stateSetters.setSelectedGroupKey(null)}
>
Clear Drill-down
</Button>
)}
</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>
)}
<Grid key={section.id} size={12}>
<Component
{...section.settings}
header={section.title}
summary={section.summary}
{...section}
reportData={data}
title={section.title}
accentColor={colors.primary}
colorScheme={colors}
// State management
mode={mode}
state={state}
stateSetters={stateSetters}
isFetching={isFetching}
periodType={periodType}
comparison={comparison}
selectedPeriodId={selectedPeriodId}
selectedGroupKey={selectedGroupKey}
togglePeriodType={togglePeriodType}
toggleComparison={toggleComparison}
setSelectedPeriodId={setSelectedPeriodId}
setSelectedGroupKey={setSelectedGroupKey}
colorScheme={colorScheme}
/>
</Grid>
);

View File

@@ -1,2 +1,2 @@
export { default } from "./Dashboard";
export { default } from "./Dashboard.view";
export * from "./Dashboard.models";

View File

@@ -9,15 +9,14 @@ import { ChartDataPoint } from "./HistoryChart.models";
// ─── Tab → PeriodKey ─────────────────────────────────────────
const TAB_TO_KEY: Record<string, PeriodKey> = {
Daily: "daily",
Weekly: "weekly",
Monthly: "monthly",
Yearly: "yearly",
"Financial Year": "fyly",
"All Time": "full",
"All Time": "all",
};
export function tabToKey(tab: string): PeriodKey {
return TAB_TO_KEY[tab] ?? "full";
return TAB_TO_KEY[tab] ?? "all";
}
// ─── Comparison ──────────────────────────────────────────────
@@ -27,10 +26,9 @@ function attachComparison(
key: PeriodKey
): ChartDataPoint[] {
const getCompareIndex = (i: number) => {
if (key === "daily") return i - 7;
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;
};
@@ -56,7 +54,7 @@ function attachComparison(
export function buildChartData(
reportData: ReportData,
key: PeriodKey,
mode: "expense" | "income",
flow: "outflows" | "inflows",
comparison: boolean
): ChartDataPoint[] {
const merged = mergeBucketPeriods(reportData.buckets, key);
@@ -64,7 +62,7 @@ export function buildChartData(
let points: ChartDataPoint[] = merged.map((p) => ({
id: p.id,
label: p.label,
amount: getAmount(p, mode),
amount: getAmount(p),
}));
if (comparison) {

View File

@@ -1,10 +1,3 @@
import {
DashboardMode,
DashboardPeriodType,
DashboardSelectedPeriodId
} from "../Dashboard";
import { ReportData } from "../../features/report";
export interface _ChartDataPoint {
id: string;
label: string;
@@ -15,26 +8,3 @@ export interface _ChartDataPoint {
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;
}

View File

@@ -0,0 +1,21 @@
import * as React from "react";
import { ComponentProps } from "../Dashboard";
import { ChartDataPoint } from "./HistoryChart.models";
export interface HistoryChartProps extends ComponentProps {
settings: {
tabs: string[];
};
}
export interface HistoryChartViewProps 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;
}

View File

@@ -1,26 +1,31 @@
import * as React from "react";
import { HistoryChartProps } from "./HistoryChart.models";
import HistoryChartView from "./HistoryChart.view";
import { buildChartData, tabToKey } from "./HistoryChart.adapter";
import { HistoryChartProps } from "./HistoryChart.props";
export default function HistoryChart(props: HistoryChartProps) {
const {
tabs,
settings,
reportData,
mode,
comparison,
selectedPeriodId,
setSelectedPeriodId
state,
stateSetters,
isFetching,
} = props;
const { flow, comparison, selectedPeriodId } = state;
const { setSelectedPeriodId } = stateSetters;
const { tabs } = settings;
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]);
return buildChartData(reportData, activeDataKey, flow, comparison);
}, [reportData, activeDataKey, flow, comparison]);
const maxAmount =
currentData.length > 0
@@ -35,11 +40,10 @@ export default function HistoryChart(props: HistoryChartProps) {
: 1;
const visibleCountMap = {
daily: 7,
weekly: 6,
monthly: 4,
yearly: 4,
fyly: 4,
full: 4,
all: 4,
};
const visibleCount = visibleCountMap[activeDataKey] ?? 4;

View File

@@ -11,49 +11,34 @@ 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";
HistoryChartViewProps,
} from "./HistoryChart.props";
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({
title,
summary,
settings,
export default function HistoryChartView(props: ViewProps) {
const {
header,
summary,
tabs,
colorScheme,
state,
stateSetters,
isFetching,
mode,
periodType,
selectedPeriodId,
comparison,
colorScheme,
togglePeriodType,
setSelectedPeriodId,
toggleComparison,
activeTab,
setActiveTab,
currentData,
visibleData,
maxAmount,
visibleCount,
startIndex,
setStartIndex,
activeDataKey,
}: HistoryChartViewProps) {
activeTab,
setActiveTab,
currentData,
visibleData,
maxAmount,
visibleCount,
startIndex,
setStartIndex,
activeDataKey,
} = props;
const { flow, periodType, selectedPeriodId, comparison } = state;
const { togglePeriodType, setSelectedPeriodId, toggleComparison } = stateSetters;
const theme = useTheme();
const isDark = theme.palette.mode === "dark";
@@ -91,11 +76,14 @@ export default function HistoryChartView(props: ViewProps) {
boxShadow: "none",
border: "1px solid",
borderColor: "divider",
bgcolor: isDark ? "background.paper" : colorScheme.light,
bgcolor: isDark ? "background.paper" : colorScheme.surface,
opacity: isFetching ? 0.6 : 1,
transition: "opacity 0.3s ease",
pointerEvents: isFetching ? "none" : "auto",
}}
>
<Typography variant="h6" fontWeight={700} gutterBottom>
{header}
{title}
</Typography>
{summary && (
@@ -105,7 +93,7 @@ export default function HistoryChartView(props: ViewProps) {
)}
<ToggleButtonGroup value={activeTab} exclusive onChange={handleTabChange} fullWidth sx={{ mb: 4 }}>
{tabs.map((tab) => (
{settings.tabs.map((tab) => (
<ToggleButton key={tab} value={tab}>
{tab}
</ToggleButton>

View File

@@ -1,56 +1,21 @@
import { ReportData, Transaction, GroupKey } from "../../features/report";
import { ReportData, GroupKey } from "../../features/report";
import {
mergeBucketPeriods,
periodIdToKey,
formatCurrency,
filterBuckets,
extractFilteredTransactions,
} 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"
selectedPeriodId: string | null | undefined,
selectedGroupKey: GroupKey | null | undefined,
flow: "outflows" | "inflows"
): LatestItem[] {
const txns = extractTransactions(reportData, selectedPeriodId, selectedGroupKey, mode);
const txns = extractFilteredTransactions(reportData, selectedPeriodId, selectedGroupKey);
return txns
.filter((t) => (mode === "expense" ? t.amount < 0 : t.amount >= 0))
.sort(
(a, b) =>
new Date(b.occurred_at).getTime() -

View File

@@ -5,10 +5,3 @@ export interface LatestItem {
amount: string;
timeAgo: string;
}
export interface LatestItemsViewProps {
items: LatestItem[];
accentColor: string;
canExpand: boolean;
onExpand: () => void;
}

View File

@@ -0,0 +1,10 @@
import { ComponentProps } from "../Dashboard";
import { LatestItem } from "./LatestItems.models";
export interface LatestItemsProps extends ComponentProps {}
export interface LatestItemsViewProps extends LatestItemsProps {
items: LatestItem[];
canExpand: boolean;
onExpand: () => void;
}

View File

@@ -1,42 +1,38 @@
import * as React from "react";
import { ReportData, GroupKey } from "../../features/report";
import { buildLatestItems } from "./LatestItems.adapter";
import LatestItemsView from "./LatestItems.view";
import { LatestItemsProps } from "./LatestItems.props";
type Props = {
reportData: ReportData;
mode: "expense" | "income";
selectedPeriodId: string | null;
selectedGroupKey?: GroupKey | null;
accentColor: string;
};
export default function LatestItems(props: LatestItemsProps) {
const {
reportData,
state,
stateSetters,
isFetching,
} = props;
export default function LatestItems({
reportData,
mode,
selectedPeriodId,
selectedGroupKey = null,
accentColor,
}: Props) {
const { flow, selectedPeriodId, selectedGroupKey } = state;
const [visibleCount, setVisibleCount] = React.useState(5);
const allItems = React.useMemo(() => {
return buildLatestItems(reportData, selectedPeriodId, selectedGroupKey, mode);
}, [reportData, selectedPeriodId, selectedGroupKey, mode]);
// Reset count when flow changes to start clean
React.useEffect(() => {
setVisibleCount(5);
}, [flow]);
const hasSelection = Boolean(selectedPeriodId) || Boolean(selectedGroupKey);
const allItems = React.useMemo(() => {
return buildLatestItems(reportData, selectedPeriodId, selectedGroupKey, flow);
}, [reportData, selectedPeriodId, selectedGroupKey, flow]);
const visibleItems = React.useMemo(() => {
if (!hasSelection) return allItems.slice(0, 5);
return allItems.slice(0, visibleCount);
}, [allItems, hasSelection, visibleCount]);
}, [allItems, visibleCount]);
const canExpand = hasSelection && visibleCount < allItems.length;
const canExpand = visibleCount < allItems.length;
return (
<LatestItemsView
{...props}
items={visibleItems}
accentColor={accentColor}
canExpand={canExpand}
onExpand={() => setVisibleCount((prev) => prev + 5)}
/>

View File

@@ -9,20 +9,25 @@ import {
Box,
IconButton,
} from "@mui/material";
import { alpha } from "@mui/material/styles";
import ExpandMoreIcon from "@mui/icons-material/ExpandMore";
import { LatestItemsViewProps } from "./LatestItems.models";
import { LatestItemsViewProps } from "./LatestItems.props";
export default function LatestItemsView({
items,
accentColor,
title,
canExpand,
onExpand,
isFetching,
colorScheme,
}: LatestItemsViewProps) {
const accentColor = colorScheme?.primary || "";
return (
<Box sx={{ width: "100%", bgcolor: "background.paper", borderRadius: 4, p: 2 }}>
<Box sx={{ width: "100%", bgcolor: "background.paper", borderRadius: 4, p: 2, opacity: isFetching ? 0.6 : 1, transition: "opacity 0.3s ease", pointerEvents: isFetching ? "none" : "auto" }}>
<Box sx={{ mb: 2, px: 2 }}>
<Typography variant="h6" fontWeight="bold">
Recent Transactions
{title}
</Typography>
</Box>
@@ -42,7 +47,7 @@ export default function LatestItemsView({
<Avatar
variant="rounded"
sx={{
bgcolor: `${accentColor}22`,
bgcolor: alpha(accentColor, 0.13),
width: 48,
height: 48,
borderRadius: 3,

View File

@@ -1,10 +0,0 @@
export interface ProgressCardProps {
header: string;
summary?: string;
progressAmount: number;
totalAmount: number;
colorTheme?: "primary" | "secondary" | "error" | "info" | "success" | "warning";
compact?: boolean;
selected?: boolean;
onClick?: () => void;
}

View File

@@ -0,0 +1,14 @@
import { ComponentProps } from "../Dashboard";
export interface ProgressCardProps extends ComponentProps {
settings: {
compact: boolean;
};
}
export interface ProgressCardViewProps extends ProgressCardProps {
progressAmount: number;
totalAmount: number;
selected: boolean;
onClick: () => void;
}

View File

@@ -1,25 +0,0 @@
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}
/>
);
}

View File

@@ -8,91 +8,79 @@ import {
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;
}
import { getPercentage, formatCurrency } from "../report.helpers";
import { ProgressCardViewProps } from "./ProgressCard.props";
export default function ProgressCardView({
header,
colorTheme = "info",
percentage,
formattedProgress,
formattedTotal,
compact = false,
title,
settings,
isFetching,
colorScheme,
progressAmount,
totalAmount,
selected,
onClick,
}: ViewProps) {
}: ProgressCardViewProps) {
const theme = useTheme();
const isDark = theme.palette.mode === "dark";
const percentage = getPercentage(progressAmount, totalAmount);
const formattedProgress = formatCurrency(progressAmount);
const formattedTotal = formatCurrency(totalAmount);
return (
<Paper
elevation={compact ? 2 : 4}
elevation={settings.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",
p: settings.compact ? { xs: 2.5, md: 3 } : { xs: 3, md: 4 },
borderRadius: settings.compact ? 3 : 4,
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",
bgcolor: colorScheme.surface,
color: colorScheme.text,
display: "flex",
flexDirection: "column",
alignItems: compact ? "flex-start" : "center",
alignItems: settings.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;
},
border: selected
? `2px solid ${colorScheme.primary}`
: "1px solid",
borderColor: selected ? colorScheme.primary : "divider",
boxShadow: "none",
opacity: isFetching ? 0.6 : 1,
pointerEvents: isFetching ? "none" : "auto",
}}
>
<Typography
variant={compact ? "body2" : "subtitle1"}
fontWeight={700}
sx={{
opacity: 0.95,
mb: compact ? 1.5 : 2,
width: '100%',
overflow: 'hidden',
textOverflow: 'ellipsis',
whiteSpace: 'nowrap',
<Typography
variant={settings.compact ? "body2" : "subtitle1"}
fontWeight={700}
sx={{
opacity: 0.95,
mb: settings.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}
{title}
</Typography>
<Box sx={{ mb: compact ? 2 : 3, width: '100%' }}>
<Box sx={{ mb: settings.compact ? 2 : 3, width: "100%" }}>
<Typography
variant={compact ? "h5" : "h3"}
variant={settings.compact ? "h5" : "h3"}
fontWeight={900}
sx={{ mb: 0.5, lineHeight: 1.2, textShadow: isDark ? '0 2px 4px rgba(0,0,0,0.3)' : 'none' }}
sx={{
mb: 0.5,
lineHeight: 1.2,
}}
>
{formattedProgress}
</Typography>
@@ -100,38 +88,38 @@ export default function ProgressCardView({
<Divider
sx={{
my: 1,
borderColor: "rgba(255,255,255,0.25)",
borderColor: "divider",
width: "100%",
}}
/>
<Typography
variant={compact ? "caption" : "body2"}
variant={settings.compact ? "caption" : "body2"}
sx={{
opacity: 0.85,
fontWeight: 500,
display: "block",
color: "rgba(255,255,255,0.9)"
color: alpha(colorScheme.text, 0.85),
}}
>
of {formattedTotal}
</Typography>
</Box>
<Box sx={{ width: "100%", mt: 'auto' }}>
<Box sx={{ width: "100%", mt: "auto" }}>
<LinearProgress
variant="determinate"
value={percentage}
sx={{
height: compact ? 6 : 10,
height: settings.compact ? 6 : 10,
borderRadius: 5,
[`&.${linearProgressClasses.colorPrimary}`]: {
backgroundColor: "rgba(0, 0, 0, 0.25)",
backgroundColor: alpha(theme.palette.divider, 0.5),
},
[`& .${linearProgressClasses.bar}`]: {
borderRadius: 5,
backgroundColor: "#fff",
boxShadow: '0 0 8px rgba(255,255,255,0.4)'
backgroundColor: colorScheme.primary,
boxShadow: `0 0 8px ${alpha(colorScheme.primary, 0.4)}`,
},
}}
/>

View File

@@ -0,0 +1,31 @@
import { GroupKey, ReportData } from "../../features/report";
import {
extractFilteredTransactions,
aggregateTransactions,
} from "../report.helpers";
export interface PayeeItem {
name: string;
amount: number;
}
export function extractTopPayees(
reportData: ReportData,
flow: "outflows" | "inflows",
selectedPeriodId?: string | null,
selectedGroupKey?: GroupKey | null
): { items: PayeeItem[]; total: number } {
const txns = extractFilteredTransactions(reportData, selectedPeriodId, selectedGroupKey);
const { items, total } = aggregateTransactions(txns, (txn) => {
if (txn.payee && txn.payee.name) {
return [txn.payee.name];
}
return [];
});
return {
items,
total,
};
}

View File

@@ -0,0 +1,83 @@
import * as React from "react";
import { Box, Paper, Typography } from "@mui/material";
import ProgressCardView from "./ProgressCard.view";
import { extractTopPayees } from "./TopPayees.adapter";
import { ProgressCardProps } from "./ProgressCard.props";
export default function TopPayees(props: ProgressCardProps) {
const {
title,
reportData,
state,
stateSetters,
isFetching,
} = props
const { flow, selectedPeriodId, selectedGroupKey } = state;
const { setSelectedGroupKey } = stateSetters;
const { items, total } = React.useMemo(() => {
return extractTopPayees(reportData, flow, selectedPeriodId, selectedGroupKey);
}, [reportData, flow, selectedPeriodId, selectedGroupKey]);
return (
<Paper
sx={{
p: { xs: 2.5, sm: 4 },
borderRadius: 4,
width: "100%",
boxShadow: "none",
border: "1px solid",
borderColor: "divider",
bgcolor: "background.paper",
opacity: isFetching ? 0.6 : 1,
transition: "opacity 0.3s ease",
pointerEvents: isFetching ? "none" : "auto",
}}
>
<Typography variant="h6" fontWeight={700} gutterBottom>
{title}
</Typography>
<Box
sx={{
display: "grid",
gridTemplateColumns: {
xs: "1fr",
sm: "repeat(2, 1fr)",
md: "repeat(4, 1fr)",
},
gap: 2,
}}
>
{items.map((item) => {
const isSelected = !!selectedGroupKey?.payee?.includes(item.name);
return (
<ProgressCardView
{...props}
key={item.name}
title={item.name}
progressAmount={item.amount}
totalAmount={total}
selected={isSelected}
onClick={() => {
if (setSelectedGroupKey) {
let newKey = selectedGroupKey ? { ...selectedGroupKey } : {};
if (isSelected) {
delete newKey.payee;
} else {
newKey.payee = [item.name];
}
setSelectedGroupKey(Object.keys(newKey).length ? newKey : null);
}
}}
/>
);
})}
</Box>
</Paper>
);
}

View File

@@ -1,32 +1,9 @@
import { ReportData } from "../../features/report";
import { ReportData, GroupKey } from "../../features/report";
import {
getAmount,
DecoratedPeriod,
extractFilteredTransactions,
aggregateTransactions,
} 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;
@@ -34,41 +11,21 @@ export interface TagItem {
export function extractTopTags(
reportData: ReportData,
mode: "expense" | "income",
selectedPeriodId?: string | null
flow: "outflows" | "inflows",
selectedPeriodId?: string | null,
selectedGroupKey?: GroupKey | null
): { items: TagItem[]; total: number } {
const tagMap = new Map<string, number>();
const txns = extractFilteredTransactions(reportData, selectedPeriodId, selectedGroupKey);
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 { items, total } = aggregateTransactions(txns, (txn) => {
if (txn.tags && txn.tags.length > 0) {
return txn.tags.map((t) => (typeof t === "string" ? t : t.name));
}
}
return ["Untagged"];
});
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 };
return {
items: items.map((item) => ({ tag: item.name, amount: item.amount })),
total,
};
}

View File

@@ -1,61 +1,83 @@
import * as React from "react";
import { Box } from "@mui/material";
import { ReportData, GroupKey } from "../../features/report";
import ProgressCard from "./ProgressCard";
import { Box, Paper, Typography } from "@mui/material";
import ProgressCardView from "./ProgressCard.view";
import { extractTopTags } from "./TopTags.adapter";
import { ProgressCardProps } from "./ProgressCard.props";
type Props = {
reportData: ReportData;
mode: "expense" | "income";
selectedPeriodId?: string | null;
selectedGroupKey?: GroupKey | null;
setSelectedGroupKey?: (key: GroupKey | null) => void;
compact?: boolean;
};
export default function TopTags(props: ProgressCardProps) {
const {
title,
reportData,
state,
stateSetters,
isFetching,
} = props
const { flow, selectedPeriodId, selectedGroupKey } = state;
const { setSelectedGroupKey } = stateSetters;
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 extractTopTags(reportData, flow, selectedPeriodId, selectedGroupKey);
}, [reportData, flow, selectedPeriodId, selectedGroupKey]);
return (
<Box
<Paper
sx={{
display: "grid",
gridTemplateColumns: {
xs: "1fr",
sm: "repeat(2, 1fr)",
md: "repeat(4, 1fr)",
},
gap: 2,
p: { xs: 2.5, sm: 4 },
borderRadius: 4,
width: "100%",
boxShadow: "none",
border: "1px solid",
borderColor: "divider",
bgcolor: "background.paper",
opacity: isFetching ? 0.6 : 1,
transition: "opacity 0.3s ease",
pointerEvents: isFetching ? "none" : "auto",
}}
>
{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>
<Typography variant="h6" fontWeight={700} gutterBottom>
{title}
</Typography>
<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 (
<ProgressCardView
{...props}
key={item.tag}
title={item.tag}
progressAmount={item.amount}
totalAmount={total}
selected={isSelected}
onClick={() => {
if (setSelectedGroupKey) {
let newKey = selectedGroupKey ? { ...selectedGroupKey } : {};
if (isSelected) {
delete newKey.tags;
} else {
newKey.tags = [item.tag];
}
setSelectedGroupKey(Object.keys(newKey).length ? newKey : null);
}
}}
/>
);
})}
</Box>
</Paper>
);
}

View File

@@ -1,2 +1,2 @@
export { default } from "./ProgressCard";
export * from "./ProgressCard.models";
export { default } from "./ProgressCard.view";
export * from "./ProgressCard.props";

View File

@@ -2,11 +2,14 @@ import {
ReportPeriod,
ReportBucket,
GroupKey,
PeriodType,
ReportData,
Transaction,
} from "../features/report";
// ─── Types ────────────────────────────────────────────────────
export type PeriodKey = "weekly" | "monthly" | "yearly" | "fyly" | "full";
export type PeriodKey = PeriodType;
export type DecoratedPeriod = ReportPeriod & {
id: string;
@@ -16,11 +19,10 @@ export type DecoratedPeriod = ReportPeriod & {
// ─── Period helpers ───────────────────────────────────────────
const PREFIX_TO_KEY: Record<string, PeriodKey> = {
D: "daily",
W: "weekly",
M: "monthly",
Y: "yearly",
FY: "fyly",
FULL: "full",
ALL: "all",
};
/**
@@ -29,19 +31,16 @@ const PREFIX_TO_KEY: Record<string, PeriodKey> = {
*/
export function periodIdToKey(periodId: string): PeriodKey {
const prefix = periodId.split(":")[0];
return PREFIX_TO_KEY[prefix] ?? "full";
return PREFIX_TO_KEY[prefix] ?? "all";
}
// ─── Metric helpers ───────────────────────────────────────────
export function getAmount(
period: ReportPeriod,
mode: "expense" | "income"
): number {
return mode === "expense" ? period.expenses.sum : period.incomes.sum;
export function getAmount(period: ReportPeriod): number {
return period.metric.sum;
}
function mergeMetric(a: ReportPeriod["expenses"], b: ReportPeriod["expenses"]) {
function mergeMetric(a: ReportPeriod["metric"], b: ReportPeriod["metric"]) {
const sum = a.sum + b.sum;
const count = a.count + b.count;
@@ -78,14 +77,12 @@ export function mergeBucketPeriods(
if (!existing) {
map.set(p.id, {
...p,
expenses: { ...p.expenses },
incomes: { ...p.incomes },
metric: { ...p.metric },
});
} else {
map.set(p.id, {
...existing,
expenses: mergeMetric(existing.expenses, p.expenses),
incomes: mergeMetric(existing.incomes, p.incomes),
metric: mergeMetric(existing.metric, p.metric),
});
}
}
@@ -126,7 +123,7 @@ export function matchesGroupKey(
selected: GroupKey
): boolean {
for (const [dim, values] of Object.entries(selected)) {
const bucketValues = bucket.group_key[dim as keyof GroupKey];
const bucketValues = bucket.group_key[dim];
if (!bucketValues) return false;
if (!(values as string[]).every((v) => bucketValues.includes(v)))
return false;
@@ -145,3 +142,89 @@ export function filterBuckets(
if (!selectedGroupKey) return buckets;
return buckets.filter((b) => matchesGroupKey(b, selectedGroupKey));
}
export function extractFilteredTransactions(
reportData: ReportData,
selectedPeriodId: string | null | undefined,
selectedGroupKey: GroupKey | null | undefined
): Transaction[] {
let txns: Transaction[] = [];
if (selectedPeriodId) {
const key = periodIdToKey(selectedPeriodId);
const periods = mergeBucketPeriods(reportData.buckets, key);
const selected = periods.find((p) => p.id === selectedPeriodId);
txns = selected?.metric.transactions || [];
} else {
const periods = mergeBucketPeriods(reportData.buckets, "all");
if (periods.length > 0) {
const period = periods.reduce((latest, p) =>
new Date(p.start).getTime() > new Date(latest.start).getTime()
? p
: latest
, periods[0]);
txns = period?.metric.transactions || [];
}
}
if (selectedGroupKey) {
txns = txns.filter((txn) => {
let match = true;
if (selectedGroupKey.tags && selectedGroupKey.tags.length > 0) {
if (!txn.tags) {
match = false;
} else {
const txnTags = txn.tags.map((t: any) =>
typeof t === "string" ? t : t.name
);
if (
!selectedGroupKey.tags.every((selectedTag) =>
txnTags.includes(selectedTag)
)
) {
match = false;
}
}
}
if (match && selectedGroupKey.payee && selectedGroupKey.payee.length > 0) {
if (!txn.payee || !txn.payee.name) {
match = false;
} else {
if (!selectedGroupKey.payee.includes(txn.payee.name)) {
match = false;
}
}
}
return match;
});
}
return txns;
}
export function aggregateTransactions(
transactions: Transaction[],
keyExtractor: (txn: Transaction) => string[],
limit = 4
): { items: { name: string; amount: number }[]; total: number } {
const map = new Map<string, number>();
for (const txn of transactions) {
const keys = keyExtractor(txn);
for (const key of keys) {
map.set(key, (map.get(key) || 0) + txn.amount);
}
}
const items = Array.from(map.entries()).map(([name, amount]) => ({
name,
amount,
}));
items.sort((a, b) => b.amount - a.amount);
const top = items.slice(0, limit);
const total = top.reduce((sum, item) => sum + item.amount, 0);
return { items: top, total };
}

View File

@@ -2,6 +2,7 @@ import HistoryChart from "./components/HistoryChart";
import LatestItems from "./components/LatestItems";
import { DashboardConfig } from "./components/Dashboard";
import TopTags from "./components/ProgressCard/TopTags";
import TopPayees from "./components/ProgressCard/TopPayees";
export const configuration: DashboardConfig = {
sections: [
@@ -12,10 +13,6 @@ export const configuration: DashboardConfig = {
component: HistoryChart,
settings: {
tabs: ["Weekly", "Monthly"],
// tabs: ["Weekly", "Monthly", "Yearly", "Financial Year", "All Time"],
},
style: {
size: 12,
},
},
{
@@ -25,44 +22,19 @@ export const configuration: DashboardConfig = {
settings: {
compact: true,
},
style: {
size: 12,
},
{
id: "top-payees",
title: 'Top Payees',
component: TopPayees,
settings: {
compact: true,
},
},
{
id: "items",
title: 'Recent Transactions',
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"
}
}
}
}
};

View File

@@ -6,7 +6,9 @@ export type {
ReportData,
ReportBucket,
ReportPeriod,
ReportQuery,
GroupKey,
PeriodType,
} from './report.models'
export {
prepareReport

View File

@@ -1,29 +1,40 @@
export interface Payor {
id?: string;
name: string;
username: string;
email: string;
}
export interface Payee {
type: "merchant" | "person" | "transfer" | "other";
name: string;
}
export interface Account {
id: string;
name: string;
number: string;
type: "cash" | "bank" | "credit_card" | "wallet" | "other";
currency: string;
is_active?: boolean;
}
export interface Tag {
id: string;
name: string;
icon: string;
description: string;
parent_id?: string | null;
}
export interface Transaction {
id: string;
payor: Payor;
payee: Payee;
amount: number;
account: Account;
tags: Tag[];
occurred_at: Date;
occurred_at: string;
created_at: string;
}
// -----------------------------
@@ -41,12 +52,12 @@ export interface ReportMetric {
// Period
// -----------------------------
export interface ReportPeriod {
start: Date;
end: Date;
export type PeriodType = "daily" | "weekly" | "monthly" | "all";
expenses: ReportMetric;
incomes: ReportMetric;
export interface ReportPeriod {
start: string;
end: string;
metric: ReportMetric;
}
// -----------------------------
@@ -54,46 +65,48 @@ export interface ReportPeriod {
// -----------------------------
export type GroupKey = {
payee?: string[];
tags?: string[];
flow?: string[];
[dimension: string]: string[];
};
export interface ReportBucket {
group_key: GroupKey;
periods: {
daily?: ReportPeriod[];
weekly?: ReportPeriod[];
monthly?: ReportPeriod[];
yearly?: ReportPeriod[];
fyly?: ReportPeriod[];
full?: ReportPeriod[];
all?: ReportPeriod[];
};
}
// -----------------------------
// Report Query
// -----------------------------
export interface ReportQuery {
accounts?: string[] | null;
ignore_self?: boolean | null;
start_date?: string | null;
end_date?: string | null;
min_amount?: number | null;
max_amount?: number | null;
}
// -----------------------------
// Final Report
// -----------------------------
export interface ReportData {
periods: ("weekly" | "monthly" | "yearly" | "fyly" | "full")[];
snapshot_id?: string | null;
rolling: boolean;
report_date?: string;
flow?: "inflows" | "outflows" | null;
group_by: ("payee" | "tags")[];
periods: PeriodType[];
ignore_self: boolean;
include_transactions: boolean;
start_date?: string | null;
end_date?: string | null;
flow?: "expense" | "income" | null;
payee?: string[] | null;
account?: string[] | null;
tags?: string[] | null;
min_amount?: number | null;
max_amount?: number | null;
payee?: string[] | null;
buckets: ReportBucket[];
query: ReportQuery;
}

View File

@@ -1,6 +1,7 @@
import {
ReportData,
ReportPeriod
ReportPeriod,
PeriodType,
} from "./report.models";
/* ---------- ID BUILDING ---------- */
@@ -13,7 +14,7 @@ function formatDate(d: Date): string {
}
function buildPeriodId(
type: "weekly" | "monthly" | "yearly" | "fyly" | "full",
type: PeriodType,
start: Date,
end: Date
): string {
@@ -21,16 +22,14 @@ function buildPeriodId(
const e = formatDate(end);
switch (type) {
case "daily":
return `D:${s}_${e}`;
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}`;
case "all":
return `ALL:${s}_${e}`;
default:
return `${s}_${e}`;
}
@@ -60,19 +59,15 @@ const yearFmt = new Intl.DateTimeFormat("en-GB", {
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",
type: PeriodType,
start: Date,
end: Date
): string {
switch (type) {
case "daily":
return dayFmt.format(start);
case "weekly": {
const sDay = start.getUTCDate();
const m = monthFmt.format(start);
@@ -82,15 +77,6 @@ function buildLabel(
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)}`;
}
@@ -99,7 +85,7 @@ function buildLabel(
/* ---------- MAIN ---------- */
function decoratePeriods(
type: "weekly" | "monthly" | "yearly" | "fyly" | "full",
type: PeriodType,
periods: ReportPeriod[]
): (ReportPeriod & { id: string; label: string })[] {
return periods.map((p) => ({

View File

@@ -1,20 +1,11 @@
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;
start_date?: string;
end_date?: string;
flow?: "expense" | "income";
snapshot_id?: string;
periods?: ("daily" | "weekly" | "monthly" | "all")[];
flow?: "inflows" | "outflows";
payee?: string[];
account?: string[];
tags?: string[];
min_amount?: number;
max_amount?: number;
}
export function useReport(params: ReportParams) {
@@ -23,6 +14,5 @@ export function useReport(params: ReportParams) {
return useList({
...params,
periods: params.periods,
group_by: params.group_by,
});
}

View File

@@ -19,7 +19,7 @@ import process from 'process';
import { AuthProvider } from "../react-auth";
import Header from './Header';
import Footer from './Footer';
import AppTheme from './AppTheme';
import AppTheme from './shared-theme/AppTheme';
window.Buffer = Buffer;
window.process = process;

View File

@@ -1,53 +1,103 @@
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';
import * as React from "react";
import {
ThemeProvider,
createTheme,
CssBaseline,
Box,
} from "@mui/material";
interface AppThemeProps {
import { getDesignTokens } from "./themePrimitives";
import { getSemanticColors } from "./themeConfig";
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";
export type ColorMode = "light" | "dark";
type ColorModeContextValue = {
mode: ColorMode;
setMode: (mode: ColorMode) => void;
toggleColorMode: () => void;
};
export const ColorModeContext =
React.createContext<ColorModeContextValue>({
mode: "light",
setMode: () => {},
toggleColorMode: () => {},
});
type AppThemeProps = {
children: React.ReactNode;
/**
* This is for the docs site. You can ignore it or remove it.
*/
disableCustomTheme?: boolean;
themeComponents?: ThemeOptions['components'];
}
defaultMode?: ColorMode;
};
export default function AppTheme({
children,
defaultMode = "light",
}: AppThemeProps) {
const [mode, setMode] =
React.useState<ColorMode>(defaultMode);
const toggleColorMode = React.useCallback(() => {
setMode((prev) =>
prev === "light" ? "dark" : "light"
);
}, []);
const contextValue = React.useMemo(
() => ({
mode,
setMode,
toggleColorMode,
}),
[mode, toggleColorMode]
);
const semantic = React.useMemo(
() => getSemanticColors(mode),
[mode]
);
const theme = React.useMemo(
() =>
createTheme({
...getDesignTokens(mode),
semantic,
components: {
...inputsCustomizations,
...dataDisplayCustomizations,
...feedbackCustomizations,
...navigationCustomizations,
...surfacesCustomizations,
},
}),
[mode, semantic]
);
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>
<ColorModeContext.Provider value={contextValue}>
<ThemeProvider theme={theme}>
<CssBaseline />
<Box
sx={{
"--bg-page": semantic.surface.page,
"--bg-card": semantic.surface.card,
"--bg-elevated": semantic.surface.elevated,
"--border-default": semantic.border.default,
"--border-subtle": semantic.border.subtle,
"--text-primary": semantic.text.primary,
"--text-secondary": semantic.text.secondary,
"--text-muted": semantic.text.muted,
}}
>
{children}
</Box>
</ThemeProvider>
</ColorModeContext.Provider>
);
}

View File

@@ -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>
);
}

View File

@@ -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>
);
}

View File

@@ -14,8 +14,8 @@ export const feedbackCustomizations: Components<Theme> = {
color: orange[500],
},
...theme.applyStyles('dark', {
backgroundColor: `${alpha(orange[900], 0.5)}`,
border: `1px solid ${alpha(orange[800], 0.5)}`,
backgroundColor: alpha(orange[900], 0.35),
border: `1px solid ${alpha(orange[800], 0.3)}`,
}),
}),
},

View File

@@ -125,15 +125,15 @@ export const inputsCustomizations: Components<Theme> = {
backgroundColor: gray[200],
},
...theme.applyStyles('dark', {
backgroundColor: gray[800],
borderColor: gray[700],
backgroundColor: 'hsla(0, 0%, 100%, 0.06)',
borderColor: (theme.vars || theme).palette.divider,
'&:hover': {
backgroundColor: gray[900],
borderColor: gray[600],
backgroundColor: 'hsla(0, 0%, 100%, 0.1)',
borderColor: 'hsla(0, 0%, 100%, 0.15)',
},
'&:active': {
backgroundColor: gray[900],
backgroundColor: 'hsla(0, 0%, 100%, 0.1)',
},
}),
},
@@ -183,12 +183,12 @@ export const inputsCustomizations: Components<Theme> = {
backgroundColor: gray[200],
},
...theme.applyStyles('dark', {
color: gray[50],
color: 'hsl(0, 0%, 92%)',
'&:hover': {
backgroundColor: gray[700],
backgroundColor: 'hsla(0, 0%, 100%, 0.08)',
},
'&:active': {
backgroundColor: alpha(gray[700], 0.7),
backgroundColor: 'hsla(0, 0%, 100%, 0.12)',
},
}),
},
@@ -241,14 +241,14 @@ export const inputsCustomizations: Components<Theme> = {
backgroundColor: gray[200],
},
...theme.applyStyles('dark', {
backgroundColor: gray[800],
borderColor: gray[700],
backgroundColor: 'hsla(0, 0%, 100%, 0.06)',
borderColor: (theme.vars || theme).palette.divider,
'&:hover': {
backgroundColor: gray[900],
borderColor: gray[600],
backgroundColor: 'hsla(0, 0%, 100%, 0.1)',
borderColor: 'hsla(0, 0%, 100%, 0.15)',
},
'&:active': {
backgroundColor: gray[900],
backgroundColor: 'hsla(0, 0%, 100%, 0.1)',
},
}),
variants: [
@@ -288,7 +288,7 @@ export const inputsCustomizations: Components<Theme> = {
[`& .${toggleButtonGroupClasses.selected}`]: {
color: '#fff',
},
boxShadow: `0 4px 16px ${alpha(brand[700], 0.5)}`,
boxShadow: `0 2px 8px ${alpha(brand[700], 0.3)}`,
}),
}),
},
@@ -302,7 +302,7 @@ export const inputsCustomizations: Components<Theme> = {
fontWeight: 500,
...theme.applyStyles('dark', {
color: gray[400],
boxShadow: '0 4px 16px rgba(0, 0, 0, 0.5)',
boxShadow: '0 2px 8px rgba(0, 0, 0, 0.25)',
[`&.${toggleButtonClasses.selected}`]: {
color: brand[300],
},

View File

@@ -49,9 +49,8 @@ export const navigationCustomizations: Components<Theme> = {
},
},
...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',
background: (theme.vars || theme).palette.background.paper,
boxShadow: '0 4px 16px rgba(0, 0, 0, 0.4), 0 8px 24px rgba(0, 0, 0, 0.3)',
}),
}),
},
@@ -84,17 +83,17 @@ export const navigationCustomizations: Components<Theme> = {
...theme.applyStyles('dark', {
borderRadius: (theme.vars || theme).shape.borderRadius,
borderColor: gray[700],
borderColor: (theme.vars || theme).palette.divider,
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)`,
boxShadow: 'inset 0 1px 0 hsla(0, 0%, 100%, 0.05)',
'&:hover': {
borderColor: alpha(gray[700], 0.7),
borderColor: 'hsla(0, 0%, 100%, 0.15)',
backgroundColor: (theme.vars || theme).palette.background.paper,
boxShadow: 'none',
},
[`&.${selectClasses.focused}`]: {
outlineOffset: 0,
borderColor: gray[900],
borderColor: 'hsl(210, 55%, 55%)',
},
'&:before, &:after': {
display: 'none',
@@ -108,7 +107,7 @@ export const navigationCustomizations: Components<Theme> = {
display: 'flex',
alignItems: 'center',
'&:focus-visible': {
backgroundColor: gray[900],
backgroundColor: (theme.vars || theme).palette.background.default,
},
}),
}),
@@ -151,6 +150,7 @@ export const navigationCustomizations: Components<Theme> = {
styleOverrides: {
paper: ({ theme }) => ({
backgroundColor: (theme.vars || theme).palette.background.default,
borderRight: `1px solid ${(theme.vars || theme).palette.divider}`,
}),
},
},
@@ -204,8 +204,8 @@ export const navigationCustomizations: Components<Theme> = {
...theme.applyStyles('dark', {
':hover': {
color: (theme.vars || theme).palette.text.primary,
backgroundColor: gray[800],
borderColor: gray[700],
backgroundColor: alpha((theme.vars || theme).palette.common.white, 0.08),
borderColor: (theme.vars || theme).palette.divider,
},
[`&.${tabClasses.selected}`]: {
color: '#fff',

View File

@@ -40,7 +40,7 @@ export const surfacesCustomizations: Components<Theme> = {
'&:hover': { backgroundColor: gray[50] },
'&:focus-visible': { backgroundColor: 'transparent' },
...theme.applyStyles('dark', {
'&:hover': { backgroundColor: gray[800] },
'&:hover': { backgroundColor: alpha(theme.palette.common.white, 0.06) },
}),
}),
},
@@ -67,7 +67,7 @@ export const surfacesCustomizations: Components<Theme> = {
border: `1px solid ${(theme.vars || theme).palette.divider}`,
boxShadow: 'none',
...theme.applyStyles('dark', {
backgroundColor: gray[800],
backgroundColor: (theme.vars || theme).palette.background.paper,
}),
variants: [
{
@@ -79,7 +79,7 @@ export const surfacesCustomizations: Components<Theme> = {
boxShadow: 'none',
background: 'hsl(0, 0%, 100%)',
...theme.applyStyles('dark', {
background: alpha(gray[900], 0.4),
background: alpha((theme.vars || theme).palette.background.paper, 0.6),
}),
},
},

View File

@@ -0,0 +1,72 @@
import { gray } from "./themePrimitives";
import { alpha } from "@mui/material/styles";
declare module "@mui/material/styles" {
interface Theme {
semantic: SemanticColors;
}
interface ThemeOptions {
semantic?: SemanticColors;
}
}
export type SemanticColorMode = "light" | "dark";
export interface SemanticColors {
surface: {
page: string;
card: string;
elevated: string;
};
border: {
default: string;
subtle: string;
};
text: {
primary: string;
secondary: string;
muted: string;
};
}
const darkBg = 'hsl(0, 0%, 9%)';
const darkPaper = 'hsl(0, 0%, 14%)';
const darkElevated = 'hsl(0, 0%, 19%)';
export function getSemanticColors(mode: SemanticColorMode): SemanticColors {
if (mode === "dark") {
return {
surface: {
page: darkBg,
card: darkPaper,
elevated: darkElevated,
},
border: {
default: 'hsla(0, 0%, 100%, 0.08)',
subtle: 'hsla(0, 0%, 100%, 0.04)',
},
text: {
primary: 'hsl(0, 0%, 92%)',
secondary: 'hsl(0, 0%, 60%)',
muted: 'hsl(0, 0%, 45%)',
},
};
}
return {
surface: {
page: "hsl(0, 0%, 99%)",
card: "hsl(220, 35%, 97%)",
elevated: gray[100],
},
border: {
default: alpha(gray[300], 0.4),
subtle: alpha(gray[200], 0.3),
},
text: {
primary: gray[800],
secondary: gray[600],
muted: gray[500],
},
};
}

View File

@@ -23,6 +23,10 @@ declare module '@mui/material/styles' {
interface Palette {
baseShadow: string;
flows: {
outflows: { primary: string; surface: string; text: string };
inflows: { primary: string; surface: string; text: string };
};
}
}
@@ -52,7 +56,9 @@ export const gray = {
500: 'hsl(220, 20%, 42%)',
600: 'hsl(220, 20%, 35%)',
700: 'hsl(220, 20%, 25%)',
750: 'hsl(220, 20%, 18%)',
800: 'hsl(220, 30%, 6%)',
850: 'hsl(220, 22%, 11%)',
900: 'hsl(220, 35%, 3%)',
};
@@ -95,10 +101,14 @@ export const red = {
900: 'hsl(0, 93%, 6%)',
};
const darkBg = 'hsl(0, 0%, 9%)';
const darkPaper = 'hsl(0, 0%, 14%)';
const darkElevated = 'hsl(0, 0%, 19%)';
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'
? '0 4px 16px rgba(0, 0, 0, 0.4), 0 8px 24px rgba(0, 0, 0, 0.3)'
: 'hsla(220, 30%, 5%, 0.07) 0px 4px 16px 0px, hsla(220, 25%, 10%, 0.07) 0px 8px 16px -5px';
return {
@@ -111,9 +121,9 @@ export const getDesignTokens = (mode: PaletteMode) => {
contrastText: brand[50],
...(mode === 'dark' && {
contrastText: brand[50],
light: brand[300],
main: brand[400],
dark: brand[700],
light: 'hsl(210, 50%, 65%)',
main: 'hsl(210, 55%, 55%)',
dark: 'hsl(210, 50%, 35%)',
}),
},
info: {
@@ -122,10 +132,10 @@ export const getDesignTokens = (mode: PaletteMode) => {
dark: brand[600],
contrastText: gray[50],
...(mode === 'dark' && {
contrastText: brand[300],
light: brand[500],
main: brand[700],
dark: brand[900],
contrastText: 'hsl(210, 30%, 80%)',
light: 'hsl(210, 40%, 50%)',
main: 'hsl(210, 35%, 40%)',
dark: 'hsl(210, 30%, 25%)',
}),
},
warning: {
@@ -133,9 +143,9 @@ export const getDesignTokens = (mode: PaletteMode) => {
main: orange[400],
dark: orange[800],
...(mode === 'dark' && {
light: orange[400],
main: orange[500],
dark: orange[700],
light: 'hsl(45, 60%, 55%)',
main: 'hsl(45, 55%, 45%)',
dark: 'hsl(45, 50%, 30%)',
}),
},
error: {
@@ -143,9 +153,9 @@ export const getDesignTokens = (mode: PaletteMode) => {
main: red[400],
dark: red[800],
...(mode === 'dark' && {
light: red[400],
main: red[500],
dark: red[700],
light: 'hsl(0, 55%, 60%)',
main: 'hsl(0, 55%, 50%)',
dark: 'hsl(0, 50%, 35%)',
}),
},
success: {
@@ -153,34 +163,46 @@ export const getDesignTokens = (mode: PaletteMode) => {
main: green[400],
dark: green[800],
...(mode === 'dark' && {
light: green[400],
main: green[500],
dark: green[700],
light: 'hsl(120, 40%, 55%)',
main: 'hsl(120, 40%, 45%)',
dark: 'hsl(120, 35%, 30%)',
}),
},
grey: {
...gray,
},
divider: mode === 'dark' ? alpha(gray[700], 0.6) : alpha(gray[300], 0.4),
divider: mode === 'dark' ? 'hsla(0, 0%, 100%, 0.08)' : 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%)' }),
...(mode === 'dark' && { default: darkBg, paper: darkPaper }),
},
text: {
primary: gray[800],
secondary: gray[600],
warning: orange[400],
...(mode === 'dark' && { primary: 'hsl(0, 0%, 100%)', secondary: gray[400] }),
...(mode === 'dark' && { primary: 'hsl(0, 0%, 92%)', secondary: 'hsl(0, 0%, 60%)' }),
},
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),
hover: 'hsla(0, 0%, 100%, 0.06)',
selected: 'hsla(0, 0%, 100%, 0.1)',
}),
},
flows: {
outflows: {
primary: mode === 'dark' ? 'hsl(0, 55%, 60%)' : '#d32f2f',
surface: mode === 'dark' ? 'hsla(0, 35%, 25%, 0.6)' : '#fdecea',
text: mode === 'dark' ? 'hsl(0, 60%, 80%)' : '#b71c1c',
},
inflows: {
primary: mode === 'dark' ? 'hsl(120, 40%, 55%)' : '#2e7d32',
surface: mode === 'dark' ? 'hsla(120, 25%, 22%, 0.6)' : '#e8f5e9',
text: mode === 'dark' ? 'hsl(120, 40%, 78%)' : '#1b5e20',
},
},
},
typography: {
fontFamily: 'Inter, sans-serif',
@@ -285,6 +307,18 @@ export const colorSchemes = {
hover: alpha(gray[200], 0.2),
selected: `${alpha(gray[200], 0.3)}`,
},
flows: {
outflows: {
primary: '#d32f2f',
surface: '#fdecea',
text: '#b71c1c',
},
inflows: {
primary: '#2e7d32',
surface: '#e8f5e9',
text: '#1b5e20',
},
},
baseShadow:
'hsla(220, 30%, 5%, 0.07) 0px 4px 16px 0px, hsla(220, 25%, 10%, 0.07) 0px 8px 16px -5px',
},
@@ -293,49 +327,60 @@ export const colorSchemes = {
palette: {
primary: {
contrastText: brand[50],
light: brand[300],
main: brand[400],
dark: brand[700],
light: 'hsl(210, 50%, 65%)',
main: 'hsl(210, 55%, 55%)',
dark: 'hsl(210, 50%, 35%)',
},
info: {
contrastText: brand[300],
light: brand[500],
main: brand[700],
dark: brand[900],
contrastText: 'hsl(210, 30%, 80%)',
light: 'hsl(210, 40%, 50%)',
main: 'hsl(210, 35%, 40%)',
dark: 'hsl(210, 30%, 25%)',
},
warning: {
light: orange[400],
main: orange[500],
dark: orange[700],
light: 'hsl(45, 60%, 55%)',
main: 'hsl(45, 55%, 45%)',
dark: 'hsl(45, 50%, 30%)',
},
error: {
light: red[400],
main: red[500],
dark: red[700],
light: 'hsl(0, 55%, 60%)',
main: 'hsl(0, 55%, 50%)',
dark: 'hsl(0, 50%, 35%)',
},
success: {
light: green[400],
main: green[500],
dark: green[700],
light: 'hsl(120, 40%, 55%)',
main: 'hsl(120, 40%, 45%)',
dark: 'hsl(120, 35%, 30%)',
},
grey: {
...gray,
},
divider: alpha(gray[700], 0.6),
divider: 'hsla(0, 0%, 100%, 0.08)',
background: {
default: gray[900],
paper: 'hsl(220, 30%, 7%)',
default: darkBg,
paper: darkPaper,
},
text: {
primary: 'hsl(0, 0%, 100%)',
secondary: gray[400],
primary: 'hsl(0, 0%, 92%)',
secondary: 'hsl(0, 0%, 60%)',
},
action: {
hover: alpha(gray[600], 0.2),
selected: alpha(gray[600], 0.3),
hover: 'hsla(0, 0%, 100%, 0.06)',
selected: 'hsla(0, 0%, 100%, 0.1)',
},
baseShadow:
'hsla(220, 30%, 5%, 0.7) 0px 4px 16px 0px, hsla(220, 25%, 10%, 0.8) 0px 8px 16px -5px',
flows: {
outflows: {
primary: 'hsl(0, 55%, 60%)',
surface: 'hsla(0, 35%, 25%, 0.6)',
text: 'hsl(0, 60%, 80%)',
},
inflows: {
primary: 'hsl(120, 40%, 55%)',
surface: 'hsla(120, 25%, 22%, 0.6)',
text: 'hsl(120, 40%, 78%)',
},
},
baseShadow: '0 4px 16px rgba(0, 0, 0, 0.4), 0 8px 24px rgba(0, 0, 0, 0.3)',
},
},
};