mirror of
https://github.com/ManInDark/HabitTrove.git
synced 2026-03-09 12:09:48 +01:00
Compare commits
34 Commits
v0.2.23
...
1b17d6b50a
| Author | SHA1 | Date | |
|---|---|---|---|
|
1b17d6b50a
|
|||
|
8269f3adad
|
|||
|
4cadf4cea7
|
|||
|
06e802f2f5
|
|||
|
6c0b196de2
|
|||
|
0f073760ee
|
|||
|
55c2e3577d
|
|||
|
043201217f
|
|||
|
4e11f17729
|
|||
|
faa6f4cb76
|
|||
|
84d6321153
|
|||
|
1af98fb233
|
|||
|
9046d40a7a
|
|||
|
be0a5c48b3
|
|||
|
3d78a00c66
|
|||
|
9c2e3f7dec
|
|||
|
e93b1c1c57
|
|||
|
92d1462010
|
|||
|
eff14f3772
|
|||
|
d9fa0426ce
|
|||
|
49a0ea8804
|
|||
|
9bf24db477
|
|||
|
8530f703d9
|
|||
|
1a447e00bf
|
|||
|
ac116e8322
|
|||
|
8c7a7a63d0
|
|||
|
7c7d0e2f32
|
|||
|
e908f1edec
|
|||
|
8e6ddf0b9f
|
|||
|
c5a8f403ef
|
|||
|
33d36d0600
|
|||
|
942356eaed
|
|||
|
e4a52657af
|
|||
|
dbd0d0c7b7
|
95
.github/workflows/docker-publish.yml
vendored
95
.github/workflows/docker-publish.yml
vendored
@@ -1,95 +0,0 @@
|
||||
name: Docker Build and Publish
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
- github-actions
|
||||
|
||||
jobs:
|
||||
build-and-push:
|
||||
runs-on: ubuntu-latest
|
||||
outputs:
|
||||
EXISTS: ${{ steps.check-version.outputs.EXISTS }}
|
||||
VERSION: ${{ steps.package-version.outputs.VERSION }}
|
||||
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Set up Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: "20"
|
||||
|
||||
- name: Get version from package.json
|
||||
id: package-version
|
||||
run: echo "VERSION=$(node -p "require('./package.json').version")" >> $GITHUB_OUTPUT
|
||||
|
||||
- name: Login to DockerHub
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
username: ${{ secrets.DOCKERHUB_USERNAME }}
|
||||
password: ${{ secrets.DOCKERHUB_TOKEN }}
|
||||
|
||||
- name: Check if version exists
|
||||
id: check-version
|
||||
run: |
|
||||
if docker pull dohsimpson/habittrove:v${{ steps.package-version.outputs.VERSION }} 2>/dev/null; then
|
||||
echo "EXISTS=true" >> $GITHUB_OUTPUT
|
||||
else
|
||||
echo "EXISTS=false" >> $GITHUB_OUTPUT
|
||||
fi
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
|
||||
- name: Build and push Docker images
|
||||
uses: docker/build-push-action@v5
|
||||
with:
|
||||
context: .
|
||||
platforms: linux/amd64,linux/arm64
|
||||
push: true
|
||||
tags: |
|
||||
${{ steps.check-version.outputs.EXISTS == 'false' && format('dohsimpson/habittrove:v{0}', steps.package-version.outputs.VERSION) || '' }}
|
||||
dohsimpson/habittrove:demo
|
||||
dohsimpson/habittrove:latest
|
||||
|
||||
deploy-demo:
|
||||
runs-on: ubuntu-latest
|
||||
needs: build-and-push
|
||||
# demo tracks the demo tag
|
||||
if: needs.build-and-push.outputs.EXISTS == 'false'
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions-hub/kubectl@master
|
||||
env:
|
||||
KUBE_CONFIG: ${{ secrets.KUBE_CONFIG }}
|
||||
with:
|
||||
args: rollout restart -n ${{ secrets.KUBE_NAMESPACE }} deploy/${{ secrets.KUBE_DEPLOYMENT }}
|
||||
|
||||
create-release:
|
||||
runs-on: ubuntu-latest
|
||||
needs: build-and-push
|
||||
if: needs.build-and-push.outputs.EXISTS == 'false'
|
||||
permissions:
|
||||
contents: write
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Create GitHub release
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GH_TOKEN }}
|
||||
VERSION: ${{ needs.build-and-push.outputs.VERSION }}
|
||||
run: |
|
||||
# Extract release notes from CHANGELOG.md
|
||||
notes=$(awk -v version="$VERSION" '
|
||||
$0 ~ "## Version " version {flag=1;next}
|
||||
$0 ~ "## Version " && flag {exit}
|
||||
flag' CHANGELOG.md)
|
||||
|
||||
gh release create "v$VERSION" \
|
||||
--repo="$GITHUB_REPOSITORY" \
|
||||
--title="v$VERSION" \
|
||||
--notes="$notes"
|
||||
40
.github/workflows/release.yml
vendored
Normal file
40
.github/workflows/release.yml
vendored
Normal file
@@ -0,0 +1,40 @@
|
||||
name: Create and publish a Docker image to Github Container Registry
|
||||
|
||||
on:
|
||||
push:
|
||||
tags:
|
||||
- v*
|
||||
|
||||
env:
|
||||
REGISTRY: ghcr.io
|
||||
IMAGE_NAME: ${{ github.repository }}
|
||||
|
||||
jobs:
|
||||
create-and-publish:
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
packages: write
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
- name: Log in to the Container registry
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
registry: ${{ env.REGISTRY }}
|
||||
username: ${{ github.actor }}
|
||||
password: ${{ secrets.GITHUB_TOKEN }}
|
||||
- name: Extract metadata (tags, labels) for Docker
|
||||
id: meta
|
||||
uses: docker/metadata-action@v5
|
||||
with:
|
||||
images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
- name: Build and push Docker image
|
||||
uses: docker/build-push-action@v5
|
||||
with:
|
||||
context: .
|
||||
push: true
|
||||
tags: ${{ steps.meta.outputs.tags }}
|
||||
labels: ${{ steps.meta.outputs.labels }}
|
||||
28
.github/workflows/test.yml
vendored
28
.github/workflows/test.yml
vendored
@@ -1,28 +0,0 @@
|
||||
name: Unit Tests
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
branches:
|
||||
- main
|
||||
|
||||
jobs:
|
||||
test:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Set up Bun
|
||||
uses: oven-sh/setup-bun@v1
|
||||
with:
|
||||
bun-version: latest
|
||||
|
||||
- name: Install dependencies
|
||||
run: bun install
|
||||
|
||||
- name: Run lint
|
||||
run: bun run lint
|
||||
|
||||
- name: Run unit tests
|
||||
run: bun test
|
||||
6
.vscode/settings.json
vendored
Normal file
6
.vscode/settings.json
vendored
Normal file
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"i18n-ally.localesPaths": [
|
||||
"i18n",
|
||||
"messages"
|
||||
]
|
||||
}
|
||||
29
README.md
29
README.md
@@ -1,14 +1,24 @@
|
||||
# <img align="left" width="50" height="50" src="https://github.com/user-attachments/assets/99dcf223-3680-4b3a-8050-d9788f051682" /> HabitTrove
|
||||
|
||||

|
||||
|
||||
HabitTrove is a gamified habit tracking application that helps you build and maintain positive habits by rewarding you with coins, which you can use to exchange for rewards.
|
||||
|
||||
> **⚠️ Important:** HabitTrove is currently in beta. Please regularly backup your `data/` directory to prevent any potential data loss.
|
||||
**⚠️ Important:** HabitTrove is currently in beta. Please regularly backup your `data/` directory to prevent any potential data loss.
|
||||
|
||||
## Try the Demo
|
||||
## Differences to Upstream
|
||||
|
||||
Want to try HabitTrove before installing? Visit the public [demo instance](https://demo.habittrove.com) to experience all features without any setup required. (do not store personal info. Data on the demo instance is reset daily)
|
||||
I generally try to keep the `main` branch up to date with upstream features, merging tagged versions and mapping them to `<upstream-version>.0`.
|
||||
|
||||
In this version I've taken steps to ensure a smoother experience and decreased the chance of the program bricking itself. This doesn't mean that it's completely stable, but I've fixed the most glaring bugs I encountered.
|
||||
|
||||
Differences (as of writing) are:
|
||||
- resolved linting problems so you can actually commit things
|
||||
- added missing dependency
|
||||
- refactored adding habit modal to cause less errors
|
||||
- resolved undefined error
|
||||
- replaced dockerhub release flow with github
|
||||
- miscellaneous refactorings
|
||||
- split habits & tasks page into two different pages
|
||||
- only display "show all" if there are more than 4 entries
|
||||
|
||||
## Features
|
||||
|
||||
@@ -25,11 +35,8 @@ Want to try HabitTrove before installing? Visit the public [demo instance](https
|
||||
## Usage
|
||||
|
||||
1. **Creating Habits**: Click the "Add Habit" button to create a new habit. Set a name, description, and coin reward.
|
||||
|
||||
2. **Tracking Habits**: Mark habits as complete on your dashboard. Each completion earns you the specified coins.
|
||||
|
||||
3. **Wishlist**: Add rewards to your wishlist that you can redeem with earned coins.
|
||||
|
||||
4. **Statistics**: View your progress through the heatmap and streak counters.
|
||||
|
||||
## Docker Deployment
|
||||
@@ -66,7 +73,7 @@ docker run -d \
|
||||
-v ./data:/app/data \
|
||||
-v ./backups:/app/backups \ # Add this line to map the backups directory
|
||||
-e AUTH_SECRET=$AUTH_SECRET \
|
||||
dohsimpson/habittrove
|
||||
ghcr.io/manindark/habittrove
|
||||
```
|
||||
|
||||
Available image tags:
|
||||
@@ -113,7 +120,7 @@ To contribute to HabitTrove, you'll need to set up a development environment. He
|
||||
1. Clone the repository and navigate to the project directory:
|
||||
|
||||
```bash
|
||||
git clone https://github.com/dohsimpson/habittrove.git
|
||||
git clone https://github.com/ManInDark/HabitTrove.git
|
||||
cd habittrove
|
||||
```
|
||||
|
||||
@@ -166,7 +173,7 @@ Run these commands regularly during development to catch issues early.
|
||||
|
||||
## Contributing
|
||||
|
||||
We welcome feature requests and bug reports! Please [open an issue](https://github.com/dohsimpson/habittrove/issues/new). We do not accept pull request at the moment.
|
||||
We welcome feature requests and bug reports! Please [open an issue](https://github.com/ManInDark/habittrove/issues/new).
|
||||
|
||||
## License
|
||||
|
||||
|
||||
@@ -1,59 +1,38 @@
|
||||
'use server'
|
||||
|
||||
import fs from 'fs/promises'
|
||||
import path from 'path'
|
||||
import { getCurrentUser, saltAndHashPassword, verifyPassword } from "@/lib/server-helpers";
|
||||
import {
|
||||
HabitsData,
|
||||
CoinsData,
|
||||
CoinTransaction,
|
||||
TransactionType,
|
||||
WishlistItemType,
|
||||
WishlistData,
|
||||
Settings,
|
||||
DataType,
|
||||
DATA_DEFAULTS,
|
||||
getDefaultSettings,
|
||||
UserData,
|
||||
getDefaultUsersData,
|
||||
User,
|
||||
getDefaultWishlistData,
|
||||
getDefaultHabitsData,
|
||||
DataType,
|
||||
getDefaultCoinsData,
|
||||
getDefaultHabitsData,
|
||||
getDefaultSettings,
|
||||
getDefaultUsersData,
|
||||
getDefaultWishlistData,
|
||||
HabitsData,
|
||||
Permission,
|
||||
ServerSettings
|
||||
} from '@/lib/types'
|
||||
import { d2t, deepMerge, getNow, checkPermission, uuid } from '@/lib/utils';
|
||||
import { verifyPassword } from "@/lib/server-helpers";
|
||||
import { saltAndHashPassword } from "@/lib/server-helpers";
|
||||
ServerSettings,
|
||||
Settings,
|
||||
TransactionType,
|
||||
User,
|
||||
UserData,
|
||||
WishlistData,
|
||||
WishlistItemType
|
||||
} from '@/lib/types';
|
||||
import { d2t, generateCryptoHash, getNow, prepareDataForHashing } from '@/lib/utils';
|
||||
import { signInSchema } from '@/lib/zod';
|
||||
import { auth } from '@/auth';
|
||||
import fs from 'fs/promises';
|
||||
import _ from 'lodash';
|
||||
import { getCurrentUser, getCurrentUserId } from '@/lib/server-helpers'
|
||||
import stableStringify from 'json-stable-stringify';
|
||||
import { prepareDataForHashing, generateCryptoHash } from '@/lib/utils';
|
||||
import path from 'path';
|
||||
|
||||
|
||||
import { PermissionError } from '@/lib/exceptions'
|
||||
|
||||
type ResourceType = 'habit' | 'wishlist' | 'coins'
|
||||
type ActionType = 'write' | 'interact'
|
||||
|
||||
|
||||
async function verifyPermission(
|
||||
resource: ResourceType,
|
||||
action: ActionType
|
||||
): Promise<void> {
|
||||
// const user = await getCurrentUser()
|
||||
|
||||
// if (!user) throw new PermissionError('User not authenticated')
|
||||
// if (user.isAdmin) return // Admins bypass permission checks
|
||||
|
||||
// if (!checkPermission(user.permissions, resource, action)) {
|
||||
// throw new PermissionError(`User does not have ${action} permission for ${resource}`)
|
||||
// }
|
||||
return
|
||||
}
|
||||
|
||||
function getDefaultData<T>(type: DataType): T {
|
||||
return DATA_DEFAULTS[type]() as T;
|
||||
}
|
||||
@@ -97,7 +76,7 @@ async function loadData<T>(type: DataType): Promise<T> {
|
||||
await fs.access(filePath)
|
||||
} catch {
|
||||
// File doesn't exist, create it with default data
|
||||
const initialData = getDefaultData(type)
|
||||
const initialData = getDefaultData<T>(type)
|
||||
await fs.writeFile(filePath, JSON.stringify(initialData, null, 2))
|
||||
return initialData as T
|
||||
}
|
||||
@@ -132,11 +111,13 @@ async function saveData<T>(type: DataType, data: T): Promise<void> {
|
||||
*/
|
||||
async function calculateServerFreshnessToken(): Promise<string | null> {
|
||||
try {
|
||||
const settings = await loadSettings();
|
||||
const habits = await loadHabitsData();
|
||||
const coins = await loadCoinsData();
|
||||
const wishlist = await loadWishlistData();
|
||||
const users = await loadUsersData();
|
||||
const [settings, habits, coins, wishlist, users] = await Promise.all([
|
||||
loadSettings(),
|
||||
loadHabitsData(),
|
||||
loadCoinsData(),
|
||||
loadWishlistData(),
|
||||
loadUsersData()
|
||||
]);
|
||||
|
||||
const dataString = prepareDataForHashing(
|
||||
settings,
|
||||
@@ -145,8 +126,7 @@ async function calculateServerFreshnessToken(): Promise<string | null> {
|
||||
wishlist,
|
||||
users
|
||||
);
|
||||
const serverToken = await generateCryptoHash(dataString);
|
||||
return serverToken;
|
||||
return generateCryptoHash(dataString);
|
||||
} catch (error) {
|
||||
console.error("Error calculating server freshness token:", error);
|
||||
throw error;
|
||||
@@ -156,7 +136,7 @@ async function calculateServerFreshnessToken(): Promise<string | null> {
|
||||
// Wishlist specific functions
|
||||
export async function loadWishlistData(): Promise<WishlistData> {
|
||||
const user = await getCurrentUser()
|
||||
if (!user) return getDefaultWishlistData()
|
||||
if (!user) return getDefaultWishlistData<WishlistData>()
|
||||
|
||||
const data = await loadData<WishlistData>('wishlist')
|
||||
return {
|
||||
@@ -171,7 +151,6 @@ export async function loadWishlistItems(): Promise<WishlistItemType[]> {
|
||||
}
|
||||
|
||||
export async function saveWishlistItems(data: WishlistData): Promise<void> {
|
||||
await verifyPermission('wishlist', 'write')
|
||||
const user = await getCurrentUser()
|
||||
|
||||
data.items = data.items.map(wishlist => ({
|
||||
@@ -194,17 +173,14 @@ export async function saveWishlistItems(data: WishlistData): Promise<void> {
|
||||
// Habits specific functions
|
||||
export async function loadHabitsData(): Promise<HabitsData> {
|
||||
const user = await getCurrentUser()
|
||||
if (!user) return getDefaultHabitsData()
|
||||
if (!user) return getDefaultHabitsData<HabitsData>()
|
||||
const data = await loadData<HabitsData>('habits')
|
||||
return {
|
||||
...data,
|
||||
habits: data.habits.filter(x => user.isAdmin || x.userIds?.includes(user.id))
|
||||
}
|
||||
}
|
||||
|
||||
export async function saveHabitsData(data: HabitsData): Promise<void> {
|
||||
await verifyPermission('habit', 'write')
|
||||
|
||||
const user = await getCurrentUser()
|
||||
// Create clone of input data
|
||||
const newData = _.cloneDeep(data)
|
||||
@@ -216,7 +192,7 @@ export async function saveHabitsData(data: HabitsData): Promise<void> {
|
||||
}))
|
||||
|
||||
if (!user?.isAdmin) {
|
||||
const existingData = await loadData<HabitsData>('habits')
|
||||
const existingData = await loadHabitsData();
|
||||
const existingHabits = existingData.habits.filter(x => user?.id && !x.userIds?.includes(user?.id))
|
||||
newData.habits = [
|
||||
...existingHabits,
|
||||
@@ -232,14 +208,14 @@ export async function saveHabitsData(data: HabitsData): Promise<void> {
|
||||
export async function loadCoinsData(): Promise<CoinsData> {
|
||||
try {
|
||||
const user = await getCurrentUser()
|
||||
if (!user) return getDefaultCoinsData()
|
||||
if (!user) return getDefaultCoinsData<CoinsData>()
|
||||
const data = await loadData<CoinsData>('coins')
|
||||
return {
|
||||
...data,
|
||||
transactions: user.isAdmin ? data.transactions : data.transactions.filter(x => x.userId === user.id)
|
||||
}
|
||||
} catch {
|
||||
return getDefaultCoinsData()
|
||||
return getDefaultCoinsData<CoinsData>()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -279,11 +255,10 @@ export async function addCoins({
|
||||
note?: string
|
||||
userId?: string
|
||||
}): Promise<CoinsData> {
|
||||
await verifyPermission('coins', type === 'MANUAL_ADJUSTMENT' ? 'write' : 'interact')
|
||||
const currentUser = await getCurrentUser()
|
||||
const data = await loadCoinsData()
|
||||
const newTransaction: CoinTransaction = {
|
||||
id: uuid(),
|
||||
id: crypto.randomUUID(),
|
||||
amount,
|
||||
type,
|
||||
description,
|
||||
@@ -303,7 +278,7 @@ export async function addCoins({
|
||||
}
|
||||
|
||||
export async function loadSettings(): Promise<Settings> {
|
||||
const defaultSettings = getDefaultSettings()
|
||||
const defaultSettings = getDefaultSettings<Settings>()
|
||||
|
||||
try {
|
||||
const user = await getCurrentUser()
|
||||
@@ -334,11 +309,10 @@ export async function removeCoins({
|
||||
note?: string
|
||||
userId?: string
|
||||
}): Promise<CoinsData> {
|
||||
await verifyPermission('coins', type === 'MANUAL_ADJUSTMENT' ? 'write' : 'interact')
|
||||
const currentUser = await getCurrentUser()
|
||||
const data = await loadCoinsData()
|
||||
const newTransaction: CoinTransaction = {
|
||||
id: uuid(),
|
||||
id: crypto.randomUUID(),
|
||||
amount: -amount,
|
||||
type,
|
||||
description,
|
||||
@@ -396,7 +370,7 @@ export async function loadUsersData(): Promise<UserData> {
|
||||
try {
|
||||
return await loadData<UserData>('auth')
|
||||
} catch {
|
||||
return getDefaultUsersData()
|
||||
return getDefaultUsersData<UserData>()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -440,7 +414,7 @@ export async function createUser(formData: FormData): Promise<User> {
|
||||
|
||||
|
||||
const newUser: User = {
|
||||
id: uuid(),
|
||||
id: crypto.randomUUID(),
|
||||
username,
|
||||
password: hashedPassword,
|
||||
permissions,
|
||||
|
||||
@@ -1,14 +1,8 @@
|
||||
import Layout from '@/components/Layout'
|
||||
import HabitCalendar from '@/components/HabitCalendar'
|
||||
import { ViewToggle } from '@/components/ViewToggle'
|
||||
import CompletionCountBadge from '@/components/CompletionCountBadge'
|
||||
|
||||
export default function CalendarPage() {
|
||||
return (
|
||||
<div className="flex flex-col gap-4">
|
||||
<div className="flex justify-end">
|
||||
{/* <ViewToggle /> */}
|
||||
</div>
|
||||
<div className="flex flex-col">
|
||||
<HabitCalendar />
|
||||
</div>
|
||||
)
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import Layout from '@/components/Layout'
|
||||
import CoinsManager from '@/components/CoinsManager'
|
||||
|
||||
export default function CoinsPage() {
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
'use client'
|
||||
|
||||
import { useHabits } from "@/hooks/useHabits";
|
||||
import { habitsAtom, settingsAtom } from "@/lib/atoms";
|
||||
import { Habit } from "@/lib/types";
|
||||
import { useAtom } from "jotai";
|
||||
|
||||
@@ -1,14 +1,9 @@
|
||||
import Layout from '@/components/Layout'
|
||||
import HabitList from '@/components/HabitList'
|
||||
import { ViewToggle } from '@/components/ViewToggle'
|
||||
|
||||
export default function HabitsPage() {
|
||||
return (
|
||||
<div className="flex flex-col gap-4">
|
||||
<div className="flex justify-end">
|
||||
{/* <ViewToggle /> */}
|
||||
</div>
|
||||
<HabitList />
|
||||
<div className="flex flex-col">
|
||||
<HabitList isTasksView={false} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,33 +1,23 @@
|
||||
import './globals.css'
|
||||
import { Inter } from 'next/font/google'
|
||||
import { DM_Sans } from 'next/font/google'
|
||||
import { JotaiProvider } from '@/components/jotai-providers'
|
||||
import { JotaiHydrate } from '@/components/jotai-hydrate'
|
||||
import { loadSettings, loadHabitsData, loadCoinsData, loadWishlistData, loadUsersData, loadServerSettings } from './actions/data'
|
||||
import { JotaiProvider } from '@/components/jotai-providers'
|
||||
import Layout from '@/components/Layout'
|
||||
import { Toaster } from '@/components/ui/toaster'
|
||||
import { ThemeProvider } from "@/components/theme-provider"
|
||||
import { SessionProvider } from 'next-auth/react'
|
||||
import { NextIntlClientProvider } from 'next-intl';
|
||||
import { getLocale, getMessages } from 'next-intl/server';
|
||||
import { Suspense } from 'react'
|
||||
import LoadingSpinner from '@/components/LoadingSpinner'
|
||||
|
||||
|
||||
// Inter (clean, modern, excellent readability)
|
||||
// const inter = Inter({
|
||||
// subsets: ['latin'],
|
||||
// weight: ['400', '500', '600', '700']
|
||||
// })
|
||||
import { ThemeProvider } from "@/components/theme-provider"
|
||||
import { Toaster } from '@/components/ui/toaster'
|
||||
import { SessionProvider } from 'next-auth/react'
|
||||
import { NextIntlClientProvider } from 'next-intl'
|
||||
import { getLocale, getMessages } from 'next-intl/server'
|
||||
import { DM_Sans } from 'next/font/google'
|
||||
import { Suspense } from 'react'
|
||||
import { loadCoinsData, loadHabitsData, loadServerSettings, loadSettings, loadUsersData, loadWishlistData } from './actions/data'
|
||||
import './globals.css'
|
||||
|
||||
// Clean and contemporary
|
||||
const dmSans = DM_Sans({
|
||||
const activeFont = DM_Sans({
|
||||
subsets: ['latin'],
|
||||
weight: ['400', '500', '600', '700']
|
||||
})
|
||||
|
||||
const activeFont = dmSans
|
||||
|
||||
export const metadata = {
|
||||
title: 'HabitTrove',
|
||||
description: 'Track your habits and get rewarded',
|
||||
|
||||
@@ -1,26 +1,24 @@
|
||||
'use client'
|
||||
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import { Switch } from '@/components/ui/switch';
|
||||
import { DynamicTimeNoSSR } from '@/components/DynamicTimeNoSSR';
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Switch } from '@/components/ui/switch';
|
||||
import {
|
||||
Tooltip,
|
||||
TooltipContent,
|
||||
TooltipProvider,
|
||||
TooltipTrigger,
|
||||
} from "@/components/ui/tooltip";
|
||||
import { DynamicTimeNoSSR } from '@/components/DynamicTimeNoSSR';
|
||||
import { toast } from '@/hooks/use-toast';
|
||||
import { serverSettingsAtom, settingsAtom } from '@/lib/atoms';
|
||||
import { Settings, WeekDay } from '@/lib/types';
|
||||
import { useAtom } from 'jotai';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import { settingsAtom, serverSettingsAtom } from '@/lib/atoms';
|
||||
import { Settings, WeekDay } from '@/lib/types'
|
||||
import { saveSettings, uploadAvatar } from '../actions/data'
|
||||
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar'
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { User, Info } from 'lucide-react'; // Import Info icon
|
||||
import { toast } from '@/hooks/use-toast'
|
||||
import { Info } from 'lucide-react'; // Import Info icon
|
||||
import { useSession } from 'next-auth/react'; // signOut removed
|
||||
import { useTranslations } from 'next-intl';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { saveSettings } from '../actions/data';
|
||||
// AlertDialog components and useState removed
|
||||
// Trash2 icon removed
|
||||
|
||||
|
||||
10
app/tasks/page.tsx
Normal file
10
app/tasks/page.tsx
Normal file
@@ -0,0 +1,10 @@
|
||||
import HabitList from '@/components/HabitList'
|
||||
|
||||
export default function TasksPage() {
|
||||
return (
|
||||
<div className="flex flex-col">
|
||||
<HabitList isTasksView={true} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import Layout from '@/components/Layout'
|
||||
import WishlistManager from '@/components/WishlistManager'
|
||||
|
||||
export default function WishlistPage() {
|
||||
|
||||
@@ -57,11 +57,13 @@ export default function AboutModal({ onClose }: AboutModalProps) {
|
||||
>
|
||||
@dohsimpson
|
||||
</a>
|
||||
<br/>
|
||||
Fork by <a href="https://github.com/ManInDark" target="_blank" rel="noopener noreferrer" className="font-medium hover:underline">@ManInDark</a>
|
||||
</div>
|
||||
|
||||
<div className="flex justify-center">
|
||||
<a
|
||||
href="https://github.com/dohsimpson/habittrove"
|
||||
href="https://github.com/ManInDark/HabitTrove"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
>
|
||||
|
||||
@@ -1,24 +1,24 @@
|
||||
'use client'
|
||||
|
||||
import { useState } from 'react'
|
||||
import { RRule, RRuleSet, rrulestr } from 'rrule'
|
||||
import { useAtom } from 'jotai'
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { settingsAtom, browserSettingsAtom, usersAtom, currentUserAtom } from '@/lib/atoms'
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from '@/components/ui/dialog'
|
||||
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Avatar, AvatarImage, AvatarFallback } from '@/components/ui/avatar'
|
||||
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { Textarea } from '@/components/ui/textarea'
|
||||
import { Zap } from 'lucide-react'
|
||||
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover'
|
||||
import { Habit, SafeUser } from '@/lib/types'
|
||||
import EmojiPickerButton from './EmojiPickerButton'
|
||||
import ModalOverlay from './ModalOverlay' // Import the new component
|
||||
import { convertHumanReadableFrequencyToMachineReadable, convertMachineReadableFrequencyToHumanReadable, d2s, d2t, serializeRRule } from '@/lib/utils'
|
||||
import { INITIAL_DUE, INITIAL_RECURRENCE_RULE, QUICK_DATES, RECURRENCE_RULE_MAP, MAX_COIN_LIMIT } from '@/lib/constants'
|
||||
import { Textarea } from '@/components/ui/textarea'
|
||||
import { currentUserAtom, settingsAtom, usersAtom } from '@/lib/atoms'
|
||||
import { INITIAL_DUE, INITIAL_RECURRENCE_RULE, MAX_COIN_LIMIT, QUICK_DATES } from '@/lib/constants'
|
||||
import { Habit } from '@/lib/types'
|
||||
import { convertHumanReadableFrequencyToMachineReadable, convertMachineReadableFrequencyToHumanReadable, d2t, serializeRRule } from '@/lib/utils'
|
||||
import { useAtom } from 'jotai'
|
||||
import { Zap } from 'lucide-react'
|
||||
import { DateTime } from 'luxon'
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { useState } from 'react'
|
||||
import { RRule } from 'rrule'
|
||||
import EmojiPickerButton from './EmojiPickerButton'
|
||||
import ModalOverlay from './ModalOverlay'; // Import the new component
|
||||
|
||||
|
||||
interface AddEditHabitModalProps {
|
||||
@@ -45,7 +45,6 @@ export default function AddEditHabitModal({ onClose, onSave, habit, isTask }: Ad
|
||||
const [ruleText, setRuleText] = useState<string>(initialRuleText)
|
||||
const [currentUser] = useAtom(currentUserAtom)
|
||||
const [isQuickDatesOpen, setIsQuickDatesOpen] = useState(false)
|
||||
const [errorMessage, setErrorMessage] = useState<string | null>(null); // State for validation message
|
||||
const [selectedUserIds, setSelectedUserIds] = useState<string[]>((habit?.userIds || []).filter(id => id !== currentUser?.id))
|
||||
const [usersData] = useAtom(usersAtom)
|
||||
const users = usersData.users
|
||||
@@ -87,6 +86,8 @@ export default function AddEditHabitModal({ onClose, onSave, habit, isTask }: Ad
|
||||
})
|
||||
}
|
||||
|
||||
const { result, message: errorMessage } = convertHumanReadableFrequencyToMachineReadable({ text: ruleText, timezone: settings.system.timezone, isRecurring: isRecurRule });
|
||||
|
||||
return (
|
||||
<>
|
||||
<ModalOverlay />
|
||||
@@ -184,25 +185,9 @@ export default function AddEditHabitModal({ onClose, onSave, habit, isTask }: Ad
|
||||
</div>
|
||||
{/* rrule input (habit) */}
|
||||
<div className="col-start-2 col-span-3 text-sm">
|
||||
{(() => {
|
||||
let displayText = '';
|
||||
const { result, message } = convertHumanReadableFrequencyToMachineReadable({ text: ruleText, timezone: settings.system.timezone, isRecurring: isRecurRule });
|
||||
if (message !== errorMessage) { // Only update if it changed to avoid re-renders
|
||||
setErrorMessage(message);
|
||||
}
|
||||
displayText = convertMachineReadableFrequencyToHumanReadable({ frequency: result, isRecurRule, timezone: settings.system.timezone })
|
||||
|
||||
return (
|
||||
<>
|
||||
<span className={errorMessage ? 'text-destructive' : 'text-muted-foreground'}>
|
||||
{displayText}
|
||||
</span>
|
||||
{errorMessage && (
|
||||
<p className="text-destructive text-xs mt-1">{errorMessage}</p>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
})()}
|
||||
<span className={errorMessage ? 'text-destructive' : 'text-muted-foreground'}>
|
||||
{errorMessage ? errorMessage : convertMachineReadableFrequencyToHumanReadable({ frequency: result, isRecurRule, timezone: settings.system.timezone })}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<div className="grid grid-cols-4 items-center gap-4">
|
||||
@@ -336,4 +321,3 @@ export default function AddEditHabitModal({ onClose, onSave, habit, isTask }: Ad
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -1,20 +1,19 @@
|
||||
import { useState, useEffect } from 'react'
|
||||
import { useAtom } from 'jotai'
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { usersAtom, currentUserAtom } from '@/lib/atoms'
|
||||
import { Avatar, AvatarFallback, AvatarImage } from './ui/avatar'
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from '@/components/ui/dialog'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { Textarea } from '@/components/ui/textarea'
|
||||
import { currentUserAtom, usersAtom } from '@/lib/atoms'
|
||||
import { MAX_COIN_LIMIT } from '@/lib/constants'
|
||||
import { WishlistItemType } from '@/lib/types'
|
||||
import { useAtom } from 'jotai'
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { useEffect, useState } from 'react'
|
||||
import EmojiPickerButton from './EmojiPickerButton'
|
||||
import ModalOverlay from './ModalOverlay'
|
||||
import { MAX_COIN_LIMIT } from '@/lib/constants'
|
||||
import { Avatar, AvatarFallback, AvatarImage } from './ui/avatar'
|
||||
|
||||
interface AddEditWishlistItemModalProps {
|
||||
isOpen: boolean
|
||||
setIsOpen: (isOpen: boolean) => void
|
||||
editingItem: WishlistItemType | null
|
||||
setEditingItem: (item: WishlistItemType | null) => void
|
||||
@@ -23,7 +22,6 @@ interface AddEditWishlistItemModalProps {
|
||||
}
|
||||
|
||||
export default function AddEditWishlistItemModal({
|
||||
isOpen,
|
||||
setIsOpen,
|
||||
editingItem,
|
||||
setEditingItem,
|
||||
|
||||
@@ -1,15 +1,15 @@
|
||||
'use client'
|
||||
|
||||
import { ReactNode, useEffect, useCallback, useState, Suspense } from 'react'
|
||||
import { useAtom, useSetAtom, useAtomValue } from 'jotai'
|
||||
import { aboutOpenAtom, pomodoroAtom, userSelectAtom, currentUserIdAtom, clientFreshnessTokenAtom } from '@/lib/atoms'
|
||||
import PomodoroTimer from './PomodoroTimer'
|
||||
import UserSelectModal from './UserSelectModal'
|
||||
import { useSession } from 'next-auth/react'
|
||||
import AboutModal from './AboutModal'
|
||||
import LoadingSpinner from './LoadingSpinner'
|
||||
import { checkDataFreshness as checkServerDataFreshness } from '@/app/actions/data'
|
||||
import RefreshBanner from './RefreshBanner'
|
||||
import { checkDataFreshness as checkServerDataFreshness } from '@/app/actions/data';
|
||||
import { aboutOpenAtom, clientFreshnessTokenAtom, currentUserIdAtom, pomodoroAtom, userSelectAtom } from '@/lib/atoms';
|
||||
import { useAtom, useAtomValue, useSetAtom } from 'jotai';
|
||||
import { useSession } from 'next-auth/react';
|
||||
import { ReactNode, Suspense, useCallback, useEffect, useState } from 'react';
|
||||
import AboutModal from './AboutModal';
|
||||
import LoadingSpinner from './LoadingSpinner';
|
||||
import PomodoroTimer from './PomodoroTimer';
|
||||
import RefreshBanner from './RefreshBanner';
|
||||
import UserSelectModal from './UserSelectModal';
|
||||
|
||||
function ClientWrapperContent({ children }: { children: ReactNode }) {
|
||||
const [pomo] = useAtom(pomodoroAtom)
|
||||
|
||||
@@ -1,23 +1,23 @@
|
||||
'use client'
|
||||
|
||||
import { useState, useEffect, useRef } from 'react' // Import useEffect, useRef
|
||||
import { useSearchParams } from 'next/navigation' // Import useSearchParams
|
||||
import { t2d, d2s, getNow, isSameDate } from '@/lib/utils'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { FormattedNumber } from '@/components/FormattedNumber'
|
||||
import { History, Pencil } from 'lucide-react'
|
||||
import { Avatar, AvatarImage, AvatarFallback } from '@/components/ui/avatar'
|
||||
import EmptyState from './EmptyState'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import { settingsAtom, usersAtom, currentUserAtom } from '@/lib/atoms'
|
||||
import Link from 'next/link'
|
||||
import { useAtom } from 'jotai'
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { useCoins } from '@/hooks/useCoins'
|
||||
import { currentUserAtom, settingsAtom, usersAtom } from '@/lib/atoms'
|
||||
import { MAX_COIN_LIMIT } from '@/lib/constants'
|
||||
import { TransactionNoteEditor } from './TransactionNoteEditor'
|
||||
import { TransactionType } from '@/lib/types'
|
||||
import { d2s, t2d } from '@/lib/utils'
|
||||
import { useAtom } from 'jotai'
|
||||
import { History } from 'lucide-react'
|
||||
import { useTranslations } from 'next-intl'
|
||||
import Link from 'next/link'
|
||||
import { useSearchParams } from 'next/navigation'; // Import useSearchParams
|
||||
import { useEffect, useRef, useState } from 'react'; // Import useEffect, useRef
|
||||
import EmptyState from './EmptyState'
|
||||
import { TransactionNoteEditor } from './TransactionNoteEditor'
|
||||
|
||||
export default function CoinsManager() {
|
||||
const t = useTranslations('CoinsManager')
|
||||
@@ -46,6 +46,7 @@ export default function CoinsManager() {
|
||||
const highlightId = searchParams.get('highlight')
|
||||
const userIdFromQuery = searchParams.get('user') // Get user ID from query
|
||||
const transactionRefs = useRef<Record<string, HTMLDivElement | null>>({});
|
||||
const PAGE_ENTRY_COUNTS = [10, 50, 100, 500];
|
||||
|
||||
// Effect to set selected user from query param if admin
|
||||
useEffect(() => {
|
||||
@@ -56,7 +57,7 @@ export default function CoinsManager() {
|
||||
}
|
||||
}
|
||||
// Only run when userIdFromQuery or currentUser changes, avoid re-running on selectedUser change within this effect
|
||||
}, [userIdFromQuery, currentUser, usersData.users]);
|
||||
}, [userIdFromQuery, currentUser, usersData.users, selectedUser]);
|
||||
|
||||
// Effect to scroll to highlighted transaction
|
||||
useEffect(() => {
|
||||
@@ -106,7 +107,7 @@ export default function CoinsManager() {
|
||||
<h1 className="text-xl xs:text-3xl font-bold mr-6">{t('title')}</h1>
|
||||
{currentUser?.isAdmin && (
|
||||
<select
|
||||
className="w-[110px] xs:w-[200px] rounded-md border border-input bg-background px-3 py-2"
|
||||
className="border rounded p-2"
|
||||
value={selectedUser}
|
||||
onChange={(e) => setSelectedUser(e.target.value)}
|
||||
>
|
||||
@@ -274,9 +275,7 @@ export default function CoinsManager() {
|
||||
setCurrentPage(1) // Reset to first page when changing page size
|
||||
}}
|
||||
>
|
||||
<option value={50}>50</option>
|
||||
<option value={100}>100</option>
|
||||
<option value={500}>500</option>
|
||||
{PAGE_ENTRY_COUNTS.map(n => <option key={n} value={n}>{n}</option>)}
|
||||
</select>
|
||||
<span className="text-sm text-muted-foreground">{t('entriesSuffix')}</span>
|
||||
</div>
|
||||
@@ -312,6 +311,7 @@ export default function CoinsManager() {
|
||||
}
|
||||
|
||||
const isHighlighted = transaction.id === highlightId;
|
||||
const transactionUser = usersData.users.find(u => u.id === transaction.userId);
|
||||
return (
|
||||
<div
|
||||
key={transaction.id}
|
||||
@@ -340,12 +340,12 @@ export default function CoinsManager() {
|
||||
{transaction.userId && currentUser?.isAdmin && (
|
||||
<Avatar className="h-6 w-6">
|
||||
<AvatarImage
|
||||
src={usersData.users.find(u => u.id === transaction.userId)?.avatarPath ?
|
||||
`/api/avatars/${usersData.users.find(u => u.id === transaction.userId)?.avatarPath?.split('/').pop()}` : undefined}
|
||||
alt={usersData.users.find(u => u.id === transaction.userId)?.username}
|
||||
src={transactionUser?.avatarPath ?
|
||||
`/api/avatars/${transactionUser?.avatarPath?.split('/').pop()}` : undefined}
|
||||
alt={transactionUser?.username}
|
||||
/>
|
||||
<AvatarFallback>
|
||||
{usersData.users.find(u => u.id === transaction.userId)?.username?.[0] || '?'}
|
||||
{transactionUser?.username?.[0] || '?'}
|
||||
</AvatarFallback>
|
||||
</Avatar>
|
||||
)}
|
||||
|
||||
@@ -1,9 +1,7 @@
|
||||
import { Badge } from "@/components/ui/badge"
|
||||
import { useAtom } from 'jotai'
|
||||
import { completedHabitsMapAtom, habitsAtom, habitsByDateFamily } from '@/lib/atoms'
|
||||
import { completedHabitsMapAtom, habitsByDateFamily, settingsAtom } from '@/lib/atoms'
|
||||
import { getTodayInTimezone } from '@/lib/utils'
|
||||
// import { useHabits } from '@/hooks/useHabits' // Not used
|
||||
import { settingsAtom } from '@/lib/atoms'
|
||||
import { useAtom } from 'jotai'
|
||||
import { useTranslations } from 'next-intl'
|
||||
|
||||
interface CompletionCountBadgeProps {
|
||||
|
||||
@@ -1,36 +1,33 @@
|
||||
import { Circle, Coins, ArrowRight, CircleCheck, ChevronDown, ChevronUp, Plus, Pin, AlertTriangle } from 'lucide-react' // Removed unused icons
|
||||
import CompletionCountBadge from './CompletionCountBadge'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import {
|
||||
ContextMenu,
|
||||
ContextMenuContent,
|
||||
ContextMenuItem,
|
||||
ContextMenuSeparator,
|
||||
ContextMenuTrigger,
|
||||
ContextMenuTrigger
|
||||
} from "@/components/ui/context-menu"
|
||||
import { cn } from '@/lib/utils'
|
||||
import Link from 'next/link'
|
||||
import { useState } from 'react'
|
||||
import { useAtom } from 'jotai'
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { pomodoroAtom, settingsAtom, completedHabitsMapAtom, browserSettingsAtom, BrowserSettings, hasTasksAtom } from '@/lib/atoms'
|
||||
import { getTodayInTimezone, isSameDate, t2d, d2t, getNow, isHabitDue, isTaskOverdue } from '@/lib/utils'
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { Progress } from '@/components/ui/progress'
|
||||
import {
|
||||
Tooltip,
|
||||
TooltipContent,
|
||||
TooltipProvider,
|
||||
TooltipTrigger,
|
||||
} from "@/components/ui/tooltip"
|
||||
import { Progress } from '@/components/ui/progress'
|
||||
import { Settings, WishlistItemType } from '@/lib/types'
|
||||
import { Habit } from '@/lib/types'
|
||||
import Linkify from './linkify'
|
||||
import { useHabits } from '@/hooks/useHabits'
|
||||
import { browserSettingsAtom, completedHabitsMapAtom, hasTasksAtom, pomodoroAtom, settingsAtom } from '@/lib/atoms'
|
||||
import { Habit, WishlistItemType } from '@/lib/types'
|
||||
import { cn, d2t, getNow, getTodayInTimezone, isHabitDue, isSameDate, isTaskOverdue, t2d } from '@/lib/utils'
|
||||
import { useAtom } from 'jotai'
|
||||
import { AlertTriangle, ArrowRight, ChevronDown, ChevronUp, Circle, CircleCheck, Coins, Pin, Plus } from 'lucide-react'; // Removed unused icons
|
||||
import { useTranslations } from 'next-intl'
|
||||
import Link from 'next/link'
|
||||
import { useState } from 'react'
|
||||
import AddEditHabitModal from './AddEditHabitModal'
|
||||
import CompletionCountBadge from './CompletionCountBadge'
|
||||
import ConfirmDialog from './ConfirmDialog'
|
||||
import { Button } from './ui/button'
|
||||
import { HabitContextMenuItems } from './HabitContextMenuItems'
|
||||
import Linkify from './linkify'
|
||||
import { Button } from './ui/button'
|
||||
import { DESKTOP_DISPLAY_ITEM_COUNT } from '@/lib/constants'
|
||||
|
||||
interface UpcomingItemsProps {
|
||||
habits: Habit[]
|
||||
@@ -169,7 +166,7 @@ const ItemSection = ({
|
||||
const bTarget = b.targetCompletions || 1;
|
||||
return bTarget - aTarget;
|
||||
})
|
||||
.slice(0, currentExpanded ? undefined : 5)
|
||||
.slice(0, currentExpanded ? undefined : DESKTOP_DISPLAY_ITEM_COUNT)
|
||||
.map((habit) => {
|
||||
const completionsToday = habit.completions.filter(completion =>
|
||||
isSameDate(t2d({ timestamp: completion, timezone: settings.system.timezone }), t2d({ timestamp: d2t({ dateTime: getNow({ timezone: settings.system.timezone }) }), timezone: settings.system.timezone }))
|
||||
@@ -226,12 +223,6 @@ const ItemSection = ({
|
||||
<Link
|
||||
href={`/habits?highlight=${habit.id}`}
|
||||
className="flex items-center gap-1 hover:text-primary transition-colors"
|
||||
onClick={() => {
|
||||
const newViewType = isTask ? 'tasks' : 'habits';
|
||||
if (browserSettings.viewType !== newViewType) {
|
||||
setBrowserSettings(prev => ({ ...prev, viewType: newViewType }));
|
||||
}
|
||||
}}
|
||||
>
|
||||
{isTask && isTaskOverdue(habit, settings.system.timezone) && !isCompleted && (
|
||||
<TooltipProvider>
|
||||
@@ -305,7 +296,7 @@ const ItemSection = ({
|
||||
onClick={() => setCurrentExpanded(!currentExpanded)}
|
||||
className="text-sm text-muted-foreground hover:text-primary flex items-center gap-1"
|
||||
>
|
||||
{currentExpanded ? (
|
||||
{items.length > DESKTOP_DISPLAY_ITEM_COUNT && (currentExpanded ? (
|
||||
<>
|
||||
{t('showLessButton')}
|
||||
<ChevronUp className="h-3 w-3" />
|
||||
@@ -315,17 +306,11 @@ const ItemSection = ({
|
||||
{t('showAllButton')}
|
||||
<ChevronDown className="h-3 w-3" />
|
||||
</>
|
||||
)}
|
||||
))}
|
||||
</button>
|
||||
<Link
|
||||
href={viewLink}
|
||||
className="text-sm text-muted-foreground hover:text-primary flex items-center gap-1"
|
||||
onClick={() => {
|
||||
const newViewType = isTask ? 'tasks' : 'habits';
|
||||
if (browserSettings.viewType !== newViewType) {
|
||||
setBrowserSettings(prev => ({ ...prev, viewType: newViewType }));
|
||||
}
|
||||
}}
|
||||
>
|
||||
View
|
||||
<ArrowRight className="h-3 w-3" />
|
||||
@@ -460,7 +445,7 @@ export default function DailyOverview({
|
||||
) : (
|
||||
<>
|
||||
{sortedWishlistItems
|
||||
.slice(0, browserSettings.expandedWishlist ? undefined : 5)
|
||||
.slice(0, browserSettings.expandedWishlist ? undefined : DESKTOP_DISPLAY_ITEM_COUNT)
|
||||
.map((item) => {
|
||||
const isRedeemable = item.coinCost <= coinBalance
|
||||
return (
|
||||
@@ -517,7 +502,7 @@ export default function DailyOverview({
|
||||
onClick={() => setBrowserSettings(prev => ({ ...prev, expandedWishlist: !prev.expandedWishlist }))}
|
||||
className="text-sm text-muted-foreground hover:text-primary flex items-center gap-1"
|
||||
>
|
||||
{browserSettings.expandedWishlist ? (
|
||||
{wishlistItems.length > DESKTOP_DISPLAY_ITEM_COUNT && (browserSettings.expandedWishlist ? (
|
||||
<>
|
||||
{t('showLessButton')}
|
||||
<ChevronUp className="h-3 w-3" />
|
||||
@@ -527,7 +512,7 @@ export default function DailyOverview({
|
||||
{t('showAllButton')}
|
||||
<ChevronDown className="h-3 w-3" />
|
||||
</>
|
||||
)}
|
||||
))}
|
||||
</button>
|
||||
<Link
|
||||
href="/wishlist"
|
||||
|
||||
@@ -1,19 +1,17 @@
|
||||
'use client'
|
||||
|
||||
import { useCoins } from '@/hooks/useCoins'
|
||||
import { habitsAtom, wishlistAtom } from '@/lib/atoms'
|
||||
import { useAtom } from 'jotai'
|
||||
import { wishlistAtom, habitsAtom, settingsAtom } from '@/lib/atoms'
|
||||
import { useTranslations } from 'next-intl'
|
||||
import CoinBalance from './CoinBalance'
|
||||
import DailyOverview from './DailyOverview'
|
||||
import HabitStreak from './HabitStreak'
|
||||
import CoinBalance from './CoinBalance'
|
||||
// import { useHabits } from '@/hooks/useHabits' // useHabits is not used
|
||||
import { useCoins } from '@/hooks/useCoins'
|
||||
import { useTranslations } from 'next-intl';
|
||||
|
||||
export default function Dashboard() {
|
||||
const t = useTranslations('Dashboard');
|
||||
const [habitsData] = useAtom(habitsAtom)
|
||||
const habits = habitsData.habits
|
||||
const [settings] = useAtom(settingsAtom)
|
||||
const { balance } = useCoins()
|
||||
const [wishlist] = useAtom(wishlistAtom)
|
||||
const wishlistItems = wishlist.items
|
||||
|
||||
@@ -1,42 +0,0 @@
|
||||
import Link from 'next/link'
|
||||
import type { ElementType } from 'react'
|
||||
|
||||
export interface NavItemType {
|
||||
icon: ElementType;
|
||||
label: string;
|
||||
href: string;
|
||||
position: 'main' | 'bottom';
|
||||
}
|
||||
|
||||
interface DesktopNavDisplayProps {
|
||||
navItems: NavItemType[];
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export default function DesktopNavDisplay({ navItems, className }: DesktopNavDisplayProps) {
|
||||
// Filter for items relevant to desktop view, typically 'main' position
|
||||
const desktopNavItems = navItems.filter(item => item.position === 'main');
|
||||
|
||||
return (
|
||||
<div className={`hidden lg:flex lg:flex-shrink-0 ${className || ''}`}>
|
||||
<div className="flex flex-col w-64">
|
||||
<div className="flex flex-col h-0 flex-1 bg-gray-800">
|
||||
<div className="flex-1 flex flex-col pt-5 pb-4 overflow-y-auto">
|
||||
<nav className="mt-5 flex-1 px-2 space-y-1">
|
||||
{desktopNavItems.map((item) => (
|
||||
<Link
|
||||
key={item.label} // Assuming labels are unique
|
||||
href={item.href}
|
||||
className="group flex items-center px-2 py-2 text-sm leading-6 font-medium rounded-md text-gray-300 hover:text-white hover:bg-gray-700"
|
||||
>
|
||||
<item.icon className="mr-4 flex-shrink-0 h-6 w-6 text-gray-400" aria-hidden="true" />
|
||||
{item.label}
|
||||
</Link>
|
||||
))}
|
||||
</nav>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,19 +1,18 @@
|
||||
'use client'
|
||||
|
||||
import { useState, useMemo, useCallback } from 'react'
|
||||
import CompletionCountBadge from '@/components/CompletionCountBadge'
|
||||
import { Calendar } from '@/components/ui/calendar'
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import CompletionCountBadge from '@/components/CompletionCountBadge'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Check, Circle, CircleCheck } from 'lucide-react'
|
||||
import { d2s, getNow, t2d, isHabitDue, getISODate, getCompletionsForDate } from '@/lib/utils'
|
||||
import { useAtom } from 'jotai'
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { useHabits } from '@/hooks/useHabits'
|
||||
import { habitsAtom, settingsAtom, completedHabitsMapAtom, hasTasksAtom } from '@/lib/atoms'
|
||||
import { DateTime } from 'luxon'
|
||||
import Linkify from './linkify'
|
||||
import { completedHabitsMapAtom, habitsAtom, hasTasksAtom, settingsAtom } from '@/lib/atoms'
|
||||
import { Habit } from '@/lib/types'
|
||||
import { d2s, getCompletionsForDate, getISODate, getNow, isHabitDue } from '@/lib/utils'
|
||||
import { useAtom } from 'jotai'
|
||||
import { Circle, CircleCheck } from 'lucide-react'
|
||||
import { DateTime } from 'luxon'
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { useCallback, useMemo, useState } from 'react'
|
||||
import Linkify from './linkify'
|
||||
|
||||
export default function HabitCalendar() {
|
||||
const t = useTranslations('HabitCalendar')
|
||||
@@ -44,7 +43,7 @@ export default function HabitCalendar() {
|
||||
|
||||
return (
|
||||
<div>
|
||||
<h1 className="text-xl xs:text-3xl font-semibold mb-6">{t('title')}</h1>
|
||||
<h1 className="text-xl xs:text-3xl font-bold mb-6">{t('title')}</h1>
|
||||
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Habit, User } from '@/lib/types';
|
||||
import { Habit } from '@/lib/types';
|
||||
import { useHabits } from '@/hooks/useHabits';
|
||||
import { useAtom } from 'jotai';
|
||||
import { pomodoroAtom, settingsAtom, currentUserAtom } from '@/lib/atoms';
|
||||
|
||||
@@ -1,25 +1,21 @@
|
||||
import { Habit, SafeUser, User, Permission } from '@/lib/types'
|
||||
import { useAtom } from 'jotai'
|
||||
import { settingsAtom, pomodoroAtom, browserSettingsAtom, usersAtom, currentUserAtom } from '@/lib/atoms'
|
||||
import { getTodayInTimezone, isSameDate, t2d, d2t, getNow, d2s, getCompletionsForToday, isTaskOverdue, convertMachineReadableFrequencyToHumanReadable } from '@/lib/utils'
|
||||
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Coins, Edit, Check, Undo2, MoreVertical, Pin } from 'lucide-react'
|
||||
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuTrigger,
|
||||
DropdownMenuTrigger
|
||||
} from '@/components/ui/dropdown-menu'
|
||||
import { useEffect, useState } from 'react'
|
||||
import { useHabits } from '@/hooks/useHabits'
|
||||
import { currentUserAtom, settingsAtom, usersAtom } from '@/lib/atoms'
|
||||
import { Habit, User } from '@/lib/types'
|
||||
import { convertMachineReadableFrequencyToHumanReadable, getCompletionsForToday, hasPermission, isTaskOverdue } from '@/lib/utils'
|
||||
import { useAtom } from 'jotai'
|
||||
import { Check, Coins, Edit, MoreVertical, Pin, Undo2 } from 'lucide-react'
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { INITIAL_RECURRENCE_RULE, RECURRENCE_RULE_MAP } from '@/lib/constants'
|
||||
import { DateTime } from 'luxon'
|
||||
import { Avatar, AvatarFallback, AvatarImage } from './ui/avatar'
|
||||
import { hasPermission } from '@/lib/utils'
|
||||
import { usePathname } from 'next/navigation'
|
||||
import { useEffect, useState } from 'react'
|
||||
import { HabitContextMenuItems } from './HabitContextMenuItems'
|
||||
import { Avatar, AvatarFallback, AvatarImage } from './ui/avatar'
|
||||
|
||||
interface HabitItemProps {
|
||||
habit: Habit
|
||||
@@ -48,21 +44,18 @@ const renderUserAvatars = (habit: Habit, currentUser: User | null, usersData: {
|
||||
|
||||
|
||||
export default function HabitItem({ habit, onEdit, onDelete }: HabitItemProps) {
|
||||
const { completeHabit, undoComplete, archiveHabit, unarchiveHabit, saveHabit } = useHabits()
|
||||
const { completeHabit, undoComplete } = useHabits()
|
||||
const [settings] = useAtom(settingsAtom)
|
||||
const [_, setPomo] = useAtom(pomodoroAtom)
|
||||
const completionsToday = getCompletionsForToday({ habit, timezone: settings.system.timezone })
|
||||
const target = habit.targetCompletions || 1
|
||||
const isCompletedToday = completionsToday >= target
|
||||
const [isHighlighted, setIsHighlighted] = useState(false)
|
||||
const t = useTranslations('HabitItem');
|
||||
const [usersData] = useAtom(usersAtom)
|
||||
const pathname = usePathname();
|
||||
const [currentUser] = useAtom(currentUserAtom)
|
||||
const canWrite = hasPermission(currentUser, 'habit', 'write')
|
||||
const canInteract = hasPermission(currentUser, 'habit', 'interact')
|
||||
const [browserSettings] = useAtom(browserSettingsAtom)
|
||||
const isTasksView = browserSettings.viewType === 'tasks'
|
||||
const isRecurRule = !isTasksView
|
||||
|
||||
useEffect(() => {
|
||||
const params = new URLSearchParams(window.location.search)
|
||||
@@ -90,7 +83,7 @@ export default function HabitItem({ habit, onEdit, onDelete }: HabitItemProps) {
|
||||
>
|
||||
<CardHeader className="flex-none">
|
||||
<div className="flex justify-between items-start">
|
||||
<CardTitle className={`line-clamp-1 ${habit.archived ? 'text-gray-400 dark:text-gray-500' : ''} flex items-center ${isTasksView ? 'w-full' : ''} justify-between`}>
|
||||
<CardTitle className={`line-clamp-1 ${habit.archived ? 'text-gray-400 dark:text-gray-500' : ''} flex items-center ${pathname.includes("tasks") ? 'w-full' : ''} justify-between`}>
|
||||
<div className="flex items-center gap-1">
|
||||
{habit.pinned && (
|
||||
<Pin className="h-4 w-4 text-yellow-500" />
|
||||
@@ -116,7 +109,7 @@ export default function HabitItem({ habit, onEdit, onDelete }: HabitItemProps) {
|
||||
{t('whenLabel', {
|
||||
frequency: convertMachineReadableFrequencyToHumanReadable({
|
||||
frequency: habit.frequency,
|
||||
isRecurRule,
|
||||
isRecurRule: pathname.includes("habits"),
|
||||
timezone: settings.system.timezone
|
||||
})
|
||||
})}
|
||||
|
||||
@@ -1,32 +1,28 @@
|
||||
'use client'
|
||||
|
||||
import { useState, useMemo, useEffect } from 'react' // Added useMemo, useEffect
|
||||
import { Plus, ArrowUpNarrowWide, ArrowDownWideNarrow, Search } from 'lucide-react' // Added sort icons, Search icon
|
||||
import { useAtom } from 'jotai'
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { habitsAtom, settingsAtom, browserSettingsAtom } from '@/lib/atoms'
|
||||
import EmptyState from './EmptyState'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import HabitItem from './HabitItem'
|
||||
import { Input } from '@/components/ui/input'; // Added
|
||||
import { Label } from '@/components/ui/label'; // Added
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'; // Added
|
||||
import { useHabits } from '@/hooks/useHabits'
|
||||
import { habitsAtom } from '@/lib/atoms'
|
||||
import { HabitIcon, TaskIcon } from '@/lib/constants'
|
||||
import { Habit } from '@/lib/types'
|
||||
import { getHabitFreq } from '@/lib/utils'; // Added
|
||||
import { useAtom } from 'jotai'
|
||||
import { ArrowDownWideNarrow, ArrowUpNarrowWide, Plus, Search } from 'lucide-react'; // Added sort icons, Search icon
|
||||
import { DateTime } from 'luxon'; // Added
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { useEffect, useMemo, useState } from 'react'; // Added useMemo, useEffect
|
||||
import AddEditHabitModal from './AddEditHabitModal'
|
||||
import ConfirmDialog from './ConfirmDialog'
|
||||
import { Habit } from '@/lib/types'
|
||||
import { useHabits } from '@/hooks/useHabits'
|
||||
import { HabitIcon, TaskIcon } from '@/lib/constants'
|
||||
import { ViewToggle } from './ViewToggle'
|
||||
import { Input } from '@/components/ui/input' // Added
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select' // Added
|
||||
import { Label } from '@/components/ui/label' // Added
|
||||
import { DateTime } from 'luxon' // Added
|
||||
import { getHabitFreq } from '@/lib/utils' // Added
|
||||
import EmptyState from './EmptyState'
|
||||
import HabitItem from './HabitItem'
|
||||
|
||||
export default function HabitList() {
|
||||
export default function HabitList({ isTasksView }: { isTasksView: boolean}) {
|
||||
const t = useTranslations('HabitList');
|
||||
const { saveHabit, deleteHabit } = useHabits()
|
||||
const [habitsData] = useAtom(habitsAtom) // setHabitsData removed as it's not used
|
||||
const [browserSettings] = useAtom(browserSettingsAtom)
|
||||
const isTasksView = browserSettings.viewType === 'tasks'
|
||||
// const [settings] = useAtom(settingsAtom); // settingsAtom is not directly used in HabitList itself.
|
||||
|
||||
type SortableField = 'name' | 'coinReward' | 'dueDate' | 'frequency';
|
||||
type SortOrder = 'asc' | 'desc';
|
||||
@@ -130,17 +126,11 @@ export default function HabitList() {
|
||||
{t(isTasksView ? 'myTasks' : 'myHabits')}
|
||||
</h1>
|
||||
<span>
|
||||
<Button className="mr-2" onClick={() => setModalConfig({ isOpen: true, isTask: true })}>
|
||||
<Plus className="mr-2 h-4 w-4" /> {t('addTaskButton')}
|
||||
</Button>
|
||||
<Button onClick={() => setModalConfig({ isOpen: true, isTask: false })}>
|
||||
<Plus className="mr-2 h-4 w-4" /> {t('addHabitButton')}
|
||||
<Button onClick={() => setModalConfig({ isOpen: true, isTask: isTasksView })}>
|
||||
<Plus className='mr-2 h-4 w-4' />{isTasksView ? t("addTaskButton") : t("addHabitButton")}
|
||||
</Button>
|
||||
</span>
|
||||
</div>
|
||||
<div className='py-4'>
|
||||
<ViewToggle />
|
||||
</div>
|
||||
|
||||
{/* Search and Sort Controls */}
|
||||
<div className="flex flex-col sm:flex-row items-center gap-4 my-4">
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
'use client'
|
||||
|
||||
import { Habit } from '@/lib/types'
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
|
||||
import { d2s, getNow, t2d } from '@/lib/utils' // Removed getCompletedHabitsForDate
|
||||
import { LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer } from 'recharts'
|
||||
import { useAtom } from 'jotai'
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { settingsAtom, hasTasksAtom, completedHabitsMapAtom } from '@/lib/atoms' // Added completedHabitsMapAtom
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { completedHabitsMapAtom, hasTasksAtom, settingsAtom } from '@/lib/atoms'; // Added completedHabitsMapAtom
|
||||
import { Habit } from '@/lib/types';
|
||||
import { d2s, getNow } from '@/lib/utils'; // Removed getCompletedHabitsForDate
|
||||
import { useAtom } from 'jotai';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import { CartesianGrid, Line, LineChart, ResponsiveContainer, Tooltip, XAxis, YAxis } from 'recharts';
|
||||
|
||||
interface HabitStreakProps {
|
||||
habits: Habit[]
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import { ResponsiveContainer } from 'recharts'
|
||||
import ClientWrapper from './ClientWrapper'
|
||||
import Header from './Header'
|
||||
import Navigation from './Navigation'
|
||||
@@ -6,21 +5,21 @@ import Navigation from './Navigation'
|
||||
export default function Layout({ children }: { children: React.ReactNode }) {
|
||||
return (
|
||||
<div className="flex flex-col h-screen bg-gray-100 dark:bg-gray-900 overflow-hidden">
|
||||
<ClientWrapper>
|
||||
<Header className="sticky top-0 z-50" />
|
||||
<div className="flex flex-1 overflow-hidden">
|
||||
<Navigation viewPort='main' />
|
||||
<div className="flex-1 flex flex-col">
|
||||
<main className="flex-1 overflow-x-hidden overflow-y-auto bg-gray-100 dark:bg-gray-900 relative">
|
||||
{/* responsive container (optimized for mobile) */}
|
||||
<div className="mx-auto px-2 xs:px-4 py-8 max-w-sm xs:max-w-full">
|
||||
<Header className="sticky top-0 z-50" />
|
||||
<div className="flex flex-1 overflow-hidden">
|
||||
<Navigation position='main' />
|
||||
<div className="flex-1 flex flex-col">
|
||||
<main className="flex-1 overflow-x-hidden overflow-y-auto bg-gray-100 dark:bg-gray-900 relative">
|
||||
{/* responsive container (optimized for mobile) */}
|
||||
<div className="mx-auto px-2 xs:px-4 py-8 max-w-sm xs:max-w-full">
|
||||
<ClientWrapper>
|
||||
{children}
|
||||
</div>
|
||||
</main>
|
||||
<Navigation viewPort='mobile' />
|
||||
</div>
|
||||
</ClientWrapper>
|
||||
</div>
|
||||
</main>
|
||||
<Navigation position='mobile' />
|
||||
</div>
|
||||
</ClientWrapper>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,60 +0,0 @@
|
||||
import Link from 'next/link'
|
||||
import type { ElementType } from 'react'
|
||||
|
||||
export interface NavItemType {
|
||||
icon: ElementType;
|
||||
label: string;
|
||||
href: string;
|
||||
position: 'main' | 'bottom';
|
||||
}
|
||||
|
||||
interface MobileNavDisplayProps {
|
||||
navItems: NavItemType[];
|
||||
}
|
||||
|
||||
// detect iOS: https://stackoverflow.com/a/9039885
|
||||
function iOS() {
|
||||
return [
|
||||
'iPad Simulator',
|
||||
'iPhone Simulator',
|
||||
'iPod Simulator',
|
||||
'iPad',
|
||||
'iPhone',
|
||||
'iPod',
|
||||
].includes(navigator.platform)
|
||||
// iPad on iOS 13 detection
|
||||
|| (navigator.userAgent.includes("Mac") && "ontouchend" in document)
|
||||
}
|
||||
|
||||
|
||||
export default function MobileNavDisplay({ navItems }: MobileNavDisplayProps) {
|
||||
// Filter for items relevant to mobile view, typically 'main' and 'bottom' positions
|
||||
const mobileNavItems = navItems.filter(item => item.position === 'main' || item.position === 'bottom');
|
||||
// The original code spread main and bottom items separately, effectively concatenating them.
|
||||
// If specific ordering or duplication was intended, that logic would be here.
|
||||
// For now, a simple filter and map should suffice if all items are distinct.
|
||||
// The original code: [...navItems(isTasksView).filter(item => item.position === 'main'), ...navItems(isTasksView).filter(item => item.position === 'bottom')]
|
||||
// This implies that items could be in 'main' or 'bottom'. The current navItems only have 'main'.
|
||||
// A simple combined list is fine.
|
||||
const isIOS = iOS()
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className={isIOS ? "pb-20" : "pb-16"} /> {/* Add padding at the bottom to prevent content from being hidden */}
|
||||
<nav className={`lg:hidden fixed bottom-0 left-0 right-0 bg-white dark:bg-gray-800 shadow-lg ${isIOS ? "pb-4" : ""}`}>
|
||||
<div className="grid grid-cols-5 w-full">
|
||||
{mobileNavItems.map((item) => (
|
||||
<Link
|
||||
key={item.label} // Assuming labels are unique
|
||||
href={item.href}
|
||||
className="flex flex-col items-center justify-center py-2 text-gray-600 dark:text-gray-300 hover:text-blue-500 dark:hover:text-blue-400"
|
||||
>
|
||||
<item.icon className="h-6 w-6" />
|
||||
<span className="text-xs mt-1">{item.label}</span>
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
</nav>
|
||||
</>
|
||||
);
|
||||
}
|
||||
61
components/NavDisplay.tsx
Normal file
61
components/NavDisplay.tsx
Normal file
@@ -0,0 +1,61 @@
|
||||
import { useHelpers } from '@/lib/client-helpers';
|
||||
import Link from 'next/link';
|
||||
import { usePathname } from 'next/navigation';
|
||||
import { NavItemType } from './Navigation';
|
||||
|
||||
export default function NavDisplay({ navItems, isMobile }: { navItems: NavItemType[], isMobile: boolean }) {
|
||||
const pathname = usePathname();
|
||||
const { isIOS } = useHelpers()
|
||||
|
||||
if (isMobile) {
|
||||
return (
|
||||
<>
|
||||
{isMobile && (<div className={isIOS ? "pb-20" : "pb-16"} />)}
|
||||
<nav className={`lg:hidden fixed bottom-0 left-0 right-0 bg-white dark:bg-gray-800 shadow-lg ${isIOS ? "pb-4" : ""}`}>
|
||||
<div className="grid grid-cols-6 w-full">
|
||||
{navItems.map((item) => (
|
||||
<Link
|
||||
key={item.label}
|
||||
href={item.href}
|
||||
className={"flex flex-col items-center py-2 hover:text-blue-600 dark:hover:text-blue-300 " +
|
||||
(pathname === (item.href) ?
|
||||
"text-blue-500 dark:text-blue-500" :
|
||||
"text-gray-300 dark:text-gray-300")
|
||||
}
|
||||
>
|
||||
<item.icon className="h-6 w-6" />
|
||||
<span className="text-xs mt-1">{item.label}</span>
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
</nav>
|
||||
</>
|
||||
);
|
||||
} else {
|
||||
return (
|
||||
<div className="hidden lg:flex lg:flex-shrink-0">
|
||||
<div className="flex flex-col w-64">
|
||||
<div className="flex flex-col h-0 flex-1 bg-gray-800">
|
||||
<div className="flex-1 flex flex-col pt-5 pb-4 overflow-y-auto">
|
||||
<nav className="mt-5 flex-1 px-2 space-y-1">
|
||||
{navItems.map((item) => (
|
||||
<Link
|
||||
key={item.label}
|
||||
href={item.href}
|
||||
className={"flex items-center px-2 py-2 font-medium rounded-md " +
|
||||
(pathname === (item.href) ?
|
||||
"text-blue-500 hover:text-blue-600 hover:bg-gray-700" :
|
||||
"text-gray-300 hover:text-white hover:bg-gray-700")}
|
||||
>
|
||||
<item.icon className="mr-4 flex-shrink-0 h-6 w-6" aria-hidden="true" />
|
||||
{item.label}
|
||||
</Link>
|
||||
))}
|
||||
</nav>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,70 +1,40 @@
|
||||
'use client'
|
||||
|
||||
import { Home, Calendar, Gift, Coins } from 'lucide-react'
|
||||
import { useAtom } from 'jotai'
|
||||
import { browserSettingsAtom } from '@/lib/atoms'
|
||||
import { useEffect, useState, ElementType } from 'react'
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { HabitIcon, TaskIcon } from '@/lib/constants'
|
||||
import MobileNavDisplay from './MobileNavDisplay'
|
||||
import DesktopNavDisplay from './DesktopNavDisplay'
|
||||
|
||||
type ViewPort = 'main' | 'mobile'
|
||||
import { Calendar, Coins, Gift, Home } from 'lucide-react'
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { ElementType, useEffect, useState } from 'react'
|
||||
import NavDisplay from './NavDisplay'
|
||||
|
||||
export interface NavItemType {
|
||||
icon: ElementType;
|
||||
label: string;
|
||||
href: string;
|
||||
position: 'main' | 'bottom';
|
||||
}
|
||||
|
||||
interface NavigationProps {
|
||||
className?: string
|
||||
viewPort: ViewPort
|
||||
}
|
||||
|
||||
|
||||
export default function Navigation({ className, viewPort }: NavigationProps) {
|
||||
const t = useTranslations('Navigation')
|
||||
const [isMobileView, setIsMobileView] = useState(false)
|
||||
const [browserSettings] = useAtom(browserSettingsAtom)
|
||||
const isTasksView = browserSettings.viewType === 'tasks'
|
||||
|
||||
const currentNavItems: NavItemType[] = [
|
||||
{ icon: Home, label: t('dashboard'), href: '/', position: 'main' },
|
||||
{
|
||||
icon: isTasksView ? TaskIcon : HabitIcon,
|
||||
label: isTasksView ? t('tasks') : t('habits'),
|
||||
href: '/habits',
|
||||
position: 'main'
|
||||
},
|
||||
{ icon: Calendar, label: t('calendar'), href: '/calendar', position: 'main' },
|
||||
{ icon: Gift, label: t('wishlist'), href: '/wishlist', position: 'main' },
|
||||
{ icon: Coins, label: t('coins'), href: '/coins', position: 'main' },
|
||||
]
|
||||
export default function Navigation({ position }: { position: 'main' | 'mobile' }) {
|
||||
const t = useTranslations('Navigation');
|
||||
const [isMobile, setIsMobile] = useState(window.innerWidth < 1024);
|
||||
|
||||
useEffect(() => {
|
||||
const handleResize = () => {
|
||||
setIsMobileView(window.innerWidth < 1024)
|
||||
}
|
||||
const handleResize = () => {setIsMobile(window.innerWidth < 1024); };
|
||||
window.addEventListener("resize", handleResize);
|
||||
return () => window.removeEventListener("resize", handleResize);
|
||||
}, [setIsMobile]);
|
||||
|
||||
// Set initial value
|
||||
handleResize()
|
||||
const currentNavItems: NavItemType[] = [
|
||||
{ icon: Home, label: t('dashboard'), href: '/' },
|
||||
{ icon: HabitIcon, label: t('habits'), href: '/habits' },
|
||||
{ icon: TaskIcon, label: t('tasks'), href: '/tasks' },
|
||||
{ icon: Calendar, label: t('calendar'), href: '/calendar' },
|
||||
{ icon: Gift, label: t('wishlist'), href: '/wishlist' },
|
||||
{ icon: Coins, label: t('coins'), href: '/coins' },
|
||||
]
|
||||
|
||||
// Add event listener
|
||||
window.addEventListener('resize', handleResize)
|
||||
|
||||
// Cleanup
|
||||
return () => window.removeEventListener('resize', handleResize)
|
||||
}, [])
|
||||
|
||||
if (viewPort === 'mobile' && isMobileView) {
|
||||
return <MobileNavDisplay navItems={currentNavItems} />
|
||||
if ((position === 'mobile' && isMobile) || (position === 'main' && !isMobile)) {
|
||||
return <NavDisplay navItems={currentNavItems} isMobile={isMobile} />
|
||||
}
|
||||
|
||||
if (viewPort === 'main' && !isMobileView) {
|
||||
return <DesktopNavDisplay navItems={currentNavItems} className={className} />
|
||||
else {
|
||||
return <></>
|
||||
}
|
||||
|
||||
return null // Explicitly return null if no view matches
|
||||
}
|
||||
|
||||
@@ -1,19 +1,18 @@
|
||||
import React from 'react';
|
||||
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
|
||||
import { DropdownMenuItem } from '@/components/ui/dropdown-menu';
|
||||
import { ScrollArea } from '@/components/ui/scroll-area';
|
||||
import { Separator } from '@/components/ui/separator';
|
||||
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
|
||||
import { CoinsData, HabitsData, WishlistData, UserData, User, CoinTransaction } from '@/lib/types';
|
||||
import { t2d } from '@/lib/utils';
|
||||
import Link from 'next/link';
|
||||
import { DropdownMenuItem } from '@/components/ui/dropdown-menu';
|
||||
import { Info } from 'lucide-react';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import {
|
||||
Tooltip,
|
||||
TooltipContent,
|
||||
TooltipProvider,
|
||||
TooltipTrigger,
|
||||
} from '@/components/ui/tooltip';
|
||||
import { CoinTransaction, HabitsData, User, UserData, WishlistData } from '@/lib/types';
|
||||
import { t2d } from '@/lib/utils';
|
||||
import { Info } from 'lucide-react';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import Link from 'next/link';
|
||||
|
||||
interface NotificationDropdownProps {
|
||||
currentUser: User | null;
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
'use client';
|
||||
|
||||
import { Avatar, AvatarFallback, AvatarImage } from './ui/avatar';
|
||||
import { Input } from './ui/input';
|
||||
import { Button } from './ui/button';
|
||||
import { Label } from './ui/label';
|
||||
import { User as UserIcon } from 'lucide-react';
|
||||
import { Permission, User } from '@/lib/types';
|
||||
import { toast } from '@/hooks/use-toast';
|
||||
import { useState } from 'react';
|
||||
import { User } from '@/lib/types';
|
||||
import { User as UserIcon } from 'lucide-react';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import { useState } from 'react';
|
||||
import { Avatar, AvatarFallback, AvatarImage } from './ui/avatar';
|
||||
import { Button } from './ui/button';
|
||||
import { Input } from './ui/input';
|
||||
import { Label } from './ui/label';
|
||||
|
||||
interface PasswordEntryFormProps {
|
||||
user: User;
|
||||
|
||||
@@ -1,15 +1,14 @@
|
||||
'use client'
|
||||
|
||||
import { useState, useEffect, useRef, useCallback } from 'react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Progress } from '@/components/ui/progress'
|
||||
import { Play, Pause, RotateCw, Minus, X, Clock, SkipForward } from 'lucide-react'
|
||||
import { useHabits } from '@/hooks/useHabits'
|
||||
import { habitsAtom, pomodoroAtom, pomodoroTodayCompletionsAtom } from '@/lib/atoms'
|
||||
import { cn } from '@/lib/utils'
|
||||
import { useAtom } from 'jotai'
|
||||
import { Clock, Minus, Pause, Play, RotateCw, SkipForward, X } from 'lucide-react'
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { settingsAtom, pomodoroAtom, habitsAtom, pomodoroTodayCompletionsAtom } from '@/lib/atoms'
|
||||
// import { getCompletionsForDate, getTodayInTimezone } from '@/lib/utils' // Not used after pomodoroTodayCompletionsAtom
|
||||
import { useHabits } from '@/hooks/useHabits'
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
|
||||
interface PomoConfig {
|
||||
getLabels: () => string[]
|
||||
@@ -39,7 +38,6 @@ export default function PomodoroTimer() {
|
||||
},
|
||||
}
|
||||
|
||||
const [settings] = useAtom(settingsAtom)
|
||||
const [pomo, setPomo] = useAtom(pomodoroAtom)
|
||||
const { show, selectedHabitId, autoStart, minimized } = pomo
|
||||
const [habitsData] = useAtom(habitsAtom)
|
||||
@@ -110,47 +108,48 @@ export default function PomodoroTimer() {
|
||||
document.removeEventListener('visibilitychange', handleVisibilityChange);
|
||||
releaseWakeLock()
|
||||
}
|
||||
}, [state])
|
||||
}, [state, t])
|
||||
|
||||
// Timer logic
|
||||
useEffect(() => {
|
||||
let interval: ReturnType<typeof setInterval> | null = null
|
||||
const handleTimerEnd = async () => {
|
||||
setState("stopped");
|
||||
const currentTimerType = currentTimerRef.current.type;
|
||||
currentTimerRef.current =
|
||||
currentTimerType === "focus" ? PomoConfigs.break : PomoConfigs.focus;
|
||||
setTimeLeft(currentTimerRef.current.duration);
|
||||
const newLabels = currentTimerRef.current.getLabels();
|
||||
setCurrentLabel(newLabels[Math.floor(Math.random() * newLabels.length)]);
|
||||
|
||||
if (state === 'started') {
|
||||
// update habits only after focus sessions
|
||||
if (selectedHabit && currentTimerType === "focus") {
|
||||
await completeHabit(selectedHabit);
|
||||
// The atom will automatically update with the new completions
|
||||
}
|
||||
};
|
||||
|
||||
let interval: ReturnType<typeof setInterval> | null = null;
|
||||
|
||||
if (state === "started") {
|
||||
// Calculate the target end time based on current timeLeft
|
||||
const targetEndTime = Date.now() + timeLeft * 1000
|
||||
const targetEndTime = Date.now() + timeLeft * 1000;
|
||||
|
||||
interval = setInterval(() => {
|
||||
const remaining = Math.floor((targetEndTime - Date.now()) / 1000)
|
||||
const remaining = Math.floor((targetEndTime - Date.now()) / 1000);
|
||||
|
||||
if (remaining <= 0) {
|
||||
handleTimerEnd()
|
||||
handleTimerEnd();
|
||||
} else {
|
||||
setTimeLeft(remaining)
|
||||
setTimeLeft(remaining);
|
||||
}
|
||||
}, 1000)
|
||||
}, 1000);
|
||||
}
|
||||
|
||||
// return handles any other states
|
||||
return () => {
|
||||
if (interval) clearInterval(interval)
|
||||
}
|
||||
}, [state])
|
||||
|
||||
const handleTimerEnd = async () => {
|
||||
setState("stopped")
|
||||
const currentTimerType = currentTimerRef.current.type
|
||||
currentTimerRef.current = currentTimerType === 'focus' ? PomoConfigs.break : PomoConfigs.focus
|
||||
setTimeLeft(currentTimerRef.current.duration)
|
||||
const newLabels = currentTimerRef.current.getLabels();
|
||||
setCurrentLabel(newLabels[Math.floor(Math.random() * newLabels.length)])
|
||||
|
||||
// update habits only after focus sessions
|
||||
if (selectedHabit && currentTimerType === 'focus') {
|
||||
await completeHabit(selectedHabit)
|
||||
// The atom will automatically update with the new completions
|
||||
}
|
||||
}
|
||||
if (interval) clearInterval(interval);
|
||||
};
|
||||
}, [state, timeLeft, PomoConfigs.break, PomoConfigs.focus, completeHabit, selectedHabit]);
|
||||
|
||||
const toggleTimer = () => {
|
||||
setState(prev => prev === 'started' ? 'paused' : 'started')
|
||||
|
||||
@@ -1,19 +1,19 @@
|
||||
'use client'
|
||||
|
||||
import { signOut } from "@/app/actions/user"
|
||||
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu"
|
||||
import { Settings, Info, User, Moon, Sun, Palette, ArrowRightLeft, LogOut, Crown } from "lucide-react"
|
||||
import { toast } from "@/hooks/use-toast"
|
||||
import { aboutOpenAtom, currentUserAtom, settingsAtom, userSelectAtom } from "@/lib/atoms"
|
||||
import { useAtom } from "jotai"
|
||||
import { ArrowRightLeft, Crown, Info, LogOut, Moon, Palette, Settings, Sun, User } from "lucide-react"
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { useTheme } from "next-themes"
|
||||
import Link from "next/link"
|
||||
import { useState } from "react"
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle } from './ui/dialog'
|
||||
import UserForm from './UserForm'
|
||||
import Link from "next/link"
|
||||
import { useAtom } from "jotai"
|
||||
import { aboutOpenAtom, settingsAtom, userSelectAtom, currentUserAtom } from "@/lib/atoms"
|
||||
import { useEffect, useState } from "react"
|
||||
import { useTheme } from "next-themes"
|
||||
import { signOut } from "@/app/actions/user"
|
||||
import { toast } from "@/hooks/use-toast"
|
||||
import { useTranslations } from 'next-intl'
|
||||
|
||||
export function Profile() {
|
||||
const t = useTranslations('Profile');
|
||||
|
||||
@@ -1,10 +1,6 @@
|
||||
'use client';
|
||||
|
||||
import { useState } from 'react';
|
||||
import { passwordSchema, usernameSchema } from '@/lib/zod';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import { Input } from './ui/input';
|
||||
import { Button } from './ui/button';
|
||||
import { createUser, updateUser, updateUserPassword, uploadAvatar } from '@/app/actions/data';
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
@@ -15,19 +11,22 @@ import {
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
AlertDialogTrigger,
|
||||
} from "@/components/ui/alert-dialog"
|
||||
} from "@/components/ui/alert-dialog";
|
||||
import { toast } from '@/hooks/use-toast';
|
||||
import { currentUserAtom, serverSettingsAtom, usersAtom } from '@/lib/atoms';
|
||||
import { Permission } from '@/lib/types';
|
||||
import { passwordSchema, usernameSchema } from '@/lib/zod';
|
||||
import { useAtom, useAtomValue } from 'jotai';
|
||||
import _ from 'lodash';
|
||||
import { User as UserIcon } from 'lucide-react';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import { useState } from 'react';
|
||||
import { PermissionSelector } from './PermissionSelector';
|
||||
import { Avatar, AvatarFallback, AvatarImage } from './ui/avatar';
|
||||
import { Button } from './ui/button';
|
||||
import { Input } from './ui/input';
|
||||
import { Label } from './ui/label';
|
||||
import { Switch } from './ui/switch';
|
||||
import { Permission } from '@/lib/types';
|
||||
import { toast } from '@/hooks/use-toast';
|
||||
import { useAtom, useAtomValue } from 'jotai';
|
||||
import { serverSettingsAtom, usersAtom, currentUserAtom } from '@/lib/atoms';
|
||||
import { createUser, updateUser, updateUserPassword, uploadAvatar } from '@/app/actions/data';
|
||||
import { SafeUser, User } from '@/lib/types';
|
||||
import { Avatar, AvatarFallback, AvatarImage } from './ui/avatar';
|
||||
import { User as UserIcon } from 'lucide-react';
|
||||
import _ from 'lodash';
|
||||
import { PermissionSelector } from './PermissionSelector';
|
||||
|
||||
|
||||
interface UserFormProps {
|
||||
|
||||
@@ -1,34 +1,19 @@
|
||||
'use client';
|
||||
|
||||
import { signIn } from '@/app/actions/user';
|
||||
import { toast } from '@/hooks/use-toast';
|
||||
import { currentUserAtom, usersAtom } from '@/lib/atoms';
|
||||
import { SafeUser, User } from '@/lib/types';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { Description } from '@radix-ui/react-dialog';
|
||||
import { useAtom } from 'jotai';
|
||||
import { Crown, Plus, User as UserIcon, UserRoundPen } from 'lucide-react';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import { useState } from 'react';
|
||||
import PasswordEntryForm from './PasswordEntryForm';
|
||||
import UserForm from './UserForm';
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle } from './ui/dialog';
|
||||
import { Avatar, AvatarFallback, AvatarImage } from './ui/avatar';
|
||||
import { Crown, Pencil, Plus, User as UserIcon, UserRoundPen, Trash2 } from 'lucide-react';
|
||||
import { Input } from './ui/input';
|
||||
import { Button } from './ui/button';
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
AlertDialogTrigger,
|
||||
} from "@/components/ui/alert-dialog"
|
||||
import { useAtom } from 'jotai';
|
||||
import { usersAtom, currentUserAtom } from '@/lib/atoms';
|
||||
import { signIn } from '@/app/actions/user';
|
||||
import { createUser } from '@/app/actions/data';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import { toast } from '@/hooks/use-toast';
|
||||
import { Description } from '@radix-ui/react-dialog';
|
||||
import { SafeUser, User } from '@/lib/types';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle } from './ui/dialog';
|
||||
|
||||
function UserCard({
|
||||
user,
|
||||
|
||||
@@ -1,34 +1,29 @@
|
||||
'use client'
|
||||
|
||||
import { cn } from '@/lib/utils'
|
||||
import { browserSettingsAtom, habitsAtom, settingsAtom } from '@/lib/atoms'
|
||||
import { HabitIcon, TaskIcon } from '@/lib/constants'
|
||||
import { cn, isHabitDueToday } from '@/lib/utils'
|
||||
import { useAtom } from 'jotai'
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { browserSettingsAtom, habitsAtom, settingsAtom } from '@/lib/atoms'
|
||||
import type { ViewType } from '@/lib/types'
|
||||
import { HabitIcon, TaskIcon } from '@/lib/constants'
|
||||
import { isHabitDueToday } from '@/lib/utils'
|
||||
import { usePathname, useRouter } from 'next/navigation'
|
||||
import { NotificationBadge } from './ui/notification-badge'
|
||||
|
||||
interface ViewToggleProps {
|
||||
defaultView?: ViewType
|
||||
className?: string
|
||||
}
|
||||
|
||||
export function ViewToggle({
|
||||
defaultView = 'habits',
|
||||
className
|
||||
}: ViewToggleProps) {
|
||||
const t = useTranslations('ViewToggle')
|
||||
const [browserSettings, setBrowserSettings] = useAtom(browserSettingsAtom)
|
||||
const [habits] = useAtom(habitsAtom)
|
||||
const [settings] = useAtom(settingsAtom)
|
||||
const pathname = usePathname();
|
||||
const router = useRouter();
|
||||
|
||||
const handleViewChange = (checked: boolean) => {
|
||||
const newView = checked ? 'tasks' : 'habits'
|
||||
setBrowserSettings({
|
||||
...browserSettings,
|
||||
viewType: newView,
|
||||
})
|
||||
const handleViewChange = () => {
|
||||
router.push(pathname.includes("habits") ? "/tasks" : "/habits");
|
||||
}
|
||||
|
||||
// Calculate due tasks count
|
||||
@@ -40,10 +35,10 @@ export function ViewToggle({
|
||||
<div className={cn('inline-flex rounded-full bg-muted/50 h-8', className)}>
|
||||
<div className="relative flex gap-0.5 rounded-full bg-background p-0.5 h-full">
|
||||
<button
|
||||
onClick={() => handleViewChange(false)}
|
||||
onClick={handleViewChange}
|
||||
className={cn(
|
||||
'relative z-10 rounded-full px-4 py-2 text-sm font-medium transition-colors flex items-center gap-2',
|
||||
browserSettings.viewType === 'habits' ? 'text-primary-foreground' : 'text-muted-foreground hover:text-foreground'
|
||||
pathname.includes('habits') ? 'text-primary-foreground' : 'text-muted-foreground hover:text-foreground'
|
||||
)}
|
||||
>
|
||||
<HabitIcon className="h-4 w-4" />
|
||||
@@ -52,14 +47,14 @@ export function ViewToggle({
|
||||
<NotificationBadge
|
||||
label={dueTasksCount}
|
||||
show={dueTasksCount > 0}
|
||||
variant={browserSettings.viewType === 'tasks' ? 'secondary' : 'default'}
|
||||
variant={pathname.includes('tasks') ? 'secondary' : 'default'}
|
||||
className="shadow-md"
|
||||
>
|
||||
<button
|
||||
onClick={() => handleViewChange(true)}
|
||||
onClick={handleViewChange}
|
||||
className={cn(
|
||||
'relative z-10 rounded-full px-4 py-2 text-sm font-medium transition-colors flex items-center gap-2',
|
||||
browserSettings.viewType === 'tasks' ? 'text-primary-foreground' : 'text-muted-foreground hover:text-foreground'
|
||||
pathname.includes('tasks') ? 'text-primary-foreground' : 'text-muted-foreground hover:text-foreground'
|
||||
)}
|
||||
>
|
||||
<TaskIcon className="h-4 w-4" />
|
||||
@@ -69,7 +64,7 @@ export function ViewToggle({
|
||||
<div
|
||||
className={cn(
|
||||
'absolute left-0.5 top-0.5 h-[calc(100%-0.25rem)] rounded-full bg-primary transition-transform',
|
||||
browserSettings.viewType === 'habits' ? 'w-[calc(50%-0.125rem)]' : 'w-[calc(50%-0.125rem)] translate-x-[calc(100%+0.125rem)]'
|
||||
pathname.includes('habits') ? 'w-[calc(50%-0.125rem)]' : 'w-[calc(50%-0.125rem)] translate-x-[calc(100%+0.125rem)]'
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -1,13 +1,5 @@
|
||||
import { WishlistItemType, User } from '@/lib/types'
|
||||
import { useAtom } from 'jotai'
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { usersAtom, currentUserAtom } from '@/lib/atoms'
|
||||
import { Avatar, AvatarFallback, AvatarImage } from './ui/avatar'
|
||||
import { hasPermission } from '@/lib/utils'
|
||||
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import ReactMarkdown from 'react-markdown'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Coins, Edit, Trash2, Gift, MoreVertical, Archive, ArchiveRestore } from 'lucide-react'
|
||||
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
@@ -15,6 +7,13 @@ import {
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuTrigger,
|
||||
} from '@/components/ui/dropdown-menu'
|
||||
import { currentUserAtom, usersAtom } from '@/lib/atoms'
|
||||
import { User, WishlistItemType } from '@/lib/types'
|
||||
import { hasPermission } from '@/lib/utils'
|
||||
import { useAtom } from 'jotai'
|
||||
import { Archive, ArchiveRestore, Coins, Edit, Gift, MoreVertical, Trash2 } from 'lucide-react'
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { Avatar, AvatarFallback, AvatarImage } from './ui/avatar'
|
||||
|
||||
interface WishlistItemProps {
|
||||
item: WishlistItemType
|
||||
|
||||
@@ -154,7 +154,6 @@ export default function WishlistManager() {
|
||||
</div>
|
||||
{isModalOpen &&
|
||||
<AddEditWishlistItemModal
|
||||
isOpen={isModalOpen}
|
||||
setIsOpen={setIsModalOpen}
|
||||
editingItem={editingItem}
|
||||
setEditingItem={setEditingItem}
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import { Moon, MoonIcon, Sun } from "lucide-react"
|
||||
import { Moon, Sun } from "lucide-react"
|
||||
import { useTheme } from "next-themes"
|
||||
|
||||
import { Button } from "@/components/ui/button"
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
services:
|
||||
habittrove:
|
||||
image: ghcr.io/manindark/habittrove
|
||||
container_name: habittrove
|
||||
ports:
|
||||
- "3000:3000"
|
||||
volumes:
|
||||
- "./data:/app/data"
|
||||
- "./backups:/app/backups"
|
||||
image: dohsimpson/habittrove
|
||||
environment:
|
||||
- AUTH_SECRET=your-secret-key-here # Replace with your actual secret
|
||||
|
||||
@@ -1,50 +1,23 @@
|
||||
import { useAtom } from 'jotai';
|
||||
import { useState, useEffect, useMemo } from 'react';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import { calculateCoinsEarnedToday, calculateCoinsSpentToday, calculateTotalEarned, calculateTotalSpent, calculateTransactionsToday, checkPermission, roundToInteger } from '@/lib/utils'
|
||||
import { addCoins, removeCoins, saveCoinsData } from '@/app/actions/data';
|
||||
import { toast } from '@/hooks/use-toast';
|
||||
import {
|
||||
coinsAtom,
|
||||
coinsBalanceAtom,
|
||||
coinsEarnedTodayAtom,
|
||||
coinsSpentTodayAtom,
|
||||
currentUserAtom,
|
||||
settingsAtom,
|
||||
totalEarnedAtom,
|
||||
totalSpentAtom,
|
||||
coinsSpentTodayAtom,
|
||||
transactionsTodayAtom,
|
||||
coinsBalanceAtom,
|
||||
settingsAtom,
|
||||
usersAtom,
|
||||
currentUserAtom,
|
||||
} from '@/lib/atoms'
|
||||
import { addCoins, removeCoins, saveCoinsData } from '@/app/actions/data'
|
||||
import { CoinsData, User } from '@/lib/types'
|
||||
import { toast } from '@/hooks/use-toast'
|
||||
import { MAX_COIN_LIMIT } from '@/lib/constants'
|
||||
|
||||
function handlePermissionCheck(
|
||||
user: User | undefined,
|
||||
resource: 'habit' | 'wishlist' | 'coins',
|
||||
action: 'write' | 'interact',
|
||||
tCommon: (key: string, values?: Record<string, any>) => string
|
||||
): boolean {
|
||||
if (!user) {
|
||||
toast({
|
||||
title: tCommon("authenticationRequiredTitle"),
|
||||
description: tCommon("authenticationRequiredDescription"),
|
||||
variant: "destructive",
|
||||
})
|
||||
return false
|
||||
}
|
||||
|
||||
if (!user.isAdmin && !checkPermission(user.permissions, resource, action)) {
|
||||
toast({
|
||||
title: tCommon("permissionDeniedTitle"),
|
||||
description: tCommon("permissionDeniedDescription", { action, resource }),
|
||||
variant: "destructive",
|
||||
})
|
||||
return false
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
} from '@/lib/atoms';
|
||||
import { MAX_COIN_LIMIT } from '@/lib/constants';
|
||||
import { CoinsData } from '@/lib/types';
|
||||
import { calculateCoinsEarnedToday, calculateCoinsSpentToday, calculateTotalEarned, calculateTotalSpent, calculateTransactionsToday, handlePermissionCheck, roundToInteger } from '@/lib/utils';
|
||||
import { useAtom } from 'jotai';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
|
||||
export function useCoins(options?: { selectedUser?: string }) {
|
||||
const t = useTranslations('useCoins');
|
||||
|
||||
@@ -1,54 +1,24 @@
|
||||
import { useAtom, atom } from 'jotai'
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { habitsAtom, coinsAtom, settingsAtom, usersAtom, habitFreqMapAtom, currentUserAtom } from '@/lib/atoms'
|
||||
import { addCoins, removeCoins, saveHabitsData } from '@/app/actions/data'
|
||||
import { Habit, Permission, SafeUser, User } from '@/lib/types'
|
||||
import { ToastAction } from '@/components/ui/toast'
|
||||
import { toast } from '@/hooks/use-toast'
|
||||
import { DateTime } from 'luxon'
|
||||
import { coinsAtom, currentUserAtom, habitFreqMapAtom, habitsAtom, settingsAtom, usersAtom } from '@/lib/atoms'
|
||||
import { Habit } from '@/lib/types'
|
||||
import {
|
||||
getNowInMilliseconds,
|
||||
getTodayInTimezone,
|
||||
isSameDate,
|
||||
t2d,
|
||||
d2s,
|
||||
d2t,
|
||||
getNow,
|
||||
getCompletionsForDate,
|
||||
getISODate,
|
||||
d2s,
|
||||
getNow,
|
||||
getTodayInTimezone,
|
||||
handlePermissionCheck,
|
||||
isSameDate,
|
||||
playSound,
|
||||
checkPermission
|
||||
t2d
|
||||
} from '@/lib/utils'
|
||||
import { ToastAction } from '@/components/ui/toast'
|
||||
import { useAtom } from 'jotai'
|
||||
import { Undo2 } from 'lucide-react'
|
||||
|
||||
|
||||
function handlePermissionCheck(
|
||||
user: SafeUser | User | undefined,
|
||||
resource: 'habit' | 'wishlist' | 'coins',
|
||||
action: 'write' | 'interact',
|
||||
tCommon: (key: string, values?: Record<string, any>) => string
|
||||
): boolean {
|
||||
if (!user) {
|
||||
toast({
|
||||
title: tCommon("authenticationRequiredTitle"),
|
||||
description: tCommon("authenticationRequiredDescription"),
|
||||
variant: "destructive",
|
||||
})
|
||||
return false
|
||||
}
|
||||
|
||||
if (!user.isAdmin && !checkPermission(user.permissions, resource, action)) {
|
||||
toast({
|
||||
title: tCommon("permissionDeniedTitle"),
|
||||
description: tCommon("permissionDeniedDescription", { action, resource }),
|
||||
variant: "destructive",
|
||||
})
|
||||
return false
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
import { DateTime } from 'luxon'
|
||||
import { useTranslations } from 'next-intl'
|
||||
|
||||
export function useHabits() {
|
||||
const t = useTranslations('useHabits');
|
||||
@@ -106,7 +76,7 @@ export function useHabits() {
|
||||
type: habit.isTask ? 'TASK_COMPLETION' : 'HABIT_COMPLETION',
|
||||
relatedItemId: habit.id,
|
||||
})
|
||||
isTargetReached && playSound()
|
||||
playSound()
|
||||
toast({
|
||||
title: t("completedTitle"),
|
||||
description: t("earnedCoinsDescription", { coinReward: habit.coinReward }),
|
||||
@@ -207,7 +177,7 @@ export function useHabits() {
|
||||
if (!handlePermissionCheck(currentUser, 'habit', 'write', tCommon)) return
|
||||
const newHabit = {
|
||||
...habit,
|
||||
id: habit.id || getNowInMilliseconds().toString()
|
||||
id: habit.id || crypto.randomUUID()
|
||||
}
|
||||
const updatedHabits = habit.id
|
||||
? habitsData.habits.map(h => h.id === habit.id ? newHabit : h)
|
||||
|
||||
@@ -1,40 +1,13 @@
|
||||
import { removeCoins, saveWishlistItems } from '@/app/actions/data'
|
||||
import { toast } from '@/hooks/use-toast'
|
||||
import { coinsAtom, currentUserAtom, wishlistAtom } from '@/lib/atoms'
|
||||
import { WishlistItemType } from '@/lib/types'
|
||||
import { handlePermissionCheck } from '@/lib/utils'
|
||||
import { celebrations } from '@/utils/celebrations'
|
||||
import { useAtom } from 'jotai'
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { wishlistAtom, coinsAtom, currentUserAtom } from '@/lib/atoms'
|
||||
import { saveWishlistItems, removeCoins } from '@/app/actions/data'
|
||||
import { toast } from '@/hooks/use-toast'
|
||||
import { WishlistItemType, User, SafeUser } from '@/lib/types'
|
||||
import { celebrations } from '@/utils/celebrations'
|
||||
import { checkPermission } from '@/lib/utils'
|
||||
import { useCoins } from './useCoins'
|
||||
|
||||
function handlePermissionCheck(
|
||||
user: User | SafeUser | undefined,
|
||||
resource: 'habit' | 'wishlist' | 'coins',
|
||||
action: 'write' | 'interact',
|
||||
tCommon: (key: string, values?: Record<string, any>) => string
|
||||
): boolean {
|
||||
if (!user) {
|
||||
toast({
|
||||
title: tCommon("authenticationRequiredTitle"),
|
||||
description: tCommon("authenticationRequiredDescription"),
|
||||
variant: "destructive",
|
||||
})
|
||||
return false
|
||||
}
|
||||
|
||||
if (!user.isAdmin && !checkPermission(user.permissions, resource, action)) {
|
||||
toast({
|
||||
title: tCommon("permissionDeniedTitle"),
|
||||
description: tCommon("permissionDeniedDescription", { action, resource }),
|
||||
variant: "destructive",
|
||||
})
|
||||
return false
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
export function useWishlist() {
|
||||
const t = useTranslations('useWishlist');
|
||||
const tCommon = useTranslations('Common');
|
||||
|
||||
72
lib/atoms.ts
72
lib/atoms.ts
@@ -1,58 +1,57 @@
|
||||
import { atom } from "jotai";
|
||||
import {
|
||||
getDefaultSettings,
|
||||
getDefaultHabitsData,
|
||||
getDefaultCoinsData,
|
||||
getDefaultWishlistData,
|
||||
Habit,
|
||||
ViewType,
|
||||
getDefaultUsersData,
|
||||
CompletionCache,
|
||||
getDefaultServerSettings,
|
||||
User,
|
||||
UserId,
|
||||
} from "./types";
|
||||
import {
|
||||
getTodayInTimezone,
|
||||
isSameDate,
|
||||
t2d,
|
||||
calculateCoinsEarnedToday,
|
||||
calculateCoinsSpentToday,
|
||||
calculateTotalEarned,
|
||||
calculateTotalSpent,
|
||||
calculateCoinsSpentToday,
|
||||
calculateTransactionsToday,
|
||||
generateCryptoHash,
|
||||
getCompletionsForToday,
|
||||
getISODate,
|
||||
isHabitDueToday,
|
||||
getNow,
|
||||
isHabitDue,
|
||||
getHabitFreq,
|
||||
roundToInteger
|
||||
isHabitDue,
|
||||
prepareDataForHashing,
|
||||
roundToInteger,
|
||||
t2d
|
||||
} from "@/lib/utils";
|
||||
import { atom } from "jotai";
|
||||
import { atomFamily, atomWithStorage } from "jotai/utils";
|
||||
import { DateTime } from "luxon";
|
||||
import { Freq } from "./types";
|
||||
import {
|
||||
CoinsData,
|
||||
CompletionCache,
|
||||
Freq,
|
||||
getDefaultCoinsData,
|
||||
getDefaultHabitsData,
|
||||
getDefaultServerSettings,
|
||||
getDefaultSettings,
|
||||
getDefaultUsersData,
|
||||
getDefaultWishlistData,
|
||||
Habit,
|
||||
HabitsData,
|
||||
ServerSettings,
|
||||
Settings,
|
||||
UserData,
|
||||
UserId,
|
||||
WishlistData
|
||||
} from "./types";
|
||||
|
||||
export interface BrowserSettings {
|
||||
viewType: ViewType
|
||||
expandedHabits: boolean
|
||||
expandedTasks: boolean
|
||||
expandedWishlist: boolean
|
||||
}
|
||||
|
||||
export const browserSettingsAtom = atomWithStorage('browserSettings', {
|
||||
viewType: 'habits',
|
||||
expandedHabits: false,
|
||||
expandedTasks: false,
|
||||
expandedWishlist: false
|
||||
} as BrowserSettings)
|
||||
|
||||
export const usersAtom = atom(getDefaultUsersData())
|
||||
export const settingsAtom = atom(getDefaultSettings());
|
||||
export const habitsAtom = atom(getDefaultHabitsData());
|
||||
export const coinsAtom = atom(getDefaultCoinsData());
|
||||
export const wishlistAtom = atom(getDefaultWishlistData());
|
||||
export const serverSettingsAtom = atom(getDefaultServerSettings());
|
||||
export const usersAtom = atom(getDefaultUsersData<UserData>())
|
||||
export const settingsAtom = atom(getDefaultSettings<Settings>());
|
||||
export const habitsAtom = atom(getDefaultHabitsData<HabitsData>());
|
||||
export const coinsAtom = atom(getDefaultCoinsData<CoinsData>());
|
||||
export const wishlistAtom = atom(getDefaultWishlistData<WishlistData>());
|
||||
export const serverSettingsAtom = atom(getDefaultServerSettings<ServerSettings>());
|
||||
|
||||
// Derived atom for coins earned today
|
||||
export const coinsEarnedTodayAtom = atom((get) => {
|
||||
@@ -129,8 +128,6 @@ export const pomodoroAtom = atom<PomodoroAtom>({
|
||||
minimized: false,
|
||||
})
|
||||
|
||||
import { prepareDataForHashing, generateCryptoHash } from '@/lib/utils';
|
||||
|
||||
export const userSelectAtom = atom<boolean>(false)
|
||||
export const aboutOpenAtom = atom<boolean>(false)
|
||||
|
||||
@@ -237,10 +234,3 @@ export const habitsByDateFamily = atomFamily((dateString: string) =>
|
||||
return habits.filter(habit => isHabitDue({ habit, timezone, date }));
|
||||
})
|
||||
);
|
||||
|
||||
// Derived atom for daily habits
|
||||
export const dailyHabitsAtom = atom((get) => {
|
||||
const settings = get(settingsAtom);
|
||||
const today = getTodayInTimezone(settings.system.timezone);
|
||||
return get(habitsByDateFamily(today));
|
||||
});
|
||||
|
||||
36
lib/client-helpers.ts
Normal file
36
lib/client-helpers.ts
Normal file
@@ -0,0 +1,36 @@
|
||||
// client helpers
|
||||
'use-client'
|
||||
|
||||
import { useAtom } from 'jotai'
|
||||
import { useSession } from "next-auth/react"
|
||||
import { usersAtom } from './atoms'
|
||||
import { hasPermission } from './utils'
|
||||
|
||||
export function useHelpers() {
|
||||
const { data: session, status } = useSession()
|
||||
const currentUserId = session?.user.id
|
||||
const [usersData] = useAtom(usersAtom)
|
||||
const currentUser = usersData.users.find((u) => u.id === currentUserId)
|
||||
// detect iOS: https://stackoverflow.com/a/9039885
|
||||
function iOS() {
|
||||
return typeof navigator !== "undefined" && ([
|
||||
'iPad Simulator',
|
||||
'iPhone Simulator',
|
||||
'iPod Simulator',
|
||||
'iPad',
|
||||
'iPhone',
|
||||
'iPod',
|
||||
].includes(navigator.platform)
|
||||
// iPad on iOS 13 detection
|
||||
|| (navigator.userAgent.includes("Mac") && "ontouchend" in document))
|
||||
}
|
||||
|
||||
return {
|
||||
currentUserId,
|
||||
currentUser,
|
||||
usersData,
|
||||
status,
|
||||
hasPermission,
|
||||
isIOS: iOS(),
|
||||
}
|
||||
}
|
||||
@@ -31,4 +31,6 @@ export const QUICK_DATES = [
|
||||
{ label: 'Sunday', value: 'this sunday' },
|
||||
] as const
|
||||
|
||||
export const MAX_COIN_LIMIT = 9999
|
||||
export const MAX_COIN_LIMIT = 9999
|
||||
|
||||
export const DESKTOP_DISPLAY_ITEM_COUNT = 4
|
||||
85
lib/types.ts
85
lib/types.ts
@@ -1,5 +1,4 @@
|
||||
import { RRule } from "rrule"
|
||||
import { uuid } from "./utils"
|
||||
import { DateTime } from "luxon"
|
||||
|
||||
export type UserId = string
|
||||
@@ -97,52 +96,58 @@ export interface WishlistData {
|
||||
}
|
||||
|
||||
// Default value functions
|
||||
export const getDefaultUsersData = (): UserData => ({
|
||||
users: [
|
||||
{
|
||||
id: uuid(),
|
||||
username: 'admin',
|
||||
// password: '', // No default password for admin initially? Or set a secure default?
|
||||
isAdmin: true,
|
||||
lastNotificationReadTimestamp: undefined, // Initialize as undefined
|
||||
}
|
||||
]
|
||||
});
|
||||
export function getDefaultUsersData<UserData>(): UserData {
|
||||
return {
|
||||
users: [
|
||||
{
|
||||
id: crypto.randomUUID(),
|
||||
username: 'admin',
|
||||
// password: '', // No default password for admin initially? Or set a secure default?
|
||||
isAdmin: true,
|
||||
lastNotificationReadTimestamp: undefined, // Initialize as undefined
|
||||
}
|
||||
]
|
||||
} as UserData;
|
||||
};
|
||||
|
||||
export const getDefaultHabitsData = (): HabitsData => ({
|
||||
habits: []
|
||||
});
|
||||
export function getDefaultHabitsData<HabitsData>(): HabitsData {
|
||||
return { habits: [] } as HabitsData;
|
||||
}
|
||||
|
||||
export function getDefaultTasksData<TasksData>(): TasksData {
|
||||
return { tasks: [] } as TasksData;
|
||||
};
|
||||
|
||||
export const getDefaultCoinsData = (): CoinsData => ({
|
||||
balance: 0,
|
||||
transactions: []
|
||||
});
|
||||
export function getDefaultCoinsData<CoinsData>(): CoinsData {
|
||||
return { balance: 0, transactions: [] } as CoinsData;
|
||||
};
|
||||
|
||||
export const getDefaultWishlistData = (): WishlistData => ({
|
||||
items: []
|
||||
});
|
||||
export function getDefaultWishlistData<WishlistData>(): WishlistData {
|
||||
return { items: [] } as WishlistData;
|
||||
}
|
||||
|
||||
export const getDefaultSettings = (): Settings => ({
|
||||
ui: {
|
||||
useNumberFormatting: true,
|
||||
useGrouping: true,
|
||||
},
|
||||
system: {
|
||||
timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
|
||||
weekStartDay: 1, // Monday
|
||||
autoBackupEnabled: true, // Add this line (default to true)
|
||||
language: 'en', // Default language
|
||||
},
|
||||
profile: {}
|
||||
});
|
||||
export function getDefaultSettings<Settings>(): Settings {
|
||||
return {
|
||||
ui: {
|
||||
useNumberFormatting: true,
|
||||
useGrouping: true,
|
||||
},
|
||||
system: {
|
||||
timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
|
||||
weekStartDay: 1, // Monday
|
||||
autoBackupEnabled: true, // Add this line (default to true)
|
||||
language: 'en', // Default language
|
||||
},
|
||||
profile: {}
|
||||
} as Settings;
|
||||
};
|
||||
|
||||
export const getDefaultServerSettings = (): ServerSettings => ({
|
||||
isDemo: false
|
||||
})
|
||||
export function getDefaultServerSettings<ServerSettings>(): ServerSettings {
|
||||
return { isDemo: false } as ServerSettings;
|
||||
}
|
||||
|
||||
// Map of data types to their default values
|
||||
export const DATA_DEFAULTS = {
|
||||
export const DATA_DEFAULTS: { [key: string]: <T>() => T } = {
|
||||
wishlist: getDefaultWishlistData,
|
||||
habits: getDefaultHabitsData,
|
||||
coins: getDefaultCoinsData,
|
||||
@@ -183,8 +188,6 @@ export type CompletionCache = {
|
||||
}
|
||||
}
|
||||
|
||||
export type ViewType = 'habits' | 'tasks'
|
||||
|
||||
export interface JotaiHydrateInitialValues {
|
||||
settings: Settings;
|
||||
coins: CoinsData;
|
||||
|
||||
@@ -3,12 +3,9 @@ import {
|
||||
cn,
|
||||
getTodayInTimezone,
|
||||
getNow,
|
||||
getNowInMilliseconds,
|
||||
t2d,
|
||||
d2t,
|
||||
d2s,
|
||||
d2sDate,
|
||||
d2n,
|
||||
isSameDate,
|
||||
calculateCoinsEarnedToday,
|
||||
calculateTotalEarned,
|
||||
@@ -16,16 +13,15 @@ import {
|
||||
calculateCoinsSpentToday,
|
||||
isHabitDueToday,
|
||||
isHabitDue,
|
||||
uuid,
|
||||
isTaskOverdue,
|
||||
deserializeRRule,
|
||||
serializeRRule,
|
||||
convertHumanReadableFrequencyToMachineReadable,
|
||||
convertMachineReadableFrequencyToHumanReadable,
|
||||
prepareDataForHashing,
|
||||
generateCryptoHash,
|
||||
getUnsupportedRRuleReason,
|
||||
roundToInteger
|
||||
roundToInteger,
|
||||
generateCryptoHash
|
||||
} from './utils'
|
||||
import { CoinTransaction, ParsedResultType, Settings, HabitsData, CoinsData, WishlistData, UserData } from './types'
|
||||
import { DateTime } from "luxon";
|
||||
@@ -178,32 +174,6 @@ describe('isTaskOverdue', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('uuid', () => {
|
||||
test('should generate valid UUIDs', () => {
|
||||
const id = uuid()
|
||||
// UUID v4 format: 8-4-4-4-12 hex digits
|
||||
expect(id).toMatch(/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/)
|
||||
})
|
||||
|
||||
test('should generate unique UUIDs', () => {
|
||||
const ids = new Set()
|
||||
for (let i = 0; i < 1000; i++) {
|
||||
ids.add(uuid())
|
||||
}
|
||||
// All 1000 UUIDs should be unique
|
||||
expect(ids.size).toBe(1000)
|
||||
})
|
||||
|
||||
test('should generate v4 UUIDs', () => {
|
||||
const id = uuid()
|
||||
// Version 4 UUID has specific bits set:
|
||||
// - 13th character is '4'
|
||||
// - 17th character is '8', '9', 'a', or 'b'
|
||||
expect(id.charAt(14)).toBe('4')
|
||||
expect('89ab').toContain(id.charAt(19))
|
||||
})
|
||||
})
|
||||
|
||||
describe('datetime utilities', () => {
|
||||
let fixedNow: DateTime;
|
||||
let currentDateIndex = 0;
|
||||
@@ -321,13 +291,6 @@ describe('getNow', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('getNowInMilliseconds', () => {
|
||||
test('should return current time in milliseconds', () => {
|
||||
const now = DateTime.now().setZone('UTC')
|
||||
expect(getNowInMilliseconds()).toBe(now.toMillis().toString())
|
||||
})
|
||||
})
|
||||
|
||||
describe('timestamp conversion utilities', () => {
|
||||
const testTimestamp = '2024-01-01T00:00:00.000Z';
|
||||
const testDateTime = DateTime.fromISO(testTimestamp);
|
||||
@@ -351,16 +314,6 @@ describe('timestamp conversion utilities', () => {
|
||||
const customFormat = d2s({ dateTime: testDateTime, format: 'yyyy-MM-dd', timezone: 'utc' });
|
||||
expect(customFormat).toBe('2024-01-01')
|
||||
})
|
||||
|
||||
test('d2sDate should format DateTime as date string', () => {
|
||||
const result = d2sDate({ dateTime: testDateTime });
|
||||
expect(result).toBeString()
|
||||
})
|
||||
|
||||
test('d2n should convert DateTime to milliseconds string', () => {
|
||||
const result = d2n({ dateTime: testDateTime });
|
||||
expect(result).toBe('1704067200000')
|
||||
})
|
||||
})
|
||||
|
||||
describe('isSameDate', () => {
|
||||
@@ -989,11 +942,11 @@ describe('convertMachineReadableFrequencyToHumanReadable', () => {
|
||||
})
|
||||
|
||||
describe('freshness utilities', () => {
|
||||
const mockSettings: Settings = getDefaultSettings();
|
||||
const mockHabits: HabitsData = getDefaultHabitsData();
|
||||
const mockCoins: CoinsData = getDefaultCoinsData();
|
||||
const mockWishlist: WishlistData = getDefaultWishlistData();
|
||||
const mockUsers: UserData = getDefaultUsersData();
|
||||
const mockSettings: Settings = getDefaultSettings<Settings>();
|
||||
const mockHabits: HabitsData = getDefaultHabitsData<HabitsData>();
|
||||
const mockCoins: CoinsData = getDefaultCoinsData<CoinsData>();
|
||||
const mockWishlist: WishlistData = getDefaultWishlistData<WishlistData>();
|
||||
const mockUsers: UserData = getDefaultUsersData<UserData>();
|
||||
|
||||
// Add a user to mockUsers for more realistic testing
|
||||
mockUsers.users.push({
|
||||
@@ -1038,11 +991,11 @@ describe('freshness utilities', () => {
|
||||
});
|
||||
|
||||
test('should handle empty data consistently', () => {
|
||||
const emptySettings = getDefaultSettings();
|
||||
const emptyHabits = getDefaultHabitsData();
|
||||
const emptyCoins = getDefaultCoinsData();
|
||||
const emptyWishlist = getDefaultWishlistData();
|
||||
const emptyUsers = getDefaultUsersData();
|
||||
const emptySettings = getDefaultSettings<Settings>();
|
||||
const emptyHabits = getDefaultHabitsData<HabitsData>();
|
||||
const emptyCoins = getDefaultCoinsData<CoinsData>();
|
||||
const emptyWishlist = getDefaultWishlistData<WishlistData>();
|
||||
const emptyUsers = getDefaultUsersData<UserData>();
|
||||
|
||||
const string1 = prepareDataForHashing(emptySettings, emptyHabits, emptyCoins, emptyWishlist, emptyUsers);
|
||||
const string2 = prepareDataForHashing(emptySettings, emptyHabits, emptyCoins, emptyWishlist, emptyUsers);
|
||||
|
||||
128
lib/utils.ts
128
lib/utils.ts
@@ -1,13 +1,12 @@
|
||||
import { clsx, type ClassValue } from "clsx"
|
||||
import { twMerge } from "tailwind-merge"
|
||||
import { DateTime, DateTimeFormatOptions } from "luxon"
|
||||
import { datetime, RRule } from 'rrule'
|
||||
import { Freq, Habit, CoinTransaction, Permission, ParsedFrequencyResult, ParsedResultType, User, Settings, HabitsData, CoinsData, WishlistData, UserData } from '@/lib/types'
|
||||
import { DUE_MAP, INITIAL_DUE, RECURRENCE_RULE_MAP } from "./constants"
|
||||
import { toast } from "@/hooks/use-toast"
|
||||
import { CoinsData, CoinTransaction, Freq, Habit, HabitsData, ParsedFrequencyResult, ParsedResultType, SafeUser, Settings, User, UserData, WishlistData } from '@/lib/types'
|
||||
import * as chrono from 'chrono-node'
|
||||
import _ from "lodash"
|
||||
import { v4 as uuidv4 } from 'uuid'
|
||||
import stableStringify from 'json-stable-stringify';
|
||||
import { clsx, type ClassValue } from "clsx"
|
||||
import { DateTime, DateTimeFormatOptions } from "luxon"
|
||||
import { Formats } from "next-intl"
|
||||
import { datetime, RRule } from 'rrule'
|
||||
import { twMerge } from "tailwind-merge"
|
||||
import { DUE_MAP, INITIAL_DUE, RECURRENCE_RULE_MAP } from "./constants"
|
||||
|
||||
export function cn(...inputs: ClassValue[]) {
|
||||
return twMerge(clsx(inputs))
|
||||
@@ -33,12 +32,6 @@ export function getNow({ timezone = 'utc', keepLocalTime }: { timezone?: string,
|
||||
return DateTime.now().setZone(timezone, { keepLocalTime });
|
||||
}
|
||||
|
||||
// get current time in epoch milliseconds
|
||||
export function getNowInMilliseconds() {
|
||||
const now = getNow({});
|
||||
return d2n({ dateTime: now });
|
||||
}
|
||||
|
||||
// iso timestamp to datetime object, most for storage read
|
||||
export function t2d({ timestamp, timezone }: { timestamp: string; timezone: string }) {
|
||||
return DateTime.fromISO(timestamp).setZone(timezone);
|
||||
@@ -61,30 +54,11 @@ export function d2s({ dateTime, format, timezone }: { dateTime: DateTime, format
|
||||
return dateTime.setZone(timezone).toLocaleString(DateTime.DATETIME_MED);
|
||||
}
|
||||
|
||||
// convert datetime object to date string, mostly for display
|
||||
export function d2sDate({ dateTime }: { dateTime: DateTime }) {
|
||||
return dateTime.toLocaleString(DateTime.DATE_MED);
|
||||
}
|
||||
|
||||
// convert datetime object to epoch milliseconds string, mostly for storage write
|
||||
export function d2n({ dateTime }: { dateTime: DateTime }) {
|
||||
return dateTime.toMillis().toString();
|
||||
}
|
||||
|
||||
// compare the date portion of two datetime objects (i.e. same year, month, day)
|
||||
export function isSameDate(a: DateTime, b: DateTime) {
|
||||
return a.hasSame(b, 'day');
|
||||
}
|
||||
|
||||
export function normalizeCompletionDate(date: string, timezone: string): string {
|
||||
// If already in ISO format, return as is
|
||||
if (date.includes('T')) {
|
||||
return date;
|
||||
}
|
||||
// Convert from yyyy-MM-dd to ISO format
|
||||
return DateTime.fromFormat(date, 'yyyy-MM-dd', { zone: timezone }).toUTC().toISO()!;
|
||||
}
|
||||
|
||||
export function getCompletionsForDate({
|
||||
habit,
|
||||
date,
|
||||
@@ -438,22 +412,20 @@ export const openWindow = (url: string): boolean => {
|
||||
return true
|
||||
}
|
||||
|
||||
export function deepMerge<T>(a: T, b: T) {
|
||||
return _.merge(a, b, (x: unknown, y: unknown) => {
|
||||
if (_.isArray(a)) {
|
||||
return a.concat(b)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
export function checkPermission(
|
||||
permissions: Permission[] | undefined,
|
||||
export function hasPermission(
|
||||
user: User | undefined,
|
||||
resource: 'habit' | 'wishlist' | 'coins',
|
||||
action: 'write' | 'interact'
|
||||
): boolean {
|
||||
if (!permissions) return false
|
||||
|
||||
return permissions.some(permission => {
|
||||
if (!user || !user.permissions) {
|
||||
return false;
|
||||
}
|
||||
// If user is admin, they have all permissions.
|
||||
if (user.isAdmin) {
|
||||
return true;
|
||||
}
|
||||
// Otherwise, check specific permissions.
|
||||
return user.permissions.some(permission => {
|
||||
switch (resource) {
|
||||
case 'habit':
|
||||
return permission.habit[action]
|
||||
@@ -467,27 +439,6 @@ export function checkPermission(
|
||||
})
|
||||
}
|
||||
|
||||
export function uuid() {
|
||||
return uuidv4()
|
||||
}
|
||||
|
||||
export function hasPermission(
|
||||
currentUser: User | undefined,
|
||||
resource: 'habit' | 'wishlist' | 'coins',
|
||||
action: 'write' | 'interact'
|
||||
): boolean {
|
||||
// If no current user, no permissions.
|
||||
if (!currentUser) {
|
||||
return false;
|
||||
}
|
||||
// If user is admin, they have all permissions.
|
||||
if (currentUser.isAdmin) {
|
||||
return true;
|
||||
}
|
||||
// Otherwise, check specific permissions.
|
||||
return checkPermission(currentUser.permissions, resource, action);
|
||||
}
|
||||
|
||||
/**
|
||||
* Prepares a consistent string representation of the data for hashing.
|
||||
* It combines all relevant data pieces into a single object and then stringifies it stably.
|
||||
@@ -499,22 +450,13 @@ export function prepareDataForHashing(
|
||||
wishlist: WishlistData,
|
||||
users: UserData
|
||||
): string {
|
||||
// Combine all data into a single object.
|
||||
// The order of keys in this object itself doesn't matter due to stableStringify,
|
||||
// but being explicit helps in understanding what's being hashed.
|
||||
const combinedData = {
|
||||
return JSON.stringify({
|
||||
settings,
|
||||
habits,
|
||||
coins,
|
||||
wishlist,
|
||||
users,
|
||||
};
|
||||
const stringifiedData = stableStringify(combinedData);
|
||||
// Handle cases where stringify might return undefined.
|
||||
if (stringifiedData === undefined) {
|
||||
throw new Error("Failed to stringify data for hashing. stableStringify returned undefined.");
|
||||
}
|
||||
return stringifiedData;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -539,3 +481,31 @@ export async function generateCryptoHash(dataString: string): Promise<string | n
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function handlePermissionCheck(
|
||||
user: User | SafeUser | undefined,
|
||||
resource: 'habit' | 'wishlist' | 'coins',
|
||||
action: 'write' | 'interact',
|
||||
tCommon: (key: string, values?: Record<string, string | number | Date> | undefined, formats?: Formats | undefined) => string
|
||||
): boolean {
|
||||
|
||||
if (!user) {
|
||||
toast({
|
||||
title: tCommon("authenticationRequiredTitle"),
|
||||
description: tCommon("authenticationRequiredDescription"),
|
||||
variant: "destructive",
|
||||
})
|
||||
return false
|
||||
}
|
||||
|
||||
if (!hasPermission(user, resource, action)) {
|
||||
toast({
|
||||
title: tCommon("permissionDeniedTitle"),
|
||||
description: tCommon("permissionDeniedDescription", { action, resource }),
|
||||
variant: "destructive",
|
||||
})
|
||||
return false
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
@@ -43,9 +43,9 @@
|
||||
"date-fns": "^3.6.0",
|
||||
"jotai": "^2.8.0",
|
||||
"js-confetti": "^0.12.0",
|
||||
"json-stable-stringify": "^1.3.0",
|
||||
"linkify": "^0.2.1",
|
||||
"linkify-react": "^4.2.0",
|
||||
"lodash": "^4.17.21",
|
||||
"lucide-react": "^0.469.0",
|
||||
"luxon": "^3.5.0",
|
||||
"next": "15.2.3",
|
||||
@@ -62,7 +62,6 @@
|
||||
"rrule": "^2.8.1",
|
||||
"tailwind-merge": "^2.6.0",
|
||||
"tailwindcss-animate": "^1.0.7",
|
||||
"uuid": "^11.0.5",
|
||||
"web-push": "^3.6.7",
|
||||
"zod": "^3.24.1"
|
||||
},
|
||||
@@ -71,7 +70,6 @@
|
||||
"@tailwindcss/typography": "^0.5.15",
|
||||
"@types/archiver": "^6.0.3",
|
||||
"@types/bun": "^1.1.14",
|
||||
"@types/json-stable-stringify": "^1.1.0",
|
||||
"@types/lodash": "^4.17.15",
|
||||
"@types/luxon": "^3.4.2",
|
||||
"@types/node": "^20.17.10",
|
||||
|
||||
Reference in New Issue
Block a user