Compare commits
11 Commits
b051d9d2ef
...
production
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ede591c89e | ||
|
|
2defd7a4a9 | ||
|
|
9cc03bc475 | ||
|
|
832b468ea7 | ||
|
|
2a260abe0a | ||
|
|
80f2ac61ac | ||
|
|
a980ee8fcd | ||
|
|
ca2ed13446 | ||
|
|
20f0ccb85b | ||
|
|
59cc8ee154 | ||
|
|
40d9489395 |
@@ -1,5 +1,5 @@
|
|||||||
import { NextRequest, NextResponse } from 'next/server';
|
import { NextRequest, NextResponse } from 'next/server';
|
||||||
import { projectService } from '@/lib/prisma';
|
import { prisma, projectService } from '@/lib/prisma';
|
||||||
import { analyticsCache } from '@/lib/redis';
|
import { analyticsCache } from '@/lib/redis';
|
||||||
import { requireSessionAuth, checkRateLimit, getRateLimitHeaders } from '@/lib/auth';
|
import { requireSessionAuth, checkRateLimit, getRateLimitHeaders } from '@/lib/auth';
|
||||||
|
|
||||||
@@ -30,39 +30,100 @@ export async function GET(request: NextRequest) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Check cache first
|
// Check cache first (but allow bypass with cache-bust parameter)
|
||||||
|
const url = new URL(request.url);
|
||||||
|
const bypassCache = url.searchParams.get('nocache') === 'true';
|
||||||
|
|
||||||
|
if (!bypassCache) {
|
||||||
const cachedStats = await analyticsCache.getOverallStats();
|
const cachedStats = await analyticsCache.getOverallStats();
|
||||||
if (cachedStats) {
|
if (cachedStats) {
|
||||||
return NextResponse.json(cachedStats);
|
return NextResponse.json(cachedStats);
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Get analytics data
|
// Get analytics data
|
||||||
const projectsResult = await projectService.getAllProjects();
|
const projectsResult = await projectService.getAllProjects();
|
||||||
const projects = projectsResult.projects || projectsResult;
|
const projects = projectsResult.projects || projectsResult;
|
||||||
const performanceStats = await projectService.getPerformanceStats();
|
const performanceStats = await projectService.getPerformanceStats();
|
||||||
|
|
||||||
|
// Get real page view data from database
|
||||||
|
const allPageViews = await prisma.pageView.findMany({
|
||||||
|
where: {
|
||||||
|
timestamp: {
|
||||||
|
gte: new Date(Date.now() - 30 * 24 * 60 * 60 * 1000) // Last 30 days
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Calculate bounce rate (sessions with only 1 pageview)
|
||||||
|
const pageViewsByIP = allPageViews.reduce((acc, pv) => {
|
||||||
|
const ip = pv.ip || 'unknown';
|
||||||
|
if (!acc[ip]) acc[ip] = [];
|
||||||
|
acc[ip].push(pv);
|
||||||
|
return acc;
|
||||||
|
}, {} as Record<string, typeof allPageViews>);
|
||||||
|
|
||||||
|
const totalSessions = Object.keys(pageViewsByIP).length;
|
||||||
|
const bouncedSessions = Object.values(pageViewsByIP).filter(session => session.length === 1).length;
|
||||||
|
const bounceRate = totalSessions > 0 ? Math.round((bouncedSessions / totalSessions) * 100) : 0;
|
||||||
|
|
||||||
|
// Calculate average session duration (simplified - time between first and last pageview per IP)
|
||||||
|
const sessionDurations = Object.values(pageViewsByIP)
|
||||||
|
.map(session => {
|
||||||
|
if (session.length < 2) return 0;
|
||||||
|
const sorted = session.sort((a, b) => a.timestamp.getTime() - b.timestamp.getTime());
|
||||||
|
return sorted[sorted.length - 1].timestamp.getTime() - sorted[0].timestamp.getTime();
|
||||||
|
})
|
||||||
|
.filter(d => d > 0);
|
||||||
|
const avgSessionDuration = sessionDurations.length > 0
|
||||||
|
? Math.round(sessionDurations.reduce((a, b) => a + b, 0) / sessionDurations.length / 1000) // in seconds
|
||||||
|
: 0;
|
||||||
|
|
||||||
|
// Get total unique users (unique IPs)
|
||||||
|
const totalUsers = new Set(allPageViews.map(pv => pv.ip).filter(Boolean)).size;
|
||||||
|
|
||||||
|
// Calculate real views from PageView table
|
||||||
|
const viewsByProject = allPageViews.reduce((acc, pv) => {
|
||||||
|
if (pv.projectId) {
|
||||||
|
acc[pv.projectId] = (acc[pv.projectId] || 0) + 1;
|
||||||
|
}
|
||||||
|
return acc;
|
||||||
|
}, {} as Record<number, number>);
|
||||||
|
|
||||||
// Calculate analytics metrics
|
// Calculate analytics metrics
|
||||||
const analytics = {
|
const analytics = {
|
||||||
overview: {
|
overview: {
|
||||||
totalProjects: projects.length,
|
totalProjects: projects.length,
|
||||||
publishedProjects: projects.filter(p => p.published).length,
|
publishedProjects: projects.filter(p => p.published).length,
|
||||||
featuredProjects: projects.filter(p => p.featured).length,
|
featuredProjects: projects.filter(p => p.featured).length,
|
||||||
totalViews: projects.reduce((sum, p) => sum + ((p.analytics as Record<string, unknown>)?.views as number || 0), 0),
|
totalViews: allPageViews.length, // Real views from PageView table
|
||||||
totalLikes: projects.reduce((sum, p) => sum + ((p.analytics as Record<string, unknown>)?.likes as number || 0), 0),
|
totalLikes: 0, // Not implemented - no like buttons
|
||||||
totalShares: projects.reduce((sum, p) => sum + ((p.analytics as Record<string, unknown>)?.shares as number || 0), 0),
|
totalShares: 0, // Not implemented - no share buttons
|
||||||
avgLighthouse: projects.length > 0
|
avgLighthouse: (() => {
|
||||||
? Math.round(projects.reduce((sum, p) => sum + ((p.performance as Record<string, unknown>)?.lighthouse as number || 0), 0) / projects.length)
|
// Only calculate if we have real performance data (not defaults)
|
||||||
: 0
|
const projectsWithPerf = projects.filter(p => {
|
||||||
|
const perf = (p.performance as Record<string, unknown>) || {};
|
||||||
|
const lighthouse = perf.lighthouse as number || 0;
|
||||||
|
return lighthouse > 0; // Only count projects with actual performance data
|
||||||
|
});
|
||||||
|
return projectsWithPerf.length > 0
|
||||||
|
? Math.round(projectsWithPerf.reduce((sum, p) => sum + ((p.performance as Record<string, unknown>)?.lighthouse as number || 0), 0) / projectsWithPerf.length)
|
||||||
|
: 0;
|
||||||
|
})()
|
||||||
},
|
},
|
||||||
projects: projects.map(project => ({
|
projects: projects.map(project => ({
|
||||||
id: project.id,
|
id: project.id,
|
||||||
title: project.title,
|
title: project.title,
|
||||||
category: project.category,
|
category: project.category,
|
||||||
difficulty: project.difficulty,
|
difficulty: project.difficulty,
|
||||||
views: (project.analytics as Record<string, unknown>)?.views as number || 0,
|
views: viewsByProject[project.id] || 0, // Only real views from PageView table
|
||||||
likes: (project.analytics as Record<string, unknown>)?.likes as number || 0,
|
likes: 0, // Not implemented
|
||||||
shares: (project.analytics as Record<string, unknown>)?.shares as number || 0,
|
shares: 0, // Not implemented
|
||||||
lighthouse: (project.performance as Record<string, unknown>)?.lighthouse as number || 0,
|
lighthouse: (() => {
|
||||||
|
const perf = (project.performance as Record<string, unknown>) || {};
|
||||||
|
const score = perf.lighthouse as number || 0;
|
||||||
|
return score > 0 ? score : 0; // Only return if we have real data
|
||||||
|
})(),
|
||||||
published: project.published,
|
published: project.published,
|
||||||
featured: project.featured,
|
featured: project.featured,
|
||||||
createdAt: project.createdAt,
|
createdAt: project.createdAt,
|
||||||
@@ -71,10 +132,25 @@ export async function GET(request: NextRequest) {
|
|||||||
categories: performanceStats.byCategory,
|
categories: performanceStats.byCategory,
|
||||||
difficulties: performanceStats.byDifficulty,
|
difficulties: performanceStats.byDifficulty,
|
||||||
performance: {
|
performance: {
|
||||||
avgLighthouse: performanceStats.avgLighthouse,
|
avgLighthouse: (() => {
|
||||||
totalViews: performanceStats.totalViews,
|
const projectsWithPerf = projects.filter(p => {
|
||||||
totalLikes: performanceStats.totalLikes,
|
const perf = (p.performance as Record<string, unknown>) || {};
|
||||||
totalShares: performanceStats.totalShares
|
return (perf.lighthouse as number || 0) > 0;
|
||||||
|
});
|
||||||
|
return projectsWithPerf.length > 0
|
||||||
|
? Math.round(projectsWithPerf.reduce((sum, p) => sum + ((p.performance as Record<string, unknown>)?.lighthouse as number || 0), 0) / projectsWithPerf.length)
|
||||||
|
: 0;
|
||||||
|
})(),
|
||||||
|
totalViews: allPageViews.length, // Real total views
|
||||||
|
totalLikes: 0,
|
||||||
|
totalShares: 0
|
||||||
|
},
|
||||||
|
metrics: {
|
||||||
|
bounceRate,
|
||||||
|
avgSessionDuration,
|
||||||
|
pagesPerSession: totalSessions > 0 ? (allPageViews.length / totalSessions).toFixed(1) : '0',
|
||||||
|
newUsers: totalUsers,
|
||||||
|
totalUsers
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -24,8 +24,73 @@ export async function GET(request: NextRequest) {
|
|||||||
take: 1000 // Last 1000 interactions
|
take: 1000 // Last 1000 interactions
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Get all projects for performance data
|
||||||
|
const projects = await prisma.project.findMany();
|
||||||
|
|
||||||
|
// Calculate real performance metrics from projects
|
||||||
|
const projectsWithPerformance = projects.map(p => ({
|
||||||
|
id: p.id,
|
||||||
|
title: p.title,
|
||||||
|
lighthouse: ((p.performance as Record<string, unknown>)?.lighthouse as number) || 0,
|
||||||
|
loadTime: ((p.performance as Record<string, unknown>)?.loadTime as number) || 0,
|
||||||
|
fcp: ((p.performance as Record<string, unknown>)?.firstContentfulPaint as number) || 0,
|
||||||
|
lcp: ((p.performance as Record<string, unknown>)?.coreWebVitals as Record<string, unknown>)?.lcp as number || 0,
|
||||||
|
cls: ((p.performance as Record<string, unknown>)?.coreWebVitals as Record<string, unknown>)?.cls as number || 0
|
||||||
|
}));
|
||||||
|
|
||||||
|
// Calculate average lighthouse score (currently unused but kept for future use)
|
||||||
|
const _avgLighthouse = projectsWithPerformance.length > 0
|
||||||
|
? Math.round(projectsWithPerformance.reduce((sum, p) => sum + p.lighthouse, 0) / projectsWithPerformance.length)
|
||||||
|
: 0;
|
||||||
|
|
||||||
|
// Calculate bounce rate from page views
|
||||||
|
const pageViewsByIP = pageViews.reduce((acc, pv) => {
|
||||||
|
const ip = pv.ip || 'unknown';
|
||||||
|
if (!acc[ip]) acc[ip] = [];
|
||||||
|
acc[ip].push(pv);
|
||||||
|
return acc;
|
||||||
|
}, {} as Record<string, typeof pageViews>);
|
||||||
|
|
||||||
|
const totalSessions = Object.keys(pageViewsByIP).length;
|
||||||
|
const bouncedSessions = Object.values(pageViewsByIP).filter(session => session.length === 1).length;
|
||||||
|
const bounceRate = totalSessions > 0 ? Math.round((bouncedSessions / totalSessions) * 100) : 0;
|
||||||
|
|
||||||
|
// Calculate average session duration
|
||||||
|
const sessionDurations = Object.values(pageViewsByIP)
|
||||||
|
.map(session => {
|
||||||
|
if (session.length < 2) return 0;
|
||||||
|
const sorted = session.sort((a, b) => a.timestamp.getTime() - b.timestamp.getTime());
|
||||||
|
return sorted[sorted.length - 1].timestamp.getTime() - sorted[0].timestamp.getTime();
|
||||||
|
})
|
||||||
|
.filter(d => d > 0);
|
||||||
|
const avgSessionDuration = sessionDurations.length > 0
|
||||||
|
? Math.round(sessionDurations.reduce((a, b) => a + b, 0) / sessionDurations.length / 1000) // in seconds
|
||||||
|
: 0;
|
||||||
|
|
||||||
|
// Calculate pages per session
|
||||||
|
const pagesPerSession = totalSessions > 0 ? (pageViews.length / totalSessions).toFixed(1) : '0';
|
||||||
|
|
||||||
// Calculate performance metrics
|
// Calculate performance metrics
|
||||||
const performance = {
|
const performance = {
|
||||||
|
avgLighthouse: (() => {
|
||||||
|
const projectsWithPerf = projects.filter(p => {
|
||||||
|
const perf = (p.performance as Record<string, unknown>) || {};
|
||||||
|
return (perf.lighthouse as number || 0) > 0;
|
||||||
|
});
|
||||||
|
return projectsWithPerf.length > 0
|
||||||
|
? Math.round(projectsWithPerf.reduce((sum, p) => {
|
||||||
|
const perf = (p.performance as Record<string, unknown>) || {};
|
||||||
|
return sum + (perf.lighthouse as number || 0);
|
||||||
|
}, 0) / projectsWithPerf.length)
|
||||||
|
: 0;
|
||||||
|
})(),
|
||||||
|
totalViews: pageViews.length,
|
||||||
|
metrics: {
|
||||||
|
bounceRate,
|
||||||
|
avgSessionDuration: avgSessionDuration,
|
||||||
|
pagesPerSession: parseFloat(pagesPerSession),
|
||||||
|
newUsers: new Set(pageViews.map(pv => pv.ip).filter(Boolean)).size
|
||||||
|
},
|
||||||
pageViews: {
|
pageViews: {
|
||||||
total: pageViews.length,
|
total: pageViews.length,
|
||||||
last24h: pageViews.filter(pv => {
|
last24h: pageViews.filter(pv => {
|
||||||
|
|||||||
@@ -33,10 +33,15 @@ export async function POST(request: NextRequest) {
|
|||||||
|
|
||||||
switch (type) {
|
switch (type) {
|
||||||
case 'analytics':
|
case 'analytics':
|
||||||
// Reset all project analytics
|
// Reset all project analytics (view counts in project.analytics JSON)
|
||||||
await prisma.project.updateMany({
|
const projects = await prisma.project.findMany();
|
||||||
|
for (const project of projects) {
|
||||||
|
const analytics = (project.analytics as Record<string, unknown>) || {};
|
||||||
|
await prisma.project.update({
|
||||||
|
where: { id: project.id },
|
||||||
data: {
|
data: {
|
||||||
analytics: {
|
analytics: {
|
||||||
|
...analytics,
|
||||||
views: 0,
|
views: 0,
|
||||||
likes: 0,
|
likes: 0,
|
||||||
shares: 0,
|
shares: 0,
|
||||||
@@ -65,6 +70,7 @@ export async function POST(request: NextRequest) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
}
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case 'pageviews':
|
case 'pageviews':
|
||||||
@@ -78,10 +84,15 @@ export async function POST(request: NextRequest) {
|
|||||||
break;
|
break;
|
||||||
|
|
||||||
case 'performance':
|
case 'performance':
|
||||||
// Reset performance metrics
|
// Reset performance metrics (preserve structure)
|
||||||
await prisma.project.updateMany({
|
const projectsForPerf = await prisma.project.findMany();
|
||||||
|
for (const project of projectsForPerf) {
|
||||||
|
const perf = (project.performance as Record<string, unknown>) || {};
|
||||||
|
await prisma.project.update({
|
||||||
|
where: { id: project.id },
|
||||||
data: {
|
data: {
|
||||||
performance: {
|
performance: {
|
||||||
|
...perf,
|
||||||
lighthouse: 0,
|
lighthouse: 0,
|
||||||
loadTime: 0,
|
loadTime: 0,
|
||||||
firstContentfulPaint: 0,
|
firstContentfulPaint: 0,
|
||||||
@@ -104,15 +115,22 @@ export async function POST(request: NextRequest) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
}
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case 'all':
|
case 'all':
|
||||||
// Reset everything
|
// Reset everything
|
||||||
|
const allProjects = await prisma.project.findMany();
|
||||||
await Promise.all([
|
await Promise.all([
|
||||||
// Reset analytics
|
// Reset analytics and performance for each project (preserve structure)
|
||||||
prisma.project.updateMany({
|
...allProjects.map(project => {
|
||||||
|
const analytics = (project.analytics as Record<string, unknown>) || {};
|
||||||
|
const perf = (project.performance as Record<string, unknown>) || {};
|
||||||
|
return prisma.project.update({
|
||||||
|
where: { id: project.id },
|
||||||
data: {
|
data: {
|
||||||
analytics: {
|
analytics: {
|
||||||
|
...analytics,
|
||||||
views: 0,
|
views: 0,
|
||||||
likes: 0,
|
likes: 0,
|
||||||
shares: 0,
|
shares: 0,
|
||||||
@@ -138,13 +156,9 @@ export async function POST(request: NextRequest) {
|
|||||||
locationStats: {},
|
locationStats: {},
|
||||||
referrerStats: {},
|
referrerStats: {},
|
||||||
lastUpdated: new Date().toISOString()
|
lastUpdated: new Date().toISOString()
|
||||||
}
|
},
|
||||||
}
|
|
||||||
}),
|
|
||||||
// Reset performance
|
|
||||||
prisma.project.updateMany({
|
|
||||||
data: {
|
|
||||||
performance: {
|
performance: {
|
||||||
|
...perf,
|
||||||
lighthouse: 0,
|
lighthouse: 0,
|
||||||
loadTime: 0,
|
loadTime: 0,
|
||||||
firstContentfulPaint: 0,
|
firstContentfulPaint: 0,
|
||||||
@@ -166,6 +180,7 @@ export async function POST(request: NextRequest) {
|
|||||||
lastUpdated: new Date().toISOString()
|
lastUpdated: new Date().toISOString()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
});
|
||||||
}),
|
}),
|
||||||
// Clear tracking tables
|
// Clear tracking tables
|
||||||
prisma.pageView.deleteMany({}),
|
prisma.pageView.deleteMany({}),
|
||||||
|
|||||||
174
app/api/analytics/track/route.ts
Normal file
174
app/api/analytics/track/route.ts
Normal file
@@ -0,0 +1,174 @@
|
|||||||
|
import { NextRequest, NextResponse } from 'next/server';
|
||||||
|
import { prisma } from '@/lib/prisma';
|
||||||
|
import { checkRateLimit, getRateLimitHeaders } from '@/lib/auth';
|
||||||
|
|
||||||
|
export async function POST(request: NextRequest) {
|
||||||
|
try {
|
||||||
|
// Rate limiting
|
||||||
|
const ip = request.headers.get('x-forwarded-for') || request.headers.get('x-real-ip') || 'unknown';
|
||||||
|
if (!checkRateLimit(ip, 100, 60000)) { // 100 requests per minute for tracking
|
||||||
|
return new NextResponse(
|
||||||
|
JSON.stringify({ error: 'Rate limit exceeded' }),
|
||||||
|
{
|
||||||
|
status: 429,
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
...getRateLimitHeaders(ip, 100, 60000)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const body = await request.json();
|
||||||
|
const { type, projectId, page, performance, session } = body;
|
||||||
|
const userAgent = request.headers.get('user-agent') || undefined;
|
||||||
|
const referrer = request.headers.get('referer') || undefined;
|
||||||
|
|
||||||
|
// Track page view
|
||||||
|
if (type === 'pageview' && page) {
|
||||||
|
const projectIdNum = projectId ? parseInt(projectId.toString()) : null;
|
||||||
|
|
||||||
|
// Create page view record
|
||||||
|
await prisma.pageView.create({
|
||||||
|
data: {
|
||||||
|
projectId: projectIdNum,
|
||||||
|
page,
|
||||||
|
ip,
|
||||||
|
userAgent,
|
||||||
|
referrer
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Update project analytics if projectId exists
|
||||||
|
if (projectIdNum) {
|
||||||
|
const project = await prisma.project.findUnique({
|
||||||
|
where: { id: projectIdNum }
|
||||||
|
});
|
||||||
|
|
||||||
|
if (project) {
|
||||||
|
const analytics = (project.analytics as Record<string, unknown>) || {};
|
||||||
|
const currentViews = (analytics.views as number) || 0;
|
||||||
|
|
||||||
|
await prisma.project.update({
|
||||||
|
where: { id: projectIdNum },
|
||||||
|
data: {
|
||||||
|
analytics: {
|
||||||
|
...analytics,
|
||||||
|
views: currentViews + 1,
|
||||||
|
lastUpdated: new Date().toISOString()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Track performance metrics
|
||||||
|
if (type === 'performance' && performance) {
|
||||||
|
// Try to get projectId from page path if not provided
|
||||||
|
let projectIdNum: number | null = null;
|
||||||
|
if (projectId) {
|
||||||
|
projectIdNum = parseInt(projectId.toString());
|
||||||
|
} else if (page) {
|
||||||
|
// Try to extract from page path like /projects/123 or /projects/slug
|
||||||
|
const match = page.match(/\/projects\/(\d+)/);
|
||||||
|
if (match) {
|
||||||
|
projectIdNum = parseInt(match[1]);
|
||||||
|
} else {
|
||||||
|
// Try to find by slug
|
||||||
|
const slugMatch = page.match(/\/projects\/([^\/]+)/);
|
||||||
|
if (slugMatch) {
|
||||||
|
const slug = slugMatch[1];
|
||||||
|
const project = await prisma.project.findFirst({
|
||||||
|
where: {
|
||||||
|
OR: [
|
||||||
|
{ id: parseInt(slug) || 0 },
|
||||||
|
{ title: { contains: slug, mode: 'insensitive' } }
|
||||||
|
]
|
||||||
|
}
|
||||||
|
});
|
||||||
|
if (project) projectIdNum = project.id;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (projectIdNum) {
|
||||||
|
const project = await prisma.project.findUnique({
|
||||||
|
where: { id: projectIdNum }
|
||||||
|
});
|
||||||
|
|
||||||
|
if (project) {
|
||||||
|
const perf = (project.performance as Record<string, unknown>) || {};
|
||||||
|
const analytics = (project.analytics as Record<string, unknown>) || {};
|
||||||
|
|
||||||
|
// Calculate lighthouse score from web vitals
|
||||||
|
const lcp = performance.lcp || 0;
|
||||||
|
const fid = performance.fid || 0;
|
||||||
|
const cls = performance.cls || 0;
|
||||||
|
const fcp = performance.fcp || 0;
|
||||||
|
const ttfb = performance.ttfb || 0;
|
||||||
|
|
||||||
|
// Only calculate lighthouse score if we have real web vitals data
|
||||||
|
// Check if we have at least LCP and FCP (most important metrics)
|
||||||
|
if (lcp > 0 || fcp > 0) {
|
||||||
|
// Simple lighthouse score calculation (0-100)
|
||||||
|
let lighthouseScore = 100;
|
||||||
|
if (lcp > 4000) lighthouseScore -= 25;
|
||||||
|
else if (lcp > 2500) lighthouseScore -= 15;
|
||||||
|
if (fid > 300) lighthouseScore -= 25;
|
||||||
|
else if (fid > 100) lighthouseScore -= 15;
|
||||||
|
if (cls > 0.25) lighthouseScore -= 25;
|
||||||
|
else if (cls > 0.1) lighthouseScore -= 15;
|
||||||
|
if (fcp > 3000) lighthouseScore -= 15;
|
||||||
|
if (ttfb > 800) lighthouseScore -= 10;
|
||||||
|
|
||||||
|
lighthouseScore = Math.max(0, Math.min(100, lighthouseScore));
|
||||||
|
|
||||||
|
await prisma.project.update({
|
||||||
|
where: { id: projectIdNum },
|
||||||
|
data: {
|
||||||
|
performance: {
|
||||||
|
...perf,
|
||||||
|
lighthouse: lighthouseScore,
|
||||||
|
loadTime: performance.loadTime || perf.loadTime || 0,
|
||||||
|
firstContentfulPaint: fcp || perf.firstContentfulPaint || 0,
|
||||||
|
largestContentfulPaint: lcp || perf.largestContentfulPaint || 0,
|
||||||
|
cumulativeLayoutShift: cls || perf.cumulativeLayoutShift || 0,
|
||||||
|
totalBlockingTime: performance.tbt || perf.totalBlockingTime || 0,
|
||||||
|
speedIndex: performance.si || perf.speedIndex || 0,
|
||||||
|
coreWebVitals: {
|
||||||
|
lcp: lcp || (perf.coreWebVitals as Record<string, unknown>)?.lcp || 0,
|
||||||
|
fid: fid || (perf.coreWebVitals as Record<string, unknown>)?.fid || 0,
|
||||||
|
cls: cls || (perf.coreWebVitals as Record<string, unknown>)?.cls || 0
|
||||||
|
},
|
||||||
|
lastUpdated: new Date().toISOString()
|
||||||
|
},
|
||||||
|
analytics: {
|
||||||
|
...analytics,
|
||||||
|
lastUpdated: new Date().toISOString()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Track session data (for bounce rate calculation)
|
||||||
|
if (type === 'session' && session) {
|
||||||
|
// Store session data in a way that allows bounce rate calculation
|
||||||
|
// A bounce is a session with only one pageview
|
||||||
|
// We'll track this via PageView records and calculate bounce rate from them
|
||||||
|
}
|
||||||
|
|
||||||
|
return NextResponse.json({ success: true });
|
||||||
|
} catch (error) {
|
||||||
|
if (process.env.NODE_ENV === 'development') {
|
||||||
|
console.error('Analytics tracking error:', error);
|
||||||
|
}
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: 'Failed to track analytics' },
|
||||||
|
{ status: 500 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,25 +1,137 @@
|
|||||||
import { NextRequest, NextResponse } from 'next/server';
|
import { type NextRequest, NextResponse } from "next/server";
|
||||||
|
import { PrismaClientKnownRequestError } from '@prisma/client/runtime/library';
|
||||||
|
import { checkRateLimit, getRateLimitHeaders } from '@/lib/auth';
|
||||||
import { prisma } from '@/lib/prisma';
|
import { prisma } from '@/lib/prisma';
|
||||||
|
|
||||||
export async function GET(request: NextRequest) {
|
export async function GET(request: NextRequest) {
|
||||||
try {
|
try {
|
||||||
// In a real app, you would check for admin session here
|
const { searchParams } = new URL(request.url);
|
||||||
// For now, we trust the 'x-admin-request' header if it's set by the server-side component or middleware
|
const filter = searchParams.get('filter') || 'all';
|
||||||
// but typically you'd verify the session cookie/token
|
const limit = parseInt(searchParams.get('limit') || '50');
|
||||||
|
const offset = parseInt(searchParams.get('offset') || '0');
|
||||||
|
|
||||||
const contacts = await prisma.contact.findMany({
|
let whereClause = {};
|
||||||
orderBy: {
|
|
||||||
createdAt: 'desc',
|
switch (filter) {
|
||||||
},
|
case 'unread':
|
||||||
take: 100,
|
whereClause = { responded: false };
|
||||||
|
break;
|
||||||
|
case 'responded':
|
||||||
|
whereClause = { responded: true };
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
whereClause = {};
|
||||||
|
}
|
||||||
|
|
||||||
|
const [contacts, total] = await Promise.all([
|
||||||
|
prisma.contact.findMany({
|
||||||
|
where: whereClause,
|
||||||
|
orderBy: { createdAt: 'desc' },
|
||||||
|
take: limit,
|
||||||
|
skip: offset,
|
||||||
|
}),
|
||||||
|
prisma.contact.count({ where: whereClause })
|
||||||
|
]);
|
||||||
|
|
||||||
|
return NextResponse.json({
|
||||||
|
contacts,
|
||||||
|
total,
|
||||||
|
hasMore: offset + contacts.length < total
|
||||||
});
|
});
|
||||||
|
|
||||||
return NextResponse.json({ contacts });
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
|
// Handle missing database table gracefully
|
||||||
|
if (error instanceof PrismaClientKnownRequestError && error.code === 'P2021') {
|
||||||
|
if (process.env.NODE_ENV === 'development') {
|
||||||
|
console.warn('Contact table does not exist. Returning empty result.');
|
||||||
|
}
|
||||||
|
return NextResponse.json({
|
||||||
|
contacts: [],
|
||||||
|
total: 0,
|
||||||
|
hasMore: false
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (process.env.NODE_ENV === 'development') {
|
||||||
console.error('Error fetching contacts:', error);
|
console.error('Error fetching contacts:', error);
|
||||||
|
}
|
||||||
return NextResponse.json(
|
return NextResponse.json(
|
||||||
{ error: 'Failed to fetch contacts' },
|
{ error: 'Failed to fetch contacts' },
|
||||||
{ status: 500 }
|
{ status: 500 }
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export async function POST(request: NextRequest) {
|
||||||
|
try {
|
||||||
|
// Rate limiting for POST requests
|
||||||
|
const ip = request.headers.get('x-forwarded-for') || request.headers.get('x-real-ip') || 'unknown';
|
||||||
|
if (!checkRateLimit(ip, 5, 60000)) { // 5 requests per minute
|
||||||
|
return new NextResponse(
|
||||||
|
JSON.stringify({ error: 'Rate limit exceeded' }),
|
||||||
|
{
|
||||||
|
status: 429,
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
...getRateLimitHeaders(ip, 5, 60000)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const body = await request.json();
|
||||||
|
const { name, email, subject, message } = body;
|
||||||
|
|
||||||
|
// Validate required fields
|
||||||
|
if (!name || !email || !subject || !message) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: 'All fields are required' },
|
||||||
|
{ status: 400 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Validate email format
|
||||||
|
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
||||||
|
if (!emailRegex.test(email)) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: 'Invalid email format' },
|
||||||
|
{ status: 400 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const contact = await prisma.contact.create({
|
||||||
|
data: {
|
||||||
|
name,
|
||||||
|
email,
|
||||||
|
subject,
|
||||||
|
message,
|
||||||
|
responded: false
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
return NextResponse.json({
|
||||||
|
message: 'Contact created successfully',
|
||||||
|
contact
|
||||||
|
}, { status: 201 });
|
||||||
|
|
||||||
|
} catch (error) {
|
||||||
|
// Handle missing database table gracefully
|
||||||
|
if (error instanceof PrismaClientKnownRequestError && error.code === 'P2021') {
|
||||||
|
if (process.env.NODE_ENV === 'development') {
|
||||||
|
console.warn('Contact table does not exist.');
|
||||||
|
}
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: 'Database table not found. Please run migrations.' },
|
||||||
|
{ status: 503 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (process.env.NODE_ENV === 'development') {
|
||||||
|
console.error('Error creating contact:', error);
|
||||||
|
}
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: 'Failed to create contact' },
|
||||||
|
{ status: 500 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,139 +0,0 @@
|
|||||||
import { type NextRequest, NextResponse } from "next/server";
|
|
||||||
import { PrismaClient } from '@prisma/client';
|
|
||||||
import { PrismaClientKnownRequestError } from '@prisma/client/runtime/library';
|
|
||||||
import { checkRateLimit, getRateLimitHeaders } from '@/lib/auth';
|
|
||||||
|
|
||||||
const prisma = new PrismaClient();
|
|
||||||
|
|
||||||
export async function GET(request: NextRequest) {
|
|
||||||
try {
|
|
||||||
const { searchParams } = new URL(request.url);
|
|
||||||
const filter = searchParams.get('filter') || 'all';
|
|
||||||
const limit = parseInt(searchParams.get('limit') || '50');
|
|
||||||
const offset = parseInt(searchParams.get('offset') || '0');
|
|
||||||
|
|
||||||
let whereClause = {};
|
|
||||||
|
|
||||||
switch (filter) {
|
|
||||||
case 'unread':
|
|
||||||
whereClause = { responded: false };
|
|
||||||
break;
|
|
||||||
case 'responded':
|
|
||||||
whereClause = { responded: true };
|
|
||||||
break;
|
|
||||||
default:
|
|
||||||
whereClause = {};
|
|
||||||
}
|
|
||||||
|
|
||||||
const [contacts, total] = await Promise.all([
|
|
||||||
prisma.contact.findMany({
|
|
||||||
where: whereClause,
|
|
||||||
orderBy: { createdAt: 'desc' },
|
|
||||||
take: limit,
|
|
||||||
skip: offset,
|
|
||||||
}),
|
|
||||||
prisma.contact.count({ where: whereClause })
|
|
||||||
]);
|
|
||||||
|
|
||||||
return NextResponse.json({
|
|
||||||
contacts,
|
|
||||||
total,
|
|
||||||
hasMore: offset + contacts.length < total
|
|
||||||
});
|
|
||||||
|
|
||||||
} catch (error) {
|
|
||||||
// Handle missing database table gracefully
|
|
||||||
if (error instanceof PrismaClientKnownRequestError && error.code === 'P2021') {
|
|
||||||
if (process.env.NODE_ENV === 'development') {
|
|
||||||
console.warn('Contact table does not exist. Returning empty result.');
|
|
||||||
}
|
|
||||||
return NextResponse.json({
|
|
||||||
contacts: [],
|
|
||||||
total: 0,
|
|
||||||
hasMore: false
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
if (process.env.NODE_ENV === 'development') {
|
|
||||||
console.error('Error fetching contacts:', error);
|
|
||||||
}
|
|
||||||
return NextResponse.json(
|
|
||||||
{ error: 'Failed to fetch contacts' },
|
|
||||||
{ status: 500 }
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function POST(request: NextRequest) {
|
|
||||||
try {
|
|
||||||
// Rate limiting for POST requests
|
|
||||||
const ip = request.headers.get('x-forwarded-for') || request.headers.get('x-real-ip') || 'unknown';
|
|
||||||
if (!checkRateLimit(ip, 5, 60000)) { // 5 requests per minute
|
|
||||||
return new NextResponse(
|
|
||||||
JSON.stringify({ error: 'Rate limit exceeded' }),
|
|
||||||
{
|
|
||||||
status: 429,
|
|
||||||
headers: {
|
|
||||||
'Content-Type': 'application/json',
|
|
||||||
...getRateLimitHeaders(ip, 5, 60000)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
const body = await request.json();
|
|
||||||
const { name, email, subject, message } = body;
|
|
||||||
|
|
||||||
// Validate required fields
|
|
||||||
if (!name || !email || !subject || !message) {
|
|
||||||
return NextResponse.json(
|
|
||||||
{ error: 'All fields are required' },
|
|
||||||
{ status: 400 }
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Validate email format
|
|
||||||
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
|
||||||
if (!emailRegex.test(email)) {
|
|
||||||
return NextResponse.json(
|
|
||||||
{ error: 'Invalid email format' },
|
|
||||||
{ status: 400 }
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
const contact = await prisma.contact.create({
|
|
||||||
data: {
|
|
||||||
name,
|
|
||||||
email,
|
|
||||||
subject,
|
|
||||||
message,
|
|
||||||
responded: false
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
return NextResponse.json({
|
|
||||||
message: 'Contact created successfully',
|
|
||||||
contact
|
|
||||||
}, { status: 201 });
|
|
||||||
|
|
||||||
} catch (error) {
|
|
||||||
// Handle missing database table gracefully
|
|
||||||
if (error instanceof PrismaClientKnownRequestError && error.code === 'P2021') {
|
|
||||||
if (process.env.NODE_ENV === 'development') {
|
|
||||||
console.warn('Contact table does not exist.');
|
|
||||||
}
|
|
||||||
return NextResponse.json(
|
|
||||||
{ error: 'Database table not found. Please run migrations.' },
|
|
||||||
{ status: 503 }
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (process.env.NODE_ENV === 'development') {
|
|
||||||
console.error('Error creating contact:', error);
|
|
||||||
}
|
|
||||||
return NextResponse.json(
|
|
||||||
{ error: 'Failed to create contact' },
|
|
||||||
{ status: 500 }
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -50,61 +50,116 @@ interface StatusData {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export default function ActivityFeed() {
|
export default function ActivityFeed() {
|
||||||
|
const [mounted, setMounted] = useState(false);
|
||||||
const [data, setData] = useState<StatusData | null>(null);
|
const [data, setData] = useState<StatusData | null>(null);
|
||||||
const [isExpanded, setIsExpanded] = useState(true);
|
const [isExpanded, setIsExpanded] = useState(true);
|
||||||
const [isMinimized, setIsMinimized] = useState(false);
|
const [isMinimized, setIsMinimized] = useState(false);
|
||||||
const [hasActivity, setHasActivity] = useState(false);
|
const [hasActivity, setHasActivity] = useState(false);
|
||||||
const [isTrackingEnabled, setIsTrackingEnabled] = useState(() => {
|
// Initialize with default value to prevent hydration mismatch
|
||||||
// Check localStorage for tracking preference
|
const [isTrackingEnabled, setIsTrackingEnabled] = useState(true);
|
||||||
if (typeof window !== "undefined") {
|
|
||||||
const stored = localStorage.getItem("activityTrackingEnabled");
|
|
||||||
return stored !== "false"; // Default to true if not set
|
|
||||||
}
|
|
||||||
return true;
|
|
||||||
});
|
|
||||||
const [quote, setQuote] = useState<{
|
const [quote, setQuote] = useState<{
|
||||||
content: string;
|
content: string;
|
||||||
author: string;
|
author: string;
|
||||||
} | null>(null);
|
} | null>(null);
|
||||||
|
|
||||||
|
// Load tracking preference from localStorage after mount to prevent hydration mismatch
|
||||||
|
useEffect(() => {
|
||||||
|
setMounted(true);
|
||||||
|
if (typeof window !== "undefined") {
|
||||||
|
try {
|
||||||
|
const stored = localStorage.getItem("activityTrackingEnabled");
|
||||||
|
setIsTrackingEnabled(stored !== "false"); // Default to true if not set
|
||||||
|
} catch (error) {
|
||||||
|
// localStorage might be disabled
|
||||||
|
if (process.env.NODE_ENV === 'development') {
|
||||||
|
console.warn('Failed to read tracking preference:', error);
|
||||||
|
}
|
||||||
|
setIsTrackingEnabled(true); // Default to enabled
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}, []);
|
||||||
|
|
||||||
// Fetch data every 30 seconds (optimized to match server cache)
|
// Fetch data every 30 seconds (optimized to match server cache)
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
// Don't fetch if tracking is disabled
|
// Don't fetch if tracking is disabled or during SSR
|
||||||
if (!isTrackingEnabled) {
|
if (!isTrackingEnabled || typeof window === 'undefined') {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const fetchData = async () => {
|
const fetchData = async () => {
|
||||||
try {
|
try {
|
||||||
|
// Check if fetch is available (should be, but safety check)
|
||||||
|
if (typeof fetch === 'undefined') {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
// Add timestamp to prevent aggressive caching but respect server cache
|
// Add timestamp to prevent aggressive caching but respect server cache
|
||||||
const res = await fetch("/api/n8n/status", {
|
const res = await fetch("/api/n8n/status", {
|
||||||
cache: "default",
|
cache: "default",
|
||||||
|
}).catch((fetchError) => {
|
||||||
|
// Handle network errors gracefully
|
||||||
|
if (process.env.NODE_ENV === 'development') {
|
||||||
|
console.warn('ActivityFeed: Fetch failed:', fetchError);
|
||||||
|
}
|
||||||
|
return null;
|
||||||
});
|
});
|
||||||
if (!res.ok) return;
|
|
||||||
let json = await res.json();
|
|
||||||
|
|
||||||
|
if (!res || !res.ok) {
|
||||||
|
if (process.env.NODE_ENV === 'development' && res) {
|
||||||
|
console.warn('ActivityFeed: API returned non-OK status:', res.status);
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
let json: unknown;
|
||||||
|
try {
|
||||||
|
json = await res.json();
|
||||||
|
} catch (parseError) {
|
||||||
|
if (process.env.NODE_ENV === 'development') {
|
||||||
|
console.warn('ActivityFeed: Failed to parse JSON response:', parseError);
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (process.env.NODE_ENV === 'development') {
|
||||||
console.log("ActivityFeed data (raw):", json);
|
console.log("ActivityFeed data (raw):", json);
|
||||||
|
}
|
||||||
|
|
||||||
// Handle array response if API returns it wrapped
|
// Handle array response if API returns it wrapped
|
||||||
if (Array.isArray(json)) {
|
if (Array.isArray(json)) {
|
||||||
json = json[0] || null;
|
json = json[0] || null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (process.env.NODE_ENV === 'development') {
|
||||||
console.log("ActivityFeed data (processed):", json);
|
console.log("ActivityFeed data (processed):", json);
|
||||||
|
}
|
||||||
|
|
||||||
setData(json);
|
if (!json || typeof json !== 'object') {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Type assertion - API should return StatusData format
|
||||||
|
const activityData = json as StatusData;
|
||||||
|
setData(activityData);
|
||||||
|
|
||||||
// Check if there's any active activity
|
// Check if there's any active activity
|
||||||
const hasActiveActivity =
|
const coding = activityData.coding;
|
||||||
json.coding?.isActive ||
|
const gaming = activityData.gaming;
|
||||||
json.gaming?.isPlaying ||
|
const music = activityData.music;
|
||||||
json.music?.isPlaying;
|
|
||||||
|
|
||||||
|
const hasActiveActivity = Boolean(
|
||||||
|
coding?.isActive ||
|
||||||
|
gaming?.isPlaying ||
|
||||||
|
music?.isPlaying
|
||||||
|
);
|
||||||
|
|
||||||
|
if (process.env.NODE_ENV === 'development') {
|
||||||
console.log("Has activity:", hasActiveActivity, {
|
console.log("Has activity:", hasActiveActivity, {
|
||||||
coding: json.coding?.isActive,
|
coding: coding?.isActive,
|
||||||
gaming: json.gaming?.isPlaying,
|
gaming: gaming?.isPlaying,
|
||||||
music: json.music?.isPlaying,
|
music: music?.isPlaying,
|
||||||
});
|
});
|
||||||
|
}
|
||||||
|
|
||||||
setHasActivity(hasActiveActivity);
|
setHasActivity(hasActiveActivity);
|
||||||
|
|
||||||
@@ -112,8 +167,12 @@ export default function ActivityFeed() {
|
|||||||
if (hasActiveActivity && !isMinimized) {
|
if (hasActiveActivity && !isMinimized) {
|
||||||
setIsExpanded(true);
|
setIsExpanded(true);
|
||||||
}
|
}
|
||||||
} catch (e) {
|
} catch (error) {
|
||||||
console.error("Failed to fetch activity", e);
|
// Silently fail - activity feed is not critical
|
||||||
|
if (process.env.NODE_ENV === 'development') {
|
||||||
|
console.error("Failed to fetch activity:", error);
|
||||||
|
}
|
||||||
|
// Don't set error state - just fail silently
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -1385,7 +1444,14 @@ export default function ActivityFeed() {
|
|||||||
const newValue = !isTrackingEnabled;
|
const newValue = !isTrackingEnabled;
|
||||||
setIsTrackingEnabled(newValue);
|
setIsTrackingEnabled(newValue);
|
||||||
if (typeof window !== "undefined") {
|
if (typeof window !== "undefined") {
|
||||||
|
try {
|
||||||
localStorage.setItem("activityTrackingEnabled", String(newValue));
|
localStorage.setItem("activityTrackingEnabled", String(newValue));
|
||||||
|
} catch (error) {
|
||||||
|
// localStorage might be full or disabled
|
||||||
|
if (process.env.NODE_ENV === 'development') {
|
||||||
|
console.warn('Failed to save tracking preference:', error);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
// Clear data when disabling
|
// Clear data when disabling
|
||||||
if (!newValue) {
|
if (!newValue) {
|
||||||
@@ -1394,6 +1460,9 @@ export default function ActivityFeed() {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// Don't render until mounted to prevent hydration mismatch
|
||||||
|
if (!mounted) return null;
|
||||||
|
|
||||||
// Don't render if tracking is disabled and no data
|
// Don't render if tracking is disabled and no data
|
||||||
if (!isTrackingEnabled && !data) return null;
|
if (!isTrackingEnabled && !data) return null;
|
||||||
|
|
||||||
|
|||||||
@@ -20,21 +20,47 @@ interface Message {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export default function ChatWidget() {
|
export default function ChatWidget() {
|
||||||
|
// Prevent hydration mismatch by only rendering after mount
|
||||||
|
const [mounted, setMounted] = useState(false);
|
||||||
const [isOpen, setIsOpen] = useState(false);
|
const [isOpen, setIsOpen] = useState(false);
|
||||||
const [messages, setMessages] = useState<Message[]>([]);
|
const [messages, setMessages] = useState<Message[]>([]);
|
||||||
const [inputValue, setInputValue] = useState("");
|
const [inputValue, setInputValue] = useState("");
|
||||||
const [isLoading, setIsLoading] = useState(false);
|
const [isLoading, setIsLoading] = useState(false);
|
||||||
const [conversationId, setConversationId] = useState(() => {
|
const [conversationId, setConversationId] = useState<string>("default");
|
||||||
// Generate or retrieve conversation ID
|
|
||||||
if (typeof window !== "undefined") {
|
useEffect(() => {
|
||||||
|
setMounted(true);
|
||||||
|
// Generate or retrieve conversation ID only on client
|
||||||
|
try {
|
||||||
const stored = localStorage.getItem("chatSessionId");
|
const stored = localStorage.getItem("chatSessionId");
|
||||||
if (stored) return stored;
|
if (stored) {
|
||||||
const newId = crypto.randomUUID();
|
setConversationId(stored);
|
||||||
localStorage.setItem("chatSessionId", newId);
|
return;
|
||||||
return newId;
|
|
||||||
}
|
}
|
||||||
return "default";
|
|
||||||
|
// Generate UUID with fallback for browsers without crypto.randomUUID
|
||||||
|
let newId: string;
|
||||||
|
if (typeof crypto !== "undefined" && crypto.randomUUID) {
|
||||||
|
newId = crypto.randomUUID();
|
||||||
|
} else {
|
||||||
|
// Fallback UUID generation
|
||||||
|
newId = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
|
||||||
|
const r = Math.random() * 16 | 0;
|
||||||
|
const v = c === 'x' ? r : (r & 0x3 | 0x8);
|
||||||
|
return v.toString(16);
|
||||||
});
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
localStorage.setItem("chatSessionId", newId);
|
||||||
|
setConversationId(newId);
|
||||||
|
} catch (error) {
|
||||||
|
// localStorage might be disabled or full
|
||||||
|
if (process.env.NODE_ENV === 'development') {
|
||||||
|
console.warn('Failed to access localStorage for chat session:', error);
|
||||||
|
}
|
||||||
|
setConversationId(`session-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`);
|
||||||
|
}
|
||||||
|
}, []);
|
||||||
|
|
||||||
const messagesEndRef = useRef<HTMLDivElement>(null);
|
const messagesEndRef = useRef<HTMLDivElement>(null);
|
||||||
const inputRef = useRef<HTMLInputElement>(null);
|
const inputRef = useRef<HTMLInputElement>(null);
|
||||||
@@ -62,6 +88,7 @@ export default function ChatWidget() {
|
|||||||
// Load messages from localStorage
|
// Load messages from localStorage
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (typeof window !== "undefined") {
|
if (typeof window !== "undefined") {
|
||||||
|
try {
|
||||||
const stored = localStorage.getItem("chatMessages");
|
const stored = localStorage.getItem("chatMessages");
|
||||||
if (stored) {
|
if (stored) {
|
||||||
try {
|
try {
|
||||||
@@ -74,7 +101,24 @@ export default function ChatWidget() {
|
|||||||
})),
|
})),
|
||||||
);
|
);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.error("Failed to load chat history", e);
|
if (process.env.NODE_ENV === 'development') {
|
||||||
|
console.error("Failed to parse chat history", e);
|
||||||
|
}
|
||||||
|
// Clear corrupted data
|
||||||
|
try {
|
||||||
|
localStorage.removeItem("chatMessages");
|
||||||
|
} catch {
|
||||||
|
// Ignore cleanup errors
|
||||||
|
}
|
||||||
|
// Add welcome message
|
||||||
|
setMessages([
|
||||||
|
{
|
||||||
|
id: "welcome",
|
||||||
|
text: "Hi! I'm Dennis's AI assistant. Ask me anything about his skills, projects, or experience! 🚀",
|
||||||
|
sender: "bot",
|
||||||
|
timestamp: new Date(),
|
||||||
|
},
|
||||||
|
]);
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
// Add welcome message
|
// Add welcome message
|
||||||
@@ -87,13 +131,35 @@ export default function ChatWidget() {
|
|||||||
},
|
},
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
} catch (error) {
|
||||||
|
// localStorage might be disabled
|
||||||
|
if (process.env.NODE_ENV === 'development') {
|
||||||
|
console.warn("Failed to load chat history from localStorage:", error);
|
||||||
|
}
|
||||||
|
// Add welcome message anyway
|
||||||
|
setMessages([
|
||||||
|
{
|
||||||
|
id: "welcome",
|
||||||
|
text: "Hi! I'm Dennis's AI assistant. Ask me anything about his skills, projects, or experience! 🚀",
|
||||||
|
sender: "bot",
|
||||||
|
timestamp: new Date(),
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
// Save messages to localStorage
|
// Save messages to localStorage
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (typeof window !== "undefined" && messages.length > 0) {
|
if (typeof window !== "undefined" && messages.length > 0) {
|
||||||
|
try {
|
||||||
localStorage.setItem("chatMessages", JSON.stringify(messages));
|
localStorage.setItem("chatMessages", JSON.stringify(messages));
|
||||||
|
} catch (error) {
|
||||||
|
// localStorage might be full or disabled
|
||||||
|
if (process.env.NODE_ENV === 'development') {
|
||||||
|
console.warn("Failed to save chat messages to localStorage:", error);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}, [messages]);
|
}, [messages]);
|
||||||
|
|
||||||
@@ -204,6 +270,11 @@ export default function ChatWidget() {
|
|||||||
]);
|
]);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// Don't render until mounted to prevent hydration mismatch
|
||||||
|
if (!mounted) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
{/* Chat Button */}
|
{/* Chat Button */}
|
||||||
|
|||||||
@@ -1,13 +1,22 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import React, { useEffect, useState, Suspense, lazy } from "react";
|
import React, { useEffect, useState } from "react";
|
||||||
import { usePathname } from "next/navigation";
|
import { usePathname } from "next/navigation";
|
||||||
|
import dynamic from "next/dynamic";
|
||||||
import { ToastProvider } from "@/components/Toast";
|
import { ToastProvider } from "@/components/Toast";
|
||||||
|
import ErrorBoundary from "@/components/ErrorBoundary";
|
||||||
import { AnalyticsProvider } from "@/components/AnalyticsProvider";
|
import { AnalyticsProvider } from "@/components/AnalyticsProvider";
|
||||||
|
|
||||||
// Lazy load heavy components to avoid webpack issues
|
// Dynamic import with SSR disabled to avoid framer-motion issues
|
||||||
const BackgroundBlobs = lazy(() => import("@/components/BackgroundBlobs"));
|
const BackgroundBlobs = dynamic(() => import("@/components/BackgroundBlobs").catch(() => ({ default: () => null })), {
|
||||||
const ChatWidget = lazy(() => import("./ChatWidget"));
|
ssr: false,
|
||||||
|
loading: () => null,
|
||||||
|
});
|
||||||
|
|
||||||
|
const ChatWidget = dynamic(() => import("./ChatWidget").catch(() => ({ default: () => null })), {
|
||||||
|
ssr: false,
|
||||||
|
loading: () => null,
|
||||||
|
});
|
||||||
|
|
||||||
export default function ClientProviders({
|
export default function ClientProviders({
|
||||||
children,
|
children,
|
||||||
@@ -16,37 +25,61 @@ export default function ClientProviders({
|
|||||||
}) {
|
}) {
|
||||||
const [mounted, setMounted] = useState(false);
|
const [mounted, setMounted] = useState(false);
|
||||||
const [is404Page, setIs404Page] = useState(false);
|
const [is404Page, setIs404Page] = useState(false);
|
||||||
|
const pathname = usePathname();
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
setMounted(true);
|
setMounted(true);
|
||||||
// Check if we're on a 404 page by looking for the data attribute
|
// Check if we're on a 404 page by looking for the data attribute or pathname
|
||||||
const check404 = () => {
|
const check404 = () => {
|
||||||
if (typeof window !== "undefined") {
|
try {
|
||||||
|
if (typeof window !== "undefined" && typeof document !== "undefined") {
|
||||||
const has404Component = document.querySelector('[data-404-page]');
|
const has404Component = document.querySelector('[data-404-page]');
|
||||||
setIs404Page(!!has404Component);
|
const is404Path = pathname === '/404' || (window.location && (window.location.pathname === '/404' || window.location.pathname.includes('404')));
|
||||||
|
setIs404Page(!!has404Component || is404Path);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
// Silently fail - 404 detection is not critical
|
||||||
|
if (process.env.NODE_ENV === 'development') {
|
||||||
|
console.warn('Error checking 404 status:', error);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
// Check immediately and after a short delay
|
// Check immediately and after a short delay
|
||||||
|
try {
|
||||||
check404();
|
check404();
|
||||||
const timeout = setTimeout(check404, 100);
|
const timeout = setTimeout(check404, 100);
|
||||||
return () => clearTimeout(timeout);
|
const interval = setInterval(check404, 500);
|
||||||
}, []);
|
return () => {
|
||||||
|
try {
|
||||||
|
clearTimeout(timeout);
|
||||||
|
clearInterval(interval);
|
||||||
|
} catch {
|
||||||
|
// Silently fail during cleanup
|
||||||
|
}
|
||||||
|
};
|
||||||
|
} catch (error) {
|
||||||
|
// If setup fails, just return empty cleanup
|
||||||
|
if (process.env.NODE_ENV === 'development') {
|
||||||
|
console.warn('Error setting up 404 check:', error);
|
||||||
|
}
|
||||||
|
return () => {};
|
||||||
|
}
|
||||||
|
}, [pathname]);
|
||||||
|
|
||||||
|
// Wrap in multiple error boundaries to isolate failures
|
||||||
return (
|
return (
|
||||||
|
<ErrorBoundary>
|
||||||
|
<ErrorBoundary>
|
||||||
<AnalyticsProvider>
|
<AnalyticsProvider>
|
||||||
|
<ErrorBoundary>
|
||||||
<ToastProvider>
|
<ToastProvider>
|
||||||
{mounted && (
|
{mounted && <BackgroundBlobs />}
|
||||||
<Suspense fallback={null}>
|
|
||||||
<BackgroundBlobs />
|
|
||||||
</Suspense>
|
|
||||||
)}
|
|
||||||
<div className="relative z-10">{children}</div>
|
<div className="relative z-10">{children}</div>
|
||||||
{mounted && !is404Page && (
|
{mounted && !is404Page && <ChatWidget />}
|
||||||
<Suspense fallback={null}>
|
|
||||||
<ChatWidget />
|
|
||||||
</Suspense>
|
|
||||||
)}
|
|
||||||
</ToastProvider>
|
</ToastProvider>
|
||||||
|
</ErrorBoundary>
|
||||||
</AnalyticsProvider>
|
</AnalyticsProvider>
|
||||||
|
</ErrorBoundary>
|
||||||
|
</ErrorBoundary>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ export default function KernelPanic404() {
|
|||||||
const inputContainerRef = useRef<HTMLDivElement>(null);
|
const inputContainerRef = useRef<HTMLDivElement>(null);
|
||||||
const overlayRef = useRef<HTMLDivElement>(null);
|
const overlayRef = useRef<HTMLDivElement>(null);
|
||||||
const bodyRef = useRef<HTMLDivElement>(null); // We'll use a wrapper div instead of document.body for some effects if possible, but strict effects might need body.
|
const bodyRef = useRef<HTMLDivElement>(null); // We'll use a wrapper div instead of document.body for some effects if possible, but strict effects might need body.
|
||||||
|
const bootStartedRef = useRef(false);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
/* --- SYSTEM CORE --- */
|
/* --- SYSTEM CORE --- */
|
||||||
@@ -21,20 +22,24 @@ export default function KernelPanic404() {
|
|||||||
|
|
||||||
if (!output || !input || !inputContainer || !overlay) return;
|
if (!output || !input || !inputContainer || !overlay) return;
|
||||||
|
|
||||||
|
// Prevent double initialization - check if boot already started or output has content
|
||||||
|
if (bootStartedRef.current || output.children.length > 0) return;
|
||||||
|
bootStartedRef.current = true;
|
||||||
|
|
||||||
let audioCtx: AudioContext | null = null;
|
let audioCtx: AudioContext | null = null;
|
||||||
let systemFrozen = false;
|
let systemFrozen = false;
|
||||||
let currentMusic: any = null;
|
let currentMusic: { stop: () => void } | null = null;
|
||||||
let hawkinsActive = false;
|
let hawkinsActive = false;
|
||||||
let fsocietyActive = false;
|
let fsocietyActive = false;
|
||||||
|
|
||||||
// Timers storage to clear on unmount
|
// Timers storage to clear on unmount
|
||||||
const timers: (NodeJS.Timeout | number)[] = [];
|
const timers: (NodeJS.Timeout | number)[] = [];
|
||||||
const interval = (fn: Function, ms: number) => {
|
const interval = (fn: () => void, ms: number) => {
|
||||||
const id = setInterval(fn, ms);
|
const id = setInterval(fn, ms);
|
||||||
timers.push(id);
|
timers.push(id);
|
||||||
return id;
|
return id;
|
||||||
};
|
};
|
||||||
const timeout = (fn: Function, ms: number) => {
|
const timeout = (fn: () => void, ms: number) => {
|
||||||
const id = setTimeout(fn, ms);
|
const id = setTimeout(fn, ms);
|
||||||
timers.push(id);
|
timers.push(id);
|
||||||
return id;
|
return id;
|
||||||
@@ -44,7 +49,7 @@ export default function KernelPanic404() {
|
|||||||
function initAudio() {
|
function initAudio() {
|
||||||
if (!audioCtx) {
|
if (!audioCtx) {
|
||||||
const AudioContextClass =
|
const AudioContextClass =
|
||||||
window.AudioContext || (window as any).webkitAudioContext;
|
window.AudioContext || (window as typeof window & { webkitAudioContext?: typeof AudioContext }).webkitAudioContext;
|
||||||
if (AudioContextClass) {
|
if (AudioContextClass) {
|
||||||
audioCtx = new AudioContextClass();
|
audioCtx = new AudioContextClass();
|
||||||
}
|
}
|
||||||
@@ -439,6 +444,7 @@ export default function KernelPanic404() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/* --- FILE SYSTEM --- */
|
/* --- FILE SYSTEM --- */
|
||||||
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||||
const fileSystem: any = {
|
const fileSystem: any = {
|
||||||
home: {
|
home: {
|
||||||
type: "dir",
|
type: "dir",
|
||||||
@@ -546,7 +552,7 @@ export default function KernelPanic404() {
|
|||||||
|
|
||||||
let currentPath = fileSystem.home.children.guest;
|
let currentPath = fileSystem.home.children.guest;
|
||||||
let pathStr = "~";
|
let pathStr = "~";
|
||||||
let commandHistory: string[] = [];
|
const commandHistory: string[] = [];
|
||||||
let historyIndex = -1;
|
let historyIndex = -1;
|
||||||
|
|
||||||
/* --- UTILS --- */
|
/* --- UTILS --- */
|
||||||
@@ -554,12 +560,19 @@ export default function KernelPanic404() {
|
|||||||
if (!output) return;
|
if (!output) return;
|
||||||
const d = document.createElement("div");
|
const d = document.createElement("div");
|
||||||
d.innerHTML = text;
|
d.innerHTML = text;
|
||||||
if (type === "log-warn") d.style.color = "#ffb000";
|
// Default color for normal text - use setProperty with important to override globals.css
|
||||||
|
if (!type || (type !== "log-warn" && type !== "log-err" && type !== "alert" && type !== "log-sys" && type !== "log-k" && type !== "log-dim")) {
|
||||||
|
d.style.setProperty("color", "var(--phosphor)", "important");
|
||||||
|
}
|
||||||
|
if (type === "log-warn") d.style.setProperty("color", "#ffb000", "important");
|
||||||
if (type === "log-err" || type === "alert")
|
if (type === "log-err" || type === "alert")
|
||||||
d.style.color = "var(--alert)";
|
d.style.setProperty("color", "var(--alert)", "important");
|
||||||
if (type === "log-dim") d.style.opacity = "0.6";
|
if (type === "log-dim") {
|
||||||
if (type === "log-sys") d.style.color = "cyan";
|
d.style.opacity = "0.6";
|
||||||
if (type === "log-k") d.style.color = "#fff";
|
d.style.setProperty("color", "var(--phosphor)", "important");
|
||||||
|
}
|
||||||
|
if (type === "log-sys") d.style.setProperty("color", "cyan", "important");
|
||||||
|
if (type === "log-k") d.style.setProperty("color", "#fff", "important");
|
||||||
if (type === "pulse-red") d.classList.add("pulse-red");
|
if (type === "pulse-red") d.classList.add("pulse-red");
|
||||||
if (type === "fsociety-mask") d.classList.add("fsociety-mask");
|
if (type === "fsociety-mask") d.classList.add("fsociety-mask");
|
||||||
if (type === "memory-error") d.classList.add("memory-error");
|
if (type === "memory-error") d.classList.add("memory-error");
|
||||||
@@ -659,7 +672,7 @@ export default function KernelPanic404() {
|
|||||||
// Clear initial output
|
// Clear initial output
|
||||||
output!.innerHTML = "";
|
output!.innerHTML = "";
|
||||||
|
|
||||||
for (let msg of bootMessages) {
|
for (const msg of bootMessages) {
|
||||||
printLine(msg.t, msg.type);
|
printLine(msg.t, msg.type);
|
||||||
await sleep(msg.d);
|
await sleep(msg.d);
|
||||||
}
|
}
|
||||||
@@ -782,7 +795,7 @@ export default function KernelPanic404() {
|
|||||||
if (suggestions.length === 0) {
|
if (suggestions.length === 0) {
|
||||||
try {
|
try {
|
||||||
playSynth("beep");
|
playSynth("beep");
|
||||||
} catch (e) {}
|
} catch {}
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -805,13 +818,13 @@ export default function KernelPanic404() {
|
|||||||
input.setSelectionRange(input.value.length, input.value.length);
|
input.setSelectionRange(input.value.length, input.value.length);
|
||||||
try {
|
try {
|
||||||
playSynth("beep");
|
playSynth("beep");
|
||||||
} catch (e) {}
|
} catch {}
|
||||||
} else {
|
} else {
|
||||||
// Multiple matches
|
// Multiple matches
|
||||||
printLine(`Possible completions: ${suggestions.join(" ")}`, "log-dim");
|
printLine(`Possible completions: ${suggestions.join(" ")}`, "log-dim");
|
||||||
try {
|
try {
|
||||||
playSynth("beep");
|
playSynth("beep");
|
||||||
} catch (e) {}
|
} catch {}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -820,7 +833,7 @@ export default function KernelPanic404() {
|
|||||||
if (systemFrozen || !input) {
|
if (systemFrozen || !input) {
|
||||||
try {
|
try {
|
||||||
playSynth("beep");
|
playSynth("beep");
|
||||||
} catch (e) {}
|
} catch {}
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -859,7 +872,7 @@ export default function KernelPanic404() {
|
|||||||
args.includes("-a") || args.includes("-la") || args.includes("-l");
|
args.includes("-a") || args.includes("-la") || args.includes("-l");
|
||||||
const longFormat = args.includes("-l") || args.includes("-la");
|
const longFormat = args.includes("-l") || args.includes("-la");
|
||||||
|
|
||||||
let items = Object.keys(currentPath.children).filter(
|
const items = Object.keys(currentPath.children).filter(
|
||||||
(n) => !n.startsWith(".") || showHidden,
|
(n) => !n.startsWith(".") || showHidden,
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -1165,7 +1178,7 @@ export default function KernelPanic404() {
|
|||||||
overlay.style.display = "none";
|
overlay.style.display = "none";
|
||||||
overlay.innerHTML = "";
|
overlay.innerHTML = "";
|
||||||
|
|
||||||
const sporeInterval = interval(() => {
|
const _sporeInterval = interval(() => {
|
||||||
const spore = document.createElement("div");
|
const spore = document.createElement("div");
|
||||||
spore.className = "spore";
|
spore.className = "spore";
|
||||||
spore.style.left = Math.random() * 100 + "%";
|
spore.style.left = Math.random() * 100 + "%";
|
||||||
@@ -1175,7 +1188,7 @@ export default function KernelPanic404() {
|
|||||||
setTimeout(() => spore.remove(), 3000);
|
setTimeout(() => spore.remove(), 3000);
|
||||||
}, 300);
|
}, 300);
|
||||||
|
|
||||||
const glitchInterval = interval(() => {
|
const _glitchInterval = interval(() => {
|
||||||
if (!hawkinsActive) return;
|
if (!hawkinsActive) return;
|
||||||
body.style.filter = "hue-rotate(180deg) contrast(1.3) brightness(0.9)";
|
body.style.filter = "hue-rotate(180deg) contrast(1.3) brightness(0.9)";
|
||||||
setTimeout(
|
setTimeout(
|
||||||
@@ -1400,7 +1413,7 @@ export default function KernelPanic404() {
|
|||||||
|
|
||||||
try {
|
try {
|
||||||
playSynth("key");
|
playSynth("key");
|
||||||
} catch (e) {}
|
} catch {}
|
||||||
|
|
||||||
if (e.key === "ArrowUp" && historyIndex > 0) {
|
if (e.key === "ArrowUp" && historyIndex > 0) {
|
||||||
historyIndex--;
|
historyIndex--;
|
||||||
@@ -1442,18 +1455,40 @@ export default function KernelPanic404() {
|
|||||||
--phosphor: #33ff00;
|
--phosphor: #33ff00;
|
||||||
--phosphor-sec: #008f11;
|
--phosphor-sec: #008f11;
|
||||||
--alert: #ff3333;
|
--alert: #ff3333;
|
||||||
--font: "Courier New", Courier, monospace;
|
--font: 'Courier New', Courier, monospace;
|
||||||
|
}
|
||||||
|
|
||||||
|
* { margin: 0; padding: 0; box-sizing: border-box; }
|
||||||
|
|
||||||
|
body {
|
||||||
|
background-color: var(--bg-color);
|
||||||
|
margin: 0;
|
||||||
|
height: 100vh;
|
||||||
|
overflow: hidden;
|
||||||
|
font-family: var(--font);
|
||||||
|
color: var(--phosphor);
|
||||||
|
user-select: none;
|
||||||
|
cursor: default;
|
||||||
|
transition: filter 0.5s, transform 0.5s;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* --- CRT EFFECTS --- */
|
/* --- CRT EFFECTS --- */
|
||||||
.crt-wrap {
|
.crt-wrap {
|
||||||
width: 100%;
|
width: 100%;
|
||||||
height: 100vh;
|
height: 100%;
|
||||||
padding: 30px;
|
padding: 30px;
|
||||||
box-sizing: border-box;
|
box-sizing: border-box;
|
||||||
background: radial-gradient(circle at center, #111 0%, #000 100%);
|
background: radial-gradient(circle at center, #111 0%, #000 100%);
|
||||||
position: relative;
|
position: relative;
|
||||||
overflow: hidden;
|
}
|
||||||
|
|
||||||
|
/* Override globals.css div color rule for 404 page - must be very specific */
|
||||||
|
html body:has([data-404-page]) .crt-wrap,
|
||||||
|
html body:has([data-404-page]) .crt-wrap *,
|
||||||
|
html body:has([data-404-page]) #output,
|
||||||
|
html body:has([data-404-page]) #output div,
|
||||||
|
html body:has([data-404-page]) #output * {
|
||||||
|
color: var(--phosphor) !important;
|
||||||
}
|
}
|
||||||
|
|
||||||
.crt-wrap::before {
|
.crt-wrap::before {
|
||||||
@@ -1463,25 +1498,22 @@ export default function KernelPanic404() {
|
|||||||
left: 0;
|
left: 0;
|
||||||
width: 100%;
|
width: 100%;
|
||||||
height: 100%;
|
height: 100%;
|
||||||
background:
|
background: linear-gradient(rgba(18, 16, 16, 0) 50%, rgba(0, 0, 0, 0.25) 50%),
|
||||||
linear-gradient(rgba(18, 16, 16, 0) 50%, rgba(0, 0, 0, 0.25) 50%),
|
linear-gradient(90deg, rgba(255, 0, 0, 0.06), rgba(0, 255, 0, 0.02), rgba(0, 0, 255, 0.06));
|
||||||
linear-gradient(
|
background-size: 100% 4px, 3px 100%;
|
||||||
90deg,
|
|
||||||
rgba(255, 0, 0, 0.06),
|
|
||||||
rgba(0, 255, 0, 0.02),
|
|
||||||
rgba(0, 0, 255, 0.06)
|
|
||||||
);
|
|
||||||
background-size:
|
|
||||||
100% 4px,
|
|
||||||
3px 100%;
|
|
||||||
pointer-events: none;
|
pointer-events: none;
|
||||||
z-index: 90;
|
z-index: 90;
|
||||||
}
|
}
|
||||||
|
|
||||||
.glow {
|
.glow {
|
||||||
text-shadow:
|
text-shadow: 0 0 2px var(--phosphor-sec), 0 0 8px var(--phosphor);
|
||||||
0 0 2px var(--phosphor-sec),
|
}
|
||||||
0 0 8px var(--phosphor);
|
|
||||||
|
/* Hide chat widget on 404 page */
|
||||||
|
body:has([data-404-page]) [data-chat-widget] {
|
||||||
|
display: none !important;
|
||||||
|
visibility: hidden !important;
|
||||||
|
opacity: 0 !important;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* --- TERMINAL --- */
|
/* --- TERMINAL --- */
|
||||||
@@ -1502,7 +1534,6 @@ export default function KernelPanic404() {
|
|||||||
margin-bottom: 20px;
|
margin-bottom: 20px;
|
||||||
font-size: 1.1rem;
|
font-size: 1.1rem;
|
||||||
line-height: 1.4;
|
line-height: 1.4;
|
||||||
color: var(--phosphor);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#output::-webkit-scrollbar {
|
#output::-webkit-scrollbar {
|
||||||
@@ -1522,7 +1553,6 @@ export default function KernelPanic404() {
|
|||||||
margin-right: 10px;
|
margin-right: 10px;
|
||||||
font-weight: bold;
|
font-weight: bold;
|
||||||
white-space: nowrap;
|
white-space: nowrap;
|
||||||
color: var(--phosphor);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#cmd-input {
|
#cmd-input {
|
||||||
@@ -1847,7 +1877,7 @@ export default function KernelPanic404() {
|
|||||||
|
|
||||||
<div id="flash-overlay" ref={overlayRef}></div>
|
<div id="flash-overlay" ref={overlayRef}></div>
|
||||||
|
|
||||||
<div className="crt-wrap glow" ref={bodyRef}>
|
<div className="crt-wrap glow" ref={bodyRef} data-404-page="true">
|
||||||
<div id="terminal">
|
<div id="terminal">
|
||||||
<div id="output" ref={outputRef}></div>
|
<div id="output" ref={outputRef}></div>
|
||||||
<div
|
<div
|
||||||
|
|||||||
41
app/components/KernelPanic404Wrapper.tsx
Normal file
41
app/components/KernelPanic404Wrapper.tsx
Normal file
@@ -0,0 +1,41 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useEffect } from "react";
|
||||||
|
|
||||||
|
export default function KernelPanic404Wrapper() {
|
||||||
|
useEffect(() => {
|
||||||
|
// Ensure body and html don't interfere
|
||||||
|
document.body.style.background = "#020202";
|
||||||
|
document.body.style.color = "#33ff00";
|
||||||
|
document.documentElement.style.background = "#020202";
|
||||||
|
document.documentElement.style.color = "#33ff00";
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
// Cleanup
|
||||||
|
document.body.style.background = "";
|
||||||
|
document.body.style.color = "";
|
||||||
|
document.documentElement.style.background = "";
|
||||||
|
document.documentElement.style.color = "";
|
||||||
|
};
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<iframe
|
||||||
|
src="/404-terminal.html"
|
||||||
|
style={{
|
||||||
|
position: "fixed",
|
||||||
|
top: 0,
|
||||||
|
left: 0,
|
||||||
|
width: "100vw",
|
||||||
|
height: "100vh",
|
||||||
|
border: "none",
|
||||||
|
zIndex: 9999,
|
||||||
|
margin: 0,
|
||||||
|
padding: 0,
|
||||||
|
backgroundColor: "#020202",
|
||||||
|
}}
|
||||||
|
data-404-page="true"
|
||||||
|
allowTransparency={false}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
import { useState, useEffect } from "react";
|
import { useState, useEffect } from "react";
|
||||||
import { motion, Variants } from "framer-motion";
|
import { motion, Variants } from "framer-motion";
|
||||||
import { ExternalLink, Github, Layers, ArrowRight, ArrowLeft, Calendar } from "lucide-react";
|
import { ExternalLink, Github, ArrowRight, Calendar } from "lucide-react";
|
||||||
import Link from "next/link";
|
import Link from "next/link";
|
||||||
import Image from "next/image";
|
import Image from "next/image";
|
||||||
|
|
||||||
|
|||||||
@@ -29,6 +29,7 @@ import {
|
|||||||
Github,
|
Github,
|
||||||
Tag,
|
Tag,
|
||||||
} from "lucide-react";
|
} from "lucide-react";
|
||||||
|
import { useToast } from "@/components/Toast";
|
||||||
|
|
||||||
interface Project {
|
interface Project {
|
||||||
id: string;
|
id: string;
|
||||||
@@ -50,6 +51,7 @@ function EditorPageContent() {
|
|||||||
const searchParams = useSearchParams();
|
const searchParams = useSearchParams();
|
||||||
const projectId = searchParams.get("id");
|
const projectId = searchParams.get("id");
|
||||||
const contentRef = useRef<HTMLDivElement>(null);
|
const contentRef = useRef<HTMLDivElement>(null);
|
||||||
|
const { showSuccess, showError } = useToast();
|
||||||
|
|
||||||
const [, setProject] = useState<Project | null>(null);
|
const [, setProject] = useState<Project | null>(null);
|
||||||
const [isAuthenticated, setIsAuthenticated] = useState(false);
|
const [isAuthenticated, setIsAuthenticated] = useState(false);
|
||||||
@@ -57,7 +59,11 @@ function EditorPageContent() {
|
|||||||
const [isSaving, setIsSaving] = useState(false);
|
const [isSaving, setIsSaving] = useState(false);
|
||||||
const [isCreating, setIsCreating] = useState(!projectId);
|
const [isCreating, setIsCreating] = useState(!projectId);
|
||||||
const [showPreview, setShowPreview] = useState(false);
|
const [showPreview, setShowPreview] = useState(false);
|
||||||
const [isTyping, setIsTyping] = useState(false);
|
const [_isTyping, setIsTyping] = useState(false);
|
||||||
|
const [history, setHistory] = useState<typeof formData[]>([]);
|
||||||
|
const [historyIndex, setHistoryIndex] = useState(-1);
|
||||||
|
const [originalFormData, setOriginalFormData] = useState<typeof formData | null>(null);
|
||||||
|
const shouldUpdateContentRef = useRef(true);
|
||||||
|
|
||||||
// Form state
|
// Form state
|
||||||
const [formData, setFormData] = useState({
|
const [formData, setFormData] = useState({
|
||||||
@@ -84,8 +90,7 @@ function EditorPageContent() {
|
|||||||
);
|
);
|
||||||
|
|
||||||
if (foundProject) {
|
if (foundProject) {
|
||||||
setProject(foundProject);
|
const initialData = {
|
||||||
setFormData({
|
|
||||||
title: foundProject.title || "",
|
title: foundProject.title || "",
|
||||||
description: foundProject.description || "",
|
description: foundProject.description || "",
|
||||||
content: foundProject.content || "",
|
content: foundProject.content || "",
|
||||||
@@ -96,7 +101,19 @@ function EditorPageContent() {
|
|||||||
github: foundProject.github || "",
|
github: foundProject.github || "",
|
||||||
live: foundProject.live || "",
|
live: foundProject.live || "",
|
||||||
image: foundProject.image || "",
|
image: foundProject.image || "",
|
||||||
});
|
};
|
||||||
|
setProject(foundProject);
|
||||||
|
setFormData(initialData);
|
||||||
|
setOriginalFormData(initialData);
|
||||||
|
setHistory([initialData]);
|
||||||
|
setHistoryIndex(0);
|
||||||
|
shouldUpdateContentRef.current = true;
|
||||||
|
// Initialize contentEditable after state update
|
||||||
|
setTimeout(() => {
|
||||||
|
if (contentRef.current && initialData.content) {
|
||||||
|
contentRef.current.textContent = initialData.content;
|
||||||
|
}
|
||||||
|
}, 0);
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
if (process.env.NODE_ENV === "development") {
|
if (process.env.NODE_ENV === "development") {
|
||||||
@@ -126,6 +143,30 @@ function EditorPageContent() {
|
|||||||
await loadProject(projectId);
|
await loadProject(projectId);
|
||||||
} else {
|
} else {
|
||||||
setIsCreating(true);
|
setIsCreating(true);
|
||||||
|
// Initialize history for new project
|
||||||
|
const initialData = {
|
||||||
|
title: "",
|
||||||
|
description: "",
|
||||||
|
content: "",
|
||||||
|
category: "web",
|
||||||
|
tags: [],
|
||||||
|
featured: false,
|
||||||
|
published: false,
|
||||||
|
github: "",
|
||||||
|
live: "",
|
||||||
|
image: "",
|
||||||
|
};
|
||||||
|
setFormData(initialData);
|
||||||
|
setOriginalFormData(initialData);
|
||||||
|
setHistory([initialData]);
|
||||||
|
setHistoryIndex(0);
|
||||||
|
shouldUpdateContentRef.current = true;
|
||||||
|
// Initialize contentEditable after state update
|
||||||
|
setTimeout(() => {
|
||||||
|
if (contentRef.current) {
|
||||||
|
contentRef.current.textContent = "";
|
||||||
|
}
|
||||||
|
}, 0);
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
setIsAuthenticated(false);
|
setIsAuthenticated(false);
|
||||||
@@ -143,18 +184,20 @@ function EditorPageContent() {
|
|||||||
init();
|
init();
|
||||||
}, [projectId, loadProject]);
|
}, [projectId, loadProject]);
|
||||||
|
|
||||||
const handleSave = async () => {
|
const handleSave = useCallback(async () => {
|
||||||
try {
|
try {
|
||||||
setIsSaving(true);
|
setIsSaving(true);
|
||||||
|
|
||||||
// Validate required fields
|
// Validate required fields
|
||||||
if (!formData.title.trim()) {
|
if (!formData.title.trim()) {
|
||||||
alert("Please enter a project title");
|
showError("Validation Error", "Please enter a project title");
|
||||||
|
setIsSaving(false);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!formData.description.trim()) {
|
if (!formData.description.trim()) {
|
||||||
alert("Please enter a project description");
|
showError("Validation Error", "Please enter a project description");
|
||||||
|
setIsSaving(false);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -205,39 +248,155 @@ function EditorPageContent() {
|
|||||||
image: savedProject.imageUrl || "",
|
image: savedProject.imageUrl || "",
|
||||||
}));
|
}));
|
||||||
|
|
||||||
// Show success and redirect
|
// Show success toast (smaller, smoother)
|
||||||
alert("Project saved successfully!");
|
showSuccess("Saved", `"${savedProject.title}" saved`);
|
||||||
setTimeout(() => {
|
|
||||||
window.location.href = "/manage";
|
// Update project ID if it was a new project
|
||||||
}, 1000);
|
if (!projectId && savedProject.id) {
|
||||||
|
const newUrl = `/editor?id=${savedProject.id}`;
|
||||||
|
window.history.replaceState({}, '', newUrl);
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
const errorData = await response.json();
|
const errorData = await response.json();
|
||||||
if (process.env.NODE_ENV === "development") {
|
if (process.env.NODE_ENV === "development") {
|
||||||
console.error("Error saving project:", response.status, errorData);
|
console.error("Error saving project:", response.status, errorData);
|
||||||
}
|
}
|
||||||
alert(`Error saving project: ${errorData.error || "Unknown error"}`);
|
showError("Save Failed", errorData.error || "Failed to save");
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
if (process.env.NODE_ENV === "development") {
|
if (process.env.NODE_ENV === "development") {
|
||||||
console.error("Error saving project:", error);
|
console.error("Error saving project:", error);
|
||||||
}
|
}
|
||||||
alert(
|
showError(
|
||||||
`Error saving project: ${error instanceof Error ? error.message : "Unknown error"}`,
|
"Save Failed",
|
||||||
|
error instanceof Error ? error.message : "Failed to save"
|
||||||
);
|
);
|
||||||
} finally {
|
} finally {
|
||||||
setIsSaving(false);
|
setIsSaving(false);
|
||||||
}
|
}
|
||||||
};
|
}, [projectId, formData, showSuccess, showError]);
|
||||||
|
|
||||||
const handleInputChange = (
|
const handleInputChange = (
|
||||||
field: string,
|
field: string,
|
||||||
value: string | boolean | string[],
|
value: string | boolean | string[],
|
||||||
) => {
|
) => {
|
||||||
setFormData((prev) => ({
|
setFormData((prev) => {
|
||||||
|
const newData = {
|
||||||
...prev,
|
...prev,
|
||||||
[field]: value,
|
[field]: value,
|
||||||
}));
|
|
||||||
};
|
};
|
||||||
|
// Add to history for undo/redo
|
||||||
|
setHistory((hist) => {
|
||||||
|
const newHistory = hist.slice(0, historyIndex + 1);
|
||||||
|
newHistory.push(newData);
|
||||||
|
// Keep only last 50 history entries
|
||||||
|
const trimmedHistory = newHistory.slice(-50);
|
||||||
|
setHistoryIndex(trimmedHistory.length - 1);
|
||||||
|
return trimmedHistory;
|
||||||
|
});
|
||||||
|
return newData;
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleUndo = useCallback(() => {
|
||||||
|
setHistoryIndex((currentIndex) => {
|
||||||
|
if (currentIndex > 0) {
|
||||||
|
const newIndex = currentIndex - 1;
|
||||||
|
shouldUpdateContentRef.current = true;
|
||||||
|
setFormData(history[newIndex]);
|
||||||
|
return newIndex;
|
||||||
|
}
|
||||||
|
return currentIndex;
|
||||||
|
});
|
||||||
|
}, [history]);
|
||||||
|
|
||||||
|
const handleRedo = useCallback(() => {
|
||||||
|
setHistoryIndex((currentIndex) => {
|
||||||
|
if (currentIndex < history.length - 1) {
|
||||||
|
const newIndex = currentIndex + 1;
|
||||||
|
shouldUpdateContentRef.current = true;
|
||||||
|
setFormData(history[newIndex]);
|
||||||
|
return newIndex;
|
||||||
|
}
|
||||||
|
return currentIndex;
|
||||||
|
});
|
||||||
|
}, [history]);
|
||||||
|
|
||||||
|
const handleRevert = useCallback(() => {
|
||||||
|
if (originalFormData) {
|
||||||
|
if (confirm("Are you sure you want to revert all changes? This cannot be undone.")) {
|
||||||
|
shouldUpdateContentRef.current = true;
|
||||||
|
setFormData(originalFormData);
|
||||||
|
setHistory([originalFormData]);
|
||||||
|
setHistoryIndex(0);
|
||||||
|
}
|
||||||
|
} else if (projectId) {
|
||||||
|
// Reload from server
|
||||||
|
if (confirm("Are you sure you want to revert all changes? This will reload the project from the server.")) {
|
||||||
|
shouldUpdateContentRef.current = true;
|
||||||
|
loadProject(projectId);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}, [originalFormData, projectId, loadProject]);
|
||||||
|
|
||||||
|
// Sync contentEditable when formData.content changes externally (undo/redo/revert)
|
||||||
|
useEffect(() => {
|
||||||
|
if (contentRef.current && shouldUpdateContentRef.current) {
|
||||||
|
const currentContent = contentRef.current.textContent || "";
|
||||||
|
if (currentContent !== formData.content) {
|
||||||
|
contentRef.current.textContent = formData.content;
|
||||||
|
}
|
||||||
|
shouldUpdateContentRef.current = false;
|
||||||
|
}
|
||||||
|
}, [formData.content]);
|
||||||
|
|
||||||
|
// Initialize contentEditable when formData.content is set and editor is empty
|
||||||
|
useEffect(() => {
|
||||||
|
if (contentRef.current) {
|
||||||
|
const currentText = contentRef.current.textContent || "";
|
||||||
|
// Initialize if editor is empty and we have content, or if content changed externally
|
||||||
|
if ((!currentText && formData.content) || (shouldUpdateContentRef.current && currentText !== formData.content)) {
|
||||||
|
contentRef.current.textContent = formData.content;
|
||||||
|
shouldUpdateContentRef.current = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}, [formData.content]);
|
||||||
|
|
||||||
|
// Keyboard shortcuts
|
||||||
|
useEffect(() => {
|
||||||
|
const handleKeyDown = (e: KeyboardEvent) => {
|
||||||
|
// Ctrl+S or Cmd+S - Save
|
||||||
|
if ((e.ctrlKey || e.metaKey) && e.key === 's') {
|
||||||
|
e.preventDefault();
|
||||||
|
if (!isSaving) {
|
||||||
|
handleSave();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Ctrl+Z or Cmd+Z - Undo
|
||||||
|
if ((e.ctrlKey || e.metaKey) && e.key === 'z' && !e.shiftKey) {
|
||||||
|
e.preventDefault();
|
||||||
|
handleUndo();
|
||||||
|
}
|
||||||
|
// Ctrl+Shift+Z or Cmd+Shift+Z - Redo
|
||||||
|
if ((e.ctrlKey || e.metaKey) && e.key === 'z' && e.shiftKey) {
|
||||||
|
e.preventDefault();
|
||||||
|
handleRedo();
|
||||||
|
}
|
||||||
|
// Ctrl+R or Cmd+R - Revert (but allow browser refresh if not in editor)
|
||||||
|
if ((e.ctrlKey || e.metaKey) && e.key === 'r') {
|
||||||
|
const target = e.target as HTMLElement;
|
||||||
|
if (target.isContentEditable || target.tagName === 'INPUT' || target.tagName === 'TEXTAREA') {
|
||||||
|
e.preventDefault();
|
||||||
|
handleRevert();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
window.addEventListener('keydown', handleKeyDown);
|
||||||
|
return () => {
|
||||||
|
window.removeEventListener('keydown', handleKeyDown);
|
||||||
|
};
|
||||||
|
}, [isSaving, handleSave, handleUndo, handleRedo, handleRevert]);
|
||||||
|
|
||||||
const handleTagsChange = (tagsString: string) => {
|
const handleTagsChange = (tagsString: string) => {
|
||||||
const tags = tagsString
|
const tags = tagsString
|
||||||
@@ -358,7 +517,7 @@ function EditorPageContent() {
|
|||||||
<motion.div
|
<motion.div
|
||||||
animate={{ rotate: 360 }}
|
animate={{ rotate: 360 }}
|
||||||
transition={{ duration: 1, repeat: Infinity, ease: "linear" }}
|
transition={{ duration: 1, repeat: Infinity, ease: "linear" }}
|
||||||
className="w-12 h-12 border-3 border-blue-500 border-t-transparent rounded-full mx-auto mb-6"
|
className="w-12 h-12 border-3 border-stone-500 border-t-transparent rounded-full mx-auto mb-6"
|
||||||
/>
|
/>
|
||||||
<h2 className="text-xl font-semibold gradient-text mb-2">
|
<h2 className="text-xl font-semibold gradient-text mb-2">
|
||||||
Loading Editor
|
Loading Editor
|
||||||
@@ -390,7 +549,7 @@ function EditorPageContent() {
|
|||||||
|
|
||||||
<button
|
<button
|
||||||
onClick={() => (window.location.href = "/manage")}
|
onClick={() => (window.location.href = "/manage")}
|
||||||
className="w-full px-6 py-3 bg-gradient-to-r from-blue-500 to-purple-500 text-white rounded-xl hover:scale-105 transition-all font-medium"
|
className="w-full px-6 py-3 bg-stone-600 text-white rounded-xl hover:bg-stone-700 transition-all font-medium"
|
||||||
>
|
>
|
||||||
Go to Admin Login
|
Go to Admin Login
|
||||||
</button>
|
</button>
|
||||||
@@ -400,15 +559,15 @@ function EditorPageContent() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="min-h-screen animated-bg">
|
<div className="min-h-screen animated-bg flex flex-col overflow-hidden">
|
||||||
{/* Header */}
|
{/* Header */}
|
||||||
<div className="glass-card border-b border-white/10 sticky top-0 z-50">
|
<div className="glass-card border-b border-white/10 sticky top-0 z-50 flex-shrink-0">
|
||||||
<div className="max-w-7xl mx-auto px-4 sm:px-6">
|
<div className="max-w-7xl mx-auto px-4 sm:px-6">
|
||||||
<div className="flex flex-col sm:flex-row items-start sm:items-center justify-between h-auto sm:h-16 py-4 sm:py-0 gap-4 sm:gap-0">
|
<div className="flex flex-col sm:flex-row items-start sm:items-center justify-between h-auto sm:h-16 py-4 sm:py-0 gap-4 sm:gap-0">
|
||||||
<div className="flex flex-col sm:flex-row items-start sm:items-center space-y-2 sm:space-y-0 sm:space-x-4">
|
<div className="flex flex-col sm:flex-row items-start sm:items-center space-y-2 sm:space-y-0 sm:space-x-4">
|
||||||
<button
|
<button
|
||||||
onClick={() => (window.location.href = "/manage")}
|
onClick={() => (window.location.href = "/manage")}
|
||||||
className="inline-flex items-center space-x-2 text-blue-400 hover:text-blue-300 transition-colors"
|
className="inline-flex items-center space-x-2 text-stone-400 hover:text-stone-300 transition-colors"
|
||||||
>
|
>
|
||||||
<ArrowLeft className="w-5 h-5" />
|
<ArrowLeft className="w-5 h-5" />
|
||||||
<span className="hidden sm:inline">Back to Dashboard</span>
|
<span className="hidden sm:inline">Back to Dashboard</span>
|
||||||
@@ -427,8 +586,8 @@ function EditorPageContent() {
|
|||||||
onClick={() => setShowPreview(!showPreview)}
|
onClick={() => setShowPreview(!showPreview)}
|
||||||
className={`flex items-center space-x-2 px-4 py-2 rounded-lg font-medium transition-all duration-200 text-sm ${
|
className={`flex items-center space-x-2 px-4 py-2 rounded-lg font-medium transition-all duration-200 text-sm ${
|
||||||
showPreview
|
showPreview
|
||||||
? "bg-blue-600 text-white shadow-lg"
|
? "bg-stone-600 text-white shadow-lg"
|
||||||
: "bg-gray-800/50 text-gray-300 hover:bg-gray-700/50 hover:text-white"
|
: "bg-gray-800/50 text-stone-300 hover:bg-gray-700/50 hover:text-stone-100"
|
||||||
}`}
|
}`}
|
||||||
>
|
>
|
||||||
<Eye className="w-4 h-4" />
|
<Eye className="w-4 h-4" />
|
||||||
@@ -452,9 +611,10 @@ function EditorPageContent() {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Editor Content */}
|
{/* Editor Content - Scrollable */}
|
||||||
|
<div className="flex-1 overflow-y-auto">
|
||||||
<div className="max-w-7xl mx-auto px-4 sm:px-6 py-6 sm:py-8">
|
<div className="max-w-7xl mx-auto px-4 sm:px-6 py-6 sm:py-8">
|
||||||
<div className="grid grid-cols-1 xl:grid-cols-4 gap-6 lg:gap-8">
|
<div className="flex flex-col lg:flex-row gap-6 lg:gap-8">
|
||||||
{/* Floating particles background */}
|
{/* Floating particles background */}
|
||||||
<div className="particles">
|
<div className="particles">
|
||||||
{[...Array(20)].map((_, i) => (
|
{[...Array(20)].map((_, i) => (
|
||||||
@@ -469,187 +629,12 @@ function EditorPageContent() {
|
|||||||
/>
|
/>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
{/* Main Editor */}
|
|
||||||
<div className="xl:col-span-3 space-y-6">
|
|
||||||
{/* Project Title */}
|
|
||||||
<motion.div
|
|
||||||
initial={{ opacity: 0, y: 20 }}
|
|
||||||
animate={{ opacity: 1, y: 0 }}
|
|
||||||
className="glass-card p-6 rounded-2xl"
|
|
||||||
>
|
|
||||||
<input
|
|
||||||
type="text"
|
|
||||||
value={formData.title}
|
|
||||||
onChange={(e) => handleInputChange("title", e.target.value)}
|
|
||||||
className="w-full text-3xl font-bold form-input-enhanced focus:outline-none p-4 rounded-lg"
|
|
||||||
placeholder="Enter project title..."
|
|
||||||
/>
|
|
||||||
</motion.div>
|
|
||||||
|
|
||||||
{/* Rich Text Toolbar */}
|
{/* Sidebar - Left (appears first in DOM for left positioning) */}
|
||||||
<motion.div
|
<div className="w-full lg:w-80 flex-shrink-0 space-y-6 order-1 lg:order-1">
|
||||||
initial={{ opacity: 0, y: 20 }}
|
|
||||||
animate={{ opacity: 1, y: 0 }}
|
|
||||||
transition={{ delay: 0.1 }}
|
|
||||||
className="glass-card p-4 rounded-2xl"
|
|
||||||
>
|
|
||||||
<div className="flex flex-wrap items-center gap-1 sm:gap-2">
|
|
||||||
<div className="flex items-center space-x-1 border-r border-white/20 pr-2 sm:pr-3">
|
|
||||||
<button
|
|
||||||
onClick={() => insertFormatting("bold")}
|
|
||||||
className="p-2 rounded-lg text-gray-300"
|
|
||||||
title="Bold"
|
|
||||||
>
|
|
||||||
<Bold className="w-4 h-4" />
|
|
||||||
</button>
|
|
||||||
<button
|
|
||||||
onClick={() => insertFormatting("italic")}
|
|
||||||
className="p-2 rounded-lg text-gray-300"
|
|
||||||
title="Italic"
|
|
||||||
>
|
|
||||||
<Italic className="w-4 h-4" />
|
|
||||||
</button>
|
|
||||||
<button
|
|
||||||
onClick={() => insertFormatting("code")}
|
|
||||||
className="p-2 rounded-lg text-gray-300"
|
|
||||||
title="Code"
|
|
||||||
>
|
|
||||||
<Code className="w-4 h-4" />
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="flex items-center space-x-1 border-r border-white/20 pr-2 sm:pr-3">
|
|
||||||
<button
|
|
||||||
onClick={() => insertFormatting("h1")}
|
|
||||||
className="p-2 rounded-lg text-gray-300"
|
|
||||||
title="Heading 1"
|
|
||||||
>
|
|
||||||
<Hash className="w-4 h-4" />
|
|
||||||
</button>
|
|
||||||
<button
|
|
||||||
onClick={() => insertFormatting("h2")}
|
|
||||||
className="p-2 hover:bg-gray-800/50 rounded-lg transition-all duration-200 text-xs sm:text-sm text-gray-300 hover:text-white hover:scale-105"
|
|
||||||
title="Heading 2"
|
|
||||||
>
|
|
||||||
H2
|
|
||||||
</button>
|
|
||||||
<button
|
|
||||||
onClick={() => insertFormatting("h3")}
|
|
||||||
className="p-2 hover:bg-gray-800/50 rounded-lg transition-all duration-200 text-xs sm:text-sm text-gray-300 hover:text-white hover:scale-105"
|
|
||||||
title="Heading 3"
|
|
||||||
>
|
|
||||||
H3
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="flex items-center space-x-1 border-r border-white/20 pr-2 sm:pr-3">
|
|
||||||
<button
|
|
||||||
onClick={() => insertFormatting("list")}
|
|
||||||
className="p-2 rounded-lg text-gray-300"
|
|
||||||
title="Bullet List"
|
|
||||||
>
|
|
||||||
<List className="w-4 h-4" />
|
|
||||||
</button>
|
|
||||||
<button
|
|
||||||
onClick={() => insertFormatting("orderedList")}
|
|
||||||
className="p-2 rounded-lg text-gray-300"
|
|
||||||
title="Numbered List"
|
|
||||||
>
|
|
||||||
<ListOrdered className="w-4 h-4" />
|
|
||||||
</button>
|
|
||||||
<button
|
|
||||||
onClick={() => insertFormatting("quote")}
|
|
||||||
className="p-2 rounded-lg text-gray-300"
|
|
||||||
title="Quote"
|
|
||||||
>
|
|
||||||
<Quote className="w-4 h-4" />
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="flex items-center space-x-1">
|
|
||||||
<button
|
|
||||||
onClick={() => insertFormatting("link")}
|
|
||||||
className="p-2 rounded-lg text-gray-300"
|
|
||||||
title="Link"
|
|
||||||
>
|
|
||||||
<Link className="w-4 h-4" />
|
|
||||||
</button>
|
|
||||||
<button
|
|
||||||
onClick={() => insertFormatting("image")}
|
|
||||||
className="p-2 rounded-lg text-gray-300"
|
|
||||||
title="Image"
|
|
||||||
>
|
|
||||||
{/* eslint-disable-next-line jsx-a11y/alt-text */}
|
|
||||||
<Image className="w-4 h-4" />
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</motion.div>
|
|
||||||
|
|
||||||
{/* Content Editor */}
|
|
||||||
<motion.div
|
|
||||||
initial={{ opacity: 0, y: 20 }}
|
|
||||||
animate={{ opacity: 1, y: 0 }}
|
|
||||||
transition={{ delay: 0.2 }}
|
|
||||||
className="glass-card p-6 rounded-2xl"
|
|
||||||
>
|
|
||||||
<h3 className="text-lg font-semibold gradient-text mb-4">
|
|
||||||
Content
|
|
||||||
</h3>
|
|
||||||
<div
|
|
||||||
ref={contentRef}
|
|
||||||
contentEditable
|
|
||||||
className="editor-content-editable w-full min-h-[400px] p-6 form-input-enhanced rounded-lg focus:outline-none leading-relaxed"
|
|
||||||
style={{ whiteSpace: "pre-wrap" }}
|
|
||||||
onInput={(e) => {
|
|
||||||
const target = e.target as HTMLDivElement;
|
|
||||||
setIsTyping(true);
|
|
||||||
setFormData((prev) => ({
|
|
||||||
...prev,
|
|
||||||
content: target.textContent || "",
|
|
||||||
}));
|
|
||||||
}}
|
|
||||||
onBlur={() => {
|
|
||||||
setIsTyping(false);
|
|
||||||
}}
|
|
||||||
suppressContentEditableWarning={true}
|
|
||||||
data-placeholder="Start writing your project content..."
|
|
||||||
>
|
|
||||||
{!isTyping ? formData.content : undefined}
|
|
||||||
</div>
|
|
||||||
<p className="text-xs text-white/50 mt-2">
|
|
||||||
Supports Markdown formatting. Use the toolbar above or type
|
|
||||||
directly.
|
|
||||||
</p>
|
|
||||||
</motion.div>
|
|
||||||
|
|
||||||
{/* Description */}
|
|
||||||
<motion.div
|
|
||||||
initial={{ opacity: 0, y: 20 }}
|
|
||||||
animate={{ opacity: 1, y: 0 }}
|
|
||||||
transition={{ delay: 0.3 }}
|
|
||||||
className="glass-card p-6 rounded-2xl"
|
|
||||||
>
|
|
||||||
<h3 className="text-lg font-semibold gradient-text mb-4">
|
|
||||||
Description
|
|
||||||
</h3>
|
|
||||||
<textarea
|
|
||||||
value={formData.description}
|
|
||||||
onChange={(e) =>
|
|
||||||
handleInputChange("description", e.target.value)
|
|
||||||
}
|
|
||||||
rows={4}
|
|
||||||
className="w-full px-4 py-3 form-input-enhanced rounded-lg focus:outline-none resize-none"
|
|
||||||
placeholder="Brief description of your project..."
|
|
||||||
/>
|
|
||||||
</motion.div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Sidebar */}
|
|
||||||
<div className="space-y-6">
|
|
||||||
{/* Project Settings */}
|
{/* Project Settings */}
|
||||||
<motion.div
|
<motion.div
|
||||||
initial={{ opacity: 0, x: 20 }}
|
initial={{ opacity: 0, x: -20 }}
|
||||||
animate={{ opacity: 1, x: 0 }}
|
animate={{ opacity: 1, x: 0 }}
|
||||||
transition={{ delay: 0.4 }}
|
transition={{ delay: 0.4 }}
|
||||||
className="glass-card p-6 rounded-2xl"
|
className="glass-card p-6 rounded-2xl"
|
||||||
@@ -660,7 +645,7 @@ function EditorPageContent() {
|
|||||||
|
|
||||||
<div className="space-y-4">
|
<div className="space-y-4">
|
||||||
<div>
|
<div>
|
||||||
<label className="block text-sm font-medium text-white/70 mb-2">
|
<label className="block text-sm font-medium text-stone-300 mb-2">
|
||||||
Category
|
Category
|
||||||
</label>
|
</label>
|
||||||
<div className="custom-select">
|
<div className="custom-select">
|
||||||
@@ -681,7 +666,7 @@ function EditorPageContent() {
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div>
|
<div>
|
||||||
<label className="block text-sm font-medium text-white/70 mb-2">
|
<label className="block text-sm font-medium text-stone-300 mb-2">
|
||||||
Tags
|
Tags
|
||||||
</label>
|
</label>
|
||||||
<input
|
<input
|
||||||
@@ -697,7 +682,7 @@ function EditorPageContent() {
|
|||||||
|
|
||||||
{/* Links */}
|
{/* Links */}
|
||||||
<motion.div
|
<motion.div
|
||||||
initial={{ opacity: 0, x: 20 }}
|
initial={{ opacity: 0, x: -20 }}
|
||||||
animate={{ opacity: 1, x: 0 }}
|
animate={{ opacity: 1, x: 0 }}
|
||||||
transition={{ delay: 0.5 }}
|
transition={{ delay: 0.5 }}
|
||||||
className="glass-card p-6 rounded-2xl"
|
className="glass-card p-6 rounded-2xl"
|
||||||
@@ -708,7 +693,7 @@ function EditorPageContent() {
|
|||||||
|
|
||||||
<div className="space-y-4">
|
<div className="space-y-4">
|
||||||
<div>
|
<div>
|
||||||
<label className="block text-sm font-medium text-white/70 mb-2">
|
<label className="block text-sm font-medium text-stone-300 mb-2">
|
||||||
GitHub URL
|
GitHub URL
|
||||||
</label>
|
</label>
|
||||||
<input
|
<input
|
||||||
@@ -723,7 +708,7 @@ function EditorPageContent() {
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div>
|
<div>
|
||||||
<label className="block text-sm font-medium text-white/70 mb-2">
|
<label className="block text-sm font-medium text-stone-300 mb-2">
|
||||||
Live URL
|
Live URL
|
||||||
</label>
|
</label>
|
||||||
<input
|
<input
|
||||||
@@ -739,7 +724,7 @@ function EditorPageContent() {
|
|||||||
|
|
||||||
{/* Publish */}
|
{/* Publish */}
|
||||||
<motion.div
|
<motion.div
|
||||||
initial={{ opacity: 0, x: 20 }}
|
initial={{ opacity: 0, x: -20 }}
|
||||||
animate={{ opacity: 1, x: 0 }}
|
animate={{ opacity: 1, x: 0 }}
|
||||||
transition={{ delay: 0.6 }}
|
transition={{ delay: 0.6 }}
|
||||||
className="glass-card p-6 rounded-2xl"
|
className="glass-card p-6 rounded-2xl"
|
||||||
@@ -756,9 +741,9 @@ function EditorPageContent() {
|
|||||||
onChange={(e) =>
|
onChange={(e) =>
|
||||||
handleInputChange("featured", e.target.checked)
|
handleInputChange("featured", e.target.checked)
|
||||||
}
|
}
|
||||||
className="w-4 h-4 text-blue-500 bg-gray-900/80 border-gray-600/50 rounded focus:ring-blue-500 focus:ring-2"
|
className="w-4 h-4 text-stone-500 bg-gray-900/80 border-gray-600/50 rounded focus:ring-stone-500 focus:ring-2"
|
||||||
/>
|
/>
|
||||||
<span className="text-white">Featured Project</span>
|
<span className="text-stone-200">Featured Project</span>
|
||||||
</label>
|
</label>
|
||||||
|
|
||||||
<label className="flex items-center space-x-3">
|
<label className="flex items-center space-x-3">
|
||||||
@@ -768,20 +753,20 @@ function EditorPageContent() {
|
|||||||
onChange={(e) =>
|
onChange={(e) =>
|
||||||
handleInputChange("published", e.target.checked)
|
handleInputChange("published", e.target.checked)
|
||||||
}
|
}
|
||||||
className="w-4 h-4 text-blue-500 bg-gray-900/80 border-gray-600/50 rounded focus:ring-blue-500 focus:ring-2"
|
className="w-4 h-4 text-stone-500 bg-gray-900/80 border-gray-600/50 rounded focus:ring-stone-500 focus:ring-2"
|
||||||
/>
|
/>
|
||||||
<span className="text-white">Published</span>
|
<span className="text-stone-200">Published</span>
|
||||||
</label>
|
</label>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="mt-6 pt-4 border-t border-white/20">
|
<div className="mt-6 pt-4 border-t border-white/20">
|
||||||
<h4 className="text-sm font-medium text-white/70 mb-2">
|
<h4 className="text-sm font-medium text-stone-300 mb-2">
|
||||||
Preview
|
Preview
|
||||||
</h4>
|
</h4>
|
||||||
<div className="text-xs text-white/50 space-y-1">
|
<div className="text-xs text-stone-400 space-y-1">
|
||||||
<p>Status: {formData.published ? "Published" : "Draft"}</p>
|
<p>Status: {formData.published ? "Published" : "Draft"}</p>
|
||||||
{formData.featured && (
|
{formData.featured && (
|
||||||
<p className="text-blue-400">⭐ Featured</p>
|
<p className="text-stone-400">⭐ Featured</p>
|
||||||
)}
|
)}
|
||||||
<p>Category: {formData.category}</p>
|
<p>Category: {formData.category}</p>
|
||||||
<p>Tags: {formData.tags.length} tags</p>
|
<p>Tags: {formData.tags.length} tags</p>
|
||||||
@@ -789,6 +774,225 @@ function EditorPageContent() {
|
|||||||
</div>
|
</div>
|
||||||
</motion.div>
|
</motion.div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{/* Main Editor - Right (appears second in DOM for right positioning) */}
|
||||||
|
<div className="flex-1 space-y-6 order-2 lg:order-2 min-w-0">
|
||||||
|
{/* Project Title */}
|
||||||
|
<motion.div
|
||||||
|
initial={{ opacity: 0, y: 20 }}
|
||||||
|
animate={{ opacity: 1, y: 0 }}
|
||||||
|
className="glass-card p-6 rounded-2xl"
|
||||||
|
>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
value={formData.title}
|
||||||
|
onChange={(e) => handleInputChange("title", e.target.value)}
|
||||||
|
className="w-full text-3xl font-bold form-input-enhanced focus:outline-none p-4 rounded-lg"
|
||||||
|
placeholder="Enter project title..."
|
||||||
|
/>
|
||||||
|
</motion.div>
|
||||||
|
|
||||||
|
{/* Description - Under Title */}
|
||||||
|
<motion.div
|
||||||
|
initial={{ opacity: 0, y: 20 }}
|
||||||
|
animate={{ opacity: 1, y: 0 }}
|
||||||
|
transition={{ delay: 0.1 }}
|
||||||
|
className="glass-card p-6 rounded-2xl"
|
||||||
|
>
|
||||||
|
<h3 className="text-lg font-semibold gradient-text mb-4">
|
||||||
|
Description
|
||||||
|
</h3>
|
||||||
|
<textarea
|
||||||
|
value={formData.description}
|
||||||
|
onChange={(e) =>
|
||||||
|
handleInputChange("description", e.target.value)
|
||||||
|
}
|
||||||
|
rows={4}
|
||||||
|
className="w-full px-4 py-3 form-input-enhanced rounded-lg focus:outline-none resize-none"
|
||||||
|
placeholder="Brief description of your project..."
|
||||||
|
/>
|
||||||
|
</motion.div>
|
||||||
|
|
||||||
|
{/* Rich Text Toolbar */}
|
||||||
|
<motion.div
|
||||||
|
initial={{ opacity: 0, y: 20 }}
|
||||||
|
animate={{ opacity: 1, y: 0 }}
|
||||||
|
transition={{ delay: 0.2 }}
|
||||||
|
className="glass-card p-4 rounded-2xl"
|
||||||
|
>
|
||||||
|
<div className="flex flex-wrap items-center gap-1 sm:gap-2">
|
||||||
|
<div className="flex items-center space-x-1 border-r border-white/20 pr-2 sm:pr-3">
|
||||||
|
<button
|
||||||
|
onClick={() => insertFormatting("bold")}
|
||||||
|
className="p-2 rounded-lg text-stone-300"
|
||||||
|
title="Bold"
|
||||||
|
>
|
||||||
|
<Bold className="w-4 h-4" />
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
onClick={() => insertFormatting("italic")}
|
||||||
|
className="p-2 rounded-lg text-stone-300"
|
||||||
|
title="Italic"
|
||||||
|
>
|
||||||
|
<Italic className="w-4 h-4" />
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
onClick={() => insertFormatting("code")}
|
||||||
|
className="p-2 rounded-lg text-stone-300"
|
||||||
|
title="Code"
|
||||||
|
>
|
||||||
|
<Code className="w-4 h-4" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex items-center space-x-1 border-r border-white/20 pr-2 sm:pr-3">
|
||||||
|
<button
|
||||||
|
onClick={() => insertFormatting("h1")}
|
||||||
|
className="p-2 rounded-lg text-stone-300"
|
||||||
|
title="Heading 1"
|
||||||
|
>
|
||||||
|
<Hash className="w-4 h-4" />
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
onClick={() => insertFormatting("h2")}
|
||||||
|
className="p-2 hover:bg-gray-800/50 rounded-lg transition-all duration-200 text-xs sm:text-sm text-stone-300 hover:text-stone-100"
|
||||||
|
title="Heading 2"
|
||||||
|
>
|
||||||
|
H2
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
onClick={() => insertFormatting("h3")}
|
||||||
|
className="p-2 hover:bg-gray-800/50 rounded-lg transition-all duration-200 text-xs sm:text-sm text-stone-300 hover:text-stone-100"
|
||||||
|
title="Heading 3"
|
||||||
|
>
|
||||||
|
H3
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex items-center space-x-1 border-r border-white/20 pr-2 sm:pr-3">
|
||||||
|
<button
|
||||||
|
onClick={() => insertFormatting("list")}
|
||||||
|
className="p-2 rounded-lg text-stone-300"
|
||||||
|
title="Bullet List"
|
||||||
|
>
|
||||||
|
<List className="w-4 h-4" />
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
onClick={() => insertFormatting("orderedList")}
|
||||||
|
className="p-2 rounded-lg text-stone-300"
|
||||||
|
title="Numbered List"
|
||||||
|
>
|
||||||
|
<ListOrdered className="w-4 h-4" />
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
onClick={() => insertFormatting("quote")}
|
||||||
|
className="p-2 rounded-lg text-stone-300"
|
||||||
|
title="Quote"
|
||||||
|
>
|
||||||
|
<Quote className="w-4 h-4" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex items-center space-x-1">
|
||||||
|
<button
|
||||||
|
onClick={() => insertFormatting("link")}
|
||||||
|
className="p-2 rounded-lg text-stone-300"
|
||||||
|
title="Link"
|
||||||
|
>
|
||||||
|
<Link className="w-4 h-4" />
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
onClick={() => insertFormatting("image")}
|
||||||
|
className="p-2 rounded-lg text-stone-300"
|
||||||
|
title="Image"
|
||||||
|
>
|
||||||
|
{/* eslint-disable-next-line jsx-a11y/alt-text */}
|
||||||
|
<Image className="w-4 h-4" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</motion.div>
|
||||||
|
|
||||||
|
{/* Content Editor */}
|
||||||
|
<motion.div
|
||||||
|
initial={{ opacity: 0, y: 20 }}
|
||||||
|
animate={{ opacity: 1, y: 0 }}
|
||||||
|
transition={{ delay: 0.3 }}
|
||||||
|
className="glass-card p-6 rounded-2xl"
|
||||||
|
>
|
||||||
|
<h3 className="text-lg font-semibold gradient-text mb-4">
|
||||||
|
Content
|
||||||
|
</h3>
|
||||||
|
<div className="relative">
|
||||||
|
<div
|
||||||
|
ref={contentRef}
|
||||||
|
contentEditable
|
||||||
|
className="editor-content-editable w-full min-h-[500px] p-6 form-input-enhanced rounded-lg focus:outline-none leading-relaxed"
|
||||||
|
style={{ whiteSpace: "pre-wrap" }}
|
||||||
|
onFocus={(e) => {
|
||||||
|
// Ensure content is set when focusing if empty
|
||||||
|
const target = e.target as HTMLDivElement;
|
||||||
|
const currentText = target.textContent || "";
|
||||||
|
if (!currentText && formData.content) {
|
||||||
|
target.textContent = formData.content;
|
||||||
|
} else if (currentText !== formData.content && shouldUpdateContentRef.current) {
|
||||||
|
// Sync if content changed externally (undo/redo)
|
||||||
|
target.textContent = formData.content;
|
||||||
|
}
|
||||||
|
shouldUpdateContentRef.current = false;
|
||||||
|
}}
|
||||||
|
onMouseDown={(e) => {
|
||||||
|
// Prevent content from being cleared on click
|
||||||
|
const target = e.target as HTMLDivElement;
|
||||||
|
const currentText = target.textContent || "";
|
||||||
|
if (!currentText && formData.content) {
|
||||||
|
target.textContent = formData.content;
|
||||||
|
}
|
||||||
|
shouldUpdateContentRef.current = false;
|
||||||
|
}}
|
||||||
|
onClick={(e) => {
|
||||||
|
// Ensure content persists on click
|
||||||
|
const target = e.target as HTMLDivElement;
|
||||||
|
if (!target.textContent && formData.content) {
|
||||||
|
target.textContent = formData.content;
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
onInput={(e) => {
|
||||||
|
const target = e.target as HTMLDivElement;
|
||||||
|
setIsTyping(true);
|
||||||
|
shouldUpdateContentRef.current = false;
|
||||||
|
const newContent = target.textContent || "";
|
||||||
|
setFormData((prev) => {
|
||||||
|
const newData = {
|
||||||
|
...prev,
|
||||||
|
content: newContent,
|
||||||
|
};
|
||||||
|
// Add to history for undo/redo
|
||||||
|
setHistory((hist) => {
|
||||||
|
const newHistory = hist.slice(0, historyIndex + 1);
|
||||||
|
newHistory.push(newData);
|
||||||
|
// Keep only last 50 history entries
|
||||||
|
const trimmedHistory = newHistory.slice(-50);
|
||||||
|
setHistoryIndex(trimmedHistory.length - 1);
|
||||||
|
return trimmedHistory;
|
||||||
|
});
|
||||||
|
return newData;
|
||||||
|
});
|
||||||
|
}}
|
||||||
|
onBlur={() => {
|
||||||
|
setIsTyping(false);
|
||||||
|
}}
|
||||||
|
suppressContentEditableWarning={true}
|
||||||
|
data-placeholder="Start writing your project content..."
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<p className="text-xs text-stone-400 mt-2">
|
||||||
|
Supports Markdown formatting. Use the toolbar above or type
|
||||||
|
directly.
|
||||||
|
</p>
|
||||||
|
</motion.div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -806,7 +1010,7 @@ function EditorPageContent() {
|
|||||||
initial={{ scale: 0.9, opacity: 0 }}
|
initial={{ scale: 0.9, opacity: 0 }}
|
||||||
animate={{ scale: 1, opacity: 1 }}
|
animate={{ scale: 1, opacity: 1 }}
|
||||||
exit={{ scale: 0.9, opacity: 0 }}
|
exit={{ scale: 0.9, opacity: 0 }}
|
||||||
className="glass-card rounded-2xl p-8 max-w-4xl w-full max-h-[90vh] overflow-y-auto"
|
className="glass-card rounded-2xl p-8 max-w-4xl w-full max-h-[90vh] overflow-y-auto scrollbar-hide"
|
||||||
onClick={(e) => e.stopPropagation()}
|
onClick={(e) => e.stopPropagation()}
|
||||||
>
|
>
|
||||||
<div className="flex items-center justify-between mb-6">
|
<div className="flex items-center justify-between mb-6">
|
||||||
@@ -834,12 +1038,12 @@ function EditorPageContent() {
|
|||||||
|
|
||||||
{/* Project Meta */}
|
{/* Project Meta */}
|
||||||
<div className="flex flex-wrap justify-center gap-4 mb-6">
|
<div className="flex flex-wrap justify-center gap-4 mb-6">
|
||||||
<div className="flex items-center space-x-2 text-gray-300">
|
<div className="flex items-center space-x-2 text-stone-300">
|
||||||
<Tag className="w-4 h-4" />
|
<Tag className="w-4 h-4" />
|
||||||
<span className="capitalize">{formData.category}</span>
|
<span className="capitalize">{formData.category}</span>
|
||||||
</div>
|
</div>
|
||||||
{formData.featured && (
|
{formData.featured && (
|
||||||
<div className="flex items-center space-x-2 text-blue-400">
|
<div className="flex items-center space-x-2 text-stone-400">
|
||||||
<span className="text-sm font-semibold">
|
<span className="text-sm font-semibold">
|
||||||
⭐ Featured
|
⭐ Featured
|
||||||
</span>
|
</span>
|
||||||
@@ -853,7 +1057,7 @@ function EditorPageContent() {
|
|||||||
{formData.tags.map((tag, index) => (
|
{formData.tags.map((tag, index) => (
|
||||||
<span
|
<span
|
||||||
key={index}
|
key={index}
|
||||||
className="px-3 py-1 bg-gray-800/50 text-gray-300 text-sm rounded-full border border-gray-700"
|
className="px-3 py-1 bg-gray-800/50 text-stone-300 text-sm rounded-full border border-gray-700"
|
||||||
>
|
>
|
||||||
{tag}
|
{tag}
|
||||||
</span>
|
</span>
|
||||||
@@ -870,7 +1074,7 @@ function EditorPageContent() {
|
|||||||
href={formData.github}
|
href={formData.github}
|
||||||
target="_blank"
|
target="_blank"
|
||||||
rel="noopener noreferrer"
|
rel="noopener noreferrer"
|
||||||
className="flex items-center space-x-2 px-4 py-2 bg-gray-800/50 text-gray-300 rounded-lg"
|
className="flex items-center space-x-2 px-4 py-2 bg-gray-800/50 text-stone-300 rounded-lg"
|
||||||
>
|
>
|
||||||
<Github className="w-4 h-4" />
|
<Github className="w-4 h-4" />
|
||||||
<span>GitHub</span>
|
<span>GitHub</span>
|
||||||
@@ -881,7 +1085,7 @@ function EditorPageContent() {
|
|||||||
href={formData.live}
|
href={formData.live}
|
||||||
target="_blank"
|
target="_blank"
|
||||||
rel="noopener noreferrer"
|
rel="noopener noreferrer"
|
||||||
className="flex items-center space-x-2 px-4 py-2 bg-blue-600/80 text-white rounded-lg"
|
className="flex items-center space-x-2 px-4 py-2 bg-stone-600/80 text-white rounded-lg"
|
||||||
>
|
>
|
||||||
<ExternalLink className="w-4 h-4" />
|
<ExternalLink className="w-4 h-4" />
|
||||||
<span>Live Demo</span>
|
<span>Live Demo</span>
|
||||||
@@ -898,7 +1102,7 @@ function EditorPageContent() {
|
|||||||
Content
|
Content
|
||||||
</h3>
|
</h3>
|
||||||
<div className="prose prose-invert max-w-none">
|
<div className="prose prose-invert max-w-none">
|
||||||
<div className="markdown text-gray-300 leading-relaxed">
|
<div className="markdown text-stone-300 leading-relaxed">
|
||||||
<ReactMarkdown components={markdownComponents}>
|
<ReactMarkdown components={markdownComponents}>
|
||||||
{formData.content}
|
{formData.content}
|
||||||
</ReactMarkdown>
|
</ReactMarkdown>
|
||||||
@@ -921,7 +1125,7 @@ function EditorPageContent() {
|
|||||||
{formData.published ? "Published" : "Draft"}
|
{formData.published ? "Published" : "Draft"}
|
||||||
</span>
|
</span>
|
||||||
{formData.featured && (
|
{formData.featured && (
|
||||||
<span className="px-3 py-1 bg-blue-500/20 text-blue-400 rounded-full text-sm font-medium">
|
<span className="px-3 py-1 bg-stone-500/20 text-stone-400 rounded-full text-sm font-medium">
|
||||||
Featured
|
Featured
|
||||||
</span>
|
</span>
|
||||||
)}
|
)}
|
||||||
|
|||||||
@@ -57,6 +57,9 @@ const AdminPage = () => {
|
|||||||
|
|
||||||
// Check if user is locked out
|
// Check if user is locked out
|
||||||
const checkLockout = useCallback(() => {
|
const checkLockout = useCallback(() => {
|
||||||
|
if (typeof window === 'undefined') return false;
|
||||||
|
|
||||||
|
try {
|
||||||
const lockoutData = localStorage.getItem('admin_lockout');
|
const lockoutData = localStorage.getItem('admin_lockout');
|
||||||
if (lockoutData) {
|
if (lockoutData) {
|
||||||
try {
|
try {
|
||||||
@@ -72,10 +75,24 @@ const AdminPage = () => {
|
|||||||
}));
|
}));
|
||||||
return true;
|
return true;
|
||||||
} else {
|
} else {
|
||||||
|
try {
|
||||||
localStorage.removeItem('admin_lockout');
|
localStorage.removeItem('admin_lockout');
|
||||||
|
} catch {
|
||||||
|
// Ignore errors
|
||||||
|
}
|
||||||
}
|
}
|
||||||
} catch {
|
} catch {
|
||||||
|
try {
|
||||||
localStorage.removeItem('admin_lockout');
|
localStorage.removeItem('admin_lockout');
|
||||||
|
} catch {
|
||||||
|
// Ignore errors
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
// localStorage might be disabled
|
||||||
|
if (process.env.NODE_ENV === 'development') {
|
||||||
|
console.warn('Failed to check lockout status:', error);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return false;
|
return false;
|
||||||
@@ -197,7 +214,11 @@ const AdminPage = () => {
|
|||||||
attempts: 0,
|
attempts: 0,
|
||||||
isLoading: false
|
isLoading: false
|
||||||
}));
|
}));
|
||||||
|
try {
|
||||||
localStorage.removeItem('admin_lockout');
|
localStorage.removeItem('admin_lockout');
|
||||||
|
} catch {
|
||||||
|
// Ignore errors
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
const newAttempts = authState.attempts + 1;
|
const newAttempts = authState.attempts + 1;
|
||||||
setAuthState(prev => ({
|
setAuthState(prev => ({
|
||||||
@@ -208,10 +229,17 @@ const AdminPage = () => {
|
|||||||
}));
|
}));
|
||||||
|
|
||||||
if (newAttempts >= 5) {
|
if (newAttempts >= 5) {
|
||||||
|
try {
|
||||||
localStorage.setItem('admin_lockout', JSON.stringify({
|
localStorage.setItem('admin_lockout', JSON.stringify({
|
||||||
timestamp: Date.now(),
|
timestamp: Date.now(),
|
||||||
attempts: newAttempts
|
attempts: newAttempts
|
||||||
}));
|
}));
|
||||||
|
} catch (error) {
|
||||||
|
// localStorage might be full or disabled
|
||||||
|
if (process.env.NODE_ENV === 'development') {
|
||||||
|
console.warn('Failed to save lockout data:', error);
|
||||||
|
}
|
||||||
|
}
|
||||||
setAuthState(prev => ({
|
setAuthState(prev => ({
|
||||||
...prev,
|
...prev,
|
||||||
isLocked: true,
|
isLocked: true,
|
||||||
@@ -252,7 +280,11 @@ const AdminPage = () => {
|
|||||||
<p className="text-stone-500">Too many failed attempts. Please try again in 15 minutes.</p>
|
<p className="text-stone-500">Too many failed attempts. Please try again in 15 minutes.</p>
|
||||||
<button
|
<button
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
|
try {
|
||||||
localStorage.removeItem('admin_lockout');
|
localStorage.removeItem('admin_lockout');
|
||||||
|
} catch {
|
||||||
|
// Ignore errors
|
||||||
|
}
|
||||||
window.location.reload();
|
window.location.reload();
|
||||||
}}
|
}}
|
||||||
className="mt-4 px-6 py-2 bg-stone-900 text-stone-50 rounded-xl hover:bg-stone-800 transition-colors"
|
className="mt-4 px-6 py-2 bg-stone-900 text-stone-50 rounded-xl hover:bg-stone-800 transition-colors"
|
||||||
@@ -322,10 +354,10 @@ const AdminPage = () => {
|
|||||||
{authState.isLoading ? (
|
{authState.isLoading ? (
|
||||||
<div className="flex items-center justify-center space-x-2">
|
<div className="flex items-center justify-center space-x-2">
|
||||||
<Loader2 className="w-5 h-5 animate-spin" />
|
<Loader2 className="w-5 h-5 animate-spin" />
|
||||||
<span>Authenticating...</span>
|
<span className="text-stone-50">Authenticating...</span>
|
||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
<span>Sign In</span>
|
<span className="text-stone-50">Sign In</span>
|
||||||
)}
|
)}
|
||||||
</button>
|
</button>
|
||||||
</form>
|
</form>
|
||||||
|
|||||||
@@ -1,30 +1,80 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { Suspense } from "react";
|
import { useEffect, useState } from "react";
|
||||||
import dynamic from "next/dynamic";
|
import dynamic from "next/dynamic";
|
||||||
|
|
||||||
// Dynamically import KernelPanic404 to avoid SSR issues
|
// Dynamically import KernelPanic404Wrapper to avoid SSR issues
|
||||||
const KernelPanic404 = dynamic(() => import("./components/KernelPanic404"), {
|
const KernelPanic404 = dynamic(() => import("./components/KernelPanic404Wrapper"), {
|
||||||
ssr: false,
|
ssr: false,
|
||||||
loading: () => (
|
loading: () => (
|
||||||
<div className="flex items-center justify-center min-h-screen bg-black text-[#33ff00] font-mono">
|
<div style={{
|
||||||
|
position: "fixed",
|
||||||
|
top: 0,
|
||||||
|
left: 0,
|
||||||
|
width: "100%",
|
||||||
|
height: "100%",
|
||||||
|
display: "flex",
|
||||||
|
alignItems: "center",
|
||||||
|
justifyContent: "center",
|
||||||
|
backgroundColor: "#020202",
|
||||||
|
color: "#33ff00",
|
||||||
|
fontFamily: "monospace"
|
||||||
|
}}>
|
||||||
<div>Loading terminal...</div>
|
<div>Loading terminal...</div>
|
||||||
</div>
|
</div>
|
||||||
),
|
),
|
||||||
});
|
});
|
||||||
|
|
||||||
export default function NotFound() {
|
export default function NotFound() {
|
||||||
|
const [mounted, setMounted] = useState(false);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
setMounted(true);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
if (!mounted) {
|
||||||
return (
|
return (
|
||||||
<main className="min-h-screen w-full bg-black overflow-hidden relative">
|
<div style={{
|
||||||
<Suspense
|
position: "fixed",
|
||||||
fallback={
|
top: 0,
|
||||||
<div className="flex items-center justify-center min-h-screen bg-black text-[#33ff00] font-mono">
|
left: 0,
|
||||||
<div>Loading terminal...</div>
|
width: "100vw",
|
||||||
|
height: "100vh",
|
||||||
|
margin: 0,
|
||||||
|
padding: 0,
|
||||||
|
overflow: "hidden",
|
||||||
|
backgroundColor: "#020202",
|
||||||
|
zIndex: 9998
|
||||||
|
}}>
|
||||||
|
<div style={{
|
||||||
|
display: "flex",
|
||||||
|
alignItems: "center",
|
||||||
|
justifyContent: "center",
|
||||||
|
width: "100%",
|
||||||
|
height: "100%",
|
||||||
|
color: "#33ff00",
|
||||||
|
fontFamily: "monospace"
|
||||||
|
}}>
|
||||||
|
Loading terminal...
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div style={{
|
||||||
|
position: "fixed",
|
||||||
|
top: 0,
|
||||||
|
left: 0,
|
||||||
|
width: "100vw",
|
||||||
|
height: "100vh",
|
||||||
|
margin: 0,
|
||||||
|
padding: 0,
|
||||||
|
overflow: "hidden",
|
||||||
|
backgroundColor: "#020202",
|
||||||
|
zIndex: 9998
|
||||||
|
}}>
|
||||||
|
<KernelPanic404 />
|
||||||
</div>
|
</div>
|
||||||
}
|
|
||||||
>
|
|
||||||
<KernelPanic404 />
|
|
||||||
</Suspense>
|
|
||||||
</main>
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ import Projects from "./components/Projects";
|
|||||||
import Contact from "./components/Contact";
|
import Contact from "./components/Contact";
|
||||||
import Footer from "./components/Footer";
|
import Footer from "./components/Footer";
|
||||||
import Script from "next/script";
|
import Script from "next/script";
|
||||||
|
import ErrorBoundary from "@/components/ErrorBoundary";
|
||||||
import ActivityFeed from "./components/ActivityFeed";
|
import ActivityFeed from "./components/ActivityFeed";
|
||||||
import { motion } from "framer-motion";
|
import { motion } from "framer-motion";
|
||||||
|
|
||||||
@@ -35,7 +36,9 @@ export default function Home() {
|
|||||||
}),
|
}),
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
|
<ErrorBoundary>
|
||||||
<ActivityFeed />
|
<ActivityFeed />
|
||||||
|
</ErrorBoundary>
|
||||||
<Header />
|
<Header />
|
||||||
{/* Spacer to prevent navbar overlap */}
|
{/* Spacer to prevent navbar overlap */}
|
||||||
<div className="h-24 md:h-32" aria-hidden="true"></div>
|
<div className="h-24 md:h-32" aria-hidden="true"></div>
|
||||||
|
|||||||
@@ -1,12 +1,11 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { motion } from 'framer-motion';
|
import { motion } from 'framer-motion';
|
||||||
import { ExternalLink, Calendar, Tag, ArrowLeft, Github as GithubIcon, Share2 } from 'lucide-react';
|
import { ExternalLink, Calendar, ArrowLeft, Github as GithubIcon, Share2 } from 'lucide-react';
|
||||||
import Link from 'next/link';
|
import Link from 'next/link';
|
||||||
import { useParams } from 'next/navigation';
|
import { useParams } from 'next/navigation';
|
||||||
import { useState, useEffect } from 'react';
|
import { useState, useEffect } from 'react';
|
||||||
import ReactMarkdown from 'react-markdown';
|
import ReactMarkdown from 'react-markdown';
|
||||||
import Image from 'next/image';
|
|
||||||
|
|
||||||
interface Project {
|
interface Project {
|
||||||
id: number;
|
id: number;
|
||||||
@@ -35,7 +34,28 @@ const ProjectDetail = () => {
|
|||||||
if (response.ok) {
|
if (response.ok) {
|
||||||
const data = await response.json();
|
const data = await response.json();
|
||||||
if (data.projects && data.projects.length > 0) {
|
if (data.projects && data.projects.length > 0) {
|
||||||
setProject(data.projects[0]);
|
const loadedProject = data.projects[0];
|
||||||
|
setProject(loadedProject);
|
||||||
|
|
||||||
|
// Track page view
|
||||||
|
try {
|
||||||
|
await fetch('/api/analytics/track', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
},
|
||||||
|
body: JSON.stringify({
|
||||||
|
type: 'pageview',
|
||||||
|
projectId: loadedProject.id.toString(),
|
||||||
|
page: `/projects/${slug}`
|
||||||
|
})
|
||||||
|
});
|
||||||
|
} catch (trackError) {
|
||||||
|
// Silently fail tracking
|
||||||
|
if (process.env.NODE_ENV === 'development') {
|
||||||
|
console.error('Error tracking page view:', trackError);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
|
|||||||
@@ -4,9 +4,7 @@ import { useState, useEffect, useCallback } from 'react';
|
|||||||
import { motion } from 'framer-motion';
|
import { motion } from 'framer-motion';
|
||||||
import {
|
import {
|
||||||
BarChart3,
|
BarChart3,
|
||||||
TrendingUp,
|
|
||||||
Eye,
|
Eye,
|
||||||
Heart,
|
|
||||||
Zap,
|
Zap,
|
||||||
Globe,
|
Globe,
|
||||||
Activity,
|
Activity,
|
||||||
@@ -18,6 +16,7 @@ import {
|
|||||||
Trash2,
|
Trash2,
|
||||||
AlertTriangle
|
AlertTriangle
|
||||||
} from 'lucide-react';
|
} from 'lucide-react';
|
||||||
|
import { useToast } from '@/components/Toast';
|
||||||
|
|
||||||
interface AnalyticsData {
|
interface AnalyticsData {
|
||||||
overview: {
|
overview: {
|
||||||
@@ -25,8 +24,6 @@ interface AnalyticsData {
|
|||||||
publishedProjects: number;
|
publishedProjects: number;
|
||||||
featuredProjects: number;
|
featuredProjects: number;
|
||||||
totalViews: number;
|
totalViews: number;
|
||||||
totalLikes: number;
|
|
||||||
totalShares: number;
|
|
||||||
avgLighthouse: number;
|
avgLighthouse: number;
|
||||||
};
|
};
|
||||||
projects: Array<{
|
projects: Array<{
|
||||||
@@ -35,8 +32,6 @@ interface AnalyticsData {
|
|||||||
category: string;
|
category: string;
|
||||||
difficulty: string;
|
difficulty: string;
|
||||||
views: number;
|
views: number;
|
||||||
likes: number;
|
|
||||||
shares: number;
|
|
||||||
lighthouse: number;
|
lighthouse: number;
|
||||||
published: boolean;
|
published: boolean;
|
||||||
featured: boolean;
|
featured: boolean;
|
||||||
@@ -48,8 +43,6 @@ interface AnalyticsData {
|
|||||||
performance: {
|
performance: {
|
||||||
avgLighthouse: number;
|
avgLighthouse: number;
|
||||||
totalViews: number;
|
totalViews: number;
|
||||||
totalLikes: number;
|
|
||||||
totalShares: number;
|
|
||||||
};
|
};
|
||||||
metrics: {
|
metrics: {
|
||||||
bounceRate: number;
|
bounceRate: number;
|
||||||
@@ -71,6 +64,7 @@ export function AnalyticsDashboard({ isAuthenticated }: AnalyticsDashboardProps)
|
|||||||
const [showResetModal, setShowResetModal] = useState(false);
|
const [showResetModal, setShowResetModal] = useState(false);
|
||||||
const [resetType, setResetType] = useState<'analytics' | 'pageviews' | 'interactions' | 'performance' | 'all'>('analytics');
|
const [resetType, setResetType] = useState<'analytics' | 'pageviews' | 'interactions' | 'performance' | 'all'>('analytics');
|
||||||
const [resetting, setResetting] = useState(false);
|
const [resetting, setResetting] = useState(false);
|
||||||
|
const { showSuccess, showError } = useToast();
|
||||||
|
|
||||||
const fetchAnalyticsData = useCallback(async () => {
|
const fetchAnalyticsData = useCallback(async () => {
|
||||||
if (!isAuthenticated) return;
|
if (!isAuthenticated) return;
|
||||||
@@ -79,11 +73,13 @@ export function AnalyticsDashboard({ isAuthenticated }: AnalyticsDashboardProps)
|
|||||||
setLoading(true);
|
setLoading(true);
|
||||||
setError(null);
|
setError(null);
|
||||||
|
|
||||||
|
// Add cache-busting parameter to ensure fresh data after reset
|
||||||
|
const cacheBust = `?nocache=true&t=${Date.now()}`;
|
||||||
const [analyticsRes, performanceRes] = await Promise.all([
|
const [analyticsRes, performanceRes] = await Promise.all([
|
||||||
fetch('/api/analytics/dashboard', {
|
fetch(`/api/analytics/dashboard${cacheBust}`, {
|
||||||
headers: { 'x-admin-request': 'true' }
|
headers: { 'x-admin-request': 'true' }
|
||||||
}),
|
}),
|
||||||
fetch('/api/analytics/performance', {
|
fetch(`/api/analytics/performance${cacheBust}`, {
|
||||||
headers: { 'x-admin-request': 'true' }
|
headers: { 'x-admin-request': 'true' }
|
||||||
})
|
})
|
||||||
]);
|
]);
|
||||||
@@ -103,23 +99,19 @@ export function AnalyticsDashboard({ isAuthenticated }: AnalyticsDashboardProps)
|
|||||||
publishedProjects: 0,
|
publishedProjects: 0,
|
||||||
featuredProjects: 0,
|
featuredProjects: 0,
|
||||||
totalViews: 0,
|
totalViews: 0,
|
||||||
totalLikes: 0,
|
|
||||||
totalShares: 0,
|
|
||||||
avgLighthouse: 90
|
avgLighthouse: 90
|
||||||
},
|
},
|
||||||
projects: analytics.projects || [],
|
projects: analytics.projects || [],
|
||||||
categories: analytics.categories || {},
|
categories: analytics.categories || {},
|
||||||
difficulties: analytics.difficulties || {},
|
difficulties: analytics.difficulties || {},
|
||||||
performance: performance.performance || {
|
performance: {
|
||||||
avgLighthouse: 90,
|
avgLighthouse: performance.avgLighthouse || analytics.overview?.avgLighthouse || 0,
|
||||||
totalViews: 0,
|
totalViews: performance.totalViews || analytics.overview?.totalViews || 0,
|
||||||
totalLikes: 0,
|
|
||||||
totalShares: 0
|
|
||||||
},
|
},
|
||||||
metrics: performance.metrics || {
|
metrics: performance.metrics || analytics.metrics || {
|
||||||
bounceRate: 35,
|
bounceRate: 0,
|
||||||
avgSessionDuration: 180,
|
avgSessionDuration: 0,
|
||||||
pagesPerSession: 2.5,
|
pagesPerSession: 0,
|
||||||
newUsers: 0
|
newUsers: 0
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
@@ -134,6 +126,7 @@ export function AnalyticsDashboard({ isAuthenticated }: AnalyticsDashboardProps)
|
|||||||
if (!isAuthenticated || resetting) return;
|
if (!isAuthenticated || resetting) return;
|
||||||
|
|
||||||
setResetting(true);
|
setResetting(true);
|
||||||
|
setError(null);
|
||||||
try {
|
try {
|
||||||
const response = await fetch('/api/analytics/reset', {
|
const response = await fetch('/api/analytics/reset', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
@@ -144,15 +137,25 @@ export function AnalyticsDashboard({ isAuthenticated }: AnalyticsDashboardProps)
|
|||||||
body: JSON.stringify({ type: resetType })
|
body: JSON.stringify({ type: resetType })
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const result = await response.json();
|
||||||
|
|
||||||
if (response.ok) {
|
if (response.ok) {
|
||||||
await fetchAnalyticsData(); // Refresh data
|
showSuccess(
|
||||||
|
'Analytics Reset',
|
||||||
|
`Successfully reset ${resetType === 'all' ? 'all analytics data' : resetType} data.`
|
||||||
|
);
|
||||||
setShowResetModal(false);
|
setShowResetModal(false);
|
||||||
|
// Clear cache and refresh data
|
||||||
|
await fetchAnalyticsData();
|
||||||
} else {
|
} else {
|
||||||
const errorData = await response.json();
|
const errorMsg = result.error || 'Failed to reset analytics';
|
||||||
setError(errorData.error || 'Failed to reset analytics');
|
setError(errorMsg);
|
||||||
|
showError('Reset Failed', errorMsg);
|
||||||
}
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
setError('Failed to reset analytics');
|
const errorMsg = 'Failed to reset analytics. Please try again.';
|
||||||
|
setError(errorMsg);
|
||||||
|
showError('Reset Failed', errorMsg);
|
||||||
console.error('Reset error:', err);
|
console.error('Reset error:', err);
|
||||||
} finally {
|
} finally {
|
||||||
setResetting(false);
|
setResetting(false);
|
||||||
@@ -165,19 +168,18 @@ export function AnalyticsDashboard({ isAuthenticated }: AnalyticsDashboardProps)
|
|||||||
}
|
}
|
||||||
}, [isAuthenticated, fetchAnalyticsData]);
|
}, [isAuthenticated, fetchAnalyticsData]);
|
||||||
|
|
||||||
const StatCard = ({ title, value, icon: Icon, color, trend, trendValue, description }: {
|
const StatCard = ({ title, value, icon: Icon, color, description, tooltip }: {
|
||||||
title: string;
|
title: string;
|
||||||
value: number | string;
|
value: number | string;
|
||||||
icon: React.ComponentType<{ className?: string; size?: number }>;
|
icon: React.ComponentType<{ className?: string; size?: number }>;
|
||||||
color: string;
|
color: string;
|
||||||
trend?: 'up' | 'down' | 'neutral';
|
|
||||||
trendValue?: string;
|
|
||||||
description?: string;
|
description?: string;
|
||||||
|
tooltip?: string;
|
||||||
}) => (
|
}) => (
|
||||||
<motion.div
|
<motion.div
|
||||||
initial={{ opacity: 0, y: 20 }}
|
initial={{ opacity: 0, y: 20 }}
|
||||||
animate={{ opacity: 1, y: 0 }}
|
animate={{ opacity: 1, y: 0 }}
|
||||||
className="bg-white border border-stone-200 p-6 rounded-xl hover:shadow-md transition-all duration-200"
|
className="bg-white border border-stone-200 p-6 rounded-xl hover:shadow-md transition-all duration-200 group relative"
|
||||||
>
|
>
|
||||||
<div className="flex items-start justify-between">
|
<div className="flex items-start justify-between">
|
||||||
<div className="flex-1">
|
<div className="flex-1">
|
||||||
@@ -191,26 +193,23 @@ export function AnalyticsDashboard({ isAuthenticated }: AnalyticsDashboardProps)
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<p className="text-3xl font-bold text-stone-900 mb-2">{value}</p>
|
<p className="text-3xl font-bold text-stone-900 mb-2">{value}</p>
|
||||||
{trend && trendValue && (
|
</div>
|
||||||
<div className={`flex items-center space-x-1 text-sm ${
|
</div>
|
||||||
trend === 'up' ? 'text-green-600' :
|
{tooltip && (
|
||||||
trend === 'down' ? 'text-red-600' : 'text-yellow-600'
|
<div className="absolute bottom-full left-1/2 -translate-x-1/2 mb-2 px-3 py-2 bg-stone-900/95 text-stone-50 text-xs font-medium rounded-lg opacity-0 group-hover:opacity-100 transition-opacity whitespace-normal max-w-xs z-50 shadow-xl backdrop-blur-sm pointer-events-none">
|
||||||
}`}>
|
{tooltip}
|
||||||
<TrendingUp className={`w-4 h-4 ${trend === 'down' ? 'rotate-180' : ''}`} />
|
<div className="absolute top-full left-1/2 -translate-x-1/2 -mt-1 w-2 h-2 bg-stone-900/95 rotate-45"></div>
|
||||||
<span>{trendValue}</span>
|
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</motion.div>
|
</motion.div>
|
||||||
);
|
);
|
||||||
|
|
||||||
const getDifficultyColor = (difficulty: string) => {
|
const getDifficultyColor = (difficulty: string) => {
|
||||||
switch (difficulty) {
|
switch (difficulty) {
|
||||||
case 'Beginner': return 'bg-green-50 text-green-700 border-green-200';
|
case 'Beginner': return 'bg-stone-50 text-stone-700 border-stone-200';
|
||||||
case 'Intermediate': return 'bg-yellow-50 text-yellow-700 border-yellow-200';
|
case 'Intermediate': return 'bg-stone-100 text-stone-700 border-stone-300';
|
||||||
case 'Advanced': return 'bg-orange-50 text-orange-700 border-orange-200';
|
case 'Advanced': return 'bg-stone-200 text-stone-800 border-stone-400';
|
||||||
case 'Expert': return 'bg-red-50 text-red-700 border-red-200';
|
case 'Expert': return 'bg-stone-300 text-stone-900 border-stone-500';
|
||||||
default: return 'bg-stone-50 text-stone-600 border-stone-200';
|
default: return 'bg-stone-50 text-stone-600 border-stone-200';
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@@ -237,7 +236,7 @@ export function AnalyticsDashboard({ isAuthenticated }: AnalyticsDashboardProps)
|
|||||||
<BarChart3 className="w-8 h-8 mr-3 text-stone-600" />
|
<BarChart3 className="w-8 h-8 mr-3 text-stone-600" />
|
||||||
Analytics Dashboard
|
Analytics Dashboard
|
||||||
</h1>
|
</h1>
|
||||||
<p className="text-stone-500 mt-2">Portfolio performance and user engagement metrics</p>
|
<p className="text-stone-500 mt-2">Portfolio performance and analytics metrics</p>
|
||||||
</div>
|
</div>
|
||||||
<div className="flex items-center space-x-3">
|
<div className="flex items-center space-x-3">
|
||||||
{/* Time Range Selector */}
|
{/* Time Range Selector */}
|
||||||
@@ -307,45 +306,42 @@ export function AnalyticsDashboard({ isAuthenticated }: AnalyticsDashboardProps)
|
|||||||
value={data.overview.totalViews.toLocaleString()}
|
value={data.overview.totalViews.toLocaleString()}
|
||||||
icon={Eye}
|
icon={Eye}
|
||||||
color="bg-stone-100 text-stone-600"
|
color="bg-stone-100 text-stone-600"
|
||||||
trend="up"
|
|
||||||
trendValue="+12.5%"
|
|
||||||
description="All-time page views"
|
description="All-time page views"
|
||||||
|
tooltip="✅ REAL DATA: Total page views tracked from the PageView database table. Each visit to a project page or the homepage is automatically recorded with IP, user agent, and timestamp."
|
||||||
/>
|
/>
|
||||||
<StatCard
|
<StatCard
|
||||||
title="Projects"
|
title="Projects"
|
||||||
value={data.overview.totalProjects}
|
value={data.overview.totalProjects}
|
||||||
icon={Globe}
|
icon={Globe}
|
||||||
color="bg-green-100 text-green-600"
|
color="bg-stone-100 text-stone-600"
|
||||||
trend="up"
|
|
||||||
trendValue="+2"
|
|
||||||
description={`${data.overview.publishedProjects} published`}
|
description={`${data.overview.publishedProjects} published`}
|
||||||
/>
|
tooltip="✅ REAL DATA: Total number of projects in your portfolio. Shows published vs unpublished projects from your database."
|
||||||
<StatCard
|
|
||||||
title="Engagement"
|
|
||||||
value={data.overview.totalLikes}
|
|
||||||
icon={Heart}
|
|
||||||
color="bg-pink-100 text-pink-600"
|
|
||||||
trend="up"
|
|
||||||
trendValue="+8.2%"
|
|
||||||
description="Total likes & shares"
|
|
||||||
/>
|
/>
|
||||||
<StatCard
|
<StatCard
|
||||||
title="Performance"
|
title="Performance"
|
||||||
value={data.overview.avgLighthouse}
|
value={data.overview.avgLighthouse > 0 ? data.overview.avgLighthouse : 'N/A'}
|
||||||
icon={Zap}
|
icon={Zap}
|
||||||
color="bg-orange-100 text-orange-600"
|
color="bg-stone-100 text-stone-600"
|
||||||
trend="up"
|
description={data.overview.avgLighthouse > 0 ? "Avg Lighthouse score" : "No performance data yet"}
|
||||||
trendValue="+5%"
|
tooltip={data.overview.avgLighthouse > 0
|
||||||
description="Avg Lighthouse score"
|
? "✅ REAL DATA: Average Lighthouse performance score (0-100) calculated from real Web Vitals metrics (LCP, FCP, CLS, FID, TTFB) collected from actual page visits. Only shown when real performance data exists."
|
||||||
|
: "No performance data collected yet. Scores will appear after visitors load your pages and Web Vitals are tracked."}
|
||||||
/>
|
/>
|
||||||
<StatCard
|
<StatCard
|
||||||
title="Bounce Rate"
|
title="Bounce Rate"
|
||||||
value={`${data.metrics.bounceRate}%`}
|
value={`${data.metrics?.bounceRate || 0}%`}
|
||||||
icon={MousePointer}
|
icon={MousePointer}
|
||||||
color="bg-stone-100 text-stone-600"
|
color="bg-stone-100 text-stone-600"
|
||||||
trend="down"
|
|
||||||
trendValue="-2.1%"
|
|
||||||
description="User retention"
|
description="User retention"
|
||||||
|
tooltip="✅ REAL DATA: Percentage of sessions where users viewed only one page before leaving. Calculated from PageView records grouped by IP address. Lower is better."
|
||||||
|
/>
|
||||||
|
<StatCard
|
||||||
|
title="Avg Session"
|
||||||
|
value={data.metrics?.avgSessionDuration ? `${Math.round(data.metrics.avgSessionDuration / 60)}m` : '0m'}
|
||||||
|
icon={Activity}
|
||||||
|
color="bg-stone-100 text-stone-600"
|
||||||
|
description="Average session duration"
|
||||||
|
tooltip="✅ REAL DATA: Average time users spend on your site per session, calculated from the time difference between first and last pageview per IP address. Only calculated for sessions with multiple pageviews."
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -355,7 +351,7 @@ export function AnalyticsDashboard({ isAuthenticated }: AnalyticsDashboardProps)
|
|||||||
{/* Top Projects */}
|
{/* Top Projects */}
|
||||||
<div className="bg-white border border-stone-200 p-6 rounded-xl shadow-sm">
|
<div className="bg-white border border-stone-200 p-6 rounded-xl shadow-sm">
|
||||||
<h3 className="text-xl font-bold text-stone-900 mb-6 flex items-center">
|
<h3 className="text-xl font-bold text-stone-900 mb-6 flex items-center">
|
||||||
<Award className="w-5 h-5 mr-2 text-yellow-500" />
|
<Award className="w-5 h-5 mr-2 text-stone-600" />
|
||||||
Top Performing Projects
|
Top Performing Projects
|
||||||
</h3>
|
</h3>
|
||||||
<div className="space-y-4">
|
<div className="space-y-4">
|
||||||
@@ -379,9 +375,13 @@ export function AnalyticsDashboard({ isAuthenticated }: AnalyticsDashboardProps)
|
|||||||
<p className="text-stone-500 text-sm">{project.category}</p>
|
<p className="text-stone-500 text-sm">{project.category}</p>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div className="text-right">
|
<div className="text-right group/views relative">
|
||||||
<p className="text-stone-900 font-bold">{project.views.toLocaleString()}</p>
|
<p className="text-stone-900 font-bold">{project.views.toLocaleString()}</p>
|
||||||
<p className="text-stone-500 text-sm">views</p>
|
<p className="text-stone-500 text-sm">views</p>
|
||||||
|
<div className="absolute bottom-full right-0 mb-2 px-3 py-2 bg-stone-900/95 text-stone-50 text-xs font-medium rounded-lg opacity-0 group-hover/views:opacity-100 transition-opacity whitespace-normal max-w-xs z-50 shadow-xl backdrop-blur-sm pointer-events-none">
|
||||||
|
✅ REAL DATA: Page views tracked from PageView table for this project. Each visit is automatically recorded.
|
||||||
|
<div className="absolute top-full right-4 -mt-1 w-2 h-2 bg-stone-900/95 rotate-45"></div>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</motion.div>
|
</motion.div>
|
||||||
))}
|
))}
|
||||||
@@ -391,7 +391,7 @@ export function AnalyticsDashboard({ isAuthenticated }: AnalyticsDashboardProps)
|
|||||||
{/* Categories Distribution */}
|
{/* Categories Distribution */}
|
||||||
<div className="bg-white border border-stone-200 p-6 rounded-xl shadow-sm">
|
<div className="bg-white border border-stone-200 p-6 rounded-xl shadow-sm">
|
||||||
<h3 className="text-xl font-bold text-stone-900 mb-6 flex items-center">
|
<h3 className="text-xl font-bold text-stone-900 mb-6 flex items-center">
|
||||||
<BarChart3 className="w-5 h-5 mr-2 text-green-600" />
|
<BarChart3 className="w-5 h-5 mr-2 text-stone-600" />
|
||||||
Categories
|
Categories
|
||||||
</h3>
|
</h3>
|
||||||
<div className="space-y-4">
|
<div className="space-y-4">
|
||||||
@@ -422,12 +422,12 @@ export function AnalyticsDashboard({ isAuthenticated }: AnalyticsDashboardProps)
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Difficulty & Engagement */}
|
{/* Difficulty & Activity */}
|
||||||
<div className="grid grid-cols-1 lg:grid-cols-2 gap-8">
|
<div className="grid grid-cols-1 lg:grid-cols-2 gap-8">
|
||||||
{/* Difficulty Distribution */}
|
{/* Difficulty Distribution */}
|
||||||
<div className="bg-white border border-stone-200 p-6 rounded-xl shadow-sm">
|
<div className="bg-white border border-stone-200 p-6 rounded-xl shadow-sm">
|
||||||
<h3 className="text-xl font-bold text-stone-900 mb-6 flex items-center">
|
<h3 className="text-xl font-bold text-stone-900 mb-6 flex items-center">
|
||||||
<Target className="w-5 h-5 mr-2 text-red-500" />
|
<Target className="w-5 h-5 mr-2 text-stone-600" />
|
||||||
Difficulty Levels
|
Difficulty Levels
|
||||||
</h3>
|
</h3>
|
||||||
<div className="grid grid-cols-2 gap-4">
|
<div className="grid grid-cols-2 gap-4">
|
||||||
@@ -465,7 +465,7 @@ export function AnalyticsDashboard({ isAuthenticated }: AnalyticsDashboardProps)
|
|||||||
transition={{ delay: index * 0.1 }}
|
transition={{ delay: index * 0.1 }}
|
||||||
className="flex items-center space-x-4 p-3 bg-stone-50 rounded-xl border border-stone-100"
|
className="flex items-center space-x-4 p-3 bg-stone-50 rounded-xl border border-stone-100"
|
||||||
>
|
>
|
||||||
<div className="w-2 h-2 bg-green-500 rounded-full animate-pulse"></div>
|
<div className="w-2 h-2 bg-stone-500 rounded-full animate-pulse"></div>
|
||||||
<div className="flex-1">
|
<div className="flex-1">
|
||||||
<p className="text-stone-900 font-medium text-sm">{project.title}</p>
|
<p className="text-stone-900 font-medium text-sm">{project.title}</p>
|
||||||
<p className="text-stone-500 text-xs">
|
<p className="text-stone-500 text-xs">
|
||||||
@@ -480,8 +480,8 @@ export function AnalyticsDashboard({ isAuthenticated }: AnalyticsDashboardProps)
|
|||||||
)}
|
)}
|
||||||
<span className={`px-2 py-1 rounded-full text-xs font-medium ${
|
<span className={`px-2 py-1 rounded-full text-xs font-medium ${
|
||||||
project.published
|
project.published
|
||||||
? 'bg-green-100 text-green-700'
|
? 'bg-stone-100 text-stone-700'
|
||||||
: 'bg-yellow-100 text-yellow-700'
|
: 'bg-stone-200 text-stone-700'
|
||||||
}`}>
|
}`}>
|
||||||
{project.published ? 'Live' : 'Draft'}
|
{project.published ? 'Live' : 'Draft'}
|
||||||
</span>
|
</span>
|
||||||
@@ -518,13 +518,13 @@ export function AnalyticsDashboard({ isAuthenticated }: AnalyticsDashboardProps)
|
|||||||
<label className="block text-stone-600 text-sm mb-2">Reset Type</label>
|
<label className="block text-stone-600 text-sm mb-2">Reset Type</label>
|
||||||
<select
|
<select
|
||||||
value={resetType}
|
value={resetType}
|
||||||
onChange={(e) => setResetType(e.target.value as 'all' | 'performance' | 'analytics')}
|
onChange={(e) => setResetType(e.target.value as 'analytics' | 'pageviews' | 'interactions' | 'performance' | 'all')}
|
||||||
className="w-full px-3 py-2 bg-stone-50 border border-stone-200 rounded-lg text-stone-900 focus:outline-none focus:ring-2 focus:ring-red-500"
|
className="w-full px-3 py-2 bg-stone-50 border border-stone-200 rounded-lg text-stone-900 focus:outline-none focus:ring-2 focus:ring-red-500"
|
||||||
>
|
>
|
||||||
<option value="analytics">Analytics Only (views, likes, shares)</option>
|
<option value="analytics">Analytics Only (project view counts)</option>
|
||||||
<option value="pageviews">Page Views Only</option>
|
<option value="pageviews">Page Views Only (all tracked visits)</option>
|
||||||
<option value="interactions">User Interactions Only</option>
|
<option value="interactions">User Interactions Only</option>
|
||||||
<option value="performance">Performance Metrics Only</option>
|
<option value="performance">Performance Metrics Only (Lighthouse scores)</option>
|
||||||
<option value="all">Everything (Complete Reset)</option>
|
<option value="all">Everything (Complete Reset)</option>
|
||||||
</select>
|
</select>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -9,27 +9,126 @@ interface AnalyticsProviderProps {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export const AnalyticsProvider: React.FC<AnalyticsProviderProps> = ({ children }) => {
|
export const AnalyticsProvider: React.FC<AnalyticsProviderProps> = ({ children }) => {
|
||||||
// Initialize Web Vitals tracking
|
// Initialize Web Vitals tracking - wrapped to prevent crashes
|
||||||
|
// Hooks must be called unconditionally, but the hook itself handles errors
|
||||||
useWebVitals();
|
useWebVitals();
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (typeof window === 'undefined') return;
|
if (typeof window === 'undefined') return;
|
||||||
|
|
||||||
|
// Wrap entire effect in try-catch to prevent any errors from breaking the app
|
||||||
|
try {
|
||||||
|
|
||||||
// Track page view
|
// Track page view
|
||||||
const trackPageView = () => {
|
const trackPageView = async () => {
|
||||||
|
const path = window.location.pathname;
|
||||||
|
const projectMatch = path.match(/\/projects\/([^\/]+)/);
|
||||||
|
const projectId = projectMatch ? projectMatch[1] : null;
|
||||||
|
|
||||||
|
// Track to Umami (if available)
|
||||||
trackEvent('page-view', {
|
trackEvent('page-view', {
|
||||||
url: window.location.pathname,
|
url: path,
|
||||||
referrer: document.referrer,
|
referrer: document.referrer,
|
||||||
timestamp: Date.now(),
|
timestamp: Date.now(),
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Track to our API
|
||||||
|
try {
|
||||||
|
await fetch('/api/analytics/track', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
},
|
||||||
|
body: JSON.stringify({
|
||||||
|
type: 'pageview',
|
||||||
|
projectId: projectId,
|
||||||
|
page: path
|
||||||
|
})
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
// Silently fail
|
||||||
|
if (process.env.NODE_ENV === 'development') {
|
||||||
|
console.error('Error tracking page view:', error);
|
||||||
|
}
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
// Track page load performance
|
// Track page load performance - wrapped in try-catch
|
||||||
|
try {
|
||||||
trackPageLoad();
|
trackPageLoad();
|
||||||
|
} catch (error) {
|
||||||
|
// Silently fail
|
||||||
|
if (process.env.NODE_ENV === 'development') {
|
||||||
|
console.warn('Error tracking page load:', error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Track initial page view
|
// Track initial page view
|
||||||
trackPageView();
|
trackPageView();
|
||||||
|
|
||||||
|
// Track performance metrics to our API
|
||||||
|
const trackPerformanceToAPI = async () => {
|
||||||
|
try {
|
||||||
|
// Get current page path to extract project ID if on project page
|
||||||
|
const path = window.location.pathname;
|
||||||
|
const projectMatch = path.match(/\/projects\/([^\/]+)/);
|
||||||
|
const projectId = projectMatch ? projectMatch[1] : null;
|
||||||
|
|
||||||
|
// Wait for page to fully load
|
||||||
|
setTimeout(async () => {
|
||||||
|
try {
|
||||||
|
const navigation = performance.getEntriesByType('navigation')[0] as PerformanceNavigationTiming | undefined;
|
||||||
|
const paintEntries = performance.getEntriesByType('paint');
|
||||||
|
const lcpEntries = performance.getEntriesByType('largest-contentful-paint');
|
||||||
|
|
||||||
|
const fcp = paintEntries.find((e: PerformanceEntry) => e.name === 'first-contentful-paint');
|
||||||
|
const lcp = lcpEntries.length > 0 ? lcpEntries[lcpEntries.length - 1] : undefined;
|
||||||
|
|
||||||
|
const performanceData = {
|
||||||
|
loadTime: navigation && navigation.loadEventEnd && navigation.fetchStart ? navigation.loadEventEnd - navigation.fetchStart : 0,
|
||||||
|
fcp: fcp ? fcp.startTime : 0,
|
||||||
|
lcp: lcp ? lcp.startTime : 0,
|
||||||
|
ttfb: navigation && navigation.responseStart && navigation.fetchStart ? navigation.responseStart - navigation.fetchStart : 0,
|
||||||
|
cls: 0, // Will be updated by CLS observer
|
||||||
|
fid: 0, // Will be updated by FID observer
|
||||||
|
si: 0 // Speed Index - would need to calculate
|
||||||
|
};
|
||||||
|
|
||||||
|
// Send performance data
|
||||||
|
await fetch('/api/analytics/track', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
},
|
||||||
|
body: JSON.stringify({
|
||||||
|
type: 'performance',
|
||||||
|
projectId: projectId,
|
||||||
|
page: path,
|
||||||
|
performance: performanceData
|
||||||
|
})
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
// Silently fail - performance tracking is not critical
|
||||||
|
if (process.env.NODE_ENV === 'development') {
|
||||||
|
console.warn('Error collecting performance data:', error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}, 2000); // Wait 2 seconds for page to stabilize
|
||||||
|
} catch (error) {
|
||||||
|
// Silently fail
|
||||||
|
if (process.env.NODE_ENV === 'development') {
|
||||||
|
console.error('Error tracking performance:', error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// Track performance after page load
|
||||||
|
if (document.readyState === 'complete') {
|
||||||
|
trackPerformanceToAPI();
|
||||||
|
} else {
|
||||||
|
window.addEventListener('load', trackPerformanceToAPI);
|
||||||
|
}
|
||||||
|
|
||||||
// Track route changes (for SPA navigation)
|
// Track route changes (for SPA navigation)
|
||||||
const handleRouteChange = () => {
|
const handleRouteChange = () => {
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
@@ -43,8 +142,13 @@ export const AnalyticsProvider: React.FC<AnalyticsProviderProps> = ({ children }
|
|||||||
|
|
||||||
// Track user interactions
|
// Track user interactions
|
||||||
const handleClick = (event: MouseEvent) => {
|
const handleClick = (event: MouseEvent) => {
|
||||||
const target = event.target as HTMLElement;
|
try {
|
||||||
const element = target.tagName.toLowerCase();
|
if (typeof window === 'undefined') return;
|
||||||
|
|
||||||
|
const target = event.target as HTMLElement | null;
|
||||||
|
if (!target) return;
|
||||||
|
|
||||||
|
const element = target.tagName ? target.tagName.toLowerCase() : 'unknown';
|
||||||
const className = target.className;
|
const className = target.className;
|
||||||
const id = target.id;
|
const id = target.id;
|
||||||
|
|
||||||
@@ -54,23 +158,48 @@ export const AnalyticsProvider: React.FC<AnalyticsProviderProps> = ({ children }
|
|||||||
id: id || undefined,
|
id: id || undefined,
|
||||||
url: window.location.pathname,
|
url: window.location.pathname,
|
||||||
});
|
});
|
||||||
|
} catch (error) {
|
||||||
|
// Silently fail - click tracking is not critical
|
||||||
|
if (process.env.NODE_ENV === 'development') {
|
||||||
|
console.warn('Error tracking click:', error);
|
||||||
|
}
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
// Track form submissions
|
// Track form submissions
|
||||||
const handleSubmit = (event: SubmitEvent) => {
|
const handleSubmit = (event: SubmitEvent) => {
|
||||||
const form = event.target as HTMLFormElement;
|
try {
|
||||||
|
if (typeof window === 'undefined') return;
|
||||||
|
|
||||||
|
const form = event.target as HTMLFormElement | null;
|
||||||
|
if (!form) return;
|
||||||
|
|
||||||
trackEvent('form-submit', {
|
trackEvent('form-submit', {
|
||||||
formId: form.id || undefined,
|
formId: form.id || undefined,
|
||||||
formClass: form.className || undefined,
|
formClass: form.className || undefined,
|
||||||
url: window.location.pathname,
|
url: window.location.pathname,
|
||||||
});
|
});
|
||||||
|
} catch (error) {
|
||||||
|
// Silently fail - form tracking is not critical
|
||||||
|
if (process.env.NODE_ENV === 'development') {
|
||||||
|
console.warn('Error tracking form submit:', error);
|
||||||
|
}
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
// Track scroll depth
|
// Track scroll depth
|
||||||
let maxScrollDepth = 0;
|
let maxScrollDepth = 0;
|
||||||
const handleScroll = () => {
|
const handleScroll = () => {
|
||||||
|
try {
|
||||||
|
if (typeof window === 'undefined' || typeof document === 'undefined') return;
|
||||||
|
|
||||||
|
const scrollHeight = document.documentElement.scrollHeight;
|
||||||
|
const innerHeight = window.innerHeight;
|
||||||
|
|
||||||
|
if (scrollHeight <= innerHeight) return; // No scrollable content
|
||||||
|
|
||||||
const scrollDepth = Math.round(
|
const scrollDepth = Math.round(
|
||||||
(window.scrollY / (document.documentElement.scrollHeight - window.innerHeight)) * 100
|
(window.scrollY / (scrollHeight - innerHeight)) * 100
|
||||||
);
|
);
|
||||||
|
|
||||||
if (scrollDepth > maxScrollDepth) {
|
if (scrollDepth > maxScrollDepth) {
|
||||||
@@ -87,6 +216,12 @@ export const AnalyticsProvider: React.FC<AnalyticsProviderProps> = ({ children }
|
|||||||
trackEvent('scroll-depth', { depth: 90, url: window.location.pathname });
|
trackEvent('scroll-depth', { depth: 90, url: window.location.pathname });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
} catch (error) {
|
||||||
|
// Silently fail - scroll tracking is not critical
|
||||||
|
if (process.env.NODE_ENV === 'development') {
|
||||||
|
console.warn('Error tracking scroll:', error);
|
||||||
|
}
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
// Add event listeners
|
// Add event listeners
|
||||||
@@ -96,20 +231,36 @@ export const AnalyticsProvider: React.FC<AnalyticsProviderProps> = ({ children }
|
|||||||
|
|
||||||
// Track errors
|
// Track errors
|
||||||
const handleError = (event: ErrorEvent) => {
|
const handleError = (event: ErrorEvent) => {
|
||||||
|
try {
|
||||||
|
if (typeof window === 'undefined') return;
|
||||||
trackEvent('error', {
|
trackEvent('error', {
|
||||||
message: event.message,
|
message: event.message || 'Unknown error',
|
||||||
filename: event.filename,
|
filename: event.filename || undefined,
|
||||||
lineno: event.lineno,
|
lineno: event.lineno || undefined,
|
||||||
colno: event.colno,
|
colno: event.colno || undefined,
|
||||||
url: window.location.pathname,
|
url: window.location.pathname,
|
||||||
});
|
});
|
||||||
|
} catch (error) {
|
||||||
|
// Silently fail - error tracking should not cause more errors
|
||||||
|
if (process.env.NODE_ENV === 'development') {
|
||||||
|
console.warn('Error tracking error event:', error);
|
||||||
|
}
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleUnhandledRejection = (event: PromiseRejectionEvent) => {
|
const handleUnhandledRejection = (event: PromiseRejectionEvent) => {
|
||||||
|
try {
|
||||||
|
if (typeof window === 'undefined') return;
|
||||||
trackEvent('unhandled-rejection', {
|
trackEvent('unhandled-rejection', {
|
||||||
reason: event.reason?.toString(),
|
reason: event.reason?.toString() || 'Unknown rejection',
|
||||||
url: window.location.pathname,
|
url: window.location.pathname,
|
||||||
});
|
});
|
||||||
|
} catch (error) {
|
||||||
|
// Silently fail - error tracking should not cause more errors
|
||||||
|
if (process.env.NODE_ENV === 'development') {
|
||||||
|
console.warn('Error tracking unhandled rejection:', error);
|
||||||
|
}
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
window.addEventListener('error', handleError);
|
window.addEventListener('error', handleError);
|
||||||
@@ -117,14 +268,27 @@ export const AnalyticsProvider: React.FC<AnalyticsProviderProps> = ({ children }
|
|||||||
|
|
||||||
// Cleanup
|
// Cleanup
|
||||||
return () => {
|
return () => {
|
||||||
|
try {
|
||||||
window.removeEventListener('popstate', handleRouteChange);
|
window.removeEventListener('popstate', handleRouteChange);
|
||||||
document.removeEventListener('click', handleClick);
|
document.removeEventListener('click', handleClick);
|
||||||
document.removeEventListener('submit', handleSubmit);
|
document.removeEventListener('submit', handleSubmit);
|
||||||
window.removeEventListener('scroll', handleScroll);
|
window.removeEventListener('scroll', handleScroll);
|
||||||
window.removeEventListener('error', handleError);
|
window.removeEventListener('error', handleError);
|
||||||
window.removeEventListener('unhandledrejection', handleUnhandledRejection);
|
window.removeEventListener('unhandledrejection', handleUnhandledRejection);
|
||||||
|
} catch {
|
||||||
|
// Silently fail during cleanup
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
} catch (error) {
|
||||||
|
// If anything fails, log but don't break the app
|
||||||
|
if (process.env.NODE_ENV === 'development') {
|
||||||
|
console.error('AnalyticsProvider initialization error:', error);
|
||||||
|
}
|
||||||
|
// Return empty cleanup function
|
||||||
|
return () => {};
|
||||||
|
}
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
|
// Always render children, even if analytics fails
|
||||||
return <>{children}</>;
|
return <>{children}</>;
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -27,7 +27,16 @@ const BackgroundBlobs = () => {
|
|||||||
const x5 = useTransform(springX, (value) => value / 15);
|
const x5 = useTransform(springX, (value) => value / 15);
|
||||||
const y5 = useTransform(springY, (value) => value / 15);
|
const y5 = useTransform(springY, (value) => value / 15);
|
||||||
|
|
||||||
|
// Prevent hydration mismatch
|
||||||
|
const [mounted, setMounted] = useState(false);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
|
setMounted(true);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!mounted) return;
|
||||||
|
|
||||||
const handleMouseMove = (e: MouseEvent) => {
|
const handleMouseMove = (e: MouseEvent) => {
|
||||||
const x = e.clientX - window.innerWidth / 2;
|
const x = e.clientX - window.innerWidth / 2;
|
||||||
const y = e.clientY - window.innerHeight / 2;
|
const y = e.clientY - window.innerHeight / 2;
|
||||||
@@ -37,14 +46,7 @@ const BackgroundBlobs = () => {
|
|||||||
|
|
||||||
window.addEventListener("mousemove", handleMouseMove);
|
window.addEventListener("mousemove", handleMouseMove);
|
||||||
return () => window.removeEventListener("mousemove", handleMouseMove);
|
return () => window.removeEventListener("mousemove", handleMouseMove);
|
||||||
}, [mouseX, mouseY]);
|
}, [mouseX, mouseY, mounted]);
|
||||||
|
|
||||||
// Prevent hydration mismatch
|
|
||||||
const [mounted, setMounted] = useState(false);
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
setMounted(true);
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
if (!mounted) return null;
|
if (!mounted) return null;
|
||||||
|
|
||||||
|
|||||||
@@ -22,18 +22,20 @@ export default class ErrorBoundary extends React.Component<
|
|||||||
|
|
||||||
render() {
|
render() {
|
||||||
if (this.state.hasError) {
|
if (this.state.hasError) {
|
||||||
|
// Still render children to prevent white screen - just log the error
|
||||||
|
if (process.env.NODE_ENV === 'development') {
|
||||||
return (
|
return (
|
||||||
<div className="p-4 m-4 bg-red-50 border border-red-200 rounded text-red-800">
|
<div>
|
||||||
<h2>Something went wrong!</h2>
|
<div className="p-2 m-2 bg-yellow-50 border border-yellow-200 rounded text-yellow-800 text-xs">
|
||||||
<button
|
⚠️ Error boundary triggered - rendering children anyway
|
||||||
className="mt-2 px-4 py-2 bg-red-600 text-white rounded hover:bg-red-700"
|
</div>
|
||||||
onClick={() => this.setState({ hasError: false })}
|
{this.props.children}
|
||||||
>
|
|
||||||
Try again
|
|
||||||
</button>
|
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
// In production, just render children silently
|
||||||
|
return this.props.children;
|
||||||
|
}
|
||||||
|
|
||||||
return this.props.children;
|
return this.props.children;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -157,14 +157,24 @@ const ModernAdminDashboard: React.FC<ModernAdminDashboardProps> = ({ isAuthentic
|
|||||||
const stats = {
|
const stats = {
|
||||||
totalProjects: projects.length,
|
totalProjects: projects.length,
|
||||||
publishedProjects: projects.filter(p => p.published).length,
|
publishedProjects: projects.filter(p => p.published).length,
|
||||||
totalViews: (analytics?.totalViews as number) || projects.reduce((sum, p) => sum + (p.analytics?.views || 0), 0),
|
totalViews: ((analytics?.overview as Record<string, unknown>)?.totalViews as number) || (analytics?.totalViews as number) || projects.reduce((sum, p) => sum + (p.analytics?.views || 0), 0),
|
||||||
unreadEmails: emails.filter(e => !(e.read as boolean)).length,
|
unreadEmails: emails.filter(e => !(e.read as boolean)).length,
|
||||||
avgPerformance: (analytics?.avgPerformance as number) || (projects.length > 0 ?
|
avgPerformance: (() => {
|
||||||
Math.round(projects.reduce((sum, p) => sum + (p.performance?.lighthouse || 90), 0) / projects.length) : 90),
|
// Only show real performance data, not defaults
|
||||||
|
const projectsWithPerf = projects.filter(p => {
|
||||||
|
const perf = p.performance as Record<string, unknown> || {};
|
||||||
|
return (perf.lighthouse as number || 0) > 0;
|
||||||
|
});
|
||||||
|
if (projectsWithPerf.length === 0) return 0;
|
||||||
|
return Math.round(projectsWithPerf.reduce((sum, p) => {
|
||||||
|
const perf = p.performance as Record<string, unknown> || {};
|
||||||
|
return sum + (perf.lighthouse as number || 0);
|
||||||
|
}, 0) / projectsWithPerf.length);
|
||||||
|
})(),
|
||||||
systemHealth: (systemStats?.status as string) || 'unknown',
|
systemHealth: (systemStats?.status as string) || 'unknown',
|
||||||
totalUsers: (analytics?.totalUsers as number) || 0,
|
totalUsers: ((analytics?.metrics as Record<string, unknown>)?.totalUsers as number) || (analytics?.totalUsers as number) || 0,
|
||||||
bounceRate: (analytics?.bounceRate as number) || 0,
|
bounceRate: ((analytics?.metrics as Record<string, unknown>)?.bounceRate as number) || (analytics?.bounceRate as number) || 0,
|
||||||
avgSessionDuration: (analytics?.avgSessionDuration as number) || 0
|
avgSessionDuration: ((analytics?.metrics as Record<string, unknown>)?.avgSessionDuration as number) || (analytics?.avgSessionDuration as number) || 0
|
||||||
};
|
};
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@@ -320,7 +330,7 @@ const ModernAdminDashboard: React.FC<ModernAdminDashboardProps> = ({ isAuthentic
|
|||||||
{/* Stats Grid - Mobile: 2x3, Desktop: 6x1 horizontal */}
|
{/* Stats Grid - Mobile: 2x3, Desktop: 6x1 horizontal */}
|
||||||
<div className="grid grid-cols-2 md:grid-cols-6 gap-3 md:gap-6">
|
<div className="grid grid-cols-2 md:grid-cols-6 gap-3 md:gap-6">
|
||||||
<div
|
<div
|
||||||
className="admin-glass-light p-4 rounded-xl cursor-pointer transition-all duration-200 transform-none hover:transform-none"
|
className="admin-glass-light p-4 rounded-xl cursor-pointer transition-all duration-200 transform-none hover:transform-none group relative"
|
||||||
onClick={() => setActiveTab('projects')}
|
onClick={() => setActiveTab('projects')}
|
||||||
>
|
>
|
||||||
<div className="flex flex-col space-y-2">
|
<div className="flex flex-col space-y-2">
|
||||||
@@ -329,12 +339,16 @@ const ModernAdminDashboard: React.FC<ModernAdminDashboardProps> = ({ isAuthentic
|
|||||||
<Database size={20} className="text-stone-400" />
|
<Database size={20} className="text-stone-400" />
|
||||||
</div>
|
</div>
|
||||||
<p className="text-xl md:text-2xl font-bold text-stone-900">{stats.totalProjects}</p>
|
<p className="text-xl md:text-2xl font-bold text-stone-900">{stats.totalProjects}</p>
|
||||||
<p className="text-green-600 text-xs font-medium">{stats.publishedProjects} published</p>
|
<p className="text-stone-600 text-xs font-medium">{stats.publishedProjects} published</p>
|
||||||
|
</div>
|
||||||
|
<div className="absolute bottom-full left-1/2 -translate-x-1/2 mb-2 px-3 py-2 bg-stone-900/95 text-stone-50 text-xs font-medium rounded-lg opacity-0 group-hover:opacity-100 transition-opacity whitespace-normal max-w-xs z-50 shadow-xl backdrop-blur-sm pointer-events-none">
|
||||||
|
✅ REAL DATA: Total projects in your portfolio from the database. Shows published vs unpublished count.
|
||||||
|
<div className="absolute top-full left-1/2 -translate-x-1/2 -mt-1 w-2 h-2 bg-stone-900/95 rotate-45"></div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div
|
<div
|
||||||
className="admin-glass-light p-4 rounded-xl cursor-pointer transition-all duration-200 transform-none hover:transform-none"
|
className="admin-glass-light p-4 rounded-xl cursor-pointer transition-all duration-200 transform-none hover:transform-none group relative"
|
||||||
onClick={() => setActiveTab('analytics')}
|
onClick={() => setActiveTab('analytics')}
|
||||||
>
|
>
|
||||||
<div className="flex flex-col space-y-2">
|
<div className="flex flex-col space-y-2">
|
||||||
@@ -345,6 +359,10 @@ const ModernAdminDashboard: React.FC<ModernAdminDashboardProps> = ({ isAuthentic
|
|||||||
<p className="text-xl md:text-2xl font-bold text-stone-900">{stats.totalViews.toLocaleString()}</p>
|
<p className="text-xl md:text-2xl font-bold text-stone-900">{stats.totalViews.toLocaleString()}</p>
|
||||||
<p className="text-stone-600 text-xs font-medium">{stats.totalUsers} users</p>
|
<p className="text-stone-600 text-xs font-medium">{stats.totalUsers} users</p>
|
||||||
</div>
|
</div>
|
||||||
|
<div className="absolute bottom-full left-1/2 -translate-x-1/2 mb-2 px-3 py-2 bg-stone-900/95 text-stone-50 text-xs font-medium rounded-lg opacity-0 group-hover:opacity-100 transition-opacity whitespace-normal max-w-xs z-50 shadow-xl backdrop-blur-sm pointer-events-none">
|
||||||
|
✅ REAL DATA: Total page views from PageView table (last 30 days). Each visit is tracked with IP, user agent, and timestamp. Users = unique IP addresses.
|
||||||
|
<div className="absolute top-full left-1/2 -translate-x-1/2 -mt-1 w-2 h-2 bg-stone-900/95 rotate-45"></div>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div
|
<div
|
||||||
@@ -362,7 +380,7 @@ const ModernAdminDashboard: React.FC<ModernAdminDashboardProps> = ({ isAuthentic
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div
|
<div
|
||||||
className="admin-glass-light p-4 rounded-xl cursor-pointer transition-all duration-200 transform-none hover:transform-none"
|
className="admin-glass-light p-4 rounded-xl cursor-pointer transition-all duration-200 transform-none hover:transform-none group relative"
|
||||||
onClick={() => setActiveTab('analytics')}
|
onClick={() => setActiveTab('analytics')}
|
||||||
>
|
>
|
||||||
<div className="flex flex-col space-y-2">
|
<div className="flex flex-col space-y-2">
|
||||||
@@ -370,13 +388,19 @@ const ModernAdminDashboard: React.FC<ModernAdminDashboardProps> = ({ isAuthentic
|
|||||||
<p className="text-stone-500 text-xs md:text-sm font-medium">Performance</p>
|
<p className="text-stone-500 text-xs md:text-sm font-medium">Performance</p>
|
||||||
<TrendingUp size={20} className="text-stone-400" />
|
<TrendingUp size={20} className="text-stone-400" />
|
||||||
</div>
|
</div>
|
||||||
<p className="text-xl md:text-2xl font-bold text-stone-900">{stats.avgPerformance}</p>
|
<p className="text-xl md:text-2xl font-bold text-stone-900">{stats.avgPerformance || 'N/A'}</p>
|
||||||
<p className="text-orange-500 text-xs font-medium">Lighthouse Score</p>
|
<p className="text-stone-600 text-xs font-medium">Lighthouse Score</p>
|
||||||
|
</div>
|
||||||
|
<div className="absolute bottom-full left-1/2 -translate-x-1/2 mb-2 px-3 py-2 bg-stone-900/95 text-stone-50 text-xs font-medium rounded-lg opacity-0 group-hover:opacity-100 transition-opacity whitespace-normal max-w-xs z-50 shadow-xl backdrop-blur-sm pointer-events-none">
|
||||||
|
{stats.avgPerformance > 0
|
||||||
|
? "✅ REAL DATA: Average Lighthouse score (0-100) calculated from real Web Vitals (LCP, FCP, CLS, FID, TTFB) collected from actual page visits. Only averages projects with real performance data."
|
||||||
|
: "No performance data yet. Scores appear after visitors load pages and Web Vitals are tracked."}
|
||||||
|
<div className="absolute top-full left-1/2 -translate-x-1/2 -mt-1 w-2 h-2 bg-stone-900/95 rotate-45"></div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div
|
<div
|
||||||
className="admin-glass-light p-4 rounded-xl cursor-pointer transition-all duration-200 transform-none hover:transform-none"
|
className="admin-glass-light p-4 rounded-xl cursor-pointer transition-all duration-200 transform-none hover:transform-none group relative"
|
||||||
onClick={() => setActiveTab('analytics')}
|
onClick={() => setActiveTab('analytics')}
|
||||||
>
|
>
|
||||||
<div className="flex flex-col space-y-2">
|
<div className="flex flex-col space-y-2">
|
||||||
@@ -385,7 +409,11 @@ const ModernAdminDashboard: React.FC<ModernAdminDashboardProps> = ({ isAuthentic
|
|||||||
<Users size={20} className="text-stone-400" />
|
<Users size={20} className="text-stone-400" />
|
||||||
</div>
|
</div>
|
||||||
<p className="text-xl md:text-2xl font-bold text-stone-900">{stats.bounceRate}%</p>
|
<p className="text-xl md:text-2xl font-bold text-stone-900">{stats.bounceRate}%</p>
|
||||||
<p className="text-red-500 text-xs font-medium">Exit rate</p>
|
<p className="text-stone-600 text-xs font-medium">Exit rate</p>
|
||||||
|
</div>
|
||||||
|
<div className="absolute bottom-full left-1/2 -translate-x-1/2 mb-2 px-3 py-2 bg-stone-900/95 text-stone-50 text-xs font-medium rounded-lg opacity-0 group-hover:opacity-100 transition-opacity whitespace-normal max-w-xs z-50 shadow-xl backdrop-blur-sm pointer-events-none">
|
||||||
|
✅ REAL DATA: Percentage of sessions with only 1 pageview (calculated from PageView records grouped by IP). Lower is better. Shows how many visitors leave after viewing just one page.
|
||||||
|
<div className="absolute top-full left-1/2 -translate-x-1/2 -mt-1 w-2 h-2 bg-stone-900/95 rotate-45"></div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -401,7 +429,7 @@ const ModernAdminDashboard: React.FC<ModernAdminDashboardProps> = ({ isAuthentic
|
|||||||
<p className="text-xl md:text-2xl font-bold text-stone-900">Online</p>
|
<p className="text-xl md:text-2xl font-bold text-stone-900">Online</p>
|
||||||
<div className="flex items-center space-x-1">
|
<div className="flex items-center space-x-1">
|
||||||
<div className="w-2 h-2 bg-green-500 rounded-full animate-pulse"></div>
|
<div className="w-2 h-2 bg-green-500 rounded-full animate-pulse"></div>
|
||||||
<p className="text-green-600 text-xs font-medium">Operational</p>
|
<p className="text-stone-600 text-xs font-medium">Operational</p>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -34,8 +34,8 @@ const ToastItem = ({ toast, onRemove }: ToastProps) => {
|
|||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (toast.duration !== 0) {
|
if (toast.duration !== 0) {
|
||||||
const timer = setTimeout(() => {
|
const timer = setTimeout(() => {
|
||||||
setTimeout(() => onRemove(toast.id), 300);
|
setTimeout(() => onRemove(toast.id), 200);
|
||||||
}, toast.duration || 5000);
|
}, toast.duration || 3000);
|
||||||
|
|
||||||
return () => clearTimeout(timer);
|
return () => clearTimeout(timer);
|
||||||
}
|
}
|
||||||
@@ -59,39 +59,39 @@ const ToastItem = ({ toast, onRemove }: ToastProps) => {
|
|||||||
const getColors = () => {
|
const getColors = () => {
|
||||||
switch (toast.type) {
|
switch (toast.type) {
|
||||||
case 'success':
|
case 'success':
|
||||||
return 'bg-white border-green-300 text-green-900 shadow-lg';
|
return 'bg-stone-50 border-green-300 text-green-900 shadow-md';
|
||||||
case 'error':
|
case 'error':
|
||||||
return 'bg-white border-red-300 text-red-900 shadow-lg';
|
return 'bg-stone-50 border-red-200 text-red-800 shadow-md';
|
||||||
case 'warning':
|
case 'warning':
|
||||||
return 'bg-white border-yellow-300 text-yellow-900 shadow-lg';
|
return 'bg-stone-50 border-yellow-200 text-yellow-800 shadow-md';
|
||||||
case 'info':
|
case 'info':
|
||||||
return 'bg-white border-blue-300 text-blue-900 shadow-lg';
|
return 'bg-stone-50 border-stone-200 text-stone-800 shadow-md';
|
||||||
default:
|
default:
|
||||||
return 'bg-white border-gray-300 text-gray-900 shadow-lg';
|
return 'bg-stone-50 border-stone-200 text-stone-800 shadow-md';
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<motion.div
|
<motion.div
|
||||||
initial={{ opacity: 0, y: -50, scale: 0.9 }}
|
initial={{ opacity: 0, y: -20, scale: 0.95 }}
|
||||||
animate={{ opacity: 1, y: 0, scale: 1 }}
|
animate={{ opacity: 1, y: 0, scale: 1 }}
|
||||||
exit={{ opacity: 0, y: -50, scale: 0.9 }}
|
exit={{ opacity: 0, y: -10, scale: 0.95 }}
|
||||||
transition={{ duration: 0.3, ease: "easeOut" }}
|
transition={{ duration: 0.2, ease: "easeOut" }}
|
||||||
className={`relative p-4 rounded-xl border ${getColors()} shadow-xl hover:shadow-2xl transition-all duration-300 max-w-sm`}
|
className={`relative p-3 rounded-lg border ${getColors()} shadow-lg hover:shadow-xl transition-all duration-200 max-w-xs text-sm`}
|
||||||
>
|
>
|
||||||
<div className="flex items-start space-x-3">
|
<div className="flex items-start space-x-2">
|
||||||
<div className="flex-shrink-0 mt-0.5">
|
<div className="flex-shrink-0 mt-0.5">
|
||||||
{getIcon()}
|
{getIcon()}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="flex-1 min-w-0">
|
<div className="flex-1 min-w-0">
|
||||||
<h4 className="text-sm font-semibold mb-1">{toast.title}</h4>
|
<h4 className="text-xs font-semibold mb-0.5 leading-tight">{toast.title}</h4>
|
||||||
<p className="text-sm opacity-90">{toast.message}</p>
|
<p className="text-xs opacity-90 leading-tight">{toast.message}</p>
|
||||||
|
|
||||||
{toast.action && (
|
{toast.action && (
|
||||||
<button
|
<button
|
||||||
onClick={toast.action.onClick}
|
onClick={toast.action.onClick}
|
||||||
className="mt-2 text-xs font-medium underline hover:no-underline transition-all"
|
className="mt-1.5 text-xs font-medium underline hover:no-underline transition-all"
|
||||||
>
|
>
|
||||||
{toast.action.label}
|
{toast.action.label}
|
||||||
</button>
|
</button>
|
||||||
@@ -100,9 +100,9 @@ const ToastItem = ({ toast, onRemove }: ToastProps) => {
|
|||||||
|
|
||||||
<button
|
<button
|
||||||
onClick={() => onRemove(toast.id)}
|
onClick={() => onRemove(toast.id)}
|
||||||
className="flex-shrink-0 p-1 rounded-lg hover:bg-gray-100 transition-colors"
|
className="flex-shrink-0 p-0.5 rounded hover:bg-gray-100/50 transition-colors"
|
||||||
>
|
>
|
||||||
<X className="w-4 h-4 text-gray-500" />
|
<X className="w-3 h-3 text-gray-500" />
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -111,8 +111,8 @@ const ToastItem = ({ toast, onRemove }: ToastProps) => {
|
|||||||
<motion.div
|
<motion.div
|
||||||
initial={{ width: '100%' }}
|
initial={{ width: '100%' }}
|
||||||
animate={{ width: '0%' }}
|
animate={{ width: '0%' }}
|
||||||
transition={{ duration: (toast.duration || 5000) / 1000, ease: "linear" }}
|
transition={{ duration: (toast.duration || 3000) / 1000, ease: "linear" }}
|
||||||
className="absolute bottom-0 left-0 h-1 bg-gradient-to-r from-stone-400 to-stone-600 rounded-b-xl"
|
className="absolute bottom-0 left-0 h-0.5 bg-gradient-to-r from-stone-400 to-stone-600 rounded-b-lg"
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
</motion.div>
|
</motion.div>
|
||||||
@@ -195,7 +195,7 @@ export const ToastProvider = ({ children }: { children: React.ReactNode }) => {
|
|||||||
type: 'error',
|
type: 'error',
|
||||||
title,
|
title,
|
||||||
message: message || '',
|
message: message || '',
|
||||||
duration: 6000
|
duration: 4000 // Shorter duration
|
||||||
});
|
});
|
||||||
}, [addToast]);
|
}, [addToast]);
|
||||||
|
|
||||||
|
|||||||
@@ -57,11 +57,13 @@ export const trackWebVitals = (metric: WebVitalsMetric) => {
|
|||||||
|
|
||||||
// Track page load performance
|
// Track page load performance
|
||||||
export const trackPageLoad = () => {
|
export const trackPageLoad = () => {
|
||||||
if (typeof window === 'undefined') return;
|
if (typeof window === 'undefined' || typeof performance === 'undefined') return;
|
||||||
|
|
||||||
const navigation = performance.getEntriesByType('navigation')[0] as PerformanceNavigationTiming;
|
try {
|
||||||
|
const navigationEntries = performance.getEntriesByType('navigation');
|
||||||
|
const navigation = navigationEntries[0] as PerformanceNavigationTiming | undefined;
|
||||||
|
|
||||||
if (navigation) {
|
if (navigation && navigation.loadEventEnd && navigation.fetchStart) {
|
||||||
trackPerformance({
|
trackPerformance({
|
||||||
name: 'page-load',
|
name: 'page-load',
|
||||||
value: navigation.loadEventEnd - navigation.fetchStart,
|
value: navigation.loadEventEnd - navigation.fetchStart,
|
||||||
@@ -72,19 +74,38 @@ export const trackPageLoad = () => {
|
|||||||
|
|
||||||
// Track individual timing phases
|
// Track individual timing phases
|
||||||
trackEvent('page-timing', {
|
trackEvent('page-timing', {
|
||||||
dns: Math.round(navigation.domainLookupEnd - navigation.domainLookupStart),
|
dns: navigation.domainLookupEnd && navigation.domainLookupStart
|
||||||
tcp: Math.round(navigation.connectEnd - navigation.connectStart),
|
? Math.round(navigation.domainLookupEnd - navigation.domainLookupStart)
|
||||||
request: Math.round(navigation.responseStart - navigation.requestStart),
|
: 0,
|
||||||
response: Math.round(navigation.responseEnd - navigation.responseStart),
|
tcp: navigation.connectEnd && navigation.connectStart
|
||||||
dom: Math.round(navigation.domContentLoadedEventEnd - navigation.responseEnd),
|
? Math.round(navigation.connectEnd - navigation.connectStart)
|
||||||
load: Math.round(navigation.loadEventEnd - navigation.domContentLoadedEventEnd),
|
: 0,
|
||||||
|
request: navigation.responseStart && navigation.requestStart
|
||||||
|
? Math.round(navigation.responseStart - navigation.requestStart)
|
||||||
|
: 0,
|
||||||
|
response: navigation.responseEnd && navigation.responseStart
|
||||||
|
? Math.round(navigation.responseEnd - navigation.responseStart)
|
||||||
|
: 0,
|
||||||
|
dom: navigation.domContentLoadedEventEnd && navigation.responseEnd
|
||||||
|
? Math.round(navigation.domContentLoadedEventEnd - navigation.responseEnd)
|
||||||
|
: 0,
|
||||||
|
load: navigation.loadEventEnd && navigation.domContentLoadedEventEnd
|
||||||
|
? Math.round(navigation.loadEventEnd - navigation.domContentLoadedEventEnd)
|
||||||
|
: 0,
|
||||||
url: window.location.pathname,
|
url: window.location.pathname,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
} catch (error) {
|
||||||
|
// Silently fail - performance tracking is not critical
|
||||||
|
if (process.env.NODE_ENV === 'development') {
|
||||||
|
console.warn('Error tracking page load:', error);
|
||||||
|
}
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
// Track API response times
|
// Track API response times
|
||||||
export const trackApiCall = (endpoint: string, duration: number, status: number) => {
|
export const trackApiCall = (endpoint: string, duration: number, status: number) => {
|
||||||
|
if (typeof window === 'undefined') return;
|
||||||
trackEvent('api-call', {
|
trackEvent('api-call', {
|
||||||
endpoint,
|
endpoint,
|
||||||
duration: Math.round(duration),
|
duration: Math.round(duration),
|
||||||
@@ -95,6 +116,7 @@ export const trackApiCall = (endpoint: string, duration: number, status: number)
|
|||||||
|
|
||||||
// Track user interactions
|
// Track user interactions
|
||||||
export const trackInteraction = (action: string, element?: string) => {
|
export const trackInteraction = (action: string, element?: string) => {
|
||||||
|
if (typeof window === 'undefined') return;
|
||||||
trackEvent('interaction', {
|
trackEvent('interaction', {
|
||||||
action,
|
action,
|
||||||
element,
|
element,
|
||||||
@@ -104,6 +126,7 @@ export const trackInteraction = (action: string, element?: string) => {
|
|||||||
|
|
||||||
// Track errors
|
// Track errors
|
||||||
export const trackError = (error: string, context?: string) => {
|
export const trackError = (error: string, context?: string) => {
|
||||||
|
if (typeof window === 'undefined') return;
|
||||||
trackEvent('error', {
|
trackEvent('error', {
|
||||||
error,
|
error,
|
||||||
context,
|
context,
|
||||||
|
|||||||
@@ -13,11 +13,15 @@ interface Metric {
|
|||||||
|
|
||||||
// Simple Web Vitals implementation (since we don't want to add external dependencies)
|
// Simple Web Vitals implementation (since we don't want to add external dependencies)
|
||||||
const getCLS = (onPerfEntry: (metric: Metric) => void) => {
|
const getCLS = (onPerfEntry: (metric: Metric) => void) => {
|
||||||
|
if (typeof window === 'undefined' || typeof PerformanceObserver === 'undefined') return null;
|
||||||
|
|
||||||
|
try {
|
||||||
let clsValue = 0;
|
let clsValue = 0;
|
||||||
let sessionValue = 0;
|
let sessionValue = 0;
|
||||||
let sessionEntries: PerformanceEntry[] = [];
|
let sessionEntries: PerformanceEntry[] = [];
|
||||||
|
|
||||||
const observer = new PerformanceObserver((list) => {
|
const observer = new PerformanceObserver((list) => {
|
||||||
|
try {
|
||||||
for (const entry of list.getEntries()) {
|
for (const entry of list.getEntries()) {
|
||||||
if (!(entry as PerformanceEntry & { hadRecentInput?: boolean }).hadRecentInput) {
|
if (!(entry as PerformanceEntry & { hadRecentInput?: boolean }).hadRecentInput) {
|
||||||
const firstSessionEntry = sessionEntries[0];
|
const firstSessionEntry = sessionEntries[0];
|
||||||
@@ -42,28 +46,64 @@ const getCLS = (onPerfEntry: (metric: Metric) => void) => {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
} catch (error) {
|
||||||
|
// Silently fail - CLS tracking is not critical
|
||||||
|
if (process.env.NODE_ENV === 'development') {
|
||||||
|
console.warn('CLS tracking error:', error);
|
||||||
|
}
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
observer.observe({ type: 'layout-shift', buffered: true });
|
observer.observe({ type: 'layout-shift', buffered: true });
|
||||||
|
return observer;
|
||||||
|
} catch (error) {
|
||||||
|
if (process.env.NODE_ENV === 'development') {
|
||||||
|
console.warn('CLS observer initialization failed:', error);
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const getFID = (onPerfEntry: (metric: Metric) => void) => {
|
const getFID = (onPerfEntry: (metric: Metric) => void) => {
|
||||||
|
if (typeof window === 'undefined' || typeof PerformanceObserver === 'undefined') return null;
|
||||||
|
|
||||||
|
try {
|
||||||
const observer = new PerformanceObserver((list) => {
|
const observer = new PerformanceObserver((list) => {
|
||||||
|
try {
|
||||||
for (const entry of list.getEntries()) {
|
for (const entry of list.getEntries()) {
|
||||||
|
const processingStart = (entry as PerformanceEntry & { processingStart?: number }).processingStart;
|
||||||
|
if (processingStart !== undefined) {
|
||||||
onPerfEntry({
|
onPerfEntry({
|
||||||
name: 'FID',
|
name: 'FID',
|
||||||
value: (entry as PerformanceEntry & { processingStart?: number }).processingStart! - entry.startTime,
|
value: processingStart - entry.startTime,
|
||||||
delta: (entry as PerformanceEntry & { processingStart?: number }).processingStart! - entry.startTime,
|
delta: processingStart - entry.startTime,
|
||||||
id: `fid-${Date.now()}`,
|
id: `fid-${Date.now()}`,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
if (process.env.NODE_ENV === 'development') {
|
||||||
|
console.warn('FID tracking error:', error);
|
||||||
|
}
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
observer.observe({ type: 'first-input', buffered: true });
|
observer.observe({ type: 'first-input', buffered: true });
|
||||||
|
return observer;
|
||||||
|
} catch (error) {
|
||||||
|
if (process.env.NODE_ENV === 'development') {
|
||||||
|
console.warn('FID observer initialization failed:', error);
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const getFCP = (onPerfEntry: (metric: Metric) => void) => {
|
const getFCP = (onPerfEntry: (metric: Metric) => void) => {
|
||||||
|
if (typeof window === 'undefined' || typeof PerformanceObserver === 'undefined') return null;
|
||||||
|
|
||||||
|
try {
|
||||||
const observer = new PerformanceObserver((list) => {
|
const observer = new PerformanceObserver((list) => {
|
||||||
|
try {
|
||||||
for (const entry of list.getEntries()) {
|
for (const entry of list.getEntries()) {
|
||||||
if (entry.name === 'first-contentful-paint') {
|
if (entry.name === 'first-contentful-paint') {
|
||||||
onPerfEntry({
|
onPerfEntry({
|
||||||
@@ -74,32 +114,67 @@ const getFCP = (onPerfEntry: (metric: Metric) => void) => {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
} catch (error) {
|
||||||
|
if (process.env.NODE_ENV === 'development') {
|
||||||
|
console.warn('FCP tracking error:', error);
|
||||||
|
}
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
observer.observe({ type: 'paint', buffered: true });
|
observer.observe({ type: 'paint', buffered: true });
|
||||||
|
return observer;
|
||||||
|
} catch (error) {
|
||||||
|
if (process.env.NODE_ENV === 'development') {
|
||||||
|
console.warn('FCP observer initialization failed:', error);
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const getLCP = (onPerfEntry: (metric: Metric) => void) => {
|
const getLCP = (onPerfEntry: (metric: Metric) => void) => {
|
||||||
|
if (typeof window === 'undefined' || typeof PerformanceObserver === 'undefined') return null;
|
||||||
|
|
||||||
|
try {
|
||||||
const observer = new PerformanceObserver((list) => {
|
const observer = new PerformanceObserver((list) => {
|
||||||
|
try {
|
||||||
const entries = list.getEntries();
|
const entries = list.getEntries();
|
||||||
const lastEntry = entries[entries.length - 1];
|
const lastEntry = entries[entries.length - 1];
|
||||||
|
|
||||||
|
if (lastEntry) {
|
||||||
onPerfEntry({
|
onPerfEntry({
|
||||||
name: 'LCP',
|
name: 'LCP',
|
||||||
value: lastEntry.startTime,
|
value: lastEntry.startTime,
|
||||||
delta: lastEntry.startTime,
|
delta: lastEntry.startTime,
|
||||||
id: `lcp-${Date.now()}`,
|
id: `lcp-${Date.now()}`,
|
||||||
});
|
});
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
if (process.env.NODE_ENV === 'development') {
|
||||||
|
console.warn('LCP tracking error:', error);
|
||||||
|
}
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
observer.observe({ type: 'largest-contentful-paint', buffered: true });
|
observer.observe({ type: 'largest-contentful-paint', buffered: true });
|
||||||
|
return observer;
|
||||||
|
} catch (error) {
|
||||||
|
if (process.env.NODE_ENV === 'development') {
|
||||||
|
console.warn('LCP observer initialization failed:', error);
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const getTTFB = (onPerfEntry: (metric: Metric) => void) => {
|
const getTTFB = (onPerfEntry: (metric: Metric) => void) => {
|
||||||
|
if (typeof window === 'undefined' || typeof PerformanceObserver === 'undefined') return null;
|
||||||
|
|
||||||
|
try {
|
||||||
const observer = new PerformanceObserver((list) => {
|
const observer = new PerformanceObserver((list) => {
|
||||||
|
try {
|
||||||
for (const entry of list.getEntries()) {
|
for (const entry of list.getEntries()) {
|
||||||
if (entry.entryType === 'navigation') {
|
if (entry.entryType === 'navigation') {
|
||||||
const navEntry = entry as PerformanceNavigationTiming;
|
const navEntry = entry as PerformanceNavigationTiming;
|
||||||
|
if (navEntry.responseStart && navEntry.fetchStart) {
|
||||||
onPerfEntry({
|
onPerfEntry({
|
||||||
name: 'TTFB',
|
name: 'TTFB',
|
||||||
value: navEntry.responseStart - navEntry.fetchStart,
|
value: navEntry.responseStart - navEntry.fetchStart,
|
||||||
@@ -108,9 +183,22 @@ const getTTFB = (onPerfEntry: (metric: Metric) => void) => {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
if (process.env.NODE_ENV === 'development') {
|
||||||
|
console.warn('TTFB tracking error:', error);
|
||||||
|
}
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
observer.observe({ type: 'navigation', buffered: true });
|
observer.observe({ type: 'navigation', buffered: true });
|
||||||
|
return observer;
|
||||||
|
} catch (error) {
|
||||||
|
if (process.env.NODE_ENV === 'development') {
|
||||||
|
console.warn('TTFB observer initialization failed:', error);
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
// Custom hook for Web Vitals tracking
|
// Custom hook for Web Vitals tracking
|
||||||
@@ -118,46 +206,101 @@ export const useWebVitals = () => {
|
|||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (typeof window === 'undefined') return;
|
if (typeof window === 'undefined') return;
|
||||||
|
|
||||||
|
// Wrap everything in try-catch to prevent errors from breaking the app
|
||||||
|
try {
|
||||||
|
// Store web vitals for batch sending
|
||||||
|
const webVitals: Record<string, number> = {};
|
||||||
|
const path = window.location.pathname;
|
||||||
|
const projectMatch = path.match(/\/projects\/([^\/]+)/);
|
||||||
|
const projectId = projectMatch ? projectMatch[1] : null;
|
||||||
|
const observers: PerformanceObserver[] = [];
|
||||||
|
|
||||||
|
const sendWebVitals = async () => {
|
||||||
|
if (Object.keys(webVitals).length >= 3) { // Wait for at least FCP, LCP, CLS
|
||||||
|
try {
|
||||||
|
await fetch('/api/analytics/track', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
},
|
||||||
|
body: JSON.stringify({
|
||||||
|
type: 'performance',
|
||||||
|
projectId: projectId,
|
||||||
|
page: path,
|
||||||
|
performance: {
|
||||||
|
fcp: webVitals.FCP || 0,
|
||||||
|
lcp: webVitals.LCP || 0,
|
||||||
|
cls: webVitals.CLS || 0,
|
||||||
|
fid: webVitals.FID || 0,
|
||||||
|
ttfb: webVitals.TTFB || 0,
|
||||||
|
loadTime: performance.now()
|
||||||
|
}
|
||||||
|
})
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
// Silently fail
|
||||||
|
if (process.env.NODE_ENV === 'development') {
|
||||||
|
console.error('Error sending web vitals:', error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
// Track Core Web Vitals
|
// Track Core Web Vitals
|
||||||
getCLS((metric) => {
|
const clsObserver = getCLS((metric) => {
|
||||||
|
webVitals.CLS = metric.value;
|
||||||
trackWebVitals({
|
trackWebVitals({
|
||||||
...metric,
|
...metric,
|
||||||
name: metric.name as 'CLS' | 'FID' | 'FCP' | 'LCP' | 'TTFB',
|
name: metric.name as 'CLS' | 'FID' | 'FCP' | 'LCP' | 'TTFB',
|
||||||
url: window.location.pathname,
|
url: window.location.pathname,
|
||||||
});
|
});
|
||||||
|
sendWebVitals();
|
||||||
});
|
});
|
||||||
|
if (clsObserver) observers.push(clsObserver);
|
||||||
|
|
||||||
getFID((metric) => {
|
const fidObserver = getFID((metric) => {
|
||||||
|
webVitals.FID = metric.value;
|
||||||
trackWebVitals({
|
trackWebVitals({
|
||||||
...metric,
|
...metric,
|
||||||
name: metric.name as 'CLS' | 'FID' | 'FCP' | 'LCP' | 'TTFB',
|
name: metric.name as 'CLS' | 'FID' | 'FCP' | 'LCP' | 'TTFB',
|
||||||
url: window.location.pathname,
|
url: window.location.pathname,
|
||||||
});
|
});
|
||||||
|
sendWebVitals();
|
||||||
});
|
});
|
||||||
|
if (fidObserver) observers.push(fidObserver);
|
||||||
|
|
||||||
getFCP((metric) => {
|
const fcpObserver = getFCP((metric) => {
|
||||||
|
webVitals.FCP = metric.value;
|
||||||
trackWebVitals({
|
trackWebVitals({
|
||||||
...metric,
|
...metric,
|
||||||
name: metric.name as 'CLS' | 'FID' | 'FCP' | 'LCP' | 'TTFB',
|
name: metric.name as 'CLS' | 'FID' | 'FCP' | 'LCP' | 'TTFB',
|
||||||
url: window.location.pathname,
|
url: window.location.pathname,
|
||||||
});
|
});
|
||||||
|
sendWebVitals();
|
||||||
});
|
});
|
||||||
|
if (fcpObserver) observers.push(fcpObserver);
|
||||||
|
|
||||||
getLCP((metric) => {
|
const lcpObserver = getLCP((metric) => {
|
||||||
|
webVitals.LCP = metric.value;
|
||||||
trackWebVitals({
|
trackWebVitals({
|
||||||
...metric,
|
...metric,
|
||||||
name: metric.name as 'CLS' | 'FID' | 'FCP' | 'LCP' | 'TTFB',
|
name: metric.name as 'CLS' | 'FID' | 'FCP' | 'LCP' | 'TTFB',
|
||||||
url: window.location.pathname,
|
url: window.location.pathname,
|
||||||
});
|
});
|
||||||
|
sendWebVitals();
|
||||||
});
|
});
|
||||||
|
if (lcpObserver) observers.push(lcpObserver);
|
||||||
|
|
||||||
getTTFB((metric) => {
|
const ttfbObserver = getTTFB((metric) => {
|
||||||
|
webVitals.TTFB = metric.value;
|
||||||
trackWebVitals({
|
trackWebVitals({
|
||||||
...metric,
|
...metric,
|
||||||
name: metric.name as 'CLS' | 'FID' | 'FCP' | 'LCP' | 'TTFB',
|
name: metric.name as 'CLS' | 'FID' | 'FCP' | 'LCP' | 'TTFB',
|
||||||
url: window.location.pathname,
|
url: window.location.pathname,
|
||||||
});
|
});
|
||||||
|
sendWebVitals();
|
||||||
});
|
});
|
||||||
|
if (ttfbObserver) observers.push(ttfbObserver);
|
||||||
|
|
||||||
// Track page load performance
|
// Track page load performance
|
||||||
const handleLoad = () => {
|
const handleLoad = () => {
|
||||||
@@ -179,7 +322,27 @@ export const useWebVitals = () => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
return () => {
|
return () => {
|
||||||
|
// Cleanup all observers
|
||||||
|
observers.forEach(observer => {
|
||||||
|
try {
|
||||||
|
observer.disconnect();
|
||||||
|
} catch {
|
||||||
|
// Silently fail
|
||||||
|
}
|
||||||
|
});
|
||||||
|
try {
|
||||||
window.removeEventListener('load', handleLoad);
|
window.removeEventListener('load', handleLoad);
|
||||||
|
} catch {
|
||||||
|
// Silently fail
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
} catch (error) {
|
||||||
|
// If Web Vitals initialization fails, don't break the app
|
||||||
|
if (process.env.NODE_ENV === 'development') {
|
||||||
|
console.warn('Web Vitals initialization failed:', error);
|
||||||
|
}
|
||||||
|
// Return empty cleanup function
|
||||||
|
return () => {};
|
||||||
|
}
|
||||||
}, []);
|
}, []);
|
||||||
};
|
};
|
||||||
|
|||||||
1700
public/404-terminal.html
Normal file
1700
public/404-terminal.html
Normal file
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user