Fix pixel persistence and improve mobile UX

- Fix pixel data storage to include user information (userId, username, timestamp)
- Enhance zoom controls to center properly without drift
- Improve mobile modal centering with flexbox layout
- Add dynamic backend URL detection for network access
- Fix CORS configuration for development mode
- Add mobile-optimized touch targets and safe area support
This commit is contained in:
martin 2025-08-22 20:14:48 +02:00
commit 194fc8da4c
14 changed files with 172 additions and 82 deletions

View file

@ -14,7 +14,9 @@
"Bash(mv:*)", "Bash(mv:*)",
"Bash(move start-dev.js scripts )", "Bash(move start-dev.js scripts )",
"Bash(move setup.js scripts)", "Bash(move setup.js scripts)",
"Bash(npm run type-check:*)" "Bash(npm run type-check:*)",
"Bash(git push:*)",
"Bash(git add:*)"
], ],
"deny": [], "deny": [],
"ask": [], "ask": [],

View file

@ -7,7 +7,7 @@ export const config = {
host: process.env.HOST || 'localhost', host: process.env.HOST || 'localhost',
nodeEnv: process.env.NODE_ENV || 'development', nodeEnv: process.env.NODE_ENV || 'development',
jwtSecret: process.env.JWT_SECRET || 'your-super-secret-jwt-key-change-in-production', jwtSecret: process.env.JWT_SECRET || 'your-super-secret-jwt-key-change-in-production',
corsOrigin: process.env.CORS_ORIGIN ? process.env.CORS_ORIGIN.split(',') : ['http://localhost:3000'], corsOrigin: process.env.CORS_ORIGIN ? process.env.CORS_ORIGIN.split(',') : (process.env.NODE_ENV === 'development' ? true : ['http://localhost:3000']),
// Rate limiting // Rate limiting
rateLimits: { rateLimits: {

View file

@ -12,14 +12,21 @@ import { config } from '../config/env';
export class CanvasService { export class CanvasService {
private readonly keyPrefix = config.redis.keyPrefix; private readonly keyPrefix = config.redis.keyPrefix;
async placePixel(canvasId: string, x: number, y: number, color: string, userId: string): Promise<boolean> { async placePixel(canvasId: string, x: number, y: number, color: string, userId: string, username?: string): Promise<boolean> {
try { try {
const { chunkX, chunkY } = getChunkCoordinates(x, y); const { chunkX, chunkY } = getChunkCoordinates(x, y);
const chunkKey = `${this.keyPrefix}canvas:${canvasId}:chunk:${getChunkKey(chunkX, chunkY)}`; const chunkKey = `${this.keyPrefix}canvas:${canvasId}:chunk:${getChunkKey(chunkX, chunkY)}`;
const pixelKey = getPixelKey(x % CANVAS_CONFIG.DEFAULT_CHUNK_SIZE, y % CANVAS_CONFIG.DEFAULT_CHUNK_SIZE); const pixelKey = getPixelKey(x % CANVAS_CONFIG.DEFAULT_CHUNK_SIZE, y % CANVAS_CONFIG.DEFAULT_CHUNK_SIZE);
// Simple approach without pipeline for better compatibility // Store pixel with user information as JSON
await redisClient.hSet(chunkKey, pixelKey, color); const pixelData = {
color,
userId,
username: username || userId,
timestamp: Date.now()
};
await redisClient.hSet(chunkKey, pixelKey, JSON.stringify(pixelData));
// Update chunk metadata // Update chunk metadata
await redisClient.hSet(`${chunkKey}:meta`, { await redisClient.hSet(`${chunkKey}:meta`, {
@ -53,9 +60,16 @@ export class CanvasService {
return null; return null;
} }
const pixels = new Map<string, string>(); const pixels = new Map<string, any>();
for (const [key, color] of Object.entries(pixelData)) { for (const [key, data] of Object.entries(pixelData)) {
pixels.set(key, String(color)); try {
// Try to parse as JSON (new format with user info)
const parsedData = JSON.parse(String(data));
pixels.set(key, parsedData);
} catch {
// Fallback for old format (just color string)
pixels.set(key, { color: String(data), userId: null, username: null, timestamp: 0 });
}
} }
return { return {

View file

@ -151,7 +151,8 @@ export class WebSocketService {
message.x, message.x,
message.y, message.y,
message.color, message.color,
userId userId,
socket.data.username
); );
if (success) { if (success) {
@ -187,12 +188,15 @@ export class WebSocketService {
const chunk = await this.canvasService.getChunk(canvasId, message.chunkX, message.chunkY); const chunk = await this.canvasService.getChunk(canvasId, message.chunkX, message.chunkY);
if (chunk) { if (chunk) {
const pixels = Array.from(chunk.pixels.entries()).map(([key, color]) => { const pixels = Array.from(chunk.pixels.entries()).map(([key, pixelInfo]) => {
const [localX, localY] = key.split(',').map(Number); const [localX, localY] = key.split(',').map(Number);
return { return {
x: message.chunkX * 64 + localX, x: message.chunkX * 64 + localX,
y: message.chunkY * 64 + localY, y: message.chunkY * 64 + localY,
color color: pixelInfo.color,
userId: pixelInfo.userId,
username: pixelInfo.username,
timestamp: pixelInfo.timestamp
}; };
}); });

View file

@ -66,4 +66,39 @@
.scrollbar-hide::-webkit-scrollbar { .scrollbar-hide::-webkit-scrollbar {
display: none; display: none;
} }
/* Mobile-first touch optimizations */
.touch-target {
min-height: 44px;
min-width: 44px;
}
/* Ensure crisp rendering on all devices */
.crisp-edges {
image-rendering: pixelated;
image-rendering: -moz-crisp-edges;
image-rendering: crisp-edges;
image-rendering: -webkit-optimize-contrast;
}
/* Mobile modal centering improvements */
.mobile-modal {
position: fixed;
inset: 0;
display: flex;
align-items: center;
justify-content: center;
padding: 1rem;
z-index: 50;
}
/* Safe area support for modern mobile devices */
@supports (padding: max(0px)) {
.mobile-modal {
padding-top: max(1rem, env(safe-area-inset-top));
padding-bottom: max(1rem, env(safe-area-inset-bottom));
padding-left: max(1rem, env(safe-area-inset-left));
padding-right: max(1rem, env(safe-area-inset-right));
}
}
} }

View file

@ -15,6 +15,9 @@ export const metadata: Metadata = {
export const viewport = { export const viewport = {
width: 'device-width', width: 'device-width',
initialScale: 1, initialScale: 1,
maximumScale: 5,
userScalable: true,
viewportFit: 'cover',
}; };
export default function RootLayout({ export default function RootLayout({

View file

@ -127,25 +127,27 @@ export default function HomePage() {
const handleZoomIn = useCallback(() => { const handleZoomIn = useCallback(() => {
const newZoom = Math.min(viewport.zoom * 1.2, 5.0); const newZoom = Math.min(viewport.zoom * 1.2, 5.0);
// Zoom towards center of screen // Zoom towards center of viewport (canvas center)
if (typeof window !== 'undefined') { if (typeof window !== 'undefined') {
const centerX = window.innerWidth / 2; const screenCenterX = window.innerWidth / 2;
const centerY = window.innerHeight / 2; const screenCenterY = window.innerHeight / 2;
// Calculate world position at center of screen // Calculate what canvas coordinate is currently at screen center
const pixelSize = 32 * viewport.zoom; // BASE_PIXEL_SIZE * current zoom const BASE_PIXEL_SIZE = 32;
const worldX = (centerX + viewport.x) / pixelSize; const currentPixelSize = BASE_PIXEL_SIZE * viewport.zoom;
const worldY = (centerY + viewport.y) / pixelSize; const newPixelSize = BASE_PIXEL_SIZE * newZoom;
// Calculate new viewport position to keep center point stable const canvasCenterX = (screenCenterX + viewport.x) / currentPixelSize;
const newPixelSize = 32 * newZoom; const canvasCenterY = (screenCenterY + viewport.y) / currentPixelSize;
const newViewportX = worldX * newPixelSize - centerX;
const newViewportY = worldY * newPixelSize - centerY; // Calculate new viewport to keep same canvas point at screen center
const newViewportX = canvasCenterX * newPixelSize - screenCenterX;
const newViewportY = canvasCenterY * newPixelSize - screenCenterY;
setViewport({ setViewport({
zoom: newZoom, zoom: newZoom,
x: Math.max(0, newViewportX), x: newViewportX,
y: Math.max(0, newViewportY), y: newViewportY,
}); });
} else { } else {
setZoom(newZoom); setZoom(newZoom);
@ -155,25 +157,27 @@ export default function HomePage() {
const handleZoomOut = useCallback(() => { const handleZoomOut = useCallback(() => {
const newZoom = Math.max(viewport.zoom / 1.2, 0.1); const newZoom = Math.max(viewport.zoom / 1.2, 0.1);
// Zoom towards center of screen // Zoom towards center of viewport (canvas center)
if (typeof window !== 'undefined') { if (typeof window !== 'undefined') {
const centerX = window.innerWidth / 2; const screenCenterX = window.innerWidth / 2;
const centerY = window.innerHeight / 2; const screenCenterY = window.innerHeight / 2;
// Calculate world position at center of screen // Calculate what canvas coordinate is currently at screen center
const pixelSize = 32 * viewport.zoom; // BASE_PIXEL_SIZE * current zoom const BASE_PIXEL_SIZE = 32;
const worldX = (centerX + viewport.x) / pixelSize; const currentPixelSize = BASE_PIXEL_SIZE * viewport.zoom;
const worldY = (centerY + viewport.y) / pixelSize; const newPixelSize = BASE_PIXEL_SIZE * newZoom;
// Calculate new viewport position to keep center point stable const canvasCenterX = (screenCenterX + viewport.x) / currentPixelSize;
const newPixelSize = 32 * newZoom; const canvasCenterY = (screenCenterY + viewport.y) / currentPixelSize;
const newViewportX = worldX * newPixelSize - centerX;
const newViewportY = worldY * newPixelSize - centerY; // Calculate new viewport to keep same canvas point at screen center
const newViewportX = canvasCenterX * newPixelSize - screenCenterX;
const newViewportY = canvasCenterY * newPixelSize - screenCenterY;
setViewport({ setViewport({
zoom: newZoom, zoom: newZoom,
x: Math.max(0, newViewportX), x: newViewportX,
y: Math.max(0, newViewportY), y: newViewportY,
}); });
} else { } else {
setZoom(newZoom); setZoom(newZoom);
@ -281,8 +285,8 @@ export default function HomePage() {
{/* Connection Status */} {/* Connection Status */}
{!isConnected && ( {!isConnected && (
<ErrorBoundary> <ErrorBoundary>
<div className="fixed top-6 left-1/2 transform -translate-x-1/2 z-50"> <div className="fixed top-4 sm:top-6 left-1/2 transform -translate-x-1/2 z-50">
<div className="bg-red-500/90 backdrop-blur-md rounded-xl px-4 py-2 text-white text-sm"> <div className="bg-red-500/90 backdrop-blur-md rounded-xl px-3 sm:px-4 py-2 text-white text-xs sm:text-sm font-medium">
Connecting... Connecting...
</div> </div>
</div> </div>

View file

@ -37,7 +37,7 @@ export function CooldownTimer({ isActive, duration, onComplete }: CooldownTimerP
return ( return (
<motion.div <motion.div
className="fixed top-4 sm:top-6 left-1/2 transform -translate-x-1/2 z-50" className="fixed top-16 sm:top-20 left-1/2 transform -translate-x-1/2 z-50"
initial={{ opacity: 0, scale: 0.8 }} initial={{ opacity: 0, scale: 0.8 }}
animate={{ opacity: 1, scale: 1 }} animate={{ opacity: 1, scale: 1 }}
exit={{ opacity: 0, scale: 0.8 }} exit={{ opacity: 0, scale: 0.8 }}

View file

@ -19,7 +19,7 @@ export function CoordinateDisplay({
}: CoordinateDisplayProps) { }: CoordinateDisplayProps) {
return ( return (
<motion.div <motion.div
className="fixed bottom-4 left-4 sm:bottom-6 sm:left-6 z-50" className="fixed bottom-4 left-4 sm:bottom-6 sm:left-6 z-50 max-w-[calc(100vw-120px)] sm:max-w-none"
initial={{ opacity: 0, y: 30 }} initial={{ opacity: 0, y: 30 }}
animate={{ opacity: 1, y: 0 }} animate={{ opacity: 1, y: 0 }}
exit={{ opacity: 0, y: 30 }} exit={{ opacity: 0, y: 30 }}

View file

@ -68,8 +68,9 @@ export function PixelConfirmModal({
/> />
{/* Modal */} {/* Modal */}
<div className="fixed inset-0 z-50 flex items-center justify-center p-4 sm:p-6">
<motion.div <motion.div
className="fixed top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2 z-50" className="w-full max-w-[350px] sm:max-w-[400px]"
initial={{ opacity: 0, scale: 0.8, y: 40, rotateX: 10 }} initial={{ opacity: 0, scale: 0.8, y: 40, rotateX: 10 }}
animate={{ opacity: 1, scale: 1, y: 0, rotateX: 0 }} animate={{ opacity: 1, scale: 1, y: 0, rotateX: 0 }}
exit={{ opacity: 0, scale: 0.8, y: 40, rotateX: 10 }} exit={{ opacity: 0, scale: 0.8, y: 40, rotateX: 10 }}
@ -81,7 +82,7 @@ export function PixelConfirmModal({
}} }}
> >
<motion.div <motion.div
className="bg-white/5 backdrop-blur-2xl rounded-2xl sm:rounded-3xl p-4 sm:p-6 md:p-8 border border-white/20 w-[95vw] max-w-[350px] sm:max-w-[400px] shadow-2xl ring-1 ring-white/10 relative overflow-hidden" className="bg-white/5 backdrop-blur-2xl rounded-2xl sm:rounded-3xl p-4 sm:p-6 md:p-8 border border-white/20 shadow-2xl ring-1 ring-white/10 relative overflow-hidden mx-auto"
whileHover={{ whileHover={{
boxShadow: "0 20px 40px rgba(0,0,0,0.2)" boxShadow: "0 20px 40px rgba(0,0,0,0.2)"
}} }}
@ -134,11 +135,11 @@ export function PixelConfirmModal({
transition={{ delay: 0.2 }} transition={{ delay: 0.2 }}
> >
<h4 className="text-white/90 text-sm font-medium mb-4">Choose Color</h4> <h4 className="text-white/90 text-sm font-medium mb-4">Choose Color</h4>
<div className="grid grid-cols-6 sm:grid-cols-8 gap-2 sm:gap-3 max-w-xs sm:max-w-sm mx-auto"> <div className="grid grid-cols-6 sm:grid-cols-8 gap-3 sm:gap-4 max-w-xs sm:max-w-sm mx-auto">
{PIXEL_COLORS.map((paletteColor, index) => ( {PIXEL_COLORS.map((paletteColor, index) => (
<motion.button <motion.button
key={paletteColor} key={paletteColor}
className={`w-7 h-7 sm:w-8 sm:h-8 rounded-lg border-2 transition-all duration-200 ring-1 ring-white/10 touch-manipulation ${ className={`w-9 h-9 sm:w-10 sm:h-10 rounded-lg border-2 transition-all duration-200 ring-1 ring-white/10 touch-manipulation min-h-[36px] min-w-[36px] ${
selectedLocalColor === paletteColor selectedLocalColor === paletteColor
? 'border-white/80 scale-110 shadow-xl ring-white/30' ? 'border-white/80 scale-110 shadow-xl ring-white/30'
: 'border-white/30 hover:border-white/60 hover:ring-white/20' : 'border-white/30 hover:border-white/60 hover:ring-white/20'
@ -170,7 +171,7 @@ export function PixelConfirmModal({
transition={{ delay: 0.3 }} transition={{ delay: 0.3 }}
> >
<motion.button <motion.button
className="flex-1 px-6 py-3 bg-white/5 backdrop-blur-xl text-white rounded-xl border border-white/20 hover:bg-white/10 transition-all duration-200 font-medium ring-1 ring-white/10 relative overflow-hidden" className="flex-1 px-4 sm:px-6 py-4 sm:py-3 bg-white/5 backdrop-blur-xl text-white rounded-xl border border-white/20 hover:bg-white/10 active:bg-white/15 transition-all duration-200 font-medium ring-1 ring-white/10 relative overflow-hidden touch-manipulation min-h-[48px] text-sm sm:text-base"
onClick={onCancel} onClick={onCancel}
whileHover={{ whileHover={{
backgroundColor: "rgba(255,255,255,0.15)" backgroundColor: "rgba(255,255,255,0.15)"
@ -181,7 +182,7 @@ export function PixelConfirmModal({
Cancel Cancel
</motion.button> </motion.button>
<motion.button <motion.button
className="flex-1 px-6 py-3 bg-gradient-to-r from-blue-500/80 to-purple-600/80 backdrop-blur-xl text-white rounded-xl hover:from-blue-600/90 hover:to-purple-700/90 transition-all duration-200 font-medium shadow-xl ring-1 ring-white/20 relative overflow-hidden" className="flex-1 px-4 sm:px-6 py-4 sm:py-3 bg-gradient-to-r from-blue-500/80 to-purple-600/80 backdrop-blur-xl text-white rounded-xl hover:from-blue-600/90 hover:to-purple-700/90 active:from-blue-700/90 active:to-purple-800/90 transition-all duration-200 font-medium shadow-xl ring-1 ring-white/20 relative overflow-hidden touch-manipulation min-h-[48px] text-sm sm:text-base"
onClick={handleConfirm} onClick={handleConfirm}
whileHover={{ whileHover={{
boxShadow: "0 10px 25px rgba(0,0,0,0.4)" boxShadow: "0 10px 25px rgba(0,0,0,0.4)"
@ -195,6 +196,7 @@ export function PixelConfirmModal({
</div> </div>
</motion.div> </motion.div>
</motion.div> </motion.div>
</div>
</> </>
)} )}
</AnimatePresence> </AnimatePresence>

View file

@ -44,15 +44,16 @@ export function UsernameModal({
/> />
{/* Modal */} {/* Modal */}
<div className="fixed inset-0 z-50 flex items-center justify-center p-4 sm:p-6">
<motion.div <motion.div
className="fixed top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2 z-50" className="w-full max-w-[320px] sm:max-w-[350px]"
initial={{ opacity: 0, scale: 0.7, y: 30 }} initial={{ opacity: 0, scale: 0.7, y: 30 }}
animate={{ opacity: 1, scale: 1, y: 0 }} animate={{ opacity: 1, scale: 1, y: 0 }}
exit={{ opacity: 0, scale: 0.7, y: 30 }} exit={{ opacity: 0, scale: 0.7, y: 30 }}
transition={{ type: "spring", stiffness: 300, damping: 25 }} transition={{ type: "spring", stiffness: 300, damping: 25 }}
> >
<form onSubmit={handleSubmit}> <form onSubmit={handleSubmit}>
<div className="bg-white/5 backdrop-blur-2xl rounded-2xl sm:rounded-3xl p-4 sm:p-6 lg:p-8 border border-white/20 w-[95vw] max-w-[320px] sm:max-w-[350px] shadow-2xl ring-1 ring-white/10"> <div className="bg-white/5 backdrop-blur-2xl rounded-2xl sm:rounded-3xl p-4 sm:p-6 lg:p-8 border border-white/20 shadow-2xl ring-1 ring-white/10 mx-auto">
<div className="text-center"> <div className="text-center">
<motion.h3 <motion.h3
className="text-white text-lg sm:text-xl font-bold mb-2" className="text-white text-lg sm:text-xl font-bold mb-2"
@ -121,6 +122,7 @@ export function UsernameModal({
</div> </div>
</form> </form>
</motion.div> </motion.div>
</div>
</> </>
)} )}
</AnimatePresence> </AnimatePresence>

View file

@ -19,10 +19,10 @@ export function ZoomControls({ zoom, onZoomIn, onZoomOut }: ZoomControlsProps) {
<div className="flex flex-col gap-2 sm:gap-3"> <div className="flex flex-col gap-2 sm:gap-3">
{/* Zoom In Button */} {/* Zoom In Button */}
<motion.button <motion.button
className="w-12 h-12 sm:w-14 sm:h-14 bg-white/10 backdrop-blur-2xl rounded-full border border-white/20 shadow-lg ring-1 ring-white/10 flex items-center justify-center text-white text-xl sm:text-2xl font-bold hover:bg-white/20 active:bg-white/30 transition-all duration-200 select-none touch-manipulation" className="w-14 h-14 sm:w-16 sm:h-16 bg-white/10 backdrop-blur-2xl rounded-full border border-white/20 shadow-lg ring-1 ring-white/10 flex items-center justify-center text-white text-2xl sm:text-3xl font-bold hover:bg-white/20 active:bg-white/30 transition-all duration-200 select-none touch-manipulation min-h-[56px] min-w-[56px]"
onClick={onZoomIn} onClick={onZoomIn}
whileHover={{ scale: 1.1 }} whileHover={{ scale: 1.05 }}
whileTap={{ scale: 0.9 }} whileTap={{ scale: 0.95 }}
transition={{ type: "spring", stiffness: 400 }} transition={{ type: "spring", stiffness: 400 }}
> >
+ +
@ -30,10 +30,10 @@ export function ZoomControls({ zoom, onZoomIn, onZoomOut }: ZoomControlsProps) {
{/* Zoom Out Button */} {/* Zoom Out Button */}
<motion.button <motion.button
className="w-12 h-12 sm:w-14 sm:h-14 bg-white/10 backdrop-blur-2xl rounded-full border border-white/20 shadow-lg ring-1 ring-white/10 flex items-center justify-center text-white text-xl sm:text-2xl font-bold hover:bg-white/20 active:bg-white/30 transition-all duration-200 select-none touch-manipulation" className="w-14 h-14 sm:w-16 sm:h-16 bg-white/10 backdrop-blur-2xl rounded-full border border-white/20 shadow-lg ring-1 ring-white/10 flex items-center justify-center text-white text-2xl sm:text-3xl font-bold hover:bg-white/20 active:bg-white/30 transition-all duration-200 select-none touch-manipulation min-h-[56px] min-w-[56px]"
onClick={onZoomOut} onClick={onZoomOut}
whileHover={{ scale: 1.1 }} whileHover={{ scale: 1.05 }}
whileTap={{ scale: 0.9 }} whileTap={{ scale: 0.95 }}
transition={{ type: "spring", stiffness: 400 }} transition={{ type: "spring", stiffness: 400 }}
> >

View file

@ -57,7 +57,23 @@ export function useWebSocket({
}; };
useEffect(() => { useEffect(() => {
const backendUrl = process.env.NEXT_PUBLIC_BACKEND_URL || 'http://localhost:3001'; // Dynamically determine backend URL based on current hostname
const getBackendUrl = () => {
if (typeof window === 'undefined') return 'http://localhost:3001';
const currentHost = window.location.hostname;
const backendPort = '3001';
// If we have a custom backend URL from env, use it
if (process.env.NEXT_PUBLIC_BACKEND_URL) {
return process.env.NEXT_PUBLIC_BACKEND_URL;
}
// Otherwise, use the same hostname as frontend but with backend port
return `http://${currentHost}:${backendPort}`;
};
const backendUrl = getBackendUrl();
console.log('🔌 Initializing WebSocket connection to:', backendUrl); console.log('🔌 Initializing WebSocket connection to:', backendUrl);
const newSocket = io(backendUrl, { const newSocket = io(backendUrl, {

View file

@ -191,9 +191,17 @@ export const useCanvasStore = create<CanvasState>()(
// If center point is provided, zoom towards that point // If center point is provided, zoom towards that point
if (centerX !== undefined && centerY !== undefined) { if (centerX !== undefined && centerY !== undefined) {
const zoomFactor = clampedZoom / state.viewport.zoom; const BASE_PIXEL_SIZE = 32;
newViewport.x = centerX - (centerX - state.viewport.x) * zoomFactor; const currentPixelSize = BASE_PIXEL_SIZE * state.viewport.zoom;
newViewport.y = centerY - (centerY - state.viewport.y) * zoomFactor; const newPixelSize = BASE_PIXEL_SIZE * clampedZoom;
// Calculate what canvas coordinate is at the center point
const canvasCenterX = (centerX + state.viewport.x) / currentPixelSize;
const canvasCenterY = (centerY + state.viewport.y) / currentPixelSize;
// Calculate new viewport to keep same canvas point at center
newViewport.x = canvasCenterX * newPixelSize - centerX;
newViewport.y = canvasCenterY * newPixelSize - centerY;
} }
set({ viewport: newViewport }); set({ viewport: newViewport });