Compare commits

...

10 Commits

Author SHA1 Message Date
jafreli
f714fa46ba Hinzufügen des Docker Containerst
Some checks failed
Build and Push Docker Image / build-and-push (push) Failing after 2m3s
2025-07-19 00:46:42 +02:00
jafreli
f551dfe00c Umbau auf 7 reihen 2025-07-19 00:40:43 +02:00
jafreli
84c026ca9b Auf Transparenz effect gewechselt 2025-07-19 00:07:04 +02:00
jafreli
ff4c0825e8 Auf Transparenz effect gewechselt 2025-07-19 00:06:50 +02:00
jafreli
93f6026346 Mehrere an einem Tag 2025-07-18 23:16:44 +02:00
jafreli
866e6c95b7 Name Ändern 2025-07-18 21:53:12 +02:00
jafreli
8580a82222 Farben der Habits wälbarmachen 2025-07-16 22:57:28 +02:00
jafreli
04c40b29d9 Streak Counter 2025-07-16 22:37:35 +02:00
jafreli
5bc7faa451 Neue Monats ansicht 2025-07-16 18:55:38 +02:00
jafreli
c78e825f2f Erste funktionierende Version 2025-07-16 18:43:11 +02:00
12 changed files with 1250 additions and 95 deletions

58
.dockerignore Normal file
View File

@@ -0,0 +1,58 @@
# Git
.git
.gitignore
.gitea
# Python
__pycache__
*.pyc
*.pyo
*.pyd
.Python
env
pip-log.txt
pip-delete-this-directory.txt
.tox
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.log
.git
.mypy_cache
.pytest_cache
.hypothesis
# Virtual environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/
# IDE
.vscode/
.idea/
*.swp
*.swo
*~
# OS
.DS_Store
.DS_Store?
._*
.Spotlight-V100
.Trashes
ehthumbs.db
Thumbs.db
# Documentation
README.md
*.md
# Database (will be created in container)
habits.json

View File

@@ -0,0 +1,76 @@
name: Build and Push Docker Image
on:
push:
branches:
- main
- master
tags:
- 'v*'
pull_request:
branches:
- main
- master
env:
REGISTRY: git.out.jafre.li # Ersetze mit deiner Gitea-Domain
IMAGE_NAME: habit-tracker
jobs:
build-and-push:
runs-on: ubuntu-latest
permissions:
contents: read
packages: write
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
- name: Log in to Container Registry
uses: docker/login-action@v3
with:
registry: ${{ env.REGISTRY }}
username: ${{ gitea.actor }}
password: ${{ secrets.GITEA_TOKEN }}
- name: Extract metadata
id: meta
uses: docker/metadata-action@v5
with:
images: ${{ env.REGISTRY }}/${{ gitea.repository_owner }}/${{ env.IMAGE_NAME }}
tags: |
type=ref,event=branch
type=ref,event=pr
type=semver,pattern={{version}}
type=semver,pattern={{major}}.{{minor}}
type=raw,value=latest,enable={{is_default_branch}}
- name: Build and push Docker image
uses: docker/build-push-action@v5
with:
context: .
platforms: linux/amd64,linux/arm64
push: true
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
cache-from: type=gha
cache-to: type=gha,mode=max
- name: Generate deployment info
run: |
echo "## Docker Image Built Successfully! 🐳" >> $GITHUB_STEP_SUMMARY
echo "" >> $GITHUB_STEP_SUMMARY
echo "**Image:** \`${{ env.REGISTRY }}/${{ gitea.repository_owner }}/${{ env.IMAGE_NAME }}:latest\`" >> $GITHUB_STEP_SUMMARY
echo "" >> $GITHUB_STEP_SUMMARY
echo "### Quick Start:" >> $GITHUB_STEP_SUMMARY
echo "\`\`\`bash" >> $GITHUB_STEP_SUMMARY
echo "docker run -d \\" >> $GITHUB_STEP_SUMMARY
echo " --name habit-tracker \\" >> $GITHUB_STEP_SUMMARY
echo " -p 5000:5000 \\" >> $GITHUB_STEP_SUMMARY
echo " -v habit-data:/app/data \\" >> $GITHUB_STEP_SUMMARY
echo " ${{ env.REGISTRY }}/${{ gitea.repository_owner }}/${{ env.IMAGE_NAME }}:latest" >> $GITHUB_STEP_SUMMARY
echo "\`\`\`" >> $GITHUB_STEP_SUMMARY

2
.vscode/settings.json vendored Normal file
View File

@@ -0,0 +1,2 @@
{
}

33
Dockerfile Normal file
View File

@@ -0,0 +1,33 @@
# Use Python 3.11 slim image
FROM python:3.11-slim
# Set working directory
WORKDIR /app
# Install system dependencies
RUN apt-get update && apt-get install -y \
gcc \
&& rm -rf /var/lib/apt/lists/*
# Copy requirements first for better caching
COPY requirements.txt .
# Install Python dependencies
RUN pip install --no-cache-dir -r requirements.txt
# Copy application code
COPY . .
# Create directory for database
RUN mkdir -p /app/data
# Expose port
EXPOSE 5000
# Set environment variables
ENV FLASK_APP=app.py
ENV FLASK_ENV=production
ENV PYTHONPATH=/app
# Run the application
CMD ["python", "-m", "flask", "run", "--host=0.0.0.0", "--port=5000"]

129
README.md Normal file
View File

@@ -0,0 +1,129 @@
# Habit Tracker
Ein einfacher Habit Tracker mit wöchentlicher Ansicht, gebaut mit Flask und JavaScript.
## Features
- 📅 Wöchentliche Ansicht (7 Zeilen für jeden Wochentag)
- 🎯 Anpassbare Tagesziele (1-20x pro Tag)
- 🎨 Individuelle Farben für jedes Habit
- 🔥 Streak-Zähler
- 📱 Responsive Design
- 🐳 Docker-Support
## Schnellstart mit Docker
### Aus der Registry
```bash
docker run -d \
--name habit-tracker \
-p 5000:5000 \
-v habit-data:/app/data \
gitea.example.com/username/habit-tracker:latest
```
### Lokal bauen
```bash
# Repository klonen
git clone <repository-url>
cd habit-tracker
# Mit Docker Compose
docker-compose up -d
# Oder manuell
docker build -t habit-tracker .
docker run -d \
--name habit-tracker \
-p 5000:5000 \
-v habit-data:/app/data \
habit-tracker
```
## Lokale Entwicklung
```bash
# Virtual Environment erstellen
python -m venv venv
source venv/bin/activate # Linux/Mac
# oder
venv\Scripts\activate # Windows
# Dependencies installieren
pip install -r requirements.txt
# App starten
python app.py
```
Die App ist dann unter http://localhost:5000 erreichbar.
## Konfiguration
### Umgebungsvariablen
- `FLASK_ENV`: `production` oder `development` (Standard: `production`)
- `FLASK_APP`: `app.py` (Standard)
### Volumes
- `/app/data`: Hier wird die `habits.json` Datenbank gespeichert
## Deployment
### Docker Compose (Empfohlen)
```yaml
version: '3.8'
services:
habit-tracker:
image: gitea.example.com/username/habit-tracker:latest
ports:
- "5000:5000"
volumes:
- ./data:/app/data
environment:
- FLASK_ENV=production
restart: unless-stopped
```
### Reverse Proxy (Nginx)
```nginx
server {
listen 80;
server_name habits.example.com;
location / {
proxy_pass http://localhost:5000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}
```
## Bedienung
1. **Habit hinzufügen**: Namen eingeben und "Hinzufügen" klicken
2. **Heute abhaken**: ✓-Button klicken (zeigt Fortschritt bei Zielen >1)
3. **Vergangene Tage bearbeiten**: Drei-Punkte-Menü → Modal öffnen
4. **Einstellungen**: Im Modal Farbe und Tagesziel anpassen
5. **Löschen**: Im Modal über den "Löschen"-Button
## Technische Details
- **Backend**: Flask (Python)
- **Frontend**: Vanilla JavaScript
- **Datenbank**: TinyDB (JSON-basiert)
- **Styling**: CSS Grid/Flexbox
- **Container**: Multi-Arch (AMD64/ARM64)
## CI/CD
Der Gitea-Workflow baut automatisch Docker-Images bei:
- Push auf `main`/`master` Branch
- Neue Tags (z.B. `v1.0.0`)
- Pull Requests
## Lizenz
MIT License

176
app.py
View File

@@ -18,30 +18,92 @@ def get_last_30_days():
dates.append(date.strftime('%Y-%m-%d')) dates.append(date.strftime('%Y-%m-%d'))
return dates[::-1] # Reverse to have oldest first return dates[::-1] # Reverse to have oldest first
# Helper function to get dates organized by weekday for more weeks to fill the width
def get_weekly_dates():
today = datetime.now()
# Find the most recent Monday (start of current week)
days_since_monday = today.weekday() # Monday = 0, Sunday = 6
current_monday = today - timedelta(days=days_since_monday)
weekly_data = {}
weekdays = ['Montag', 'Dienstag', 'Mittwoch', 'Donnerstag', 'Freitag', 'Samstag', 'Sonntag']
# Use more weeks to fill the available width (about 15-20 weeks)
num_weeks = 18 # This should provide good coverage without being too much
for weekday_idx in range(7): # 0 = Monday, 6 = Sunday
weekly_data[weekdays[weekday_idx]] = []
for week_offset in range(num_weeks):
date = current_monday + timedelta(days=weekday_idx - (week_offset * 7))
if date <= today: # Only include dates up to today
weekly_data[weekdays[weekday_idx]].append(date.strftime('%Y-%m-%d'))
# Reverse each weekday list to show oldest first (left to right)
for weekday in weekly_data:
weekly_data[weekday] = weekly_data[weekday][::-1]
return weekly_data
@app.route('/') @app.route('/')
def index(): def index():
return render_template('index.html') return render_template('index.html')
@app.route('/habits', methods=['GET']) @app.route('/habits', methods=['GET'])
def get_habits(): def get_habits():
habits_data = db.all() raw_habits = db.all()
# Add completion status for the last 30 days formatted_habits = []
last_30_days = get_last_30_days() weekly_dates = get_weekly_dates()
for habit in habits_data:
habit['completion_history'] = {} for habit_doc in raw_habits:
for date_str in last_30_days: # Handle migration from old format (list) to new format (dict)
habit['completion_history'][date_str] = date_str in habit.get('completed_dates', []) completed_dates = habit_doc.get('completed_dates', {})
return jsonify(habits_data) if isinstance(completed_dates, list):
# Convert old format to new format
new_completed_dates = {}
for date in completed_dates:
new_completed_dates[date] = 1
completed_dates = new_completed_dates
# Update in database
db.update({'completed_dates': completed_dates}, doc_ids=[habit_doc.doc_id])
current_habit_data = {
'id': habit_doc.doc_id,
'name': habit_doc.get('name'),
'completed_dates': completed_dates,
'color': habit_doc.get('color', '#4CAF50'),
'daily_target': habit_doc.get('daily_target', 1)
}
# Create weekly completion history
weekly_completion = {}
for weekday, dates in weekly_dates.items():
weekly_completion[weekday] = []
for date_str in dates:
completed_count = completed_dates.get(date_str, 0)
target_count = current_habit_data['daily_target']
weekly_completion[weekday].append({
'date': date_str,
'completed': completed_count,
'target': target_count,
'is_complete': completed_count >= target_count
})
current_habit_data['weekly_completion'] = weekly_completion
formatted_habits.append(current_habit_data)
return jsonify(formatted_habits)
@app.route('/habits', methods=['POST']) @app.route('/habits', methods=['POST'])
def add_habit(): def add_habit():
data = request.json data = request.json
name = data.get('name') name = data.get('name')
color = data.get('color', '#4CAF50') # Default green color
daily_target = data.get('daily_target', 1) # Default 1x per day
if not name: if not name:
return jsonify({'error': 'Habit name is required'}), 400 return jsonify({'error': 'Habit name is required'}), 400
habit_id = db.insert({'name': name, 'completed_dates': []}) habit_id = db.insert({'name': name, 'completed_dates': {}, 'color': color, 'daily_target': daily_target})
return jsonify({'id': habit_id, 'name': name, 'completed_dates': []}), 201 return jsonify({'id': habit_id, 'name': name, 'completed_dates': {}, 'color': color, 'daily_target': daily_target}), 201
@app.route('/habits/<int:habit_id>/complete', methods=['POST']) @app.route('/habits/<int:habit_id>/complete', methods=['POST'])
def complete_habit(habit_id): def complete_habit(habit_id):
@@ -51,11 +113,25 @@ def complete_habit(habit_id):
if not habit: if not habit:
return jsonify({'error': 'Habit not found'}), 404 return jsonify({'error': 'Habit not found'}), 404
if date_to_complete not in habit['completed_dates']: # Handle migration from old format (list) to new format (dict)
habit['completed_dates'].append(date_to_complete) completed_dates = habit.get('completed_dates', {})
db.update({'completed_dates': habit['completed_dates']}, doc_ids=[habit_id]) if isinstance(completed_dates, list):
new_completed_dates = {}
for date in completed_dates:
new_completed_dates[date] = 1
completed_dates = new_completed_dates
return jsonify({'message': f'Habit {habit_id} marked as completed for {date_to_complete}', 'completed_dates': habit['completed_dates']}) # Increment completion count for the date
current_count = completed_dates.get(date_to_complete, 0)
completed_dates[date_to_complete] = current_count + 1
db.update({'completed_dates': completed_dates}, doc_ids=[habit_id])
return jsonify({
'message': f'Habit {habit_id} marked as completed for {date_to_complete}',
'completed_dates': completed_dates,
'current_count': completed_dates[date_to_complete]
})
@app.route('/habits/<int:habit_id>/uncomplete', methods=['POST']) @app.route('/habits/<int:habit_id>/uncomplete', methods=['POST'])
def uncomplete_habit(habit_id): def uncomplete_habit(habit_id):
@@ -65,26 +141,82 @@ def uncomplete_habit(habit_id):
if not habit: if not habit:
return jsonify({'error': 'Habit not found'}), 404 return jsonify({'error': 'Habit not found'}), 404
if date_to_uncomplete in habit['completed_dates']: # Handle migration from old format (list) to new format (dict)
habit['completed_dates'].remove(date_to_uncomplete) completed_dates = habit.get('completed_dates', {})
db.update({'completed_dates': habit['completed_dates']}, doc_ids=[habit_id]) if isinstance(completed_dates, list):
new_completed_dates = {}
for date in completed_dates:
new_completed_dates[date] = 1
completed_dates = new_completed_dates
return jsonify({'message': f'Habit {habit_id} marked as uncompleted for {date_to_uncomplete}', 'completed_dates': habit['completed_dates']}) # Decrement completion count for the date
if date_to_uncomplete in completed_dates:
current_count = completed_dates[date_to_uncomplete]
if current_count > 1:
completed_dates[date_to_uncomplete] = current_count - 1
else:
del completed_dates[date_to_uncomplete]
db.update({'completed_dates': completed_dates}, doc_ids=[habit_id])
return jsonify({
'message': f'Habit {habit_id} marked as uncompleted for {date_to_uncomplete}',
'completed_dates': completed_dates,
'current_count': completed_dates.get(date_to_uncomplete, 0)
})
@app.route('/habits/<int:habit_id>', methods=['PUT']) @app.route('/habits/<int:habit_id>', methods=['PUT'])
def update_habit(habit_id): def update_habit(habit_id):
data = request.json data = request.json
name = data.get('name') name = data.get('name')
color = data.get('color')
daily_target = data.get('daily_target')
if not name: if not name and not color and not daily_target:
return jsonify({'error': 'Habit name is required'}), 400 return jsonify({'error': 'Habit name, color, or daily target is required'}), 400
habit = db.get(doc_id=habit_id) habit = db.get(doc_id=habit_id)
if not habit: if not habit:
return jsonify({'error': 'Habit not found'}), 404 return jsonify({'error': 'Habit not found'}), 404
db.update({'name': name}, doc_ids=[habit_id]) update_data = {}
return jsonify({'message': f'Habit {habit_id} updated', 'name': name}) if name:
update_data['name'] = name
if color:
update_data['color'] = color
if daily_target:
update_data['daily_target'] = int(daily_target)
db.update(update_data, doc_ids=[habit_id])
return jsonify({'message': f'Habit {habit_id} updated', **update_data})
@app.route('/habits/<int:habit_id>/reset', methods=['POST'])
def reset_habit(habit_id):
date_to_reset = request.json.get('date', get_current_date())
habit = db.get(doc_id=habit_id)
if not habit:
return jsonify({'error': 'Habit not found'}), 404
# Handle migration from old format (list) to new format (dict)
completed_dates = habit.get('completed_dates', {})
if isinstance(completed_dates, list):
new_completed_dates = {}
for date in completed_dates:
new_completed_dates[date] = 1
completed_dates = new_completed_dates
# Reset completion count for the date to 0
if date_to_reset in completed_dates:
del completed_dates[date_to_reset]
db.update({'completed_dates': completed_dates}, doc_ids=[habit_id])
return jsonify({
'message': f'Habit {habit_id} reset for {date_to_reset}',
'completed_dates': completed_dates,
'current_count': 0
})
@app.route('/habits/<int:habit_id>', methods=['DELETE']) @app.route('/habits/<int:habit_id>', methods=['DELETE'])
def delete_habit(habit_id): def delete_habit(habit_id):

15
docker-compose.yml Normal file
View File

@@ -0,0 +1,15 @@
version: '3.8'
services:
habit-tracker:
build: .
ports:
- "5000:5000"
volumes:
- habit-data:/app/data
environment:
- FLASK_ENV=production
restart: unless-stopped
volumes:
habit-data:

View File

@@ -1 +1 @@
{"_default": {"1": {"name": "Zocken", "completed_dates": []}, "2": {"name": "Gehen", "completed_dates": []}}} {"_default": {"1": {"name": "Mega Zock", "completed_dates": {"2025-07-14": 1, "2025-08-01": 1, "2025-08-09": 1, "2025-08-17": 1, "2025-07-01": 1, "2025-07-10": 1, "2025-07-15": 1, "2025-07-11": 1, "2025-07-12": 1, "2025-07-13": 1, "2025-07-06": 1, "2025-07-05": 1, "2025-07-04": 1, "2025-07-03": 1, "2025-07-08": 1, "2025-07-07": 1, "2025-07-19": 1, "2025-07-16": 1, "2025-07-02": 1, "2025-07-09": 1, "2025-07-17": 1, "2025-07-18": 1}, "color": "#14cc1a"}, "2": {"name": "Laufen", "completed_dates": {"2025-07-14": 3, "2025-07-15": 4, "2025-06-02": 1, "2025-06-03": 1, "2025-07-19": 1}, "color": "#1a3ed1", "daily_target": 1}, "4": {"name": "Essen", "completed_dates": {"2025-07-14": 3, "2025-07-15": 3, "2025-07-16": 3, "2025-07-17": 3, "2025-07-18": 3}, "color": "#f01000", "daily_target": 3}}}

3
requirements.txt Normal file
View File

@@ -0,0 +1,3 @@
Flask==2.3.3
tinydb==4.8.0
Werkzeug==2.3.7

View File

@@ -81,20 +81,74 @@ h1 {
color: #e0e0e0; color: #e0e0e0;
font-size: 1.5em; font-size: 1.5em;
cursor: pointer; cursor: pointer;
margin-left: 5px;
} }
.habit-actions button:hover { .habit-actions button:hover {
color: #666; color: #666;
} }
.habit-actions button.completed-today {
color: var(--habit-color, #4CAF50);
}
.habit-actions button.not-completed-today {
color: #888;
}
.habit-actions button.completed-today:hover {
color: var(--habit-color, #45a049);
filter: brightness(0.9);
}
.habit-actions button.not-completed-today:hover {
color: var(--habit-color, #4CAF50);
}
/* Weekly Grid Layout */
.weekly-grid {
display: flex;
flex-direction: column;
gap: 3px;
padding: 10px 0;
}
.weekday-row {
display: flex;
align-items: center;
gap: 3px;
}
.weekday-label {
width: 30px;
font-size: 0.8em;
font-weight: bold;
color: #b0b0b0;
text-align: center;
flex-shrink: 0;
}
.weekday-row .date-square {
flex: 1;
min-width: 0;
aspect-ratio: 1;
max-width: 25px;
height: auto;
}
/* Legacy date-grid for backward compatibility */
.date-grid { .date-grid {
display: grid; display: grid;
grid-template-columns: repeat(30, 1fr); /* Adjust based on your date range */ grid-template-columns: repeat(30, 1fr);
/* Adjust based on your date range */
gap: 2px; gap: 2px;
padding: 5px 0; padding: 5px 0;
overflow-x: auto; /* Enable horizontal scrolling if dates exceed width */ overflow-x: auto;
-ms-overflow-style: none; /* IE and Edge */ /* Enable horizontal scrolling if dates exceed width */
scrollbar-width: none; /* Firefox */ -ms-overflow-style: none;
/* IE and Edge */
scrollbar-width: none;
/* Firefox */
} }
/* Hide scrollbar for Chrome, Safari and Opera */ /* Hide scrollbar for Chrome, Safari and Opera */
@@ -103,28 +157,58 @@ h1 {
} }
.date-square { .date-square {
width: 15px; /* Adjust size as needed */ width: 15px;
/* Adjust size as needed */
height: 15px; height: 15px;
background-color: #555; background-color: #555;
border-radius: 2px; border-radius: 2px;
cursor: pointer; cursor: pointer;
} }
.date-square-readonly {
cursor: default;
opacity: 0.9;
}
.date-square.completed { .date-square.completed {
background-color: #4CAF50; background-color: var(--habit-color, #4CAF50);
}
.date-square.partial {
background-color: #555;
position: relative;
}
.date-square.partial::before {
content: '';
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: var(--habit-color, #4CAF50);
opacity: var(--completion-opacity, 0.5);
border-radius: inherit;
} }
/* Modal Styles */ /* Modal Styles */
.modal { .modal {
display: none; /* Hidden by default */ display: none;
position: fixed; /* Stay in place */ /* Hidden by default */
z-index: 1; /* Sit on top */ position: fixed;
/* Stay in place */
z-index: 1;
/* Sit on top */
left: 0; left: 0;
top: 0; top: 0;
width: 100%; /* Full width */ width: 100%;
height: 100%; /* Full height */ /* Full width */
overflow: auto; /* Enable scroll if needed */ height: 100%;
background-color: rgba(0,0,0,0.4); /* Black w/ opacity */ /* Full height */
overflow: auto;
/* Enable scroll if needed */
background-color: rgba(0, 0, 0, 0.4);
/* Black w/ opacity */
justify-content: center; justify-content: center;
align-items: center; align-items: center;
} }
@@ -159,13 +243,57 @@ h1 {
#modalHabitName { #modalHabitName {
text-align: center; text-align: center;
color: #4CAF50; color: var(--current-habit-color, #4CAF50);
margin-bottom: 20px; margin-bottom: 20px;
} }
.month-navigation {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 15px;
}
.month-navigation button {
background-color: var(--current-habit-color, #4CAF50);
color: var(--current-habit-text-color, white);
border: none;
border-radius: 5px;
padding: 8px 12px;
cursor: pointer;
font-size: 16px;
}
.month-navigation button:hover {
background-color: var(--current-habit-color, #45a049);
color: var(--current-habit-text-color, white);
filter: brightness(0.9);
}
#currentMonthYear {
font-size: 1.2em;
font-weight: bold;
color: #e0e0e0;
}
.weekdays-header {
display: grid;
grid-template-columns: repeat(7, 1fr);
gap: 5px;
margin-bottom: 10px;
text-align: center;
font-weight: bold;
color: var(--current-habit-color, #4CAF50);
}
.weekdays-header div {
padding: 5px;
}
.date-grid-modal { .date-grid-modal {
display: grid; display: grid;
grid-template-columns: repeat(7, 1fr); /* 7 days a week */ grid-template-columns: repeat(7, 1fr);
/* 7 days a week */
gap: 5px; gap: 5px;
margin-bottom: 20px; margin-bottom: 20px;
} }
@@ -180,11 +308,80 @@ h1 {
} }
.date-cell.completed { .date-cell.completed {
background-color: #4CAF50; background-color: var(--current-habit-color, #4CAF50);
color: var(--current-habit-text-color, white);
}
.date-cell.partial {
background-color: #444;
position: relative;
color: #e0e0e0;
}
.date-cell.partial::before {
content: '';
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: var(--current-habit-color, #4CAF50);
opacity: var(--completion-opacity, 0.5);
border-radius: inherit;
z-index: 1;
}
.date-cell.partial .date-day,
.date-cell.partial .date-counter {
position: relative;
z-index: 2;
} }
.date-cell.today { .date-cell.today {
border: 2px solid #007bff; /* Highlight today */ border: 2px solid #007bff;
/* Highlight today */
}
.date-cell.empty {
background-color: transparent;
cursor: default;
}
.date-day {
font-size: 1em;
font-weight: bold;
line-height: 1;
}
.date-counter {
font-size: 0.7em;
opacity: 0.8;
line-height: 1;
margin-top: 2px;
}
.streak-container {
display: flex;
align-items: center;
justify-content: center;
margin-top: 10px;
padding: 5px;
background-color: #444;
border-radius: 15px;
width: fit-content;
margin-left: auto;
margin-right: auto;
}
.flame-icon {
font-size: 1.2em;
margin-right: 5px;
}
.streak-count {
color: #e0e0e0;
font-size: 0.9em;
font-weight: bold;
} }
.modal-actions { .modal-actions {
@@ -203,12 +400,14 @@ h1 {
} }
#modalCompleteTodayBtn { #modalCompleteTodayBtn {
background-color: #4CAF50; background-color: var(--current-habit-color, #4CAF50);
color: white; color: var(--current-habit-text-color, white);
} }
#modalCompleteTodayBtn:hover { #modalCompleteTodayBtn:hover {
background-color: #45a049; background-color: var(--current-habit-color, #45a049);
color: var(--current-habit-text-color, white);
filter: brightness(0.9);
} }
#modalEditBtn { #modalEditBtn {
@@ -228,3 +427,52 @@ h1 {
#modalDeleteBtn:hover { #modalDeleteBtn:hover {
background-color: #c82333; background-color: #c82333;
} }
.color-picker-section {
display: flex;
align-items: center;
justify-content: center;
margin-bottom: 20px;
gap: 10px;
}
.color-picker-section label {
color: #e0e0e0;
font-weight: bold;
}
#habitColorPicker {
width: 40px;
height: 40px;
border: none;
border-radius: 50%;
cursor: pointer;
background: none;
}
.daily-target-section {
display: flex;
align-items: center;
justify-content: center;
margin-bottom: 20px;
gap: 10px;
}
.daily-target-section label {
color: #e0e0e0;
font-weight: bold;
}
#habitDailyTarget {
width: 60px;
padding: 5px;
border: 1px solid #444;
border-radius: 5px;
background-color: #333;
color: #e0e0e0;
text-align: center;
}
.daily-target-section span {
color: #e0e0e0;
}

View File

@@ -5,8 +5,15 @@ const dateModal = document.getElementById('dateModal');
const modalHabitName = document.getElementById('modalHabitName'); const modalHabitName = document.getElementById('modalHabitName');
const modalDateGrid = document.getElementById('modalDateGrid'); const modalDateGrid = document.getElementById('modalDateGrid');
const modalCompleteTodayBtn = document.getElementById('modalCompleteTodayBtn'); const modalCompleteTodayBtn = document.getElementById('modalCompleteTodayBtn');
const modalEditBtn = document.getElementById('modalEditBtn'); // Neu hinzugefügt
const modalDeleteBtn = document.getElementById('modalDeleteBtn'); // Neu hinzugefügt
let currentHabitId = null;
let currentHabitId = null; // Stellt sicher, dass diese globale Variable korrekt ist
let currentModalDate = new Date(); // Aktueller Monat im Modal
let currentHabitCompletedDates = {}; // Completed dates für das aktuelle Habit (now object with counts)
let currentHabitColor = '#4CAF50'; // Current habit color
let currentHabitDailyTarget = 1; // Current habit daily target
function getCurrentDate() { function getCurrentDate() {
const today = new Date(); const today = new Date();
@@ -29,6 +36,37 @@ function getPastDates(days) {
return dates; return dates;
} }
function calculateStreak(completedDates, dailyTarget) {
if (!completedDates || Object.keys(completedDates).length === 0) {
return 0;
}
const today = getCurrentDate();
let streak = 0;
let currentDate = new Date();
// Check if today is completed, if not, start from yesterday
const todayCount = completedDates[today] || 0;
if (todayCount < dailyTarget) {
currentDate.setDate(currentDate.getDate() - 1);
}
// Count consecutive days backwards from today (or yesterday)
while (true) {
const dateStr = `${currentDate.getFullYear()}-${String(currentDate.getMonth() + 1).padStart(2, '0')}-${String(currentDate.getDate()).padStart(2, '0')}`;
const count = completedDates[dateStr] || 0;
if (count >= dailyTarget) {
streak++;
currentDate.setDate(currentDate.getDate() - 1);
} else {
break;
}
}
return streak;
}
async function fetchHabits() { async function fetchHabits() {
try { try {
const response = await fetch('/habits'); const response = await fetch('/habits');
@@ -41,13 +79,16 @@ async function fetchHabits() {
function renderHabits(habits) { function renderHabits(habits) {
habitListDiv.innerHTML = ''; // Clear previous habits habitListDiv.innerHTML = ''; // Clear previous habits
const last30Days = getPastDates(30);
habits.forEach(habit => { habits.forEach(habit => {
const habitItem = document.createElement('div'); const habitItem = document.createElement('div');
habitItem.className = 'habit-item'; habitItem.className = 'habit-item';
habitItem.dataset.id = habit.id; // Store habit ID habitItem.dataset.id = habit.id; // Store habit ID
// Apply custom color to the habit item
const habitColor = habit.color || '#4CAF50';
habitItem.style.setProperty('--habit-color', habitColor);
const habitHeader = document.createElement('div'); const habitHeader = document.createElement('div');
habitHeader.className = 'habit-header'; habitHeader.className = 'habit-header';
@@ -58,26 +99,92 @@ function renderHabits(habits) {
const habitActions = document.createElement('div'); const habitActions = document.createElement('div');
habitActions.className = 'habit-actions'; habitActions.className = 'habit-actions';
const openModalButton = document.createElement('button');
openModalButton.innerHTML = '&#x2714;'; // Checkmark symbol // Haken-Button für heute abhaken/rückgängig machen mit Zähler
openModalButton.onclick = () => openHabitModal(habit.id, habit.name, habit.completed_dates); const todayToggleButton = document.createElement('button');
habitActions.appendChild(openModalButton); const today = getCurrentDate();
const todayCount = habit.completed_dates[today] || 0;
const dailyTarget = habit.daily_target || 1;
const isCompletedToday = todayCount >= dailyTarget;
// Show count if target > 1, otherwise just checkmark
if (dailyTarget > 1) {
todayToggleButton.innerHTML = `${todayCount}/${dailyTarget}`;
} else {
todayToggleButton.innerHTML = '&#x2713;'; // Checkmark symbol
}
todayToggleButton.className = isCompletedToday ? 'completed-today' : 'not-completed-today';
todayToggleButton.onclick = () => toggleTodayCompletion(habit.id, today, todayToggleButton, habit.daily_target);
habitActions.appendChild(todayToggleButton);
// Drei-Punkte-Menü für erweiterte Optionen
const menuButton = document.createElement('button');
menuButton.innerHTML = '&#x22EE;'; // Vertical ellipsis (drei Punkte)
menuButton.onclick = () => openHabitModal(habit.id, habit.name, habit.completed_dates, habitColor, habit.daily_target);
habitActions.appendChild(menuButton);
habitHeader.appendChild(habitActions); habitHeader.appendChild(habitActions);
habitItem.appendChild(habitHeader); habitItem.appendChild(habitHeader);
const dateGrid = document.createElement('div'); // Create weekly grid instead of single row
dateGrid.className = 'date-grid'; const weeklyGrid = document.createElement('div');
weeklyGrid.className = 'weekly-grid';
last30Days.forEach(date => { const weekdays = ['Montag', 'Dienstag', 'Mittwoch', 'Donnerstag', 'Freitag', 'Samstag', 'Sonntag'];
weekdays.forEach(weekday => {
const weekdayRow = document.createElement('div');
weekdayRow.className = 'weekday-row';
// Weekday label
const weekdayLabel = document.createElement('div');
weekdayLabel.className = 'weekday-label';
weekdayLabel.textContent = weekday.substring(0, 2); // Show first 2 letters
weekdayRow.appendChild(weekdayLabel);
// Date squares for this weekday
const weekdayDates = habit.weekly_completion[weekday] || [];
weekdayDates.forEach(dateInfo => {
const dateSquare = document.createElement('div'); const dateSquare = document.createElement('div');
dateSquare.className = 'date-square'; dateSquare.className = 'date-square date-square-readonly';
if (habit.completed_dates && habit.completed_dates.includes(date)) { dateSquare.dataset.date = dateInfo.date;
dateSquare.classList.add('completed');
// Apply gradient styling based on completion percentage
applyCompletionStyling(dateSquare, dateInfo.completed, dateInfo.target, habitColor);
// Show count in tooltip if target > 1
if (dateInfo.target > 1) {
dateSquare.title = `${dateInfo.date}: ${dateInfo.completed}/${dateInfo.target}`;
} else {
dateSquare.title = dateInfo.date;
} }
dateSquare.title = date; // Show date on hover
dateGrid.appendChild(dateSquare); // No click handler - dates are read-only in main view
weekdayRow.appendChild(dateSquare);
}); });
habitItem.appendChild(dateGrid);
weeklyGrid.appendChild(weekdayRow);
});
habitItem.appendChild(weeklyGrid);
// Streak Counter hinzufügen
const streakContainer = document.createElement('div');
streakContainer.className = 'streak-container';
const flameIcon = document.createElement('span');
flameIcon.className = 'flame-icon';
flameIcon.innerHTML = '🔥'; // Flammen-Emoji
const streakCount = document.createElement('span');
streakCount.className = 'streak-count';
const currentStreak = calculateStreak(habit.completed_dates, dailyTarget);
streakCount.textContent = `${currentStreak} Tag${currentStreak !== 1 ? 'e' : ''}`;
streakContainer.appendChild(flameIcon);
streakContainer.appendChild(streakCount);
habitItem.appendChild(streakContainer);
habitListDiv.appendChild(habitItem); habitListDiv.appendChild(habitItem);
}); });
@@ -107,79 +214,159 @@ async function addHabit() {
} }
} }
async function openHabitModal(habitId, habitName, completedDates) { async function openHabitModal(habitId, habitName, completedDates, habitColor = '#4CAF50', dailyTarget = 1) {
currentHabitId = habitId; currentHabitId = habitId;
currentHabitCompletedDates = completedDates;
currentHabitColor = habitColor;
currentHabitDailyTarget = dailyTarget;
currentModalDate = new Date(); // Reset to current month
modalHabitName.textContent = habitName; modalHabitName.textContent = habitName;
modalCompleteTodayBtn.dataset.habitId = habitId; // Store habit ID for button
// Setzen der habitId auf den Buttons im Modal
modalCompleteTodayBtn.dataset.habitId = habitId;
modalEditBtn.dataset.habitId = habitId;
modalDeleteBtn.dataset.habitId = habitId;
// Set color picker to current habit color
document.getElementById('habitColorPicker').value = habitColor;
// Set daily target input to current value
document.getElementById('habitDailyTarget').value = dailyTarget;
// Set CSS variable for modal elements
dateModal.style.setProperty('--current-habit-color', habitColor);
// Set contrast color for text on colored backgrounds
const contrastColor = getContrastColor(habitColor);
dateModal.style.setProperty('--current-habit-text-color', contrastColor);
renderModalCalendar();
dateModal.style.display = 'flex';
}
function renderModalCalendar() {
modalDateGrid.innerHTML = ''; modalDateGrid.innerHTML = '';
const today = getCurrentDate();
const startOfWeek = new Date();
startOfWeek.setDate(startOfWeek.getDate() - (startOfWeek.getDay() + 6) % 7); // Go back to Monday
for (let i = 0; i < 35; i++) { // Display 5 weeks (5 * 7 days) // Update month/year display
const d = new Date(startOfWeek); const monthNames = ['Januar', 'Februar', 'März', 'April', 'Mai', 'Juni',
d.setDate(startOfWeek.getDate() + i); 'Juli', 'August', 'September', 'Oktober', 'November', 'Dezember'];
const dateStr = `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`; document.getElementById('currentMonthYear').textContent =
`${monthNames[currentModalDate.getMonth()]} ${currentModalDate.getFullYear()}`;
const today = getCurrentDate();
const year = currentModalDate.getFullYear();
const month = currentModalDate.getMonth();
// Get first day of month and calculate starting position
const firstDay = new Date(year, month, 1);
const lastDay = new Date(year, month + 1, 0);
const startingDayOfWeek = (firstDay.getDay() + 6) % 7; // Monday = 0
// Add empty cells for days before month starts
for (let i = 0; i < startingDayOfWeek; i++) {
const emptyCell = document.createElement('div');
emptyCell.className = 'date-cell empty';
modalDateGrid.appendChild(emptyCell);
}
// Add days of the month
for (let day = 1; day <= lastDay.getDate(); day++) {
const dateStr = `${year}-${String(month + 1).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
const dateCell = document.createElement('div'); const dateCell = document.createElement('div');
dateCell.className = 'date-cell'; dateCell.className = 'date-cell';
dateCell.textContent = d.getDate(); dateCell.textContent = day;
if (completedDates.includes(dateStr)) {
const dateCount = currentHabitCompletedDates[dateStr] || 0;
const isCompleted = dateCount >= currentHabitDailyTarget;
if (isCompleted) {
dateCell.classList.add('completed'); dateCell.classList.add('completed');
} }
// Use the new display function for consistent formatting
updateDateCellDisplay(dateCell, dateStr, dateCount);
if (dateStr === today) { if (dateStr === today) {
dateCell.classList.add('today'); dateCell.classList.add('today');
} }
dateCell.dataset.date = dateStr; dateCell.dataset.date = dateStr;
dateCell.onclick = (event) => toggleCompletionForDate(event, habitId, dateStr); dateCell.onclick = (event) => toggleCompletionForDate(event, currentHabitId, dateStr);
modalDateGrid.appendChild(dateCell); modalDateGrid.appendChild(dateCell);
} }
}
dateModal.style.display = 'flex'; // Show the modal function changeMonth(direction) {
currentModalDate.setMonth(currentModalDate.getMonth() + direction);
renderModalCalendar();
} }
function closeModal() { function closeModal() {
dateModal.style.display = 'none'; dateModal.style.display = 'none';
currentHabitId = null; currentHabitId = null; // Zurücksetzen, wenn das Modal geschlossen wird
fetchHabits(); // Refresh habits after closing modal fetchHabits(); // Refresh habits after closing modal
} }
async function toggleCompletionForDate(event, habitId, date) { async function toggleCompletionForDate(event, habitId, date) {
const cell = event.target; // Find the actual date cell, even if clicked on child elements
let cell = event.target;
if (!cell.classList.contains('date-cell')) {
cell = cell.closest('.date-cell');
}
if (!cell) return; // Safety check
let response; let response;
let data; let data;
if (cell.classList.contains('completed')) { const currentCount = currentHabitCompletedDates[date] || 0;
// Mark as uncompleted const shouldDecrement = event.shiftKey || event.ctrlKey || currentCount >= currentHabitDailyTarget;
if (shouldDecrement && currentCount > 0) {
// Decrement completion count
response = await fetch(`/habits/${habitId}/uncomplete`, { response = await fetch(`/habits/${habitId}/uncomplete`, {
method: 'POST', method: 'POST',
headers: { 'Content-Type': 'application/json' }, headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ date: date }) body: JSON.stringify({ date: date })
}); });
data = await response.json();
if (response.ok) {
cell.classList.remove('completed');
// Update the completion_history in the rendered habits
// (You might need to re-fetch or update the local habit data for the main view)
}
} else { } else {
// Mark as completed // Increment completion count
response = await fetch(`/habits/${habitId}/complete`, { response = await fetch(`/habits/${habitId}/complete`, {
method: 'POST', method: 'POST',
headers: { 'Content-Type': 'application/json' }, headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ date: date }) body: JSON.stringify({ date: date })
}); });
data = await response.json();
if (response.ok) {
cell.classList.add('completed');
// Update the completion_history
} }
data = await response.json();
if (response.ok) {
// Update local completed dates object
currentHabitCompletedDates[date] = data.current_count;
// Update cell appearance
const newCount = data.current_count;
const isCompleted = newCount >= currentHabitDailyTarget;
if (isCompleted) {
cell.classList.add('completed');
} else {
cell.classList.remove('completed');
}
// Update cell text display
updateDateCellDisplay(cell, date, newCount);
} }
} }
async function completeHabitForDate(event, habitId, date) { async function completeHabitForDate(event, habitId, date) {
// Der habitId kommt jetzt direkt vom dataset des Buttons oder der Funktion, die ihn aufruft
// Sicherstellen, dass habitId gültig ist
if (!habitId) {
console.error('Habit ID is undefined for completion.');
return;
}
try { try {
const response = await fetch(`/habits/${habitId}/complete`, { const response = await fetch(`/habits/${habitId}/complete`, {
method: 'POST', method: 'POST',
@@ -195,8 +382,6 @@ async function completeHabitForDate(event, habitId, date) {
cell.classList.add('completed'); cell.classList.add('completed');
} }
}); });
// Optionally, disable the "Today erledigen" button if already completed
// modalCompleteTodayBtn.disabled = true;
} else { } else {
console.error('Failed to complete habit:', data.error); console.error('Failed to complete habit:', data.error);
} }
@@ -206,10 +391,15 @@ async function completeHabitForDate(event, habitId, date) {
} }
async function editHabitName() { async function editHabitName() {
// Sicherstellen, dass currentHabitId gesetzt ist
if (!currentHabitId) {
console.error('No habit selected for editing.');
return;
}
const newName = prompt("Neuen Namen für die Gewohnheit eingeben:", modalHabitName.textContent); const newName = prompt("Neuen Namen für die Gewohnheit eingeben:", modalHabitName.textContent);
if (newName && newName.trim() !== "") { if (newName && newName.trim() !== "") {
try { try {
const response = await fetch(`/habits/${currentHabitId}`, { const response = await fetch(`/habits/${currentHabitId}`, { // Verwendet currentHabitId
method: 'PUT', method: 'PUT',
headers: { 'Content-Type': 'application/json' }, headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: newName.trim() }) body: JSON.stringify({ name: newName.trim() })
@@ -228,9 +418,14 @@ async function editHabitName() {
} }
async function deleteHabitFromModal() { async function deleteHabitFromModal() {
// Sicherstellen, dass currentHabitId gesetzt ist
if (!currentHabitId) {
console.error('No habit selected for deletion.');
return;
}
if (confirm("Bist du sicher, dass du diese Gewohnheit löschen möchtest?")) { if (confirm("Bist du sicher, dass du diese Gewohnheit löschen möchtest?")) {
try { try {
const response = await fetch(`/habits/${currentHabitId}`, { const response = await fetch(`/habits/${currentHabitId}`, { // Verwendet currentHabitId
method: 'DELETE' method: 'DELETE'
}); });
const data = await response.json(); const data = await response.json();
@@ -245,3 +440,244 @@ async function deleteHabitFromModal() {
} }
} }
} }
async function toggleDateCompletion(event, habitId, date) {
try {
// Always increment completion count for weekly grid clicks
const response = await fetch(`/habits/${habitId}/complete`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ date: date })
});
const data = await response.json();
if (response.ok) {
// Refresh the entire habits display to show updated completion status
fetchHabits();
} else {
console.error('Failed to toggle habit completion:', data.error);
}
} catch (error) {
console.error('Error toggling habit completion:', error);
}
}
async function toggleTodayCompletion(habitId, date, buttonElement, dailyTarget = 1) {
try {
// Get current count first to check if we should increment or reset
const currentHabits = await fetch('/habits');
const habits = await currentHabits.json();
const currentHabit = habits.find(h => h.id === habitId);
const currentCount = currentHabit?.completed_dates[date] || 0;
let response;
if (currentCount >= dailyTarget) {
// If already at or above target, reset to 0 with single API call
response = await fetch(`/habits/${habitId}/reset`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ date: date })
});
} else {
// Increment completion count
response = await fetch(`/habits/${habitId}/complete`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ date: date })
});
}
const data = await response.json();
if (response.ok) {
const newCount = data.current_count;
const isCompleted = newCount >= dailyTarget;
// Update button appearance and text
if (dailyTarget > 1) {
buttonElement.innerHTML = `${newCount}/${dailyTarget}`;
}
buttonElement.className = isCompleted ? 'completed-today' : 'not-completed-today';
// Refresh the date grid to show updated completion status
fetchHabits();
} else {
console.error('Failed to toggle habit completion:', data.error);
}
} catch (error) {
console.error('Error toggling habit completion:', error);
}
}
async function updateHabitColor() {
if (!currentHabitId) {
console.error('No habit selected for color update.');
return;
}
const newColor = document.getElementById('habitColorPicker').value;
currentHabitColor = newColor;
try {
const response = await fetch(`/habits/${currentHabitId}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ color: newColor })
});
const data = await response.json();
if (response.ok) {
// Update CSS variable for modal elements
dateModal.style.setProperty('--current-habit-color', newColor);
// Update contrast color for text on colored backgrounds
const contrastColor = getContrastColor(newColor);
dateModal.style.setProperty('--current-habit-text-color', contrastColor);
// Update modal calendar colors immediately
updateModalColors(newColor);
// Refresh habits list to show new color
fetchHabits();
} else {
console.error('Failed to update habit color:', data.error);
}
} catch (error) {
console.error('Error updating habit color:', error);
}
}
function updateModalColors(color) {
// Update all date cells in modal to use new color
const allCells = modalDateGrid.querySelectorAll('.date-cell');
allCells.forEach(cell => {
const dateStr = cell.dataset.date;
if (dateStr) {
const dateCount = currentHabitCompletedDates[dateStr] || 0;
// Re-apply styling with new color
applyModalCompletionStyling(cell, dateCount, currentHabitDailyTarget, color);
}
});
}
function getContrastColor(hexColor) {
// Convert hex to RGB
const r = parseInt(hexColor.slice(1, 3), 16);
const g = parseInt(hexColor.slice(3, 5), 16);
const b = parseInt(hexColor.slice(5, 7), 16);
// Calculate luminance
const luminance = (0.299 * r + 0.587 * g + 0.114 * b) / 255;
// Return dark text for light colors, light text for dark colors
return luminance > 0.5 ? '#333333' : '#ffffff';
}
async function updateDailyTarget() {
if (!currentHabitId) {
console.error('No habit selected for daily target update.');
return;
}
const newTarget = parseInt(document.getElementById('habitDailyTarget').value);
if (newTarget < 1 || newTarget > 20) {
alert('Tägliches Ziel muss zwischen 1 und 20 liegen.');
return;
}
currentHabitDailyTarget = newTarget;
try {
const response = await fetch(`/habits/${currentHabitId}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ daily_target: newTarget })
});
const data = await response.json();
if (response.ok) {
// Re-render modal calendar with new target
renderModalCalendar();
// Refresh habits list to show new target
fetchHabits();
} else {
console.error('Failed to update daily target:', data.error);
}
} catch (error) {
console.error('Error updating daily target:', error);
}
}
function updateDateCellDisplay(cell, date, count) {
const day = date.split('-')[2]; // Get day from YYYY-MM-DD format
// Clear any existing content first
cell.innerHTML = '';
// Apply gradient styling for modal cells
applyModalCompletionStyling(cell, count, currentHabitDailyTarget, currentHabitColor);
if (currentHabitDailyTarget > 1) {
// Create structured display with date on top, counter below
const dayDiv = document.createElement('div');
dayDiv.className = 'date-day';
dayDiv.textContent = parseInt(day);
const counterDiv = document.createElement('div');
counterDiv.className = 'date-counter';
counterDiv.textContent = `${count}/${currentHabitDailyTarget}`;
cell.appendChild(dayDiv);
cell.appendChild(counterDiv);
} else {
cell.textContent = parseInt(day);
}
}
function applyCompletionStyling(element, currentCount, targetCount, color) {
// Remove existing classes
element.classList.remove('completed', 'partial');
if (currentCount === 0) {
// No completion - default background
return;
} else if (currentCount >= targetCount) {
// Fully completed - solid color
element.classList.add('completed');
} else {
// Partially completed - transparency overlay
element.classList.add('partial');
const opacity = currentCount / targetCount; // 0.0 to 1.0
element.style.setProperty('--completion-opacity', opacity);
element.style.setProperty('--habit-color', color);
}
}
function applyModalCompletionStyling(element, currentCount, targetCount, color) {
// Remove existing classes
element.classList.remove('completed', 'partial');
if (currentCount === 0) {
// No completion - default background and text
element.style.removeProperty('color');
return;
} else if (currentCount >= targetCount) {
// Fully completed - solid color with contrast text
element.classList.add('completed');
const contrastColor = getContrastColor(color);
element.style.setProperty('color', contrastColor);
} else {
// Partially completed - transparency overlay with smart text color
element.classList.add('partial');
const opacity = currentCount / targetCount; // 0.0 to 1.0
element.style.setProperty('--completion-opacity', opacity);
element.style.setProperty('--current-habit-color', color);
// For partial completion, use contrast color if more than 50% completed
if (opacity > 0.5) {
const contrastColor = getContrastColor(color);
element.style.setProperty('color', contrastColor);
} else {
// Use default text color for low completion
element.style.setProperty('color', '#e0e0e0');
}
}
}

View File

@@ -3,7 +3,7 @@
<head> <head>
<meta charset="UTF-8"> <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>HabitKit Clone</title> <title>Habit Tracker</title>
<link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}"> <link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}">
</head> </head>
<body> <body>
@@ -21,9 +21,32 @@
<div class="modal-content"> <div class="modal-content">
<span class="close-button" onclick="closeModal()">&times;</span> <span class="close-button" onclick="closeModal()">&times;</span>
<h2 id="modalHabitName"></h2> <h2 id="modalHabitName"></h2>
<div class="month-navigation">
<button id="prevMonthBtn" onclick="changeMonth(-1)">&lt;</button>
<span id="currentMonthYear"></span>
<button id="nextMonthBtn" onclick="changeMonth(1)">&gt;</button>
</div>
<div class="weekdays-header">
<div>Mo</div>
<div>Di</div>
<div>Mi</div>
<div>Do</div>
<div>Fr</div>
<div>Sa</div>
<div>So</div>
</div>
<div id="modalDateGrid" class="date-grid-modal"></div> <div id="modalDateGrid" class="date-grid-modal"></div>
<div class="color-picker-section">
<label for="habitColorPicker">Farbe wählen:</label>
<input type="color" id="habitColorPicker" onchange="updateHabitColor()">
</div>
<div class="daily-target-section">
<label for="habitDailyTarget">Tägliches Ziel:</label>
<input type="number" id="habitDailyTarget" min="1" max="20" onchange="updateDailyTarget()">
<span>x pro Tag</span>
</div>
<div class="modal-actions"> <div class="modal-actions">
<button id="modalCompleteTodayBtn" onclick="completeHabitForDate(event, this.dataset.habitId, getCurrentDate())">Heute erledigen</button> <button id="modalCompleteTodayBtn" onclick="completeHabitForDate(event, currentHabitId, getCurrentDate())">Heute erledigen</button>
<button id="modalEditBtn" onclick="editHabitName()">Bearbeiten</button> <button id="modalEditBtn" onclick="editHabitName()">Bearbeiten</button>
<button id="modalDeleteBtn" onclick="deleteHabitFromModal()">Löschen</button> <button id="modalDeleteBtn" onclick="deleteHabitFromModal()">Löschen</button>
</div> </div>