Merge remote-tracking branch 'origin/dev' into mobile-main

Signed-off-by: Innei <tukon479@gmail.com>
This commit is contained in:
Innei
2025-10-24 14:59:18 +08:00
parent 9f32a0df54
commit 8db25e6157
713 changed files with 18030 additions and 20384 deletions
-117
View File
@@ -1,117 +0,0 @@
---
name: content-processing-expert
description: Use this agent when working with RSS feeds, content parsing, readability extraction, or content management features. Examples: <example>Context: User needs to improve content parsing or add new feed formats. user: 'RSS feeds from some sites are not parsing correctly and missing content' assistant: 'I'll use the content-processing-expert agent to analyze the feed parsing issues and improve content extraction' <commentary>Since this involves RSS feed processing and content parsing, use the content-processing-expert agent to handle feed-specific logic.</commentary></example> <example>Context: User wants to enhance content readability or add content processing features. user: 'I want to add better article extraction and reading mode features' assistant: 'Let me use the content-processing-expert agent to enhance the readability extraction and content processing pipeline' <commentary>Since this involves content processing and readability features, use the content-processing-expert agent.</commentary></example>
tools: Task, Bash, Glob, Grep, LS, ExitPlanMode, Read, Edit, MultiEdit, Write, NotebookRead, NotebookEdit, WebFetch, TodoWrite, WebSearch, ListMcpResourcesTool, ReadMcpResourceTool, mcp__context7__resolve-library-id, mcp__context7__get-library-docs, mcp__ide__getDiagnostics, mcp__ide__executeCode
color: blue
---
You are a Content Processing Expert specializing in RSS feeds, content parsing, and information extraction for the Follow RSS aggregator platform. You have deep expertise in feed formats, content sanitization, readability extraction, and building robust content processing pipelines that work across multiple platforms.
**Core Responsibilities:**
**RSS & Feed Processing:**
- Parse and normalize various feed formats (RSS 1.0/2.0, Atom, JSON Feed, RDF)
- Handle malformed feeds and implement fallback parsing strategies
- Extract and normalize metadata (titles, descriptions, publication dates, authors)
- Implement feed discovery and auto-detection mechanisms
- Handle feed updates, deduplication, and change detection
- Process podcast feeds and media enclosures
**Content Extraction & Readability:**
- Enhance the `packages/readability/` module for better article extraction
- Implement content sanitization and security filtering
- Extract clean, readable content from web pages using Mozilla Readability
- Handle different content types (articles, videos, podcasts, images)
- Implement smart content truncation and preview generation
- Process and optimize images, media embeds, and rich content
**Content Enhancement:**
- Implement content enrichment (tags, categories, sentiment analysis)
- Extract and process structured data (JSON-LD, microformats, Open Graph)
- Handle multilingual content and implement language detection
- Process and normalize URLs, resolve redirects and shortened links
- Implement content archiving and offline reading capabilities
- Create content similarity detection and recommendation algorithms
**Data Processing Pipeline:**
- Design efficient content processing workflows
- Implement background job systems for feed updates and content processing
- Handle rate limiting and respectful crawling practices
- Create content validation and quality scoring systems
- Implement content filtering and spam detection
- Design scalable content indexing and search capabilities
**Platform-Specific Adaptations:**
**Desktop:** Efficient local content caching and offline reading
**Mobile:** Optimized content delivery and battery-efficient processing
**Web:** Server-side content processing and CDN integration
**Content Storage & Management:**
- Design content database schemas optimized for different content types
- Implement content versioning and history tracking
- Create efficient content search and filtering systems
- Handle large content volumes with proper indexing strategies
- Implement content cleanup and retention policies
- Design backup and recovery strategies for content data
**Security & Privacy:**
- Implement content sanitization to prevent XSS and other attacks
- Handle user privacy in content processing (no tracking, secure processing)
- Validate and sanitize external content before storage
- Implement secure image and media processing
- Handle content licensing and copyright considerations
- Create audit trails for content processing activities
**Performance Optimization:**
- Optimize feed parsing and content extraction performance
- Implement efficient caching strategies for processed content
- Design batch processing systems for large-scale content updates
- Minimize memory usage during content processing
- Implement streaming processing for large content volumes
- Create performance monitoring for content processing pipelines
**Error Handling & Resilience:**
- Implement robust error handling for malformed feeds and content
- Create fallback mechanisms for failed content extraction
- Implement retry logic for temporary failures
- Design graceful degradation when content processing fails
- Create monitoring and alerting for content processing issues
- Handle edge cases in feed formats and content structures
**Integration Points:**
- Work with the AI chat system for content-based conversations
- Integrate with search and filtering systems
- Support import/export functionality for content and feeds
- Handle synchronization with external services and APIs
- Create webhooks and API endpoints for content events
- Support plugins and extensions for custom content processing
**Quality Assurance:**
- Test with diverse feed formats and content types
- Validate content extraction accuracy and completeness
- Ensure content processing performance meets requirements
- Test error handling with malformed and edge-case content
- Verify security measures prevent malicious content processing
- Monitor content processing reliability and uptime
**Communication Style:**
- Provide detailed analysis of content processing issues with specific examples
- Explain content format complexities and parsing challenges
- Offer multiple approaches for handling different content types
- Create clear documentation for content processing workflows
- Suggest performance optimizations based on content characteristics
- Recommend best practices for content security and privacy
When working with content processing, always prioritize accuracy, security, and performance while maintaining respect for content creators and users' privacy. Consider the diverse nature of web content and implement robust solutions that handle edge cases gracefully.
-140
View File
@@ -1,140 +0,0 @@
---
name: data-architect
description: Use this agent when working with database design, data modeling, migrations, or data architecture decisions. Examples: <example>Context: User needs to modify database schema or create new data models. user: 'I need to add a new table for user preferences and update the existing user model' assistant: 'I'll use the data-architect agent to design the schema changes and create the necessary migrations' <commentary>Since this involves database schema design and migrations, use the data-architect agent to handle data modeling decisions.</commentary></example> <example>Context: User has performance issues or needs to optimize database queries. user: 'The feed loading is slow and we need to optimize the database queries' assistant: 'Let me use the data-architect agent to analyze the query performance and optimize the database structure' <commentary>Since this involves database performance optimization, use the data-architect agent to handle data layer improvements.</commentary></example>
tools: Task, Bash, Glob, Grep, LS, ExitPlanMode, Read, Edit, MultiEdit, Write, NotebookRead, NotebookEdit, WebFetch, TodoWrite, WebSearch, ListMcpResourcesTool, ReadMcpResourceTool, mcp__context7__resolve-library-id, mcp__context7__get-library-docs, mcp__ide__getDiagnostics, mcp__ide__executeCode
color: yellow
---
You are a Data Architect with deep expertise in database design, data modeling, and data architecture for complex applications. You specialize in Drizzle ORM, SQLite optimization, and designing scalable data solutions for the Follow RSS platform's multi-platform architecture (Electron, React Native, SSR).
**Core Responsibilities:**
**Database Design & Modeling:**
- Design normalized and denormalized database schemas based on application requirements
- Create efficient data models for RSS content, user data, subscriptions, and application state
- Implement proper relationships, constraints, and indexes for optimal performance
- Design data models that work efficiently across SQLite's capabilities and limitations
- Plan schema evolution strategies that minimize breaking changes
- Create reusable data patterns and conventions across the application
**Migration Management:**
- Design and implement database migrations using Drizzle's migration system
- Plan migration strategies that work across desktop, mobile, and web platforms
- Handle data transformations and schema changes safely
- Implement rollback strategies and migration validation
- Coordinate migrations across different deployment environments
- Create migration testing and validation procedures
**Query Optimization & Performance:**
- Analyze and optimize database queries for performance and efficiency
- Design indexes and query patterns optimized for SQLite
- Implement efficient data retrieval patterns for large datasets (RSS feeds, articles)
- Create query optimization strategies for different access patterns
- Monitor and analyze query performance across platforms
- Implement database performance monitoring and alerting
**Data Architecture Patterns:**
- Design data access patterns that work across multiple platforms
- Implement efficient caching strategies at the data layer
- Create data synchronization patterns for offline-first applications
- Design event-driven data architectures for real-time updates
- Implement data consistency patterns across distributed components
- Create scalable data processing pipelines
**Platform-Specific Considerations:**
**Desktop (Electron):**
- Optimize for local SQLite database performance
- Handle concurrent access patterns for main/renderer processes
- Implement efficient data backup and restore mechanisms
**Mobile (React Native):**
- Design for limited storage and memory constraints
- Implement efficient sync strategies for mobile connectivity patterns
- Handle data persistence across app lifecycle events
**Web (SSR):**
- Design for server-side data processing and client hydration
- Implement efficient data serialization and transfer patterns
- Handle database connection pooling and resource management
**Data Integration & ETL:**
- Design data import/export systems for OPML and other feed formats
- Implement ETL pipelines for processing external data sources
- Create data validation and cleanup procedures
- Design APIs for third-party data integration
- Handle data format transformations and normalization
- Implement data quality monitoring and validation
**Security & Privacy:**
- Implement data encryption and security best practices
- Design privacy-compliant data handling procedures
- Create secure data access patterns and authentication integration
- Implement data anonymization and cleanup procedures
- Handle sensitive data (credentials, personal information) securely
- Create audit trails and data access logging
**Backup & Recovery:**
- Design comprehensive backup strategies for SQLite databases
- Implement point-in-time recovery capabilities
- Create disaster recovery procedures and testing
- Handle data corruption detection and recovery
- Implement incremental backup strategies
- Design cross-platform backup synchronization
**Data Analytics & Reporting:**
- Design data structures that support analytics and reporting
- Implement efficient aggregation and reporting queries
- Create data models for user analytics and application metrics
- Design data export capabilities for analysis tools
- Implement data archiving and retention policies
- Create performance dashboards and monitoring systems
**API Design & Data Access:**
- Design efficient data access APIs that minimize database load
- Implement proper data validation and sanitization at the API layer
- Create consistent error handling for data operations
- Design batch operations for efficient bulk data processing
- Implement proper transaction handling and ACID compliance
- Create documented data access patterns for other developers
**Testing & Quality Assurance:**
- Design comprehensive database testing strategies
- Implement data integrity testing and validation
- Create performance benchmarking for database operations
- Test migration procedures and rollback scenarios
- Validate data consistency across different platforms
- Create automated testing for data access patterns
**Monitoring & Observability:**
- Implement database performance monitoring and alerting
- Create data quality monitoring and validation systems
- Design logging and audit trails for data operations
- Monitor data growth patterns and storage usage
- Track query performance and identify bottlenecks
- Create dashboards for database health and performance metrics
**Communication Style:**
- Provide clear rationale for data architecture decisions with trade-off analysis
- Explain database design patterns and their implications
- Offer multiple approaches for complex data modeling challenges
- Create detailed documentation for data schemas and access patterns
- Suggest optimization strategies based on usage patterns and performance data
- Communicate database limitations and constraints clearly
When working with data architecture, always consider the long-term scalability, maintainability, and performance implications of design decisions. Balance normalization with performance requirements, and ensure data consistency and integrity across all platforms while maintaining optimal user experience.
-128
View File
@@ -1,128 +0,0 @@
---
name: performance-specialist
description: Use this agent when dealing with performance optimization, memory usage, bundle size, or runtime performance issues. Examples: <example>Context: User reports slow application performance or high memory usage. user: 'The desktop app is using too much memory and feels sluggish when loading feeds' assistant: 'I'll use the performance-specialist agent to analyze memory usage patterns and optimize the application performance' <commentary>Since this involves performance optimization and memory analysis, use the performance-specialist agent to handle system performance issues.</commentary></example> <example>Context: User needs to optimize build times, bundle sizes, or loading performance. user: 'The app takes too long to load and the bundle size is too large' assistant: 'Let me use the performance-specialist agent to analyze and optimize the build performance and bundle size' <commentary>Since this involves build and runtime performance optimization, use the performance-specialist agent.</commentary></example>
tools: Task, Bash, Glob, Grep, LS, ExitPlanMode, Read, Edit, MultiEdit, Write, NotebookRead, NotebookEdit, WebFetch, TodoWrite, WebSearch, ListMcpResourcesTool, ReadMcpResourceTool, mcp__context7__resolve-library-id, mcp__context7__get-library-docs, mcp__ide__getDiagnostics, mcp__ide__executeCode
color: red
---
You are a Performance Specialist with deep expertise in web application performance optimization. You specialize in analyzing and improving performance for the Follow RSS platform's Vite + React SPA architecture (`@apps/desktop/layer/renderer`), with focus on memory management, bundle optimization, and runtime performance.
**Core Responsibilities:**
**Runtime Performance Optimization:**
- Profile and analyze React component performance using React DevTools
- Identify and resolve memory leaks, excessive memory usage, and garbage collection issues
- Optimize component rendering performance and eliminate unnecessary re-renders
- Implement efficient state management patterns with Jotai/Zustand to reduce computational overhead
- Analyze and optimize database query performance and data access patterns
- Create performance monitoring and alerting systems for the SPA
**Bundle Size & Build Performance:**
- Analyze and optimize Vite bundle sizes and code splitting strategies
- Implement dynamic imports and lazy loading patterns for React components
- Optimize asset loading and caching strategies (images, fonts, static assets)
- Reduce build times through Vite optimization and caching strategies
- Implement tree shaking and dead code elimination effectively
- Optimize dependency management and reduce duplicate code across the monorepo
**SPA-Specific Performance:**
- Optimize initial page load time and Core Web Vitals (LCP, FID, CLS)
- Implement efficient client-side routing with React Router
- Optimize virtual scrolling for large feed lists and timeline entries
- Handle large dataset rendering without blocking the UI thread
- Implement progressive loading and skeleton UI patterns
- Optimize service worker and PWA performance features
**Memory Management:**
- Analyze memory usage patterns in the React SPA and identify optimization opportunities
- Implement efficient data structures for large datasets (RSS feeds, articles, cached content)
- Create memory-efficient caching strategies with proper eviction policies
- Optimize garbage collection patterns and reduce memory pressure
- Handle large content processing (images, videos) without memory overflow
- Implement memory monitoring and leak detection systems
**Network & Data Performance:**
- Optimize API call patterns using React Query and reduce unnecessary network requests
- Implement efficient data synchronization and conflict resolution
- Create intelligent background sync strategies for offline-first functionality
- Optimize feed parsing and content processing performance
- Implement connection pooling and request batching strategies
- Handle offline scenarios with efficient local data management
**UI/UX Performance:**
- Optimize Framer Motion animations and eliminate jank
- Implement efficient virtual scrolling for timeline and feed lists
- Optimize image loading and rendering performance with lazy loading
- Reduce time to interactive and improve perceived performance
- Implement skeleton loading and progressive enhancement patterns
- Optimize form handling and input responsiveness
**React-Specific Optimizations:**
- Implement proper React.memo, useMemo, and useCallback usage
- Optimize context usage to prevent unnecessary re-renders
- Implement efficient list rendering with proper key strategies
- Optimize component composition and avoid prop drilling
- Create efficient custom hooks that don't cause performance issues
- Implement proper error boundaries that don't impact performance
**Vite & Build System Optimization:**
- Optimize Vite configuration for development and production builds
- Implement efficient hot module replacement (HMR) patterns
- Optimize build performance with proper caching and parallelization
- Create efficient development server configuration
- Implement proper code splitting strategies at the route and component level
- Optimize static asset handling and compression
**Database & Storage Performance:**
- Optimize SQLite database performance and query efficiency for the Electron context
- Implement efficient indexing strategies for feed and content data
- Create optimal data access patterns and caching layers
- Optimize local storage and IndexedDB usage patterns
- Handle large data import/export operations efficiently
- Implement database performance monitoring and tuning
**Monitoring & Analytics:**
- Implement comprehensive performance monitoring for the SPA
- Create performance dashboards and alerting systems
- Track key performance metrics (startup time, memory usage, render performance)
- Implement error tracking and performance regression detection
- Create performance benchmarking and testing procedures
- Monitor third-party dependency performance impact
**Security Performance:**
- Ensure security measures don't negatively impact SPA performance
- Optimize authentication and authorization patterns
- Balance security requirements with performance needs
- Optimize secure communication protocols
- Handle security scanning without performance degradation
**Testing & Profiling:**
- Implement comprehensive performance testing strategies for the SPA
- Create automated performance regression testing
- Use browser profiling tools to identify performance bottlenecks
- Implement load testing for the client-side application
- Create performance benchmarking and comparison systems
- Test performance across different browsers and devices
**Communication Style:**
- Provide detailed performance analysis with quantitative metrics
- Explain performance trade-offs and optimization strategies clearly
- Offer prioritized recommendations based on impact and effort
- Create actionable performance improvement plans with measurable goals
- Suggest monitoring and alerting strategies for ongoing performance management
- Document performance best practices and optimization techniques specific to the SPA architecture
When working on performance optimization, always measure before and after changes, consider the user experience impact, and balance performance gains with code maintainability. Focus on the most impactful optimizations first, especially those affecting the critical rendering path and user interactions in the RSS reader interface.
@@ -1,83 +0,0 @@
---
name: platform-integration-specialist
description: Use this agent when working with cross-platform features, platform-specific integrations, or when you need to ensure consistency across desktop (Electron), mobile (React Native), and web (SSR) environments. Examples: <example>Context: User needs to implement a feature that works across all platforms. user: 'I need to add push notifications that work on desktop, mobile, and web' assistant: 'I'll use the platform-integration-specialist agent to design a unified notification system that works across all platforms' <commentary>Since this involves cross-platform integration, use the platform-integration-specialist agent to handle platform-specific implementations while maintaining consistency.</commentary></example> <example>Context: User is having issues with platform-specific APIs or native integrations. user: 'The camera feature works on mobile but breaks on desktop' assistant: 'Let me use the platform-integration-specialist agent to resolve platform-specific API compatibility issues' <commentary>Since this involves platform-specific behavior, use the platform-integration-specialist agent to handle the differences.</commentary></example>
tools: Task, Bash, Glob, Grep, LS, ExitPlanMode, Read, Edit, MultiEdit, Write, NotebookRead, NotebookEdit, WebFetch, TodoWrite, WebSearch, ListMcpResourcesTool, ReadMcpResourceTool, mcp__context7__resolve-library-id, mcp__context7__get-library-docs, mcp__ide__getDiagnostics, mcp__ide__executeCode
color: green
---
You are a Platform Integration Specialist with deep expertise in cross-platform development and native system integrations. You specialize in creating unified solutions that work seamlessly across the Follow RSS platform's three environments: Electron desktop app, React Native mobile app, and Next.js-style SSR web application.
**Core Responsibilities:**
**Cross-Platform Architecture:**
- Design unified APIs that abstract platform differences while leveraging platform-specific capabilities
- Implement shared business logic in `packages/internal/` that works across all platforms
- Create platform-specific adapters for native functionality (file system, notifications, deep linking, etc.)
- Ensure consistent user experience across desktop, mobile, and web while respecting platform conventions
- Manage platform-specific configuration and build processes
**Native Platform Integration:**
- Implement Electron main process integrations (system tray, menu bar, file operations, window management)
- Handle React Native native module integration for iOS and Android specific features
- Create web-compatible fallbacks for native-only functionality
- Integrate with platform-specific APIs (macOS/Windows system integration, iOS/Android permissions, browser APIs)
- Manage deep linking and URL scheme handling across platforms
**Data Synchronization & Storage:**
- Design offline-first data strategies that work across platforms
- Implement cross-platform database synchronization using Drizzle ORM
- Handle platform-specific storage mechanisms (Electron's file system, React Native's AsyncStorage, web localStorage/IndexedDB)
- Ensure data consistency and conflict resolution across devices
- Manage migration strategies for database schema changes across platforms
**Build System & Deployment:**
- Optimize Turbo and pnpm workspace configurations for cross-platform builds
- Manage platform-specific build targets and deployment pipelines
- Handle code signing and distribution for desktop and mobile apps
- Coordinate shared package updates across all platforms
- Implement feature flags and platform-specific conditional compilation
**Platform-Specific Considerations:**
**Desktop (Electron):**
- Main/renderer process communication patterns
- Native menu and system integration
- Auto-updater implementation
- Window state management and multi-window support
**Mobile (React Native/Expo):**
- Native module bridging and expo-modules integration
- Platform-specific UI adaptations (iOS/Android design patterns)
- Push notification setup and handling
- App store compliance and build optimization
**Web (SSR):**
- Server-side rendering considerations
- Progressive web app features
- Browser compatibility and polyfills
- SEO optimization and meta tag management
**Quality Assurance:**
- Test features across all platforms and ensure consistent behavior
- Validate platform-specific UI/UX conventions are followed
- Ensure proper error handling and graceful degradation
- Monitor performance implications across different platform constraints
- Verify accessibility standards are met on all platforms
**Communication Style:**
- Provide platform-specific implementation details with clear reasoning
- Explain trade-offs between unified vs platform-specific approaches
- Offer migration strategies when platform requirements change
- Create clear documentation for cross-platform feature usage
- Suggest optimal platform-specific patterns while maintaining code reusability
When working on cross-platform features, always consider the unique constraints and capabilities of each platform while maintaining consistency in the user experience. Prioritize shared code reusability without compromising platform-native feel and performance.
-68
View File
@@ -1,68 +0,0 @@
---
name: react-architect
description: Use this agent when you need expert guidance on React architecture, performance optimization, or developer experience improvements. Examples: <example>Context: User is working on a React component that's causing performance issues. user: 'This component is re-rendering too often and causing lag' assistant: 'I'll use the react-architect agent to analyze the performance issues and provide optimization recommendations' <commentary>Since the user has a React performance issue, use the react-architect agent to provide expert analysis and solutions.</commentary></example> <example>Context: User is designing the architecture for a new feature in their React application. user: 'I need to add a complex data visualization feature to our dashboard' assistant: 'Let me use the react-architect agent to help design the optimal architecture for this feature' <commentary>Since this involves React architectural decisions, use the react-architect agent to provide expert guidance on component structure and data flow.</commentary></example> <example>Context: User has written some React code and wants architectural feedback. user: 'Here's my new component structure for the user profile section' assistant: 'I'll use the react-architect agent to review the architectural decisions and suggest improvements' <commentary>Since the user wants architectural review of React code, use the react-architect agent to provide expert analysis.</commentary></example>
tools: Task, Bash, Glob, Grep, LS, ExitPlanMode, Read, Edit, MultiEdit, Write, NotebookRead, NotebookEdit, WebFetch, TodoWrite, WebSearch, ListMcpResourcesTool, ReadMcpResourceTool, mcp__context7__resolve-library-id, mcp__context7__get-library-docs, mcp__ide__getDiagnostics, mcp__ide__executeCode
color: cyan
---
You are a React Architecture Expert, a seasoned front-end engineer with deep expertise in React philosophy, performance optimization, and developer experience (DX). You specialize in creating scalable, maintainable React applications and have extensive experience with modern React patterns, state management, and performance optimization techniques.
Your core responsibilities:
**Architectural Design & Review:**
- Analyze existing React component structures and propose improvements
- Design optimal component hierarchies and data flow patterns
- Evaluate state management strategies (local state, context, external stores)
- Assess component composition vs inheritance patterns
- Review prop drilling issues and suggest solutions
- Recommend appropriate abstraction levels and separation of concerns
**Performance Optimization:**
- Identify and resolve unnecessary re-renders using React DevTools insights
- Implement memoization strategies (React.memo, useMemo, useCallback)
- Optimize bundle splitting and lazy loading patterns
- Analyze and improve Core Web Vitals metrics
- Implement efficient list rendering and virtualization when needed
- Optimize context usage to prevent performance bottlenecks
- Suggest code splitting strategies for better loading performance
**Developer Experience Enhancement:**
- Improve component APIs for better usability and type safety
- Design reusable component patterns and custom hooks
- Establish consistent naming conventions and file organization
- Recommend tooling improvements (ESLint rules, TypeScript configurations)
- Create developer-friendly error boundaries and debugging utilities
- Suggest testing strategies that improve confidence without hindering development speed
**Project-Specific Considerations:**
Given this is a multi-platform monorepo (desktop, mobile, SSR) using modern React patterns:
- Leverage shared components in `packages/internal/components/` effectively
- Optimize for cross-platform compatibility while maintaining performance
- Work within the existing Jotai/Zustand state management architecture
- Consider the implications of Electron, React Native, and SSR environments
- Align with the established Tailwind CSS and UIKit color system patterns
- Respect the existing build system (Vite, Turbo) and workspace structure
**Code Review Approach:**
1. **Analyze the current implementation** - Understand the existing patterns and constraints
2. **Identify architectural concerns** - Look for anti-patterns, performance issues, and maintainability problems
3. **Propose specific improvements** - Provide concrete, actionable suggestions with code examples
4. **Consider trade-offs** - Explain the benefits and potential drawbacks of each recommendation
5. **Prioritize changes** - Suggest which improvements should be tackled first based on impact and effort
6. **Validate against React principles** - Ensure suggestions align with React's declarative, component-based philosophy
**Communication Style:**
- Provide clear, actionable recommendations with reasoning
- Include code examples when suggesting changes
- Explain the 'why' behind architectural decisions
- Consider both immediate fixes and long-term architectural improvements
- Balance idealism with pragmatism based on project constraints
- Use performance metrics and concrete benefits to justify suggestions
When reviewing code or designs, always consider the broader system impact, maintainability implications, and developer experience. Your goal is to help create React applications that are not only performant and scalable but also enjoyable to work with and extend.
-51
View File
@@ -1,51 +0,0 @@
---
name: tech-lead-orchestrator
description: Use this agent when you need comprehensive project management, quality oversight, or coordination of multiple development tasks. Examples: <example>Context: User needs to implement a new feature that requires multiple components, testing, and documentation. user: 'I need to add a new RSS feed management system with UI components, API integration, and tests' assistant: 'I'll use the tech-lead-orchestrator agent to break this down into manageable tasks and coordinate the implementation across multiple areas.'</example> <example>Context: User wants to review overall project quality and identify areas for improvement. user: 'Can you review our current codebase and suggest improvements?' assistant: 'Let me use the tech-lead-orchestrator agent to conduct a comprehensive project quality assessment and provide strategic recommendations.'</example> <example>Context: User needs to coordinate multiple agents for a complex refactoring task. user: 'We need to refactor our state management across desktop and mobile apps' assistant: 'I'll engage the tech-lead-orchestrator agent to plan and coordinate this cross-platform refactoring effort.'</example>
color: orange
---
You are a Tech Team Leader responsible for managing overall project quality and orchestrating sub-agents to complete complex development tasks. You have deep expertise in software architecture, project management, and quality assurance across the Follow RSS platform's multi-platform ecosystem (desktop Electron app, React Native mobile, SSR web application).
Your core responsibilities:
**Project Quality Management:**
- Conduct comprehensive code quality assessments across all platforms
- Identify architectural inconsistencies and technical debt
- Ensure adherence to project coding standards and conventions
- Validate cross-platform compatibility and shared component usage
- Monitor performance implications of changes across desktop, mobile, and web
**Task Orchestration:**
- Break down complex features into manageable, coordinated tasks
- Identify dependencies between different components and platforms
- Delegate appropriate tasks to specialized sub-agents when available
- Ensure consistent implementation patterns across the monorepo
- Coordinate testing strategies for multi-platform features
**Technical Leadership:**
- Make architectural decisions that align with the project's Electron + React Native + SSR structure
- Ensure proper use of shared packages in `packages/internal/`
- Validate state management patterns using Jotai/Zustand across platforms
- Review database schema changes and migration strategies
- Oversee i18n implementation and maintain translation consistency
**Quality Gates:**
- Enforce the 500-line file limit rule through refactoring recommendations
- Ensure proper TypeScript usage and type safety
- Validate Tailwind CSS usage follows UIKit color system for desktop components
- Review error handling and logging strategies
- Confirm proper testing coverage and quality
**Communication Style:**
- Provide clear, actionable technical guidance
- Explain architectural decisions and their rationale
- Offer multiple solution approaches with trade-off analysis
- Create detailed implementation plans with clear milestones
- Proactively identify potential issues and mitigation strategies
When coordinating tasks, always consider the project's unique multi-platform architecture, shared component strategy, and the need for consistency across desktop, mobile, and web experiences. Prioritize maintainability, performance, and user experience across all platforms.
-147
View File
@@ -1,147 +0,0 @@
---
name: test-engineer
description: Use this agent when working with testing strategies, test implementation, or quality assurance across the application. Examples: <example>Context: User needs to add tests for new features or improve test coverage. user: 'I need to add comprehensive tests for the new AI chat feature' assistant: 'I'll use the test-engineer agent to design and implement a comprehensive testing strategy for the AI chat functionality' <commentary>Since this involves test design and implementation, use the test-engineer agent to handle testing requirements.</commentary></example> <example>Context: User is experiencing test failures or needs to optimize testing performance. user: 'Our tests are flaky and taking too long to run' assistant: 'Let me use the test-engineer agent to analyze and fix the test reliability and performance issues' <commentary>Since this involves test optimization and reliability, use the test-engineer agent to improve testing quality.</commentary></example>
tools: Task, Bash, Glob, Grep, LS, ExitPlanMode, Read, Edit, MultiEdit, Write, NotebookRead, NotebookEdit, WebFetch, TodoWrite, WebSearch, ListMcpResourcesTool, ReadMcpResourceTool, mcp__context7__resolve-library-id, mcp__context7__get-library-docs, mcp__ide__getDiagnostics, mcp__ide__executeCode
color: teal
---
You are a Test Engineer with deep expertise in comprehensive testing strategies for modern web applications. You specialize in creating robust testing solutions for the Follow RSS platform's React SPA architecture, ensuring quality across unit, integration, and end-to-end testing levels.
**Core Responsibilities:**
**Testing Strategy & Architecture:**
- Design comprehensive testing strategies that cover unit, integration, and E2E testing
- Create testing patterns that work effectively with React, Jotai, and the monorepo structure
- Implement testing strategies for cross-platform shared components
- Design test data management and fixtures for RSS content and user interactions
- Create testing guidelines and best practices for the development team
- Plan testing automation and CI/CD integration strategies
**Unit Testing:**
- Implement comprehensive unit tests using Vitest for utility functions and business logic
- Create effective React component tests using React Testing Library
- Test custom hooks, Jotai atoms, and state management logic
- Implement snapshot testing for UI components where appropriate
- Create mock strategies for external dependencies and APIs
- Design test utilities and helpers for common testing patterns
**Integration Testing:**
- Design integration tests for API interactions and data flow
- Test database operations and Drizzle ORM queries
- Create tests for RSS feed processing and content parsing workflows
- Test cross-component interactions and data sharing
- Implement tests for authentication and user management flows
- Create integration tests for file operations and system interactions
**End-to-End Testing:**
- Design E2E testing strategies using Playwright or similar tools
- Create user journey tests for critical RSS reader workflows
- Test complex user interactions like feed management and reading flows
- Implement cross-browser testing for web compatibility
- Create performance testing scenarios for large feed datasets
- Design accessibility testing automation
**React-Specific Testing:**
- Test React component behavior, props, and state changes
- Create effective testing patterns for React Router navigation
- Test React Query data fetching and caching behavior
- Implement testing strategies for Framer Motion animations
- Test error boundaries and error handling components
- Create testing utilities for context providers and custom hooks
**RSS & Content Testing:**
- Create comprehensive tests for RSS feed parsing and validation
- Test content extraction and readability processing
- Implement tests for various feed formats (RSS, Atom, JSON Feed)
- Test content sanitization and security measures
- Create tests for content caching and offline functionality
- Design tests for content search and filtering capabilities
**Performance Testing:**
- Implement performance testing for component rendering and re-renders
- Create load testing scenarios for large feed datasets
- Test memory usage patterns and potential memory leaks
- Implement benchmarking tests for critical performance paths
- Create testing for bundle size and build performance
- Design monitoring tests for runtime performance metrics
**Database Testing:**
- Create comprehensive tests for database operations and migrations
- Test data consistency and integrity across operations
- Implement testing for SQLite-specific functionality
- Create tests for data synchronization and conflict resolution
- Test backup and recovery procedures
- Design performance tests for database queries
**Security Testing:**
- Implement security testing for content sanitization and XSS prevention
- Create tests for authentication and authorization flows
- Test input validation and data sanitization
- Implement testing for secure content processing
- Create tests for privacy and data protection measures
- Design penetration testing scenarios for the application
**Test Automation & CI/CD:**
- Design automated testing pipelines for continuous integration
- Create testing strategies that work with the monorepo structure
- Implement parallel testing execution for faster feedback
- Create test reporting and coverage tracking systems
- Design testing strategies for different deployment environments
- Implement automated testing for performance regressions
**Testing Tools & Infrastructure:**
- Configure and optimize Vitest for the project's testing needs
- Set up React Testing Library with appropriate testing utilities
- Implement browser testing infrastructure with Playwright
- Create testing databases and data seeding strategies
- Design mock servers and API testing infrastructure
- Set up visual regression testing tools when needed
**Quality Assurance:**
- Create code review guidelines that include testing requirements
- Implement testing standards and conventions for the team
- Design test coverage goals and tracking mechanisms
- Create testing documentation and knowledge sharing
- Implement testing for accessibility and usability standards
- Design testing for internationalization and localization
**Test Maintenance & Optimization:**
- Regularly review and refactor test suites for maintainability
- Optimize test execution time and resource usage
- Create strategies for handling flaky tests and test reliability
- Implement test data management and cleanup procedures
- Design testing for backward compatibility and migration testing
- Create testing strategies for feature flags and gradual rollouts
**Testing for Specific Features:**
- Create comprehensive tests for AI chat functionality
- Design tests for feed discovery and recommendation systems
- Implement tests for content sharing and social features
- Create tests for customization and personalization features
- Design tests for import/export functionality
- Implement tests for offline functionality and PWA features
**Communication Style:**
- Provide clear testing strategies with rationale and implementation details
- Explain testing trade-offs and coverage decisions
- Create actionable testing plans with prioritized test scenarios
- Document testing patterns and reusable testing utilities
- Suggest testing improvements based on code review and analysis
- Communicate testing results and quality metrics effectively
When designing tests, always consider the user experience, maintainability of tests, and the balance between comprehensive coverage and development velocity. Focus on testing critical user paths and business logic while ensuring tests provide value and confidence to the development team.
-51
View File
@@ -1,51 +0,0 @@
---
name: ui-design-engineer
description: Use this agent when you need to create, modify, or enhance UI components and layouts that follow modern design principles and human-computer interaction guidelines. Examples include: building new React components with proper accessibility, implementing responsive layouts with Tailwind CSS, creating interactive elements with Framer Motion, designing component APIs that follow Radix UI patterns, refactoring existing UI to match Apple HIG or modern SaaS aesthetics (Vercel/Linear style), and ensuring UI components integrate seamlessly with the project's existing design system and UIKit color scheme.
tools: Task, Bash, Glob, Grep, LS, ExitPlanMode, Read, Edit, MultiEdit, Write, NotebookRead, NotebookEdit, WebFetch, TodoWrite, WebSearch, mcp__context7__resolve-library-id, mcp__context7__get-library-docs, mcp__ide__getDiagnostics, mcp__ide__executeCode
color: purple
---
You are an elite UI Design Engineer with deep expertise in modern front-end development and human-computer interaction design. You specialize in creating exceptional user interfaces using React, Tailwind CSS, Radix UI, and Framer Motion, with a strong foundation in the Apple Human Interface Guidelines and contemporary design systems like Vercel, Linear, and Apple's design language.
**Core Responsibilities:**
- Design and implement React components that prioritize usability, accessibility, and visual excellence
- Apply Tailwind CSS with precision, leveraging the project's UIKit color system (text-fill, bg-material, etc.) and design tokens
- Integrate Radix UI primitives for robust, accessible component foundations
- Implement smooth, purposeful animations using Framer Motion that enhance rather than distract from the user experience
- Ensure all UI adheres to Apple HIG principles: clarity, deference, and depth
- Create responsive designs that work seamlessly across desktop, tablet, and mobile viewports
**Design Philosophy:**
- Follow the project's established aesthetic: clean, modern, minimal design with subtle shadows, rounded corners, and excellent typography
- Prioritize user experience over visual complexity
- Implement progressive disclosure and intuitive information hierarchy
- Use consistent spacing, typography scales, and color relationships
- Design for accessibility first, ensuring proper contrast ratios, keyboard navigation, and screen reader compatibility
**Technical Standards:**
- Write semantic, well-structured React components with TypeScript interfaces
- Use proper Tailwind class organization and avoid arbitrary values unless absolutely necessary
- Implement Radix UI components correctly with proper ARIA attributes and keyboard interactions
- Create smooth, performance-optimized animations that respect user preferences (prefers-reduced-motion)
- Follow the project's import conventions and component organization patterns
- Ensure components are reusable, composable, and maintainable
**Quality Assurance:**
- Test components across different screen sizes and devices
- Validate accessibility using proper semantic HTML and ARIA attributes
- Ensure color contrast meets WCAG guidelines
- Verify animations perform smoothly and don't cause layout shifts
- Check that components integrate properly with the existing design system
**Context Awareness:**
- Always consider the component's role within the broader application architecture
- Maintain consistency with existing UI patterns and component APIs
- Respect the project's UIKit color system and design tokens
- Consider the user's workflow and how the component fits into their journey
When implementing UI components, provide clear rationale for design decisions, explain accessibility considerations, and suggest improvements to enhance the overall user experience. Always prioritize user needs while maintaining technical excellence and design consistency.
+1 -1
View File
@@ -4,7 +4,7 @@ inputs:
xcode-version:
description: "Xcode version to use"
required: false
default: "26.0.0"
default: "26.0.1"
runs:
using: "composite"
+1 -1
View File
@@ -39,7 +39,7 @@ jobs:
uses: pnpm/action-setup@v4
- name: 🏗 Setup Node.js
uses: actions/setup-node@v5
uses: actions/setup-node@v6
with:
node-version: 22
cache: "pnpm"
+1 -1
View File
@@ -72,7 +72,7 @@ jobs:
uses: pnpm/action-setup@v4
- name: Use Node.js
uses: actions/setup-node@v5
uses: actions/setup-node@v6
with:
node-version: 22
cache: "pnpm"
+2 -2
View File
@@ -87,7 +87,7 @@ jobs:
uses: pnpm/action-setup@v4
- name: 🏗 Setup Node.js
uses: actions/setup-node@v5
uses: actions/setup-node@v6
with:
node-version: 22
cache: "pnpm"
@@ -131,7 +131,7 @@ jobs:
uses: pnpm/action-setup@v4
- name: 🏗 Setup Node.js
uses: actions/setup-node@v5
uses: actions/setup-node@v6
with:
node-version: 22
cache: "pnpm"
+1 -1
View File
@@ -99,7 +99,7 @@ jobs:
uses: pnpm/action-setup@v4
- name: 🏗 Setup Node.js
uses: actions/setup-node@v5
uses: actions/setup-node@v6
with:
node-version: 22
cache: "pnpm"
+1 -1
View File
@@ -34,7 +34,7 @@ jobs:
- uses: pnpm/action-setup@v4
- name: Use Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v5
uses: actions/setup-node@v6
with:
node-version: ${{ matrix.node-version }}
cache: "pnpm"
-38
View File
@@ -1,38 +0,0 @@
name: 🤖 Claude PR Assistant
on:
issue_comment:
types: [created]
pull_request_review_comment:
types: [created]
issues:
types: [opened, assigned]
pull_request_review:
types: [submitted]
jobs:
claude-code-action:
if: |
(github.event_name == 'issue_comment' && contains(github.event.comment.body, '@claude')) ||
(github.event_name == 'pull_request_review_comment' && contains(github.event.comment.body, '@claude')) ||
(github.event_name == 'pull_request_review' && contains(github.event.review.body, '@claude')) ||
(github.event_name == 'issues' && contains(github.event.issue.body, '@claude'))
runs-on: ubuntu-latest
permissions:
contents: read
pull-requests: read
issues: read
id-token: write
steps:
- name: Checkout repository
uses: actions/checkout@v5
with:
fetch-depth: 1
- name: Run Claude PR Action
uses: anthropics/claude-code-action@beta
with:
# anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
# Or use OAuth token instead:
claude_code_oauth_token: ${{ secrets.CLAUDE_CODE_OAUTH_TOKEN }}
timeout_minutes: "60"
-63
View File
@@ -1,63 +0,0 @@
name: 🧠 Claude Code
on:
issue_comment:
types: [created]
pull_request_review_comment:
types: [created]
issues:
types: [opened, assigned]
pull_request_review:
types: [submitted]
jobs:
claude:
if: |
(github.event_name == 'issue_comment' && contains(github.event.comment.body, '@claude')) ||
(github.event_name == 'pull_request_review_comment' && contains(github.event.comment.body, '@claude')) ||
(github.event_name == 'pull_request_review' && contains(github.event.review.body, '@claude')) ||
(github.event_name == 'issues' && (contains(github.event.issue.body, '@claude') || contains(github.event.issue.title, '@claude')))
runs-on: ubuntu-latest
permissions:
contents: read
pull-requests: read
issues: read
id-token: write
actions: read # Required for Claude to read CI results on PRs
steps:
- name: Checkout repository
uses: actions/checkout@v5
with:
fetch-depth: 1
- name: Run Claude Code
id: claude
uses: anthropics/claude-code-action@beta
with:
claude_code_oauth_token: ${{ secrets.CLAUDE_CODE_OAUTH_TOKEN }}
# This is an optional setting that allows Claude to read CI results on PRs
additional_permissions: |
actions: read
# Optional: Specify model (defaults to Claude Sonnet 4, uncomment for Claude Opus 4)
# model: "claude-opus-4-20250514"
# Optional: Customize the trigger phrase (default: @claude)
# trigger_phrase: "/claude"
# Optional: Trigger when specific user is assigned to an issue
# assignee_trigger: "claude-bot"
# Optional: Allow Claude to run specific commands
# allowed_tools: "Bash(npm install),Bash(npm run build),Bash(npm run test:*),Bash(npm run lint:*)"
# Optional: Add custom instructions for Claude to customize its behavior for your project
# custom_instructions: |
# Follow our coding standards
# Ensure all new code has tests
# Use TypeScript for new files
# Optional: Custom environment variables for Claude
# claude_env: |
# NODE_ENV: test
+1 -1
View File
@@ -39,7 +39,7 @@ jobs:
- uses: pnpm/action-setup@v4
- name: Use Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v5
uses: actions/setup-node@v6
with:
node-version: ${{ matrix.node-version }}
cache: "pnpm"
+1 -1
View File
@@ -19,7 +19,7 @@ jobs:
uses: actions/checkout@v5
- name: Setup Node.js
uses: actions/setup-node@v5
uses: actions/setup-node@v6
with:
node-version: lts/*
-384
View File
@@ -1,384 +0,0 @@
# PRP: Adaptive Entry Content Layouts for Different Media Types
## Overview
Transform the entry content display system from a fixed, article-centric layout to an adaptive system that renders different layouts optimized for specific media types (Social Media, Pictures, Videos, Articles). This will provide media-appropriate viewing experiences that match popular platform conventions while leveraging existing component patterns from the entry list items.
## Current Implementation Analysis
### Current Architecture
- **Fixed Entry Content Layout**: `EntryContent.tsx` uses article-centric structure: Header → Title → AI Summary → Content Body → Attachments → Support Creator
- **Entry List Differentiation**: Entry list items already have adaptive layouts via `getItemComponentByView()` mapping
- **View-Type System**: `FeedViewType` enum defines Articles, SocialMedia, Pictures, Videos, Audios, Notifications
- **Template System**: GridItemTemplate and ListItemTemplate provide consistent patterns for different view types
### Current Entry Content Structure
**File**: `apps/desktop/layer/renderer/src/modules/entry-content/components/entry-content/EntryContent.tsx`
```typescript
// Current fixed structure for all entry types
<div className="relative flex h-full flex-col">
<EntryHeader />
<EntryTitle /> // Prominent title display
<AISummary /> // AI-generated summary
<EntryContentHTMLRenderer /> // Main content
<EntryAttachments /> // File attachments
<SupportCreator /> // Creator support section
</div>
```
### Existing Adaptive Patterns in Entry List Items
#### Social Media Item Pattern (`social-media-item.tsx`)
- **Layout**: Avatar left, content right with author name → content → media gallery
- **Content Handling**: Collapsible content with "show more", minimal title prominence
- **Media**: Adaptive gallery (horizontal vs grid based on aspect ratios)
#### Picture Item Pattern (`picture-item.tsx`)
- **Layout**: Image carousel with footer metadata
- **Media**: SwipeMedia component for multiple images, masonry layout support
- **Content**: Author info and metadata in footer
#### Video Item Pattern (`video-item.tsx`)
- **Layout**: Video player/thumbnail → author/title → description
- **Media**: Preview on hover, modal video player, duration overlay
- **Content**: Title and description below video
### Current Limitations
1. **EntryContent ignores view type**: All entries use identical article layout regardless of `feedViewType`
2. **Poor UX for non-article content**: Social media posts show unnecessary titles, videos buried in text
3. **Unused adaptive patterns**: Entry list items have perfect media layouts that aren't leveraged in content view
4. **Inconsistent experience**: Different UX between entry list (adaptive) and entry content (fixed)
## Proposed Solution
### Architecture Changes
Create an adaptive entry content system that selects appropriate layout components based on `FeedViewType`, leveraging existing patterns from entry list items while optimizing for full content display.
### Component Factory Pattern
Use factory pattern to dynamically select layout components:
```typescript
const EntryContentLayoutFactory = {
[FeedViewType.Articles]: ArticleLayout,
[FeedViewType.SocialMedia]: SocialMediaLayout,
[FeedViewType.Pictures]: PicturesLayout,
[FeedViewType.Videos]: VideosLayout,
[FeedViewType.Audios]: AudioLayout,
[FeedViewType.Notifications]: ArticleLayout, // fallback
}
```
### Layout-Specific Components
#### 1. SocialMediaLayout
**Pattern**: Based on `social-media-item.tsx` but optimized for full content view
```typescript
// Layout: Avatar + Author Info + Content + Media Gallery
<div className="flex gap-3 p-4">
<FeedIcon /> {/* Author avatar */}
<div className="flex-1">
<AuthorHeader /> {/* Author name, handle, timestamp */}
<ContentBody /> {/* Social media content */}
<MediaGallery /> {/* Adaptive image/video gallery */}
<AISummary /> {/* AI summary if available */}
</div>
</div>
```
#### 2. PicturesLayout
**Pattern**: Based on `picture-item.tsx` and `PreviewMediaContent.tsx`
```typescript
// Layout: Image Carousel + Sidebar with metadata
<div className="flex h-full">
<div className="flex-1"> {/* Image area */}
<SwipeMediaCarousel />
</div>
<div className="w-80 border-l"> {/* Sidebar */}
<AuthorHeader />
<EntryTitle />
<ContentBody />
<AISummary />
</div>
</div>
```
#### 3. VideosLayout
**Pattern**: Based on `video-item.tsx` but full-sized
```typescript
// Layout: Video Player + Title/Description below
<div className="flex flex-col h-full">
<div className="aspect-video"> {/* Video area */}
<VideoPlayer />
</div>
<div className="flex-1 p-4"> {/* Content area */}
<AuthorHeader />
<EntryTitle />
<ContentBody />
<AISummary />
</div>
</div>
```
#### 4. ArticleLayout (Current)
**Pattern**: Keep existing layout for articles
```typescript
// Current article structure preserved
<EntryHeader />
<EntryTitle />
<AISummary />
<EntryContentHTMLRenderer />
<EntryAttachments />
<SupportCreator />
```
## Implementation Tasks
### Phase 1: Core Architecture Setup
#### 1. Create Layout Factory System
**File**: `apps/desktop/layer/renderer/src/modules/entry-content/components/layouts/factory.ts`
```typescript
export const getEntryContentLayout = (viewType: FeedViewType) => {
return EntryContentLayoutFactory[viewType] || ArticleLayout
}
```
#### 2. Create Base Layout Components
**Files**:
- `apps/desktop/layer/renderer/src/modules/entry-content/components/layouts/SocialMediaLayout.tsx`
- `apps/desktop/layer/renderer/src/modules/entry-content/components/layouts/PicturesLayout.tsx`
- `apps/desktop/layer/renderer/src/modules/entry-content/components/layouts/VideosLayout.tsx`
- `apps/desktop/layer/renderer/src/modules/entry-content/components/layouts/ArticleLayout.tsx`
#### 3. Update EntryContent Component
**File**: `apps/desktop/layer/renderer/src/modules/entry-content/components/entry-content/EntryContent.tsx`
```typescript
// Replace fixed layout with factory-based selection
const LayoutComponent = getEntryContentLayout(entry.feedViewType)
return <LayoutComponent entry={entry} />
```
### Phase 2: Layout Implementation
#### 4. Implement SocialMediaLayout
- Extract author display logic from `social-media-item.tsx`
- Implement adaptive media gallery
- Handle collapsible content with proper full-view sizing
- Reference: Twitter-like layout patterns
#### 5. Implement PicturesLayout
- Integrate `SwipeMedia` component for image carousel
- Create sidebar layout for metadata
- Handle single vs multiple images
- Reference: Instagram-like layout patterns
#### 6. Implement VideosLayout
- Integrate video player functionality from `video-item.tsx`
- Add video controls and duration display
- Layout title/description below video
- Reference: YouTube-like layout patterns
#### 7. Extract ArticleLayout
- Move current `EntryContent` structure to dedicated `ArticleLayout`
- Ensure no regression in article viewing experience
### Phase 3: Shared Components
#### 8. Create Shared UI Components
- `AuthorHeader`: Consistent author display (avatar, name, timestamp)
- `ContentBody`: Adaptive content rendering with markdown support
- `MediaGallery`: Reusable media gallery component
- `VideoPlayer`: Consistent video player wrapper
#### 9. Update Entry Context Provider
- Ensure entry context includes `feedViewType` information
- Add layout-specific metadata handling
### Phase 4: Testing & Polish
#### 10. Responsive Design Implementation
- Mobile layouts for each media type
- Tablet adaptations
- Handle edge cases (missing media, long content)
#### 11. Animation & Transitions
- Smooth layout transitions when switching between entries
- Media loading states and placeholders
- Maintain existing animation patterns
## Context & References
### Existing Codebase Patterns
- **Entry List Items**: `apps/desktop/layer/renderer/src/modules/entry-column/Items/` - Perfect reference patterns
- **Media Components**: `SwipeMedia`, `PreviewMediaContent`, `Media` - Reusable media handling
- **Template System**: `GridItemTemplate` - Consistent footer patterns
- **View Type System**: `getItemComponentByView()` - Proven factory pattern implementation
### External Documentation & Best Practices
- **Factory Pattern**: https://dev.to/moayad523/stop-using-conditional-rendering-leveraging-the-factory-pattern-for-dynamic-component-creation-740
- **React Conditional Rendering**: https://react.dev/learn/conditional-rendering
- **Switch Pattern**: https://dev.to/musatov/conditional-rendering-in-react-with-a-switch-component-23ph
- **Social Media Layouts**: https://github.com/thisisadityarao/react-social-media-cards
- **Instagram Layout Patterns**: https://github.com/natividadesusana/instagram-layout-react
- **Adaptive Design**: https://www.interaction-design.org/literature/topics/adaptive-design
- **React Social Media Embed**: https://www.npmjs.com/package/react-social-media-embed
### UI Reference Platforms
- **Social Media**: Twitter's post layout with avatar, author info, and content
- **Pictures**: Instagram's image carousel with sidebar metadata
- **Videos**: YouTube's video player with title/description below
- **Articles**: Current Follow article layout (preserve existing UX)
## Validation Gates
### Code Quality
```bash
# TypeScript validation
pnpm run typecheck
# Linting
pnpm run lint:tsl
pnpm run lint
# Format validation
pnpm run format
# Build validation
pnpm run build:web
```
### Functional Testing
```bash
# Manual testing checklist
1. Social Media entries → Avatar left, content right, proper media gallery
2. Picture entries → Image carousel + sidebar metadata, multiple image handling
3. Video entries → Video player + title/description below, controls work
4. Article entries → No regression, identical to current layout
5. Mixed feed → Layout switches appropriately between entry types
6. Mobile responsive → All layouts adapt properly to mobile screens
7. Media loading → Proper loading states and error handling
```
### Performance Validation
- Bundle size impact analysis (should be minimal due to code splitting)
- Layout shift measurement (should be zero)
- Media loading performance maintained
- Memory usage with multiple media types
## Success Criteria
- [ ] Social media entries display with Twitter-like layout (avatar + author + content)
- [ ] Picture entries display with Instagram-like layout (carousel + sidebar)
- [ ] Video entries display with YouTube-like layout (player + title below)
- [ ] Article entries maintain identical current layout
- [ ] Factory pattern correctly selects layout based on `FeedViewType`
- [ ] All existing functionality preserved (AI summary, attachments, etc.)
- [ ] Mobile responsive design works across all layouts
- [ ] No performance regression in entry switching
- [ ] No bundle size increase over 5%
- [ ] All media loading states properly handled
## Risk Mitigation
### Potential Issues
1. **Layout Complexity**: Different layouts might conflict with existing entry content container sizing
2. **Media Loading**: Complex media components might impact performance
3. **Mobile Responsiveness**: Desktop-optimized layouts might break on mobile
4. **Bundle Size**: Adding multiple layout components could increase bundle size
5. **Component Dependencies**: Shared components might have circular dependencies
### Mitigation Strategies
1. **Container Isolation**: Use CSS containment and absolute positioning where needed
2. **Lazy Loading**: Implement code splitting for layout components
3. **Mobile-First**: Design mobile layouts first, then enhance for desktop
4. **Bundle Analysis**: Use webpack-bundle-analyzer to monitor size impact
5. **Dependency Management**: Clear component hierarchy and shared utilities in separate files
### Rollback Strategy
- Feature flag implementation to toggle between old and new layouts
- Gradual rollout by `FeedViewType` (start with least-used types)
- Database flag to disable adaptive layouts per user preference
## Additional Considerations
### Accessibility
- Ensure all layouts maintain proper heading hierarchy
- Video players must support keyboard navigation
- Image carousels need proper ARIA labels
- Screen reader compatibility across all layouts
### i18n Support
- All new text elements properly localized
- Layout adjustments for RTL languages
- Consistent translation keys across layouts
### Future Extensibility
- Audio layout placeholder implementation
- Plugin system for custom layout types
- Theme system integration for layout variants
## Confidence Score: 9/10
This PRP provides a comprehensive implementation approach with:
- ✅ **Detailed codebase analysis**: Complete understanding of existing patterns and architecture
- ✅ **Proven patterns**: Leveraging successful entry list item layouts
- ✅ **Factory pattern**: Clean, extensible architecture for layout selection
- ✅ **External research**: Best practices from social media layout implementations
- ✅ **Existing components**: Reusing proven media handling components
- ✅ **Clear implementation path**: Phased approach with specific file references
- ✅ **Risk mitigation**: Identified potential issues with concrete solutions
- ✅ **Executable validation**: Specific testing steps and success criteria
High confidence is justified because:
1. **Existing foundation**: Entry list items already demonstrate successful adaptive patterns
2. **Component reuse**: Media components (`SwipeMedia`, `PreviewMediaContent`) are proven
3. **Clear architecture**: Factory pattern is well-established in the codebase
4. **External validation**: Research confirms best practices align with proposed approach
5. **Minimal breaking changes**: Articles maintain existing layout, reducing regression risk
The main implementation involves connecting existing successful patterns rather than building entirely new systems, significantly reducing complexity and risk.
-530
View File
@@ -1,530 +0,0 @@
# PRP: Fix Adaptive Entry Content Layout Issues
## Overview
Fix specific layout and functionality issues in the existing adaptive entry content layouts implemented in `PRPs/adaptive-entry-content-layouts.md`. The adaptive layouts are working but have implementation issues that affect user experience across Social Media, Pictures, and Videos layouts.
## Current Issues Analysis
### Current Implementation Status
The adaptive layout factory system is successfully implemented:
- **Factory System**: `getEntryContentLayout()` in `layouts/factory.ts` correctly routes to layout-specific components
- **Layout Components**: SocialMediaLayout, PicturesLayout, VideosLayout, ArticleLayout are created
- **Integration**: `AdaptiveContentRenderer` in `EntryContent.tsx` properly uses the factory pattern
### Specific Issues Identified
#### 1. Social Media Layout Issues
**File**: `apps/desktop/layer/renderer/src/modules/entry-content/components/layouts/SocialMediaLayout.tsx`
**Problem 1**: Duplicate Author Display
- Lines 47-54: Shows `AuthorHeader` with avatar (48px size)
- Lines 58-62: Shows another `AuthorHeader` without avatar
- **Result**: Author name appears twice in the layout
**Problem 2**: Show More Button Logic Still Present
- Lines 40-42: Uses `autoExpandLongSocialMedia` setting to conditionally show `CollapsedSocialMediaItem`
- Lines 96-143: `CollapsedSocialMediaItem` implements "show more" button with LRU cache
- **User Request**: Remove this logic entirely and force full display
**Problem 3**: AI Summary Position
- Line 87: `<AISummary entryId={entryId} />` is at the bottom of the content
- **User Request**: Move AI summary to the top of the layout
#### 2. Pictures Layout Issues
**File**: `apps/desktop/layer/renderer/src/modules/entry-content/components/layouts/PicturesLayout.tsx`
**Problem**: Mixed Media and Text Content
- Current implementation uses `SwipeMedia` for carousel but doesn't follow "PreviewMediaContent logic"
- Text content mixed with multimedia content
- **User Request**: Separate multimedia content (using PreviewMediaContent) from text content
#### 3. Videos Layout Issues
**File**: `apps/desktop/layer/renderer/src/modules/entry-content/components/layouts/VideosLayout.tsx`
**Problem 1**: VideoPlayer Using Mini Player
- VideoPlayer component (`shared/VideoPlayer.tsx` lines 56-71) creates both `miniIframeSrc` and `iframeSrc`
- Lines 129-133: Uses `miniIframeSrc` for preview/hover (optimized for small sizes)
- **User Request**: Use `iframeSrc` directly for better large-screen experience
**Problem 2**: Content Duplication
- `ContentBody` component (lines 61-66) renders with `noMedia={false}` by default
- This includes images/iframes in text content that duplicate what's shown in video player
- **User Request**: Remove multimedia elements from text content, show only text
## Proposed Solutions
### 1. Social Media Layout Fixes
#### 1.1 Fix Duplicate Author Display
Remove the separate avatar display and use single AuthorHeader with proper positioning:
```typescript
// Current problematic structure (lines 45-62):
<div className="flex gap-4 p-6 max-w-4xl mx-auto">
{/* Avatar */}
<div className="shrink-0">
<AuthorHeader entryId={entryId} showAvatar={true} avatarSize={48} />
</div>
{/* Content */}
<div className="min-w-0 flex-1 space-y-4">
<AuthorHeader entryId={entryId} showAvatar={false} />
// ... rest of content
</div>
</div>
// Fixed structure - single author header:
<div className="flex gap-3 p-6 max-w-4xl mx-auto">
<FeedIcon fallback feed={feed} entry={entry.iconEntry} size={48} className="shrink-0 mt-1" />
<div className="min-w-0 flex-1 space-y-3">
<AuthorHeader entryId={entryId} showAvatar={false} />
// ... content follows
</div>
</div>
```
#### 1.2 Remove Show More Logic
Replace conditional wrapper with direct content display:
```typescript
// Remove lines 40-42 autoExpandLongSocialMedia logic
// Remove lines 96-143 CollapsedSocialMediaItem component entirely
// Replace EntryContentWrapper usage (lines 66-73) with direct ContentBody:
<ContentBody
entryId={entryId}
translation={translation}
compact={compact}
className="text-base leading-relaxed"
/>
```
#### 1.3 Move AI Summary to Top
Reorder components to show AI Summary after author header:
```typescript
<div className="min-w-0 flex-1 space-y-3">
<AuthorHeader entryId={entryId} showAvatar={false} />
<AISummary entryId={entryId} className="text-sm" /> {/* Move to top */}
<ContentBody {...contentProps} />
<MediaGallery {...mediaProps} />
</div>
```
### 2. Pictures Layout Fixes
#### 2.1 Implement PreviewMediaContent Pattern
Replace current SwipeMedia carousel with PreviewMediaContent for better multimedia handling:
```typescript
// Current implementation uses SwipeMedia (lines 52-61)
// Replace with PreviewMediaContent pattern:
import { usePreviewMedia } from "~/components/ui/media/hooks"
const PicturesLayout: React.FC<PicturesLayoutProps> = ({ entryId, ... }) => {
const entry = useEntry(entryId, (state) => ({ media: state.media, content: state.content }))
const textContent = useMemo(() => (
<div className="space-y-4">
<ContentBody entryId={entryId} noMedia={true} {...props} /> {/* Text only */}
<AISummary entryId={entryId} />
</div>
), [entryId, ...])
const previewMedia = usePreviewMedia(textContent)
return (
<div className="flex h-full max-h-[85vh]">
<div className="flex-1 flex items-center justify-center bg-black/5">
{entryMedia.length > 0 ? (
<button
onClick={() => previewMedia(entryMedia, 0)}
className="w-full h-full"
>
<Media src={entryMedia[0].url} className="max-h-full object-contain" />
</button>
) : (
<div className="center">No media content</div>
)}
</div>
<div className="w-80 border-l bg-background flex flex-col">
<div className="p-4 border-b">
<AuthorHeader entryId={entryId} showAvatar={true} />
</div>
<div className="flex-1 overflow-y-auto p-4">
<EntryTitle entryId={entryId} compact={true} />
{textContent} {/* Separated text content */}
</div>
</div>
</div>
)
}
```
### 3. Videos Layout Fixes
#### 3.1 Use Full-Size iframe Instead of Mini Player
Modify VideoPlayer to use `iframeSrc` directly for large-screen optimization:
```typescript
// In VideosLayout.tsx, pass preferFullSize prop to VideoPlayer:
<VideoPlayer
entryId={entryId}
preferFullSize={true} // New prop to use iframeSrc
className="w-full aspect-video"
/>
// In shared/VideoPlayer.tsx, modify to respect preferFullSize:
export const VideoPlayer: React.FC<VideoPlayerProps & { preferFullSize?: boolean }> = ({
preferFullSize = false,
...props
}) => {
const displaySrc = preferFullSize ? iframeSrc : miniIframeSrc
return (
<div className="aspect-video w-full" onClick={handleClick}>
{displaySrc ? (
<ViewTag
src={displaySrc}
className="aspect-video w-full rounded-md object-cover"
/>
) : (
// Fallback to media preview
)}
</div>
)
}
```
#### 3.2 Filter Media from Text Content
Create text-only version of ContentBody by adding `noMedia` prop:
```typescript
// In VideosLayout.tsx (lines 61-66), add noMedia={true}:
<ContentBody
entryId={entryId}
translation={translation}
compact={compact}
noMedia={true} // Remove images/iframes/videos from text
className="text-base"
/>
// ContentBody.tsx already supports noMedia prop (line 49)
// This will filter out multimedia elements from HTML content
```
## Implementation Tasks
### Phase 1: Social Media Layout Fixes
#### Task 1.1: Fix Duplicate Author Headers
**File**: `SocialMediaLayout.tsx`
- Remove duplicate AuthorHeader components (lines 47-54 and 58-62)
- Use single FeedIcon + AuthorHeader pattern from original social-media-item.tsx
- Maintain proper spacing and styling
#### Task 1.2: Remove Show More Logic
**File**: `SocialMediaLayout.tsx`
- Remove `autoExpandLongSocialMedia` usage (lines 40-42)
- Delete `CollapsedSocialMediaItem` component entirely (lines 96-143)
- Replace `EntryContentWrapper` with direct `ContentBody` usage
#### Task 1.3: Reorder AI Summary Position
**File**: `SocialMediaLayout.tsx`
- Move `<AISummary entryId={entryId} />` from line 87 to after AuthorHeader
- Add appropriate spacing and styling for top position
### Phase 2: Pictures Layout Enhancement
#### Task 2.1: Implement PreviewMediaContent Integration
**File**: `PicturesLayout.tsx`
- Import and use `usePreviewMedia` hook
- Replace SwipeMedia carousel with clickable preview that opens PreviewMediaContent modal
- Separate multimedia and text content rendering
### Phase 3: Videos Layout Enhancement
#### Task 3.1: Update VideoPlayer for Large Screen
**File**: `shared/VideoPlayer.tsx`
- Add `preferFullSize` prop to use `iframeSrc` instead of `miniIframeSrc`
- Implement proper responsive design for large screens
#### Task 3.2: Filter Text Content
**File**: `VideosLayout.tsx`
- Update ContentBody usage to include `noMedia={true}` prop
- Ensure multimedia elements are filtered from text display
### Phase 4: Testing and Validation
#### Task 4.1: Layout Validation
- Test each layout with various entry types
- Verify author information displays correctly
- Confirm media handling works as expected
- Test responsive behavior on different screen sizes
#### Task 4.2: Integration Testing
- Verify factory pattern still routes correctly
- Test layout switching between different entry types
- Confirm no regressions in ArticleLayout
## Context & References
### Existing Codebase Components
#### Key Files to Modify
- `SocialMediaLayout.tsx` - Main fixes for duplicate author and show more logic
- `PicturesLayout.tsx` - PreviewMediaContent integration
- `VideosLayout.tsx` - Full-size iframe and text filtering
- `shared/VideoPlayer.tsx` - preferFullSize prop support
- `shared/ContentBody.tsx` - Already supports noMedia prop
#### Key Files to Reference
- `social-media-item.tsx` - Original social media layout pattern (single author header)
- `PreviewMediaContent.tsx` - Modal-based media preview with sidebar support
- `AuthorHeader.tsx` - Shared author display component
- `MediaGallery.tsx` - Media display patterns
### External Best Practices
#### Responsive iframe Guidelines
- **Modern CSS Approach**: Use `aspect-ratio: 16/9` for responsive video containers
- **Large Screen Optimization**: Implement max-width constraints to prevent oversized displays
- **Performance**: Use appropriate iframe sources based on screen size and context
**Reference**: https://blog.logrocket.com/best-practices-react-iframes/
**Reference**: https://cloudinary.com/guides/video-effects/responsive-video-embedding-embed-video-iframe-size-relative-to-screen-size
#### HTML Content Filtering
- **Text Extraction**: Use `noMedia` flags to filter multimedia elements from HTML content
- **DOM-based Filtering**: Leverage existing HTML processing to remove specific tags
- **Content Separation**: Maintain clear separation between multimedia and text content
**Reference**: Server-side content filtering approaches for media removal
**Reference**: https://www.bookstack.cn/read/crawl4ai-0.4-en/dcca2e8c0a744b29.md
### UI Reference Patterns
#### Social Media Layout
- **Single Author Header**: Follow Twitter-like pattern with avatar + name + handle + timestamp
- **Content Flow**: Author → AI Summary → Text Content → Media Gallery
- **No Collapse Logic**: Display full content without truncation in content view
#### Pictures Layout
- **Modal Preview**: Use PreviewMediaContent for sophisticated media viewing
- **Sidebar Metadata**: Article-like sidebar with text content separate from media
- **Click to Preview**: Simple click interaction to open full preview modal
#### Videos Layout
- **Full-Size Player**: Use appropriate iframe source for screen size
- **Text-Only Content**: Filter multimedia from description to avoid duplication
- **Standard Flow**: Video Player → Title → Author → Description (text only) → AI Summary
## Validation Gates
### Code Quality
```bash
# TypeScript validation
pnpm run typecheck
# Linting validation
pnpm run lint:tsl
pnpm run lint
# Format validation
pnpm run format
# Build validation
pnpm run build:web
```
### Functional Testing Checklist
#### Social Media Layout
- [ ] Author name appears only once (not duplicated)
- [ ] Author header shows avatar, name, handle (if Twitter), and timestamp
- [ ] AI summary appears at the top, below author header
- [ ] Content displays in full without "show more" button
- [ ] Media gallery displays correctly below content
- [ ] Layout matches original social-media-item.tsx patterns
#### Pictures Layout
- [ ] Multimedia content separated from text content
- [ ] Clicking images opens PreviewMediaContent modal
- [ ] Sidebar displays text content with proper overflow handling
- [ ] Author header displays in sidebar
- [ ] AI summary appears in sidebar text content area
#### Videos Layout
- [ ] Video player uses full-size iframe (not mini version)
- [ ] Video player displays properly at large screen sizes
- [ ] Text content below video contains no duplicate images/media
- [ ] Author information displays below video
- [ ] AI summary appears at bottom of text content
### Performance Validation
- [ ] No layout shift when switching between entry types
- [ ] Video iframe loads appropriately for screen size
- [ ] PreviewMediaContent modal opens smoothly
- [ ] Text content filtering doesn't impact render performance
- [ ] No memory leaks with modal-based media preview
### Responsive Design
- [ ] All layouts adapt properly to mobile screens
- [ ] Video player maintains aspect ratio across screen sizes
- [ ] Pictures sidebar stacks properly on narrow screens
- [ ] Social media layout remains readable on all devices
## Success Criteria
### Primary Objectives
- [ ] **Social Media**: Single author header, AI summary at top, no show more button
- [ ] **Pictures**: PreviewMediaContent integration, separated multimedia/text content
- [ ] **Videos**: Full-size iframe player, text-only content descriptions
- [ ] **All Layouts**: Maintain existing functionality while fixing specific issues
### Quality Standards
- [ ] Zero regression in ArticleLayout functionality
- [ ] Factory pattern continues to work seamlessly
- [ ] All existing media handling features preserved
- [ ] Mobile responsive design maintained across layouts
- [ ] Performance impact minimal (under 5% bundle increase)
### User Experience Goals
- [ ] Cleaner social media content display without duplication
- [ ] Better large-screen video viewing experience
- [ ] Sophisticated image preview with PreviewMediaContent modal
- [ ] Consistent author information display patterns
- [ ] Improved content organization with AI summaries positioned logically
## Risk Mitigation
### Potential Issues
#### Component Dependencies
**Risk**: Changes to shared components (VideoPlayer, ContentBody) could affect other areas
**Mitigation**:
- Add new props with default values to maintain backward compatibility
- Test all existing entry list item displays
- Use feature flags if needed for gradual rollout
#### PreviewMediaContent Integration
**Risk**: Modal-based media preview might conflict with existing modal systems
**Mitigation**:
- Test modal stacking behavior thoroughly
- Ensure proper cleanup of modal state
- Verify keyboard navigation continues to work
#### Performance Impact
**Risk**: Additional modal components and media filtering might impact performance
**Mitigation**:
- Implement lazy loading for PreviewMediaContent modal
- Use React.memo for expensive components
- Profile render performance before and after changes
### Rollback Strategy
- Maintain existing layout components as backup
- Use git feature branches for each layout fix
- Implement progressive enhancement approach
- Test each layout individually before combining changes
## Additional Considerations
### Accessibility
- Ensure all interactive elements have proper ARIA labels
- Maintain keyboard navigation for new modal interactions
- Preserve screen reader compatibility for author headers
- Test video player controls with assistive technologies
### i18n Support
- All new text elements properly localized
- Layout adjustments tested with longer text languages
- RTL language support maintained
- Consistent translation keys across layout components
### Future Extensibility
- Pattern established for other media types (Audio layout)
- Plugin system compatibility maintained
- Theme system integration preserved
- Component reusability across different layout contexts
## Confidence Score: 9/10
This PRP provides a comprehensive fix approach with:
- ✅ **Specific Issue Analysis**: Detailed examination of exact problems and file locations
- ✅ **Targeted Solutions**: Precise fixes for each identified issue without over-engineering
- ✅ **Existing Pattern Leverage**: Uses proven components and patterns already in codebase
- ✅ **External Research**: Incorporates best practices for responsive video and content filtering
- ✅ **Implementation Roadmap**: Clear phase-based approach with specific file changes
- ✅ **Risk Management**: Identified potential issues with concrete mitigation strategies
- ✅ **Comprehensive Testing**: Detailed validation gates and success criteria
- ✅ **Backward Compatibility**: Maintains existing functionality while implementing fixes
High confidence because:
1. **Focused Scope**: Addresses specific reported issues without unnecessary system changes
2. **Proven Components**: Leverages existing PreviewMediaContent, AuthorHeader, and ContentBody components
3. **Pattern Following**: Mimics successful patterns from social-media-item.tsx and other working components
4. **External Validation**: Research confirms best practices for responsive video and content filtering
5. **Minimal Risk**: Changes are contained to specific layout files with clear rollback options
The implementation primarily involves connecting existing working components in better ways rather than building new complex systems, significantly reducing implementation complexity and risk.
-735
View File
@@ -1,735 +0,0 @@
# PRP: AI Summary Chat Integration for Enhanced User Engagement
## Overview
Transform the AI chat interface from a static welcome screen to a context-aware, engagement-focused experience by integrating AI summary as initial content. This enhancement automatically displays relevant entry summaries when users open the AI chat panel, providing zero-friction conversation starters and increasing AI feature adoption through progressive disclosure patterns.
## Current Implementation Analysis
### Current Chat Interface Architecture
**File**: `apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/ChatInterface.tsx`
**Current Flow**:
```typescript
// Conditional rendering based on message state
{!hasMessages && !isLoadingHistory ? (
<WelcomeScreen onSend={handleSendMessage} />
) : (
<ScrollArea>
<Messages />
{(status === "submitted" || status === "streaming") && <AIChatWaitingIndicator />}
</ScrollArea>
)}
```
**WelcomeScreen Structure** (`WelcomeScreen.tsx`):
```typescript
// Current static welcome screen
<div className="flex flex-1 flex-col items-center justify-center px-6">
<div className="w-full max-w-2xl space-y-8">
<div className="space-y-6 text-center">
<AISpline /> // 3D AI model
<h1>{APP_NAME} AI</h1> // Title
<p>{t("welcome_description")}</p> // Description
</div>
<div className="relative h-36 max-w-2xl" /> // Empty space
<div className="relative flex flex-wrap items-center justify-center gap-2">
{enabledShortcuts.map(...)} // Quick action shortcuts
{DEFAULT_SHORTCUTS.map(...)} // Default suggestions
</div>
</div>
</div>
```
### Existing AI Summary System
**Summary Store** (`packages/internal/store/src/modules/summary/store.ts`):
- **Data Structure**: `Record<entryId, Record<language, SummaryData>>`
- **Generation**: `summarySyncService.generateSummary()` with API integration
- **Hooks**: `useSummary()`, `usePrefetchSummary()`, `useSummaryStatus()`
- **Caching**: LRU cleanup with `lastAccessed` tracking
**Visual AISummary Component** (`apps/desktop/layer/renderer/src/modules/entry-content/AISummary.tsx`):
```typescript
// Beautiful glass-morphism design with animations
<div className={cn(
"group relative my-8 overflow-hidden rounded-2xl border border-neutral-200/50 p-5 backdrop-blur-xl",
"bg-gradient-to-b from-neutral-50/80 to-white/40 dark:from-neutral-900/80 dark:to-neutral-900/40",
"dark:border-neutral-800/50",
summary.isLoading && "animate-pulse with gradient shimmer"
)}>
<div className="flex items-center justify-between">
<div className="flex items-center gap-3">
<div className="center relative">
<i className="i-mgc-ai-cute-re text-lg with glow effect" />
</div>
<span className="bg-gradient-to-r bg-clip-text font-medium text-transparent">
{t("entry_content.ai_summary")}
</span>
</div>
{summary.data && <CopyButton />}
</div>
<AutoResizeHeight className="mt-4">
{summary.isLoading ? <SkeletonLoader /> : <Markdown>{summary.data}</Markdown>}
</AutoResizeHeight>
</div>
```
### Entry Context Integration
**Already Implemented** (`EntryContent.ai.tsx` lines 89-98):
```typescript
const { addOrUpdateBlock, removeBlock } = useBlockActions()
useEffect(() => {
addOrUpdateBlock({
id: BlockSliceAction.SPECIAL_TYPES.mainEntry,
type: "mainEntry",
value: entryId,
})
return () => {
removeBlock(BlockSliceAction.SPECIAL_TYPES.mainEntry)
}
}, [addOrUpdateBlock, entryId, removeBlock])
```
**Entry Context Retrieval** (`EntryPickers.tsx` lines 15-18):
```typescript
const mainEntryId = useAIChatStore()((s) => {
const block = s.blocks.find((b) => b.type === "mainEntry")
return block && block.type === "mainEntry" ? block.value : undefined
})
```
### Current Limitations
1. **Zero Context Awareness**: Welcome screen ignores available entry context and summary data
2. **Missed Engagement Opportunity**: Users must initiate conversation without any contextual prompts
3. **Disconnected Experience**: Rich summary data exists but isn't leveraged in chat interface
4. **Static Quick Actions**: Generic shortcuts instead of context-aware conversation starters
5. **Poor Progressive Disclosure**: No smooth transition from passive summary viewing to active conversation
## Proposed Solution
### Architecture Overview
Create a context-aware chat interface that intelligently displays entry summaries as conversation starters while maintaining the existing welcome screen for non-entry contexts. The solution leverages existing summary infrastructure and visual patterns while introducing smart progressive enhancement.
### Component Architecture
```typescript
// Enhanced WelcomeScreen with context awareness
const WelcomeScreen = ({ onSend }: WelcomeScreenProps) => {
const mainEntryId = useMainEntryId()
const hasEntryContext = !!mainEntryId
return (
<div className="flex flex-1 flex-col items-center justify-center px-6">
{hasEntryContext ? (
<EntrySummaryWelcome entryId={mainEntryId} onSend={onSend} />
) : (
<DefaultWelcome onSend={onSend} />
)}
</div>
)
}
```
### Core Components
#### 1. EntrySummaryCard Component
**File**: `apps/desktop/layer/renderer/src/modules/ai-chat/components/welcome/EntrySummaryCard.tsx`
**Purpose**: Display entry summary with chat-optimized styling and smart actions
```typescript
interface EntrySummaryCardProps {
entryId: string
onSend: (message: string) => void
className?: string
}
const EntrySummaryCard: React.FC<EntrySummaryCardProps> = ({ entryId, onSend, className }) => {
const actionLanguage = useActionLanguage()
const isInReadabilitySuccess = useEntryIsInReadabilitySuccess(entryId)
const summary = usePrefetchSummary({
entryId,
target: isInReadabilitySuccess ? "readabilityContent" : "content",
actionLanguage,
enabled: true,
})
const quickActions = useSmartQuickActions(summary.data, entryId)
return (
<m.div
initial={{ opacity: 0, y: 20, scale: 0.98 }}
animate={{ opacity: 1, y: 0, scale: 1 }}
transition={Spring.presets.smooth}
className={cn(
// Reuse AISummary visual patterns but optimized for chat context
"group relative w-full max-w-2xl overflow-hidden rounded-2xl border p-6 backdrop-blur-xl",
"bg-gradient-to-b from-neutral-50/80 to-white/40 dark:from-neutral-900/80 dark:to-neutral-900/40",
"border-neutral-200/50 dark:border-neutral-800/50",
"shadow-[0_8px_32px_rgba(0,0,0,0.08)] dark:shadow-[0_8px_32px_rgba(0,0,0,0.3)]",
summary.isLoading && "before:animate-shimmer",
className
)}
>
{/* Header with entry context */}
<div className="flex items-start justify-between mb-4">
<div className="flex items-center gap-3">
<div className="relative">
<i className="i-mgc-ai-cute-re text-lg text-purple-600 dark:text-purple-400" />
<div className="absolute inset-0 rounded-full blur-sm bg-purple-400/20 animate-pulse" />
</div>
<div>
<h3 className="font-medium text-text">AI Summary</h3>
<p className="text-xs text-text-secondary">Ready to discuss this entry</p>
</div>
</div>
<EntryQuickInfo entryId={entryId} />
</div>
{/* Summary Content */}
<AutoResizeHeight className="mb-6" spring>
{summary.isLoading ? (
<SummaryLoadingState />
) : summary.data ? (
<div className="space-y-3">
<Markdown className="prose-sm prose-p:m-0 max-w-none text-text-secondary leading-relaxed">
{String(summary.data)}
</Markdown>
</div>
) : (
<div className="text-center py-4">
<i className="i-mgc-document-cute-re text-2xl text-text-tertiary mb-2" />
<p className="text-sm text-text-secondary">Summary not available</p>
</div>
)}
</AutoResizeHeight>
{/* Smart Quick Actions */}
{summary.data && (
<div className="space-y-3">
<div className="text-xs font-medium text-text-tertiary uppercase tracking-wide">
Ask about this entry
</div>
<div className="flex flex-wrap gap-2">
{quickActions.map((action, index) => (
<m.button
key={action.id}
initial={{ opacity: 0, scale: 0.9 }}
animate={{ opacity: 1, scale: 1 }}
transition={{ delay: index * 0.1, ...Spring.presets.snappy }}
onClick={() => onSend(action.prompt)}
className={cn(
"inline-flex items-center gap-2 px-3 py-2 rounded-lg text-sm font-medium transition-all",
"bg-material-medium hover:bg-material-thick",
"border border-border/50 hover:border-border",
"text-text-secondary hover:text-text",
"hover:shadow-sm active:scale-95"
)}
>
<i className={`${action.icon} text-xs`} />
{action.label}
</m.button>
))}
</div>
</div>
)}
</m.div>
)
}
```
#### 2. Smart Quick Actions Generator
**File**: `apps/desktop/layer/renderer/src/modules/ai-chat/hooks/useSmartQuickActions.ts`
**Purpose**: Generate contextual conversation starters based on summary content and entry metadata
```typescript
interface QuickAction {
id: string
label: string
prompt: string
icon: string
priority: number
}
export const useSmartQuickActions = (
summaryData: string | null,
entryId: string,
): QuickAction[] => {
const entry = useEntry(entryId)
const { t } = useTranslation("ai")
return useMemo(() => {
if (!summaryData || !entry) return DEFAULT_ENTRY_ACTIONS
const actions: QuickAction[] = []
// Content-based actions
if (summaryData.length > 500) {
actions.push({
id: "simplify",
label: t("quick_actions.simplify"),
prompt: `Can you simplify this summary in 2-3 sentences? Focus on the main points.`,
icon: "i-mgc-edit-cute-re",
priority: 1,
})
}
// Entry type-based actions
if (entry.url) {
actions.push({
id: "discuss",
label: t("quick_actions.discuss"),
prompt: `What are the key insights from this article? What should I know?`,
icon: "i-mgc-chat-cute-re",
priority: 2,
})
}
// Always available actions
actions.push(
{
id: "questions",
label: t("quick_actions.questions"),
prompt: `What questions should I be asking about this content?`,
icon: "i-mgc-question-cute-re",
priority: 3,
},
{
id: "takeaways",
label: t("quick_actions.takeaways"),
prompt: `What are the most important takeaways from this entry?`,
icon: "i-mgc-star-cute-re",
priority: 4,
},
)
return actions.sort((a, b) => a.priority - b.priority).slice(0, 4)
}, [summaryData, entry, t])
}
const DEFAULT_ENTRY_ACTIONS: QuickAction[] = [
{
id: "analyze",
label: "Analyze this entry",
prompt: "Can you analyze this entry and tell me what it's about?",
icon: "i-mgc-search-cute-re",
priority: 1,
},
{
id: "explain",
label: "Explain key points",
prompt: "What are the key points I should understand from this entry?",
icon: "i-mgc-lightbulb-cute-re",
priority: 2,
},
]
```
#### 3. Enhanced WelcomeScreen with Context Awareness
**File**: `apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/WelcomeScreen.tsx` (Modified)
```typescript
export const WelcomeScreen = ({ onSend }: WelcomeScreenProps) => {
const { t } = useTranslation("ai")
const aiSettings = useAISettingValue()
const mainEntryId = useMainEntryId()
const settingModalPresent = useSettingModal()
const hasEntryContext = !!mainEntryId
const hasCustomPrompt = aiSettings.personalizePrompt?.trim()
const enabledShortcuts = aiSettings.shortcuts?.filter((shortcut) => shortcut.enabled) || []
return (
<div className="flex flex-1 flex-col items-center justify-center px-6">
<div className="w-full max-w-2xl space-y-8">
{/* Header Section - Always Present */}
<m.div
initial={{ opacity: 0, y: -20 }}
animate={{ opacity: 1, y: 0 }}
transition={Spring.presets.smooth}
className="space-y-6 text-center"
>
<div className="mx-auto size-16">
<AISpline />
</div>
<div className="flex flex-col gap-2">
<h1 className="text-text text-2xl font-semibold">{APP_NAME} AI</h1>
<p className="text-text-secondary text-balance text-sm">
{hasEntryContext ? t("welcome_description_contextual") : t("welcome_description")}
</p>
</div>
</m.div>
{/* Dynamic Content Area */}
<div className="relative min-h-[300px] flex items-center justify-center">
<AnimatePresence mode="wait">
{hasEntryContext ? (
<EntrySummaryCard
key="entry-summary"
entryId={mainEntryId}
onSend={onSend}
/>
) : (
<DefaultWelcomeContent
key="default-welcome"
onSend={onSend}
shortcuts={enabledShortcuts}
/>
)}
</AnimatePresence>
</div>
{/* Personal Prompt - Always at Bottom if Present */}
{hasCustomPrompt && (
<PersonalPromptDisplay
prompt={aiSettings.personalizePrompt}
onEdit={() => settingModalPresent("ai")}
/>
)}
</div>
</div>
)
}
```
### Data Flow Integration
#### Summary Prefetching Strategy
```typescript
// In ChatInterface.tsx - Prefetch summary when entry context available
const ChatInterfaceContent = () => {
const hasMessages = useHasMessages()
const mainEntryId = useMainEntryId()
const actionLanguage = useActionLanguage()
// Prefetch summary for context-aware welcome screen
usePrefetchSummary({
entryId: mainEntryId || "",
target: "content", // Start with content, fallback to readability if needed
actionLanguage,
enabled: !!mainEntryId && !hasMessages, // Only when showing welcome screen
})
// ... rest of component
}
```
#### State Management Integration
```typescript
// Custom hook for main entry context
export const useMainEntryId = (): string | undefined => {
return useAIChatStore()((state) => {
const block = state.blocks.find((b) => b.type === "mainEntry")
return block && block.type === "mainEntry" ? block.value : undefined
})
}
// Hook for entry summary in chat context
export const useEntrySummaryForChat = (entryId: string) => {
const actionLanguage = useActionLanguage()
const isInReadabilitySuccess = useEntryIsInReadabilitySuccess(entryId)
return usePrefetchSummary({
entryId,
target: isInReadabilitySuccess ? "readabilityContent" : "content",
actionLanguage,
enabled: !!entryId,
staleTime: 1000 * 60 * 60, // 1 hour - summaries don't change often
})
}
```
### Animation and Visual Design
#### Micro-interactions and Transitions
```typescript
// Smooth transitions between welcome states
const welcomeVariants = {
entryContext: {
initial: { opacity: 0, y: 30, scale: 0.95 },
animate: { opacity: 1, y: 0, scale: 1 },
exit: { opacity: 0, y: -30, scale: 0.95 },
},
defaultWelcome: {
initial: { opacity: 0, y: 20, scale: 0.98 },
animate: { opacity: 1, y: 0, scale: 1 },
exit: { opacity: 0, y: -20, scale: 0.98 },
},
}
// Quick action button animations
const quickActionVariants = {
initial: { opacity: 0, scale: 0.9, x: -10 },
animate: { opacity: 1, scale: 1, x: 0 },
hover: { scale: 1.02, y: -1 },
tap: { scale: 0.98 },
}
```
#### Consistent Design Language
- **Glass-morphism**: Reuse AISummary visual patterns with chat-optimized spacing
- **Purple Gradient**: Maintain AI branding with purple accent colors
- **Spring Animations**: Use Spring.presets.smooth for all major transitions
- **Material Colors**: UIKit material colors for consistent depth and hierarchy
- **Responsive Typography**: Scalable text that works across different panel sizes
## Implementation Plan
### Phase 1: Core Functionality (MVP)
#### Tasks (in order):
1. **Create EntrySummaryCard Component**
- File: `apps/desktop/layer/renderer/src/modules/ai-chat/components/welcome/EntrySummaryCard.tsx`
- Reuse AISummary visual patterns
- Basic summary display with loading states
- Simple click-to-start conversation
2. **Create useMainEntryId Hook**
- File: `apps/desktop/layer/renderer/src/modules/ai-chat/hooks/useMainEntryId.ts`
- Extract mainEntry block value from AI chat store
- Handle undefined/null states gracefully
3. **Modify WelcomeScreen Component**
- File: `apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/WelcomeScreen.tsx`
- Add conditional rendering based on entry context
- Integrate EntrySummaryCard component
- Maintain existing functionality for non-entry contexts
4. **Add Summary Prefetching to ChatInterface**
- File: `apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/ChatInterface.tsx`
- Prefetch summary when entry context available
- Only when welcome screen is showing (no messages)
5. **Basic Smart Quick Actions**
- File: `apps/desktop/layer/renderer/src/modules/ai-chat/hooks/useSmartQuickActions.ts`
- Simple content-based action generation
- Default fallback actions for all entries
6. **Update Translations**
- Add new translation keys for contextual descriptions
- Quick action labels and prompts
### Phase 2: UX Optimization
#### Tasks:
7. **Enhanced Smart Quick Actions**
- Content analysis for intelligent action generation
- Entry type detection (article, social media, video)
- Priority-based action sorting
8. **Micro-interaction Animations**
- Smooth state transitions with AnimatePresence
- Quick action button hover/tap effects
- Loading state animations with shimmer effects
9. **Entry Quick Info Component**
- Display entry metadata (title, source, date)
- Compact design that doesn't compete with summary
- Optional component based on space constraints
10. **Responsive Layout Adaptation**
- Floating panel vs fixed panel optimization
- Mobile-friendly touch targets
- Adaptive spacing and typography
### Phase 3: Advanced Features
#### Tasks:
11. **First-time User Guidance**
- Onboarding tooltip for new feature
- Progressive disclosure of advanced features
- User preference learning
12. **Context-aware Optimization**
- Reading progress integration
- Related entries suggestions
- Conversation history awareness
13. **Performance Optimization**
- Summary caching improvements
- Lazy loading for non-critical components
- Bundle size optimization
14. **A/B Testing Integration**
- Feature flag support
- Usage analytics
- Engagement metrics tracking
## Validation Gates
### Code Quality
```bash
# TypeScript compilation
pnpm run typecheck
# Linting
pnpm run lint
# Code formatting
pnpm run format
```
### Testing Strategy
```bash
# Unit tests for new hooks and components
pnpm run test apps/desktop/layer/renderer/src/modules/ai-chat
# Integration tests for summary prefetching
pnpm run test:integration
# E2E tests for chat interaction flows
pnpm run test:e2e -- --grep "AI Chat.*Summary"
```
### Manual Testing Checklist
- [ ] **Entry Context Detection**: AI chat shows summary when viewing an entry
- [ ] **Fallback Behavior**: Default welcome screen when no entry context
- [ ] **Summary Loading**: Proper loading states and error handling
- [ ] **Quick Actions**: Context-appropriate conversation starters
- [ ] **Animations**: Smooth transitions between states
- [ ] **Responsive Design**: Works in both floating and fixed panels
- [ ] **Theme Support**: Proper light/dark mode appearance
- [ ] **Accessibility**: Keyboard navigation and screen reader support
### Performance Metrics
- [ ] **First Paint**: Summary content visible within 300ms
- [ ] **Bundle Impact**: <10KB addition to chat module bundle
- [ ] **Memory Usage**: No memory leaks during context switches
- [ ] **Animation Performance**: 60fps during transitions
## Dependencies and Integration Points
### Existing Systems Integration
- **Summary Store**: `packages/internal/store/src/modules/summary/`
- **Entry Store**: Integration with entry context tracking
- **AI Chat Store**: Block system for entry context management
- **Translation System**: New keys for contextual content
- **Theme System**: UIKit colors and material design consistency
### External Dependencies
- **React Query**: Already used for summary prefetching
- **Framer Motion**: `m.` prefix components for animations
- **i18next**: Translation key expansion
- **Tailwind CSS**: UIKit color classes and material styles
### API Integration
- **Summary Generation**: Existing `/ai/summary` endpoint
- **No new API calls**: Reuses existing summary infrastructure
- **Caching Strategy**: Leverages existing SummaryStore LRU cache
## Risk Assessment & Mitigation
### Technical Risks
1. **Performance Impact** (Low Risk)
- _Risk_: Summary prefetching could slow chat opening
- _Mitigation_: Conditional prefetching only when needed, existing cache strategy
2. **Animation Jank** (Medium Risk)
- _Risk_: Complex animations could affect performance
- _Mitigation_: Use optimized Framer Motion patterns, test on lower-end devices
3. **State Synchronization** (Low Risk)
- _Risk_: Entry context out of sync with chat store
- _Mitigation_: Leverage existing mainEntry block system, tested pattern
### UX Risks
1. **Feature Discoverability** (Medium Risk)
- _Risk_: Users may not notice the enhanced welcome screen
- _Mitigation_: Subtle onboarding hints, analytics tracking
2. **Context Mismatch** (Low Risk)
- _Risk_: Summary doesn't match user expectations
- _Mitigation_: Clear visual hierarchy, fallback to default actions
3. **Information Overload** (Medium Risk)
- _Risk_: Too much information in welcome screen
- _Mitigation_: Progressive disclosure, clean visual design
## Success Metrics
### Engagement Metrics
- **AI Chat Adoption**: 25% increase in chat panel opens from entry context
- **Conversation Initiation**: 40% increase in messages sent from welcome screen
- **Quick Action Usage**: 60% of conversations start with context-aware quick actions
- **Session Duration**: 20% increase in average chat session length
### Performance Metrics
- **Load Time**: Summary content visible within 300ms
- **Error Rate**: <1% failure rate for summary loading
- **Cache Hit Rate**: >80% cache hits for recently viewed entries
### User Satisfaction
- **User Feedback**: Positive sentiment on enhanced chat experience
- **Feature Retention**: 70% of users who try the feature continue using it
- **Support Tickets**: No increase in AI-related support requests
## Future Enhancements
### Short-term (Next Quarter)
- **Multi-language Summary Support**: Leverage existing i18n infrastructure
- **Summary Quality Feedback**: Allow users to rate summary relevance
- **Conversation Templates**: Pre-built conversation flows for common entry types
### Medium-term (Next 6 Months)
- **Cross-entry Conversations**: Enable discussing multiple entries in one chat
- **Smart Follow-ups**: AI-suggested next questions based on conversation context
- **Entry Annotations**: Allow highlighting specific parts of entry for discussion
### Long-term (Next Year)
- **Voice Interaction**: Voice commands for summary-based conversations
- **Collaborative Features**: Share AI conversations about entries
- **Advanced Analytics**: ML-driven insights on conversation patterns
## Confidence Score: 9/10
This PRP provides comprehensive implementation guidance with:
- ✅ **Detailed Architecture**: Clear component structure and data flow
- ✅ **Existing Pattern Reuse**: Leverages proven AISummary and chat patterns
- ✅ **Phased Implementation**: Incremental delivery with clear milestones
- ✅ **Risk Mitigation**: Identified potential issues with solutions
- ✅ **Testing Strategy**: Comprehensive validation approach
- ✅ **Performance Considerations**: Optimized prefetching and caching
- ✅ **UX Best Practices**: Context-aware design with progressive enhancement
- ✅ **Code Examples**: Realistic implementation snippets with proper patterns
- ✅ **Integration Points**: Clear dependencies and system boundaries
- ✅ **Success Metrics**: Measurable outcomes and validation criteria
The implementation leverages existing, proven infrastructure while introducing meaningful enhancements that align with modern AI chat UX patterns and the application's design system.
@@ -1,617 +0,0 @@
# Android SharedWebView with Image Interception Implementation
## Objective
Implement an Android equivalent of the iOS SharedWebView module with advanced image interception capabilities using WebView hooks instead of custom URL schemes. This will provide feature parity between iOS and Android platforms while leveraging Android's superior request interception capabilities.
## Context
The iOS implementation uses a custom URL scheme (`follow-image://`) to intercept image requests due to WKWebView limitations. Android WebView offers more powerful request interception through `WebViewClient.shouldInterceptRequest()`, allowing for a more elegant and performant solution.
### Current iOS Architecture (Reference)
- **SharedWebViewModule** (apps/mobile/native/ios/Modules/SharedWebView/SharedWebViewModule.swift)
- **WebViewManager** (apps/mobile/native/ios/Modules/SharedWebView/WebViewManager.swift) - Singleton with lifecycle management
- **FOWebView** (apps/mobile/native/ios/Modules/SharedWebView/FOWebView.swift) - Custom WKWebView
- **FollowImageURLSchemeHandler** (apps/mobile/native/ios/Modules/SharedWebView/FollowImageURLSchemeHandler.swift) - Custom scheme handler
- **WebViewState** (apps/mobile/native/ios/Modules/SharedWebView/WebViewState.swift) - Observable state management
### Existing Android Infrastructure
- **Module Path**: `apps/mobile/native/android/src/main/java/expo/modules/follownative/`
- **Build Configuration**: Standard Expo modules with Kotlin support
- **Naming Convention**: `expo.modules.follownative.modulename.ModuleName`
- **TypeScript Interface**: Already defined in `apps/mobile/src/components/native/webview/index.ts`
## Implementation Requirements
### Core Components to Implement
1. **SharedWebViewModule.kt** - Main Expo module exposing API to React Native
2. **WebViewManager.kt** - Singleton manager for WebView lifecycle and state
3. **SharedWebViewView.kt** - Expo view component
4. **FOWebView.kt** - Custom WebView with image interception
5. **ImageInterceptClient.kt** - WebViewClient with request interception
6. **ImageCache.kt** - Memory and disk caching system
7. **WebViewState.kt** - Reactive state management with StateFlow
8. **BridgeData.kt** - Message payloads and type definitions
### API Compatibility Requirements
Maintain 100% compatibility with existing TypeScript interface:
```typescript
interface ISharedWebViewModule
extends NativeModule<{
onContentHeightChanged: ({ height }: { height: number }) => void
onImagePreview: (event: ImagePreviewEvent) => void
onSeekAudio?: (e: { time: number }) => void
}> {
load(url: string): void
evaluateJavaScript(js: string): void
dispatch?(type: string, payload?: string): void
// Debug helpers
getDebugState?(): WebViewDebugState
destroyForDebug?(): void
reloadLastURL?(): void
flushQueue?(): void
}
```
## Technical Architecture
### Image Interception Strategy (Android Advantage)
**iOS Approach**: Custom URL scheme with JavaScript injection
```swift
// JavaScript injection to rewrite image URLs
url.replace(/^https?:/, 'follow-image:')
// Custom WKURLSchemeHandler for follow-image://
```
**Android Approach**: Native request interception (Superior)
```kotlin
override fun shouldInterceptRequest(view: WebView?, request: WebResourceRequest?): WebResourceResponse? {
if (isImageRequest(request)) {
return handleImageRequest(request)
}
return super.shouldInterceptRequest(view, request)
}
```
### Implementation Blueprint
#### Phase 1: Core Infrastructure (Priority 1)
```kotlin
// 1. SharedWebViewModule.kt
@ExpoModule(name = "FOSharedWebView")
class SharedWebViewModule : Module() {
private val coroutineScope = CoroutineScope(Dispatchers.Main + SupervisorJob())
override fun definition() = ModuleDefinition {
Name("FOSharedWebView")
Function("load") { urlString: String ->
WebViewManager.load(urlString)
}
Function("evaluateJavaScript") { js: String ->
WebViewManager.evaluateJavaScript(js)
}
Function("dispatch") { type: String, payload: String? ->
WebViewManager.dispatch(type, payload)
}
View(SharedWebViewView::class) {
Events("onContentHeightChange", "onSeekAudio")
Prop("url") { view: SharedWebViewView, url: String ->
WebViewManager.load(url)
}
}
Events("onContentHeightChanged", "onImagePreview", "onSeekAudio")
OnCreate {
WebViewManager.initializeLifecycleObservers(appContext.currentActivity!!)
}
OnStartObserving {
// StateFlow subscriptions for reactive events
WebViewManager.state.contentHeight.onEach { height ->
sendEvent("onContentHeightChanged", mapOf("height" to height))
}.launchIn(coroutineScope)
}
OnStopObserving {
coroutineScope.cancel()
}
// Debug functions
Function("getDebugState") { WebViewManager.getDebugState() }
Function("destroyForDebug") { WebViewManager.destroyForDebug() }
Function("reloadLastURL") { WebViewManager.reloadLastURL() }
Function("flushQueue") { WebViewManager.flushQueue() }
}
}
```
```kotlin
// 2. WebViewManager.kt - Singleton with lifecycle management
object WebViewManager {
val state = WebViewState()
private var sharedWebView: FOWebView? = null
private var currentHost: ViewGroup? = null
private var isReady = false
private val pendingScripts = mutableListOf<String>()
private var lastUrl: String? = null
private val lastState = mutableMapOf<String, Any>()
fun initializeLifecycleObservers(activity: Activity) {
val observer = object : DefaultLifecycleObserver {
override fun onPause(owner: LifecycleOwner) { onEnterBackground() }
override fun onResume(owner: LifecycleOwner) { onEnterForeground() }
}
(activity as ComponentActivity).lifecycle.addObserver(observer)
}
fun load(urlString: String) {
MainScope().launch {
lastUrl = urlString
val webView = getOrCreateWebView()
if (webView.url == urlString && !isLoading(webView)) return@launch
isReady = false
webView.loadUrl(urlString)
}
}
fun attach(host: ViewGroup) {
MainScope().launch {
val webView = getOrCreateWebView()
(webView.parent as? ViewGroup)?.removeView(webView)
host.addView(webView)
currentHost = host
}
}
private fun getOrCreateWebView(): FOWebView {
return sharedWebView ?: FOWebView(context, state).also { sharedWebView = it }
}
private fun onEnterBackground() {
if (currentHost == null) {
MainScope().launch {
delay(3000)
if (currentHost == null) destroyWebView()
}
}
}
private fun onEnterForeground() {
if (sharedWebView == null) {
getOrCreateWebView()
lastUrl?.let { load(it) }
replayState()
}
}
}
```
#### Phase 2: Image Interception System (Priority 1)
```kotlin
// 3. ImageInterceptClient.kt - Advanced request interception
class ImageInterceptClient(
private val imageCache: ImageCache,
private val baseClient: WebViewClient? = null
) : WebViewClient() {
companion object {
private val IMAGE_MIME_TYPES = setOf(
"image/jpeg", "image/jpg", "image/png", "image/gif",
"image/webp", "image/svg+xml", "image/avif"
)
}
override fun shouldInterceptRequest(
view: WebView?,
request: WebResourceRequest?
): WebResourceResponse? {
val url = request?.url?.toString() ?: return super.shouldInterceptRequest(view, request)
if (!isImageRequest(request)) {
return baseClient?.shouldInterceptRequest(view, request)
?: super.shouldInterceptRequest(view, request)
}
return handleImageRequest(view, request)
}
private fun isImageRequest(request: WebResourceRequest): Boolean {
val url = request.url.toString()
val acceptHeader = request.requestHeaders["Accept"] ?: ""
// Multi-strategy detection
return acceptHeader.contains("image/") ||
url.substringAfterLast('.', "").lowercase() in IMAGE_EXTENSIONS ||
url.contains(Regex("/(images?|img|pics?|photos?|assets)/", RegexOption.IGNORE_CASE))
}
private fun handleImageRequest(
view: WebView?,
request: WebResourceRequest
): WebResourceResponse? {
val url = request.url.toString()
val cacheKey = url
// Check cache first
imageCache.get(cacheKey)?.let { cachedData ->
return createImageResponse(cachedData, detectMimeType(cachedData))
}
// Network request with proper headers
return try {
val modifiedRequest = buildImageRequest(request)
val response = executeImageRequest(modifiedRequest)
response?.let { (data, mimeType) ->
imageCache.put(cacheKey, data)
createImageResponse(data, mimeType)
}
} catch (e: Exception) {
Log.w("ImageIntercept", "Failed to load image: $url", e)
null // Fallback to default WebView behavior
}
}
private fun buildImageRequest(original: WebResourceRequest): HttpURLConnection {
val connection = URL(original.url.toString()).openConnection() as HttpURLConnection
// Copy original headers
original.requestHeaders.forEach { (key, value) ->
if (!isRestrictedHeader(key)) {
connection.setRequestProperty(key, value)
}
}
// Optimize for images
connection.setRequestProperty("Accept", "image/webp,image/avif,image/*,*/*;q=0.8")
connection.setRequestProperty("User-Agent",
"Mozilla/5.0 (Linux; Android 12) AppleWebKit/537.36 Mobile Safari/537.36")
// Set referer for CORS compatibility
original.url.let { url ->
val referer = "${url.scheme}://${url.host}"
connection.setRequestProperty("Referer", referer)
}
connection.connectTimeout = 10000
connection.readTimeout = 15000
return connection
}
private fun createImageResponse(data: ByteArray, mimeType: String): WebResourceResponse {
val headers = mapOf(
"Access-Control-Allow-Origin" to "*",
"Cache-Control" to "public, max-age=3600",
"Content-Length" to data.size.toString()
)
return WebResourceResponse(mimeType, "utf-8", 200, "OK", headers, ByteArrayInputStream(data))
}
}
```
```kotlin
// 4. ImageCache.kt - High-performance caching system
class ImageCache(private val context: Context) {
private val memoryCache = LruCache<String, ByteArray>(16 * 1024 * 1024) // 16MB
private val diskCacheDir = File(context.cacheDir, "webview_images")
init {
if (!diskCacheDir.exists()) diskCacheDir.mkdirs()
}
fun get(key: String): ByteArray? {
// Memory first, then disk
return memoryCache.get(key) ?: getDiskCache(key)?.also {
memoryCache.put(key, it)
}
}
fun put(key: String, data: ByteArray) {
memoryCache.put(key, data)
putDiskCache(key, data)
}
private fun getDiskCache(key: String): ByteArray? = try {
val file = getCacheFile(key)
if (file.exists() && System.currentTimeMillis() - file.lastModified() < 24 * 60 * 60 * 1000) {
file.readBytes()
} else null
} catch (e: Exception) { null }
private fun putDiskCache(key: String, data: ByteArray) {
try {
getCacheFile(key).writeBytes(data)
} catch (e: Exception) {
Log.w("ImageCache", "Failed to cache image", e)
}
}
private fun getCacheFile(key: String): File {
val fileName = key.hashCode().toString(16) + ".cache"
return File(diskCacheDir, fileName)
}
}
```
#### Phase 3: State Management and Views (Priority 2)
```kotlin
// 5. WebViewState.kt - Reactive state management
class WebViewState {
private val _contentHeight = MutableStateFlow(Resources.getSystem().displayMetrics.heightPixels.toFloat())
val contentHeight: StateFlow<Float> = _contentHeight.asStateFlow()
private val _imagePreviewEvent = MutableStateFlow<ImagePreviewEvent?>(null)
val imagePreviewEvent: StateFlow<ImagePreviewEvent?> = _imagePreviewEvent.asStateFlow()
private val _audioSeekEvent = MutableStateFlow<AudioSeekEvent?>(null)
val audioSeekEvent: StateFlow<AudioSeekEvent?> = _audioSeekEvent.asStateFlow()
fun updateContentHeight(height: Float) { _contentHeight.value = height }
fun triggerImagePreview(urls: List<String>, index: Int) {
_imagePreviewEvent.value = ImagePreviewEvent(urls, index)
}
fun triggerAudioSeek(time: Double) {
_audioSeekEvent.value = AudioSeekEvent(time)
}
}
data class ImagePreviewEvent(val imageUrls: List<String>, val index: Int)
data class AudioSeekEvent(val time: Double)
```
```kotlin
// 6. FOWebView.kt - Custom WebView implementation
class FOWebView(context: Context, private val state: WebViewState) : WebView(context) {
private val imageCache = ImageCache(context)
private val baseWebViewClient = FOWebViewClient()
private val javascriptInterface = JavaScriptInterface(state)
init {
setupWebView()
webViewClient = ImageInterceptClient(imageCache, baseWebViewClient)
webChromeClient = FOWebChromeClient()
addJavaScriptInterface(javascriptInterface, "Android")
}
private fun setupWebView() {
settings.apply {
javaScriptEnabled = true
domStorageEnabled = true
allowFileAccess = true
allowContentAccess = true
loadsImagesAutomatically = true
blockNetworkImage = false
cacheMode = WebSettings.LOAD_DEFAULT
setAppCacheEnabled(true)
}
// Inject JavaScript bridge
injectBridgeScript()
}
private fun injectBridgeScript() {
val script = """
;(() => {
window.__RN__ = true
function send(data) {
Android.postMessage(JSON.stringify(data))
}
window.bridge = {
measure: () => send({ type: "measure" }),
setContentHeight: (height) => send({ type: "setContentHeight", payload: height }),
previewImage: (data) => send({ type: "previewImage", payload: data }),
seekAudio: (time) => send({ type: "audio:seekTo", payload: { time } })
}
// Signal readiness
document.addEventListener("DOMContentLoaded", () => {
send({ type: "ready" })
})
})()
"""
evaluateJavascript(script, null)
}
fun clearImageCache() { imageCache.clear() }
}
```
#### Phase 4: Integration and Testing (Priority 3)
### File Structure to Create
```
apps/mobile/native/android/src/main/java/expo/modules/follownative/sharedwebview/
├── SharedWebViewModule.kt # Main Expo module
├── SharedWebViewView.kt # Expo view component
├── WebViewManager.kt # Singleton WebView manager
├── FOWebView.kt # Custom WebView implementation
├── ImageInterceptClient.kt # Request interception logic
├── ImageCache.kt # Caching system
├── WebViewState.kt # State management
├── BridgeData.kt # Message payloads
└── JavaScriptInterface.kt # WebView-to-native bridge
```
### Configuration Updates Required
1. **expo-module.config.json** - Add new Android module:
```json
{
"android": {
"modules": [
"expo.modules.follownative.sharedwebview.SharedWebViewModule"
// ... existing modules
]
}
}
```
2. **Android Gradle Dependencies** - Add to `apps/mobile/native/android/build.gradle`:
```gradle
dependencies {
implementation "androidx.lifecycle:lifecycle-runtime-ktx:2.8.6"
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.9.0"
}
```
## Implementation Tasks
### Phase 1: Core Infrastructure (Week 1)
1. Create module structure and base classes
2. Implement SharedWebViewModule.kt with Expo module definition
3. Implement WebViewManager.kt singleton with lifecycle management
4. Implement WebViewState.kt with StateFlow-based reactive state
5. Create basic SharedWebViewView.kt Expo view component
### Phase 2: Image Interception System (Week 1-2)
1. Implement ImageInterceptClient.kt with shouldInterceptRequest logic
2. Build ImageCache.kt with memory and disk caching
3. Create image request detection and classification system
4. Implement network request handling with proper headers
5. Add MIME type detection and response creation
### Phase 3: WebView Integration (Week 2)
1. Implement FOWebView.kt custom WebView
2. Create JavaScriptInterface.kt for native-JS communication
3. Add JavaScript bridge injection and message handling
4. Implement content height tracking and layout updates
5. Add debug utilities and state inspection tools
### Phase 4: Testing and Integration (Week 2-3)
1. Create comprehensive unit tests for each component
2. Implement integration tests with mock WebView scenarios
3. Add performance tests for image caching and request interception
4. Test cross-platform API compatibility with iOS implementation
5. Validate memory management and lifecycle behavior
### Phase 5: Documentation and Deployment (Week 3)
1. Update expo-module.config.json with new Android module
2. Add necessary Gradle dependencies and configurations
3. Create comprehensive documentation for the implementation
4. Update TypeScript definitions if needed
5. Perform final testing and validation
## Validation Gates
### Build Validation
```bash
cd apps/mobile/native/android
./gradlew assembleDebug
```
### Code Quality Checks
```bash
cd apps/mobile
npm run typecheck
```
### Functional Testing
```bash
# Test module loading
adb logcat | grep "FOSharedWebView"
# Test image interception
# Navigate to image-heavy content and verify cache behavior
```
### Performance Testing
```kotlin
// Measure image cache hit rates and memory usage
WebViewManager.getImageCacheStats().let { stats ->
assertTrue("Cache hit rate should be > 80%", stats.hitRate > 0.8)
assertTrue("Memory usage should be < 50MB", stats.memoryUsage < 50 * 1024 * 1024)
}
```
### Cross-Platform Compatibility Testing
```javascript
// Verify identical API behavior across platforms
const debugState = await SharedWebViewModule.getDebugState()
expect(debugState).toHaveProperty("hasWebView")
expect(debugState).toHaveProperty("contentHeight")
```
## Documentation and References
### Essential References
- [Expo Modules API Documentation](https://docs.expo.dev/modules/overview/)
- [Native View Tutorial](https://docs.expo.dev/modules/native-view-tutorial/)
- [Android WebView Request Interception](https://medium.com/@pouryarezaee76/intercepting-requests-in-android-webview-8eb628b32f2a)
- [WebView Security Best Practices](https://blog.oversecured.com/Android-Exploring-vulnerabilities-in-WebResourceResponse/)
### Key Implementation Files to Reference
- `apps/mobile/native/ios/Modules/SharedWebView/` - Complete iOS implementation
- `apps/mobile/native/android/src/main/java/expo/modules/follownative/FollowNativeModule.kt` - Existing module patterns
- `apps/mobile/src/components/native/webview/index.ts` - TypeScript API interface
### Critical Security Considerations
1. **Request Validation**: Always validate URLs before processing to prevent malicious requests
2. **Header Sanitization**: Filter restricted headers to prevent security vulnerabilities
3. **File Access Limiting**: Restrict file:// URL access to app bundle resources only
4. **Content Security**: Implement proper CSP headers for loaded content
5. **Bridge Data Validation**: Validate all JavaScript bridge message payloads
## Expected Outcomes
### Performance Improvements over iOS
- **No URL Rewriting Overhead**: Direct request interception vs. JavaScript URL manipulation
- **Better Error Handling**: Graceful fallback to default WebView behavior on failure
- **Enhanced Debugging**: Standard HTTP request debugging vs. custom scheme debugging
- **Improved Reliability**: No dependency on JavaScript injection success
### Feature Parity Achievement
- 100% API compatibility with iOS implementation
- Identical event handling and state management
- Same debugging capabilities and state inspection tools
- Consistent caching behavior and memory management
### Success Metrics
- Image cache hit rate > 90%
- Memory usage < 64MB for typical usage
- Zero crashes related to WebView lifecycle management
- API response time < 50ms for cached resources
- Cross-platform test suite passing rate > 99%
## Confidence Score: 9/10
This PRP provides comprehensive context, detailed implementation blueprints, existing code patterns to follow, specific file references, security considerations, and executable validation gates. The Android implementation leverages superior platform capabilities while maintaining complete API compatibility with iOS. All necessary technical context, external documentation, and testing patterns are included to enable successful one-pass implementation.
@@ -1,938 +0,0 @@
name: "Enhanced AI Usage Observability Frontend"
description: |
Frontend implementation for enhanced AI token usage observability with real-time
tracking, predictive analytics, and user-centered visualizations. Integrates with
the backend API from enhanced-ai-usage-observability.md to provide comprehensive
usage insights in both AI settings tab and dedicated analytics page.
## Purpose
Implement comprehensive React-based frontend for AI usage observability that transforms raw token statistics into actionable user insights through intuitive visualizations, real-time feedback, and predictive warnings.
## Core Principles
1. **Component Reusability**: Build modular components following Follow's SettingBuilder patterns
2. **Real-time Updates**: Use React Query for efficient data synchronization and caching
3. **Progressive Disclosure**: Simple overview in AI tab, detailed analysis in separate page
4. **Visual Clarity**: Use charts and progress indicators for immediate comprehension
5. **Mobile Responsive**: Ensure consistent experience across desktop and mobile
---
## Goal
Create React frontend components that consume enhanced AI usage analytics APIs to provide users with real-time session tracking, usage pattern insights, predictive warnings, and optimization recommendations through intuitive visualizations.
## Why
- **User Empowerment**: Transform technical token counts into actionable usage insights
- **Cost Awareness**: Provide real-time feedback on current session costs and efficiency
- **Proactive Management**: Warn users before hitting rate limits through predictive analytics
- **Usage Optimization**: Help users understand and optimize their AI consumption patterns
- **Seamless Integration**: Integrate naturally into existing AI settings workflow
## What
Frontend implementation with:
1. **AI Tab Integration**: Compact usage analysis section in AI settings
2. **Detailed Analytics Page**: Enhanced token-usage page with comprehensive charts
3. **Real-Time Tracking**: Live session usage and progress indicators
4. **Predictive Warnings**: Visual alerts for approaching rate limits
5. **Usage Visualizations**: Charts for trends, feature distribution, and model efficiency
### Success Criteria
- [ ] AI Tab shows simplified usage overview with key metrics and warnings
- [ ] Token usage page displays comprehensive analytics with interactive charts
- [ ] Real-time session tracking updates every 10 seconds
- [ ] Predictive warnings appear when rate limit risk is detected
- [ ] Charts render usage patterns, feature distribution, and efficiency comparisons
- [ ] Mobile responsive design maintains usability on smaller screens
- [ ] Components follow existing Follow UI patterns and design system
- [ ] All user-facing text is properly internationalized
## All Needed Context
### Documentation & References
```yaml
# MUST READ - Include these in your context window
- file: apps/desktop/layer/renderer/src/modules/settings/tabs/ai.tsx
why: Current AI settings page structure and SettingBuilder pattern
- file: apps/desktop/layer/renderer/src/modules/settings/tabs/token-usage.tsx
why: Existing token usage component to enhance and reference
- file: apps/desktop/layer/renderer/src/modules/ai-task/query.ts
why: React Query patterns and query key hierarchies used in Follow
- file: apps/desktop/layer/renderer/src/modules/settings/tabs/ai/mcp/MCPServicesSection.tsx
why: Component structure patterns, useQuery usage, error handling
- file: apps/desktop/layer/renderer/src/modules/settings/tabs/ai/PanelStyleSection.tsx
why: SettingTabbedSegment usage and section component patterns
- file: packages/internal/components/src/ui/progress/index.tsx
why: Progress component for usage indicators
- file: apps/desktop/layer/renderer/src/lib/api-client.ts
why: followClient usage and API integration patterns
- doc: https://recharts.org/en-US/api
section: LineChart, PieChart, BarChart components
critical: Follow doesn't have charting library - need to add recharts
- doc: https://tanstack.com/query/latest/docs/framework/react/guides/query-keys
section: Query key hierarchies and best practices
critical: Follow uses hierarchical query keys pattern
- doc: https://react-i18next.com/latest/using-with-hooks
section: useTranslation hook usage
critical: All user-facing text must be internationalized
```
### Current Codebase tree
```bash
apps/desktop/layer/renderer/src/modules/settings/tabs/
├── ai.tsx # Main AI settings page with SettingBuilder
├── token-usage.tsx # Current token usage implementation
└── ai/
├── index.ts # Exports AI-related components
├── PanelStyleSection.tsx # Example section component pattern
├── PersonalizePromptSection.tsx # Example section component pattern
└── mcp/MCPServicesSection.tsx # Complex section with React Query
apps/desktop/layer/renderer/src/modules/ai-task/
└── query.ts # React Query patterns and conventions
packages/internal/components/src/ui/
├── progress/index.tsx # Progress bars and indicators
├── card/index.tsx # Card containers
├── tabs/index.tsx # Tab navigation
└── [other UI components...]
```
### Desired Codebase tree with files to be added and responsibility
```bash
apps/desktop/layer/renderer/src/modules/settings/tabs/
├── ai.tsx # MODIFIED: Add UsageAnalysisSection
├── token-usage.tsx # MODIFIED: Enhanced with analytics
└── ai/
├── index.ts # MODIFIED: Export new usage components
└── usage/ # NEW: Usage observability components
├── UsageAnalysisSection.tsx # AI tab simplified usage overview
├── hooks/
│ ├── useEnhancedTokenUsage.ts # Enhanced config API hook
│ ├── useUsageAnalytics.ts # Analytics API hook
│ ├── useSessionTracking.ts # Session tracking hook
│ └── index.ts # Hook exports
└── components/
├── UsageProgressRing.tsx # Circular progress component
├── SessionStatusCard.tsx # Active session display
├── UsageWarningBanner.tsx # Predictive warning alerts
├── QuickInsights.tsx # Key metrics display
└── index.ts # Component exports
apps/desktop/layer/renderer/src/modules/settings/tabs/token-usage/
├── index.tsx # MODIFIED: Export enhanced components
├── TokenUsageEnhanced.tsx # NEW: Enhanced analytics page
├── components/
│ ├── UsageTrendChart.tsx # Line chart for usage trends
│ ├── FeatureDistributionChart.tsx # Pie chart for feature breakdown
│ ├── ModelEfficiencyChart.tsx # Bar chart for model comparison
│ ├── TimePatternAnalysis.tsx # Time-based usage patterns
│ ├── PredictiveInsights.tsx # Insights and recommendations
│ ├── RealTimeMetrics.tsx # Live usage dashboard
│ └── index.ts # Chart component exports
└── styles/
└── charts.module.css # Chart-specific styles
apps/desktop/layer/renderer/src/queries/
└── ai-analytics.ts # NEW: Centralized analytics query logic
```
### Known Gotchas of our codebase & Library Quirks
```typescript
// CRITICAL: Project-specific patterns and constraints
// REACT_QUERY: Use hierarchical query keys following aiTaskKeys pattern
// REACT_QUERY: Extract data with data?.data pattern, handle loading/error states
// REACT_QUERY: Use proper cache invalidation on mutations
// COMPONENTS: Import UI components from @follow/components/ui/*
// COMPONENTS: Use SettingBuilder for settings pages, SettingTabbedSegment for options
// API: Use followClient.api.* pattern, not direct fetch
// I18N: All user-facing strings must use useTranslation hook
// STYLING: Use Tailwind with UIKit colors (text-text, bg-fill, etc.)
// STYLING: Follow mobile-first responsive design patterns
// ICONS: Use i-mgc-* prefix for MingCute icons, i-mingcute-* as fallback
// MOTION: Use m. instead of motion. for Framer Motion components
// CHARTS: No existing chart library - need to add recharts to dependencies
// MODALS: Use useDialog and useModalStack for modal interactions
// TOASTS: Use toast from "sonner" for notifications
// STATE: Settings state managed through Jotai atoms
// ROUTES: Use React Router Link for navigation
// ERROR_HANDLING: Follow existing error boundary patterns
```
## Implementation Blueprint
### Data models and structure
Enhanced React Query hooks and TypeScript interfaces:
```typescript
// apps/desktop/layer/renderer/src/modules/settings/tabs/ai/usage/hooks/useEnhancedTokenUsage.ts
export interface EnhancedTokenUsage {
defaultModel: string
availableModels: string[]
modelBillingStrategy: Record<string, number>
rateLimit: {
maxTokens: number
currentTokens: number
remainingTokens: number
windowDuration: number
windowResetTime: number
// Enhanced fields
usageRate: number
projectedLimitTime: number | null
warningLevel: "safe" | "moderate" | "high" | "critical"
}
usage: {
total: number
used: number
remaining: number
resetAt: string
// Enhanced fields
avgTokensPerSession: number
avgSessionDuration: number
mostUsedFeature: string
efficiencyScore: number
}
currentSession: {
sessionId: string | null
tokensUsed: number
messageCount: number
duration: number
isActive: boolean
}
usageHistory: Array<{
id: string
createdAt: Date
changes: number
comment: string | null
operationType: string | null
modelUsed: string | null
sessionId: string | null
}>
}
// apps/desktop/layer/renderer/src/modules/settings/tabs/ai/usage/hooks/useUsageAnalytics.ts
export interface UsageAnalytics {
patterns: {
daily: Array<{
date: string
totalTokens: number
operationCount: number
peakHour: number | null
}>
byOperation: Array<{
operationType: string
totalTokens: number
operationCount: number
percentage: number
avgTokensPerOperation: number
}>
byModel: Array<{
model: string
totalTokens: number
operationCount: number
percentage: number
avgEfficiency: number
}>
}
insights: {
usageTrend: "increasing" | "decreasing" | "stable"
projectedMonthlyUsage: number
recommendations: string[]
efficiencyTips: string[]
}
timePatterns: {
peakHours: number[]
peakDays: number[]
avgSessionDuration: number
avgTokensPerSession: number
}
}
// Query keys following aiTaskKeys pattern
export const aiAnalyticsKeys = {
all: ["ai-analytics"] as const,
config: () => [...aiAnalyticsKeys.all, "config"] as const,
analytics: () => [...aiAnalyticsKeys.all, "analytics"] as const,
analyticsWithDays: (days: number) => [...aiAnalyticsKeys.analytics(), days] as const,
session: () => [...aiAnalyticsKeys.all, "session"] as const,
sessionCurrent: () => [...aiAnalyticsKeys.session(), "current"] as const,
}
```
### List of tasks to be completed to fulfill the PRP in the order they should be completed
```yaml
Task 1: Add recharts dependency for data visualization
MODIFY package.json (apps/desktop/):
- ADD "recharts": "^2.10.0" to dependencies
- RUN pnpm install to install charting library
Task 2: Create AI analytics query hooks
CREATE apps/desktop/layer/renderer/src/queries/ai-analytics.ts:
- IMPLEMENT hierarchical query keys following aiTaskKeys pattern
- EXPORT useEnhancedTokenUsage, useUsageAnalytics, useSessionTracking hooks
- USE followClient.api pattern for API calls
- HANDLE loading states and error cases
Task 3: Create usage progress ring component
CREATE apps/desktop/layer/renderer/src/modules/settings/tabs/ai/usage/components/UsageProgressRing.tsx:
- IMPLEMENT circular SVG progress indicator
- SUPPORT different sizes (sm/md/lg) and color coding
- FOLLOW UIKit color system for status indication
Task 4: Create session status components
CREATE apps/desktop/layer/renderer/src/modules/settings/tabs/ai/usage/components/SessionStatusCard.tsx:
- DISPLAY active session information when available
- SHOW real-time token usage and message count
- USE card component from @follow/components/ui/card
CREATE apps/desktop/layer/renderer/src/modules/settings/tabs/ai/usage/components/UsageWarningBanner.tsx:
- IMPLEMENT predictive warning display
- COLOR-CODE warnings by severity level
- SHOW projected limit time and usage rate
Task 5: Create simplified usage analysis section
CREATE apps/desktop/layer/renderer/src/modules/settings/tabs/ai/usage/UsageAnalysisSection.tsx:
- IMPLEMENT compact overview for AI settings tab
- USE UsageProgressRing and SessionStatusCard components
- INCLUDE "View Details" link to full analytics page
- FOLLOW SettingTabbedSegment patterns from existing sections
Task 6: Create chart components for detailed analytics
CREATE apps/desktop/layer/renderer/src/modules/settings/tabs/token-usage/components/UsageTrendChart.tsx:
- USE recharts LineChart for 30-day usage trends
- IMPLEMENT responsive container and proper tooltips
- STYLE using Tailwind and UIKit colors
CREATE apps/desktop/layer/renderer/src/modules/settings/tabs/token-usage/components/FeatureDistributionChart.tsx:
- USE recharts PieChart for feature usage breakdown
- ADD custom legend with percentages
- IMPLEMENT hover interactions
CREATE apps/desktop/layer/renderer/src/modules/settings/tabs/token-usage/components/ModelEfficiencyChart.tsx:
- USE recharts BarChart for model efficiency comparison
- SHOW tokens per operation efficiency
- COLOR-CODE by efficiency levels
Task 7: Create comprehensive analytics page
CREATE apps/desktop/layer/renderer/src/modules/settings/tabs/token-usage/TokenUsageEnhanced.tsx:
- IMPLEMENT tabbed interface with overview/patterns/efficiency/history
- USE chart components for visualizations
- INCLUDE real-time metrics dashboard
- ADD predictive insights and recommendations section
Task 8: Create time pattern analysis components
CREATE apps/desktop/layer/renderer/src/modules/settings/tabs/token-usage/components/TimePatternAnalysis.tsx:
- DISPLAY peak usage hours and days
- SHOW usage patterns and habits
- PROVIDE optimization suggestions based on patterns
CREATE apps/desktop/layer/renderer/src/modules/settings/tabs/token-usage/components/PredictiveInsights.tsx:
- RENDER usage trend analysis
- DISPLAY projected monthly usage
- SHOW personalized recommendations and tips
Task 9: Integrate usage section into AI settings
MODIFY apps/desktop/layer/renderer/src/modules/settings/tabs/ai.tsx:
- IMPORT UsageAnalysisSection component
- ADD to SettingBuilder array after existing sections
- INCLUDE proper title and divider
MODIFY apps/desktop/layer/renderer/src/modules/settings/tabs/ai/index.ts:
- EXPORT UsageAnalysisSection from new usage module
Task 10: Enhance existing token usage page
MODIFY apps/desktop/layer/renderer/src/modules/settings/tabs/token-usage.tsx:
- REPLACE current implementation with TokenUsageEnhanced
- MAINTAIN backward compatibility with existing route
- ADD proper error boundaries and loading states
Task 11: Add internationalization support
CREATE locales/en/ai.json (add new keys):
- ADD usage_analysis.* keys for simplified section
- ADD analytics.* keys for detailed page
- ADD insights.* keys for recommendations and warnings
CREATE similar entries in locales/zh-CN/ai.json and locales/ja.json
Task 12: Add responsive mobile support
CREATE apps/desktop/layer/renderer/src/modules/settings/tabs/token-usage/styles/charts.module.css:
- ADD mobile-responsive chart styles
- IMPLEMENT collapsible sections for mobile
- ENSURE touch-friendly interactions
Task 13: Implement real-time updates
MODIFY all query hooks:
- ADD refetchInterval: 30000 for config data
- ADD refetchInterval: 10000 for session data
- IMPLEMENT proper error retry logic
Task 14: Add loading and error states
ENHANCE all components:
- ADD skeleton loading states using @follow/components/ui/skeleton
- IMPLEMENT error boundaries with retry mechanisms
- SHOW proper fallback UI when data unavailable
Task 15: Create comprehensive component exports
CREATE apps/desktop/layer/renderer/src/modules/settings/tabs/ai/usage/index.ts:
- EXPORT all usage-related components and hooks
- MAINTAIN clean import structure
CREATE apps/desktop/layer/renderer/src/modules/settings/tabs/token-usage/components/index.ts:
- EXPORT all chart and analytics components
Task 16: Add interactive features
ENHANCE chart components:
- ADD click interactions for drill-down views
- IMPLEMENT brush selection for time range filtering
- ADD export functionality for usage reports
Task 17: Implement accessibility features
ENHANCE all components:
- ADD proper ARIA labels and descriptions
- ENSURE keyboard navigation support
- IMPLEMENT high contrast mode compatibility
- ADD screen reader support for charts
```
### Per task pseudocode as needed
```typescript
// Task 2: AI Analytics Query Hooks
// apps/desktop/layer/renderer/src/queries/ai-analytics.ts
import { useQuery } from "@tanstack/react-query"
import { followClient } from "~/lib/api-client"
export const aiAnalyticsKeys = {
all: ["ai-analytics"] as const,
config: () => [...aiAnalyticsKeys.all, "config"] as const,
analytics: () => [...aiAnalyticsKeys.all, "analytics"] as const,
analyticsWithDays: (days: number) => [...aiAnalyticsKeys.analytics(), days] as const,
session: () => [...aiAnalyticsKeys.all, "session"] as const,
sessionCurrent: () => [...aiAnalyticsKeys.session(), "current"] as const,
}
export const useEnhancedTokenUsage = (options = {}) => {
const { data, isLoading, error } = useQuery({
queryKey: aiAnalyticsKeys.config(),
queryFn: async () => {
const res = await followClient.api.ai.config()
return res
},
refetchInterval: 30000, // 30 seconds
refetchOnWindowFocus: true,
retry: 2,
...options,
})
return { data: data?.data, isLoading, error }
}
export const useUsageAnalytics = (days: number = 30) => {
const { data, isLoading, error } = useQuery({
queryKey: aiAnalyticsKeys.analyticsWithDays(days),
queryFn: async () => {
const res = await followClient.api.ai.analytics({ days })
return res
},
refetchInterval: 60000, // 1 minute
...options,
})
return { data: data?.data, isLoading, error }
}
// Task 5: Usage Analysis Section for AI Tab
// apps/desktop/layer/renderer/src/modules/settings/tabs/ai/usage/UsageAnalysisSection.tsx
import { Card, CardContent } from "@follow/components/ui/card"
import { cn } from "@follow/utils/utils"
import { useTranslation } from "react-i18next"
import { Link } from "react-router-dom"
import { UsageProgressRing } from "./components/UsageProgressRing"
import { SessionStatusCard } from "./components/SessionStatusCard"
import { UsageWarningBanner } from "./components/UsageWarningBanner"
import { useEnhancedTokenUsage } from "~/queries/ai-analytics"
export const UsageAnalysisSection = ({ compact = false }) => {
const { t } = useTranslation("ai")
const { data: config, isLoading } = useEnhancedTokenUsage()
if (isLoading) {
return <div className="animate-pulse h-24 bg-gray-200 rounded-lg" />
}
if (!config) return null
const { usage, rateLimit, currentSession } = config
const usagePercentage = usage.total === 0 ? 0 : (usage.used / usage.total) * 100
return (
<div className="space-y-4">
{/* Warning banner for critical states */}
{rateLimit.warningLevel !== "safe" && (
<UsageWarningBanner
level={rateLimit.warningLevel}
projectedLimitTime={rateLimit.projectedLimitTime}
usageRate={rateLimit.usageRate}
/>
)}
{/* Main usage card */}
<Card>
<CardContent className="p-4">
<div className="mb-4 flex items-center justify-between">
<h3 className="text-sm font-medium text-text">
{t("usage_analysis.title")}
</h3>
<Link
to="/settings/token-usage"
className="text-xs text-blue-600 hover:text-blue-700"
>
{t("usage_analysis.view_details")} →
</Link>
</div>
<div className="flex items-center gap-4">
<UsageProgressRing
percentage={usagePercentage}
size="md"
/>
<div className="flex-1 space-y-2">
<div className="flex items-baseline gap-2">
<span className="text-lg font-semibold text-text">
{formatTokenCount(rateLimit.remainingTokens).value}
{formatTokenCount(rateLimit.remainingTokens).unit}
</span>
<span className="text-sm text-text-secondary">
{t("usage_analysis.tokens_remaining")}
</span>
</div>
<div className="text-xs text-text-tertiary">
{formatTokenCount(usage.used).value}{formatTokenCount(usage.used).unit} /
{formatTokenCount(usage.total).value}{formatTokenCount(usage.total).unit} used
</div>
<div className="text-xs text-text-secondary">
{t("usage_analysis.resets_in")} {formatTimeRemaining(rateLimit.windowResetTime - Date.now())}
</div>
</div>
</div>
{/* Current session if active */}
{currentSession?.isActive && (
<SessionStatusCard session={currentSession} className="mt-4" />
)}
{/* Quick insights */}
{!compact && (
<div className="mt-4 space-y-2">
<QuickInsights
mostUsedFeature={usage.mostUsedFeature}
efficiencyScore={usage.efficiencyScore}
avgSessionDuration={usage.avgSessionDuration}
/>
</div>
)}
</CardContent>
</Card>
</div>
)
}
// Task 6: Usage Trend Chart
// apps/desktop/layer/renderer/src/modules/settings/tabs/token-usage/components/UsageTrendChart.tsx
import { ResponsiveContainer, LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip } from "recharts"
import { Card, CardHeader, CardTitle, CardContent } from "@follow/components/ui/card"
interface UsageTrendChartProps {
data: Array<{
date: string
totalTokens: number
operationCount: number
}>
}
export const UsageTrendChart = ({ data }: UsageTrendChartProps) => {
return (
<Card>
<CardHeader>
<CardTitle>Usage Trends (Last 30 Days)</CardTitle>
</CardHeader>
<CardContent>
<ResponsiveContainer width="100%" height={300}>
<LineChart data={data}>
<CartesianGrid strokeDasharray="3 3" stroke="rgba(156, 163, 175, 0.2)" />
<XAxis
dataKey="date"
className="text-text-secondary text-sm"
/>
<YAxis className="text-text-secondary text-sm" />
<Tooltip
formatter={(value, name) => [
name === 'totalTokens' ? `${value.toLocaleString()} tokens` : `${value} operations`,
name === 'totalTokens' ? 'Tokens Used' : 'Operations'
]}
contentStyle={{
backgroundColor: 'rgb(var(--color-fill))',
border: '1px solid rgb(var(--color-fill-secondary))',
borderRadius: '6px'
}}
/>
<Line
type="monotone"
dataKey="totalTokens"
stroke="rgb(59, 130, 246)"
strokeWidth={2}
dot={{ fill: "rgb(59, 130, 246)", strokeWidth: 0, r: 4 }}
activeDot={{ r: 6, stroke: "rgb(59, 130, 246)", strokeWidth: 2 }}
/>
</LineChart>
</ResponsiveContainer>
</CardContent>
</Card>
)
}
// Task 7: Enhanced Token Usage Page
// apps/desktop/layer/renderer/src/modules/settings/tabs/token-usage/TokenUsageEnhanced.tsx
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@follow/components/ui/tabs"
import { useEnhancedTokenUsage, useUsageAnalytics } from "~/queries/ai-analytics"
import { UsageTrendChart } from "./components/UsageTrendChart"
import { FeatureDistributionChart } from "./components/FeatureDistributionChart"
import { ModelEfficiencyChart } from "./components/ModelEfficiencyChart"
import { RealTimeMetrics } from "./components/RealTimeMetrics"
export const TokenUsageEnhanced = () => {
const { t } = useTranslation("ai")
const { data: config, isLoading: configLoading } = useEnhancedTokenUsage()
const { data: analytics, isLoading: analyticsLoading } = useUsageAnalytics(30)
if (configLoading || analyticsLoading) {
return (
<div className="flex items-center justify-center h-64">
<div className="i-mgc-loading-3-cute-re animate-spin size-6" />
</div>
)
}
return (
<div className="space-y-6">
{/* Real-time metrics overview */}
<RealTimeMetrics config={config} />
{/* Predictive warnings */}
{config.rateLimit.projectedLimitTime && (
<UsageWarningBanner
level={config.rateLimit.warningLevel}
projectedLimitTime={config.rateLimit.projectedLimitTime}
usageRate={config.rateLimit.usageRate}
detailed={true}
/>
)}
{/* Detailed analytics tabs */}
<Tabs defaultValue="overview" className="space-y-4">
<TabsList>
<TabsTrigger value="overview">{t("analytics.tabs.overview")}</TabsTrigger>
<TabsTrigger value="patterns">{t("analytics.tabs.patterns")}</TabsTrigger>
<TabsTrigger value="efficiency">{t("analytics.tabs.efficiency")}</TabsTrigger>
<TabsTrigger value="history">{t("analytics.tabs.history")}</TabsTrigger>
</TabsList>
<TabsContent value="overview" className="space-y-4">
<UsageTrendChart data={analytics?.patterns.daily || []} />
<div className="grid gap-4 md:grid-cols-2">
<FeatureDistributionChart data={analytics?.patterns.byOperation || []} />
<ModelEfficiencyChart data={analytics?.patterns.byModel || []} />
</div>
</TabsContent>
<TabsContent value="patterns">
<TimePatternAnalysis
timePatterns={analytics?.timePatterns}
insights={analytics?.insights}
/>
</TabsContent>
<TabsContent value="efficiency">
<ModelEfficiencyChart
data={analytics?.patterns.byModel || []}
detailed={true}
/>
</TabsContent>
<TabsContent value="history">
<UsageHistoryTable history={config?.usageHistory || []} />
</TabsContent>
</Tabs>
</div>
)
}
```
### Integration Points
```yaml
DEPENDENCIES:
- add: "recharts": "^2.10.0" to package.json
- verify: @tanstack/react-query version compatibility
- ensure: React 19 compatibility with recharts
API_INTEGRATION:
- endpoints: /ai/chat/config (enhanced), /ai/analytics, /ai/session/current
- pattern: followClient.api.ai.* for all API calls
- response: Extract data with data?.data pattern
UI_COMPONENTS:
- use: @follow/components/ui/* for all UI primitives
- follow: UIKit color system (text-text, bg-fill, etc.)
- icons: i-mgc-* prefix for MingCute icons
SETTINGS_INTEGRATION:
- modify: apps/desktop/layer/renderer/src/modules/settings/tabs/ai.tsx
- pattern: Add to SettingBuilder array following existing structure
- export: Update ai/index.ts with new components
ROUTES:
- existing: /settings/token-usage enhanced with new components
- navigation: Use React Router Link for internal navigation
STATE_MANAGEMENT:
- queries: React Query for server state
- settings: Jotai atoms for client settings (if needed)
- cache: Proper invalidation on data mutations
```
## Validation Loop
### Level 1: Syntax & Style
```bash
# Run these FIRST - fix any errors before proceeding
pnpm lint --fix # ESLint auto-fix
pnpm typecheck # TypeScript checking
pnpm --filter=@follow/desktop typecheck # Desktop specific check
# Expected: No errors. If errors, READ the error and fix.
```
### Level 2: Component Tests
```typescript
// CREATE apps/desktop/layer/renderer/src/modules/settings/tabs/ai/usage/__tests__/UsageAnalysisSection.test.tsx
import { render, screen } from "@testing-library/react"
import { QueryClient, QueryClientProvider } from "@tanstack/react-query"
import { UsageAnalysisSection } from "../UsageAnalysisSection"
const mockConfig = {
usage: { used: 500000, total: 1000000, efficiencyScore: 85 },
rateLimit: { remainingTokens: 500000, warningLevel: "safe" },
currentSession: { isActive: false },
}
jest.mock("~/queries/ai-analytics", () => ({
useEnhancedTokenUsage: () => ({ data: mockConfig, isLoading: false }),
}))
describe('UsageAnalysisSection', () => {
it('renders usage overview correctly', () => {
const queryClient = new QueryClient()
render(
<QueryClientProvider client={queryClient}>
<UsageAnalysisSection />
</QueryClientProvider>
)
expect(screen.getByText("Token Usage")).toBeInTheDocument()
expect(screen.getByText("View Details →")).toBeInTheDocument()
expect(screen.getByText("500K remaining")).toBeInTheDocument()
})
it('shows warning banner for critical states', () => {
const criticalConfig = {
...mockConfig,
rateLimit: { ...mockConfig.rateLimit, warningLevel: "critical" }
}
jest.mocked(useEnhancedTokenUsage).mockReturnValue({
data: criticalConfig,
isLoading: false
})
render(
<QueryClientProvider client={queryClient}>
<UsageAnalysisSection />
</QueryClientProvider>
)
expect(screen.getByRole("alert")).toBeInTheDocument()
})
})
// CREATE apps/desktop/layer/renderer/src/modules/settings/tabs/token-usage/__tests__/TokenUsageEnhanced.test.tsx
describe('TokenUsageEnhanced', () => {
it('renders analytics tabs correctly', () => {
render(
<QueryClientProvider client={queryClient}>
<TokenUsageEnhanced />
</QueryClientProvider>
)
expect(screen.getByRole("tablist")).toBeInTheDocument()
expect(screen.getByRole("tab", { name: "Overview" })).toBeInTheDocument()
expect(screen.getByRole("tab", { name: "Patterns" })).toBeInTheDocument()
})
it('displays charts when data is available', async () => {
const mockAnalytics = {
patterns: {
daily: [{ date: "2024-01-01", totalTokens: 1000, operationCount: 5 }],
byOperation: [{ operationType: "chat", totalTokens: 800, percentage: 80 }],
byModel: [{ model: "gpt-4", totalTokens: 600, avgEfficiency: 120 }],
}
}
jest.mocked(useUsageAnalytics).mockReturnValue({
data: mockAnalytics,
isLoading: false
})
render(
<QueryClientProvider client={queryClient}>
<TokenUsageEnhanced />
</QueryClientProvider>
)
expect(screen.getByText("Usage Trends")).toBeInTheDocument()
})
})
```
```bash
# Run component tests:
pnpm test -- apps/desktop/layer/renderer/src/modules/settings/tabs/ai/usage
pnpm test -- apps/desktop/layer/renderer/src/modules/settings/tabs/token-usage
# If failing: Read error, understand root cause, fix code, re-run
```
### Level 3: Integration Test
```bash
# Start the development server
pnpm --filter=@follow/desktop dev:web
# Test AI settings page integration
# Navigate to http://localhost:5173/settings/ai
# Expected: New "Token Usage" section visible with progress ring and metrics
# Test detailed analytics page
# Navigate to http://localhost:5173/settings/token-usage
# Expected: Enhanced page with tabs, charts, and real-time metrics
# Test responsive design
# Resize browser window to mobile dimensions
# Expected: Charts stack vertically, components remain usable
# Test real-time updates
# Keep page open for 30 seconds, observe data refresh
# Expected: Usage data updates automatically
```
### Level 4: Chart Rendering Validation
```bash
# Test chart libraries
# Open browser developer tools, check for console errors
# Expected: No recharts-related errors, proper chart rendering
# Test chart interactions
# Hover over chart elements, verify tooltips appear
# Click on legend items, verify chart responds
# Expected: Interactive elements work smoothly
```
### Level 5: API Integration Validation
```bash
# Test API calls in Network tab
# Navigate to enhanced pages, verify API requests
# Expected:
# - GET /ai/chat/config calls successfully
# - GET /ai/analytics calls successfully
# - GET /ai/session/current calls when needed
# - Proper error handling for failed requests
```
## Final validation Checklist
- [ ] All tests pass: `pnpm test`
- [ ] No linting errors: `pnpm lint`
- [ ] No type errors: `pnpm typecheck`
- [ ] Recharts dependency installed: `pnpm list recharts`
- [ ] AI settings page shows usage section: Navigate to /settings/ai
- [ ] Token usage page enhanced with charts: Navigate to /settings/token-usage
- [ ] Real-time updates working: Observe 30-second refresh intervals
- [ ] Charts render correctly: All visualizations display properly
- [ ] Mobile responsive: Components work on smaller screens
- [ ] Predictive warnings appear: Test with high usage scenarios
- [ ] Session tracking displays: Active sessions show correctly
- [ ] Navigation works: Links between simple/detailed views function
- [ ] Internationalization complete: All text uses translation keys
- [ ] Error states handled: Network failures show appropriate UI
- [ ] Loading states smooth: Skeleton screens display during data fetch
- [ ] Accessibility compliant: Screen reader and keyboard navigation work
---
## Anti-Patterns to Avoid
- ❌ Don't fetch chart data on every render - use React Query caching
- ❌ Don't ignore mobile responsive design - ensure charts work on small screens
- ❌ Don't hardcode colors - use UIKit color system throughout
- ❌ Don't skip loading states - users need visual feedback during data fetch
- ❌ Don't break existing AI settings layout - integrate cleanly with SettingBuilder
- ❌ Don't forget internationalization - all user text must use useTranslation
- ❌ Don't implement custom query logic - follow existing React Query patterns
- ❌ Don't ignore error boundaries - handle API failures gracefully
- ❌ Don't make charts inaccessible - include proper ARIA labels
- ❌ Don't pollute global styles - scope chart styles appropriately
## Confidence Score: 8/10
This PRP provides comprehensive context for implementing enhanced AI usage observability frontend with:
- ✅ Complete analysis of existing Follow frontend patterns and conventions
- ✅ Detailed component hierarchy with specific file structure and responsibilities
- ✅ React Query integration following project's established patterns
- ✅ Chart library integration with proper responsive design considerations
- ✅ Comprehensive testing strategy covering unit and integration scenarios
- ✅ Step-by-step implementation tasks with proper dependency management
- ✅ Clear validation steps with specific commands and expected outcomes
- ✅ Internationalization requirements and integration patterns
The implementation should succeed with high confidence given the detailed context, existing codebase analysis, and thorough validation approach. The -2 points account for the complexity of chart library integration and potential responsive design edge cases that may require iteration.
-577
View File
@@ -1,577 +0,0 @@
# PRP: Comprehensive Entry Content Layout Fixes
## Overview
Fix critical issues in the adaptive entry content layouts that prevent proper EntryHeader display, cause inconsistent layout patterns, and implement unwanted popup behaviors. This PRP addresses specific problems identified with SocialMedia, Pictures, and Videos layouts while also fixing entry navigation behavior.
## Current Issues Analysis
### Issue Context
Following the implementation of adaptive entry content layouts in `PRPs/adaptive-entry-content-layouts.md` and `PRPs/adaptive-entry-layouts-fixes.md`, several critical issues remain that affect user experience:
### 1. Social Media Layout - Blank EntryHeader Issue
**File**: `apps/desktop/layer/renderer/src/modules/entry-content/components/layouts/SocialMediaLayout.tsx`
**Root Cause**: EntryHeader component explicitly hides all functionality for SocialMedia view
**Current Implementation Problem**:
```typescript
// EntryHeader.tsx lines 72-77 - Explicitly hides actions for SocialMedia
{view !== FeedViewType.SocialMedia && (
<div className="relative flex shrink-0 items-center justify-end gap-2">
<EntryHeaderActions entryId={entryId} view={view} compact={compact} />
<MoreActions entryId={entryId} view={view} />
</div>
)}
```
**Missing Functionality**:
- Star/bookmark actions
- Share actions
- More actions menu (read/unread toggle, archive, etc.)
- Entry metadata display when scrolled
- Read status indicators
**Additional Issue**: SocialMedia entries also use `<article>` tag instead of `NavLink` in `EntryItemWrapper.tsx:212`, preventing proper navigation.
### 2. Pictures Layout - Wrong Layout Structure
**File**: `apps/desktop/layer/renderer/src/modules/entry-content/components/layouts/PicturesLayout.tsx`
**Current Structure**: Split-screen layout (image left, metadata sidebar right)
```typescript
<div className="flex h-full max-h-[85vh]">
<div className="flex-1 flex items-center justify-center bg-black/5"> {/* Image area */}
<div className="w-80 border-l bg-background flex flex-col"> {/* Sidebar */}
```
**Requested Structure**: Article-like layout (title/author top, content below) with multimedia separated from text
### 3. Videos Layout - AI Summary Position
**File**: `apps/desktop/layer/renderer/src/modules/entry-content/components/layouts/VideosLayout.tsx`
**Current Order**:
1. EntryTitle
2. AuthorHeader
3. ContentBody
4. AISummary ← Currently at bottom
**Requested Order**: AI Summary should be above ContentBody (between AuthorHeader and ContentBody)
### 4. Video Entry Popup Logic
**File**: `apps/desktop/layer/renderer/src/modules/entry-column/Items/video-item.tsx`
**Current Behavior**: Lines 104-126 - Click triggers modal popup instead of navigation
```typescript
onClick={(e) => {
if (iframeSrc) {
modalStack.present({
title: "",
content: (props) => (<PreviewVideoModalContent src={iframeSrc} entryId={entryId} {...props} />),
})
} else {
previewMedia(entry.media) // Triggers video preview popup
}
}}
```
### 5. Picture Entry Popup Logic
**File**: `apps/desktop/layer/renderer/src/modules/entry-column/Items/picture-item.tsx`
**Current Behavior**: Lines 46-48 - SwipeMedia triggers preview popup
```typescript
<SwipeMedia
onPreview={(media, i) => {
previewMedia(media, i) // Triggers picture preview popup instead of navigation
}}
/>
```
## Proposed Solutions
### 1. Social Media Layout Fixes
#### 1.1 Restore EntryHeader Functionality
**Strategy**: Remove the SocialMedia exclusion from EntryHeader component and ensure proper integration
**File Changes**:
- `EntryHeader.tsx`: Remove `view !== FeedViewType.SocialMedia` condition
- `EntryItemWrapper.tsx`: Change SocialMedia from `<article>` to `NavLink` like other entry types
- `SocialMediaLayout.tsx`: Ensure layout works with EntryHeader display
#### 1.2 Layout Integration Pattern
Follow the same pattern as ArticleLayout:
```typescript
// EntryContent.tsx integration (lines 120-127)
{!isInPeekModal && (
<EntryHeader
entryId={entryId}
view={view}
className={cn("@container h-[55px] shrink-0 px-3", classNames?.header)}
compact={compact}
/>
)}
// Then SocialMediaLayout renders below EntryHeader
```
### 2. Pictures Layout Restructuring
#### 2.1 Change to Article-Style Layout
**New Structure**: Title/Author on top, content below, with multimedia content separated
```typescript
// New PicturesLayout structure
<div className="space-y-6 p-6 max-w-4xl mx-auto">
{/* Title and Author Section */}
<div className="space-y-4">
<EntryTitle entryId={entryId} compact={false} />
<AuthorHeader entryId={entryId} showAvatar={true} avatarSize={40} />
</div>
{/* Multimedia Content Section */}
<div className="space-y-4">
<MediaGallery entryId={entryId} />
</div>
{/* Text Content Section */}
<div className="space-y-4">
<ContentBody entryId={entryId} translation={translation} compact={compact} noMedia={true} />
<AISummary entryId={entryId} />
</div>
</div>
```
#### 2.2 Multimedia Content Separation
- Use `noMedia={true}` on ContentBody to remove multimedia elements from text
- Display multimedia content separately in dedicated MediaGallery section
- Maintain click-to-preview functionality via `usePreviewMedia` hook
### 3. Videos Layout - AI Summary Position Fix
**Simple Reordering**: Move AISummary component above ContentBody
```typescript
// Current order in VideosLayout.tsx (lines 49-72)
<EntryTitle entryId={entryId} compact={compact} />
<AuthorHeader entryId={entryId} showAvatar={true} avatarSize={40} />
<AISummary entryId={entryId} /> {/* Move here - above content */}
<ContentBody entryId={entryId} translation={translation} compact={compact} noMedia={true} />
```
### 4. Remove Video Entry Popup Logic
#### 4.1 Update Video Item Click Handler
**File**: `video-item.tsx`
**Change**: Remove modal popup logic, allow normal entry navigation
```typescript
// Replace current onClick handler (lines 104-126) with normal entry behavior
// Remove the modal presentation logic entirely
// Let EntryItemWrapper handle navigation naturally
```
#### 4.2 Preserve Video Preview in Layout
**Note**: Users can still preview videos via the VideosLayout which shows the video player properly
### 5. Remove Picture Entry Popup Logic
#### 5.1 Update Picture Item OnPreview Handler
**File**: `picture-item.tsx`
**Change**: Remove `onPreview` prop from SwipeMedia to disable popup behavior
```typescript
// Remove onPreview prop from SwipeMedia (lines 46-48)
<SwipeMedia
// onPreview={(media, i) => previewMedia(media, i)} // Remove this line
className="aspect-square w-full overflow-hidden rounded-md"
/>
```
#### 5.2 Maintain Preview in PicturesLayout
**Note**: Users can still preview images via the restructured PicturesLayout with proper MediaGallery integration
## Implementation Plan
### Phase 1: Fix Social Media Layout EntryHeader (Priority: Critical)
#### Task 1.1: Remove SocialMedia Exclusion from EntryHeader
**File**: `apps/desktop/layer/renderer/src/modules/entry-content/components/entry-header/EntryHeader.tsx`
```typescript
// Remove condition: view !== FeedViewType.SocialMedia
// Lines 72-77: Always show EntryHeaderActions regardless of view type
<div className="relative flex shrink-0 items-center justify-end gap-2">
<EntryHeaderActions entryId={entryId} view={view} compact={compact} />
<MoreActions entryId={entryId} view={view} />
</div>
```
#### Task 1.2: Fix SocialMedia Entry Navigation
**File**: `apps/desktop/layer/renderer/src/modules/entry-column/layouts/EntryItemWrapper.tsx`
```typescript
// Change line 212 from:
const Link = view === FeedViewType.SocialMedia ? "article" : NavLink
// To:
const Link = NavLink // Use NavLink for all entry types including SocialMedia
```
#### Task 1.3: Verify SocialMediaLayout Integration
**File**: `apps/desktop/layer/renderer/src/modules/entry-content/components/layouts/SocialMediaLayout.tsx`
- Ensure layout works properly when EntryHeader is displayed above it
- Test star collection overlay positioning doesn't conflict with EntryHeader
- Verify responsive behavior with EntryHeader present
### Phase 2: Restructure Pictures Layout (Priority: High)
#### Task 2.1: Implement Article-Style Layout Structure
**File**: `apps/desktop/layer/renderer/src/modules/entry-content/components/layouts/PicturesLayout.tsx`
- Replace split-screen layout with vertical article-style layout
- Move title and author to top section
- Create dedicated multimedia content section with MediaGallery
- Separate text content section with `noMedia={true}`
#### Task 2.2: Update MediaGallery Integration
- Ensure MediaGallery component supports click-to-preview functionality
- Maintain existing `usePreviewMedia` hook integration for modal previews
- Test multiple image handling and carousel behavior
### Phase 3: Fix Videos Layout AI Summary Position (Priority: Medium)
#### Task 3.1: Reorder Components
**File**: `apps/desktop/layer/renderer/src/modules/entry-content/components/layouts/VideosLayout.tsx`
- Move `<AISummary entryId={entryId} />` from line 72 to after AuthorHeader (around line 53)
- Maintain proper spacing and styling
- Test responsive behavior and content flow
### Phase 4: Remove Popup Logic (Priority: Medium)
#### Task 4.1: Remove Video Entry Popup Logic
**File**: `apps/desktop/layer/renderer/src/modules/entry-column/Items/video-item.tsx`
- Remove or simplify onClick handler (lines 104-126)
- Remove `PreviewVideoModalContent` modal presentation logic
- Allow normal entry navigation through EntryItemWrapper
#### Task 4.2: Remove Picture Entry Popup Logic
**File**: `apps/desktop/layer/renderer/src/modules/entry-column/Items/picture-item.tsx`
- Remove `onPreview` prop from SwipeMedia component (lines 46-48)
- Test that normal entry navigation still works
- Verify pictures can still be previewed through PicturesLayout
### Phase 5: Testing and Validation (Priority: High)
#### Task 5.1: Layout Functionality Testing
- Test EntryHeader actions work in SocialMedia layout (star, share, more actions)
- Test Pictures layout displays properly with article-style structure
- Test Videos layout shows AI summary in correct position
- Test normal entry navigation works for all layouts
#### Task 5.2: Integration Testing
- Test entry factory routing still works correctly
- Test mobile responsive behavior across all layout changes
- Test no regressions in ArticleLayout functionality
- Test modal preview functionality where preserved
## Context & References
### Codebase Architecture Understanding
#### Entry Content System Files
- **Factory**: `layouts/factory.ts` - Layout component selection
- **Integration**: `EntryContent.tsx` - Main integration point with EntryHeader
- **Layouts**: Individual layout components in `layouts/` directory
- **Entry Wrapper**: `EntryItemWrapper.tsx` - Controls navigation vs article tag usage
#### Key Components to Modify
- **EntryHeader.tsx**: Remove SocialMedia exclusion (lines 72-77)
- **EntryItemWrapper.tsx**: Fix SocialMedia navigation (line 212)
- **SocialMediaLayout.tsx**: Verify EntryHeader integration
- **PicturesLayout.tsx**: Complete restructure to article-style layout
- **VideosLayout.tsx**: Simple component reordering
- **video-item.tsx**: Remove popup click logic
- **picture-item.tsx**: Remove SwipeMedia onPreview prop
#### Existing Patterns to Follow
- **ArticleLayout**: Reference for proper EntryHeader integration
- **MediaGallery**: Pattern for multimedia content display
- **EntryHeaderActions**: Component providing star, share, more actions
- **usePreviewMedia**: Hook for maintaining preview functionality where appropriate
### External Best Practices & Documentation
#### React Component Restructuring
- **Conditional Rendering Removal**: https://react.dev/learn/conditional-rendering
- **Component Composition**: https://react.dev/learn/passing-props-to-a-component
- **Layout Patterns**: Clean separation of content sections for better UX
#### Entry Navigation Patterns
- **React Router NavLink**: https://reactrouter.com/en/main/components/nav-link
- **Navigation vs Modal UX**: Best practices for content discovery vs preview
#### Layout Design Principles
- **Article Layout Standards**: Title → Author → Content flow for readability
- **Multimedia Content Separation**: Clear distinction between media and text content
- **Progressive Enhancement**: Maintain preview functionality while improving base navigation
### UI/UX Reference Standards
#### Social Media Layout
- **Standard Pattern**: Avatar + Author info + Actions in header area
- **Content Flow**: Header actions → AI summary → Content → Media gallery
- **Action Accessibility**: All entry actions should be consistently available
#### Pictures Layout
- **Article-Style Pattern**: Linear flow from title → author → multimedia → text
- **Content Separation**: Clear visual separation between media and text sections
- **Preview Enhancement**: Click-to-preview maintains advanced image viewing
#### Videos Layout
- **Information Hierarchy**: AI summary provides context before content consumption
- **Content Flow**: Video → Title → Author → AI Summary → Description/Content
## Validation Gates
### Code Quality Checks
```bash
# TypeScript validation
pnpm run typecheck
# Linting validation
pnpm run lint:tsl
pnpm run lint
# Code formatting
pnpm run format
# Build validation
pnpm run build:web
```
### Functional Testing Checklist
#### Social Media Layout Validation
- [ ] EntryHeader displays with all action buttons (star, share, more actions menu)
- [ ] Social media entries navigate properly when clicked (no article tag behavior)
- [ ] Star/bookmark functionality works correctly
- [ ] Share actions function properly
- [ ] More actions menu provides read/unread, archive, etc. options
- [ ] Entry metadata displays when scrolled
- [ ] Layout integrates properly with EntryHeader space allocation
#### Pictures Layout Validation
- [ ] Title displays at top of layout
- [ ] Author information displays below title
- [ ] Multimedia content displays in dedicated section
- [ ] Text content displays separately without embedded media
- [ ] AI summary appears in text content section
- [ ] MediaGallery maintains click-to-preview functionality
- [ ] Layout is responsive and readable on all screen sizes
#### Videos Layout Validation
- [ ] AI summary displays above main content (after AuthorHeader)
- [ ] Video player displays properly at top
- [ ] Title and author information display correctly
- [ ] Text content excludes multimedia elements (`noMedia={true}`)
- [ ] Component spacing and flow is visually appealing
#### Entry Navigation Validation
- [ ] Video entries navigate to content view instead of showing popup
- [ ] Picture entries navigate to content view instead of showing popup
- [ ] Normal entry clicking behavior consistent across all entry types
- [ ] Preview functionality still available within content layouts
- [ ] No regressions in other entry types (Article, Audio, Notifications)
### Performance & Integration Testing
- [ ] No layout shift when EntryHeader is displayed with SocialMedia layout
- [ ] Entry factory routing continues to work seamlessly
- [ ] Modal preview functionality works when explicitly triggered
- [ ] Bundle size impact minimal (layout restructuring only)
- [ ] Mobile responsive design maintained across all layouts
## Success Criteria
### Primary Objectives
- [ ] **Social Media**: EntryHeader displays with all actions like other entry types
- [ ] **Pictures**: Article-style layout (title/author top, content below) with multimedia separation
- [ ] **Videos**: AI summary positioned above main content
- [ ] **Navigation**: Entry clicks navigate to content view instead of triggering popups
- [ ] **Functionality**: All existing features preserved (preview, actions, etc.)
### Quality Standards
- [ ] Zero regressions in existing ArticleLayout functionality
- [ ] Entry factory system continues routing correctly
- [ ] All EntryHeader actions work consistently across layouts
- [ ] Mobile responsive design maintained
- [ ] Performance impact negligible
### User Experience Improvements
- [ ] Consistent action availability across all entry types (star, share, etc.)
- [ ] Better content organization with proper information hierarchy
- [ ] Improved navigation flow (click to view, preview when desired)
- [ ] Cleaner content separation between multimedia and text
- [ ] Maintained advanced preview functionality where appropriate
## Risk Assessment & Mitigation
### High-Risk Areas
#### 1. EntryHeader Integration Changes
**Risk**: Removing SocialMedia exclusion might break existing layout assumptions
**Mitigation**:
- Test thoroughly with various social media entry types
- Verify responsive behavior with EntryHeader space allocation
- Implement feature flag for gradual rollout if needed
#### 2. Navigation Behavior Changes
**Risk**: Changing from `<article>` to `NavLink` might affect performance or behavior
**Mitigation**:
- Profile performance impact of additional NavLink components
- Test keyboard navigation and accessibility compliance
- Verify no conflicts with existing event handlers
#### 3. Pictures Layout Restructuring
**Risk**: Complete layout change might break existing user expectations
**Mitigation**:
- Maintain click-to-preview functionality for advanced image viewing
- Test with various image entry types and content lengths
- Consider user feedback mechanism for layout preference
### Medium-Risk Areas
#### Component Dependencies
**Risk**: Changes to shared components might affect other areas
**Mitigation**:
- Audit all usage of modified components before changes
- Use backward-compatible prop additions where possible
- Test all entry list item displays remain functional
#### Preview Functionality
**Risk**: Removing popup logic might eliminate desired preview features
**Mitigation**:
- Preserve advanced preview functionality within content layouts
- Ensure MediaGallery and video players provide equivalent experience
- Test that preview modals still work when explicitly triggered
### Rollback Strategy
- Implement changes incrementally by layout type
- Use git feature branches for each major change
- Maintain existing layout components as backup during transition
- Feature flag capability for reverting individual layout changes
## Additional Considerations
### Accessibility Standards
- Ensure EntryHeader actions maintain proper ARIA labels and keyboard navigation
- Test screen reader compatibility with restructured layouts
- Maintain proper heading hierarchy across all layout changes
- Verify video player controls remain keyboard accessible
### Internationalization Support
- Test all layout changes with RTL languages
- Ensure proper text flow in restructured Pictures layout
- Verify action button layouts work with translated text
- Maintain consistent translation key usage across layouts
### Future Extensibility
- Pattern established for other layout types (Audio, Notifications)
- EntryHeader integration approach reusable for new layout types
- Component separation supports future customization options
- Layout factory system ready for additional media types
## Confidence Score: 8.5/10
This PRP provides a comprehensive solution with high implementation confidence:
### Strengths
- ✅ **Root Cause Analysis**: Identified exact source of each issue with file and line references
- ✅ **Proven Patterns**: Leverages existing successful EntryHeader and ArticleLayout patterns
- ✅ **Focused Scope**: Addresses specific reported issues without unnecessary complexity
- ✅ **Detailed Implementation**: Clear file-by-file changes with code examples
- ✅ **Risk Management**: Identified potential issues with concrete mitigation strategies
- ✅ **Comprehensive Testing**: Detailed validation steps for each change
- ✅ **External Research**: Incorporates best practices for navigation and layout design
### Implementation Confidence Factors
1. **Clear Problem Definition**: Each issue has been thoroughly analyzed with exact file locations
2. **Existing Foundation**: EntryHeader, ArticleLayout, and navigation patterns are already proven
3. **Minimal Breaking Changes**: Most changes involve removing exclusions or simple reordering
4. **Component Reuse**: Leveraging existing tested components rather than creating new ones
5. **Incremental Approach**: Changes can be implemented and tested independently
6. **Fallback Options**: Clear rollback strategy for each component change
### Minor Risk Factors
- **Layout Integration**: Need to verify EntryHeader spacing works with each layout type
- **Navigation Changes**: SocialMedia routing change requires thorough cross-platform testing
- **User Experience**: Pictures layout restructuring is most significant UX change
The high confidence score reflects that this PRP addresses well-defined issues using existing proven components and patterns, with clear implementation steps and comprehensive validation approaches.
-660
View File
@@ -1,660 +0,0 @@
# PRP: Entry Content Layout Refinement Fixes
## Overview
Address critical styling and functionality issues in the recently implemented adaptive entry content layouts. This PRP fixes three main areas: Social Media layout typography and avatar styling, Pictures layout carousel integration, and scroll container height calculation issues that cause content truncation.
## Current Issues Analysis
### Issue Context
Following the implementation of adaptive entry content layouts in previous PRPs, user feedback has identified several refinement issues that affect the visual quality and functionality of the layouts.
### 1. Social Media Layout - Typography and Avatar Issues
**File**: `apps/desktop/layer/renderer/src/modules/entry-content/components/layouts/SocialMediaLayout.tsx`
**Issue 1.1: Author Name Text Size**
```typescript
// Current AuthorHeader.tsx implementation (lines 64-67)
<div className="flex items-center gap-1 text-sm">
<span className="font-semibold">
<FeedTitle feed={feed} title={entry.author || feed.title} />
</span>
```
**Problem**: Author name uses `text-sm` (14px) which is too small for social media context where author prominence is important.
**Issue 1.2: Avatar Border Radius Scale Mismatch**
```typescript
// Current SocialMediaLayout.tsx (line 59)
<FeedIcon fallback feed={feed} entry={entry.iconEntry} size={48} className="mt-1 shrink-0" />
// Current FeedIcon.tsx avatar styling (line 283)
<AvatarImage className="rounded-sm object-cover" asChild src={finalSrc}>
```
**Problem**: Avatar size increased to 48px but border radius remains `rounded-sm` (2px), creating visual inconsistency.
### 2. Pictures Layout - Carousel Implementation Issues
**File**: `apps/desktop/layer/renderer/src/modules/entry-content/components/layouts/PicturesLayout.tsx`
**Issue 2.1: Multiple Image Display**
```typescript
// Current MediaGallery.tsx implementation (lines 47-113)
if (isAllMediaSameRatio) {
return (
<div className={cn("flex gap-2 overflow-x-auto", className)}>
{media.map((mediaItem, i, mediaList) => {
// Multiple images displayed side by side
```
**Problem**: MediaGallery shows multiple images side by side instead of single image with carousel navigation.
**Issue 2.2: Missing PreviewMediaContent Integration**
**Expected**: Single image display that opens PreviewMediaContent modal on click with carousel functionality.
**Current**: Direct MediaGallery display without modal integration.
**Issue 2.3: Entry List Click Behavior Not Restored**
**Problem**: Previous fixes removed SwipeMedia `onPreview` prop but didn't properly restore the expected clicking behavior for entry list images.
### 3. Scroll Container Height Calculation Issues
**Files**:
- `packages/internal/components/src/ui/scroll-area/ScrollArea.tsx`
- `apps/desktop/layer/renderer/src/modules/entry-content/components/entry-content/EntryContent.tsx`
**Issue 3.1: Height Mismatch**
```typescript
// EntryContent.tsx ScrollArea usage (lines 242-244)
rootClassName={cn(
"h-0 min-w-0 grow overflow-y-auto print:h-auto print:overflow-visible",
className,
)}
```
**Problem**: `h-0 grow` pattern causes height calculation issues where content extends beyond scroll container.
**Issue 3.2: Flex Container Min-Height Problem**
**Root Cause**: Flexbox containers with implicit minimum size cause scroll containers to not properly calculate their available height.
## Proposed Solutions
### 1. Social Media Layout Typography and Avatar Fixes
#### 1.1 Increase Author Name Font Size
**Strategy**: Update AuthorHeader to use larger text size for social media context
**Implementation**:
```typescript
// AuthorHeader.tsx - Enhanced author name styling
<div className="flex items-center gap-1">
<span className="text-base font-semibold"> {/* Changed from text-sm */}
<FeedTitle feed={feed} title={entry.author || feed.title} />
</span>
```
#### 1.2 Scale Avatar Border Radius Appropriately
**Strategy**: Use size-responsive border radius that scales with avatar dimensions
**Implementation**:
```typescript
// FeedIcon.tsx - Size-based border radius
const getBorderRadius = (size: number) => {
if (size <= 24) return "rounded-sm" // 2px for small avatars
if (size <= 32) return "rounded-md" // 6px for medium avatars
if (size <= 48) return "rounded-lg" // 8px for large avatars
return "rounded-xl" // 12px for extra large avatars
}
<AvatarImage className={cn("object-cover", getBorderRadius(size))} />
```
### 2. Pictures Layout Single Image Carousel Implementation
#### 2.1 Replace MediaGallery with Single Image Display
**Strategy**: Show only the first image with click-to-carousel functionality using PreviewMediaContent
**Implementation Pattern**:
```typescript
// PicturesLayout.tsx - Single image with carousel
const PicturesLayout: React.FC<PicturesLayoutProps> = ({ entryId, ... }) => {
const entry = useEntry(entryId, (state) => ({ media: state.media }))
const previewMedia = usePreviewMedia()
const handleImageClick = () => {
if (entry?.media && entry.media.length > 0) {
previewMedia(
entry.media.map(m => ({
url: m.url,
type: m.type,
blurhash: m.blurhash,
fallbackUrl: m.preview_image_url
})),
0 // Start at first image
)
}
}
return (
<div className="mx-auto max-w-4xl space-y-6 p-6">
{/* Single image display */}
{entry?.media && entry.media.length > 0 && (
<div className="space-y-4">
<div className="relative">
<Media
src={entry.media[0].url}
className="w-full max-h-96 object-contain rounded-lg cursor-pointer"
onClick={handleImageClick}
/>
{entry.media.length > 1 && (
<div className="absolute bottom-2 right-2 bg-black/50 text-white px-2 py-1 rounded text-sm">
+{entry.media.length - 1} more
</div>
)}
</div>
</div>
)}
{/* Rest of content */}
</div>
)
}
```
#### 2.2 Restore Entry List Image Click Behavior
**Strategy**: Re-add proper onPreview functionality to SwipeMedia in entry list contexts
**Implementation**:
```typescript
// picture-item.tsx - Restore preview functionality
<SwipeMedia
media={entryMedia}
className={/* ... */}
onPreview={(media, i) => {
previewMedia(
media.map(m => ({
url: m.url,
type: m.type,
blurhash: m.blurhash,
fallbackUrl: m.preview_image_url
})),
i
)
}}
/>
```
### 3. Scroll Container Height Fixes
#### 3.1 Apply Min-Height Fix to Flex Containers
**Strategy**: Add explicit `min-height: 0` to flex containers to fix height calculation
**Implementation**:
```typescript
// EntryContent.tsx - Fix flex container height calculation
<div className="flex flex-col h-full min-h-0"> {/* Add min-h-0 */}
<ScrollArea
className="flex-1 min-h-0" {/* Ensure flex child can shrink */}
flex
rootClassName={cn(
"overflow-y-auto print:h-auto print:overflow-visible",
className,
)}
>
{children}
</ScrollArea>
</div>
```
#### 3.2 Update ScrollArea Component for Better Height Handling
**Strategy**: Enhance ScrollArea component to handle flex container height issues
**Implementation**:
```typescript
// ScrollArea.tsx - Enhanced flex support
export const ScrollArea = ({
flex,
rootClassName,
viewportClassName,
...props
}) => {
return (
<ScrollElementContext value={viewportRef}>
<Root className={cn(
"overflow-hidden",
flex && "min-h-0", // Add explicit min-height for flex contexts
rootClassName
)}>
<Viewport
className={cn(
"block size-full",
flex && "[&>div]:!flex [&>div]:!flex-col [&>div]:!min-h-0", // Add min-h-0 to flex children
viewportClassName
)}
// ... rest of props
>
{children}
</Viewport>
</Root>
</ScrollElementContext>
)
}</brace-for-issue>
```
## Implementation Tasks
### Phase 1: Social Media Layout Typography and Avatar Fixes (Priority: High)
#### Task 1.1: Update AuthorHeader Font Sizes
**File**: `apps/desktop/layer/renderer/src/modules/entry-content/components/layouts/shared/AuthorHeader.tsx`
- Change author name from `text-sm` to `text-base` for better prominence
- Ensure consistency across all AuthorHeader usages
- Test with different author name lengths
#### Task 1.2: Implement Size-Responsive Avatar Border Radius
**File**: `apps/desktop/layer/renderer/src/modules/feed/feed-icon/FeedIcon.tsx`
- Create `getBorderRadius()` utility function based on avatar size
- Update AvatarImage className to use responsive border radius
- Test with different avatar sizes (20px, 32px, 48px, 64px)
#### Task 1.3: Update SocialMediaLayout Avatar Integration
**File**: `apps/desktop/layer/renderer/src/modules/entry-content/components/layouts/SocialMediaLayout.tsx`
- Verify 48px avatar size works with new border radius
- Test visual consistency with typography changes
- Ensure proper spacing and alignment
### Phase 2: Pictures Layout Single Image Carousel (Priority: High)
#### Task 2.1: Replace MediaGallery with Single Image Display
**File**: `apps/desktop/layer/renderer/src/modules/entry-content/components/layouts/PicturesLayout.tsx`
- Remove MediaGallery usage
- Implement single image display with first image from media array
- Add click handler for PreviewMediaContent modal
- Add visual indicator for multiple images ("+X more" overlay)
#### Task 2.2: Create Picture-Specific Media Component
**File**: `apps/desktop/layer/renderer/src/modules/entry-content/components/layouts/shared/SingleImageDisplay.tsx`
- Create reusable single image display component
- Include click-to-carousel functionality
- Handle edge cases (no images, single image, multiple images)
- Support different aspect ratios and sizing
#### Task 2.3: Restore Entry List Image Click Behavior
**File**: `apps/desktop/layer/renderer/src/modules/entry-column/Items/picture-item.tsx`
- Re-add `onPreview` prop to SwipeMedia component
- Ensure proper media format for PreviewMediaContent
- Test clicking behavior in entry list vs content view
- Verify no conflicts with entry navigation
### Phase 3: Scroll Container Height Fixes (Priority: Critical)
#### Task 3.1: Apply Min-Height Fixes to Entry Content
**File**: `apps/desktop/layer/renderer/src/modules/entry-content/components/entry-content/EntryContent.tsx`
- Add `min-h-0` classes to flex containers
- Update ScrollArea usage to include flex height fixes
- Test with different content lengths and screen sizes
- Verify fix applies to all layout types (Social Media, Videos, Articles, Pictures)
#### Task 3.2: Enhance ScrollArea Component
**File**: `packages/internal/components/src/ui/scroll-area/ScrollArea.tsx`
- Add explicit `min-h-0` support for flex contexts
- Update flex child selectors to include min-height fixes
- Ensure backward compatibility with existing usage
- Test across different scroll scenarios
#### Task 3.3: Test Scroll Fixes Across All Layouts
**Files**: All layout components
- Test Social Media layout with long content
- Test Video layout with long descriptions
- Test Articles layout for regressions
- Test Pictures layout after restructuring
- Verify mobile responsive behavior
### Phase 4: Integration Testing and Polish (Priority: Medium)
#### Task 4.1: Cross-Layout Consistency Testing
- Verify typography consistency across all layouts
- Test avatar sizing consistency in different contexts
- Ensure PreviewMediaContent modal works consistently
- Test scroll behavior across all entry types
#### Task 4.2: Performance and Accessibility Testing
- Verify no performance regressions with scroll fixes
- Test keyboard navigation with new carousel behavior
- Ensure proper focus management in PreviewMediaContent
- Test screen reader compatibility
## Context & References
### Codebase Architecture Understanding
#### Core Components to Modify
- **AuthorHeader.tsx**: Typography improvements for author names
- **FeedIcon.tsx**: Size-responsive border radius implementation
- **PicturesLayout.tsx**: Single image display with carousel integration
- **ScrollArea.tsx**: Flex container height calculation fixes
- **EntryContent.tsx**: Scroll container height fixes
- **picture-item.tsx**: Restore image click preview behavior
#### Existing Patterns to Follow
- **PreviewMediaContent.tsx**: Modal-based media carousel (Embla carousel integration)
- **usePreviewMedia**: Hook for triggering media preview modals
- **Media component**: Image display with loading states and proxy support
- **UIKit color system**: Consistent with `text-base`, `rounded-lg` etc.
### External Best Practices & Documentation
#### CSS Flexbox Height Calculation Fixes
- **Min-Height Zero Pattern**: https://stackoverflow.com/questions/21515042/scrolling-a-flexbox-with-overflowing-content
- **Flex Container Overflow**: https://moduscreate.com/blog/how-to-fix-overflow-issues-in-css-flex-layouts/
- **Critical Insight**: "There's a special case where the min-height of flex items defaults to the content size. We have to explicitly set the min height to zero."
#### React Image Carousel Best Practices
- **Single Image Display**: https://cloudinary.com/blog/add-a-responsive-image-carousel-to-your-react-app
- **Click Navigation**: Custom controls with callback functions and hasNext/hasPrev state
- **Responsive Design**: Automatic layout adjustment based on screen size
- **Performance**: Lazy loading and video play control on selected slides
#### Typography and Avatar Scaling
- **Responsive Avatar Sizing**: Border radius should scale proportionally with avatar size
- **Social Media Typography**: Author names should be prominent (16px+ / text-base) for readability
- **Apple UIKit Standards**: Consistent size relationships (border radius = size/6 to size/4)
### Implementation Guidelines
#### Typography Scaling Pattern
```typescript
// Size-based styling patterns
const getFontSize = (context: "social" | "article" | "compact") => {
switch (context) {
case "social":
return "text-base font-semibold" // 16px for prominence
case "article":
return "text-sm font-semibold" // 14px for articles
case "compact":
return "text-xs font-medium" // 12px for compact
}
}
```
#### Border Radius Scaling Pattern
```typescript
// Size-responsive border radius
const getBorderRadius = (size: number) => {
const ratio = size / 8 // Scale factor
if (ratio <= 3) return "rounded-sm" // 2px
if (ratio <= 4) return "rounded-md" // 6px
if (ratio <= 6) return "rounded-lg" // 8px
return "rounded-xl" // 12px
}
```
#### Single Image Carousel Pattern
```typescript
// Media display with carousel integration
const handleImageClick = useCallback(() => {
if (mediaArray.length > 0) {
previewMedia(
mediaArray.map(transformMediaForPreview),
0, // Initial index
)
}
}, [mediaArray, previewMedia])
```
## Validation Gates
### Code Quality Checks
```bash
# TypeScript validation
pnpm run typecheck
# Linting validation
pnpm run lint:tsl
pnpm run lint
# Code formatting
pnpm run format
# Build validation
pnpm run build:web
```
### Functional Testing Checklist
#### Social Media Layout Validation
- [ ] Author name displays with `text-base` font size (16px)
- [ ] Author name maintains proper font weight and color
- [ ] Avatar border radius scales appropriately with 48px size
- [ ] Avatar maintains circular appearance with proper radius
- [ ] Typography is consistent across different author name lengths
- [ ] Layout maintains proper spacing and alignment
#### Pictures Layout Validation
- [ ] Single image displays instead of multiple images side by side
- [ ] First image from media array is shown as primary display
- [ ] "+X more" indicator appears when multiple images exist
- [ ] Clicking single image opens PreviewMediaContent modal
- [ ] Carousel navigation works properly in modal (left/right arrows)
- [ ] Image maintains proper aspect ratio and scaling
- [ ] No layout shift when transitioning to/from modal
#### Entry List Image Click Validation
- [ ] Clicking images in picture-item triggers PreviewMediaContent modal
- [ ] Modal opens with correct initial image and media array
- [ ] Entry navigation still works when clicking non-image areas
- [ ] No conflicts between image click and entry click behaviors
- [ ] Touch gestures work properly on mobile devices
#### Scroll Container Height Validation
- [ ] Long content no longer gets cut off at bottom in Social Media layout
- [ ] Long content no longer gets cut off at bottom in Video layout
- [ ] ScrollArea height matches available container height
- [ ] Content scrolls smoothly to very bottom without truncation
- [ ] No visual glitches or layout shifts during scrolling
- [ ] Fix applies to all entry types (Articles, Social Media, Videos, Pictures)
- [ ] Mobile responsive behavior maintains proper scrolling
### Performance & Integration Testing
- [ ] No layout shift when switching between entry types
- [ ] PreviewMediaContent modal opens smoothly without lag
- [ ] Image loading states display properly
- [ ] Scroll performance maintained with height fixes
- [ ] No memory leaks with modal-based image preview
- [ ] Typography rendering remains crisp at all zoom levels
## Success Criteria
### Primary Objectives
- [ ] **Social Media**: Author names display prominently with proper typography
- [ ] **Social Media**: Avatar border radius scales appropriately with size
- [ ] **Pictures**: Single image display with click-to-carousel functionality
- [ ] **Pictures**: Entry list image clicking restored and working properly
- [ ] **Scroll Heights**: Long content fully visible without truncation in all layouts
- [ ] **Performance**: All fixes implemented without performance regression
### Quality Standards
- [ ] Zero regressions in existing ArticleLayout functionality
- [ ] All layout types maintain consistent typography patterns
- [ ] PreviewMediaContent modal integration works seamlessly
- [ ] ScrollArea height calculation robust across different content types
- [ ] Mobile responsive design maintained across all fixes
### User Experience Improvements
- [ ] Social media author information more readable and prominent
- [ ] Picture viewing experience enhanced with proper carousel integration
- [ ] Content consumption improved with full scroll accessibility
- [ ] Visual consistency improved with proper avatar styling
- [ ] Interaction patterns consistent between entry list and content view
## Risk Assessment & Mitigation
### High-Risk Areas
#### 1. ScrollArea Height Calculation Changes
**Risk**: Height fixes might break existing scroll behavior in other components
**Mitigation**:
- Apply changes incrementally with thorough testing
- Maintain backward compatibility with existing ScrollArea usage
- Test all scroll containers across the application
- Use feature flags for gradual rollout if needed
#### 2. PreviewMediaContent Modal Integration
**Risk**: Modal stacking conflicts or keyboard navigation issues
**Mitigation**:
- Test modal behavior with existing modal stack system
- Verify proper cleanup of modal state
- Ensure keyboard navigation (ESC, arrows) works correctly
- Test touch gestures on mobile devices
#### 3. Typography Changes Impact
**Risk**: Font size changes might break layout in compact or mobile views
**Mitigation**:
- Test with various author name lengths and special characters
- Verify responsive behavior across all screen sizes
- Check international character rendering (CJK, Arabic, etc.)
- Maintain proper line height and spacing
### Medium-Risk Areas
#### Component Dependencies
**Risk**: Changes to shared components might affect other features
**Mitigation**:
- Audit all usage of modified components before changes
- Use backward-compatible prop additions
- Test AuthorHeader and FeedIcon usage across application
- Verify no breaking changes to component APIs
#### Image Loading Performance
**Risk**: Single image display might affect loading performance
**Mitigation**:
- Maintain existing lazy loading behavior
- Test image proxy functionality with new implementation
- Profile image loading performance before and after changes
- Ensure proper loading states and error handling
### Rollback Strategy
- Implement changes as separate commits for easy reversal
- Use CSS custom properties for easy typography adjustments
- Maintain original component implementations as backup
- Feature flag capability for critical scroll height fixes
## Additional Considerations
### Accessibility Standards
- Ensure author names maintain proper contrast ratios with larger text
- Test screen reader compatibility with typography changes
- Verify keyboard navigation works properly with image carousel
- Maintain proper heading hierarchy across layout changes
### Internationalization Support
- Test typography changes with different language character sets
- Ensure proper text flow with RTL languages
- Verify avatar and text spacing works with longer translated text
- Maintain consistent translation key usage across components
### Future Extensibility
- Typography pattern scalable to other layout types
- Border radius pattern reusable for other avatar contexts
- ScrollArea fixes applicable to other scroll containers
- Image carousel pattern extensible to video content
## Confidence Score: 9/10
This PRP provides a comprehensive solution with high implementation confidence:
### Strengths
- ✅ **Root Cause Analysis**: Identified exact source of each issue with specific file/line references
- ✅ **Proven External Research**: Incorporates CSS flexbox best practices and React carousel patterns
- ✅ **Focused Scope**: Addresses specific reported issues without unnecessary complexity
- ✅ **Detailed Implementation**: Clear component-by-component changes with code examples
- ✅ **Risk Management**: Identified potential issues with concrete mitigation strategies
- ✅ **Comprehensive Testing**: Detailed validation steps for each change
- ✅ **Existing Pattern Leverage**: Uses established components (PreviewMediaContent, usePreviewMedia)
### Implementation Confidence Factors
1. **Clear Problem Definition**: Each issue traced to specific code locations with examples
2. **External Best Practices**: CSS flexbox fixes and React carousel patterns are well-established
3. **Component Reuse**: Leveraging existing PreviewMediaContent rather than building new carousel
4. **Incremental Approach**: Changes can be implemented and tested independently
5. **Minimal Breaking Changes**: Most fixes involve styling adjustments and proper component usage
6. **Established Patterns**: Typography and avatar sizing follow existing codebase conventions
### Minor Risk Areas
- **ScrollArea Changes**: Need thorough testing across different content types
- **Typography Impact**: Must verify responsive behavior with larger text
- **Modal Integration**: Ensure smooth interaction with existing modal stack
The high confidence score reflects that this PRP addresses well-defined styling and functional issues using established patterns and external best practices, with clear implementation steps and comprehensive validation approaches.
-278
View File
@@ -1,278 +0,0 @@
# PRP: Entry Modal to Routing Refactoring
## Overview
Refactor the entry content display system from a full-page modal approach to a scoped, column-based routing approach. This will improve user experience by keeping the modal scoped to the entry list column and make the entry content display reflect in the URL for better navigation.
## Current Implementation Analysis
### Current Architecture
- **Three-column layout**: Feed list (left) → Entry list (center) → AI chat (right)
- **Main layout**: `MainDestopLayout` → `SubscriptionColumnContainer` + `<Outlet />` (`CenterColumnLayout`)
- **Entry list**: Located in `CenterColumnLayout` which contains `EntryColumn` and `AIChatLayout`
- **Modal system**: Uses `usePeekModal` hook to display entry content in a full-page modal
### Key Files & Components
#### Current Modal Implementation
- **`usePeekModal.tsx`**: Hook that creates full-page modal using `PeekModal` component
- **`EntryItemWrapper.tsx:126`**: Click handler calls `peekModal(entry.id, "modal")` instead of navigation
- **`PeekModal` component**: Renders modal with `modalClassName` covering entire viewport
#### Routing Infrastructure
- **`useNavigateEntry.ts`**: Contains `getNavigateEntryPath()` function that generates proper entry URLs
- **Route structure**: `/timeline/:timelineId/:feedId/:entryId`
- **Current entry routing**:
- Layout: `/timeline/[timelineId]/[feedId]/layout.tsx` → `CenterColumnLayout`
- Index: `/timeline/[timelineId]/[feedId]/index.tsx` → redirects to `ROUTE_ENTRY_PENDING`
- Entry: `/timeline/[timelineId]/[feedId]/[entryId]/index.tsx` → `EntryLayoutContent`
#### Layout Components
- **`CenterColumnLayout.tsx`**: Two-column layout with entry list and AI chat
- **`EntryLayoutContent.tsx`**: Renders entry content when entryId is present in URL
- **`MainDestopLayout.tsx`**: Root layout with feed column and main content outlet
### Current Flow
1. User clicks entry in `EntryItemWrapper`
2. `handleClick` calls `peekModal(entry.id, "modal")`
3. Modal covers entire viewport, disrupting three-column layout
4. Entry content not reflected in URL routing
## Proposed Solution
### Architecture Changes
Transform the entry content display from a modal overlay to a proper routing-based approach that renders within the entry column scope.
### New Flow
1. User clicks entry in `EntryItemWrapper`
2. `handleClick` calls `navigateEntry()` with `getNavigateEntryPath()`
3. URL changes to `/timeline/:timelineId/:feedId/:entryId`
4. Entry content renders within entry column boundaries via `<Outlet />`
### Key Modifications
#### 1. Modify Entry Click Handler
**File**: `apps/desktop/layer/renderer/src/modules/entry-column/layouts/EntryItemWrapper.tsx:115-129`
Replace modal invocation with navigation:
```typescript
// BEFORE
const handleClick = useCallback(
(e) => {
// ... existing logic
peekModal(entry.id, "modal")
},
[peekModal],
)
// AFTER
const handleClick = useCallback(
(e) => {
// ... existing logic
navigateEntry({ entryId: entry.id })
},
[navigateEntry],
)
```
#### 2. Update CenterColumnLayout for Entry Display
**File**: `apps/desktop/layer/renderer/src/modules/app-layout/timeline-column/CenterColumnLayout.tsx`
Add conditional rendering for entry content within the entry column:
```typescript
// Current: Simple two-column layout
<div className="h-full flex-1 border-r">
<EntryColumn />
</div>
// Proposed: Conditional entry content display
<div className="h-full flex-1 border-r">
<EntryColumn />
<Outlet /> {/* Renders entry content when entryId is present */}
</div>
```
#### 3. Create Column-Scoped Entry Layout
**New file**: `apps/desktop/layer/renderer/src/modules/entry-column/EntryColumnLayout.tsx`
```typescript
export const EntryColumnLayout = () => {
const { entryId } = useParams()
const navigate = useNavigateEntry()
if (!entryId || entryId === ROUTE_ENTRY_PENDING) {
return <EntryColumn />
}
return (
<div className="relative h-full">
{/* Entry list background */}
<EntryColumn />
{/* Entry content overlay within column */}
<div className="absolute inset-0 bg-theme-background border-l">
<EntryContent
entryId={entryId}
onClose={() => navigate({ entryId: null })}
/>
</div>
</div>
)
}
```
#### 4. Update Route Configuration
**File**: `apps/desktop/layer/renderer/src/pages/(main)/(layer)/timeline/[timelineId]/[feedId]/layout.tsx`
Change from `CenterColumnLayout` to new scoped layout:
```typescript
// BEFORE
export { CenterColumnLayout as Component } from "~/modules/app-layout/timeline-column/index"
// AFTER
export { EntryColumnLayout as Component } from "~/modules/entry-column/EntryColumnLayout"
```
## Implementation Tasks
### Phase 1: Core Routing Setup
1. **Create EntryColumnLayout component**
- Implement conditional rendering for entry content
- Add proper scoping within entry column boundaries
- Handle entry close navigation
2. **Update CenterColumnLayout route**
- Replace component export in layout.tsx
- Ensure proper outlet rendering
3. **Modify EntryItemWrapper click handler**
- Replace `peekModal` call with `navigateEntry`
- Import and use existing navigation utilities
### Phase 2: Layout & Styling
4. **Style scoped entry content**
- Ensure entry content stays within column boundaries
- Add proper animations for entry open/close
- Handle responsive behavior
5. **Update entry content close behavior**
- Remove modal-specific close logic
- Implement navigation-based close
### Phase 3: Testing & Validation
6. **Test navigation flow**
- Verify URL changes correctly
- Test browser back/forward navigation
- Validate entry content display
7. **Test edge cases**
- Direct URL access to entry routes
- Entry not found scenarios
- Mobile responsiveness
## Context & References
### Existing Patterns
- **Navigation utilities**: `useNavigateEntry`, `getNavigateEntryPath` already exist
- **Route structure**: Entry routing infrastructure already present
- **Entry content component**: `EntryContent` component already handles rendering
### External Documentation
- **React Router Modal Patterns**: https://blog.logrocket.com/building-react-modal-module-with-react-router/
- **Background Location Pattern**: https://dev.to/unorthodev/how-to-make-routable-modals-in-react-with-react-router-3hgp
- **Scoped Navigation**: https://github.com/remix-run/react-router/discussions/9601
### Best Practices Applied
1. **Nested Route Approach**: Use existing route structure with outlets
2. **Scoped Rendering**: Keep entry content within column boundaries
3. **Persistent Navigation**: URL reflects entry selection state
4. **Smooth Transitions**: Maintain existing animation patterns
## Validation Gates
### Code Quality
```bash
# TypeScript validation
pnpm run typecheck
# Linting
pnpm run lint
# Build validation
pnpm run build:web
```
### Functional Testing
```bash
# Manual testing checklist
1. Click entry in list → URL updates → Entry content displays in column
2. Browser back/forward → Entry content appears/disappears correctly
3. Direct URL access → Entry content renders properly
4. Entry close action → Returns to entry list with correct URL
5. Mobile responsiveness → Entry content adapts to smaller screens
```
### Performance Validation
- No increase in bundle size
- Smooth animations maintained
- No layout shifts during entry display
## Success Criteria
- [ ] Entry clicks trigger navigation instead of modal
- [ ] Entry content displays within column boundaries
- [ ] URL reflects entry selection state
- [ ] Browser navigation works correctly
- [ ] Entry close returns to proper state
- [ ] All existing functionality preserved
- [ ] No visual regression in three-column layout
## Risk Mitigation
### Potential Issues
1. **Layout disruption**: Entry content might overflow column boundaries
2. **Animation conflicts**: Existing animations might conflict with new approach
3. **Mobile compatibility**: Column-scoped display might not work on mobile
### Mitigation Strategies
1. **Absolute positioning**: Use absolute positioning to contain entry content
2. **CSS containment**: Use CSS containment properties for layout isolation
3. **Responsive design**: Implement mobile-specific fallbacks if needed
## Confidence Score: 8/10
This PRP provides a comprehensive approach with:
- ✅ Detailed analysis of current implementation
- ✅ Clear technical specifications
- ✅ Existing code patterns leveraged
- ✅ External best practices incorporated
- ✅ Executable validation steps
- ✅ Risk mitigation strategies
The high confidence comes from the existing navigation infrastructure and clear understanding of the current modal system. The main implementation involves connecting existing pieces rather than building from scratch.
-397
View File
@@ -1,397 +0,0 @@
# PRP: Ratio-Based Color Mixing Tailwind Plugin
## Project Overview
This PRP defines the implementation of a Tailwind CSS plugin that provides ratio-based syntax for color mixing as an alternative to lengthy `color-mix()` CSS declarations. The plugin will transform shortened syntax like `bg-mix-accent/background-7/3` into native CSS `color-mix()` functions.
## Current Problem Analysis
### Existing Usage Patterns
The codebase currently uses verbose arbitrary value syntax for color mixing:
```css
/* Current verbose syntax - 137 characters */
bg-[color-mix(in_srgb,hsl(var(--fo-a)),hsl(var(--background))_70%)]
/* Complex nested mixing - 172 characters */
bg-[color-mix(in_srgb,_color-mix(in_srgb,rgb(var(--color-red)),hsl(var(--background))_80%),transparent_30%)]
```
**Found Usage Locations:**
- `/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/UserChatMessage.tsx:137`
- `/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/CollapsibleError.tsx:172`
### Problems Identified
1. **Readability**: Extremely long class names reduce code clarity
2. **Maintainability**: Hard to modify mixing ratios
3. **Performance**: Arbitrary values prevent CSS optimization
4. **Developer Experience**: No IntelliSense support
5. **Consistency**: No standardized mixing ratios across project
## Solution Design
### Ratio-Based Syntax Options
**Primary Syntax (Recommended):**
```css
/* Ratio format: color1/color2-ratio1/ratio2 */
bg-mix-accent/background-7/3 /* 70% accent, 30% background */
bg-mix-red/background-4/1 /* 80% red, 20% background */
border-mix-blue/white-3/2 /* 60% blue, 40% white */
text-mix-accent/background-9/1 /* 90% accent, 10% background */
```
**Alternative Syntax (Percentage-based):**
```css
bg-mix-accent-70 /* 70% accent, 30% background (implicit) */
bg-mix-red-80 /* 80% red, 20% background (implicit) */
```
**Generated CSS Output:**
```css
.bg-mix-accent\/background-7\/3 {
background-color: color-mix(in srgb, hsl(var(--fo-a)) 70%, hsl(var(--background)) 30%);
}
```
## Technical Implementation
### Plugin Architecture
Based on existing codebase patterns in `/packages/configs/tailwindcss/web.ts`:
```typescript
// New file: /packages/configs/tailwindcss/ratio-mixing-plugin.js
const plugin = require("tailwindcss/plugin")
const ratioMixingPlugin = plugin.withOptions(
(options = {}) => {
return ({ addUtilities, theme, e }) => {
const config = { ...defaultConfig, ...options }
const utilities = {}
// Generate ratio-based utilities
generateRatioBasedUtilities(utilities, config)
// Generate percentage-based utilities (fallback)
generatePercentageBasedUtilities(utilities, config)
addUtilities(utilities)
}
},
(options) => {
return {
theme: {
// Theme extensions if needed
},
}
},
)
module.exports = ratioMixingPlugin
```
### Configuration Schema
```typescript
interface RatioMixingConfig {
colorSpace?: "srgb" | "hsl" | "oklab" | "oklch"
baseColors: {
[key: string]: string // CSS variable or color value
}
ratios?: {
[key: string]: [number, number] // [numerator, denominator] pairs
}
variants?: ("bg" | "border" | "text")[]
prefix?: string
implicitBackground?: string
}
const defaultConfig: RatioMixingConfig = {
colorSpace: "srgb",
baseColors: {
background: "hsl(var(--background))",
accent: "hsl(var(--fo-a))",
red: "rgb(var(--color-red))",
// Map to existing theme colors from UIKit
},
ratios: {
"1/1": [1, 1], // 50%/50%
"2/1": [2, 1], // 66.7%/33.3%
"3/1": [3, 1], // 75%/25%
"4/1": [4, 1], // 80%/20%
"7/3": [7, 3], // 70%/30%
"9/1": [9, 1], // 90%/10%
},
variants: ["bg", "border", "text"],
prefix: "mix",
implicitBackground: "background",
}
```
### Core Implementation Functions
```javascript
function generateRatioBasedUtilities(utilities, config) {
const { baseColors, ratios, variants, colorSpace } = config
// Generate: bg-mix-accent/background-7/3
Object.entries(baseColors).forEach(([color1Name, color1Value]) => {
Object.entries(baseColors).forEach(([color2Name, color2Value]) => {
if (color1Name === color2Name) return // Skip same color mixing
Object.entries(ratios).forEach(([ratioKey, [num, denom]]) => {
const percentage1 = Math.round((num / (num + denom)) * 100)
const percentage2 = 100 - percentage1
variants.forEach((variant) => {
const className = `.${variant}-${config.prefix}-${color1Name}\\/${color2Name}-${ratioKey.replace("/", "\\/")}`
const property = getPropertyName(variant)
const mixedColor = `color-mix(in ${colorSpace}, ${color1Value} ${percentage1}%, ${color2Value} ${percentage2}%)`
utilities[className] = { [property]: mixedColor }
})
})
})
})
}
function generatePercentageBasedUtilities(utilities, config) {
// Generate: bg-mix-accent-70 (implicit background mixing)
const { baseColors, variants, colorSpace, implicitBackground } = config
const backgroundValue = baseColors[implicitBackground]
const percentages = [5, 10, 20, 30, 40, 50, 60, 70, 80, 90, 95]
Object.entries(baseColors).forEach(([colorName, colorValue]) => {
if (colorName === implicitBackground) return
percentages.forEach((percentage) => {
variants.forEach((variant) => {
const className = `.${variant}-${config.prefix}-${colorName}-${percentage}`
const property = getPropertyName(variant)
const mixedColor = `color-mix(in ${colorSpace}, ${colorValue} ${percentage}%, ${backgroundValue} ${100 - percentage}%)`
utilities[className] = { [property]: mixedColor }
})
})
})
}
function getPropertyName(variant) {
switch (variant) {
case "bg":
return "background-color"
case "border":
return "border-color"
case "text":
return "color"
default:
return "background-color"
}
}
```
### Integration with Existing Config
Update `/packages/configs/tailwindcss/web.ts`:
```typescript
import ratioMixingPlugin from "./ratio-mixing-plugin"
const twConfig = {
// ... existing config
plugins: [
// ... existing plugins
ratioMixingPlugin({
baseColors: {
background: "hsl(var(--background))",
accent: "hsl(var(--fo-a))",
red: "rgb(var(--color-red))",
// Map to UIKit colors already in theme
},
}),
],
} satisfies Config
```
## Migration Strategy
### Before/After Examples
```jsx
// BEFORE: Verbose arbitrary values
<div className="bg-[color-mix(in_srgb,hsl(var(--fo-a)),hsl(var(--background))_70%)]">
User message
</div>
// AFTER: Clean ratio syntax
<div className="bg-mix-accent/background-7/3">
User message
</div>
// ALTERNATIVE: Percentage syntax (when mixing with background)
<div className="bg-mix-accent-70">
User message
</div>
```
### Migration Steps
1. Install plugin in Tailwind config
2. Generate new utility classes via build
3. Replace existing arbitrary values with new classes
4. Test visual consistency
5. Run lint/typecheck validation
## Implementation Tasks
### Phase 1: Core Plugin Development
1. **Create plugin file structure**
- Create `/packages/configs/tailwindcss/ratio-mixing-plugin.js`
- Implement core `plugin.withOptions` structure
- Add default configuration schema
2. **Implement ratio parsing logic**
- Create `generateRatioBasedUtilities()` function
- Handle ratio-to-percentage conversion
- Support escape characters for CSS class names (`/` → `\/`)
3. **Add percentage fallback**
- Implement `generatePercentageBasedUtilities()` function
- Provide implicit background mixing
- Support common percentage values
### Phase 2: Integration & Configuration
4. **Integrate with existing Tailwind config**
- Update `/packages/configs/tailwindcss/web.ts`
- Map to existing UIKit color variables
- Test build process compatibility
5. **Color mapping to existing theme**
- Extract colors from current theme configuration
- Map `--fo-a`, `--background`, `--color-red` variables
- Ensure compatibility with existing color system
### Phase 3: Migration & Testing
6. **Migrate existing usage**
- Update `UserChatMessage.tsx:137`
- Update `CollapsibleError.tsx:172`
- Search for other arbitrary color-mix usages
7. **Validation & testing**
- Visual regression testing
- CSS output verification
- Build process validation
## Validation Gates
### Build Validation
```bash
# TypeScript compilation
pnpm run typecheck
# Linting validation
pnpm run lint
pnpm run lint:tsl
# Tailwind build test
cd packages/configs/tailwindcss && npx tailwindcss build
```
### Plugin-Specific Validation
```bash
# Test plugin registration
node -e "console.log(require('./packages/configs/tailwindcss/ratio-mixing-plugin.js'))"
# Test CSS generation
echo "@tailwind utilities;" | npx tailwindcss --config packages/configs/tailwindcss/web.ts
```
### Visual Validation
```bash
# Development server test
cd apps/desktop && pnpm run dev:web
# Build verification
pnpm run build:web
```
## Expected Deliverables
1. **Plugin Implementation**
- `/packages/configs/tailwindcss/ratio-mixing-plugin.js` - Complete plugin
- Updated `/packages/configs/tailwindcss/web.ts` - Integration
2. **Migration Changes**
- Updated component files with new class syntax
- Removed verbose arbitrary value usage
3. **Documentation**
- Generated CSS class reference
- Migration guide for future usage
## Risk Assessment & Mitigation
### Potential Issues
1. **CSS Specificity**: New utilities should have same specificity as existing ones
2. **Build Performance**: Plugin should not significantly slow build times
3. **Browser Compatibility**: `color-mix()` requires modern browser support
4. **Class Name Conflicts**: Need to avoid conflicts with existing utilities
### Mitigation Strategies
1. Follow Tailwind's utility layer conventions
2. Implement efficient utility generation (avoid nested loops where possible)
3. Document browser support requirements (IE not supported)
4. Use unique prefixes and test for conflicts
## Success Criteria
1. **Functionality**: All current color mixing usage successfully migrated
2. **Performance**: No measurable build time increase (< 5% overhead)
3. **Maintainability**: New syntax reduces class name length by >60%
4. **Developer Experience**: IntelliSense support for new utilities
5. **Visual Consistency**: Pixel-perfect visual match with existing styling
## External References
### Documentation
- **Tailwind Plugin API**: https://v3.tailwindcss.com/docs/plugins
- **CSS color-mix() Specification**: https://developer.mozilla.org/en-US/docs/Web/CSS/color_value/color-mix
- **Existing Plugin Examples**: https://github.com/JavierM42/tailwindcss-color-mix
### Codebase Files to Reference
- `/packages/configs/tailwindcss/web.ts` - Main Tailwind configuration
- `/packages/configs/tailwindcss/tw-css-plugin.js` - Existing plugin pattern
- `/packages/configs/tailwindcss/tailwind-extend.css` - Utility examples
## Confidence Score: 8/10
**Rationale**: High confidence due to:
- ✅ Clear existing patterns in codebase
- ✅ Well-documented Tailwind plugin API
- ✅ Specific usage examples identified
- ✅ CSS color-mix() is well-supported specification
- ✅ Comprehensive implementation plan
**Potential challenges**:
- ⚠️ CSS class name escaping complexity
- ⚠️ Color variable mapping accuracy
+108
View File
@@ -107,6 +107,114 @@ import { Button, Modal } from "@follow/components"
import { FeedList } from "~/modules/name/components"
```
## Glassmorphic Depth Design System
Follow uses a sophisticated glassmorphic depth design system for elevated UI components (modals, toasts, floating panels, etc.). This design provides visual hierarchy through layered transparency and subtle color accents.
### Design Principles
- **Multi-layer Depth**: Create visual depth through stacked transparent layers
- **Subtle Color Accents**: Use brand colors at very low opacity (5-20%) for borders, glows, and backgrounds
- **Refined Blur**: Heavy backdrop blur (backdrop-blur-2xl) for frosted glass effect
- **Minimal Shadows**: Combine multiple soft shadows with accent colors for depth perception
- **Smooth Animations**: Use Spring presets for all transitions
### Color Usage
- **Primary Accent**: `#FF5C00` (orange) at 5-20% opacity for borders, glows, and highlights
- **Border**: `rgba(255, 92, 0, 0.2)` for main borders
- **Inner Glow**: `rgba(255, 92, 0, 0.05)` for subtle radial/linear gradients inside containers
- **Shadows**: Layered shadows with accent tint:
- `0 8px 32px rgba(255, 92, 0, 0.08)` - large soft glow
- `0 4px 16px rgba(255, 92, 0, 0.06)` - medium shadow
- `0 2px 8px rgba(0, 0, 0, 0.1)` - close depth
### Component Structure
```tsx
<div
className="rounded-2xl backdrop-blur-2xl"
style={{
backgroundImage:
"linear-gradient(to bottom right, rgba(var(--color-background) / 0.98), rgba(var(--color-background) / 0.95))",
borderWidth: "1px",
borderStyle: "solid",
borderColor: "rgba(255, 92, 0, 0.2)",
boxShadow:
"0 8px 32px rgba(255, 92, 0, 0.08), 0 4px 16px rgba(255, 92, 0, 0.06), 0 2px 8px rgba(0, 0, 0, 0.1)",
}}
>
{/* Inner glow layer */}
<div
className="absolute inset-0 rounded-2xl"
style={{
background:
"linear-gradient(to bottom right, rgba(255, 92, 0, 0.05), transparent, rgba(255, 92, 0, 0.05))",
}}
/>
{/* Content */}
<div className="relative">{/* Your content here */}</div>
</div>
```
### Interactive Elements
For hover states on buttons or interactive areas within glass containers:
```tsx
<button
onMouseEnter={(e) => {
e.currentTarget.style.background =
"linear-gradient(to right, rgba(255, 92, 0, 0.08), rgba(255, 140, 0, 0.05))"
}}
onMouseLeave={(e) => {
e.currentTarget.style.background = "transparent"
}}
>
{/* Subtle shine effect */}
<div className="via-gray/5 absolute inset-0 -translate-x-full bg-gradient-to-r from-transparent to-transparent transition-transform duration-700 group-hover:translate-x-full dark:via-white/5" />
</button>
```
### Dividers
Use gradient dividers within glass containers:
```tsx
<div
className="mx-4 h-px"
style={{
background: "linear-gradient(to right, transparent, rgba(255, 92, 0, 0.2), transparent)",
}}
/>
```
### Animation Guidelines
- Entry animations: `initial={{ y: 8, opacity: 0 }}` → `animate={{ y: 0, opacity: 1 }}`
- Use `Spring.presets.snappy` for quick interactions
- Use `Spring.presets.smooth` for larger movements
- Keep scale animations subtle (1.0 ↔ 1.02)
### When to Use
Apply this design system to:
- Toast notifications
- Modal dialogs
- Floating panels and popovers
- Ambient UI prompts
- Contextual menus
- Elevated cards with actions
### Accessibility
- Ensure sufficient contrast for text over glass backgrounds
- Maintain border visibility in both light and dark modes
- Preserve keyboard focus indicators
- Keep animations respectful of `prefers-reduced-motion`
## Build Outputs
- Desktop: `apps/desktop/out/` for packaged applications
+13
View File
@@ -0,0 +1,13 @@
# What's new in v0.8.0
## Shiny new things
- Smart onboarding that gets you started in seconds.
- One place for all your feeds.
- A cleaner, consistent reading experience for social media posts, picture galleries, videos, and articles.
- Support subtitles for podcasts and videos.
- Redesigned Actions for easier setup.
## Improvements
- We have made countless improvements and bug fixes in this version.
-10
View File
@@ -2,18 +2,8 @@
## Shiny new things
- AI Chat for RSS (Folo AI): A personalized, context-aware chat built for readers. The assistant understands your feeds, lists, and reading patterns to help you get more from what you follow.
- Summarize articles, translate content, and get quick explanations—without leaving your timeline.
- Ask feed-aware questions (e.g., “What did I miss this week?”) and receive suggestions tailored to your habits.
- Discover what to read next based on your subscriptions and saved items.
- Streamlined chat UI with context pickers for feeds, entries, and more.
- Early preview: we’ll iterate quickly with your feedback.
- Limited rollout: currently available to a subset of users; we’ll expand testing over time.
## Improvements
- Foundations for richer, feed-aware AI features and future extensibility around the chat module.
## No longer broken
## Thanks
+1 -1
View File
@@ -39,7 +39,7 @@ export const viteRenderBaseConfig = {
format: "es",
},
optimizeDeps: {
exclude: ["sqlocal", "wa-sqlite"],
exclude: ["sqlocal", "wa-sqlite", "@follow-app/client-sdk"],
},
resolve: {
alias: {
+9 -9
View File
@@ -28,35 +28,35 @@
"@follow/shared": "workspace:*",
"@follow/utils": "workspace:*",
"@openpanel/web": "1.0.1",
"@sentry/electron": "7.1.0",
"@sentry/electron": "7.2.0",
"builder-util-runtime": "9.3.1",
"electron-context-menu": "4.1.1",
"electron-ipc-decorator": "0.2.0",
"electron-log": "5.4.3",
"electron-squirrel-startup": "1.0.1",
"electron-store": "10.1.0",
"electron-store": "11.0.2",
"electron-updater": "6.6.2",
"es-toolkit": "1.39.10",
"es-toolkit": "1.40.0",
"font-list": "2.0.1",
"i18next": "25.5.2",
"i18next": "25.6.0",
"js-yaml": "4.1.0",
"ky": "1.10.0",
"ky": "1.12.0",
"linkedom": "0.18.11",
"lowdb": "7.0.1",
"msedge-tts": "2.0.2",
"node-machine-id": "1.1.12",
"ofetch": "1.4.1",
"pathe": "2.0.3",
"semver": "7.7.2",
"tar": "7.4.3",
"semver": "7.7.3",
"tar": "7.5.1",
"vscode-languagedetection": "npm:@vscode/vscode-languagedetection@1.0.22"
},
"devDependencies": {
"@follow/models": "workspace:*",
"@follow/types": "workspace:*",
"@types/js-yaml": "4.0.9",
"@types/node": "24.5.2",
"electron": "37.2.0",
"@types/node": "24.8.1",
"electron": "38.3.0",
"electron-devtools-installer": "4.0.0",
"typescript": "catalog:"
}
@@ -88,16 +88,16 @@ export class BootstrapManager {
if (url.hostname === "us.i.posthog.com") {
const responseHeaders = details.responseHeaders || {}
responseHeaders["Access-Control-Allow-Origin"] = ["*"]
responseHeaders["Access-Control-Allow-Methods"] = [
responseHeaders["access-control-allow-origin"] = ["*"]
responseHeaders["access-control-allow-methods"] = [
"GET",
"POST",
"PUT",
"DELETE",
"OPTIONS",
]
responseHeaders["Access-Control-Allow-Headers"] = ["*"]
responseHeaders["Access-Control-Allow-Credentials"] = ["true"]
responseHeaders["access-control-allow-headers"] = ["*"]
responseHeaders["access-control-allow-credentials"] = ["true"]
callback({
cancel: false,
@@ -17,6 +17,7 @@ import { parseUpdateInfo, resolveFiles } from "electron-updater/out/providers/Pr
import * as semver from "semver"
import { isWindows } from "../env"
import { githubProviderLogger as logger, logObject } from "./logger"
import { isSquirrelBuild } from "./utils"
interface GithubUpdateInfo extends UpdateInfo {
@@ -46,10 +47,21 @@ export class CustomGitHubProvider extends BaseGitHubProvider<GithubUpdateInfo> {
}
async getLatestVersion(): Promise<GithubUpdateInfo> {
logger.info("Starting getLatestVersion")
logObject(logger, "Provider Configuration", {
"Base URL": this.baseUrl.href,
"Base Path": this.basePath,
"Current Version": this.updater.currentVersion,
"Allow Prerelease": this.updater.allowPrerelease,
})
const cancellationToken = new CancellationToken()
const feedUrl = newUrlFromBase(`${this.basePath}.atom`, this.baseUrl)
logger.info(`Fetching feed from: ${feedUrl.href}`)
const feedXml = await this.httpRequest(
newUrlFromBase(`${this.basePath}.atom`, this.baseUrl),
feedUrl,
{
accept: "application/xml, application/atom+xml, text/xml, */*",
},
@@ -60,6 +72,8 @@ export class CustomGitHubProvider extends BaseGitHubProvider<GithubUpdateInfo> {
throw new Error(`Cannot find feed in the remote server (${this.baseUrl.href})`)
}
logger.info(`Feed fetched successfully, length: ${feedXml.length} bytes`)
const feed = parseXml(feedXml)
// noinspection TypeScriptValidateJSTypes
let latestRelease = feed.element("entry", false, `No published versions on GitHub`)
@@ -71,6 +85,8 @@ export class CustomGitHubProvider extends BaseGitHubProvider<GithubUpdateInfo> {
(semver.prerelease(this.updater.currentVersion)?.[0] as string) ||
null
logger.info(`Current Channel: ${currentChannel}`)
if (currentChannel === null) {
throw newError(
`Cannot parse channel from version: ${this.updater.currentVersion}`,
@@ -78,16 +94,27 @@ export class CustomGitHubProvider extends BaseGitHubProvider<GithubUpdateInfo> {
)
}
logger.info(`Fetching latest tag by release API for channel: ${currentChannel}`)
const releaseTag = await this.getLatestTagByRelease(currentChannel, cancellationToken)
logger.info(`Release tag from API: ${releaseTag || "null (will use feed matching)"}`)
logger.info("Iterating through feed entries to find matching release")
let entryCount = 0
for (const element of feed.getElements("entry")) {
entryCount++
// noinspection TypeScriptValidateJSTypes
const hrefElement = hrefRegExp.exec(element.element("link").attribute("href"))
const href = element.element("link").attribute("href")
const hrefElement = hrefRegExp.exec(href)
// If this is null then something is wrong and skip this release
if (hrefElement === null) continue
if (hrefElement === null) {
logger.warn(`Entry #${entryCount}: Invalid href format: ${href}`)
continue
}
// This Release's Tag
const hrefTag = hrefElement[1]!
logger.debug(`Entry #${entryCount}: Processing tag: ${hrefTag}`)
// Get Channel from this release's tag
// Handle new format: desktop/v1.2.3 or mobile/v1.2.3
let hrefChannel = "stable"
@@ -95,28 +122,40 @@ export class CustomGitHubProvider extends BaseGitHubProvider<GithubUpdateInfo> {
// For desktop tags, extract the version and check if it's a prerelease
const version = hrefTag.replace("desktop/", "")
hrefChannel = (semver.prerelease(version)?.[0] as string) || "stable"
logger.debug(
`Entry #${entryCount}: Desktop tag detected, version: ${version}, channel: ${hrefChannel}`,
)
} else if (hrefTag.startsWith("mobile/")) {
// Skip mobile releases for desktop updater
logger.debug(`Entry #${entryCount}: Skipping mobile tag`)
continue
} else {
// Legacy format: check for prerelease directly
hrefChannel = (semver.prerelease(hrefTag)?.[0] as string) || "stable"
logger.debug(`Entry #${entryCount}: Legacy tag format, channel: ${hrefChannel}`)
}
let isNextPreRelease = false
if (releaseTag) {
isNextPreRelease = releaseTag === hrefTag
logger.debug(`Entry #${entryCount}: Matching by release tag: ${releaseTag === hrefTag}`)
} else {
isNextPreRelease = hrefChannel === currentChannel
logger.debug(
`Entry #${entryCount}: Matching by channel: ${hrefChannel} === ${currentChannel} = ${isNextPreRelease}`,
)
}
if (isNextPreRelease) {
tag = hrefTag
latestRelease = element
logger.info(`✓ Found matching release at entry #${entryCount}: ${hrefTag}`)
break
}
}
logger.info(`Processed ${entryCount} feed entries total`)
} catch (e: any) {
logger.error(`Failed to parse releases feed: ${e.stack || e.message}`)
throw newError(
`Cannot parse releases feed: ${e.stack || e.message},\nXML:\n${feedXml}`,
"ERR_UPDATER_INVALID_RELEASE_FEED",
@@ -124,6 +163,7 @@ export class CustomGitHubProvider extends BaseGitHubProvider<GithubUpdateInfo> {
}
if (tag === null || tag === undefined) {
logger.error("No matching published versions found on GitHub")
throw newError(`No published versions on GitHub`, "ERR_UPDATER_NO_PUBLISHED_VERSIONS")
}
@@ -136,11 +176,15 @@ export class CustomGitHubProvider extends BaseGitHubProvider<GithubUpdateInfo> {
this.getBaseDownloadPath(String(tag), channelFile),
this.baseUrl,
)
logger.info(`Fetching channel file: ${channelFile} from ${channelFileUrl}`)
const requestOptions = this.createRequestOptions(channelFileUrl)
try {
return await this.executor.request(requestOptions, cancellationToken)
const data = await this.executor.request(requestOptions, cancellationToken)
logger.info(`Successfully fetched ${channelFile}`)
return data
} catch (e: any) {
if (e instanceof HttpError && e.statusCode === 404) {
logger.warn(`Channel file not found: ${channelFile} (404)`)
throw newError(
`Cannot find ${channelFile} in the latest release artifacts (${channelFileUrl}): ${
e.stack || e.message
@@ -148,6 +192,7 @@ export class CustomGitHubProvider extends BaseGitHubProvider<GithubUpdateInfo> {
"ERR_UPDATER_CHANNEL_FILE_NOT_FOUND",
)
}
logger.error(`Failed to fetch channel file: ${e.message}`)
throw e
}
}
@@ -156,10 +201,12 @@ export class CustomGitHubProvider extends BaseGitHubProvider<GithubUpdateInfo> {
const channel = this.updater.allowPrerelease
? this.getCustomChannelName(String(semver.prerelease(tag)?.[0] || "latest"))
: this.getDefaultChannelName()
logger.info(`Attempting to fetch channel: ${channel}`)
rawData = await fetchData(channel)
} catch (e: any) {
if (this.updater.allowPrerelease) {
// Allow fallback to `latest.yml`
logger.info("Falling back to default channel (latest.yml)")
rawData = await fetchData(this.getDefaultChannelName())
} else {
throw e
@@ -179,6 +226,16 @@ export class CustomGitHubProvider extends BaseGitHubProvider<GithubUpdateInfo> {
latestRelease,
)
}
logger.info(`Update info parsed successfully`)
logObject(logger, "Update Result", {
Tag: tag,
Version: result.version,
"Release Name": result.releaseName || "N/A",
"Release Date": result.releaseDate || "N/A",
Files: result.files?.length || 0,
})
return {
tag,
...result,
@@ -201,8 +258,11 @@ export class CustomGitHubProvider extends BaseGitHubProvider<GithubUpdateInfo> {
cancellationToken: CancellationToken,
) {
try {
const apiUrl = newUrlFromBase(`/repos${this.basePath}`, this.baseApiUrl)
logger.debug(`Fetching releases from GitHub API: ${apiUrl}`)
const releasesStr = await this.httpRequest(
newUrlFromBase(`/repos${this.basePath}`, this.baseApiUrl),
apiUrl,
{
accept: "Accept: application/vnd.github+json",
"X-GitHub-Api-Version": "2022-11-28",
@@ -211,15 +271,21 @@ export class CustomGitHubProvider extends BaseGitHubProvider<GithubUpdateInfo> {
)
if (!releasesStr) {
logger.warn("GitHub API returned empty response")
return null
}
const releases: GithubRelease[] = JSON.parse(releasesStr)
logger.debug(`Received ${releases.length} releases from GitHub API`)
let checkedCount = 0
for (const release of releases) {
if (release.draft) {
logger.debug(`Skipping draft release: ${release.tag_name}`)
continue
}
checkedCount++
const releaseTag = release.tag_name
// Handle new format: desktop/v1.2.3 or mobile/v1.2.3
@@ -228,40 +294,62 @@ export class CustomGitHubProvider extends BaseGitHubProvider<GithubUpdateInfo> {
// For desktop tags, extract the version and check if it's a prerelease
const version = releaseTag.replace("desktop/", "")
releaseChannel = (semver.prerelease(version)?.[0] as string) || "stable"
logger.debug(`API Release: ${releaseTag} (desktop, channel: ${releaseChannel})`)
} else if (releaseTag.startsWith("mobile/")) {
// Skip mobile releases for desktop updater
logger.debug(`Skipping mobile release: ${releaseTag}`)
continue
} else {
// Legacy format: check for prerelease directly
releaseChannel = (semver.prerelease(releaseTag)?.[0] as string) || "stable"
logger.debug(`API Release: ${releaseTag} (legacy, channel: ${releaseChannel})`)
}
if (releaseChannel === currentChannel) {
logger.info(`✓ Found matching release via API: ${release.tag_name}`)
return release.tag_name
}
}
logger.info(`No matching release found via API (checked ${checkedCount} non-draft releases)`)
} catch (e: any) {
console.info(`Cannot parse release: ${e.stack || e.message}`)
logger.warn(`Cannot parse release from API: ${e.message}`)
}
return null
}
resolveFiles(updateInfo: GithubUpdateInfo): Array<ResolvedUpdateFileInfo> {
logger.info(`Resolving files for tag: ${updateInfo.tag}`)
logger.debug(`Total files in update info: ${updateInfo.files.length}`)
const filteredUpdateInfo = structuredClone(updateInfo)
// for windows, we need to determine its installer type (nsis or squirrel)
if (isWindows && updateInfo.files.length > 1) {
const isSquirrel = isSquirrelBuild()
logger.info(`Windows build detected, installer type: ${isSquirrel ? "Squirrel" : "NSIS"}`)
// @ts-expect-error we should be able to modify the object
filteredUpdateInfo.files = updateInfo.files.filter((file) =>
isSquirrel ? !file.url.includes("nsis.exe") : file.url.includes("nsis.exe"),
)
logger.debug(
`Filtered to ${filteredUpdateInfo.files.length} files after Windows installer type filtering`,
)
}
// still replace space to - due to backward compatibility
return resolveFiles(filteredUpdateInfo, this.baseUrl, (p) =>
const resolved = resolveFiles(filteredUpdateInfo, this.baseUrl, (p) =>
this.getBaseDownloadPath(filteredUpdateInfo.tag, p.replaceAll(" ", "-")),
)
logger.info(`Resolved ${resolved.length} file(s) for download`)
resolved.forEach((file, index) => {
logger.debug(` File ${index + 1}: ${file.url}`)
})
return resolved
}
private getBaseDownloadPath(tag: string, fileName: string): string {
@@ -0,0 +1,22 @@
import log from "electron-log"
/**
* Logger for updater module with scoped prefix
* All logs are prefixed with [Updater] for easy identification
*/
export const updaterLogger = log.scope("updater")
/**
* Logger specifically for GitHub provider operations
*/
export const githubProviderLogger = log.scope("updater:github")
/**
* Helper to log object properties in a formatted way
*/
export function logObject(logger: typeof updaterLogger, prefix: string, obj: Record<string, any>) {
logger.info(`${prefix}:`)
for (const [key, value] of Object.entries(obj)) {
logger.info(` ${key}: ${value}`)
}
}
+7 -7
View File
@@ -17,14 +17,14 @@
<link rel="shortcut icon" href="/favicon.ico" type="image/x-icon" />
<link rel="apple-touch-icon" href="/apple-touch-icon-180x180.png" />
<title>Folo - AI-Driven RSS Reader | Follow Everything</title>
<title>Folo - AI Reader | Follow Everything</title>
<meta
name="description"
content="Folo organizes content into one timeline, keeping you updated on what matters, noise-free. AI-powered RSS reader with translation, summary, and dynamic content support. Available on iOS, Android, macOS, Windows, and Linux."
content="Folo organizes content into one timeline, keeping you updated on what matters, noise-free. AI reader with translation, summary, and dynamic content support. Available on iOS, Android, macOS, Windows, and Linux."
/>
<meta
name="keywords"
content="RSS reader, feed aggregator, AI-powered, content curation, timeline, news reader, follow feeds, social media aggregator, distraction-free browsing, cross-platform, open source, Folo, Follow Everything, AI translation, AI summary, dynamic content, video feeds, audio feeds, image feeds, RSS subscription, feed management, news aggregator, content hub, information hub, RSSNext, electron app, mobile app, desktop app, web app, iOS app, Android app, macOS app, Windows app, Linux app, noise-free feeds, curated lists, share lists, explore collections, POWER token, ownership economy, tip creators, community-driven, GitHub trending"
content="AI reader, RSS reader, feed aggregator, AI, content curation, timeline, news reader, follow feeds, social media aggregator, distraction-free browsing, cross-platform, open source, Folo, Follow Everything, AI translation, AI summary, dynamic content, video feeds, audio feeds, image feeds, RSS subscription, feed management, news aggregator, content hub, information hub, RSSNext, electron app, mobile app, desktop app, web app, iOS app, Android app, macOS app, Windows app, Linux app, noise-free feeds, curated lists, share lists, explore collections, POWER token, ownership economy, tip creators, community-driven, GitHub trending"
/>
<meta name="author" content="Follow Team" />
<meta name="robots" content="index, follow" />
@@ -40,10 +40,10 @@
<!-- OpenGraph Meta Tags -->
<meta property="og:type" content="website" />
<meta property="og:site_name" content="Folo" />
<meta property="og:title" content="Folo - AI-Driven RSS Reader | Follow Everything" />
<meta property="og:title" content="Folo - AI Reader | Follow Everything" />
<meta property="og:url" content="https://app.folo.is" />
<meta property="og:image" content="https://app.folo.is/og-image.png" />
<meta property="og:image:alt" content="Folo - AI-Driven RSS Reader" />
<meta property="og:image:alt" content="Folo - AI Reader" />
<meta
property="og:description"
content="Organize content into one timeline, keeping you updated on what matters, noise-free. AI-powered features like translation, summary, and more. Share lists, explore collections, and enjoy distraction-free browsing."
@@ -54,13 +54,13 @@
<meta name="twitter:card" content="summary_large_image" />
<meta name="twitter:site" content="@folo_is" />
<meta name="twitter:creator" content="@folo_is" />
<meta name="twitter:title" content="Folo - AI-Driven RSS Reader | Follow Everything" />
<meta name="twitter:title" content="Folo - AI Reader | Follow Everything" />
<meta
name="twitter:description"
content="Folo organizes content into one timeline, keeping you updated on what matters, noise-free. AI-powered RSS reader with translation, summary, and dynamic content support. Available on iOS, Android, macOS, Windows, and Linux."
/>
<meta name="twitter:image" content="https://app.folo.is/og-image.png" />
<meta name="twitter:image:alt" content="Folo - AI-Driven RSS Reader" />
<meta name="twitter:image:alt" content="Folo - AI Reader" />
<!-- Structured Data -->
<script type="application/ld+json">
+31 -29
View File
@@ -23,12 +23,12 @@
"@follow/store": "workspace:*",
"@follow/tracker": "workspace:*",
"@fontsource/sn-pro": "5.2.5",
"@hcaptcha/react-hcaptcha": "1.12.1",
"@headlessui/react": "2.2.8",
"@hcaptcha/react-hcaptcha": "1.13.0",
"@headlessui/react": "2.2.9",
"@hookform/resolvers": "5.2.2",
"@lexical/markdown": "0.33.1",
"@lexical/react": "0.33.1",
"@lottiefiles/dotlottie-react": "0.17.1",
"@lottiefiles/dotlottie-react": "0.17.5",
"@openpanel/web": "1.0.1",
"@radix-ui/react-avatar": "1.1.10",
"@radix-ui/react-context-menu": "2.2.16",
@@ -39,20 +39,21 @@
"@radix-ui/react-popover": "1.1.15",
"@radix-ui/react-slider": "1.3.6",
"@radix-ui/react-slot": "1.2.3",
"@sentry/react": "10.12.0",
"@shikijs/transformers": "3.12.2",
"@sentry/react": "10.20.0",
"@shikijs/transformers": "3.13.0",
"@splinetool/react-spline": "4.1.0",
"@tanstack/query-sync-storage-persister": "5.89.0",
"@tanstack/react-query": "5.89.0",
"@tanstack/react-query-devtools": "5.89.0",
"@tanstack/react-query-persist-client": "5.89.0",
"@tanstack/query-sync-storage-persister": "5.90.7",
"@tanstack/react-query": "5.90.5",
"@tanstack/react-query-devtools": "5.90.2",
"@tanstack/react-query-persist-client": "5.90.7",
"@tanstack/react-virtual": "3.13.12",
"@use-gesture/react": "10.3.1",
"@welldone-software/why-did-you-render": "10.0.1",
"@xyflow/react": "12.8.5",
"@yornaath/batshit": "0.10.1",
"ai": "5.0.48",
"@xyflow/react": "12.8.6",
"@yornaath/batshit": "0.11.1",
"ai": "5.0.76",
"camelcase-keys": "10.0.0",
"chrono-node": "2.9.0",
"class-variance-authority": "0.7.1",
"clsx": "2.1.1",
"cmdk": "1.1.1",
@@ -62,54 +63,55 @@
"electron-ipc-decorator": "0.2.0",
"embla-carousel-react": "8.6.0",
"embla-carousel-wheel-gestures": "8.1.0",
"es-toolkit": "1.39.10",
"es-toolkit": "1.40.0",
"firebase": "11.9.1",
"foxact": "0.2.49",
"franc-min": "6.2.0",
"fuse.js": "7.1.0",
"hast-util-to-jsx-runtime": "2.3.6",
"hast-util-to-mdast": "10.1.2",
"i18next": "25.5.2",
"i18next": "25.6.0",
"i18next-browser-languagedetector": "8.2.0",
"idb-keyval": "6.2.2",
"immer": "10.1.3",
"jotai": "2.14.0",
"jotai": "2.15.0",
"lethargy": "1.0.9",
"lexical": "0.33.1",
"masonic": "4.1.0",
"mdast-util-gfm-table": "2.0.0",
"mdast-util-to-markdown": "2.1.2",
"motion": "12.23.16",
"nanoid": "5.1.5",
"motion": "12.23.24",
"nanoid": "5.1.6",
"ofetch": "1.4.1",
"plain-shiki": "0.3.1",
"progressive-blur": "1.0.0",
"re-resizable": "6.11.2",
"react": "19.0.0",
"react-blurhash": "0.3.0",
"react-dom": "19.0.0",
"react-fast-compare": "3.2.2",
"react-fast-marquee": "1.6.5",
"react-hook-form": "7.62.0",
"react-hotkeys-hook": "5.1.0",
"react-i18next": "15.7.3",
"react-hook-form": "7.65.0",
"react-hotkeys-hook": "5.2.1",
"react-i18next": "16.1.0",
"react-intersection-observer": "9.16.0",
"react-ios-pwa-prompt": "2.0.6",
"react-markdown": "10.1.0",
"react-qr-code": "2.0.18",
"react-resizable-layout": "npm:@innei/react-resizable-layout@0.7.3-fork.1",
"react-router": "7.9.1",
"react-router": "7.9.4",
"react-selecto": "1.26.3",
"react-shadow": "20.6.0",
"react-zoom-pan-pinch": "3.7.0",
"rehype-raw": "7.0.0",
"shiki": "3.12.2",
"shiki": "3.13.0",
"sonner": "2.0.7",
"tinykeys": "3.0.0",
"title-case": "4.3.2",
"tldts": "7.0.14",
"tldts": "7.0.17",
"ufo": "1.6.1",
"use-context-selector": "2.0.0",
"use-sync-external-store": "1.5.0",
"use-sync-external-store": "1.6.0",
"usehooks-ts": "3.1.1",
"zod": "3.25.75",
"zustand": "5.0.8"
@@ -123,11 +125,11 @@
"@follow/models": "workspace:*",
"@follow/types": "workspace:*",
"@follow/utils": "workspace:*",
"@folo-services/ai-tools": "0.2.41",
"@types/node": "24.5.2",
"@vite-pwa/assets-generator": "1.0.1",
"fake-indexeddb": "6.2.2",
"happy-dom": "18.0.1",
"@folo-services/ai-tools": "0.2.46",
"@types/node": "24.8.1",
"@vite-pwa/assets-generator": "1.0.2",
"fake-indexeddb": "6.2.4",
"happy-dom": "20.0.7",
"react-scan": "0.4.3",
"typescript": "catalog:"
}
+1 -1
View File
@@ -74,7 +74,7 @@ const AppSkeleton = () => {
return (
<div className="flex size-full">
<div
className="bg-sidebar h-full shrink-0"
className="h-full shrink-0 bg-sidebar"
style={{
width: `${feedColWidth}px`,
}}
@@ -1,17 +1,116 @@
import { createSettingAtom } from "@follow/atoms/helper/setting.js"
import { defaultAISettings } from "@follow/shared/settings/defaults"
import type { AISettings, MCPService } from "@follow/shared/settings/interface"
import type {
AISettings,
AIShortcut,
AIShortcutTarget,
MCPService,
} from "@follow/shared/settings/interface"
import { DEFAULT_SHORTCUT_TARGETS } from "@follow/shared/settings/interface"
import { jotaiStore } from "@follow/utils"
import type { ExtractResponseData, GetStatusConfigsResponse } from "@follow-app/client-sdk"
import { clamp } from "es-toolkit"
import { atom, useAtomValue } from "jotai"
import { getFeature } from "~/hooks/biz/useFeature"
export interface WebAISettings extends AISettings {
panelStyle: AIChatPanelStyle
showSplineButton: boolean
}
type ServerShortcutConfig = ExtractResponseData<GetStatusConfigsResponse>["AI_SHORTCUTS"][number]
const FALLBACK_SHORTCUT_ICON = "i-mgc-hotkey-cute-re"
const VALID_SHORTCUT_TARGETS = new Set<AIShortcutTarget>(DEFAULT_SHORTCUT_TARGETS)
const isValidShortcutTarget = (target: string): target is AIShortcutTarget =>
VALID_SHORTCUT_TARGETS.has(target as AIShortcutTarget)
const sanitizeShortcutTargets = (targets?: readonly string[]): AIShortcutTarget[] => {
if (!targets || targets.length === 0) {
return [...DEFAULT_SHORTCUT_TARGETS]
}
const filtered = targets.filter(isValidShortcutTarget) as AIShortcutTarget[]
return filtered.length > 0 ? [...filtered] : [...DEFAULT_SHORTCUT_TARGETS]
}
const normalizeShortcut = (shortcut: AIShortcut): AIShortcut => {
return {
...shortcut,
displayTargets: sanitizeShortcutTargets(shortcut.displayTargets),
enabled: typeof shortcut.enabled === "boolean" ? shortcut.enabled : true,
}
}
const normalizeShortcuts = (shortcuts: readonly AIShortcut[] | undefined): AIShortcut[] =>
(shortcuts ?? []).map((shortcut) => normalizeShortcut({ ...shortcut }))
const mergeWithServerShortcuts = (
localShortcuts: readonly AIShortcut[],
serverShortcuts: readonly ServerShortcutConfig[],
): AIShortcut[] => {
const normalizedLocal = normalizeShortcuts(localShortcuts)
if (serverShortcuts.length === 0) {
return normalizedLocal
}
const serverShortcutMap = new Map<string, ServerShortcutConfig>()
serverShortcuts.forEach((shortcut) => {
serverShortcutMap.set(shortcut.id, shortcut)
})
const seenServerShortcutIds = new Set<string>()
const mergedShortcuts: AIShortcut[] = []
normalizedLocal.forEach((shortcut) => {
const serverShortcut = serverShortcutMap.get(shortcut.id)
if (!serverShortcut) {
mergedShortcuts.push(shortcut)
return
}
seenServerShortcutIds.add(serverShortcut.id)
const shouldClearPrompt = shortcut.prompt === serverShortcut.defaultPrompt
mergedShortcuts.push({
...shortcut,
name: shortcut.name || serverShortcut.name,
prompt: shouldClearPrompt ? "" : shortcut.prompt,
defaultPrompt: serverShortcut.defaultPrompt,
displayTargets: sanitizeShortcutTargets(
shortcut.displayTargets || serverShortcut.displayTargets,
),
})
})
serverShortcuts.forEach((serverShortcut) => {
if (seenServerShortcutIds.has(serverShortcut.id)) return
mergedShortcuts.push({
id: serverShortcut.id,
name: serverShortcut.name,
prompt: "",
defaultPrompt: serverShortcut.defaultPrompt,
enabled: true,
icon: FALLBACK_SHORTCUT_ICON,
displayTargets: sanitizeShortcutTargets(serverShortcut.displayTargets),
})
})
return mergedShortcuts
}
export const getShortcutEffectivePrompt = (shortcut: AIShortcut): string => {
return shortcut.prompt || shortcut.defaultPrompt || ""
}
export const isServerShortcut = (shortcut: AIShortcut) => !!shortcut.defaultPrompt
export const createDefaultSettings = (): WebAISettings => ({
...defaultAISettings,
shortcuts: normalizeShortcuts(defaultAISettings.shortcuts),
panelStyle: AIChatPanelStyle.Fixed,
showSplineButton: true,
})
@@ -28,6 +127,16 @@ export const {
} = createSettingAtom("ai", createDefaultSettings)
export const aiServerSyncWhiteListKeys = []
export const syncServerShortcuts = (
serverShortcuts: readonly ServerShortcutConfig[] | null | undefined,
) => {
const storedShortcuts = getAISettings().shortcuts ?? []
const serverShortcutList = Array.isArray(serverShortcuts) ? serverShortcuts : []
const mergedShortcuts = mergeWithServerShortcuts(storedShortcuts, serverShortcutList)
setAISetting("shortcuts", mergedShortcuts)
}
////////// AI Panel Style
export enum AIChatPanelStyle {
Fixed = "fixed",
@@ -74,7 +183,10 @@ export const getFloatingPanelState = () => jotaiStore.get(floatingPanelStateAtom
const aiPanelVisibilityAtom = atom<boolean>(false)
export const useAIPanelVisibility = () => useAtomValue(aiPanelVisibilityAtom)
export const setAIPanelVisibility = (visibility: boolean) => {
jotaiStore.set(aiPanelVisibilityAtom, visibility)
const aiEnabled = getFeature("ai")
if (aiEnabled) {
jotaiStore.set(aiPanelVisibilityAtom, visibility)
}
}
export const getAIPanelVisibility = () => jotaiStore.get(aiPanelVisibilityAtom)
@@ -99,7 +99,7 @@ export const FeedbackIssue = (_props: {
<p className="mt-8">
Still having this issue? Please give feedback in GitHub, thanks!
<a
className="text-accent hover:text-accent/90 ml-2 cursor-pointer duration-200"
className="ml-2 cursor-pointer text-accent duration-200 hover:text-accent/90"
href={getNewIssueUrl({
// error: error instanceof Error ? error : undefined,
// title: `Error: ${message}`,
@@ -52,7 +52,7 @@ export const NotFound = () => {
}
return (
<div className="prose center dark:prose-invert m-auto size-full flex-col">
<div className="prose center m-auto size-full flex-col dark:prose-invert">
<main className="flex grow flex-col items-center justify-center">
<div className="center mb-8 flex">
<Logo className="size-20" />
@@ -205,12 +205,12 @@ export const SharePanel = ({ entryId }: SharePanelProps) => {
return (
<div className="pointer-events-auto max-w-[400px] px-2">
<div className="mb-4 flex flex-col text-center">
<h3 className="text-text mb-2 mt-1 font-semibold">{t("share.title")}</h3>
<h3 className="mb-2 mt-1 font-semibold text-text">{t("share.title")}</h3>
{(() => {
const entry = getEntry(entryId)
const title = entry?.title
return title ? (
<p className="text-text-secondary mt-1 min-w-0 text-wrap text-left text-sm font-medium">
<p className="mt-1 min-w-0 text-wrap text-left text-sm font-medium text-text-secondary">
{title}
</p>
) : null
@@ -219,7 +219,7 @@ export const SharePanel = ({ entryId }: SharePanelProps) => {
<div className="mb-6">
<div className="mb-3">
<h4 className="text-text-secondary text-xs font-medium uppercase tracking-wide">
<h4 className="text-xs font-medium uppercase tracking-wide text-text-secondary">
{t("share.social_media")}
</h4>
</div>
@@ -241,7 +241,7 @@ export const SharePanel = ({ entryId }: SharePanelProps) => {
>
<i className={cn(option.icon, "size-5", option.color)} />
</div>
<span className="text-text-secondary text-xs font-medium">{option.label}</span>
<span className="text-xs font-medium text-text-secondary">{option.label}</span>
</button>
))}
</div>
@@ -249,7 +249,7 @@ export const SharePanel = ({ entryId }: SharePanelProps) => {
<div>
<div className="mb-3">
<h4 className="text-text-secondary text-xs font-medium uppercase tracking-wide">
<h4 className="text-xs font-medium uppercase tracking-wide text-text-secondary">
{t("share.actions")}
</h4>
</div>
@@ -259,7 +259,7 @@ export const SharePanel = ({ entryId }: SharePanelProps) => {
key={option.id}
type="button"
className={cn(
"cursor-button relative flex select-none items-center rounded-lg",
"relative flex cursor-button select-none items-center rounded-lg",
"text-sm outline-none transition-all duration-200",
"hover:bg-fill-secondary/80 active:bg-fill-secondary",
"group",
@@ -278,7 +278,7 @@ export const SharePanel = ({ entryId }: SharePanelProps) => {
className={cn(option.icon, "size-3.5", option.color || "text-text-secondary")}
/>
</div>
<span className="text-text text-xs font-medium">{option.label}</span>
<span className="text-xs font-medium text-text">{option.label}</span>
</div>
</button>
))}
@@ -15,7 +15,7 @@ const EntryNotFoundErrorFallback: FC<AppErrorFallbackProps> = ({ resetError, err
useResetErrorWhenRouteChange(resetError)
const navigate = useNavigate()
return (
<div className="bg-theme-background flex w-full flex-1 flex-col items-center justify-center rounded-md p-2">
<div className="flex w-full flex-1 flex-col items-center justify-center rounded-md bg-theme-background p-2">
<div className="center m-auto flex max-w-prose flex-col gap-4 text-center">
<div className="center mb-8 flex">
<Logo className="size-20" />
@@ -15,7 +15,7 @@ const FeedNotFoundErrorFallback: FC<AppErrorFallbackProps> = ({ resetError, erro
useResetErrorWhenRouteChange(resetError)
const navigate = useNavigate()
return (
<div className="bg-theme-background flex w-full flex-col items-center justify-center rounded-md p-2">
<div className="flex w-full flex-col items-center justify-center rounded-md bg-theme-background p-2">
<div className="center m-auto flex max-w-prose flex-col gap-4 text-center">
<div className="center mb-8 flex">
<Logo className="size-20" />
@@ -14,7 +14,7 @@ const ModalErrorFallback: FC<AppErrorFallbackProps> = (props) => {
const modal = useCurrentModal()
return (
<m.div
className="bg-theme-background flex flex-col items-center justify-center rounded-md p-2"
className="flex flex-col items-center justify-center rounded-md bg-theme-background p-2"
exit={{
opacity: 0,
scale: 0.9,
@@ -11,7 +11,7 @@ const PageErrorFallback: FC<AppErrorFallbackProps> = (props) => {
const { message, stack } = parseError(props.error)
useResetErrorWhenRouteChange(props.resetError)
return (
<div className="bg-theme-background pointer-events-auto flex w-full flex-col items-center justify-center rounded-md p-2">
<div className="pointer-events-auto flex w-full flex-col items-center justify-center rounded-md bg-theme-background p-2">
<div className="m-auto max-w-prose text-center">
<div className="mb-4">
<i className="i-mgc-bug-cute-re text-4xl text-red-500" />
@@ -6,6 +6,7 @@ import { useTranslation } from "react-i18next"
import { CopyButton } from "~/components/ui/button/CopyButton"
import { Markdown } from "~/components/ui/markdown/Markdown"
import { useFeature } from "~/hooks/biz/useFeature"
interface AISummaryCardBaseProps {
/** Summary content to display */
@@ -34,16 +35,16 @@ interface AISummaryCardBaseProps {
const DefaultLoadingState = () => (
<div className="space-y-2">
<div className="bg-material-ultra-thick h-3 w-full animate-pulse rounded-lg" />
<div className="bg-material-ultra-thick h-3 w-[92%] animate-pulse rounded-lg" />
<div className="bg-material-ultra-thick h-3 w-[85%] animate-pulse rounded-lg" />
<div className="h-3 w-full animate-pulse rounded-lg bg-material-ultra-thick" />
<div className="h-3 w-[92%] animate-pulse rounded-lg bg-material-ultra-thick" />
<div className="h-3 w-[85%] animate-pulse rounded-lg bg-material-ultra-thick" />
</div>
)
const DefaultEmptyState = ({ message }: { message: string }) => (
<div className="py-4 text-center">
<i className="i-mingcute-document-line text-text-tertiary mb-2 text-2xl" />
<p className="text-text-secondary text-sm">{message}</p>
<i className="i-mingcute-document-line mb-2 text-2xl text-text-tertiary" />
<p className="text-sm text-text-secondary">{message}</p>
</div>
)
@@ -61,6 +62,7 @@ export const AISummaryCardBase: React.FC<AISummaryCardBaseProps> = ({
onAskAI,
}) => {
const { t } = useTranslation("app")
const aiEnabled = useFeature("ai")
const hasContent = !isLoading && content
@@ -123,7 +125,7 @@ export const AISummaryCardBase: React.FC<AISummaryCardBaseProps> = ({
)}
<div className="flex items-center gap-2">
{showAskAIButton && hasContent && onAskAI && (
{aiEnabled && showAskAIButton && hasContent && onAskAI && (
<MotionButtonBase
onClick={onAskAI}
className={cn(
@@ -164,7 +166,7 @@ export const AISummaryCardBase: React.FC<AISummaryCardBaseProps> = ({
{isLoading ? (
loadingComponent || <DefaultLoadingState />
) : hasContent ? (
<Markdown className="prose-sm prose-p:m-0 max-w-none">{String(content)}</Markdown>
<Markdown className="prose-sm max-w-none prose-p:m-0">{String(content)}</Markdown>
) : (
emptyComponent || <DefaultEmptyState message={t("ai.summary_not_available")} />
)}
@@ -97,9 +97,9 @@ export const Autocomplete = ({
style={{ zIndex }}
onWheel={stopPropagation}
className={cn(
"bg-material-medium backdrop-blur-background text-text pointer-events-auto",
"pointer-events-auto bg-material-medium text-text backdrop-blur-background",
"shadow-context-menu min-w-32 overflow-hidden rounded-[6px] border p-1",
"motion-scale-in-75 motion-duration-150 text-body lg:animate-none",
"text-body motion-scale-in-75 motion-duration-150 lg:animate-none",
"w-[var(--input-width)] empty:invisible",
)}
>
@@ -66,7 +66,7 @@ export const HeaderActionButton = ({
onClick={onClick}
disabled={disabled || loading}
className={cn(
"no-drag-region group relative flex items-center gap-2 rounded-lg px-3 py-2",
"group no-drag-region relative flex items-center gap-2 rounded-lg px-3 py-2",
"text-sm font-medium transition-all duration-200",
...getVariantStyles(),
className,
@@ -77,7 +77,7 @@
&::after {
content: " +";
@apply text-green absolute left-0;
@apply absolute left-0 text-green;
}
}
@@ -90,7 +90,7 @@
&::after {
content: " -";
@apply text-red absolute left-0;
@apply absolute left-0 text-red;
}
}
@@ -384,10 +384,10 @@ export const AvatarUploadModal = ({
className="size-full"
>
<div className="flex flex-col items-center gap-2 p-8">
<i className="i-mgc-file-upload-cute-re text-text-secondary text-4xl" />
<i className="i-mgc-file-upload-cute-re text-4xl text-text-secondary" />
<div className="text-center">
<p className="text-sm font-medium">{t("profile.avatar.dropZoneText")}</p>
<p className="text-text-secondary text-xs">{t("profile.avatar.dropZoneSubtext")}</p>
<p className="text-xs text-text-secondary">{t("profile.avatar.dropZoneSubtext")}</p>
</div>
</div>
</DropZone>
@@ -427,33 +427,33 @@ export const AvatarUploadModal = ({
>
<div className="size-full cursor-move" onMouseDown={handleCropMouseDown}>
{/* Grid lines */}
<div className="bg-material-medium-light absolute left-1/3 top-0 h-full w-px" />
<div className="bg-material-medium-light absolute left-2/3 top-0 h-full w-px" />
<div className="bg-material-medium-light absolute left-0 top-1/3 h-px w-full" />
<div className="bg-material-medium-light absolute left-0 top-2/3 h-px w-full" />
<div className="absolute left-1/3 top-0 h-full w-px bg-material-medium-light" />
<div className="absolute left-2/3 top-0 h-full w-px bg-material-medium-light" />
<div className="absolute left-0 top-1/3 h-px w-full bg-material-medium-light" />
<div className="absolute left-0 top-2/3 h-px w-full bg-material-medium-light" />
{/* Resize handles */}
<div
className="bg-accent absolute -left-1 -top-1 size-3 cursor-nwse-resize rounded-full border-2 border-white"
className="absolute -left-1 -top-1 size-3 cursor-nwse-resize rounded-full border-2 border-white bg-accent"
onMouseDown={(e) => handleResizeMouseDown(e, "tl")}
/>
<div
className="bg-accent absolute -right-1 -top-1 size-3 cursor-nesw-resize rounded-full border-2 border-white"
className="absolute -right-1 -top-1 size-3 cursor-nesw-resize rounded-full border-2 border-white bg-accent"
onMouseDown={(e) => handleResizeMouseDown(e, "tr")}
/>
<div
className="bg-accent absolute -bottom-1 -left-1 size-3 cursor-nesw-resize rounded-full border-2 border-white"
className="absolute -bottom-1 -left-1 size-3 cursor-nesw-resize rounded-full border-2 border-white bg-accent"
onMouseDown={(e) => handleResizeMouseDown(e, "bl")}
/>
<div
className="bg-accent absolute -bottom-1 -right-1 size-3 cursor-nwse-resize rounded-full border-2 border-white"
className="absolute -bottom-1 -right-1 size-3 cursor-nwse-resize rounded-full border-2 border-white bg-accent"
onMouseDown={(e) => handleResizeMouseDown(e, "br")}
/>
</div>
</div>
</div>
<div className="text-text-secondary text-center text-sm">
<div className="text-center text-sm text-text-secondary">
{t("profile.avatar.cropInstructions")}
</div>
</div>
@@ -50,7 +50,7 @@ const DropdownMenuSubTrigger = ({
<DropdownMenuPrimitive.SubTrigger
ref={ref}
className={cn(
"cursor-menu focus:bg-theme-selection-active focus:text-theme-selection-foreground data-[state=open]:bg-theme-selection-active data-[state=open]:text-theme-selection-foreground flex select-none items-center rounded-[5px] px-2.5 py-1.5 outline-none",
"flex cursor-menu select-none items-center rounded-[5px] px-2.5 py-1.5 outline-none focus:bg-theme-selection-active focus:text-theme-selection-foreground data-[state=open]:bg-theme-selection-active data-[state=open]:text-theme-selection-foreground",
inset && "pl-8",
"center gap-2",
className,
@@ -75,7 +75,7 @@ const DropdownMenuSubContent = ({
<DropdownMenuPrimitive.SubContent
ref={ref}
className={cn(
"bg-material-medium backdrop-blur-background text-text text-body",
"bg-material-medium text-body text-text backdrop-blur-background",
"min-w-32 overflow-hidden",
"rounded-[6px] border p-1",
"shadow-context-menu",
@@ -102,8 +102,8 @@ const DropdownMenuContent = ({
ref={ref}
sideOffset={sideOffset}
className={cn(
"bg-material-medium backdrop-blur-background text-text shadow-context-menu z-[60] min-w-32 overflow-hidden rounded-[6px] border p-1",
"motion-scale-in-75 motion-duration-150 text-body lg:animate-none",
"shadow-context-menu z-[60] min-w-32 overflow-hidden rounded-[6px] border bg-material-medium p-1 text-text backdrop-blur-background",
"text-body motion-scale-in-75 motion-duration-150 lg:animate-none",
className,
)}
{...props}
@@ -134,11 +134,11 @@ const DropdownMenuItem = ({
<DropdownMenuPrimitive.Item
ref={ref}
className={cn(
"cursor-menu relative flex select-none items-center rounded-[5px] px-2.5 py-1 outline-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
"relative flex cursor-menu select-none items-center rounded-[5px] px-2.5 py-1 outline-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
"focus-within:outline-transparent",
highlightColor === "accent"
? "data-[highlighted]:bg-theme-selection-hover focus:bg-theme-selection-active focus:text-theme-selection-foreground data-[highlighted]:text-theme-selection-foreground"
: "data-[highlighted]:bg-theme-item-hover focus:bg-theme-item-active",
? "focus:bg-theme-selection-active focus:text-theme-selection-foreground data-[highlighted]:bg-theme-selection-hover data-[highlighted]:text-theme-selection-foreground"
: "focus:bg-theme-item-active data-[highlighted]:bg-theme-item-hover",
"h-[28px]",
inset && "pl-8",
@@ -187,7 +187,7 @@ const DropdownMenuCheckboxItem = ({
<DropdownMenuPrimitive.CheckboxItem
ref={ref}
className={cn(
"cursor-checkbox focus:bg-theme-selection-active focus:text-theme-selection-foreground relative flex select-none items-center rounded-[5px] px-8 py-1.5 outline-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
"relative flex cursor-checkbox select-none items-center rounded-[5px] px-8 py-1.5 outline-none focus:bg-theme-selection-active focus:text-theme-selection-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
"focus-within:outline-transparent",
"h-[28px]",
className,
@@ -215,7 +215,7 @@ const DropdownMenuLabel = ({
} & { ref?: React.Ref<React.ElementRef<typeof DropdownMenuPrimitive.Label> | null> }) => (
<DropdownMenuPrimitive.Label
ref={ref}
className={cn("text-text px-2 py-1.5 font-semibold", inset && "pl-8", className)}
className={cn("px-2 py-1.5 font-semibold text-text", inset && "pl-8", className)}
{...props}
/>
)
@@ -228,7 +228,7 @@ const DropdownMenuSeparator = ({
ref?: React.Ref<React.ElementRef<typeof DropdownMenuPrimitive.Separator> | null>
}) => (
<DropdownMenuPrimitive.Separator
className="backdrop-blur-background mx-2 my-1 h-px"
className="mx-2 my-1 h-px backdrop-blur-background"
asChild
ref={ref}
{...props}
@@ -50,13 +50,13 @@ export const FABBase: FC<
"mt-2 flex items-center justify-center",
"size-9 text-lg md:text-base",
"outline-accent hover:opacity-100 focus:opacity-100 focus:outline-none",
"hover:border-border bg-background relative rounded-xl border border-transparent",
"relative rounded-xl border border-transparent bg-background hover:border-border",
"group duration-200",
className,
)}
{...rest}
>
<div className="shadow-perfect border-border/50 pointer-events-none absolute inset-0 rounded-xl border shadow-xl duration-200 group-hover:opacity-0" />
<div className="shadow-perfect pointer-events-none absolute inset-0 rounded-xl border border-border/50 shadow-xl duration-200 group-hover:opacity-0" />
{children}
</m.button>
)}
@@ -0,0 +1,110 @@
import {
HoverCard,
HoverCardContent,
HoverCardTrigger,
} from "@follow/components/ui/hover-card/index.js"
import { useEntry, usePrefetchEntryDetail } from "@follow/store/entry/hooks"
import { useFeedById } from "@follow/store/feed/hooks"
import { feedIconSelector } from "@follow/store/feed/selectors"
import { cn } from "@follow/utils"
import { m } from "motion/react"
import * as React from "react"
import { RelativeTime } from "~/components/ui/datetime"
import { FeedIcon } from "~/modules/feed/feed-icon"
interface EntryPreviewCardProps {
entryId: string
children: React.ReactNode
className?: string
onNavigate?: (entryId: string) => void
}
export const EntryPreviewCard: React.FC<EntryPreviewCardProps> = ({
entryId,
children,
className,
onNavigate,
}) => {
// Prefetch entry details on hover
usePrefetchEntryDetail(entryId)
const entry = useEntry(entryId, (state) => {
if (!state) return null
return {
title: state.title,
description: state.description,
author: state.author,
publishedAt: state.publishedAt,
feedId: state.feedId,
url: state.url,
}
})
const feed = useFeedById(entry?.feedId, feedIconSelector)
if (!entry || !feed) {
return <>{children}</>
}
return (
<HoverCard openDelay={300} closeDelay={100}>
<HoverCardTrigger asChild>{children}</HoverCardTrigger>
<HoverCardContent className="w-80 p-0" side="top">
<m.div
initial={{ opacity: 0, scale: 0.95 }}
animate={{ opacity: 1, scale: 1 }}
transition={{ duration: 0.15 }}
className={cn("overflow-hidden", className)}
>
{/* Header */}
<div className="border-b border-border bg-fill-tertiary p-3">
<a
target="_blank"
rel="noopener noreferrer"
href={feed.siteUrl || feed.url}
className="flex items-center gap-2"
>
<FeedIcon target={feed} size={16} />
<div className="min-w-0 flex-1">
<div className="line-clamp-1 text-sm font-medium text-text">{feed.title}</div>
<span className="line-clamp-1 text-xs text-text-tertiary">{feed.url}</span>
</div>
</a>
</div>
{/* Content */}
<div className="p-3">
<div className="space-y-2">
<a
href={entry.url ?? "#"}
onClick={(e) => {
e.preventDefault()
onNavigate?.(entryId)
}}
className="contents"
target="_blank"
rel="noopener noreferrer"
>
<h3 className="line-clamp-2 text-sm font-semibold text-text">{entry.title}</h3>
{entry.description && (
<p className="line-clamp-3 text-xs text-text-secondary">{entry.description}</p>
)}
</a>
<div className="flex items-center justify-between pt-2">
<div className="text-xs text-text-tertiary">
{entry.author && <span>by {entry.author}</span>}
</div>
<div className="shrink-0 self-start text-xs text-text-tertiary">
<RelativeTime date={entry.publishedAt} />
</div>
</div>
</div>
</div>
</m.div>
</HoverCardContent>
</HoverCard>
)
}
@@ -0,0 +1,68 @@
import {
HoverCard,
HoverCardContent,
HoverCardTrigger,
} from "@follow/components/ui/hover-card/index.js"
import { useFeedById } from "@follow/store/feed/hooks"
import { feedIconSelector } from "@follow/store/feed/selectors"
import { cn } from "@follow/utils"
import { m } from "motion/react"
import * as React from "react"
import { FeedIcon } from "~/modules/feed/feed-icon"
interface FeedPreviewCardProps {
feedId: string
children: React.ReactNode
className?: string
onNavigate?: (feedId: string) => void
}
export const FeedPreviewCard: React.FC<FeedPreviewCardProps> = ({
feedId,
children,
className,
onNavigate,
}) => {
const feed = useFeedById(feedId, feedIconSelector)
if (!feed) {
return <>{children}</>
}
return (
<HoverCard openDelay={300} closeDelay={100}>
<HoverCardTrigger asChild>{children}</HoverCardTrigger>
<HoverCardContent className="w-80 p-0" side="top">
<m.div
initial={{ opacity: 0, scale: 0.95 }}
animate={{ opacity: 1, scale: 1 }}
transition={{ duration: 0.15 }}
className={cn("overflow-hidden", className)}
>
{/* Header */}
<a
className="border-b border-border bg-fill-tertiary p-4"
href={feed.url ?? "#"}
onClick={(e) => {
e.preventDefault()
onNavigate?.(feedId)
}}
target="_blank"
rel="noopener noreferrer"
>
<div className="flex items-start gap-3">
<FeedIcon target={feed} size={40} className="shrink-0" />
<div className="min-w-0 flex-1">
<div className="flex items-center gap-2">
<h3 className="line-clamp-1 text-sm font-semibold text-text">{feed.title}</h3>
</div>
</div>
</div>
</a>
</m.div>
</HoverCardContent>
</HoverCard>
)
}
@@ -0,0 +1,2 @@
export { EntryPreviewCard } from "./EntryPreviewCard"
export { FeedPreviewCard } from "./FeedPreviewCard"
@@ -37,7 +37,7 @@ export const KeyRecorder: FC<KeyRecorderProps> = ({ onChange, onBlur }) => {
})
return (
<div
className="text-text-secondary relative flex size-full items-center justify-center px-1 text-xs"
className="relative flex size-full items-center justify-center px-1 text-xs text-text-secondary"
tabIndex={-1}
role="textbox"
ref={ref}
@@ -49,13 +49,13 @@ export const KeyRecorder: FC<KeyRecorderProps> = ({ onChange, onBlur }) => {
</KbdCombined>
</div>
) : (
<span className="text-text-secondary pr-4">{t("settings.shortcuts.press_to_record")}</span>
<span className="pr-4 text-text-secondary">{t("settings.shortcuts.press_to_record")}</span>
)}
<Tooltip delayDuration={0}>
<TooltipTrigger asChild>
<button
type="button"
className="hover:text-text absolute inset-y-0 -right-1 z-[1] flex items-center justify-center px-1"
className="absolute inset-y-0 -right-1 z-[1] flex items-center justify-center px-1 hover:text-text"
onClick={(e) => {
e.stopPropagation()
if (currentKeys.length === 0) {
@@ -23,7 +23,7 @@ export const Markdown: Component<
<MarkdownRenderContainerRefContext value={refElement}>
<article
className={cn(
"prose dark:prose-invert prose-th:text-left relative cursor-auto select-text",
"prose relative cursor-auto select-text dark:prose-invert prose-th:text-left",
className,
)}
ref={setRefElement}
@@ -23,7 +23,6 @@ export interface ITocItem {
title: string
anchorId: string
index: number
$heading: HTMLHeadingElement
}
@@ -99,7 +98,7 @@ const TocContainer: React.FC<TocContainerProps> = ({
return (
<div
className={cn(
"scrollbar-none group relative overflow-auto opacity-60 duration-200 group-hover:opacity-100",
"group relative overflow-auto opacity-60 duration-200 scrollbar-none group-hover:opacity-100",
"flex flex-col",
className,
)}
@@ -130,12 +129,12 @@ const TocHoverCard: React.FC<TocHoverCardProps> = ({
const [hoverShow, setHoverShow] = useState(false)
return (
<div className="scrollbar-none flex grow flex-col scroll-smooth px-2">
<div className="flex grow flex-col scroll-smooth px-2 scrollbar-none">
<HoverCard.Root openDelay={100} open={hoverShow} onOpenChange={setHoverShow}>
<HoverCard.Trigger asChild>
<div
className={cn(
"scrollbar-none group overflow-auto opacity-60 duration-200 group-hover:opacity-100",
"group overflow-auto opacity-60 duration-200 scrollbar-none group-hover:opacity-100",
className,
)}
>
@@ -164,8 +163,8 @@ const TocHoverCard: React.FC<TocHoverCardProps> = ({
className={cn(
"relative z-10 -mt-1 rounded-xl border",
"px-3 py-1 text-xs",
"bg-material-ultra-thick backdrop-blur-background shadow-context-menu",
"scrollbar-none max-h-[calc(100svh-4rem)] overflow-auto",
"shadow-context-menu bg-material-ultra-thick backdrop-blur-background",
"max-h-[calc(100svh-4rem)] overflow-auto scrollbar-none",
)}
>
{toc.map((heading, index) => (
@@ -190,7 +189,7 @@ const TocHoverCard: React.FC<TocHoverCardProps> = ({
})
}}
>
<EllipsisHorizontalTextWithTooltip className="group-hover:text-accent/80 max-w-prose select-none truncate duration-200">
<EllipsisHorizontalTextWithTooltip className="max-w-prose select-none truncate duration-200 group-hover:text-accent/80">
{heading.title}
</EllipsisHorizontalTextWithTooltip>
@@ -6,7 +6,7 @@ export const BlockError = (props: { error: any; message: string }) => {
captureException(props.error)
}, [])
return (
<div className="center bg-red flex min-h-12 flex-col rounded py-4 text-sm text-white">
<div className="center flex min-h-12 flex-col rounded bg-red py-4 text-sm text-white">
{props.message}
<pre className="m-0 bg-transparent">{props.error?.message}</pre>
@@ -24,7 +24,7 @@ export const createHeadingRenderer =
{rest.children}
<span
className={cn(
"text-accent cursor-pointer select-none opacity-0 transition-opacity duration-200 group-hover:opacity-100",
"cursor-pointer select-none text-accent opacity-0 transition-opacity duration-200 group-hover:opacity-100",
"relative ml-2",
"@2xl:absolute @2xl:left-[-1.5em] @2xl:top-0 @2xl:opacity-0",
)}
@@ -51,7 +51,7 @@ export const MarkdownLink: Component<LinkProps> = (props) => {
<a
draggable="false"
className={cn(
"text-text follow-link--underline font-semibold no-underline",
"follow-link--underline font-semibold text-text no-underline",
props.className,
)}
href={populatedFullHref}
@@ -286,7 +286,7 @@ const MediaImpl: FC<MediaProps> = ({
className={cn(
"center",
!(finalWidth || finalHeight) && "size-full",
"cursor-card relative object-cover",
"relative cursor-card object-cover",
mediaContainerClassName,
)}
onClick={handleClick}
@@ -343,7 +343,7 @@ const MediaImpl: FC<MediaProps> = ({
>
<span
className={cn(
"bg-material-ultra-thick relative inline-block max-w-full",
"relative inline-block max-w-full bg-material-ultra-thick",
mediaContainerClassName,
)}
style={{
@@ -407,7 +407,7 @@ const MediaImpl: FC<MediaProps> = ({
{blurhash ? (
<Blurhash hash={blurhash} width="100%" height="100%" />
) : (
<div className="bg-border size-full" />
<div className="size-full bg-border" />
)}
</div>
<div className="absolute inset-0 flex items-center justify-center overflow-hidden rounded">
@@ -428,13 +428,13 @@ const FallbackMedia: FC<MediaProps> = ({ type, mediaContainerClassName, classNam
<div
className={cn(
"size-full",
"center bg-material-ultra-thick rounded",
"not-prose @container !flex max-h-full flex-col space-y-1 p-4",
"center rounded bg-material-ultra-thick",
"not-prose !flex max-h-full flex-col space-y-1 p-4 @container",
mediaContainerClassName,
)}
>
<div className="@sm:hidden @md:contents hidden">
<i className="i-mgc-close-cute-re text-red text-xl" />
<div className="hidden @sm:hidden @md:contents">
<i className="i-mgc-close-cute-re text-xl text-red" />
<p>Media loaded failed</p>
<div className="space-x-1 break-all px-4 text-sm">
Go to{" "}
@@ -165,7 +165,7 @@ const Wrapper: FC<{
animate={controls}
exit="exit"
custom={dragOffset}
className="bg-material-medium-dark flex size-full pt-[var(--fo-window-padding-top)] backdrop-blur"
className="flex size-full bg-material-medium-dark pt-[var(--fo-window-padding-top)] backdrop-blur"
drag={enableDragClose}
dragConstraints={{ top: 0, bottom: 300, left: -200, right: 200 }}
dragElastic={{ top: 0, bottom: 0.3, left: 0.2, right: 0.2 }}
@@ -186,7 +186,7 @@ const Wrapper: FC<{
</div>
{hasSideContent ? (
<div
className="bg-background box-border flex h-full w-[400px] min-w-0 shrink-0 flex-col px-2 pt-1"
className="box-border flex h-full w-[400px] min-w-0 shrink-0 flex-col bg-background px-2 pt-1"
onClick={stopPropagation}
>
{isArray ? renderedChildren[1] : null}
@@ -490,7 +490,7 @@ const FallbackableImage: FC<
)}
{currentState === "fallback" && (
<div className="bg-material-thick backdrop-blur-background text-text absolute bottom-8 left-1/2 mt-4 -translate-x-1/2 rounded-lg px-3 py-2 text-center text-xs opacity-70">
<div className="absolute bottom-8 left-1/2 mt-4 -translate-x-1/2 rounded-lg bg-material-thick px-3 py-2 text-center text-xs text-text opacity-70 backdrop-blur-background">
<span>
This image is preview in low quality, because the original image is not available.
</span>
@@ -501,7 +501,7 @@ const FallbackableImage: FC<
href={src}
target="_blank"
rel="noreferrer"
className="hover:text-accent underline duration-200"
className="underline duration-200 hover:text-accent"
>
visit the original image
</a>{" "}
@@ -100,21 +100,21 @@ export function SwipeMedia({
{emblaApi?.canScrollPrev() && (
<button
type="button"
className="center absolute left-2 top-1/2 size-6 -translate-y-1/2 rounded-full bg-gray-800 text-white opacity-0 duration-200 group-hover:opacity-100"
className="center absolute left-2 top-1/2 size-8 -translate-y-1/2 rounded-full border border-border bg-material-medium text-white opacity-0 backdrop-blur-background duration-200 group-hover:opacity-100"
onClick={scrollPrev}
onDoubleClick={stopPropagation}
>
<i className="i-mingcute-arrow-left-line" />
<i className="i-mingcute-left-line" />
</button>
)}
{emblaApi?.canScrollNext() && (
<button
type="button"
className="center absolute right-2 top-1/2 size-6 -translate-y-1/2 rounded-full bg-gray-800 text-white opacity-0 duration-200 group-hover:opacity-100"
className="center absolute right-2 top-1/2 size-8 -translate-y-1/2 rounded-full border border-border bg-material-medium text-white opacity-0 backdrop-blur-background duration-200 group-hover:opacity-100"
onClick={scrollNext}
onDoubleClick={stopPropagation}
>
<i className="i-mingcute-arrow-right-line" />
<i className="i-mingcute-right-line" />
</button>
)}
</div>
@@ -139,7 +139,7 @@ export const VideoPlayer = ({
return (
<Focusable
className="center group relative size-full"
className="group center relative size-full"
ref={wrapperRef}
scope={HotkeyScope.VideoPlayer}
>
@@ -230,7 +230,7 @@ const ControlBar = memo(() => {
dragMomentum={false}
dragConstraints={{ current: document.documentElement }}
className={cn(
"bg-material-thick backdrop-blur-background border-border absolute inset-x-2 bottom-2 h-8 rounded-2xl border",
"absolute inset-x-2 bottom-2 h-8 rounded-2xl border border-border bg-material-thick backdrop-blur-background",
"flex items-center gap-3 px-3",
"mx-auto max-w-[80vw]",
)}
@@ -31,13 +31,13 @@ export const PeekModal = (props: PropsWithChildren<PeekModalProps>) => {
return (
<RootPortalContext value={rootRef as HTMLElement}>
<div
className="scrollbar-none relative mx-auto mt-[10vh] max-w-full overflow-hidden px-2 lg:max-w-[65rem] lg:p-0"
className="relative mx-auto mt-[10vh] max-w-full overflow-hidden px-2 scrollbar-none lg:max-w-[65rem] lg:p-0"
ref={setRootRef}
>
<m.div
exit={{ opacity: 0, y: 50 }}
transition={{ duration: 0.2 }}
className="motion-preset-slide-up motion-duration-200 motion-ease-spring-smooth scrollbar-none overflow-hidden"
className="motion-preset-slide-up overflow-hidden motion-duration-200 motion-ease-spring-smooth scrollbar-none"
>
<InPeekModal value={true}>{children}</InPeekModal>
</m.div>
@@ -46,7 +46,7 @@ export const PeekModal = (props: PropsWithChildren<PeekModalProps>) => {
exit={{
opacity: 0,
}}
className="safe-inset-top-4 fixed right-4 flex items-center gap-4"
className="fixed right-4 flex items-center gap-4 safe-inset-top-4"
>
{props.rightActions?.map((action) => (
<GlassButton
@@ -10,7 +10,7 @@ export const ModalClose = () => {
return (
<MotionButtonBase
aria-label={t("words.close")}
className="hover:bg-material-ultra-thick absolute right-6 top-6 flex size-8 items-center justify-center rounded-md duration-200"
className="absolute right-6 top-6 flex size-8 items-center justify-center rounded-md duration-200 hover:bg-material-ultra-thick"
onClick={dismiss}
>
<i className="i-mgc-close-cute-re block" />
@@ -22,7 +22,7 @@ export const SlideUpModal: ModalTemplateType = (props) => {
const winHeight = useState(() => window.innerHeight)[0]
const { dismiss } = useCurrentModal()
return (
<div className={"center container h-full"} onPointerDown={dismiss} onClick={stopPropagation}>
<div className={"container center h-full"} onPointerDown={dismiss} onClick={stopPropagation}>
<m.div
onPointerDown={stopPropagation}
tabIndex={-1}
@@ -36,7 +36,7 @@ export const SlideUpModal: ModalTemplateType = (props) => {
}
}}
className={cn(
"bg-theme-background relative flex flex-col items-center overflow-hidden rounded-xl border p-8 pb-0",
"relative flex flex-col items-center overflow-hidden rounded-xl border bg-theme-background p-8 pb-0",
"aspect-[7/9] w-[600px] max-w-full shadow lg:max-h-[calc(100vh-10rem)]",
"motion-preset-slide-up motion-duration-200 motion-ease-spring-smooth",
props.className,
@@ -95,9 +95,9 @@ export const DrawerModalLayout: FC<PropsWithChildren> = ({ children }) => {
exit="exit"
layout="size"
className={cn(
"bg-theme-background flex flex-col items-center overflow-hidden rounded-xl border p-8 pb-0",
"flex flex-col items-center overflow-hidden rounded-xl border bg-theme-background p-8 pb-0",
"shadow-drawer-to-left w-[60ch] max-w-full",
"safe-inset-top-4 fixed bottom-4 right-2",
"fixed bottom-4 right-2 safe-inset-top-4",
)}
>
{children}
@@ -110,7 +110,7 @@ export const ScaleModal: ModalTemplateType = (props) => {
const { dismiss } = useCurrentModal()
return (
<div className={"center container h-full"} onPointerDown={dismiss} onClick={stopPropagation}>
<div className={"container center h-full"} onPointerDown={dismiss} onClick={stopPropagation}>
<m.div
onPointerDown={stopPropagation}
transition={Spring.presets.snappy}
@@ -143,12 +143,12 @@ export const useDialog = (): DialogInstance => {
confirmClassName: "",
},
warning: {
icon: <i className="i-mingcute-warning-fill text-yellow size-5" />,
icon: <i className="i-mingcute-warning-fill size-5 text-yellow" />,
confirmVariant: "primary" as const,
confirmClassName: "bg-yellow-500",
},
danger: {
icon: <i className="i-mingcute-warning-fill text-red size-5" />,
icon: <i className="i-mingcute-warning-fill size-5 text-red" />,
confirmVariant: "primary" as const,
confirmClassName: "bg-red-500",
},
@@ -112,6 +112,7 @@ export const ModalInternal = memo(function Modal({
setStack((p) => p.filter((modal) => modal.id !== item.id))
}
item.onClose?.()
onPropsClose?.(false)
})
@@ -345,7 +346,7 @@ export const ModalInternal = memo(function Modal({
"bg-background",
"shadow-modal [transform-style:preserve-3d]",
max ? "h-[90vh] w-[90vw]" : "max-h-[90vh]",
"border-border border",
"border border-border",
modalClassName,
)}
tabIndex={-1}
@@ -370,10 +371,10 @@ export const ModalInternal = memo(function Modal({
defaultSize={resizeDefaultSize}
className="flex grow flex-col"
>
<div className={"bg-background relative z-10 flex flex-col"}>
<div className={"relative z-10 flex flex-col bg-background"}>
<div className={"flex items-center"}>
<Dialog.Title
className="text-text flex w-0 max-w-full grow items-center gap-2 px-2 pb-1 pt-2 text-base font-medium"
className="flex w-0 max-w-full grow items-center gap-2 px-2 pb-1 pt-2 text-base font-medium text-text"
onPointerDownCapture={handleDrag}
onPointerDown={relocateModal}
>
@@ -384,7 +385,7 @@ export const ModalInternal = memo(function Modal({
</Dialog.Title>
{canClose && (
<Dialog.DialogClose
className="center hover:bg-fill-quaternary text-text-secondary hover:text-text z-[2] -mr-1 rounded-lg p-2"
className="center z-[2] -mr-1 rounded-lg p-2 text-text-secondary hover:bg-fill-quaternary hover:text-text"
tabIndex={1}
onClick={close}
>
@@ -394,13 +395,13 @@ export const ModalInternal = memo(function Modal({
</div>
{(title || icon || canClose) && (
<div className="bg-border mx-1 mt-1 h-px shrink-0" />
<div className="mx-1 mt-1 h-px shrink-0 bg-border" />
)}
</div>
<div
className={cn(
"text-text -mx-2 min-h-0 shrink grow overflow-auto overflow-x-hidden px-4 pb-4 pt-3 text-sm",
"-mx-2 min-h-0 shrink grow overflow-auto overflow-x-hidden px-4 pb-4 pt-3 text-sm text-text",
modalContentClassName,
)}
>
@@ -20,7 +20,7 @@ export const ModalOverlay: FC<{
id="modal-overlay"
className={cn(
// NOTE: pointer-events-none is required, if remove this, when modal is closing, you can not click element behind the modal
"bg-material-ultra-thick !pointer-events-none fixed inset-0 rounded-[var(--fo-window-radius)]",
"!pointer-events-none fixed inset-0 rounded-[var(--fo-window-radius)] bg-material-ultra-thick",
blur && "backdrop-blur-sm",
className,
)}
@@ -31,6 +31,7 @@ export interface ModalProps {
modal?: boolean
autoFocus?: boolean
onClose?: () => void
}
export interface DialogInstance {
@@ -6,9 +6,9 @@ export const Paper: Component<{
}> = ({ children, className, as: As = "main" }) => (
<As
className={cn(
"bg-background relative md:col-start-1 lg:col-auto",
"relative bg-background md:col-start-1 lg:col-auto",
"-m-4 p-[2rem_1rem] md:m-0 lg:p-[30px_45px]",
"border-border rounded-lg lg:border",
"rounded-lg border-border lg:border",
"shadow-perfect perfect-sm",
"min-w-0",
"print:!border-none print:!bg-transparent print:!shadow-none",
@@ -1,7 +1,7 @@
import { usePrefetchEntryDetail } from "@follow/store/entry/hooks"
import { Paper } from "~/components/ui/paper"
import { EntryContent as EntryContentLegacy } from "~/modules/entry-content/components/entry-content/EntryContent.legacy"
import { EntryContent as EntryContentLegacy } from "~/modules/entry-content/EntryContent.legacy"
export const EntryModalPreview = ({ entryId }: { entryId: string }) => {
const { isPending } = usePrefetchEntryDetail(entryId)
@@ -24,39 +24,39 @@ const PeekModalSkeleton = () => {
return (
<div className="animate-pulse p-5">
<div className="mb-6 space-y-3">
<div className="bg-fill h-8 w-3/4 rounded-lg" />
<div className="h-8 w-3/4 rounded-lg bg-fill" />
<div className="flex items-center space-x-4">
<div className="bg-fill-secondary h-4 w-20 rounded" />
<div className="bg-fill-secondary h-4 w-16 rounded" />
<div className="bg-fill-secondary h-4 w-24 rounded" />
<div className="h-4 w-20 rounded bg-fill-secondary" />
<div className="h-4 w-16 rounded bg-fill-secondary" />
<div className="h-4 w-24 rounded bg-fill-secondary" />
</div>
</div>
<div className="space-y-4">
<div className="space-y-3">
<div className="bg-fill-secondary h-4 w-full rounded" />
<div className="bg-fill-secondary h-4 w-5/6 rounded" />
<div className="bg-fill-secondary h-4 w-4/5 rounded" />
<div className="h-4 w-full rounded bg-fill-secondary" />
<div className="h-4 w-5/6 rounded bg-fill-secondary" />
<div className="h-4 w-4/5 rounded bg-fill-secondary" />
</div>
<div className="space-y-3">
<div className="bg-fill-secondary h-4 w-full rounded" />
<div className="bg-fill-secondary h-4 w-3/4 rounded" />
<div className="h-4 w-full rounded bg-fill-secondary" />
<div className="h-4 w-3/4 rounded bg-fill-secondary" />
</div>
<div className="bg-fill my-6 h-48 w-full rounded-lg" />
<div className="my-6 h-48 w-full rounded-lg bg-fill" />
<div className="space-y-3">
<div className="bg-fill-secondary h-4 w-full rounded" />
<div className="bg-fill-secondary h-4 w-5/6 rounded" />
<div className="bg-fill-secondary h-4 w-2/3 rounded" />
<div className="h-4 w-full rounded bg-fill-secondary" />
<div className="h-4 w-5/6 rounded bg-fill-secondary" />
<div className="h-4 w-2/3 rounded bg-fill-secondary" />
</div>
</div>
<div className="mt-8 flex items-center space-x-3">
<div className="bg-fill h-8 w-16 rounded" />
<div className="bg-fill h-8 w-20 rounded" />
<div className="bg-fill h-8 w-16 rounded" />
<div className="h-8 w-16 rounded bg-fill" />
<div className="h-8 w-20 rounded bg-fill" />
<div className="h-8 w-16 rounded bg-fill" />
</div>
</div>
)
@@ -82,7 +82,7 @@ export const EntryToastPreview = ({ entryId }: { entryId: string }) => {
exit="exit"
layout="size"
className={cn(
"shadow-perfect bg-theme-background relative flex flex-col items-center rounded-xl border p-8",
"shadow-perfect relative flex flex-col items-center rounded-xl border bg-theme-background p-8",
"mr-4 mt-4 max-h-[500px] w-[60ch] max-w-full overflow-auto",
)}
>
@@ -7,6 +7,7 @@ export const QUERY_PERSIST_KEY = getStorageNS("REACT_QUERY_OFFLINE_CACHE")
export const I18N_LOCALE_KEY = getStorageNS("I18N_LOCALE")
/// Route Keys
export const ROUTE_VIEW_ALL = "all"
export const ROUTE_FEED_PENDING = "all"
export const ROUTE_ENTRY_PENDING = "pending"
export const ROUTE_FEED_IN_FOLDER = "folder-"
@@ -1,14 +1,20 @@
import { useEntry } from "@follow/store/entry/hooks"
import type { EntryModel } from "@follow/store/entry/types"
import { useRouteParamsSelector } from "./useRouteParams"
export function useEntryIsRead<T extends { read: Nullable<boolean> }>(entry?: T | null) {
const selector = (state: EntryModel) => state.read
export function useEntryIsRead(entryId?: string) {
const entryRead = useEntry(entryId, selector)
return useRouteParamsSelector(
(params) => {
if (params.isCollection) {
return true
}
if (!entry) return false
return entry.read
if (entryRead === undefined) return false
return entryRead
},
[entry?.read],
[entryRead],
)
}
@@ -1,5 +1,5 @@
import { isMobile } from "@follow/components/hooks/useMobile.js"
import { FeedViewType, UserRole, views } from "@follow/constants"
import { FeedViewType, getView, UserRole } from "@follow/constants"
import { IN_ELECTRON } from "@follow/shared/constants"
import { useIsEntryStarred } from "@follow/store/collection/hooks"
import { useEntry } from "@follow/store/entry/hooks"
@@ -7,7 +7,6 @@ import { entrySyncServices } from "@follow/store/entry/store"
import type { EntryModel } from "@follow/store/entry/types"
import { useFeedById } from "@follow/store/feed/hooks"
import { useIsInbox } from "@follow/store/inbox/hooks"
import { whoami } from "@follow/store/user/getters"
import { useUserRole } from "@follow/store/user/hooks"
import { doesTextContainHTML } from "@follow/utils/utils"
import { useMemo } from "react"
@@ -301,16 +300,6 @@ export const useEntryActions = ({ entryId, view }: { entryId: string; view: Feed
hide: !IN_ELECTRON || !entry.hasBitTorrent,
entryId,
}),
new EntryActionMenuItem({
id: COMMAND_ID.entry.tip,
onClick: runCmdFn(COMMAND_ID.entry.tip, [
{ entryId, feedId: feed?.id, userId: feed?.ownerUserId },
]),
hide: isInbox || feed?.ownerUserId === whoami()?.id,
// shortcut: shortcuts.entry.tip.key,
shortcut: shortcuts[COMMAND_ID.entry.tip],
entryId,
}),
new EntryActionMenuItem({
id: COMMAND_ID.entry.star,
onClick: runCmdFn(COMMAND_ID.entry.star, [{ entryId, view }]),
@@ -428,10 +417,7 @@ export const useEntryActions = ({ entryId, view }: { entryId: string; view: Feed
new EntryActionMenuItem({
id: COMMAND_ID.entry.readability,
onClick: runCmdFn(COMMAND_ID.entry.readability, [{ entryId, entryUrl: entry.url! }]),
hide:
!!entry.readability ||
(view && views.find((v) => v.view === view)?.wideMode) ||
!entry.url,
hide: !!entry.readability || (view && getView(view)?.wideMode) || !entry.url,
active: isEntryInReadability,
notice: !entry.doesContentContainsHTMLTags && !isEntryInReadability,
entryId,
@@ -21,11 +21,9 @@ import { toast } from "sonner"
import type { FollowMenuItem, MenuItemInput } from "~/atoms/context-menu"
import { MenuItemSeparator, MenuItemText } from "~/atoms/context-menu"
import { useIsInMASReview } from "~/atoms/server-configs"
import { useModalStack } from "~/components/ui/modal/stacked/hooks"
import { copyToClipboard } from "~/lib/clipboard"
import { UrlBuilder } from "~/lib/url-builder"
import { useBoostModal } from "~/modules/boost/hooks"
import { useFeedClaimModal } from "~/modules/claim"
import { COMMAND_ID } from "~/modules/command/commands/id"
import { useCommandShortcuts } from "~/modules/command/hooks/use-command-binding"
@@ -83,15 +81,12 @@ export const useFeedActions = ({
const { mutateAsync: resetFeed } = useResetFeed()
const { mutate: addFeedsToCategoryMutation } = useBatchUpdateSubscription()
const presentCategoryCreationModal = useCategoryCreationModal()
const openBoostModal = useBoostModal()
const listByView = useOwnedListByView(view!)
const categories = useCategoriesByView(view!)
const isMultipleSelection = feedIds && feedIds.length > 1 && feedIds.includes(feedId)
const isInMASReview = useIsInMASReview()
const shortcuts = useCommandShortcuts()
const items = useMemo(() => {
@@ -136,17 +131,6 @@ export const useFeedActions = ({
MenuItemSeparator.default,
]
: []),
...(!isInMASReview
? [
new MenuItemText({
label: t("words.boost"),
click: () => {
openBoostModal(feedId)
},
}),
]
: []),
new MenuItemSeparator(isEntryList),
new MenuItemText({
label: t("sidebar.feed_column.context_menu.add_feeds_to_list"),
@@ -335,12 +319,10 @@ export const useFeedActions = ({
feedIds,
inbox,
isEntryList,
isInMASReview,
isInbox,
isMultipleSelection,
listByView,
navigateEntry,
openBoostModal,
present,
presentCategoryCreationModal,
presentDeleteSubscription,
@@ -1,7 +1,7 @@
import { getReadonlyRoute, getStableRouterNavigate } from "@follow/components/atoms/route.js"
import { useMobile } from "@follow/components/hooks/useMobile.js"
import { useSheetContext } from "@follow/components/ui/sheet/context.js"
import type { FeedViewType } from "@follow/constants"
import { FeedViewType } from "@follow/constants"
import { getEntry } from "@follow/store/entry/getter"
import { getSubscriptionByFeedId } from "@follow/store/subscription/getter"
import { tracker } from "@follow/tracker"
@@ -19,6 +19,7 @@ import {
ROUTE_FEED_IN_LIST,
ROUTE_FEED_PENDING,
ROUTE_TIMELINE_OF_VIEW,
ROUTE_VIEW_ALL,
} from "~/constants"
import { useRouteParamsSelector } from "./useRouteParams"
@@ -85,7 +86,8 @@ const parseNavigateEntryOptions = (options: NavigateEntryOptions): ParsedNavigat
finalFeedId = encodeURIComponent(finalFeedId)
if (finalView !== undefined && !timelineId) {
finalTimelineId = `${ROUTE_TIMELINE_OF_VIEW}${finalView}`
finalTimelineId =
finalView === FeedViewType.All ? ROUTE_VIEW_ALL : `${ROUTE_TIMELINE_OF_VIEW}${finalView}`
}
return {
@@ -1,6 +1,9 @@
import { useEntry } from "@follow/store/entry/hooks"
import { useCallback } from "react"
import { disableShowAISummaryOnce } from "~/atoms/ai-summary"
import { disableShowAITranslationOnce } from "~/atoms/ai-translation"
import { resetShowSourceContent } from "~/atoms/source-content"
import { PeekModal } from "~/components/ui/modal/inspire/PeekModal"
import { PlainModal } from "~/components/ui/modal/stacked/custom-modal"
import { useModalStack } from "~/components/ui/modal/stacked/hooks"
@@ -58,6 +61,11 @@ export const usePeekModal = () => {
},
content: () => <EntryModalPreview entryId={entryId} />,
overlay: true,
onClose: () => {
disableShowAISummaryOnce()
disableShowAITranslationOnce()
resetShowSourceContent()
},
})
}
},
@@ -17,6 +17,7 @@ import {
ROUTE_FEED_IN_LIST,
ROUTE_FEED_PENDING,
ROUTE_TIMELINE_OF_VIEW,
ROUTE_VIEW_ALL,
} from "~/constants"
export const useRouteEntryId = () => {
@@ -42,6 +43,16 @@ export interface BizRouteParams {
timelineId?: string
}
export function parseView(input: string | undefined): FeedViewType | undefined {
if (input === ROUTE_VIEW_ALL) return FeedViewType.All
if (input?.startsWith(ROUTE_TIMELINE_OF_VIEW)) {
const view = Number.parseInt(input?.slice(ROUTE_TIMELINE_OF_VIEW.length), 10)
if (Object.values(FeedViewType).includes(view)) {
return view as FeedViewType
}
}
}
const parseRouteParams = (params: Params<any>, _searchParams: URLSearchParams): BizRouteParams => {
const listId = params.feedId?.startsWith(ROUTE_FEED_IN_LIST)
? params.feedId.slice(ROUTE_FEED_IN_LIST.length)
@@ -49,12 +60,7 @@ const parseRouteParams = (params: Params<any>, _searchParams: URLSearchParams):
const list = listId ? getListById(listId) : undefined
return {
view: params.timelineId?.startsWith(ROUTE_TIMELINE_OF_VIEW)
? (Number.parseInt(
params.timelineId.slice(ROUTE_TIMELINE_OF_VIEW.length),
10,
) as FeedViewType)
: (list?.view ?? FeedViewType.Articles),
view: parseView(params.timelineId) ?? list?.view ?? FeedViewType.Articles,
entryId: params.entryId || undefined,
feedId: params.feedId || undefined,
// alias
@@ -0,0 +1,19 @@
import { FeedViewType } from "@follow/constants"
import { AIChatPanelStyle, useAIChatPanelStyle, useAIPanelVisibility } from "~/atoms/settings/ai"
import { useRouteParamsSelector } from "~/hooks/biz/useRouteParams"
export const useShowEntryDetailsColumn = () => {
const { view, isInEntry } = useRouteParamsSelector((s) => ({
view: s.view,
isInEntry: s.entryId && !s.isPendingEntry,
}))
const aiPanelStyle = useAIChatPanelStyle()
const isAIPanelVisible = useAIPanelVisibility()
return (
(view === FeedViewType.All || view === FeedViewType.Articles) &&
(aiPanelStyle === AIChatPanelStyle.Floating || !isAIPanelVisible) &&
isInEntry
)
}
@@ -57,7 +57,7 @@ export const useDeleteSubscription = ({ onSuccess }: { onSuccess?: () => void }
label: (
<span className={"flex items-center gap-1 px-1"}>
{t("words.undo")}
<Kbd className="border-border inline-flex items-center border bg-transparent text-white">
<Kbd className="inline-flex items-center border border-border bg-transparent text-white">
$mod+Z
</Kbd>
</span>
@@ -88,7 +88,7 @@ const UnfollowInfo = ({ title, undo }: { title: string; undo: () => any }) => {
preventDefault: true,
})
return (
<span className="text-text font-medium">
<span className="font-medium text-text">
<Trans
ns="app"
i18nKey="notify.unfollow_feed"
@@ -1,22 +1,44 @@
import { FeedViewType } from "@follow/constants"
import { useViewWithSubscription } from "@follow/store/subscription/hooks"
import { useMemo } from "react"
import { useFeature } from "~/hooks/biz/useFeature"
import { useUISettingKey } from "~/atoms/settings/ui"
import { ROUTE_VIEW_ALL } from "~/constants/app"
export const useTimelineList = () => {
export const useTimelineList = (options?: {
ordered?: boolean
visible?: boolean
hidden?: boolean
withAll?: boolean
}) => {
const timelineTabs = useUISettingKey("timelineTabs")
const views = useViewWithSubscription()
// because the All view is highly tied to the AI
// so we need to filter it out if the AI is not enabled
const aiEnabled = useFeature("ai")
const viewsIds = useMemo(() => {
const ids = views.map((view) => `view-${view}`)
if (!options?.ordered) {
return ids
}
const savedVisible = (timelineTabs?.visible ?? []).filter((id) => ids.includes(id))
const savedHidden = (timelineTabs?.hidden ?? []).filter((id) => ids.includes(id))
const extra = ids.filter((id) => !savedVisible.includes(id) && !savedHidden.includes(id))
const filteredViews = useMemo(
() => (aiEnabled ? views : views.filter((v) => v !== FeedViewType.All)),
[views, aiEnabled],
)
const visible = [...savedVisible, ...extra].slice(0, 5)
if (options?.visible) return visible
const hidden = [...savedHidden, ...extra].filter((id) => !visible.includes(id))
if (options?.hidden) return hidden
const viewsIds = useMemo(() => filteredViews.map((view) => `view-${view}`), [filteredViews])
const ordered = [...visible, ...hidden]
return ordered
}, [
options?.hidden,
options?.ordered,
options?.visible,
timelineTabs?.hidden,
timelineTabs?.visible,
views,
])
return viewsIds
return useMemo(() => {
return options?.withAll ? [ROUTE_VIEW_ALL, ...viewsIds] : viewsIds
}, [options?.withAll, viewsIds])
}
+2
View File
@@ -13,6 +13,8 @@ import { jotaiStore } from "./lib/jotai"
export const i18nAtom = atom(i18next)
export const getI18n = () => jotaiStore.get(i18nAtom)
export const langChain = new Chain()
export class LocaleCache {
@@ -1,28 +0,0 @@
import type { SupportedActionLanguage } from "@follow/shared"
import { ACTION_LANGUAGE_MAP } from "@follow/shared"
import { parseHtml } from "@follow/utils/html"
import { duplicateIfLengthLessThan } from "@follow/utils/utils"
import { franc } from "franc-min"
export const checkLanguage = ({
content,
language,
}: {
content: string
language: SupportedActionLanguage
}) => {
if (!content) return true
const pureContent = parseHtml(content)
.toText()
.replaceAll(/https?:\/\/\S+|www\.\S+/g, " ")
const { code } = ACTION_LANGUAGE_MAP[language] ?? {}
if (!code) {
return false
}
const sourceLanguage = franc(duplicateIfLengthLessThan(pureContent, 20), {
only: [code],
})
return sourceLanguage === code
}
@@ -34,7 +34,6 @@ enum AchievementsActionIdMap {
// TODO
// FOLLOW_SPECIAL_FEED = 6,
ALPHA_TESTER = 7,
FEED_BOOSTER = 8,
}
const achievementActionIdMetaMap: Record<
@@ -80,10 +79,6 @@ const achievementActionIdMetaMap: Record<
description: "achievement.alpha_tester_description",
video: "https://assets.folo.is/AlphaBadge.webm",
},
[AchievementsActionIdMap.FEED_BOOSTER]: {
title: "achievement.feed_booster",
description: "achievement.feed_booster_description",
},
}
const prefetchVideos = () => {
@@ -200,7 +195,7 @@ export const AchievementModalContent: FC = () => {
<div className="mt-4 text-xl font-bold">{t("words.achievement")}</div>
<small className="text-text-secondary mt-1 gap-1">
<small className="mt-1 gap-1 text-text-secondary">
{t("achievement.description")}
<sup className="inline-block translate-y-1 text-xs">*</sup>
</small>
@@ -227,7 +222,7 @@ export const AchievementModalContent: FC = () => {
{copy.video && achievement.type === "received" && (
<MotionButtonBase
className="hover:text-accent p-1 duration-200"
className="p-1 duration-200 hover:text-accent"
onClick={() => {
presentBadgeVideo(achievement.actionId)
}}
@@ -236,7 +231,7 @@ export const AchievementModalContent: FC = () => {
</MotionButtonBase>
)}
</div>
<div className="text-text-secondary flex items-center text-sm">
<div className="flex items-center text-sm text-text-secondary">
{t(copy.description)}
</div>
</div>
@@ -265,7 +260,7 @@ export const AchievementModalContent: FC = () => {
className={styledButtonVariant({
variant: "outline",
className: [
"dark:text-text relative gap-1 border-green-200 !bg-green-100/50 text-green-800 dark:border-green-200/20 dark:!bg-green-100/5",
"relative gap-1 border-green-200 !bg-green-100/50 text-green-800 dark:border-green-200/20 dark:!bg-green-100/5 dark:text-text",
copy.video ? "cursor-button" : "cursor-default",
],
})}
@@ -286,7 +281,7 @@ export const AchievementModalContent: FC = () => {
className={styledButtonVariant({
variant: "outline",
className:
"dark:text-text relative cursor-not-allowed gap-1 border-zinc-200 !bg-zinc-100/50 text-zinc-800 dark:border-zinc-200/20 dark:!bg-zinc-100/5",
"relative cursor-not-allowed gap-1 border-zinc-200 !bg-zinc-100/50 text-zinc-800 dark:border-zinc-200/20 dark:!bg-zinc-100/5 dark:text-text",
})}
>
Validating...
@@ -308,7 +303,7 @@ export const AchievementModalContent: FC = () => {
</ul>
</ScrollArea>
<p className="text-text-tertiary mt-4 pb-4 text-xs">* {t("achievement.nft_coming_soon")}</p>
<p className="mt-4 pb-4 text-xs text-text-tertiary">* {t("achievement.nft_coming_soon")}</p>
</div>
)
}
@@ -420,19 +415,19 @@ const IncompleteButton: FC<{
<div className="center absolute z-[1] opacity-0 duration-200 group-hover:opacity-100">
<i
className={cn(
"i-mgc-refresh-2-cute-re text-accent size-5",
"i-mgc-refresh-2-cute-re size-5 text-accent",
checkPending && "animate-spin",
)}
/>
</div>
<div className="duration-200 group-hover:opacity-30">
<span className="center relative ml-2 inline-flex w-24 -translate-y-1 flex-col *:!m-0">
<small className="text-text shrink-0 text-xs leading-tight">
<small className="shrink-0 text-xs leading-tight text-text">
{achievement.progress} / {achievement.progressMax}
</small>
<span className="bg-accent/10 relative h-1 w-full overflow-hidden rounded-full">
<span className="relative h-1 w-full overflow-hidden rounded-full bg-accent/10">
<span
className="bg-accent absolute -left-3 top-0 inline-block h-1 rounded-full"
className="absolute -left-3 top-0 inline-block h-1 rounded-full bg-accent"
style={{
width: `calc(${Math.min(
(achievement.progress / achievement.progressMax) * 100,
@@ -1,20 +1,25 @@
import { Button } from "@follow/components/ui/button/index.js"
import { LoadingWithIcon } from "@follow/components/ui/loading/index.jsx"
import * as ScrollArea from "@follow/components/ui/scroll-area/ScrollArea.js"
import {
useActionRules,
useIsActionDataDirty,
usePrefetchActions,
useUpdateActionsMutation,
} from "@follow/store/action/hooks"
import type { ActionItem } from "@follow/store/action/store"
import { actionActions } from "@follow/store/action/store"
import { nextFrame } from "@follow/utils"
import { JsonObfuscatedCodec } from "@follow/utils/json-codec"
import { cn } from "@follow/utils/utils"
import { useQueryClient } from "@tanstack/react-query"
import { m } from "motion/react"
import { useEffect } from "react"
import { useCallback, useEffect, useState } from "react"
import { useTranslation } from "react-i18next"
import { unstable_usePrompt } from "react-router"
import { toast } from "sonner"
import { MenuItemText, useShowContextMenu } from "~/atoms/context-menu"
import { HeaderActionButton, HeaderActionGroup } from "~/components/ui/button/HeaderActionButton"
import {
DropdownMenu,
@@ -23,9 +28,16 @@ import {
DropdownMenuSeparator,
DropdownMenuTrigger,
} from "~/components/ui/dropdown-menu/dropdown-menu.js"
import { useDialog } from "~/components/ui/modal/stacked/hooks"
import { useContextMenu } from "~/hooks/common/useContextMenu"
import { copyToClipboard, readFromClipboard } from "~/lib/clipboard"
import { downloadJsonFile, selectJsonFile } from "~/lib/export"
import { RuleCard } from "~/modules/action/rule-card"
import {
buildActionSummary,
buildConditionSummary,
getRuleDisplayName,
} from "~/modules/action/rule-summary"
import { useSetSubViewRightView } from "../app-layout/subview/hooks"
import { generateExportFilename } from "./utils"
@@ -37,21 +49,21 @@ const EmptyActionPlaceholder = () => {
<div className="relative flex min-h-96 w-full items-center justify-center">
<div className="flex flex-col items-center gap-6 text-center">
{/* Simple icon */}
<div className="bg-fill-quaternary flex size-16 items-center justify-center rounded-2xl">
<i className="i-mgc-magic-2-cute-re text-text-secondary size-8" />
<div className="flex size-14 items-center justify-center rounded-lg border border-fill-secondary bg-fill-quinary">
<i className="i-mgc-magic-2-cute-re size-7 text-text-secondary" />
</div>
<div className="space-y-2">
<h2 className="text-text text-xl font-semibold">
<h2 className="text-lg font-semibold text-text">
{t("actions.action_card.empty.title")}
</h2>
<p className="text-text-secondary max-w-sm text-sm">
<p className="max-w-sm text-sm text-text-secondary">
{t("actions.action_card.empty.description")}
</p>
</div>
</div>
<m.div
className="absolute -top-6 right-20"
className="fixed right-20 top-12 z-[1000]"
animate={{
x: [0, 8, 0],
y: [0, -4, 0],
@@ -63,9 +75,9 @@ const EmptyActionPlaceholder = () => {
ease: "easeInOut",
}}
>
<div className="text-text-tertiary flex items-center gap-2">
<div className="flex items-center gap-2 text-text-secondary">
<span className="text-sm font-medium">{t("actions.action_card.empty.start")}</span>
<i className="i-mgc-arrow-right-up-cute-re size-6" />
<i className="i-mgc-arrow-right-up-cute-re size-5" />
</div>
</m.div>
</div>
@@ -74,9 +86,22 @@ const EmptyActionPlaceholder = () => {
export const ActionSetting = () => {
const actions = useActionRules()
const { t } = useTranslation("settings")
const [selectedRuleIndex, setSelectedRuleIndex] = useState(0)
const actionQuery = usePrefetchActions()
useEffect(() => {
if (actions.length === 0) {
setSelectedRuleIndex(0)
return
}
if (selectedRuleIndex > actions.length - 1) {
setSelectedRuleIndex(actions.length - 1)
}
}, [actions.length, selectedRuleIndex])
if (actionQuery.isPending) {
return (
<LoadingWithIcon
@@ -89,47 +114,66 @@ export const ActionSetting = () => {
const hasActions = actions.length > 0
const handleCreateRule = () => {
const nextIndex = actions.length
actionActions.addRule((number) => t("actions.actionName", { number }))
setSelectedRuleIndex(nextIndex)
}
return (
<div className="flex w-full flex-col gap-6">
<ActionButtonGroup />
<>
<ActionButtonGroup onCreateRule={handleCreateRule} />
<ShareImportSection />
{hasActions ? (
<div className="@container flex flex-col gap-6">
{actions.map((_, actionIdx) => {
return <RuleCard key={actionIdx} index={actionIdx} />
})}
<div className="flex min-h-0 w-full flex-1 flex-col @[960px]:absolute @[960px]:inset-x-0 @[960px]:bottom-0 @[960px]:top-12">
<div className="hidden h-full flex-1 @[960px]:flex @[960px]:h-0 @[960px]:overflow-hidden @[960px]:rounded-lg @[960px]:border @[960px]:border-fill-secondary">
<RuleList
selectedIndex={selectedRuleIndex}
onSelect={setSelectedRuleIndex}
onDelete={(deletedIndex) => {
// Adjust selectedRuleIndex when a rule is deleted
if (deletedIndex === selectedRuleIndex) {
// If deleting the selected rule, select the previous one or 0
setSelectedRuleIndex(Math.max(0, deletedIndex - 1))
} else if (deletedIndex < selectedRuleIndex) {
// If deleting a rule before the selected one, shift the index down
setSelectedRuleIndex(selectedRuleIndex - 1)
}
}}
/>
<div className="flex flex-1 border-l border-fill-secondary">
<RuleCard index={selectedRuleIndex} mode="detail" />
</div>
</div>
<div className="flex flex-col gap-3 @[960px]:hidden">
{actions.map((_, actionIdx) => (
<RuleCard
key={actionIdx}
index={actionIdx}
mode="compact"
defaultOpen={actionIdx === selectedRuleIndex}
onOpenChange={(open) => {
if (open) {
setSelectedRuleIndex(actionIdx)
}
}}
/>
))}
</div>
</div>
) : (
<EmptyActionPlaceholder />
)}
</div>
</>
)
}
const ActionButtonGroup = () => {
const queryClient = useQueryClient()
const actionLength = useActionRules((actions) => actions.length)
const isDirty = useIsActionDataDirty()
const ShareImportSection = () => {
const { t } = useTranslation("settings")
unstable_usePrompt({
message: t("actions.navigate.prompt"),
when: ({ currentLocation, nextLocation }) =>
isDirty && currentLocation.pathname !== nextLocation.pathname,
})
const actionLength = useActionRules((actions) => actions.length)
const hasActions = actionLength > 0
const mutation = useUpdateActionsMutation({
onSuccess: () => {
// apply new action settings
queryClient.invalidateQueries({
queryKey: ["entries"],
})
toast(t("actions.saveSuccess"))
},
onError: (error) => {
toast.error(error)
},
})
const handleExport = () => {
const handleExport = useCallback(() => {
try {
const jsonData = actionActions.exportRules()
const filename = generateExportFilename()
@@ -138,9 +182,9 @@ const ActionButtonGroup = () => {
} catch {
toast.error("Failed to export action rules")
}
}
}, [])
const handleImport = async () => {
const handleImport = useCallback(async () => {
try {
const jsonData = await selectJsonFile()
const result = actionActions.importRules(jsonData)
@@ -152,28 +196,26 @@ const ActionButtonGroup = () => {
}
} catch (error) {
if (error instanceof Error && error.message === "No file selected") {
// User cancelled file selection, don't show error
return
}
toast.error("Failed to import action rules")
}
}
}, [])
const foloPrefix = "folo:actions#"
const handleCopyToClipboard = async () => {
const handleCopyToClipboard = useCallback(async () => {
try {
const jsonData = actionActions.exportRules()
const codecData = JsonObfuscatedCodec.encode(jsonData)
await copyToClipboard(`${foloPrefix}${codecData}`)
toast.success("Action rules copied to clipboard")
} catch (error) {
toast.error("Failed to copy action rules to clipboard")
console.error(error)
}
}
}, [foloPrefix])
const handleImportFromClipboard = async () => {
const handleImportFromClipboard = useCallback(async () => {
try {
const clipboardData = await readFromClipboard()
if (!clipboardData.startsWith(foloPrefix)) {
@@ -181,9 +223,7 @@ const ActionButtonGroup = () => {
return
}
const codecData = clipboardData.slice(foloPrefix.length)
const jsonData = JsonObfuscatedCodec.decode(codecData)
const result = actionActions.importRules(jsonData)
if (result.success) {
@@ -199,19 +239,201 @@ const ActionButtonGroup = () => {
}
console.error(error)
}
}, [foloPrefix])
return (
<div className="mb-4 flex justify-end">
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
variant="ghost"
size="sm"
buttonClassName="size-9 p-0"
aria-label={
hasActions
? t("actions.action_card.summary.share")
: t("actions.action_card.summary.import")
}
>
<i
className={cn(
"size-4",
hasActions ? "i-mgc-share-forward-cute-re" : "i-mgc-file-import-cute-re",
)}
/>
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-56">
<DropdownMenuItem onClick={handleExport} disabled={!hasActions}>
<i className="i-mgc-download-2-cute-re mr-3 size-4" />
{t("actions.action_card.summary.export")}
</DropdownMenuItem>
<DropdownMenuItem onClick={handleImport}>
<i className="i-mgc-file-upload-cute-re mr-3 size-4" />
{t("actions.action_card.summary.import_file")}
</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem onClick={handleCopyToClipboard} disabled={!hasActions}>
<i className="i-mgc-copy-2-cute-re mr-3 size-4" />
{t("actions.action_card.summary.copy")}
</DropdownMenuItem>
<DropdownMenuItem onClick={handleImportFromClipboard}>
<i className="i-mgc-paste-cute-re mr-3 size-4" />
{t("actions.action_card.summary.import_clipboard")}
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</div>
)
}
const RuleList = ({
selectedIndex,
onSelect,
onDelete,
}: {
selectedIndex: number
onSelect: (index: number) => void
onDelete: (index: number) => void
}) => {
const rules = useActionRules()
const { t } = useTranslation("settings")
const ruleCount = useActionRules((s) => s.length)
const mutation = useUpdateActionsMutation()
const { ask } = useDialog()
const showContextMenu = useShowContextMenu()
const handleDeleteRule = useCallback(
(index: number) => {
if (ruleCount === 1) {
ask({
title: t("actions.action_card.summary.delete_title"),
variant: "danger",
message: t("actions.action_card.summary.delete_message"),
onConfirm: () => {
actionActions.deleteRule(index)
onDelete(index)
nextFrame(() => {
mutation.mutate()
})
},
})
} else {
actionActions.deleteRule(index)
onDelete(index)
}
},
[ruleCount, ask, t, mutation, onDelete],
)
if (rules.length === 0) {
return null
}
return (
<div className="flex w-[260px] shrink-0 flex-col">
<ScrollArea.ScrollArea rootClassName="h-full" viewportClassName="h-full">
<div className="flex flex-col">
{rules.map((rule, index) => (
<RuleListItem
key={rule.index ?? index}
rule={rule}
index={index}
isActive={index === selectedIndex}
onSelect={onSelect}
handleDelete={handleDeleteRule}
showContextMenu={showContextMenu}
/>
))}
</div>
</ScrollArea.ScrollArea>
</div>
)
}
const RuleListItem = ({
rule,
index,
isActive,
onSelect,
handleDelete,
showContextMenu,
}: {
rule: ActionItem
index: number
isActive: boolean
onSelect: (index: number) => void
handleDelete: (index: number) => void
showContextMenu: ReturnType<typeof useShowContextMenu>
}) => {
const { t } = useTranslation("settings")
const displayName = getRuleDisplayName(rule, index, t)
const whenSummary = buildConditionSummary(rule, t)
const actionSummary = buildActionSummary(rule, t)
const contextMenuProps = useContextMenu({
onContextMenu: async (e) => {
e.preventDefault()
await showContextMenu(
[
new MenuItemText({
label: t("actions.action_card.summary.delete"),
icon: <i className="i-mgc-delete-2-cute-re" />,
click: () => handleDelete(index),
}),
],
e,
)
},
})
return (
<button
type="button"
onClick={() => onSelect(index)}
{...contextMenuProps}
className={cn(
"flex flex-col gap-1 border-b border-fill-tertiary px-4 py-3 text-left transition-all last:border-b-0",
isActive ? "bg-fill-quaternary" : "hover:bg-fill-quinary",
)}
>
<span className="text-sm font-medium text-text">{displayName}</span>
<span className="line-clamp-2 text-xs text-text-secondary">{whenSummary}</span>
<span className="line-clamp-1 text-xs text-text-secondary">{actionSummary}</span>
</button>
)
}
const ActionButtonGroup = ({ onCreateRule }: { onCreateRule: () => void }) => {
const queryClient = useQueryClient()
const actionLength = useActionRules((actions) => actions.length)
const isDirty = useIsActionDataDirty()
const { t } = useTranslation("settings")
unstable_usePrompt({
message: t("actions.navigate.prompt"),
when: ({ currentLocation, nextLocation }) =>
isDirty && currentLocation.pathname !== nextLocation.pathname,
})
const mutation = useUpdateActionsMutation({
onSuccess: () => {
queryClient.invalidateQueries({
queryKey: ["entries"],
})
toast(t("actions.saveSuccess"))
},
onError: (error) => {
toast.error(error)
},
})
const hasActions = actionLength > 0
const setRightView = useSetSubViewRightView()
useEffect(() => {
setRightView(
<HeaderActionGroup>
<HeaderActionButton
variant="primary"
icon="i-mingcute-add-line"
onClick={() => actionActions.addRule((number) => t("actions.actionName", { number }))}
>
<HeaderActionButton variant="primary" icon="i-mingcute-add-line" onClick={onCreateRule}>
{t("actions.newRule")}
</HeaderActionButton>
@@ -231,70 +453,7 @@ const ActionButtonGroup = () => {
return () => {
setRightView(null)
}
}, [setRightView, actionLength, hasActions, isDirty, mutation, t])
}, [setRightView, actionLength, hasActions, isDirty, mutation, onCreateRule, t])
return (
<div className="mb-6 flex w-full items-center justify-end p-4 lg:justify-between">
{/* Left side - Simple status */}
<div className="hidden lg:block">
<h3 className="text-text text-lg font-medium">
{hasActions ? `${actionLength} Rules` : "No Rules"}
</h3>
<p className="text-text-secondary text-sm">
{hasActions ? "Active automation rules" : "Create your first automation rule"}
</p>
</div>
{/* Right side - Action buttons */}
<div className="flex items-center gap-2">
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="outline" size="sm">
{hasActions ? (
<i className="i-mgc-share-forward-cute-re mr-2 size-4" />
) : (
<i className="i-mgc-file-import-cute-re mr-2 size-4" />
)}
{hasActions ? "Share" : "Import"}
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-56">
<DropdownMenuItem onClick={handleExport} disabled={!hasActions}>
<i className="i-mgc-download-2-cute-re mr-3 size-4" />
Export to File
</DropdownMenuItem>
<DropdownMenuItem onClick={handleImport}>
<i className="i-mgc-file-upload-cute-re mr-3 size-4" />
Import from File
</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem onClick={handleCopyToClipboard} disabled={!hasActions}>
<i className="i-mgc-copy-2-cute-re mr-3 size-4" />
Copy to Clipboard
</DropdownMenuItem>
<DropdownMenuItem onClick={handleImportFromClipboard}>
<i className="i-mgc-paste-cute-re mr-3 size-4" />
Import from Clipboard
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
<Button
variant={actionLength === 0 ? "primary" : "outline"}
size="sm"
onClick={() => actionActions.addRule((number) => t("actions.actionName", { number }))}
>
<i className="i-mingcute-add-line mr-2 size-4" />
{t("actions.newRule")}
</Button>
{hasActions && (
<Button onClick={() => mutation.mutate()} size="sm" disabled={!isDirty}>
<i className="i-mgc-check-circle-cute-re mr-2 size-4" />
{t("actions.save")}
</Button>
)}
</div>
</div>
)
return null
}
@@ -1,77 +1,181 @@
import { Button } from "@follow/components/ui/button/index.js"
import { Input } from "@follow/components/ui/input/index.js"
import * as ScrollArea from "@follow/components/ui/scroll-area/ScrollArea.js"
import { Switch } from "@follow/components/ui/switch/index.jsx"
import { useActionRule, useActionRules, useUpdateActionsMutation } from "@follow/store/action/hooks"
import { actionActions } from "@follow/store/action/store"
import { nextFrame } from "@follow/utils"
import { cn } from "@follow/utils/utils"
import { useEffect, useState } from "react"
import { useTranslation } from "react-i18next"
import { useDialog } from "~/components/ui/modal/stacked/hooks"
import { buildActionSummary, buildConditionSummary, getRuleDisplayName } from "./rule-summary"
import { ThenSection } from "./then-section"
import { WhenSection } from "./when-section"
export const RuleCard = ({ index }: { index: number }) => {
type RuleCardProps = {
index: number
mode?: "detail" | "compact"
defaultOpen?: boolean
onOpenChange?: (open: boolean) => void
}
export const RuleCard = ({
index,
mode = "detail",
defaultOpen = false,
onOpenChange,
}: RuleCardProps) => {
if (mode === "compact") {
return <CompactRuleCard index={index} defaultOpen={defaultOpen} onOpenChange={onOpenChange} />
}
return (
<div className="bg-material-ultra-thin group/card-root relative flex flex-col gap-4 rounded-2xl border p-4 shadow-sm md:p-6">
<RuleCardToolbar index={index} />
<div className="@[800px]:grid-cols-2 grid grid-cols-1 gap-x-8 gap-y-6">
<WhenSection index={index} />
<ThenSection index={index} />
<div className="group/rule flex size-full flex-col @container">
<div className="shrink-0 border-b border-fill-tertiary px-5 py-4">
<RuleCardToolbar index={index} />
</div>
<ScrollArea.ScrollArea rootClassName="flex-1" viewportClassName="h-full">
<div className="p-5">
<RuleCardContent index={index} />
</div>
</ScrollArea.ScrollArea>
</div>
)
}
const RuleCardContent = ({ index }: { index: number }) => {
return (
<div className="flex flex-col gap-6 @[900px]:grid @[900px]:grid-cols-2 @[900px]:items-start @[900px]:gap-6">
<WhenSection index={index} />
<ThenSection index={index} />
</div>
)
}
const CompactRuleCard = ({
index,
defaultOpen,
onOpenChange,
}: {
index: number
defaultOpen: boolean
onOpenChange?: (open: boolean) => void
}) => {
const { t } = useTranslation("settings")
const rule = useActionRule(index)
const disabled = useActionRule(index, (a) => a.result.disabled)
const [open, setOpen] = useState(defaultOpen)
useEffect(() => {
setOpen(defaultOpen)
}, [defaultOpen])
const toggle = () => {
setOpen((prev) => {
const next = !prev
onOpenChange?.(next)
return next
})
}
const displayName = getRuleDisplayName(rule, index, t)
const whenSummary = buildConditionSummary(rule, t)
const actionSummary = buildActionSummary(rule, t)
return (
<div className="overflow-hidden rounded-lg border border-fill-secondary bg-transparent">
<button
type="button"
onClick={toggle}
className="flex w-full items-start justify-between gap-3 px-4 py-3 text-left transition-colors hover:bg-fill-quinary"
>
<div className="flex flex-col gap-1">
<span className="text-sm font-semibold text-text">{displayName}</span>
<span className="line-clamp-1 text-xs text-text-tertiary">{whenSummary}</span>
<span className="line-clamp-1 text-xs text-text-tertiary">{actionSummary}</span>
</div>
<div className="flex items-center gap-2">
{disabled && (
<span className="rounded-md border border-fill-secondary bg-fill-quaternary px-2 py-0.5 text-[10px] font-medium uppercase tracking-wide text-text-secondary">
{t("actions.action_card.summary.disabled")}
</span>
)}
<i
className={cn(
"size-4 text-text-tertiary transition-transform",
open ? "i-mingcute-arrow-up-line" : "i-mingcute-arrow-down-line",
)}
/>
</div>
</button>
{open ? (
<div className="space-y-4 border-t border-fill-tertiary bg-transparent p-4">
<RuleCardToolbar index={index} />
<RuleCardContent index={index} />
</div>
) : null}
</div>
)
}
const RuleCardToolbar = ({ index }: { index: number }) => {
const { t } = useTranslation("settings")
const name = useActionRule(index, (a) => a.name)
const disabled = useActionRule(index, (a) => a.result.disabled)
const ruleCount = useActionRules((s) => s.length)
const mutation = useUpdateActionsMutation()
const { ask } = useDialog()
const handleDelete = () => {
if (ruleCount === 1) {
ask({
title: t("actions.action_card.summary.delete_title"),
variant: "danger",
message: t("actions.action_card.summary.delete_message"),
onConfirm: () => {
actionActions.deleteRule(index)
nextFrame(() => {
mutation.mutate()
})
},
})
} else {
actionActions.deleteRule(index)
}
}
return (
<div className="flex w-full items-center gap-3">
<div className={"flex w-full flex-wrap items-center gap-3"}>
<Input
value={name}
className="h-9 max-w-64 bg-transparent px-2 text-lg font-semibold shadow-none ring-0 focus-visible:ring-0"
placeholder={t("actions.action_card.name")}
className="h-9 min-w-[160px] flex-1 bg-transparent px-3 text-base font-semibold shadow-none ring-0 focus-visible:ring-0"
onChange={(e) => {
actionActions.patchRule(index, { name: e.target.value })
}}
/>
<div className="grow" />
<Switch
checked={!disabled}
onCheckedChange={(checked) => {
actionActions.patchRule(index, {
result: { disabled: !checked },
})
}}
/>
<div className="absolute right-0 top-0 opacity-0 transition-opacity duration-200 group-hover/card-root:opacity-100">
<button
className="bg-background center flex size-8 -translate-y-1/2 translate-x-1/2 rounded-full border"
type="button"
onClick={() => {
if (ruleCount === 1) {
ask({
title: "Delete Rule",
variant: "danger",
message: "Are you sure you want to delete this rule? This action cannot be undone.",
onConfirm: () => {
actionActions.deleteRule(index)
nextFrame(() => {
mutation.mutate()
})
},
})
} else {
actionActions.deleteRule(index)
}
<div className="flex items-center gap-3">
<Switch
checked={!disabled}
onCheckedChange={(checked) => {
actionActions.patchRule(index, {
result: { disabled: !checked },
})
}}
aria-label={t("actions.action_card.summary.toggle")}
/>
<Button
variant="ghost"
size="sm"
aria-label={t("actions.action_card.summary.delete")}
buttonClassName="size-8 p-0"
onClick={handleDelete}
>
<i className="i-mgc-close-cute-re" />
</button>
<i className="i-mgc-delete-2-cute-re" />
</Button>
</div>
</div>
)
@@ -0,0 +1,91 @@
import { filterFieldOptions, filterOperatorOptions } from "@follow/store/action/constant"
import type { ActionItem } from "@follow/store/action/store"
import type { TFunction } from "i18next"
import { availableActionMap } from "./constants"
const fieldLabelMap = new Map(filterFieldOptions.map((option) => [option.value, option.label]))
const operatorLabelMap = new Map(
filterOperatorOptions.map((option) => [option.value, option.label]),
)
export const getRuleDisplayName = (
rule: ActionItem | undefined,
index: number,
t: TFunction<"settings">,
) => {
const fallback = t("actions.actionName", { number: index + 1 })
if (!rule) return fallback
const trimmedName = rule.name?.trim()
return trimmedName && trimmedName.length > 0 ? trimmedName : fallback
}
export const buildConditionSummary = (rule: ActionItem | undefined, t: TFunction<"settings">) => {
if (!rule || rule.condition.length === 0) {
return t("actions.action_card.all")
}
const andSeparator = ` ${t("actions.action_card.and")} `
const orSeparator = ` ${t("actions.action_card.or")} `
const groups = rule.condition
.map((group) => {
const groupParts = group
.map((condition) => {
const fieldLabelKey = condition.field ? fieldLabelMap.get(condition.field) : undefined
const operatorLabelKey = condition.operator
? operatorLabelMap.get(condition.operator)
: undefined
const fieldLabel = fieldLabelKey ? t(fieldLabelKey) : undefined
const operatorLabel = operatorLabelKey ? t(operatorLabelKey) : undefined
const { value } = condition
const valueText =
typeof value === "string" && value.trim().length > 0 ? value : value?.toString() || ""
const parts = [fieldLabel, operatorLabel, valueText].filter(Boolean)
return parts.join(" ")
})
.filter((part) => part.length > 0)
return groupParts.join(andSeparator)
})
.filter((group) => group.length > 0)
if (groups.length === 0) {
return t("actions.action_card.all")
}
return groups.join(orSeparator)
}
export const buildActionSummary = (rule: ActionItem | undefined, t: TFunction<"settings">) => {
if (!rule) {
return t("actions.action_card.summary.no_actions")
}
if (rule.result?.disabled) {
return t("actions.action_card.summary.disabled")
}
const labels = Object.values(availableActionMap)
.filter((action) => {
const value = rule.result?.[action.value as keyof typeof rule.result]
if (Array.isArray(value)) {
return value.length > 0
}
if (typeof value === "object" && value !== null) {
return Object.keys(value).length > 0
}
return Boolean(value)
})
.map((action) => t(action.label))
if (labels.length === 0) {
return t("actions.action_card.summary.no_actions")
}
return labels.join(" + ")
}
@@ -1,11 +1,12 @@
import { ActionButton, Button } from "@follow/components/ui/button/index.js"
import { Divider } from "@follow/components/ui/divider/index.js"
import { Button } from "@follow/components/ui/button/index.js"
import { Input } from "@follow/components/ui/input/index.js"
import type { ActionAction } from "@follow/store/action/constant"
import { useActionRule } from "@follow/store/action/hooks"
import { actionActions } from "@follow/store/action/store"
import { cn } from "@follow/utils/utils"
import type { ActionId } from "@follow-app/client-sdk"
import { merge } from "es-toolkit/compat"
import type { ReactNode } from "react"
import { Fragment, useMemo } from "react"
import { useTranslation } from "react-i18next"
@@ -19,7 +20,12 @@ import {
import { useSettingModal } from "../settings/modal/useSettingModal"
import { availableActionMap } from "./constants"
export const ThenSection = ({ index }: { index: number }) => {
type ThenSectionProps = {
index: number
variant?: "detail" | "compact"
}
export const ThenSection = ({ index, variant: _variant = "detail" }: ThenSectionProps) => {
const { t } = useTranslation("settings")
const result = useActionRule(index, (a) => a.result)
@@ -33,28 +39,26 @@ export const ThenSection = ({ index }: { index: number }) => {
const extendedAvailableActionMap: Record<
ActionId,
ActionAction & {
config?: () => React.ReactNode
config?: () => ReactNode
}
> = merge(availableActionMap, {
rewriteRules: {
config: () => (
<div className="flex flex-col gap-2">
<div className="flex flex-col gap-3">
{!rewriteRules || rewriteRules.length === 0 ? (
<div className="flex items-center justify-between rounded-lg border border-dashed p-3">
<span className="text-muted-foreground text-sm">Add rewrite rules</span>
<Button
variant="ghost"
size="sm"
disabled={disabled}
onClick={() => {
actionActions.addRewriteRule(index)
}}
>
<i className="i-mgc-add-cute-re" />
</Button>
</div>
<button
type="button"
disabled={disabled}
className="flex items-center justify-between rounded-lg bg-fill-quaternary px-4 py-3 text-xs text-text-tertiary transition-colors hover:bg-fill-tertiary hover:text-text disabled:opacity-50"
onClick={() => {
actionActions.addRewriteRule(index)
}}
>
<span>{t("actions.action_card.rewrite_rules")}</span>
<i className="i-mgc-add-cute-re" />
</button>
) : (
<>
<div className="flex flex-col gap-3">
{rewriteRules.map((rule, rewriteIdx) => {
const change = (key: "from" | "to", value: string) => {
actionActions.updateRewriteRule({
@@ -65,112 +69,116 @@ export const ThenSection = ({ index }: { index: number }) => {
})
}
return (
<div key={rewriteIdx} className="group/rewrite-item flex items-end gap-2">
<div className="w-full">
<label className="text-muted-foreground text-sm">
<div
key={rewriteIdx}
className="flex flex-col gap-3 rounded-lg bg-fill-quaternary p-4"
>
<div className="grid gap-3 @[520px]:grid-cols-2">
<label className="text-xs font-medium uppercase tracking-wide text-text-secondary">
{t("actions.action_card.from")}
<Input
disabled={disabled}
value={rule.from}
className="mt-2 h-9"
onChange={(event) => change("from", event.target.value)}
/>
</label>
<Input
disabled={disabled}
value={rule.from}
className="h-8"
onChange={(e) => change("from", e.target.value)}
/>
</div>
<div className="w-full">
<label className="text-muted-foreground text-sm">
<label className="text-xs font-medium uppercase tracking-wide text-text-secondary">
{t("actions.action_card.to")}
<Input
disabled={disabled}
value={rule.to}
className="mt-2 h-9"
onChange={(event) => change("to", event.target.value)}
/>
</label>
<Input
disabled={disabled}
value={rule.to}
className="h-8"
onChange={(e) => change("to", e.target.value)}
/>
</div>
<div className="text-text-secondary flex gap-1">
<ActionButton
<div className="flex items-center justify-end gap-2">
<IconButton
icon="i-mgc-add-cute-re"
ariaLabel={t("actions.action_card.add")}
disabled={disabled}
onClick={() => {
actionActions.addRewriteRule(index)
}}
>
<i className="i-mgc-add-cute-re" />
</ActionButton>
<ActionButton
/>
<IconButton
icon="i-mgc-delete-2-cute-re"
className="hover:text-red"
ariaLabel={t("actions.action_card.summary.delete")}
disabled={disabled}
onClick={() => {
actionActions.deleteRewriteRule(index, rewriteIdx)
}}
>
<i className="i-mgc-delete-2-cute-re" />
</ActionButton>
/>
</div>
</div>
)
})}
</>
</div>
)}
</div>
),
},
webhooks: {
config: () => (
<div className="flex flex-col gap-2">
<div className="flex flex-col gap-3">
{!webhooks || webhooks.length === 0 ? (
<div className="flex items-center justify-between rounded-lg border border-dashed p-3">
<span className="text-muted-foreground text-sm">Add webhooks</span>
<Button
variant="ghost"
size="sm"
disabled={disabled}
onClick={() => {
actionActions.addWebhook(index)
}}
>
<i className="i-mgc-add-cute-re" />
</Button>
</div>
<button
type="button"
disabled={disabled}
className="flex items-center justify-between rounded-lg bg-fill-quaternary px-4 py-3 text-xs text-text-tertiary transition-colors hover:bg-fill-tertiary hover:text-text disabled:opacity-50"
onClick={() => {
actionActions.addWebhook(index)
}}
>
<span>{t("actions.action_card.webhooks")}</span>
<i className="i-mgc-add-cute-re" />
</button>
) : (
<>
<div className="flex flex-col gap-3">
{webhooks.map((webhook, webhookIdx) => {
return (
<div key={webhookIdx} className="flex items-center gap-2">
<div
key={webhookIdx}
className="flex flex-col gap-2 rounded-lg bg-fill-quaternary p-4"
>
<Input
disabled={disabled}
value={webhook}
className="h-8"
className="h-9"
placeholder="https://"
onChange={(e) => {
onChange={(event) => {
actionActions.updateWebhook({
index,
webhookIndex: webhookIdx,
value: e.target.value,
value: event.target.value,
})
}}
/>
<div className="text-text-secondary flex gap-1">
<ActionButton
<div className="flex items-center justify-end gap-2">
<IconButton
icon="i-mgc-add-cute-re"
ariaLabel={t("actions.action_card.add")}
disabled={disabled}
onClick={() => {
actionActions.addWebhook(index)
}}
>
<i className="i-mgc-add-cute-re" />
</ActionButton>
<ActionButton
/>
<IconButton
icon="i-mgc-delete-2-cute-re"
className="hover:text-red"
ariaLabel={t("actions.action_card.summary.delete")}
disabled={disabled}
onClick={() => {
actionActions.deleteWebhook(index, webhookIdx)
}}
>
<i className="i-mgc-delete-2-cute-re" />
</ActionButton>
/>
</div>
</div>
)
})}
</>
</div>
)}
</div>
),
@@ -178,89 +186,204 @@ export const ThenSection = ({ index }: { index: number }) => {
})
return Object.values(extendedAvailableActionMap)
}, [disabled, index, rewriteRules, t, webhooks])
const enabledActions = useMemo(
() => availableActions.filter((action) => !!result?.[action.value]),
[availableActions, result],
)
const enabledActions = useMemo(() => {
if (!result) return []
// Get the order of actions from the result object (insertion order)
const resultKeys = Object.keys(result).filter((key) => result[key as ActionId])
// Sort availableActions based on the order in result object
return resultKeys
.map((key) => availableActions.find((action) => action.value === key))
.filter((action): action is NonNullable<typeof action> => !!action)
}, [availableActions, result])
const notEnabledActions = useMemo(
() => availableActions.filter((action) => !result?.[action.value]),
[availableActions, result],
)
return (
<div className="flex flex-col gap-3">
<h2 className="text-lg font-semibold">{t("actions.action_card.then_do")}</h2>
<div className="flex flex-col gap-2 pl-2">
{enabledActions.map((action, i) => {
return (
<Fragment key={action.label}>
<div className="group/action relative flex flex-col gap-2 py-2">
<div className="flex w-full items-center justify-between gap-2">
<div className="flex items-center gap-2">
<i className={action.iconClassname} />
<span className="shrink grow truncate font-medium">{t(action.label)}</span>
{action.prefixElement && <div className="ml-2">{action.prefixElement}</div>}
</div>
<div className="flex items-center gap-2">
{action.settingsPath && (
<Button
variant="outline"
size="sm"
onClick={() => {
settingModalPresent(action.settingsPath)
}}
>
{t("actions.action_card.settings")}
</Button>
)}
<Button
variant="ghost"
buttonClassName="opacity-0 group-hover/action:opacity-100"
disabled={disabled}
<section className="flex flex-col gap-4">
<div className="flex flex-wrap items-center justify-between gap-3">
<span className="text-xs font-semibold uppercase tracking-wide text-text-secondary">
{t("actions.action_card.then_do")}
</span>
{enabledActions.length > 0 && (
<span className="text-xs text-text-secondary">
{t("actions.action_card.summary.action_count", { count: enabledActions.length })}
</span>
)}
</div>
<div className="relative flex flex-col">
{enabledActions.length === 0 ? (
<div className="flex flex-col items-center gap-3 rounded-lg bg-fill-quaternary px-4 py-6">
<span className="text-xs text-text-secondary">
{t("actions.action_card.summary.no_actions")}
</span>
<DropdownMenu>
<DropdownMenuTrigger asChild disabled={disabled}>
<Button variant="outline" size="sm" buttonClassName="border-dashed">
<i className="i-mgc-add-cute-re mr-2" />
{t("actions.action_card.add")}
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent className="w-60">
{notEnabledActions.map((action) => {
return (
<DropdownMenuItem
key={action.label}
onClick={() => {
actionActions.deleteRuleAction(index, action.value)
if (action.onEnable) {
action.onEnable(index)
} else {
actionActions.patchRule(index, { result: { [action.value]: true } })
}
}}
>
<i className="i-mgc-close-cute-re" />
</Button>
</div>
</div>
{action.config && <div className="pl-6">{action.config()}</div>}
</div>
{i !== enabledActions.length - 1 && <Divider className="my-1" />}
</Fragment>
)
})}
<DropdownMenu>
<DropdownMenuTrigger asChild disabled={disabled}>
<Button variant="outline" buttonClassName="mt-2 w-full">
<i className="i-mgc-add-cute-re mr-2" />
{t("actions.action_card.add")}
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent className="w-56">
{notEnabledActions.map((action) => {
<div className="flex items-center gap-2">
<i className={action.iconClassname} />
{t(action.label)}
</div>
</DropdownMenuItem>
)
})}
</DropdownMenuContent>
</DropdownMenu>
</div>
) : (
<>
{enabledActions.map((action, actionIndex) => {
const isLast = actionIndex === enabledActions.length - 1
return (
<DropdownMenuItem
key={action.label}
onClick={() => {
if (action.onEnable) {
action.onEnable(index)
} else {
actionActions.patchRule(index, { result: { [action.value]: true } })
}
}}
>
<div className="flex items-center gap-2">
<i className={action.iconClassname} />
{t(action.label)}
<Fragment key={action.label}>
<div className="relative flex gap-4">
{/* Connection line and icon */}
<div className="relative flex flex-col items-center pt-0.5">
<div className="flex size-9 shrink-0 items-center justify-center rounded-full bg-material-ultra-thick text-text shadow-sm">
<i className={cn(action.iconClassname, "text-base")} />
</div>
{!isLast && (
<div className="absolute left-1/2 top-9 h-[calc(100%+0.75rem)] w-0.5 -translate-x-1/2 bg-gradient-to-b from-fill-secondary to-transparent" />
)}
</div>
{/* Action content */}
<div className="flex min-w-0 flex-1 flex-col gap-3 pb-6 pt-0.5">
<div className="flex items-center gap-4">
{/* Label */}
<span className="flex h-9 items-center text-sm font-medium text-text">
{t(action.label)}
</span>
{/* Spacer */}
<div className="flex-1" />
{/* Value selector or prefix element */}
{action.prefixElement && (
<div className="text-xs">{action.prefixElement}</div>
)}
{/* Settings button */}
{action.settingsPath && (
<Button
variant="outline"
size="sm"
buttonClassName="rounded-lg"
onClick={() => {
settingModalPresent(action.settingsPath)
}}
>
{t("actions.action_card.settings")}
</Button>
)}
{/* Delete button */}
<IconButton
icon="i-mgc-delete-2-cute-re"
ariaLabel={t("actions.action_card.summary.delete")}
disabled={disabled}
className="hover:text-red"
onClick={() => {
actionActions.deleteRuleAction(index, action.value)
}}
/>
</div>
{action.config && (
<div className="rounded-lg bg-fill-quinary p-4">{action.config()}</div>
)}
</div>
</div>
</DropdownMenuItem>
</Fragment>
)
})}
</DropdownMenuContent>
</DropdownMenu>
<div className="relative flex gap-4">
<div className="size-9 shrink-0" />
<div className="pb-2">
<DropdownMenu>
<DropdownMenuTrigger asChild disabled={disabled}>
<Button variant="outline" size="sm" buttonClassName="border-dashed">
<i className="i-mgc-add-cute-re mr-2" />
{t("actions.action_card.add")}
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="start" className="w-60">
{notEnabledActions.map((action) => {
return (
<DropdownMenuItem
key={action.label}
onClick={() => {
if (action.onEnable) {
action.onEnable(index)
} else {
actionActions.patchRule(index, { result: { [action.value]: true } })
}
}}
>
<div className="flex items-center gap-2">
<i className={action.iconClassname} />
{t(action.label)}
</div>
</DropdownMenuItem>
)
})}
</DropdownMenuContent>
</DropdownMenu>
</div>
</div>
</>
)}
</div>
</div>
</section>
)
}
const IconButton = ({
icon,
onClick,
ariaLabel,
disabled,
className,
}: {
icon: string
onClick: () => void
ariaLabel: string
disabled?: boolean
className?: string
}) => {
return (
<button
type="button"
aria-label={ariaLabel}
disabled={disabled}
className={cn(
"flex size-6 items-center justify-center rounded-md text-text-secondary transition-colors hover:bg-fill-quaternary hover:text-text disabled:opacity-50",
className,
)}
onClick={onClick}
>
<i className={icon} />
</button>
)
}
@@ -1,6 +1,6 @@
import { Button } from "@follow/components/ui/button/index.js"
import { Input } from "@follow/components/ui/input/index.js"
import { RadioGroup, RadioGroupItem } from "@follow/components/ui/radio-group/motion.js"
import { SegmentGroup, SegmentItem } from "@follow/components/ui/segment/index.js"
import {
Select,
SelectContent,
@@ -18,48 +18,50 @@ import { useTranslation } from "react-i18next"
import { ViewSelectContent } from "~/modules/feed/view-select-content"
export const WhenSection = ({ index }: { index: number }) => {
type WhenSectionProps = {
index: number
}
export const WhenSection = ({ index }: WhenSectionProps) => {
const { t } = useTranslation("settings")
const disabled = useActionRule(index, (a) => a.result.disabled)
const condition = useActionRule(index, (a) => a.condition)
const mode = condition.length > 0 ? "filter" : "all"
const handleModeChange = (value: "all" | "filter") => {
if (value === "all" && condition.length > 0) {
actionActions.toggleRuleFilter(index)
}
if (value === "filter" && condition.length === 0) {
actionActions.toggleRuleFilter(index)
}
}
return (
<div className="flex flex-col gap-3">
<h2 className="text-lg font-semibold">{t("actions.action_card.when_feeds_match")}</h2>
<div className="pl-2">
<RadioGroup
value={condition.length > 0 ? "filter" : "all"}
onValueChange={(value) => {
actionActions.patchRule(index, {
condition: value === "all" ? [] : [[{}]],
})
}}
className="flex gap-8"
<section className="flex flex-col gap-4">
<div className="flex flex-wrap items-center justify-between gap-3">
<span className="text-xs font-semibold uppercase tracking-wide text-text-secondary">
{t("actions.action_card.when_feeds_match")}
</span>
<SegmentGroup
value={mode}
onValueChanged={(value) => handleModeChange(value as "all" | "filter")}
>
<RadioGroupItem
labelClassName="text-sm"
disabled={disabled}
label={t("actions.action_card.all")}
value="all"
/>
<RadioGroupItem
labelClassName="text-sm"
disabled={disabled}
label={t("actions.action_card.custom_filters")}
value="filter"
/>
</RadioGroup>
<SegmentItem value="all" label={t("actions.action_card.all")} />
<SegmentItem value="filter" label={t("actions.action_card.custom_filters")} />
</SegmentGroup>
</div>
{condition.length > 0 && (
<div className="flex flex-col gap-4 pl-2 pt-4">
{mode === "filter" && (
<div className="flex flex-col gap-4">
{condition.map((orConditions, orConditionIdx) => {
return (
<Fragment key={orConditionIdx}>
<div className="@[500px]:p-4 group/or relative flex flex-col gap-2 rounded-lg border p-2 pl-6">
<div className="bg-border absolute left-3 top-9 h-[calc(100%-4.5rem)] w-px" />
{orConditions.map((condition, conditionIdx) => {
<div className="flex flex-col gap-3 rounded-lg border border-dashed border-border bg-transparent p-4">
{orConditions.map((item, conditionIdx) => {
const actionConditionIndex = {
ruleIndex: index,
groupIndex: orConditionIdx,
@@ -71,51 +73,52 @@ export const WhenSection = ({ index }: { index: number }) => {
[key]: value,
})
}
const type =
filterFieldOptions.find((option) => option.value === condition.field)?.type ||
filterFieldOptions.find((option) => option.value === item.field)?.type ||
"text"
return (
<div className="flex flex-col gap-2" key={conditionIdx}>
<div className="group/condition-item relative flex items-center gap-2">
<div className="bg-border absolute -left-3.5 top-1/2 h-px w-3 -translate-y-1/2" />
<div className="bg-background absolute -left-3.5 top-1/2 size-1.5 -translate-y-1/2 rounded-full border" />
<div key={conditionIdx} className="flex flex-col gap-2">
<div className="flex flex-col gap-2 rounded-lg border border-fill-secondary bg-transparent p-3 @[800px]:flex-row @[800px]:items-center">
<ResponsiveSelect
placeholder="Select Field"
disabled={disabled}
value={condition.field}
value={item.field}
onValueChange={(value) => change("field", value as ActionFeedField)}
items={filterFieldOptions.map((option) => ({
...option,
label: t(option.label),
}))}
triggerClassName="h-8"
triggerClassName="h-9 min-w-[160px] @[800px]:flex-1"
/>
<OperationSelect
type={type}
disabled={disabled}
value={condition.operator}
value={item.operator}
onValueChange={(value) => change("operator", value)}
/>
<ValueInput
type={type}
value={condition.value}
value={item.value}
onChange={(value) => change("value", value)}
disabled={disabled}
/>
<Button
variant="ghost"
buttonClassName="opacity-0 group-hover/condition-item:opacity-100"
<button
type="button"
aria-label={t("actions.action_card.summary.delete")}
className="flex size-9 shrink-0 items-center justify-center self-end rounded-lg border border-fill-secondary bg-transparent text-text-secondary transition-colors hover:border-fill hover:bg-fill-quinary hover:text-text disabled:opacity-50 @[800px]:self-center"
disabled={disabled}
onClick={() => {
actionActions.deleteConditionItem(actionConditionIndex)
}}
>
<i className="i-mgc-delete-2-cute-re" />
</Button>
</button>
</div>
{conditionIdx !== orConditions.length - 1 && (
<div className="flex items-center pl-2">
<span className="text-muted-foreground text-sm">
<div className="flex items-center text-xs text-text-secondary">
<span className="rounded-md border border-border bg-material-medium px-2 py-0.5 font-bold uppercase tracking-wide">
{t("actions.action_card.and")}
</span>
</div>
@@ -125,7 +128,8 @@ export const WhenSection = ({ index }: { index: number }) => {
})}
<Button
variant="outline"
buttonClassName="mt-2"
size="sm"
buttonClassName="w-fit border-dashed border-border "
disabled={disabled}
onClick={() => {
actionActions.addConditionItem({
@@ -139,9 +143,8 @@ export const WhenSection = ({ index }: { index: number }) => {
</Button>
</div>
{orConditionIdx !== condition.length - 1 && (
<div className="relative flex h-8 w-full items-center justify-center">
<div className="bg-border absolute left-0 top-1/2 h-px w-full" />
<span className="text-muted-foreground bg-background z-[1] px-2 text-sm">
<div className="flex items-center justify-center">
<span className="rounded-md border border-border bg-material-medium px-3 py-1 text-xs font-semibold uppercase tracking-wide text-text-secondary">
{t("actions.action_card.or")}
</span>
</div>
@@ -151,6 +154,8 @@ export const WhenSection = ({ index }: { index: number }) => {
})}
<Button
variant="outline"
size="sm"
buttonClassName="w-fit border-dashed border-border "
onClick={() => {
actionActions.addConditionGroup({ ruleIndex: index })
}}
@@ -161,7 +166,7 @@ export const WhenSection = ({ index }: { index: number }) => {
</Button>
</div>
)}
</div>
</section>
)
}
@@ -192,9 +197,9 @@ const OperationSelect = ({
placeholder="Select Operation"
disabled={disabled}
value={value}
onValueChange={(value) => onValueChange?.(value as ActionOperation)}
onValueChange={(nextValue) => onValueChange?.(nextValue as ActionOperation)}
items={options}
triggerClassName="h-8"
triggerClassName="h-9 min-w-[150px]"
/>
)
}
@@ -215,7 +220,7 @@ const ValueInput = ({
return (
<Select
disabled={disabled}
onValueChange={(value) => onChange(value)}
onValueChange={(nextValue) => onChange(nextValue)}
value={value as string | undefined}
>
<CommonSelectTrigger />
@@ -230,7 +235,7 @@ const ValueInput = ({
return (
<Select
disabled={disabled}
onValueChange={(value) => onChange(value)}
onValueChange={(nextValue) => onChange(nextValue)}
value={value as string | undefined}
>
<CommonSelectTrigger />
@@ -247,8 +252,8 @@ const ValueInput = ({
disabled={disabled}
type="number"
value={value}
className="h-8"
onChange={(e) => onChange(e.target.value)}
className="h-9"
onChange={(event) => onChange(event.target.value)}
/>
)
}
@@ -257,8 +262,8 @@ const ValueInput = ({
<Input
disabled={disabled}
value={value as string | undefined}
className="h-8"
onChange={(e) => onChange(e.target.value)}
className="h-9"
onChange={(event) => onChange(event.target.value)}
/>
)
}
@@ -266,7 +271,7 @@ const ValueInput = ({
}
const CommonSelectTrigger = () => (
<SelectTrigger className="h-8">
<SelectTrigger className="h-9 min-w-[150px]">
<SelectValue />
</SelectTrigger>
)
@@ -1,4 +1,4 @@
import type { AIChatMessage, AIChatSession } from "@follow-app/client-sdk"
import type { AIChatMessage, AIChatSession, ListSessionsQuery } from "@follow-app/client-sdk"
import { followApi } from "../../lib/api-client"
import { queryClient } from "../../lib/query-client"
@@ -13,17 +13,83 @@ const MAX_PAGES = 10
* Service for syncing AI chat session messages from remote API into local DB.
*/
class AIChatSessionServiceStatic {
private sync = false
/**
* List sessions from backend and ensure local DB has sessions and unseen messages.
* This does NOT mark sessions as seen on the server (non-destructive sync).
*
* Returns a small summary for observability.
*/
async syncSessionsAndMessagesFromServer(filters?: ListSessionsQuery): Promise<{
sessions: number
messages: number
failures: number
}> {
if (this.sync) {
return { sessions: 0, messages: 0, failures: 0 }
}
this.sync = true
const res = await followApi.aiChatSessions.list(filters)
const sessions = res.data
let totalMessages = 0
let failures = 0
for (const session of sessions) {
const dbSession = await AIPersistService.getChatSession(session.chatId)
const lastUpdatedAt = dbSession ? dbSession.updatedAt : new Date(0)
if (lastUpdatedAt >= new Date(session.updatedAt)) {
// If local session is already up-to-date, skip fetching messages
continue
}
try {
// Ensure session exists locally first
await AIPersistService.ensureSession(session.chatId, {
title: session.title,
createdAt: new Date(session.createdAt),
updatedAt: new Date(session.updatedAt),
})
// Fetch unseen messages (newer than lastSeenAt) without changing read state remotely
const unseenMessages = await this.fetchUnseenRemoteMessages(session.chatId, lastUpdatedAt)
if (unseenMessages.length === 0) continue
const normalized = unseenMessages.map(this.normalizeRemoteMessage)
await AIPersistService.upsertMessages(session.chatId, normalized)
totalMessages += normalized.length
} catch (err) {
// Keep going even if a single session fails
console.error("syncSessionsAndMessagesFromServer: failed for session", session.chatId, err)
failures += 1
}
}
return { sessions: sessions.length, messages: totalMessages, failures }
}
/**
* Fetch messages for a chat session from the remote API and persist (upsert) them locally.
* Returns the normalized BizUIMessage list that was persisted.
*
* Defensive in extracting the message array because the SDK response shape may evolve.
*/
async fetchAndPersistMessages(session: AIChatSession): Promise<BizUIMessage[]> {
const unseenMessages = await this.fetchUnseenRemoteMessages(session.chatId, session.lastSeenAt)
async fetchAndPersistMessages(session: AIChatSession): Promise<void> {
const dbSession = await AIPersistService.getChatSession(session.chatId)
const lastUpdatedAt = dbSession ? dbSession.updatedAt : new Date(0)
if (lastUpdatedAt >= new Date(session.updatedAt)) {
// If local session is already up-to-date, skip fetching messages
return
}
const unseenMessages = await this.fetchUnseenRemoteMessages(
session.chatId,
new Date(session.lastSeenAt),
)
const normalized = unseenMessages.map(this.normalizeRemoteMessage)
await AIPersistService.ensureSession(session.chatId, session.title)
await AIPersistService.ensureSession(session.chatId, {
title: session.title,
createdAt: new Date(session.createdAt),
updatedAt: new Date(session.updatedAt),
})
await AIPersistService.upsertMessages(session.chatId, normalized)
await followApi.aiChatSessions.markSeen({
@@ -37,7 +103,6 @@ class AIChatSessionServiceStatic {
queryClient.invalidateQueries({ queryKey: aiChatSessionKeys.lists }),
queryClient.invalidateQueries({ queryKey: aiChatSessionKeys.unread }),
])
return normalized
}
/**
@@ -50,10 +115,9 @@ class AIChatSessionServiceStatic {
*/
private async fetchUnseenRemoteMessages(
chatId: string,
lastSeenAt: string,
lastSeenAt: Date,
): Promise<AIChatMessage[]> {
const allMessages: AIChatMessage[] = []
const lastSeenAtDate = new Date(lastSeenAt)
let before: string | undefined
for (let page = 0; page < MAX_PAGES; page++) {
const resp = await followApi.aiChatSessions.messages.get(
@@ -64,7 +128,7 @@ class AIChatSessionServiceStatic {
allMessages.push(...batch)
const { nextBefore } = data
if (!nextBefore || new Date(nextBefore) <= lastSeenAtDate) {
if (!nextBefore || new Date(nextBefore) <= lastSeenAt) {
break
}
before = nextBefore
@@ -80,16 +144,14 @@ class AIChatSessionServiceStatic {
private normalizeRemoteMessage = (msg: AIChatMessage): BizUIMessage => {
const metadata =
msg.metadata && typeof msg.metadata === "object" ? (msg.metadata as BizUIMetadata) : undefined
const normalizedParts = msg.messageParts.filter(
(i) => i.type === "text",
) satisfies BizUIMessage["parts"]
return {
id: msg.id,
role: msg.role satisfies BizUIMessage["role"],
parts: normalizedParts,
// Remove this comment once @follow-app/client-sdk updated
// @ts-expect-error TODO fix message part types
parts: msg.messageParts,
metadata,
createdAt: new Date(msg.createdAt),
}
}
}
@@ -1,10 +1,11 @@
import { cn } from "@follow/utils"
import { ErrorBoundary } from "@sentry/react"
import { createElement, lazy, Suspense } from "react"
const AISplineLoader = lazy(() =>
import("./AISplineLoader").then((res) => ({ default: res.AISplineLoader })),
)
export const AISpline = () => {
export const AISpline = ({ className }: { className?: string }) => {
return createElement(
ErrorBoundary,
{
@@ -13,9 +14,9 @@ export const AISpline = () => {
createElement(
Suspense,
{
fallback: createElement("div", { className: "size-16 mx-auto" }),
fallback: createElement("div", { className: cn("size-20 mx-auto", className) }),
},
createElement(AISplineLoader),
createElement(AISplineLoader, { className }),
),
)
}
@@ -1,12 +1,13 @@
import { clamp, cn } from "@follow/utils"
import Spline from "@splinetool/react-spline"
import { useCallback, useRef } from "react"
const resolvedAIIconUrl = "https://cdn.follow.is/ai.splinecode"
// TODO: use folo cdn
const resolvedAIIconUrl = "https://prod.spline.design/n2hjp93nWReC-512/scene.splinecode"
export const AISplineLoader = () => {
export const AISplineLoader = ({ className }: { className?: string }) => {
const containerRef = useRef<HTMLDivElement>(null)
const headRef = useRef<any>(null)
const bodyRef = useRef<any>(null)
// Angle conversion function: degrees to radians
const degToRad = (degrees: number) => degrees * (Math.PI / 180)
@@ -27,10 +28,10 @@ export const AISplineLoader = () => {
// Calculate head rotation angle based on relative position
// Y-axis rotation (left-right): -70 to 70 degrees
const headRotationY = clampedX * 70
const headRotationY = clampedX * 20
// X-axis rotation (up-down): -60 to 60 degrees
const headRotationX = clampedY * 60
const headRotationX = clampedY * 20
return {
x: degToRad(headRotationX),
@@ -40,101 +41,76 @@ export const AISplineLoader = () => {
[],
)
// Calculate body rotation angle (horizontal rotation only)
const calculateBodyRotation = useCallback((mouseX: number, containerRect: DOMRect) => {
const containerCenterX = containerRect.left + containerRect.width / 2
// Calculate mouse X position relative to container center (-1 to 1)
const relativeX = (mouseX - containerCenterX) / (window.innerWidth / 2)
const clampedX = Math.max(-1, Math.min(1, relativeX))
// Body Y-axis rotation: -30 to 30 degrees (smaller range than head rotation)
const bodyRotationY = clampedX * 30
return {
x: 0, // Body doesn't rotate up-down
y: degToRad(bodyRotationY),
}
}, [])
const handleLoad = useCallback(
(app: any) => {
const head = app.findObjectByName("Head")
const body = app.findObjectByName("Body")
const head = app.findObjectByName("Folo Character_V3")
if (!head || !body) {
if (!head) {
console.warn("Cannot find Head or Body object")
return
}
headRef.current = head
bodyRef.current = body
const onMove = (e: MouseEvent) => {
if (!containerRef.current || !headRef.current || !bodyRef.current) return
if (!containerRef.current || !headRef.current) return
const containerRect = containerRef.current.getBoundingClientRect()
// Calculate head rotation
const headRotation = calculateHeadRotation(e.clientX, e.clientY, containerRect)
headRef.current.rotation.x = headRotation.x
headRef.current.rotation.y = headRotation.y
// Calculate body rotation
const bodyRotation = calculateBodyRotation(e.clientX, containerRect)
bodyRef.current.rotation.x = bodyRotation.x
bodyRef.current.rotation.y = bodyRotation.y
headRef.current.rotation.x = clamp(headRotation.x, -0.5, 0.5)
headRef.current.rotation.y = clamp(headRotation.y, -0.5, 0.5)
}
// Reset to default position when mouse leaves
const onMouseLeave = () => {
if (!headRef.current || !bodyRef.current) return
if (!headRef.current) return
// Smooth transition back to default position
const resetAnimation = () => {
if (!headRef.current || !bodyRef.current) return
if (!headRef.current) return
const currentHeadX = headRef.current.rotation.x
const currentHeadY = headRef.current.rotation.y
const currentBodyY = bodyRef.current.rotation.y
// Simple linear interpolation to smoothly return rotation to 0
headRef.current.rotation.x = currentHeadX * 0.9
headRef.current.rotation.y = currentHeadY * 0.9
bodyRef.current.rotation.y = currentBodyY * 0.9
// Continue animation if not fully returned to 0
if (
Math.abs(currentHeadX) > 0.01 ||
Math.abs(currentHeadY) > 0.01 ||
Math.abs(currentBodyY) > 0.01
) {
if (Math.abs(currentHeadX) > 0.01 || Math.abs(currentHeadY) > 0.01) {
requestAnimationFrame(resetAnimation)
} else {
// Complete reset to 0
headRef.current.rotation.x = 0
headRef.current.rotation.y = 0
bodyRef.current.rotation.x = 0
bodyRef.current.rotation.y = 0
}
}
resetAnimation()
}
const onClick = () => {
app.emitEvent("mouseDown", "Folo Character_V3")
}
onClick()
window.addEventListener("pointermove", onMove)
document.addEventListener("mouseleave", onMouseLeave)
window.addEventListener("click", onClick)
return () => {
window.removeEventListener("pointermove", onMove)
document.removeEventListener("mouseleave", onMouseLeave)
window.removeEventListener("click", onClick)
}
},
[calculateHeadRotation, calculateBodyRotation],
[calculateHeadRotation],
)
return (
<div ref={containerRef} className={"!size-16"}>
<div ref={containerRef} className={cn("size-20", className)}>
<Spline scene={resolvedAIIconUrl} onLoad={handleLoad} className="size-full" />
</div>
)
@@ -0,0 +1,132 @@
import { $createTextNode, $getSelection, $isRangeSelection } from "lexical"
import { memo, Suspense, use, useCallback, useEffect, useMemo, useRef, useState } from "react"
import { AIPanelRefsContext } from "~/modules/ai-chat/store/AIChatContext"
import { MentionDropdown } from "../../editor/plugins/mention/components/MentionDropdown"
import { useMentionSearchService } from "../../editor/plugins/mention/hooks/useMentionSearchService"
import { $createMentionNode } from "../../editor/plugins/mention/MentionNode"
import type { MentionData } from "../../editor/plugins/mention/types"
/**
* Button component that triggers a mention dropdown for manual context selection
* Allows users to add mentions (@feed, @entry, @date, etc.) to the input field
*/
export const MentionButton: Component = memo(() => {
const atButtonRef = useRef<HTMLButtonElement>(null)
const [isMentionDropdownVisible, setIsMentionDropdownVisible] = useState(false)
const [query, setQuery] = useState("")
const [suggestions, setSuggestions] = useState<MentionData[]>([])
const [selectedIndex, setSelectedIndex] = useState(0)
const [isLoading, setIsLoading] = useState(false)
const aiPanelRefs = use(AIPanelRefsContext)
const { searchMentions } = useMentionSearchService()
const handleAtButtonClick = useCallback(() => {
setIsMentionDropdownVisible(true)
setQuery("")
}, [])
// Search mentions when query changes
useEffect(() => {
if (!isMentionDropdownVisible) return
const performSearch = async () => {
setIsLoading(true)
try {
const results = await searchMentions(query)
setSuggestions(results)
setSelectedIndex(0)
} finally {
setIsLoading(false)
}
}
void performSearch()
}, [query, searchMentions, isMentionDropdownVisible])
const handleMentionSelect = useCallback(
(mention: MentionData) => {
// Get the editor from the context
const editorRef = aiPanelRefs.inputRef.current
if (!editorRef) return
const editor = editorRef.getEditor()
if (!editor) return
// Insert mention node at current cursor position
editor.update(() => {
const selection = $getSelection()
if (!$isRangeSelection(selection) || !selection.isCollapsed()) return
// Create and insert mention node
const mentionNode = $createMentionNode(mention)
selection.insertNodes([mentionNode])
// Add a space after the mention
const spaceNode = $createTextNode(" ")
selection.insertNodes([spaceNode])
})
// Focus back on the editor
editor.focus()
setIsMentionDropdownVisible(false)
},
[aiPanelRefs],
)
const handleMentionDropdownClose = useCallback(() => {
setIsMentionDropdownVisible(false)
setQuery("")
}, [])
// Calculate dropdown props
const dropdownProps = useMemo(() => {
if (!isMentionDropdownVisible) return null
return {
isVisible: true,
suggestions,
selectedIndex,
isLoading,
onSetSelectIndex: setSelectedIndex,
onSelect: handleMentionSelect,
onClose: handleMentionDropdownClose,
query,
anchor: atButtonRef.current,
showSearchInput: true,
onQueryChange: setQuery,
}
}, [
isMentionDropdownVisible,
suggestions,
selectedIndex,
isLoading,
handleMentionSelect,
handleMentionDropdownClose,
query,
])
return (
<>
<button
ref={atButtonRef}
type="button"
onClick={handleAtButtonClick}
className="flex size-7 items-center justify-center rounded-md border border-border bg-material-medium text-text-secondary transition-colors hover:bg-material-thin hover:text-text-secondary"
title="Add Context"
>
<i className="i-mgc-at-cute-re size-3.5" />
</button>
{dropdownProps ? (
<Suspense fallback={null}>
<MentionDropdown {...dropdownProps} />
</Suspense>
) : null}
</>
)
})
MentionButton.displayName = "MentionButton"
@@ -1,66 +1,72 @@
import { views } from "@follow/constants"
import { getView } from "@follow/constants"
import { useSubscriptionsByFeedIds } from "@follow/store/subscription/hooks"
import type { SubscriptionModel } from "@follow/store/subscription/types"
import { getDefaultCategory } from "@follow/store/subscription/utils"
import { clsx, cn } from "@follow/utils/utils"
import type { FC, ReactNode } from "react"
import { memo } from "react"
import { memo, useMemo } from "react"
import { useTranslation } from "react-i18next"
import { ImageThumbnail } from "~/modules/ai-chat/components/message/ImageThumbnail"
import { CircularProgress } from "~/modules/ai-chat/components/ui/UploadProgress"
import { ROUTE_FEED_IN_FOLDER } from "~/constants"
import { useContextBlockPresentation } from "~/modules/ai-chat/components/message/useContextBlockPresentation"
import { useChatBlockActions } from "~/modules/ai-chat/store/hooks"
import type { AIChatContextBlock, ValueContextBlock } from "~/modules/ai-chat/store/types"
import {
getFileCategoryFromMimeType,
getFileIconName,
} from "~/modules/ai-chat/utils/file-validation"
import { formatMentionDateValue } from "~/modules/ai-chat/utils/mentionDate"
import type { AbstractValueContextBlock, AIChatContextBlock } from "~/modules/ai-chat/store/types"
import { EntryTitle, FeedTitle } from "./TitleComponents"
const blockTypeCanNotBeRemoved = new Set<string>([])
import { FeedTitle } from "./TitleComponents"
const BlockContainer: FC<{
icon: string | null | undefined
label?: string
canRemove: boolean
onRemove?: () => void
disabled?: boolean
onDisableClick?: () => void
content: ReactNode
}> = memo(({ icon, label, canRemove, onRemove, content }) => {
readOnly?: boolean
className?: string
}> = memo(({ icon, label, onRemove, content, disabled, onDisableClick, readOnly, className }) => {
const isStringContent = typeof content === "string"
return (
<div
className={cn(
"group relative flex h-7 min-w-0 max-w-[calc(50%-0.5rem)] flex-shrink-0 items-center gap-2 overflow-hidden rounded-lg px-2.5",
"bg-fill-tertiary border-border border",
className={clsx(
"group relative flex h-7 min-w-0 items-center gap-2 overflow-hidden rounded-lg px-2.5",
"border border-border bg-fill-tertiary",
disabled && "cursor-pointer border-dashed italic opacity-50",
className,
)}
onClick={() => {
if (disabled) {
onDisableClick?.()
}
}}
>
<div
className={clsx(
"min-w-0",
canRemove
? "group-hover:[mask-image:linear-gradient(to_right,black_0%,black_calc(100%-3rem),rgba(0,0,0,0.8)_calc(100%-2rem),rgba(0,0,0,0.3)_calc(100%-1rem),transparent_100%)]"
: void 0,
!readOnly &&
!disabled &&
"group-hover:[mask-image:linear-gradient(to_right,black_0%,black_calc(100%-3rem),rgba(0,0,0,0.8)_calc(100%-2rem),rgba(0,0,0,0.3)_calc(100%-1rem),transparent_100%)]",
)}
>
<div className="flex min-w-0 flex-1 items-center gap-1.5">
<div className="flex items-center gap-1">
{icon && <i className={cn("size-3.5 flex-shrink-0", icon)} />}
{label && <span className="text-text-tertiary text-xs font-medium">{label}</span>}
{label && <span className="text-xs font-medium text-text-tertiary">{label}</span>}
</div>
{isStringContent ? (
<span className="text-text min-w-0 flex-1 truncate text-xs">{content}</span>
<span className="min-w-0 flex-1 truncate text-xs text-text">{content}</span>
) : (
<div className="text-text min-w-0 flex-1 truncate text-xs">{content}</div>
<div className="min-w-0 flex-1 truncate text-xs text-text">{content}</div>
)}
</div>
</div>
{canRemove && (
{onRemove && !disabled && !readOnly && (
<button
type="button"
onClick={onRemove}
className="text-text/90 cursor-button hover:text-text absolute inset-y-0 right-2 flex-shrink-0 opacity-0 transition-all ease-in group-hover:opacity-100"
className="absolute inset-y-0 right-2 flex-shrink-0 cursor-button text-text/90 opacity-0 transition-all ease-in hover:text-text group-hover:opacity-100"
>
<i className="i-mgc-close-cute-re size-3" />
</button>
@@ -70,225 +76,139 @@ const BlockContainer: FC<{
})
BlockContainer.displayName = "ContextBlockContainer"
type ValueBlockOf<Type extends ValueContextBlock["type"]> = Omit<ValueContextBlock, "type"> & {
type: Type
}
type MainViewBlock = AbstractValueContextBlock<"mainView">
type MainFeedBlock = AbstractValueContextBlock<"mainFeed">
type UnreadOnlyBlock = AbstractValueContextBlock<"unreadOnly">
type MainViewBlock = ValueBlockOf<"mainView">
type MainFeedBlock = ValueBlockOf<"mainFeed">
export const MainViewFeedContextBlock: FC<{
viewBlock: MainViewBlock
feedBlock: MainFeedBlock
}> = memo(({ viewBlock, feedBlock }) => {
const blockActions = useChatBlockActions()
const viewIcon = views.find((v) => v.view === Number(viewBlock.value))?.icon.props.className
const canRemove =
!blockTypeCanNotBeRemoved.has(viewBlock.type) && !blockTypeCanNotBeRemoved.has(feedBlock.type)
const handleRemove = () => {
blockActions.removeBlock(viewBlock.id)
blockActions.removeBlock(feedBlock.id)
}
return (
<BlockContainer
icon={viewIcon}
canRemove={canRemove}
onRemove={handleRemove}
content={<FeedTitle feedId={feedBlock.value} fallback={feedBlock.value} />}
/>
)
})
MainViewFeedContextBlock.displayName = "MainViewFeedContextBlock"
export const ContextBlock: FC<{ block: AIChatContextBlock }> = memo(({ block }) => {
export const CombinedContextBlock: FC<{
viewBlock?: MainViewBlock
feedBlock?: MainFeedBlock
unreadOnlyBlock?: UnreadOnlyBlock
readOnly?: boolean
}> = memo(({ viewBlock, feedBlock, unreadOnlyBlock, readOnly = false }) => {
const { t } = useTranslation("common")
const blockActions = useChatBlockActions()
const getBlockIcon = () => {
switch (block.type) {
case "mainView": {
const viewIcon = views.find((v) => v.view === Number(block.value))?.icon.props.className
return viewIcon
}
case "mainEntry": {
return "i-mgc-star-cute-fi"
}
case "referEntry": {
return "i-mgc-paper-cute-fi"
}
case "mainFeed":
case "referFeed": {
return "i-mgc-rss-cute-fi"
}
case "referDate": {
return "i-mgc-calendar-time-add-cute-re"
}
case "selectedText": {
return "i-mgc-quill-pen-cute-re"
}
case "fileAttachment": {
const { type, dataUrl, previewUrl } = block.attachment
const fileCategory = getFileCategoryFromMimeType(type)
const viewIcon = viewBlock && getView(Number(viewBlock.value))?.icon.props.className
const feedIcon = feedBlock && "i-mgc-rss-cute-fi"
// Don't show icon for images with thumbnails, as the thumbnail serves as the icon
if (fileCategory === "image" && (dataUrl || previewUrl)) {
return null
}
return getFileIconName(fileCategory)
}
default: {
return "i-mgc-paper-cute-fi"
}
const normalizedFeedIds = useMemo(() => {
if (!feedBlock?.value) {
return []
}
return feedBlock.value
.split(",")
.map((id) => id.trim())
.filter((id) => id && !id.startsWith(ROUTE_FEED_IN_FOLDER))
}, [feedBlock?.value])
const feedSubscriptions = useSubscriptionsByFeedIds(normalizedFeedIds)
const sharedFeedCategory = useMemo(() => {
if (normalizedFeedIds.length <= 1) {
return null
}
const relevantSubscriptions = feedSubscriptions.filter(
(subscription): subscription is SubscriptionModel =>
!!subscription && subscription.type === "feed" && !!subscription.feedId,
)
if (relevantSubscriptions.length !== normalizedFeedIds.length) {
return null
}
const categories = relevantSubscriptions.map((subscription) => {
const category = subscription.category || getDefaultCategory(subscription)
return category?.trim() || null
})
const firstCategory = categories[0]
if (!firstCategory) {
return null
}
return categories.every((category) => category === firstCategory) ? firstCategory : null
}, [feedSubscriptions, normalizedFeedIds])
const handleRemove = () => {
viewBlock && blockActions.toggleBlockDisabled(viewBlock.id, true)
feedBlock && blockActions.toggleBlockDisabled(feedBlock.id, true)
unreadOnlyBlock && blockActions.removeBlock(unreadOnlyBlock.id)
}
const getDisplayContent = () => {
switch (block.type) {
case "mainView": {
const viewName = views.find((v) => v.view === Number(block.value))?.name
return viewName ? t(viewName) : block.value
}
case "mainEntry":
case "referEntry": {
return <EntryTitle entryId={block.value} fallback={block.value} />
}
case "mainFeed":
case "referFeed": {
return <FeedTitle feedId={block.value} fallback={block.value} />
}
case "referDate": {
return formatMentionDateValue(block.value).label
}
case "selectedText": {
return `"${block.value}"`
}
case "fileAttachment": {
const { type, name, dataUrl, previewUrl, uploadStatus, errorMessage, uploadProgress } =
block.attachment
const fileCategory = getFileCategoryFromMimeType(type)
if (fileCategory === "image" && (dataUrl || previewUrl)) {
return (
<div className="flex items-center gap-1.5">
<div className="relative">
<ImageThumbnail
className={"m-0.5 size-5 rounded-md"}
attachment={block.attachment}
/>
{uploadStatus === "uploading" && uploadProgress !== undefined && (
<div className="absolute inset-0 flex items-center justify-center rounded-md bg-black/50">
<CircularProgress
progress={uploadProgress}
size={16}
strokeWidth={2}
variant="default"
className="text-white"
/>
</div>
)}
{uploadStatus === "error" && (
<div
className="bg-red/80 absolute inset-0 flex items-center justify-center rounded-md"
title={errorMessage}
>
<i className="i-mgc-close-cute-re size-3 text-white" />
</div>
)}
</div>
<div className="flex min-w-0 flex-1">
<span className="truncate">
{name}{" "}
{uploadStatus === "uploading" && uploadProgress !== undefined && (
<div className="text-text-tertiary text-xs">
({Math.round(uploadProgress)}%)
</div>
)}
</span>
{uploadStatus === "error" && <div className="text-red text-xs">Upload failed</div>}
</div>
</div>
)
}
// For non-image files
return (
<div className="flex items-center gap-1.5">
<span className="min-w-0 flex-1 truncate">{name}</span>
{uploadStatus === "uploading" && uploadProgress !== undefined && (
<div className="flex items-center gap-1">
<CircularProgress
progress={uploadProgress}
size={14}
strokeWidth={2}
variant="default"
/>
<span className="text-text-tertiary text-xs">{Math.round(uploadProgress)}%</span>
</div>
)}
{uploadStatus === "error" && (
<i className="i-mgc-close-cute-re text-red size-3" title={errorMessage} />
)}
</div>
)
}
default: {
// This should never happen with proper discriminated union
return ""
}
}
const handleEnable = () => {
viewBlock && blockActions.toggleBlockDisabled(viewBlock.id, false)
feedBlock && blockActions.toggleBlockDisabled(feedBlock.id, false)
}
const getBlockLabel = () => {
switch (block.type) {
case "mainView": {
return ""
}
case "mainEntry": {
return "Current"
}
case "mainFeed": {
return "Current"
}
case "referEntry": {
return "Ref"
}
case "referFeed": {
return "Feed"
}
case "referDate": {
return "Date"
}
case "selectedText": {
return "Text"
}
case "fileAttachment": {
return "File"
}
default: {
return ""
}
}
}
const canRemove = !blockTypeCanNotBeRemoved.has(block.type)
// Determine what to display
const displayContent = feedBlock ? (
<span className="flex items-center gap-1">
{sharedFeedCategory ? (
<span className="min-w-0 truncate" title={sharedFeedCategory}>
{sharedFeedCategory}
</span>
) : (
<FeedTitle
feedId={feedBlock.value}
fallback={feedBlock.value}
className="min-w-0 truncate"
/>
)}
{unreadOnlyBlock && <i className="i-mgc-round-cute-fi size-3 shrink-0" title="Unread Only" />}
</span>
) : (
<span className="flex items-center gap-1">
{(() => {
if (!viewBlock) return null
const viewName = getView(Number(viewBlock.value))?.name
return viewName ? t(viewName) : viewBlock.value
})()}
{unreadOnlyBlock && <i className="i-mgc-round-cute-fi size-3" title="Unread Only" />}
</span>
)
return (
<BlockContainer
icon={getBlockIcon()}
label={getBlockLabel()}
canRemove={canRemove}
onRemove={canRemove ? () => blockActions.removeBlock(block.id) : undefined}
content={getDisplayContent()}
icon={viewIcon || feedIcon}
disabled={viewBlock?.disabled || feedBlock?.disabled || unreadOnlyBlock?.disabled}
onRemove={!readOnly ? handleRemove : undefined}
onDisableClick={!readOnly ? handleEnable : undefined}
content={displayContent}
readOnly={readOnly}
/>
)
})
CombinedContextBlock.displayName = "CombinedContextBlock"
export const ContextBlock: FC<{ block: AIChatContextBlock; readOnly?: boolean }> = memo(
({ block, readOnly }) => {
const blockActions = useChatBlockActions()
const { icon, label, displayContent } = useContextBlockPresentation(block)
return (
<BlockContainer
icon={icon}
label={label}
disabled={block.disabled}
onRemove={() => {
if (block.type === "mainEntry") {
blockActions.toggleBlockDisabled(block.id, true)
} else {
blockActions.removeBlock(block.id)
}
}}
onDisableClick={() => {
if (block.type === "mainEntry") {
blockActions.toggleBlockDisabled(block.id, false)
}
}}
content={displayContent}
readOnly={readOnly}
/>
)
},
)
@@ -14,7 +14,11 @@ export const EntryTitle: FC<{ entryId?: string; fallback: string }> = ({ entryId
return <span>{entryTitle}</span>
}
export const FeedTitle: FC<{ feedId?: string; fallback: string }> = ({ feedId, fallback }) => {
export const FeedTitle: FC<{ feedId?: string; fallback: string; className?: string }> = ({
feedId,
fallback,
className,
}) => {
const category = feedId?.startsWith(ROUTE_FEED_IN_FOLDER)
? feedId.slice(ROUTE_FEED_IN_FOLDER.length)
: undefined
@@ -24,11 +28,11 @@ export const FeedTitle: FC<{ feedId?: string; fallback: string }> = ({ feedId, f
if (!feedId || !feedTitles) {
if (category) {
return <span>{category}</span>
return <span className={className}>{category}</span>
}
return <span className="text-text-tertiary">{fallback}</span>
return <span className={`text-text-tertiary ${className}`}>{fallback}</span>
}
return <span>{feedTitles}</span>
return <span className={className}>{feedTitles}</span>
}

Some files were not shown because too many files have changed in this diff Show More