Compare commits
16 Commits
main
...
96aeb22210
| Author | SHA1 | Date | |
|---|---|---|---|
| 96aeb22210 | |||
| 75b8dc5d15 | |||
| 98ffee7764 | |||
| 429c1dd557 | |||
| 80989a248e | |||
| bade9c0a15 | |||
| 3561db616c | |||
| fc278ed256 | |||
| a0f3489656 | |||
| d959f4929d | |||
| df1e316930 | |||
| 2838df5e05 | |||
| 8a6947f4ea | |||
| 1cfcd628d4 | |||
| 21cb105cd0 | |||
| fdb6e5e618 |
11
Dockerfile
Normal file
@@ -0,0 +1,11 @@
|
||||
# Use the official Nginx image as the base image
|
||||
FROM nginx:alpine
|
||||
|
||||
# Remove the default Nginx static files
|
||||
RUN rm -rf /usr/share/nginx/html/*
|
||||
|
||||
# Copy all your app's files into the Nginx directory
|
||||
COPY . /usr/share/nginx/html
|
||||
|
||||
# Expose port 80
|
||||
EXPOSE 80
|
||||
67
README.md
@@ -1,3 +1,68 @@
|
||||
# game-timer
|
||||
# Game Timer
|
||||
|
||||
Multi-player chess timer with carousel navigation
|
||||
|
||||
# PWA Containerized Deployment
|
||||
|
||||
This document provides step-by-step instructions to pull the source code and deploy the Progressive Web App (PWA) using Docker on a production server.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- **Git:** Installed on your production server.
|
||||
- **Docker:** Installed and running on your production server.
|
||||
- **Basic Knowledge:** Familiarity with the command line.
|
||||
|
||||
## Steps
|
||||
|
||||
### 1. Clone the Repository
|
||||
|
||||
Log in to your production server and navigate to the directory where you want to store the project. Then run:
|
||||
|
||||
```bash
|
||||
git clone https://gitea.virtonline.eu/2HoursProject/game-timer.git
|
||||
cd game-timer
|
||||
```
|
||||
|
||||
### 2. Build the docker image
|
||||
|
||||
From the repository root, run the following command to build your Docker image:
|
||||
|
||||
```bash
|
||||
docker build -t 'game-timer:latest' .
|
||||
```
|
||||
|
||||
### 3. Run the Docker Container
|
||||
|
||||
Once the image is built, run the container on port 8080 with:
|
||||
|
||||
```bash
|
||||
docker run -d -p 8080:80 --name game-timer-container game-timer:latest
|
||||
```
|
||||
|
||||
### 4. Verify the Deployment
|
||||
|
||||
Check if it's running:
|
||||
|
||||
```bash
|
||||
docker ps
|
||||
```
|
||||
|
||||
View logs (if needed):
|
||||
|
||||
```bash
|
||||
docker logs game-timer-container
|
||||
```
|
||||
|
||||
After running the container, open your web browser and navigate to:
|
||||
|
||||
```bash
|
||||
http://localhost
|
||||
```
|
||||
|
||||
### 5. Terminate
|
||||
|
||||
To stop your running game-timer-container, use:
|
||||
|
||||
```bash
|
||||
docker stop game-timer-container
|
||||
```
|
||||
315
audio.js
Normal file
@@ -0,0 +1,315 @@
|
||||
// Audio Manager using Web Audio API
|
||||
const audioManager = {
|
||||
audioContext: null,
|
||||
muted: false,
|
||||
sounds: {},
|
||||
lowTimeThreshold: 10, // Seconds threshold for low time warning
|
||||
lastTickTime: 0, // Track when we started continuous ticking
|
||||
tickFadeoutTime: 3, // Seconds after which tick sound fades out
|
||||
|
||||
// Initialize the audio context
|
||||
init() {
|
||||
try {
|
||||
// Create AudioContext (with fallback for older browsers)
|
||||
this.audioContext = new (window.AudioContext || window.webkitAudioContext)();
|
||||
|
||||
// Check for saved mute preference
|
||||
const savedMute = localStorage.getItem('gameTimerMuted');
|
||||
this.muted = savedMute === 'true';
|
||||
|
||||
// Create all the sounds
|
||||
this.createSounds();
|
||||
|
||||
console.log('Web Audio API initialized successfully');
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.error('Web Audio API initialization failed:', error);
|
||||
return false;
|
||||
}
|
||||
},
|
||||
|
||||
// Create all the sound generators
|
||||
createSounds() {
|
||||
// Game sounds
|
||||
this.sounds.tick = this.createTickSound();
|
||||
this.sounds.lowTime = this.createLowTimeSound();
|
||||
this.sounds.timeUp = this.createTimeUpSound();
|
||||
this.sounds.gameStart = this.createGameStartSound();
|
||||
this.sounds.gamePause = this.createGamePauseSound();
|
||||
this.sounds.gameResume = this.createGameResumeSound();
|
||||
this.sounds.gameOver = this.createGameOverSound();
|
||||
this.sounds.playerSwitch = this.createPlayerSwitchSound();
|
||||
|
||||
// UI sounds
|
||||
this.sounds.buttonClick = this.createButtonClickSound();
|
||||
this.sounds.modalOpen = this.createModalOpenSound();
|
||||
this.sounds.modalClose = this.createModalCloseSound();
|
||||
this.sounds.playerAdded = this.createPlayerAddedSound();
|
||||
this.sounds.playerEdited = this.createPlayerEditedSound();
|
||||
this.sounds.playerDeleted = this.createPlayerDeletedSound();
|
||||
},
|
||||
|
||||
// Helper function to create an oscillator
|
||||
createOscillator(type, frequency, startTime, duration, gain = 1.0, ramp = false) {
|
||||
if (this.audioContext === null) this.init();
|
||||
|
||||
const oscillator = this.audioContext.createOscillator();
|
||||
const gainNode = this.audioContext.createGain();
|
||||
|
||||
oscillator.type = type;
|
||||
oscillator.frequency.value = frequency;
|
||||
gainNode.gain.value = gain;
|
||||
|
||||
oscillator.connect(gainNode);
|
||||
gainNode.connect(this.audioContext.destination);
|
||||
|
||||
oscillator.start(startTime);
|
||||
|
||||
if (ramp) {
|
||||
gainNode.gain.exponentialRampToValueAtTime(0.001, startTime + duration);
|
||||
}
|
||||
|
||||
oscillator.stop(startTime + duration);
|
||||
|
||||
return { oscillator, gainNode };
|
||||
},
|
||||
|
||||
// Sound creators
|
||||
createTickSound() {
|
||||
return () => {
|
||||
const now = this.audioContext.currentTime;
|
||||
const currentTime = Date.now() / 1000;
|
||||
|
||||
// Initialize lastTickTime if it's not set
|
||||
if (this.lastTickTime === 0) {
|
||||
this.lastTickTime = currentTime;
|
||||
}
|
||||
|
||||
// Calculate how long we've been ticking continuously
|
||||
const tickDuration = currentTime - this.lastTickTime;
|
||||
|
||||
// Determine volume based on duration
|
||||
let volume = 0.1; // Default/initial volume
|
||||
|
||||
if (tickDuration <= this.tickFadeoutTime) {
|
||||
// Linear fade from 0.1 to 0 over tickFadeoutTime seconds
|
||||
volume = 0.1 * (1 - (tickDuration / this.tickFadeoutTime));
|
||||
} else {
|
||||
// After tickFadeoutTime, don't play any sound
|
||||
return; // Exit without playing sound
|
||||
}
|
||||
|
||||
// Only play if volume is significant
|
||||
if (volume > 0.001) {
|
||||
this.createOscillator('sine', 800, now, 0.03, volume);
|
||||
}
|
||||
};
|
||||
},
|
||||
|
||||
createLowTimeSound() {
|
||||
return () => {
|
||||
const now = this.audioContext.currentTime;
|
||||
// Low time warning is always audible
|
||||
this.createOscillator('triangle', 660, now, 0.1, 0.2);
|
||||
// Reset tick fade timer on low time warning
|
||||
this.lastTickTime = 0;
|
||||
};
|
||||
},
|
||||
|
||||
createTimeUpSound() {
|
||||
return () => {
|
||||
const now = this.audioContext.currentTime;
|
||||
|
||||
// First note
|
||||
this.createOscillator('sawtooth', 440, now, 0.2, 0.3);
|
||||
|
||||
// Second note (lower)
|
||||
this.createOscillator('sawtooth', 220, now + 0.25, 0.3, 0.4);
|
||||
|
||||
// Reset tick fade timer
|
||||
this.lastTickTime = 0;
|
||||
};
|
||||
},
|
||||
|
||||
createGameStartSound() {
|
||||
return () => {
|
||||
const now = this.audioContext.currentTime;
|
||||
|
||||
// Rising sequence
|
||||
this.createOscillator('sine', 440, now, 0.1, 0.3);
|
||||
this.createOscillator('sine', 554, now + 0.1, 0.1, 0.3);
|
||||
this.createOscillator('sine', 659, now + 0.2, 0.3, 0.3, true);
|
||||
|
||||
// Reset tick fade timer
|
||||
this.lastTickTime = 0;
|
||||
};
|
||||
},
|
||||
|
||||
createGamePauseSound() {
|
||||
return () => {
|
||||
const now = this.audioContext.currentTime;
|
||||
|
||||
// Two notes pause sound
|
||||
this.createOscillator('sine', 659, now, 0.1, 0.3);
|
||||
this.createOscillator('sine', 523, now + 0.15, 0.2, 0.3, true);
|
||||
|
||||
// Reset tick fade timer
|
||||
this.lastTickTime = 0;
|
||||
};
|
||||
},
|
||||
|
||||
createGameResumeSound() {
|
||||
return () => {
|
||||
const now = this.audioContext.currentTime;
|
||||
|
||||
// Rising sequence (opposite of pause)
|
||||
this.createOscillator('sine', 523, now, 0.1, 0.3);
|
||||
this.createOscillator('sine', 659, now + 0.15, 0.2, 0.3, true);
|
||||
|
||||
// Reset tick fade timer
|
||||
this.lastTickTime = 0;
|
||||
};
|
||||
},
|
||||
|
||||
createGameOverSound() {
|
||||
return () => {
|
||||
const now = this.audioContext.currentTime;
|
||||
|
||||
// Fanfare
|
||||
this.createOscillator('square', 440, now, 0.1, 0.3);
|
||||
this.createOscillator('square', 554, now + 0.1, 0.1, 0.3);
|
||||
this.createOscillator('square', 659, now + 0.2, 0.1, 0.3);
|
||||
this.createOscillator('square', 880, now + 0.3, 0.4, 0.3, true);
|
||||
|
||||
// Reset tick fade timer
|
||||
this.lastTickTime = 0;
|
||||
};
|
||||
},
|
||||
|
||||
createPlayerSwitchSound() {
|
||||
return () => {
|
||||
const now = this.audioContext.currentTime;
|
||||
this.createOscillator('sine', 1200, now, 0.05, 0.2);
|
||||
|
||||
// Reset tick fade timer on player switch
|
||||
this.lastTickTime = 0;
|
||||
};
|
||||
},
|
||||
|
||||
createButtonClickSound() {
|
||||
return () => {
|
||||
const now = this.audioContext.currentTime;
|
||||
this.createOscillator('sine', 700, now, 0.04, 0.1);
|
||||
};
|
||||
},
|
||||
|
||||
createModalOpenSound() {
|
||||
return () => {
|
||||
const now = this.audioContext.currentTime;
|
||||
|
||||
// Ascending sound
|
||||
this.createOscillator('sine', 400, now, 0.1, 0.2);
|
||||
this.createOscillator('sine', 600, now + 0.1, 0.1, 0.2);
|
||||
};
|
||||
},
|
||||
|
||||
createModalCloseSound() {
|
||||
return () => {
|
||||
const now = this.audioContext.currentTime;
|
||||
|
||||
// Descending sound
|
||||
this.createOscillator('sine', 600, now, 0.1, 0.2);
|
||||
this.createOscillator('sine', 400, now + 0.1, 0.1, 0.2);
|
||||
};
|
||||
},
|
||||
|
||||
createPlayerAddedSound() {
|
||||
return () => {
|
||||
const now = this.audioContext.currentTime;
|
||||
|
||||
// Positive ascending notes
|
||||
this.createOscillator('sine', 440, now, 0.1, 0.2);
|
||||
this.createOscillator('sine', 523, now + 0.1, 0.1, 0.2);
|
||||
this.createOscillator('sine', 659, now + 0.2, 0.2, 0.2, true);
|
||||
};
|
||||
},
|
||||
|
||||
createPlayerEditedSound() {
|
||||
return () => {
|
||||
const now = this.audioContext.currentTime;
|
||||
|
||||
// Two note confirmation
|
||||
this.createOscillator('sine', 440, now, 0.1, 0.2);
|
||||
this.createOscillator('sine', 523, now + 0.15, 0.15, 0.2);
|
||||
};
|
||||
},
|
||||
|
||||
createPlayerDeletedSound() {
|
||||
return () => {
|
||||
const now = this.audioContext.currentTime;
|
||||
|
||||
// Descending notes
|
||||
this.createOscillator('sine', 659, now, 0.1, 0.2);
|
||||
this.createOscillator('sine', 523, now + 0.1, 0.1, 0.2);
|
||||
this.createOscillator('sine', 392, now + 0.2, 0.2, 0.2, true);
|
||||
};
|
||||
},
|
||||
|
||||
// Play a sound if not muted
|
||||
play(soundName) {
|
||||
if (this.muted || !this.sounds[soundName]) return;
|
||||
|
||||
// Resume audio context if it's suspended (needed for newer browsers)
|
||||
if (this.audioContext.state === 'suspended') {
|
||||
this.audioContext.resume();
|
||||
}
|
||||
|
||||
this.sounds[soundName]();
|
||||
},
|
||||
|
||||
// Toggle mute state
|
||||
toggleMute() {
|
||||
this.muted = !this.muted;
|
||||
localStorage.setItem('gameTimerMuted', this.muted);
|
||||
return this.muted;
|
||||
},
|
||||
|
||||
// Play timer sounds based on remaining time
|
||||
playTimerSound(remainingSeconds) {
|
||||
if (remainingSeconds <= 0) {
|
||||
// Reset tick fade timer when timer stops
|
||||
this.lastTickTime = 0;
|
||||
return; // Don't play sounds for zero time
|
||||
}
|
||||
|
||||
if (remainingSeconds <= this.lowTimeThreshold) {
|
||||
// Play low time warning sound (this resets the tick fade timer)
|
||||
this.play('lowTime');
|
||||
} else if (remainingSeconds % 1 === 0) {
|
||||
// Normal tick sound on every second
|
||||
this.play('tick');
|
||||
}
|
||||
},
|
||||
|
||||
// Play timer expired sound
|
||||
playTimerExpired() {
|
||||
this.play('timeUp');
|
||||
},
|
||||
|
||||
// Stop all sounds and reset the tick fading
|
||||
stopAllSounds() {
|
||||
// Reset tick fade timer when stopping sounds
|
||||
this.lastTickTime = 0;
|
||||
},
|
||||
|
||||
// Reset the tick fading (call this when timer is paused or player changes)
|
||||
resetTickFade() {
|
||||
this.lastTickTime = 0;
|
||||
}
|
||||
};
|
||||
|
||||
// Initialize audio on module load
|
||||
audioManager.init();
|
||||
|
||||
// Export the audio manager
|
||||
export default audioManager;
|
||||
135
deeplinks.js
Normal file
@@ -0,0 +1,135 @@
|
||||
// deeplinks.js - Deep Link Manager for Game Timer
|
||||
|
||||
// Available actions
|
||||
const VALID_ACTIONS = ['start', 'pause', 'toggle', 'nextplayer', 'reset'];
|
||||
|
||||
// Class to manage all deep link functionality
|
||||
class DeepLinkManager {
|
||||
constructor() {
|
||||
this.actionHandlers = {};
|
||||
|
||||
// Initialize listeners
|
||||
this.initServiceWorkerListener();
|
||||
this.initHashChangeListener();
|
||||
this.initPopStateListener();
|
||||
}
|
||||
|
||||
// Register action handlers
|
||||
registerHandler(action, handlerFn) {
|
||||
if (VALID_ACTIONS.includes(action)) {
|
||||
this.actionHandlers[action] = handlerFn;
|
||||
console.log(`Registered handler for action: ${action}`);
|
||||
} else {
|
||||
console.warn(`Attempted to register handler for invalid action: ${action}`);
|
||||
}
|
||||
}
|
||||
|
||||
// Extract action from URL parameters (search or hash)
|
||||
getActionFromUrl() {
|
||||
// Check for action in both search params and hash
|
||||
const searchParams = new URLSearchParams(window.location.search);
|
||||
const hashParams = new URLSearchParams(window.location.hash.substring(1));
|
||||
|
||||
// First check search params (for direct curl or navigation)
|
||||
const searchAction = searchParams.get('action');
|
||||
if (searchAction && VALID_ACTIONS.includes(searchAction)) {
|
||||
console.log('Found action in search params:', searchAction);
|
||||
return searchAction;
|
||||
}
|
||||
|
||||
// Then check hash params (existing deep link mechanism)
|
||||
const hashAction = hashParams.get('action');
|
||||
if (hashAction && VALID_ACTIONS.includes(hashAction)) {
|
||||
console.log('Found action in hash params:', hashAction);
|
||||
return hashAction;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
// Process an action
|
||||
handleAction(action) {
|
||||
if (!action) return;
|
||||
|
||||
console.log('Processing action:', action);
|
||||
|
||||
if (this.actionHandlers[action]) {
|
||||
this.actionHandlers[action]();
|
||||
} else {
|
||||
console.log('No handler registered for action:', action);
|
||||
}
|
||||
}
|
||||
|
||||
// Handle deep links from URL
|
||||
processDeepLink() {
|
||||
// Get action from URL parameters
|
||||
const action = this.getActionFromUrl();
|
||||
|
||||
// Process the action if found
|
||||
if (action) {
|
||||
this.handleAction(action);
|
||||
|
||||
// Clear the parameters to prevent duplicate actions if page is refreshed
|
||||
if (window.history && window.history.replaceState) {
|
||||
// Create new URL without the action parameter
|
||||
const newUrl = window.location.pathname;
|
||||
window.history.replaceState({}, document.title, newUrl);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Initialize service worker message listener
|
||||
initServiceWorkerListener() {
|
||||
if ('serviceWorker' in navigator) {
|
||||
navigator.serviceWorker.addEventListener('message', (event) => {
|
||||
if (event.data && event.data.type === 'ACTION') {
|
||||
console.log('Received action from service worker:', event.data.action);
|
||||
this.handleAction(event.data.action);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Initialize hash change listener
|
||||
initHashChangeListener() {
|
||||
window.addEventListener('hashchange', () => {
|
||||
console.log('Hash changed, checking for actions');
|
||||
this.processDeepLink();
|
||||
});
|
||||
}
|
||||
|
||||
// Initialize popstate listener for navigation events
|
||||
initPopStateListener() {
|
||||
window.addEventListener('popstate', () => {
|
||||
console.log('Navigation occurred, checking for actions');
|
||||
this.processDeepLink();
|
||||
});
|
||||
}
|
||||
|
||||
// Send an action to the service worker
|
||||
sendActionToServiceWorker(action) {
|
||||
if ('serviceWorker' in navigator && navigator.serviceWorker.controller) {
|
||||
navigator.serviceWorker.controller.postMessage({
|
||||
type: 'PROCESS_ACTION',
|
||||
action: action
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Generate a deep link URL for a specific action
|
||||
generateDeepLink(action, useHash = false) {
|
||||
if (!VALID_ACTIONS.includes(action)) {
|
||||
console.warn(`Cannot generate deep link for invalid action: ${action}`);
|
||||
return null;
|
||||
}
|
||||
|
||||
const baseUrl = window.location.origin + window.location.pathname;
|
||||
return useHash ?
|
||||
`${baseUrl}#action=${action}` :
|
||||
`${baseUrl}?action=${action}`;
|
||||
}
|
||||
}
|
||||
|
||||
// Export singleton instance
|
||||
const deepLinkManager = new DeepLinkManager();
|
||||
export default deepLinkManager;
|
||||
BIN
favicon.ico
Normal file
|
After Width: | Height: | Size: 15 KiB |
BIN
icons/android-chrome-192x192.png
Normal file
|
After Width: | Height: | Size: 5.9 KiB |
BIN
icons/android-chrome-512x512.png
Normal file
|
After Width: | Height: | Size: 18 KiB |
BIN
icons/apple-touch-icon.png
Normal file
|
After Width: | Height: | Size: 5.2 KiB |
BIN
icons/favicon-16x16.png
Normal file
|
After Width: | Height: | Size: 398 B |
BIN
icons/favicon-32x32.png
Normal file
|
After Width: | Height: | Size: 770 B |
184
index.html
Normal file
@@ -0,0 +1,184 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<meta name="theme-color" content="#2c3e50">
|
||||
<title>Game Timer</title>
|
||||
<link rel="manifest" href="manifest.json">
|
||||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.2/css/all.min.css">
|
||||
<link rel="stylesheet" href="styles.css">
|
||||
|
||||
<!-- Deep Linking - App Links for Android -->
|
||||
<link rel="alternate" href="android-app://eu.virtonline.gametimer/https://game-timer.virtonline.eu" />
|
||||
|
||||
<!-- Deep Linking - Universal Links for iOS -->
|
||||
<meta name="apple-itunes-app" content="app-id=yourAppID, app-argument=https://game-timer.virtonline.eu">
|
||||
|
||||
<!-- Deep Linking - Web App URL Handling -->
|
||||
<link rel="alternate" href="web+gametimer://action" />
|
||||
</head>
|
||||
<body>
|
||||
<div class="app-container">
|
||||
<header class="header">
|
||||
<div class="game-controls">
|
||||
<button id="gameButton" class="game-button">Start Game</button>
|
||||
</div>
|
||||
<div class="header-buttons">
|
||||
<button id="resetButton" class="header-button" title="Reset All Data">
|
||||
<i class="fas fa-redo-alt"></i>
|
||||
</button>
|
||||
<button id="addPlayerButton" class="header-button" title="Add New Player">
|
||||
<i class="fas fa-user-plus"></i>
|
||||
</button>
|
||||
<button id="setupButton" class="header-button" title="Setup Current Player">
|
||||
<i class="fas fa-cog"></i>
|
||||
</button>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<div class="carousel-container">
|
||||
<div id="carousel" class="carousel">
|
||||
<!-- Player cards will be dynamically inserted here -->
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Player Edit Modal -->
|
||||
<div id="playerModal" class="modal">
|
||||
<div class="modal-content">
|
||||
<h2 id="modalTitle">Edit Player</h2>
|
||||
<form id="playerForm">
|
||||
<div class="form-group">
|
||||
<label for="playerName">Name</label>
|
||||
<input type="text" id="playerName" required>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label for="playerImage">Image</label>
|
||||
<div class="image-input-container">
|
||||
<input type="file" id="playerImage" accept="image/*">
|
||||
<button type="button" id="cameraButton" class="camera-button">
|
||||
<i class="fas fa-camera"></i> Take Photo
|
||||
</button>
|
||||
</div>
|
||||
<div id="imagePreview" class="player-image" style="margin-top: 0.5rem;">
|
||||
<i class="fas fa-user"></i>
|
||||
</div>
|
||||
</div>
|
||||
<div id="playerTimeContainer" class="form-group">
|
||||
<label for="playerTime">Time (minutes)</label>
|
||||
<input type="number" id="playerTime" min="1" max="180" value="5" required>
|
||||
</div>
|
||||
<div id="remainingTimeContainer" class="form-group" style="display: none;">
|
||||
<label for="playerRemainingTime">Remaining Time (MM:SS)</label>
|
||||
<input type="text" id="playerRemainingTime" pattern="[0-9]{2}:[0-9]{2}" placeholder="05:00">
|
||||
<small>Format: Minutes:Seconds (e.g., 05:30)</small>
|
||||
</div>
|
||||
<div class="form-buttons">
|
||||
<button type="button" id="cancelButton" class="cancel-button">Cancel</button>
|
||||
<button type="submit" class="save-button">Save</button>
|
||||
</div>
|
||||
<div class="form-buttons delete-button-container">
|
||||
<button type="button" id="deletePlayerButton" class="delete-button">Delete Player</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Reset Confirmation Modal -->
|
||||
<div id="resetModal" class="modal">
|
||||
<div class="modal-content">
|
||||
<h2>Reset All Data</h2>
|
||||
<p>Are you sure you want to reset all players and timers? This action cannot be undone.</p>
|
||||
<div class="form-buttons">
|
||||
<button type="button" id="resetCancelButton" class="cancel-button">Cancel</button>
|
||||
<button type="button" id="resetConfirmButton" class="save-button">Reset</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Camera Capture UI -->
|
||||
<div id="cameraContainer" class="camera-container">
|
||||
<div class="camera-view">
|
||||
<video id="cameraView" autoplay playsinline></video>
|
||||
<canvas id="cameraCanvas" style="display: none;"></canvas>
|
||||
</div>
|
||||
<div class="camera-controls">
|
||||
<button id="cameraCancelButton" class="camera-button-cancel">Cancel</button>
|
||||
<button id="cameraCaptureButton" class="camera-button-large"></button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Script for handling URL scheme and deep links -->
|
||||
<script type="module">
|
||||
// Register the custom URL protocol handler (web+gametimer://)
|
||||
if ('registerProtocolHandler' in navigator) {
|
||||
try {
|
||||
navigator.registerProtocolHandler(
|
||||
'web+gametimer',
|
||||
'https://game-timer.virtonline.eu/?action=%s',
|
||||
'Game Timer'
|
||||
);
|
||||
console.log('Protocol handler registered');
|
||||
} catch (e) {
|
||||
console.error('Failed to register protocol handler:', e);
|
||||
}
|
||||
}
|
||||
|
||||
// Function to parse URL parameters
|
||||
function getUrlParams() {
|
||||
const searchParams = new URLSearchParams(window.location.search);
|
||||
const hashParams = new URLSearchParams(window.location.hash.substring(1));
|
||||
|
||||
// Check search parameters first (for direct links)
|
||||
const action = searchParams.get('action');
|
||||
if (action) {
|
||||
// Clean the action parameter (remove 'web+gametimer://' if present)
|
||||
return action.replace('web+gametimer://', '');
|
||||
}
|
||||
|
||||
// Then check hash parameters (for deep links)
|
||||
return hashParams.get('action');
|
||||
}
|
||||
|
||||
// Initialize URL handling
|
||||
function initUrlHandling() {
|
||||
const action = getUrlParams();
|
||||
if (action) {
|
||||
console.log('URL action detected:', action);
|
||||
// Set the action in the hash to be processed by the main app
|
||||
window.location.hash = `action=${action}`;
|
||||
}
|
||||
}
|
||||
|
||||
// Run initialization when DOM is fully loaded
|
||||
document.addEventListener('DOMContentLoaded', initUrlHandling);
|
||||
</script>
|
||||
|
||||
<!-- Main application script -->
|
||||
<script type="module" src="app.js"></script>
|
||||
<script>
|
||||
if ("serviceWorker" in navigator) {
|
||||
navigator.serviceWorker.register("/sw.js")
|
||||
.then(() => console.log("Service Worker Registered"))
|
||||
.catch((err) => console.log("Service Worker Failed", err));
|
||||
}
|
||||
</script>
|
||||
<script>
|
||||
// Request notification permission on page load
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
if ('Notification' in window) {
|
||||
Notification.requestPermission().then(permission => {
|
||||
console.log('Notification permission:', permission);
|
||||
});
|
||||
}
|
||||
});
|
||||
</script>
|
||||
<footer class="app-footer">
|
||||
<div class="author-info">
|
||||
<p>Vibe coded by Martin</p>
|
||||
<p>Version 0.0.1</p>
|
||||
</div>
|
||||
</footer>
|
||||
</body>
|
||||
</html>
|
||||
20
labels.example
Normal file
@@ -0,0 +1,20 @@
|
||||
traefik.enable=true
|
||||
traefik.docker.network=traefik
|
||||
traefik.http.routers.game-timer.rule=Host(`game-timer.virtonline.eu`)
|
||||
traefik.http.routers.game-timer.service=game-timer
|
||||
traefik.http.routers.game-timer.tls=true
|
||||
traefik.http.routers.game-timer.tls.certResolver=default
|
||||
traefik.http.routers.game-timer.entrypoints=web-secure
|
||||
traefik.http.services.game-timer.loadbalancer.server.port=80
|
||||
|
||||
traefik.http.routers.game-timer.middlewares=game-timer-auth
|
||||
# Declaring the user list
|
||||
#
|
||||
# Note: when used in docker-compose.yml all dollar signs in the hash need to be doubled for escaping.
|
||||
# To create a user:password pair, the following command can be used:
|
||||
# echo $(htpasswd -nb user password) | sed -e s/\\$/\\$\\$/g
|
||||
#
|
||||
# Also note that dollar signs should NOT be doubled when they are not evaluated (e.g. Ansible docker_container module).
|
||||
# for docker lables use
|
||||
# `htpasswd -nb user password`
|
||||
traefik.http.middlewares.game-timer-auth.basicauth.users=user:$apr1$rFge2lVe$DpoqxMsxSVJubFLXu4OMr1
|
||||
100
manifest.json
Normal file
@@ -0,0 +1,100 @@
|
||||
{
|
||||
"name": "Game Timer PWA",
|
||||
"short_name": "Game Timer",
|
||||
"description": "Multi-player chess-like timer with carousel navigation",
|
||||
"start_url": "/index.html",
|
||||
"display": "standalone",
|
||||
"background_color": "#f5f5f5",
|
||||
"theme_color": "#2c3e50",
|
||||
"icons": [
|
||||
{
|
||||
"src": "/icons/android-chrome-192x192.png",
|
||||
"sizes": "192x192",
|
||||
"type": "image/png"
|
||||
},
|
||||
{
|
||||
"src": "/icons/android-chrome-512x512.png",
|
||||
"sizes": "512x512",
|
||||
"type": "image/png"
|
||||
},
|
||||
{
|
||||
"src": "/icons/apple-touch-icon.png",
|
||||
"sizes": "180x180",
|
||||
"type": "image/png"
|
||||
},
|
||||
{
|
||||
"src": "/icons/favicon-32x32.png",
|
||||
"sizes": "32x32",
|
||||
"type": "image/png"
|
||||
},
|
||||
{
|
||||
"src": "/icons/favicon-16x16.png",
|
||||
"sizes": "16x16",
|
||||
"type": "image/png"
|
||||
}
|
||||
],
|
||||
"screenshots": [
|
||||
{
|
||||
"src": "/screenshots/screenshot1.png",
|
||||
"sizes": "2604x2269",
|
||||
"type": "image/png",
|
||||
"form_factor": "wide"
|
||||
},
|
||||
{
|
||||
"src": "/screenshots/screenshot2.png",
|
||||
"sizes": "1082x2402",
|
||||
"type": "image/png"
|
||||
}
|
||||
],
|
||||
"url_handlers": [
|
||||
{
|
||||
"origin": "https://game-timer.virtonline.eu"
|
||||
}
|
||||
],
|
||||
"handle_links": "preferred",
|
||||
"file_handlers": [],
|
||||
"protocol_handlers": [
|
||||
{
|
||||
"protocol": "web+gametimer",
|
||||
"url": "/?action=%s"
|
||||
}
|
||||
],
|
||||
"shortcuts": [
|
||||
{
|
||||
"name": "Start Game",
|
||||
"short_name": "Start",
|
||||
"description": "Start the game timer",
|
||||
"url": "/?action=start",
|
||||
"icons": [{ "src": "/icons/play.png", "sizes": "192x192" }]
|
||||
},
|
||||
{
|
||||
"name": "Pause Game",
|
||||
"short_name": "Pause",
|
||||
"description": "Pause the game timer",
|
||||
"url": "/?action=pause",
|
||||
"icons": [{ "src": "/icons/pause.png", "sizes": "192x192" }]
|
||||
},
|
||||
{
|
||||
"name": "Toggle Game",
|
||||
"short_name": "Toggle",
|
||||
"description": "Toggle game state (start/pause)",
|
||||
"url": "/?action=toggle",
|
||||
"icons": [{ "src": "/icons/toggle.png", "sizes": "192x192" }]
|
||||
},
|
||||
{
|
||||
"name": "Next Player",
|
||||
"short_name": "Next",
|
||||
"description": "Go to next player",
|
||||
"url": "/?action=nextplayer",
|
||||
"icons": [{ "src": "/icons/next.png", "sizes": "192x192" }]
|
||||
},
|
||||
{
|
||||
"name": "Reset Game",
|
||||
"short_name": "Reset",
|
||||
"description": "Reset the entire game",
|
||||
"url": "/?action=reset",
|
||||
"icons": [{ "src": "/icons/reset.png", "sizes": "192x192" }]
|
||||
}
|
||||
],
|
||||
"gcm_sender_id": "103953800507"
|
||||
}
|
||||
BIN
screenshots/screenshot1.png
Normal file
|
After Width: | Height: | Size: 320 KiB |
BIN
screenshots/screenshot2.png
Normal file
|
After Width: | Height: | Size: 416 KiB |
19
site.webmanifest
Normal file
@@ -0,0 +1,19 @@
|
||||
{
|
||||
"name": "Game Timer",
|
||||
"short_name": "Game Timer",
|
||||
"icons": [
|
||||
{
|
||||
"src": "/icons/android-chrome-192x192.png",
|
||||
"sizes": "192x192",
|
||||
"type": "image/png"
|
||||
},
|
||||
{
|
||||
"src": "/icons/android-chrome-512x512.png",
|
||||
"sizes": "512x512",
|
||||
"type": "image/png"
|
||||
}
|
||||
],
|
||||
"theme_color": "#ffffff",
|
||||
"background_color": "#ffffff",
|
||||
"display": "standalone"
|
||||
}
|
||||
370
styles.css
Normal file
@@ -0,0 +1,370 @@
|
||||
* {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
box-sizing: border-box;
|
||||
font-family: Arial, sans-serif;
|
||||
}
|
||||
|
||||
body {
|
||||
background-color: #f5f5f5;
|
||||
color: #333;
|
||||
overflow-x: hidden;
|
||||
}
|
||||
|
||||
.app-container {
|
||||
max-width: 100%;
|
||||
margin: 0 auto;
|
||||
min-height: 100vh;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.header {
|
||||
background-color: #2c3e50;
|
||||
color: white;
|
||||
padding: 1rem;
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
position: fixed;
|
||||
top: 0;
|
||||
width: 100%;
|
||||
z-index: 10;
|
||||
}
|
||||
|
||||
.game-controls {
|
||||
text-align: center;
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.game-button {
|
||||
background-color: #3498db;
|
||||
color: white;
|
||||
border: none;
|
||||
padding: 0.5rem 1rem;
|
||||
border-radius: 4px;
|
||||
font-size: 1rem;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.header-buttons {
|
||||
display: flex;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.header-button {
|
||||
background-color: transparent;
|
||||
color: white;
|
||||
border: none;
|
||||
font-size: 1.2rem;
|
||||
cursor: pointer;
|
||||
width: 40px;
|
||||
height: 40px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
border-radius: 50%;
|
||||
}
|
||||
|
||||
.header-button:hover {
|
||||
background-color: rgba(255, 255, 255, 0.1);
|
||||
}
|
||||
|
||||
.carousel-container {
|
||||
margin-top: 70px;
|
||||
margin-bottom: 60px; /* Add some space for the footer */
|
||||
width: 100%;
|
||||
overflow: hidden;
|
||||
flex: 1;
|
||||
touch-action: pan-x;
|
||||
}
|
||||
|
||||
.carousel {
|
||||
display: flex;
|
||||
transition: transform 0.3s ease;
|
||||
height: calc(100vh - 70px);
|
||||
}
|
||||
|
||||
/* Adjust the preview image in the modal to maintain consistency */
|
||||
#imagePreview.player-image {
|
||||
width: 180px; /* Slightly smaller than the main display but still larger than original 120px */
|
||||
height: 180px;
|
||||
margin: 0.5rem auto;
|
||||
}
|
||||
|
||||
.player-card {
|
||||
min-width: 100%;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 2rem; /* Increased from 1rem for more spacing */
|
||||
transition: all 0.3s ease;
|
||||
}
|
||||
|
||||
.active-player {
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
.inactive-player {
|
||||
opacity: 0.6;
|
||||
}
|
||||
|
||||
/* New styles for timer active state */
|
||||
.player-timer {
|
||||
font-size: 4rem;
|
||||
font-weight: bold;
|
||||
margin: 1rem 0;
|
||||
padding: 0.5rem 1.5rem;
|
||||
border-radius: 12px;
|
||||
position: relative;
|
||||
}
|
||||
|
||||
/* Timer background effect when game is running */
|
||||
.timer-active {
|
||||
background-color: #ffecee; /* Light red base color */
|
||||
box-shadow: 0 0 15px rgba(231, 76, 60, 0.5);
|
||||
animation: pulsate 1.5s ease-out infinite;
|
||||
}
|
||||
|
||||
/* Timer of a player that has run out of time */
|
||||
.timer-finished {
|
||||
color: #e74c3c;
|
||||
text-decoration: line-through;
|
||||
opacity: 0.7;
|
||||
}
|
||||
|
||||
/* Pulsating animation */
|
||||
@keyframes pulsate {
|
||||
0% {
|
||||
box-shadow: 0 0 0 0 rgba(231, 76, 60, 0.7);
|
||||
background-color: #ffecee;
|
||||
}
|
||||
50% {
|
||||
box-shadow: 0 0 20px 0 rgba(231, 76, 60, 0.5);
|
||||
background-color: #ffe0e0;
|
||||
}
|
||||
100% {
|
||||
box-shadow: 0 0 0 0 rgba(231, 76, 60, 0.7);
|
||||
background-color: #ffecee;
|
||||
}
|
||||
}
|
||||
|
||||
.player-image {
|
||||
width: 240px; /* Doubled from 120px */
|
||||
height: 240px; /* Doubled from 120px */
|
||||
border-radius: 50%;
|
||||
background-color: #ddd;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
margin-bottom: 2rem; /* Increased from 1rem */
|
||||
overflow: hidden;
|
||||
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2); /* Added shadow for better visual presence */
|
||||
}
|
||||
|
||||
.player-image img {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
object-fit: cover;
|
||||
}
|
||||
|
||||
.player-image i {
|
||||
font-size: 6rem; /* Doubled from 3rem */
|
||||
color: #888;
|
||||
}
|
||||
|
||||
.player-name {
|
||||
font-size: 3rem; /* Doubled from 1.5rem */
|
||||
margin-bottom: 1rem; /* Increased from 0.5rem */
|
||||
font-weight: bold;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.modal {
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
background-color: rgba(0, 0, 0, 0.7);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
z-index: 20;
|
||||
opacity: 0;
|
||||
pointer-events: none;
|
||||
transition: opacity 0.3s ease;
|
||||
}
|
||||
|
||||
.modal.active {
|
||||
opacity: 1;
|
||||
pointer-events: auto;
|
||||
}
|
||||
|
||||
.modal-content {
|
||||
background-color: white;
|
||||
padding: 2rem;
|
||||
border-radius: 8px;
|
||||
width: 90%;
|
||||
max-width: 500px;
|
||||
}
|
||||
|
||||
.form-group {
|
||||
margin-bottom: 1rem;
|
||||
}
|
||||
|
||||
.form-group label {
|
||||
display: block;
|
||||
margin-bottom: 0.5rem;
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
.form-group input {
|
||||
width: 100%;
|
||||
padding: 0.5rem;
|
||||
border: 1px solid #ddd;
|
||||
border-radius: 4px;
|
||||
}
|
||||
|
||||
.form-buttons {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
margin-top: 1rem;
|
||||
}
|
||||
|
||||
.form-buttons button {
|
||||
padding: 0.5rem 1rem;
|
||||
border: none;
|
||||
border-radius: 4px;
|
||||
cursor: pointer;
|
||||
flex: 1;
|
||||
margin: 0 0.5rem;
|
||||
}
|
||||
|
||||
.form-buttons button:first-child {
|
||||
margin-left: 0;
|
||||
}
|
||||
|
||||
.form-buttons button:last-child {
|
||||
margin-right: 0;
|
||||
}
|
||||
|
||||
.delete-button-container {
|
||||
margin-top: 1rem;
|
||||
}
|
||||
|
||||
.save-button {
|
||||
background-color: #27ae60;
|
||||
color: white;
|
||||
}
|
||||
|
||||
.cancel-button {
|
||||
background-color: #e74c3c;
|
||||
color: white;
|
||||
}
|
||||
|
||||
.delete-button {
|
||||
background-color: #e74c3c;
|
||||
color: white;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
/* Add these styles to your styles.css file */
|
||||
|
||||
.image-input-container {
|
||||
display: flex;
|
||||
gap: 10px;
|
||||
align-items: center;
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
|
||||
.camera-button {
|
||||
background-color: #3498db;
|
||||
color: white;
|
||||
border: none;
|
||||
padding: 0.5rem;
|
||||
border-radius: 4px;
|
||||
cursor: pointer;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 5px;
|
||||
}
|
||||
|
||||
.camera-button:hover {
|
||||
background-color: #2980b9;
|
||||
}
|
||||
|
||||
/* Optional: Hide the default file input appearance and use a custom button */
|
||||
input[type="file"] {
|
||||
max-width: 120px;
|
||||
}
|
||||
|
||||
.camera-container {
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
background-color: #000;
|
||||
z-index: 30;
|
||||
display: none;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.camera-container.active {
|
||||
display: flex;
|
||||
}
|
||||
|
||||
.camera-view {
|
||||
flex: 1;
|
||||
position: relative;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.camera-view video {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
object-fit: cover;
|
||||
}
|
||||
|
||||
.camera-controls {
|
||||
display: flex;
|
||||
justify-content: space-around;
|
||||
padding: 1rem;
|
||||
background-color: #222;
|
||||
}
|
||||
|
||||
.camera-button-large {
|
||||
width: 60px;
|
||||
height: 60px;
|
||||
border-radius: 50%;
|
||||
background-color: #fff;
|
||||
border: 3px solid #3498db;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.camera-button-cancel {
|
||||
background-color: #e74c3c;
|
||||
color: white;
|
||||
border: none;
|
||||
padding: 0.5rem 1rem;
|
||||
border-radius: 4px;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.app-footer {
|
||||
background-color: #2c3e50;
|
||||
color: white;
|
||||
padding: 1rem;
|
||||
text-align: center;
|
||||
font-size: 0.9rem;
|
||||
margin-top: auto; /* This pushes the footer to the bottom when possible */
|
||||
}
|
||||
|
||||
.author-info {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: 0.3rem;
|
||||
}
|
||||
267
sw.js
Normal file
@@ -0,0 +1,267 @@
|
||||
// Service Worker version
|
||||
const CACHE_VERSION = 'v1.0.0';
|
||||
const CACHE_NAME = `game-timer-${CACHE_VERSION}`;
|
||||
|
||||
// Files to cache
|
||||
const CACHE_FILES = [
|
||||
'/',
|
||||
'/index.html',
|
||||
'/app.js',
|
||||
'/audio.js',
|
||||
'/deeplinks.js',
|
||||
'/styles.css',
|
||||
'/manifest.json',
|
||||
'/icons/android-chrome-192x192.png',
|
||||
'/icons/android-chrome-512x512.png',
|
||||
'/icons/apple-touch-icon.png',
|
||||
'/icons/favicon-32x32.png',
|
||||
'/icons/favicon-16x16.png'
|
||||
];
|
||||
|
||||
// Valid deep link actions
|
||||
const VALID_ACTIONS = ['start', 'pause', 'toggle', 'nextplayer', 'reset'];
|
||||
|
||||
// Install event - Cache files
|
||||
self.addEventListener('install', event => {
|
||||
console.log('[ServiceWorker] Install');
|
||||
event.waitUntil(
|
||||
caches.open(CACHE_NAME)
|
||||
.then(cache => {
|
||||
console.log('[ServiceWorker] Caching app shell');
|
||||
return cache.addAll(CACHE_FILES);
|
||||
})
|
||||
.then(() => {
|
||||
console.log('[ServiceWorker] Skip waiting on install');
|
||||
return self.skipWaiting();
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
// Activate event - Clean old caches
|
||||
self.addEventListener('activate', event => {
|
||||
console.log('[ServiceWorker] Activate');
|
||||
event.waitUntil(
|
||||
caches.keys().then(keyList => {
|
||||
return Promise.all(keyList.map(key => {
|
||||
if (key !== CACHE_NAME) {
|
||||
console.log('[ServiceWorker] Removing old cache', key);
|
||||
return caches.delete(key);
|
||||
}
|
||||
}));
|
||||
})
|
||||
.then(() => {
|
||||
console.log('[ServiceWorker] Claiming clients');
|
||||
return self.clients.claim();
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
// Fetch event - Serve from cache, fallback to network
|
||||
self.addEventListener('fetch', event => {
|
||||
console.log('[ServiceWorker] Fetch', event.request.url);
|
||||
|
||||
// For navigation requests that include our deep link parameters,
|
||||
// skip the cache and go straight to network
|
||||
if (event.request.mode === 'navigate') {
|
||||
const url = new URL(event.request.url);
|
||||
|
||||
// Check if request has action parameter or hash
|
||||
if (url.searchParams.has('action') || url.hash.includes('action=')) {
|
||||
console.log('[ServiceWorker] Processing deep link navigation');
|
||||
|
||||
// Verify the action is valid
|
||||
const action = url.searchParams.get('action') ||
|
||||
new URLSearchParams(url.hash.substring(1)).get('action');
|
||||
|
||||
if (action && VALID_ACTIONS.includes(action)) {
|
||||
console.log('[ServiceWorker] Valid action found:', action);
|
||||
|
||||
// For navigation requests with valid actions, let the request go through
|
||||
// so our app can handle the deep link
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
event.respondWith(
|
||||
caches.match(event.request)
|
||||
.then(response => {
|
||||
return response || fetch(event.request)
|
||||
.then(res => {
|
||||
// Check if we should cache this response
|
||||
if (shouldCacheResponse(event.request, res)) {
|
||||
return caches.open(CACHE_NAME)
|
||||
.then(cache => {
|
||||
console.log('[ServiceWorker] Caching new resource:', event.request.url);
|
||||
cache.put(event.request, res.clone());
|
||||
return res;
|
||||
});
|
||||
}
|
||||
return res;
|
||||
});
|
||||
})
|
||||
.catch(error => {
|
||||
console.log('[ServiceWorker] Fetch failed; returning offline page', error);
|
||||
// You could return a custom offline page here
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
// Helper function to determine if a response should be cached
|
||||
function shouldCacheResponse(request, response) {
|
||||
// Only cache GET requests
|
||||
if (request.method !== 'GET') return false;
|
||||
|
||||
// Don't cache errors
|
||||
if (!response || response.status !== 200) return false;
|
||||
|
||||
// Check if URL should be cached
|
||||
const url = new URL(request.url);
|
||||
|
||||
// Don't cache query parameters (except common ones for content)
|
||||
if (url.search && !url.search.match(/\?(v|version|cache)=/)) return false;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
// Handle deep links from other apps (including Flic)
|
||||
self.addEventListener('message', event => {
|
||||
if (event.data && event.data.type === 'PROCESS_ACTION') {
|
||||
const action = event.data.action;
|
||||
console.log('[ServiceWorker] Received action message:', action);
|
||||
|
||||
// Validate the action
|
||||
if (!VALID_ACTIONS.includes(action)) {
|
||||
console.warn('[ServiceWorker] Invalid action received:', action);
|
||||
return;
|
||||
}
|
||||
|
||||
// Broadcast the action to all clients
|
||||
self.clients.matchAll().then(clients => {
|
||||
clients.forEach(client => {
|
||||
client.postMessage({
|
||||
type: 'ACTION',
|
||||
action: action
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
self.addEventListener('push', event => {
|
||||
console.log('[ServiceWorker] Push received');
|
||||
|
||||
let pushData = {
|
||||
title: 'Flic Action',
|
||||
body: 'Button pressed!',
|
||||
data: { action: 'Unknown', button: 'Unknown' } // Default data
|
||||
};
|
||||
|
||||
// --- Attempt to parse data payload ---
|
||||
if (event.data) {
|
||||
try {
|
||||
const parsedData = event.data.json();
|
||||
console.log('[ServiceWorker] Push data:', parsedData);
|
||||
|
||||
// Use parsed data for notification and message
|
||||
pushData = {
|
||||
title: parsedData.title || pushData.title,
|
||||
body: parsedData.body || pushData.body,
|
||||
// IMPORTANT: Extract the action details sent from your backend
|
||||
data: parsedData.data || pushData.data // Expecting { action: 'SingleClick', button: '...' }
|
||||
};
|
||||
|
||||
} catch (e) {
|
||||
console.error('[ServiceWorker] Error parsing push data:', e);
|
||||
// Use default notification if parsing fails
|
||||
pushData.body = event.data.text() || pushData.body; // Fallback to text
|
||||
}
|
||||
} else {
|
||||
console.log('[ServiceWorker] Push event but no data');
|
||||
}
|
||||
|
||||
// --- Send message to client(s) ---
|
||||
const messagePayload = {
|
||||
type: 'flic-action', // Custom message type
|
||||
action: pushData.data.action, // e.g., 'SingleClick', 'DoubleClick', 'Hold'
|
||||
button: pushData.data.button, // e.g., the button name
|
||||
timestamp: pushData.data.timestamp // e.g., the timestamp of the action
|
||||
};
|
||||
|
||||
// Send message to all open PWA windows controlled by this SW
|
||||
event.waitUntil(
|
||||
self.clients.matchAll({
|
||||
type: 'window', // Only target window clients
|
||||
includeUncontrolled: true // Include clients that might not be fully controlled yet
|
||||
}).then(clientList => {
|
||||
if (!clientList || clientList.length === 0) {
|
||||
console.log('[ServiceWorker] No client windows found to send message to.');
|
||||
// If no window is open, we MUST show a notification
|
||||
return self.registration.showNotification(pushData.title, {
|
||||
body: pushData.body,
|
||||
icon: '/icons/icon-192x192.png', // Optional: path to an icon
|
||||
data: pushData.data // Pass data if needed when notification is clicked
|
||||
});
|
||||
}
|
||||
|
||||
// Post message to each client
|
||||
let messageSent = false;
|
||||
clientList.forEach(client => {
|
||||
console.log(`[ServiceWorker] Posting message to client: ${client.id}`, messagePayload);
|
||||
client.postMessage(messagePayload);
|
||||
messageSent = true; // Mark that we at least tried to send a message
|
||||
});
|
||||
|
||||
// Decide whether to still show a notification even if a window is open.
|
||||
// Generally good practice unless you are SURE the app will handle it visibly.
|
||||
// You might choose *not* to show a notification if a client was found and focused.
|
||||
// For simplicity here, we'll still show one. Adjust as needed.
|
||||
if (!messageSent) { // Only show notification if no message was sent? Or always show?
|
||||
return self.registration.showNotification(pushData.title, {
|
||||
body: pushData.body,
|
||||
icon: '/icons/icon-192x192.png',
|
||||
data: pushData.data
|
||||
});
|
||||
}
|
||||
})
|
||||
);
|
||||
|
||||
// --- Show a notification (Important!) ---
|
||||
// Push notifications generally REQUIRE showing a notification to the user
|
||||
// unless the PWA is already in the foreground AND handles the event visually.
|
||||
// It's safer to always show one unless you have complex foreground detection.
|
||||
/* This part is now handled inside the clients.matchAll promise */
|
||||
/*
|
||||
const notificationOptions = {
|
||||
body: pushData.body,
|
||||
icon: '/icons/icon-192x192.png', // Optional: path to an icon
|
||||
data: pushData.data // Attach data if needed when notification is clicked
|
||||
};
|
||||
event.waitUntil(
|
||||
self.registration.showNotification(pushData.title, notificationOptions)
|
||||
);
|
||||
*/
|
||||
});
|
||||
|
||||
// This helps with navigation after app is installed
|
||||
self.addEventListener('notificationclick', event => {
|
||||
console.log('[ServiceWorker] Notification click received');
|
||||
|
||||
event.notification.close();
|
||||
|
||||
// Handle the notification click
|
||||
event.waitUntil(
|
||||
self.clients.matchAll({ type: 'window' })
|
||||
.then(clientList => {
|
||||
for (const client of clientList) {
|
||||
if (client.url.startsWith(self.location.origin) && 'focus' in client) {
|
||||
return client.focus();
|
||||
}
|
||||
}
|
||||
|
||||
if (self.clients.openWindow) {
|
||||
return self.clients.openWindow('/');
|
||||
}
|
||||
})
|
||||
);
|
||||
});
|
||||