Files
TimeTracker/app/templates/base.html
Dries Peeters 20824dbcb1 feat: Add customizable Kanban board columns and enhance CSRF configuration
This commit introduces a comprehensive Kanban board customization system and
improves CSRF token configuration for Docker deployments.

## Major Features

### 1. Customizable Kanban Board Columns
Add complete kanban column customization system allowing users to define
custom workflow states beyond the default columns.

**New Components:**
- Add KanbanColumn model with full CRUD operations (app/models/kanban_column.py)
- Add kanban routes blueprint with admin endpoints (app/routes/kanban.py)
- Add kanban column management templates (app/templates/kanban/)
- Add migration 019 for kanban_columns table (migrations/)

**Features:**
- Create unlimited custom columns with unique keys, labels, icons, and colors
- Drag-and-drop column reordering with position persistence
- Toggle column visibility without deletion
- Protected system columns (todo, in_progress, done) prevent accidental deletion
- Complete state marking for columns that should mark tasks as done
- Real-time updates via SocketIO broadcasts when columns change
- Font Awesome icon support (5000+ icons)
- Bootstrap color scheme integration
- Comprehensive validation and error handling

**Integration:**
- Update Task model to work with dynamic column statuses (app/models/task.py)
- Update task routes to use kanban column API (app/routes/tasks.py)
- Update project routes to fetch active columns (app/routes/projects.py)
- Add kanban column management links to base template (app/templates/base.html)
- Update kanban board templates to render dynamic columns (app/templates/tasks/)
- Add cache prevention headers to force fresh column data

**API Endpoints:**
- GET /api/kanban/columns - Fetch all active columns
- POST /api/kanban/columns/reorder - Reorder columns
- GET /kanban/columns - Column management interface (admin only)
- POST /kanban/columns/create - Create new column (admin only)
- POST /kanban/columns/<id>/edit - Edit column (admin only)
- POST /kanban/columns/<id>/delete - Delete column (admin only)
- POST /kanban/columns/<id>/toggle - Toggle column visibility (admin only)

### 2. Enhanced CSRF Configuration
Improve CSRF token configuration and documentation for Docker deployments.

**Configuration Updates:**
- Add WTF_CSRF_ENABLED environment variable to all docker-compose files
- Add WTF_CSRF_TIME_LIMIT environment variable with 1-hour default
- Update app/config.py to read CSRF settings from environment
- Add SECRET_KEY validation in app/__init__.py to prevent production deployment
  with default keys

**Docker Compose Updates:**
- docker-compose.yml: CSRF enabled by default for security testing
- docker-compose.remote.yml: CSRF always enabled in production
- docker-compose.remote-dev.yml: CSRF enabled with production-like settings
- docker-compose.local-test.yml: CSRF can be disabled for local testing
- Add helpful comments explaining each CSRF-related environment variable
- Update env.example with CSRF configuration examples

**Verification Scripts:**
- Add scripts/verify_csrf_config.sh for Unix systems
- Add scripts/verify_csrf_config.bat for Windows systems
- Scripts check SECRET_KEY, CSRF_ENABLED, and CSRF_TIME_LIMIT settings

### 3. Database Initialization Improvements
- Update app/__init__.py to run pending migrations on startup
- Add automatic kanban column initialization after migrations
- Improve error handling and logging during database setup

### 4. Configuration Management
- Update app/config.py with new CSRF and kanban-related settings
- Add environment variable parsing with sensible defaults
- Improve configuration validation and error messages

## Documentation

### New Documentation Files
- CUSTOM_KANBAN_README.md: Quick start guide for kanban customization
- KANBAN_CUSTOMIZATION.md: Detailed technical documentation
- IMPLEMENTATION_SUMMARY.md: Implementation details and architecture
- KANBAN_AUTO_REFRESH_COMPLETE.md: Real-time update system documentation
- KANBAN_REFRESH_FINAL_FIX.md: Cache and refresh troubleshooting
- KANBAN_REFRESH_SOLUTION.md: Technical solution for data freshness
- docs/CSRF_CONFIGURATION.md: Comprehensive CSRF setup guide
- CSRF_DOCKER_CONFIGURATION_SUMMARY.md: Docker-specific CSRF setup
- CSRF_TROUBLESHOOTING.md: Common CSRF issues and solutions
- APPLY_KANBAN_MIGRATION.md: Migration application guide
- APPLY_FIXES_NOW.md: Quick fix reference
- DEBUG_KANBAN_COLUMNS.md: Debugging guide
- DIAGNOSIS_STEPS.md: System diagnosis procedures
- BROWSER_CACHE_FIX.md: Browser cache troubleshooting
- FORCE_NO_CACHE_FIX.md: Cache prevention solutions
- SESSION_CLOSE_ERROR_FIX.md: Session handling fixes
- QUICK_FIX.md: Quick reference for common fixes

### Updated Documentation
- README.md: Add kanban customization feature description
- Update project documentation with new features

## Testing

### New Test Files
- test_kanban_refresh.py: Test kanban column refresh functionality

## Technical Details

**Database Changes:**
- New table: kanban_columns with 11 columns
- Indexes on: key, position
- Default data: 4 system columns (todo, in_progress, review, done)
- Support for both SQLite (development) and PostgreSQL (production)

**Real-Time Updates:**
- SocketIO events: 'kanban_columns_updated' with action type
- Automatic page refresh when columns are created/updated/deleted/reordered
- Prevents stale data by expiring SQLAlchemy caches after changes

**Security:**
- Admin-only access to column management
- CSRF protection on all column mutation endpoints
- API endpoints exempt from CSRF (use JSON and other auth mechanisms)
- System column protection prevents data integrity issues
- Validation prevents deletion of columns with active tasks

**Performance:**
- Efficient querying with position-based ordering
- Cached column data with cache invalidation on changes
- No-cache headers on API responses to prevent stale data
- Optimized database indexes for fast lookups

## Breaking Changes

None. This is a fully backward-compatible addition.

Existing workflows continue to work with the default columns.
Custom columns are opt-in via the admin interface.

## Migration Notes

1. Run migration 019 to create kanban_columns table
2. Default columns are initialized automatically on first run
3. No data migration needed for existing tasks
4. Existing task statuses map to new column keys

## Environment Variables

New environment variables (all optional with defaults):
- WTF_CSRF_ENABLED: Enable/disable CSRF protection (default: true)
- WTF_CSRF_TIME_LIMIT: CSRF token expiration in seconds (default: 3600)
- SECRET_KEY: Required in production, must be cryptographically secure

See env.example for complete configuration reference.

## Deployment Notes
2025-10-11 19:56:45 +02:00

720 lines
39 KiB
HTML

<!DOCTYPE html>
<html lang="{{ current_locale or 'en' }}">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<meta name="mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="default">
<meta name="theme-color" content="#3b82f6" id="meta-theme-color">
<meta id="user-theme-pref" data-user-theme="{{ current_user.theme_preference if current_user.is_authenticated else '' }}">
<title>{% block title %}{{ app_name }}{% endblock %}</title>
{% if csrf_token %}
<meta name="csrf-token" content="{{ csrf_token() }}">
{% endif %}
<!-- Favicon -->
{% if settings and settings.has_logo() %}
<link rel="icon" type="image/x-icon" href="{{ settings.get_logo_url() }}">
{% else %}
<link rel="icon" type="image/svg+xml" href="{{ url_for('static', filename='images/drytrix-logo.svg') }}">
{% endif %}
<!-- Persist compact density ASAP to avoid flicker across pages -->
<script>
(function(){
try {
var d = localStorage.getItem('tt-density');
if (d === 'compact') { document.documentElement.classList.add('compact'); }
} catch(e) {}
})();
</script>
<!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
<!-- Font Awesome -->
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
<!-- Google Fonts -->
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
<!-- Custom CSS (cache-busted with app_version) -->
<link rel="stylesheet" href="{{ url_for('static', filename='base.css') }}?v={{ app_version }}">
<link rel="stylesheet" href="{{ url_for('static', filename='mobile.css') }}?v={{ app_version }}">
<link rel="stylesheet" href="{{ url_for('static', filename='ui.css') }}?v={{ app_version }}">
<link rel="stylesheet" href="{{ url_for('static', filename='loading-states.css') }}?v={{ app_version }}">
<link rel="stylesheet" href="{{ url_for('static', filename='micro-interactions.css') }}?v={{ app_version }}">
<link rel="stylesheet" href="{{ url_for('static', filename='empty-states.css') }}?v={{ app_version }}">
<link rel="stylesheet" href="{{ url_for('static', filename='enhanced-search.css') }}?v={{ app_version }}">
<link rel="stylesheet" href="{{ url_for('static', filename='keyboard-shortcuts.css') }}?v={{ app_version }}">
<link rel="stylesheet" href="{{ url_for('static', filename='enhanced-tables.css') }}?v={{ app_version }}">
<link rel="stylesheet" href="{{ url_for('static', filename='toast-notifications.css') }}?v={{ app_version }}">
<link rel="manifest" href="{{ url_for('static', filename='manifest.webmanifest') }}">
{% block extra_css %}{% endblock %}
{% block head_extra %}{% endblock %}
<script>
(function() {
try {
const storageKey = 'tt-theme';
const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
const saved = localStorage.getItem(storageKey);
const userMeta = document.getElementById('user-theme-pref');
const serverPrefRaw = userMeta ? (userMeta.getAttribute('data-user-theme') || '').trim().toLowerCase() : '';
const serverPref = (serverPrefRaw === 'light' || serverPrefRaw === 'dark') ? serverPrefRaw : null;
const theme = serverPref || saved || (prefersDark ? 'dark' : 'light');
const root = document.documentElement;
root.setAttribute('data-theme', theme);
if (serverPref) {
root.setAttribute('data-theme-locked', 'user');
} else if (saved) {
root.setAttribute('data-theme-locked', 'local');
}
const meta = document.getElementById('meta-theme-color');
if (meta) meta.setAttribute('content', theme === 'dark' ? '#0b1220' : '#3b82f6');
} catch (e) {}
})();
</script>
</head>
<body>
<a class="skip-link" href="#main-content">{{ _('Skip to content') }}</a>
<!-- Modern Toast Notification Container -->
<div id="toast-notification-container"></div>
<!-- Legacy toast container for backwards compatibility -->
<div id="toast-container" class="toast-container position-fixed top-0 end-0 p-3" style="display: none;"></div>
<!-- Enhanced Navigation -->
<nav class="navbar navbar-expand-lg navbar-light sticky-top">
<div class="container-fluid px-3">
<a class="navbar-brand" href="{{ url_for('main.dashboard') }}">
{% if settings and settings.has_logo() %}
<img src="{{ settings.get_logo_url() }}" alt="Company Logo" width="36" height="36">
{% else %}
<img src="{{ url_for('static', filename='images/drytrix-logo.svg') }}" alt="DryTrix Logo" width="36" height="36">
{% endif %}
<span class="text-dark fw-bold ms-2 d-none d-md-inline">{{ _('Time Tracker') }}</span>
</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNav">
{% if current_user.is_authenticated %}
<ul class="navbar-nav me-auto">
<li class="nav-item">
<a class="nav-link {% if request.endpoint == 'main.dashboard' %}active{% endif %}" {% if request.endpoint == 'main.dashboard' %}aria-current="page"{% endif %} href="{{ url_for('main.dashboard') }}">
<i class="fas fa-tachometer-alt"></i>{{ _('Dashboard') }}
</a>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle {% if request.endpoint and ('projects.' in request.endpoint or 'clients.' in request.endpoint or 'tasks.' in request.endpoint or 'timer.' in request.endpoint) %}active{% endif %}"
href="#" id="workDropdown" role="button" data-bs-toggle="dropdown" data-bs-auto-close="outside" aria-expanded="false">
<i class="fas fa-briefcase"></i>{{ _('Work') }}
</a>
<ul class="dropdown-menu" aria-labelledby="workDropdown">
<li><a class="dropdown-item" href="{{ url_for('projects.list_projects') }}"><i class="fas fa-project-diagram me-2"></i>{{ _('Projects') }}</a></li>
<li><a class="dropdown-item" href="{{ url_for('clients.list_clients') }}"><i class="fas fa-building me-2"></i>{{ _('Clients') }}</a></li>
<li><a class="dropdown-item" href="{{ url_for('tasks.list_tasks') }}"><i class="fas fa-tasks me-2"></i>{{ _('Tasks') }}</a></li>
<li><hr class="dropdown-divider"></li>
<li><a class="dropdown-item" href="{{ url_for('timer.manual_entry') }}"><i class="fas fa-plus me-2"></i>{{ _('Log Time') }}</a></li>
<li><a class="dropdown-item" href="{{ url_for('timer.bulk_entry') }}"><i class="fas fa-calendar-plus me-2"></i>{{ _('Bulk Time Entry') }}</a></li>
<li><a class="dropdown-item" href="{{ url_for('timer.calendar_view') }}"><i class="fas fa-calendar-alt me-2"></i>{{ _('Calendar') }}</a></li>
</ul>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle {% if request.endpoint and ('reports.' in request.endpoint or 'invoices.' in request.endpoint or 'analytics.' in request.endpoint) %}active{% endif %}"
href="#" id="insightsDropdown" role="button" data-bs-toggle="dropdown" data-bs-auto-close="outside" aria-expanded="false">
<i class="fas fa-chart-line"></i>{{ _('Insights') }}
</a>
<ul class="dropdown-menu" aria-labelledby="insightsDropdown">
<li><a class="dropdown-item" href="{{ url_for('reports.reports') }}"><i class="fas fa-chart-bar me-2"></i>{{ _('Reports') }}</a></li>
<li><a class="dropdown-item" href="{{ url_for('invoices.list_invoices') }}"><i class="fas fa-file-invoice-dollar me-2"></i>{{ _('Invoices') }}</a></li>
<li><a class="dropdown-item" href="{{ url_for('analytics.analytics_dashboard') }}"><i class="fas fa-chart-line me-2"></i>{{ _('Analytics') }}</a></li>
</ul>
</li>
{% if current_user.is_admin %}
<li class="nav-item">
<a class="nav-link {% if request.endpoint and 'admin.' in request.endpoint %}active{% endif %}" {% if request.endpoint and 'admin.' in request.endpoint %}aria-current="page"{% endif %} href="{{ url_for('admin.admin_dashboard') }}">
<i class="fas fa-cog"></i>{{ _('Admin') }}
</a>
</li>
{% endif %}
</ul>
<ul class="navbar-nav ms-auto">
<!-- Global Search (desktop) -->
<li class="nav-item d-none d-xl-flex align-items-center me-2">
<form class="navbar-search" role="search" action="{{ url_for('main.search') }}" method="get">
<input name="q" type="search" placeholder="{{ _('Search') }}" aria-label="{{ _('Search') }}" data-enhanced-search='{"endpoint": "/api/search", "minChars": 2, "maxResults": 10}' data-bs-toggle="tooltip" data-bs-placement="bottom" title="{{ _('Search') }} ({{ _('Ctrl') }}+K)">
</form>
</li>
<!-- Command Palette Launcher (desktop) -->
<li class="nav-item d-none d-xl-flex align-items-center me-2">
<button id="commandPaletteBtn" class="btn btn-quiet nav-control" type="button" onclick="try{ window.keyboardShortcuts?.openCommandPalette(); }catch(e){}" data-bs-toggle="tooltip" data-bs-placement="bottom" title="{{ _('Open Command Palette') }} (?)">
<i class="fas fa-terminal"></i>
</button>
</li>
<!-- Visual divider between actions and account -->
<li class="nav-item d-none d-xl-flex align-items-center nav-divider" aria-hidden="true"></li>
<!-- Language Switcher -->
<li class="nav-item dropdown me-2 d-flex align-items-center">
<a class="nav-link dropdown-toggle d-flex align-items-center nav-control nav-quiet"
href="#"
id="langDropdown"
role="button"
data-bs-toggle="dropdown"
aria-expanded="false"
title="{{ _('Language') }}: {{ current_language_label }}">
<i class="fas fa-globe me-1"></i>
<span class="d-none d-lg-inline">{{ current_language_label }}</span>
</a>
<ul class="dropdown-menu dropdown-menu-end shadow-sm" aria-labelledby="langDropdown">
<li class="dropdown-header">{{ _('Language') }}</li>
{% for code, label in config['LANGUAGES'].items() %}
<li>
<a class="dropdown-item {% if current_language_code == code %}active{% endif %}"
href="{{ url_for('main.set_language') }}?lang={{ code }}"
{% if current_language_code == code %}aria-current="true"{% endif %}>
{% if current_language_code == code %}<i class="fas fa-check me-2"></i>{% endif %}{{ label }}
</a>
</li>
{% endfor %}
</ul>
</li>
{% if current_user.is_authenticated %}
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle d-flex align-items-center" href="#" id="navbarDropdown" role="button" data-bs-toggle="dropdown" data-bs-display="static" aria-expanded="false">
<div class="bg-primary bg-opacity-10 rounded-circle d-flex align-items-center justify-content-center me-2" style="width: 36px; height: 36px;">
<i class="fas fa-user text-primary"></i>
</div>
<span class="d-none d-xl-inline">{{ current_user.display_name }}</span>
</a>
<ul class="dropdown-menu dropdown-menu-end">
<li>
<a class="dropdown-item" href="#" onclick="try{ window.keyboardShortcuts?.openCommandPalette(); }catch(e){}">
<i class="fas fa-keyboard me-2"></i>{{ _('Keyboard Shortcuts') }}
</a>
</li>
<li>
<a class="dropdown-item d-none" id="installAppMenuItem" href="#">
<i class="fas fa-download me-2"></i>{{ _('Install App') }}
</a>
</li>
<li><hr class="dropdown-divider"></li>
<li><a class="dropdown-item" href="{{ url_for('auth.profile') }}">
<i class="fas fa-user-circle me-2"></i>{{ _('Profile') }}
</a></li>
<li><hr class="dropdown-divider"></li>
<li><a class="dropdown-item" href="{{ url_for('auth.logout') }}">
<i class="fas fa-sign-out-alt me-2"></i>{{ _('Logout') }}
</a></li>
</ul>
</li>
{% endif %}
</ul>
{% endif %}
</div>
</div>
</nav>
<!-- Enhanced Main Content -->
<main id="main-content" class="container-fluid mt-4 px-3 px-md-4">
<!-- Flash Messages (converted to toast notifications by JS) -->
{% with messages = get_flashed_messages(with_categories=true) %}
{% if messages %}
<div id="flash-messages-container" style="display: none;">
{% for category, message in messages %}
<div class="alert alert-{{ 'danger' if category == 'error' else category }}" role="alert" data-toast-message="{{ message }}" data-toast-type="{{ 'error' if category == 'error' else category }}">
{{ message }}
</div>
{% endfor %}
</div>
{% endif %}
{% endwith %}
<!-- Enhanced Page Content -->
{% block content %}{% endblock %}
</main>
<!-- Mobile Bottom Tab Bar -->
{% if current_user.is_authenticated %}
<div class="mobile-tabbar d-lg-none">
<a href="{{ url_for('main.dashboard') }}" class="tab-item {% if request.endpoint == 'main.dashboard' %}active{% endif %}" aria-label="{{ _('Dashboard') }}">
<i class="fas fa-tachometer-alt tab-icon"></i>
<span>{{ _('Home') }}</span>
</a>
<a href="{{ url_for('timer.manual_entry') }}" class="tab-item {% if request.endpoint and 'timer.' in request.endpoint %}active{% endif %}" aria-label="{{ _('Log Time') }}">
<i class="fas fa-plus tab-icon"></i>
<span>{{ _('Log') }}</span>
</a>
<a href="{{ url_for('tasks.list_tasks') }}" class="tab-item {% if request.endpoint and 'tasks.' in request.endpoint %}active{% endif %}" aria-label="{{ _('Tasks') }}">
<i class="fas fa-tasks tab-icon"></i>
<span>{{ _('Tasks') }}</span>
</a>
<a href="{{ url_for('reports.reports') }}" class="tab-item {% if request.endpoint and 'reports.' in request.endpoint %}active{% endif %}" aria-label="{{ _('Reports') }}">
<i class="fas fa-chart-bar tab-icon"></i>
<span>{{ _('Reports') }}</span>
</a>
</div>
{% endif %}
<!-- Enhanced Footer -->
<footer class="footer mt-auto">
<div class="container">
<div class="row align-items-center">
<div class="col-md-6">
<p class="mb-0 text-muted">
&copy; 2025 <strong>DryTrix</strong>. {{ _('All rights reserved.') }}
</p>
</div>
<div class="col-md-6 text-md-end">
<div class="d-flex justify-content-md-end gap-3 align-items-center">
<small class="text-muted">{{ app_version }}</small>
<small><a href="{{ url_for('main.about') }}" class="text-decoration-none">{{ _('About') }}</a></small>
<small><a href="{{ url_for('main.help') }}" class="text-decoration-none">{{ _('Help') }}</a></small>
<small>
<a href="https://buymeacoffee.com/DryTrix" target="_blank" rel="noopener" class="text-decoration-none">
<i class="fas fa-mug-hot me-1"></i> {{ _('Buy me a coffee') }}
</a>
</small>
</div>
</div>
</div>
</div>
</footer>
<!-- Command Palette is created dynamically by keyboard-shortcuts.js -->
<!-- Global Confirm Modal -->
<div class="modal" id="globalConfirmModal" tabindex="-1" aria-hidden="true" aria-labelledby="globalConfirmTitle">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="globalConfirmTitle">{{ _('Please confirm') }}</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="{{ _('Close') }}"></button>
</div>
<div class="modal-body" id="globalConfirmMessage"></div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">{{ _('Cancel') }}</button>
<button type="button" class="btn btn-danger" id="globalConfirmOk">{{ _('Confirm') }}</button>
</div>
</div>
</div>
</div>
<!-- Bootstrap JS -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script type="application/json" id="i18n-json">
{
"close": {{ _('Close')|tojson }},
"timer_started_for": {{ _('Timer started for')|tojson }},
"timer_stopped_duration": {{ _('Timer stopped. Duration:')|tojson }},
"switch_to_light_mode": {{ _('Switch to light mode')|tojson }},
"switch_to_dark_mode": {{ _('Switch to dark mode')|tojson }},
"light_mode": {{ _('Light mode')|tojson }},
"dark_mode": {{ _('Dark mode')|tojson }}
}
</script>
<script>
// Parse i18n JSON into a global variable
var i18n = (function(){
try {
var el = document.getElementById('i18n-json');
return el ? JSON.parse(el.textContent) : {};
} catch (e) { return {}; }
})();
// Global helpers available on all pages
function formatDuration(seconds) {
const total = Number(seconds) || 0;
const hours = Math.floor(total / 3600);
const minutes = Math.floor((total % 3600) / 60);
const secs = total % 60;
return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
}
// Legacy showToast function - redirects to new toast system
// Will be overridden by toast-notifications.js when it loads
function showToast(message, type = 'info') {
// Temporary implementation until toast-notifications.js loads
console.log('Toast:', type, message);
}
// Navbar scrolled shadow behavior
document.addEventListener('scroll', function() {
const nav = document.querySelector('.navbar');
if (!nav) return;
if (window.scrollY > 4) {
nav.classList.add('scrolled');
} else {
nav.classList.remove('scrolled');
}
}, { passive: true });
// Use Bootstrap's default dropdown behavior; no custom backdrop
</script>
<!-- Global theme toggle logic -->
<script>
(function(){
try {
const storageKey = 'tt-theme';
const btn = document.getElementById('theme-toggle-global');
const meta = document.getElementById('meta-theme-color');
const root = document.documentElement;
const updateUrl = btn ? btn.getAttribute('data-update-theme-url') : null;
function currentTheme(){
return root.getAttribute('data-theme') || 'light';
}
function updateIcon(theme){
if (!btn) return;
const icon = btn.querySelector('i');
if (icon) icon.className = theme === 'dark' ? 'fas fa-sun' : 'fas fa-moon';
if (typeof i18n !== 'undefined') {
btn.setAttribute('aria-label', theme === 'dark' ? i18n.switch_to_light_mode : i18n.switch_to_dark_mode);
btn.title = theme === 'dark' ? i18n.light_mode : i18n.dark_mode;
} else {
btn.setAttribute('aria-label', theme === 'dark' ? 'Switch to light mode' : 'Switch to dark mode');
btn.title = theme === 'dark' ? 'Light mode' : 'Dark mode';
}
}
function applyTheme(theme, persist){
root.setAttribute('data-theme', theme);
if (meta) meta.setAttribute('content', theme === 'dark' ? '#0b1220' : '#3b82f6');
updateIcon(theme);
if (persist) {
try { localStorage.setItem(storageKey, theme); } catch(e) {}
if (updateUrl) {
try {
fetch(updateUrl, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ theme })
}).catch(function(){});
} catch(e) {}
}
}
}
if (btn) {
// Initialize icon to current theme
updateIcon(currentTheme());
btn.addEventListener('click', function(){
const next = currentTheme() === 'dark' ? 'light' : 'dark';
applyTheme(next, true);
});
// Enable tooltip if available
try { new bootstrap.Tooltip(btn); } catch(e) {}
try { var cp = document.getElementById('commandPaletteBtn'); if (cp) { new bootstrap.Tooltip(cp); } } catch(e) {}
}
// Keep icon in sync if theme changes elsewhere
try {
new MutationObserver(function(){ updateIcon(currentTheme()); })
.observe(root, { attributes: true, attributeFilter: ['data-theme'] });
} catch(e) {}
} catch(e) {}
})();
</script>
{% if current_user.is_authenticated %}
<!-- Socket.IO only for authenticated users -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.7.2/socket.io.js"></script>
{% endif %}
<!-- Toast Notification System -->
<script src="{{ url_for('static', filename='toast-notifications.js') }}?v={{ app_version }}"></script>
{% if request.endpoint != 'auth.login' %}
<!-- Custom JS (disabled on login to avoid interference) -->
<script src="{{ url_for('static', filename='mobile.js') }}"></script>
<script src="{{ url_for('static', filename='interactions.js') }}?v={{ app_version }}"></script>
<script src="{{ url_for('static', filename='enhanced-search.js') }}?v={{ app_version }}"></script>
<script src="{{ url_for('static', filename='keyboard-shortcuts.js') }}?v={{ app_version }}"></script>
<script src="{{ url_for('static', filename='enhanced-tables.js') }}?v={{ app_version }}"></script>
<script src="{{ url_for('static', filename='idle.js') }}?v={{ app_version }}"></script>
{% endif %}
{% if current_user.is_authenticated %}
<script>
// Initialize Socket.IO only when logged in
try {
const socket = io();
socket.on('connect', () => console.log('Connected to server'));
socket.on('disconnect', () => console.log('Disconnected from server'));
socket.on('timer_started', (data) => {
if (window.toastManager) {
window.toastManager.success(`{{ _('Timer started for') }} ${data.project_name}`, '{{ _('Timer Started') }}');
}
if (typeof updateTimerDisplay === 'function') updateTimerDisplay();
});
socket.on('timer_stopped', (data) => {
if (window.toastManager) {
window.toastManager.info(`{{ _('Timer stopped. Duration:') }} ${data.duration}`, '{{ _('Timer Stopped') }}');
}
if (typeof updateTimerDisplay === 'function') updateTimerDisplay();
});
// Listen for kanban column updates; prefer live in-page handler, fallback to reload
socket.on('kanban_columns_updated', (data) => {
console.log('Kanban columns updated:', data);
try {
if (typeof window.handleKanbanColumnsUpdated === 'function') {
// Let the active page update its DOM live
window.handleKanbanColumnsUpdated(data);
} else {
// Fallback: show toast and hard-reload to reflect changes
if (window.toastManager) {
window.toastManager.info('{{ _('Kanban columns updated. Refreshing...') }}', '{{ _('Update') }}');
} else {
try { showToast('{{ _('Kanban columns updated. Refreshing...') }}', 'info'); } catch(_) {}
}
setTimeout(() => {
if ('caches' in window) {
caches.keys().then(names => { names.forEach(name => caches.delete(name)); });
}
window.location.reload(true);
}, 500);
}
} catch (e) {
console.warn('Kanban update handler failed, reloading:', e);
setTimeout(() => window.location.reload(true), 500);
}
});
// Make socket globally available
window.appSocket = socket;
console.log('Base template initialized - Socket.IO and global functions ready');
} catch (e) {
console.warn('Socket.IO init failed:', e);
}
</script>
{% endif %}
<script>
// Cross-tab Kanban update fallbacks: BroadcastChannel + localStorage
(function(){
try {
function triggerKanbanUpdate(data){
try {
if (typeof window.handleKanbanColumnsUpdated === 'function') {
window.handleKanbanColumnsUpdated(data || { source: 'broadcast' });
} else if (window.toastManager) {
window.toastManager.info('{{ _('Kanban columns updated') }}', '{{ _('Update') }}');
} else {
try { showToast('{{ _('Kanban columns updated') }}', 'info'); } catch(_) {}
}
} catch(e) { console.warn('Kanban update trigger failed', e); }
}
// BroadcastChannel listener
try {
if ('BroadcastChannel' in window) {
var kanbanChannel = new BroadcastChannel('kanban');
kanbanChannel.onmessage = function(ev){
var msg = ev && ev.data || {};
if (msg && (msg.type === 'columns_updated')) {
triggerKanbanUpdate(msg);
}
};
window._kanbanBroadcastChannel = kanbanChannel;
}
} catch(_) {}
// localStorage fallback
window.addEventListener('storage', function(ev){
try {
if (ev && ev.key === 'kanban_columns_updated' && ev.newValue) {
var data = null;
try { data = JSON.parse(ev.newValue); } catch(e) {}
triggerKanbanUpdate(data || { type: 'columns_updated' });
}
} catch(_) {}
});
} catch(e) {}
})();
</script>
{% block scripts_extra %}{% endblock %}
{% block extra_js %}{% endblock %}
<script>
// Service Worker registration and PWA install UI
(function(){
try {
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/service-worker.js').catch(function(){});
}
var deferredPrompt = null;
var installItem = document.getElementById('installAppMenuItem');
window.addEventListener('beforeinstallprompt', function(e){
try { e.preventDefault(); } catch(_) {}
deferredPrompt = e;
if (installItem) installItem.classList.remove('d-none');
});
if (installItem) {
installItem.addEventListener('click', async function(ev){
ev.preventDefault();
if (!deferredPrompt) return;
try {
deferredPrompt.prompt();
await deferredPrompt.userChoice;
} catch (_) {}
deferredPrompt = null;
installItem.classList.add('d-none');
});
}
window.addEventListener('appinstalled', function(){ try { showToast('{{ _('App installed') }}', 'success'); } catch(_) {} });
} catch(e) {}
})();
</script>
<script>
// Promise-based global confirm helper
(function(){
try {
window.showConfirm = function(message, options){
return new Promise(function(resolve){
try {
var modalEl = document.getElementById('globalConfirmModal');
if (!modalEl) return resolve(confirm(message));
var msgEl = document.getElementById('globalConfirmMessage');
var okBtn = document.getElementById('globalConfirmOk');
if (msgEl) msgEl.textContent = message || '';
var bsModal = bootstrap.Modal.getOrCreateInstance(modalEl);
function cleanup(){
okBtn.removeEventListener('click', onOk);
modalEl.removeEventListener('hidden.bs.modal', onHide);
}
function onOk(){ cleanup(); bsModal.hide(); resolve(true); }
function onHide(){ cleanup(); resolve(false); }
okBtn.addEventListener('click', onOk);
modalEl.addEventListener('hidden.bs.modal', onHide, { once:true });
bsModal.show();
} catch(e) { resolve(confirm(message)); }
});
}
} catch(e) {}
})();
</script>
<!-- Mobile FAB: Log Time -->
{% if current_user.is_authenticated %}
<a href="{{ url_for('timer.manual_entry') }}" class="fab-log-time d-lg-none" aria-label="{{ _('Log time') }}">
<i class="fas fa-plus"></i>
</a>
{% endif %}
<script>
// Compact density toggle
(function(){
try {
const key = 'tt-density';
const saved = localStorage.getItem(key);
if (saved === 'compact') document.documentElement.classList.add('compact');
window.toggleDensity = function(){
const root = document.documentElement;
const isCompact = root.classList.toggle('compact');
localStorage.setItem(key, isCompact ? 'compact' : 'comfortable');
};
} catch (e) {}
})();
</script>
<script>
// CSRF auto-injection for forms and AJAX/fetch + optional token refresh
(function(){
try {
var meta = document.querySelector('meta[name="csrf-token"]');
function getToken(){
return meta ? (meta.getAttribute('content') || '') : '';
}
function setToken(t){
if (meta && typeof t === 'string' && t) meta.setAttribute('content', t);
}
function isPostForm(form){
var m = (form.getAttribute('method') || form.method || '').toString().toUpperCase();
return m === 'POST';
}
function ensureFormHasToken(form, token){
if (!isPostForm(form) || form.hasAttribute('data-no-csrf-auto')) return;
var input = form.querySelector('input[name="csrf_token"]');
if (!input) {
input = document.createElement('input');
input.type = 'hidden';
input.name = 'csrf_token';
form.insertBefore(input, form.firstChild);
}
input.value = token;
}
function updateAllCsrfInputs(token){
// Update existing CSRF inputs
document.querySelectorAll('input[name="csrf_token"]').forEach(function(i){ i.value = token; });
// Ensure all POST forms have a token
Array.prototype.forEach.call(document.forms, function(form){ ensureFormHasToken(form, token); });
}
var initial = getToken();
if (!initial) return;
updateAllCsrfInputs(initial);
// jQuery AJAX: attach header automatically for same-origin, non-GET
if (window.$ && $.ajaxSetup) {
$.ajaxSetup({
beforeSend: function(xhr, settings){
try {
var method = (settings.type || '').toUpperCase();
var url = settings.url || '';
var sameOrigin = url.indexOf('http://') !== 0 && url.indexOf('https://') !== 0 || url.indexOf(location.origin) === 0;
if (sameOrigin && ['GET','HEAD','OPTIONS','TRACE'].indexOf(method) === -1) {
xhr.setRequestHeader('X-CSRFToken', getToken());
}
} catch(e) {}
}
});
}
// fetch(): wrap to add CSRF header automatically for same-origin, non-GET
if (window.fetch) {
var _origFetch = window.fetch;
window.fetch = function(input, init){
try {
var req = new Request(input, init);
var url = new URL(req.url, window.location.origin);
var sameOrigin = url.origin === window.location.origin;
var method = (req.method || '').toUpperCase();
if (sameOrigin && ['GET','HEAD','OPTIONS','TRACE'].indexOf(method) === -1) {
var headers = new Headers(req.headers || {});
if (!headers.has('X-CSRFToken')) headers.set('X-CSRFToken', getToken());
return _origFetch(new Request(req, { headers: headers }));
}
return _origFetch(req);
} catch(e) {
return _origFetch(input, init);
}
};
}
// Periodic CSRF token refresh (avoids expiry on long-lived pages)
var csrfRefreshUrl = "{{ url_for('get_csrf_token') }}";
function refreshCsrfToken(){
try {
if (!csrfRefreshUrl) return;
return fetch(csrfRefreshUrl, { credentials: 'same-origin', cache: 'no-store' })
.then(function(r){ return r.ok ? r.json() : null; })
.then(function(data){
if (data && data.csrf_token) {
setToken(data.csrf_token);
updateAllCsrfInputs(data.csrf_token);
}
})
.catch(function(){});
} catch(e) {}
}
// Refresh when tab becomes visible and on an interval
document.addEventListener('visibilitychange', function(){
if (!document.hidden) refreshCsrfToken();
});
// Refresh every 20 minutes (default token TTL is 60 minutes)
try { setInterval(refreshCsrfToken, 20 * 60 * 1000); } catch(e) {}
} catch(e) {}
})();
</script>
</body>
</html>