3 Commits
Author SHA1 Message Date
dimitar 4ccb65ba88 pin to homepage and liveblog ticker 2026-01-29 06:06:54 +01:00
dimitar 5a457fa99f checkpoint
need polishing
2026-01-29 05:13:52 +01:00
dimitar 0351726eeb live blog implemented 2026-01-29 04:01:55 +01:00
42 changed files with 9984 additions and 333 deletions

No files matched your search

+20
View File
@@ -13,6 +13,7 @@
"@nestjs/common": "^11.0.1", "@nestjs/common": "^11.0.1",
"@nestjs/config": "^4.0.2", "@nestjs/config": "^4.0.2",
"@nestjs/core": "^11.0.1", "@nestjs/core": "^11.0.1",
"@nestjs/event-emitter": "^3.0.1",
"@nestjs/platform-express": "^11.0.1", "@nestjs/platform-express": "^11.0.1",
"@nestjs/typeorm": "^11.0.0", "@nestjs/typeorm": "^11.0.0",
"class-transformer": "^0.5.1", "class-transformer": "^0.5.1",
@@ -2410,6 +2411,19 @@
} }
} }
}, },
"node_modules/@nestjs/event-emitter": {
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/@nestjs/event-emitter/-/event-emitter-3.0.1.tgz",
"integrity": "sha512-0Ln/x+7xkU6AJFOcQI9tIhUMXVF7D5itiaQGOyJbXtlAfAIt8gzDdJm+Im7cFzKoWkiW5nCXCPh6GSvdQd/3Dw==",
"license": "MIT",
"dependencies": {
"eventemitter2": "6.4.9"
},
"peerDependencies": {
"@nestjs/common": "^10.0.0 || ^11.0.0",
"@nestjs/core": "^10.0.0 || ^11.0.0"
}
},
"node_modules/@nestjs/platform-express": { "node_modules/@nestjs/platform-express": {
"version": "11.1.10", "version": "11.1.10",
"resolved": "https://registry.npmjs.org/@nestjs/platform-express/-/platform-express-11.1.10.tgz", "resolved": "https://registry.npmjs.org/@nestjs/platform-express/-/platform-express-11.1.10.tgz",
@@ -5741,6 +5755,12 @@
"node": ">= 0.6" "node": ">= 0.6"
} }
}, },
"node_modules/eventemitter2": {
"version": "6.4.9",
"resolved": "https://registry.npmjs.org/eventemitter2/-/eventemitter2-6.4.9.tgz",
"integrity": "sha512-JEPTiaOt9f04oa6NOkc4aH+nVp5I3wEjpHbIPqfgCdD5v5bUzy7xQqwcVO2aDQgOWhI28da57HksMrzK9HlRxg==",
"license": "MIT"
},
"node_modules/events": { "node_modules/events": {
"version": "3.3.0", "version": "3.3.0",
"resolved": "https://registry.npmjs.org/events/-/events-3.3.0.tgz", "resolved": "https://registry.npmjs.org/events/-/events-3.3.0.tgz",
+1
View File
@@ -26,6 +26,7 @@
"@nestjs/common": "^11.0.1", "@nestjs/common": "^11.0.1",
"@nestjs/config": "^4.0.2", "@nestjs/config": "^4.0.2",
"@nestjs/core": "^11.0.1", "@nestjs/core": "^11.0.1",
"@nestjs/event-emitter": "^3.0.1",
"@nestjs/platform-express": "^11.0.1", "@nestjs/platform-express": "^11.0.1",
"@nestjs/typeorm": "^11.0.0", "@nestjs/typeorm": "^11.0.0",
"class-transformer": "^0.5.1", "class-transformer": "^0.5.1",
+10 -2
View File
@@ -5,7 +5,14 @@ import { AppController } from './app.controller';
import { AppService } from './app.service'; import { AppService } from './app.service';
import { ArticlesModule } from './modules/articles.module'; import { ArticlesModule } from './modules/articles.module';
import { StrapiModule } from './modules/strapi.module'; import { StrapiModule } from './modules/strapi.module';
import { Article, Author, Category } from './modules/entities'; import { LiveBlogModule } from './modules/live-blog.module';
import {
Article,
Author,
Category,
LiveBlog,
LiveBlogUpdate,
} from './modules/entities';
@Module({ @Module({
imports: [ imports: [
@@ -15,12 +22,13 @@ import { Article, Author, Category } from './modules/entities';
TypeOrmModule.forRoot({ TypeOrmModule.forRoot({
type: 'sqlite', type: 'sqlite',
database: process.env.DATABASE_PATH ?? './database.sqlite', database: process.env.DATABASE_PATH ?? './database.sqlite',
entities: [Article, Author, Category], entities: [Article, Author, Category, LiveBlog, LiveBlogUpdate],
synchronize: process.env.NODE_ENV !== 'production', synchronize: process.env.NODE_ENV !== 'production',
logging: process.env.NODE_ENV === 'development', logging: process.env.NODE_ENV === 'development',
}), }),
ArticlesModule, ArticlesModule,
StrapiModule, StrapiModule,
LiveBlogModule,
], ],
controllers: [AppController], controllers: [AppController],
providers: [AppService], providers: [AppService],
+141 -1
View File
@@ -5,8 +5,10 @@ import {
IsArray, IsArray,
IsUUID, IsUUID,
IsNumber, IsNumber,
IsBoolean,
IsDate,
} from 'class-validator'; } from 'class-validator';
import { ArticleStatus } from './entities'; import { ArticleStatus, LiveBlogStatus } from './entities';
export class CreateArticleDto { export class CreateArticleDto {
@IsString() @IsString()
@@ -120,3 +122,141 @@ export class FindArticlesDto {
@IsOptional() @IsOptional()
limit?: number; limit?: number;
} }
export class CreateLiveBlogDto {
@IsString()
title: string;
@IsString()
slug: string;
@IsOptional()
@IsString()
description?: string;
@IsOptional()
@IsEnum(LiveBlogStatus)
status?: LiveBlogStatus;
@IsOptional()
@IsBoolean()
isPinned?: boolean;
@IsOptional()
@IsString()
strapiId?: string;
@IsOptional()
@IsUUID()
authorId?: string;
@IsOptional()
@IsUUID()
categoryId?: string;
}
export class UpdateLiveBlogDto {
@IsOptional()
@IsString()
title?: string;
@IsOptional()
@IsString()
slug?: string;
@IsOptional()
@IsString()
description?: string;
@IsOptional()
@IsEnum(LiveBlogStatus)
status?: LiveBlogStatus;
@IsOptional()
@IsBoolean()
isPinned?: boolean;
@IsOptional()
@IsString()
strapiId?: string;
@IsOptional()
@IsUUID()
authorId?: string;
@IsOptional()
@IsUUID()
categoryId?: string;
}
export class CreateLiveBlogUpdateDto {
@IsString()
content: string;
@IsOptional()
@IsBoolean()
isPinned?: boolean;
@IsOptional()
@IsUUID()
authorId?: string;
@IsOptional()
@IsDate()
scheduledAt?: Date;
@IsOptional()
@IsString()
strapiId?: string;
}
export class UpdateLiveBlogUpdateDto {
@IsOptional()
@IsString()
content?: string;
@IsOptional()
@IsBoolean()
isPinned?: boolean;
@IsOptional()
@IsUUID()
authorId?: string;
@IsOptional()
@IsDate()
scheduledAt?: Date;
@IsOptional()
@IsString()
strapiId?: string;
}
export class FindLiveBlogsDto {
@IsOptional()
@IsString()
category?: string;
@IsOptional()
@IsString()
author?: string;
@IsOptional()
@IsString()
status?: string;
@IsOptional()
@IsBoolean()
isPinned?: boolean;
@IsOptional()
@IsString()
search?: string;
@IsOptional()
@IsNumber()
page?: number;
@IsOptional()
limit?: number;
}
+99 -1
View File
@@ -7,6 +7,7 @@ import {
ManyToOne, ManyToOne,
JoinColumn, JoinColumn,
ValueTransformer, ValueTransformer,
OneToMany,
} from 'typeorm'; } from 'typeorm';
class ArrayTransformer implements ValueTransformer { class ArrayTransformer implements ValueTransformer {
@@ -15,7 +16,7 @@ class ArrayTransformer implements ValueTransformer {
} }
from(value: string): string[] { from(value: string): string[] {
try { try {
return value ? JSON.parse(value) : []; return value ? (JSON.parse(value) as string[]) : [];
} catch { } catch {
return []; return [];
} }
@@ -28,6 +29,13 @@ export enum ArticleStatus {
ARCHIVED = 'archived', ARCHIVED = 'archived',
} }
export enum LiveBlogStatus {
DRAFT = 'draft',
LIVE = 'live',
ENDED = 'ended',
ARCHIVED = 'archived',
}
@Entity('authors') @Entity('authors')
export class Author { export class Author {
@PrimaryGeneratedColumn('uuid') @PrimaryGeneratedColumn('uuid')
@@ -145,3 +153,93 @@ export class Article {
@JoinColumn({ name: 'categoryId' }) @JoinColumn({ name: 'categoryId' })
category: Category; category: Category;
} }
@Entity('live_blogs')
export class LiveBlog {
@PrimaryGeneratedColumn('uuid')
id: string;
@Column()
title: string;
@Column({ unique: true })
slug: string;
@Column({ type: 'text', nullable: true })
description: string;
@Column({
type: 'text',
default: 'draft',
})
status: LiveBlogStatus;
@Column({ default: false })
isPinned: boolean;
@Column({ nullable: true })
strapiId: string;
@Column({ nullable: true })
authorId: string;
@Column({ nullable: true })
categoryId: string;
@Column({ default: 0 })
viewCount: number;
@CreateDateColumn()
createdAt: Date;
@UpdateDateColumn()
updatedAt: Date;
@ManyToOne(() => Author, { onDelete: 'SET NULL' })
@JoinColumn({ name: 'authorId' })
author: Author;
@ManyToOne(() => Category, { onDelete: 'SET NULL' })
@JoinColumn({ name: 'categoryId' })
category: Category;
@OneToMany(() => LiveBlogUpdate, (update) => update.liveBlog, {
cascade: true,
})
updates: LiveBlogUpdate[];
}
@Entity('live_blog_updates')
export class LiveBlogUpdate {
@PrimaryGeneratedColumn('uuid')
id: string;
@Column('text')
content: string;
@Column({ default: false })
isPinned: boolean;
@Column({ nullable: true })
authorId: string;
@Column({ type: 'datetime', nullable: true })
scheduledAt: Date;
@Column({ nullable: true })
strapiId: string;
@CreateDateColumn()
createdAt: Date;
@UpdateDateColumn()
updatedAt: Date;
@ManyToOne(() => Author, { onDelete: 'SET NULL' })
@JoinColumn({ name: 'authorId' })
author: Author;
@ManyToOne(() => LiveBlog, { onDelete: 'CASCADE' })
@JoinColumn({ name: 'liveBlogId' })
liveBlog: LiveBlog;
}
+139
View File
@@ -0,0 +1,139 @@
import {
Controller,
Get,
Post,
Put,
Delete,
Body,
Param,
Query,
ValidationPipe,
Res,
Logger,
Headers,
} from '@nestjs/common';
import type { Response as ExpressResponse } from 'express';
import { LiveBlogService } from './live-blog.service';
import {
CreateLiveBlogDto,
UpdateLiveBlogDto,
FindLiveBlogsDto,
CreateLiveBlogUpdateDto,
UpdateLiveBlogUpdateDto,
} from './articles.dto';
@Controller('live-blogs')
export class LiveBlogController {
private readonly logger = new Logger(LiveBlogController.name);
constructor(private readonly liveBlogService: LiveBlogService) {}
// Live Blog CRUD operations
@Get('featured')
getFeatured() {
this.logger.log('GET /featured called');
return this.liveBlogService.findPinned();
}
@Get('active')
getActive() {
return this.liveBlogService.findActive();
}
@Get('recent')
getRecent() {
return this.liveBlogService.getLiveBlogsWithRecentUpdates();
}
@Post()
create(
@Body(new ValidationPipe({ transform: true })) dto: CreateLiveBlogDto,
) {
return this.liveBlogService.create(dto);
}
@Get()
findAll(
@Query(new ValidationPipe({ transform: true })) dto: FindLiveBlogsDto,
) {
return this.liveBlogService.findAll(dto);
}
@Get(':id')
findOne(@Param('id') id: string) {
return this.liveBlogService.findOne(id);
}
@Get('slug/:slug')
findBySlug(@Param('slug') slug: string) {
return this.liveBlogService.findBySlug(slug);
}
@Put(':id')
update(
@Param('id') id: string,
@Body(new ValidationPipe({ transform: true })) dto: UpdateLiveBlogDto,
) {
return this.liveBlogService.update(id, dto);
}
@Delete(':id')
remove(@Param('id') id: string) {
return this.liveBlogService.remove(id);
}
// Live Blog Updates CRUD operations
@Post(':id/updates')
createUpdate(
@Param('id') liveBlogId: string,
@Body(new ValidationPipe({ transform: true })) dto: CreateLiveBlogUpdateDto,
) {
return this.liveBlogService.createUpdate(dto, liveBlogId);
}
@Get(':id/updates')
findUpdates(
@Param('id') liveBlogId: string,
@Query('page') page = 1,
@Query('limit') limit = 50,
) {
return this.liveBlogService.findUpdates(
liveBlogId,
parseInt(page.toString()),
parseInt(limit.toString()),
);
}
@Put(':id/updates/:updateId')
updateUpdate(
@Param('id') liveBlogId: string,
@Param('updateId') updateId: string,
@Body(new ValidationPipe({ transform: true })) dto: UpdateLiveBlogUpdateDto,
) {
return this.liveBlogService.updateUpdate(liveBlogId, updateId, dto);
}
@Delete(':id/updates/:updateId')
removeUpdate(
@Param('id') liveBlogId: string,
@Param('updateId') updateId: string,
) {
return this.liveBlogService.removeUpdate(liveBlogId, updateId);
}
// SSE endpoint for real-time updates
@Get(':id/stream')
stream(
@Param('id') liveBlogId: string,
@Res() response: ExpressResponse,
@Headers('last-event-id') lastEventId?: string,
) {
this.logger.log(`SSE connection request for live blog ${liveBlogId}`);
if (lastEventId) {
this.logger.log(`Client resuming with last event ID: ${lastEventId}`);
}
this.liveBlogService.createStream(liveBlogId, response);
}
}
+17
View File
@@ -0,0 +1,17 @@
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { EventEmitterModule } from '@nestjs/event-emitter';
import { LiveBlogService } from './live-blog.service';
import { LiveBlogController } from './live-blog.controller';
import { LiveBlog, LiveBlogUpdate, Author, Category } from './entities';
@Module({
imports: [
TypeOrmModule.forFeature([LiveBlog, LiveBlogUpdate, Author, Category]),
EventEmitterModule.forRoot(),
],
controllers: [LiveBlogController],
providers: [LiveBlogService],
exports: [LiveBlogService],
})
export class LiveBlogModule {}
+469
View File
@@ -0,0 +1,469 @@
import {
Injectable,
NotFoundException,
Logger,
OnModuleInit,
} from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, In } from 'typeorm';
import { EventEmitter2 } from '@nestjs/event-emitter';
import { Response } from 'express';
import { LiveBlog, LiveBlogUpdate, LiveBlogStatus } from './entities';
import {
CreateLiveBlogDto,
UpdateLiveBlogDto,
FindLiveBlogsDto,
CreateLiveBlogUpdateDto,
UpdateLiveBlogUpdateDto,
} from './articles.dto';
interface SseClient {
id: string;
response: Response;
blogId: string;
}
interface LiveBlogUpdateEvent {
blogId: string;
update: LiveBlogUpdate;
}
interface LiveBlogStatusChangeEvent {
blogId: string;
status: LiveBlogStatus;
}
interface LiveBlogPinUpdateEvent {
blogId: string;
updateId: string;
isPinned: boolean;
}
@Injectable()
export class LiveBlogService implements OnModuleInit {
private readonly logger = new Logger(LiveBlogService.name);
private readonly sseClients = new Map<string, SseClient>();
constructor(
@InjectRepository(LiveBlog)
private readonly liveBlogRepository: Repository<LiveBlog>,
@InjectRepository(LiveBlogUpdate)
private readonly liveBlogUpdateRepository: Repository<LiveBlogUpdate>,
private readonly eventEmitter: EventEmitter2,
) {}
onModuleInit() {
this.eventEmitter.on('live-blog.update', (data: LiveBlogUpdateEvent) => {
this.broadcastToClients(data.blogId, {
type: 'update',
data: data.update,
});
});
this.eventEmitter.on(
'live-blog.status-change',
(data: LiveBlogStatusChangeEvent) => {
this.broadcastToClients(data.blogId, {
type: 'status-change',
data: { status: data.status },
});
},
);
this.eventEmitter.on(
'live-blog.pin-update',
(data: LiveBlogPinUpdateEvent) => {
this.broadcastToClients(data.blogId, {
type: 'pin-update',
data: { updateId: data.updateId, isPinned: data.isPinned },
});
},
);
}
// Live Blog CRUD operations
async create(dto: CreateLiveBlogDto): Promise<LiveBlog> {
const liveBlog = this.liveBlogRepository.create({
...dto,
status: dto.status || LiveBlogStatus.DRAFT,
});
return await this.liveBlogRepository.save(liveBlog);
}
async findAll(
dto: FindLiveBlogsDto,
): Promise<{ data: LiveBlog[]; total: number }> {
const {
category,
author,
status,
isPinned,
search,
page = 1,
limit = 10,
} = dto;
const queryBuilder = this.liveBlogRepository
.createQueryBuilder('liveBlog')
.leftJoinAndSelect('liveBlog.author', 'author')
.leftJoinAndSelect('liveBlog.category', 'category');
// Handle status filter - can be single value or comma-separated list
if (status) {
if (typeof status === 'string' && status.includes(',')) {
const statuses = status.split(',').map((s) => s.trim());
queryBuilder.where('liveBlog.status IN (:...statuses)', { statuses });
} else {
queryBuilder.where('liveBlog.status = :status', { status });
}
} else if (!isPinned) {
// Default to live blogs if no status specified AND not querying for pinned blogs
// Pinned blogs can be either live or ended
queryBuilder.where('liveBlog.status = :status', {
status: LiveBlogStatus.LIVE,
});
}
if (category) {
queryBuilder.andWhere('category.slug = :category', { category });
}
if (author) {
queryBuilder.andWhere('author.slug = :author', { author });
}
if (search) {
queryBuilder.andWhere(
'(liveBlog.title ILIKE :search OR liveBlog.description ILIKE :search)',
{ search: `%${search}%` },
);
}
if (isPinned !== undefined) {
queryBuilder.andWhere('liveBlog.isPinned = :isPinned', { isPinned });
}
const [data, total] = await queryBuilder
.orderBy('liveBlog.createdAt', 'DESC')
.skip((page - 1) * limit)
.take(limit)
.getManyAndCount();
return { data, total };
}
async findOne(id: string): Promise<LiveBlog> {
const liveBlog = await this.liveBlogRepository.findOne({
where: { id },
relations: ['author', 'category', 'updates'],
});
if (!liveBlog) {
throw new NotFoundException(`Live blog with ID ${id} not found`);
}
// Increment view count
await this.liveBlogRepository.increment({ id }, 'viewCount', 1);
return liveBlog;
}
async findOneWithoutIncrement(id: string): Promise<LiveBlog> {
const liveBlog = await this.liveBlogRepository.findOne({
where: { id },
relations: ['author', 'category', 'updates'],
});
if (!liveBlog) {
throw new NotFoundException(`Live blog with ID ${id} not found`);
}
return liveBlog;
}
async findBySlug(slug: string): Promise<LiveBlog> {
const liveBlog = await this.liveBlogRepository.findOne({
where: { slug },
relations: ['author', 'category', 'updates'],
});
if (!liveBlog) {
throw new NotFoundException(`Live blog with slug ${slug} not found`);
}
// Increment view count
await this.liveBlogRepository.increment({ slug }, 'viewCount', 1);
return liveBlog;
}
async update(id: string, dto: UpdateLiveBlogDto): Promise<LiveBlog> {
const liveBlog = await this.liveBlogRepository.findOne({
where: { id },
relations: ['author', 'category'],
});
if (!liveBlog) {
throw new NotFoundException(`Live blog with ID ${id} not found`);
}
// Track if status changed for event emission
const oldStatus = liveBlog.status;
// Update fields
if (dto.title !== undefined) {
liveBlog.title = dto.title;
}
if (dto.slug !== undefined) {
liveBlog.slug = dto.slug;
}
if (dto.description !== undefined) {
liveBlog.description = dto.description;
}
if (dto.status !== undefined) {
liveBlog.status = dto.status;
}
if (dto.strapiId !== undefined) {
liveBlog.strapiId = dto.strapiId;
}
if (dto.authorId !== undefined) {
liveBlog.authorId = dto.authorId;
}
if (dto.categoryId !== undefined) {
liveBlog.categoryId = dto.categoryId;
}
if (dto.isPinned !== undefined) {
liveBlog.isPinned = dto.isPinned;
}
// Save the updated entity
const updatedBlog = await this.liveBlogRepository.save(liveBlog);
// Emit status change event if status changed
if (dto.status !== undefined && dto.status !== oldStatus) {
this.eventEmitter.emit('live-blog.status-change', {
blogId: id,
status: dto.status,
});
}
return updatedBlog;
}
async remove(id: string): Promise<void> {
const liveBlog = await this.findOne(id);
await this.liveBlogRepository.remove(liveBlog);
}
// Live Blog Update CRUD operations
async createUpdate(
dto: CreateLiveBlogUpdateDto,
liveBlogId: string,
): Promise<LiveBlogUpdate> {
const liveBlogEntity = await this.findOne(liveBlogId);
const update = this.liveBlogUpdateRepository.create({
...dto,
liveBlog: liveBlogEntity,
});
const savedUpdate = await this.liveBlogUpdateRepository.save(update);
// Emit update event
this.eventEmitter.emit('live-blog.update', {
blogId: liveBlogId,
update: savedUpdate,
});
return savedUpdate;
}
async findUpdates(
liveBlogId: string,
page = 1,
limit = 50,
): Promise<{ data: LiveBlogUpdate[]; total: number }> {
const [data, total] = await this.liveBlogUpdateRepository.findAndCount({
where: { liveBlog: { id: liveBlogId } },
relations: ['author'],
order: {
isPinned: 'DESC',
createdAt: 'ASC',
},
skip: (page - 1) * limit,
take: limit,
});
return { data, total };
}
async updateUpdate(
liveBlogId: string,
updateId: string,
dto: UpdateLiveBlogUpdateDto,
): Promise<LiveBlogUpdate> {
const update = await this.liveBlogUpdateRepository.findOne({
where: { id: updateId, liveBlog: { id: liveBlogId } },
relations: ['liveBlog'],
});
if (!update) {
throw new NotFoundException(`Update with ID ${updateId} not found`);
}
Object.assign(update, dto);
const savedUpdate = await this.liveBlogUpdateRepository.save(update);
// Emit pin change event
if (dto.isPinned !== undefined) {
this.eventEmitter.emit('live-blog.pin-update', {
blogId: liveBlogId,
updateId,
isPinned: dto.isPinned,
});
}
return savedUpdate;
}
async removeUpdate(liveBlogId: string, updateId: string): Promise<void> {
const update = await this.liveBlogUpdateRepository.findOne({
where: { id: updateId, liveBlog: { id: liveBlogId } },
});
if (!update) {
throw new NotFoundException(`Update with ID ${updateId} not found`);
}
await this.liveBlogUpdateRepository.remove(update);
}
// SSE operations
createStream(liveBlogId: string, response: Response): void {
// Verify live blog exists and is live
this.findOne(liveBlogId).catch(() => {
response.end();
return;
});
const clientId = `${Date.now()}-${Math.random()}`;
// Set SSE headers
response.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
Connection: 'keep-alive',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': 'Cache-Control',
});
// Send initial connection message
response.write(
`data: ${JSON.stringify({ type: 'connected', clientId })}\n\n`,
);
// Store client connection
this.sseClients.set(clientId, {
id: clientId,
response,
blogId: liveBlogId,
});
// Handle client disconnect
response.on('close', () => {
this.sseClients.delete(clientId);
this.logger.log(
`Client ${clientId} disconnected from live blog ${liveBlogId}`,
);
});
this.logger.log(`Client ${clientId} connected to live blog ${liveBlogId}`);
}
private broadcastToClients(liveBlogId: string, message: any): void {
const clients = Array.from(this.sseClients.values()).filter(
(client) => client.blogId === liveBlogId,
);
clients.forEach((client) => {
try {
client.response.write(`data: ${JSON.stringify(message)}\n\n`);
} catch (error) {
this.logger.error(
`Failed to send message to client ${client.id}:`,
error,
);
this.sseClients.delete(client.id);
}
});
this.logger.debug(
`Broadcasted message to ${clients.length} clients for live blog ${liveBlogId}`,
);
}
// Strapi sync operations
async syncFromStrapi(
strapiId: string,
data: Partial<CreateLiveBlogDto>,
): Promise<LiveBlog> {
let liveBlog = await this.liveBlogRepository.findOne({
where: { strapiId },
});
if (!liveBlog) {
liveBlog = this.liveBlogRepository.create({
strapiId,
...data,
status: data.status || LiveBlogStatus.DRAFT,
});
} else {
Object.assign(liveBlog, data);
}
return await this.liveBlogRepository.save(liveBlog);
}
// Utility methods
async getLiveBlogsWithRecentUpdates(hours = 24): Promise<LiveBlog[]> {
const since = new Date();
since.setHours(since.getHours() - hours);
return await this.liveBlogRepository
.createQueryBuilder('liveBlog')
.leftJoinAndSelect('liveBlog.author', 'author')
.leftJoinAndSelect('liveBlog.updates', 'updates')
.where('liveBlog.status = :status', { status: LiveBlogStatus.LIVE })
.andWhere('updates.createdAt > :since', { since })
.orderBy('updates.createdAt', 'DESC')
.getMany();
}
async findPinned(): Promise<LiveBlog[]> {
return this.liveBlogRepository.find({
where: {
isPinned: true,
status: In([LiveBlogStatus.LIVE, LiveBlogStatus.ENDED]), // Show both live and ended pinned blogs
},
relations: ['author', 'category', 'updates'],
order: { updatedAt: 'DESC' },
take: 5,
});
}
async findActive(): Promise<LiveBlog[]> {
return this.liveBlogRepository.find({
where: { status: LiveBlogStatus.LIVE },
relations: ['author', 'category'],
order: { createdAt: 'DESC' },
take: 20,
});
}
}
+28 -1
View File
@@ -28,6 +28,33 @@ export class StrapiController {
@Post('sync/all') @Post('sync/all')
async syncAllArticles() { async syncAllArticles() {
await this.strapiService.syncArticles(); await this.strapiService.syncArticles();
return { message: 'Sync completed' }; return { message: 'Articles sync completed' };
}
@Post('live-blog')
async handleLiveBlogWebhook(@Body() body: WebhookBody) {
const { event, model, entry } = body;
if (model !== 'live-blog') {
return { message: 'Ignored: not a live blog' };
}
await this.strapiService.handleWebhook(event, entry);
return { message: 'Live blog webhook processed successfully' };
}
@Post('sync/live-blogs')
async syncAllLiveBlogs() {
await this.strapiService.syncLiveBlogs();
return { message: 'Live blogs sync completed' };
}
@Post('sync/everything')
async syncEverything() {
await Promise.all([
this.strapiService.syncArticles(),
this.strapiService.syncLiveBlogs(),
]);
return { message: 'Full sync completed' };
} }
} }
+2 -1
View File
@@ -3,9 +3,10 @@ import { HttpModule } from '@nestjs/axios';
import { StrapiService } from './strapi.service'; import { StrapiService } from './strapi.service';
import { StrapiController } from './strapi.controller'; import { StrapiController } from './strapi.controller';
import { ArticlesModule } from './articles.module'; import { ArticlesModule } from './articles.module';
import { LiveBlogModule } from './live-blog.module';
@Module({ @Module({
imports: [HttpModule, ArticlesModule], imports: [HttpModule, ArticlesModule, LiveBlogModule],
controllers: [StrapiController], controllers: [StrapiController],
providers: [StrapiService], providers: [StrapiService],
exports: [StrapiService], exports: [StrapiService],
+118 -5
View File
@@ -3,8 +3,9 @@ import { ConfigService } from '@nestjs/config';
import { HttpService } from '@nestjs/axios'; import { HttpService } from '@nestjs/axios';
import { lastValueFrom } from 'rxjs'; import { lastValueFrom } from 'rxjs';
import { ArticlesService } from './articles.service'; import { ArticlesService } from './articles.service';
import { CreateArticleDto } from './articles.dto'; import { LiveBlogService } from './live-blog.service';
import { ArticleStatus } from './entities'; import { CreateArticleDto, CreateLiveBlogDto } from './articles.dto';
import { ArticleStatus, LiveBlogStatus } from './entities';
interface StrapiArticle { interface StrapiArticle {
id: number; id: number;
@@ -18,6 +19,18 @@ interface StrapiArticle {
updatedAt: string; updatedAt: string;
} }
interface StrapiLiveBlog {
id: number;
documentId: string;
title: string;
description: string;
slug: string;
status: 'draft' | 'live' | 'ended' | 'archived';
publishedAt: string | null;
createdAt: string;
updatedAt: string;
}
interface StrapiResponse<T> { interface StrapiResponse<T> {
data: T; data: T;
meta: { meta: {
@@ -40,6 +53,7 @@ export class StrapiService {
private readonly configService: ConfigService, private readonly configService: ConfigService,
private readonly httpService: HttpService, private readonly httpService: HttpService,
private readonly articlesService: ArticlesService, private readonly articlesService: ArticlesService,
private readonly liveBlogService: LiveBlogService,
) { ) {
this.strapiUrl = this.strapiUrl =
this.configService.get<string>('STRAPI_URL') || 'http://localhost:1337'; this.configService.get<string>('STRAPI_URL') || 'http://localhost:1337';
@@ -140,17 +154,116 @@ export class StrapiService {
} }
} }
async syncLiveBlogs(): Promise<void> {
try {
this.logger.log('Starting live blogs sync from Strapi...');
const response = await lastValueFrom(
this.httpService.get<StrapiResponse<StrapiLiveBlog[]>>(
`${this.strapiUrl}/api/live-blogs`,
{
headers: this.getHeaders(),
},
),
);
const strapiLiveBlogs = response.data.data;
let syncedCount = 0;
for (const strapiLiveBlog of strapiLiveBlogs) {
const liveBlogData: Partial<CreateLiveBlogDto> = {
title: strapiLiveBlog.title,
description: strapiLiveBlog.description,
slug: strapiLiveBlog.slug,
status: this.mapStrapiStatusToLiveBlogStatus(strapiLiveBlog.status),
};
await this.liveBlogService.syncFromStrapi(
strapiLiveBlog.documentId,
liveBlogData,
);
syncedCount++;
}
this.logger.log(
`Successfully synced ${syncedCount} live blogs from Strapi`,
);
} catch (error) {
this.logger.error('Failed to sync live blogs from Strapi', error);
throw error;
}
}
async syncSingleLiveBlog(strapiId: string): Promise<void> {
try {
this.logger.log(`Syncing single live blog from Strapi: ${strapiId}`);
const response = await lastValueFrom(
this.httpService.get<StrapiResponse<StrapiLiveBlog>>(
`${this.strapiUrl}/api/live-blogs/${strapiId}`,
{
headers: this.getHeaders(),
},
),
);
const strapiLiveBlog = response.data.data;
const liveBlogData: Partial<CreateLiveBlogDto> = {
title: strapiLiveBlog.title,
description: strapiLiveBlog.description,
slug: strapiLiveBlog.slug,
status: this.mapStrapiStatusToLiveBlogStatus(strapiLiveBlog.status),
};
await this.liveBlogService.syncFromStrapi(
strapiLiveBlog.documentId,
liveBlogData,
);
this.logger.log(`Successfully synced live blog: ${strapiLiveBlog.title}`);
} catch (error) {
this.logger.error(
`Failed to sync live blog ${strapiId} from Strapi`,
error,
);
throw error;
}
}
private mapStrapiStatusToLiveBlogStatus(status: string): LiveBlogStatus {
switch (status) {
case 'live':
return LiveBlogStatus.LIVE;
case 'draft':
return LiveBlogStatus.DRAFT;
case 'ended':
return LiveBlogStatus.ENDED;
case 'archived':
return LiveBlogStatus.ARCHIVED;
default:
return LiveBlogStatus.DRAFT;
}
}
async handleWebhook( async handleWebhook(
event: 'entry.create' | 'entry.update' | 'entry.delete', event: 'entry.create' | 'entry.update' | 'entry.delete',
data: { documentId: string }, data: { documentId: string; model?: string },
): Promise<void> { ): Promise<void> {
this.logger.log(`Received webhook event: ${event}`); this.logger.log(
`Received webhook event: ${event} for model: ${data.model}`,
);
if (event === 'entry.delete') { if (event === 'entry.delete') {
this.logger.log(`Handling delete for document: ${data.documentId}`); this.logger.log(`Handling delete for document: ${data.documentId}`);
return; return;
} }
await this.syncSingleArticle(data.documentId); // Route to appropriate sync method based on model
if (data.model === 'article') {
await this.syncSingleArticle(data.documentId);
} else if (data.model === 'live-blog') {
await this.syncSingleLiveBlog(data.documentId);
} else {
this.logger.warn(`Unknown model type in webhook: ${data.model}`);
}
} }
} }
+1240 -1
View File
File diff suppressed because it is too large. Load diff
+4
View File
@@ -15,7 +15,11 @@
"test:coverage": "vitest --coverage" "test:coverage": "vitest --coverage"
}, },
"dependencies": { "dependencies": {
"@radix-ui/react-label": "^2.1.8",
"@radix-ui/react-select": "^2.2.6",
"@radix-ui/react-slot": "^1.2.4", "@radix-ui/react-slot": "^1.2.4",
"@radix-ui/react-switch": "^1.2.6",
"@radix-ui/react-tabs": "^1.1.13",
"@tailwindcss/vite": "^4.1.18", "@tailwindcss/vite": "^4.1.18",
"@tanstack/react-query": "^5.90.14", "@tanstack/react-query": "^5.90.14",
"@tanstack/react-router": "^1.144.0", "@tanstack/react-router": "^1.144.0",
+4327
View File
File diff suppressed because it is too large. Load diff
+49
View File
@@ -0,0 +1,49 @@
import { useQuery } from '@tanstack/react-query'
import { Link } from '@tanstack/react-router'
import * as api from '@/lib/api'
export function ArticleTicker() {
const { data } = useQuery({
queryKey: ['ticker-articles'],
queryFn: () => api.fetchArticles({ status: 'published', limit: 10 }),
})
const articles = data?.data.slice(0, 10) || []
if (articles.length === 0) return null
return (
<div className="overflow-hidden bg-muted/50 border-y">
<div className="container mx-auto max-w-6xl px-4">
<div className="py-2 flex items-center gap-4">
<span className="text-sm font-semibold text-primary whitespace-nowrap">
Latest:
</span>
<div className="overflow-hidden flex-1 relative">
<div className="flex animate-marquee whitespace-nowrap">
{articles.map((article, index) => (
<Link
key={`${article.id}-${index}`}
to={`/articles/${article.id}`}
className="text-sm text-muted-foreground hover:text-foreground hover:underline inline-block px-4"
>
{article.title || 'No title'}
</Link>
))}
{/* Duplicate for seamless scrolling */}
{articles.map((article, index) => (
<Link
key={`dup-${article.id}-${index}`}
to={`/articles/${article.id}`}
className="text-sm text-muted-foreground hover:text-foreground hover:underline inline-block px-4"
>
{article.title || 'No title'}
</Link>
))}
</div>
</div>
</div>
</div>
</div>
)
}
@@ -0,0 +1,192 @@
import React, { useState } from 'react';
import { useCreateLiveBlog } from '@/queries/live-blogs';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { useNavigate } from '@tanstack/react-router';
import { Plus } from 'lucide-react';
interface CreateLiveBlogProps {
onSuccess?: () => void;
className?: string;
}
export function CreateLiveBlog({ onSuccess, className }: CreateLiveBlogProps) {
const navigate = useNavigate();
const [formData, setFormData] = useState({
title: '',
slug: '',
description: '',
status: 'draft' as 'draft' | 'live' | 'ended' | 'archived',
});
const [errors, setErrors] = useState<Record<string, string>>({});
const createMutation = useCreateLiveBlog();
const generateSlug = (title: string) => {
return title
.toLowerCase()
.replace(/[^\w\s-]/g, '')
.replace(/\s+/g, '-')
.replace(/--+/g, '-')
.trim();
};
const handleTitleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const title = e.target.value;
setFormData({
...formData,
title,
slug: formData.slug || generateSlug(title),
});
if (errors.title) setErrors({ ...errors, title: '' });
};
const handleSlugChange = (e: React.ChangeEvent<HTMLInputElement>) => {
setFormData({ ...formData, slug: e.target.value });
if (errors.slug) setErrors({ ...errors, slug: '' });
};
const validateForm = () => {
const newErrors: Record<string, string> = {};
if (!formData.title.trim()) {
newErrors.title = 'Title is required';
}
if (!formData.slug.trim()) {
newErrors.slug = 'Slug is required';
} else if (!/^[a-z0-9-]+$/.test(formData.slug)) {
newErrors.slug = 'Slug can only contain lowercase letters, numbers, and hyphens';
}
setErrors(newErrors);
return Object.keys(newErrors).length === 0;
};
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
if (!validateForm()) return;
try {
const result = await createMutation.mutateAsync(formData);
// Reset form
setFormData({
title: '',
slug: '',
description: '',
status: 'draft',
});
setErrors({});
// Navigate to the new live blog
navigate({ to: `/admin/live-blogs/${result.slug}` });
if (onSuccess) onSuccess();
} catch (error) {
console.error('Failed to create live blog:', error);
setErrors({ submit: 'Failed to create live blog. Please try again.' });
}
};
return (
<Card className={className}>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Plus className="w-5 h-5" />
Create New Live Blog
</CardTitle>
</CardHeader>
<CardContent>
<form onSubmit={handleSubmit} className="space-y-4">
<div className="space-y-2">
<Label htmlFor="title">Title *</Label>
<Input
id="title"
value={formData.title}
onChange={handleTitleChange}
placeholder="Enter live blog title"
disabled={createMutation.isPending}
/>
{errors.title && (
<p className="text-sm text-destructive">{errors.title}</p>
)}
</div>
<div className="space-y-2">
<Label htmlFor="slug">Slug *</Label>
<Input
id="slug"
value={formData.slug}
onChange={handleSlugChange}
placeholder="URL-friendly identifier"
disabled={createMutation.isPending}
/>
{errors.slug && (
<p className="text-sm text-destructive">{errors.slug}</p>
)}
<p className="text-xs text-muted-foreground">
This will be used in the URL: /live-blogs/your-slug-here
</p>
</div>
<div className="space-y-2">
<Label htmlFor="description">Description</Label>
<Textarea
id="description"
value={formData.description}
onChange={(e) => setFormData({ ...formData, description: e.target.value })}
placeholder="Optional description for this live blog"
rows={3}
disabled={createMutation.isPending}
/>
</div>
<div className="space-y-2">
<Label htmlFor="status">Initial Status</Label>
<Select
value={formData.status}
onValueChange={(value: 'draft' | 'live' | 'ended' | 'archived') =>
setFormData({ ...formData, status: value })
}
disabled={createMutation.isPending}
>
<SelectTrigger>
<SelectValue placeholder="Select status" />
</SelectTrigger>
<SelectContent>
<SelectItem value="draft">Draft (Not visible to public)</SelectItem>
<SelectItem value="live">Live (Visible and accepting updates)</SelectItem>
<SelectItem value="ended">Ended (Visible but not accepting updates)</SelectItem>
<SelectItem value="archived">Archived (Hidden from public)</SelectItem>
</SelectContent>
</Select>
<p className="text-xs text-muted-foreground">
You can change this later in the settings
</p>
</div>
{errors.submit && (
<div className="p-3 bg-destructive/10 border border-destructive/20 rounded-lg">
<p className="text-sm text-destructive">{errors.submit}</p>
</div>
)}
<div className="flex justify-end gap-2 pt-4">
<Button
type="submit"
disabled={createMutation.isPending}
>
{createMutation.isPending ? 'Creating...' : 'Create Live Blog'}
</Button>
</div>
</form>
</CardContent>
</Card>
);
}
@@ -0,0 +1,531 @@
import React, { useState } from 'react';
import {
useLiveBlog,
useDeleteLiveBlogUpdate,
useUpdateLiveBlog,
useDeleteLiveBlog
} from '@/queries/live-blogs';
import { UpdatePublisher } from './UpdatePublisher';
import { LiveBlogUpdate } from '@/components/features/live-blog/LiveBlogUpdate';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import type { LiveBlogUpdate as ApiLiveBlogUpdate, UpdateLiveBlogDto } from '@/lib/api';
import {
ArrowLeft,
Edit,
Play,
Square,
Archive,
Eye,
MessageSquare,
Pin,
PinOff
} from 'lucide-react';
interface LiveBlogManagerProps {
slug: string;
onBack?: () => void;
className?: string;
}
export function LiveBlogManager({ slug, onBack, className }: LiveBlogManagerProps) {
const [activeTab, setActiveTab] = useState('updates');
const [isEditing, setIsEditing] = useState(false);
const [editForm, setEditForm] = useState<UpdateLiveBlogDto>({});
const { data: liveBlog, isLoading, error } = useLiveBlog(slug);
const deleteUpdateMutation = useDeleteLiveBlogUpdate();
const updateLiveBlogMutation = useUpdateLiveBlog();
const deleteLiveBlogMutation = useDeleteLiveBlog();
const handleDeleteUpdate = async (update: ApiLiveBlogUpdate) => {
if (!liveBlog) return;
if (confirm('Are you sure you want to delete this update? This action cannot be undone.')) {
try {
await deleteUpdateMutation.mutateAsync({
liveBlogId: liveBlog.id,
updateId: update.id,
});
} catch (error) {
console.error('Failed to delete update:', error);
}
}
};
const handleEditUpdate = (update: ApiLiveBlogUpdate) => {
// The UpdatePublisher component handles editing internally
console.log('Editing update:', update);
};
const handleStartEdit = () => {
if (!liveBlog) return;
setIsEditing(true);
setEditForm({
title: liveBlog.title,
slug: liveBlog.slug,
description: liveBlog.description || '',
status: liveBlog.status,
});
};
const handleCancelEdit = () => {
setIsEditing(false);
setEditForm({});
};
const handleSaveEdit = async () => {
if (!liveBlog) return;
try {
await updateLiveBlogMutation.mutateAsync({
id: liveBlog.id,
dto: editForm,
});
setIsEditing(false);
setEditForm({});
} catch (error) {
console.error('Failed to update live blog:', error);
}
};
const handleStatusChange = async (newStatus: 'draft' | 'live' | 'ended' | 'archived') => {
if (!liveBlog) return;
try {
await updateLiveBlogMutation.mutateAsync({
id: liveBlog.id,
dto: { status: newStatus },
});
} catch (error) {
console.error('Failed to update status:', error);
alert(`Failed to update status: ${error instanceof Error ? error.message : 'Unknown error'}`);
}
};
const handleTogglePin = async () => {
if (!liveBlog) return;
try {
await updateLiveBlogMutation.mutateAsync({
id: liveBlog.id,
dto: { isPinned: !liveBlog.isPinned },
});
} catch (error) {
console.error('Failed to toggle pin:', error);
alert(`Failed to toggle pin: ${error instanceof Error ? error.message : 'Unknown error'}`);
}
};
const handleDeleteLiveBlog = async () => {
if (!liveBlog) return;
if (confirm('Are you sure you want to delete this live blog? This action cannot be undone and will delete all updates.')) {
try {
await deleteLiveBlogMutation.mutateAsync(liveBlog.id);
if (onBack) onBack();
} catch (error) {
console.error('Failed to delete live blog:', error);
}
}
};
if (isLoading) {
return (
<Card className={className}>
<CardContent className="p-6">
<div className="animate-pulse space-y-4">
<div className="h-8 bg-muted rounded w-3/4"></div>
<div className="h-4 bg-muted rounded w-1/2"></div>
<div className="h-32 bg-muted rounded"></div>
</div>
</CardContent>
</Card>
);
}
if (error || !liveBlog) {
return (
<Card className={className}>
<CardContent className="p-6">
<div className="text-center text-destructive">
<h3 className="text-lg font-semibold mb-2">Failed to load live blog</h3>
<p className="text-sm mb-4">
{error instanceof Error ? error.message : 'Unknown error occurred'}
</p>
{onBack && (
<Button variant="outline" onClick={onBack}>
<ArrowLeft className="w-4 h-4 mr-2" />
Back
</Button>
)}
</div>
</CardContent>
</Card>
);
}
const getStatusColor = (status: string) => {
switch (status) {
case 'live': return 'bg-green-100 text-green-800 border-green-200';
case 'draft': return 'bg-gray-100 text-gray-800 border-gray-200';
case 'ended': return 'bg-red-100 text-red-800 border-red-200';
case 'archived': return 'bg-blue-100 text-blue-800 border-blue-200';
default: return 'bg-gray-100 text-gray-800 border-gray-200';
}
};
const getStatusIcon = (status: string) => {
switch (status) {
case 'live': return <Play className="w-3 h-3" />;
case 'draft': return <Edit className="w-3 h-3" />;
case 'ended': return <Square className="w-3 h-3" />;
case 'archived': return <Archive className="w-3 h-3" />;
default: return null;
}
};
return (
<div className={className}>
{/* Header */}
<Card className="mb-6">
<CardHeader>
<div className="flex items-start justify-between">
<div className="flex-1">
<div className="flex items-center gap-3 mb-2">
{onBack && (
<Button variant="ghost" size="sm" onClick={onBack}>
<ArrowLeft className="w-4 h-4" />
</Button>
)}
<CardTitle className="text-2xl">{liveBlog.title}</CardTitle>
</div>
{liveBlog.description && (
<p className="text-muted-foreground mb-4">{liveBlog.description}</p>
)}
<div className="flex items-center gap-4 text-sm">
<Badge className={getStatusColor(liveBlog.status)} variant="outline">
<div className="flex items-center gap-1">
{getStatusIcon(liveBlog.status)}
{liveBlog.status}
</div>
</Badge>
<div className="flex items-center gap-1 text-muted-foreground">
<Eye className="w-4 h-4" />
{liveBlog.viewCount} views
</div>
<div className="flex items-center gap-1 text-muted-foreground">
<MessageSquare className="w-4 h-4" />
{liveBlog.updates?.length || 0} updates
</div>
{liveBlog.author && (
<div className="flex items-center gap-2">
{liveBlog.author.avatar && (
<img
src={liveBlog.author.avatar}
alt={liveBlog.author.name}
className="w-6 h-6 rounded-full"
/>
)}
<span className="text-muted-foreground">{liveBlog.author.name}</span>
</div>
)}
</div>
</div>
</div>
</CardHeader>
</Card>
{/* Main content */}
<Tabs value={activeTab} onValueChange={setActiveTab}>
<TabsList className="grid w-full grid-cols-2">
<TabsTrigger value="updates">Updates</TabsTrigger>
<TabsTrigger value="settings">Settings</TabsTrigger>
</TabsList>
<TabsContent value="updates" className="space-y-6">
<UpdatePublisher
liveBlogId={liveBlog.id}
authorId={liveBlog.authorId || undefined}
/>
{/* Recent updates preview */}
{liveBlog.updates && liveBlog.updates.length > 0 && (
<Card>
<CardHeader>
<CardTitle className="text-lg">All Updates</CardTitle>
</CardHeader>
<CardContent>
<div className="space-y-4">
{liveBlog.updates.map((update) => (
<LiveBlogUpdate
key={update.id}
update={update}
showAdminControls={true}
onEdit={handleEditUpdate}
onDelete={handleDeleteUpdate}
onPinToggle={(update) => {
// Handle pin toggle
console.log('Toggle pin for update:', update);
}}
/>
))}
</div>
</CardContent>
</Card>
)}
</TabsContent>
<TabsContent value="settings" className="space-y-6">
<Card>
<CardHeader>
<div className="flex items-center justify-between">
<CardTitle>Live Blog Settings</CardTitle>
{!isEditing ? (
<Button variant="outline" size="sm" onClick={handleStartEdit}>
<Edit className="w-4 h-4 mr-2" />
Edit
</Button>
) : (
<div className="flex gap-2">
<Button variant="outline" size="sm" onClick={handleCancelEdit}>
Cancel
</Button>
<Button size="sm" onClick={handleSaveEdit}>
Save Changes
</Button>
</div>
)}
</div>
</CardHeader>
<CardContent>
<div className="space-y-6">
{isEditing ? (
<div className="space-y-4">
<div className="space-y-2">
<Label htmlFor="title">Title</Label>
<Input
id="title"
value={editForm.title || ''}
onChange={(e) => setEditForm({ ...editForm, title: e.target.value })}
/>
</div>
<div className="space-y-2">
<Label htmlFor="slug">Slug</Label>
<Input
id="slug"
value={editForm.slug || ''}
onChange={(e) => setEditForm({ ...editForm, slug: e.target.value })}
placeholder="URL-friendly identifier"
/>
</div>
<div className="space-y-2">
<Label htmlFor="description">Description</Label>
<Textarea
id="description"
value={editForm.description || ''}
onChange={(e) => setEditForm({ ...editForm, description: e.target.value })}
rows={3}
/>
</div>
<div className="space-y-2">
<Label htmlFor="status">Status</Label>
<Select
value={editForm.status}
onValueChange={(value: 'draft' | 'live' | 'ended' | 'archived') =>
setEditForm({ ...editForm, status: value })
}
>
<SelectTrigger>
<SelectValue placeholder="Select status" />
</SelectTrigger>
<SelectContent>
<SelectItem value="draft">Draft</SelectItem>
<SelectItem value="live">Live</SelectItem>
<SelectItem value="ended">Ended</SelectItem>
<SelectItem value="archived">Archived</SelectItem>
</SelectContent>
</Select>
</div>
</div>
) : (
<>
<div className="p-4 bg-muted rounded-lg">
<h4 className="font-medium mb-2">Status Management</h4>
<p className="text-sm text-muted-foreground mb-4">
Control the live blog status and visibility
</p>
<div className="flex flex-wrap gap-2">
{liveBlog.status !== 'live' && (
<Button
variant="outline"
size="sm"
onClick={() => handleStatusChange('live')}
disabled={updateLiveBlogMutation.isPending}
>
<Play className="w-4 h-4 mr-2" />
{updateLiveBlogMutation.isPending ? 'Updating...' : 'Go Live'}
</Button>
)}
{liveBlog.status === 'live' && (
<Button
variant="outline"
size="sm"
onClick={() => handleStatusChange('ended')}
disabled={updateLiveBlogMutation.isPending}
>
<Square className="w-4 h-4 mr-2" />
{updateLiveBlogMutation.isPending ? 'Updating...' : 'End Live Session'}
</Button>
)}
{liveBlog.status !== 'archived' && (
<Button
variant="outline"
size="sm"
onClick={() => handleStatusChange('archived')}
disabled={updateLiveBlogMutation.isPending}
>
<Archive className="w-4 h-4 mr-2" />
{updateLiveBlogMutation.isPending ? 'Updating...' : 'Archive'}
</Button>
)}
{liveBlog.status === 'archived' && (
<Button
variant="outline"
size="sm"
onClick={() => handleStatusChange('draft')}
disabled={updateLiveBlogMutation.isPending}
>
<Edit className="w-4 h-4 mr-2" />
{updateLiveBlogMutation.isPending ? 'Updating...' : 'Unarchive'}
</Button>
)}
<Button
variant={liveBlog.isPinned ? "default" : "outline"}
size="sm"
onClick={handleTogglePin}
disabled={updateLiveBlogMutation.isPending}
>
{liveBlog.isPinned ? (
<>
<PinOff className="w-4 h-4 mr-2" />
{updateLiveBlogMutation.isPending ? 'Updating...' : 'Unpin'}
</>
) : (
<>
<Pin className="w-4 h-4 mr-2" />
{updateLiveBlogMutation.isPending ? 'Updating...' : 'Pin to Homepage'}
</>
)}
</Button>
</div>
</div>
<div className="p-4 bg-muted rounded-lg">
<h4 className="font-medium mb-2">Live Blog Information</h4>
<div className="space-y-3 text-sm">
<div className="flex justify-between">
<span className="text-muted-foreground">Title:</span>
<span className="font-medium">{liveBlog.title}</span>
</div>
<div className="flex justify-between">
<span className="text-muted-foreground">Slug:</span>
<span className="font-medium">{liveBlog.slug}</span>
</div>
{liveBlog.description && (
<div className="flex justify-between">
<span className="text-muted-foreground">Description:</span>
<span className="font-medium text-right max-w-xs">{liveBlog.description}</span>
</div>
)}
<div className="flex justify-between">
<span className="text-muted-foreground">Status:</span>
<Badge className={getStatusColor(liveBlog.status)} variant="outline">
<div className="flex items-center gap-1">
{getStatusIcon(liveBlog.status)}
{liveBlog.status}
</div>
</Badge>
</div>
<div className="flex justify-between">
<span className="text-muted-foreground">Pinned:</span>
<Badge variant={liveBlog.isPinned ? "default" : "outline"}>
<div className="flex items-center gap-1">
{liveBlog.isPinned ? <Pin className="w-3 h-3" /> : <PinOff className="w-3 h-3" />}
{liveBlog.isPinned ? 'Yes' : 'No'}
</div>
</Badge>
</div>
</div>
</div>
</>
)}
<div className="p-4 bg-muted rounded-lg">
<h4 className="font-medium mb-2">Analytics</h4>
<div className="grid grid-cols-2 gap-4 text-sm">
<div>
<span className="text-muted-foreground">Total Views:</span>
<div className="font-medium">{liveBlog.viewCount}</div>
</div>
<div>
<span className="text-muted-foreground">Total Updates:</span>
<div className="font-medium">{liveBlog.updates?.length || 0}</div>
</div>
<div>
<span className="text-muted-foreground">Created:</span>
<div className="font-medium">
{new Date(liveBlog.createdAt).toLocaleDateString()}
</div>
</div>
<div>
<span className="text-muted-foreground">Last Updated:</span>
<div className="font-medium">
{new Date(liveBlog.updatedAt).toLocaleDateString()}
</div>
</div>
</div>
</div>
<div className="p-4 border border-destructive/20 rounded-lg">
<h4 className="font-medium mb-2 text-destructive">Danger Zone</h4>
<p className="text-sm text-muted-foreground mb-4">
Once you delete a live blog, there is no going back. Please be certain.
</p>
<Button
variant="destructive"
size="sm"
onClick={handleDeleteLiveBlog}
disabled={deleteLiveBlogMutation.isPending}
>
{deleteLiveBlogMutation.isPending ? 'Deleting...' : 'Delete Live Blog'}
</Button>
</div>
</div>
</CardContent>
</Card>
</TabsContent>
</Tabs>
</div>
);
}
@@ -0,0 +1,263 @@
import React, { useState, useRef } from 'react';
import { useCreateLiveBlogUpdate, useUpdateLiveBlogUpdate, useLiveBlogUpdates } from '@/queries/live-blogs';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Textarea } from '@/components/ui/textarea';
import { Switch } from '@/components/ui/switch';
import { Label } from '@/components/ui/label';
import type { LiveBlogUpdate, CreateLiveBlogUpdateDto } from '@/lib/api';
import { cn } from '@/lib/utils';
import { Send, Pin, Calendar, Edit } from 'lucide-react';
interface UpdatePublisherProps {
liveBlogId: string;
authorId?: string;
className?: string;
}
export function UpdatePublisher({ liveBlogId, authorId, className }: UpdatePublisherProps) {
const [content, setContent] = useState('');
const [isPinned, setIsPinned] = useState(false);
const [scheduledAt, setScheduledAt] = useState('');
const [isScheduleMode, setIsScheduleMode] = useState(false);
const textareaRef = useRef<HTMLTextAreaElement>(null);
const createMutation = useCreateLiveBlogUpdate();
const updateMutation = useUpdateLiveBlogUpdate();
const [editingUpdate, setEditingUpdate] = useState<LiveBlogUpdate | null>(null);
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
if (!content.trim()) return;
const updateData: CreateLiveBlogUpdateDto = {
content: content.trim(),
isPinned,
authorId,
...(isScheduleMode && scheduledAt ? { scheduledAt } : {}),
};
try {
if (editingUpdate) {
// Update existing update
await updateMutation.mutateAsync({
liveBlogId,
updateId: editingUpdate.id,
dto: {
content: content.trim(),
isPinned,
},
});
setEditingUpdate(null);
} else {
// Create new update
await createMutation.mutateAsync({
liveBlogId,
dto: updateData,
});
}
// Reset form
setContent('');
setIsPinned(false);
setScheduledAt('');
setIsScheduleMode(false);
textareaRef.current?.focus();
} catch (error) {
console.error('Failed to save update:', error);
}
};
const handleEdit = (update: LiveBlogUpdate) => {
setContent(update.content);
setIsPinned(update.isPinned);
setEditingUpdate(update);
setIsScheduleMode(false);
textareaRef.current?.focus();
};
const handleCancelEdit = () => {
setEditingUpdate(null);
setContent('');
setIsPinned(false);
setIsScheduleMode(false);
};
const isLoading = createMutation.isPending || updateMutation.isPending;
// Get minimum date for scheduling (now + 5 minutes)
const minScheduleDate = new Date().toISOString().slice(0, 16);
return (
<Card className={className}>
<CardHeader>
<CardTitle className="flex items-center gap-2">
{editingUpdate ? 'Edit Update' : 'Publish Update'}
{editingUpdate && (
<span className="text-xs bg-muted px-2 py-1 rounded-full">
ID: {editingUpdate.id.slice(0, 8)}
</span>
)}
</CardTitle>
</CardHeader>
<CardContent>
<form onSubmit={handleSubmit} className="space-y-4">
{/* Content textarea */}
<div className="space-y-2">
<Label htmlFor="content">
{editingUpdate ? 'Edit content' : 'Update content'}
</Label>
<Textarea
id="content"
ref={textareaRef}
placeholder="What's the latest update?"
value={content}
onChange={(e) => setContent(e.target.value)}
rows={4}
className="resize-none"
disabled={isLoading}
/>
</div>
{/* Options */}
<div className="flex flex-wrap gap-4">
{/* Pin toggle */}
<div className="flex items-center space-x-2">
<Switch
id="pin"
checked={isPinned}
onCheckedChange={setIsPinned}
disabled={isLoading}
/>
<Label htmlFor="pin" className="flex items-center gap-2">
<Pin className="w-4 h-4" />
Pin to top
</Label>
</div>
{/* Schedule toggle */}
<div className="flex items-center space-x-2">
<Switch
id="schedule"
checked={isScheduleMode}
onCheckedChange={setIsScheduleMode}
disabled={isLoading}
/>
<Label htmlFor="schedule" className="flex items-center gap-2">
<Calendar className="w-4 h-4" />
Schedule
</Label>
</div>
</div>
{/* Schedule date/time picker */}
{isScheduleMode && (
<div className="space-y-2">
<Label htmlFor="scheduleAt">Schedule for (minimum 5 minutes from now)</Label>
<input
id="scheduleAt"
type="datetime-local"
min={minScheduleDate}
value={scheduledAt}
onChange={(e) => setScheduledAt(e.target.value)}
className="w-full p-2 border rounded-md"
disabled={isLoading}
/>
</div>
)}
{/* Action buttons */}
<div className="flex gap-2">
<Button
type="submit"
disabled={!content.trim() || isLoading}
className="flex-1"
>
{isLoading ? (
'Saving...'
) : editingUpdate ? (
'Update'
) : (
<>
<Send className="w-4 h-4 mr-2" />
{isScheduleMode ? 'Schedule' : 'Publish'}
</>
)}
</Button>
{editingUpdate && (
<Button
type="button"
variant="outline"
onClick={handleCancelEdit}
disabled={isLoading}
>
Cancel
</Button>
)}
</div>
</form>
{/* Recent updates for editing */}
{editingUpdate === null && (
<div className="mt-6 pt-6 border-t">
<h4 className="text-sm font-medium mb-3">Recent Updates (Click to edit)</h4>
<RecentUpdates
liveBlogId={liveBlogId}
onEdit={handleEdit}
isLoading={isLoading}
/>
</div>
)}
</CardContent>
</Card>
);
}
interface RecentUpdatesProps {
liveBlogId: string;
onEdit: (update: LiveBlogUpdate) => void;
isLoading: boolean;
}
function RecentUpdates({ liveBlogId, onEdit, isLoading }: RecentUpdatesProps) {
const { data: updatesData } = useLiveBlogUpdates(liveBlogId, 1, 5);
const updates = updatesData?.data || [];
if (updates.length === 0) {
return (
<p className="text-sm text-muted-foreground">No updates yet. Start by publishing your first update!</p>
);
}
return (
<div className="space-y-2">
{updates.map((update) => (
<div
key={update.id}
className={cn(
'p-3 rounded border cursor-pointer hover:bg-muted/50 transition-colors',
isLoading && 'opacity-50 pointer-events-none'
)}
onClick={() => onEdit(update)}
>
<div className="flex items-start justify-between mb-2">
<div className="flex items-center gap-2">
{update.isPinned && <Pin className="w-3 h-3 text-primary" />}
<span className="text-xs text-muted-foreground">
{new Date(update.createdAt).toLocaleString()}
</span>
</div>
<Edit className="w-3 h-3 text-muted-foreground" />
</div>
<p className="text-sm line-clamp-2">{update.content}</p>
</div>
))}
</div>
);
}
@@ -0,0 +1,238 @@
import React, { useState, useEffect, useRef } from 'react';
import { Link } from '@tanstack/react-router';
import { useActiveLiveBlogs } from '@/queries/live-blogs';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Play, Pause, ChevronRight, Radio } from 'lucide-react';
interface LiveBlogTickerProps {
className?: string;
maxItems?: number;
autoScroll?: boolean;
scrollSpeed?: number; // pixels per second
}
export function LiveBlogTicker({
className = '',
maxItems = 10,
autoScroll = true,
scrollSpeed = 30
}: LiveBlogTickerProps) {
const { data: activeBlogs, isLoading } = useActiveLiveBlogs();
const [isPaused, setIsPaused] = useState(false);
const [scrollPosition, setScrollPosition] = useState(0);
const tickerRef = useRef<HTMLDivElement>(null);
const contentRef = useRef<HTMLDivElement>(null);
const animationRef = useRef<number>();
// Calculate total width needed for scrolling
const [totalWidth, setTotalWidth] = useState(0);
useEffect(() => {
if (contentRef.current) {
const width = contentRef.current.scrollWidth;
setTotalWidth(width);
}
}, [activeBlogs]);
// Auto-scroll animation
useEffect(() => {
if (!autoScroll || isPaused || !activeBlogs || activeBlogs.length === 0) {
if (animationRef.current) {
cancelAnimationFrame(animationRef.current);
}
return;
}
let lastTime: number;
const animate = (time: number) => {
if (!lastTime) lastTime = time;
const delta = time - lastTime;
lastTime = time;
setScrollPosition(prev => {
let newPos = prev + (scrollSpeed * delta) / 1000;
// Reset when scrolled past content
if (newPos > totalWidth) {
newPos = -tickerRef.current?.offsetWidth || 0;
}
return newPos;
});
animationRef.current = requestAnimationFrame(animate);
};
animationRef.current = requestAnimationFrame(animate);
return () => {
if (animationRef.current) {
cancelAnimationFrame(animationRef.current);
}
};
}, [autoScroll, isPaused, activeBlogs, scrollSpeed, totalWidth]);
if (isLoading) {
return (
<div className={`bg-muted/50 border rounded-lg p-3 ${className}`}>
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
<div className="animate-pulse h-4 w-24 bg-muted rounded"></div>
</div>
<div className="animate-pulse h-8 w-20 bg-muted rounded"></div>
</div>
</div>
);
}
if (!activeBlogs || activeBlogs.length === 0) {
return null; // Don't show ticker if no active blogs
}
const displayBlogs = activeBlogs.slice(0, maxItems);
const handlePauseToggle = () => {
setIsPaused(!isPaused);
};
const handleBlogClick = () => {
// Reset scroll position when user interacts
setScrollPosition(0);
};
return (
<div className={`bg-background border rounded-lg overflow-hidden ${className}`}>
{/* Ticker header */}
<div className="flex items-center justify-between px-4 py-2 border-b bg-muted/30">
<div className="flex items-center gap-2">
<Radio className="w-4 h-4 text-primary" />
<span className="font-medium text-sm">Live Now</span>
<Badge variant="secondary" className="text-xs">
{activeBlogs.length} active
</Badge>
</div>
<div className="flex items-center gap-2">
{autoScroll && (
<Button
variant="ghost"
size="sm"
onClick={handlePauseToggle}
className="h-7 px-2"
>
{isPaused ? (
<Play className="w-3 h-3" />
) : (
<Pause className="w-3 h-3" />
)}
<span className="ml-1 text-xs">{isPaused ? 'Play' : 'Pause'}</span>
</Button>
)}
<Link to="/live-blogs">
<Button variant="ghost" size="sm" className="h-7 px-2">
<span className="text-xs">View All</span>
<ChevronRight className="w-3 h-3 ml-1" />
</Button>
</Link>
</div>
</div>
{/* Ticker content */}
<div
ref={tickerRef}
className="relative h-12 overflow-hidden"
style={{
maskImage: 'linear-gradient(to right, transparent, black 20px, black calc(100% - 20px), transparent)',
WebkitMaskImage: 'linear-gradient(to right, transparent, black 20px, black calc(100% - 20px), transparent)'
}}
>
<div
ref={contentRef}
className="absolute top-0 left-0 h-full flex items-center whitespace-nowrap"
style={{
transform: `translateX(-${scrollPosition}px)`,
transition: isPaused ? 'transform 0.3s ease' : 'none'
}}
>
{displayBlogs.map((blog, index) => (
<React.Fragment key={blog.id}>
<Link
to="/live-blogs/$slug"
params={{ slug: blog.slug }}
onClick={handleBlogClick}
className="inline-flex items-center gap-2 px-4 py-1 rounded-full hover:bg-accent transition-colors group"
>
<div className="flex items-center gap-2">
<div className="relative">
<div className="w-2 h-2 bg-green-500 rounded-full animate-pulse"></div>
<div className="absolute inset-0 w-2 h-2 bg-green-500 rounded-full animate-ping"></div>
</div>
<span className="font-medium text-sm group-hover:text-primary transition-colors">
{blog.title}
</span>
{blog.updates && blog.updates.length > 0 && (
<Badge variant="outline" className="text-xs">
{blog.updates.length} updates
</Badge>
)}
</div>
</Link>
{/* Separator (except after last item) */}
{index < displayBlogs.length - 1 && (
<div className="mx-2 text-muted-foreground">•</div>
)}
</React.Fragment>
))}
{/* Duplicate content for seamless looping */}
{displayBlogs.map((blog, index) => (
<React.Fragment key={`${blog.id}-dup`}>
<Link
to="/live-blogs/$slug"
params={{ slug: blog.slug }}
onClick={handleBlogClick}
className="inline-flex items-center gap-2 px-4 py-1 rounded-full hover:bg-accent transition-colors group"
>
<div className="flex items-center gap-2">
<div className="relative">
<div className="w-2 h-2 bg-green-500 rounded-full animate-pulse"></div>
<div className="absolute inset-0 w-2 h-2 bg-green-500 rounded-full animate-ping"></div>
</div>
<span className="font-medium text-sm group-hover:text-primary transition-colors">
{blog.title}
</span>
{blog.updates && blog.updates.length > 0 && (
<Badge variant="outline" className="text-xs">
{blog.updates.length} updates
</Badge>
)}
</div>
</Link>
{index < displayBlogs.length - 1 && (
<div className="mx-2 text-muted-foreground">•</div>
)}
</React.Fragment>
))}
</div>
</div>
{/* Progress indicator */}
{autoScroll && totalWidth > 0 && (
<div className="px-4 pb-2">
<div className="h-1 bg-muted rounded-full overflow-hidden">
<div
className="h-full bg-primary transition-all duration-300"
style={{
width: `${Math.min(100, (scrollPosition / totalWidth) * 100 * 2)}%`
}}
/>
</div>
</div>
)}
</div>
);
}
@@ -0,0 +1,145 @@
import React from 'react';
import type { LiveBlogUpdate as ApiLiveBlogUpdate } from '@/lib/api';
import { Button } from '@/components/ui/button';
import { cn } from '@/lib/utils';
import {
Pin,
PinOff,
Edit,
Trash2,
Clock,
User
} from 'lucide-react';
interface LiveBlogUpdateProps {
update: ApiLiveBlogUpdate;
isEditing?: boolean;
onEdit?: (update: ApiLiveBlogUpdate) => void;
onDelete?: (update: ApiLiveBlogUpdate) => void;
onPinToggle?: (update: ApiLiveBlogUpdate) => void;
showAdminControls?: boolean;
}
export function LiveBlogUpdate({
update,
isEditing = false,
onEdit,
onDelete,
onPinToggle,
showAdminControls = false,
}: LiveBlogUpdateProps) {
const isPinned = update.isPinned;
return (
<div
className={cn(
'relative p-4 rounded-lg border transition-all duration-200',
isPinned && 'border-primary bg-primary/5 shadow-sm',
!isPinned && 'border-border hover:border-muted-foreground/20'
)}
>
{/* Pinned indicator */}
{isPinned && (
<div className="absolute -top-2 -left-2 bg-primary text-primary-foreground text-xs px-2 py-1 rounded-full flex items-center gap-1">
<Pin className="w-3 h-3" />
Pinned
</div>
)}
{/* Admin controls */}
{showAdminControls && (
<div className="absolute top-2 right-2 flex gap-1 opacity-0 group-hover:opacity-100 transition-opacity">
<Button
variant="ghost"
size="sm"
onClick={() => onPinToggle?.(update)}
className="h-8 w-8 p-0"
>
{isPinned ? <PinOff className="w-4 h-4" /> : <Pin className="w-4 h-4" />}
</Button>
<Button
variant="ghost"
size="sm"
onClick={() => onEdit?.(update)}
className="h-8 w-8 p-0"
>
<Edit className="w-4 h-4" />
</Button>
<Button
variant="ghost"
size="sm"
onClick={() => onDelete?.(update)}
className="h-8 w-8 p-0 text-destructive hover:text-destructive"
>
<Trash2 className="w-4 h-4" />
</Button>
</div>
)}
<div className="flex items-start justify-between mb-3">
<div className="flex items-center gap-3">
{update.author ? (
<>
{update.author.avatar ? (
<img
src={update.author.avatar}
alt={update.author.name}
className="w-8 h-8 rounded-full object-cover"
/>
) : (
<div className="w-8 h-8 rounded-full bg-muted flex items-center justify-center">
<User className="w-4 h-4 text-muted-foreground" />
</div>
)}
<div>
<div className="font-medium text-sm">{update.author.name}</div>
{update.author.slug && (
<div className="text-xs text-muted-foreground">@{update.author.slug}</div>
)}
</div>
</>
) : (
<div className="flex items-center gap-2 text-muted-foreground">
<User className="w-4 h-4" />
<span className="text-sm">Anonymous</span>
</div>
)}
</div>
<div className="flex items-center gap-2 text-xs text-muted-foreground">
<Clock className="w-3 h-3" />
<span>{new Date(update.createdAt).toLocaleTimeString()}</span>
</div>
</div>
{/* Update content */}
<div className="prose prose-sm max-w-none">
{isEditing ? (
<textarea
defaultValue={update.content}
className="w-full p-2 border rounded-md resize-none focus:outline-none focus:ring-2 focus:ring-primary"
rows={3}
autoFocus
/>
) : (
<div className="text-sm leading-relaxed whitespace-pre-wrap">
{update.content}
</div>
)}
</div>
{/* Scheduled indicator */}
{update.scheduledAt && new Date(update.scheduledAt) > new Date() && (
<div className="mt-2 text-xs text-muted-foreground flex items-center gap-1">
<Clock className="w-3 h-3" />
Scheduled for: {new Date(update.scheduledAt).toLocaleString()}
</div>
)}
{/* Update metadata */}
<div className="mt-2 text-xs text-muted-foreground">
ID: {update.id.slice(0, 8)}
</div>
</div>
);
}
@@ -0,0 +1,301 @@
import React, { useState, useEffect, useRef, useCallback } from 'react';
import { useLiveBlogStream } from '@/hooks/useLiveBlogStream';
import { useLiveBlog, useLiveBlogUpdates } from '@/queries/live-blogs';
import type { LiveBlogUpdate as ApiLiveBlogUpdate } from '@/lib/api';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { cn } from '@/lib/utils';
interface LiveBlogViewerProps {
slug: string;
className?: string;
}
export function LiveBlogViewer({ slug, className }: LiveBlogViewerProps) {
const [autoScroll, setAutoScroll] = useState(true);
const [newUpdatesCount, setNewUpdatesCount] = useState(0);
const [isScrolledUp, setIsScrolledUp] = useState(false);
const updatesContainerRef = useRef<HTMLDivElement>(null);
const lastUpdateCountRef = useRef(0);
const { data: liveBlog, isLoading: blogLoading, error: blogError } = useLiveBlog(slug);
const {
data: updatesData,
isLoading: updatesLoading,
refetch: refetchUpdates
} = useLiveBlogUpdates(liveBlog?.id || '', 1, 100);
const {
isConnected,
lastEvent,
connectionError,
reconnectAttempts,
connect
} = useLiveBlogStream(liveBlog?.id || '');
const scrollToBottom = useCallback(() => {
if (updatesContainerRef.current && autoScroll) {
const container = updatesContainerRef.current;
container.scrollTo({
top: container.scrollHeight,
behavior: 'smooth'
});
}
}, [autoScroll]);
const handleScroll = useCallback(() => {
if (!updatesContainerRef.current) return;
const container = updatesContainerRef.current;
const isAtBottom = container.scrollHeight - container.scrollTop <= container.clientHeight + 50;
setIsScrolledUp(!isAtBottom);
if (isAtBottom) {
setNewUpdatesCount(0);
}
}, []);
const handleAutoScrollToggle = useCallback(() => {
setAutoScroll(!autoScroll);
if (!autoScroll) {
scrollToBottom();
setNewUpdatesCount(0);
}
}, [autoScroll, scrollToBottom]);
const showNewUpdates = useCallback(() => {
setNewUpdatesCount(0);
scrollToBottom();
setIsScrolledUp(false);
}, [scrollToBottom]);
// Handle new updates from SSE
useEffect(() => {
if (lastEvent?.type === 'update') {
const handleUpdate = () => {
refetchUpdates();
if (autoScroll && !isScrolledUp) {
// Add a small delay to ensure the update is in the DOM
setTimeout(() => {
scrollToBottom();
}, 100);
} else if (!autoScroll || isScrolledUp) {
setNewUpdatesCount(prev => prev + 1);
}
};
handleUpdate();
}
}, [lastEvent, autoScroll, isScrolledUp, refetchUpdates, scrollToBottom]);
// Initial scroll to bottom when data loads
useEffect(() => {
if (updatesData?.data && updatesData.data.length > 0) {
const currentUpdateCount = updatesData.data.length;
// Only auto-scroll if this is the initial load or user is at bottom
if (currentUpdateCount > lastUpdateCountRef.current && !isScrolledUp) {
setTimeout(scrollToBottom, 100);
}
lastUpdateCountRef.current = currentUpdateCount;
}
}, [updatesData, scrollToBottom, isScrolledUp]);
if (blogLoading) {
return (
<Card className={cn('w-full max-w-4xl mx-auto', className)}>
<CardContent className="p-6">
<div className="animate-pulse space-y-4">
<div className="h-8 bg-muted rounded w-3/4"></div>
<div className="h-4 bg-muted rounded w-1/2"></div>
<div className="space-y-2">
<div className="h-16 bg-muted rounded"></div>
<div className="h-16 bg-muted rounded"></div>
<div className="h-16 bg-muted rounded"></div>
</div>
</div>
</CardContent>
</Card>
);
}
if (blogError || !liveBlog) {
return (
<Card className={cn('w-full max-w-4xl mx-auto', className)}>
<CardContent className="p-6">
<div className="text-center text-destructive">
<h3 className="text-lg font-semibold mb-2">Failed to load live blog</h3>
<p className="text-sm">
{blogError instanceof Error ? blogError.message : 'Unknown error occurred'}
</p>
</div>
</CardContent>
</Card>
);
}
const updates = updatesData?.data || [];
const isLive = liveBlog.status === 'live';
return (
<Card className={cn('w-full max-w-4xl mx-auto', className)}>
<CardHeader>
<div className="flex items-center justify-between">
<div className="flex-1">
<CardTitle className="text-2xl mb-2">{liveBlog.title}</CardTitle>
{liveBlog.description && (
<p className="text-muted-foreground">{liveBlog.description}</p>
)}
<div className="flex items-center gap-4 mt-4 text-sm text-muted-foreground">
<div className="flex items-center gap-2">
<div className={cn(
'w-2 h-2 rounded-full',
isLive ? 'bg-green-500' : 'bg-gray-400'
)} />
<span>{isLive ? 'Live' : 'Ended'}</span>
</div>
{isLive && (
<div className="flex items-center gap-2">
<div className={cn(
'w-2 h-2 rounded-full',
isConnected ? 'bg-green-500' : 'bg-red-500'
)} />
<span>
{isConnected ? 'Connected' : `Reconnecting... (${reconnectAttempts})`}
</span>
</div>
)}
<span>{liveBlog.viewCount} views</span>
<span>{updates.length} updates</span>
</div>
</div>
<div className="flex items-center gap-2">
<Button
variant={autoScroll ? 'default' : 'outline'}
size="sm"
onClick={handleAutoScrollToggle}
>
{autoScroll ? 'Auto-scroll ON' : 'Auto-scroll OFF'}
</Button>
{!isConnected && (
<Button
variant="outline"
size="sm"
onClick={connect}
>
Reconnect
</Button>
)}
</div>
</div>
</CardHeader>
<CardContent className="p-0">
{connectionError && (
<div className="m-6 p-4 bg-destructive/10 border border-destructive/20 rounded-lg">
<div className="flex items-center justify-between">
<p className="text-sm text-destructive">
{connectionError}
</p>
<Button
variant="outline"
size="sm"
onClick={connect}
>
Try Again
</Button>
</div>
</div>
)}
<div
ref={updatesContainerRef}
className="max-h-[600px] overflow-y-auto px-6 pb-6"
onScroll={handleScroll}
>
{updates.length === 0 && !updatesLoading ? (
<div className="text-center py-12 text-muted-foreground">
<p>No updates yet. Check back soon!</p>
</div>
) : (
<div className="space-y-4">
{updates.map((update) => (
<LiveBlogUpdate key={update.id} update={update} />
))}
{updatesLoading && (
<div className="animate-pulse">
<div className="h-16 bg-muted rounded"></div>
</div>
)}
</div>
)}
</div>
{/* New updates indicator */}
{isScrolledUp && newUpdatesCount > 0 && (
<div className="sticky bottom-0 bg-background border-t p-4">
<div className="flex items-center justify-between">
<span className="text-sm text-muted-foreground">
{newUpdatesCount} new {newUpdatesCount === 1 ? 'update' : 'updates'}
</span>
<Button size="sm" onClick={showNewUpdates}>
Show Updates
</Button>
</div>
</div>
)}
</CardContent>
</Card>
);
}
interface LiveBlogUpdateProps {
update: ApiLiveBlogUpdate;
}
function LiveBlogUpdate({ update }: LiveBlogUpdateProps) {
const isPinned = update.isPinned;
return (
<div
className={cn(
'relative p-4 rounded-lg border',
isPinned && 'border-primary bg-primary/5'
)}
>
{isPinned && (
<div className="absolute -top-2 -left-2 bg-primary text-primary-foreground text-xs px-2 py-1 rounded-full">
Pinned
</div>
)}
<div className="flex items-start justify-between mb-2">
<div className="flex items-center gap-2">
{update.author && (
<>
{update.author.avatar && (
<img
src={update.author.avatar}
alt={update.author.name}
className="w-6 h-6 rounded-full"
/>
)}
<span className="text-sm font-medium">{update.author.name}</span>
</>
)}
</div>
<span className="text-xs text-muted-foreground">
{new Date(update.createdAt).toLocaleTimeString()}
</span>
</div>
<div className="text-sm leading-relaxed whitespace-pre-wrap">
{update.content}
</div>
</div>
);
}
@@ -0,0 +1,199 @@
import React from 'react';
import { Link } from '@tanstack/react-router';
import { usePinnedLiveBlogs } from '@/queries/live-blogs';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import {
Clock,
MessageSquare,
Eye,
Pin,
Play,
Square,
ChevronRight
} from 'lucide-react';
interface PinnedLiveBlogSidebarProps {
className?: string;
maxItems?: number;
}
export function PinnedLiveBlogSidebar({
className = '',
maxItems = 3
}: PinnedLiveBlogSidebarProps) {
const { data: pinnedBlogs, isLoading, error } = usePinnedLiveBlogs();
if (isLoading) {
return (
<Card className={className}>
<CardHeader>
<CardTitle className="text-lg flex items-center gap-2">
<Pin className="w-4 h-4" />
Pinned Live Blogs
</CardTitle>
</CardHeader>
<CardContent>
<div className="space-y-4">
{[1, 2, 3].map((i) => (
<div key={i} className="animate-pulse space-y-2">
<div className="h-4 bg-muted rounded w-3/4"></div>
<div className="h-3 bg-muted rounded w-1/2"></div>
<div className="h-2 bg-muted rounded w-1/4"></div>
</div>
))}
</div>
</CardContent>
</Card>
);
}
if (error || !pinnedBlogs || pinnedBlogs.length === 0) {
return null; // Don't show sidebar if no pinned blogs
}
const displayBlogs = pinnedBlogs.slice(0, maxItems);
const getStatusColor = (status: string) => {
switch (status) {
case 'live': return 'bg-green-100 text-green-800 border-green-200';
case 'ended': return 'bg-red-100 text-red-800 border-red-200';
default: return 'bg-gray-100 text-gray-800 border-gray-200';
}
};
const getStatusIcon = (status: string) => {
switch (status) {
case 'live': return <Play className="w-3 h-3" />;
case 'ended': return <Square className="w-3 h-3" />;
default: return null;
}
};
const formatTime = (dateString: string) => {
const date = new Date(dateString);
const now = new Date();
const diffMs = now.getTime() - date.getTime();
const diffMins = Math.floor(diffMs / 60000);
if (diffMins < 60) {
return `${diffMins}m ago`;
} else if (diffMins < 1440) {
return `${Math.floor(diffMins / 60)}h ago`;
} else {
return `${Math.floor(diffMins / 1440)}d ago`;
}
};
const getLatestUpdate = (blog: LiveBlog) => {
if (!blog.updates || blog.updates.length === 0) return null;
return blog.updates[blog.updates.length - 1];
};
return (
<Card className={className}>
<CardHeader className="pb-3">
<div className="flex items-center justify-between">
<CardTitle className="text-lg flex items-center gap-2">
<Pin className="w-4 h-4" />
Live Coverage
</CardTitle>
<Badge variant="outline" className="text-xs">
{pinnedBlogs.length} pinned
</Badge>
</div>
</CardHeader>
<CardContent className="pt-0">
<div className="space-y-4">
{displayBlogs.map((blog) => {
const latestUpdate = getLatestUpdate(blog);
return (
<Link
key={blog.id}
to="/live-blogs/$slug"
params={{ slug: blog.slug }}
className="block group"
>
<div className="p-3 rounded-lg border hover:border-primary/50 hover:bg-accent/50 transition-colors">
{/* Header */}
<div className="flex items-start justify-between mb-2">
<div className="flex-1">
<h3 className="font-medium text-sm leading-tight group-hover:text-primary transition-colors line-clamp-2">
{blog.title}
</h3>
{blog.description && (
<p className="text-xs text-muted-foreground mt-1 line-clamp-2">
{blog.description}
</p>
)}
</div>
<Badge
className={getStatusColor(blog.status)}
variant="outline"
size="sm"
>
<div className="flex items-center gap-1">
{getStatusIcon(blog.status)}
{blog.status}
</div>
</Badge>
</div>
{/* Latest update preview */}
{latestUpdate && (
<div className="mt-2 p-2 bg-muted/50 rounded text-xs">
<div className="flex items-center gap-1 text-muted-foreground mb-1">
<Clock className="w-3 h-3" />
<span>{formatTime(latestUpdate.createdAt)}</span>
</div>
<p className="line-clamp-2">{latestUpdate.content}</p>
</div>
)}
{/* Stats */}
<div className="flex items-center justify-between mt-3 text-xs text-muted-foreground">
<div className="flex items-center gap-3">
<div className="flex items-center gap-1">
<Eye className="w-3 h-3" />
<span>{blog.viewCount}</span>
</div>
<div className="flex items-center gap-1">
<MessageSquare className="w-3 h-3" />
<span>{blog.updates?.length || 0}</span>
</div>
</div>
<div className="flex items-center gap-1 text-primary">
<span className="text-xs">View live</span>
<ChevronRight className="w-3 h-3" />
</div>
</div>
</div>
</Link>
);
})}
</div>
{pinnedBlogs.length > maxItems && (
<div className="mt-4 pt-3 border-t">
<Link
to="/live-blogs"
className="w-full"
>
<Button variant="ghost" size="sm" className="w-full justify-between">
<span>View all pinned blogs</span>
<ChevronRight className="w-4 h-4" />
</Button>
</Link>
</div>
)}
</CardContent>
</Card>
);
}
@@ -0,0 +1,97 @@
import { useQuery } from '@tanstack/react-query'
import { Link } from '@tanstack/react-router'
import * as api from '@/lib/api'
export function ArticleDetailComponent({ id }: { id: string }) {
const { data, isLoading, error } = useQuery({
queryKey: ['article', id],
queryFn: () => api.fetchArticleById(id),
})
if (isLoading) {
return (
<div className="min-h-screen flex items-center justify-center">
<div className="text-lg">Loading article...</div>
</div>
)
}
if (error) {
return (
<div className="min-h-screen flex items-center justify-center">
<div className="text-lg text-red-500">Error loading article</div>
</div>
)
}
if (!data) {
return (
<div className="min-h-screen flex items-center justify-center">
<div className="text-lg">Article not found</div>
</div>
)
}
return (
<article className="max-w-3xl mx-auto">
<Link
to="/articles"
className="inline-flex items-center gap-2 text-muted-foreground hover:text-foreground mb-8"
>
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
<path d="m15 18-6-6 6-6" />
<path d="M19 6H5" />
</svg>
Back to articles
</Link>
<h1 className="text-4xl font-bold mb-6">{data.title}</h1>
<div className="flex items-center gap-4 text-sm text-muted-foreground mb-8">
<span>
{new Date(data.createdAt).toLocaleDateString('mk-MK', {
day: 'numeric',
month: 'long',
year: 'numeric',
})}
</span>
<span>•</span>
<span>{data.views} views</span>
{data.author && (
<>
<span>•</span>
<span>By {data.author.name}</span>
</>
)}
</div>
{data.featuredImage && (
<img
src={data.featuredImage}
alt={data.title}
className="w-full h-64 md:h-96 object-cover rounded-xl mb-8"
/>
)}
<div className="prose prose-slate max-w-none">
<p className="text-lg leading-relaxed mb-6">{data.content}</p>
</div>
{data.tags && Array.isArray(data.tags) && data.tags.length > 0 && (
<div className="mt-8 pt-8 border-t">
<h3 className="text-sm font-semibold mb-4 text-muted-foreground">Tags</h3>
<div className="flex flex-wrap gap-2">
{data.tags.map((tag) => (
<span
key={tag}
className="px-3 py-1 text-sm rounded-full bg-secondary text-secondary-foreground"
>
{tag}
</span>
))}
</div>
</div>
)}
</article>
)
}
@@ -0,0 +1,72 @@
import { useQuery } from '@tanstack/react-query'
import { Link } from '@tanstack/react-router'
import * as api from '@/lib/api'
export function ArticlesComponent() {
const { data, isLoading, error } = useQuery({
queryKey: ['articles'],
queryFn: () => api.fetchArticles({ status: 'published' }),
})
if (isLoading) {
return (
<div className="min-h-screen flex items-center justify-center">
<div className="text-lg">Loading articles...</div>
</div>
)
}
if (error) {
return (
<div className="min-h-screen flex items-center justify-center">
<div className="text-lg text-red-500">Error loading articles</div>
</div>
)
}
return (
<div>
<div className="mb-8">
<h1 className="text-3xl font-bold">Articles</h1>
<p className="text-muted-foreground">Latest news and articles</p>
</div>
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
{data?.data.map((article) => (
<Link
key={article.id}
to={`/articles/${article.id}`}
className="p-6 rounded-xl border bg-card hover:shadow-lg transition-shadow cursor-pointer block"
>
<h2 className="text-xl font-semibold mb-2 line-clamp-2">
{article.title}
</h2>
{article.excerpt && (
<p className="text-muted-foreground text-sm mb-4 line-clamp-3">
{article.excerpt}
</p>
)}
<div className="flex items-center justify-between text-sm text-muted-foreground">
<span>
{new Date(article.createdAt).toLocaleDateString('mk-MK', {
day: 'numeric',
month: 'short',
year: 'numeric',
})}
</span>
<span>{article.views} views</span>
</div>
</Link>
))}
</div>
{data?.data.length === 0 && (
<div className="text-center py-12">
<p className="text-muted-foreground text-lg">
No articles published yet. Check back soon!
</p>
</div>
)}
</div>
)
}
@@ -0,0 +1,39 @@
import { CreateLiveBlog } from '@/components/admin/live-blog/CreateLiveBlog';
import { Button } from '@/components/ui/button';
import { Card, CardContent } from '@/components/ui/card';
import { Link } from '@tanstack/react-router';
import { ArrowLeft } from 'lucide-react';
export function CreateLiveBlogComponent() {
return (
<div className="max-w-2xl mx-auto">
<div className="mb-6">
<Link to="/live-blogs">
<Button variant="ghost" size="sm">
<ArrowLeft className="w-4 h-4 mr-2" />
Back to Live Blogs
</Button>
</Link>
</div>
<CreateLiveBlog
onSuccess={() => {
// Success is handled by navigation in the component
}}
/>
<Card className="mt-6">
<CardContent className="p-6">
<h3 className="font-medium mb-2">Tips for creating a successful live blog:</h3>
<ul className="text-sm text-muted-foreground space-y-1 list-disc pl-5">
<li>Choose a clear, descriptive title that tells readers what to expect</li>
<li>Use a URL-friendly slug (lowercase, hyphens, no spaces)</li>
<li>Start with a draft status to prepare content before going live</li>
<li>Use the description to provide context for readers</li>
<li>Remember: you can always edit these details later</li>
</ul>
</CardContent>
</Card>
</div>
);
}
@@ -0,0 +1,12 @@
import { LiveBlogManager } from '@/components/admin/live-blog/LiveBlogManager'
export function LiveBlogAdminComponent({ slug }: { slug: string }) {
return (
<div className="py-8">
<LiveBlogManager
slug={slug}
onBack={() => window.history.back()}
/>
</div>
)
}
@@ -0,0 +1,5 @@
import { LiveBlogViewer } from '@/components/features/live-blog/LiveBlogViewer'
export function LiveBlogDetailComponent({ slug }: { slug: string }) {
return <LiveBlogViewer slug={slug} className="py-8" />
}
@@ -0,0 +1,104 @@
import { useQuery } from '@tanstack/react-query'
import { Link } from '@tanstack/react-router'
import * as api from '@/lib/api'
import { LiveBlogTicker } from '@/components/features/live-blog/LiveBlogTicker'
export function LiveBlogsComponent() {
const { data, isLoading, error } = useQuery({
queryKey: ['liveBlogs'],
queryFn: () => api.fetchLiveBlogs({ status: 'live' }),
})
if (isLoading) {
return (
<div className="min-h-screen flex items-center justify-center">
<div className="text-lg">Loading live blogs...</div>
</div>
)
}
if (error) {
return (
<div className="min-h-screen flex items-center justify-center">
<div className="text-lg text-red-500">Error loading live blogs</div>
</div>
)
}
return (
<div className="space-y-6">
<LiveBlogTicker />
<div className="mb-8">
<h1 className="text-3xl font-bold">Live Blogs</h1>
<p className="text-muted-foreground">Breaking news and live updates</p>
</div>
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
{data?.data.map((liveBlog) => (
<Link
key={liveBlog.id}
to={`/live-blogs/${liveBlog.slug}`}
className="p-6 rounded-xl border bg-card hover:shadow-lg transition-shadow cursor-pointer block"
>
<div className="flex items-start justify-between mb-4">
<div className="flex-1">
<div className="flex items-center gap-2 mb-2">
<div className="w-2 h-2 rounded-full bg-green-500"></div>
<span className="text-sm text-muted-foreground">
{liveBlog.status === 'live' ? 'LIVE NOW' : liveBlog.status.toUpperCase()}
</span>
</div>
<h2 className="text-xl font-semibold mb-2 line-clamp-2">
{liveBlog.title}
</h2>
{liveBlog.description && (
<p className="text-muted-foreground text-sm mb-4 line-clamp-3">
{liveBlog.description}
</p>
)}
</div>
</div>
<div className="flex items-center justify-between text-sm text-muted-foreground">
<div className="flex items-center gap-4">
<span>{liveBlog.viewCount} views</span>
<span>{liveBlog.updates?.length || 0} updates</span>
</div>
<span>
{new Date(liveBlog.createdAt).toLocaleDateString('mk-MK', {
day: 'numeric',
month: 'short',
year: 'numeric',
})}
</span>
</div>
{liveBlog.author && (
<div className="flex items-center gap-2 mt-4 pt-4 border-t">
{liveBlog.author.avatar && (
<img
src={liveBlog.author.avatar}
alt={liveBlog.author.name}
className="w-6 h-6 rounded-full"
/>
)}
<span className="text-sm text-muted-foreground">
By {liveBlog.author.name}
</span>
</div>
)}
</Link>
))}
</div>
{data?.data.length === 0 && (
<div className="text-center py-12">
<p className="text-muted-foreground text-lg">
No live blogs are currently active. Check back soon!
</p>
</div>
)}
</div>
)
}
@@ -0,0 +1,21 @@
import { cva } from "class-variance-authority"
export const badgeVariants = cva(
"inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",
{
variants: {
variant: {
default:
"border-transparent bg-primary text-primary-foreground hover:bg-primary/80",
secondary:
"border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80",
destructive:
"border-transparent bg-destructive text-destructive-foreground hover:bg-destructive/80",
outline: "text-foreground",
},
},
defaultVariants: {
variant: "default",
},
}
)
+16
View File
@@ -0,0 +1,16 @@
import * as React from "react"
import { type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
import { badgeVariants } from "./badge-variants"
export interface BadgeProps
extends React.HTMLAttributes<HTMLDivElement>,
VariantProps<typeof badgeVariants> {}
function Badge({ className, variant, ...props }: BadgeProps) {
return (
<div className={cn(badgeVariants({ variant }), className)} {...props} />
)
}
export { Badge }
@@ -0,0 +1,30 @@
import { cva } from "class-variance-authority"
export const buttonVariants = cva(
"inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",
{
variants: {
variant: {
default: "bg-primary text-primary-foreground hover:bg-primary/90",
destructive:
"bg-destructive text-destructive-foreground hover:bg-destructive/90",
outline:
"border border-input bg-background hover:bg-accent hover:text-accent-foreground",
secondary:
"bg-secondary text-secondary-foreground hover:bg-secondary/80",
ghost: "hover:bg-accent hover:text-accent-foreground",
link: "text-primary underline-offset-4 hover:underline",
},
size: {
default: "h-10 px-4 py-2",
sm: "h-9 rounded-md px-3",
lg: "h-11 rounded-md px-8",
icon: "h-10 w-10",
},
},
defaultVariants: {
variant: "default",
size: "default",
},
}
)
+3 -31
View File
@@ -1,37 +1,9 @@
import * as React from "react" import * as React from "react"
import { Slot } from "@radix-ui/react-slot" import { Slot } from "@radix-ui/react-slot"
import { cva, type VariantProps } from "class-variance-authority" import { type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils" import { cn } from "@/lib/utils"
import { buttonVariants } from "./button-variants"
const buttonVariants = cva(
"inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",
{
variants: {
variant: {
default: "bg-primary text-primary-foreground hover:bg-primary/90",
destructive:
"bg-destructive text-destructive-foreground hover:bg-destructive/90",
outline:
"border border-input bg-background hover:bg-accent hover:text-accent-foreground",
secondary:
"bg-secondary text-secondary-foreground hover:bg-secondary/80",
ghost: "hover:bg-accent hover:text-accent-foreground",
link: "text-primary underline-offset-4 hover:underline",
},
size: {
default: "h-10 px-4 py-2",
sm: "h-9 rounded-md px-3",
lg: "h-11 rounded-md px-8",
icon: "h-10 w-10",
},
},
defaultVariants: {
variant: "default",
size: "default",
},
}
)
export interface ButtonProps export interface ButtonProps
extends React.ButtonHTMLAttributes<HTMLButtonElement>, extends React.ButtonHTMLAttributes<HTMLButtonElement>,
@@ -53,4 +25,4 @@ const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
) )
Button.displayName = "Button" Button.displayName = "Button"
export { Button, buttonVariants } export { Button }
+24
View File
@@ -0,0 +1,24 @@
import * as React from "react"
import { cn } from "@/lib/utils"
export type InputProps = React.InputHTMLAttributes<HTMLInputElement>
const Input = React.forwardRef<HTMLInputElement, InputProps>(
({ className, type, ...props }, ref) => {
return (
<input
type={type}
className={cn(
"flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",
className
)}
ref={ref}
{...props}
/>
)
}
)
Input.displayName = "Input"
export { Input }
+23
View File
@@ -0,0 +1,23 @@
import * as React from "react"
import * as LabelPrimitive from "@radix-ui/react-label"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
const labelVariants = cva(
"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
)
const Label = React.forwardRef<
React.ElementRef<typeof LabelPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof LabelPrimitive.Root> &
VariantProps<typeof labelVariants>
>(({ className, ...props }, ref) => (
<LabelPrimitive.Root
ref={ref}
className={cn(labelVariants(), className)}
{...props}
/>
))
Label.displayName = LabelPrimitive.Root.displayName
export { Label }
+119
View File
@@ -0,0 +1,119 @@
import * as React from "react"
import * as SelectPrimitive from "@radix-ui/react-select"
import { Check, ChevronDown } from "lucide-react"
import { cn } from "@/lib/utils"
const Select = SelectPrimitive.Root
const SelectGroup = SelectPrimitive.Group
const SelectValue = SelectPrimitive.Value
const SelectTrigger = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Trigger>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Trigger>
>(({ className, children, ...props }, ref) => (
<SelectPrimitive.Trigger
ref={ref}
className={cn(
"flex h-10 w-full items-center justify-between rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",
className
)}
{...props}
>
{children}
<SelectPrimitive.Icon asChild>
<ChevronDown className="h-4 w-4 opacity-50" />
</SelectPrimitive.Icon>
</SelectPrimitive.Trigger>
))
SelectTrigger.displayName = SelectPrimitive.Trigger.displayName
const SelectContent = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Content>
>(({ className, children, position = "popper", ...props }, ref) => (
<SelectPrimitive.Portal>
<SelectPrimitive.Content
ref={ref}
className={cn(
"relative z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
position === "popper" &&
"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",
className
)}
position={position}
{...props}
>
<SelectPrimitive.Viewport
className={cn(
"p-1",
position === "popper" &&
"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"
)}
>
{children}
</SelectPrimitive.Viewport>
</SelectPrimitive.Content>
</SelectPrimitive.Portal>
))
SelectContent.displayName = SelectPrimitive.Content.displayName
const SelectLabel = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Label>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Label>
>(({ className, ...props }, ref) => (
<SelectPrimitive.Label
ref={ref}
className={cn("py-1.5 pl-8 pr-2 text-sm font-semibold", className)}
{...props}
/>
))
SelectLabel.displayName = SelectPrimitive.Label.displayName
const SelectItem = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Item>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Item>
>(({ className, children, ...props }, ref) => (
<SelectPrimitive.Item
ref={ref}
className={cn(
"relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
className
)}
{...props}
>
<span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
<SelectPrimitive.ItemIndicator>
<Check className="h-4 w-4" />
</SelectPrimitive.ItemIndicator>
</span>
<SelectPrimitive.ItemText>{children}</SelectPrimitive.ItemText>
</SelectPrimitive.Item>
))
SelectItem.displayName = SelectPrimitive.Item.displayName
const SelectSeparator = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Separator>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Separator>
>(({ className, ...props }, ref) => (
<SelectPrimitive.Separator
ref={ref}
className={cn("-mx-1 my-1 h-px bg-muted", className)}
{...props}
/>
))
SelectSeparator.displayName = SelectPrimitive.Separator.displayName
export {
Select,
SelectGroup,
SelectValue,
SelectTrigger,
SelectContent,
SelectLabel,
SelectItem,
SelectSeparator,
}
+26
View File
@@ -0,0 +1,26 @@
import * as React from "react"
import * as SwitchPrimitives from "@radix-ui/react-switch"
import { cn } from "@/lib/utils"
const Switch = React.forwardRef<
React.ElementRef<typeof SwitchPrimitives.Root>,
React.ComponentPropsWithoutRef<typeof SwitchPrimitives.Root>
>(({ className, ...props }, ref) => (
<SwitchPrimitives.Root
className={cn(
"peer inline-flex h-6 w-11 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=unchecked]:bg-input",
className
)}
{...props}
ref={ref}
>
<SwitchPrimitives.Thumb
className={cn(
"pointer-events-none block h-5 w-5 rounded-full bg-background shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-5 data-[state=unchecked]:translate-x-0"
)}
/>
</SwitchPrimitives.Root>
))
Switch.displayName = SwitchPrimitives.Root.displayName
export { Switch }
+52
View File
@@ -0,0 +1,52 @@
import * as React from "react"
import * as TabsPrimitive from "@radix-ui/react-tabs"
import { cn } from "@/lib/utils"
const Tabs = TabsPrimitive.Root
const TabsList = React.forwardRef<
React.ElementRef<typeof TabsPrimitive.List>,
React.ComponentPropsWithoutRef<typeof TabsPrimitive.List>
>(({ className, ...props }, ref) => (
<TabsPrimitive.List
ref={ref}
className={cn(
"inline-flex h-10 items-center justify-center rounded-md bg-muted p-1 text-muted-foreground",
className
)}
{...props}
/>
))
TabsList.displayName = TabsPrimitive.List.displayName
const TabsTrigger = React.forwardRef<
React.ElementRef<typeof TabsPrimitive.Trigger>,
React.ComponentPropsWithoutRef<typeof TabsPrimitive.Trigger>
>(({ className, ...props }, ref) => (
<TabsPrimitive.Trigger
ref={ref}
className={cn(
"inline-flex items-center justify-center whitespace-nowrap rounded-sm px-3 py-1.5 text-sm font-medium ring-offset-background transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow-sm",
className
)}
{...props}
/>
))
TabsTrigger.displayName = TabsPrimitive.Trigger.displayName
const TabsContent = React.forwardRef<
React.ElementRef<typeof TabsPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof TabsPrimitive.Content>
>(({ className, ...props }, ref) => (
<TabsPrimitive.Content
ref={ref}
className={cn(
"mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",
className
)}
{...props}
/>
))
TabsContent.displayName = TabsPrimitive.Content.displayName
export { Tabs, TabsList, TabsTrigger, TabsContent }
+22
View File
@@ -0,0 +1,22 @@
import * as React from "react"
import { cn } from "@/lib/utils"
export type TextareaProps = React.TextareaHTMLAttributes<HTMLTextAreaElement>;
const Textarea = React.forwardRef<HTMLTextAreaElement, TextareaProps>(
({ className, ...props }, ref) => {
return (
<textarea
className={cn(
"flex min-h-[80px] w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",
className
)}
ref={ref}
{...props}
/>
)
}
)
Textarea.displayName = "Textarea"
export { Textarea }
+172
View File
@@ -0,0 +1,172 @@
import { useEffect, useRef, useState } from 'react';
export interface LiveBlogStreamEvent {
type: 'connected' | 'update' | 'status-change' | 'pin-update' | 'error';
data: unknown;
clientId?: string;
}
export interface LiveBlogStreamOptions {
autoReconnect?: boolean;
reconnectInterval?: number;
maxReconnectAttempts?: number;
}
export function useLiveBlogStream(
liveBlogId: string,
options: LiveBlogStreamOptions = {}
) {
const [isConnected, setIsConnected] = useState(false);
const [lastEvent, setLastEvent] = useState<LiveBlogStreamEvent | null>(null);
const [connectionError, setConnectionError] = useState<string | null>(null);
const [reconnectAttempts, setReconnectAttempts] = useState(0);
const eventSourceRef = useRef<EventSource | null>(null);
const reconnectTimeoutRef = useRef<NodeJS.Timeout | null>(null);
const lastEventIdRef = useRef<string | null>(null);
const optionsRef = useRef(options);
const reconnectAttemptsRef = useRef(reconnectAttempts);
// Update refs when props change
useEffect(() => {
optionsRef.current = options;
}, [options]);
useEffect(() => {
reconnectAttemptsRef.current = reconnectAttempts;
}, [reconnectAttempts]);
useEffect(() => {
if (!liveBlogId) return;
const disconnect = () => {
if (eventSourceRef.current) {
eventSourceRef.current.close();
eventSourceRef.current = null;
}
if (reconnectTimeoutRef.current) {
clearTimeout(reconnectTimeoutRef.current);
reconnectTimeoutRef.current = null;
}
setIsConnected(false);
setReconnectAttempts(0);
console.log('Disconnected from live blog stream');
};
const createConnection = () => {
// Close existing connection if any
if (eventSourceRef.current) {
eventSourceRef.current.close();
}
const url = new URL(`${import.meta.env.VITE_API_URL}/api/v1/live-blogs/${liveBlogId}/stream`, window.location.origin);
if (lastEventIdRef.current) {
url.searchParams.set('last-event-id', lastEventIdRef.current);
}
try {
eventSourceRef.current = new EventSource(url.toString());
eventSourceRef.current.onopen = () => {
setIsConnected(true);
setConnectionError(null);
setReconnectAttempts(0);
console.log(`Connected to live blog stream for ${liveBlogId}`);
};
eventSourceRef.current.onmessage = (event) => {
try {
const parsedEvent: LiveBlogStreamEvent = JSON.parse(event.data);
setLastEvent(parsedEvent);
// Store last event ID for reconnection
if (event.lastEventId) {
lastEventIdRef.current = event.lastEventId;
}
// Handle different event types
switch (parsedEvent.type) {
case 'connected':
console.log('Stream connected:', parsedEvent.clientId);
break;
case 'update':
console.log('New update received:', parsedEvent.data);
break;
case 'status-change':
console.log('Status change received:', parsedEvent.data);
break;
case 'pin-update':
console.log('Pin update received:', parsedEvent.data);
break;
default:
console.log('Unknown event type:', parsedEvent.type);
}
} catch (error) {
console.error('Error parsing SSE event:', error);
setLastEvent({
type: 'error',
data: 'Failed to parse server event',
});
}
};
eventSourceRef.current.onerror = () => {
console.error('SSE connection error');
setIsConnected(false);
setConnectionError('Connection to live blog lost');
// Attempt reconnection if enabled and within limits
if (optionsRef.current.autoReconnect && reconnectAttemptsRef.current < (optionsRef.current.maxReconnectAttempts || 5)) {
const nextAttempt = reconnectAttemptsRef.current + 1;
setReconnectAttempts(nextAttempt);
reconnectTimeoutRef.current = setTimeout(() => {
console.log(`Attempting reconnection (${nextAttempt}/${optionsRef.current.maxReconnectAttempts || 5})`);
createConnection();
}, optionsRef.current.reconnectInterval || 3000);
} else if (reconnectAttemptsRef.current >= (optionsRef.current.maxReconnectAttempts || 5)) {
setConnectionError('Failed to reconnect after multiple attempts');
}
};
} catch (error) {
console.error('Failed to create EventSource connection:', error);
setConnectionError('Failed to connect to live blog stream');
setIsConnected(false);
}
};
createConnection();
return () => {
disconnect();
};
}, [liveBlogId]);
const manualReconnect = () => {
setReconnectAttempts(0);
setConnectionError(null);
// Trigger reconnection by updating liveBlogId dependency
// This will cause the useEffect to run again
if (eventSourceRef.current) {
eventSourceRef.current.close();
eventSourceRef.current = null;
}
// The useEffect will automatically reconnect
};
return {
isConnected,
lastEvent,
connectionError,
reconnectAttempts,
connect: manualReconnect,
disconnect: () => {
if (eventSourceRef.current) {
eventSourceRef.current.close();
eventSourceRef.current = null;
}
setIsConnected(false);
},
};
}
+263
View File
@@ -92,3 +92,266 @@ export async function fetchArticleById(id: string): Promise<Article> {
} }
return response.json(); return response.json();
} }
// Live Blog Types
export interface LiveBlogUpdate {
id: string;
content: string;
isPinned: boolean;
authorId: string | null;
scheduledAt: string | null;
strapiId: string | null;
author?: {
id: string;
name: string;
slug: string;
bio: string | null;
avatar: string | null;
};
createdAt: string;
updatedAt: string;
}
export interface LiveBlog {
id: string;
title: string;
slug: string;
description: string | null;
status: 'draft' | 'live' | 'ended' | 'archived';
strapiId: string | null;
authorId: string | null;
categoryId: string | null;
viewCount: number;
author?: {
id: string;
name: string;
slug: string;
bio: string | null;
avatar: string | null;
};
category?: {
id: string;
name: string;
slug: string;
description: string | null;
};
updates?: LiveBlogUpdate[];
createdAt: string;
updatedAt: string;
}
export interface LiveBlogsResponse {
data: LiveBlog[];
total: number;
page?: number;
limit?: number;
}
export interface LiveBlogUpdatesResponse {
data: LiveBlogUpdate[];
total: number;
page?: number;
limit?: number;
}
export interface FindLiveBlogsParams {
category?: string;
author?: string;
status?: 'draft' | 'live' | 'ended' | 'archived';
search?: string;
page?: number;
limit?: number;
}
export interface CreateLiveBlogUpdateDto {
content: string;
isPinned?: boolean;
authorId?: string;
scheduledAt?: string;
strapiId?: string;
}
export interface UpdateLiveBlogUpdateDto {
content?: string;
isPinned?: boolean;
authorId?: string;
scheduledAt?: string;
strapiId?: string;
}
export interface CreateLiveBlogDto {
title: string;
slug?: string;
description?: string;
status?: 'draft' | 'live' | 'ended' | 'archived';
authorId?: string;
categoryId?: string;
strapiId?: string;
}
export interface UpdateLiveBlogDto {
title?: string;
slug?: string;
description?: string;
status?: 'draft' | 'live' | 'ended' | 'archived';
authorId?: string;
categoryId?: string;
strapiId?: string;
}
// Live Blog API Functions
export async function fetchLiveBlogs(params: FindLiveBlogsParams = {}): Promise<LiveBlogsResponse> {
const searchParams = new URLSearchParams();
Object.entries(params).forEach(([key, value]) => {
if (value !== undefined && value !== null) {
if (typeof value === 'number') {
searchParams.append(key, value.toString());
} else {
searchParams.append(key, String(value));
}
}
});
const response = await fetch(`${API_BASE_URL}/live-blogs?${searchParams}`);
if (!response.ok) {
throw new Error('Failed to fetch live blogs');
}
return response.json();
}
export async function fetchLiveBlogBySlug(slug: string): Promise<LiveBlog> {
const response = await fetch(`${API_BASE_URL}/live-blogs/slug/${slug}`);
if (!response.ok) {
throw new Error('Failed to fetch live blog');
}
return response.json();
}
export async function fetchLiveBlogById(id: string): Promise<LiveBlog> {
const response = await fetch(`${API_BASE_URL}/live-blogs/${id}`);
if (!response.ok) {
throw new Error('Failed to fetch live blog');
}
return response.json();
}
export async function fetchLiveBlogUpdates(
liveBlogId: string,
page = 1,
limit = 50
): Promise<LiveBlogUpdatesResponse> {
const response = await fetch(
`${API_BASE_URL}/live-blogs/${liveBlogId}/updates?page=${page}&limit=${limit}`
);
if (!response.ok) {
throw new Error('Failed to fetch live blog updates');
}
return response.json();
}
export async function fetchRecentLiveBlogs(): Promise<LiveBlog[]> {
const response = await fetch(`${API_BASE_URL}/live-blogs/recent`);
if (!response.ok) {
throw new Error('Failed to fetch recent live blogs');
}
return response.json();
}
export async function fetchPinnedLiveBlogs(): Promise<LiveBlog[]> {
const response = await fetch(`${API_BASE_URL}/live-blogs/featured`);
if (!response.ok) {
throw new Error('Failed to fetch pinned live blogs');
}
return response.json();
}
export async function fetchActiveLiveBlogs(): Promise<LiveBlog[]> {
const response = await fetch(`${API_BASE_URL}/live-blogs/active`);
if (!response.ok) {
throw new Error('Failed to fetch active live blogs');
}
return response.json();
}
// Admin functions
export async function createLiveBlogUpdate(
liveBlogId: string,
dto: CreateLiveBlogUpdateDto
): Promise<LiveBlogUpdate> {
const response = await fetch(`${API_BASE_URL}/live-blogs/${liveBlogId}/updates`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(dto),
});
if (!response.ok) {
throw new Error('Failed to create live blog update');
}
return response.json();
}
export async function updateLiveBlogUpdate(
liveBlogId: string,
updateId: string,
dto: UpdateLiveBlogUpdateDto
): Promise<LiveBlogUpdate> {
const response = await fetch(`${API_BASE_URL}/live-blogs/${liveBlogId}/updates/${updateId}`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(dto),
});
if (!response.ok) {
throw new Error('Failed to update live blog update');
}
return response.json();
}
export async function deleteLiveBlogUpdate(liveBlogId: string, updateId: string): Promise<void> {
const response = await fetch(`${API_BASE_URL}/live-blogs/${liveBlogId}/updates/${updateId}`, {
method: 'DELETE',
});
if (!response.ok) {
throw new Error('Failed to delete live blog update');
}
}
export async function createLiveBlog(dto: CreateLiveBlogDto): Promise<LiveBlog> {
const response = await fetch(`${API_BASE_URL}/live-blogs`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(dto),
});
if (!response.ok) {
throw new Error('Failed to create live blog');
}
return response.json();
}
export async function updateLiveBlog(id: string, dto: UpdateLiveBlogDto): Promise<LiveBlog> {
const response = await fetch(`${API_BASE_URL}/live-blogs/${id}`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(dto),
});
if (!response.ok) {
throw new Error('Failed to update live blog');
}
return response.json();
}
export async function deleteLiveBlog(id: string): Promise<void> {
const response = await fetch(`${API_BASE_URL}/live-blogs/${id}`, {
method: 'DELETE',
});
if (!response.ok) {
throw new Error('Failed to delete live blog');
}
}
+157
View File
@@ -0,0 +1,157 @@
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import * as api from '../lib/api';
// Live Blog Queries
export function useLiveBlogs(params: api.FindLiveBlogsParams = {}) {
return useQuery({
queryKey: ['liveBlogs', params],
queryFn: () => api.fetchLiveBlogs(params),
});
}
export function useLiveBlog(slug: string) {
return useQuery({
queryKey: ['liveBlog', slug],
queryFn: () => api.fetchLiveBlogBySlug(slug),
enabled: !!slug,
refetchOnWindowFocus: true,
refetchOnMount: true,
});
}
export function useLiveBlogById(id: string) {
return useQuery({
queryKey: ['liveBlog', id],
queryFn: () => api.fetchLiveBlogById(id),
enabled: !!id,
});
}
export function useLiveBlogUpdates(liveBlogId: string, page = 1, limit = 50) {
return useQuery({
queryKey: ['liveBlogUpdates', liveBlogId, page, limit],
queryFn: () => api.fetchLiveBlogUpdates(liveBlogId, page, limit),
enabled: !!liveBlogId,
});
}
export function useRecentLiveBlogs() {
return useQuery({
queryKey: ['recentLiveBlogs'],
queryFn: () => api.fetchRecentLiveBlogs(),
refetchInterval: 30000, // Refetch every 30 seconds
});
}
export function usePinnedLiveBlogs() {
return useQuery({
queryKey: ['pinnedLiveBlogs'],
queryFn: () => api.fetchPinnedLiveBlogs(),
refetchInterval: 30000, // Refetch every 30 seconds
});
}
export function useActiveLiveBlogs() {
return useQuery({
queryKey: ['activeLiveBlogs'],
queryFn: () => api.fetchActiveLiveBlogs(),
refetchInterval: 10000, // Refetch every 10 seconds for ticker
});
}
// Live Blog Mutations (Admin)
export function useCreateLiveBlogUpdate() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: ({ liveBlogId, dto }: { liveBlogId: string; dto: api.CreateLiveBlogUpdateDto }) =>
api.createLiveBlogUpdate(liveBlogId, dto),
onSuccess: (data, variables) => {
// Invalidate live blog queries
queryClient.invalidateQueries({ queryKey: ['liveBlog', variables.liveBlogId] });
queryClient.invalidateQueries({ queryKey: ['liveBlogUpdates', variables.liveBlogId] });
},
});
}
export function useUpdateLiveBlogUpdate() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: ({ liveBlogId, updateId, dto }: {
liveBlogId: string;
updateId: string;
dto: api.UpdateLiveBlogUpdateDto
}) => api.updateLiveBlogUpdate(liveBlogId, updateId, dto),
onSuccess: (data, variables) => {
// Invalidate live blog queries
queryClient.invalidateQueries({ queryKey: ['liveBlog', variables.liveBlogId] });
queryClient.invalidateQueries({ queryKey: ['liveBlogUpdates', variables.liveBlogId] });
},
});
}
export function useDeleteLiveBlogUpdate() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: ({ liveBlogId, updateId }: { liveBlogId: string; updateId: string }) =>
api.deleteLiveBlogUpdate(liveBlogId, updateId),
onSuccess: (data, variables) => {
// Invalidate live blog queries
queryClient.invalidateQueries({ queryKey: ['liveBlog', variables.liveBlogId] });
queryClient.invalidateQueries({ queryKey: ['liveBlogUpdates', variables.liveBlogId] });
},
});
}
// Live Blog CRUD Mutations
export function useCreateLiveBlog() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: (dto: api.CreateLiveBlogDto) => api.createLiveBlog(dto),
onSuccess: () => {
// Invalidate all live blogs queries
queryClient.invalidateQueries({ queryKey: ['liveBlogs'] });
queryClient.invalidateQueries({ queryKey: ['recentLiveBlogs'] });
},
});
}
export function useUpdateLiveBlog() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: ({ id, dto }: { id: string; dto: api.UpdateLiveBlogDto }) =>
api.updateLiveBlog(id, dto),
onSuccess: () => {
// Force immediate refetch of all live blog queries
queryClient.invalidateQueries({
queryKey: ['liveBlog'],
refetchType: 'active'
});
queryClient.invalidateQueries({
queryKey: ['liveBlogs'],
refetchType: 'active'
});
queryClient.invalidateQueries({
queryKey: ['recentLiveBlogs'],
refetchType: 'active'
});
},
});
}
export function useDeleteLiveBlog() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: (id: string) => api.deleteLiveBlog(id),
onSuccess: () => {
// Invalidate all live blogs queries
queryClient.invalidateQueries({ queryKey: ['liveBlogs'] });
queryClient.invalidateQueries({ queryKey: ['recentLiveBlogs'] });
},
});
}
+194 -290
View File
@@ -1,56 +1,15 @@
import { createRootRoute, createRoute, createRouter, Outlet, Link } from '@tanstack/react-router' import { createRootRoute, createRoute, createRouter, Outlet, Link } from '@tanstack/react-router'
import { useQuery } from '@tanstack/react-query' import { ArticleTicker } from './components/ArticleTicker'
import * as api from './lib/api' import { ArticlesComponent } from './components/routes/ArticlesComponent'
import { ArticleDetailComponent } from './components/routes/ArticleDetailComponent'
import { LiveBlogsComponent } from './components/routes/LiveBlogsComponent'
import { LiveBlogDetailComponent } from './components/routes/LiveBlogDetailComponent'
import { LiveBlogAdminComponent } from './components/routes/LiveBlogAdminComponent'
import { CreateLiveBlogComponent } from './components/routes/CreateLiveBlogComponent'
import { LiveBlogTicker } from './components/features/live-blog/LiveBlogTicker'
import { PinnedLiveBlogSidebar } from './components/features/live-blog/PinnedLiveBlogSidebar'
import './styles.css' import './styles.css'
function ArticleTicker() {
const { data } = useQuery({
queryKey: ['ticker-articles'],
queryFn: () => api.fetchArticles({ status: 'published', limit: 10 }),
})
const articles = data?.data.slice(0, 10) || []
if (articles.length === 0) return null
return (
<div className="overflow-hidden bg-muted/50 border-y">
<div className="container mx-auto max-w-6xl px-4">
<div className="py-2 flex items-center gap-4">
<span className="text-sm font-semibold text-primary whitespace-nowrap">
Latest:
</span>
<div className="overflow-hidden flex-1 relative">
<div className="flex animate-marquee whitespace-nowrap">
{articles.map((article, index) => (
<Link
key={`${article.id}-${index}`}
to={`/articles/${article.id}` as any}
className="text-sm text-muted-foreground hover:text-foreground hover:underline inline-block px-4"
>
{article.title || 'No title'}
</Link>
))}
{/* Duplicate for seamless scrolling */}
{articles.map((article, index) => (
<Link
key={`dup-${article.id}-${index}`}
to={`/articles/${article.id}` as any}
className="text-sm text-muted-foreground hover:text-foreground hover:underline inline-block px-4"
>
{article.title || 'No title'}
</Link>
))}
</div>
</div>
</div>
</div>
</div>
)
}
const rootRoute = createRootRoute({ const rootRoute = createRootRoute({
head: () => ({ head: () => ({
meta: [ meta: [
@@ -67,14 +26,20 @@ const rootRoute = createRootRoute({
<h1 className="text-3xl font-bold"> <h1 className="text-3xl font-bold">
<Link to="/" className="hover:underline">Placebo.mk</Link> <Link to="/" className="hover:underline">Placebo.mk</Link>
</h1> </h1>
<nav className="flex gap-4"> <nav className="flex gap-4">
<Link to="/" className="text-sm font-medium hover:underline"> <Link to="/" className="text-sm font-medium hover:underline">
Home Home
</Link> </Link>
<Link to="/articles" className="text-sm font-medium hover:underline"> <Link to="/articles" className="text-sm font-medium hover:underline">
Articles Articles
</Link> </Link>
</nav> <Link to="/live-blogs" className="text-sm font-medium hover:underline">
Live
</Link>
<Link to="/admin/live-blogs/create" className="text-sm font-medium hover:underline text-primary">
+ New Live Blog
</Link>
</nav>
</div> </div>
</header> </header>
@@ -95,84 +60,142 @@ const indexRoute = createRoute({
getParentRoute: () => rootRoute, getParentRoute: () => rootRoute,
path: '/', path: '/',
component: () => ( component: () => (
<div> <div className="space-y-6">
{/* Article Ticker at the top */}
<ArticleTicker /> <ArticleTicker />
<div className="py-12 md:py-20">
<div className="max-w-4xl mx-auto text-center mb-12"> {/* Live Blog Ticker below article ticker */}
<div className="inline-flex items-center justify-center w-16 h-16 rounded-full bg-primary/10 mb-6"> <LiveBlogTicker className="mt-4" />
<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className="text-primary">
<path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z" /> <div className="py-8 md:py-12">
<polyline points="14 2 14 8 20 8" /> <div className="max-w-7xl mx-auto">
<line x1="16" x2="8" y1="13" y2="13" /> <div className="grid grid-cols-1 lg:grid-cols-4 gap-8">
<line x1="16" x2="8" y1="17" y2="17" /> {/* Main content - 3 columns */}
<line x1="10" x2="8" y1="9" y2="9" /> <div className="lg:col-span-3 space-y-8">
</svg> {/* Hero section */}
</div> <div className="rounded-xl border bg-card p-8 text-center">
<h1 className="text-4xl md:text-5xl font-bold tracking-tight mb-4"> <div className="inline-flex items-center justify-center w-16 h-16 rounded-full bg-primary/10 mb-6">
Placebo<span className="text-primary">.mk</span> <svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className="text-primary">
</h1> <path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z" />
<p className="text-xl text-muted-foreground max-w-2xl mx-auto"> <polyline points="14 2 14 8 20 8" />
Unapologetically sarcastic news and commentary on local and global affairs in Macedonia. Because sometimes the truth hurts more than fiction. <line x1="16" x2="8" y1="13" y2="13" />
</p> <line x1="16" x2="8" y1="17" y2="17" />
</div> <line x1="10" x2="8" y1="9" y2="9" />
</svg>
</div>
<h1 className="text-4xl md:text-5xl font-bold tracking-tight mb-4">
Placebo<span className="text-primary">.mk</span>
</h1>
<p className="text-xl text-muted-foreground max-w-2xl mx-auto">
Unapologetically sarcastic news and commentary on local and global affairs in Macedonia. Because sometimes the truth hurts more than fiction.
</p>
</div>
<div className="grid md:grid-cols-3 gap-6 max-w-5xl mx-auto"> {/* Features grid */}
<div className="p-6 rounded-xl border bg-card hover:shadow-lg transition-all duration-300 group"> <div className="grid md:grid-cols-3 gap-6">
<div className="w-10 h-10 rounded-lg bg-primary/10 flex items-center justify-center mb-4 group-hover:bg-primary/20 transition-colors"> <div className="p-6 rounded-xl border bg-card hover:shadow-lg transition-all duration-300 group">
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className="text-primary"> <div className="w-10 h-10 rounded-lg bg-primary/10 flex items-center justify-center mb-4 group-hover:bg-primary/20 transition-colors">
<path d="M4 22h16a2 2 0 0 0 2-2V4a2 2 0 0 0-2-2H8a2 2 0 0 0-2 2v16a2 2 0 0 1-2 2Zm0 0a2 2 0 0 1-2-2v-9c0-1.1.9-2 2-2h2" /> <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className="text-primary">
<path d="M18 14h-8" /> <path d="M4 22h16a2 2 0 0 0 2-2V4a2 2 0 0 0-2-2H8a2 2 0 0 0-2 2v16a2 2 0 0 1-2 2Zm0 0a2 2 0 0 1-2-2v-9c0-1.1.9-2 2-2h2" />
<path d="M15 18h-5" /> <path d="M18 14h-8" />
<path d="M10 6h8v4h-8V6Z" /> <path d="M15 18h-5" />
</svg> <path d="M10 6h8v4h-8V6Z" />
</svg>
</div>
<h3 className="text-lg font-semibold mb-2">Latest Articles</h3>
<p className="text-muted-foreground text-sm">
Freshly brewed sarcasm on current events, politics, and everything in between.
</p>
</div>
<div className="p-6 rounded-xl border bg-card hover:shadow-lg transition-all duration-300 group">
<div className="w-10 h-10 rounded-lg bg-primary/10 flex items-center justify-center mb-4 group-hover:bg-primary/20 transition-colors">
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className="text-primary">
<circle cx="12" cy="12" r="10" />
<path d="M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3" />
<path d="M12 17h.01" />
</svg>
</div>
<h3 className="text-lg font-semibold mb-2">No Filter</h3>
<p className="text-muted-foreground text-sm">
We don't do nuance. We don't do diplomatic language. Just honest (and slightly mean) commentary.
</p>
</div>
<div className="p-6 rounded-xl border bg-card hover:shadow-lg transition-all duration-300 group">
<div className="w-10 h-10 rounded-lg bg-primary/10 flex items-center justify-center mb-4 group-hover:bg-primary/20 transition-colors">
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className="text-primary">
<path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2" />
<circle cx="9" cy="7" r="4" />
<path d="M23 21v-2a4 4 0 0 0-3-3.87" />
<path d="M16 3.13a4 4 0 0 1 0 7.75" />
</svg>
</div>
<h3 className="text-lg font-semibold mb-2">Live Coverage</h3>
<p className="text-muted-foreground text-sm">
Real-time updates on breaking news with our live blogging system. No delays, just facts.
</p>
</div>
</div>
{/* Call to action */}
<div className="rounded-xl border bg-card p-8 text-center">
<h2 className="text-2xl font-bold mb-4">Ready for some unfiltered truth?</h2>
<p className="text-muted-foreground mb-6 max-w-2xl mx-auto">
Dive into our articles or follow live coverage of breaking news as it happens.
</p>
<div className="flex flex-col sm:flex-row gap-4 justify-center">
<Link
to="/articles"
className="inline-flex items-center justify-center rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 bg-primary text-primary-foreground hover:bg-primary/90 h-10 px-6 py-2"
>
Read Articles
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className="ml-2">
<path d="M5 12h14" />
<path d="m12 5 7 7-7 7" />
</svg>
</Link>
<Link
to="/live-blogs"
className="inline-flex items-center justify-center rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 border border-input bg-background hover:bg-accent hover:text-accent-foreground h-10 px-6 py-2"
>
View Live Blogs
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className="ml-2">
<circle cx="12" cy="12" r="10" />
<polyline points="12 6 12 12 16 14" />
</svg>
</Link>
</div>
</div>
</div> </div>
<h3 className="text-lg font-semibold mb-2">Latest Articles</h3>
<p className="text-muted-foreground text-sm">
Freshly brewed sarcasm on current events, politics, and everything in between.
</p>
</div>
<div className="p-6 rounded-xl border bg-card hover:shadow-lg transition-all duration-300 group"> {/* Sidebar - 1 column */}
<div className="w-10 h-10 rounded-lg bg-primary/10 flex items-center justify-center mb-4 group-hover:bg-primary/20 transition-colors"> <div className="lg:col-span-1">
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className="text-primary"> <PinnedLiveBlogSidebar />
<circle cx="12" cy="12" r="10" />
<path d="M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3" /> {/* Additional sidebar content */}
<path d="M12 17h.01" /> <div className="mt-6 rounded-xl border bg-card p-6">
</svg> <h3 className="font-semibold mb-4">About Placebo.mk</h3>
<p className="text-sm text-muted-foreground mb-4">
We're not here to make friends. We're here to tell the truth with a healthy dose of sarcasm.
</p>
<div className="text-xs text-muted-foreground">
<div className="flex items-center gap-2 mb-2">
<div className="w-2 h-2 bg-green-500 rounded-full"></div>
<span>Live coverage updated in real-time</span>
</div>
<div className="flex items-center gap-2 mb-2">
<div className="w-2 h-2 bg-blue-500 rounded-full"></div>
<span>No ads, no sponsors, no BS</span>
</div>
<div className="flex items-center gap-2">
<div className="w-2 h-2 bg-purple-500 rounded-full"></div>
<span>100% independent journalism</span>
</div>
</div>
</div>
</div> </div>
<h3 className="text-lg font-semibold mb-2">No Filter</h3>
<p className="text-muted-foreground text-sm">
We don't do nuance. We don't do diplomatic language. Just honest (and slightly mean) commentary.
</p>
</div> </div>
<div className="p-6 rounded-xl border bg-card hover:shadow-lg transition-all duration-300 group">
<div className="w-10 h-10 rounded-lg bg-primary/10 flex items-center justify-center mb-4 group-hover:bg-primary/20 transition-colors">
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className="text-primary">
<path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2" />
<circle cx="9" cy="7" r="4" />
<path d="M23 21v-2a4 4 0 0 0-3-3.87" />
<path d="M16 3.13a4 4 0 0 1 0 7.75" />
</svg>
</div>
<h3 className="text-lg font-semibold mb-2">Community</h3>
<p className="text-muted-foreground text-sm">
Join thousands of readers who appreciate the finer art of Macedonian sarcasm.
</p>
</div>
</div>
<div className="mt-16 text-center">
<Link
to="/articles"
className="inline-flex items-center gap-2 px-6 py-3 rounded-lg bg-primary text-primary-foreground font-medium hover:bg-primary/90 transition-colors"
>
Browse Articles
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
<path d="M5 12h14" />
<path d="m12 5 7 7-7 7" />
</svg>
</Link>
</div> </div>
</div> </div>
</div> </div>
@@ -182,74 +205,7 @@ const indexRoute = createRoute({
const articlesRoute = createRoute({ const articlesRoute = createRoute({
getParentRoute: () => rootRoute, getParentRoute: () => rootRoute,
path: '/articles', path: '/articles',
component: () => { component: ArticlesComponent,
const { data, isLoading, error } = useQuery({
queryKey: ['articles'],
queryFn: () => api.fetchArticles({ status: 'published' }),
})
if (isLoading) {
return (
<div className="min-h-screen flex items-center justify-center">
<div className="text-lg">Loading articles...</div>
</div>
)
}
if (error) {
return (
<div className="min-h-screen flex items-center justify-center">
<div className="text-lg text-red-500">Error loading articles</div>
</div>
)
}
return (
<div>
<div className="mb-8">
<h1 className="text-3xl font-bold">Articles</h1>
<p className="text-muted-foreground">Latest news and articles</p>
</div>
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
{data?.data.map((article) => (
<Link
key={article.id}
to={`/articles/${article.id}` as any}
className="p-6 rounded-xl border bg-card hover:shadow-lg transition-shadow cursor-pointer block"
>
<h2 className="text-xl font-semibold mb-2 line-clamp-2">
{article.title}
</h2>
{article.excerpt && (
<p className="text-muted-foreground text-sm mb-4 line-clamp-3">
{article.excerpt}
</p>
)}
<div className="flex items-center justify-between text-sm text-muted-foreground">
<span>
{new Date(article.createdAt).toLocaleDateString('mk-MK', {
day: 'numeric',
month: 'short',
year: 'numeric',
})}
</span>
<span>{article.views} views</span>
</div>
</Link>
))}
</div>
{data?.data.length === 0 && (
<div className="text-center py-12">
<p className="text-muted-foreground text-lg">
No articles published yet. Check back soon!
</p>
</div>
)}
</div>
)
},
}) })
const articleDetailRoute = createRoute({ const articleDetailRoute = createRoute({
@@ -257,101 +213,49 @@ const articleDetailRoute = createRoute({
path: '/articles/$id', path: '/articles/$id',
component: () => { component: () => {
const { id } = articleDetailRoute.useParams() const { id } = articleDetailRoute.useParams()
const { data, isLoading, error } = useQuery({ return <ArticleDetailComponent id={id} />
queryKey: ['article', id],
queryFn: () => api.fetchArticleById(id),
})
if (isLoading) {
return (
<div className="min-h-screen flex items-center justify-center">
<div className="text-lg">Loading article...</div>
</div>
)
}
if (error) {
return (
<div className="min-h-screen flex items-center justify-center">
<div className="text-lg text-red-500">Error loading article</div>
</div>
)
}
if (!data) {
return (
<div className="min-h-screen flex items-center justify-center">
<div className="text-lg">Article not found</div>
</div>
)
}
return (
<article className="max-w-3xl mx-auto">
<Link
to="/articles"
className="inline-flex items-center gap-2 text-muted-foreground hover:text-foreground mb-8"
>
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
<path d="m15 18-6-6 6-6" />
<path d="M19 6H5" />
</svg>
Back to articles
</Link>
<h1 className="text-4xl font-bold mb-6">{data.title}</h1>
<div className="flex items-center gap-4 text-sm text-muted-foreground mb-8">
<span>
{new Date(data.createdAt).toLocaleDateString('mk-MK', {
day: 'numeric',
month: 'long',
year: 'numeric',
})}
</span>
<span>•</span>
<span>{data.views} views</span>
{data.author && (
<>
<span>•</span>
<span>By {data.author.name}</span>
</>
)}
</div>
{data.featuredImage && (
<img
src={data.featuredImage}
alt={data.title}
className="w-full h-64 md:h-96 object-cover rounded-xl mb-8"
/>
)}
<div className="prose prose-slate max-w-none">
<p className="text-lg leading-relaxed mb-6">{data.content}</p>
</div>
{data.tags && Array.isArray(data.tags) && data.tags.length > 0 && (
<div className="mt-8 pt-8 border-t">
<h3 className="text-sm font-semibold mb-4 text-muted-foreground">Tags</h3>
<div className="flex flex-wrap gap-2">
{data.tags.map((tag) => (
<span
key={tag}
className="px-3 py-1 text-sm rounded-full bg-secondary text-secondary-foreground"
>
{tag}
</span>
))}
</div>
</div>
)}
</article>
)
}, },
}) })
const routeTree = rootRoute.addChildren([indexRoute, articlesRoute, articleDetailRoute]) const liveBlogsRoute = createRoute({
getParentRoute: () => rootRoute,
path: '/live-blogs',
component: LiveBlogsComponent,
})
const liveBlogDetailRoute = createRoute({
getParentRoute: () => rootRoute,
path: '/live-blogs/$slug',
component: () => {
const { slug } = liveBlogDetailRoute.useParams()
return <LiveBlogDetailComponent slug={slug} />
},
})
const liveBlogAdminRoute = createRoute({
getParentRoute: () => rootRoute,
path: '/admin/live-blogs/$slug',
component: () => {
const { slug } = liveBlogAdminRoute.useParams()
return <LiveBlogAdminComponent slug={slug} />
},
})
const createLiveBlogRoute = createRoute({
getParentRoute: () => rootRoute,
path: '/admin/live-blogs/create',
component: CreateLiveBlogComponent,
})
const routeTree = rootRoute.addChildren([
indexRoute,
articlesRoute,
articleDetailRoute,
liveBlogsRoute,
liveBlogDetailRoute,
liveBlogAdminRoute,
createLiveBlogRoute,
])
export const router = createRouter({ routeTree }) export const router = createRouter({ routeTree })