init ana page with apis

This commit is contained in:
2025-03-21 12:08:37 +08:00
commit 271230fca7
71 changed files with 15699 additions and 0 deletions

View File

@@ -0,0 +1,28 @@
import { NextRequest, NextResponse } from 'next/server';
import { getDeviceAnalysis } from '@/lib/analytics';
export async function GET(request: NextRequest) {
try {
// 获取请求参数
const { searchParams } = new URL(request.url);
const linkId = searchParams.get('linkId') || undefined;
const startDate = searchParams.get('startDate') || undefined;
const endDate = searchParams.get('endDate') || undefined;
// 获取设备分析详情
const analysisData = await getDeviceAnalysis(
startDate,
endDate,
linkId
);
// 返回数据
return NextResponse.json(analysisData);
} catch (error) {
console.error('Error in device-analysis API:', error);
return NextResponse.json(
{ error: 'Failed to fetch device analysis data' },
{ status: 500 }
);
}
}

View File

@@ -0,0 +1,36 @@
import { NextRequest, NextResponse } from 'next/server';
import { getConversionFunnel } from '@/lib/analytics';
export async function GET(request: NextRequest) {
try {
// 获取请求参数
const { searchParams } = new URL(request.url);
const linkId = searchParams.get('linkId');
const startDate = searchParams.get('startDate') || undefined;
const endDate = searchParams.get('endDate') || undefined;
// 验证必要参数
if (!linkId) {
return NextResponse.json(
{ error: 'Missing required parameter: linkId' },
{ status: 400 }
);
}
// 获取转化漏斗数据
const funnelData = await getConversionFunnel(
linkId,
startDate || undefined,
endDate || undefined
);
// 返回数据
return NextResponse.json(funnelData);
} catch (error) {
console.error('Error in funnel API:', error);
return NextResponse.json(
{ error: 'Failed to fetch funnel data' },
{ status: 500 }
);
}
}

View File

@@ -0,0 +1,36 @@
import { NextRequest, NextResponse } from 'next/server';
import { getLinkPerformance } from '@/lib/analytics';
export async function GET(request: NextRequest) {
try {
// 获取请求参数
const { searchParams } = new URL(request.url);
const linkId = searchParams.get('linkId');
const startDate = searchParams.get('startDate') || undefined;
const endDate = searchParams.get('endDate') || undefined;
// 验证必要参数
if (!linkId) {
return NextResponse.json(
{ error: 'Missing required parameter: linkId' },
{ status: 400 }
);
}
// 获取链接表现数据
const performanceData = await getLinkPerformance(
linkId,
startDate || undefined,
endDate || undefined
);
// 返回数据
return NextResponse.json(performanceData);
} catch (error) {
console.error('Error in link-performance API:', error);
return NextResponse.json(
{ error: 'Failed to fetch link performance data' },
{ status: 500 }
);
}
}

View File

@@ -0,0 +1,28 @@
import { NextRequest, NextResponse } from 'next/server';
import { getLinkStatusDistribution } from '@/lib/analytics';
export async function GET(request: NextRequest) {
try {
// 获取请求参数
const { searchParams } = new URL(request.url);
const projectId = searchParams.get('projectId') || undefined;
const startDate = searchParams.get('startDate') || undefined;
const endDate = searchParams.get('endDate') || undefined;
// 获取链接状态分布数据
const distributionData = await getLinkStatusDistribution(
startDate,
endDate,
projectId
);
// 返回数据
return NextResponse.json(distributionData);
} catch (error) {
console.error('Error in link-status-distribution API:', error);
return NextResponse.json(
{ error: 'Failed to fetch link status distribution data' },
{ status: 500 }
);
}
}

View File

@@ -0,0 +1,28 @@
import { NextRequest, NextResponse } from 'next/server';
import { getOverviewCards } from '@/lib/analytics';
export async function GET(request: NextRequest) {
try {
// 获取请求参数
const { searchParams } = new URL(request.url);
const projectId = searchParams.get('projectId') || undefined;
const startDate = searchParams.get('startDate') || undefined;
const endDate = searchParams.get('endDate') || undefined;
// 获取概览卡片数据
const cardsData = await getOverviewCards(
startDate,
endDate,
projectId
);
// 返回数据
return NextResponse.json(cardsData);
} catch (error) {
console.error('Error in overview-cards API:', error);
return NextResponse.json(
{ error: 'Failed to fetch overview cards data' },
{ status: 500 }
);
}
}

View File

@@ -0,0 +1,36 @@
import { NextRequest, NextResponse } from 'next/server';
import { getLinkOverview } from '@/lib/analytics';
export async function GET(request: NextRequest) {
try {
// 获取请求参数
const { searchParams } = new URL(request.url);
const linkId = searchParams.get('linkId');
const startDate = searchParams.get('startDate') || undefined;
const endDate = searchParams.get('endDate') || undefined;
// 验证必要参数
if (!linkId) {
return NextResponse.json(
{ error: 'Missing required parameter: linkId' },
{ status: 400 }
);
}
// 获取链接概览数据
const overviewData = await getLinkOverview(
linkId,
startDate || undefined,
endDate || undefined
);
// 返回数据
return NextResponse.json(overviewData);
} catch (error) {
console.error('Error in overview API:', error);
return NextResponse.json(
{ error: 'Failed to fetch overview data' },
{ status: 500 }
);
}
}

View File

@@ -0,0 +1,28 @@
import { NextRequest, NextResponse } from 'next/server';
import { getPlatformDistribution } from '@/lib/analytics';
export async function GET(request: NextRequest) {
try {
// 获取请求参数
const { searchParams } = new URL(request.url);
const linkId = searchParams.get('linkId') || undefined;
const startDate = searchParams.get('startDate') || undefined;
const endDate = searchParams.get('endDate') || undefined;
// 获取平台分布数据
const distributionData = await getPlatformDistribution(
startDate,
endDate,
linkId
);
// 返回数据
return NextResponse.json(distributionData);
} catch (error) {
console.error('Error in platform-distribution API:', error);
return NextResponse.json(
{ error: 'Failed to fetch platform distribution data' },
{ status: 500 }
);
}
}

View File

@@ -0,0 +1,32 @@
import { NextRequest, NextResponse } from 'next/server';
import { getPopularLinks } from '@/lib/analytics';
export async function GET(request: NextRequest) {
try {
// 获取请求参数
const { searchParams } = new URL(request.url);
const projectId = searchParams.get('projectId') || undefined;
const startDate = searchParams.get('startDate') || undefined;
const endDate = searchParams.get('endDate') || undefined;
const sortBy = searchParams.get('sortBy') as 'visits' | 'uniqueVisitors' | 'conversionRate' || 'visits';
const limit = searchParams.get('limit') ? parseInt(searchParams.get('limit') as string, 10) : 10;
// 获取热门链接数据
const linksData = await getPopularLinks(
startDate,
endDate,
projectId,
sortBy,
limit
);
// 返回数据
return NextResponse.json(linksData);
} catch (error) {
console.error('Error in popular-links API:', error);
return NextResponse.json(
{ error: 'Failed to fetch popular links data' },
{ status: 500 }
);
}
}

View File

@@ -0,0 +1,32 @@
import { NextRequest, NextResponse } from 'next/server';
import { getPopularReferrers } from '@/lib/analytics';
export async function GET(request: NextRequest) {
try {
// 获取请求参数
const { searchParams } = new URL(request.url);
const linkId = searchParams.get('linkId') || undefined;
const startDate = searchParams.get('startDate') || undefined;
const endDate = searchParams.get('endDate') || undefined;
const type = searchParams.get('type') as 'domain' | 'full' || 'domain';
const limit = searchParams.get('limit') ? parseInt(searchParams.get('limit') as string, 10) : 10;
// 获取热门引荐来源数据
const referrersData = await getPopularReferrers(
startDate,
endDate,
linkId,
type,
limit
);
// 返回数据
return NextResponse.json(referrersData);
} catch (error) {
console.error('Error in popular-referrers API:', error);
return NextResponse.json(
{ error: 'Failed to fetch popular referrers data' },
{ status: 500 }
);
}
}

View File

@@ -0,0 +1,30 @@
import { NextRequest, NextResponse } from 'next/server';
import { getQrCodeAnalysis } from '@/lib/analytics';
export async function GET(request: NextRequest) {
try {
// 获取请求参数
const { searchParams } = new URL(request.url);
const linkId = searchParams.get('linkId') || undefined;
const qrCodeId = searchParams.get('qrCodeId') || undefined;
const startDate = searchParams.get('startDate') || undefined;
const endDate = searchParams.get('endDate') || undefined;
// 获取QR码分析数据
const analysisData = await getQrCodeAnalysis(
startDate,
endDate,
linkId,
qrCodeId
);
// 返回数据
return NextResponse.json(analysisData);
} catch (error) {
console.error('Error in qr-code-analysis API:', error);
return NextResponse.json(
{ error: 'Failed to fetch QR code analysis data' },
{ status: 500 }
);
}
}

View File

@@ -0,0 +1,68 @@
import { NextRequest, NextResponse } from 'next/server';
import { trackEvent, EventType, ConversionType } from '@/lib/analytics';
export async function POST(request: NextRequest) {
try {
// 解析请求体
const body = await request.json();
// 验证必要字段
if (!body.linkId) {
return NextResponse.json(
{ error: 'Missing required field: linkId' },
{ status: 400 }
);
}
if (!body.eventType || !Object.values(EventType).includes(body.eventType)) {
return NextResponse.json(
{
error: 'Invalid or missing eventType',
validValues: Object.values(EventType)
},
{ status: 400 }
);
}
// 验证转化类型(如果提供)
if (
body.conversionType &&
!Object.values(ConversionType).includes(body.conversionType)
) {
return NextResponse.json(
{
error: 'Invalid conversionType',
validValues: Object.values(ConversionType)
},
{ status: 400 }
);
}
// 添加客户端IP
const clientIp = request.headers.get('x-forwarded-for') ||
request.headers.get('x-real-ip') ||
'0.0.0.0';
// 添加用户代理
const userAgent = request.headers.get('user-agent') || '';
// 合并数据
const eventData = {
...body,
ipAddress: body.ipAddress || clientIp,
userAgent: body.userAgent || userAgent,
};
// 追踪事件
const result = await trackEvent(eventData);
// 返回结果
return NextResponse.json(result);
} catch (error) {
console.error('Error in track API:', error);
return NextResponse.json(
{ error: 'Failed to track event' },
{ status: 500 }
);
}
}

View File

@@ -0,0 +1,50 @@
import { NextRequest, NextResponse } from 'next/server';
import { getVisitTrends, TimeGranularity } from '@/lib/analytics';
export async function GET(request: NextRequest) {
try {
// 获取请求参数
const { searchParams } = new URL(request.url);
const linkId = searchParams.get('linkId');
const startDate = searchParams.get('startDate') || undefined;
const endDate = searchParams.get('endDate') || undefined;
const granularity = searchParams.get('granularity') as TimeGranularity || TimeGranularity.DAY;
// 验证必要参数
if (!linkId) {
return NextResponse.json(
{ error: 'Missing required parameter: linkId' },
{ status: 400 }
);
}
// 验证粒度参数
const validGranularities = Object.values(TimeGranularity);
if (granularity && !validGranularities.includes(granularity)) {
return NextResponse.json(
{
error: 'Invalid granularity value',
validValues: validGranularities
},
{ status: 400 }
);
}
// 获取访问趋势数据
const trendsData = await getVisitTrends(
linkId,
startDate || undefined,
endDate || undefined,
granularity
);
// 返回数据
return NextResponse.json(trendsData);
} catch (error) {
console.error('Error in trends API:', error);
return NextResponse.json(
{ error: 'Failed to fetch trends data' },
{ status: 500 }
);
}
}

View File

@@ -0,0 +1,28 @@
import { NextRequest, NextResponse } from 'next/server';
import { getLinkDetailsById } from '@/app/api/links/service';
export async function GET(
request: NextRequest,
context: { params: { linkId: string } }
) {
try {
const params = await context.params;
const linkId = params.linkId;
const link = await getLinkDetailsById(linkId);
if (!link) {
return NextResponse.json(
{ error: 'Link not found' },
{ status: 404 }
);
}
return NextResponse.json(link);
} catch (error) {
console.error('Failed to fetch link details:', error);
return NextResponse.json(
{ error: 'Failed to fetch link details', message: (error as Error).message },
{ status: 500 }
);
}
}

View File

@@ -0,0 +1,27 @@
import { NextRequest, NextResponse } from 'next/server';
import { getLinkById } from '../service';
export async function GET(
request: NextRequest,
{ params }: { params: { linkId: string } }
) {
try {
const { linkId } = params;
const link = await getLinkById(linkId);
if (!link) {
return NextResponse.json(
{ error: 'Link not found' },
{ status: 404 }
);
}
return NextResponse.json(link);
} catch (error) {
console.error('Failed to fetch link details:', error);
return NextResponse.json(
{ error: 'Failed to fetch link details', message: (error as Error).message },
{ status: 500 }
);
}
}

157
app/api/links/repository.ts Normal file
View File

@@ -0,0 +1,157 @@
import { executeQuery, executeQuerySingle } from '@/lib/clickhouse';
import { Link, LinkQueryParams } from '../types';
/**
* Find links with filtering options
*/
export async function findLinks({
limit = 10,
offset = 0,
searchTerm = '',
tagFilter = '',
isActive = null,
}: LinkQueryParams) {
// Build WHERE conditions
const conditions = [];
if (searchTerm) {
conditions.push(`
(lower(title) LIKE lower('%${searchTerm}%') OR
lower(original_url) LIKE lower('%${searchTerm}%'))
`);
}
if (tagFilter) {
conditions.push(`hasAny(tags, ['${tagFilter}'])`);
}
if (isActive !== null) {
conditions.push(`is_active = ${isActive ? 'true' : 'false'}`);
}
const whereClause = conditions.length > 0
? `WHERE ${conditions.join(' AND ')}`
: '';
// Get total count
const countQuery = `
SELECT count() as total
FROM links
${whereClause}
`;
const countData = await executeQuery<{ total: number }>(countQuery);
const total = countData.length > 0 ? countData[0].total : 0;
// 使用左连接获取链接数据和统计信息
const linksQuery = `
SELECT
l.link_id,
l.original_url,
l.created_at,
l.created_by,
l.title,
l.description,
l.tags,
l.is_active,
l.expires_at,
l.team_id,
l.project_id,
count(le.event_id) as visits,
count(DISTINCT le.visitor_id) as unique_visits
FROM links l
LEFT JOIN link_events le ON l.link_id = le.link_id
${whereClause}
GROUP BY
l.link_id,
l.original_url,
l.created_at,
l.created_by,
l.title,
l.description,
l.tags,
l.is_active,
l.expires_at,
l.team_id,
l.project_id
ORDER BY l.created_at DESC
LIMIT ${limit}
OFFSET ${offset}
`;
const links = await executeQuery<Link>(linksQuery);
return {
links,
total,
limit,
offset,
page: Math.floor(offset / limit) + 1,
totalPages: Math.ceil(total / limit)
};
}
/**
* Find a single link by ID
*/
export async function findLinkById(linkId: string): Promise<Link | null> {
const query = `
SELECT
l.link_id,
l.original_url,
l.created_at,
l.created_by,
l.title,
l.description,
l.tags,
l.is_active,
l.expires_at,
l.team_id,
l.project_id,
count(le.event_id) as visits,
count(DISTINCT le.visitor_id) as unique_visits
FROM links l
LEFT JOIN link_events le ON l.link_id = le.link_id
WHERE l.link_id = '${linkId}'
GROUP BY
l.link_id,
l.original_url,
l.created_at,
l.created_by,
l.title,
l.description,
l.tags,
l.is_active,
l.expires_at,
l.team_id,
l.project_id
LIMIT 1
`;
return await executeQuerySingle<Link>(query);
}
/**
* Find a single link by ID - only basic info without statistics
*/
export async function findLinkDetailsById(linkId: string): Promise<Omit<Link, 'visits' | 'unique_visits'> | null> {
const query = `
SELECT
link_id,
original_url,
created_at,
created_by,
title,
description,
tags,
is_active,
expires_at,
team_id,
project_id
FROM links
WHERE link_id = '${linkId}'
LIMIT 1
`;
return await executeQuerySingle<Omit<Link, 'visits' | 'unique_visits'>>(query);
}

32
app/api/links/route.ts Normal file
View File

@@ -0,0 +1,32 @@
import { NextRequest, NextResponse } from 'next/server';
import { LinkQueryParams } from '../types';
import { getLinks } from './service';
export async function GET(request: NextRequest) {
try {
const searchParams = request.nextUrl.searchParams;
// Parse request parameters
const params: LinkQueryParams = {
limit: searchParams.has('limit') ? Number(searchParams.get('limit')) : 10,
page: searchParams.has('page') ? Number(searchParams.get('page')) : 1,
searchTerm: searchParams.get('search') || '',
tagFilter: searchParams.get('tag') || '',
};
// Handle active status filter
const activeFilter = searchParams.get('active');
if (activeFilter === 'true') params.isActive = true;
if (activeFilter === 'false') params.isActive = false;
// Get link data
const result = await getLinks(params);
return NextResponse.json(result);
} catch (error) {
console.error('Failed to fetch links:', error);
return NextResponse.json(
{ error: 'Failed to fetch links', message: (error as Error).message },
{ status: 500 }
);
}
}

42
app/api/links/service.ts Normal file
View File

@@ -0,0 +1,42 @@
import { Link, LinkQueryParams, PaginatedResponse } from '../types';
import { findLinkById, findLinkDetailsById, findLinks } from './repository';
/**
* Get links with pagination information
*/
export async function getLinks(params: LinkQueryParams): Promise<PaginatedResponse<Link>> {
// Convert page number to offset
const { page, limit = 10, ...otherParams } = params;
const offset = page ? (page - 1) * limit : params.offset || 0;
const result = await findLinks({
...otherParams,
limit,
offset
});
return {
data: result.links,
pagination: {
total: result.total,
limit: result.limit,
offset: result.offset,
page: result.page,
totalPages: result.totalPages
}
};
}
/**
* Get a single link by ID with full details (including statistics)
*/
export async function getLinkById(linkId: string): Promise<Link | null> {
return await findLinkById(linkId);
}
/**
* Get a single link by ID - only basic info without statistics
*/
export async function getLinkDetailsById(linkId: string): Promise<Omit<Link, 'visits' | 'unique_visits'> | null> {
return await findLinkDetailsById(linkId);
}

View File

@@ -0,0 +1,21 @@
import { executeQuerySingle } from '@/lib/clickhouse';
import { StatsOverview } from '../types';
/**
* Get overview statistics for links
*/
export async function findStatsOverview(): Promise<StatsOverview | null> {
const query = `
WITH
toUInt64(count()) as total_links,
toUInt64(countIf(is_active = true)) as active_links
FROM links
SELECT
total_links as totalLinks,
active_links as activeLinks,
(SELECT count() FROM link_events) as totalVisits,
(SELECT count() FROM link_events) / NULLIF(total_links, 0) as conversionRate
`;
return await executeQuerySingle<StatsOverview>(query);
}

15
app/api/stats/route.ts Normal file
View File

@@ -0,0 +1,15 @@
import { NextResponse } from 'next/server';
import { getStatsOverview } from './service';
export async function GET() {
try {
const stats = await getStatsOverview();
return NextResponse.json(stats);
} catch (error) {
console.error('获取统计概览失败:', error);
return NextResponse.json(
{ error: '获取统计概览失败', message: (error as Error).message },
{ status: 500 }
);
}
}

21
app/api/stats/service.ts Normal file
View File

@@ -0,0 +1,21 @@
import { StatsOverview } from '../types';
import { findStatsOverview } from './repository';
/**
* Get link statistics overview
*/
export async function getStatsOverview(): Promise<StatsOverview> {
const stats = await findStatsOverview();
// Return default values if no data
if (!stats) {
return {
totalLinks: 0,
activeLinks: 0,
totalVisits: 0,
conversionRate: 0
};
}
return stats;
}

View File

@@ -0,0 +1,19 @@
import { executeQuery } from '@/lib/clickhouse';
import { Tag } from '../types';
/**
* Get all tags with usage counts
*/
export async function findAllTags(): Promise<Tag[]> {
const query = `
SELECT
tag,
count() as count
FROM links
ARRAY JOIN tags as tag
GROUP BY tag
ORDER BY count DESC
`;
return await executeQuery<Tag>(query);
}

15
app/api/tags/route.ts Normal file
View File

@@ -0,0 +1,15 @@
import { NextResponse } from 'next/server';
import { getAllTags } from './service';
export async function GET() {
try {
const tags = await getAllTags();
return NextResponse.json(tags);
} catch (error) {
console.error('Failed to fetch tags:', error);
return NextResponse.json(
{ error: 'Failed to fetch tags', message: (error as Error).message },
{ status: 500 }
);
}
}

9
app/api/tags/service.ts Normal file
View File

@@ -0,0 +1,9 @@
import { Tag } from '../types';
import { findAllTags } from './repository';
/**
* Get all available tags
*/
export async function getAllTags(): Promise<Tag[]> {
return await findAllTags();
}

221
app/api/types.ts Normal file
View File

@@ -0,0 +1,221 @@
// 链接数据类型
export interface Link {
link_id: string;
original_url: string;
created_at: string;
created_by: string;
title: string;
description: string;
tags: string[];
is_active: boolean;
expires_at: string | null;
team_id: string;
project_id: string;
visits: number;
unique_visits: number;
}
// 分页响应类型
export interface PaginatedResponse<T> {
data: T[];
pagination: {
total: number;
limit: number;
offset: number;
page: number;
totalPages: number;
}
}
// 链接查询参数
export interface LinkQueryParams {
limit?: number;
offset?: number;
page?: number;
searchTerm?: string;
tagFilter?: string;
isActive?: boolean | null;
}
// 标签类型
export interface Tag {
tag: string;
count: number;
}
// 统计概览类型
export interface StatsOverview {
totalLinks: number;
activeLinks: number;
totalVisits: number;
conversionRate: number;
}
// Analytics数据类型
export interface LinkOverviewData {
totalVisits: number;
uniqueVisitors: number;
averageTimeSpent: number;
bounceCount: number;
conversionCount: number;
uniqueReferrers: number;
deviceTypes: {
mobile: number;
tablet: number;
desktop: number;
other: number;
};
qrScanCount: number;
totalConversionValue: number;
}
export interface FunnelStep {
name: string;
value: number;
percent: number;
}
export interface ConversionFunnelData {
steps: FunnelStep[];
totalConversions: number;
conversionRate: number;
}
export interface TrendPoint {
timestamp: string;
visits: number;
uniqueVisitors: number;
}
export interface VisitTrendsData {
trends: TrendPoint[];
totals: {
visits: number;
uniqueVisitors: number;
};
}
export interface TrackEventRequest {
linkId: string;
eventType: string;
visitorId?: string;
sessionId?: string;
referrer?: string;
userAgent?: string;
ipAddress?: string;
timeSpent?: number;
conversionType?: string;
conversionValue?: number;
customData?: Record<string, unknown>;
isQrScan?: boolean;
qrCodeId?: string;
utmSource?: string;
utmMedium?: string;
utmCampaign?: string;
}
export interface TrackEventResponse {
success: boolean;
eventId: string;
timestamp: string;
}
// 链接表现数据
export interface LinkPerformanceData {
totalClicks: number;
uniqueVisitors: number;
averageTimeSpent: number;
bounceRate: number;
uniqueReferrers: number;
conversionRate: number;
activeDays: number;
lastClickTime: string | null;
deviceDistribution: {
mobile: number;
desktop: number;
};
}
// 平台分布数据
export interface PlatformItem {
name: string;
count: number;
percent: number;
}
export interface PlatformDistributionData {
totalVisits: number;
platforms: PlatformItem[];
browsers: PlatformItem[];
}
// 设备分析数据
export interface DeviceItem {
name: string;
count: number;
percent: number;
}
export interface DeviceModelItem {
type: string;
brand: string;
model: string;
count: number;
percent: number;
}
export interface DeviceAnalysisData {
totalVisits: number;
deviceTypes: DeviceItem[];
deviceBrands: DeviceItem[];
deviceModels: DeviceModelItem[];
}
// 热门引荐来源数据
export interface ReferrerItem {
source: string;
visitCount: number;
uniqueVisitors: number;
conversionCount: number;
conversionRate: number;
averageTimeSpent: number;
percent: number;
}
export interface PopularReferrersData {
referrers: ReferrerItem[];
totalVisits: number;
}
// QR码分析数据
export interface LocationItem {
city: string;
country: string;
scanCount: number;
percent: number;
}
export interface DeviceDistributionItem {
type: string;
count: number;
percent: number;
}
export interface HourlyDistributionItem {
hour: number;
scanCount: number;
percent: number;
}
export interface QrCodeAnalysisData {
overview: {
totalScans: number;
uniqueScanners: number;
conversionCount: number;
conversionRate: number;
averageTimeSpent: number;
};
locations: LocationItem[];
deviceDistribution: DeviceDistributionItem[];
hourlyDistribution: HourlyDistributionItem[];
}

View File

@@ -0,0 +1,46 @@
interface ChartPlaceholderProps {
text: string;
height?: string;
colorScheme?: 'blue' | 'green' | 'red' | 'purple' | 'teal' | 'orange' | 'pink' | 'yellow';
}
export default function ChartPlaceholder({
text,
height = "h-64",
colorScheme = 'blue'
}: ChartPlaceholderProps) {
const borderColor = {
blue: 'border-accent-blue',
green: 'border-accent-green',
red: 'border-accent-red',
purple: 'border-accent-purple',
teal: 'border-accent-teal',
orange: 'border-accent-orange',
pink: 'border-accent-pink',
yellow: 'border-accent-yellow',
}[colorScheme];
const textColor = {
blue: 'text-accent-blue',
green: 'text-accent-green',
red: 'text-accent-red',
purple: 'text-accent-purple',
teal: 'text-accent-teal',
orange: 'text-accent-orange',
pink: 'text-accent-pink',
yellow: 'text-accent-yellow',
}[colorScheme];
return (
<div className={`${height} flex items-center justify-center bg-card-bg bg-opacity-50 rounded-md border-2 border-dashed ${borderColor}`}>
<div className="text-center">
<div className="mx-auto w-12 h-12 mb-3 rounded-full bg-background flex items-center justify-center">
<svg className={`w-6 h-6 ${textColor}`} fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z" />
</svg>
</div>
<p className={`${textColor} text-sm font-medium`}>{text}</p>
</div>
</div>
);
}

View File

@@ -0,0 +1,432 @@
"use client";
import { useState, useEffect } from 'react';
interface LinkDetails {
id: string;
name: string;
shortUrl: string;
originalUrl: string;
creator: string;
createdAt: string;
visits: number;
visitChange: number;
uniqueVisitors: number;
uniqueVisitorsChange: number;
avgTime: string;
avgTimeChange: number;
conversionRate: number;
conversionChange: number;
status: 'active' | 'inactive' | 'expired';
tags: string[];
}
interface LinkDetailsCardProps {
linkId: string | null;
onClose: () => void;
}
export default function LinkDetailsCard({ linkId, onClose }: LinkDetailsCardProps) {
const [linkDetails, setLinkDetails] = useState<LinkDetails | null>(null);
const [loading, setLoading] = useState(true);
const [activeTab, setActiveTab] = useState<'overview' | 'referrers' | 'devices' | 'locations'>('overview');
useEffect(() => {
if (linkId) {
// Simulate API call to fetch link details
const fetchData = async () => {
setLoading(true);
// In a real app, this would be an API call like:
// const response = await fetch(`/api/links/${linkId}`);
// const data = await response.json();
// For demo, using mock data
setTimeout(() => {
setLinkDetails({
id: linkId,
name: "Product Launch Campaign",
shortUrl: "short.io/prlaunch",
originalUrl: "https://example.com/products/new-product-launch-summer-2023",
creator: "Sarah Johnson",
createdAt: "2023-05-15",
visits: 3240,
visitChange: 12.5,
uniqueVisitors: 2180,
uniqueVisitorsChange: 8.3,
avgTime: "2m 45s",
avgTimeChange: -5.2,
conversionRate: 4.8,
conversionChange: 1.2,
status: 'active',
tags: ["marketing", "product", "summer"]
});
setLoading(false);
}, 800);
};
fetchData();
}
}, [linkId]);
if (!linkId) return null;
return (
<div className="fixed inset-0 z-20 overflow-y-auto bg-background/80 backdrop-blur-sm">
<div className="flex items-center justify-center min-h-screen px-4 pt-4 pb-20 text-center sm:block sm:p-0">
<div className="inline-block w-full max-w-4xl overflow-hidden text-left align-middle transition-all transform bg-card-bg rounded-xl shadow-xl">
{/* Header */}
<div className="flex items-center justify-between p-4 border-b border-card-border">
<div className="flex items-center">
{loading ? (
<div className="w-52 h-7 bg-progress-bg animate-pulse rounded"></div>
) : (
<div className="flex items-center space-x-3">
<div className="p-2 bg-accent-blue/20 rounded-lg">
<svg xmlns="http://www.w3.org/2000/svg" className="w-6 h-6 text-accent-blue" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth="1.5" d="M13.828 10.172a4 4 0 00-5.656 0l-4 4a4 4 0 105.656 5.656l1.102-1.101" />
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth="1.5" d="M10.172 13.828a4 4 0 005.656 0l4-4a4 4 0 10-5.656-5.656l-1.102 1.101" />
</svg>
</div>
<h3 className="text-xl font-medium text-foreground">
{linkDetails?.name}
</h3>
</div>
)}
</div>
<button
type="button"
onClick={onClose}
className="text-text-secondary hover:text-foreground rounded-md focus:outline-none"
>
<span className="sr-only">Close</span>
<svg className="w-6 h-6" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor" aria-hidden="true">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M6 18L18 6M6 6l12 12" />
</svg>
</button>
</div>
{loading ? (
<div className="p-8 flex flex-col space-y-4 items-center justify-center">
<div className="w-12 h-12 border-t-2 border-b-2 border-accent-blue rounded-full animate-spin"></div>
<p className="text-text-secondary">Loading link details...</p>
</div>
) : (
<>
{/* Link Info */}
<div className="p-6 border-b border-card-border grid grid-cols-1 lg:grid-cols-3 gap-6">
<div className="col-span-2">
<div className="flex flex-col space-y-2">
<div>
<span className="text-xs font-medium text-text-secondary uppercase">Short URL</span>
<div className="flex items-center mt-1">
<a
href={linkDetails ? `https://${linkDetails.shortUrl}` : '#'}
target="_blank"
rel="noopener noreferrer"
className="text-accent-blue hover:underline font-medium break-all"
>
{linkDetails?.shortUrl}
</a>
<button
type="button"
className="ml-2 text-text-secondary hover:text-foreground"
onClick={() => linkDetails && navigator.clipboard.writeText(`https://${linkDetails.shortUrl}`)}
>
<svg xmlns="http://www.w3.org/2000/svg" className="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M8 5H6a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2v-1M8 5a2 2 0 002 2h2a2 2 0 002-2M8 5a2 2 0 012-2h2a2 2 0 012 2m0 0h2a2 2 0 012 2v3m2 4H10m0 0l3-3m-3 3l3 3" />
</svg>
</button>
</div>
</div>
<div className="mt-3">
<span className="text-xs font-medium text-text-secondary uppercase">Original URL</span>
<div className="mt-1">
<a
href={linkDetails?.originalUrl || '#'}
target="_blank"
rel="noopener noreferrer"
className="text-foreground hover:underline break-all"
>
{linkDetails?.originalUrl}
</a>
</div>
</div>
</div>
</div>
<div>
<div className="flex flex-col space-y-3">
<div>
<span className="text-xs font-medium text-text-secondary uppercase">Created By</span>
<p className="mt-1 text-foreground">{linkDetails?.creator}</p>
</div>
<div>
<span className="text-xs font-medium text-text-secondary uppercase">Created At</span>
<p className="mt-1 text-foreground">{linkDetails?.createdAt}</p>
</div>
<div>
<span className="text-xs font-medium text-text-secondary uppercase">Status</span>
<div className="mt-1">
{linkDetails && (
<span
className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium
${linkDetails.status === 'active' ? 'bg-green-500/10 text-accent-green' :
linkDetails.status === 'inactive' ? 'bg-gray-500/10 text-text-secondary' :
'bg-red-500/10 text-accent-red'
}`}
>
{linkDetails.status.charAt(0).toUpperCase() + linkDetails.status.slice(1)}
</span>
)}
</div>
</div>
{linkDetails?.tags && linkDetails.tags.length > 0 && (
<div>
<span className="text-xs font-medium text-text-secondary uppercase">Tags</span>
<div className="mt-1 flex flex-wrap gap-2">
{linkDetails.tags.map((tag) => (
<span
key={tag}
className="inline-flex items-center px-2 py-0.5 text-xs font-medium bg-blue-500/10 rounded-full text-accent-blue"
>
{tag}
</span>
))}
</div>
</div>
)}
</div>
</div>
</div>
{/* Metrics Overview */}
{linkDetails && (
<div className="p-6 border-b border-card-border">
<h4 className="text-lg font-medium text-foreground mb-4">Performance Metrics</h4>
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
{/* Total Visits */}
<div className="bg-card-bg p-4 rounded-lg border border-card-border">
<div className="flex items-center justify-between">
<h5 className="text-sm font-medium text-text-secondary">Total Visits</h5>
<span
className={`inline-flex items-center text-xs font-medium rounded-full px-2 py-0.5
${linkDetails.visitChange >= 0
? 'bg-green-500/10 text-accent-green'
: 'bg-red-500/10 text-accent-red'
}`}
>
<svg
className={`w-3 h-3 mr-1 ${linkDetails.visitChange >= 0 ? 'text-accent-green' : 'text-accent-red transform rotate-180'}`}
fill="currentColor"
viewBox="0 0 20 20"
xmlns="http://www.w3.org/2000/svg"
>
<path fillRule="evenodd" d="M5.293 9.707a1 1 0 010-1.414l4-4a1 1 0 011.414 0l4 4a1 1 0 01-1.414 1.414L11 7.414V15a1 1 0 11-2 0V7.414L6.707 9.707a1 1 0 01-1.414 0z" clipRule="evenodd" />
</svg>
{Math.abs(linkDetails.visitChange)}%
</span>
</div>
<div className="mt-2">
<p className="text-2xl font-bold text-foreground">{linkDetails.visits.toLocaleString()}</p>
</div>
</div>
{/* Unique Visitors */}
<div className="bg-card-bg p-4 rounded-lg border border-card-border">
<div className="flex items-center justify-between">
<h5 className="text-sm font-medium text-text-secondary">Unique Visitors</h5>
<span
className={`inline-flex items-center text-xs font-medium rounded-full px-2 py-0.5
${linkDetails.uniqueVisitorsChange >= 0
? 'bg-green-500/10 text-accent-green'
: 'bg-red-500/10 text-accent-red'
}`}
>
<svg
className={`w-3 h-3 mr-1 ${linkDetails.uniqueVisitorsChange >= 0 ? 'text-accent-green' : 'text-accent-red transform rotate-180'}`}
fill="currentColor"
viewBox="0 0 20 20"
xmlns="http://www.w3.org/2000/svg"
>
<path fillRule="evenodd" d="M5.293 9.707a1 1 0 010-1.414l4-4a1 1 0 011.414 0l4 4a1 1 0 01-1.414 1.414L11 7.414V15a1 1 0 11-2 0V7.414L6.707 9.707a1 1 0 01-1.414 0z" clipRule="evenodd" />
</svg>
{Math.abs(linkDetails.uniqueVisitorsChange)}%
</span>
</div>
<div className="mt-2">
<p className="text-2xl font-bold text-foreground">{linkDetails.uniqueVisitors.toLocaleString()}</p>
</div>
</div>
{/* Average Time */}
<div className="bg-card-bg p-4 rounded-lg border border-card-border">
<div className="flex items-center justify-between">
<h5 className="text-sm font-medium text-text-secondary">Average Time</h5>
<span
className={`inline-flex items-center text-xs font-medium rounded-full px-2 py-0.5
${linkDetails.avgTimeChange >= 0
? 'bg-green-500/10 text-accent-green'
: 'bg-red-500/10 text-accent-red'
}`}
>
<svg
className={`w-3 h-3 mr-1 ${linkDetails.avgTimeChange >= 0 ? 'text-accent-green' : 'text-accent-red transform rotate-180'}`}
fill="currentColor"
viewBox="0 0 20 20"
xmlns="http://www.w3.org/2000/svg"
>
<path fillRule="evenodd" d="M5.293 9.707a1 1 0 010-1.414l4-4a1 1 0 011.414 0l4 4a1 1 0 01-1.414 1.414L11 7.414V15a1 1 0 11-2 0V7.414L6.707 9.707a1 1 0 01-1.414 0z" clipRule="evenodd" />
</svg>
{Math.abs(linkDetails.avgTimeChange)}%
</span>
</div>
<div className="mt-2">
<p className="text-2xl font-bold text-foreground">{linkDetails.avgTime}</p>
</div>
</div>
{/* Conversion Rate */}
<div className="bg-card-bg p-4 rounded-lg border border-card-border">
<div className="flex items-center justify-between">
<h5 className="text-sm font-medium text-text-secondary">Conversion Rate</h5>
<span
className={`inline-flex items-center text-xs font-medium rounded-full px-2 py-0.5
${linkDetails.conversionChange >= 0
? 'bg-green-500/10 text-accent-green'
: 'bg-red-500/10 text-accent-red'
}`}
>
<svg
className={`w-3 h-3 mr-1 ${linkDetails.conversionChange >= 0 ? 'text-accent-green' : 'text-accent-red transform rotate-180'}`}
fill="currentColor"
viewBox="0 0 20 20"
xmlns="http://www.w3.org/2000/svg"
>
<path fillRule="evenodd" d="M5.293 9.707a1 1 0 010-1.414l4-4a1 1 0 011.414 0l4 4a1 1 0 01-1.414 1.414L11 7.414V15a1 1 0 11-2 0V7.414L6.707 9.707a1 1 0 01-1.414 0z" clipRule="evenodd" />
</svg>
{Math.abs(linkDetails.conversionChange)}%
</span>
</div>
<div className="mt-2">
<p className="text-2xl font-bold text-foreground">{linkDetails.conversionRate}%</p>
</div>
</div>
</div>
</div>
)}
{/* Tabs Navigation */}
<div className="border-b border-card-border">
<nav className="flex -mb-px">
<button
onClick={() => setActiveTab('overview')}
className={`py-4 px-6 font-medium text-sm border-b-2 ${
activeTab === 'overview'
? 'border-accent-blue text-accent-blue'
: 'border-transparent text-text-secondary hover:text-foreground hover:border-card-border'
}`}
>
Overview
</button>
<button
onClick={() => setActiveTab('referrers')}
className={`py-4 px-6 font-medium text-sm border-b-2 ${
activeTab === 'referrers'
? 'border-accent-blue text-accent-blue'
: 'border-transparent text-text-secondary hover:text-foreground hover:border-card-border'
}`}
>
Referrers
</button>
<button
onClick={() => setActiveTab('devices')}
className={`py-4 px-6 font-medium text-sm border-b-2 ${
activeTab === 'devices'
? 'border-accent-blue text-accent-blue'
: 'border-transparent text-text-secondary hover:text-foreground hover:border-card-border'
}`}
>
Devices
</button>
<button
onClick={() => setActiveTab('locations')}
className={`py-4 px-6 font-medium text-sm border-b-2 ${
activeTab === 'locations'
? 'border-accent-blue text-accent-blue'
: 'border-transparent text-text-secondary hover:text-foreground hover:border-card-border'
}`}
>
Locations
</button>
</nav>
</div>
{/* Tab Content */}
<div className="p-6">
{activeTab === 'overview' && (
<div className="text-center py-12">
<svg className="mx-auto h-12 w-12 text-text-secondary" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth="1.5" d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z" />
</svg>
<h3 className="mt-2 text-sm font-medium text-foreground">No chart data available</h3>
<p className="mt-1 text-sm text-text-secondary">
Charts and detailed analytics would appear here.
</p>
</div>
)}
{activeTab === 'referrers' && (
<div className="text-center py-12">
<svg className="mx-auto h-12 w-12 text-text-secondary" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth="1.5" d="M13 10V3L4 14h7v7l9-11h-7z" />
</svg>
<h3 className="mt-2 text-sm font-medium text-foreground">No referrer data available</h3>
<p className="mt-1 text-sm text-text-secondary">
Information about traffic sources would appear here.
</p>
</div>
)}
{activeTab === 'devices' && (
<div className="text-center py-12">
<svg className="mx-auto h-12 w-12 text-text-secondary" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth="1.5" d="M9.75 17L9 20l-1 1h8l-1-1-.75-3M3 13h18M5 17h14a2 2 0 002-2V5a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z" />
</svg>
<h3 className="mt-2 text-sm font-medium text-foreground">No device data available</h3>
<p className="mt-1 text-sm text-text-secondary">
Breakdown of devices used to access the link would appear here.
</p>
</div>
)}
{activeTab === 'locations' && (
<div className="text-center py-12">
<svg className="mx-auto h-12 w-12 text-text-secondary" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth="1.5" d="M17.657 16.657L13.414 20.9a1.998 1.998 0 01-2.827 0l-4.244-4.243a8 8 0 1111.314 0z" />
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth="1.5" d="M15 11a3 3 0 11-6 0 3 3 0 016 0z" />
</svg>
<h3 className="mt-2 text-sm font-medium text-foreground">No location data available</h3>
<p className="mt-1 text-sm text-text-secondary">
Geographic distribution of visitors would appear here.
</p>
</div>
)}
</div>
{/* Footer */}
<div className="px-4 py-3 bg-card-bg flex justify-end border-t border-card-border">
<button
type="button"
onClick={onClose}
className="px-4 py-2 text-sm font-medium text-text-secondary bg-card-bg border border-card-border rounded-md shadow-sm hover:bg-card-bg/80 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-accent-blue"
>
Close
</button>
</div>
</>
)}
</div>
</div>
</div>
);
}

View File

@@ -0,0 +1,72 @@
interface StatsCardProps {
title: string;
value: string | number;
change: number;
unit?: string;
colorScheme?: 'blue' | 'green' | 'red' | 'purple';
}
export default function StatsCard({
title,
value,
change,
unit = '',
colorScheme = 'blue'
}: StatsCardProps) {
const isPositive = change >= 0;
const hasPercentUnit = unit === '%';
// Color mappings based on the colorScheme
const gradientBg = {
blue: 'bg-gradient-blue',
green: 'bg-gradient-green',
red: 'bg-gradient-red',
purple: 'bg-gradient-purple',
}[colorScheme];
const accentColor = {
blue: 'text-accent-blue',
green: 'text-accent-green',
red: 'text-accent-red',
purple: 'text-accent-purple',
}[colorScheme];
return (
<div className="bg-card-bg border border-card-border rounded-lg overflow-hidden">
{/* Colorful top bar */}
<div className={`h-1 ${gradientBg}`}></div>
<div className="p-5">
<h2 className="text-text-secondary text-sm font-medium mb-2">{title}</h2>
<div className="flex flex-col">
<div className="flex items-baseline">
<p className={`text-3xl font-bold ${accentColor}`}>
{value}
{hasPercentUnit && <span className={accentColor}>%</span>}
</p>
<div className={`ml-3 px-2 py-0.5 rounded-md text-sm font-medium flex items-center ${
isPositive ? 'text-accent-green' : 'text-accent-red'
}`}>
<span className={`inline-block w-2 h-2 rounded-full mr-1 ${
isPositive ? 'bg-accent-green' : 'bg-accent-red'
}`}></span>
{isPositive ? '+' : ''}{change}%
</div>
</div>
{/* Visual indicator for percentages */}
{hasPercentUnit && (
<div className="mt-3 w-full bg-progress-bg h-2 rounded-full overflow-hidden">
<div
className={`${gradientBg} h-full rounded-full`}
style={{ width: `${Math.min(Number(value), 100)}%` }}
></div>
</div>
)}
</div>
</div>
</div>
);
}

View File

@@ -0,0 +1,67 @@
'use client';
import Link from 'next/link';
import ThemeToggle from "../ui/ThemeToggle";
export default function Navbar() {
return (
<header className="w-full py-4 border-b border-card-border bg-background">
<div className="container flex items-center justify-between px-4 mx-auto">
<div className="flex items-center space-x-4">
<Link href="/" className="flex items-center space-x-2">
<svg
className="w-6 h-6 text-accent-blue"
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
>
<path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"></path>
<path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"></path>
</svg>
<span className="text-xl font-bold text-foreground">ShortURL</span>
</Link>
<nav className="hidden space-x-4 md:flex">
<Link
href="/links"
className="text-sm text-foreground hover:text-accent-blue transition-colors"
>
Links
</Link>
<Link
href="/analytics"
className="text-sm text-foreground hover:text-accent-blue transition-colors"
>
Analytics
</Link>
</nav>
</div>
<div className="flex items-center space-x-3">
<ThemeToggle />
<button className="p-2 text-sm text-foreground rounded-md gradient-border">
Upgrade
</button>
<button className="p-2 text-sm text-foreground hover:text-accent-blue">
<svg
className="w-5 h-5"
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
>
<circle cx="12" cy="12" r="10"></circle>
<circle cx="12" cy="10" r="3"></circle>
<path d="M7 20.662V19a2 2 0 0 1 2-2h6a2 2 0 0 1 2 2v1.662"></path>
</svg>
</button>
</div>
</div>
</header>
);
}

View File

@@ -0,0 +1,57 @@
import { ReactNode } from 'react';
interface CardProps {
title: string;
children: ReactNode;
className?: string;
colorScheme?: 'blue' | 'green' | 'red' | 'purple' | 'teal' | 'orange' | 'pink' | 'yellow' | 'none';
glowEffect?: boolean;
}
export default function Card({
title,
children,
className = '',
colorScheme = 'none',
glowEffect = false
}: CardProps) {
// Only add color-specific classes if a colorScheme is specified
const headerColor = colorScheme !== 'none' ? {
blue: 'text-accent-blue',
green: 'text-accent-green',
red: 'text-accent-red',
purple: 'text-accent-purple',
teal: 'text-accent-teal',
orange: 'text-accent-orange',
pink: 'text-accent-pink',
yellow: 'text-accent-yellow',
}[colorScheme] : 'text-foreground';
const glowClass = glowEffect && colorScheme !== 'none' ? {
blue: 'shadow-[0_0_15px_rgba(59,130,246,0.15)]',
green: 'shadow-[0_0_15px_rgba(16,185,129,0.15)]',
red: 'shadow-[0_0_15px_rgba(244,63,94,0.15)]',
purple: 'shadow-[0_0_15px_rgba(139,92,246,0.15)]',
teal: 'shadow-[0_0_15px_rgba(20,184,166,0.15)]',
orange: 'shadow-[0_0_15px_rgba(249,115,22,0.15)]',
pink: 'shadow-[0_0_15px_rgba(236,72,153,0.15)]',
yellow: 'shadow-[0_0_15px_rgba(245,158,11,0.15)]',
}[colorScheme] : '';
// Define the indicator dot color
const indicatorColor = colorScheme !== 'none' ? `bg-accent-${colorScheme}` : 'bg-gray-500';
return (
<div className={`bg-card-bg border border-card-border rounded-lg ${glowClass} ${className}`}>
<div className="flex items-center border-b border-card-border p-5 pb-4">
<h2 className={`text-lg font-medium ${headerColor}`}>{title}</h2>
{colorScheme !== 'none' && (
<div className={`ml-2 h-1.5 w-1.5 rounded-full ${indicatorColor}`}></div>
)}
</div>
<div className="p-5 pt-4">
{children}
</div>
</div>
);
}

View File

@@ -0,0 +1,242 @@
"use client";
import { useState } from 'react';
interface LinkData {
name: string;
originalUrl: string;
customSlug: string;
expiresAt: string;
tags: string[];
}
interface CreateLinkModalProps {
onClose: () => void;
onSubmit: (linkData: LinkData) => void;
}
export default function CreateLinkModal({ onClose, onSubmit }: CreateLinkModalProps) {
const [formData, setFormData] = useState({
name: '',
originalUrl: '',
customSlug: '',
expiresAt: '',
tags: [] as string[],
tagInput: ''
});
const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
const { name, value } = e.target;
setFormData(prev => ({
...prev,
[name]: value
}));
};
const handleTagKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
if (e.key === 'Enter' && formData.tagInput.trim()) {
e.preventDefault();
addTag();
}
};
const addTag = () => {
if (formData.tagInput.trim() && !formData.tags.includes(formData.tagInput.trim())) {
setFormData(prev => ({
...prev,
tags: [...prev.tags, prev.tagInput.trim()],
tagInput: ''
}));
}
};
const removeTag = (tagToRemove: string) => {
setFormData(prev => ({
...prev,
tags: prev.tags.filter(tag => tag !== tagToRemove)
}));
};
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault();
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const { tagInput, ...submitData } = formData;
onSubmit(submitData as LinkData);
};
return (
<div className="fixed inset-0 z-10 overflow-y-auto bg-background/80 backdrop-blur-sm">
<div className="flex items-center justify-center min-h-screen px-4 pt-4 pb-20 text-center sm:block sm:p-0">
<div className="inline-block w-full max-w-xl overflow-hidden text-left align-middle transition-all transform bg-card-bg rounded-xl shadow-xl">
{/* Header */}
<div className="flex items-center justify-between p-4 border-b border-card-border">
<div className="flex items-center space-x-3">
<div className="p-2 bg-accent-blue/20 rounded-lg">
<svg xmlns="http://www.w3.org/2000/svg" className="w-6 h-6 text-accent-blue" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth="1.5" d="M12 4.5v15m7.5-7.5h-15" />
</svg>
</div>
<h3 className="text-xl font-medium leading-6 text-foreground">
Create New Link
</h3>
</div>
<button
type="button"
onClick={onClose}
className="text-text-secondary rounded-md hover:text-foreground focus:outline-none"
>
<span className="sr-only">Close</span>
<svg className="w-6 h-6" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor" aria-hidden="true">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M6 18L18 6M6 6l12 12" />
</svg>
</button>
</div>
{/* Form */}
<form onSubmit={handleSubmit} className="p-6 space-y-6 overflow-y-auto max-h-[70vh]">
{/* Link Name */}
<div>
<label htmlFor="name" className="block text-sm font-medium text-foreground">
Link Name <span className="text-accent-red">*</span>
</label>
<input
type="text"
id="name"
name="name"
value={formData.name}
onChange={handleChange}
placeholder="e.g. Product Launch Campaign"
className="block w-full px-3 py-2 mt-1 text-foreground bg-card-bg border border-card-border rounded-md shadow-sm focus:outline-none focus:ring-accent-blue focus:border-accent-blue sm:text-sm"
required
/>
</div>
{/* Original URL */}
<div>
<label htmlFor="originalUrl" className="block text-sm font-medium text-foreground">
Original URL <span className="text-accent-red">*</span>
</label>
<input
type="url"
id="originalUrl"
name="originalUrl"
value={formData.originalUrl}
onChange={handleChange}
placeholder="https://example.com/your-long-url"
className="block w-full px-3 py-2 mt-1 text-foreground bg-card-bg border border-card-border rounded-md shadow-sm focus:outline-none focus:ring-accent-blue focus:border-accent-blue sm:text-sm"
required
/>
</div>
{/* Custom Slug */}
<div>
<label htmlFor="customSlug" className="block text-sm font-medium text-foreground">
Custom Slug <span className="text-text-secondary">(Optional)</span>
</label>
<div className="flex mt-1 rounded-md shadow-sm">
<span className="inline-flex items-center px-3 py-2 text-sm text-text-secondary border border-r-0 border-card-border rounded-l-md bg-card-bg/60">
short.io/
</span>
<input
type="text"
id="customSlug"
name="customSlug"
value={formData.customSlug}
onChange={handleChange}
placeholder="custom-slug"
className="flex-1 block w-full min-w-0 px-3 py-2 text-foreground bg-card-bg border border-card-border rounded-none rounded-r-md focus:outline-none focus:ring-accent-blue focus:border-accent-blue sm:text-sm"
/>
</div>
<p className="mt-1 text-xs text-text-secondary">
Leave blank to generate a random slug
</p>
</div>
{/* Expiration Date */}
<div>
<label htmlFor="expiresAt" className="block text-sm font-medium text-foreground">
Expiration Date <span className="text-text-secondary">(Optional)</span>
</label>
<input
type="date"
id="expiresAt"
name="expiresAt"
value={formData.expiresAt}
onChange={handleChange}
className="block w-full px-3 py-2 mt-1 text-foreground bg-card-bg border border-card-border rounded-md shadow-sm focus:outline-none focus:ring-accent-blue focus:border-accent-blue sm:text-sm"
/>
<p className="mt-1 text-xs text-text-secondary">
Leave blank for a non-expiring link
</p>
</div>
{/* Tags */}
<div>
<label htmlFor="tagInput" className="block text-sm font-medium text-foreground">
Tags <span className="text-text-secondary">(Optional)</span>
</label>
<div className="flex mt-1 rounded-md shadow-sm">
<input
type="text"
id="tagInput"
name="tagInput"
value={formData.tagInput}
onChange={handleChange}
onKeyDown={handleTagKeyDown}
placeholder="Add tag and press Enter"
className="flex-1 block w-full min-w-0 px-3 py-2 text-foreground bg-card-bg border border-card-border rounded-l-md focus:outline-none focus:ring-accent-blue focus:border-accent-blue sm:text-sm"
/>
<button
type="button"
onClick={addTag}
className="inline-flex items-center px-3 py-2 text-sm font-medium text-white border border-transparent rounded-r-md shadow-sm bg-accent-blue hover:bg-blue-600 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-accent-blue"
>
Add
</button>
</div>
{formData.tags.length > 0 && (
<div className="flex flex-wrap gap-2 mt-2">
{formData.tags.map(tag => (
<span key={tag} className="inline-flex items-center px-2 py-0.5 text-xs font-medium bg-blue-500/10 rounded-full text-accent-blue">
{tag}
<button
type="button"
onClick={() => removeTag(tag)}
className="flex-shrink-0 ml-1 text-accent-blue rounded-full hover:text-blue-400 focus:outline-none"
>
<span className="sr-only">Remove tag {tag}</span>
<svg className="w-3 h-3" fill="currentColor" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg">
<path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z" clipRule="evenodd" />
</svg>
</button>
</span>
))}
</div>
)}
</div>
</form>
{/* Footer */}
<div className="px-4 py-3 bg-card-bg flex justify-end space-x-3 border-t border-card-border">
<button
type="button"
onClick={onClose}
className="px-4 py-2 text-sm font-medium text-foreground bg-card-bg/70 border border-card-border rounded-md shadow-sm hover:bg-card-bg focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-accent-blue"
>
Cancel
</button>
<button
type="button"
onClick={handleSubmit}
className="inline-flex justify-center px-4 py-2 text-sm font-medium text-white bg-accent-blue border border-transparent rounded-md shadow-sm hover:bg-blue-600 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-accent-blue"
>
Create Link
</button>
</div>
</div>
</div>
</div>
);
}

View File

@@ -0,0 +1,64 @@
"use client";
import { useState, useEffect } from 'react';
export default function ThemeToggle() {
const [darkMode, setDarkMode] = useState(false);
// Initialize theme on component mount
useEffect(() => {
const isDarkMode = localStorage.getItem('darkMode') === 'true';
setDarkMode(isDarkMode);
if (isDarkMode) {
document.documentElement.classList.add('dark');
} else {
document.documentElement.classList.remove('dark');
}
}, []);
// Update theme when darkMode state changes
const toggleTheme = () => {
const newDarkMode = !darkMode;
setDarkMode(newDarkMode);
localStorage.setItem('darkMode', newDarkMode.toString());
if (newDarkMode) {
document.documentElement.classList.add('dark');
} else {
document.documentElement.classList.remove('dark');
}
};
return (
<button
onClick={toggleTheme}
className="p-2 rounded-md bg-card-bg border border-card-border hover:bg-card-bg/80 transition-colors"
aria-label={darkMode ? "Switch to light mode" : "Switch to dark mode"}
>
{darkMode ? (
<svg
className="w-5 h-5 text-accent-yellow"
fill="currentColor"
viewBox="0 0 20 20"
xmlns="http://www.w3.org/2000/svg"
>
<path
fillRule="evenodd"
d="M10 2a1 1 0 011 1v1a1 1 0 11-2 0V3a1 1 0 011-1zm4 8a4 4 0 11-8 0 4 4 0 018 0zm-.464 4.95l.707.707a1 1 0 001.414-1.414l-.707-.707a1 1 0 00-1.414 1.414zm2.12-10.607a1 1 0 010 1.414l-.706.707a1 1 0 11-1.414-1.414l.707-.707a1 1 0 011.414 0zM17 11a1 1 0 100-2h-1a1 1 0 100 2h1zm-7 4a1 1 0 011 1v1a1 1 0 11-2 0v-1a1 1 0 011-1zM5.05 6.464A1 1 0 106.465 5.05l-.708-.707a1 1 0 00-1.414 1.414l.707.707zm1.414 8.486l-.707.707a1 1 0 01-1.414-1.414l.707-.707a1 1 0 011.414 1.414zM4 11a1 1 0 100-2H3a1 1 0 000 2h1z"
clipRule="evenodd"
/>
</svg>
) : (
<svg
className="w-5 h-5 text-foreground"
fill="currentColor"
viewBox="0 0 20 20"
xmlns="http://www.w3.org/2000/svg"
>
<path d="M17.293 13.293A8 8 0 016.707 2.707a8.001 8.001 0 1010.586 10.586z" />
</svg>
)}
</button>
);
}

BIN
app/favicon.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

90
app/globals.css Normal file
View File

@@ -0,0 +1,90 @@
@import "tailwindcss";
:root {
/* Light Mode - Default */
--background: #f8fafc;
--foreground: #0f172a;
/* Card colors */
--card-bg: #ffffff;
--card-border: #e2e8f0;
/* Vibrant accent colors */
--accent-blue: #3b82f6;
--accent-green: #10b981;
--accent-red: #f43f5e;
--accent-yellow: #f59e0b;
--accent-purple: #8b5cf6;
--accent-pink: #ec4899;
--accent-teal: #14b8a6;
--accent-orange: #f97316;
/* UI colors */
--text-secondary: #64748b;
--progress-bg: #e2e8f0;
/* Gradient colors */
--gradient-blue: linear-gradient(135deg, #3b82f6, #2563eb);
--gradient-purple: linear-gradient(135deg, #8b5cf6, #7c3aed);
--gradient-green: linear-gradient(135deg, #10b981, #059669);
--gradient-red: linear-gradient(135deg, #f43f5e, #e11d48);
}
.dark {
/* Dark Mode */
--background: #0f172a;
--foreground: #ffffff;
/* Card colors */
--card-bg: #1e293b;
--card-border: #334155;
/* Vibrant accent colors */
--accent-blue: #3b82f6;
--accent-green: #10b981;
--accent-red: #f43f5e;
--accent-yellow: #f59e0b;
--accent-purple: #8b5cf6;
--accent-pink: #ec4899;
--accent-teal: #14b8a6;
--accent-orange: #f97316;
/* UI colors */
--text-secondary: #94a3b8;
--progress-bg: #334155;
}
@theme inline {
--color-background: var(--background);
--color-foreground: var(--foreground);
--font-sans: var(--font-geist-sans);
--font-mono: var(--font-geist-mono);
}
body {
background: var(--background);
color: var(--foreground);
font-family: var(--font-sans), sans-serif;
}
/* Colorful gradient borders */
.gradient-border {
position: relative;
border-radius: 0.5rem;
overflow: hidden;
}
.gradient-border::before {
content: '';
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
border-radius: 0.5rem;
padding: 2px;
background: linear-gradient(45deg, var(--accent-blue), var(--accent-purple), var(--accent-pink));
-webkit-mask: linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0);
-webkit-mask-composite: xor;
mask-composite: exclude;
}

38
app/layout.tsx Normal file
View File

@@ -0,0 +1,38 @@
import './globals.css';
import type { Metadata } from 'next';
import { Geist, Geist_Mono } from "next/font/google";
import Navbar from "./components/layout/Navbar";
const geistSans = Geist({
variable: "--font-geist-sans",
subsets: ["latin"],
});
const geistMono = Geist_Mono({
variable: "--font-geist-mono",
subsets: ["latin"],
});
export const metadata: Metadata = {
title: 'ShortURL Analytics',
description: 'Analytics dashboard for short URL management',
};
export default function RootLayout({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
return (
<html lang="en" suppressHydrationWarning>
<body
className={`${geistSans.variable} ${geistMono.variable} antialiased bg-background`}
>
<Navbar />
<main className="min-h-screen px-4 py-6">
{children}
</main>
</body>
</html>
);
}

21
app/layouts.tsx Normal file
View File

@@ -0,0 +1,21 @@
import './globals.css';
import type { Metadata } from 'next';
export const metadata: Metadata = {
title: 'Link Management & Analytics',
description: 'Track and analyze shortened links',
};
export default function RootLayout({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
return (
<html lang="en" suppressHydrationWarning>
<body>
{children}
</body>
</html>
);
}

1354
app/links/[id]/page.tsx Normal file

File diff suppressed because it is too large Load Diff

473
app/links/page.tsx Normal file
View File

@@ -0,0 +1,473 @@
"use client";
import { useState, useEffect } from 'react';
import CreateLinkModal from '../components/ui/CreateLinkModal';
import { Link, StatsOverview, Tag } from '../api/types';
// Define type for link data
interface LinkData {
name: string;
originalUrl: string;
customSlug: string;
expiresAt: string;
tags: string[];
}
// 映射API数据到UI所需格式
interface UILink {
id: string;
name: string;
shortUrl: string;
originalUrl: string;
creator: string;
createdAt: string;
visits: number;
visitChange: number;
uniqueVisitors: number;
uniqueVisitorsChange: number;
avgTime: string;
avgTimeChange: number;
conversionRate: number;
conversionChange: number;
status: string;
tags: string[];
}
export default function LinksPage() {
const [links, setLinks] = useState<UILink[]>([]);
const [allTags, setAllTags] = useState<Tag[]>([]);
const [stats, setStats] = useState<StatsOverview>({
totalLinks: 0,
activeLinks: 0,
totalVisits: 0,
conversionRate: 0
});
const [searchQuery, setSearchQuery] = useState('');
const [showCreateModal, setShowCreateModal] = useState(false);
const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
// 映射API数据到UI所需格式的函数
const mapApiLinkToUiLink = (apiLink: Link): UILink => {
// 生成短URL显示 - 因为数据库中没有short_url字段
const shortUrlDisplay = generateShortUrlDisplay(apiLink.link_id, apiLink.original_url);
return {
id: apiLink.link_id,
name: apiLink.title || 'Untitled Link',
shortUrl: shortUrlDisplay,
originalUrl: apiLink.original_url,
creator: apiLink.created_by,
createdAt: new Date(apiLink.created_at).toLocaleDateString(),
visits: apiLink.visits,
visitChange: 0, // API doesn't provide change data yet
uniqueVisitors: apiLink.unique_visits,
uniqueVisitorsChange: 0,
avgTime: '0m 0s', // API doesn't provide average time yet
avgTimeChange: 0,
conversionRate: 0, // API doesn't provide conversion rate yet
conversionChange: 0,
status: apiLink.is_active ? 'active' : 'inactive',
tags: apiLink.tags || []
};
};
// 从link_id和原始URL生成短URL显示
const generateShortUrlDisplay = (linkId: string, originalUrl: string): string => {
try {
// 尝试从原始URL提取域名
const urlObj = new URL(originalUrl);
const domain = urlObj.hostname.replace('www.', '');
// 使用link_id的前8个字符作为短代码
const shortCode = linkId.substring(0, 8);
return `${domain}/${shortCode}`;
} catch {
// 如果URL解析失败返回一个基于linkId的默认值
return `short.link/${linkId.substring(0, 8)}`;
}
};
// 获取链接数据
useEffect(() => {
const fetchLinks = async () => {
try {
setIsLoading(true);
setError(null);
// 获取链接列表
const linksResponse = await fetch('/api/links');
if (!linksResponse.ok) {
throw new Error(`Failed to fetch links: ${linksResponse.statusText}`);
}
const linksData = await linksResponse.json();
// 获取标签列表
const tagsResponse = await fetch('/api/tags');
if (!tagsResponse.ok) {
throw new Error(`Failed to fetch tags: ${tagsResponse.statusText}`);
}
const tagsData = await tagsResponse.json();
// 获取统计数据
const statsResponse = await fetch('/api/stats');
if (!statsResponse.ok) {
throw new Error(`Failed to fetch stats: ${statsResponse.statusText}`);
}
const statsData = await statsResponse.json();
// 处理并设置数据
const uiLinks = linksData.data.map(mapApiLinkToUiLink);
setLinks(uiLinks);
setAllTags(tagsData);
setStats(statsData);
} catch (err) {
console.error('Data loading failed:', err);
setError(err instanceof Error ? err.message : 'Unknown error');
} finally {
setIsLoading(false);
}
};
fetchLinks();
}, []);
const filteredLinks = links.filter(link =>
link.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
link.shortUrl.toLowerCase().includes(searchQuery.toLowerCase()) ||
link.tags.some(tag => tag.toLowerCase().includes(searchQuery.toLowerCase()))
);
const handleOpenLinkDetails = (id: string) => {
window.location.href = `/links/${id}`;
};
const handleCreateLink = async (linkData: LinkData) => {
try {
setIsLoading(true);
// 在实际应用中,这里会发送 POST 请求到 API
console.log('创建链接:', linkData);
// 刷新链接列表
const response = await fetch('/api/links');
if (!response.ok) {
throw new Error(`刷新链接列表失败: ${response.statusText}`);
}
const newData = await response.json();
const uiLinks = newData.data.map(mapApiLinkToUiLink);
setLinks(uiLinks);
setShowCreateModal(false);
} catch (err) {
console.error('创建链接失败:', err);
setError(err instanceof Error ? err.message : '未知错误');
} finally {
setIsLoading(false);
}
};
// 加载状态
if (isLoading && links.length === 0) {
return (
<div className="flex items-center justify-center min-h-screen">
<div className="p-4 text-center">
<div className="w-12 h-12 mx-auto border-4 rounded-full border-accent-blue border-t-transparent animate-spin"></div>
<p className="mt-4 text-lg text-foreground">Loading data...</p>
</div>
</div>
);
}
// 错误状态
if (error && links.length === 0) {
return (
<div className="flex items-center justify-center min-h-screen">
<div className="p-6 text-center rounded-lg bg-red-500/10">
<svg className="w-12 h-12 mx-auto text-accent-red" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
</svg>
<h2 className="mt-4 text-xl font-bold text-foreground">Loading Failed</h2>
<p className="mt-2 text-text-secondary">{error}</p>
<button
onClick={() => window.location.reload()}
className="px-4 py-2 mt-4 text-white rounded-lg bg-accent-blue hover:bg-blue-600"
>
Reload
</button>
</div>
</div>
);
}
return (
<div className="container px-4 py-8 mx-auto">
<div className="flex flex-col gap-8">
{/* Header */}
<div className="flex flex-col gap-4 md:flex-row md:justify-between md:items-center">
<div>
<h1 className="text-2xl font-bold text-foreground">Link Management</h1>
<p className="mt-1 text-sm text-text-secondary">
View and manage all your shortened links
</p>
</div>
<div className="flex gap-2">
<div className="relative flex-1 min-w-[200px]">
<div className="absolute inset-y-0 left-0 flex items-center pl-3 pointer-events-none">
<svg className="w-4 h-4 text-text-secondary" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
</svg>
</div>
<input
type="search"
className="block w-full p-2.5 pl-10 text-sm border rounded-lg bg-card-bg border-card-border text-foreground placeholder-text-secondary focus:ring-accent-blue focus:border-accent-blue"
placeholder="Search links..."
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
/>
</div>
<button
onClick={() => setShowCreateModal(true)}
className="px-4 py-2.5 bg-accent-blue text-white rounded-lg text-sm font-medium hover:bg-blue-600 focus:outline-none focus:ring-4 focus:ring-blue-300"
>
<span className="flex items-center gap-1">
<svg xmlns="http://www.w3.org/2000/svg" className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M12 6v6m0 0v6m0-6h6m-6 0H6" />
</svg>
New Link
</span>
</button>
</div>
</div>
{/* Stats Summary */}
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-4">
<div className="p-4 border rounded-lg shadow bg-card-bg border-card-border">
<div className="flex items-center">
<div className="p-3 mr-4 rounded-full text-accent-blue bg-blue-500/10">
<svg xmlns="http://www.w3.org/2000/svg" className="w-6 h-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M13.828 10.172a4 4 0 00-5.656 0l-4 4a4 4 0 105.656 5.656l1.102-1.101" />
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M10.172 13.828a4 4 0 005.656 0l4-4a4 4 0 10-5.656-5.656l-1.102 1.101" />
</svg>
</div>
<div>
<p className="text-sm font-medium text-text-secondary">Total Links</p>
<p className="text-2xl font-semibold text-foreground">{stats.totalLinks}</p>
</div>
</div>
</div>
<div className="p-4 border rounded-lg shadow bg-card-bg border-card-border">
<div className="flex items-center">
<div className="p-3 mr-4 rounded-full text-accent-green bg-green-500/10">
<svg xmlns="http://www.w3.org/2000/svg" className="w-6 h-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
</svg>
</div>
<div>
<p className="text-sm font-medium text-text-secondary">Active Links</p>
<p className="text-2xl font-semibold text-foreground">{stats.activeLinks}</p>
</div>
</div>
</div>
<div className="p-4 border rounded-lg shadow bg-card-bg border-card-border">
<div className="flex items-center">
<div className="p-3 mr-4 rounded-full text-accent-purple bg-purple-500/10">
<svg xmlns="http://www.w3.org/2000/svg" className="w-6 h-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
</svg>
</div>
<div>
<p className="text-sm font-medium text-text-secondary">Total Visits</p>
<p className="text-2xl font-semibold text-foreground">{stats.totalVisits.toLocaleString()}</p>
</div>
</div>
</div>
<div className="p-4 border rounded-lg shadow bg-card-bg border-card-border">
<div className="flex items-center">
<div className="p-3 mr-4 rounded-full bg-amber-500/10 text-accent-yellow">
<svg xmlns="http://www.w3.org/2000/svg" className="w-6 h-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z" />
</svg>
</div>
<div>
<p className="text-sm font-medium text-text-secondary">Conversion Rate</p>
<p className="text-2xl font-semibold text-foreground">{(stats.conversionRate * 100).toFixed(1)}%</p>
</div>
</div>
</div>
</div>
{/* Links Table */}
<div className="overflow-hidden border rounded-lg shadow bg-card-bg border-card-border">
<div className="overflow-x-auto">
<table className="w-full text-sm text-left text-text-secondary">
<thead className="text-xs uppercase border-b bg-card-bg/60 text-text-secondary border-card-border">
<tr>
<th scope="col" className="px-6 py-3">Link Info</th>
<th scope="col" className="px-6 py-3">Visits</th>
<th scope="col" className="px-6 py-3">Unique Visitors</th>
<th scope="col" className="px-6 py-3">Avg Time</th>
<th scope="col" className="px-6 py-3">Conversion</th>
<th scope="col" className="px-6 py-3">Status</th>
<th scope="col" className="px-6 py-3">
<span className="sr-only">Actions</span>
</th>
</tr>
</thead>
<tbody>
{isLoading && links.length === 0 ? (
<tr className="border-b bg-card-bg border-card-border">
<td colSpan={7} className="px-6 py-4 text-center text-text-secondary">
<div className="flex items-center justify-center">
<div className="w-6 h-6 border-2 rounded-full border-accent-blue border-t-transparent animate-spin"></div>
<span className="ml-2">Loading...</span>
</div>
</td>
</tr>
) : filteredLinks.length === 0 ? (
<tr className="border-b bg-card-bg border-card-border">
<td colSpan={7} className="px-6 py-4 text-center text-text-secondary">
No links found matching your search criteria
</td>
</tr>
) : (
filteredLinks.map((link) => (
<tr
key={link.id}
className="border-b cursor-pointer bg-card-bg border-card-border hover:bg-card-bg/80"
onClick={() => handleOpenLinkDetails(link.id)}
>
<td className="px-6 py-4">
<div className="font-medium text-foreground">{link.name}</div>
<div className="text-xs text-accent-blue">{link.shortUrl}</div>
</td>
<td className="px-6 py-4">
<div className="font-medium text-foreground">{link.visits.toLocaleString()}</div>
<div className={`text-xs flex items-center ${link.visitChange >= 0 ? 'text-accent-green' : 'text-accent-red'}`}>
<svg
className={`w-3 h-3 mr-1 ${link.visitChange >= 0 ? '' : 'transform rotate-180'}`}
fill="currentColor"
viewBox="0 0 20 20"
xmlns="http://www.w3.org/2000/svg"
>
<path fillRule="evenodd" d="M5.293 9.707a1 1 0 010-1.414l4-4a1 1 0 011.414 0l4 4a1 1 0 01-1.414 1.414L11 7.414V15a1 1 0 11-2 0V7.414L6.707 9.707a1 1 0 01-1.414 0z" clipRule="evenodd"></path>
</svg>
{Math.abs(link.visitChange)}%
</div>
</td>
<td className="px-6 py-4">
<div className="font-medium text-foreground">{link.uniqueVisitors.toLocaleString()}</div>
<div className={`text-xs flex items-center ${link.uniqueVisitorsChange >= 0 ? 'text-accent-green' : 'text-accent-red'}`}>
<svg
className={`w-3 h-3 mr-1 ${link.uniqueVisitorsChange >= 0 ? '' : 'transform rotate-180'}`}
fill="currentColor"
viewBox="0 0 20 20"
xmlns="http://www.w3.org/2000/svg"
>
<path fillRule="evenodd" d="M5.293 9.707a1 1 0 010-1.414l4-4a1 1 0 011.414 0l4 4a1 1 0 01-1.414 1.414L11 7.414V15a1 1 0 11-2 0V7.414L6.707 9.707a1 1 0 01-1.414 0z" clipRule="evenodd"></path>
</svg>
{Math.abs(link.uniqueVisitorsChange)}%
</div>
</td>
<td className="px-6 py-4">
<div className="font-medium text-foreground">{link.avgTime}</div>
<div className={`text-xs flex items-center ${link.avgTimeChange >= 0 ? 'text-accent-green' : 'text-accent-red'}`}>
<svg
className={`w-3 h-3 mr-1 ${link.avgTimeChange >= 0 ? '' : 'transform rotate-180'}`}
fill="currentColor"
viewBox="0 0 20 20"
xmlns="http://www.w3.org/2000/svg"
>
<path fillRule="evenodd" d="M5.293 9.707a1 1 0 010-1.414l4-4a1 1 0 011.414 0l4 4a1 1 0 01-1.414 1.414L11 7.414V15a1 1 0 11-2 0V7.414L6.707 9.707a1 1 0 01-1.414 0z" clipRule="evenodd"></path>
</svg>
{Math.abs(link.avgTimeChange)}%
</div>
</td>
<td className="px-6 py-4">
<div className="font-medium text-foreground">{link.conversionRate}%</div>
<div className={`text-xs flex items-center ${link.conversionChange >= 0 ? 'text-accent-green' : 'text-accent-red'}`}>
<svg
className={`w-3 h-3 mr-1 ${link.conversionChange >= 0 ? '' : 'transform rotate-180'}`}
fill="currentColor"
viewBox="0 0 20 20"
xmlns="http://www.w3.org/2000/svg"
>
<path fillRule="evenodd" d="M5.293 9.707a1 1 0 010-1.414l4-4a1 1 0 011.414 0l4 4a1 1 0 01-1.414 1.414L11 7.414V15a1 1 0 11-2 0V7.414L6.707 9.707a1 1 0 01-1.414 0z" clipRule="evenodd"></path>
</svg>
{Math.abs(link.conversionChange)}%
</div>
</td>
<td className="px-6 py-4">
<span
className={`px-2 py-1 text-xs font-medium rounded-full ${
link.status === 'active'
? 'bg-green-500/10 text-accent-green'
: link.status === 'inactive'
? 'bg-gray-500/10 text-text-secondary'
: 'bg-red-500/10 text-accent-red'
}`}
>
{link.status === 'active' ? 'Active' : link.status === 'inactive' ? 'Inactive' : 'Expired'}
</span>
</td>
<td className="px-6 py-4 text-right">
<button
onClick={(e) => {
e.stopPropagation();
handleOpenLinkDetails(link.id);
}}
className="text-sm font-medium text-accent-blue hover:underline"
>
Details
</button>
</td>
</tr>
))
)}
</tbody>
</table>
</div>
</div>
{/* Tags Section */}
{allTags.length > 0 && (
<div className="p-4 border rounded-lg shadow bg-card-bg border-card-border">
<h2 className="mb-4 text-lg font-medium text-foreground">Tags</h2>
<div className="flex flex-wrap gap-2">
{allTags.map(tagItem => (
<span
key={tagItem.tag}
className="inline-flex items-center px-3 py-1 text-sm font-medium rounded-full text-accent-blue bg-blue-500/10"
onClick={() => setSearchQuery(tagItem.tag)}
style={{ cursor: 'pointer' }}
>
{tagItem.tag}
<span className="ml-1.5 text-xs bg-blue-500/20 px-1.5 py-0.5 rounded-full">
{tagItem.count}
</span>
</span>
))}
</div>
</div>
)}
</div>
{/* Create Link Modal */}
{showCreateModal && (
<CreateLinkModal
onClose={() => setShowCreateModal(false)}
onSubmit={handleCreateLink}
/>
)}
</div>
);
}

50
app/page.tsx Normal file
View File

@@ -0,0 +1,50 @@
import Link from 'next/link';
export default function Home() {
return (
<main className="flex min-h-screen flex-col items-center justify-center p-24 relative overflow-hidden">
{/* Colorful background elements */}
<div className="absolute top-0 left-0 w-full h-full overflow-hidden z-0">
<div className="absolute top-10 left-1/4 w-64 h-64 rounded-full bg-accent-blue opacity-10 blur-3xl"></div>
<div className="absolute bottom-10 right-1/4 w-96 h-96 rounded-full bg-accent-purple opacity-10 blur-3xl"></div>
<div className="absolute top-1/3 right-1/3 w-48 h-48 rounded-full bg-accent-green opacity-10 blur-3xl"></div>
</div>
<div className="text-center max-w-xl z-10 relative">
<div className="flex items-center justify-center mb-6">
<div className="h-10 w-10 rounded-lg bg-gradient-blue flex items-center justify-center shadow-lg">
<svg className="h-6 w-6 text-white" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 7h8m0 0v8m0-8l-8 8-4-4-6 6" />
</svg>
</div>
<h1 className="text-4xl font-bold ml-3 text-foreground">ShortURL <span className="text-accent-blue">Analytics</span></h1>
</div>
<p className="text-text-secondary text-xl mb-10">Your complete analytics suite for tracking and optimizing short URL performance</p>
<div className="flex flex-col md:flex-row items-center justify-center space-y-4 md:space-y-0 md:space-x-4">
<Link
href="/dashboard"
className="bg-gradient-blue hover:opacity-90 text-white font-medium py-2.5 px-6 rounded-md text-lg transition-colors inline-flex items-center shadow-lg"
>
Go to Dashboard
<svg className="ml-2 h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M14 5l7 7m0 0l-7 7m7-7H3" />
</svg>
</Link>
<Link
href="/links"
className="bg-card-bg border border-card-border hover:border-accent-purple text-foreground font-medium py-2.5 px-6 rounded-md text-lg transition-all inline-flex items-center"
>
View Links
<svg className="ml-2 h-5 w-5 text-accent-purple" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13.828 10.172a4 4 0 00-5.656 0l-4 4a4 4 0 105.656 5.656l1.102-1.101" />
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M14.828 14.828a4 4 0 005.656 0l4-4a4 4 0 00-5.656-5.656l-1.1 1.1" />
</svg>
</Link>
</div>
</div>
</main>
)
}