diff --git a/.dockerignore b/.dockerignore
new file mode 100644
index 0000000..6aa9de4
--- /dev/null
+++ b/.dockerignore
@@ -0,0 +1,40 @@
+# Git files
+.git
+.gitignore
+
+# Node modules - these are installed within the Docker build context
+node_modules
+
+# Docker specific files (if any, other than Dockerfile itself)
+# .dockerignore (to avoid including itself if context changes)
+docker
+systemd
+
+# Local development environment files
+.env
+.env*.local
+
+# Logs and temporary files
+logs
+*.log
+npm-debug.log*
+yarn-debug.log*
+pnpm-debug.log*
+
+# OS-specific files
+.DS_Store
+Thumbs.db
+
+# IDE configuration
+.idea/
+.vscode/
+*.sublime-workspace
+*.sublime-project
+
+# Build output (if you ever build locally before Docker)
+dist/
+# If your build output is different, change the line above
+
+# Coverage reports
+coverage/
+.nyc_output/
\ No newline at end of file
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..6b4db6c
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,146 @@
+# docker labels
+labels
+# Logs
+logs
+*.log
+npm-debug.log*
+yarn-debug.log*
+yarn-error.log*
+pnpm-debug.log*
+lerna-debug.log*
+
+# Diagnostic reports (https://nodejs.org/api/report.html)
+report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
+
+# Runtime data
+pids
+*.pid
+*.seed
+*.pid.lock
+
+# Directory for instrumented libs generated by jscoverage/JSCover
+lib-cov
+
+# Coverage directory used by tools like istanbul
+coverage
+*.lcov
+
+# nyc test coverage
+.nyc_output
+
+# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
+.grunt
+
+# Bower dependency directory (https://bower.io/)
+bower_components
+
+# node-waf configuration
+.lock-wscript
+
+# Compiled binary addons (https://nodejs.org/api/addons.html)
+build/Release
+
+# Dependency directories
+node_modules/
+jspm_packages/
+
+# Snowpack dependency directory (https://snowpack.dev/)
+web_modules/
+
+# TypeScript cache
+*.tsbuildinfo
+
+# Optional npm cache directory
+.npm
+
+# Optional eslint cache
+.eslintcache
+
+# Microbundle cache
+.rpt2_cache/
+.rts2_cache_cjs/
+.rts2_cache_es/
+.rts2_cache_umd/
+
+# Optional REPL history
+.node_repl_history
+
+# Output of 'npm pack'
+*.tgz
+
+# Yarn Integrity file
+.yarnclean
+
+# dotenv environment variables file
+.env
+.env*.local
+.env.development.local
+.env.test.local
+.env.production.local
+
+# parcel-bundler cache files
+.cache
+.parcel-cache
+
+# Next.js build output
+.next
+out
+
+# Nuxt.js build output
+.nuxt
+dist
+
+# Svelte Sapper build output
+__sapper__
+
+# Gatsby files
+.cache/
+# Comment in the public line in if your project uses Gatsby and not Next.js
+# https://nextjs.org/blog/next-9-1#public-directory-support
+# public
+
+# vuepress build output
+.vuepress/dist
+
+# Serverless directories
+.serverless/
+
+# FuseBox cache
+.fusebox/
+
+# DynamoDB Local files
+.dynamodb/
+
+# TernJS port file
+.tern-port
+
+# Stores VSCode versions used for testing VSCode extensions
+.vscode-test
+
+# Vite local development server cache
+.vite
+
+# Vite build output directory
+/dist
+# If your build output is different, change the line above to /your-build-output-dir
+
+# Mac OS system files
+.DS_Store
+Thumbs.db
+
+# IDE specific
+.idea/
+*.suo
+*.ntvs*
+*.njsproj
+*.sln
+*.sublime-workspace
+*.sublime-project
+
+# Editor directories and files
+.vscode/*
+!.vscode/settings.json
+!.vscode/tasks.json
+!.vscode/launch.json
+!.vscode/extensions.json
+*.code-workspace
\ No newline at end of file
diff --git a/Dockerfile b/Dockerfile
new file mode 100644
index 0000000..36b0b91
--- /dev/null
+++ b/Dockerfile
@@ -0,0 +1,17 @@
+# Stage 1: Build the Vue.js application
+FROM node:24-alpine AS builder
+WORKDIR /app
+COPY package*.json ./
+RUN npm install
+COPY . .
+RUN npm run build
+
+# Stage 2: Serve the application with Nginx
+FROM nginx:stable-alpine
+COPY ./nginx.conf /etc/nginx/conf.d/default.conf
+
+RUN find /usr/share/nginx/html -mindepth 1 -delete
+COPY --from=builder /app/dist /usr/share/nginx/html
+
+EXPOSE 80
+CMD ["nginx", "-g", "daemon off;"]
\ No newline at end of file
diff --git a/README.md b/README.md
index ff454c2..85e7796 100644
--- a/README.md
+++ b/README.md
@@ -1,3 +1,87 @@
-# OrreryTimer
+# Nexus Timer 🕰️✨
+
+Nexus Timer is a dynamic multi-player timer designed for games, workshops, or any activity where turns pass sequentially in a circular fashion. It provides a clear visual focus on the current participant and their immediate successor, ensuring everyone stays engaged and aware of who is next. This document serves as a detailed specification for a Progressive Web App (PWA) prototype aimed at game enthusiasts.
+
+## Core Concept
+
+Nexus Timer visualizes players in a circular sequence. The **Current Player** is prominently displayed in the top half of the screen, and the **Next Player** is in the bottom half. This clear visual pairing indicates the flow of turns, making it perfect for board games, role-playing games, timed presentations, or any scenario needing structured turn management with individual countdowns.
+
+## Target Audience
+
+Game enthusiasts who play turn-based games (board games, tabletop RPGs, card games) and need a visually clear and customizable timer solution.
+
+## Hardware Recommendations (Optional Enhancement)
+
+For an enhanced tactile experience, Nexus Timer supports Smart Buttons based on Bluetooth-connected microcontroller (e.g., XIAO nRF52840) implementing HID (Human Interface Device) protocol.
+
+* **Buttons:** Connect 3 physical buttons, potentially extended (e.g., via 1.5m wires) for easy player access.
+* **Configuration:**
+ * **Player 1's Button:** Single Click: Emulates a key press (e.g., 'a'). Configure this as Player 1's "Pass Turn / My Pause" hotkey in the app.
+ * **Player 2's Button:** Single Click: Emulates a key press (e.g., 'b'). Configure as Player 2's "Pass Turn / My Pause" hotkey.
+ * **Player 3's Button:** Single Click: Emulates a key press (e.g., 'c'). Configure as Player 3's "Pass Turn / My Pause" hotkey.
+ * **If Player 3 is Game Admin:**
+ * **Player 3's Button:** Long Press: Emulates a key press (e.g., 's'). Configure as the "Global Stop/Pause All" hotkey in the app.
+ * **Player 3's Button:** Double Click: Emulates a key press (e.g., 'x'). Configure as the "Global Run All Timers" hotkey in the app.
+
+## Key Features
+
+* **Circular Player Display:**
+ 1. **Normal Mode (Default):** Central focus on the **Current Player** (top) and **Next Player** (bottom).
+ 2. **All Timers Running Mode:** List of players with running timers.
+* **Individual Player Timers:**
+ * Customizable countdown timer (MM:SS) for each player.
+ * Timers continue into **negative time** (e.g., -MM:SS) up to a limit (e.g., -59:59).
+ * Players reaching max negative time are **skipped** until reset or timer edit.
+ * Visual feedback: Pulsating effect for active timers (background for positive, text for negative). Skipped players are visually distinct (e.g., greyed out).
+* **Two Game Modes:**
+ 1. **Normal Mode (Default):**
+ * Only the **Current Player's** timer runs.
+ * Pass the turn via **Swipe Up** on the Next Player's area or the Current Player's "Pass Turn / My Pause" hotkey.
+ * 3-seconds ticking sound when the timer starts to alert players about the "Pass Turn".
+ * Tap Current Player's area or use "Global Stop/Pause All" hotkey to pause/resume their timer without passing the turn.
+ * To pass the turn: **Swipe Up** on the Next Player's area or have the Current Player press their "Pass Turn / My Pause" hotkey. The current timer pauses, the next player becomes Current, and their timer starts.
+ * If the current player's timer is paused, and then the turn is passed (via swipe up or hotkey), the next player should become the current player, but their timer should not automatically start. It should remain paused.
+ 2. **All Timers Running Mode:**
+ * All active player timers run simultaneously.
+ * Enter by clicking "All Timers Mode" (starts all timers).
+ * Continuous ticking sound when active.
+ * Initially, all players are shown in a list with their photo, name and timer value.
+ * Tapping on a player in the list pauses its timer. Any player can use their "Pass Turn / My Pause" hotkey to pause their *own* timer.
+ * Only players with a running timer are shown in the list.
+ * If all players pause their timers, automatically reverts to Normal Mode.
+ * Main button: "Stop All Timers" (pauses all, returns to Normal Mode) or "Start All Timers" (resumes all in this mode). Can also be triggered by "Global Stop/Pause All" hotkey.
+* **Player Management:**
+ * Add, edit, and delete players (2-7 players).
+ * Use device camera (access via browser API) or default avatars for the player's picture.
+ * Set initial timer values per player (Default: 60:00).
+ * Assign unique "Pass Turn / My Pause" hotkeys (single keypresses). E.g.: Use the Player's 1 "single click" action to insert the key.
+ * Assign the "Global Stop/Pause All" hotkey (single keypresses). E.g.: Use the Player's 3 "long press" action to insert the key.
+ * Assign the "Run All Timers" hotkey (single keypresses). E.g.: Use the Player's 3 "double click" action to insert the key.
+ * Re-order players (drag-and-drop planned), reverse, shuffle.
+* **Intuitive Controls:**
+ * **Swipe Up:** (On the Next Player's area). Primary gesture for passing turns (Normal Mode).
+ * **On-Screen Taps:** (On the Current Player's area). For pausing/resuming timers contextually.
+* **Audio Feedback:**
+ * Continuous ticking in "All Timers Running Mode" when active.
+ * Brief 3-second tick when a timer starts in Normal Mode. Cancel the sound when the timer pauses.
+ * Global mute option.
+* **Visuals:**
+ * Designed for mobile phone screens (portrait orientation).
+ * Light/Dark theme options.
+* **Persistence:** Player setups, timer states, and settings are saved locally using browser Local Storage.
+* **Global Reset:** "Reset Game" button restores all timers to initial values and resets game state.
+
+## UI/UX Considerations
+
+* **Minimalist Design:** Focus on clarity and ease of use. Avoid clutter.
+* **Large, Clear Timers:** Timers should be easily readable at a glance.
+* **Color Coding:** Use color to indicate timer state (e.g., green for running, red for negative time, grey for skipped).
+* **Responsive Layout:** The UI should adapt to different (mobile phone) screen sizes.
+* **Touch-Friendly:** Buttons and interactive elements should be large enough for easy tapping.
+
+### For Developer Setup, see [Developer Setup Guide](docs/development.md).
+### For Deployment Setup, see [Deployment Setup Guide](docs/deployment.md).
+### For Architecture Docs, see [Architecture](docs/architecture.md).
+
+
-OrreryTimer is a dynamic multi-player timer designed for games, workshops, or any activity where turns pass sequentially in a circular fashion. It provides a clear visual focus on the current participant, their immediate predecessor and successor, and the direction of play, ensuring everyone stays engaged and aware of the flow.
\ No newline at end of file
diff --git a/assets/favicon-16x16.png b/assets/favicon-16x16.png
new file mode 100644
index 0000000..8d52034
Binary files /dev/null and b/assets/favicon-16x16.png differ
diff --git a/assets/favicon-32x32.png b/assets/favicon-32x32.png
new file mode 100644
index 0000000..ec20525
Binary files /dev/null and b/assets/favicon-32x32.png differ
diff --git a/docker/traefik.labels b/docker/traefik.labels
new file mode 100644
index 0000000..6550fc8
--- /dev/null
+++ b/docker/traefik.labels
@@ -0,0 +1,8 @@
+traefik.enable=true
+traefik.docker.network=traefik
+traefik.http.routers.virt-nexus-timer.rule=Host("nexus-timer.virtonline.eu")
+traefik.http.routers.virt-nexus-timer.service=virt-nexus-timer
+traefik.http.routers.virt-nexus-timer.tls=true
+traefik.http.routers.virt-nexus-timer.tls.certResolver=default
+traefik.http.routers.virt-nexus-timer.entrypoints=web-secure
+traefik.http.services.virt-nexus-timer.loadbalancer.server.port=80
\ No newline at end of file
diff --git a/docs/architecture.md b/docs/architecture.md
new file mode 100644
index 0000000..bb7d7ce
--- /dev/null
+++ b/docs/architecture.md
@@ -0,0 +1,58 @@
+## Tech Stack
+* **HTML5:** For structuring the user interface.
+* **CSS3:** For styling and visual presentation, including animations. Consider a CSS framework like Tailwind CSS for rapid prototyping.
+* **JavaScript:** For application logic, timer functionality, and event handling.
+* **Web Audio API:** For audio feedback (ticking sounds, alerts).
+* **Browser API:** For capturing Players' photo.
+* **Screen Wake Lock API:** For preventing of the screen lock in a PWA.
+* **Local Storage/IndexedDB:** For persistent storage of player data, timer states, and settings.
+* **Service Worker:** Essential for PWA functionality (offline access, push notifications - potential future feature).
+* **Manifest File:** Defines the PWA's metadata (name, icons, theme color).
+* **Web Framework:** Use Vue.js
+* **Tailwind CSS:** Utility-first CSS framework for rapid UI development.
+
+## Data Model (For AI Generation)
+```json
+{
+ "players": [
+ {
+ "id": "1",
+ "name": "Player 1",
+ "avatar": null,
+ "initialTimerSec": 3600,
+ "currentTimerSec": 3600,
+ "hotkey": "a",
+ "isSkipped": false
+ },
+ {
+ "id": "2",
+ "name": "Player 2",
+ "avatar": null,
+ "initialTimerSec": 3600,
+ "currentTimerSec": 3600,
+ "hotkey": "b",
+ "isSkipped": false
+ }
+ ],
+ "globalHotkeyStopPause": "s",
+ "globalHotkeyRunAll": "x",
+ "currentPlayerIndex": 0,
+ "gameMode": "normal", // "normal" or "allTimers"
+ "isMuted": false,
+ "theme": "dark"
+}
+```
+
+## Build-time Information & Service Worker Versioning
+The application incorporates build-time information and a mechanism for service worker updates:
+
+1. **Build Timestamp:**
+ * The build date and time are automatically injected into the application during the Vite build process.
+ * This is configured in `vite.config.js` using Vite's `define` feature, making `import.meta.env.VITE_APP_BUILD_TIME` available in the Vue components.
+ * The timestamp (formatted for the `sk-SK` locale) is displayed on the "About" screen (`src/views/InfoView.vue`).
+
+2. **Service Worker Cache Versioning:**
+ * The `CACHE_VERSION` constant within the service worker (`src/sw.js`) is also dynamically generated during the Vite build.
+ * `vite.config.js` uses the `define` feature to replace a placeholder (`__APP_CACHE_VERSION__`) in `src/sw.js` with a unique version string. This string typically incorporates the application's version from `package.json` and a build timestamp (`Date.now()`) to ensure uniqueness.
+ * The `src/sw.js` file is configured as a separate Rollup entry point in `vite.config.js` so that Vite processes it and performs this replacement, outputting the final `service-worker.js` to the `dist` directory root.
+ * When a new version of the app is deployed with a changed `service-worker.js` (due to this new `CACHE_VERSION`), the browser detects the difference. The updated service worker installs, and upon activation, it clears out old caches associated with previous versions. This mechanism is key to how the PWA updates and provides users with the latest assets. The "Check for Update" feature on the "About" screen manually triggers the browser to check for a new `service-worker.js` file.
\ No newline at end of file
diff --git a/docs/deployment.md b/docs/deployment.md
new file mode 100644
index 0000000..7903c8a
--- /dev/null
+++ b/docs/deployment.md
@@ -0,0 +1,68 @@
+## Deployment Setup
+### On the Server
+Navigate to the service directory on the server
+```bash
+cd /virt
+```
+Clone the repository
+```bash
+git clone --depth 1 https://gitea.virtonline.eu/2HoursProject/nexus-timer.git
+cd nexus-timer
+```
+Build the docker image
+```bash
+docker build -t virt-nexus-timer .
+```
+## Exposing the App Behind Traefik (Reverse Proxy)
+### Review the provided docker labels and systemd service file
+
+Copy the example label file to its destination
+```bash
+cp docker/traefik.labels labels
+```
+View the example service definition:
+```bash
+cat systemd/virt-nexus-timer.service
+```
+### Create the systemd service
+Use the editor to create or overwrite the service:
+```bash
+sudo systemctl edit --force --full virt-nexus-timer.service
+```
+Paste the content from `systemd/virt-nexus-timer.service`, then save and exit.
+
+Enable on system boot and start the service
+```bash
+sudo systemctl enable --now virt-nexus-timer.service
+```
+Check the service status
+```bash
+systemctl status virt-nexus-timer.service
+```
+View real-time logs
+```bash
+journalctl -fu virt-nexus-timer.service
+```
+### Test the web application
+Verify that the application is accessible via HTTPS:
+```bash
+curl https://nexus-timer.virtonline.eu
+```
+Or open it in your browser:
+[https://nexus-timer.virtonline.eu](https://nexus-timer.virtonline.eu)
+
+## Release the update
+### On the Server
+Navigate to the app directory on your server
+```bash
+cd /virt/nexus-timer
+```
+Pull the changes, build the docker image and restart the service
+```bash
+git pull && docker build -t virt-nexus-timer . && systemctl restart virt-nexus-timer.service
+```
+View real-time logs
+```bash
+journalctl -fu virt-nexus-timer.service
+```
+The previously installed PWA should update automatically or offer an upgrade
\ No newline at end of file
diff --git a/docs/development.md b/docs/development.md
new file mode 100644
index 0000000..076b3e6
--- /dev/null
+++ b/docs/development.md
@@ -0,0 +1,22 @@
+## Developer Setup
+Clone the repository
+```bash
+git clone https://gitea.virtonline.eu/2HoursProject/nexus-timer.git
+cd nexus-timer
+```
+Run the live update server locally
+```bash
+npm run dev
+```
+### Modify the app
+Make code changes...
+### Test the PWA locally
+Open it in your browser:
+[http://localhost:8080/](http://localhost:8080/)
+### Commit & Push
+Stage changes, commit and push
+```bash
+git add .
+git commit -m 'My cool feature'
+git push
+```
\ No newline at end of file
diff --git a/index.html b/index.html
new file mode 100644
index 0000000..8be2b52
--- /dev/null
+++ b/index.html
@@ -0,0 +1,30 @@
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/src/assets/default-avatar.png b/src/assets/default-avatar.png
new file mode 100644
index 0000000..6812f6f
Binary files /dev/null and b/src/assets/default-avatar.png differ
diff --git a/src/assets/tailwind.css b/src/assets/tailwind.css
new file mode 100644
index 0000000..d4e13c1
--- /dev/null
+++ b/src/assets/tailwind.css
@@ -0,0 +1,54 @@
+@tailwind base;
+@tailwind components;
+@tailwind utilities;
+
+body {
+ @apply bg-gray-100 dark:bg-gray-900 text-gray-900 dark:text-gray-100 antialiased select-none;
+ overscroll-behavior-y: contain; /* Prevents pull-to-refresh on mobile */
+}
+
+/* Safe area insets for mobile devices (status bar, home indicator) */
+.safe-area-padding {
+ padding-top: env(safe-area-inset-top);
+ /* padding-bottom: env(safe-area-inset-bottom); */
+}
+
+.safe-area-height {
+ height: calc(100dvh - env(safe-area-inset-top));
+ min-height: 0;
+}
+
+/* Basic button styling */
+.btn {
+ @apply px-4 py-2 rounded font-semibold focus:outline-none focus:ring-2 focus:ring-opacity-50;
+}
+.btn-primary {
+ @apply bg-blue-500 hover:bg-blue-600 text-white focus:ring-blue-400;
+}
+.btn-secondary {
+ @apply bg-gray-500 hover:bg-gray-600 text-white focus:ring-gray-400;
+}
+.btn-danger {
+ @apply bg-red-500 hover:bg-red-600 text-white focus:ring-red-400;
+}
+.btn-warning {
+ @apply bg-yellow-500 hover:bg-yellow-600 text-black focus:ring-yellow-400;
+}
+.btn-icon {
+ @apply p-2 rounded-full hover:bg-gray-200 dark:hover:bg-gray-700;
+}
+
+/* Input styling */
+.input-base {
+ @apply mt-1 block w-full px-3 py-2 bg-white dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm;
+}
+
+/* For preventing text selection during swipes/taps */
+.no-select {
+ -webkit-touch-callout: none; /* iOS Safari */
+ -webkit-user-select: none; /* Safari */
+ -khtml-user-select: none; /* Konqueror HTML */
+ -moz-user-select: none; /* Old versions of Firefox */
+ -ms-user-select: none; /* Internet Explorer/Edge */
+ user-select: none; /* Non-prefixed version, currently supported by Chrome, Edge, Opera and Firefox */
+}
\ No newline at end of file
diff --git a/src/components/DefaultAvatarIcon.vue b/src/components/DefaultAvatarIcon.vue
new file mode 100644
index 0000000..a67623e
--- /dev/null
+++ b/src/components/DefaultAvatarIcon.vue
@@ -0,0 +1,9 @@
+
+
+
+
+
\ No newline at end of file
diff --git a/src/components/HotkeyCaptureOverlay.vue b/src/components/HotkeyCaptureOverlay.vue
new file mode 100644
index 0000000..66e920a
--- /dev/null
+++ b/src/components/HotkeyCaptureOverlay.vue
@@ -0,0 +1,79 @@
+
+
+
+
+ Press a Key
+
+
+ Waiting for a single key press to assign as the hotkey.
+
+ (Esc to cancel)
+
+
+ Listening...
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/src/components/PlayerDisplay.vue b/src/components/PlayerDisplay.vue
new file mode 100644
index 0000000..823d519
--- /dev/null
+++ b/src/components/PlayerDisplay.vue
@@ -0,0 +1,145 @@
+
+
+
+
+
+
+
+
+
+
+ {{ player.name }}
+
+
+
SKIPPED
+
+
+
+
\ No newline at end of file
diff --git a/src/components/PlayerForm.vue b/src/components/PlayerForm.vue
new file mode 100644
index 0000000..5a71357
--- /dev/null
+++ b/src/components/PlayerForm.vue
@@ -0,0 +1,226 @@
+
+
+
+
{{ isEditing ? 'Edit Player' : 'Add New Player' }}
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/src/components/PlayerListItem.vue b/src/components/PlayerListItem.vue
new file mode 100644
index 0000000..de4b31b
--- /dev/null
+++ b/src/components/PlayerListItem.vue
@@ -0,0 +1,70 @@
+
+
+
+
+
+
+
{{ player.name }}
+
SKIPPED
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/src/components/TimerDisplay.vue b/src/components/TimerDisplay.vue
new file mode 100644
index 0000000..f705405
--- /dev/null
+++ b/src/components/TimerDisplay.vue
@@ -0,0 +1,27 @@
+
+
+ {{ formattedTime }}
+
+
+
+
\ No newline at end of file
diff --git a/src/main.js b/src/main.js
new file mode 100644
index 0000000..50523cb
--- /dev/null
+++ b/src/main.js
@@ -0,0 +1,26 @@
+// src/main.js
+import { createApp } from 'vue'
+import App from './App.vue'
+import router from './router' // router will be initialized here
+import store from './store' // store will be initialized here
+import './assets/tailwind.css'
+
+const app = createApp(App)
+
+// Dispatch loadState immediately after store is created and before app is mounted
+// and before router is fully used by the app.
+store.dispatch('loadState').then(() => {
+ // Now that the state is loaded (or attempted to be loaded),
+ // we can safely use the router and mount the app.
+ app.use(router)
+ app.use(store) // Using store here is fine, it's already created.
+ app.mount('#app')
+}).catch(error => {
+ console.error("Failed to load initial state for the store:", error);
+ // Fallback: Mount the app even if state loading fails, guards should handle it.
+ // Or display an error message to the user.
+ // For now, let's still try to mount.
+ app.use(router)
+ app.use(store)
+ app.mount('#app')
+});
\ No newline at end of file
diff --git a/src/router/index.js b/src/router/index.js
new file mode 100644
index 0000000..1dd1032
--- /dev/null
+++ b/src/router/index.js
@@ -0,0 +1,59 @@
+import { createRouter, createWebHistory } from 'vue-router';
+import SetupView from '../views/SetupView.vue';
+import GameView from '../views/GameView.vue';
+import InfoView from '../views/InfoView.vue';
+import store from '../store';
+
+const routes = [
+ {
+ path: '/',
+ name: 'Setup',
+ component: SetupView,
+ beforeEnter: (to, from, next) => {
+ // Check if we are navigating FROM the Game view.
+ // If so, the user explicitly clicked the Setup button, so allow it.
+ if (from.name === 'Game') {
+ console.log('Router Guard: Allowing navigation from Game to Setup.');
+ next(); // Allow navigation to Setup
+ return; // Stop further processing of this guard
+ }
+
+ // Original logic for initial load or other navigations TO Setup:
+ if (store.state.players && store.state.players.length >= 2) {
+ // If 2 or more players exist (and not coming from Game), redirect to Game.
+ console.log('Router Guard: Players found, redirecting to Game (not coming from Game).');
+ next({ name: 'Game', replace: true });
+ } else {
+ // Otherwise (fewer than 2 players), allow navigation to the Setup view.
+ console.log('Router Guard: Not enough players, proceeding to Setup.');
+ next();
+ }
+ }
+ },
+ {
+ path: '/game',
+ name: 'Game',
+ component: GameView,
+ beforeEnter: (to, from, next) => {
+ // Keep this guard: prevent direct access to /game without enough players
+ if (!store.state.players || store.state.players.length < 2) {
+ console.log('Router Guard: Attempted to access Game without enough players, redirecting to Setup.');
+ next({ name: 'Setup' });
+ } else {
+ next();
+ }
+ }
+ },
+ {
+ path: '/info',
+ name: 'Info',
+ component: InfoView
+ }
+];
+
+const router = createRouter({
+ history: createWebHistory(import.meta.env.BASE_URL),
+ routes
+});
+
+export default router;
\ No newline at end of file
diff --git a/src/services/AudioService.js b/src/services/AudioService.js
new file mode 100644
index 0000000..ed4ab17
--- /dev/null
+++ b/src/services/AudioService.js
@@ -0,0 +1,133 @@
+let audioContext;
+let tickSoundBuffer; // For short tick
+let passTurnSoundBuffer; // For 3s pass turn alert
+let isMutedGlobally = false;
+let continuousTickInterval = null; // For setInterval based continuous ticking
+let passTurnSoundTimeout = null;
+
+function getAudioContext() {
+ if (!audioContext && (window.AudioContext || window.webkitAudioContext)) {
+ audioContext = new (window.AudioContext || window.webkitAudioContext)();
+ }
+ return audioContext;
+}
+
+function createBeepBuffer(frequency = 440, duration = 0.1, type = 'sine') {
+ const ctx = getAudioContext();
+ if (!ctx) return null;
+ const sampleRate = ctx.sampleRate;
+ const numFrames = duration * sampleRate;
+ const buffer = ctx.createBuffer(1, numFrames, sampleRate);
+ const data = buffer.getChannelData(0);
+ const gain = 0.1; // Reduce gain to make beeps softer
+
+ for (let i = 0; i < numFrames; i++) {
+ // Simple fade out
+ const currentGain = gain * (1 - (i / numFrames));
+ if (type === 'square') {
+ data[i] = (Math.sin(2 * Math.PI * frequency * (i / sampleRate)) >= 0 ? 1 : -1) * currentGain;
+ } else { // sine
+ data[i] = Math.sin(2 * Math.PI * frequency * (i / sampleRate)) * currentGain;
+ }
+ }
+ return buffer;
+}
+
+async function initSounds() {
+ const ctx = getAudioContext();
+ if (!ctx) return;
+ // Tick sound (shorter, slightly different pitch)
+ if (!tickSoundBuffer) {
+ // Using a square wave for a more 'digital' tick, short duration
+ tickSoundBuffer = createBeepBuffer(1000, 0.03, 'square');
+ }
+ // Pass turn alert sound (3 beeps)
+ if (!passTurnSoundBuffer) {
+ passTurnSoundBuffer = createBeepBuffer(660, 0.08, 'sine');
+ }
+}
+initSounds();
+
+function playSoundBuffer(buffer) {
+ if (isMutedGlobally || !buffer || !audioContext || audioContext.state === 'suspended') return;
+ const source = audioContext.createBufferSource();
+ source.buffer = buffer;
+ source.connect(audioContext.destination);
+ source.start();
+}
+
+export const AudioService = {
+ setMuted(muted) {
+ isMutedGlobally = muted;
+ if (muted) {
+ this.stopContinuousTick();
+ this.cancelPassTurnSound();
+ }
+ },
+
+ // This is the single, short tick sound for "All Timers Running" mode.
+ _playSingleTick() {
+ playSoundBuffer(tickSoundBuffer);
+ },
+
+ playPassTurnAlert() {
+ if (isMutedGlobally || !audioContext || audioContext.state === 'suspended') return;
+ this.cancelPassTurnSound();
+
+ let count = 0;
+ const playAndSchedule = () => {
+ if (count < 3 && !isMutedGlobally && audioContext.state !== 'suspended') {
+ playSoundBuffer(passTurnSoundBuffer);
+ count++;
+ passTurnSoundTimeout = setTimeout(playAndSchedule, 1000); // Beep every second for 3s
+ } else {
+ passTurnSoundTimeout = null;
+ }
+ };
+ playAndSchedule();
+ },
+
+ cancelPassTurnSound() {
+ if (passTurnSoundTimeout) {
+ clearTimeout(passTurnSoundTimeout);
+ passTurnSoundTimeout = null;
+ }
+ },
+
+ startContinuousTick() {
+ this.stopContinuousTick(); // Clear any existing interval
+ if (isMutedGlobally || !audioContext || audioContext.state === 'suspended') return;
+
+ // Play immediately once, then set interval
+ this._playSingleTick();
+ continuousTickInterval = setInterval(() => {
+ if (!isMutedGlobally && audioContext.state !== 'suspended') {
+ this._playSingleTick();
+ } else {
+ this.stopContinuousTick(); // Stop if muted or context suspended during interval
+ }
+ }, 1000); // Tick every second
+ },
+
+ stopContinuousTick() {
+ if (continuousTickInterval) {
+ clearInterval(continuousTickInterval);
+ continuousTickInterval = null;
+ }
+ // Ensure no rogue oscillators are playing.
+ // If an oscillator was ever used directly and not disconnected, it could persist.
+ // The current implementation relies on BufferSource which stops automatically.
+ },
+
+ resumeContext() {
+ const ctx = getAudioContext();
+ if (ctx && ctx.state === 'suspended') {
+ ctx.resume().then(() => {
+ console.log("AudioContext resumed successfully.");
+ initSounds(); // Re-initialize sounds if context was suspended for long
+ }).catch(e => console.error("Error resuming AudioContext:", e));
+ } else if (ctx && !tickSoundBuffer) { // If context was fine but sounds not loaded
+ initSounds();
+ }
+ }
+};
\ No newline at end of file
diff --git a/src/services/CameraService.js b/src/services/CameraService.js
new file mode 100644
index 0000000..b15a32a
--- /dev/null
+++ b/src/services/CameraService.js
@@ -0,0 +1,69 @@
+export const CameraService = {
+ async getPhoto() {
+ return new Promise(async (resolve, reject) => {
+ if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
+ reject(new Error('Camera API not available.'));
+ return;
+ }
+
+ try {
+ const stream = await navigator.mediaDevices.getUserMedia({ video: { facingMode: "user" }, audio: false });
+
+ // Create a modal or an overlay to show the video stream and a capture button
+ const videoElement = document.createElement('video');
+ videoElement.srcObject = stream;
+ videoElement.setAttribute('playsinline', ''); // Required for iOS
+ videoElement.style.cssText = "position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%); max-width: 90%; max-height: 70vh; z-index: 1001; border-radius: 8px; box-shadow: 0 4px 12px rgba(0,0,0,0.2);";
+
+ const captureButton = document.createElement('button');
+ captureButton.textContent = 'Capture';
+ captureButton.style.cssText = "position: fixed; bottom: 10%; left: 50%; transform: translateX(-50%); z-index: 1002; padding: 12px 24px; background-color: #3b82f6; color: white; border: none; border-radius: 8px; font-size: 16px; cursor: pointer;";
+
+ const closeButton = document.createElement('button');
+ closeButton.textContent = 'Cancel';
+ closeButton.style.cssText = "position: fixed; top: 10px; right: 10px; z-index: 1002; padding: 8px 12px; background-color: #ef4444; color: white; border: none; border-radius: 8px; font-size: 14px; cursor: pointer;";
+
+
+ const overlay = document.createElement('div');
+ overlay.style.cssText = "position: fixed; top: 0; left: 0; width: 100%; height: 100%; background-color: rgba(0,0,0,0.7); z-index: 1000;";
+
+ document.body.appendChild(overlay);
+ document.body.appendChild(videoElement);
+ document.body.appendChild(captureButton);
+ document.body.appendChild(closeButton);
+
+ videoElement.onloadedmetadata = () => {
+ videoElement.play();
+ };
+
+ const cleanup = () => {
+ stream.getTracks().forEach(track => track.stop());
+ document.body.removeChild(videoElement);
+ document.body.removeChild(captureButton);
+ document.body.removeChild(closeButton);
+ document.body.removeChild(overlay);
+ };
+
+ captureButton.onclick = () => {
+ const canvas = document.createElement('canvas');
+ canvas.width = videoElement.videoWidth;
+ canvas.height = videoElement.videoHeight;
+ const context = canvas.getContext('2d');
+ context.drawImage(videoElement, 0, 0, canvas.width, canvas.height);
+ const dataUrl = canvas.toDataURL('image/png');
+ cleanup();
+ resolve(dataUrl);
+ };
+
+ closeButton.onclick = () => {
+ cleanup();
+ reject(new Error('User cancelled photo capture.'));
+ };
+
+ } catch (err) {
+ console.error("Error accessing camera: ", err);
+ reject(err);
+ }
+ });
+ }
+ };
\ No newline at end of file
diff --git a/src/services/StorageService.js b/src/services/StorageService.js
new file mode 100644
index 0000000..7dbf34d
--- /dev/null
+++ b/src/services/StorageService.js
@@ -0,0 +1,23 @@
+const STORAGE_KEY = 'nexusTimerState';
+
+export const StorageService = {
+ getState() {
+ const savedState = localStorage.getItem(STORAGE_KEY);
+ if (savedState) {
+ try {
+ return JSON.parse(savedState);
+ } catch (e) {
+ console.error("Error parsing saved state from localStorage", e);
+ localStorage.removeItem(STORAGE_KEY); // Clear corrupted data
+ return null;
+ }
+ }
+ return null;
+ },
+ saveState(state) {
+ localStorage.setItem(STORAGE_KEY, JSON.stringify(state));
+ },
+ clearState() {
+ localStorage.removeItem(STORAGE_KEY);
+ }
+};
\ No newline at end of file
diff --git a/src/services/WakeLockService.js b/src/services/WakeLockService.js
new file mode 100644
index 0000000..b66d8c4
--- /dev/null
+++ b/src/services/WakeLockService.js
@@ -0,0 +1,65 @@
+let wakeLock = null;
+let wakeLockActive = false;
+
+const requestWakeLock = async () => {
+ if ('wakeLock' in navigator && !wakeLockActive) {
+ try {
+ wakeLock = await navigator.wakeLock.request('screen');
+ wakeLockActive = true;
+ console.log('Screen Wake Lock activated.');
+
+ wakeLock.addEventListener('release', () => {
+ console.log('Screen Wake Lock was released.');
+ wakeLockActive = false;
+ wakeLock = null; // Clear the reference
+ // Optionally, re-request if it was released unexpectedly and should be active
+ // For now, we'll let it be re-requested manually by the app logic
+ });
+ } catch (err) {
+ console.error(`Failed to acquire Screen Wake Lock: ${err.name}, ${err.message}`);
+ wakeLock = null;
+ wakeLockActive = false;
+ }
+ } else {
+ console.warn('Screen Wake Lock API not supported or already active.');
+ }
+};
+
+const releaseWakeLock = async () => {
+ if (wakeLock && wakeLockActive) {
+ try {
+ await wakeLock.release();
+ // The 'release' event listener on wakeLock itself will set wakeLockActive = false and wakeLock = null
+ } catch (err) {
+ console.error(`Failed to release Screen Wake Lock: ${err.name}, ${err.message}`);
+ // Even if release fails, mark as inactive to allow re-request
+ wakeLock = null;
+ wakeLockActive = false;
+ }
+ } else {
+ // console.log('No active Screen Wake Lock to release or already released.');
+ }
+};
+
+// Handle visibility changes to re-acquire lock if necessary
+const handleVisibilityChange = () => {
+ if (wakeLock !== null && document.visibilityState === 'visible') {
+ // If we had a wake lock and the page became visible again,
+ // it might have been released by the browser. Try to re-acquire.
+ // This behavior is usually handled automatically by the browser with the 'release' event
+ // but can be a fallback. For now, we rely on manual re-request.
+ // console.log('Page visible, checking wake lock status.');
+ } else if (document.visibilityState === 'hidden' && wakeLockActive) {
+ // The browser usually releases the wake lock when tab is hidden.
+ // Our 'release' event listener should handle this.
+ }
+};
+
+document.addEventListener('visibilitychange', handleVisibilityChange);
+// document.addEventListener('fullscreenchange', handleVisibilityChange); // Also useful for fullscreen
+
+export const WakeLockService = {
+ request: requestWakeLock,
+ release: releaseWakeLock,
+ isActive: () => wakeLockActive,
+};
\ No newline at end of file
diff --git a/src/store/index.js b/src/store/index.js
new file mode 100644
index 0000000..f5715ac
--- /dev/null
+++ b/src/store/index.js
@@ -0,0 +1,460 @@
+import { createStore } from 'vuex';
+import { StorageService } from '../services/StorageService';
+import { parseTime, formatTime } from '../utils/timeFormatter';
+
+const MAX_NEGATIVE_SECONDS = -(59 * 60 + 59); // -59:59
+const DEFAULT_AVATAR_MARKER = null; // Ensure this is defined
+
+// Define predefined players
+const predefinedPlayers = [
+ {
+ id: 'predefined-1', // Unique ID for predefined player 1
+ name: 'Player 1',
+ avatar: DEFAULT_AVATAR_MARKER, // Or a specific avatar path if you have one
+ initialTimerSec: 60 * 60, // 60:00
+ currentTimerSec: 60 * 60,
+ hotkey: '1', // Hotkey '1'
+ isSkipped: false,
+ isTimerRunning: false,
+ },
+ {
+ id: 'predefined-2', // Unique ID for predefined player 2
+ name: 'Player 2',
+ avatar: DEFAULT_AVATAR_MARKER, // Or a specific avatar path
+ initialTimerSec: 60 * 60, // 60:00
+ currentTimerSec: 60 * 60,
+ hotkey: '2', // Hotkey '2'
+ isSkipped: false,
+ isTimerRunning: false,
+ }
+];
+
+const initialState = {
+ players: JSON.parse(JSON.stringify(predefinedPlayers)), // Start with predefined players (deep copy)
+ globalHotkeyStopPause: null,
+ globalHotkeyRunAll: null,
+ currentPlayerIndex: 0,
+ gameMode: 'normal',
+ isMuted: false,
+ theme: 'dark',
+ gameRunning: false,
+};
+
+export default createStore({
+ state: () => { // This function already loads from storage ONCE during store creation
+ const persistedState = StorageService.getState();
+ if (persistedState) {
+ let playersToUse = persistedState.players;
+
+ if (!playersToUse || (playersToUse.length === 0 && !persistedState.hasOwnProperty('players'))) {
+ playersToUse = JSON.parse(JSON.stringify(predefinedPlayers));
+ } else if (persistedState.hasOwnProperty('players') && playersToUse.length === 0) {
+ playersToUse = [];
+ }
+
+ playersToUse = playersToUse.map(p => ({
+ ...p,
+ id: p.id || Date.now().toString() + Math.random(),
+ avatar: p.avatar === undefined ? DEFAULT_AVATAR_MARKER : p.avatar,
+ initialTimerSec: typeof p.initialTimerSec === 'number' ? p.initialTimerSec : parseTime(p.initialTimer || "60:00"),
+ currentTimerSec: typeof p.currentTimerSec === 'number' ? p.currentTimerSec : (typeof p.initialTimerSec === 'number' ? p.initialTimerSec : parseTime(p.currentTimer || p.initialTimer || "60:00")),
+ isSkipped: p.isSkipped || false,
+ isTimerRunning: false,
+ hotkey: p.hotkey || null,
+ }));
+
+ return {
+ ...initialState,
+ ...persistedState,
+ players: playersToUse,
+ gameRunning: false,
+ currentPlayerIndex: persistedState.currentPlayerIndex !== undefined && persistedState.currentPlayerIndex < playersToUse.length ? persistedState.currentPlayerIndex : 0,
+ };
+ }
+ return JSON.parse(JSON.stringify(initialState));
+ },
+ mutations: {
+ SET_PLAYERS(state, players) {
+ state.players = players.map(p => ({
+ ...p,
+ id: p.id || Date.now().toString() + Math.random(),
+ avatar: p.avatar || DEFAULT_AVATAR_MARKER,
+ initialTimerSec: typeof p.initialTimerSec === 'number' ? p.initialTimerSec : parseTime(p.initialTimer || "60:00"),
+ currentTimerSec: typeof p.currentTimerSec === 'number' ? p.currentTimerSec : (typeof p.initialTimerSec === 'number' ? p.initialTimerSec : parseTime(p.currentTimer || p.initialTimer || "60:00")),
+ isSkipped: p.isSkipped || false,
+ isTimerRunning: p.isTimerRunning || false, // Retain running state if explicitly set
+ hotkey: p.hotkey || null,
+ }));
+ },
+ ADD_PLAYER(state, player) {
+ const newPlayer = {
+ id: Date.now().toString() + Math.random(), // More robust unique ID
+ name: player.name || `Player ${state.players.length + 1}`,
+ avatar: player.avatar || DEFAULT_AVATAR_MARKER,
+ initialTimerSec: player.initialTimerSec || 3600,
+ currentTimerSec: player.initialTimerSec || 3600,
+ hotkey: player.hotkey || null,
+ isSkipped: false,
+ isTimerRunning: false,
+ };
+ if (state.players.length < 99) {
+ state.players.push(newPlayer);
+ } else {
+ console.warn("Maximum player limit (99) reached.");
+ alert("Maximum player limit (99) reached.");
+ }
+ },
+ UPDATE_PLAYER(state, updatedPlayer) {
+ const index = state.players.findIndex(p => p.id === updatedPlayer.id);
+ if (index !== -1) {
+ state.players[index] = { ...state.players[index], ...updatedPlayer };
+ }
+ },
+ DELETE_PLAYER(state, playerId) {
+ state.players = state.players.filter(p => p.id !== playerId);
+ if (state.currentPlayerIndex >= state.players.length && state.players.length > 0) {
+ state.currentPlayerIndex = state.players.length - 1;
+ } else if (state.players.length === 0) {
+ state.currentPlayerIndex = 0;
+ }
+ },
+ REORDER_PLAYERS(state, players) {
+ state.players = players;
+ },
+ SHUFFLE_PLAYERS(state) {
+ for (let i = state.players.length - 1; i > 0; i--) {
+ const j = Math.floor(Math.random() * (i + 1));
+ [state.players[i], state.players[j]] = [state.players[j], state.players[i]];
+ }
+ },
+ REVERSE_PLAYERS(state) {
+ state.players.reverse();
+ },
+ SET_CURRENT_PLAYER_INDEX(state, index) {
+ state.currentPlayerIndex = index;
+ },
+ SET_GAME_MODE(state, mode) {
+ state.gameMode = mode;
+ },
+ SET_IS_MUTED(state, muted) {
+ state.isMuted = muted;
+ },
+ TOGGLE_THEME(state) {
+ state.theme = state.theme === 'light' ? 'dark' : 'light';
+ },
+ SET_GLOBAL_HOTKEY_STOP_PAUSE(state, key) {
+ state.globalHotkeyStopPause = key;
+ },
+ SET_GLOBAL_HOTKEY_RUN_ALL(state, key) {
+ state.globalHotkeyRunAll = key;
+ },
+ SET_THEME(state, theme) {
+ state.theme = theme;
+ },
+ DECREMENT_TIMER(state, { playerIndex }) {
+ const player = state.players[playerIndex];
+ if (player && player.isTimerRunning && !player.isSkipped) {
+ player.currentTimerSec--;
+ if (player.currentTimerSec < MAX_NEGATIVE_SECONDS) {
+ player.currentTimerSec = MAX_NEGATIVE_SECONDS;
+ player.isSkipped = true; // Auto-skip if max negative time reached
+ player.isTimerRunning = false;
+ }
+ }
+ },
+ RESET_PLAYER_TIMER(state, playerIndex) {
+ if (state.players[playerIndex]) {
+ state.players[playerIndex].currentTimerSec = state.players[playerIndex].initialTimerSec;
+ state.players[playerIndex].isSkipped = false;
+ state.players[playerIndex].isTimerRunning = false;
+ }
+ },
+ RESET_ALL_TIMERS(state) {
+ // When resetting, decide if you want to go back to *only* predefined players
+ // or reset existing players' timers. The current spec "restores all timers to initial values"
+ // implies resetting existing players. If it meant reverting to the initial player set,
+ // this logic would need to change to:
+ // state.players = JSON.parse(JSON.stringify(predefinedPlayers));
+ // For now, sticking to resetting current players' timers:
+ state.players.forEach(player => {
+ player.currentTimerSec = player.initialTimerSec;
+ player.isSkipped = false;
+ player.isTimerRunning = false;
+ });
+ state.currentPlayerIndex = 0;
+ state.gameMode = 'normal';
+ state.gameRunning = false;
+ },
+ START_PLAYER_TIMER(state, playerIndex) {
+ if(state.players[playerIndex] && !state.players[playerIndex].isSkipped) {
+ state.players[playerIndex].isTimerRunning = true;
+ state.gameRunning = true;
+ }
+ },
+ PAUSE_PLAYER_TIMER(state, playerIndex) {
+ if(state.players[playerIndex]) {
+ state.players[playerIndex].isTimerRunning = false;
+ }
+ if (!state.players.some(p => p.isTimerRunning)) {
+ state.gameRunning = false;
+ }
+ },
+ PAUSE_ALL_TIMERS(state) {
+ state.players.forEach(p => p.isTimerRunning = false);
+ state.gameRunning = false;
+ },
+ SET_GAME_RUNNING(state, isRunning) {
+ state.gameRunning = isRunning;
+ },
+ },
+ actions: {
+ loadState({ commit, state }) {
+ // The state initializer already did the main loading from localStorage.
+ // This action can be used for any *additional* setup after initial hydration
+ // or to re-apply certain defaults if needed.
+ // For now, it's mainly a confirmation that persisted state is used.
+
+ // Example: ensure theme is applied if it was loaded
+ // This is already handled by App.vue's watcher, but could be centralized.
+ // if (state.theme === 'dark') {
+ // document.documentElement.classList.add('dark');
+ // } else {
+ // document.documentElement.classList.remove('dark');
+ // }
+ console.log("Store state loaded/initialized.");
+ // It's good practice for actions to return a Promise if they are async
+ // or if other parts of the app expect to chain .then()
+ return Promise.resolve(); // Resolve immediately
+ },
+ saveState({ state }) {
+ StorageService.saveState({
+ players: state.players.map(p => ({
+ id: p.id,
+ name: p.name,
+ avatar: p.avatar,
+ initialTimerSec: p.initialTimerSec,
+ currentTimerSec: p.currentTimerSec,
+ hotkey: p.hotkey,
+ isSkipped: p.isSkipped,
+ })),
+ globalHotkeyStopPause: state.globalHotkeyStopPause,
+ globalHotkeyRunAll: state.globalHotkeyRunAll,
+ currentPlayerIndex: state.currentPlayerIndex,
+ gameMode: state.gameMode,
+ isMuted: state.isMuted,
+ theme: state.theme,
+ });
+ },
+ addPlayer({ commit, dispatch }, player) {
+ commit('ADD_PLAYER', player);
+ dispatch('saveState');
+ },
+ updatePlayer({ commit, dispatch }, player) {
+ commit('UPDATE_PLAYER', player);
+ dispatch('saveState');
+ },
+ deletePlayer({ commit, dispatch }, playerId) {
+ commit('DELETE_PLAYER', playerId);
+ dispatch('saveState');
+ },
+ reorderPlayers({commit, dispatch}, players) {
+ commit('REORDER_PLAYERS', players);
+ dispatch('saveState');
+ },
+ shufflePlayers({commit, dispatch}) {
+ commit('SHUFFLE_PLAYERS');
+ dispatch('saveState');
+ },
+ reversePlayers({commit, dispatch}) {
+ commit('REVERSE_PLAYERS');
+ dispatch('saveState');
+ },
+ toggleTheme({ commit, dispatch }) {
+ commit('TOGGLE_THEME');
+ dispatch('saveState');
+ },
+ setGlobalHotkey({ commit, dispatch }, key) {
+ commit('SET_GLOBAL_HOTKEY_STOP_PAUSE', key);
+ dispatch('saveState');
+ },
+ setMuted({ commit, dispatch }, muted) {
+ commit('SET_IS_MUTED', muted);
+ dispatch('saveState');
+ },
+ resetGame({ commit, dispatch }) { // This is for resetting timers during a game session
+ commit('RESET_ALL_TIMERS');
+ dispatch('saveState');
+ },
+ setGlobalHotkeyStopPause({ commit, dispatch }, key) { // <-- New action
+ commit('SET_GLOBAL_HOTKEY_STOP_PAUSE', key);
+ dispatch('saveState');
+ },
+ setGlobalHotkeyRunAll({ commit, dispatch }, key) { // <-- New action
+ commit('SET_GLOBAL_HOTKEY_RUN_ALL', key);
+ dispatch('saveState');
+ },
+ fullResetApp({ commit, dispatch, state: currentGlobalState }) {
+ StorageService.clearState();
+ const freshInitialState = JSON.parse(JSON.stringify(initialState));
+
+ commit('SET_PLAYERS', freshInitialState.players);
+ commit('SET_CURRENT_PLAYER_INDEX', freshInitialState.currentPlayerIndex);
+ commit('SET_GAME_MODE', freshInitialState.gameMode);
+ commit('SET_IS_MUTED', freshInitialState.isMuted);
+ commit('SET_GLOBAL_HOTKEY_STOP_PAUSE', freshInitialState.globalHotkeyStopPause);
+ commit('SET_GLOBAL_HOTKEY_RUN_ALL', freshInitialState.globalHotkeyRunAll);
+
+ if (currentGlobalState.theme !== freshInitialState.theme) {
+ commit('SET_THEME', freshInitialState.theme);
+ }
+ commit('SET_GAME_RUNNING', false);
+ dispatch('saveState');
+ },
+ tick({ commit, state }) {
+ if (state.gameMode === 'normal') {
+ if (state.players[state.currentPlayerIndex]?.isTimerRunning) {
+ commit('DECREMENT_TIMER', { playerIndex: state.currentPlayerIndex });
+ }
+ } else if (state.gameMode === 'allTimers') {
+ state.players.forEach((player, index) => {
+ if (player.isTimerRunning) {
+ commit('DECREMENT_TIMER', { playerIndex: index });
+ }
+ });
+ }
+ },
+ passTurn({ commit, state, dispatch }) {
+ const numPlayers = state.players.length;
+ if (numPlayers === 0) return;
+
+ const currentIdx = state.currentPlayerIndex;
+ const currentPlayerTimerWasRunning = state.players[currentIdx]?.isTimerRunning;
+
+ commit('PAUSE_PLAYER_TIMER', currentIdx);
+
+ let nextPlayerIndex = (currentIdx + 1) % numPlayers;
+ let skippedCount = 0;
+ while(state.players[nextPlayerIndex]?.isSkipped && skippedCount < numPlayers) {
+ nextPlayerIndex = (nextPlayerIndex + 1) % numPlayers;
+ skippedCount++;
+ }
+
+ if (skippedCount === numPlayers) {
+ commit('PAUSE_ALL_TIMERS');
+ dispatch('saveState');
+ return;
+ }
+
+ commit('SET_CURRENT_PLAYER_INDEX', nextPlayerIndex);
+
+ if (currentPlayerTimerWasRunning && !state.players[nextPlayerIndex].isSkipped) {
+ commit('START_PLAYER_TIMER', nextPlayerIndex);
+ } else {
+ if (state.players[nextPlayerIndex] && !state.players[nextPlayerIndex].isSkipped) {
+ commit('PAUSE_PLAYER_TIMER', nextPlayerIndex);
+ }
+ }
+
+ dispatch('saveState');
+ },
+ toggleCurrentPlayerTimerNormalMode({ commit, state, dispatch }) {
+ const player = state.players[state.currentPlayerIndex];
+ if (!player) return;
+
+ if (player.isTimerRunning) {
+ commit('PAUSE_PLAYER_TIMER', state.currentPlayerIndex);
+ } else if (!player.isSkipped) {
+ commit('START_PLAYER_TIMER', state.currentPlayerIndex);
+ }
+ dispatch('saveState');
+ },
+ togglePlayerTimerAllTimersMode({ commit, state, dispatch }, playerIndex) {
+ const player = state.players[playerIndex];
+ if (!player) return;
+
+ if (player.isTimerRunning) {
+ commit('PAUSE_PLAYER_TIMER', playerIndex);
+ } else if (!player.isSkipped) {
+ commit('START_PLAYER_TIMER', playerIndex);
+ }
+
+ const anyTimerRunning = state.players.some(p => p.isTimerRunning && !p.isSkipped);
+ if (!anyTimerRunning && state.players.length > 0 && state.gameMode === 'allTimers') {
+ // This auto-revert logic is now in GameView.vue watcher for better control over timing
+ }
+ dispatch('saveState');
+ },
+ globalStopPauseAll({ commit, state, dispatch }) {
+ if (state.gameMode === 'normal') {
+ dispatch('toggleCurrentPlayerTimerNormalMode');
+ } else {
+ const anyTimerRunning = state.players.some(p => p.isTimerRunning && !p.isSkipped);
+ if (anyTimerRunning) {
+ commit('PAUSE_ALL_TIMERS');
+ } else {
+ state.players.forEach((player, index) => {
+ if (!player.isSkipped) {
+ commit('START_PLAYER_TIMER', index);
+ }
+ });
+ }
+ }
+ dispatch('saveState');
+ },
+ switchToAllTimersMode({ commit, state, dispatch }) {
+ commit('SET_GAME_MODE', 'allTimers');
+ let anyStarted = false;
+ state.players.forEach((player, index) => {
+ if (!player.isSkipped) {
+ commit('START_PLAYER_TIMER', index);
+ anyStarted = true;
+ }
+ });
+ if(anyStarted) commit('SET_GAME_RUNNING', true);
+ else commit('SET_GAME_RUNNING', false);
+ dispatch('saveState');
+ },
+ switchToNormalMode({commit, state, dispatch}) {
+ commit('PAUSE_ALL_TIMERS');
+ commit('SET_GAME_MODE', 'normal');
+ // Determine current player for normal mode, respecting skips
+ let currentIdx = state.currentPlayerIndex;
+ let skippedCount = 0;
+ while(state.players[currentIdx]?.isSkipped && skippedCount < state.players.length) {
+ currentIdx = (currentIdx + 1) % state.players.length;
+ skippedCount++;
+ }
+ if (skippedCount < state.players.length) {
+ commit('SET_CURRENT_PLAYER_INDEX', currentIdx);
+ // Timer for this player should remain paused as per PAUSE_ALL_TIMERS
+ } else {
+ // All players skipped, game is effectively paused.
+ commit('SET_GAME_RUNNING', false);
+ }
+ dispatch('saveState');
+ }
+ },
+ getters: {
+ players: state => state.players,
+ currentPlayer: state => state.players[state.currentPlayerIndex],
+ nextPlayer: state => {
+ if (!state.players || state.players.length < 1) return null;
+ let nextIndex = (state.currentPlayerIndex + 1) % state.players.length;
+ let count = 0;
+ while(state.players[nextIndex]?.isSkipped && count < state.players.length) {
+ nextIndex = (nextIndex + 1) % state.players.length;
+ count++;
+ }
+ return state.players[nextIndex];
+ },
+ getPlayerById: (state) => (id) => state.players.find(p => p.id === id),
+ gameMode: state => state.gameMode,
+ isMuted: state => state.isMuted,
+ theme: state => state.theme,
+ globalHotkeyStopPause: state => state.globalHotkeyStopPause,
+ globalHotkeyRunAll: state => state.globalHotkeyRunAll,
+ totalPlayers: state => state.players.length,
+ gameRunning: state => state.gameRunning,
+ maxNegativeTimeReached: () => MAX_NEGATIVE_SECONDS,
+ }
+});
\ No newline at end of file
diff --git a/src/sw.js b/src/sw.js
new file mode 100644
index 0000000..0cc7aac
--- /dev/null
+++ b/src/sw.js
@@ -0,0 +1,150 @@
+// This global constant __APP_CACHE_VERSION__ will be replaced by Vite
+// during the build process due to the `define` config in vite.config.js.
+const CACHE_VERSION = typeof __APP_CACHE_VERSION__ !== 'undefined'
+ ? __APP_CACHE_VERSION__
+ : 'nexus-timer-cache-fallback-dev-vManual'; // Fallback for dev or if define fails
+
+const APP_SHELL_URLS = [
+ // Note: '/' (index.html) is handled by NetworkFirst strategy, no need to precache explicitly here.
+ '/manifest.json', // Will be served from public, copied to dist root
+ '/favicon.ico', // Will be served from public, copied to dist root
+ // Icons from public/icons, will be copied to dist/icons
+ '/icons/icon-192x192.png',
+ '/icons/icon-512x512.png',
+ '/icons/maskable-icon-192x192.png',
+ '/icons/maskable-icon-512x512.png',
+ '/icons/shortcut-setup-96x96.png',
+ '/icons/shortcut-info-96x96.png',
+ // Any other critical static assets from the public folder that should be part of the app shell
+];
+
+self.addEventListener('install', event => {
+ console.log(`[SW ${CACHE_VERSION}] Install`);
+ event.waitUntil(
+ caches.open(CACHE_VERSION)
+ .then(cache => {
+ console.log(`[SW ${CACHE_VERSION}] Caching app shell essentials`);
+ return cache.addAll(APP_SHELL_URLS);
+ })
+ .then(() => {
+ console.log(`[SW ${CACHE_VERSION}] Skip waiting on install.`);
+ return self.skipWaiting();
+ })
+ );
+});
+
+self.addEventListener('activate', event => {
+ console.log(`[SW ${CACHE_VERSION}] Activate`);
+ event.waitUntil(
+ caches.keys().then(cacheNames => {
+ return Promise.all(
+ cacheNames.map(cacheName => {
+ if (cacheName !== CACHE_VERSION) {
+ console.log(`[SW ${CACHE_VERSION}] Deleting old cache: ${cacheName}`);
+ return caches.delete(cacheName);
+ }
+ })
+ );
+ }).then(() => {
+ console.log(`[SW ${CACHE_VERSION}] Clients claimed.`);
+ return self.clients.claim();
+ })
+ );
+});
+
+self.addEventListener('fetch', event => {
+ const { request } = event;
+ const url = new URL(request.url);
+
+ if (request.method !== 'GET' || !url.protocol.startsWith('http')) {
+ // console.log(`[SW ${CACHE_VERSION}] Ignoring non-GET or non-http(s) request: ${request.url}`);
+ return;
+ }
+
+ // Strategy 1: Network First for HTML (navigations or direct / request)
+ if (request.mode === 'navigate' || (request.destination === 'document' || url.pathname === '/')) {
+ // console.log(`[SW ${CACHE_VERSION}] NetworkFirst for: ${request.url}`);
+ event.respondWith(
+ fetch(request)
+ .then(response => {
+ if (response.ok) {
+ const responseClone = response.clone();
+ caches.open(CACHE_VERSION).then(cache => cache.put(request, responseClone));
+ }
+ return response;
+ })
+ .catch(async () => {
+ // console.warn(`[SW ${CACHE_VERSION}] Network fetch failed for ${request.url}, trying cache.`);
+ const cachedResponse = await caches.match(request);
+ if (cachedResponse) return cachedResponse;
+ // Fallback to root /index.html from cache if specific page not found offline
+ const rootCache = await caches.match('/');
+ if (rootCache) return rootCache;
+ // console.error(`[SW ${CACHE_VERSION}] Network and cache miss for navigation: ${request.url}`);
+ return new Response('Network error: You are offline and this page is not cached.', {
+ status: 404,
+ statusText: 'Not Found',
+ headers: { 'Content-Type': 'text/html' } // Important for SPA offline fallback
+ });
+ })
+ );
+ return;
+ }
+
+ // Strategy 2: Stale-While-Revalidate for assets (CSS, JS, images, fonts)
+ if (request.destination === 'style' ||
+ request.destination === 'script' ||
+ request.destination === 'worker' ||
+ request.destination === 'image' ||
+ request.destination === 'font') {
+ // console.log(`[SW ${CACHE_VERSION}] StaleWhileRevalidate for: ${request.url}`);
+ event.respondWith(
+ caches.open(CACHE_VERSION).then(cache => {
+ return cache.match(request).then(cachedResponse => {
+ const fetchPromise = fetch(request).then(networkResponse => {
+ if (networkResponse.ok) {
+ const responseToCache = networkResponse.clone();
+ cache.put(request, responseToCache);
+ } else {
+ // console.warn(`[SW ${CACHE_VERSION}] StaleWhileRevalidate: Network fetch for ${request.url} failed with status ${networkResponse.status}`);
+ }
+ return networkResponse;
+ }).catch(err => {
+ // console.warn(`[SW ${CACHE_VERSION}] StaleWhileRevalidate: Network fetch error for ${request.url}:`, err);
+ // If fetch fails, and we already served from cache, that's okay.
+ // If cache also missed (i.e., cachedResponse was null), then this error will propagate.
+ throw err;
+ });
+ return cachedResponse || fetchPromise;
+ }).catch(err => {
+ // This catch block handles errors from cache.match() or if fetchPromise was returned and rejected
+ // console.error(`[SW ${CACHE_VERSION}] StaleWhileRevalidate: Error for ${request.url}. Trying network fallback.`, err);
+ return fetch(request); // Final fallback to network if cache interactions fail
+ });
+ })
+ );
+ return;
+ }
+
+ // Strategy 3: Cache First for other types of requests (e.g., manifest.json if not in APP_SHELL_URLS)
+ // console.log(`[SW ${CACHE_VERSION}] CacheFirst for: ${request.url}`);
+ event.respondWith(
+ caches.match(request)
+ .then(response => {
+ return response || fetch(request).then(networkResponse => {
+ if(networkResponse.ok) {
+ const responseClone = networkResponse.clone();
+ caches.open(CACHE_VERSION).then(cache => cache.put(request, responseClone));
+ }
+ return networkResponse;
+ });
+ })
+ );
+});
+
+self.addEventListener('message', event => {
+ if (event.data && event.data.action === 'skipWaiting') {
+ console.log(`[SW ${CACHE_VERSION}] Received skipWaiting message, activating new SW.`);
+ self.skipWaiting();
+ }
+});
\ No newline at end of file
diff --git a/src/utils/timeFormatter.js b/src/utils/timeFormatter.js
new file mode 100644
index 0000000..e6d5300
--- /dev/null
+++ b/src/utils/timeFormatter.js
@@ -0,0 +1,32 @@
+export function formatTime(totalSeconds) {
+ const isNegative = totalSeconds < 0;
+ if (isNegative) {
+ totalSeconds = -totalSeconds;
+ }
+
+ const minutes = Math.floor(totalSeconds / 60);
+ const seconds = totalSeconds % 60;
+
+ const paddedMinutes = String(minutes).padStart(2, '0');
+ const paddedSeconds = String(seconds).padStart(2, '0');
+
+ return `${isNegative ? '-' : ''}${paddedMinutes}:${paddedSeconds}`;
+ }
+
+ export function parseTime(timeString) { // MM:SS or -MM:SS
+ if (!timeString || typeof timeString !== 'string') return 0;
+ const isNegative = timeString.startsWith('-');
+ if (isNegative) {
+ timeString = timeString.substring(1);
+ }
+ const parts = timeString.split(':');
+ if (parts.length !== 2) return 0;
+
+ const minutes = parseInt(parts[0], 10);
+ const seconds = parseInt(parts[1], 10);
+
+ if (isNaN(minutes) || isNaN(seconds)) return 0;
+
+ let totalSeconds = (minutes * 60) + seconds;
+ return isNegative ? -totalSeconds : totalSeconds;
+ }
\ No newline at end of file
diff --git a/src/views/GameView.vue b/src/views/GameView.vue
new file mode 100644
index 0000000..123f219
--- /dev/null
+++ b/src/views/GameView.vue
@@ -0,0 +1,282 @@
+
+
+ No players eligible to run. (All skipped or issue)
+
+
+ No players to display.
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/src/views/InfoView.vue b/src/views/InfoView.vue
new file mode 100644
index 0000000..6503e89
--- /dev/null
+++ b/src/views/InfoView.vue
@@ -0,0 +1,129 @@
+
+
+
+
About Nexus Timer
+
+ Build: {{ buildTime }}
+
+
+
+ {{ updateStatusMessage }}
+
+
+
+
+
+ Nexus Timer is a dynamic multi-player timer designed for games, workshops, or any activity where turns pass sequentially in a circular fashion.
+ It provides a clear visual focus on the current participant and their immediate successor, ensuring everyone stays engaged and aware of who is next.
+
+
+
Key Features:
+
+
Circular player display focusing on Current and Next player.
+
Individual customizable countdown timers (MM:SS) per player.
+
Timers can go into negative time.
+
Two game modes: Normal (one timer runs) and All Timers Running.
+
Player management: Add, edit, delete, reorder players.
+
Photo avatars using device camera or defaults.
+
Configurable hotkeys for passing turns and global pause/resume.
+
Audio feedback for timer events.
+
Light/Dark theme options.
+
Persistent storage of game state.
+
Screen Wake Lock to keep screen on during active gameplay.
+
+
+
\ No newline at end of file
diff --git a/src/views/SetupView.vue b/src/views/SetupView.vue
new file mode 100644
index 0000000..8f61fd8
--- /dev/null
+++ b/src/views/SetupView.vue
@@ -0,0 +1,310 @@
+
+