Inital commit
This commit is contained in:
commit
917effe259
30 files changed
+22019
No files matched your search
@@ -0,0 +1,7 @@
|
|||||||
|
node_modules/
|
||||||
|
build/
|
||||||
|
dist/
|
||||||
|
data/
|
||||||
|
.env
|
||||||
|
.env.local
|
||||||
|
.npm/
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
{
|
||||||
|
"PORT": 3010,
|
||||||
|
"VALIDATOR_STRING": "VCk4RTbsSfYWd8WNZvRryRErYhCAbgjE"
|
||||||
|
}
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
"use strict";
|
||||||
|
Object.defineProperty(exports, "__esModule", { value: true });
|
||||||
|
require("./dist/index");
|
||||||
Generated
+19469
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,53 @@
|
|||||||
|
{
|
||||||
|
"name": "flog",
|
||||||
|
"version": "1.0.0",
|
||||||
|
"private": true,
|
||||||
|
"description": "Finance/expense logger",
|
||||||
|
"main": "index.js",
|
||||||
|
"scripts": {
|
||||||
|
"start": "ts-node -P tsconfig.server.json index.ts",
|
||||||
|
"dev": "concurrently -k \"npm run start\" \"npm run dev:client\"",
|
||||||
|
"dev:client": "react-scripts start",
|
||||||
|
"build": "npm run build:client && npm run build:server",
|
||||||
|
"build:client": "react-scripts build",
|
||||||
|
"build:server": "tsc -p tsconfig.server.json",
|
||||||
|
"tsc": "tsc -p tsconfig.server.json"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"@fortawesome/fontawesome-svg-core": "^6.6.0",
|
||||||
|
"@fortawesome/free-solid-svg-icons": "^6.6.0",
|
||||||
|
"@fortawesome/react-fontawesome": "^0.2.2",
|
||||||
|
"express": "^4.21.1",
|
||||||
|
"react": "^18.3.1",
|
||||||
|
"react-dom": "^18.3.1",
|
||||||
|
"recharts": "^2.15.3",
|
||||||
|
"styled-components": "^6.1.13"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@types/express": "^5.0.0",
|
||||||
|
"@types/node": "^22.9.0",
|
||||||
|
"@types/react": "^18.3.12",
|
||||||
|
"@types/react-dom": "^18.3.1",
|
||||||
|
"concurrently": "^9.1.2",
|
||||||
|
"react-scripts": "5.0.1",
|
||||||
|
"ts-node": "^10.9.2",
|
||||||
|
"typescript": "~4.9.5"
|
||||||
|
},
|
||||||
|
"eslintConfig": {
|
||||||
|
"extends": [
|
||||||
|
"react-app"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"browserslist": {
|
||||||
|
"production": [
|
||||||
|
">0.2%",
|
||||||
|
"not dead",
|
||||||
|
"not op_mini all"
|
||||||
|
],
|
||||||
|
"development": [
|
||||||
|
"last 1 chrome version",
|
||||||
|
"last 1 firefox version",
|
||||||
|
"last 1 safari version"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
Binary file not shown.
|
After Width: | Height: | Size: 66 KiB |
@@ -0,0 +1,48 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8" />
|
||||||
|
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||||
|
<meta name="theme-color" content="#000000" />
|
||||||
|
<link rel="preconnect" href="https://fonts.googleapis.com">
|
||||||
|
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
||||||
|
<link href="https://fonts.googleapis.com/css2?family=Ubuntu:ital,wght@0,300;0,400;0,500;0,700;1,300;1,400;1,500;1,700&display=swap" rel="stylesheet">
|
||||||
|
<meta
|
||||||
|
name="description"
|
||||||
|
content="Log whatever you feel like"
|
||||||
|
/>
|
||||||
|
<link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
|
||||||
|
<!--
|
||||||
|
manifest.json provides metadata used when your web app is installed on a
|
||||||
|
user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
|
||||||
|
-->
|
||||||
|
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
|
||||||
|
<!--
|
||||||
|
Notice the use of %PUBLIC_URL% in the tags above.
|
||||||
|
It will be replaced with the URL of the `public` folder during the build.
|
||||||
|
Only files inside the `public` folder can be referenced from the HTML.
|
||||||
|
|
||||||
|
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
|
||||||
|
work correctly both with client-side routing and a non-root public URL.
|
||||||
|
Learn how to configure a non-root public URL by running `npm run build`.
|
||||||
|
-->
|
||||||
|
<title>Flog App</title>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<noscript>You need to enable JavaScript to run this app.</noscript>
|
||||||
|
<div id="root"></div>
|
||||||
|
<!--
|
||||||
|
This HTML file is a template.
|
||||||
|
If you open it directly in the browser, you will see an empty page.
|
||||||
|
|
||||||
|
You can add webfonts, meta tags, or analytics to this file.
|
||||||
|
The build step will place the bundled scripts into the <body> tag.
|
||||||
|
|
||||||
|
To begin the development, run `npm start` or `yarn start`.
|
||||||
|
To create a production bundle, use `npm run build` or `yarn build`.
|
||||||
|
-->
|
||||||
|
|
||||||
|
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
Binary file not shown.
|
After Width: | Height: | Size: 5.2 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 9.4 KiB |
@@ -0,0 +1,25 @@
|
|||||||
|
{
|
||||||
|
"short_name": "React App",
|
||||||
|
"name": "Create React App Sample",
|
||||||
|
"icons": [
|
||||||
|
{
|
||||||
|
"src": "favicon.ico",
|
||||||
|
"sizes": "64x64 32x32 24x24 16x16",
|
||||||
|
"type": "image/x-icon"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"src": "logo192.png",
|
||||||
|
"type": "image/png",
|
||||||
|
"sizes": "192x192"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"src": "logo512.png",
|
||||||
|
"type": "image/png",
|
||||||
|
"sizes": "512x512"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"start_url": ".",
|
||||||
|
"display": "standalone",
|
||||||
|
"theme_color": "#000000",
|
||||||
|
"background_color": "#ffffff"
|
||||||
|
}
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
# https://www.robotstxt.org/robotstxt.html
|
||||||
|
User-agent: *
|
||||||
|
Disallow:
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
import express from "express";
|
||||||
|
import { basicAuth, CustomRequest } from "./utils";
|
||||||
|
import { Encryptor } from "./encryptor";
|
||||||
|
|
||||||
|
export const api = express.Router();
|
||||||
|
api.use(basicAuth as any);
|
||||||
|
api.use((req, res, next) => {
|
||||||
|
req.body = [];
|
||||||
|
req.on('data', chunk => {
|
||||||
|
req.body.push(chunk);
|
||||||
|
});
|
||||||
|
req.on('end', () => {
|
||||||
|
req.body = Buffer.concat(req.body);
|
||||||
|
next();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
|
||||||
|
api.get("/check", async (req: any, res: any) => {
|
||||||
|
try {
|
||||||
|
const r = req as CustomRequest;
|
||||||
|
const result = await Encryptor.exist(r._user!.username, r._user!.password);
|
||||||
|
return res.send(!!result);
|
||||||
|
} catch (error) {
|
||||||
|
return res.sendStatus(500);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
api.get("/:file", async (req: any, res: any) => {
|
||||||
|
try {
|
||||||
|
const r = req as CustomRequest;
|
||||||
|
const en = await Encryptor.createEncryptor(r._user!.username, r._user!.password, r.params.file as string);
|
||||||
|
const buffer = await en.decrypt();
|
||||||
|
if (buffer) {
|
||||||
|
res.send(buffer)
|
||||||
|
} else {
|
||||||
|
return res.sendStatus(404);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
return res.sendStatus(403);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
api.post("/:file", async (req: any, res: any) => {
|
||||||
|
try {
|
||||||
|
const r = req as CustomRequest;
|
||||||
|
const en = await Encryptor.createEncryptor(r._user!.username, r._user!.password, r.params.file as string);
|
||||||
|
en.encrypt(req.body);
|
||||||
|
return res.send(true);
|
||||||
|
} catch (error) {
|
||||||
|
console.error(error);
|
||||||
|
return res.sendStatus(403);
|
||||||
|
}
|
||||||
|
});
|
||||||
@@ -0,0 +1,108 @@
|
|||||||
|
import * as crypto from "crypto";
|
||||||
|
import * as path from "path";
|
||||||
|
import { promises as fs , existsSync, mkdirSync } from "fs";
|
||||||
|
|
||||||
|
const dataDir = path.join(process.cwd(), 'data');
|
||||||
|
if (!existsSync(dataDir)) {
|
||||||
|
mkdirSync(dataDir);
|
||||||
|
}
|
||||||
|
|
||||||
|
export class Encryptor {
|
||||||
|
private static magic = "";
|
||||||
|
private static validatorFile = 'key-validator';
|
||||||
|
private constructor(private key: Buffer, private filePath: string) {}
|
||||||
|
|
||||||
|
static setMagic(magic: string) {
|
||||||
|
Encryptor.magic = magic;
|
||||||
|
}
|
||||||
|
|
||||||
|
static async exist(identifier: string, key: string) {
|
||||||
|
identifier = this.makeFileSafeString(identifier);
|
||||||
|
const storeDirectory = path.join(dataDir, identifier);
|
||||||
|
const validatorFileBin = path.join(storeDirectory, `${this.validatorFile}.bin`);
|
||||||
|
const keyHash = crypto.createHash('sha256').update(key).digest()
|
||||||
|
try {
|
||||||
|
await fs.access(validatorFileBin)
|
||||||
|
} catch (error) {
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
|
||||||
|
const en = new Encryptor(keyHash, validatorFileBin);
|
||||||
|
try {
|
||||||
|
const validator = await en.decrypt();
|
||||||
|
|
||||||
|
if (!validator || validator.toString('utf8') !== Encryptor.magic) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
static async createEncryptor(identifier: string, key: string, file: string) {
|
||||||
|
if (file === this.validatorFile)
|
||||||
|
throw new Error(`File cannot be ${this.validatorFile}`);
|
||||||
|
|
||||||
|
identifier = this.makeFileSafeString(identifier);
|
||||||
|
const storeDirectory = path.join(dataDir, identifier);
|
||||||
|
const validatorFileBin = path.join(storeDirectory, `${this.validatorFile}.bin`);
|
||||||
|
const writableDir = path.join(storeDirectory, `${file}.bin`);
|
||||||
|
const keyHash = crypto.createHash('sha256').update(key).digest()
|
||||||
|
|
||||||
|
const en = new Encryptor(keyHash, validatorFileBin);
|
||||||
|
try {
|
||||||
|
await fs.access(validatorFileBin)
|
||||||
|
} catch (error) {
|
||||||
|
if (!existsSync(storeDirectory)) {
|
||||||
|
mkdirSync(storeDirectory);
|
||||||
|
}
|
||||||
|
await en.encrypt(Buffer.from(Encryptor.magic, 'utf8'));
|
||||||
|
return new Encryptor(keyHash, file);
|
||||||
|
};
|
||||||
|
const validator = await en.decrypt();
|
||||||
|
|
||||||
|
if (!validator || validator.toString('utf8') !== Encryptor.magic) {
|
||||||
|
throw new Error("Invalid key");
|
||||||
|
}
|
||||||
|
return new Encryptor(keyHash, writableDir);
|
||||||
|
}
|
||||||
|
|
||||||
|
static makeFileSafeString(input: string) {
|
||||||
|
return input
|
||||||
|
.replace(/\s+/g, '_')
|
||||||
|
.replace(/[^a-zA-Z0-9_.-]/g, '')
|
||||||
|
.substring(0, 255);
|
||||||
|
}
|
||||||
|
|
||||||
|
private encryptBuffer(data: Buffer): Buffer {
|
||||||
|
const iv = crypto.randomBytes(16);
|
||||||
|
const cipher = crypto.createCipheriv('aes-256-cbc', this.key, iv);
|
||||||
|
const encrypted = Buffer.concat([cipher.update(data), cipher.final()]);
|
||||||
|
return Buffer.concat([iv, encrypted]);
|
||||||
|
}
|
||||||
|
|
||||||
|
private decryptBuffer(buffer: Buffer): Buffer {
|
||||||
|
const iv = buffer.subarray(0, 16);
|
||||||
|
const encryptedData = buffer.subarray(16);
|
||||||
|
const decipher = crypto.createDecipheriv('aes-256-cbc', this.key, iv);
|
||||||
|
const decrypted = Buffer.concat([decipher.update(encryptedData), decipher.final()]);
|
||||||
|
return decrypted;
|
||||||
|
}
|
||||||
|
|
||||||
|
async encrypt(data: Buffer): Promise<void> {
|
||||||
|
const encryptedBuffer = this.encryptBuffer(data);
|
||||||
|
await fs.writeFile(this.filePath, encryptedBuffer);
|
||||||
|
}
|
||||||
|
|
||||||
|
async decrypt(): Promise<Buffer | null> {
|
||||||
|
try {
|
||||||
|
await fs.access(this.filePath);
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
const buffer = await fs.readFile(this.filePath);
|
||||||
|
const decryptedData = this.decryptBuffer(buffer);
|
||||||
|
return decryptedData;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
import { Encryptor } from "./encryptor";
|
||||||
|
import { readFileSync } from "fs";
|
||||||
|
import * as path from "path";
|
||||||
|
import express from "express";
|
||||||
|
import { api } from "./api";
|
||||||
|
|
||||||
|
const config = JSON.parse(readFileSync(path.join(process.cwd(), "config.json"), "utf8")) as {
|
||||||
|
PORT: number;
|
||||||
|
VALIDATOR_STRING: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
Encryptor.setMagic(config.VALIDATOR_STRING);
|
||||||
|
|
||||||
|
const app = express();
|
||||||
|
|
||||||
|
app.disable('x-powered-by');
|
||||||
|
app.use(express.static("build"));
|
||||||
|
app.use((req, res, next) => {
|
||||||
|
res.header('Access-Control-Allow-Origin', '*');
|
||||||
|
res.header('Access-Control-Allow-Methods', 'GET,POST,PUT,DELETE,OPTIONS');
|
||||||
|
res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization');
|
||||||
|
if (req.method === 'OPTIONS') {
|
||||||
|
return res.sendStatus(204); // Respond to preflight requests
|
||||||
|
}
|
||||||
|
next();
|
||||||
|
});
|
||||||
|
|
||||||
|
|
||||||
|
app.use("/api", api);
|
||||||
|
|
||||||
|
app.listen(config.PORT, () => {
|
||||||
|
console.log(`Listening to ${config.PORT}`);
|
||||||
|
});
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
import { Request, Response, NextFunction } from "express";
|
||||||
|
import { Encryptor } from "./encryptor";
|
||||||
|
|
||||||
|
export interface CustomRequest extends Request {
|
||||||
|
_user?: { username: string; password: string };
|
||||||
|
}
|
||||||
|
|
||||||
|
export function basicAuth(req: CustomRequest, res: Response, next: NextFunction) {
|
||||||
|
const authHeader = req.headers['authorization'];
|
||||||
|
|
||||||
|
if (!authHeader) {
|
||||||
|
return res.sendStatus(401);
|
||||||
|
}
|
||||||
|
|
||||||
|
const base64Credentials = authHeader.split(' ')[1];
|
||||||
|
const credentials = Buffer.from(base64Credentials, 'base64').toString('utf-8');
|
||||||
|
const [username, password] = credentials.split(':');
|
||||||
|
const safeString = Encryptor.makeFileSafeString(username);
|
||||||
|
|
||||||
|
if (safeString.length < 6) {
|
||||||
|
return res.sendStatus(401);
|
||||||
|
}
|
||||||
|
|
||||||
|
req._user = {
|
||||||
|
username,
|
||||||
|
password,
|
||||||
|
}
|
||||||
|
next();
|
||||||
|
};
|
||||||
+30
@@ -0,0 +1,30 @@
|
|||||||
|
import { useEffect, useState } from "react"
|
||||||
|
import { WebsiteStorage } from "./Storage";
|
||||||
|
import { Login } from "./Login";
|
||||||
|
import { Page } from "./Page";
|
||||||
|
import "./Base.css";
|
||||||
|
|
||||||
|
|
||||||
|
export function App(props: { baseUrl: string }) {
|
||||||
|
const [storage] = useState(new WebsiteStorage(props.baseUrl));
|
||||||
|
const [hasAccount, setHasAccount] = useState<boolean | undefined>();
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
storage.hasAccount().then(result => {
|
||||||
|
setHasAccount(result)
|
||||||
|
}).catch(() => {
|
||||||
|
setHasAccount(false)
|
||||||
|
});
|
||||||
|
}, [storage]);
|
||||||
|
|
||||||
|
if (hasAccount) {
|
||||||
|
return <Page storage={storage} logout={() => {
|
||||||
|
storage.password = "";
|
||||||
|
setHasAccount(false);
|
||||||
|
}} />
|
||||||
|
} else {
|
||||||
|
return <Login storage={storage} login={() => {
|
||||||
|
setHasAccount(true);
|
||||||
|
}}/>
|
||||||
|
}
|
||||||
|
}
|
||||||
+141
@@ -0,0 +1,141 @@
|
|||||||
|
:root {
|
||||||
|
--color-bg: #000000;
|
||||||
|
--color-surface: #111214;
|
||||||
|
--color-surface-alt: #1a1d22;
|
||||||
|
--color-border: #2b2f36;
|
||||||
|
--color-border-strong: #4a5058;
|
||||||
|
--color-text: #f2f3f5;
|
||||||
|
--color-text-muted: #c3c7cf;
|
||||||
|
--color-text-faint: #8a9099;
|
||||||
|
--color-income: #3ddc84;
|
||||||
|
--color-expense: #ff6b6b;
|
||||||
|
--color-accent: #5b9dff;
|
||||||
|
--color-focus-ring: #7ab3ff;
|
||||||
|
--color-danger-bg: #2a1210;
|
||||||
|
--color-danger-border: #8a2f28;
|
||||||
|
|
||||||
|
--radius-sm: 6px;
|
||||||
|
--radius-md: 10px;
|
||||||
|
--radius-lg: 14px;
|
||||||
|
|
||||||
|
--space-xs: 4px;
|
||||||
|
--space-sm: 8px;
|
||||||
|
--space-md: 12px;
|
||||||
|
--space-lg: 16px;
|
||||||
|
--space-xl: 24px;
|
||||||
|
--space-xxl: 40px;
|
||||||
|
}
|
||||||
|
|
||||||
|
* {
|
||||||
|
padding: 0;
|
||||||
|
margin: 0;
|
||||||
|
box-sizing: border-box;
|
||||||
|
font-family: "Ubuntu", system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
|
||||||
|
}
|
||||||
|
|
||||||
|
html {
|
||||||
|
color-scheme: dark;
|
||||||
|
}
|
||||||
|
|
||||||
|
body {
|
||||||
|
background-color: var(--color-bg);
|
||||||
|
color: var(--color-text);
|
||||||
|
-webkit-font-smoothing: antialiased;
|
||||||
|
text-rendering: optimizeLegibility;
|
||||||
|
}
|
||||||
|
|
||||||
|
html,
|
||||||
|
body,
|
||||||
|
#root {
|
||||||
|
width: 100%;
|
||||||
|
min-height: 100%;
|
||||||
|
}
|
||||||
|
|
||||||
|
body {
|
||||||
|
overflow-x: hidden;
|
||||||
|
}
|
||||||
|
|
||||||
|
button,
|
||||||
|
input,
|
||||||
|
select,
|
||||||
|
textarea {
|
||||||
|
font: inherit;
|
||||||
|
letter-spacing: inherit;
|
||||||
|
}
|
||||||
|
|
||||||
|
button {
|
||||||
|
background-color: transparent;
|
||||||
|
color: var(--color-text);
|
||||||
|
border: 1px solid var(--color-border-strong);
|
||||||
|
border-radius: var(--radius-sm);
|
||||||
|
padding: 10px 14px;
|
||||||
|
min-height: 40px;
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
|
||||||
|
button:hover {
|
||||||
|
background-color: var(--color-surface-alt);
|
||||||
|
}
|
||||||
|
|
||||||
|
button:active {
|
||||||
|
transform: translateY(1px);
|
||||||
|
}
|
||||||
|
|
||||||
|
button:disabled {
|
||||||
|
opacity: 0.5;
|
||||||
|
cursor: not-allowed;
|
||||||
|
}
|
||||||
|
|
||||||
|
input {
|
||||||
|
background-color: var(--color-surface);
|
||||||
|
color: var(--color-text);
|
||||||
|
border: 1px solid var(--color-border);
|
||||||
|
border-radius: var(--radius-sm);
|
||||||
|
padding: 10px 12px;
|
||||||
|
min-height: 40px;
|
||||||
|
}
|
||||||
|
|
||||||
|
input::placeholder {
|
||||||
|
color: var(--color-text-faint);
|
||||||
|
}
|
||||||
|
|
||||||
|
button:focus-visible,
|
||||||
|
input:focus-visible,
|
||||||
|
select:focus-visible,
|
||||||
|
textarea:focus-visible {
|
||||||
|
outline: 2px solid var(--color-focus-ring);
|
||||||
|
outline-offset: 2px;
|
||||||
|
}
|
||||||
|
|
||||||
|
input[type="date"]::-webkit-calendar-picker-indicator,
|
||||||
|
input[type="month"]::-webkit-calendar-picker-indicator {
|
||||||
|
filter: invert(1);
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
|
||||||
|
.sr-only {
|
||||||
|
position: absolute;
|
||||||
|
width: 1px;
|
||||||
|
height: 1px;
|
||||||
|
padding: 0;
|
||||||
|
margin: -1px;
|
||||||
|
overflow: hidden;
|
||||||
|
clip: rect(0 0 0 0);
|
||||||
|
white-space: nowrap;
|
||||||
|
border: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.alert {
|
||||||
|
color: #ffb3a7;
|
||||||
|
background-color: var(--color-danger-bg);
|
||||||
|
border: 1px solid var(--color-danger-border);
|
||||||
|
border-radius: var(--radius-sm);
|
||||||
|
padding: 10px 12px;
|
||||||
|
font-size: 0.875rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.center {
|
||||||
|
margin: auto;
|
||||||
|
width: 50%;
|
||||||
|
padding: 10px;
|
||||||
|
}
|
||||||
+168
@@ -0,0 +1,168 @@
|
|||||||
|
import { PieChart, Pie, Cell, Tooltip, ResponsiveContainer } from "recharts";
|
||||||
|
import { Data } from "./Storage";
|
||||||
|
import styled from "styled-components";
|
||||||
|
import { theme } from "./theme";
|
||||||
|
|
||||||
|
const Scrollbar = styled.div`
|
||||||
|
|
||||||
|
scrollbar-width: thin;
|
||||||
|
scrollbar-color: white rgba(0,0,0,0.1);
|
||||||
|
|
||||||
|
|
||||||
|
&::-webkit-scrollbar {
|
||||||
|
width: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
&::-webkit-scrollbar-track {
|
||||||
|
background: rgba(0,0,0,0.1);
|
||||||
|
border-radius: 0px;
|
||||||
|
}
|
||||||
|
|
||||||
|
&::-webkit-scrollbar-thumb {
|
||||||
|
background-color: white;
|
||||||
|
border-radius: 0px;
|
||||||
|
border: 2px solid rgba(0,0,0,0.1);
|
||||||
|
}
|
||||||
|
|
||||||
|
&::-webkit-scrollbar-thumb:hover {
|
||||||
|
background-color: white;
|
||||||
|
}
|
||||||
|
`;
|
||||||
|
|
||||||
|
|
||||||
|
export function CategoryGraphs({ data }: { data: Data<Date>[] }) {
|
||||||
|
const keys: (keyof Data<Date>)[] = ["name", "location", "category"];
|
||||||
|
const COLORS = [
|
||||||
|
"#4AF626", "#3B9DFF", "#FF5733", "#FFD700",
|
||||||
|
"#9B59B6", "#00CED1", "#FF69B4", "#8BFF8B",
|
||||||
|
"#FF8C00", "#1E90FF", "#ADFF2F", "#DC143C"
|
||||||
|
];
|
||||||
|
|
||||||
|
const getGroupedNegativeData = (key: keyof Data<Date>) => {
|
||||||
|
const map = new Map<string, number>();
|
||||||
|
data.forEach(entry => {
|
||||||
|
if (entry.amount < 0) {
|
||||||
|
const k = entry[key] as string;
|
||||||
|
map.set(k, (map.get(k) || 0) + Math.abs(entry.amount));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
return Array.from(map.entries()).map(([name, value]) => ({ name, value }));
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div style={{ display: "flex", flexDirection: "column", gap: theme.spacing.xl }}>
|
||||||
|
{keys.map(key => {
|
||||||
|
const chartData = getGroupedNegativeData(key).map(e => ({
|
||||||
|
...e,
|
||||||
|
value: parseFloat(e.value.toFixed(2))
|
||||||
|
}));
|
||||||
|
if (chartData.length === 0) return null;
|
||||||
|
|
||||||
|
const total = chartData.reduce((sum, e) => sum + e.value, 0);
|
||||||
|
const uniquePrefix = `p-${key}`;
|
||||||
|
const sortedData = [...chartData].sort((a, b) => b.value - a.value);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div key={String(key)} style={{ width: "100%" }}>
|
||||||
|
<h3 style={{ margin: `${theme.spacing.sm}px 0`, color: theme.colors.text }}>{String(key).toUpperCase()}</h3>
|
||||||
|
|
||||||
|
<Scrollbar style={{ display: "flex", alignItems: "flex-start", gap: theme.spacing.lg }}>
|
||||||
|
<div style={{ flex: "1 1 0%", height: 340, minWidth: 240 }}>
|
||||||
|
<ResponsiveContainer width="100%" height="100%">
|
||||||
|
<PieChart>
|
||||||
|
<defs>
|
||||||
|
|
||||||
|
{sortedData.map((_, i) => {
|
||||||
|
const color = COLORS[i % COLORS.length];
|
||||||
|
const pid = `${uniquePrefix}-pattern-${i}`;
|
||||||
|
const patternDefs: Record<number, JSX.Element> = {
|
||||||
|
0: <path d="M0,8 L8,0" stroke="black" strokeWidth="1" />,
|
||||||
|
1: <path d="M0,0 L8,8" stroke="black" strokeWidth="1" />,
|
||||||
|
2: <path d="M4,0 L4,8" stroke="black" strokeWidth="1" />,
|
||||||
|
3: <path d="M0,4 L8,4" stroke="black" strokeWidth="1" />,
|
||||||
|
4: <circle cx="2" cy="2" r="1" fill="black" />,
|
||||||
|
5: <circle cx="4" cy="4" r="1.2" fill="black" />,
|
||||||
|
6: <path d="M0,0 L8,8 M8,0 L0,8" stroke="black" strokeWidth="1" />,
|
||||||
|
7: <path d="M0,0 L8,0 M0,4 L8,4 M0,8 L8,8" stroke="black" strokeWidth="1" />,
|
||||||
|
8: <path d="M0,2 L8,2" stroke="black" strokeWidth="2" />,
|
||||||
|
9: <path d="M2,0 L2,8" stroke="black" strokeWidth="2" />,
|
||||||
|
10: <path d="M0,0 L8,4 L0,8 Z" fill="black" opacity="0.3" />,
|
||||||
|
11: <path d="M4,0 L8,8 L0,8 Z" fill="black" opacity="0.3" />,
|
||||||
|
};
|
||||||
|
const type = i % 12;
|
||||||
|
return (
|
||||||
|
<pattern
|
||||||
|
key={pid}
|
||||||
|
id={pid}
|
||||||
|
patternUnits="userSpaceOnUse"
|
||||||
|
width="8"
|
||||||
|
height="8"
|
||||||
|
>
|
||||||
|
<rect x="0" y="0" width="8" height="8" fill={color} />
|
||||||
|
{patternDefs[type]}
|
||||||
|
</pattern>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
|
||||||
|
</defs>
|
||||||
|
|
||||||
|
<Pie
|
||||||
|
data={chartData}
|
||||||
|
dataKey="value"
|
||||||
|
nameKey="name"
|
||||||
|
cx="45%"
|
||||||
|
cy="50%"
|
||||||
|
outerRadius={120}
|
||||||
|
innerRadius={50}
|
||||||
|
labelLine={false}
|
||||||
|
label={false}
|
||||||
|
>
|
||||||
|
{sortedData.map((_, i) => (
|
||||||
|
<Cell key={i} fill={`url(#${uniquePrefix}-pattern-${i})`} />
|
||||||
|
))}
|
||||||
|
</Pie>
|
||||||
|
<Tooltip />
|
||||||
|
</PieChart>
|
||||||
|
</ResponsiveContainer>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div style={{
|
||||||
|
width: 240,
|
||||||
|
maxHeight: 340,
|
||||||
|
overflowY: "auto",
|
||||||
|
padding: 8,
|
||||||
|
boxSizing: "border-box",
|
||||||
|
borderLeft: `1px solid ${theme.colors.border}`
|
||||||
|
}}>
|
||||||
|
{sortedData.map((slice, i) => {
|
||||||
|
const pid = `${uniquePrefix}-pattern-${i}`;
|
||||||
|
const percentage = ((slice.value / total) * 100).toFixed(1);
|
||||||
|
return (
|
||||||
|
<div key={slice.name} style={{
|
||||||
|
display: "flex",
|
||||||
|
gap: theme.spacing.sm,
|
||||||
|
alignItems: "center",
|
||||||
|
padding: "6px 4px",
|
||||||
|
whiteSpace: "nowrap"
|
||||||
|
}}>
|
||||||
|
<svg width="28" height="18" viewBox="0 0 28 18" style={{ flex: "0 0 28px" }}>
|
||||||
|
<rect x="0" y="0" width="28" height="18" fill={`url(#${pid})`} />
|
||||||
|
</svg>
|
||||||
|
<div style={{ overflow: "hidden", textOverflow: "ellipsis" }}>
|
||||||
|
<div style={{ fontSize: 13, color: theme.colors.text }}>{slice.name}</div>
|
||||||
|
<div style={{ fontSize: 12, color: theme.colors.textFaint }}>
|
||||||
|
{slice.value.toFixed(2)} ({percentage}%)
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
</Scrollbar>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
+153
@@ -0,0 +1,153 @@
|
|||||||
|
import { useState } from "react";
|
||||||
|
import { WebsiteStorage } from "./Storage";
|
||||||
|
import styled from "styled-components";
|
||||||
|
import { theme } from "./theme";
|
||||||
|
import { FormEvent } from "react";
|
||||||
|
|
||||||
|
const Shell = styled.div`
|
||||||
|
min-height: 100%;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
padding: ${theme.spacing.xl}px;
|
||||||
|
`;
|
||||||
|
|
||||||
|
const Card = styled.div`
|
||||||
|
width: 100%;
|
||||||
|
max-width: 380px;
|
||||||
|
background: ${theme.colors.surface};
|
||||||
|
border: 1px solid ${theme.colors.border};
|
||||||
|
border-radius: ${theme.radius.lg}px;
|
||||||
|
padding: ${theme.spacing.xl}px;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: ${theme.spacing.lg}px;
|
||||||
|
`;
|
||||||
|
|
||||||
|
const Title = styled.h1`
|
||||||
|
margin: 0;
|
||||||
|
text-align: center;
|
||||||
|
font-size: ${theme.font.sizes.xl};
|
||||||
|
`;
|
||||||
|
|
||||||
|
const Subtitle = styled.p`
|
||||||
|
margin: 0;
|
||||||
|
text-align: center;
|
||||||
|
color: ${theme.colors.textMuted};
|
||||||
|
font-size: ${theme.font.sizes.sm};
|
||||||
|
`;
|
||||||
|
|
||||||
|
const Form = styled.form`
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: ${theme.spacing.md}px;
|
||||||
|
`;
|
||||||
|
|
||||||
|
const Field = styled.label`
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: ${theme.spacing.xs}px;
|
||||||
|
font-size: ${theme.font.sizes.xs};
|
||||||
|
font-weight: 700;
|
||||||
|
text-transform: uppercase;
|
||||||
|
letter-spacing: 0.06em;
|
||||||
|
color: ${theme.colors.textMuted};
|
||||||
|
`;
|
||||||
|
|
||||||
|
const Primary = styled.button`
|
||||||
|
background: ${theme.colors.accent};
|
||||||
|
border-color: ${theme.colors.accent};
|
||||||
|
color: #0b0d10;
|
||||||
|
font-weight: 600;
|
||||||
|
padding: 12px 16px;
|
||||||
|
border-radius: ${theme.radius.md}px;
|
||||||
|
`;
|
||||||
|
|
||||||
|
const Buttons = styled.div`
|
||||||
|
display: flex;
|
||||||
|
justify-content: center;
|
||||||
|
gap: ${theme.spacing.sm}px;
|
||||||
|
`;
|
||||||
|
|
||||||
|
export function Login(props: {login: () => void, storage: WebsiteStorage}) {
|
||||||
|
const [username, setUsername] = useState(props.storage.username);
|
||||||
|
const [password, setPassword] = useState(props.storage.password);
|
||||||
|
const [confirm, setConfirm] = useState(false);
|
||||||
|
const [error, setError] = useState("");
|
||||||
|
const [sending, setSending] = useState(false);
|
||||||
|
|
||||||
|
const submit = async () => {
|
||||||
|
if (sending) return;
|
||||||
|
setSending(true);
|
||||||
|
props.storage.username = username;
|
||||||
|
props.storage.password = password;
|
||||||
|
|
||||||
|
try {
|
||||||
|
if (await props.storage.hasAccount()) {
|
||||||
|
props.login();
|
||||||
|
} else {
|
||||||
|
setConfirm(true);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
setError((error as any).message);
|
||||||
|
}
|
||||||
|
setSending(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
const mkAccount = async () => {
|
||||||
|
setConfirm(false);
|
||||||
|
setSending(true);
|
||||||
|
try {
|
||||||
|
await props.storage.createAccount();
|
||||||
|
props.login();
|
||||||
|
} catch (error) {
|
||||||
|
setError((error as any).message);
|
||||||
|
}
|
||||||
|
setSending(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (sending) {
|
||||||
|
return <Shell>
|
||||||
|
<Card>
|
||||||
|
<p role="status" style={{ textAlign: "center", color: theme.colors.textMuted }}>Loading…</p>
|
||||||
|
</Card>
|
||||||
|
</Shell>
|
||||||
|
}
|
||||||
|
|
||||||
|
if (confirm) {
|
||||||
|
return <Shell>
|
||||||
|
<Card>
|
||||||
|
<Title>Register account</Title>
|
||||||
|
<Subtitle>An account for “{username}” does not exist. Would you like to register it?</Subtitle>
|
||||||
|
<Buttons>
|
||||||
|
<Primary onClick={() => mkAccount()}>Yes</Primary>
|
||||||
|
<button className="danger" onClick={() => setConfirm(false)}>No</button>
|
||||||
|
</Buttons>
|
||||||
|
</Card>
|
||||||
|
</Shell>
|
||||||
|
}
|
||||||
|
|
||||||
|
return <Shell>
|
||||||
|
<Card>
|
||||||
|
<Title>Flog</Title>
|
||||||
|
<Subtitle>Log in to your expense journal</Subtitle>
|
||||||
|
<Form onSubmit={(ev: FormEvent) => {
|
||||||
|
ev.preventDefault();
|
||||||
|
submit();
|
||||||
|
}}>
|
||||||
|
<Field>
|
||||||
|
Username
|
||||||
|
<input type="text" placeholder="Username"
|
||||||
|
value={username} autoComplete="username" onChange={(ev) => setUsername(ev.target.value)} />
|
||||||
|
</Field>
|
||||||
|
<Field>
|
||||||
|
Password
|
||||||
|
<input type="password" placeholder="Password"
|
||||||
|
value={password} autoComplete="current-password" onChange={(ev) => setPassword(ev.target.value)} />
|
||||||
|
</Field>
|
||||||
|
<Primary type="submit" disabled={sending || !(username && password)}>Login / Register</Primary>
|
||||||
|
</Form>
|
||||||
|
{error ? <div className="alert" role="alert">{error}</div> : undefined}
|
||||||
|
</Card>
|
||||||
|
</Shell>
|
||||||
|
}
|
||||||
+353
@@ -0,0 +1,353 @@
|
|||||||
|
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||||
|
import type { ChangeEvent } from "react";
|
||||||
|
import { Data, DataKeys, migrateSuggestions, Suggestions, SuggestionEntry, WebsiteStorage } from "./Storage";
|
||||||
|
import { Table } from "./Table";
|
||||||
|
import { AmountTone, formatSigned, getMonth } from "./utils";
|
||||||
|
import { CategoryGraphs } from "./Charts";
|
||||||
|
import { SuggestionsManager } from "./Suggestions";
|
||||||
|
import styled from "styled-components";
|
||||||
|
import { theme } from "./theme";
|
||||||
|
|
||||||
|
const Div = styled.div`
|
||||||
|
min-height: 100%;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
`;
|
||||||
|
|
||||||
|
const Header = styled.header`
|
||||||
|
position: sticky;
|
||||||
|
top: 0;
|
||||||
|
z-index: 20;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
gap: ${theme.spacing.md}px;
|
||||||
|
padding: ${theme.spacing.md}px ${theme.spacing.xl}px;
|
||||||
|
background: ${theme.colors.bg};
|
||||||
|
border-bottom: 1px solid ${theme.colors.border};
|
||||||
|
|
||||||
|
@media (max-width: ${theme.breakpoints.mobile}) {
|
||||||
|
padding: ${theme.spacing.sm}px ${theme.spacing.md}px;
|
||||||
|
}
|
||||||
|
`;
|
||||||
|
|
||||||
|
const Brand = styled.div`
|
||||||
|
display: flex;
|
||||||
|
align-items: baseline;
|
||||||
|
gap: ${theme.spacing.md}px;
|
||||||
|
`;
|
||||||
|
|
||||||
|
const Title = styled.h1`
|
||||||
|
margin: 0;
|
||||||
|
font-size: ${theme.font.sizes.lg};
|
||||||
|
font-weight: 700;
|
||||||
|
letter-spacing: 0.02em;
|
||||||
|
`;
|
||||||
|
|
||||||
|
const MonthBadge = styled.span`
|
||||||
|
font-variant-numeric: tabular-nums;
|
||||||
|
color: ${theme.colors.textMuted};
|
||||||
|
font-size: ${theme.font.sizes.sm};
|
||||||
|
`;
|
||||||
|
|
||||||
|
const Controls = styled.div`
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: ${theme.spacing.sm}px;
|
||||||
|
`;
|
||||||
|
|
||||||
|
const MonthInput = styled.input.attrs({ type: "month" })`
|
||||||
|
min-width: 150px;
|
||||||
|
max-width: 200px;
|
||||||
|
`;
|
||||||
|
|
||||||
|
const Main = styled.main`
|
||||||
|
width: 100%;
|
||||||
|
max-width: 1200px;
|
||||||
|
margin: 0 auto;
|
||||||
|
padding: ${theme.spacing.xl}px;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: ${theme.spacing.xl}px;
|
||||||
|
flex: 1;
|
||||||
|
|
||||||
|
@media (max-width: ${theme.breakpoints.mobile}) {
|
||||||
|
padding: ${theme.spacing.lg}px;
|
||||||
|
gap: ${theme.spacing.lg}px;
|
||||||
|
}
|
||||||
|
`;
|
||||||
|
|
||||||
|
const SummaryGrid = styled.section`
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
|
||||||
|
gap: ${theme.spacing.md}px;
|
||||||
|
`;
|
||||||
|
|
||||||
|
const StatCard = styled.div<{ hero?: boolean }>`
|
||||||
|
background: ${p => (p.hero ? theme.colors.surfaceAlt : theme.colors.surface)};
|
||||||
|
border: 1px solid ${p => (p.hero ? theme.colors.borderStrong : theme.colors.border)};
|
||||||
|
border-radius: ${theme.radius.md}px;
|
||||||
|
padding: ${theme.spacing.lg}px;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: ${theme.spacing.xs}px;
|
||||||
|
`;
|
||||||
|
|
||||||
|
const StatLabel = styled.span`
|
||||||
|
font-size: ${theme.font.sizes.xs};
|
||||||
|
font-weight: 700;
|
||||||
|
text-transform: uppercase;
|
||||||
|
letter-spacing: 0.08em;
|
||||||
|
color: ${theme.colors.textMuted};
|
||||||
|
`;
|
||||||
|
|
||||||
|
const StatValue = styled.span<{ tone?: AmountTone }>`
|
||||||
|
font-size: ${theme.font.sizes.xl};
|
||||||
|
font-weight: 700;
|
||||||
|
font-variant-numeric: tabular-nums;
|
||||||
|
text-align: right;
|
||||||
|
color: ${p =>
|
||||||
|
p.tone === "income" ? theme.colors.income
|
||||||
|
: p.tone === "expense" ? theme.colors.expense
|
||||||
|
: theme.colors.text};
|
||||||
|
`;
|
||||||
|
|
||||||
|
const EmptyHint = styled.div`
|
||||||
|
background: ${theme.colors.surface};
|
||||||
|
border: 1px dashed ${theme.colors.borderStrong};
|
||||||
|
border-radius: ${theme.radius.md}px;
|
||||||
|
padding: ${theme.spacing.xl}px;
|
||||||
|
text-align: center;
|
||||||
|
color: ${theme.colors.textMuted};
|
||||||
|
`;
|
||||||
|
|
||||||
|
const Message = styled.div`
|
||||||
|
flex: 1;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
gap: ${theme.spacing.md}px;
|
||||||
|
padding: ${theme.spacing.xl}px;
|
||||||
|
text-align: center;
|
||||||
|
color: ${theme.colors.textMuted};
|
||||||
|
`;
|
||||||
|
|
||||||
|
const ErrorTitle = styled.h2`
|
||||||
|
color: ${theme.colors.expense};
|
||||||
|
margin: 0;
|
||||||
|
`;
|
||||||
|
|
||||||
|
const fmtMoney = (n: number) =>
|
||||||
|
Math.abs(n).toLocaleString("en-US", { minimumFractionDigits: 2, maximumFractionDigits: 2 });
|
||||||
|
|
||||||
|
export function Page(props: { storage: WebsiteStorage, logout: () => void }) {
|
||||||
|
const [month, setMonth] = useState("");
|
||||||
|
const [data, setData] = useState<Data<Date>[]>([]);
|
||||||
|
const [past, setPast] = useState<Data<Date>[][]>([]);
|
||||||
|
const [future, setFuture] = useState<Data<Date>[][]>([]);
|
||||||
|
const [loading, setLoading] = useState(true);
|
||||||
|
const [error, setError] = useState("");
|
||||||
|
const [suggestions, setAutoSuggestions] = useState<Suggestions>({});
|
||||||
|
const [suggestionsOpen, setSuggestionsOpen] = useState(false);
|
||||||
|
|
||||||
|
const setDate = async (month: string) => {
|
||||||
|
setLoading(true);
|
||||||
|
setPast([]);
|
||||||
|
setFuture([]);
|
||||||
|
try {
|
||||||
|
const data = await props.storage.load(month);
|
||||||
|
setMonth(month);
|
||||||
|
setData(data ?? []);
|
||||||
|
} catch (error) {
|
||||||
|
console.error(error);
|
||||||
|
setError((error as any).message)
|
||||||
|
setMonth(month);
|
||||||
|
setData([]);
|
||||||
|
}
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
const fetchAutoSuggestions = async () => {
|
||||||
|
const autoSuggestions = await props.storage.getAutoSuggestions();
|
||||||
|
setAutoSuggestions(autoSuggestions);
|
||||||
|
}
|
||||||
|
|
||||||
|
const setSuggestions = (next: Suggestions) => {
|
||||||
|
const migrated = migrateSuggestions(next);
|
||||||
|
setAutoSuggestions(migrated);
|
||||||
|
props.storage.setAutoSuggestions(migrated);
|
||||||
|
}
|
||||||
|
|
||||||
|
const modifySuggestions = async (key: DataKeys, value: string[]) => {
|
||||||
|
const clone = migrateSuggestions({ ...suggestions });
|
||||||
|
const items: Record<string, SuggestionEntry> = {};
|
||||||
|
value.forEach(entry => {
|
||||||
|
if (entry.trim()) {
|
||||||
|
const normalized = entry.trim();
|
||||||
|
const existing = clone[key]?.items[normalized];
|
||||||
|
items[normalized] = existing
|
||||||
|
? { ...existing, count: existing.count }
|
||||||
|
: { count: 1, lastUsed: Date.now() };
|
||||||
|
}
|
||||||
|
});
|
||||||
|
clone[key] = { items };
|
||||||
|
setSuggestions(clone);
|
||||||
|
}
|
||||||
|
|
||||||
|
const addSuggestions = async (values: {key: DataKeys, value: string}[]) => {
|
||||||
|
const clone = migrateSuggestions({ ...suggestions });
|
||||||
|
const now = Date.now();
|
||||||
|
for (const { key, value } of values) {
|
||||||
|
const actualValue = value.trim();
|
||||||
|
if (!actualValue) continue;
|
||||||
|
clone[key] = clone[key] ?? { items: {} };
|
||||||
|
const group = clone[key]!;
|
||||||
|
const found = Object.keys(group.items).find(e => e.toLowerCase() === actualValue.toLowerCase());
|
||||||
|
|
||||||
|
if (found) {
|
||||||
|
const prev = group.items[found];
|
||||||
|
const prevCount = prev.count + 1;
|
||||||
|
delete group.items[found];
|
||||||
|
group.items[actualValue] = { count: prevCount, lastUsed: now };
|
||||||
|
} else {
|
||||||
|
group.items[actualValue] = {
|
||||||
|
count: (group.items[actualValue]?.count ?? 0) + 1,
|
||||||
|
lastUsed: now
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
setSuggestions(clone);
|
||||||
|
}
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
setDate(getMonth());
|
||||||
|
fetchAutoSuggestions();
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const commitData = (next: Data<Date>[]) => {
|
||||||
|
props.storage.save(next, month);
|
||||||
|
setPast(p => [...p, data]);
|
||||||
|
setFuture([]);
|
||||||
|
setData(next);
|
||||||
|
};
|
||||||
|
|
||||||
|
const undo = useCallback(() => {
|
||||||
|
if (past.length === 0) return;
|
||||||
|
const previous = past[past.length - 1];
|
||||||
|
setPast(p => p.slice(0, -1));
|
||||||
|
setFuture(f => [...f, data]);
|
||||||
|
props.storage.save(previous, month);
|
||||||
|
setData(previous);
|
||||||
|
}, [past, data, month, props.storage]);
|
||||||
|
|
||||||
|
const redo = useCallback(() => {
|
||||||
|
if (future.length === 0) return;
|
||||||
|
const next = future[future.length - 1];
|
||||||
|
setFuture(f => f.slice(0, -1));
|
||||||
|
setPast(p => [...p, data]);
|
||||||
|
props.storage.save(next, month);
|
||||||
|
setData(next);
|
||||||
|
}, [future, data, month, props.storage]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const onKey = (e: KeyboardEvent) => {
|
||||||
|
if (!(e.ctrlKey || e.metaKey)) return;
|
||||||
|
const target = e.target as HTMLElement | null;
|
||||||
|
const tag = target?.tagName;
|
||||||
|
if (tag === "INPUT" || tag === "TEXTAREA" || tag === "SELECT" || target?.isContentEditable) return;
|
||||||
|
const key = e.key.toLowerCase();
|
||||||
|
if (key === "z" && e.shiftKey) { e.preventDefault(); redo(); }
|
||||||
|
else if (key === "z") { e.preventDefault(); undo(); }
|
||||||
|
else if (key === "y") { e.preventDefault(); redo(); }
|
||||||
|
};
|
||||||
|
window.addEventListener("keydown", onKey);
|
||||||
|
return () => window.removeEventListener("keydown", onKey);
|
||||||
|
}, [undo, redo]);
|
||||||
|
|
||||||
|
const summary = useMemo(() => {
|
||||||
|
let income = 0;
|
||||||
|
let expense = 0;
|
||||||
|
for (const entry of data) {
|
||||||
|
if (entry.amount > 0) income += entry.amount;
|
||||||
|
else expense += entry.amount;
|
||||||
|
}
|
||||||
|
return { income, expense: Math.abs(expense), net: income + expense };
|
||||||
|
}, [data]);
|
||||||
|
|
||||||
|
if (error) {
|
||||||
|
return <Div>
|
||||||
|
<Message role="alert">
|
||||||
|
<ErrorTitle>Something went wrong</ErrorTitle>
|
||||||
|
<p>{error}</p>
|
||||||
|
<button onClick={() => setDate(month || getMonth())}>Try again</button>
|
||||||
|
</Message>
|
||||||
|
</Div>
|
||||||
|
}
|
||||||
|
|
||||||
|
if (loading) {
|
||||||
|
return <Div>
|
||||||
|
<Message role="status">Loading…</Message>
|
||||||
|
</Div>
|
||||||
|
}
|
||||||
|
|
||||||
|
return <Div>
|
||||||
|
<Header>
|
||||||
|
<Brand>
|
||||||
|
<Title>Flog</Title>
|
||||||
|
<MonthBadge>{month}</MonthBadge>
|
||||||
|
</Brand>
|
||||||
|
<Controls>
|
||||||
|
<MonthInput aria-label="Select month" value={month} onChange={(d: ChangeEvent<HTMLInputElement>) => setDate(d.target.value)} />
|
||||||
|
<button onClick={undo} disabled={past.length === 0} aria-label="Undo" title="Undo (Ctrl+Z)">Undo</button>
|
||||||
|
<button onClick={redo} disabled={future.length === 0} aria-label="Redo" title="Redo (Ctrl+Y)">Redo</button>
|
||||||
|
<button onClick={() => setSuggestionsOpen(true)}>Suggestions</button>
|
||||||
|
<button onClick={() => props.logout()}>Logout</button>
|
||||||
|
</Controls>
|
||||||
|
</Header>
|
||||||
|
|
||||||
|
<Main>
|
||||||
|
<SummaryGrid>
|
||||||
|
<StatCard hero>
|
||||||
|
<StatLabel>Balance</StatLabel>
|
||||||
|
<StatValue tone={summary.net > 0 ? "income" : summary.net < 0 ? "expense" : "neutral"}>
|
||||||
|
{formatSigned(summary.net)}
|
||||||
|
</StatValue>
|
||||||
|
</StatCard>
|
||||||
|
<StatCard>
|
||||||
|
<StatLabel>Income</StatLabel>
|
||||||
|
<StatValue tone="income">+{fmtMoney(summary.income)}</StatValue>
|
||||||
|
</StatCard>
|
||||||
|
<StatCard>
|
||||||
|
<StatLabel>Expenses</StatLabel>
|
||||||
|
<StatValue tone="expense">-{fmtMoney(summary.expense)}</StatValue>
|
||||||
|
</StatCard>
|
||||||
|
</SummaryGrid>
|
||||||
|
|
||||||
|
{data.length === 0 && (
|
||||||
|
<EmptyHint>
|
||||||
|
No entries for this month yet. Add your first transaction below.
|
||||||
|
</EmptyHint>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<Table
|
||||||
|
data={data}
|
||||||
|
month={month}
|
||||||
|
autosuggestions={suggestions}
|
||||||
|
updateAutoSuggestions={addSuggestions}
|
||||||
|
modifySuggestions={modifySuggestions}
|
||||||
|
onChange={commitData}/>
|
||||||
|
|
||||||
|
<CategoryGraphs data={data} />
|
||||||
|
</Main>
|
||||||
|
|
||||||
|
{suggestionsOpen && (
|
||||||
|
<SuggestionsManager
|
||||||
|
suggestions={suggestions}
|
||||||
|
onSave={setSuggestions}
|
||||||
|
onClose={() => setSuggestionsOpen(false)} />
|
||||||
|
)}
|
||||||
|
</Div>;
|
||||||
|
}
|
||||||
+169
@@ -0,0 +1,169 @@
|
|||||||
|
export interface Data<T> {
|
||||||
|
date: T;
|
||||||
|
name: string;
|
||||||
|
location: string;
|
||||||
|
category: string;
|
||||||
|
amount: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type DataKeys = keyof Omit<Data<null>, 'date'>;
|
||||||
|
|
||||||
|
export interface SuggestionEntry {
|
||||||
|
count: number;
|
||||||
|
lastUsed: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface SuggestionGroup {
|
||||||
|
items: Record<string, SuggestionEntry>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type Suggestions = {
|
||||||
|
[K in DataKeys]?: SuggestionGroup;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type LegacySuggestions = {
|
||||||
|
[K in DataKeys]?: string[];
|
||||||
|
};
|
||||||
|
|
||||||
|
function isGroup(value: SuggestionGroup | string[] | undefined | null): value is SuggestionGroup {
|
||||||
|
return !!value && typeof value === "object" && !Array.isArray(value) && value.items !== undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function migrateSuggestions(suggestions: Suggestions | LegacySuggestions | null | undefined): Suggestions {
|
||||||
|
if (!suggestions) return {};
|
||||||
|
const result: Suggestions = {};
|
||||||
|
(Object.keys(suggestions) as DataKeys[]).forEach(key => {
|
||||||
|
const value = suggestions[key];
|
||||||
|
if (isGroup(value)) {
|
||||||
|
result[key] = value;
|
||||||
|
} else if (Array.isArray(value)) {
|
||||||
|
const items: Record<string, SuggestionEntry> = {};
|
||||||
|
value.forEach(entry => {
|
||||||
|
if (typeof entry === "string" && entry.trim()) {
|
||||||
|
const normalized = entry.trim();
|
||||||
|
if (items[normalized]) {
|
||||||
|
items[normalized].count += 1;
|
||||||
|
} else {
|
||||||
|
items[normalized] = { count: 1, lastUsed: Date.now() };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
result[key] = { items };
|
||||||
|
}
|
||||||
|
});
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function suggestionsToList(suggestions: Suggestions, key: DataKeys): string[] {
|
||||||
|
const group = suggestions[key];
|
||||||
|
if (!group) return [];
|
||||||
|
return Object.keys(group.items)
|
||||||
|
.filter(name => {
|
||||||
|
const entry = group.items[name];
|
||||||
|
return entry.lastUsed >= Date.now() - 90 * 24 * 60 * 60 * 1000;
|
||||||
|
})
|
||||||
|
.sort((a, b) => group.items[b].count - group.items[a].count || group.items[b].lastUsed - group.items[a].lastUsed);
|
||||||
|
}
|
||||||
|
|
||||||
|
export class WebsiteStorage {
|
||||||
|
private readonly STORAGE_KEY_USERNAME = "username";
|
||||||
|
private readonly STORAGE_KEY_PASSWORD = "password";
|
||||||
|
private _username = localStorage.getItem(this.STORAGE_KEY_USERNAME) || "";
|
||||||
|
private _password = localStorage.getItem(this.STORAGE_KEY_PASSWORD) || "";
|
||||||
|
|
||||||
|
constructor(private baseUrl = "") {
|
||||||
|
this.baseUrl = baseUrl.endsWith("/") ? baseUrl.substring(0, baseUrl.length - 1) : baseUrl;
|
||||||
|
};
|
||||||
|
|
||||||
|
private encodeToBase64(str: string) {
|
||||||
|
return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, (match, p1) => String.fromCharCode(parseInt(p1, 16))));
|
||||||
|
}
|
||||||
|
private createBasicAuthHeader(username: string, password: string) {
|
||||||
|
const authString = `${username}:${password}`;
|
||||||
|
const base64AuthString = this.encodeToBase64(authString);
|
||||||
|
return `Basic ${base64AuthString}`;
|
||||||
|
}
|
||||||
|
get username() {
|
||||||
|
return this._username;
|
||||||
|
}
|
||||||
|
set username(value: string) {
|
||||||
|
localStorage.setItem(this.STORAGE_KEY_USERNAME, value);
|
||||||
|
this._username = value;
|
||||||
|
}
|
||||||
|
get password() {
|
||||||
|
return this._password;
|
||||||
|
}
|
||||||
|
set password(value: string) {
|
||||||
|
localStorage.setItem(this.STORAGE_KEY_PASSWORD, value);
|
||||||
|
this._password = value;
|
||||||
|
}
|
||||||
|
async save(data: Data<Date>[], date: string) {
|
||||||
|
const toSave: Data<string>[] = []
|
||||||
|
for (const { name, amount, category, date, location } of data) {
|
||||||
|
toSave.push({
|
||||||
|
name,
|
||||||
|
amount,
|
||||||
|
category,
|
||||||
|
location,
|
||||||
|
date: date.toISOString(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
await this.fetch(date, "POST", toSave);
|
||||||
|
}
|
||||||
|
async load(date: string): Promise<Data<Date>[] | undefined> {
|
||||||
|
const data: Data<Date>[] = [];
|
||||||
|
const dataStr = await this.fetch<Data<string>[]>(date, "GET");
|
||||||
|
|
||||||
|
if (!dataStr)
|
||||||
|
return undefined;
|
||||||
|
|
||||||
|
for (const { name, amount, category, date, location } of dataStr) {
|
||||||
|
data.push({
|
||||||
|
name,
|
||||||
|
amount,
|
||||||
|
category,
|
||||||
|
location,
|
||||||
|
date: new Date(date),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return data;
|
||||||
|
}
|
||||||
|
|
||||||
|
async getAutoSuggestions(): Promise<Suggestions> {
|
||||||
|
return migrateSuggestions((await this.fetch<Suggestions>("/suggestions", "GET")) || {});
|
||||||
|
}
|
||||||
|
async setAutoSuggestions(suggestions: Suggestions) {
|
||||||
|
return (await this.fetch<Suggestions>("/suggestions", "POST", migrateSuggestions(suggestions))) || {};
|
||||||
|
}
|
||||||
|
private async fetch<T>(url: string, method: string, data?: object | string): Promise<T | undefined> {
|
||||||
|
const headers: HeadersInit = {
|
||||||
|
authorization: this.createBasicAuthHeader(this._username, this._password)
|
||||||
|
};
|
||||||
|
|
||||||
|
headers["content-type"] = "application/json";
|
||||||
|
|
||||||
|
const result = await fetch(`${this.baseUrl}/api/${url}`, {
|
||||||
|
method,
|
||||||
|
body: data ? new TextEncoder().encode(typeof data === "string" ? data : JSON.stringify(data)) : undefined,
|
||||||
|
headers
|
||||||
|
});
|
||||||
|
if (result.ok) {
|
||||||
|
const buffer = await result.arrayBuffer();
|
||||||
|
const text = new TextDecoder('utf-8').decode(new Uint8Array(buffer));
|
||||||
|
return JSON.parse(text);
|
||||||
|
} else {
|
||||||
|
if(result.status === 404) {
|
||||||
|
return undefined;
|
||||||
|
} else {
|
||||||
|
throw new Error(`Error: ${result.status}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
hasAccount() {
|
||||||
|
return this.fetch<boolean>("check", "GET")
|
||||||
|
}
|
||||||
|
createAccount() {
|
||||||
|
return this.fetch("created", "POST", new Date().toISOString());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,315 @@
|
|||||||
|
import { useEffect, useState } from "react";
|
||||||
|
import type { ChangeEvent, KeyboardEvent as ReactKeyboardEvent, MouseEvent as ReactMouseEvent } from "react";
|
||||||
|
import styled from "styled-components";
|
||||||
|
import { DataKeys, SuggestionGroup, Suggestions, suggestionsToList } from "./Storage";
|
||||||
|
import { theme } from "./theme";
|
||||||
|
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
|
||||||
|
import { faCheck, faPen, faPlus, faTimes } from "@fortawesome/free-solid-svg-icons";
|
||||||
|
|
||||||
|
const KEYS = ["name", "location", "category"] as const;
|
||||||
|
type SuggestKey = typeof KEYS[number];
|
||||||
|
|
||||||
|
const Overlay = styled.div`
|
||||||
|
position: fixed;
|
||||||
|
inset: 0;
|
||||||
|
z-index: 50;
|
||||||
|
background: rgba(0, 0, 0, 0.6);
|
||||||
|
display: flex;
|
||||||
|
align-items: flex-start;
|
||||||
|
justify-content: center;
|
||||||
|
padding: ${theme.spacing.xl}px;
|
||||||
|
overflow-y: auto;
|
||||||
|
|
||||||
|
@media (max-width: ${theme.breakpoints.mobile}) {
|
||||||
|
padding: ${theme.spacing.md}px;
|
||||||
|
}
|
||||||
|
`;
|
||||||
|
|
||||||
|
const Card = styled.div`
|
||||||
|
width: 100%;
|
||||||
|
max-width: 520px;
|
||||||
|
background: ${theme.colors.surface};
|
||||||
|
border: 1px solid ${theme.colors.border};
|
||||||
|
border-radius: ${theme.radius.lg}px;
|
||||||
|
padding: ${theme.spacing.xl}px;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: ${theme.spacing.lg}px;
|
||||||
|
|
||||||
|
@media (max-width: ${theme.breakpoints.mobile}) {
|
||||||
|
padding: ${theme.spacing.lg}px;
|
||||||
|
}
|
||||||
|
`;
|
||||||
|
|
||||||
|
const Header = styled.div`
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: ${theme.spacing.sm}px;
|
||||||
|
`;
|
||||||
|
|
||||||
|
const Title = styled.h2`
|
||||||
|
margin: 0;
|
||||||
|
font-size: ${theme.font.sizes.lg};
|
||||||
|
`;
|
||||||
|
|
||||||
|
const Section = styled.section`
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: ${theme.spacing.sm}px;
|
||||||
|
border-top: 1px solid ${theme.colors.border};
|
||||||
|
padding-top: ${theme.spacing.md}px;
|
||||||
|
`;
|
||||||
|
|
||||||
|
const SectionTitle = styled.h3`
|
||||||
|
margin: 0;
|
||||||
|
font-size: ${theme.font.sizes.xs};
|
||||||
|
font-weight: 700;
|
||||||
|
text-transform: uppercase;
|
||||||
|
letter-spacing: 0.08em;
|
||||||
|
color: ${theme.colors.textMuted};
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
`;
|
||||||
|
|
||||||
|
const Count = styled.span`
|
||||||
|
color: ${theme.colors.textFaint};
|
||||||
|
font-weight: 400;
|
||||||
|
`;
|
||||||
|
|
||||||
|
const ItemRow = styled.div`
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: ${theme.spacing.sm}px;
|
||||||
|
`;
|
||||||
|
|
||||||
|
const ItemName = styled.span`
|
||||||
|
flex: 1;
|
||||||
|
min-width: 0;
|
||||||
|
overflow: hidden;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
white-space: nowrap;
|
||||||
|
`;
|
||||||
|
|
||||||
|
const UsingBadge = styled.span`
|
||||||
|
font-variant-numeric: tabular-nums;
|
||||||
|
font-size: ${theme.font.sizes.xs};
|
||||||
|
color: ${theme.colors.textFaint};
|
||||||
|
white-space: nowrap;
|
||||||
|
min-width: 40px;
|
||||||
|
text-align: right;
|
||||||
|
`;
|
||||||
|
|
||||||
|
const IconButton = styled.button`
|
||||||
|
min-width: 34px;
|
||||||
|
min-height: 34px;
|
||||||
|
padding: 6px;
|
||||||
|
background: ${theme.colors.surfaceAlt};
|
||||||
|
border: 1px solid ${theme.colors.border};
|
||||||
|
border-radius: ${theme.radius.sm}px;
|
||||||
|
color: ${theme.colors.textMuted};
|
||||||
|
line-height: 1;
|
||||||
|
|
||||||
|
&:hover {
|
||||||
|
color: ${theme.colors.text};
|
||||||
|
}
|
||||||
|
|
||||||
|
&.danger {
|
||||||
|
color: #ffb3a7;
|
||||||
|
}
|
||||||
|
`;
|
||||||
|
|
||||||
|
const RowInput = styled.input`
|
||||||
|
width: 100%;
|
||||||
|
`;
|
||||||
|
|
||||||
|
const AddRow = styled.div`
|
||||||
|
display: flex;
|
||||||
|
gap: ${theme.spacing.sm}px;
|
||||||
|
`;
|
||||||
|
|
||||||
|
const Hint = styled.p`
|
||||||
|
margin: 0;
|
||||||
|
font-size: ${theme.font.sizes.xs};
|
||||||
|
color: ${theme.colors.textFaint};
|
||||||
|
`;
|
||||||
|
|
||||||
|
const Done = styled.button`
|
||||||
|
background: ${theme.colors.accent};
|
||||||
|
border-color: ${theme.colors.accent};
|
||||||
|
color: #0b0d10;
|
||||||
|
font-weight: 600;
|
||||||
|
padding: 12px 16px;
|
||||||
|
border-radius: ${theme.radius.md}px;
|
||||||
|
`;
|
||||||
|
|
||||||
|
const Footer = styled.div`
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: ${theme.spacing.md}px;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
`;
|
||||||
|
|
||||||
|
function emptyGroup(): SuggestionGroup {
|
||||||
|
return { items: {} };
|
||||||
|
}
|
||||||
|
|
||||||
|
function cloneSuggestions(suggestions: Suggestions): Suggestions {
|
||||||
|
const clone: Suggestions = {};
|
||||||
|
for (const key of Object.keys(suggestions) as DataKeys[]) {
|
||||||
|
const group = suggestions[key];
|
||||||
|
if (group) clone[key] = { items: { ...group.items } };
|
||||||
|
}
|
||||||
|
return clone;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function SuggestionsManager({ suggestions, onSave, onClose }: {
|
||||||
|
suggestions: Suggestions;
|
||||||
|
onSave: (next: Suggestions) => void;
|
||||||
|
onClose: () => void;
|
||||||
|
}) {
|
||||||
|
const [draft, setDraft] = useState<Suggestions>(() => cloneSuggestions(suggestions));
|
||||||
|
const [newValue, setNewValue] = useState<Record<SuggestKey, string>>({ name: "", location: "", category: "" });
|
||||||
|
const [editing, setEditing] = useState<{ key: SuggestKey; value: string } | null>(null);
|
||||||
|
const [editValue, setEditValue] = useState("");
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
setDraft(cloneSuggestions(suggestions));
|
||||||
|
}, [suggestions]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const onKey = (e: KeyboardEvent) => {
|
||||||
|
if (e.key === "Escape") onClose();
|
||||||
|
};
|
||||||
|
window.addEventListener("keydown", onKey);
|
||||||
|
return () => window.removeEventListener("keydown", onKey);
|
||||||
|
}, [onClose]);
|
||||||
|
|
||||||
|
const commit = (next: Suggestions) => {
|
||||||
|
setDraft(next);
|
||||||
|
onSave(next);
|
||||||
|
};
|
||||||
|
|
||||||
|
const add = (key: SuggestKey) => {
|
||||||
|
const value = newValue[key].trim();
|
||||||
|
if (!value) return;
|
||||||
|
const next = cloneSuggestions(draft);
|
||||||
|
const group = next[key] ?? emptyGroup();
|
||||||
|
const existing = Object.keys(group.items).find(k => k.toLowerCase() === value.toLowerCase());
|
||||||
|
if (existing) {
|
||||||
|
group.items[existing] = { ...group.items[existing], count: group.items[existing].count + 1, lastUsed: Date.now() };
|
||||||
|
} else {
|
||||||
|
group.items[value] = { count: 1, lastUsed: Date.now() };
|
||||||
|
}
|
||||||
|
next[key] = group;
|
||||||
|
commit(next);
|
||||||
|
setNewValue(prev => ({ ...prev, [key]: "" }));
|
||||||
|
};
|
||||||
|
|
||||||
|
const startEdit = (key: SuggestKey, value: string) => {
|
||||||
|
setEditing({ key, value });
|
||||||
|
setEditValue(value);
|
||||||
|
};
|
||||||
|
|
||||||
|
const confirmRename = () => {
|
||||||
|
if (!editing) return;
|
||||||
|
const to = editValue.trim();
|
||||||
|
const from = editing.value;
|
||||||
|
const key = editing.key;
|
||||||
|
setEditing(null);
|
||||||
|
if (!to || to === from) return;
|
||||||
|
const next = cloneSuggestions(draft);
|
||||||
|
const group = next[key]!;
|
||||||
|
const entry = group.items[from];
|
||||||
|
if (entry) {
|
||||||
|
delete group.items[from];
|
||||||
|
if (group.items[to]) {
|
||||||
|
group.items[to].count += entry.count;
|
||||||
|
group.items[to].lastUsed = Math.max(group.items[to].lastUsed, entry.lastUsed);
|
||||||
|
} else {
|
||||||
|
group.items[to] = entry;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
next[key] = group;
|
||||||
|
commit(next);
|
||||||
|
};
|
||||||
|
|
||||||
|
const remove = (key: SuggestKey, value: string) => {
|
||||||
|
const next = cloneSuggestions(draft);
|
||||||
|
const group = next[key];
|
||||||
|
if (group) {
|
||||||
|
delete group.items[value];
|
||||||
|
next[key] = group;
|
||||||
|
}
|
||||||
|
commit(next);
|
||||||
|
};
|
||||||
|
|
||||||
|
return <Overlay onClick={onClose} role="presentation">
|
||||||
|
<Card role="dialog" aria-modal="true" aria-label="Manage suggestions" onClick={(ev: ReactMouseEvent<HTMLDivElement>) => ev.stopPropagation()}>
|
||||||
|
<Header>
|
||||||
|
<Title>Suggestions</Title>
|
||||||
|
<IconButton onClick={onClose} aria-label="Close"><FontAwesomeIcon icon={faTimes} /></IconButton>
|
||||||
|
</Header>
|
||||||
|
|
||||||
|
{KEYS.map(key => {
|
||||||
|
const list = suggestionsToList(draft, key);
|
||||||
|
const group = draft[key];
|
||||||
|
const count = group ? Object.keys(group.items).length : 0;
|
||||||
|
return <Section key={key}>
|
||||||
|
<SectionTitle>
|
||||||
|
{key}
|
||||||
|
<Count>{count}</Count>
|
||||||
|
</SectionTitle>
|
||||||
|
|
||||||
|
{list.length === 0 ? (
|
||||||
|
<Hint>No {key} suggestions yet. Add one below.</Hint>
|
||||||
|
) : list.map(name => (
|
||||||
|
editing && editing.key === key && editing.value === name ? (
|
||||||
|
<ItemRow key={name}>
|
||||||
|
<RowInput autoFocus value={editValue}
|
||||||
|
aria-label={`Rename ${key} suggestion`}
|
||||||
|
onChange={(e: ChangeEvent<HTMLInputElement>) => setEditValue(e.target.value)}
|
||||||
|
onKeyDown={(ev: ReactKeyboardEvent<HTMLInputElement>) => {
|
||||||
|
if (ev.key === "Enter") confirmRename();
|
||||||
|
if (ev.key === "Escape") setEditing(null);
|
||||||
|
}} />
|
||||||
|
<IconButton onClick={confirmRename} aria-label="Save rename"><FontAwesomeIcon icon={faCheck} /></IconButton>
|
||||||
|
<IconButton className="danger" onClick={() => setEditing(null)} aria-label="Cancel rename"><FontAwesomeIcon icon={faTimes} /></IconButton>
|
||||||
|
</ItemRow>
|
||||||
|
) : (
|
||||||
|
<ItemRow key={name}>
|
||||||
|
<ItemName title={name}>{name}</ItemName>
|
||||||
|
<UsingBadge aria-label={`used ${group?.items[name].count ?? 1} times`}>
|
||||||
|
×{group?.items[name].count ?? 1}
|
||||||
|
</UsingBadge>
|
||||||
|
<IconButton onClick={() => startEdit(key, name)} aria-label={`Rename ${name}`}><FontAwesomeIcon icon={faPen} /></IconButton>
|
||||||
|
<IconButton className="danger" onClick={() => remove(key, name)} aria-label={`Delete ${name}`}><FontAwesomeIcon icon={faTimes} /></IconButton>
|
||||||
|
</ItemRow>
|
||||||
|
)
|
||||||
|
))}
|
||||||
|
|
||||||
|
<AddRow>
|
||||||
|
<RowInput placeholder={`Add ${key}…`}
|
||||||
|
value={newValue[key] ?? ""}
|
||||||
|
aria-label={`Add new ${key} suggestion`}
|
||||||
|
onChange={(e: ChangeEvent<HTMLInputElement>) => setNewValue(prev => ({ ...prev, [key]: e.target.value }))}
|
||||||
|
onKeyDown={(ev: ReactKeyboardEvent<HTMLInputElement>) => {
|
||||||
|
if (ev.key === "Enter") {
|
||||||
|
ev.preventDefault();
|
||||||
|
add(key);
|
||||||
|
}
|
||||||
|
}} />
|
||||||
|
<IconButton onClick={() => add(key)} aria-label="Add suggestion"><FontAwesomeIcon icon={faPlus} /></IconButton>
|
||||||
|
</AddRow>
|
||||||
|
</Section>;
|
||||||
|
})}
|
||||||
|
|
||||||
|
<Footer>
|
||||||
|
<Hint>Listed most-used first.</Hint>
|
||||||
|
<Done onClick={onClose}>Done</Done>
|
||||||
|
</Footer>
|
||||||
|
</Card>
|
||||||
|
</Overlay>;
|
||||||
|
}
|
||||||
+641
@@ -0,0 +1,641 @@
|
|||||||
|
// Assuming you have `styled-components` installed
|
||||||
|
import styled from "styled-components";
|
||||||
|
import { useEffect, useLayoutEffect, useRef, useState } from "react";
|
||||||
|
import { Data, DataKeys, suggestionsToList, Suggestions } from "./Storage";
|
||||||
|
import { amountTone, formatSigned, getDate } from "./utils";
|
||||||
|
import { evaluateMathExpression } from "./math-expression";
|
||||||
|
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
|
||||||
|
import { faCheck, faTimes } from "@fortawesome/free-solid-svg-icons";
|
||||||
|
import { theme } from "./theme";
|
||||||
|
|
||||||
|
type SortType = 'date' | 'name' | 'location' | 'category' | 'amount';
|
||||||
|
|
||||||
|
type EditField = "date" | "name" | "location" | "category" | "amount";
|
||||||
|
|
||||||
|
interface EditingState {
|
||||||
|
field: EditField;
|
||||||
|
draft: string;
|
||||||
|
}
|
||||||
|
interface Sort {
|
||||||
|
type: SortType;
|
||||||
|
acs: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
const HEADERS: SortType[] = ["date", "name", "location", "category", "amount"];
|
||||||
|
|
||||||
|
interface TableProps {
|
||||||
|
month: string;
|
||||||
|
data: Data<Date>[];
|
||||||
|
onChange: (newData: Data<Date>[]) => void;
|
||||||
|
autosuggestions: Suggestions;
|
||||||
|
updateAutoSuggestions: (values: { key: DataKeys, value: string }[]) => void;
|
||||||
|
modifySuggestions: (key: DataKeys, value: string[]) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
const TableWrapper = styled.div`
|
||||||
|
background: ${theme.colors.surface};
|
||||||
|
border: 1px solid ${theme.colors.border};
|
||||||
|
border-radius: ${theme.radius.lg}px;
|
||||||
|
overflow: hidden;
|
||||||
|
`;
|
||||||
|
|
||||||
|
const TableScroll = styled.div`
|
||||||
|
overflow-x: auto;
|
||||||
|
`;
|
||||||
|
|
||||||
|
const StyledTable = styled.table`
|
||||||
|
width: 100%;
|
||||||
|
border-collapse: collapse;
|
||||||
|
color: ${theme.colors.text};
|
||||||
|
font-size: 0.9375rem;
|
||||||
|
|
||||||
|
th, td {
|
||||||
|
padding: ${theme.spacing.sm}px ${theme.spacing.md}px;
|
||||||
|
text-align: left;
|
||||||
|
vertical-align: middle;
|
||||||
|
}
|
||||||
|
|
||||||
|
thead th {
|
||||||
|
background: ${theme.colors.surfaceAlt};
|
||||||
|
color: ${theme.colors.textMuted};
|
||||||
|
font-size: ${theme.font.sizes.xs};
|
||||||
|
font-weight: 700;
|
||||||
|
text-transform: uppercase;
|
||||||
|
letter-spacing: 0.06em;
|
||||||
|
border-bottom: 2px solid ${theme.colors.borderStrong};
|
||||||
|
cursor: pointer;
|
||||||
|
user-select: none;
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
tbody td {
|
||||||
|
border-bottom: 1px solid ${theme.colors.border};
|
||||||
|
}
|
||||||
|
|
||||||
|
tbody tr.frozen td {
|
||||||
|
background: rgba(91, 157, 255, 0.12);
|
||||||
|
box-shadow: inset 3px 0 0 ${theme.colors.accent};
|
||||||
|
}
|
||||||
|
|
||||||
|
tbody tr:last-child td {
|
||||||
|
border-bottom: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
th.amount, td.amount {
|
||||||
|
text-align: right;
|
||||||
|
}
|
||||||
|
|
||||||
|
.actions {
|
||||||
|
text-align: right;
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
.actions button {
|
||||||
|
margin-right: ${theme.spacing.xs + 2}px;
|
||||||
|
min-width: 36px;
|
||||||
|
min-height: 36px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.actions button:last-child {
|
||||||
|
margin-right: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
button {
|
||||||
|
background: ${theme.colors.surfaceAlt};
|
||||||
|
border: 1px solid ${theme.colors.border};
|
||||||
|
border-radius: ${theme.radius.sm}px;
|
||||||
|
color: ${theme.colors.text};
|
||||||
|
padding: ${theme.spacing.sm}px ${theme.spacing.md}px;
|
||||||
|
min-height: 36px;
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
|
||||||
|
button:hover {
|
||||||
|
background: ${theme.colors.borderStrong};
|
||||||
|
}
|
||||||
|
|
||||||
|
button.danger {
|
||||||
|
background: ${theme.colors.dangerBg};
|
||||||
|
border-color: ${theme.colors.dangerBorder};
|
||||||
|
color: #ffb3a7;
|
||||||
|
}
|
||||||
|
|
||||||
|
button.primary {
|
||||||
|
background: ${theme.colors.accent};
|
||||||
|
border-color: ${theme.colors.accent};
|
||||||
|
color: #0b0d10;
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
|
|
||||||
|
input {
|
||||||
|
width: 100%;
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
`;
|
||||||
|
|
||||||
|
const Amount = styled.span<{ tone: "income" | "expense" | "neutral" }>`
|
||||||
|
font-variant-numeric: tabular-nums;
|
||||||
|
font-weight: 600;
|
||||||
|
white-space: nowrap;
|
||||||
|
color: ${p =>
|
||||||
|
p.tone === "income" ? theme.colors.income
|
||||||
|
: p.tone === "expense" ? theme.colors.expense
|
||||||
|
: theme.colors.text};
|
||||||
|
`;
|
||||||
|
|
||||||
|
const TotalRow = styled.tr`
|
||||||
|
background: ${theme.colors.surfaceAlt};
|
||||||
|
|
||||||
|
td {
|
||||||
|
border-top: 2px solid ${theme.colors.borderStrong};
|
||||||
|
padding-top: ${theme.spacing.md}px;
|
||||||
|
padding-bottom: ${theme.spacing.md}px;
|
||||||
|
}
|
||||||
|
|
||||||
|
td.totals-label {
|
||||||
|
text-align: right;
|
||||||
|
color: ${theme.colors.textMuted};
|
||||||
|
font-weight: 700;
|
||||||
|
text-transform: uppercase;
|
||||||
|
letter-spacing: 0.06em;
|
||||||
|
font-size: ${theme.font.sizes.xs};
|
||||||
|
}
|
||||||
|
`;
|
||||||
|
|
||||||
|
const CellButton = styled.button`
|
||||||
|
border: none;
|
||||||
|
background: transparent;
|
||||||
|
border-radius: ${theme.radius.sm}px;
|
||||||
|
padding: ${theme.spacing.xs}px ${theme.spacing.sm}px;
|
||||||
|
min-height: 0;
|
||||||
|
width: 100%;
|
||||||
|
text-align: inherit;
|
||||||
|
color: inherit;
|
||||||
|
font: inherit;
|
||||||
|
cursor: text;
|
||||||
|
|
||||||
|
&:hover {
|
||||||
|
background: ${theme.colors.surfaceAlt};
|
||||||
|
}
|
||||||
|
|
||||||
|
&:active {
|
||||||
|
transform: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
&:focus-visible {
|
||||||
|
outline: 2px solid ${theme.colors.focusRing};
|
||||||
|
outline-offset: -2px;
|
||||||
|
background: ${theme.colors.surfaceAlt};
|
||||||
|
}
|
||||||
|
`;
|
||||||
|
|
||||||
|
const TableToolbar = styled.div`
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: flex-end;
|
||||||
|
gap: ${theme.spacing.sm}px;
|
||||||
|
padding: ${theme.spacing.sm}px ${theme.spacing.md}px;
|
||||||
|
border-bottom: 1px solid ${theme.colors.border};
|
||||||
|
color: ${theme.colors.textFaint};
|
||||||
|
font-size: ${theme.font.sizes.xs};
|
||||||
|
`;
|
||||||
|
|
||||||
|
const autoOptions = (list?: string[]) => list?.map((x, idx) => <option key={`${x}-${idx}`} value={x} />);
|
||||||
|
|
||||||
|
const SORT_FREEZE_MS = 1000;
|
||||||
|
const FLIP_MS = 400;
|
||||||
|
|
||||||
|
const rowIds = new WeakMap<Data<Date>, string>();
|
||||||
|
let rowIdSeq = 0;
|
||||||
|
function rowId(row: Data<Date>): string {
|
||||||
|
let id = rowIds.get(row);
|
||||||
|
if (!id) {
|
||||||
|
id = `r${++rowIdSeq}`;
|
||||||
|
rowIds.set(row, id);
|
||||||
|
}
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
|
||||||
|
function sameRows(a: Data<Date>[], b: Data<Date>[]): boolean {
|
||||||
|
if (a.length !== b.length) return false;
|
||||||
|
return a.every(r => b.includes(r));
|
||||||
|
}
|
||||||
|
|
||||||
|
function defaultAddDate(month: string) {
|
||||||
|
const today = getDate();
|
||||||
|
if (/^\d{4}-\d{2}$/.test(month)) {
|
||||||
|
return today.startsWith(month) ? today : `${month}-01`;
|
||||||
|
}
|
||||||
|
return today;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function Table({ month, data, onChange, autosuggestions, updateAutoSuggestions, modifySuggestions }: TableProps) {
|
||||||
|
const [snapShot, setSnapshot] = useState(data);
|
||||||
|
const [copy, setCopy] = useState(data);
|
||||||
|
const [sortBy, setSortBy] = useState<Sort>({type: "date", acs: true});
|
||||||
|
const [frozenId, setFrozenId] = useState<string | null>(null);
|
||||||
|
|
||||||
|
const sortTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||||
|
const prevTops = useRef<Map<string, number>>(new Map());
|
||||||
|
const rowRefs = useRef<Map<string, HTMLTableRowElement | null>>(new Map());
|
||||||
|
|
||||||
|
const captureTops = () => {
|
||||||
|
const map = new Map<string, number>();
|
||||||
|
rowRefs.current.forEach((el, id) => {
|
||||||
|
if (el) map.set(id, el.getBoundingClientRect().top);
|
||||||
|
});
|
||||||
|
prevTops.current = map;
|
||||||
|
};
|
||||||
|
|
||||||
|
const sortByAction = (type: SortType, acs: boolean, copy2 = copy, keepFrozen = false) => {
|
||||||
|
if (sortTimer.current) {
|
||||||
|
clearTimeout(sortTimer.current);
|
||||||
|
sortTimer.current = null;
|
||||||
|
}
|
||||||
|
if (!keepFrozen) setFrozenId(null);
|
||||||
|
captureTops();
|
||||||
|
const sorted = [...copy2];
|
||||||
|
sorted.sort((a, b) => {
|
||||||
|
if (a[type] > b[type]) return acs ? 1 : -1;
|
||||||
|
if (a[type] < b[type]) return acs ? -1 : 1;
|
||||||
|
return 0;
|
||||||
|
});
|
||||||
|
setCopy(sorted);
|
||||||
|
setSortBy({ type, acs });
|
||||||
|
};
|
||||||
|
|
||||||
|
const sync = (next: Data<Date>[], freezeId?: string) => {
|
||||||
|
onChange([...next].sort((a, b) => a.date > b.date ? 1 : -1));
|
||||||
|
setCopy(next);
|
||||||
|
if (freezeId) {
|
||||||
|
setFrozenId(freezeId);
|
||||||
|
if (sortTimer.current) clearTimeout(sortTimer.current);
|
||||||
|
sortTimer.current = setTimeout(() => {
|
||||||
|
sortTimer.current = null;
|
||||||
|
sortByAction(sortBy.type, sortBy.acs, next, true);
|
||||||
|
setTimeout(() => setFrozenId(null), FLIP_MS + 100);
|
||||||
|
}, SORT_FREEZE_MS);
|
||||||
|
} else {
|
||||||
|
sortByAction(sortBy.type, sortBy.acs, next);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (data !== snapShot) {
|
||||||
|
setSnapshot(data);
|
||||||
|
if (!sameRows(data, copy)) {
|
||||||
|
sortByAction(sortBy.type, sortBy.acs, data);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}, [data]);
|
||||||
|
|
||||||
|
useEffect(() => () => {
|
||||||
|
if (sortTimer.current) clearTimeout(sortTimer.current);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
useLayoutEffect(() => {
|
||||||
|
const prev = prevTops.current;
|
||||||
|
prevTops.current = new Map();
|
||||||
|
if (prev.size === 0) return;
|
||||||
|
rowRefs.current.forEach((el, id) => {
|
||||||
|
if (!el) return;
|
||||||
|
const start = prev.get(id);
|
||||||
|
if (start === undefined) return;
|
||||||
|
const end = el.getBoundingClientRect().top;
|
||||||
|
const delta = end - start;
|
||||||
|
if (Math.abs(delta) < 1) return;
|
||||||
|
el.style.transition = "none";
|
||||||
|
el.style.transform = `translateY(${start - end}px)`;
|
||||||
|
void el.getBoundingClientRect();
|
||||||
|
el.style.transition = `transform ${FLIP_MS}ms cubic-bezier(0.2, 0.8, 0.2, 1)`;
|
||||||
|
el.style.transform = "translateY(0)";
|
||||||
|
});
|
||||||
|
}, [copy]);
|
||||||
|
|
||||||
|
let sum = copy.reduce((acc, val) => acc + val.amount, 0);
|
||||||
|
|
||||||
|
return <TableWrapper>
|
||||||
|
<TableToolbar>
|
||||||
|
<span>Click a value to edit · Enter to save · Esc to cancel</span>
|
||||||
|
</TableToolbar>
|
||||||
|
<TableScroll>
|
||||||
|
<StyledTable>
|
||||||
|
<caption className="sr-only">Transactions for {month}</caption>
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
{HEADERS.map(k => {
|
||||||
|
const active = sortBy.type === k;
|
||||||
|
return (
|
||||||
|
<th key={k} className={k === "amount" ? "amount" : ""}
|
||||||
|
tabIndex={0} role="button"
|
||||||
|
aria-label={`Sort by ${k}${active ? (sortBy.acs ? ", ascending" : ", descending") : ""}`}
|
||||||
|
onClick={() => sortByAction(k, active ? !sortBy.acs : true)}
|
||||||
|
onKeyDown={ev => {
|
||||||
|
if (ev.key === "Enter" || ev.key === " ") {
|
||||||
|
ev.preventDefault();
|
||||||
|
sortByAction(k, active ? !sortBy.acs : true);
|
||||||
|
}
|
||||||
|
}}>
|
||||||
|
{k}{active ? (sortBy.acs ? "\u00A0\u25B2" : "\u00A0\u25BC") : ""}
|
||||||
|
</th>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
<th className="sr-only">Actions</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{copy.map((e, i) => {
|
||||||
|
const id = rowId(e);
|
||||||
|
return <Row i={i} key={id} row={e}
|
||||||
|
frozen={id === frozenId}
|
||||||
|
rowRef={el => {
|
||||||
|
if (el) rowRefs.current.set(id, el);
|
||||||
|
else rowRefs.current.delete(id);
|
||||||
|
}}
|
||||||
|
autosuggestions={autosuggestions}
|
||||||
|
updateAutoSuggestions={updateAutoSuggestions}
|
||||||
|
onUpdate={(updated) => {
|
||||||
|
const c = [...copy];
|
||||||
|
const index = c.indexOf(e);
|
||||||
|
if (index !== -1) c[index] = updated;
|
||||||
|
sync(c, rowId(updated));
|
||||||
|
}} onRemove={(entry) => {
|
||||||
|
const c = [...copy];
|
||||||
|
const index = c.indexOf(entry);
|
||||||
|
if (index !== -1) {
|
||||||
|
c.splice(index, 1);
|
||||||
|
sync(c);
|
||||||
|
}
|
||||||
|
}} />;
|
||||||
|
})}
|
||||||
|
<TotalRow>
|
||||||
|
<td colSpan={4} className="totals-label">Total</td>
|
||||||
|
<td className="amount">
|
||||||
|
<Amount tone={amountTone(sum)}>{formatSigned(sum)}</Amount>
|
||||||
|
</td>
|
||||||
|
<td className="actions" />
|
||||||
|
</TotalRow>
|
||||||
|
<Add
|
||||||
|
modifySuggestions={modifySuggestions}
|
||||||
|
month={month}
|
||||||
|
onPost={(row) => {
|
||||||
|
const a = [...copy];
|
||||||
|
a.push(row);
|
||||||
|
sync(a);
|
||||||
|
}}
|
||||||
|
autosuggestions={autosuggestions}
|
||||||
|
updateAutoSuggestions={updateAutoSuggestions}
|
||||||
|
/>
|
||||||
|
</tbody>
|
||||||
|
</StyledTable>
|
||||||
|
</TableScroll>
|
||||||
|
</TableWrapper>;
|
||||||
|
}
|
||||||
|
|
||||||
|
function Row({ row, onUpdate, onRemove, autosuggestions, updateAutoSuggestions, i, frozen, rowRef }: {
|
||||||
|
row: Data<Date>,
|
||||||
|
onUpdate: (row: Data<Date>) => void,
|
||||||
|
onRemove: (data: Data<Date>) => void,
|
||||||
|
i: number,
|
||||||
|
autosuggestions: Suggestions,
|
||||||
|
updateAutoSuggestions: (values: {key: DataKeys, value: string} []) => void,
|
||||||
|
frozen: boolean,
|
||||||
|
rowRef: (el: HTMLTableRowElement | null) => void,
|
||||||
|
}) {
|
||||||
|
const [confirm, setConfirm] = useState(false);
|
||||||
|
const [editing, setEditing] = useState<EditingState | null>(null);
|
||||||
|
const editingRef = useRef<EditingState | null>(null);
|
||||||
|
const doneRef = useRef(false);
|
||||||
|
|
||||||
|
editingRef.current = editing;
|
||||||
|
|
||||||
|
const names = suggestionsToList(autosuggestions, "name");
|
||||||
|
const locations = suggestionsToList(autosuggestions, "location");
|
||||||
|
const categories = suggestionsToList(autosuggestions, "category");
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
setConfirm(false);
|
||||||
|
setEditing(null);
|
||||||
|
}, [row]);
|
||||||
|
|
||||||
|
const startEdit = (field: EditField) => {
|
||||||
|
doneRef.current = false;
|
||||||
|
const draft = field === "date"
|
||||||
|
? row.date.toISOString().split("T")[0]
|
||||||
|
: field === "amount"
|
||||||
|
? `${row.amount}`
|
||||||
|
: (row[field] as string);
|
||||||
|
setEditing({ field, draft });
|
||||||
|
};
|
||||||
|
|
||||||
|
const finishEdit = (kind: "commit" | "cancel") => {
|
||||||
|
const state = editingRef.current;
|
||||||
|
if (!state) return;
|
||||||
|
doneRef.current = true;
|
||||||
|
if (kind === "commit") {
|
||||||
|
const { field, draft } = state;
|
||||||
|
let next: Data<Date> | null = null;
|
||||||
|
if (field === "date") {
|
||||||
|
const d = new Date(draft);
|
||||||
|
if (!isNaN(d.getTime()) && d.getTime() !== row.date.getTime()) {
|
||||||
|
next = { ...row, date: d };
|
||||||
|
}
|
||||||
|
} else if (field === "amount") {
|
||||||
|
const parsed = evaluateMathExpression(draft) ?? parseFloat(draft);
|
||||||
|
if (!isNaN(parsed) && parsed !== row.amount) {
|
||||||
|
next = { ...row, amount: parsed };
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
const trimmed = draft.trim();
|
||||||
|
if (trimmed && trimmed !== (row[field] as string)) {
|
||||||
|
next = { ...row, [field]: trimmed } as Data<Date>;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (next) {
|
||||||
|
if (field !== "date" && field !== "amount") {
|
||||||
|
updateAutoSuggestions([{ key: field, value: next[field] as string }]);
|
||||||
|
}
|
||||||
|
onUpdate(next);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
setEditing(null);
|
||||||
|
};
|
||||||
|
|
||||||
|
const editableInput = () => {
|
||||||
|
if (!editing) return null;
|
||||||
|
const { field, draft } = editing;
|
||||||
|
const common = {
|
||||||
|
autoFocus: true,
|
||||||
|
value: draft,
|
||||||
|
onFocus: (e: React.FocusEvent<HTMLInputElement>) => e.target.select(),
|
||||||
|
onKeyDown: (e: React.KeyboardEvent<HTMLInputElement>) => {
|
||||||
|
if (e.key === "Enter") finishEdit("commit");
|
||||||
|
if (e.key === "Escape") finishEdit("cancel");
|
||||||
|
},
|
||||||
|
onBlur: () => {
|
||||||
|
if (doneRef.current) { doneRef.current = false; return; }
|
||||||
|
finishEdit("commit");
|
||||||
|
},
|
||||||
|
};
|
||||||
|
if (field === "date") {
|
||||||
|
return <input type="date" aria-label="Edit date" {...common}
|
||||||
|
onChange={e => setEditing({ field, draft: e.target.value })} />;
|
||||||
|
}
|
||||||
|
if (field === "amount") {
|
||||||
|
return <input type="text" inputMode="decimal" aria-label="Edit amount" {...common}
|
||||||
|
onChange={e => setEditing({ field, draft: e.target.value })} />;
|
||||||
|
}
|
||||||
|
const listId = `${i}-${field}`;
|
||||||
|
const options = field === "name" ? names : field === "location" ? locations : categories;
|
||||||
|
return <>
|
||||||
|
<input aria-label={`Edit ${field}`} list={listId} {...common}
|
||||||
|
onChange={e => setEditing({ field, draft: e.target.value })} />
|
||||||
|
<datalist id={listId}>{autoOptions(options)}</datalist>
|
||||||
|
</>;
|
||||||
|
};
|
||||||
|
|
||||||
|
const viewCell = (field: EditField, content: React.ReactNode) => (
|
||||||
|
<CellButton onClick={() => startEdit(field)} aria-label={`Edit ${field}`}>
|
||||||
|
{content}
|
||||||
|
</CellButton>
|
||||||
|
);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<tr ref={rowRef} className={frozen ? "frozen" : ""}>
|
||||||
|
<td>{editing?.field === "date" ? editableInput() : viewCell("date", row.date.toLocaleDateString())}</td>
|
||||||
|
<td>{editing?.field === "name" ? editableInput() : viewCell("name", row.name)}</td>
|
||||||
|
<td>{editing?.field === "location" ? editableInput() : viewCell("location", row.location)}</td>
|
||||||
|
<td>{editing?.field === "category" ? editableInput() : viewCell("category", row.category)}</td>
|
||||||
|
<td className="amount">
|
||||||
|
{editing?.field === "amount" ? editableInput() : viewCell("amount", <Amount tone={amountTone(row.amount)}>{formatSigned(row.amount)}</Amount>)}
|
||||||
|
</td>
|
||||||
|
<td className="actions">
|
||||||
|
{confirm && <button className="danger" onClick={() => { onRemove(row); setConfirm(false); }} aria-label="Confirm delete" title="Confirm delete"><FontAwesomeIcon icon={faCheck} /></button>}
|
||||||
|
<button className="danger" onClick={() => setConfirm(!confirm)} aria-label="Delete" title="Delete"><FontAwesomeIcon icon={faTimes} /></button>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
function Add({ month, onPost, autosuggestions, updateAutoSuggestions, modifySuggestions }: {
|
||||||
|
month: string,
|
||||||
|
onPost: (data: Data<Date>) => void,
|
||||||
|
autosuggestions: Suggestions,
|
||||||
|
modifySuggestions: (key: DataKeys, value: string[]) => void,
|
||||||
|
updateAutoSuggestions: (values: {key: DataKeys, value: string} []) => void }) {
|
||||||
|
const [ date, setDate ] = useState(() => defaultAddDate(month));
|
||||||
|
const [name, setName] = useState("");
|
||||||
|
const [location, setLocation] = useState("");
|
||||||
|
const [category, setCategory] = useState("");
|
||||||
|
const [amount, setAmount] = useState("");
|
||||||
|
const [ canPost, setCanPost ] = useState(false);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
setDate(defaultAddDate(month));
|
||||||
|
}, [month]);
|
||||||
|
|
||||||
|
const names = suggestionsToList(autosuggestions, "name");
|
||||||
|
const locations = suggestionsToList(autosuggestions, "location");
|
||||||
|
const categories = suggestionsToList(autosuggestions, "category");
|
||||||
|
|
||||||
|
const editAutoSuggestions = (key: DataKeys) => {
|
||||||
|
const group = autosuggestions[key];
|
||||||
|
const list = group ? Object.keys(group.items).join(", ") : "";
|
||||||
|
const result = prompt(`Edit autosuggestions for ${key}`, list);
|
||||||
|
if (result) {
|
||||||
|
const newArray = result.split(",").map(e => e.trim()).filter(e => e);
|
||||||
|
modifySuggestions(key, newArray);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const post = () => {
|
||||||
|
if (canPost) {
|
||||||
|
const parsed = evaluateMathExpression(amount) ?? parseFloat(amount);
|
||||||
|
updateAutoSuggestions([
|
||||||
|
{ key: "name", value: name },
|
||||||
|
{ key: "location", value: location },
|
||||||
|
{ key: "category", value: category}
|
||||||
|
]);
|
||||||
|
onPost({ name, location, category, amount: parsed, date: new Date(date) });
|
||||||
|
setName("");
|
||||||
|
setLocation("");
|
||||||
|
setCategory("");
|
||||||
|
setAmount("");
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const val = amount ? evaluateMathExpression(amount) ?? parseFloat(amount) : NaN;
|
||||||
|
setCanPost(!!(name && location && category && amount && !isNaN(val)));
|
||||||
|
}, [name, location, category, amount]);
|
||||||
|
|
||||||
|
const sDate = (value: string) => {
|
||||||
|
setDate(`${month}-${value.split("-")[2]}`);
|
||||||
|
};
|
||||||
|
|
||||||
|
const amountPreview = (() => {
|
||||||
|
if (!amount) return null;
|
||||||
|
const val = evaluateMathExpression(amount);
|
||||||
|
return val !== null && !isNaN(val) ? val.toFixed(2) : null;
|
||||||
|
})();
|
||||||
|
|
||||||
|
return <tr>
|
||||||
|
<td>
|
||||||
|
<input
|
||||||
|
type="date"
|
||||||
|
aria-label="Date"
|
||||||
|
value={date}
|
||||||
|
onChange={ev => sDate(ev.target.value)} />
|
||||||
|
</td>
|
||||||
|
<td>
|
||||||
|
<input
|
||||||
|
list="names"
|
||||||
|
aria-label="Name"
|
||||||
|
onDoubleClick={() => editAutoSuggestions("name")}
|
||||||
|
value={name}
|
||||||
|
onKeyDown={ev => ev.key === "Enter" && post()}
|
||||||
|
onChange={ev => setName(ev.target.value)}
|
||||||
|
placeholder="Name" />
|
||||||
|
<datalist id="names">{autoOptions(names)}</datalist>
|
||||||
|
</td>
|
||||||
|
<td>
|
||||||
|
<input
|
||||||
|
aria-label="Location"
|
||||||
|
onDoubleClick={() => editAutoSuggestions("location")}
|
||||||
|
list="locations"
|
||||||
|
value={location}
|
||||||
|
onKeyDown={ev => ev.key === "Enter" && post()}
|
||||||
|
onChange={ev => setLocation(ev.target.value)}
|
||||||
|
placeholder="Location" />
|
||||||
|
<datalist id="locations">{autoOptions(locations)}</datalist>
|
||||||
|
</td>
|
||||||
|
<td>
|
||||||
|
<input
|
||||||
|
aria-label="Category"
|
||||||
|
onDoubleClick={() => editAutoSuggestions("category")}
|
||||||
|
list="categories"
|
||||||
|
value={category}
|
||||||
|
onKeyDown={ev => ev.key === "Enter" && post()}
|
||||||
|
onChange={ev => setCategory(ev.target.value)}
|
||||||
|
placeholder="Category" />
|
||||||
|
<datalist id="categories">{autoOptions(categories)}</datalist>
|
||||||
|
</td>
|
||||||
|
<td>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
inputMode="decimal"
|
||||||
|
aria-label="Amount"
|
||||||
|
value={amount}
|
||||||
|
onKeyDown={ev => ev.key === "Enter" && post()}
|
||||||
|
onChange={ev => setAmount(ev.target.value)}
|
||||||
|
placeholder="Amount" />
|
||||||
|
<span style={{ display: "block", lineHeight: 1.4, fontSize: `${theme.font.sizes.xs}`, color: theme.colors.textMuted }}>{amountPreview?.trim() || "0"}</span>
|
||||||
|
</td>
|
||||||
|
<td className="actions">
|
||||||
|
<button className="primary" disabled={!canPost} onClick={post} aria-label="Add transaction">
|
||||||
|
<FontAwesomeIcon icon={faCheck} /> Add
|
||||||
|
</button>
|
||||||
|
</td>
|
||||||
|
</tr>;
|
||||||
|
}
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
import React from 'react';
|
||||||
|
import ReactDOM from 'react-dom/client';
|
||||||
|
import { App } from './App';
|
||||||
|
|
||||||
|
const root = ReactDOM.createRoot(
|
||||||
|
document.getElementById('root') as HTMLElement
|
||||||
|
);
|
||||||
|
|
||||||
|
const baseUrl = "https://flog.lidcer.dev"
|
||||||
|
|
||||||
|
root.render(
|
||||||
|
<React.StrictMode>
|
||||||
|
<App baseUrl={baseUrl} />
|
||||||
|
</React.StrictMode>
|
||||||
|
);
|
||||||
@@ -0,0 +1,81 @@
|
|||||||
|
export function evaluateMathExpression(input: string): number | null {
|
||||||
|
const expr = input.replace(/\s+/g, '');
|
||||||
|
if (!expr) return null;
|
||||||
|
|
||||||
|
let pos = 0;
|
||||||
|
|
||||||
|
function peek(): string {
|
||||||
|
return expr[pos] || '';
|
||||||
|
}
|
||||||
|
|
||||||
|
function consume(): string {
|
||||||
|
return expr[pos++] || '';
|
||||||
|
}
|
||||||
|
|
||||||
|
function parseNumber(): number {
|
||||||
|
const start = pos;
|
||||||
|
if (pos < expr.length && (expr[pos] === '-' || expr[pos] === '+')) {
|
||||||
|
if (pos > 0) {
|
||||||
|
throw new Error('unexpected sign');
|
||||||
|
}
|
||||||
|
pos++;
|
||||||
|
}
|
||||||
|
while (pos < expr.length && ((expr[pos] >= '0' && expr[pos] <= '9') || expr[pos] === '.')) {
|
||||||
|
pos++;
|
||||||
|
}
|
||||||
|
if (pos === start) {
|
||||||
|
throw new Error('expected number');
|
||||||
|
}
|
||||||
|
return parseFloat(expr.slice(start, pos));
|
||||||
|
}
|
||||||
|
|
||||||
|
function parseFactor(): number {
|
||||||
|
if (peek() === '(') {
|
||||||
|
consume();
|
||||||
|
const val = parseExpression();
|
||||||
|
if (peek() !== ')') {
|
||||||
|
throw new Error('missing closing parenthesis');
|
||||||
|
}
|
||||||
|
consume();
|
||||||
|
return val;
|
||||||
|
}
|
||||||
|
return parseNumber();
|
||||||
|
}
|
||||||
|
|
||||||
|
function parseTerm(): number {
|
||||||
|
let left = parseFactor();
|
||||||
|
while (peek() === '*' || peek() === '/') {
|
||||||
|
const op = consume();
|
||||||
|
const right = parseFactor();
|
||||||
|
left = op === '*' ? left * right : left / right;
|
||||||
|
}
|
||||||
|
return left;
|
||||||
|
}
|
||||||
|
|
||||||
|
function parseExpression(): number {
|
||||||
|
let left = parseTerm();
|
||||||
|
while (peek() === '+' || peek() === '-') {
|
||||||
|
const op = consume();
|
||||||
|
const right = parseTerm();
|
||||||
|
left = op === '+' ? left + right : left - right;
|
||||||
|
}
|
||||||
|
return left;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const result = parseExpression();
|
||||||
|
if (pos !== expr.length) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
if (!isFinite(result)) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return Math.round(result * 100) / 100;
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function isMathExpression(input: string): boolean {
|
||||||
|
return (/[+\-*/()]/.test(input) && /[0-9]/.test(input));
|
||||||
|
}
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
export const theme = {
|
||||||
|
colors: {
|
||||||
|
bg: "#000000",
|
||||||
|
surface: "#111214",
|
||||||
|
surfaceAlt: "#1a1d22",
|
||||||
|
border: "#2b2f36",
|
||||||
|
borderStrong: "#4a5058",
|
||||||
|
text: "#f2f3f5",
|
||||||
|
textMuted: "#c3c7cf",
|
||||||
|
textFaint: "#8a9099",
|
||||||
|
income: "#3ddc84",
|
||||||
|
expense: "#ff6b6b",
|
||||||
|
accent: "#5b9dff",
|
||||||
|
focusRing: "#7ab3ff",
|
||||||
|
dangerBg: "#2a1210",
|
||||||
|
dangerBorder: "#8a2f28",
|
||||||
|
},
|
||||||
|
spacing: {
|
||||||
|
xs: 4,
|
||||||
|
sm: 8,
|
||||||
|
md: 12,
|
||||||
|
lg: 16,
|
||||||
|
xl: 24,
|
||||||
|
xxl: 40,
|
||||||
|
},
|
||||||
|
radius: {
|
||||||
|
sm: 6,
|
||||||
|
md: 10,
|
||||||
|
lg: 14,
|
||||||
|
},
|
||||||
|
font: {
|
||||||
|
family: "\"Ubuntu\", system-ui, -apple-system, \"Segoe UI\", Roboto, sans-serif",
|
||||||
|
sizes: {
|
||||||
|
xxs: "0.75rem",
|
||||||
|
xs: "0.8125rem",
|
||||||
|
sm: "0.875rem",
|
||||||
|
md: "1rem",
|
||||||
|
lg: "1.125rem",
|
||||||
|
xl: "1.5rem",
|
||||||
|
xxl: "2rem",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
breakpoints: {
|
||||||
|
mobile: "640px",
|
||||||
|
tablet: "960px",
|
||||||
|
},
|
||||||
|
} as const;
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
export function getMonth(date = new Date()) {
|
||||||
|
const year = date.getFullYear();
|
||||||
|
const month = pad(date.getMonth() + 1);
|
||||||
|
return `${year}-${month}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function pad(something: string | number, pad = 2, padder = "0") {
|
||||||
|
return something.toString().padStart(pad, padder);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getDate(date = new Date()) {
|
||||||
|
const year = date.getFullYear();
|
||||||
|
const month = pad(date.getMonth() + 1);
|
||||||
|
const day = pad(date.getDate());
|
||||||
|
|
||||||
|
return `${year}-${month}-${day}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type AmountTone = "income" | "expense" | "neutral";
|
||||||
|
|
||||||
|
export function amountTone(n: number): AmountTone {
|
||||||
|
return n > 0 ? "income" : n < 0 ? "expense" : "neutral";
|
||||||
|
}
|
||||||
|
|
||||||
|
export function formatSigned(n: number) {
|
||||||
|
const abs = Math.abs(n).toLocaleString("en-US", { minimumFractionDigits: 2, maximumFractionDigits: 2 });
|
||||||
|
return n === 0 ? "0.00" : `${n < 0 ? "-" : "+"}${abs}`;
|
||||||
|
}
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
{
|
||||||
|
"compilerOptions": {
|
||||||
|
"target": "es5",
|
||||||
|
"lib": [
|
||||||
|
"dom",
|
||||||
|
"dom.iterable",
|
||||||
|
"esnext"
|
||||||
|
],
|
||||||
|
"allowJs": true,
|
||||||
|
"skipLibCheck": true,
|
||||||
|
"esModuleInterop": true,
|
||||||
|
"allowSyntheticDefaultImports": true,
|
||||||
|
"strict": true,
|
||||||
|
"forceConsistentCasingInFileNames": true,
|
||||||
|
"noFallthroughCasesInSwitch": true,
|
||||||
|
"module": "esnext",
|
||||||
|
"moduleResolution": "node",
|
||||||
|
"resolveJsonModule": true,
|
||||||
|
"isolatedModules": true,
|
||||||
|
"noEmit": true,
|
||||||
|
"jsx": "react-jsx"
|
||||||
|
},
|
||||||
|
"include": [
|
||||||
|
"src"
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
{
|
||||||
|
"compilerOptions": {
|
||||||
|
"target": "es2016",
|
||||||
|
"module": "commonjs",
|
||||||
|
"outDir": "./dist",
|
||||||
|
"esModuleInterop": true,
|
||||||
|
"forceConsistentCasingInFileNames": true,
|
||||||
|
"strict": true,
|
||||||
|
"skipLibCheck": true
|
||||||
|
},
|
||||||
|
"include": [
|
||||||
|
"index.ts",
|
||||||
|
"server/**/*.ts"
|
||||||
|
]
|
||||||
|
}
|
||||||
Reference in new issue
Block a user