Merge pull request #4467 from RSSNext/release/mobile/0.2.8
release(mobile): Release v0.2.8
This commit is contained in:
@@ -13,6 +13,102 @@ runs:
|
||||
with:
|
||||
xcode-version: ${{ inputs.xcode-version }}
|
||||
|
||||
- name: Download iOS Platform
|
||||
run: xcodebuild -downloadPlatform iOS
|
||||
- name: Setup Xcode Environment
|
||||
run: |
|
||||
set -e
|
||||
|
||||
echo "=== Checking CI Environment ==="
|
||||
echo "Current user: $(whoami)"
|
||||
echo "User groups: $(groups)"
|
||||
echo "Sudo available: $(sudo -n true 2>/dev/null && echo 'YES' || echo 'NO')"
|
||||
echo "Xcode path: $(xcode-select -p 2>/dev/null || echo 'Not set')"
|
||||
|
||||
# Set Xcode path and accept license
|
||||
echo "=== Setting up Xcode ==="
|
||||
if command -v sudo >/dev/null && sudo -n true 2>/dev/null; then
|
||||
sudo xcode-select -s /Applications/Xcode_${{ inputs.xcode-version }}.app/Contents/Developer
|
||||
sudo xcodebuild -license accept
|
||||
echo "Using sudo for Xcode setup"
|
||||
else
|
||||
xcode-select -s /Applications/Xcode_${{ inputs.xcode-version }}.app/Contents/Developer
|
||||
xcodebuild -license accept
|
||||
echo "Using direct access for Xcode setup"
|
||||
fi
|
||||
|
||||
echo "Final Xcode path: $(xcode-select -p)"
|
||||
shell: bash
|
||||
|
||||
- name: Start Simulator Service
|
||||
run: |
|
||||
echo "=== Starting Simulator Service ==="
|
||||
# Try to start simulator service (ignore errors if already running)
|
||||
sudo launchctl load -w /System/Library/LaunchDaemons/com.apple.CoreSimulator.CoreSimulatorService.plist 2>/dev/null || {
|
||||
echo "CoreSimulator service might already be running or command unavailable"
|
||||
}
|
||||
|
||||
# Alternative for newer macOS versions
|
||||
sudo launchctl bootstrap system /System/Library/LaunchDaemons/com.apple.CoreSimulator.CoreSimulatorService.plist 2>/dev/null || {
|
||||
echo "Bootstrap command failed or service already running"
|
||||
}
|
||||
|
||||
# Wait a moment for service to start
|
||||
sleep 3
|
||||
shell: bash
|
||||
|
||||
- name: Download iOS Platform
|
||||
run: |
|
||||
set -e
|
||||
|
||||
echo "=== Checking Available SDKs ==="
|
||||
echo "Currently available SDKs:"
|
||||
xcodebuild -showsdks | grep -E "(iOS|Simulator)" || echo "No iOS SDKs found yet"
|
||||
|
||||
echo "=== Attempting iOS Platform Download ==="
|
||||
|
||||
# Method 1: Try standard download
|
||||
if xcodebuild -downloadPlatform iOS -quiet 2>/dev/null; then
|
||||
echo "✅ iOS platform downloaded successfully with xcodebuild"
|
||||
elif xcrun xcodebuild -downloadPlatform iOS -quiet 2>/dev/null; then
|
||||
echo "✅ iOS platform downloaded successfully with xcrun xcodebuild"
|
||||
else
|
||||
echo "⚠️ Platform download failed, checking if iOS SDK is already available..."
|
||||
|
||||
# Check if iOS SDK is available
|
||||
if xcodebuild -showsdks | grep -q "iOS"; then
|
||||
echo "✅ iOS SDK is already available, continuing..."
|
||||
else
|
||||
echo "❌ No iOS SDK found and download failed"
|
||||
echo "Available SDKs:"
|
||||
xcodebuild -showsdks
|
||||
|
||||
# Try alternative download method
|
||||
echo "Trying alternative download method..."
|
||||
xcodebuild -downloadAllPlatforms -quiet || {
|
||||
echo "❌ All download methods failed"
|
||||
exit 1
|
||||
}
|
||||
fi
|
||||
fi
|
||||
|
||||
echo "=== Final SDK Status ==="
|
||||
echo "Available iOS SDKs:"
|
||||
xcodebuild -showsdks | grep -E "(iOS|Simulator)" || echo "No iOS SDKs found"
|
||||
|
||||
echo "Available simulators:"
|
||||
xcrun simctl list devices available | head -20 || echo "No simulators found"
|
||||
shell: bash
|
||||
|
||||
- name: Verify Setup
|
||||
run: |
|
||||
echo "=== Verification ==="
|
||||
echo "Xcode version: $(xcodebuild -version | head -1)"
|
||||
echo "Selected Xcode: $(xcode-select -p)"
|
||||
echo "iOS SDK available: $(xcodebuild -showsdks | grep -c iOS || echo 0)"
|
||||
|
||||
# Test basic functionality
|
||||
if xcodebuild -showsdks | grep -q "iOS"; then
|
||||
echo "✅ Setup completed successfully!"
|
||||
else
|
||||
echo "⚠️ Setup completed but iOS SDK may not be fully available"
|
||||
fi
|
||||
shell: bash
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
messages:
|
||||
- role: system
|
||||
content: |-
|
||||
You are a GitHub assistant with access to GitHub Model Context Protocol (MCP)
|
||||
tools in read-only mode. Your task is to search this repository's issues to find
|
||||
previously filed issues similar to the provided issue title and body. Use the
|
||||
GitHub tools via MCP to perform the search and retrieve real issue data (do not
|
||||
fabricate results). Consider semantic similarity across title and body. Exclude
|
||||
the current issue. Return up to 3 of the most similar past issues. If none are
|
||||
reasonably similar, return an empty list. Output must follow the response schema
|
||||
exactly and include only data you actually retrieved from GitHub tools.
|
||||
The current GitHub repository is: "{{repository}}".
|
||||
- role: user
|
||||
content: |-
|
||||
Find similar issues for this new issue:
|
||||
Title: {{issue_title}}
|
||||
Body:
|
||||
{{issue_body}}
|
||||
model: custom/openai/gpt-5
|
||||
responseFormat: json_schema
|
||||
jsonSchema: |-
|
||||
{
|
||||
"name": "similar_issues_result",
|
||||
"strict": true,
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"matches": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"number": { "type": "integer" },
|
||||
"title": { "type": "string" },
|
||||
"url": { "type": "string" },
|
||||
"similarity_score": { "type": "number", "minimum": 0, "maximum": 1 }
|
||||
},
|
||||
"required": ["number", "title", "url", "similarity_score"],
|
||||
"additionalProperties": false
|
||||
}
|
||||
}
|
||||
},
|
||||
"required": ["matches"],
|
||||
"additionalProperties": false
|
||||
}
|
||||
}
|
||||
@@ -45,7 +45,7 @@ jobs:
|
||||
cache: "pnpm"
|
||||
|
||||
- name: Set up JDK 17
|
||||
uses: actions/setup-java@v4
|
||||
uses: actions/setup-java@v5
|
||||
with:
|
||||
java-version: "17"
|
||||
distribution: "zulu"
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
name: Similar Issues via AI MCP
|
||||
|
||||
on:
|
||||
issues:
|
||||
types: [opened]
|
||||
|
||||
jobs:
|
||||
find-similar:
|
||||
permissions:
|
||||
contents: read
|
||||
issues: write
|
||||
models: read
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Check out repository
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Prepare prompt variables
|
||||
id: prepare_input
|
||||
uses: actions/github-script@v7
|
||||
with:
|
||||
script: |
|
||||
const issue = context.payload.issue || {};
|
||||
const title = issue.title || '';
|
||||
const body = issue.body || '';
|
||||
const indent = ' ';
|
||||
// Indent subsequent lines so YAML block scalar indentation remains valid
|
||||
const bodyIndented = body.replace(/\n/g, '\n' + indent);
|
||||
core.setOutput('issue_title_json', JSON.stringify(title));
|
||||
core.setOutput('issue_body_indented_json', JSON.stringify(bodyIndented));
|
||||
|
||||
- name: Find similar issues with AI (MCP)
|
||||
id: inference
|
||||
uses: actions/ai-inference@v1
|
||||
with:
|
||||
prompt-file: ./.github/prompts/similar_issues.prompt.yml
|
||||
input: |
|
||||
issue_title: ${{ steps.prepare_input.outputs.issue_title_json }}
|
||||
issue_body: ${{ steps.prepare_input.outputs.issue_body_indented_json }}
|
||||
repository: ${{ github.repository }}
|
||||
enable-github-mcp: true
|
||||
token: ${{ secrets.USER_PAT }}
|
||||
github-mcp-token: ${{ secrets.USER_PAT }}
|
||||
endpoint: https://models.github.ai/orgs/RSSNext/inference
|
||||
|
||||
- name: Prepare comment body
|
||||
id: prepare
|
||||
uses: actions/github-script@v7
|
||||
env:
|
||||
AI_RESPONSE: ${{ steps.inference.outputs.response }}
|
||||
with:
|
||||
script: |
|
||||
let data;
|
||||
try {
|
||||
data = JSON.parse(process.env.AI_RESPONSE || '{}');
|
||||
} catch (e) {
|
||||
core.setOutput('has_matches', 'false');
|
||||
return;
|
||||
}
|
||||
const matches = Array.isArray(data.matches) ? data.matches : [];
|
||||
if (!matches.length) {
|
||||
core.setOutput('has_matches', 'false');
|
||||
return;
|
||||
}
|
||||
const lines = [];
|
||||
lines.push('I found similar issues that might help:');
|
||||
for (const m of matches.slice(0, 3)) {
|
||||
const num = m.number != null ? `#${m.number}` : '';
|
||||
const title = m.title || 'Untitled';
|
||||
const url = m.url || '';
|
||||
const score = typeof m.similarity_score === 'number' ? ` (similarity: ${m.similarity_score.toFixed(2)})` : '';
|
||||
lines.push(`- ${url}${score}`.trim());
|
||||
}
|
||||
core.setOutput('has_matches', 'true');
|
||||
core.setOutput('comment_body', lines.join('\n'));
|
||||
|
||||
- name: Comment similar issues
|
||||
if: steps.prepare.outputs.has_matches == 'true'
|
||||
uses: actions/github-script@v7
|
||||
with:
|
||||
script: |
|
||||
const body = ${{ toJson(steps.prepare.outputs.comment_body) }};
|
||||
await github.rest.issues.createComment({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
issue_number: context.payload.issue.number,
|
||||
body
|
||||
});
|
||||
@@ -28,4 +28,3 @@ buildServer.json
|
||||
apps/desktop/build/appxmanifest.xml
|
||||
|
||||
.claude/settings.local.json
|
||||
PRPS/*
|
||||
|
||||
@@ -9,4 +9,8 @@ apps/mobile/android
|
||||
apps/mobile/ios
|
||||
apps/mobile/native/example
|
||||
|
||||
apps/mobile/native/android
|
||||
apps/mobile/native/ios
|
||||
apps/mobile/.expo
|
||||
|
||||
generated-routes.ts
|
||||
|
||||
@@ -38,7 +38,6 @@ Follow (Folo) is a modern RSS aggregator and content management platform with mu
|
||||
- `utils/` - Utility functions and helpers
|
||||
- `tracker/` - Analytics and tracking
|
||||
- `logger/` - Logging utilities
|
||||
- `legal/` - Legal and compliance utilities
|
||||
- **`packages/configs/`** - Shared configuration files
|
||||
- `tailwindcss/` - Tailwind CSS configurations
|
||||
- TypeScript and build configurations
|
||||
@@ -100,6 +99,12 @@ pnpm run typecheck
|
||||
pnpm run test
|
||||
```
|
||||
|
||||
You must first use `typecheck` to check if the code types are correct, and after making modifications, you need to use `typecheck` again until it passes.
|
||||
|
||||
After the `typecheck` passes, you can use `lint:fix` to check the code quality.
|
||||
|
||||
This project is a monorepo, and you can use the typecheck and `lint:fix` of sub-packages as needed, but please note that you must follow the above steps in order.
|
||||
|
||||
## Architecture Guidelines
|
||||
|
||||
### Multi-Platform Architecture
|
||||
@@ -137,6 +142,7 @@ For mobile, see @apps/mobile/CLAUDE.md
|
||||
3. For plural-sensitive languages, use `_one` and `_other` suffixes
|
||||
4. **Avoid conflicting flat keys** - During build, flat dot-separated keys (e.g., 'exif.custom.rendered.custom') are automatically converted to nested objects, which can cause conflicts. For example, 'exif.custom.rendered.custom' conflicts with 'exif.custom.rendered'. Avoid such patterns.
|
||||
5. **Never use `defaultValue` in translations** - Always add proper translations to all three required language files: `en.json`, `zh-CN.json`, and `ja.json` in the appropriate feature directories under `locales/`
|
||||
6. **Top-scope variables with translatable content** - Use `const` assertions (`as const`) instead of functions for type safety
|
||||
|
||||
Example:
|
||||
|
||||
|
||||
@@ -0,0 +1,384 @@
|
||||
# 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.
|
||||
@@ -0,0 +1,530 @@
|
||||
# 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.
|
||||
@@ -0,0 +1,735 @@
|
||||
# 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.
|
||||
@@ -0,0 +1,617 @@
|
||||
# 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.
|
||||
@@ -0,0 +1,938 @@
|
||||
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.
|
||||
@@ -0,0 +1,577 @@
|
||||
# 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.
|
||||
@@ -0,0 +1,660 @@
|
||||
# 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.
|
||||
@@ -0,0 +1,278 @@
|
||||
# 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.
|
||||
@@ -0,0 +1,397 @@
|
||||
# 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
|
||||
@@ -96,12 +96,6 @@ Because we know content is more than just text. From articles to videos, images
|
||||
|
||||

|
||||
|
||||
### $POWER An Ownership Economy
|
||||
|
||||
Tip creators across instantly with $POWER, support content you love, and unlock value in your own work. Your content, your power.
|
||||
|
||||

|
||||
|
||||
### More Than Just An App
|
||||
|
||||
This isn’t just another app. Folo is a community — introducing a new era of openness and community-driven experience.
|
||||
|
||||
@@ -2,8 +2,18 @@
|
||||
|
||||
## 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,5 +1,2 @@
|
||||
// Export types for renderer to use
|
||||
export type { IpcServices } from "./src/ipc"
|
||||
|
||||
// Export services for potential main process use
|
||||
export { services } from "./src/ipc"
|
||||
|
||||
@@ -23,6 +23,7 @@
|
||||
"@electron-toolkit/preload": "3.0.2",
|
||||
"@electron-toolkit/utils": "4.0.0",
|
||||
"@eneris/push-receiver": "4.3.0",
|
||||
"@follow-app/client-sdk": "catalog:",
|
||||
"@follow-app/readability": "workspace:*",
|
||||
"@follow/shared": "workspace:*",
|
||||
"@follow/utils": "workspace:*",
|
||||
@@ -30,6 +31,7 @@
|
||||
"@sentry/electron": "6.8.0",
|
||||
"builder-util-runtime": "9.3.1",
|
||||
"electron-context-menu": "4.0.5",
|
||||
"electron-ipc-decorator": "0.2.0",
|
||||
"electron-log": "5.4.1",
|
||||
"electron-squirrel-startup": "1.0.1",
|
||||
"electron-store": "10.1.0",
|
||||
|
||||
@@ -1,118 +0,0 @@
|
||||
import type { IpcMainInvokeEvent, WebContents } from "electron"
|
||||
import { ipcMain } from "electron"
|
||||
|
||||
// Base context for IPC methods
|
||||
export interface IpcContext {
|
||||
sender: WebContents
|
||||
event: IpcMainInvokeEvent
|
||||
}
|
||||
|
||||
// Metadata storage for decorated methods
|
||||
const methodMetadata = new WeakMap<any, Map<string, string>>()
|
||||
|
||||
// Decorator for IPC methods
|
||||
export function IpcMethod(methodName?: string) {
|
||||
return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) {
|
||||
const { constructor } = target
|
||||
|
||||
if (!methodMetadata.has(constructor)) {
|
||||
methodMetadata.set(constructor, new Map())
|
||||
}
|
||||
|
||||
const methods = methodMetadata.get(constructor)!
|
||||
const finalMethodName = methodName || propertyKey
|
||||
methods.set(propertyKey, finalMethodName)
|
||||
|
||||
return descriptor
|
||||
}
|
||||
}
|
||||
|
||||
// Handler registry for IPC methods
|
||||
export class IpcHandler {
|
||||
private static instance: IpcHandler
|
||||
private registeredChannels = new Set<string>()
|
||||
|
||||
static getInstance(): IpcHandler {
|
||||
if (!IpcHandler.instance) {
|
||||
IpcHandler.instance = new IpcHandler()
|
||||
}
|
||||
return IpcHandler.instance
|
||||
}
|
||||
|
||||
registerMethod<TOutput>(
|
||||
channel: string,
|
||||
handler: (context: IpcContext, ...args: any[]) => Promise<TOutput> | TOutput,
|
||||
) {
|
||||
if (this.registeredChannels.has(channel)) {
|
||||
return // Already registered
|
||||
}
|
||||
|
||||
this.registeredChannels.add(channel)
|
||||
|
||||
ipcMain.handle(channel, async (event: IpcMainInvokeEvent, ...args: any[]) => {
|
||||
const context: IpcContext = {
|
||||
sender: event.sender,
|
||||
event,
|
||||
}
|
||||
|
||||
try {
|
||||
return await handler(context, ...args)
|
||||
} catch (error) {
|
||||
console.error(`Error in IPC method ${channel}:`, error)
|
||||
throw error
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// Send events to renderer
|
||||
sendToRenderer<T = any>(webContents: WebContents, channel: string, data: T) {
|
||||
webContents.send(channel, data)
|
||||
}
|
||||
}
|
||||
|
||||
// Base class for IPC service groups
|
||||
export abstract class IpcService {
|
||||
protected handler = IpcHandler.getInstance()
|
||||
|
||||
constructor(protected groupName: string) {
|
||||
this.registerMethods()
|
||||
}
|
||||
|
||||
protected registerMethods(): void {
|
||||
const { constructor } = this
|
||||
const methods = methodMetadata.get(constructor)
|
||||
|
||||
if (methods) {
|
||||
for (const [propertyKey, methodName] of methods) {
|
||||
const method = (this as any)[propertyKey]
|
||||
if (typeof method === "function") {
|
||||
this.registerMethod(methodName, method.bind(this))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
protected registerMethod<TOutput>(
|
||||
methodName: string,
|
||||
handler: (context: IpcContext, ...args: any[]) => Promise<TOutput> | TOutput,
|
||||
) {
|
||||
const channel = `${this.groupName}.${methodName}`
|
||||
this.handler.registerMethod(channel, handler)
|
||||
}
|
||||
}
|
||||
|
||||
// Extract method signatures from service class, removing context parameter
|
||||
export type ExtractServiceMethods<T> = {
|
||||
[K in keyof T as T[K] extends (...args: any[]) => any ? K : never]: T[K] extends (
|
||||
context: IpcContext,
|
||||
...args: infer Args
|
||||
) => infer Output
|
||||
? Args extends []
|
||||
? () => AlwaysPromise<Output>
|
||||
: Args extends [infer Input]
|
||||
? (input: Input) => AlwaysPromise<Output>
|
||||
: (...args: Args) => AlwaysPromise<Output>
|
||||
: never
|
||||
}
|
||||
|
||||
type AlwaysPromise<T> = Promise<Awaited<T>>
|
||||
@@ -1,4 +1,6 @@
|
||||
import type { ExtractServiceMethods } from "./base"
|
||||
import type { MergeIpcService } from "electron-ipc-decorator"
|
||||
import { createServices } from "electron-ipc-decorator"
|
||||
|
||||
import { AppService } from "./services/app"
|
||||
import { AuthService } from "./services/auth"
|
||||
import { DebugService } from "./services/debug"
|
||||
@@ -9,31 +11,22 @@ import { ReaderService } from "./services/reader"
|
||||
import { SettingService } from "./services/setting"
|
||||
|
||||
// Initialize all services
|
||||
export const services = {
|
||||
app: new AppService(),
|
||||
auth: new AuthService(),
|
||||
debug: new DebugService(),
|
||||
dock: new DockService(),
|
||||
menu: new MenuService(),
|
||||
reader: new ReaderService(),
|
||||
setting: new SettingService(),
|
||||
integration: new IntegrationService(),
|
||||
} as const
|
||||
|
||||
const services = createServices([
|
||||
AppService,
|
||||
AuthService,
|
||||
DebugService,
|
||||
DockService,
|
||||
MenuService,
|
||||
ReaderService,
|
||||
SettingService,
|
||||
IntegrationService,
|
||||
])
|
||||
// Extract method types automatically from services
|
||||
export type IpcServices = {
|
||||
app: ExtractServiceMethods<AppService>
|
||||
auth: ExtractServiceMethods<AuthService>
|
||||
debug: ExtractServiceMethods<DebugService>
|
||||
dock: ExtractServiceMethods<DockService>
|
||||
menu: ExtractServiceMethods<MenuService>
|
||||
reader: ExtractServiceMethods<ReaderService>
|
||||
setting: ExtractServiceMethods<SettingService>
|
||||
integration: ExtractServiceMethods<IntegrationService>
|
||||
}
|
||||
export type IpcServices = MergeIpcService<typeof services>
|
||||
|
||||
// Initialize all services (this will register all IPC handlers)
|
||||
export function initializeIpcServices() {
|
||||
// Services are already initialized in the services constant above
|
||||
console.info("IPC services initialized")
|
||||
void services
|
||||
}
|
||||
|
||||
@@ -4,8 +4,11 @@ import { fileURLToPath } from "node:url"
|
||||
import { callWindowExpose } from "@follow/shared/bridge"
|
||||
import { DEV } from "@follow/shared/constants"
|
||||
import { app, BrowserWindow, clipboard, dialog, shell } from "electron"
|
||||
import type { IpcContext } from "electron-ipc-decorator"
|
||||
import { IpcMethod, IpcService } from "electron-ipc-decorator"
|
||||
import path from "pathe"
|
||||
|
||||
import { START_IN_TRAY_ARGS } from "~/constants/app"
|
||||
import { getCacheSize } from "~/lib/cleaner"
|
||||
import { i18n } from "~/lib/i18n"
|
||||
import { store, StoreKey } from "~/lib/store"
|
||||
@@ -17,8 +20,6 @@ import { cleanupOldRender, loadDynamicRenderEntry } from "~/updater/hot-updater"
|
||||
|
||||
import { downloadFile } from "../../lib/download"
|
||||
import { checkForAppUpdates, quitAndInstall } from "../../updater"
|
||||
import type { IpcContext } from "../base"
|
||||
import { IpcMethod, IpcService } from "../base"
|
||||
|
||||
interface WindowActionInput {
|
||||
action: "close" | "minimize" | "maximum"
|
||||
@@ -34,9 +35,7 @@ interface Sender extends Electron.WebContents {
|
||||
}
|
||||
|
||||
export class AppService extends IpcService {
|
||||
constructor() {
|
||||
super("app")
|
||||
}
|
||||
static override readonly groupName = "app"
|
||||
|
||||
@IpcMethod()
|
||||
getAppVersion(): string {
|
||||
@@ -183,6 +182,16 @@ export class AppService extends IpcService {
|
||||
return path.join(app.getAppPath(), input)
|
||||
}
|
||||
|
||||
@IpcMethod()
|
||||
readyToShowMainWindow(_context: IpcContext) {
|
||||
const shouldShowWindow =
|
||||
!app.getLoginItemSettings().wasOpenedAsHidden && !process.argv.includes(START_IN_TRAY_ARGS)
|
||||
if (shouldShowWindow) {
|
||||
const window = WindowManager.getMainWindow()
|
||||
if (window) window.show()
|
||||
}
|
||||
}
|
||||
|
||||
@IpcMethod()
|
||||
openCacheFolder(_context: IpcContext): void {
|
||||
const dir = path.join(app.getPath("userData"), "cache")
|
||||
@@ -217,22 +226,6 @@ export class AppService extends IpcService {
|
||||
})
|
||||
}
|
||||
|
||||
// getCacheLimit: t.procedure.action(async () => {
|
||||
// return store.get(StoreKey.CacheSizeLimit)
|
||||
// }),
|
||||
|
||||
// clearCache: t.procedure.action(async () => {
|
||||
|
||||
// }),
|
||||
|
||||
// limitCacheSize: t.procedure.input<number>().action(async ({ input }) => {
|
||||
// logger.info("set limitCacheSize", input)
|
||||
// if (input === 0) {
|
||||
// store.delete(StoreKey.CacheSizeLimit)
|
||||
// } else {
|
||||
// store.set(StoreKey.CacheSizeLimit, input)
|
||||
// }
|
||||
// }),
|
||||
@IpcMethod()
|
||||
limitCacheSize(_context: IpcContext, input: number): void {
|
||||
if (input === 0) {
|
||||
|
||||
@@ -1,11 +1,10 @@
|
||||
import type { IpcContext } from "electron-ipc-decorator"
|
||||
import { IpcMethod, IpcService } from "electron-ipc-decorator"
|
||||
|
||||
import { deleteNotificationsToken, updateNotificationsToken } from "../../lib/user"
|
||||
import type { IpcContext } from "../base"
|
||||
import { IpcMethod, IpcService } from "../base"
|
||||
|
||||
export class AuthService extends IpcService {
|
||||
constructor() {
|
||||
super("auth")
|
||||
}
|
||||
static override readonly groupName = "auth"
|
||||
|
||||
@IpcMethod()
|
||||
async sessionChanged(_context: IpcContext): Promise<void> {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import type { IpcContext } from "../base"
|
||||
import { IpcMethod, IpcService } from "../base"
|
||||
import type { IpcContext } from "electron-ipc-decorator"
|
||||
import { IpcMethod, IpcService } from "electron-ipc-decorator"
|
||||
|
||||
interface InspectElementInput {
|
||||
x: number
|
||||
@@ -7,9 +7,7 @@ interface InspectElementInput {
|
||||
}
|
||||
|
||||
export class DebugService extends IpcService {
|
||||
constructor() {
|
||||
super("debug")
|
||||
}
|
||||
static override readonly groupName = "debug"
|
||||
|
||||
@IpcMethod()
|
||||
inspectElement(context: IpcContext, input: InspectElementInput): void {
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import type { IpcContext } from "electron-ipc-decorator"
|
||||
import { IpcMethod, IpcService } from "electron-ipc-decorator"
|
||||
|
||||
import { UNREAD_BACKGROUND_POLLING_INTERVAL } from "../../constants/app"
|
||||
import { apiClient } from "../../lib/api-client"
|
||||
import { setDockCount } from "../../lib/dock"
|
||||
import type { IpcContext } from "../base"
|
||||
import { IpcMethod, IpcService } from "../base"
|
||||
|
||||
class PollingManager {
|
||||
private abortController: AbortController | null = null
|
||||
@@ -58,9 +59,7 @@ class PollingManager {
|
||||
export class DockService extends IpcService {
|
||||
private unreadPollingManager = new PollingManager()
|
||||
|
||||
constructor() {
|
||||
super("dock")
|
||||
}
|
||||
static override readonly groupName = "dock"
|
||||
|
||||
@IpcMethod()
|
||||
async pollingUpdateUnreadCount(): Promise<void> {
|
||||
@@ -77,7 +76,8 @@ export class DockService extends IpcService {
|
||||
|
||||
@IpcMethod()
|
||||
async updateUnreadCount(): Promise<void> {
|
||||
const res = await apiClient.reads["total-count"].$get()
|
||||
const res = await apiClient.reads.getTotalCount()
|
||||
|
||||
setDockCount(res.data.count)
|
||||
}
|
||||
|
||||
|
||||
@@ -2,14 +2,13 @@ import { existsSync } from "node:fs"
|
||||
import fsp from "node:fs/promises"
|
||||
|
||||
import { shell } from "electron"
|
||||
import type { IpcContext } from "electron-ipc-decorator"
|
||||
import { IpcMethod, IpcService } from "electron-ipc-decorator"
|
||||
import path from "pathe"
|
||||
|
||||
import { store } from "~/lib/store"
|
||||
import { logger } from "~/logger"
|
||||
|
||||
import type { IpcContext } from "../base"
|
||||
import { IpcMethod, IpcService } from "../base"
|
||||
|
||||
// Taken from https://github.com/rollup/rollup/blob/4f69d33af3b2ec9320c43c9e6c65ea23a02bdde3/src/utils/sanitizeFileName.ts
|
||||
// https://datatracker.ietf.org/doc/html/rfc2396
|
||||
// eslint-disable-next-line no-control-regex
|
||||
@@ -55,9 +54,7 @@ interface CustomFetchInput {
|
||||
}
|
||||
|
||||
export class IntegrationService extends IpcService {
|
||||
constructor() {
|
||||
super("integration")
|
||||
}
|
||||
static override readonly groupName = "integration"
|
||||
|
||||
@IpcMethod()
|
||||
async saveToObsidian(
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
import type { MenuItemConstructorOptions, MessageBoxOptions } from "electron"
|
||||
import { dialog, Menu, ShareMenu } from "electron"
|
||||
|
||||
import type { IpcContext } from "../base"
|
||||
import { IpcMethod, IpcService } from "../base"
|
||||
import type { IpcContext } from "electron-ipc-decorator"
|
||||
import { IpcMethod, IpcService } from "electron-ipc-decorator"
|
||||
|
||||
type SerializableMenuItem = Omit<MenuItemConstructorOptions, "click" | "submenu"> & {
|
||||
submenu?: SerializableMenuItem[]
|
||||
@@ -19,9 +18,7 @@ interface ShowConfirmDialogInput {
|
||||
}
|
||||
|
||||
export class MenuService extends IpcService {
|
||||
constructor() {
|
||||
super("menu")
|
||||
}
|
||||
static override readonly groupName = "menu"
|
||||
|
||||
private normalizeMenuItems(
|
||||
items: SerializableMenuItem[],
|
||||
|
||||
@@ -3,13 +3,13 @@ import fs from "node:fs"
|
||||
import { callWindowExpose } from "@follow/shared/bridge"
|
||||
import { readability } from "@follow-app/readability"
|
||||
import { app, BrowserWindow } from "electron"
|
||||
import type { IpcContext } from "electron-ipc-decorator"
|
||||
import { IpcMethod, IpcService } from "electron-ipc-decorator"
|
||||
import { MsEdgeTTS, OUTPUT_FORMAT } from "msedge-tts"
|
||||
import path from "pathe"
|
||||
import type { ModelResult } from "vscode-languagedetection"
|
||||
|
||||
import { detectCodeStringLanguage } from "../../modules/language-detection"
|
||||
import type { IpcContext } from "../base"
|
||||
import { IpcMethod, IpcService } from "../base"
|
||||
|
||||
const tts = new MsEdgeTTS()
|
||||
|
||||
@@ -29,9 +29,7 @@ interface DetectCodeStringLanguageInput {
|
||||
}
|
||||
|
||||
export class ReaderService extends IpcService {
|
||||
constructor() {
|
||||
super("reader")
|
||||
}
|
||||
static override readonly groupName = "reader"
|
||||
|
||||
@IpcMethod()
|
||||
async readability(_context: IpcContext, input: ReadabilityInput) {
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
import { createRequire } from "node:module"
|
||||
|
||||
import { app, nativeTheme } from "electron"
|
||||
import type { IpcContext } from "electron-ipc-decorator"
|
||||
import { IpcMethod, IpcService } from "electron-ipc-decorator"
|
||||
|
||||
import { WindowManager } from "~/manager/window"
|
||||
|
||||
import { setProxyConfig, updateProxy } from "../../lib/proxy"
|
||||
import { store } from "../../lib/store"
|
||||
import { getTrayConfig, setTrayConfig } from "../../lib/tray"
|
||||
import type { IpcContext } from "../base"
|
||||
import { IpcMethod, IpcService } from "../base"
|
||||
|
||||
const require = createRequire(import.meta.url)
|
||||
|
||||
@@ -20,9 +20,7 @@ interface SetLoginItemSettingsInput {
|
||||
}
|
||||
|
||||
export class SettingService extends IpcService {
|
||||
constructor() {
|
||||
super("setting")
|
||||
}
|
||||
static override readonly groupName = "setting"
|
||||
|
||||
@IpcMethod()
|
||||
getLoginItemSettings(_context: IpcContext): Electron.LoginItemSettings {
|
||||
|
||||
@@ -1,49 +1,80 @@
|
||||
import type { AppType } from "@follow/shared"
|
||||
import { env } from "@follow/shared/env.desktop"
|
||||
import { createDesktopAPIHeaders } from "@follow/utils/headers"
|
||||
import { FollowClient } from "@follow-app/client-sdk"
|
||||
import PKG from "@pkg"
|
||||
import { hc } from "hono/client"
|
||||
import { ofetch } from "ofetch"
|
||||
|
||||
import { BETTER_AUTH_COOKIE_NAME_SESSION_TOKEN } from "~/constants/app"
|
||||
import { WindowManager } from "~/manager/window"
|
||||
|
||||
import { logger } from "../logger"
|
||||
|
||||
const abortController = new AbortController()
|
||||
const apiFetch = ofetch.create({
|
||||
baseURL: env.VITE_API_URL,
|
||||
export const followClient = new FollowClient({
|
||||
credentials: "include",
|
||||
signal: abortController.signal,
|
||||
retry: false,
|
||||
cache: "no-store",
|
||||
onRequest({ request }) {
|
||||
logger.info(`API Request: ${request.toString()}`)
|
||||
},
|
||||
onRequestError(context) {
|
||||
if (context.error.name === "AbortError") {
|
||||
return
|
||||
}
|
||||
},
|
||||
timeout: 10000,
|
||||
|
||||
baseURL: env.VITE_API_URL,
|
||||
fetch: async (input, options = {}) =>
|
||||
fetch(input.toString(), {
|
||||
...options,
|
||||
cache: "no-store",
|
||||
}),
|
||||
})
|
||||
|
||||
export const apiClient = hc<AppType>("", {
|
||||
fetch: async (input, options = {}) => apiFetch(input.toString(), options),
|
||||
async headers() {
|
||||
const window = WindowManager.getMainWindow()
|
||||
const cookies = await window?.webContents.session.cookies.get({
|
||||
domain: new URL(env.VITE_API_URL).hostname,
|
||||
})
|
||||
const sessionCookie = cookies?.find((cookie) =>
|
||||
cookie.name.includes(BETTER_AUTH_COOKIE_NAME_SESSION_TOKEN),
|
||||
)
|
||||
const headerCookie = sessionCookie ? `${sessionCookie.name}=${sessionCookie.value}` : ""
|
||||
const userAgent = window?.webContents.getUserAgent() || `Folo/${PKG.version}`
|
||||
export const followApi = followClient.api
|
||||
|
||||
return {
|
||||
...createDesktopAPIHeaders({ version: PKG.version }),
|
||||
Cookie: headerCookie,
|
||||
"User-Agent": userAgent,
|
||||
}
|
||||
},
|
||||
followClient.addRequestInterceptor(async (ctx) => {
|
||||
const { options } = ctx
|
||||
const header = options.headers || {}
|
||||
|
||||
const apiHeader = createDesktopAPIHeaders({ version: PKG.version })
|
||||
|
||||
// Get cookies for authentication
|
||||
const window = WindowManager.getMainWindow()
|
||||
const cookies = await window?.webContents.session.cookies.get({
|
||||
domain: new URL(env.VITE_API_URL).hostname,
|
||||
})
|
||||
const sessionCookie = cookies?.find((cookie) =>
|
||||
cookie.name.includes(BETTER_AUTH_COOKIE_NAME_SESSION_TOKEN),
|
||||
)
|
||||
const headerCookie = sessionCookie ? `${sessionCookie.name}=${sessionCookie.value}` : ""
|
||||
const userAgent = window?.webContents.getUserAgent() || `Folo/${PKG.version}`
|
||||
|
||||
options.headers = {
|
||||
...header,
|
||||
...apiHeader,
|
||||
Cookie: headerCookie,
|
||||
"User-Agent": userAgent,
|
||||
}
|
||||
return ctx
|
||||
})
|
||||
|
||||
followClient.addResponseInterceptor(({ response }) => {
|
||||
logger.info(`API Response: ${response.status} ${response.statusText}`)
|
||||
return response
|
||||
})
|
||||
|
||||
followClient.addErrorInterceptor(async ({ error, response }) => {
|
||||
if (!response) {
|
||||
logger.error("API Request failed - no response", error)
|
||||
return error
|
||||
}
|
||||
|
||||
logger.error(`API Request failed: ${response.status} ${response.statusText}`, error)
|
||||
|
||||
// Handle specific error cases if needed in main process
|
||||
if (response.status === 401) {
|
||||
logger.warn("Authentication failed in main process")
|
||||
}
|
||||
|
||||
try {
|
||||
const json = await response.clone().json()
|
||||
logger.error("API Error details:", json)
|
||||
} catch {
|
||||
// ignore JSON parsing errors
|
||||
}
|
||||
|
||||
return error
|
||||
})
|
||||
|
||||
// Legacy export for compatibility
|
||||
export const apiClient = followApi
|
||||
|
||||
@@ -21,11 +21,9 @@ export const updateNotificationsToken = async (newCredentials?: Credentials) =>
|
||||
const credentials = newCredentials || store.get("notifications-credentials")
|
||||
if (credentials?.fcm?.token) {
|
||||
try {
|
||||
await apiClient.messaging.$post({
|
||||
json: {
|
||||
token: credentials.fcm.token,
|
||||
channel: notificationChannel,
|
||||
},
|
||||
await apiClient.messaging.createToken({
|
||||
token: credentials.fcm.token,
|
||||
channel: notificationChannel,
|
||||
})
|
||||
logger.info("updateNotificationsToken success: ", credentials.fcm.token)
|
||||
} catch (error) {
|
||||
@@ -35,9 +33,7 @@ export const updateNotificationsToken = async (newCredentials?: Credentials) =>
|
||||
}
|
||||
|
||||
export const deleteNotificationsToken = async () => {
|
||||
await apiClient.messaging.$delete({
|
||||
json: {
|
||||
channel: notificationChannel,
|
||||
},
|
||||
await apiClient.messaging.deleteToken({
|
||||
channel: notificationChannel,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -5,11 +5,10 @@ import { LEGACY_APP_PROTOCOL } from "@follow/shared"
|
||||
import { callWindowExpose, WindowState } from "@follow/shared/bridge"
|
||||
import { APP_PROTOCOL, DEV } from "@follow/shared/constants"
|
||||
import type { BrowserWindowConstructorOptions } from "electron"
|
||||
import { app, BrowserWindow, screen, shell } from "electron"
|
||||
import { BrowserWindow, screen, shell } from "electron"
|
||||
import type { Event } from "electron/main"
|
||||
import path from "pathe"
|
||||
|
||||
import { START_IN_TRAY_ARGS } from "~/constants/app"
|
||||
import { isMacOS, isWindows, isWindows11 } from "~/env"
|
||||
import { filePathToAppUrl, getIconPath } from "~/helper"
|
||||
import { t } from "~/lib/i18n"
|
||||
@@ -83,12 +82,6 @@ class WindowManagerStatic {
|
||||
refreshBound(window, this.config.refreshBoundDelay)
|
||||
})
|
||||
|
||||
window.on("ready-to-show", () => {
|
||||
const shouldShowWindow =
|
||||
!app.getLoginItemSettings().wasOpenedAsHidden && !process.argv.includes(START_IN_TRAY_ARGS)
|
||||
if (shouldShowWindow) window.show()
|
||||
})
|
||||
|
||||
window.webContents.setWindowOpenHandler((details) => {
|
||||
shell.openExternal(details.url)
|
||||
return { action: "deny" }
|
||||
|
||||
@@ -17,17 +17,101 @@
|
||||
<link rel="shortcut icon" href="/favicon.ico" type="image/x-icon" />
|
||||
<link rel="apple-touch-icon" href="/apple-touch-icon-180x180.png" />
|
||||
|
||||
<title>Folo</title>
|
||||
<title>Folo - AI-Driven RSS 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."
|
||||
/>
|
||||
<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"
|
||||
/>
|
||||
<meta name="author" content="Follow Team" />
|
||||
<meta name="robots" content="index, follow" />
|
||||
<meta name="language" content="en" />
|
||||
<link rel="canonical" href="https://app.folo.is" />
|
||||
|
||||
<!-- Apple Meta Tags -->
|
||||
<meta name="apple-itunes-app" content="app-id=6739802604" />
|
||||
<meta name="apple-mobile-web-app-capable" content="yes" />
|
||||
<meta name="apple-mobile-web-app-status-bar-style" content="default" />
|
||||
<meta name="apple-mobile-web-app-title" content="Folo" />
|
||||
|
||||
<!-- OpenGraph Meta Tags -->
|
||||
<meta property="og:type" content="website" />
|
||||
<meta property="og:title" content="Folo" />
|
||||
<meta property="og:site_name" content="Folo" />
|
||||
<meta property="og:title" content="Folo - AI-Driven RSS 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:description" content="Your Self-custodial Feeds." />
|
||||
<meta property="og:image:alt" content="Folo - AI-Driven RSS 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."
|
||||
/>
|
||||
<meta property="og:locale" content="en_US" />
|
||||
|
||||
<!-- Twitter Meta Tags -->
|
||||
<meta name="twitter:card" content="summary_large_image" />
|
||||
<meta name="twitter:title" content="Folo" />
|
||||
<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: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" />
|
||||
|
||||
<!-- Structured Data -->
|
||||
<script type="application/ld+json">
|
||||
{
|
||||
"@context": "https://schema.org",
|
||||
"@type": "SoftwareApplication",
|
||||
"name": "Folo",
|
||||
"alternateName": "Follow Everything",
|
||||
"description": "AI-driven, user-friendly RSS reader that organizes content into one timeline, keeping you updated on what matters, noise-free. Share lists, explore collections, and enjoy distraction-free browsing.",
|
||||
"url": "https://app.folo.is",
|
||||
"image": "https://app.folo.is/og-image.png",
|
||||
"applicationCategory": "ProductivityApplication",
|
||||
"operatingSystem": ["iOS", "Android", "macOS", "Windows", "Linux", "Web"],
|
||||
"offers": {
|
||||
"@type": "Offer",
|
||||
"price": "0",
|
||||
"priceCurrency": "USD"
|
||||
},
|
||||
"publisher": {
|
||||
"@type": "Organization",
|
||||
"name": "RSSNext",
|
||||
"url": "https://github.com/RSSNext"
|
||||
},
|
||||
"downloadUrl": [
|
||||
"https://apps.apple.com/us/app/folo-follow-everything/id6739802604",
|
||||
"https://play.google.com/store/apps/details?id=is.follow",
|
||||
"https://apps.microsoft.com/detail/9nvfzpv0v0ht?mode=direct",
|
||||
"https://github.com/RSSNext/Folo/releases/latest"
|
||||
],
|
||||
"screenshot": [
|
||||
"https://github.com/user-attachments/assets/11dc7d21-f5d8-4e41-9269-24fc352aa02b",
|
||||
"https://github.com/user-attachments/assets/37cf4f2f-4c5e-4775-86e8-2fa1a1b2ecf5",
|
||||
"https://github.com/user-attachments/assets/d1379fd6-8767-476e-b0dc-d61753715e26"
|
||||
],
|
||||
"featureList": [
|
||||
"Customized Information Hub",
|
||||
"AI-powered translation and summary",
|
||||
"Dynamic content support (articles, videos, images, audio)",
|
||||
"Distraction-free browsing",
|
||||
"Cross-platform availability",
|
||||
"Open source community-driven"
|
||||
],
|
||||
"aggregateRating": {
|
||||
"@type": "AggregateRating",
|
||||
"ratingValue": "4.8",
|
||||
"ratingCount": "1000",
|
||||
"bestRating": "5",
|
||||
"worstRating": "1"
|
||||
}
|
||||
}
|
||||
</script>
|
||||
<!-- Check Browser Script Inject -->
|
||||
|
||||
<script>
|
||||
|
||||
@@ -59,6 +59,7 @@
|
||||
"cookie-es": "2.0.0",
|
||||
"dayjs": "1.11.13",
|
||||
"dnum": "2.15.0",
|
||||
"electron-ipc-decorator": "0.2.0",
|
||||
"embla-carousel-react": "8.6.0",
|
||||
"embla-carousel-wheel-gestures": "8.0.2",
|
||||
"es-toolkit": "1.39.6",
|
||||
@@ -91,12 +92,14 @@
|
||||
"react-i18next": "15.6.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.6.3",
|
||||
"react-selecto": "1.26.3",
|
||||
"react-shadow": "20.6.0",
|
||||
"react-zoom-pan-pinch": "3.7.0",
|
||||
"rehype-raw": "7.0.0",
|
||||
"shiki": "3.7.0",
|
||||
"sonner": "2.0.6",
|
||||
"tinykeys": "3.0.0",
|
||||
@@ -118,7 +121,7 @@
|
||||
"@follow/models": "workspace:*",
|
||||
"@follow/types": "workspace:*",
|
||||
"@follow/utils": "workspace:*",
|
||||
"@folo-services/ai-tools": "0.2.20",
|
||||
"@folo-services/ai-tools": "0.2.36",
|
||||
"@types/node": "24.0.10",
|
||||
"@vite-pwa/assets-generator": "1.0.0",
|
||||
"fake-indexeddb": "6.0.1",
|
||||
|
||||
@@ -1,14 +1,16 @@
|
||||
import { isMobile } from "@follow/components/hooks/useMobile.js"
|
||||
import { IN_ELECTRON } from "@follow/shared/constants"
|
||||
import { tracker } from "@follow/tracker"
|
||||
import { nextFrame } from "@follow/utils"
|
||||
import { cn, getOS } from "@follow/utils/utils"
|
||||
import { useEffect } from "react"
|
||||
import { useEffect, useLayoutEffect, useRef } from "react"
|
||||
import { Outlet } from "react-router"
|
||||
|
||||
import { useAppIsReady } from "./atoms/app"
|
||||
import { useUISettingKey } from "./atoms/settings/ui"
|
||||
import { applyAfterReadyCallbacks } from "./initialize/queue"
|
||||
import { removeAppSkeleton } from "./lib/app"
|
||||
import { ipcServices } from "./lib/client"
|
||||
import { appLog } from "./lib/log"
|
||||
import { Titlebar } from "./modules/app/Titlebar"
|
||||
import { RootProviders } from "./providers/root-providers"
|
||||
@@ -37,13 +39,19 @@ function App() {
|
||||
const AppLayer = () => {
|
||||
const appIsReady = useAppIsReady()
|
||||
|
||||
useEffect(() => {
|
||||
removeAppSkeleton()
|
||||
const onceReady = useRef(false)
|
||||
useLayoutEffect(() => {
|
||||
if (appIsReady && !onceReady.current) {
|
||||
onceReady.current = true
|
||||
ipcServices?.app.readyToShowMainWindow()
|
||||
nextFrame(removeAppSkeleton)
|
||||
}
|
||||
}, [appIsReady])
|
||||
|
||||
useEffect(() => {
|
||||
const doneTime = Math.trunc(performance.now())
|
||||
tracker.uiRenderInit(doneTime)
|
||||
appLog("App is ready", `${doneTime}ms`)
|
||||
|
||||
applyAfterReadyCallbacks()
|
||||
|
||||
if (isMobile()) {
|
||||
|
||||
@@ -1,12 +1 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<svg version="1.1" xmlns="http://www.w3.org/2000/svg" width="470" height="470" viewBox="-10 -10 490 490">
|
||||
<path
|
||||
d="M0 0 C1.9825408 -0.00435531 3.96507991 -0.00954117 5.94761658 -0.01548767 C11.29914353 -0.02880291 16.65059953 -0.02946456 22.00213981 -0.02692437 C26.48711863 -0.02584926 30.97208341 -0.03075194 35.4570592 -0.03552979 C46.04918311 -0.04659982 56.64127155 -0.04707695 67.23339844 -0.04101562 C78.11865952 -0.03498176 89.00379115 -0.04727776 99.88903016 -0.06858569 C109.27124526 -0.08626837 118.65341942 -0.09219246 128.03565055 -0.08894795 C133.62296658 -0.08714506 139.21019031 -0.0896708 144.79749107 -0.10366249 C150.0581393 -0.1163447 155.3185876 -0.11419964 160.57923317 -0.1012516 C162.49546505 -0.09890846 164.41171146 -0.10153786 166.32792664 -0.10987473 C204.8488433 -0.26520886 239.2517555 12.70339909 268.08325195 38.2746582 C269.13672369 39.14749773 270.19270311 40.01731985 271.2512207 40.8840332 C274.98874055 44.03901548 277.97488568 47.51127222 281.08325195 51.2746582 C281.92114258 52.2749707 282.7590332 53.2752832 283.62231445 54.3059082 C307.20952489 82.9980649 317.41167497 116.39634833 317.35791016 153.19140625 C317.36226547 155.17394705 317.36745132 157.15648616 317.37339783 159.13902283 C317.38671307 164.49054978 317.38737471 169.84200578 317.38483453 175.19354606 C317.38375941 179.67852488 317.3886621 184.16348966 317.39343995 188.64846545 C317.40450997 199.24058936 317.40498711 209.8326778 317.39892578 220.42480469 C317.39289192 231.31006577 317.40518791 242.1951974 317.42649585 253.08043641 C317.44417853 262.46265151 317.45010262 271.84482567 317.44685811 281.2270568 C317.44505522 286.81437283 317.44758096 292.40159656 317.46157265 297.98889732 C317.47425485 303.24954555 317.4721098 308.50999385 317.45916176 313.77063942 C317.45681862 315.6868713 317.45944801 317.60311771 317.46778488 319.51933289 C317.62311902 358.04024955 304.65451106 392.44316175 279.08325195 421.2746582 C278.21041243 422.32812994 277.34059031 423.38410936 276.47387695 424.44262695 C273.31889468 428.1801468 269.84663793 431.16629193 266.08325195 434.2746582 C264.5827832 435.53149414 264.5827832 435.53149414 263.05200195 436.8137207 C246.64807275 450.29904125 221.15879029 467.2746582 199.08325195 467.2746582 C199.70155235 463.7527437 200.62736171 460.59849883 201.9387207 457.2746582 C202.31101807 456.31599854 202.68331543 455.35733887 203.06689453 454.36962891 C203.46416748 453.34828857 203.86144043 452.32694824 204.27075195 451.2746582 C228.81811101 386.77872712 226.90931904 315.03997803 199.49682617 251.62988281 C187.88874913 225.78099281 172.41465985 202.6479464 153.3293457 181.7434082 C151.82622596 180.09128355 150.33923169 178.42434933 148.8684082 176.7434082 C143.63303823 170.7811591 138.12599689 165.41465121 132.08325195 160.2746582 C131.51751465 159.79125977 130.95177734 159.30786133 130.36889648 158.80981445 C94.75519251 128.56126737 48.98095846 105.38997381 2.27856445 99.59887695 C0.08325195 99.2746582 0.08325195 99.2746582 -1.91674805 98.2746582 C-15.44086231 96.32228344 -29.02835583 96.06070803 -42.66674805 96.0246582 C-43.82069565 96.01702957 -43.82069565 96.01702957 -44.99795532 96.00924683 C-59.7457176 95.93093387 -74.27430498 96.87030628 -88.6237793 100.48950195 C-93.73689751 101.70864402 -98.91162422 102.55083535 -104.0925293 103.4309082 C-107.56151278 104.19628147 -110.6011106 105.21696947 -113.88769531 106.51196289 C-117.269316 107.78307143 -120.75000326 108.68709249 -124.22924805 109.6496582 C-130.30789962 111.3774146 -135.96632622 113.44103147 -141.66674805 116.2043457 C-144.34618602 117.47893946 -147.07438595 118.42963163 -149.91674805 119.2746582 C-149.34869805 113.47663069 -148.22107294 108.28681653 -146.35424805 102.7746582 C-145.96160767 101.60942627 -145.96160767 101.60942627 -145.56103516 100.4206543 C-142.73179119 92.32041118 -139.00847008 84.80013691 -134.91674805 77.2746582 C-134.08530273 75.70458008 -134.08530273 75.70458008 -133.23706055 74.1027832 C-128.65110321 65.80856371 -122.93390267 58.55711322 -116.91674805 51.2746582 C-116.26319336 50.47672852 -115.60963867 49.67879883 -114.9362793 48.85668945 C-110.97590247 44.17130085 -106.65400365 40.1632198 -101.91674805 36.2746582 C-100.91901367 35.4393457 -99.9212793 34.6040332 -98.89331055 33.7434082 C-70.20437402 10.14837602 -36.79614021 -0.05376639 0 0 Z"
|
||||
fill="none" stroke="currentColor" stroke-width="2" transform="translate(152.916748046875,-0.274658203125)" />
|
||||
<path
|
||||
d="M0 0 C1.9825408 -0.00435531 3.96507991 -0.00954117 5.94761658 -0.01548767 C11.29914353 -0.02880291 16.65059953 -0.02946456 22.00213981 -0.02692437 C26.48711863 -0.02584926 30.97208341 -0.03075194 35.4570592 -0.03552979 C46.04918311 -0.04659982 56.64127155 -0.04707695 67.23339844 -0.04101562 C78.11865952 -0.03498176 89.00379115 -0.04727776 99.88903016 -0.06858569 C109.27124526 -0.08626837 118.65341942 -0.09219246 128.03565055 -0.08894795 C133.62296658 -0.08714506 139.21019031 -0.0896708 144.79749107 -0.10366249 C150.0581393 -0.1163447 155.3185876 -0.11419964 160.57923317 -0.1012516 C162.49546505 -0.09890846 164.41171146 -0.10153786 166.32792664 -0.10987473 C204.8488433 -0.26520886 239.2517555 12.70339909 268.08325195 38.2746582 C269.13672369 39.14749773 270.19270311 40.01731985 271.2512207 40.8840332 C274.98874055 44.03901548 277.97488568 47.51127222 281.08325195 51.2746582 C281.92114258 52.2749707 282.7590332 53.2752832 283.62231445 54.3059082 C307.20952489 82.9980649 317.41167497 116.39634833 317.35791016 153.19140625 C317.36226547 155.17394705 317.36745132 157.15648616 317.37339783 159.13902283 C317.38671307 164.49054978 317.38737471 169.84200578 317.38483453 175.19354606 C317.38375941 179.67852488 317.3886621 184.16348966 317.39343995 188.64846545 C317.40450997 199.24058936 317.40498711 209.8326778 317.39892578 220.42480469 C317.39289192 231.31006577 317.40518791 242.1951974 317.42649585 253.08043641 C317.44417853 262.46265151 317.45010262 271.84482567 317.44685811 281.2270568 C317.44505522 286.81437283 317.44758096 292.40159656 317.46157265 297.98889732 C317.47425485 303.24954555 317.4721098 308.50999385 317.45916176 313.77063942 C317.45681862 315.6868713 317.45944801 317.60311771 317.46778488 319.51933289 C317.62311902 358.04024955 304.65451106 392.44316175 279.08325195 421.2746582 C278.21041243 422.32812994 277.34059031 423.38410936 276.47387695 424.44262695 C273.31889468 428.1801468 269.84663793 431.16629193 266.08325195 434.2746582 C264.5827832 435.53149414 264.5827832 435.53149414 263.05200195 436.8137207 C246.64807275 450.29904125 221.15879029 467.2746582 199.08325195 467.2746582 C199.70155235 463.7527437 200.62736171 460.59849883 201.9387207 457.2746582 C202.31101807 456.31599854 202.68331543 455.35733887 203.06689453 454.36962891 C203.46416748 453.34828857 203.86144043 452.32694824 204.27075195 451.2746582 C228.81811101 386.77872712 226.90931904 315.03997803 199.49682617 251.62988281 C187.88874913 225.78099281 172.41465985 202.6479464 153.3293457 181.7434082 C151.82622596 180.09128355 150.33923169 178.42434933 148.8684082 176.7434082 C143.63303823 170.7811591 138.12599689 165.41465121 132.08325195 160.2746582 C131.51751465 159.79125977 130.95177734 159.30786133 130.36889648 158.80981445 C94.75519251 128.56126737 48.98095846 105.38997381 2.27856445 99.59887695 C0.08325195 99.2746582 0.08325195 99.2746582 -1.91674805 98.2746582 C-15.44086231 96.32228344 -29.02835583 96.06070803 -42.66674805 96.0246582 C-43.82069565 96.01702957 -43.82069565 96.01702957 -44.99795532 96.00924683 C-59.7457176 95.93093387 -74.27430498 96.87030628 -88.6237793 100.48950195 C-93.73689751 101.70864402 -98.91162422 102.55083535 -104.0925293 103.4309082 C-107.56151278 104.19628147 -110.6011106 105.21696947 -113.88769531 106.51196289 C-117.269316 107.78307143 -120.75000326 108.68709249 -124.22924805 109.6496582 C-130.30789962 111.3774146 -135.96632622 113.44103147 -141.66674805 116.2043457 C-144.34618602 117.47893946 -147.07438595 118.42963163 -149.91674805 119.2746582 C-149.34869805 113.47663069 -148.22107294 108.28681653 -146.35424805 102.7746582 C-145.96160767 101.60942627 -145.96160767 101.60942627 -145.56103516 100.4206543 C-142.73179119 92.32041118 -139.00847008 84.80013691 -134.91674805 77.2746582 C-134.08530273 75.70458008 -134.08530273 75.70458008 -133.23706055 74.1027832 C-128.65110321 65.80856371 -122.93390267 58.55711322 -116.91674805 51.2746582 C-116.26319336 50.47672852 -115.60963867 49.67879883 -114.9362793 48.85668945 C-110.97590247 44.17130085 -106.65400365 40.1632198 -101.91674805 36.2746582 C-100.91901367 35.4393457 -99.9212793 34.6040332 -98.89331055 33.7434082 C-70.20437402 10.14837602 -36.79614021 -0.05376639 0 0 Z"
|
||||
fill="none" stroke="currentColor" stroke-width="2" transform="translate(152.916748046875,-0.274658203125)" />
|
||||
<path
|
||||
d="M0 0 C17.15700425 13.25398907 28.35288193 28.77836264 35.41015625 49.16015625 C36.06177734 50.98353516 36.06177734 50.98353516 36.7265625 52.84375 C43.66996482 75.70617229 40.45865786 101.91157533 29.48486328 122.93261719 C24.29969041 132.5798008 18.08253396 140.39334928 10.41015625 148.16015625 C9.84039062 148.80210937 9.270625 149.4440625 8.68359375 150.10546875 C-5.93673884 166.22532263 -29.62326077 175.04768946 -50.96240234 176.29931641 C-70.74714593 177.09921741 -88.54362556 173.60397865 -105.78515625 163.7109375 C-108.47111156 162.12408821 -108.47111156 162.12408821 -111.08203125 161.28515625 C-114.48750406 159.75746751 -116.92466766 157.39445523 -119.58984375 154.84765625 C-120.35167969 154.13706055 -120.35167969 154.13706055 -121.12890625 153.41210938 C-140.43009318 135.32343291 -140.43009318 135.32343291 -143.58984375 126.16015625 C-144.55809417 124.0925091 -145.53864911 122.03060584 -146.52734375 119.97265625 C-157.80156804 95.52185717 -159.05147691 69.16927104 -149.72900391 43.81933594 C-139.63216064 18.48145826 -120.47190027 -0.77581862 -95.58984375 -11.83984375 C-63.09642631 -24.46725509 -28.508196 -20.25242883 0 0 Z"
|
||||
fill="none" stroke="currentColor" stroke-width="2" transform="translate(170.58984375,278.83984375)" />
|
||||
</svg>
|
||||
<svg role="img" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><title>RSSHub</title><rect width="24" height="24" fill="#ffd6a6" rx="7.636"/><path fill="#ff8549" d="M.142 6.16Q.002 6.875 0 7.635v8.728A7.636 7.636 0 0 0 7.636 24h8.728a7.7 7.7 0 0 0 1.477-.142 13.26 13.26 0 0 0 1.25-5.64c0-7.35-5.959-13.309-13.31-13.309a13.25 13.25 0 0 0-5.64 1.25"/><circle cx="5.727" cy="18.273" r="4.964" fill="#ff2900"/></svg>
|
||||
|
Before Width: | Height: | Size: 9.8 KiB After Width: | Height: | Size: 420 B |
@@ -7,11 +7,13 @@ import { atom, useAtomValue } from "jotai"
|
||||
|
||||
export interface WebAISettings extends AISettings {
|
||||
panelStyle: AIChatPanelStyle
|
||||
showSplineButton: boolean
|
||||
}
|
||||
|
||||
export const createDefaultSettings = (): WebAISettings => ({
|
||||
...defaultAISettings,
|
||||
panelStyle: AIChatPanelStyle.Fixed,
|
||||
showSplineButton: true,
|
||||
})
|
||||
|
||||
export const {
|
||||
|
||||
@@ -79,9 +79,7 @@ export const useToggleZenMode = () => {
|
||||
const setZenMode = useSetZenMode()
|
||||
const isZenMode = useIsZenMode()
|
||||
return useEventCallback(() => {
|
||||
const newIsZenMode = !isZenMode
|
||||
document.documentElement.dataset.zenMode = newIsZenMode.toString()
|
||||
setZenMode(newIsZenMode)
|
||||
setZenMode(!isZenMode)
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -7,20 +7,20 @@ import { getIsZenMode, useIsZenMode } from "./settings/ui"
|
||||
const [
|
||||
,
|
||||
,
|
||||
internal_useTimelineColumnShow,
|
||||
internal_useSubscriptionColumnShow,
|
||||
,
|
||||
internal_getTimelineColumnShow,
|
||||
internal_getSubscriptionShow,
|
||||
setTimelineColumnShow,
|
||||
] = createAtomHooks(atom(true))
|
||||
|
||||
export const useTimelineColumnShow = () => {
|
||||
export const useSubscriptionColumnShow = () => {
|
||||
const isZenMode = useIsZenMode()
|
||||
return internal_useTimelineColumnShow() && !isZenMode
|
||||
return internal_useSubscriptionColumnShow() && !isZenMode
|
||||
}
|
||||
|
||||
export const getFeedColumnShow = () => {
|
||||
export const getSubscriptionColumnShow = () => {
|
||||
const isZenMode = getIsZenMode()
|
||||
return internal_getTimelineColumnShow() && !isZenMode
|
||||
return internal_getSubscriptionShow() && !isZenMode
|
||||
}
|
||||
|
||||
export { setTimelineColumnShow }
|
||||
@@ -28,8 +28,8 @@ export { setTimelineColumnShow }
|
||||
export const [
|
||||
,
|
||||
,
|
||||
useTimelineColumnTempShow,
|
||||
useSubscriptionColumnTempShow,
|
||||
,
|
||||
getTimelineColumnTempShow,
|
||||
setTimelineColumnTempShow,
|
||||
getSubscriptionColumnTempShow,
|
||||
setSubscriptionColumnTempShow,
|
||||
] = createAtomHooks(atom(false))
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
import type { FC } from "react"
|
||||
import { createElement } from "react"
|
||||
|
||||
import type { ErrorComponentType } from "../errors/enum"
|
||||
import { AppErrorBoundary } from "./AppErrorBoundary"
|
||||
|
||||
interface WithErrorBoundaryOptions {
|
||||
errorType: ErrorComponentType | ErrorComponentType[]
|
||||
height?: number | string
|
||||
}
|
||||
|
||||
/**
|
||||
* Higher-order component that wraps a component with AppErrorBoundary
|
||||
* @param Component - The component to wrap with ErrorBoundary
|
||||
* @param options - Configuration options for the ErrorBoundary wrapper
|
||||
* @returns A new component wrapped with ErrorBoundary
|
||||
*/
|
||||
export function withAppErrorBoundary<P extends object>(
|
||||
Component: FC<P>,
|
||||
options: WithErrorBoundaryOptions,
|
||||
): FC<P> {
|
||||
const { errorType, height } = options
|
||||
|
||||
const WrappedComponent = (props: P) => {
|
||||
return createElement(AppErrorBoundary, { errorType, height }, createElement(Component, props))
|
||||
}
|
||||
|
||||
WrappedComponent.displayName = `withErrorBoundary(${Component.displayName || Component.name || "Component"})`
|
||||
|
||||
return WrappedComponent as FC<P>
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
import { Logo } from "@follow/components/icons/logo.jsx"
|
||||
import { Button } from "@follow/components/ui/button/index.js"
|
||||
import type { FC } from "react"
|
||||
import { useNavigate } from "react-router"
|
||||
|
||||
import { CustomSafeError } from "../../errors/CustomSafeError"
|
||||
import type { AppErrorFallbackProps } from "../common/AppErrorBoundary"
|
||||
import { useResetErrorWhenRouteChange } from "./helper"
|
||||
|
||||
const EntryNotFoundErrorFallback: FC<AppErrorFallbackProps> = ({ resetError, error }) => {
|
||||
if (!(error instanceof EntryNotFound)) {
|
||||
throw error
|
||||
}
|
||||
|
||||
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="center m-auto flex max-w-prose flex-col gap-4 text-center">
|
||||
<div className="center mb-8 flex">
|
||||
<Logo className="size-20" />
|
||||
</div>
|
||||
<p className="font-semibold">
|
||||
The entry you're looking for could not be found. It may have been removed or the URL is
|
||||
incorrect.
|
||||
</p>
|
||||
|
||||
<div className="center mt-12 gap-4">
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => {
|
||||
navigate("/")
|
||||
setTimeout(() => {
|
||||
resetError()
|
||||
}, 100)
|
||||
}}
|
||||
>
|
||||
Back
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
export default EntryNotFoundErrorFallback
|
||||
|
||||
export class EntryNotFound extends CustomSafeError {
|
||||
constructor() {
|
||||
super("Entry 404")
|
||||
}
|
||||
}
|
||||
@@ -7,4 +7,5 @@ export enum ErrorComponentType {
|
||||
FeedNotFound = "FeedNotFound",
|
||||
// Section
|
||||
RSSHubDiscoverError = "RSSHubDiscoverError",
|
||||
EntryNotFound = "EntryNotFound",
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ const ErrorFallbackMap = {
|
||||
[ErrorComponentType.Page]: lazy(() => import("./PageError")),
|
||||
[ErrorComponentType.FeedNotFound]: lazy(() => import("./FeedNotFound")),
|
||||
[ErrorComponentType.RSSHubDiscoverError]: lazy(() => import("./RSSHubError")),
|
||||
[ErrorComponentType.EntryNotFound]: lazy(() => import("./EntryNotFound")),
|
||||
}
|
||||
|
||||
export const getErrorFallback = (type: ErrorComponentType) => ErrorFallbackMap[type]
|
||||
|
||||
@@ -0,0 +1,177 @@
|
||||
import { AutoResizeHeight } from "@follow/components/ui/auto-resize-height/index.js"
|
||||
import { MotionButtonBase } from "@follow/components/ui/button/index.js"
|
||||
import { cn } from "@follow/utils/utils"
|
||||
import type { ReactNode } from "react"
|
||||
import { useTranslation } from "react-i18next"
|
||||
|
||||
import { CopyButton } from "~/components/ui/button/CopyButton"
|
||||
import { Markdown } from "~/components/ui/markdown/Markdown"
|
||||
|
||||
interface AISummaryCardBaseProps {
|
||||
/** Summary content to display */
|
||||
content?: string | null
|
||||
/** Whether the summary is currently loading */
|
||||
isLoading?: boolean
|
||||
/** Additional className for the container */
|
||||
className?: string
|
||||
/** Custom header content (replaces default AI Summary header) */
|
||||
headerContent?: ReactNode
|
||||
/** Additional content to render below the summary */
|
||||
footerContent?: ReactNode
|
||||
/** Custom loading state component */
|
||||
loadingComponent?: ReactNode
|
||||
/** Custom empty state component */
|
||||
emptyComponent?: ReactNode
|
||||
/** Title text for the AI Summary header */
|
||||
title?: string
|
||||
/** Whether to show the copy button */
|
||||
showCopyButton?: boolean
|
||||
/** Whether to show the Ask AI button when there's content */
|
||||
showAskAIButton?: boolean
|
||||
/** Callback when Ask AI button is clicked */
|
||||
onAskAI?: () => void
|
||||
}
|
||||
|
||||
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>
|
||||
)
|
||||
|
||||
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>
|
||||
</div>
|
||||
)
|
||||
|
||||
export const AISummaryCardBase: React.FC<AISummaryCardBaseProps> = ({
|
||||
content,
|
||||
isLoading = false,
|
||||
className,
|
||||
headerContent,
|
||||
footerContent,
|
||||
loadingComponent,
|
||||
emptyComponent,
|
||||
title = "AI Summary",
|
||||
showCopyButton = true,
|
||||
showAskAIButton = false,
|
||||
onAskAI,
|
||||
}) => {
|
||||
const { t } = useTranslation("app")
|
||||
|
||||
const hasContent = !isLoading && content
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
"group relative 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",
|
||||
|
||||
isLoading &&
|
||||
"before:absolute before:inset-0 before:-z-10 before:animate-[pulse_2s_cubic-bezier(0.4,0,0.6,1)_infinite] before:bg-gradient-to-r before:from-purple-100/0 before:via-purple-300/10 before:to-purple-100/0 dark:before:from-purple-900/0 dark:before:via-purple-600/10 dark:before:to-purple-900/0",
|
||||
className,
|
||||
)}
|
||||
>
|
||||
{/* Animated background gradient */}
|
||||
<div
|
||||
className={cn(
|
||||
"absolute inset-0 -z-10 bg-gradient-to-br opacity-50",
|
||||
"from-purple-100/20 via-transparent to-blue-100/20",
|
||||
"dark:from-purple-900/20 dark:to-blue-900/20",
|
||||
isLoading && "animate-[glow_4s_ease-in-out_infinite]",
|
||||
)}
|
||||
/>
|
||||
|
||||
{/* Header */}
|
||||
<div className="flex items-center justify-between">
|
||||
{headerContent || (
|
||||
<div className="flex items-center gap-3">
|
||||
{/* Glowing AI icon */}
|
||||
<div className="center relative">
|
||||
<i
|
||||
className={cn(
|
||||
"i-mgc-ai-cute-re text-lg",
|
||||
isLoading
|
||||
? "text-purple-500/70 dark:text-purple-400/70"
|
||||
: "text-purple-600 dark:text-purple-400",
|
||||
)}
|
||||
/>
|
||||
<div
|
||||
className={cn(
|
||||
"absolute inset-0 rounded-full blur-sm",
|
||||
isLoading
|
||||
? "animate-[pulse_2s_infinite] bg-purple-400/30 dark:bg-purple-500/30"
|
||||
: "animate-pulse bg-purple-400/20 dark:bg-purple-500/20",
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
<span
|
||||
className={cn(
|
||||
"bg-gradient-to-r bg-clip-text font-medium text-transparent",
|
||||
isLoading
|
||||
? "from-purple-500/70 to-blue-500/70 dark:from-purple-400/70 dark:to-blue-400/70"
|
||||
: "from-purple-600 to-blue-600 dark:from-purple-400 dark:to-blue-400",
|
||||
)}
|
||||
>
|
||||
{title}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex items-center gap-2">
|
||||
{showAskAIButton && hasContent && onAskAI && (
|
||||
<MotionButtonBase
|
||||
onClick={onAskAI}
|
||||
className={cn(
|
||||
"flex h-7 items-center gap-1.5 rounded-lg px-3 text-sm font-medium",
|
||||
"bg-gradient-to-r from-purple-500/10 to-blue-500/10",
|
||||
"border border-purple-200/30 dark:border-purple-800/30",
|
||||
"text-purple-600 dark:text-purple-400",
|
||||
"hover:from-purple-500/20 hover:to-blue-500/20",
|
||||
"hover:border-purple-300/50 dark:hover:border-purple-700/50",
|
||||
"transition-all duration-200",
|
||||
"backdrop-blur-sm",
|
||||
"sm:opacity-0 sm:duration-300 sm:group-hover:translate-y-0 sm:group-hover:opacity-100",
|
||||
)}
|
||||
>
|
||||
<i className="i-mingcute-ai-line text-base" />
|
||||
<span>Ask AI</span>
|
||||
</MotionButtonBase>
|
||||
)}
|
||||
|
||||
{showCopyButton && hasContent && (
|
||||
<CopyButton
|
||||
value={content}
|
||||
variant="outline"
|
||||
className={cn(
|
||||
"!bg-white/10 !text-purple-600 dark:!text-purple-400",
|
||||
"hover:!bg-white/20 dark:hover:!bg-neutral-800/30",
|
||||
"!border-purple-200/30 dark:!border-purple-800/30",
|
||||
"sm:opacity-0 sm:duration-300 sm:group-hover:translate-y-0 sm:group-hover:opacity-100",
|
||||
"backdrop-blur-sm",
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Content */}
|
||||
<AutoResizeHeight className="mt-4 text-sm leading-relaxed text-neutral-700 dark:text-neutral-300">
|
||||
{isLoading ? (
|
||||
loadingComponent || <DefaultLoadingState />
|
||||
) : hasContent ? (
|
||||
<Markdown className="prose-sm prose-p:m-0 max-w-none">{String(content)}</Markdown>
|
||||
) : (
|
||||
emptyComponent || <DefaultEmptyState message={t("ai.summary_not_available")} />
|
||||
)}
|
||||
</AutoResizeHeight>
|
||||
|
||||
{/* Footer */}
|
||||
{footerContent}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
export { AISummaryCardBase } from "./AISummaryCardBase"
|
||||
@@ -12,7 +12,7 @@ import type { FC, ReactNode } from "react"
|
||||
|
||||
export interface GlassButtonProps {
|
||||
description?: string
|
||||
onClick: () => void
|
||||
onClick?: () => void
|
||||
className?: string
|
||||
children: ReactNode
|
||||
/**
|
||||
@@ -54,7 +54,7 @@ const glassButtonVariants = cva(
|
||||
},
|
||||
variant: {
|
||||
glass: ["backdrop-blur-md border shadow-lg"],
|
||||
flat: ["border shadow-none"],
|
||||
flat: ["border shadow-sm hover:shadow-md"],
|
||||
},
|
||||
},
|
||||
compoundVariants: [
|
||||
@@ -90,7 +90,12 @@ const glassButtonVariants = cva(
|
||||
{
|
||||
variant: "flat",
|
||||
theme: "light",
|
||||
className: ["bg-white/80 hover:bg-white/90", "border-gray/20 hover:border-gray/30"],
|
||||
className: [
|
||||
"bg-white/80 hover:bg-white/90",
|
||||
"border-gray/20 hover:border-gray/30",
|
||||
// Subtle shadow color for clearer hover feedback
|
||||
"shadow-gray/10 hover:shadow-gray/25",
|
||||
],
|
||||
},
|
||||
{
|
||||
variant: "flat",
|
||||
@@ -98,6 +103,7 @@ const glassButtonVariants = cva(
|
||||
className: [
|
||||
"bg-fill-secondary hover:bg-fill-tertiary",
|
||||
"border-gray/20 hover:border-gray/30",
|
||||
"shadow-black/10 hover:shadow-black/25",
|
||||
],
|
||||
},
|
||||
{
|
||||
@@ -106,6 +112,7 @@ const glassButtonVariants = cva(
|
||||
className: [
|
||||
"bg-white/80 hover:bg-white/90 dark:bg-fill-secondary dark:hover:bg-fill-tertiary",
|
||||
"border-gray/20 hover:border-gray/30",
|
||||
"shadow-gray/10 hover:shadow-gray/25 dark:shadow-black/10 dark:hover:shadow-black/25",
|
||||
],
|
||||
},
|
||||
],
|
||||
@@ -164,7 +171,7 @@ export const GlassButton: FC<GlassButtonProps> = ({
|
||||
type="button"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
onClick()
|
||||
onClick?.()
|
||||
}}
|
||||
className={cn(glassButtonVariants({ size, theme, variant }), className)}
|
||||
initial={{ scale: 1 }}
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import { Button } from "@follow/components/ui/button/index.js"
|
||||
import { MagneticHoverEffect } from "@follow/components/ui/effect/MagneticHoverEffect.js"
|
||||
import type { LinkProps } from "@follow/components/ui/link/LinkWithTooltip.js"
|
||||
import {
|
||||
Tooltip,
|
||||
@@ -49,10 +48,12 @@ export const MarkdownLink: Component<LinkProps> = (props) => {
|
||||
return (
|
||||
<Tooltip delayDuration={0}>
|
||||
<TooltipTrigger asChild>
|
||||
<MagneticHoverEffect
|
||||
as="a"
|
||||
<a
|
||||
draggable="false"
|
||||
className={cn("text-text font-semibold no-underline", props.className)}
|
||||
className={cn(
|
||||
"text-text follow-link--underline font-semibold no-underline",
|
||||
props.className,
|
||||
)}
|
||||
href={populatedFullHref}
|
||||
title={props.title}
|
||||
target="_blank"
|
||||
@@ -64,7 +65,7 @@ export const MarkdownLink: Component<LinkProps> = (props) => {
|
||||
{typeof props.children === "string" && (
|
||||
<i className="i-mgc-arrow-right-up-cute-re size-[0.9em] translate-y-[2px] opacity-70" />
|
||||
)}
|
||||
</MagneticHoverEffect>
|
||||
</a>
|
||||
</TooltipTrigger>
|
||||
{!!populatedFullHref && (
|
||||
<TooltipPortal>
|
||||
|
||||
@@ -23,6 +23,7 @@ type BaseProps = {
|
||||
blurhash?: string
|
||||
inline?: boolean
|
||||
fitContent?: boolean
|
||||
videoClassName?: string
|
||||
}
|
||||
|
||||
const isImageLoadedSet = new Set<string>()
|
||||
@@ -71,6 +72,7 @@ const MediaImpl: FC<MediaProps> = ({
|
||||
width,
|
||||
inline,
|
||||
fitContent,
|
||||
videoClassName,
|
||||
...rest
|
||||
} = props
|
||||
|
||||
@@ -287,7 +289,12 @@ const MediaImpl: FC<MediaProps> = ({
|
||||
)}
|
||||
onClick={handleClick}
|
||||
>
|
||||
<VideoPreview src={src!} previewImageUrl={previewImageSrc} thumbnail={thumbnail} />
|
||||
<VideoPreview
|
||||
src={src!}
|
||||
previewImageUrl={previewImageSrc}
|
||||
thumbnail={thumbnail}
|
||||
videoClassName={videoClassName}
|
||||
/>
|
||||
</span>
|
||||
)
|
||||
}
|
||||
@@ -487,7 +494,8 @@ const VideoPreview: FC<{
|
||||
src: string
|
||||
previewImageUrl?: string
|
||||
thumbnail?: boolean
|
||||
}> = ({ src, previewImageUrl, thumbnail = false }) => {
|
||||
videoClassName?: string
|
||||
}> = ({ src, previewImageUrl, thumbnail = false, videoClassName }) => {
|
||||
const [isInitVideoPlayer, setIsInitVideoPlayer] = useState(!previewImageUrl)
|
||||
|
||||
const [videoRef, setVideoRef] = useState<VideoPlayerRef | null>(null)
|
||||
@@ -507,7 +515,7 @@ const VideoPreview: FC<{
|
||||
{!isInitVideoPlayer ? (
|
||||
<img
|
||||
src={previewImageUrl}
|
||||
className="size-full object-cover"
|
||||
className={cn("size-full object-cover", videoClassName)}
|
||||
onMouseEnter={() => {
|
||||
setIsInitVideoPlayer(true)
|
||||
}}
|
||||
@@ -520,7 +528,7 @@ const VideoPreview: FC<{
|
||||
poster={previewImageUrl}
|
||||
ref={setVideoRef}
|
||||
muted
|
||||
className="not-prose relative size-full object-cover"
|
||||
className={cn("not-prose relative size-full object-cover", videoClassName)}
|
||||
/>
|
||||
)}
|
||||
|
||||
|
||||
@@ -149,6 +149,7 @@ const Wrapper: FC<{
|
||||
|
||||
return (
|
||||
<div ref={containerRef} className="fixed inset-0">
|
||||
<HeaderActions src={src} />
|
||||
<m.div
|
||||
variants={modalVariants}
|
||||
initial="initial"
|
||||
@@ -172,7 +173,6 @@ const Wrapper: FC<{
|
||||
hasSideContent ? "min-w-96 items-center justify-center" : "",
|
||||
)}
|
||||
>
|
||||
<HeaderActions src={src} />
|
||||
{isArray ? renderedChildren[0] : renderedChildren}
|
||||
</div>
|
||||
{hasSideContent ? (
|
||||
@@ -188,6 +188,11 @@ const Wrapper: FC<{
|
||||
)
|
||||
}
|
||||
|
||||
const headerActionsVariants = {
|
||||
initial: { opacity: 0, translateY: "-20px" },
|
||||
animate: { opacity: 1, translateY: "0px" },
|
||||
exit: { opacity: 0, translateY: "-20px" },
|
||||
}
|
||||
const GLASS_BUTTON_CLASS = tw`group-hover/left:opacity-100 opacity-0`
|
||||
const HeaderActions: FC<{
|
||||
src: string
|
||||
@@ -196,7 +201,14 @@ const HeaderActions: FC<{
|
||||
|
||||
const { dismiss } = useCurrentModal()
|
||||
return (
|
||||
<div className="pointer-events-none absolute inset-x-0 top-0 z-[100] flex h-16 items-center justify-end gap-2 px-3">
|
||||
<m.div
|
||||
className="pointer-events-none absolute inset-x-0 top-0 z-[100] flex h-16 items-center justify-end gap-2 px-3"
|
||||
variants={headerActionsVariants}
|
||||
initial="initial"
|
||||
animate="animate"
|
||||
exit="exit"
|
||||
transition={Spring.presets.smooth}
|
||||
>
|
||||
<GlassButton
|
||||
theme="dark"
|
||||
className={GLASS_BUTTON_CLASS}
|
||||
@@ -229,7 +241,7 @@ const HeaderActions: FC<{
|
||||
>
|
||||
<i className="i-mgc-close-cute-re" />
|
||||
</GlassButton>
|
||||
</div>
|
||||
</m.div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -557,12 +569,8 @@ const DOMImageViewer: FC<{
|
||||
smooth={true}
|
||||
onInit={(e) => {
|
||||
if (e.instance.wrapperComponent) {
|
||||
e.instance.wrapperComponent.onclick = (e) => {
|
||||
if (e.target instanceof HTMLDivElement && e.target.dataset.imageContainer) {
|
||||
e.stopPropagation()
|
||||
} else {
|
||||
dismiss()
|
||||
}
|
||||
e.instance.wrapperComponent.onclick = () => {
|
||||
dismiss()
|
||||
}
|
||||
}
|
||||
}}
|
||||
@@ -581,7 +589,7 @@ const DOMImageViewer: FC<{
|
||||
wrapperProps={{
|
||||
onClick: stopPropagation,
|
||||
}}
|
||||
wrapperClass="!w-full !h-full !absolute !inset-0"
|
||||
wrapperClass="!w-full !h-full !absolute !inset-0 cursor-zoom-out"
|
||||
contentClass="!w-full !h-full flex items-center justify-center"
|
||||
>
|
||||
<div
|
||||
|
||||
@@ -71,8 +71,8 @@ export const VideoPlayer = ({
|
||||
const isPlayer = variant === "player"
|
||||
const [clickToStatus, setClickToStatus] = useState(null as "play" | "pause" | null)
|
||||
|
||||
const scaleValue = useSpring(1, Spring.presets.softSpring)
|
||||
const opacityValue = useSpring(0, Spring.presets.softSpring)
|
||||
const scaleValue = useSpring(1, Spring.presets.smooth)
|
||||
const opacityValue = useSpring(0, Spring.presets.smooth)
|
||||
const handleClick = useEventCallback((e?: any) => {
|
||||
if (!isPlayer) return
|
||||
e?.stopPropagation()
|
||||
|
||||
@@ -42,6 +42,7 @@ export const useAsyncModal = () => {
|
||||
|
||||
const LazyContent = () => {
|
||||
const ctx = use(AsyncModalContext)
|
||||
|
||||
const queryResult = ctx.useDataFetcher()
|
||||
|
||||
return (
|
||||
|
||||
@@ -1,10 +1,14 @@
|
||||
import { createEventBus } from "@follow/utils/event-bus"
|
||||
|
||||
export const ModalEventBus = createEventBus<{
|
||||
MODAL_DISPATCH: ModalDisposeEvent
|
||||
DISMISS: ModalDisposeEvent
|
||||
RE_PRESENT: ModalRePresentEvent
|
||||
}>()
|
||||
|
||||
export type ModalDisposeEvent = {
|
||||
type: "dismiss"
|
||||
id: string
|
||||
}
|
||||
|
||||
export type ModalRePresentEvent = {
|
||||
id: string
|
||||
}
|
||||
|
||||
@@ -2,12 +2,15 @@ import { Spring } from "@follow/components/constants/spring.js"
|
||||
import type { MotionProps, TargetAndTransition } from "motion/react"
|
||||
|
||||
const enterStyle: TargetAndTransition = {
|
||||
scale: 1,
|
||||
opacity: 1,
|
||||
// Draw the modal towards the viewer from depth
|
||||
transformPerspective: 1200,
|
||||
z: 0,
|
||||
}
|
||||
const initialStyle: TargetAndTransition = {
|
||||
scale: 0.96,
|
||||
opacity: 0,
|
||||
transformPerspective: 1200,
|
||||
z: -48,
|
||||
}
|
||||
|
||||
export const modalMontionConfig = {
|
||||
@@ -15,12 +18,9 @@ export const modalMontionConfig = {
|
||||
animate: enterStyle,
|
||||
exit: {
|
||||
...initialStyle,
|
||||
// no spring
|
||||
transition: {
|
||||
type: "tween",
|
||||
},
|
||||
transition: Spring.presets.smooth,
|
||||
},
|
||||
transition: Spring.presets.microRebound,
|
||||
transition: Spring.presets.snappy,
|
||||
} satisfies MotionProps
|
||||
|
||||
// Radix context menu z-index 999
|
||||
|
||||
@@ -2,7 +2,7 @@ import { Button } from "@follow/components/ui/button/index.js"
|
||||
import { atom, useAtomValue } from "jotai"
|
||||
import type { DragControls } from "motion/react"
|
||||
import type { ResizeCallback, ResizeStartCallback } from "re-resizable"
|
||||
import { use, useState } from "react"
|
||||
import { use, useDeferredValue, useState } from "react"
|
||||
import { flushSync } from "react-dom"
|
||||
import { useTranslation } from "react-i18next"
|
||||
import { useContextSelector } from "use-context-selector"
|
||||
@@ -36,8 +36,7 @@ const actions = {
|
||||
return jotaiStore.get(modalStackAtom).find((item) => item.id === id)
|
||||
},
|
||||
dismiss(id: string) {
|
||||
ModalEventBus.dispatch("MODAL_DISPATCH", {
|
||||
type: "dismiss",
|
||||
ModalEventBus.dispatch("DISMISS", {
|
||||
id,
|
||||
})
|
||||
},
|
||||
@@ -166,7 +165,7 @@ export const useDialog = (): DialogInstance => {
|
||||
</div>
|
||||
),
|
||||
content: ({ dismiss }) => (
|
||||
<div className="flex max-w-prose flex-col gap-3">
|
||||
<div className="flex max-w-[45ch] flex-col gap-3">
|
||||
<div className="whitespace-pre text-wrap">{options.message}</div>
|
||||
|
||||
<div className="flex items-center justify-end gap-3">
|
||||
@@ -203,4 +202,9 @@ export const useDialog = (): DialogInstance => {
|
||||
}
|
||||
|
||||
const modalStackLengthAtom = atom((get) => get(modalStackAtom).length)
|
||||
export const useHasModal = () => useAtomValue(modalStackLengthAtom) > 0
|
||||
export const useHasModal = () => {
|
||||
// The keydown event of modal exit is triggered in the same loop,
|
||||
// leading to unexpected simultaneous responses to other hotkeys,
|
||||
// so deferredValue is added to delay the update
|
||||
return useDeferredValue(useAtomValue(modalStackLengthAtom) > 0)
|
||||
}
|
||||
|
||||
+46
-14
@@ -1,59 +1,91 @@
|
||||
import { Spring } from "@follow/components/constants/spring.js"
|
||||
import { nextFrame } from "@follow/utils/dom"
|
||||
import { useAnimationControls } from "motion/react"
|
||||
import { useCallback, useEffect, useLayoutEffect } from "react"
|
||||
import { useCallback, useEffect, useLayoutEffect, useState } from "react"
|
||||
import { useEventCallback } from "usehooks-ts"
|
||||
|
||||
import { ModalEventBus } from "../bus"
|
||||
import { modalMontionConfig } from "../constants"
|
||||
|
||||
export interface ModalAnimateControls {
|
||||
animateController: ReturnType<typeof useAnimationControls>
|
||||
playNoticeAnimation: () => void
|
||||
playExitAnimation: () => Promise<void>
|
||||
isClosing: boolean
|
||||
readyToClose: () => void
|
||||
}
|
||||
|
||||
/**
|
||||
* @internal
|
||||
* Hook for managing modal animations including enter, notice, and exit animations
|
||||
*/
|
||||
export const useModalAnimate = (isTop: boolean) => {
|
||||
export const useModalAnimate = (isTop: boolean, modalId: string): ModalAnimateControls => {
|
||||
const animateController = useAnimationControls()
|
||||
|
||||
const [isClosing, setIsClosing] = useState(false)
|
||||
// Initial enter animation
|
||||
useEffect(() => {
|
||||
ModalEventBus.subscribe("RE_PRESENT", (data) => {
|
||||
if (data.id !== modalId) {
|
||||
return
|
||||
}
|
||||
setIsClosing(false)
|
||||
animateController.start(modalMontionConfig.animate)
|
||||
})
|
||||
nextFrame(() => {
|
||||
animateController.start(modalMontionConfig.animate)
|
||||
})
|
||||
}, [animateController])
|
||||
const noticeModal = useCallback(() => {
|
||||
}, [animateController, modalId, setIsClosing])
|
||||
|
||||
// Notice animation for when modal can't be dismissed
|
||||
const playNoticeAnimation = useCallback(() => {
|
||||
animateController
|
||||
.start({
|
||||
scale: 1.01,
|
||||
z: 6,
|
||||
transition: Spring.snappy(0.06),
|
||||
})
|
||||
.then(() => {
|
||||
animateController.start({
|
||||
scale: 1,
|
||||
z: 0,
|
||||
})
|
||||
})
|
||||
}, [animateController])
|
||||
|
||||
// Stack position animation
|
||||
useLayoutEffect(() => {
|
||||
if (isTop) return
|
||||
animateController.start({
|
||||
scale: 0.96,
|
||||
y: 10,
|
||||
z: -64,
|
||||
rotateX: 2.5,
|
||||
y: 8,
|
||||
})
|
||||
return () => {
|
||||
try {
|
||||
animateController.stop()
|
||||
animateController.start({
|
||||
scale: 1,
|
||||
z: 0,
|
||||
rotateX: 0,
|
||||
y: 0,
|
||||
})
|
||||
} catch {
|
||||
/* empty */
|
||||
}
|
||||
}
|
||||
}, [isTop])
|
||||
}, [isTop, animateController])
|
||||
|
||||
// Exit animation
|
||||
const playExitAnimation = useEventCallback(async () => {
|
||||
await animateController.start(modalMontionConfig.exit)
|
||||
})
|
||||
|
||||
return {
|
||||
noticeModal,
|
||||
animateController,
|
||||
dismissing: useEventCallback(async () => {
|
||||
await animateController.start(modalMontionConfig.exit)
|
||||
playNoticeAnimation,
|
||||
playExitAnimation,
|
||||
isClosing,
|
||||
readyToClose: useEventCallback(() => {
|
||||
if (isClosing) return // Prevent multiple calls
|
||||
|
||||
setIsClosing(true)
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
+1
-1
@@ -6,7 +6,7 @@ import type { ModalActionsInternal } from "../context"
|
||||
/** @internal */
|
||||
export const useModalSubscriber = (id: string, ctx: ModalActionsInternal) => {
|
||||
useEffect(() => {
|
||||
return ModalEventBus.subscribe("MODAL_DISPATCH", (data) => {
|
||||
return ModalEventBus.subscribe("DISMISS", (data) => {
|
||||
if (data.id === id) {
|
||||
ctx.dismiss()
|
||||
}
|
||||
|
||||
@@ -89,20 +89,29 @@ export const ModalInternal = memo(function Modal({
|
||||
|
||||
const setStack = useSetAtom(modalStackAtom)
|
||||
|
||||
const [currentIsClosing, setCurrentIsClosing] = useState(false)
|
||||
const { noticeModal, animateController, dismissing } = useModalAnimate(!!isTop)
|
||||
// Animation controls
|
||||
const { animateController, playNoticeAnimation, playExitAnimation, isClosing, readyToClose } =
|
||||
useModalAnimate(!!isTop, item.id)
|
||||
|
||||
const close = useEventCallback((forceClose = false) => {
|
||||
// Simple dismiss logic
|
||||
const close = useEventCallback(async (forceClose = false) => {
|
||||
if (!canClose && !forceClose) return
|
||||
setCurrentIsClosing(true)
|
||||
|
||||
if (!CustomModalComponent) {
|
||||
dismissing().then(() => {
|
||||
readyToClose()
|
||||
try {
|
||||
if (CustomModalComponent) {
|
||||
// Custom modals handle their own animation
|
||||
setStack((p) => p.filter((modal) => modal.id !== item.id))
|
||||
})
|
||||
} else {
|
||||
} else {
|
||||
// Play exit animation then remove from stack\
|
||||
await playExitAnimation()
|
||||
setStack((p) => p.filter((modal) => modal.id !== item.id))
|
||||
}
|
||||
} catch (error) {
|
||||
// If animation fails, still remove from stack
|
||||
console.warn("Modal animation failed:", error)
|
||||
setStack((p) => p.filter((modal) => modal.id !== item.id))
|
||||
}
|
||||
|
||||
onPropsClose?.(false)
|
||||
})
|
||||
|
||||
@@ -120,7 +129,6 @@ export const ModalInternal = memo(function Modal({
|
||||
const dismiss = useCallback(
|
||||
(e: SyntheticEvent) => {
|
||||
e.stopPropagation()
|
||||
|
||||
close(true)
|
||||
},
|
||||
[close],
|
||||
@@ -186,11 +194,11 @@ export const ModalInternal = memo(function Modal({
|
||||
)
|
||||
|
||||
useEffect(() => {
|
||||
if (currentIsClosing) {
|
||||
if (isClosing) {
|
||||
// Radix dialog will block pointer events
|
||||
document.body.style.pointerEvents = "auto"
|
||||
}
|
||||
}, [currentIsClosing])
|
||||
}, [isClosing])
|
||||
|
||||
const modalStyle = resizeableStyle
|
||||
const { handleSelectStart, handleDetectSelectEnd, isSelectingRef } = useModalSelect()
|
||||
@@ -198,10 +206,13 @@ export const ModalInternal = memo(function Modal({
|
||||
(e: SyntheticEvent) => {
|
||||
if (isSelectingRef.current) return
|
||||
|
||||
const fn = modal ? (clickOutsideToDismiss && canClose ? dismiss : noticeModal) : undefined
|
||||
fn?.(e)
|
||||
if (modal && clickOutsideToDismiss && canClose) {
|
||||
dismiss(e)
|
||||
} else if (modal) {
|
||||
playNoticeAnimation()
|
||||
}
|
||||
},
|
||||
[canClose, clickOutsideToDismiss, dismiss, modal, noticeModal, isSelectingRef],
|
||||
[canClose, clickOutsideToDismiss, dismiss, modal, playNoticeAnimation, isSelectingRef],
|
||||
)
|
||||
|
||||
const openAutoFocus = useCallback(
|
||||
@@ -230,9 +241,7 @@ export const ModalInternal = memo(function Modal({
|
||||
<ModalOverlay
|
||||
zIndex={currentModalZIndex - 1}
|
||||
blur={overlayOptions?.blur}
|
||||
hidden={
|
||||
item.overlay ? currentIsClosing : !(modalSettingOverlay && isBottom) || currentIsClosing
|
||||
}
|
||||
hidden={item.overlay ? isClosing : !(modalSettingOverlay && isBottom) || isClosing}
|
||||
/>
|
||||
)
|
||||
|
||||
@@ -258,7 +267,7 @@ export const ModalInternal = memo(function Modal({
|
||||
className={cn(
|
||||
"no-drag-region fixed",
|
||||
modal ? "inset-0 overflow-auto" : "left-0 top-0",
|
||||
currentIsClosing ? "!pointer-events-none" : "!pointer-events-auto",
|
||||
isClosing ? "!pointer-events-none" : "!pointer-events-auto",
|
||||
modalContainerClassName,
|
||||
)}
|
||||
style={{
|
||||
@@ -311,7 +320,7 @@ export const ModalInternal = memo(function Modal({
|
||||
className={cn(
|
||||
"fixed flex",
|
||||
modal ? "inset-0 overflow-auto" : "left-0 top-0",
|
||||
currentIsClosing && "!pointer-events-none",
|
||||
isClosing && "!pointer-events-none",
|
||||
modalContainerClassName,
|
||||
!isResizeable && "center",
|
||||
)}
|
||||
@@ -320,6 +329,7 @@ export const ModalInternal = memo(function Modal({
|
||||
onClick={handleClickOutsideToDismiss}
|
||||
style={{
|
||||
zIndex: currentModalZIndex,
|
||||
perspective: 1200,
|
||||
}}
|
||||
tabIndex={-1}
|
||||
>
|
||||
@@ -327,7 +337,7 @@ export const ModalInternal = memo(function Modal({
|
||||
|
||||
<m.div
|
||||
ref={modalElementRef}
|
||||
style={modalStyle}
|
||||
style={{ ...modalStyle, transformStyle: "preserve-3d" }}
|
||||
{...modalMontionConfig}
|
||||
animate={animateController}
|
||||
className={cn(
|
||||
@@ -382,11 +392,13 @@ export const ModalInternal = memo(function Modal({
|
||||
</Dialog.DialogClose>
|
||||
)}
|
||||
</div>
|
||||
<div className="bg-border mx-1 mt-2 h-px shrink-0" />
|
||||
{(title || icon || canClose) && (
|
||||
<div className="bg-border mx-1 mt-2 h-px shrink-0" />
|
||||
)}
|
||||
|
||||
<div
|
||||
className={cn(
|
||||
"-mx-2 min-h-0 shrink grow overflow-auto p-4",
|
||||
"-mx-2 min-h-0 shrink grow overflow-auto overflow-x-hidden p-4",
|
||||
modalContentClassName,
|
||||
)}
|
||||
>
|
||||
|
||||
@@ -7,6 +7,7 @@ import { getUISettings } from "~/atoms/settings/ui"
|
||||
import { jotaiStore } from "~/lib/jotai"
|
||||
|
||||
import { modalStackAtom } from "./atom"
|
||||
import { ModalEventBus } from "./bus"
|
||||
import { PresentModalContextInternal } from "./context"
|
||||
import { modalIdToPropsMap } from "./hooks"
|
||||
import { ModalStack } from "./modal-stack"
|
||||
@@ -35,6 +36,7 @@ export const ModalStackProvider: FC<PropsWithChildren> = ({ children }) => {
|
||||
const index = p.indexOf(existingModal)
|
||||
return [...p.slice(0, index), ...p.slice(index + 1), existingModal]
|
||||
})
|
||||
ModalEventBus.dispatch("RE_PRESENT", { id: modalId })
|
||||
} else {
|
||||
// NOTE: The props of the Command Modal are immutable, so we'll just take the store value and inject it.
|
||||
// There is no need to inject `overlay` props, this is rendered responsively based on ui changes.
|
||||
|
||||
@@ -49,7 +49,7 @@ export const EntryMoreActions: FC<{ entryId: string }> = ({ entryId }) => {
|
||||
return (
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<i className="i-mgc-more-1-cute-re" />
|
||||
<i className="i-mingcute-more-1-fill" />
|
||||
</DropdownMenuTrigger>
|
||||
<RootPortal>
|
||||
<DropdownMenuContent alignOffset={20} sideOffset={30}>
|
||||
|
||||
@@ -228,7 +228,7 @@ export const useEntryActions = ({
|
||||
compact?: boolean
|
||||
}) => {
|
||||
const entry = useEntry(entryId, entrySelector)
|
||||
const { isCollection } = useRouteParams()
|
||||
const { isCollection, entryId: routeEntryId } = useRouteParams()
|
||||
const isInCollection = useIsEntryStarred(entryId)
|
||||
const isEntryInReadability = useEntryIsInReadability(entryId)
|
||||
|
||||
@@ -256,6 +256,8 @@ export const useEntryActions = ({
|
||||
|
||||
const shortcuts = useCommandShortcuts()
|
||||
|
||||
const isCurrentVisitEntry = routeEntryId === entryId
|
||||
|
||||
const actionConfigs: EntryActionItem[] = useMemo(() => {
|
||||
if (!hasEntry) return []
|
||||
|
||||
@@ -338,6 +340,7 @@ export const useEntryActions = ({
|
||||
}),
|
||||
new EntryActionMenuItem({
|
||||
id: COMMAND_ID.entry.exportAsPDF,
|
||||
hide: !isCurrentVisitEntry,
|
||||
onClick: runCmdFn(COMMAND_ID.entry.exportAsPDF, [{ entryId }]),
|
||||
entryId,
|
||||
}),
|
||||
@@ -432,7 +435,11 @@ export const useEntryActions = ({
|
||||
new EntryActionMenuItem({
|
||||
id: COMMAND_ID.entry.readability,
|
||||
onClick: runCmdFn(COMMAND_ID.entry.readability, [{ entryId, entryUrl: entry.url! }]),
|
||||
hide: !!entry.readability || compact || (view && views[view]!.wideMode) || !entry.url,
|
||||
hide:
|
||||
!!entry.readability ||
|
||||
compact ||
|
||||
(view && views.find((v) => v.view === view)?.wideMode) ||
|
||||
!entry.url,
|
||||
active: isEntryInReadability,
|
||||
notice: !entry.doesContentContainsHTMLTags && !isEntryInReadability,
|
||||
entryId,
|
||||
@@ -493,6 +500,7 @@ export const useEntryActions = ({
|
||||
shortcuts,
|
||||
view,
|
||||
isInCollection,
|
||||
isCurrentVisitEntry,
|
||||
isShowSourceContent,
|
||||
isShowAISummaryAuto,
|
||||
isShowAISummaryOnce,
|
||||
@@ -502,7 +510,6 @@ export const useEntryActions = ({
|
||||
isCollection,
|
||||
compact,
|
||||
isEntryInReadability,
|
||||
|
||||
integrationSettings.customIntegration,
|
||||
integrationSettings.enableCustomIntegration,
|
||||
])
|
||||
|
||||
@@ -62,7 +62,7 @@ const parseNavigateEntryOptions = (options: NavigateEntryOptions): ParsedNavigat
|
||||
let finalTimelineId = timelineId || params.timelineId || ROUTE_FEED_PENDING
|
||||
const finalEntryId = entryId || ROUTE_ENTRY_PENDING
|
||||
const subscription = getSubscriptionByFeedId(finalFeedId)
|
||||
const finalView = subscription?.view || view
|
||||
const finalView = view || subscription?.view
|
||||
|
||||
if ("feedId" in options && feedId === null) {
|
||||
finalFeedId = ROUTE_FEED_PENDING
|
||||
|
||||
@@ -1,10 +1,22 @@
|
||||
import { FeedViewType } from "@follow/constants"
|
||||
import { useViewWithSubscription } from "@follow/store/subscription/hooks"
|
||||
import { useMemo } from "react"
|
||||
|
||||
import { useFeature } from "~/hooks/biz/useFeature"
|
||||
|
||||
export const useTimelineList = () => {
|
||||
const views = useViewWithSubscription()
|
||||
|
||||
const viewsIds = useMemo(() => views.map((view) => `view-${view}`), [views])
|
||||
// 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 filteredViews = useMemo(
|
||||
() => (aiEnabled ? views : views.filter((v) => v !== FeedViewType.All)),
|
||||
[views, aiEnabled],
|
||||
)
|
||||
|
||||
const viewsIds = useMemo(() => filteredViews.map((view) => `view-${view}`), [filteredViews])
|
||||
|
||||
return viewsIds
|
||||
}
|
||||
|
||||
@@ -1,12 +1,5 @@
|
||||
import type {
|
||||
InfiniteData,
|
||||
QueryKey,
|
||||
UseInfiniteQueryOptions,
|
||||
UseInfiniteQueryResult,
|
||||
UseQueryOptions,
|
||||
UseQueryResult,
|
||||
} from "@tanstack/react-query"
|
||||
import { useInfiniteQuery, useQuery } from "@tanstack/react-query"
|
||||
import type { QueryKey, UseQueryOptions, UseQueryResult } from "@tanstack/react-query"
|
||||
import { useQuery } from "@tanstack/react-query"
|
||||
import type { FetchError } from "ofetch"
|
||||
|
||||
import { useLoginModalShow } from "~/atoms/user"
|
||||
@@ -41,33 +34,3 @@ export function useAuthQuery<
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
export function useAuthInfiniteQuery<
|
||||
T extends DefinedQuery<any, any>,
|
||||
E = FetchError,
|
||||
FNR = Awaited<ReturnType<T["fn"]>>,
|
||||
R = FNR,
|
||||
>(
|
||||
query: T,
|
||||
options: Omit<UseInfiniteQueryOptions<FNR, E>, "queryKey" | "queryFn">,
|
||||
): CombinedObject<
|
||||
UseInfiniteQueryResult<InfiniteData<R>, FetchError>,
|
||||
{ key: T["key"]; fn: T["fn"] }
|
||||
> {
|
||||
const authFail = useLoginModalShow()
|
||||
// @ts-expect-error
|
||||
return Object.assign(
|
||||
{},
|
||||
// @ts-expect-error
|
||||
useInfiniteQuery<T, E>({
|
||||
queryFn: query.fn,
|
||||
queryKey: query.key,
|
||||
enabled: !authFail && options.enabled !== false,
|
||||
...options,
|
||||
}),
|
||||
{
|
||||
key: query.key,
|
||||
fn: query.fn,
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ import { callWindowExposeRenderer } from "@follow/shared/bridge"
|
||||
interface ShortcutDefinition {
|
||||
accelerator: string
|
||||
action: () => void
|
||||
inputBypass?: boolean
|
||||
}
|
||||
|
||||
const parseAccelerator = (
|
||||
@@ -23,6 +24,7 @@ export const registerAppGlobalShortcuts = () => {
|
||||
{
|
||||
accelerator: "CmdOrCtrl+,",
|
||||
action: () => window.router.showSettings(),
|
||||
inputBypass: true,
|
||||
},
|
||||
{
|
||||
accelerator: "CmdOrCtrl+T",
|
||||
@@ -41,15 +43,16 @@ export const registerAppGlobalShortcuts = () => {
|
||||
]
|
||||
|
||||
const handleKeydown = (e: KeyboardEvent) => {
|
||||
// Prevent on input, textarea, [contenteditable]
|
||||
if (
|
||||
["INPUT", "TEXTAREA"].includes((e.target as HTMLElement)?.tagName) ||
|
||||
(e.target as HTMLElement)?.contentEditable === "true"
|
||||
) {
|
||||
return
|
||||
}
|
||||
shortcuts.forEach(({ accelerator, action, inputBypass }) => {
|
||||
// Prevent on input, textarea, [contenteditable]
|
||||
if (
|
||||
!inputBypass &&
|
||||
(["INPUT", "TEXTAREA"].includes((e.target as HTMLElement)?.tagName) ||
|
||||
(e.target as HTMLElement)?.contentEditable === "true")
|
||||
) {
|
||||
return
|
||||
}
|
||||
|
||||
shortcuts.forEach(({ accelerator, action }) => {
|
||||
const { key, ctrl, meta, shift } = parseAccelerator(accelerator)
|
||||
|
||||
const matchesKey = e.key.toLowerCase() === key.toLowerCase()
|
||||
|
||||
@@ -1,8 +1,14 @@
|
||||
import { env } from "@follow/shared/env.desktop"
|
||||
import type { BrowserOptions } from "@sentry/react"
|
||||
import { FetchError } from "ofetch"
|
||||
|
||||
import { CustomSafeError } from "../errors/CustomSafeError"
|
||||
import {
|
||||
captureConsoleIntegration,
|
||||
eventFiltersIntegration,
|
||||
httpClientIntegration,
|
||||
moduleMetadataIntegration,
|
||||
reactRouterV6BrowserTracingIntegration,
|
||||
} from "@sentry/react"
|
||||
import { useEffect } from "react"
|
||||
import { createRoutesFromChildren, matchRoutes, useLocation, useNavigationType } from "react-router"
|
||||
|
||||
const ERROR_PATTERNS = [
|
||||
/Network Error/i,
|
||||
@@ -10,17 +16,50 @@ const ERROR_PATTERNS = [
|
||||
/XHR Error/i,
|
||||
/adsbygoogle/i,
|
||||
/Failed to fetch/i,
|
||||
"FetchError",
|
||||
"FollowAuthError",
|
||||
"fetch failed",
|
||||
"Unable to open cursor",
|
||||
"Document is not focused.",
|
||||
"Tracker",
|
||||
"HTTP Client Error",
|
||||
// Biz errors
|
||||
"Chain aborted",
|
||||
"The database connection is closing",
|
||||
"NotSupportedError",
|
||||
"Request failed",
|
||||
"The user rejected the request",
|
||||
"TypeError: Failed to fetch",
|
||||
"ResizeObserver loop completed with undelivered notifications",
|
||||
"ResizeObserver loop limit exceeded",
|
||||
"A mutation operation was attempted on a database that did not allow mutations",
|
||||
"401",
|
||||
"HTTP Client Error with status code: ",
|
||||
"DatabaseClosedError",
|
||||
"SecurityError",
|
||||
"NotFoundError",
|
||||
"Large Render Blocking Asset",
|
||||
]
|
||||
|
||||
export const SentryConfig: BrowserOptions = {
|
||||
dsn: env.VITE_SENTRY_DSN,
|
||||
environment: RELEASE_CHANNEL,
|
||||
integrations: [
|
||||
eventFiltersIntegration(),
|
||||
moduleMetadataIntegration(),
|
||||
httpClientIntegration(),
|
||||
reactRouterV6BrowserTracingIntegration({
|
||||
useEffect,
|
||||
useLocation,
|
||||
useNavigationType,
|
||||
createRoutesFromChildren,
|
||||
matchRoutes,
|
||||
}),
|
||||
captureConsoleIntegration({
|
||||
levels: ["error"],
|
||||
}),
|
||||
],
|
||||
ignoreErrors: ERROR_PATTERNS,
|
||||
// Performance Monitoring
|
||||
tracesSampleRate: 1, // Capture 100% of the transactions
|
||||
// Set 'tracePropagationTargets' to control for which URLs distributed tracing should be enabled
|
||||
@@ -31,26 +70,6 @@ export const SentryConfig: BrowserOptions = {
|
||||
|
||||
beforeSend(event, hint) {
|
||||
const error = hint.originalException
|
||||
const errorMessage = error instanceof Error ? error.message : String(error)
|
||||
const isIgnoredError = ERROR_PATTERNS.some((pattern) =>
|
||||
pattern instanceof RegExp ? pattern.test(errorMessage) : errorMessage.includes(pattern),
|
||||
)
|
||||
|
||||
if (isIgnoredError) {
|
||||
return null
|
||||
}
|
||||
|
||||
const isPassthroughError = [CustomSafeError, FetchError].some((errorType) => {
|
||||
if (error instanceof errorType) {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
})
|
||||
const isAbortError = error instanceof Error && error.name === "AbortError"
|
||||
|
||||
if (isPassthroughError || isAbortError) {
|
||||
return null
|
||||
}
|
||||
|
||||
if (error instanceof Error && "traceId" in error && error.traceId) {
|
||||
event.tags = {
|
||||
|
||||
@@ -1,11 +1,8 @@
|
||||
import { ELECTRON_BUILD } from "@follow/shared/constants"
|
||||
import { env } from "@follow/shared/env.desktop"
|
||||
import { whoami } from "@follow/store/user/getters"
|
||||
import { appSessionTraceId } from "@follow/utils/environment"
|
||||
import { version } from "@pkg"
|
||||
import { nanoid } from "nanoid"
|
||||
import { useEffect } from "react"
|
||||
import { createRoutesFromChildren, matchRoutes, useLocation, useNavigationType } from "react-router"
|
||||
|
||||
import { SentryConfig } from "./sentry.config"
|
||||
|
||||
@@ -21,25 +18,7 @@ export const initSentry = async () => {
|
||||
if (!window.SENTRY_RELEASE) return
|
||||
if (import.meta.env.DEV) return
|
||||
const Sentry = await import("@sentry/react")
|
||||
Sentry.init({
|
||||
dsn: env.VITE_SENTRY_DSN,
|
||||
environment: RELEASE_CHANNEL,
|
||||
integrations: [
|
||||
Sentry.moduleMetadataIntegration(),
|
||||
Sentry.httpClientIntegration(),
|
||||
Sentry.reactRouterV6BrowserTracingIntegration({
|
||||
useEffect,
|
||||
useLocation,
|
||||
useNavigationType,
|
||||
createRoutesFromChildren,
|
||||
matchRoutes,
|
||||
}),
|
||||
Sentry.captureConsoleIntegration({
|
||||
levels: ["error"],
|
||||
}),
|
||||
],
|
||||
...SentryConfig,
|
||||
})
|
||||
Sentry.init(SentryConfig)
|
||||
|
||||
const user = whoami()
|
||||
if (user) {
|
||||
|
||||
@@ -1,25 +1,7 @@
|
||||
import type { IpcServices } from "@follow/electron-main"
|
||||
import type { IpcRenderer } from "electron"
|
||||
import { createIpcProxy } from "electron-ipc-decorator/client"
|
||||
|
||||
function createIpcProxy(): IpcServices | null {
|
||||
if (!window.electron) {
|
||||
return null
|
||||
}
|
||||
|
||||
return new Proxy({} as IpcServices, {
|
||||
get(target, groupName: string) {
|
||||
return new Proxy(
|
||||
{},
|
||||
{
|
||||
get(_, methodName: string) {
|
||||
return (...args: any[]) => {
|
||||
const channel = `${groupName}.${methodName}`
|
||||
return window.electron!.ipcRenderer.invoke(channel, args[0])
|
||||
}
|
||||
},
|
||||
},
|
||||
)
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
export const ipcServices = createIpcProxy()
|
||||
export const ipcServices = createIpcProxy<IpcServices>(
|
||||
window.electron?.ipcRenderer as unknown as IpcRenderer,
|
||||
)
|
||||
|
||||
@@ -79,8 +79,7 @@ export const loadLanguageAndApply = async (lang: string) => {
|
||||
|
||||
if (IN_ELECTRON) {
|
||||
importFilePath =
|
||||
(await (ipcServices as any)?.app.resolveAppAsarPath(`dist/renderer/locales/${lang}.js`)) ||
|
||||
""
|
||||
(await ipcServices?.app.resolveAppAsarPath(`dist/renderer/locales/${lang}.js`)) || ""
|
||||
} else {
|
||||
importFilePath = `/locales/${lang}.js`
|
||||
}
|
||||
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
} from "@follow/store/context"
|
||||
import { getOS } from "@follow/utils/utils"
|
||||
import * as React from "react"
|
||||
import { flushSync } from "react-dom"
|
||||
import ReactDOM from "react-dom/client"
|
||||
import { RouterProvider } from "react-router/dom"
|
||||
|
||||
@@ -37,7 +38,8 @@ initializeApp().finally(() => {
|
||||
}
|
||||
})
|
||||
|
||||
setAppIsReady(true)
|
||||
// eslint-disable-next-line @eslint-react/dom/no-flush-sync
|
||||
flushSync(() => setAppIsReady(true))
|
||||
})
|
||||
|
||||
const $container = document.querySelector("#root") as HTMLElement
|
||||
@@ -51,7 +53,7 @@ if (IN_ELECTRON) {
|
||||
break
|
||||
}
|
||||
case "macOS": {
|
||||
document.body.style.cssText += `--fo-macos-traffic-light-width: 100px; --fo-macos-traffic-light-height: 30px;`
|
||||
document.body.style.cssText += `--fo-macos-traffic-light-width: 80px; --fo-macos-traffic-light-height: 30px;`
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
export * from "./query"
|
||||
export * from "./service"
|
||||
@@ -0,0 +1,120 @@
|
||||
import type {
|
||||
DeleteSessionRequest,
|
||||
GetMessagesQuery,
|
||||
GetUnreadQuery,
|
||||
ListSessionsQuery,
|
||||
MarkSeenRequest,
|
||||
SessionResponse,
|
||||
UpdateSessionRequest,
|
||||
} from "@follow-app/client-sdk"
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"
|
||||
|
||||
import { followApi } from "~/lib/api-client"
|
||||
|
||||
const aiChatSessionKey = "ai-chat-session"
|
||||
export const aiChatSessionKeys = {
|
||||
lists: [aiChatSessionKey, "list"] as const,
|
||||
list: (filters?: ListSessionsQuery) => [aiChatSessionKey, "list", filters] as const,
|
||||
details: [aiChatSessionKey, "detail"] as const,
|
||||
detail: (chatId: string) => [aiChatSessionKey, "detail", chatId] as const,
|
||||
messages: [aiChatSessionKey, "messages"] as const,
|
||||
message: (chatId: string, filters?: GetMessagesQuery) =>
|
||||
[aiChatSessionKey, "messages", chatId, filters] as const,
|
||||
unread: [aiChatSessionKey, "unread"] as const,
|
||||
} as const
|
||||
|
||||
// Queries
|
||||
|
||||
export const useAIChatSessionListQuery = (filters?: ListSessionsQuery) => {
|
||||
const { data } = useQuery({
|
||||
queryKey: aiChatSessionKeys.list(filters),
|
||||
queryFn: () => followApi.aiChatSessions.list(filters).then((res) => res.data),
|
||||
refetchInterval: 1 * 60 * 1000, // 1 minute
|
||||
})
|
||||
return data
|
||||
}
|
||||
|
||||
export const useAIChatSessionQuery = (chatId: string | undefined, opts?: { enabled?: boolean }) => {
|
||||
const enabled = !!chatId && (opts?.enabled ?? true)
|
||||
const { data } = useQuery({
|
||||
queryKey: chatId ? aiChatSessionKeys.detail(chatId) : aiChatSessionKeys.details,
|
||||
queryFn: () =>
|
||||
followApi.aiChatSessions.get({ chatId: chatId as string }).then((res) => res.data),
|
||||
enabled,
|
||||
})
|
||||
return data
|
||||
}
|
||||
|
||||
export const useAIChatMessagesQuery = (
|
||||
chatId: string | undefined,
|
||||
filters?: GetMessagesQuery,
|
||||
opts?: { enabled?: boolean },
|
||||
) => {
|
||||
const enabled = !!chatId && (opts?.enabled ?? true)
|
||||
const { data } = useQuery({
|
||||
queryKey: chatId ? aiChatSessionKeys.message(chatId, filters) : aiChatSessionKeys.messages,
|
||||
queryFn: () =>
|
||||
followApi.aiChatSessions.messages
|
||||
.get({ chatId: chatId as string, ...filters })
|
||||
.then((res) => res.data),
|
||||
enabled,
|
||||
})
|
||||
return data
|
||||
}
|
||||
|
||||
export const useUnreadChatSessionsQuery = (filters?: GetUnreadQuery) => {
|
||||
const { data } = useQuery({
|
||||
queryKey: aiChatSessionKeys.unread,
|
||||
queryFn: () => followApi.aiChatSessions.unread(filters).then((res) => res.data),
|
||||
})
|
||||
return data
|
||||
}
|
||||
|
||||
// Mutations
|
||||
|
||||
export const useUpdateAIChatSessionMutation = () => {
|
||||
const qc = useQueryClient()
|
||||
return useMutation<SessionResponse, unknown, UpdateSessionRequest>({
|
||||
mutationFn: (input) => followApi.aiChatSessions.update(input),
|
||||
onSuccess: async (res) => {
|
||||
const chatId = res?.data?.chatId ?? undefined
|
||||
await Promise.all([
|
||||
qc.invalidateQueries({ queryKey: aiChatSessionKeys.lists }),
|
||||
chatId
|
||||
? qc.invalidateQueries({ queryKey: aiChatSessionKeys.detail(chatId) })
|
||||
: Promise.resolve(),
|
||||
])
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
export const useDeleteAIChatSessionMutation = () => {
|
||||
const qc = useQueryClient()
|
||||
return useMutation<{ success: boolean }, unknown, DeleteSessionRequest>({
|
||||
mutationFn: (input) => followApi.aiChatSessions.delete(input),
|
||||
onSuccess: async (_res, vars) => {
|
||||
await Promise.all([
|
||||
qc.invalidateQueries({ queryKey: aiChatSessionKeys.lists }),
|
||||
qc.invalidateQueries({ queryKey: aiChatSessionKeys.detail(vars.chatId) }),
|
||||
qc.invalidateQueries({ queryKey: aiChatSessionKeys.messages }),
|
||||
])
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
export const useMarkChatSessionSeenMutation = () => {
|
||||
const qc = useQueryClient()
|
||||
return useMutation<SessionResponse, unknown, MarkSeenRequest>({
|
||||
mutationFn: (input) => followApi.aiChatSessions.markSeen(input),
|
||||
onSuccess: async (res) => {
|
||||
const chatId = res?.data?.chatId ?? undefined
|
||||
await Promise.all([
|
||||
qc.invalidateQueries({ queryKey: aiChatSessionKeys.lists }),
|
||||
qc.invalidateQueries({ queryKey: aiChatSessionKeys.unread }),
|
||||
chatId
|
||||
? qc.invalidateQueries({ queryKey: aiChatSessionKeys.detail(chatId) })
|
||||
: Promise.resolve(),
|
||||
])
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
import type { AIChatMessage, AIChatSession } from "@follow-app/client-sdk"
|
||||
|
||||
import { followApi } from "../../lib/api-client"
|
||||
import { queryClient } from "../../lib/query-client"
|
||||
import { AIPersistService } from "../ai-chat/services"
|
||||
import type { BizUIMessage, BizUIMetadata } from "../ai-chat/store/types"
|
||||
import { aiChatSessionKeys } from "./query"
|
||||
|
||||
// Hard cap on pagination to prevent excessive API calls while keeping initial sync fast.
|
||||
const MAX_PAGES = 10
|
||||
|
||||
/**
|
||||
* Service for syncing AI chat session messages from remote API into local DB.
|
||||
*/
|
||||
class AIChatSessionServiceStatic {
|
||||
/**
|
||||
* 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)
|
||||
const normalized = unseenMessages.map(this.normalizeRemoteMessage)
|
||||
|
||||
await AIPersistService.ensureSession(session.chatId, session.title)
|
||||
await AIPersistService.upsertMessages(session.chatId, normalized)
|
||||
|
||||
await followApi.aiChatSessions.markSeen({
|
||||
chatId: session.chatId,
|
||||
lastSeenAt: new Date().toISOString(),
|
||||
})
|
||||
|
||||
// Invalidate related queries so UI updates outside of hook-based mutation flows
|
||||
Promise.all([
|
||||
queryClient.invalidateQueries({ queryKey: aiChatSessionKeys.detail(session.chatId) }),
|
||||
queryClient.invalidateQueries({ queryKey: aiChatSessionKeys.lists }),
|
||||
queryClient.invalidateQueries({ queryKey: aiChatSessionKeys.unread }),
|
||||
])
|
||||
return normalized
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch remote messages for a chat session that are newer than the provided lastSeenAt timestamp.
|
||||
* Implements keyset pagination using `before` / `nextBefore` and stops when:
|
||||
* - We have paged past (<=) lastSeenAt, or
|
||||
* - There is no further `nextBefore`, or
|
||||
* - A safety MAX_PAGES cap is reached.
|
||||
* Returns only unseen (newer) remote messages.
|
||||
*/
|
||||
private async fetchUnseenRemoteMessages(
|
||||
chatId: string,
|
||||
lastSeenAt: string,
|
||||
): 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(
|
||||
before ? { chatId, before } : { chatId },
|
||||
)
|
||||
const { data } = resp
|
||||
const batch = data.messages
|
||||
allMessages.push(...batch)
|
||||
|
||||
const { nextBefore } = data
|
||||
if (!nextBefore || new Date(nextBefore) <= lastSeenAtDate) {
|
||||
break
|
||||
}
|
||||
before = nextBefore
|
||||
}
|
||||
return allMessages.sort(
|
||||
(a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime(),
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalize a remote message object into BizUIMessage shape expected by the local chat system.
|
||||
*/
|
||||
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,
|
||||
metadata,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export const AIChatSessionService = new AIChatSessionServiceStatic()
|
||||
@@ -1,7 +1,25 @@
|
||||
import { getStorageNS } from "@follow/utils/ns"
|
||||
import { atom } from "jotai"
|
||||
import { atomWithStorage } from "jotai/utils"
|
||||
|
||||
import { createAtomHooks } from "~/lib/jotai"
|
||||
|
||||
// Edit state management for messages
|
||||
export const [, , useEditingMessageId, useSetEditingMessageId, , setEditingMessageId] =
|
||||
createAtomHooks(atom<string | null>(null))
|
||||
|
||||
// AI Model persistence
|
||||
interface AIModelState {
|
||||
selectedModel: string | null
|
||||
}
|
||||
|
||||
const aiModelInitialState: AIModelState = {
|
||||
selectedModel: null,
|
||||
}
|
||||
|
||||
export const [, , useAIModelState, useSetAIModelState, getAIModelState, setAIModelState] =
|
||||
createAtomHooks<AIModelState>(
|
||||
atomWithStorage(getStorageNS("ai-chat-model"), aiModelInitialState, undefined, {
|
||||
getOnInit: true,
|
||||
}),
|
||||
)
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { ErrorBoundary } from "@sentry/react"
|
||||
import { createElement, lazy, Suspense } from "react"
|
||||
|
||||
const AISplineLoader = lazy(() =>
|
||||
@@ -5,10 +6,16 @@ const AISplineLoader = lazy(() =>
|
||||
)
|
||||
export const AISpline = () => {
|
||||
return createElement(
|
||||
Suspense,
|
||||
ErrorBoundary,
|
||||
{
|
||||
fallback: createElement("div", { className: "size-16 mx-auto" }),
|
||||
handled: true,
|
||||
},
|
||||
createElement(AISplineLoader),
|
||||
createElement(
|
||||
Suspense,
|
||||
{
|
||||
fallback: createElement("div", { className: "size-16 mx-auto" }),
|
||||
},
|
||||
createElement(AISplineLoader),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
+20
-3
@@ -1,6 +1,8 @@
|
||||
import { views } from "@follow/constants"
|
||||
import { clsx, cn } from "@follow/utils/utils"
|
||||
import type { FC } from "react"
|
||||
import { memo } from "react"
|
||||
import { useTranslation } from "react-i18next"
|
||||
|
||||
import { ImageThumbnail } from "~/modules/ai-chat/components/layouts/ImageThumbnail"
|
||||
import { CircularProgress } from "~/modules/ai-chat/components/ui/UploadProgress"
|
||||
@@ -13,11 +15,18 @@ import {
|
||||
|
||||
import { EntryTitle, FeedTitle } from "./TitleComponents"
|
||||
|
||||
const blockTypeCanNotBeRemoved = new Set(["mainEntry", "mainView"])
|
||||
|
||||
export const ContextBlock: FC<{ block: AIChatContextBlock }> = memo(({ block }) => {
|
||||
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"
|
||||
}
|
||||
@@ -50,6 +59,10 @@ export const ContextBlock: FC<{ block: AIChatContextBlock }> = memo(({ block })
|
||||
|
||||
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} />
|
||||
@@ -67,12 +80,13 @@ export const ContextBlock: FC<{ block: AIChatContextBlock }> = memo(({ block })
|
||||
const fileCategory = getFileCategoryFromMimeType(type)
|
||||
|
||||
if (fileCategory === "image" && (dataUrl || previewUrl)) {
|
||||
const validPreviewUrl = (dataUrl || previewUrl)!
|
||||
return (
|
||||
<div className="flex items-center gap-1.5">
|
||||
<div className="relative">
|
||||
<ImageThumbnail
|
||||
previewUrl={previewUrl || dataUrl}
|
||||
originalUrl={dataUrl}
|
||||
previewUrl={validPreviewUrl}
|
||||
originalUrl={dataUrl || validPreviewUrl}
|
||||
alt={name}
|
||||
filename={name}
|
||||
className={"m-0.5 size-5 rounded-md"}
|
||||
@@ -144,6 +158,9 @@ export const ContextBlock: FC<{ block: AIChatContextBlock }> = memo(({ block })
|
||||
|
||||
const getBlockLabel = () => {
|
||||
switch (block.type) {
|
||||
case "mainView": {
|
||||
return ""
|
||||
}
|
||||
case "mainEntry": {
|
||||
return "Current"
|
||||
}
|
||||
@@ -166,7 +183,7 @@ export const ContextBlock: FC<{ block: AIChatContextBlock }> = memo(({ block })
|
||||
}
|
||||
}
|
||||
|
||||
const canRemove = block.type !== "mainEntry"
|
||||
const canRemove = !blockTypeCanNotBeRemoved.has(block.type)
|
||||
|
||||
return (
|
||||
<div
|
||||
|
||||
+3
-3
@@ -51,7 +51,7 @@ const FeedAnalytics = ({ data }: { data: AnalyticsData["feedData"] }) => {
|
||||
</div>
|
||||
|
||||
{analytics && (
|
||||
<div className="@[400px]:grid-cols-2 grid grid-cols-1 gap-4">
|
||||
<div className="@[600px]:grid-cols-2 @[400px]:grid-cols-2 grid grid-cols-1 gap-4">
|
||||
<StatCard title="Views" value={analytics.view || 0} emoji="👀" />
|
||||
<StatCard
|
||||
title="Last Checked"
|
||||
@@ -258,7 +258,7 @@ const AIDisplayAnalyticsPartBase = ({
|
||||
}
|
||||
|
||||
return (
|
||||
<Card className="mx-auto mb-2 w-full max-w-4xl">
|
||||
<Card className="w-[calc(var(--ai-chat-layout-width,65ch)] mx-auto mb-2">
|
||||
<CardHeader>
|
||||
<CardTitle className="text-text flex items-center gap-2 text-xl font-semibold">
|
||||
<span className="text-lg">📊</span>
|
||||
@@ -279,5 +279,5 @@ export const AIDisplayAnalyticsPart = withDisplayStateHandler<AIDisplayAnalytics
|
||||
title: "Analytics",
|
||||
loadingDescription: "Fetching analytics data...",
|
||||
errorTitle: "Analytics Error",
|
||||
maxWidth: "max-w-4xl",
|
||||
maxWidth: "max-w-full",
|
||||
})(AIDisplayAnalyticsPartBase)
|
||||
|
||||
+25
-302
@@ -1,323 +1,46 @@
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
} from "@follow/components/ui/card/index.js"
|
||||
import { entrySyncServices } from "@follow/store/entry/store"
|
||||
import dayjs from "dayjs"
|
||||
import { memo } from "react"
|
||||
|
||||
import { usePeekModal } from "~/hooks/biz/usePeekModal"
|
||||
import { FeedIcon } from "~/modules/feed/feed-icon"
|
||||
|
||||
import type { AIDisplayEntriesTool } from "../../store/types"
|
||||
import { DisplayCardWrapper, withDisplayStateHandler } from "./share"
|
||||
import { CategoryTag, EmptyState, StatCard } from "./shared"
|
||||
|
||||
type EntryData = AIDisplayEntriesTool["output"]["entries"]
|
||||
type EntryItem = EntryData[number]
|
||||
|
||||
interface EntryCardProps {
|
||||
item: EntryItem
|
||||
showSummary: boolean
|
||||
showMetadata: boolean
|
||||
}
|
||||
|
||||
const formatDisplayType = (displayType: string) => {
|
||||
const displayTypeMap = {
|
||||
timeline: "Timeline View",
|
||||
list: "List View",
|
||||
grid: "Grid View",
|
||||
card: "Card View",
|
||||
magazine: "Magazine View",
|
||||
}
|
||||
return displayTypeMap[displayType as keyof typeof displayTypeMap] || displayType
|
||||
}
|
||||
|
||||
const formatGroupBy = (groupBy: string) => {
|
||||
const groupByMap = {
|
||||
date: "By Date",
|
||||
feed: "By Feed",
|
||||
none: "No Grouping",
|
||||
}
|
||||
return groupByMap[groupBy as keyof typeof groupByMap] || groupBy
|
||||
}
|
||||
|
||||
const EntriesGrid = ({
|
||||
data,
|
||||
showSummary,
|
||||
showMetadata,
|
||||
}: {
|
||||
data: EntryData
|
||||
showSummary: boolean
|
||||
showMetadata: boolean
|
||||
}) => {
|
||||
if (!data?.length) {
|
||||
return <EmptyState message="No entries found" />
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="@[600px]:grid-cols-2 @[900px]:grid-cols-3 grid grid-cols-1 gap-4">
|
||||
{data.map((item) => (
|
||||
<EntryCard
|
||||
key={item.entry.id}
|
||||
item={item}
|
||||
showSummary={showSummary}
|
||||
showMetadata={showMetadata}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const EntryCard = memo(({ item, showSummary, showMetadata }: EntryCardProps) => {
|
||||
const peekModal = usePeekModal()
|
||||
return (
|
||||
<Card
|
||||
key={item.entry.id}
|
||||
className="hover:bg-fill-tertiary cursor-pointer p-4"
|
||||
onMouseEnter={() => entrySyncServices.fetchEntryDetail(item.entry.id)}
|
||||
onClick={() => peekModal(item.entry.id, "modal")}
|
||||
>
|
||||
<CardHeader className="h-auto px-2 py-3">
|
||||
<div className="flex items-start gap-3">
|
||||
<FeedIcon
|
||||
feed={item.feed ? { ...item.feed, type: "feed" as const } : null}
|
||||
size={32}
|
||||
className="shrink-0"
|
||||
noMargin
|
||||
/>
|
||||
<div className="-mt-1 min-w-0 flex-1">
|
||||
<CardTitle className="line-clamp-2 text-base">
|
||||
{item.entry.title || "Untitled Entry"}
|
||||
</CardTitle>
|
||||
{item.feed?.title && (
|
||||
<CardDescription className="mt-1 text-xs">{item.feed.title}</CardDescription>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</CardHeader>
|
||||
|
||||
<CardContent className="space-y-3 p-0 px-2 pb-3">
|
||||
{showSummary && item.entry.description && (
|
||||
<div className="text-text-secondary line-clamp-3 text-sm">{item.entry.description}</div>
|
||||
)}
|
||||
|
||||
{showMetadata && (
|
||||
<div className="space-y-2">
|
||||
<div className="text-text-secondary text-xs">
|
||||
Published: {dayjs(item.entry.publishedAt).format("MMM DD, YYYY HH:mm")}
|
||||
</div>
|
||||
{item.entry.author && (
|
||||
<div className="text-text-secondary text-xs">By: {item.entry.author}</div>
|
||||
)}
|
||||
{item.entry.categories?.length && (
|
||||
<div className="flex flex-wrap gap-1">
|
||||
{item.entry.categories.slice(0, 3).map((category, index) => (
|
||||
<CategoryTag key={index} category={category} />
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
)
|
||||
})
|
||||
|
||||
const TimelineView = ({
|
||||
data,
|
||||
showSummary,
|
||||
showMetadata,
|
||||
}: {
|
||||
data: EntryData
|
||||
showSummary: boolean
|
||||
showMetadata: boolean
|
||||
}) => {
|
||||
const peekModal = usePeekModal()
|
||||
|
||||
if (!data?.length) {
|
||||
return <EmptyState message="No entries found" />
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{data.map((item) => (
|
||||
<Card
|
||||
key={item.entry.id}
|
||||
className="hover:bg-fill-tertiary cursor-pointer p-4"
|
||||
onMouseEnter={() => entrySyncServices.fetchEntryDetail(item.entry.id)}
|
||||
onClick={() => peekModal(item.entry.id, "modal")}
|
||||
>
|
||||
<div className="flex gap-4">
|
||||
<FeedIcon
|
||||
feed={item.feed ? { ...item.feed, type: "feed" as const } : null}
|
||||
size={40}
|
||||
className="shrink-0"
|
||||
noMargin
|
||||
/>
|
||||
<div className="min-w-0 flex-1">
|
||||
<CardHeader className="p-0">
|
||||
<CardTitle className="text-text line-clamp-2 text-lg">
|
||||
{item.entry.title || "Untitled Entry"}
|
||||
</CardTitle>
|
||||
<CardDescription className="flex items-center gap-2 text-sm">
|
||||
{item.feed?.title && <span>{item.feed.title}</span>}
|
||||
<span>•</span>
|
||||
<span>{dayjs(item.entry.publishedAt).format("MMM DD, YYYY HH:mm")}</span>
|
||||
{item.entry.author && (
|
||||
<>
|
||||
<span>•</span>
|
||||
<span>By {item.entry.author}</span>
|
||||
</>
|
||||
)}
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
|
||||
<CardContent className="mt-3 p-0">
|
||||
{showSummary && item.entry.description && (
|
||||
<div className="text-text-secondary mb-3 line-clamp-2">
|
||||
{item.entry.description}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{showMetadata && item.entry.categories?.length && (
|
||||
<div className="flex flex-wrap gap-1">
|
||||
{item.entry.categories.slice(0, 5).map((category, index) => (
|
||||
<CategoryTag key={index} category={category} />
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</div>
|
||||
</div>
|
||||
</Card>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const GroupedEntries = ({
|
||||
data,
|
||||
groupBy,
|
||||
displayType,
|
||||
showSummary,
|
||||
showMetadata,
|
||||
}: {
|
||||
data: EntryData
|
||||
groupBy: string
|
||||
displayType: string
|
||||
showSummary: boolean
|
||||
showMetadata: boolean
|
||||
}) => {
|
||||
if (!data?.length || groupBy === "none") {
|
||||
return null
|
||||
}
|
||||
|
||||
const groups = data.reduce(
|
||||
(acc, item) => {
|
||||
let key: string
|
||||
if (groupBy === "date") {
|
||||
key = dayjs(item.entry.publishedAt).format("YYYY-MM-DD")
|
||||
} else if (groupBy === "feed") {
|
||||
key = item.feed?.title || "Unknown Feed"
|
||||
} else {
|
||||
key = "All"
|
||||
}
|
||||
|
||||
if (!acc[key]) acc[key] = []
|
||||
acc[key]?.push(item)
|
||||
return acc
|
||||
},
|
||||
{} as Record<string, EntryData>,
|
||||
)
|
||||
|
||||
const renderGroup = (groupData: EntryData) => {
|
||||
if (displayType === "timeline") {
|
||||
return <TimelineView data={groupData} showSummary={showSummary} showMetadata={showMetadata} />
|
||||
}
|
||||
return <EntriesGrid data={groupData} showSummary={showSummary} showMetadata={showMetadata} />
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{Object.entries(groups)
|
||||
.sort(([a], [b]) => {
|
||||
if (groupBy === "date") {
|
||||
return dayjs(b).isAfter(dayjs(a)) ? 1 : -1
|
||||
}
|
||||
return a.localeCompare(b)
|
||||
})
|
||||
.map(([groupName, groupData]) => (
|
||||
<div key={groupName}>
|
||||
<h3 className="text-text mb-4 text-lg font-semibold">
|
||||
{groupBy === "date" ? dayjs(groupName).format("MMMM DD, YYYY") : groupName}
|
||||
</h3>
|
||||
{renderGroup(groupData)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
import { withDisplayStateHandler } from "./share"
|
||||
|
||||
type SingleEntry = NonNullable<AIDisplayEntriesTool["output"]>[number]
|
||||
const AIDisplayEntriesPartBase = ({
|
||||
output,
|
||||
}: {
|
||||
output: NonNullable<AIDisplayEntriesTool["output"]>
|
||||
}) => {
|
||||
const {
|
||||
entries,
|
||||
displayType = "grid",
|
||||
showSummary = true,
|
||||
showMetadata = true,
|
||||
title,
|
||||
groupBy = "none",
|
||||
} = output
|
||||
return output.map((entry) => {
|
||||
return <SingleEntryCard key={entry.id} entry={entry} />
|
||||
})
|
||||
}
|
||||
|
||||
// Calculate statistics
|
||||
const totalEntries = entries.length
|
||||
const feedsCount = new Set(entries.map((e) => e.entry.feedId)).size
|
||||
const authorsCount = new Set(entries.map((e) => e.entry.author).filter(Boolean)).size
|
||||
const categoriesCount = new Set(entries.flatMap((e) => e.entry.categories || [])).size
|
||||
const SingleEntryCard = ({ entry }: { entry: SingleEntry }) => {
|
||||
const peek = usePeekModal()
|
||||
|
||||
const renderEntries = () => {
|
||||
if (groupBy !== "none") {
|
||||
return (
|
||||
<GroupedEntries
|
||||
data={entries}
|
||||
groupBy={groupBy}
|
||||
displayType={displayType}
|
||||
showSummary={showSummary}
|
||||
showMetadata={showMetadata}
|
||||
/>
|
||||
)
|
||||
}
|
||||
const handleClick = (e: React.MouseEvent) => {
|
||||
e.preventDefault()
|
||||
|
||||
if (displayType === "timeline") {
|
||||
return <TimelineView data={entries} showSummary={showSummary} showMetadata={showMetadata} />
|
||||
}
|
||||
return <EntriesGrid data={entries} showSummary={showSummary} showMetadata={showMetadata} />
|
||||
peek(entry.id, "modal")
|
||||
}
|
||||
|
||||
return (
|
||||
<DisplayCardWrapper
|
||||
title={title || "Entries"}
|
||||
emoji="📰"
|
||||
description={`${formatDisplayType(displayType)} • ${formatGroupBy(groupBy)} • ${totalEntries} entries`}
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleClick}
|
||||
className="bg-material-thick/80 border-border hover:bg-theme-item-hover group relative flex w-full flex-col items-start justify-start overflow-hidden rounded-lg border p-4 backdrop-blur-sm transition-colors"
|
||||
>
|
||||
{/* Statistics Overview */}
|
||||
<div className="@[600px]:grid-cols-4 @[400px]:grid-cols-2 grid grid-cols-1 gap-4">
|
||||
<StatCard title="Total Entries" value={totalEntries} emoji="📄" />
|
||||
<StatCard title="Feeds" value={feedsCount} emoji="📡" />
|
||||
<StatCard title="Authors" value={authorsCount} emoji="✍️" />
|
||||
<StatCard title="Categories" value={categoriesCount} emoji="🏷️" />
|
||||
{/* Header */}
|
||||
<div className="flex w-full items-start justify-between">
|
||||
<div className="flex">
|
||||
<FeedIcon disableFadeIn entry={null} feed={undefined} siteUrl={entry.url ?? undefined} />
|
||||
<h3 className="text-text line-clamp-2 flex-1 font-semibold leading-tight">
|
||||
{entry.title || "Untitled Entry"}
|
||||
</h3>
|
||||
</div>
|
||||
<i className="i-mgc-external-link-cute-re text-text-tertiary shrink-0 opacity-60 transition-opacity group-hover:opacity-100" />
|
||||
</div>
|
||||
|
||||
{/* Entries Display */}
|
||||
{renderEntries()}
|
||||
</DisplayCardWrapper>
|
||||
</button>
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
+49
-113
@@ -1,128 +1,64 @@
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
} from "@follow/components/ui/card/index.js"
|
||||
import dayjs from "dayjs"
|
||||
|
||||
import { useNavigateEntry } from "~/hooks/biz/useNavigateEntry"
|
||||
import { FeedIcon } from "~/modules/feed/feed-icon"
|
||||
|
||||
import type { AIDisplayFeedsTool } from "../../store/types"
|
||||
import { DisplayCardWrapper, withDisplayStateHandler } from "./share"
|
||||
import { AnalyticsMetrics, EmptyState, StatCard } from "./shared"
|
||||
import type { AIDisplayFeedTool } from "../../store/types"
|
||||
import { withDisplayStateHandler } from "./share"
|
||||
|
||||
type FeedData = AIDisplayFeedsTool["output"]["feeds"]
|
||||
const AIDisplayFeedPartBase = ({
|
||||
input,
|
||||
output,
|
||||
}: {
|
||||
input: NonNullable<AIDisplayFeedTool["input"]>
|
||||
output: NonNullable<AIDisplayFeedTool["output"]>
|
||||
}) => {
|
||||
const { title, description, image, siteUrl } = output
|
||||
const { feedId } = input
|
||||
|
||||
const FeedsGrid = ({ data, showAnalytics }: { data: FeedData; showAnalytics: boolean }) => {
|
||||
if (!data?.length) {
|
||||
return <EmptyState message="No feeds found" />
|
||||
const navigateEntry = useNavigateEntry()
|
||||
const handleUrlClick = (e: React.MouseEvent) => {
|
||||
e.preventDefault()
|
||||
navigateEntry({ feedId })
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="@[600px]:grid-cols-3 @[400px]:grid-cols-2 grid grid-cols-1 gap-4">
|
||||
{data.map((item) => (
|
||||
<Card key={item.feed.id} className="hover:bg-fill-tertiary cursor-pointer p-4">
|
||||
<CardHeader className="h-24 px-2 py-3">
|
||||
<div className="flex items-start gap-3">
|
||||
<FeedIcon
|
||||
feed={item.feed ? { ...item.feed, type: "feed" as const } : null}
|
||||
size={32}
|
||||
className="shrink-0"
|
||||
noMargin
|
||||
/>
|
||||
<div className="-mt-1 min-w-0 flex-1">
|
||||
<CardTitle className="line-clamp-2 text-base">
|
||||
{item.feed.title || "Unknown Feed"}
|
||||
</CardTitle>
|
||||
{item.feed.description && (
|
||||
<CardDescription className="mt-1 line-clamp-2 text-xs">
|
||||
{item.feed.description}
|
||||
</CardDescription>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</CardHeader>
|
||||
|
||||
<CardContent className="space-y-3 p-0 px-2 pb-3">
|
||||
{item.feed.errorMessage && (
|
||||
<div className="bg-red/10 text-red rounded px-2 py-1 text-xs">
|
||||
Error: {item.feed.errorMessage}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="text-text-secondary text-xs">
|
||||
Last checked: {dayjs(item.feed.checkedAt).format("MMM DD, YYYY HH:mm")}
|
||||
</div>
|
||||
|
||||
{item.feed.language && (
|
||||
<div className="text-text-secondary text-xs">Language: {item.feed.language}</div>
|
||||
)}
|
||||
|
||||
{showAnalytics && item.analytics && (
|
||||
<AnalyticsMetrics
|
||||
metrics={[
|
||||
{ label: "Updates/Week", value: item.analytics.updatesPerWeek || 0 },
|
||||
{ label: "Subscribers", value: item.analytics.subscriptionCount || 0 },
|
||||
{ label: "Views", value: item.analytics.view || 0 },
|
||||
]}
|
||||
/>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const AIDisplayFeedsPartBase = ({
|
||||
output,
|
||||
}: {
|
||||
output: NonNullable<AIDisplayFeedsTool["output"]>
|
||||
}) => {
|
||||
const { feeds, showAnalytics = true, title } = output
|
||||
|
||||
// Calculate statistics
|
||||
const totalFeeds = feeds.length
|
||||
const activeFeeds = feeds.filter((f) => !f.feed.errorMessage).length
|
||||
const errorFeeds = feeds.filter((f) => f.feed.errorMessage).length
|
||||
const totalSubscriptions = feeds.reduce(
|
||||
(acc, f) => acc + (f.analytics?.subscriptionCount || 0),
|
||||
0,
|
||||
)
|
||||
const totalViews = feeds.reduce((acc, f) => acc + (f.analytics?.view || 0), 0)
|
||||
|
||||
return (
|
||||
<DisplayCardWrapper title={title || "RSS Feeds"} emoji="📡" description={`${totalFeeds} feeds`}>
|
||||
{/* Statistics Overview */}
|
||||
<div className="@[600px]:grid-cols-4 grid grid-cols-2 gap-4 md:grid-cols-4">
|
||||
<StatCard title="Total Feeds" value={totalFeeds} emoji="📊" />
|
||||
<StatCard
|
||||
title="Active Feeds"
|
||||
value={activeFeeds}
|
||||
description={`${errorFeeds} with errors`}
|
||||
emoji="🟢"
|
||||
/>
|
||||
{showAnalytics && (
|
||||
<>
|
||||
<StatCard
|
||||
title="Total Subscribers"
|
||||
value={totalSubscriptions.toLocaleString()}
|
||||
emoji="👥"
|
||||
/>
|
||||
<StatCard title="Total Views" value={totalViews.toLocaleString()} emoji="👀" />
|
||||
</>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleUrlClick}
|
||||
className="bg-material-thick/80 border-border hover:bg-theme-item-hover group relative flex w-full flex-col items-start justify-start overflow-hidden rounded-lg border p-4 backdrop-blur-sm transition-colors"
|
||||
>
|
||||
{/* Header */}
|
||||
<div className="flex w-full items-start justify-between">
|
||||
<div className="flex">
|
||||
<FeedIcon
|
||||
disableFadeIn
|
||||
feed={{
|
||||
type: "feed",
|
||||
title,
|
||||
id: feedId,
|
||||
image,
|
||||
siteUrl,
|
||||
}}
|
||||
siteUrl={siteUrl!}
|
||||
/>
|
||||
<h3 className="text-text line-clamp-2 flex-1 font-semibold leading-tight">
|
||||
{title || "Untitled Feed"}
|
||||
</h3>
|
||||
</div>
|
||||
<i className="i-mgc-external-link-cute-re text-text-tertiary shrink-0 opacity-60 transition-opacity group-hover:opacity-100" />
|
||||
</div>
|
||||
|
||||
<FeedsGrid data={feeds} showAnalytics={showAnalytics} />
|
||||
</DisplayCardWrapper>
|
||||
{/* Description */}
|
||||
{description && (
|
||||
<p className="text-text-secondary mt-2 line-clamp-3 text-sm leading-relaxed">
|
||||
{description}
|
||||
</p>
|
||||
)}
|
||||
</button>
|
||||
)
|
||||
}
|
||||
|
||||
export const AIDisplayFeedsPart = withDisplayStateHandler<AIDisplayFeedsTool["output"]>({
|
||||
export const AIDisplayFeedPart = withDisplayStateHandler<AIDisplayFeedTool["output"]>({
|
||||
title: "Feeds",
|
||||
loadingDescription: "Fetching feed data...",
|
||||
errorTitle: "Feeds Error",
|
||||
})(AIDisplayFeedsPartBase)
|
||||
})(AIDisplayFeedPartBase)
|
||||
|
||||
+58
-58
@@ -1,13 +1,14 @@
|
||||
import "@xyflow/react/dist/style.css"
|
||||
|
||||
import { useIsDark } from "@follow/hooks"
|
||||
import { thenable } from "@follow/utils"
|
||||
import { cn } from "@follow/utils/utils"
|
||||
import type { ToolWithState } from "@folo-services/ai-tools"
|
||||
import { Background, Controls, ReactFlow } from "@xyflow/react"
|
||||
import { useCallback } from "react"
|
||||
|
||||
import { useModalStack } from "~/components/ui/modal/stacked/hooks"
|
||||
|
||||
import type { AIDisplayFlowTool } from "../../store/types"
|
||||
import { toolMemo } from "./share"
|
||||
|
||||
const FlowPreviewModal = ({
|
||||
@@ -41,64 +42,63 @@ const FlowPreviewModal = ({
|
||||
)
|
||||
}
|
||||
|
||||
export const AIDisplayFlowPart = toolMemo(
|
||||
({ part, loadingElement }: { part: AIDisplayFlowTool; loadingElement: React.ReactNode }) => {
|
||||
if (!part.input) return loadingElement
|
||||
if (part.state === "input-streaming") {
|
||||
return loadingElement
|
||||
}
|
||||
export const AIDisplayFlowPart = toolMemo(({ part }: { part: ToolWithState<any> }) => {
|
||||
if (!part.input) throw thenable
|
||||
if (part.state === "input-streaming") {
|
||||
throw thenable
|
||||
}
|
||||
|
||||
const { nodes, edges } = part.input.flowChart as any
|
||||
const colorMode = useIsDark() ? "dark" : "light"
|
||||
const { present } = useModalStack()
|
||||
// `part.input.flowChart` to make compatible with old data
|
||||
const { nodes, edges } = part.input.flowChart || (part.input.schema.flowChart as any)
|
||||
const colorMode = useIsDark() ? "dark" : "light"
|
||||
const { present } = useModalStack()
|
||||
|
||||
const handleOpenModal = useCallback(() => {
|
||||
present({
|
||||
title: "Flow Chart Preview",
|
||||
content: () => <FlowPreviewModal nodes={nodes} edges={edges} colorMode={colorMode} />,
|
||||
max: true,
|
||||
canClose: true,
|
||||
clickOutsideToDismiss: false,
|
||||
modalContentClassName: "p-0 h-full",
|
||||
modalClassName: "h-[90vh] w-[90vw]",
|
||||
})
|
||||
}, [nodes, edges, colorMode, present])
|
||||
const handleOpenModal = useCallback(() => {
|
||||
present({
|
||||
title: "Flow Chart Preview",
|
||||
content: () => <FlowPreviewModal nodes={nodes} edges={edges} colorMode={colorMode} />,
|
||||
max: true,
|
||||
canClose: true,
|
||||
clickOutsideToDismiss: false,
|
||||
modalContentClassName: "p-0 h-full",
|
||||
modalClassName: "h-[90vh] w-[90vw]",
|
||||
})
|
||||
}, [nodes, edges, colorMode, present])
|
||||
|
||||
return (
|
||||
<div className="group relative my-2 aspect-[4/3] w-[calc(var(--ai-chat-layout-width,65ch)-120px)] max-w-prose overflow-hidden rounded-md">
|
||||
<ReactFlow
|
||||
colorMode={colorMode}
|
||||
nodes={nodes}
|
||||
edges={edges}
|
||||
fitView
|
||||
nodesDraggable={false}
|
||||
nodesConnectable={false}
|
||||
nodesFocusable={false}
|
||||
edgesFocusable={false}
|
||||
elementsSelectable={false}
|
||||
preventScrolling={false}
|
||||
>
|
||||
<Background />
|
||||
<Controls />
|
||||
</ReactFlow>
|
||||
return (
|
||||
<div className="group relative my-2 aspect-[4/3] w-[calc(var(--ai-chat-layout-width,65ch))] max-w-full overflow-hidden rounded-md">
|
||||
<ReactFlow
|
||||
colorMode={colorMode}
|
||||
nodes={nodes}
|
||||
edges={edges}
|
||||
fitView
|
||||
nodesDraggable={false}
|
||||
nodesConnectable={false}
|
||||
nodesFocusable={false}
|
||||
edgesFocusable={false}
|
||||
elementsSelectable={false}
|
||||
preventScrolling={false}
|
||||
>
|
||||
<Background />
|
||||
<Controls />
|
||||
</ReactFlow>
|
||||
|
||||
{/* Expand/Preview button */}
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleOpenModal}
|
||||
className={cn(
|
||||
"absolute right-2 top-2 flex items-center gap-1.5 rounded-lg px-2.5 py-1.5",
|
||||
"bg-material-thick text-text-secondary text-sm font-medium",
|
||||
"opacity-0 transition-all duration-200 group-hover:opacity-100",
|
||||
"hover:bg-material-medium hover:text-text focus:opacity-100",
|
||||
"focus:ring-blue focus:outline-none focus:ring-2 focus:ring-offset-1",
|
||||
)}
|
||||
title="Open in full screen"
|
||||
>
|
||||
<i className="i-mgc-external-link-cute-re size-4" />
|
||||
<span>Preview</span>
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
},
|
||||
)
|
||||
{/* Expand/Preview button */}
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleOpenModal}
|
||||
className={cn(
|
||||
"absolute right-2 top-2 flex items-center gap-1.5 rounded-lg px-2.5 py-1.5",
|
||||
"bg-material-thick text-text-secondary text-sm font-medium",
|
||||
"opacity-0 transition-all duration-200 group-hover:opacity-100",
|
||||
"hover:bg-material-medium hover:text-text focus:opacity-100",
|
||||
"focus:ring-blue focus:outline-none focus:ring-2 focus:ring-offset-1",
|
||||
)}
|
||||
title="Open in full screen"
|
||||
>
|
||||
<i className="i-mgc-external-link-cute-re size-4" />
|
||||
<span>Preview</span>
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
})
|
||||
|
||||
+68
-221
@@ -1,240 +1,87 @@
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
} from "@follow/components/ui/card/index.js"
|
||||
import { views } from "@follow/constants"
|
||||
import dayjs from "dayjs"
|
||||
import { memo, useCallback } from "react"
|
||||
import { useTranslation } from "react-i18next"
|
||||
|
||||
import { useNavigateEntry } from "~/hooks/biz/useNavigateEntry"
|
||||
import { FeedIcon } from "~/modules/feed/feed-icon"
|
||||
|
||||
import type { AIDisplaySubscriptionsTool } from "../../store/types"
|
||||
import { DisplayCardWrapper, withDisplayStateHandler } from "./share"
|
||||
import { AnalyticsMetrics, CategoryTag, EmptyState, StatCard } from "./shared"
|
||||
import { withDisplayStateHandler } from "./share"
|
||||
|
||||
type SubscriptionData = AIDisplaySubscriptionsTool["output"]["subscriptions"]
|
||||
|
||||
const formatDisplayType = (displayType: string) => {
|
||||
const displayTypeMap = {
|
||||
list: "List View",
|
||||
grid: "Grid View",
|
||||
card: "Card View",
|
||||
compact: "Compact View",
|
||||
}
|
||||
return displayTypeMap[displayType as keyof typeof displayTypeMap] || displayType
|
||||
}
|
||||
|
||||
const formatGroupBy = (groupBy: string) => {
|
||||
const groupByMap = {
|
||||
category: "By Category",
|
||||
status: "By Status",
|
||||
none: "No Grouping",
|
||||
}
|
||||
return groupByMap[groupBy as keyof typeof groupByMap] || groupBy
|
||||
}
|
||||
|
||||
const formatFilterBy = (filterBy: string) => {
|
||||
const filterByMap = {
|
||||
all: "All Subscriptions",
|
||||
active: "Active Only",
|
||||
inactive: "Inactive Only",
|
||||
recent: "Recent (30 days)",
|
||||
}
|
||||
return filterByMap[filterBy as keyof typeof filterByMap] || filterBy
|
||||
}
|
||||
|
||||
const SubscriptionsGrid = ({
|
||||
data,
|
||||
showAnalytics,
|
||||
showCategories,
|
||||
}: {
|
||||
data: SubscriptionData
|
||||
showAnalytics: boolean
|
||||
showCategories: boolean
|
||||
}) => {
|
||||
if (!data?.length) {
|
||||
return <EmptyState message="No subscriptions found" />
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="@[600px]:grid-cols-3 @[400px]:grid-cols-2 grid grid-cols-1 gap-4">
|
||||
{data.map((sub) => (
|
||||
<Card
|
||||
key={`${sub.subscription?.userId}-${sub.subscription?.feedId}`}
|
||||
className="hover:bg-fill-tertiary cursor-pointer p-4"
|
||||
>
|
||||
<CardHeader className="h-24 px-2 py-3">
|
||||
<div className="flex items-start gap-3">
|
||||
<FeedIcon
|
||||
feed={sub.feed ? { ...sub.feed, type: "feed" as const } : null}
|
||||
size={32}
|
||||
className="shrink-0"
|
||||
noMargin
|
||||
/>
|
||||
<div className="-mt-1 min-w-0 flex-1">
|
||||
<CardTitle className="line-clamp-2 text-base">
|
||||
{sub.feed?.title || sub.subscription?.title || "Unknown Feed"}
|
||||
</CardTitle>
|
||||
{sub.feed?.description && (
|
||||
<CardDescription className="mt-1 line-clamp-2 text-xs">
|
||||
{sub.feed.description}
|
||||
</CardDescription>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</CardHeader>
|
||||
|
||||
<CardContent className="space-y-3 p-0 px-2 pb-3">
|
||||
{showCategories && sub.subscription?.category && (
|
||||
<div>
|
||||
<CategoryTag category={sub.subscription.category} />
|
||||
</div>
|
||||
)}
|
||||
<div className="text-text-secondary text-xs">
|
||||
<span>
|
||||
Subscribed:{" "}
|
||||
<span>
|
||||
{sub.subscription?.createdAt
|
||||
? dayjs(sub.subscription.createdAt).format("MMM DD, YYYY")
|
||||
: "Unknown"}
|
||||
</span>
|
||||
</span>
|
||||
</div>
|
||||
{showAnalytics && (
|
||||
<AnalyticsMetrics
|
||||
metrics={[
|
||||
{ label: "Updates/Week", value: sub.analytics?.updatesPerWeek || 0 },
|
||||
{ label: "Views", value: sub.analytics?.view || sub.subscription?.view || 0 },
|
||||
]}
|
||||
/>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const GroupedSubscriptions = ({
|
||||
data,
|
||||
groupBy,
|
||||
showAnalytics,
|
||||
showCategories,
|
||||
}: {
|
||||
data: SubscriptionData
|
||||
groupBy: string
|
||||
showAnalytics: boolean
|
||||
showCategories: boolean
|
||||
}) => {
|
||||
if (!data?.length || groupBy === "none") {
|
||||
return null
|
||||
}
|
||||
|
||||
const groups = data.reduce(
|
||||
(acc, sub) => {
|
||||
let key: string
|
||||
if (groupBy === "category") {
|
||||
key = sub.subscription?.category || "No Category"
|
||||
} else if (groupBy === "status") {
|
||||
// Simple status based on error state
|
||||
key = sub.feed?.errorMessage ? "Inactive" : "Active"
|
||||
} else {
|
||||
key = "All"
|
||||
}
|
||||
|
||||
if (!acc[key]) acc[key] = []
|
||||
acc[key]?.push(sub)
|
||||
return acc
|
||||
},
|
||||
{} as Record<string, SubscriptionData>,
|
||||
)
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{Object.entries(groups).map(([groupName, groupData]) => (
|
||||
<div key={groupName}>
|
||||
<h3 className="text-text mb-4 text-lg font-semibold">{groupName}</h3>
|
||||
<SubscriptionsGrid
|
||||
data={groupData}
|
||||
showAnalytics={showAnalytics}
|
||||
showCategories={showCategories}
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
type SingleSubscription = NonNullable<AIDisplaySubscriptionsTool["output"]>[number]
|
||||
|
||||
const AIDisplaySubscriptionsPartBase = ({
|
||||
output,
|
||||
}: {
|
||||
output: NonNullable<AIDisplaySubscriptionsTool["output"]>
|
||||
input: NonNullable<AIDisplaySubscriptionsTool["input"]>
|
||||
}) => {
|
||||
const {
|
||||
subscriptions,
|
||||
displayType = "list",
|
||||
showAnalytics = true,
|
||||
showCategories = true,
|
||||
title,
|
||||
groupBy = "none",
|
||||
filterBy = "all",
|
||||
} = output
|
||||
const navigateEntry = useNavigateEntry()
|
||||
|
||||
// Calculate statistics
|
||||
const totalSubscriptions = subscriptions.length
|
||||
const categoriesCount = new Set(
|
||||
subscriptions.map((s) => s.subscription?.category).filter(Boolean),
|
||||
).size
|
||||
const activeSubscriptions = subscriptions.filter((s) => !s.feed?.errorMessage).length
|
||||
const totalViews = subscriptions.reduce((acc, s) => acc + (s.subscription?.view || 0), 0)
|
||||
|
||||
const renderSubscriptions = () => {
|
||||
if (groupBy !== "none") {
|
||||
return (
|
||||
<GroupedSubscriptions
|
||||
data={subscriptions}
|
||||
groupBy={groupBy}
|
||||
showAnalytics={showAnalytics}
|
||||
showCategories={showCategories}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<SubscriptionsGrid
|
||||
data={subscriptions}
|
||||
showAnalytics={showAnalytics}
|
||||
showCategories={showCategories}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<DisplayCardWrapper
|
||||
title={title || "My Subscriptions"}
|
||||
emoji="📋"
|
||||
description={`${formatDisplayType(displayType)} • ${formatFilterBy(filterBy)} • ${formatGroupBy(groupBy)}`}
|
||||
>
|
||||
{/* Statistics Overview */}
|
||||
<div className="@[700px]:grid-cols-4 grid grid-cols-2 gap-4">
|
||||
<StatCard title="Total Subscriptions" value={totalSubscriptions} emoji="📊" />
|
||||
<StatCard
|
||||
title="Active Feeds"
|
||||
value={activeSubscriptions}
|
||||
description={`${totalSubscriptions - activeSubscriptions} inactive`}
|
||||
emoji="🟢"
|
||||
/>
|
||||
{showCategories && <StatCard title="Categories" value={categoriesCount} emoji="🏷️" />}
|
||||
<StatCard title="Total Views" value={totalViews.toLocaleString()} emoji="👀" />
|
||||
</div>
|
||||
|
||||
{/* Subscriptions Display */}
|
||||
{renderSubscriptions()}
|
||||
</DisplayCardWrapper>
|
||||
const handleClick = useCallback(
|
||||
(sub: SingleSubscription) => (e: React.MouseEvent) => {
|
||||
e.preventDefault()
|
||||
navigateEntry({ feedId: sub.feedId, view: sub.view })
|
||||
},
|
||||
[navigateEntry],
|
||||
)
|
||||
|
||||
return output.map((sub) => <Item key={sub.feedId} sub={sub} handleClick={handleClick} />)
|
||||
}
|
||||
|
||||
const Item = memo(
|
||||
({
|
||||
sub,
|
||||
handleClick,
|
||||
}: {
|
||||
sub: SingleSubscription
|
||||
handleClick: (sub: SingleSubscription) => (e: React.MouseEvent) => void
|
||||
}) => {
|
||||
const { feedId, title, image, siteUrl, category, subscribedAt, view } = sub
|
||||
const { t } = useTranslation()
|
||||
const currentView = views[view]
|
||||
if (currentView === undefined) {
|
||||
return null
|
||||
}
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
key={feedId}
|
||||
onClick={handleClick(sub)}
|
||||
className="bg-material-thick/80 border-border hover:bg-theme-item-hover group relative flex w-full flex-col items-start justify-start overflow-hidden rounded-lg border p-4 text-left backdrop-blur-sm transition-colors"
|
||||
>
|
||||
<div className="flex w-full items-start justify-between">
|
||||
<div className="flex">
|
||||
<FeedIcon
|
||||
disableFadeIn
|
||||
feed={{
|
||||
type: "feed",
|
||||
title,
|
||||
id: feedId,
|
||||
image,
|
||||
siteUrl,
|
||||
}}
|
||||
siteUrl={siteUrl!}
|
||||
/>
|
||||
<div className="flex min-w-0 flex-col">
|
||||
<h3 className="text-text line-clamp-2 font-semibold leading-tight">
|
||||
{title || "Untitled Feed"}
|
||||
</h3>
|
||||
<div className="text-text-tertiary mt-1 flex items-center gap-2 text-xs">
|
||||
{category ? <span className="text-text-secondary">{category}</span> : null}
|
||||
<span>Subscribed {dayjs(subscribedAt).format("MMM DD, YYYY")}</span>
|
||||
{currentView.icon}
|
||||
<span>{t(currentView.name, { ns: "common" })}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<i className="i-mgc-external-link-cute-re text-text-tertiary shrink-0 opacity-60 transition-opacity group-hover:opacity-100" />
|
||||
</div>
|
||||
</button>
|
||||
)
|
||||
},
|
||||
)
|
||||
export const AIDisplaySubscriptionsPart = withDisplayStateHandler<
|
||||
AIDisplaySubscriptionsTool["output"]
|
||||
>({
|
||||
|
||||
+64
@@ -0,0 +1,64 @@
|
||||
import { CollapseCss, CollapseCssGroup } from "@follow/components/ui/collapse/CollapseCss.js"
|
||||
import { cn } from "@follow/utils"
|
||||
import * as React from "react"
|
||||
|
||||
interface AIReasoningPartProps {
|
||||
text: string
|
||||
isStreaming?: boolean
|
||||
className?: string
|
||||
}
|
||||
|
||||
export const AIReasoningPart: React.FC<AIReasoningPartProps> = React.memo(
|
||||
({ text, isStreaming = false, className }) => {
|
||||
const collapseId = React.useMemo(() => `reasoning-${Math.random().toString(36).slice(2)}`, [])
|
||||
// Re-mount CollapseCssGroup when streaming state changes or when we need to force-open while streaming
|
||||
const [remountTick, setRemountTick] = React.useState(0)
|
||||
const groupKey = `${isStreaming ? "streaming" : "idle"}:${remountTick}`
|
||||
if (!text) return null
|
||||
|
||||
return (
|
||||
<div className={cn("border-border min-w-0 max-w-full text-left", className)}>
|
||||
<div className="w-[calc(var(--ai-chat-layout-width,65ch))]" />
|
||||
|
||||
<CollapseCssGroup key={groupKey}>
|
||||
<div>
|
||||
<CollapseCss
|
||||
hideArrow
|
||||
collapseId={collapseId}
|
||||
defaultOpen={isStreaming}
|
||||
onOpenChange={(opened) => {
|
||||
// While streaming, keep it open and block manual collapse
|
||||
if (isStreaming && !opened) {
|
||||
setRemountTick((x) => x + 1)
|
||||
}
|
||||
}}
|
||||
title={
|
||||
<div className="group flex h-6 min-w-0 flex-1 items-center justify-between py-0">
|
||||
<div className="flex items-center gap-2 text-xs">
|
||||
<i className="i-mingcute-bulb-2-line text-purple" />
|
||||
<span className="text-text-secondary">
|
||||
{isStreaming ? "Reasoning..." : "Reasoning"}
|
||||
</span>
|
||||
</div>
|
||||
<div className="ml-auto flex items-center justify-center opacity-0 transition-opacity duration-200 group-hover:opacity-100">
|
||||
<i className="i-mgc-right-cute-re size-3 shrink-0 transition-transform duration-200 group-data-[state=open]:rotate-90" />
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
className="group w-full border-none"
|
||||
contentClassName="pb-0 pt-2"
|
||||
>
|
||||
<div className="text-xs">
|
||||
<pre className="text-text-secondary bg-material-medium overflow-x-auto whitespace-pre-wrap rounded p-3 text-[11px] leading-relaxed">
|
||||
{text}
|
||||
</pre>
|
||||
</div>
|
||||
</CollapseCss>
|
||||
</div>
|
||||
</CollapseCssGroup>
|
||||
</div>
|
||||
)
|
||||
},
|
||||
)
|
||||
|
||||
AIReasoningPart.displayName = "AIReasoningPart"
|
||||
@@ -1,4 +1,5 @@
|
||||
export { AIDisplayAnalyticsPart } from "./AIDisplayAnalyticsPart"
|
||||
export { AIDisplayEntriesPart } from "./AIDisplayEntriesPart"
|
||||
export { AIDisplayFeedsPart } from "./AIDisplayFeedsPart"
|
||||
export { AIDisplayFeedPart } from "./AIDisplayFeedsPart"
|
||||
export { AIDisplaySubscriptionsPart } from "./AIDisplaySubscriptionsPart"
|
||||
export { AIReasoningPart } from "./AIReasoningPart"
|
||||
|
||||
@@ -1,11 +1,4 @@
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
} from "@follow/components/ui/card/index.js"
|
||||
import type { ComponentType, ReactNode } from "react"
|
||||
import type { ComponentType } from "react"
|
||||
import { memo } from "react"
|
||||
import isEqual from "react-fast-compare"
|
||||
|
||||
@@ -30,8 +23,8 @@ export function withDisplayStateHandler<T>(config: {
|
||||
errorTitle: string
|
||||
maxWidth?: string
|
||||
}) {
|
||||
return function <P extends { part: { state: string; output?: T } }>(
|
||||
WrappedComponent: ComponentType<P & { output: NonNullable<T> }>,
|
||||
return function <P extends { part: { state: string; output?: T; input?: any } }>(
|
||||
WrappedComponent: ComponentType<P & { output: NonNullable<T>; input: any }>,
|
||||
): ComponentType<P> {
|
||||
const WithDisplayStateHandler = toolMemo((props: P) => {
|
||||
const { part } = props
|
||||
@@ -39,27 +32,19 @@ export function withDisplayStateHandler<T>(config: {
|
||||
// Handle error state
|
||||
if (part.state === "output-error") {
|
||||
return (
|
||||
<ErrorState
|
||||
title={config.errorTitle}
|
||||
error={`An error occurred while loading ${config.title.toLowerCase()}`}
|
||||
maxWidth={config.maxWidth || "max-w-6xl"}
|
||||
/>
|
||||
<ErrorState error={`An error occurred while loading ${config.title.toLowerCase()}`} />
|
||||
)
|
||||
}
|
||||
|
||||
// Handle loading/invalid state
|
||||
if (part.state !== "output-available" || !part.output) {
|
||||
return (
|
||||
<LoadingState
|
||||
title={`Loading ${config.title}...`}
|
||||
description={config.loadingDescription}
|
||||
maxWidth={config.maxWidth || "max-w-6xl"}
|
||||
/>
|
||||
)
|
||||
return <LoadingState description={config.loadingDescription} />
|
||||
}
|
||||
|
||||
// Render the wrapped component with the validated output
|
||||
return <WrappedComponent {...props} output={part.output as NonNullable<T>} />
|
||||
return (
|
||||
<WrappedComponent {...props} output={part.output as NonNullable<T>} input={part.input} />
|
||||
)
|
||||
})
|
||||
|
||||
WithDisplayStateHandler.displayName = `withDisplayStateHandler(${WrappedComponent.displayName || WrappedComponent.name})`
|
||||
@@ -67,30 +52,3 @@ export function withDisplayStateHandler<T>(config: {
|
||||
return WithDisplayStateHandler
|
||||
}
|
||||
}
|
||||
|
||||
// Common card wrapper for display components
|
||||
export const DisplayCardWrapper = ({
|
||||
title,
|
||||
emoji,
|
||||
description,
|
||||
children,
|
||||
maxWidth = "max-w-6xl",
|
||||
}: {
|
||||
title: string
|
||||
emoji: string
|
||||
description?: string
|
||||
children: ReactNode
|
||||
maxWidth?: string
|
||||
}) => (
|
||||
<Card className={`mb-2 w-full min-w-0 ${maxWidth}`}>
|
||||
<div className="w-[9999px] max-w-[calc(var(--ai-chat-layout-width,65ch)_-120px)]" />
|
||||
<CardHeader>
|
||||
<CardTitle className="text-text flex items-center gap-2 text-xl font-semibold">
|
||||
<span className="text-lg">{emoji}</span>
|
||||
<span>{title}</span>
|
||||
</CardTitle>
|
||||
{description && <CardDescription>{description}</CardDescription>}
|
||||
</CardHeader>
|
||||
<CardContent className="@container space-y-6">{children}</CardContent>
|
||||
</Card>
|
||||
)
|
||||
|
||||
+20
-4
@@ -1,12 +1,15 @@
|
||||
import { cn } from "@follow/utils/utils"
|
||||
import { memo, useCallback, useMemo, useRef } from "react"
|
||||
import { memo, useCallback, useEffect, useMemo, useRef } from "react"
|
||||
|
||||
import { useAISettingValue } from "~/atoms/settings/ai"
|
||||
import { DropdownMenu, DropdownMenuTrigger } from "~/components/ui/dropdown-menu/dropdown-menu"
|
||||
import { useRouteParamsSelector } from "~/hooks/biz/useRouteParams"
|
||||
import { useFileUploadWithDefaults } from "~/modules/ai-chat/hooks/useFileUpload"
|
||||
import { useAIChatStore } from "~/modules/ai-chat/store/AIChatContext"
|
||||
import { SUPPORTED_MIME_ACCEPT } from "~/modules/ai-chat/utils/file-validation"
|
||||
|
||||
import { useBlockActions } from "../../store/hooks"
|
||||
import { BlockSliceAction } from "../../store/slices/block.slice"
|
||||
import { ContextBlock } from "../context-bar/blocks"
|
||||
import { ContextMenuContent, ShortcutsMenuContent } from "../context-bar/menus"
|
||||
|
||||
@@ -27,6 +30,19 @@ export const AIChatContextBar: Component<{ onSendShortcut?: (prompt: string) =>
|
||||
fileInputRef.current?.click()
|
||||
}, [])
|
||||
|
||||
const view = useRouteParamsSelector((i) => i.view)
|
||||
const { addOrUpdateBlock, removeBlock } = useBlockActions()
|
||||
useEffect(() => {
|
||||
addOrUpdateBlock({
|
||||
id: BlockSliceAction.SPECIAL_TYPES.mainView,
|
||||
type: "mainView",
|
||||
value: `${view}`,
|
||||
})
|
||||
return () => {
|
||||
removeBlock(BlockSliceAction.SPECIAL_TYPES.mainView)
|
||||
}
|
||||
}, [addOrUpdateBlock, view, removeBlock])
|
||||
|
||||
return (
|
||||
<div className={cn("flex flex-wrap items-center gap-2 px-4 py-3", className)}>
|
||||
{/* Add Context Button */}
|
||||
@@ -34,7 +50,7 @@ export const AIChatContextBar: Component<{ onSendShortcut?: (prompt: string) =>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<button
|
||||
type="button"
|
||||
className="bg-fill-secondary hover:bg-fill-tertiary border-border text-text-tertiary hover:text-text-secondary flex size-7 items-center justify-center rounded-md border transition-colors"
|
||||
className="bg-material-medium hover:bg-material-thin border-border text-text-secondary hover:text-text-secondary flex size-7 items-center justify-center rounded-md border transition-colors"
|
||||
>
|
||||
<i className="i-mgc-add-cute-re size-3.5" />
|
||||
</button>
|
||||
@@ -46,7 +62,7 @@ export const AIChatContextBar: Component<{ onSendShortcut?: (prompt: string) =>
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleAttachFile}
|
||||
className="bg-fill-secondary hover:bg-fill-tertiary border-border text-text-tertiary hover:text-text-secondary flex size-7 items-center justify-center rounded-md border transition-colors"
|
||||
className="bg-material-medium hover:bg-material-thin border-border text-text-secondary hover:text-text-secondary flex size-7 items-center justify-center rounded-md border transition-colors"
|
||||
title="Upload Files"
|
||||
>
|
||||
<i className="i-mgc-attachment-cute-re size-3.5" />
|
||||
@@ -68,7 +84,7 @@ export const AIChatContextBar: Component<{ onSendShortcut?: (prompt: string) =>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<button
|
||||
type="button"
|
||||
className="bg-fill-secondary hover:bg-fill-tertiary border-border text-text-tertiary hover:text-text-secondary flex size-7 items-center justify-center rounded-md border transition-colors"
|
||||
className="bg-material-medium hover:bg-material-thin border-border text-text-secondary hover:text-text-secondary flex size-7 items-center justify-center rounded-md border transition-colors"
|
||||
title="AI Shortcuts"
|
||||
>
|
||||
<i className="i-mgc-magic-2-cute-re size-3.5" />
|
||||
|
||||
@@ -1,11 +1,18 @@
|
||||
import { atom } from "jotai"
|
||||
import type { FC, PropsWithChildren } from "react"
|
||||
import { useMemo, useRef } from "react"
|
||||
import { useEffect, useMemo, useRef } from "react"
|
||||
|
||||
import { Focusable } from "~/components/common/Focusable"
|
||||
import { HotkeyScope } from "~/constants"
|
||||
|
||||
import { useAIShortcut } from "../../hooks/useAIShortcut"
|
||||
import type { AIPanelRefs } from "../../store/AIChatContext"
|
||||
import { AIChatStoreContext, AIPanelRefsContext } from "../../store/AIChatContext"
|
||||
import {
|
||||
AIChatStoreContext,
|
||||
AIPanelRefsContext,
|
||||
AIRootStateContext,
|
||||
} from "../../store/AIChatContext"
|
||||
import { ChatSliceActions } from "../../store/chat-core/chat-actions"
|
||||
import { useChatActions, useCurrentChatId } from "../../store/hooks"
|
||||
import { createAIChatStore } from "../../store/store"
|
||||
|
||||
@@ -28,6 +35,7 @@ const AIChatRootInner: FC<AIChatRootProps> = ({ children, chatId: externalChatId
|
||||
const panelRef = useRef<HTMLDivElement>(null!)
|
||||
const inputRef = useRef<HTMLTextAreaElement>(null!)
|
||||
const refsContext = useMemo<AIPanelRefs>(() => ({ panelRef, inputRef }), [panelRef, inputRef])
|
||||
useAIShortcut()
|
||||
|
||||
if (!currentChatId) {
|
||||
return (
|
||||
@@ -49,10 +57,24 @@ export const AIChatRoot: FC<AIChatRootProps> = ({
|
||||
chatId: externalChatId,
|
||||
}) => {
|
||||
const useAiContextStore = useMemo(createAIChatStore, [])
|
||||
const chatActions = useAiContextStore((state) => state.chatActions)
|
||||
|
||||
useEffect(() => {
|
||||
ChatSliceActions.setActiveInstance(chatActions)
|
||||
}, [chatActions])
|
||||
|
||||
const Element = (
|
||||
<AIChatStoreContext value={useAiContextStore}>
|
||||
<AIChatRootInner chatId={externalChatId}>{children}</AIChatRootInner>
|
||||
<AIRootStateContext
|
||||
value={useMemo(
|
||||
() => ({
|
||||
isScrolledBeyondThreshold: atom(false),
|
||||
}),
|
||||
[],
|
||||
)}
|
||||
>
|
||||
<AIChatRootInner chatId={externalChatId}>{children}</AIChatRootInner>
|
||||
</AIRootStateContext>
|
||||
</AIChatStoreContext>
|
||||
)
|
||||
|
||||
@@ -65,3 +87,4 @@ export const AIChatRoot: FC<AIChatRootProps> = ({
|
||||
}
|
||||
return Element
|
||||
}
|
||||
AIChatRoot.displayName = "AIChatRoot"
|
||||
|
||||
+28
-12
@@ -24,6 +24,15 @@ const providerIcons: Record<ProviderType, string> = {
|
||||
meta: "i-simple-icons-meta",
|
||||
}
|
||||
|
||||
const AIModelNameMapping = {
|
||||
"gpt-4o": "GPT-4o",
|
||||
"gpt-4o-mini": "GPT-4o mini",
|
||||
"gpt-4": "GPT-4",
|
||||
"gpt-5": "GPT-5",
|
||||
"gpt-5-mini": "GPT-5 mini",
|
||||
"gpt-5-nano": "GPT-5 nano",
|
||||
}
|
||||
|
||||
const parseModelString = (modelString: string) => {
|
||||
if (!modelString || !modelString.includes("/")) {
|
||||
return { provider: "openai" as ProviderType, modelName: modelString || "Unknown" }
|
||||
@@ -39,12 +48,12 @@ const parseModelString = (modelString: string) => {
|
||||
}
|
||||
|
||||
export const AIModelIndicator = memo(({ className, onModelChange }: AIModelIndicatorProps) => {
|
||||
const { data } = useAIModel()
|
||||
const { currentModel, availableModels = [] } = data || {}
|
||||
const { data, changeModel } = useAIModel()
|
||||
const { defaultModel, availableModels = [], currentModel } = data || {}
|
||||
|
||||
const { provider, modelName } = useMemo(() => {
|
||||
return parseModelString(currentModel || "")
|
||||
}, [currentModel])
|
||||
return parseModelString(currentModel || defaultModel || "")
|
||||
}, [currentModel, defaultModel])
|
||||
|
||||
const iconClass = providerIcons[provider] || providerIcons.openai
|
||||
const hasMultipleModels = availableModels && availableModels.length > 1
|
||||
@@ -52,12 +61,13 @@ export const AIModelIndicator = memo(({ className, onModelChange }: AIModelIndic
|
||||
const modelContent = (
|
||||
<div
|
||||
className={cn(
|
||||
"inline-flex items-center rounded-full border font-medium backdrop-blur-sm transition-colors",
|
||||
"inline-flex shrink-0 items-center rounded-full border font-medium backdrop-blur-sm transition-colors",
|
||||
hasMultipleModels
|
||||
? "hover:bg-material-medium cursor-pointer"
|
||||
? "hover:bg-material-medium cursor-button"
|
||||
: "hover:bg-material-medium/50",
|
||||
"duration-200",
|
||||
"gap-1.5 px-2 py-1 text-xs",
|
||||
"gap-1.5 p-1 text-xs",
|
||||
hasMultipleModels && "px-2",
|
||||
"bg-material-ultra-thin border-border/50",
|
||||
"text-text-secondary",
|
||||
|
||||
@@ -65,7 +75,9 @@ export const AIModelIndicator = memo(({ className, onModelChange }: AIModelIndic
|
||||
)}
|
||||
>
|
||||
<i className={cn("size-3", iconClass)} />
|
||||
<span className="max-w-20 truncate">{modelName}</span>
|
||||
<span className="@md:inline hidden max-w-20 truncate">
|
||||
{AIModelNameMapping[modelName] || modelName}
|
||||
</span>
|
||||
{hasMultipleModels && <i className="i-mingcute-down-line size-3 opacity-60" />}
|
||||
</div>
|
||||
)
|
||||
@@ -81,18 +93,22 @@ export const AIModelIndicator = memo(({ className, onModelChange }: AIModelIndic
|
||||
{availableModels.map((model) => {
|
||||
const { provider: itemProvider, modelName: itemModelName } = parseModelString(model)
|
||||
const itemIconClass = providerIcons[itemProvider] || providerIcons.openai
|
||||
const isSelected = model === currentModel
|
||||
const isSelected = model === (currentModel || defaultModel)
|
||||
|
||||
const handleModelSelect = () => {
|
||||
changeModel(model)
|
||||
onModelChange?.(model)
|
||||
}
|
||||
|
||||
return (
|
||||
<DropdownMenuItem
|
||||
key={model}
|
||||
className="gap-2"
|
||||
onClick={() => onModelChange?.(model)}
|
||||
onClick={handleModelSelect}
|
||||
checked={isSelected}
|
||||
>
|
||||
<i className={cn("size-3", itemIconClass)} />
|
||||
<span className="truncate">{itemModelName}</span>
|
||||
{isSelected && <i className="i-mgc-check-cute-re text-accent ml-auto size-3" />}
|
||||
<span className="truncate">{AIModelNameMapping[itemModelName] || itemModelName}</span>
|
||||
</DropdownMenuItem>
|
||||
)
|
||||
})}
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
/* CSS animations for AISmartSidebar (replacing motion/react) */
|
||||
|
||||
.ai-ambient-bar {
|
||||
transform-origin: right center;
|
||||
transition:
|
||||
width 0.3s ease-out,
|
||||
opacity 0.3s ease-out,
|
||||
transform 0.3s ease-out;
|
||||
}
|
||||
|
||||
@keyframes ai-bar-pulse {
|
||||
0%,
|
||||
100% {
|
||||
transform: scale(1);
|
||||
}
|
||||
50% {
|
||||
transform: scale(1.1);
|
||||
}
|
||||
}
|
||||
|
||||
.ai-ambient-pulse {
|
||||
animation: ai-bar-pulse 2s ease-in-out infinite;
|
||||
}
|
||||
|
||||
.ai-glow-blob {
|
||||
transition:
|
||||
opacity 0.3s cubic-bezier(0.22, 1, 0.36, 1),
|
||||
transform 0.3s cubic-bezier(0.22, 1, 0.36, 1);
|
||||
will-change: transform, opacity;
|
||||
border-radius: 9999px;
|
||||
}
|
||||
|
||||
.ai-prompt-container {
|
||||
opacity: 0;
|
||||
transform: translateX(20px);
|
||||
transition:
|
||||
opacity 0.25s cubic-bezier(0.22, 1, 0.36, 1),
|
||||
transform 0.25s cubic-bezier(0.22, 1, 0.36, 1);
|
||||
}
|
||||
|
||||
.ai-prompt-visible {
|
||||
opacity: 1;
|
||||
transform: translateX(0);
|
||||
}
|
||||
|
||||
@keyframes ai-dot-pulse-kf {
|
||||
0%,
|
||||
100% {
|
||||
transform: scale(1);
|
||||
opacity: 0.7;
|
||||
}
|
||||
50% {
|
||||
transform: scale(1.2);
|
||||
opacity: 1;
|
||||
}
|
||||
}
|
||||
|
||||
.ai-dot-pulse {
|
||||
animation: ai-dot-pulse-kf 2s ease-in-out infinite;
|
||||
}
|
||||
+117
@@ -0,0 +1,117 @@
|
||||
// Replaced motion/react animations with CSS animations
|
||||
import "./AISmartSidebar.css"
|
||||
|
||||
import { Spring } from "@follow/components/constants/spring.js"
|
||||
import { useMousePosition } from "@follow/components/hooks/useMouse.js"
|
||||
import { AnimatePresence, m } from "motion/react"
|
||||
import * as React from "react"
|
||||
import { useEffect, useState } from "react"
|
||||
|
||||
import { setAIPanelVisibility, useAIPanelVisibility } from "~/atoms/settings/ai"
|
||||
|
||||
const AIAmbientSidebar: React.FC<{ onExpand: () => void }> = ({ onExpand }) => {
|
||||
const [intensity, setIntensity] = useState(0)
|
||||
const [showPrompt, setShowPrompt] = useState(false)
|
||||
const isShowPromptRef = React.useRef(false)
|
||||
const mousePosition = useMousePosition()
|
||||
|
||||
useEffect(() => {
|
||||
const rightEdgeDistance = window.innerWidth - mousePosition.x
|
||||
const maxDistance = 500
|
||||
const threshold = 80
|
||||
const showedThreshold = 300
|
||||
const topBoundary = 100
|
||||
|
||||
if (mousePosition.y <= topBoundary) {
|
||||
setIntensity(0)
|
||||
setShowPrompt(false)
|
||||
isShowPromptRef.current = false
|
||||
return
|
||||
}
|
||||
|
||||
if (isShowPromptRef.current && rightEdgeDistance <= showedThreshold) {
|
||||
return
|
||||
}
|
||||
|
||||
if (rightEdgeDistance <= maxDistance) {
|
||||
const newIntensity = Math.max(0, (maxDistance - rightEdgeDistance) / maxDistance)
|
||||
setIntensity(newIntensity)
|
||||
const shouldShow = rightEdgeDistance <= threshold
|
||||
setShowPrompt(shouldShow)
|
||||
isShowPromptRef.current = shouldShow
|
||||
} else {
|
||||
setIntensity(0)
|
||||
setShowPrompt(false)
|
||||
isShowPromptRef.current = false
|
||||
}
|
||||
}, [mousePosition])
|
||||
|
||||
return (
|
||||
<>
|
||||
<div
|
||||
className={`ai-ambient-bar pointer-events-none fixed right-0 top-0 z-40 h-full w-2 ${
|
||||
intensity > 0.3 ? "ai-ambient-pulse" : ""
|
||||
}`}
|
||||
style={{
|
||||
opacity: intensity * 0.8,
|
||||
width: intensity > 0 ? 8 + intensity * 40 : 2,
|
||||
background: `linear-gradient(to left, rgba(255, 92, 0, ${intensity * 0.4}) 0%, rgba(255, 140, 0, ${intensity * 0.3}) 50%, transparent 100%)`,
|
||||
}}
|
||||
/>
|
||||
|
||||
<AnimatePresence>
|
||||
{showPrompt && (
|
||||
<>
|
||||
<m.div
|
||||
initial={{ opacity: 0, scale: 0.5, x: 0 }}
|
||||
animate={{
|
||||
opacity: intensity * 0.6,
|
||||
scale: 0.5 + intensity * 1.5,
|
||||
x: intensity > 0 ? -10 - intensity * 30 : 0,
|
||||
}}
|
||||
exit={{ opacity: 0, scale: 0.5, x: 0 }}
|
||||
transition={Spring.presets.smooth}
|
||||
className="ai-glow-blob pointer-events-none fixed bottom-12 right-0 z-40"
|
||||
style={{
|
||||
opacity: intensity * 0.6,
|
||||
transform: `translateX(${intensity > 0 ? -10 - intensity * 30 : 0}px) scale(${0.5 + intensity * 1.5})`,
|
||||
width: 100,
|
||||
height: 100,
|
||||
background: `radial-gradient(circle, rgba(255, 92, 0, ${intensity * 0.3}) 0%, rgba(255, 140, 0, ${intensity * 0.2}) 40%, transparent 70%)`,
|
||||
}}
|
||||
/>
|
||||
<m.div
|
||||
initial={{ opacity: 0, x: 20 }}
|
||||
animate={{ opacity: 1, x: 0 }}
|
||||
exit={{ opacity: 0, x: 20 }}
|
||||
className="ai-prompt-container ai-prompt-visible fixed bottom-12 right-6 z-50 flex flex-col items-end gap-3"
|
||||
>
|
||||
<div className="bg-background/90 border-folo/30 rounded-2xl border px-4 py-3 backdrop-blur-xl">
|
||||
<div className="text-right">
|
||||
<p className="text-text text-sm font-medium">Ask AI anything</p>
|
||||
<p className="text-text-secondary mt-1 text-xs">
|
||||
Get insights about this article
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
className="border-folo/40 from-folo/20 hover:from-folo/30 rounded-full border bg-gradient-to-r to-red-500/20 px-6 py-2 backdrop-blur-xl transition-all duration-300 hover:to-red-500/30"
|
||||
onClick={onExpand}
|
||||
>
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="from-folo ai-dot-pulse size-2 rounded-full bg-gradient-to-r to-red-500" />
|
||||
<span className="text-text text-sm font-medium">Open AI Chat</span>
|
||||
</div>
|
||||
</button>
|
||||
</m.div>
|
||||
</>
|
||||
)}
|
||||
</AnimatePresence>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
export const AISmartSidebar: React.FC = () =>
|
||||
!useAIPanelVisibility() && <AIAmbientSidebar onExpand={() => setAIPanelVisibility(true)} />
|
||||
@@ -1,23 +1,30 @@
|
||||
import { ActionButton } from "@follow/components/ui/button/index.js"
|
||||
import { cn } from "@follow/utils"
|
||||
import { useAtomValue } from "jotai"
|
||||
import type { ReactNode } from "react"
|
||||
import { useCallback } from "react"
|
||||
import { useTranslation } from "react-i18next"
|
||||
|
||||
import { AIChatPanelStyle, setAIPanelVisibility, useAIChatPanelStyle } from "~/atoms/settings/ai"
|
||||
import { useDialog } from "~/components/ui/modal/stacked/hooks"
|
||||
import { useBlockActions, useChatActions, useCurrentTitle } from "~/modules/ai-chat/store/hooks"
|
||||
import { useSettingModal } from "~/modules/settings/modal/use-setting-modal-hack"
|
||||
|
||||
import { useAIRootState } from "../../store/AIChatContext"
|
||||
import { ChatMoreDropdown } from "./ChatMoreDropdown"
|
||||
import { EditableTitle } from "./EditableTitle"
|
||||
import { TaskReportDropdown } from "./TaskReportDropdown"
|
||||
|
||||
export const ChatHeader = () => {
|
||||
// Base header layout with shared logic inside
|
||||
const ChatHeaderLayout = ({
|
||||
renderActions,
|
||||
}: {
|
||||
renderActions: (ctx: {
|
||||
onNewChatClick: () => void
|
||||
currentTitle: string | undefined
|
||||
onSaveTitle: (newTitle: string) => Promise<void>
|
||||
}) => ReactNode
|
||||
}) => {
|
||||
const currentTitle = useCurrentTitle()
|
||||
|
||||
const settingModalPresent = useSettingModal()
|
||||
const chatActions = useChatActions()
|
||||
const blockActions = useBlockActions()
|
||||
const { ask } = useDialog()
|
||||
const { t } = useTranslation("ai")
|
||||
|
||||
const handleNewChatClick = useCallback(() => {
|
||||
const messages = chatActions.getMessages()
|
||||
@@ -27,7 +34,7 @@ export const ChatHeader = () => {
|
||||
|
||||
chatActions.newChat()
|
||||
blockActions.clearBlocks({ keepSpecialTypes: true })
|
||||
}, [chatActions, currentTitle, ask, t, blockActions])
|
||||
}, [chatActions, currentTitle, blockActions])
|
||||
|
||||
const handleTitleSave = useCallback(
|
||||
async (newTitle: string) => {
|
||||
@@ -36,34 +43,68 @@ export const ChatHeader = () => {
|
||||
[chatActions],
|
||||
)
|
||||
|
||||
const panelStyle = useAIChatPanelStyle()
|
||||
const maskImage = `linear-gradient(to bottom, black 0%, black 75%, transparent 100%)`
|
||||
const isFloating = useAIChatPanelStyle() === AIChatPanelStyle.Floating
|
||||
|
||||
const { isScrolledBeyondThreshold } = useAIRootState()
|
||||
const isScrolledBeyondThresholdValue = useAtomValue(isScrolledBeyondThreshold)
|
||||
|
||||
return (
|
||||
<div className="absolute inset-x-0 top-0 z-[1] h-12">
|
||||
<div
|
||||
className="bg-background/70 backdrop-blur-background absolute inset-0"
|
||||
style={{
|
||||
maskImage,
|
||||
WebkitMaskImage: maskImage,
|
||||
}}
|
||||
/>
|
||||
<div
|
||||
className={cn(
|
||||
"absolute inset-x-0 top-0 z-[1] duration-200",
|
||||
!isFloating && "bg-background data-[scrolled-beyond-threshold=true]:border-b",
|
||||
)}
|
||||
data-scrolled-beyond-threshold={isScrolledBeyondThresholdValue}
|
||||
>
|
||||
<div className="h-entry-header">
|
||||
{isFloating && (
|
||||
<div
|
||||
className="bg-background/70 backdrop-blur-background absolute inset-0"
|
||||
style={{
|
||||
maskImage: `linear-gradient(to bottom, black 0%, black 90%, transparent 100%)`,
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
|
||||
<div className="relative z-10 flex h-full items-center justify-between px-4">
|
||||
<div className="mr-2 flex min-w-0 flex-1 items-center">
|
||||
<EditableTitle title={currentTitle} onSave={handleTitleSave} placeholder="New Chat" />
|
||||
<div className="relative z-10 flex h-full items-center justify-between px-4">
|
||||
<div className="mr-2 flex min-w-0 flex-1 items-center">
|
||||
<EditableTitle title={currentTitle} onSave={handleTitleSave} placeholder="New Chat" />
|
||||
</div>
|
||||
|
||||
{/* Right side - Actions */}
|
||||
<div className="flex items-center gap-2">
|
||||
{renderActions({
|
||||
onNewChatClick: handleNewChatClick,
|
||||
currentTitle,
|
||||
onSaveTitle: handleTitleSave,
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
{/* Right side - Actions */}
|
||||
<div className="flex items-center gap-2">
|
||||
<ActionButton tooltip="New Chat" onClick={handleNewChatClick}>
|
||||
export const ChatHeader = () => {
|
||||
const panelStyle = useAIChatPanelStyle()
|
||||
|
||||
return (
|
||||
<ChatHeaderLayout
|
||||
renderActions={({ onNewChatClick }) => (
|
||||
<>
|
||||
<ActionButton tooltip="New Chat" onClick={onNewChatClick}>
|
||||
<i className="i-mgc-add-cute-re text-text-secondary size-5" />
|
||||
</ActionButton>
|
||||
|
||||
<ActionButton tooltip="AI Settings" onClick={() => settingModalPresent("ai")}>
|
||||
<i className="i-mgc-user-setting-cute-re text-text-secondary size-5" />
|
||||
</ActionButton>
|
||||
<TaskReportDropdown />
|
||||
|
||||
<ChatMoreDropdown />
|
||||
<ChatMoreDropdown
|
||||
triggerElement={
|
||||
<ActionButton tooltip="More">
|
||||
<i className="i-mingcute-more-1-fill text-text-secondary size-5" />
|
||||
</ActionButton>
|
||||
}
|
||||
/>
|
||||
|
||||
{panelStyle === AIChatPanelStyle.Floating && (
|
||||
<>
|
||||
@@ -73,8 +114,34 @@ export const ChatHeader = () => {
|
||||
</ActionButton>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export const ChatPageHeader = () => {
|
||||
return (
|
||||
<ChatHeaderLayout
|
||||
renderActions={({ onNewChatClick }) => (
|
||||
<>
|
||||
<ActionButton tooltip="New Chat" onClick={onNewChatClick}>
|
||||
<i className="i-mgc-add-cute-re text-text-secondary size-5" />
|
||||
</ActionButton>
|
||||
|
||||
<TaskReportDropdown />
|
||||
|
||||
<div className="bg-border mx-2 h-5 w-px" />
|
||||
<ChatMoreDropdown
|
||||
canToggleMode={false}
|
||||
triggerElement={
|
||||
<ActionButton tooltip="More">
|
||||
<i className="i-mingcute-more-1-fill text-text-secondary size-5" />
|
||||
</ActionButton>
|
||||
}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -18,8 +18,9 @@ import { AIModelIndicator } from "./AIModelIndicator"
|
||||
|
||||
const chatInputVariants = cva(
|
||||
[
|
||||
"bg-background focus-within:ring-accent/20 focus-within:border-accent/80 border-border/80",
|
||||
"relative overflow-hidden rounded-2xl border backdrop-blur-xl duration-200 focus-within:ring-2",
|
||||
"bg-mix-background/transparent-8/2 focus-within:ring-accent/20 focus-within:border-accent/80 border-border/80",
|
||||
"relative overflow-hidden rounded-2xl border backdrop-blur-background duration-200 focus-within:ring-2",
|
||||
"z-[1]",
|
||||
],
|
||||
{
|
||||
variants: {
|
||||
@@ -114,7 +115,7 @@ export const ChatInput = memo(({ onSend, variant }: ChatInputProps) => {
|
||||
{/* Context Bar - Always shown, positioned below the input area */}
|
||||
<div className="border-border/20 relative z-10 border-t bg-transparent">
|
||||
<div className="flex items-center justify-between px-4 py-2.5">
|
||||
<div className="flex-1">
|
||||
<div className="min-w-0 flex-1 shrink">
|
||||
<AIChatContextBar
|
||||
className="border-0 bg-transparent p-0"
|
||||
onSendShortcut={(prompt) => onSend(prompt, null)}
|
||||
|
||||
+122
-40
@@ -7,8 +7,8 @@ import { ErrorBoundary } from "@sentry/react"
|
||||
import type { EditorState, LexicalEditor } from "lexical"
|
||||
import { AnimatePresence } from "motion/react"
|
||||
import { nanoid } from "nanoid"
|
||||
import type { FC } from "react"
|
||||
import { Suspense, useEffect, useState } from "react"
|
||||
import type { FC, Ref } from "react"
|
||||
import { Suspense, useEffect, useRef, useState } from "react"
|
||||
import { useEventCallback } from "usehooks-ts"
|
||||
|
||||
import { useAISettingKey } from "~/atoms/settings/ai"
|
||||
@@ -17,6 +17,7 @@ import {
|
||||
AIChatMessage,
|
||||
AIChatWaitingIndicator,
|
||||
} from "~/modules/ai-chat/components/message/AIChatMessage"
|
||||
import { UserChatMessage } from "~/modules/ai-chat/components/message/UserChatMessage"
|
||||
import { useAutoScroll } from "~/modules/ai-chat/hooks/useAutoScroll"
|
||||
import { useLoadMessages } from "~/modules/ai-chat/hooks/useLoadMessages"
|
||||
import { useMainEntryId } from "~/modules/ai-chat/hooks/useMainEntryId"
|
||||
@@ -30,6 +31,8 @@ import {
|
||||
useMessages,
|
||||
} from "~/modules/ai-chat/store/hooks"
|
||||
|
||||
import { useAttachScrollBeyond } from "../../hooks/useAttachScrollBeyond"
|
||||
import type { AIChatContextBlock } from "../../store/types"
|
||||
import { convertLexicalToMarkdown } from "../../utils/lexical-markdown"
|
||||
import { GlobalFileDropZone } from "../file/GlobalFileDropZone"
|
||||
import { AIErrorFallback } from "./AIErrorFallback"
|
||||
@@ -39,7 +42,7 @@ import { WelcomeScreen } from "./WelcomeScreen"
|
||||
|
||||
const SCROLL_BOTTOM_THRESHOLD = 100
|
||||
|
||||
const ChatInterfaceContent = () => {
|
||||
const ChatInterfaceContent = ({ centerInputOnEmpty }: ChatInterfaceProps) => {
|
||||
const hasMessages = useHasMessages()
|
||||
const status = useChatStatus()
|
||||
const chatActions = useChatActions()
|
||||
@@ -64,9 +67,14 @@ const ChatInterfaceContent = () => {
|
||||
|
||||
const [scrollAreaRef, setScrollAreaRef] = useState<HTMLDivElement | null>(null)
|
||||
const [isAtBottom, setIsAtBottom] = useState(true)
|
||||
const [messageContainerMinHeight, setMessageContainerMinHeight] = useState<number | undefined>()
|
||||
const previousMinHeightRef = useRef<number>(0)
|
||||
const messagesContentRef = useRef<HTMLDivElement | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
setIsAtBottom(true)
|
||||
setMessageContainerMinHeight(undefined)
|
||||
previousMinHeightRef.current = 0
|
||||
}, [currentChatId])
|
||||
|
||||
const { isLoading: isLoadingHistory } = useLoadMessages(currentChatId || "", {
|
||||
@@ -114,11 +122,38 @@ const ChatInterfaceContent = () => {
|
||||
}, [scrollAreaRef])
|
||||
|
||||
const blockActions = useBlockActions()
|
||||
|
||||
const scrollHeightBeforeSendingRef = useRef<number>(0)
|
||||
const scrollContainerParentRef = useRef<HTMLDivElement | null>(null)
|
||||
const handleScrollPositioning = useEventCallback(() => {
|
||||
const $scrollContainerParent = scrollContainerParentRef.current
|
||||
if (!scrollAreaRef || !$scrollContainerParent) return
|
||||
|
||||
const parentClientHeight = $scrollContainerParent.clientHeight
|
||||
// Use actual content height captured before send (messages container height), not inflated by minHeight
|
||||
const currentScrollHeight = scrollHeightBeforeSendingRef.current
|
||||
|
||||
// Calculate new minimum height based on actual content height
|
||||
// Use previousMinHeightRef which tracks the real content height, not reserved space
|
||||
const baseHeight = Math.max(previousMinHeightRef.current, currentScrollHeight)
|
||||
const newMinHeight = baseHeight + parentClientHeight - 250
|
||||
|
||||
setMessageContainerMinHeight(newMinHeight)
|
||||
|
||||
// Scroll to the end immediately to position user message at top
|
||||
nextFrame(() => {
|
||||
scrollAreaRef.scrollTo({
|
||||
top: scrollAreaRef.scrollHeight,
|
||||
behavior: "instant",
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
const handleSendMessage = useEventCallback(
|
||||
(message: string | EditorState, editor: LexicalEditor | null) => {
|
||||
resetScrollState()
|
||||
|
||||
const blocks = [] as any[]
|
||||
const blocks = [] as AIChatContextBlock[]
|
||||
|
||||
for (const block of blockActions.getBlocks()) {
|
||||
if (block.type === "fileAttachment" && block.attachment.serverUrl) {
|
||||
@@ -159,12 +194,19 @@ const ChatInterfaceContent = () => {
|
||||
})
|
||||
}
|
||||
|
||||
// Capture actual content height (messages container), not including reserved minHeight
|
||||
scrollHeightBeforeSendingRef.current = messagesContentRef.current?.scrollHeight ?? 0
|
||||
chatActions.sendMessage({
|
||||
parts,
|
||||
role: "user",
|
||||
id: nanoid(),
|
||||
})
|
||||
tracker.aiChatMessageSent()
|
||||
|
||||
nextFrame(() => {
|
||||
// Calculate and adjust scroll positioning immediately
|
||||
handleScrollPositioning()
|
||||
})
|
||||
},
|
||||
)
|
||||
|
||||
@@ -172,36 +214,57 @@ const ChatInterfaceContent = () => {
|
||||
if (status === "submitted") {
|
||||
resetScrollState()
|
||||
}
|
||||
}, [status, resetScrollState])
|
||||
|
||||
// When AI response is complete, update the reference height but keep the container height unchanged
|
||||
// This avoids CLS while ensuring next calculation is based on actual content
|
||||
if (status === "ready" && scrollAreaRef && messagesContentRef.current) {
|
||||
// Update the reference to actual content height for next calculation (use messages container)
|
||||
previousMinHeightRef.current = messagesContentRef.current.scrollHeight
|
||||
// Keep the current minHeight unchanged to avoid CLS
|
||||
}
|
||||
}, [status, resetScrollState, messageContainerMinHeight, scrollAreaRef])
|
||||
|
||||
const shouldShowScrollToBottom = hasMessages && !isAtBottom && !isLoadingHistory
|
||||
|
||||
const { handleScroll } = useAttachScrollBeyond()
|
||||
return (
|
||||
<GlobalFileDropZone className="flex size-full flex-col">
|
||||
<div className="flex min-h-0 flex-1 flex-col">
|
||||
<GlobalFileDropZone className="@container flex size-full flex-col">
|
||||
<div className="flex min-h-0 flex-1 flex-col" ref={scrollContainerParentRef}>
|
||||
<AnimatePresence>
|
||||
{!hasMessages && !isLoadingHistory ? (
|
||||
<WelcomeScreen onSend={handleSendMessage} />
|
||||
<WelcomeScreen onSend={handleSendMessage} centerInputOnEmpty={centerInputOnEmpty} />
|
||||
) : (
|
||||
<ScrollArea
|
||||
flex
|
||||
scrollbarClassName="mb-40 mt-12"
|
||||
ref={setScrollAreaRef}
|
||||
rootClassName="flex-1"
|
||||
viewportClassName={cn("pt-12 pb-32", error && "pb-48")}
|
||||
>
|
||||
{isLoadingHistory ? (
|
||||
<div className="flex min-h-96 items-center justify-center">
|
||||
<i className="i-mgc-loading-3-cute-re text-text size-8 animate-spin" />
|
||||
</div>
|
||||
) : (
|
||||
<div className="mx-auto w-full max-w-4xl px-6 py-8">
|
||||
<Messages />
|
||||
<>
|
||||
<ScrollArea
|
||||
onScroll={handleScroll}
|
||||
flex
|
||||
scrollbarClassName="mb-40 mt-12"
|
||||
ref={setScrollAreaRef}
|
||||
rootClassName="flex-1"
|
||||
viewportClassName={cn("pt-12 pb-32", error && "pb-48")}
|
||||
>
|
||||
{isLoadingHistory ? (
|
||||
<div className="flex min-h-96 items-center justify-center">
|
||||
<i className="i-mgc-loading-3-cute-re text-text size-8 animate-spin" />
|
||||
</div>
|
||||
) : (
|
||||
<div
|
||||
className="mx-auto w-full max-w-4xl px-6 py-8"
|
||||
style={{
|
||||
minHeight: messageContainerMinHeight
|
||||
? `${messageContainerMinHeight}px`
|
||||
: undefined,
|
||||
}}
|
||||
>
|
||||
<Messages contentRef={messagesContentRef} />
|
||||
|
||||
{(status === "submitted" || status === "streaming") && <AIChatWaitingIndicator />}
|
||||
</div>
|
||||
)}
|
||||
</ScrollArea>
|
||||
{(status === "submitted" || status === "streaming") && (
|
||||
<AIChatWaitingIndicator />
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</ScrollArea>
|
||||
</>
|
||||
)}
|
||||
</AnimatePresence>
|
||||
</div>
|
||||
@@ -212,8 +275,8 @@ const ChatInterfaceContent = () => {
|
||||
type="button"
|
||||
onClick={() => resetScrollState()}
|
||||
className={cn(
|
||||
"center bg-background group flex size-8 items-center gap-2 rounded-full border transition-all",
|
||||
"border-border/40",
|
||||
"center bg-mix-background/transparent-8/2 backdrop-blur-background group flex size-8 items-center gap-2 rounded-full border transition-all",
|
||||
"border-border",
|
||||
"hover:border-border/60 active:scale-[0.98]",
|
||||
)}
|
||||
>
|
||||
@@ -223,35 +286,54 @@ const ChatInterfaceContent = () => {
|
||||
)}
|
||||
|
||||
<div
|
||||
className={clsx(
|
||||
"absolute mx-auto duration-200 ease-in-out",
|
||||
className={cn(
|
||||
"absolute mx-auto duration-500 ease-in-out",
|
||||
hasMessages && "inset-x-0 bottom-0 max-w-4xl px-6 pb-6",
|
||||
!hasMessages && "inset-x-0 bottom-0 max-w-3xl px-6 pb-6",
|
||||
!hasMessages && "inset-x-0 bottom-0 max-w-3xl px-6 pb-6 duration-200",
|
||||
centerInputOnEmpty &&
|
||||
!hasMessages &&
|
||||
"bottom-1/2 translate-y-[calc(100%+1rem)] duration-200",
|
||||
)}
|
||||
>
|
||||
{error && <CollapsibleError error={error} />}
|
||||
<ChatInput onSend={handleSendMessage} variant={!hasMessages ? "minimal" : "default"} />
|
||||
{!centerInputOnEmpty && (
|
||||
<div
|
||||
className="bg-background backdrop-blur-background absolute inset-x-0 bottom-0 h-28"
|
||||
style={{ maskImage: "linear-gradient(to bottom, transparent, black)" }}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</GlobalFileDropZone>
|
||||
)
|
||||
}
|
||||
|
||||
export const ChatInterface = () => (
|
||||
interface ChatInterfaceProps {
|
||||
centerInputOnEmpty?: boolean
|
||||
}
|
||||
export const ChatInterface = (props: ChatInterfaceProps) => (
|
||||
<ErrorBoundary fallback={AIErrorFallback}>
|
||||
<ChatInterfaceContent />
|
||||
<ChatInterfaceContent {...props} />
|
||||
</ErrorBoundary>
|
||||
)
|
||||
|
||||
const Messages: FC = () => {
|
||||
const Messages: FC<{ contentRef?: Ref<HTMLDivElement> }> = ({ contentRef }) => {
|
||||
const messages = useMessages()
|
||||
|
||||
return (
|
||||
<div className="relative flex min-w-0 flex-1 flex-col">
|
||||
{messages.map((message) => (
|
||||
<Suspense key={message.id}>
|
||||
<AIChatMessage message={message} />
|
||||
</Suspense>
|
||||
))}
|
||||
<div ref={contentRef} className="relative flex min-w-0 flex-1 flex-col">
|
||||
{messages.map((message, index) => {
|
||||
const isLastMessage = index === messages.length - 1
|
||||
return (
|
||||
<Suspense key={message.id}>
|
||||
{message.role === "user" ? (
|
||||
<UserChatMessage message={message} />
|
||||
) : (
|
||||
<AIChatMessage message={message} isLastMessage={isLastMessage} />
|
||||
)}
|
||||
</Suspense>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
+51
-19
@@ -1,9 +1,13 @@
|
||||
import { ActionButton } from "@follow/components/ui/button/index.js"
|
||||
import { useCallback, useState } from "react"
|
||||
import { startTransition, useCallback, useRef, useState } from "react"
|
||||
import { useTranslation } from "react-i18next"
|
||||
import { toast } from "sonner"
|
||||
|
||||
import { AIChatPanelStyle, setAIChatPanelStyle, useAIChatPanelStyle } from "~/atoms/settings/ai"
|
||||
import {
|
||||
AIChatPanelStyle,
|
||||
setAIChatPanelStyle,
|
||||
setAIPanelVisibility,
|
||||
useAIChatPanelStyle,
|
||||
} from "~/atoms/settings/ai"
|
||||
import { RelativeDay } from "~/components/ui/datetime"
|
||||
import {
|
||||
DropdownMenu,
|
||||
@@ -20,11 +24,21 @@ import { useChatHistory } from "~/modules/ai-chat/hooks/useChatHistory"
|
||||
import { AIPersistService } from "~/modules/ai-chat/services"
|
||||
import { useChatActions, useCurrentChatId, useCurrentTitle } from "~/modules/ai-chat/store/hooks"
|
||||
import { downloadMarkdown, exportChatToMarkdown } from "~/modules/ai-chat/utils/export"
|
||||
import { useSettingModal } from "~/modules/settings/modal/use-setting-modal-hack"
|
||||
|
||||
export const ChatMoreDropdown = () => {
|
||||
export const ChatMoreDropdown = ({
|
||||
triggerElement,
|
||||
asChild = true,
|
||||
canToggleMode = true,
|
||||
}: {
|
||||
triggerElement: React.ReactNode
|
||||
asChild?: boolean
|
||||
canToggleMode?: boolean
|
||||
}) => {
|
||||
const currentTitle = useCurrentTitle()
|
||||
const currentChatId = useCurrentChatId()
|
||||
const panelStyle = useAIChatPanelStyle()
|
||||
const settingModalPresent = useSettingModal()
|
||||
|
||||
const chatActions = useChatActions()
|
||||
const { t } = useTranslation("ai")
|
||||
@@ -99,13 +113,13 @@ export const ChatMoreDropdown = () => {
|
||||
setAIChatPanelStyle(newStyle)
|
||||
}, [panelStyle])
|
||||
|
||||
const handleCloseSidebar = useRef(() => {
|
||||
setAIPanelVisibility(false)
|
||||
}).current
|
||||
|
||||
return (
|
||||
<DropdownMenu onOpenChange={handleDropdownOpen}>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<ActionButton tooltip="More">
|
||||
<i className="i-mingcute-more-1-fill size-5 opacity-80" />
|
||||
</ActionButton>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuTrigger asChild={asChild}>{triggerElement}</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end" className="w-56">
|
||||
{/* Chat History Submenu */}
|
||||
<DropdownMenuSub>
|
||||
@@ -126,7 +140,7 @@ export const ChatMoreDropdown = () => {
|
||||
{sessions.map((session) => (
|
||||
<DropdownMenuItem
|
||||
key={session.chatId}
|
||||
onClick={() => chatActions.switchToChat(session.chatId)}
|
||||
onClick={() => startTransition(() => chatActions.switchToChat(session.chatId))}
|
||||
className="group flex h-12 cursor-pointer items-center justify-between rounded-md px-2 py-3"
|
||||
>
|
||||
<div className="min-w-0 flex-1">
|
||||
@@ -171,17 +185,35 @@ export const ChatMoreDropdown = () => {
|
||||
</DropdownMenuItem>
|
||||
|
||||
<DropdownMenuSeparator />
|
||||
{canToggleMode && (
|
||||
<>
|
||||
<DropdownMenuItem onClick={handleToggleMode}>
|
||||
<i
|
||||
className={`mr-2 size-4 ${panelStyle === AIChatPanelStyle.Fixed ? "i-mingcute-rectangle-vertical-line" : "i-mingcute-layout-right-line"}`}
|
||||
/>
|
||||
<span>
|
||||
{panelStyle === AIChatPanelStyle.Fixed
|
||||
? "Switch to Floating Panel"
|
||||
: "Switch to Fixed Panel"}
|
||||
</span>
|
||||
</DropdownMenuItem>
|
||||
</>
|
||||
)}
|
||||
|
||||
<DropdownMenuItem onClick={handleToggleMode}>
|
||||
<i
|
||||
className={`mr-2 size-4 ${panelStyle === AIChatPanelStyle.Fixed ? "i-mingcute-rectangle-vertical-line" : "i-mingcute-layout-right-line"}`}
|
||||
/>
|
||||
<span>
|
||||
{panelStyle === AIChatPanelStyle.Fixed
|
||||
? "Switch to Floating Panel"
|
||||
: "Switch to Fixed Panel"}
|
||||
</span>
|
||||
<DropdownMenuItem onClick={() => settingModalPresent("ai")}>
|
||||
<i className="i-mgc-settings-1-cute-re mr-2 size-4" />
|
||||
<span>AI Settings</span>
|
||||
</DropdownMenuItem>
|
||||
|
||||
{panelStyle !== AIChatPanelStyle.Floating && (
|
||||
<>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem onClick={handleCloseSidebar}>
|
||||
<i className="i-mgc-close-cute-re mr-2 size-4" />
|
||||
<span>Close Sidebar</span>
|
||||
</DropdownMenuItem>
|
||||
</>
|
||||
)}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
)
|
||||
|
||||
+34
-51
@@ -1,7 +1,6 @@
|
||||
import { Spring } from "@follow/components/constants/spring.js"
|
||||
import { ScrollArea } from "@follow/components/ui/scroll-area/ScrollArea.js"
|
||||
import { cn } from "@follow/utils"
|
||||
import { ExceptionCodeMap } from "@follow-app/client-sdk"
|
||||
import { m } from "motion/react"
|
||||
import * as React from "react"
|
||||
|
||||
import { useI18n } from "~/hooks/common/useI18n"
|
||||
@@ -12,6 +11,7 @@ interface CollapsibleErrorProps {
|
||||
className?: string
|
||||
collapsedHeight?: string
|
||||
icon?: string
|
||||
expandedMaxHeight?: string
|
||||
}
|
||||
|
||||
interface ErrorData {
|
||||
@@ -27,6 +27,7 @@ export const CollapsibleError: React.FC<CollapsibleErrorProps> = ({
|
||||
className,
|
||||
collapsedHeight = "48px",
|
||||
icon = "i-mgc-alert-cute-fi",
|
||||
expandedMaxHeight = "240px",
|
||||
}) => {
|
||||
const [isExpanded, setIsExpanded] = React.useState(false)
|
||||
const t = useI18n()
|
||||
@@ -159,60 +160,42 @@ export const CollapsibleError: React.FC<CollapsibleErrorProps> = ({
|
||||
onMouseEnter={() => setIsExpanded(true)}
|
||||
onMouseLeave={() => setIsExpanded(false)}
|
||||
>
|
||||
<m.div
|
||||
initial={false}
|
||||
animate={{
|
||||
height: isExpanded ? "auto" : collapsedHeight,
|
||||
}}
|
||||
transition={Spring.presets.snappy}
|
||||
className="overflow-hidden"
|
||||
<div
|
||||
className={
|
||||
"border-red/20 shadow-red/5 dark:shadow-red/10 backdrop-blur-background bg-mix-red-20 relative overflow-hidden rounded-xl transition-all duration-200"
|
||||
}
|
||||
>
|
||||
{/* Collapsed Content */}
|
||||
<div
|
||||
className={cn(
|
||||
"bg-red/5 border-red/20 shadow-red/5 dark:shadow-red/10 relative overflow-hidden rounded-xl backdrop-blur-2xl transition-all duration-200",
|
||||
"group-hover:bg-red/10 group-hover:border-red/30",
|
||||
)}
|
||||
className="relative z-10 flex items-center gap-3 p-3"
|
||||
style={{ minHeight: collapsedHeight }}
|
||||
>
|
||||
{/* Glass effect overlay */}
|
||||
<div className="from-red/5 absolute inset-0 bg-gradient-to-r to-transparent" />
|
||||
|
||||
{/* Collapsed Content */}
|
||||
<div className="relative z-10 flex items-center gap-3 p-3">
|
||||
<m.div
|
||||
transition={{ duration: 0.2 }}
|
||||
className="bg-red/20 flex size-6 flex-shrink-0 items-center justify-center rounded-full"
|
||||
>
|
||||
<i className={cn(icon, "text-red size-3")} />
|
||||
</m.div>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="text-red text-sm font-medium">{getErrorTitle()}</div>
|
||||
</div>
|
||||
<m.span
|
||||
animate={{
|
||||
opacity: isExpanded ? 0 : 1,
|
||||
scale: isExpanded ? 0.8 : 1,
|
||||
}}
|
||||
transition={{ duration: 0.15 }}
|
||||
className="text-text-tertiary text-xs"
|
||||
>
|
||||
hover to expand
|
||||
</m.span>
|
||||
<div className="bg-red/20 flex size-6 flex-shrink-0 items-center justify-center rounded-full transition-colors duration-200">
|
||||
<i className={cn(icon, "text-red size-3")} />
|
||||
</div>
|
||||
|
||||
{/* Expanded Content */}
|
||||
<m.div
|
||||
animate={{
|
||||
opacity: isExpanded ? 1 : 0,
|
||||
height: isExpanded ? "auto" : 0,
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="text-red text-sm font-medium">{getErrorTitle()}</div>
|
||||
</div>
|
||||
<span
|
||||
className="text-text-tertiary text-xs transition-all duration-150"
|
||||
style={{
|
||||
opacity: isExpanded ? 0 : 1,
|
||||
transform: isExpanded ? "scale(0.95)" : "scale(1)",
|
||||
}}
|
||||
transition={{
|
||||
duration: 0.2,
|
||||
ease: "easeOut",
|
||||
}}
|
||||
className="overflow-hidden"
|
||||
>
|
||||
hover to expand
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{/* Expanded Content */}
|
||||
<div
|
||||
className="overflow-hidden transition-[max-height,opacity] duration-200 ease-out"
|
||||
style={{ maxHeight: isExpanded ? expandedMaxHeight : "0px", opacity: isExpanded ? 1 : 0 }}
|
||||
aria-hidden={!isExpanded}
|
||||
>
|
||||
<ScrollArea focusable={false} viewportProps={{ style: { maxHeight: expandedMaxHeight } }}>
|
||||
<div className="border-red/20 bg-red/5 border-t px-3 pb-3">
|
||||
<div className="text-red/80 bg-red/10 mt-2 rounded-md p-3 text-xs leading-relaxed">
|
||||
<div className="text-red/80 bg-red/10 mt-2 cursor-text select-text break-all rounded-md p-3 text-xs leading-relaxed">
|
||||
{displayMessage as string}
|
||||
</div>
|
||||
{contextualInfo && (
|
||||
@@ -221,9 +204,9 @@ export const CollapsibleError: React.FC<CollapsibleErrorProps> = ({
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</m.div>
|
||||
</ScrollArea>
|
||||
</div>
|
||||
</m.div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
+227
@@ -0,0 +1,227 @@
|
||||
import { ActionButton } from "@follow/components/ui/button/index.js"
|
||||
import type { AIChatSession } from "@follow-app/client-sdk"
|
||||
import type { ReactElement } from "react"
|
||||
import { useCallback, useMemo, useState } from "react"
|
||||
import { useTranslation } from "react-i18next"
|
||||
import { toast } from "sonner"
|
||||
|
||||
import { RelativeDay } from "~/components/ui/datetime"
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuTrigger,
|
||||
} from "~/components/ui/dropdown-menu/dropdown-menu"
|
||||
import { useDialog, useModalStack } from "~/components/ui/modal/stacked/hooks"
|
||||
import { useChatActions, useCurrentChatId } from "~/modules/ai-chat/store/hooks"
|
||||
import { AIChatSessionService } from "~/modules/ai-chat-session"
|
||||
import {
|
||||
useAIChatSessionListQuery,
|
||||
useDeleteAIChatSessionMutation,
|
||||
} from "~/modules/ai-chat-session/query"
|
||||
import { AITaskModal, useCanCreateNewAITask } from "~/modules/ai-task"
|
||||
|
||||
import { AIPersistService } from "../../services"
|
||||
|
||||
interface TaskReportDropdownProps {
|
||||
triggerElement?: ReactElement
|
||||
asChild?: boolean
|
||||
}
|
||||
|
||||
interface SessionItemProps {
|
||||
session: AIChatSession
|
||||
onClick?: () => void
|
||||
onDelete?: (e: React.MouseEvent) => void
|
||||
isLoading?: boolean
|
||||
}
|
||||
|
||||
// Helper to determine if a session has unread messages
|
||||
const isSessionUnread = (session: AIChatSession): boolean => {
|
||||
if (!session.lastSeenAt || !session.updatedAt) return false
|
||||
return new Date(session.updatedAt) > new Date(session.lastSeenAt)
|
||||
}
|
||||
|
||||
const SessionItem = ({ session, onClick, onDelete, isLoading }: SessionItemProps) => {
|
||||
return (
|
||||
<DropdownMenuItem
|
||||
onClick={onClick}
|
||||
className={`group relative ${onClick ? "cursor-pointer" : "cursor-default"}`}
|
||||
>
|
||||
<div className="flex min-w-0 flex-1 justify-between">
|
||||
<div className="flex min-w-0 flex-1 items-center gap-2">
|
||||
<p className="mb-0.5 truncate font-medium">{session.title || "Untitled Chat"}</p>
|
||||
</div>
|
||||
<div className="relative flex min-w-0 items-center">
|
||||
<p className="text-text-secondary ml-2 shrink-0 truncate text-xs">
|
||||
<RelativeDay date={new Date(session.createdAt)} />
|
||||
</p>
|
||||
{onDelete && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onDelete}
|
||||
className="bg-accent absolute inset-y-0 right-0 flex items-center px-2 py-1 text-white opacity-0 shadow-lg backdrop-blur-sm group-data-[highlighted]:text-white group-data-[highlighted]:opacity-100"
|
||||
disabled={isLoading}
|
||||
>
|
||||
{isLoading ? (
|
||||
<i className="i-mgc-loading-3-cute-re size-4 animate-spin" />
|
||||
) : (
|
||||
<i className="i-mgc-delete-2-cute-re size-4" />
|
||||
)}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</DropdownMenuItem>
|
||||
)
|
||||
}
|
||||
|
||||
const EmptyState = () => {
|
||||
return (
|
||||
<div className="flex flex-col items-center py-8 text-center">
|
||||
<i className="i-mgc-calendar-time-add-cute-re text-text-secondary mb-2 block size-8" />
|
||||
<p className="text-text-secondary text-sm">All task reports read</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export const TaskReportDropdown = ({ triggerElement, asChild = true }: TaskReportDropdownProps) => {
|
||||
const sessions = useAIChatSessionListQuery()
|
||||
const currentChatId = useCurrentChatId()
|
||||
const chatActions = useChatActions()
|
||||
const deleteSessionMutation = useDeleteAIChatSessionMutation()
|
||||
const { ask } = useDialog()
|
||||
const { t } = useTranslation("ai")
|
||||
const [loadingChatId, setLoadingChatId] = useState<string | null>(null)
|
||||
|
||||
// Only keep unread sessions for display
|
||||
const unreadSessions = useMemo(
|
||||
() => (sessions || []).filter((s) => isSessionUnread(s)),
|
||||
[sessions],
|
||||
)
|
||||
|
||||
const hasUnreadSessions = unreadSessions.length > 0
|
||||
|
||||
const { present } = useModalStack()
|
||||
const canCreateNewTask = useCanCreateNewAITask()
|
||||
const handleScheduleActionClick = () => {
|
||||
if (!canCreateNewTask) {
|
||||
toast.error("Please remove an existing task before creating a new one.")
|
||||
return
|
||||
}
|
||||
present({
|
||||
title: "New AI Task",
|
||||
canClose: true,
|
||||
content: () => <AITaskModal showSettingsTip />,
|
||||
})
|
||||
}
|
||||
|
||||
const handleSessionSelect = useCallback(
|
||||
async (session: AIChatSession) => {
|
||||
if (session.chatId === currentChatId) return
|
||||
try {
|
||||
await AIChatSessionService.fetchAndPersistMessages(session)
|
||||
} catch (e) {
|
||||
console.error("Failed to sync chat session messages:", e)
|
||||
toast.error("Failed to load chat messages")
|
||||
}
|
||||
chatActions.switchToChat(session.chatId)
|
||||
},
|
||||
[chatActions, currentChatId],
|
||||
)
|
||||
|
||||
const handleDeleteSession = useCallback(
|
||||
async (chatId: string, e: React.MouseEvent) => {
|
||||
e.stopPropagation()
|
||||
e.preventDefault()
|
||||
|
||||
const session = sessions?.find((s) => s.chatId === chatId)
|
||||
if (!session) return
|
||||
|
||||
const confirm = await ask({
|
||||
title: t("delete_chat"),
|
||||
message: t("delete_chat_message", { title: session.title || "Untitled Chat" }),
|
||||
variant: "danger",
|
||||
})
|
||||
|
||||
if (!confirm) return
|
||||
|
||||
setLoadingChatId(chatId)
|
||||
try {
|
||||
await Promise.all([
|
||||
deleteSessionMutation.mutateAsync({ chatId }),
|
||||
AIPersistService.deleteSession(chatId),
|
||||
])
|
||||
toast.success(t("delete_chat_success"))
|
||||
|
||||
if (chatId === currentChatId) {
|
||||
chatActions.newChat()
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Failed to delete session:", error)
|
||||
toast.error(t("delete_chat_error"))
|
||||
} finally {
|
||||
setLoadingChatId(null)
|
||||
}
|
||||
},
|
||||
[sessions, ask, t, currentChatId, chatActions, deleteSessionMutation],
|
||||
)
|
||||
|
||||
const defaultTrigger = (
|
||||
<ActionButton tooltip="Task Reports" className="relative">
|
||||
<i className="i-mgc-calendar-time-add-cute-re text-text-secondary size-5" />
|
||||
{hasUnreadSessions && (
|
||||
<span
|
||||
className="bg-accent absolute right-1 top-1 block size-2 rounded-full shadow-[0_0_0_2px_var(--color-bg-default)] dark:shadow-[0_0_0_2px_var(--color-bg-default)]"
|
||||
aria-label="Unread task reports"
|
||||
/>
|
||||
)}
|
||||
</ActionButton>
|
||||
)
|
||||
|
||||
return (
|
||||
<DropdownMenu>
|
||||
{asChild ? (
|
||||
<DropdownMenuTrigger asChild={asChild}>
|
||||
{triggerElement || defaultTrigger}
|
||||
</DropdownMenuTrigger>
|
||||
) : (
|
||||
<DropdownMenuTrigger className="relative">
|
||||
{triggerElement || defaultTrigger}
|
||||
{hasUnreadSessions && triggerElement && (
|
||||
<span
|
||||
className="bg-accent absolute right-1 top-1 block size-2 rounded-full shadow-[0_0_0_2px_var(--color-bg-default)] dark:shadow-[0_0_0_2px_var(--color-bg-default)]"
|
||||
aria-label="Unread task reports"
|
||||
/>
|
||||
)}
|
||||
</DropdownMenuTrigger>
|
||||
)}
|
||||
|
||||
<DropdownMenuContent align="end" className="w-80">
|
||||
{unreadSessions.length > 0 ? (
|
||||
unreadSessions.map((session) => (
|
||||
<SessionItem
|
||||
key={session.chatId}
|
||||
session={session}
|
||||
onClick={() => handleSessionSelect(session)}
|
||||
onDelete={(e) => handleDeleteSession(session.chatId, e)}
|
||||
isLoading={loadingChatId === session.chatId}
|
||||
/>
|
||||
))
|
||||
) : (
|
||||
<EmptyState />
|
||||
)}
|
||||
|
||||
{canCreateNewTask && (
|
||||
<>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem onClick={handleScheduleActionClick}>
|
||||
<i className="i-mgc-add-cute-re mr-2 size-4" />
|
||||
New Task
|
||||
</DropdownMenuItem>
|
||||
</>
|
||||
)}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
)
|
||||
}
|
||||
+26
-11
@@ -1,3 +1,6 @@
|
||||
import { Folo } from "@follow/components/icons/folo.js"
|
||||
import { ScrollArea } from "@follow/components/ui/scroll-area/ScrollArea.js"
|
||||
import { clsx } from "@follow/utils"
|
||||
import type { EditorState, LexicalEditor } from "lexical"
|
||||
import { AnimatePresence, m } from "motion/react"
|
||||
import { useTranslation } from "react-i18next"
|
||||
@@ -5,14 +8,16 @@ import { useTranslation } from "react-i18next"
|
||||
import { useAISettingValue } from "~/atoms/settings/ai"
|
||||
import { AISpline } from "~/modules/ai-chat/components/3d-models/AISpline"
|
||||
|
||||
import { useAttachScrollBeyond } from "../../hooks/useAttachScrollBeyond"
|
||||
import { useMainEntryId } from "../../hooks/useMainEntryId"
|
||||
import { DefaultWelcomeContent, EntrySummaryCard } from "../welcome"
|
||||
|
||||
interface WelcomeScreenProps {
|
||||
onSend: (message: EditorState | string, editor: LexicalEditor | null) => void
|
||||
centerInputOnEmpty?: boolean
|
||||
}
|
||||
|
||||
export const WelcomeScreen = ({ onSend }: WelcomeScreenProps) => {
|
||||
export const WelcomeScreen = ({ onSend, centerInputOnEmpty }: WelcomeScreenProps) => {
|
||||
const { t } = useTranslation("ai")
|
||||
const aiSettings = useAISettingValue()
|
||||
const mainEntryId = useMainEntryId()
|
||||
@@ -20,9 +25,16 @@ export const WelcomeScreen = ({ onSend }: WelcomeScreenProps) => {
|
||||
const hasEntryContext = !!mainEntryId
|
||||
const enabledShortcuts = aiSettings.shortcuts?.filter((shortcut) => shortcut.enabled) || []
|
||||
|
||||
const { handleScroll } = useAttachScrollBeyond()
|
||||
return (
|
||||
<div className="flex flex-1 flex-col items-center px-6 pb-32">
|
||||
<div className="flex w-full max-w-2xl flex-1 flex-col justify-center space-y-8">
|
||||
<ScrollArea
|
||||
rootClassName="flex min-h-0 flex-1"
|
||||
viewportClassName="px-6 pt-24 flex min-h-0 grow"
|
||||
scrollbarClassName="mb-40 mt-12"
|
||||
flex
|
||||
onScroll={handleScroll}
|
||||
>
|
||||
<div className="mx-auto flex w-full flex-1 flex-col justify-center space-y-8 pb-52">
|
||||
{/* Header Section - Always Present */}
|
||||
<m.div
|
||||
initial={{ opacity: 0, y: -20 }}
|
||||
@@ -33,7 +45,9 @@ export const WelcomeScreen = ({ onSend }: WelcomeScreenProps) => {
|
||||
<AISpline />
|
||||
</div>
|
||||
<div className="flex flex-col gap-2">
|
||||
<h1 className="text-text text-2xl font-semibold">{APP_NAME} AI</h1>
|
||||
<h1 className="text-text flex items-center justify-center gap-2 text-2xl font-semibold">
|
||||
<Folo className="size-11" /> AI
|
||||
</h1>
|
||||
<p className="text-text-secondary text-balance text-sm">
|
||||
{hasEntryContext
|
||||
? t("welcome_description_contextual", {
|
||||
@@ -45,14 +59,15 @@ export const WelcomeScreen = ({ onSend }: WelcomeScreenProps) => {
|
||||
</m.div>
|
||||
|
||||
{/* Dynamic Content Area */}
|
||||
<div className="relative flex items-start justify-center">
|
||||
<div
|
||||
className={clsx(
|
||||
"relative flex items-start justify-center",
|
||||
centerInputOnEmpty && "absolute bottom-0 translate-y-40",
|
||||
)}
|
||||
>
|
||||
<AnimatePresence mode="wait">
|
||||
{hasEntryContext ? (
|
||||
<EntrySummaryCard
|
||||
key="entry-summary"
|
||||
entryId={mainEntryId}
|
||||
onSend={(message) => onSend(message, null)}
|
||||
/>
|
||||
<EntrySummaryCard key="entry-summary" entryId={mainEntryId} />
|
||||
) : (
|
||||
<DefaultWelcomeContent
|
||||
key="default-welcome"
|
||||
@@ -63,6 +78,6 @@ export const WelcomeScreen = ({ onSend }: WelcomeScreenProps) => {
|
||||
</AnimatePresence>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</ScrollArea>
|
||||
)
|
||||
}
|
||||
|
||||
+58
-145
@@ -1,21 +1,18 @@
|
||||
import { createDefaultLexicalEditor } from "@follow/components/ui/lexical-rich-editor/editor.js"
|
||||
import { cn, stopPropagation, thenable } from "@follow/utils"
|
||||
import type { UIDataTypes, UIMessage } from "ai"
|
||||
import type { LexicalEditor, SerializedEditorState } from "lexical"
|
||||
import { stopPropagation, thenable } from "@follow/utils"
|
||||
import type { LexicalEditor } from "lexical"
|
||||
import { m } from "motion/react"
|
||||
import * as React from "react"
|
||||
import { toast } from "sonner"
|
||||
|
||||
import { copyToClipboard } from "~/lib/clipboard"
|
||||
import { useEditingMessageId, useSetEditingMessageId } from "~/modules/ai-chat/atoms/session"
|
||||
import { useChatActions } from "~/modules/ai-chat/store/hooks"
|
||||
import type { BizUIMetadata, BizUITools } from "~/modules/ai-chat/store/types"
|
||||
import type { BizUIMessage } from "~/modules/ai-chat/store/types"
|
||||
|
||||
import { MentionPlugin } from "../../editor"
|
||||
import type { RichTextPart } from "../../types/ChatSession"
|
||||
import { convertLexicalToMarkdown } from "../../utils/lexical-markdown"
|
||||
import { AIMessageParts } from "./AIMessageParts"
|
||||
import { EditableMessage } from "./EditableMessage"
|
||||
import { TokenUsagePill } from "./TokenUsagePill"
|
||||
|
||||
export interface ChatMessage {
|
||||
id: string
|
||||
@@ -25,32 +22,13 @@ export interface ChatMessage {
|
||||
}
|
||||
|
||||
interface AIChatMessageProps {
|
||||
message: UIMessage<BizUIMetadata, UIDataTypes, BizUITools>
|
||||
onEdit?: (messageId: string) => void
|
||||
streaming?: boolean
|
||||
message: BizUIMessage
|
||||
isLastMessage: boolean
|
||||
}
|
||||
|
||||
export const AIChatMessage: React.FC<AIChatMessageProps> = React.memo(({ message }) => {
|
||||
if (message.parts.length === 0) {
|
||||
throw thenable
|
||||
}
|
||||
const chatActions = useChatActions()
|
||||
|
||||
const messageId = message.id
|
||||
const [isHovered, setIsHovered] = React.useState(false)
|
||||
const editingMessageId = useEditingMessageId()
|
||||
const setEditingMessageId = useSetEditingMessageId()
|
||||
|
||||
const isEditing = editingMessageId === messageId
|
||||
const isUserMessage = message.role === "user"
|
||||
|
||||
const handleEdit = React.useCallback(() => {
|
||||
if (isUserMessage) {
|
||||
setEditingMessageId(messageId)
|
||||
}
|
||||
}, [isUserMessage, messageId, setEditingMessageId])
|
||||
|
||||
const getMessageMarkdownFormat = React.useCallback(() => {
|
||||
// Utility function for converting message to markdown
|
||||
const useMessageMarkdownFormat = (message: BizUIMessage) => {
|
||||
return React.useCallback(() => {
|
||||
let content = ""
|
||||
for (const part of message.parts) {
|
||||
let lexicalEditor: LexicalEditor | null = null
|
||||
@@ -78,133 +56,67 @@ export const AIChatMessage: React.FC<AIChatMessageProps> = React.memo(({ message
|
||||
}
|
||||
return content
|
||||
}, [message.parts])
|
||||
}
|
||||
|
||||
const handleSaveEdit = React.useCallback(
|
||||
(newState: SerializedEditorState, editor: LexicalEditor) => {
|
||||
const messageContent = convertLexicalToMarkdown(editor)
|
||||
const messages = chatActions.getMessages()
|
||||
const messageIndex = messages.findIndex((msg) => msg.id === messageId)
|
||||
if (messageIndex !== -1) {
|
||||
const messagesToKeep = messages.slice(0, messageIndex)
|
||||
const nextMessage = messages[messageIndex]!
|
||||
chatActions.setMessages(messagesToKeep)
|
||||
|
||||
const richTextPart = nextMessage.parts.find(
|
||||
(part) => part.type === "data-rich-text",
|
||||
) as RichTextPart
|
||||
if (richTextPart) {
|
||||
richTextPart.data = {
|
||||
state: newState,
|
||||
text: messageContent,
|
||||
}
|
||||
}
|
||||
|
||||
// Send the edited message
|
||||
chatActions.sendMessage(nextMessage)
|
||||
}
|
||||
setEditingMessageId(null)
|
||||
},
|
||||
[chatActions, messageId, setEditingMessageId],
|
||||
)
|
||||
|
||||
const handleCancelEdit = React.useCallback(() => {
|
||||
setEditingMessageId(null)
|
||||
}, [setEditingMessageId])
|
||||
|
||||
const handleCopy = React.useCallback(async () => {
|
||||
const messageContent = getMessageMarkdownFormat()
|
||||
try {
|
||||
await copyToClipboard(messageContent)
|
||||
toast.success("Message copied to clipboard")
|
||||
} catch {
|
||||
toast.error("Failed to copy message")
|
||||
// AI message component
|
||||
export const AIChatMessage: React.FC<AIChatMessageProps> = React.memo(
|
||||
({ message, isLastMessage }) => {
|
||||
if (message.parts.length === 0) {
|
||||
throw thenable
|
||||
}
|
||||
}, [getMessageMarkdownFormat])
|
||||
|
||||
const handleRetry = React.useCallback(() => {
|
||||
chatActions.regenerate({ messageId })
|
||||
}, [chatActions, messageId])
|
||||
const getMessageMarkdownFormat = useMessageMarkdownFormat(message)
|
||||
|
||||
return (
|
||||
<div
|
||||
onContextMenu={stopPropagation}
|
||||
className={`flex ${message.role === "user" ? "justify-end" : "justify-start"} group`}
|
||||
onMouseEnter={() => setIsHovered(true)}
|
||||
onMouseLeave={() => setIsHovered(false)}
|
||||
>
|
||||
<div className="text-text relative flex max-w-[calc(100%-1rem)] flex-col gap-2">
|
||||
{/* Show editable message if editing */}
|
||||
{isEditing && isUserMessage ? (
|
||||
<EditableMessage
|
||||
messageId={messageId}
|
||||
parts={message.parts}
|
||||
onSave={handleSaveEdit}
|
||||
onCancel={handleCancelEdit}
|
||||
/>
|
||||
) : (
|
||||
<>
|
||||
{/* Normal message display */}
|
||||
<div
|
||||
className={cn(
|
||||
`text-text backdrop-blur-sm`,
|
||||
message.role === "user" && "rounded-2xl bg-gray-100 px-4 py-2.5 dark:bg-gray-800",
|
||||
)}
|
||||
>
|
||||
<div className={`flex select-text flex-col gap-2 text-sm`}>
|
||||
<AIMessageParts message={message} />
|
||||
</div>
|
||||
const handleCopy = React.useCallback(async () => {
|
||||
const messageContent = getMessageMarkdownFormat()
|
||||
try {
|
||||
await copyToClipboard(messageContent)
|
||||
toast.success("Message copied to clipboard")
|
||||
} catch {
|
||||
toast.error("Failed to copy message")
|
||||
}
|
||||
}, [getMessageMarkdownFormat])
|
||||
|
||||
return (
|
||||
<div onContextMenu={stopPropagation} className="group flex justify-start">
|
||||
<div className="text-text relative flex max-w-full flex-col gap-2">
|
||||
{/* Normal message display */}
|
||||
<div className="text-text">
|
||||
<div className="flex select-text flex-col gap-2 text-sm">
|
||||
<AIMessageParts message={message} isLastMessage={isLastMessage} />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Action buttons */}
|
||||
<m.div
|
||||
className={`absolute bottom-1 flex ${message.role === "user" ? "right-0" : "left-0"} gap-1`}
|
||||
initial={{ opacity: 0 }}
|
||||
animate={{
|
||||
opacity: isHovered ? 1 : 0,
|
||||
}}
|
||||
transition={{ duration: 0.2, ease: "easeOut" }}
|
||||
{/* Action buttons */}
|
||||
<div className="absolute -left-2 bottom-1 right-0 flex gap-1 opacity-0 transition-opacity duration-200 group-hover:opacity-100">
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleCopy}
|
||||
className="text-text-secondary hover:bg-fill-tertiary flex items-center gap-1 rounded-md px-2 py-1 text-xs transition-colors"
|
||||
title="Copy message"
|
||||
>
|
||||
{message.role === "user" ? (
|
||||
<>
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleEdit}
|
||||
className="text-text hover:bg-fill-secondary flex items-center gap-1 rounded-md px-2 py-1 text-xs transition-colors"
|
||||
title="Edit message"
|
||||
>
|
||||
<i className="i-mgc-edit-cute-re size-3" />
|
||||
<span>Edit</span>
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleRetry}
|
||||
className="text-text hover:bg-fill-secondary flex items-center gap-1 rounded-md px-2 py-1 text-xs transition-colors"
|
||||
title="Retry"
|
||||
>
|
||||
<i className="i-mgc-refresh-2-cute-re size-3" />
|
||||
<span>Retry</span>
|
||||
</button>
|
||||
</>
|
||||
) : (
|
||||
<i className="i-mgc-copy-2-cute-re size-3" />
|
||||
<span>Copy</span>
|
||||
</button>
|
||||
|
||||
{message.metadata && (
|
||||
<TokenUsagePill metadata={message.metadata}>
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleCopy}
|
||||
className="text-text hover:bg-fill-tertiary flex items-center gap-1 rounded-md px-2 py-1 text-xs transition-colors"
|
||||
title="Copy message"
|
||||
className="text-text-secondary hover:bg-fill-tertiary absolute right-0 flex items-center gap-1 rounded-md px-2 py-1 text-xs transition-colors"
|
||||
>
|
||||
<i className="i-mgc-copy-2-cute-re size-3" />
|
||||
<span>Copy</span>
|
||||
<i className="i-mgc-information-cute-re size-3" />
|
||||
</button>
|
||||
)}
|
||||
</m.div>
|
||||
</TokenUsagePill>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="h-6" />
|
||||
</>
|
||||
)}
|
||||
<div className="h-6" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
})
|
||||
)
|
||||
},
|
||||
)
|
||||
|
||||
export const AIChatWaitingIndicator: React.FC = () => {
|
||||
return (
|
||||
@@ -213,6 +125,7 @@ export const AIChatWaitingIndicator: React.FC = () => {
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
exit={{ opacity: 0, y: 8 }}
|
||||
transition={{ duration: 0.2, ease: [0.25, 0.46, 0.45, 0.94] }}
|
||||
className="mb-4"
|
||||
>
|
||||
<div className="text-text-secondary flex items-center gap-2 rounded-full text-xs">
|
||||
<i className="i-mgc-loading-3-cute-re size-3 animate-spin" />
|
||||
|
||||
+12
-11
@@ -1,4 +1,6 @@
|
||||
import { views } from "@follow/constants"
|
||||
import { cn } from "@follow/utils/utils"
|
||||
import { t } from "i18next"
|
||||
import * as React from "react"
|
||||
|
||||
import type { AIChatContextBlock } from "~/modules/ai-chat/store/types"
|
||||
@@ -23,6 +25,10 @@ interface AIDataBlockItemProps {
|
||||
*/
|
||||
const getDisplayContent = (block: AIChatContextBlock): React.ReactNode => {
|
||||
switch (block.type) {
|
||||
case "mainView": {
|
||||
const viewName = views.find((v) => v.view === Number(block.value))?.name
|
||||
return viewName ? t(viewName, { ns: "common" }) : block.value
|
||||
}
|
||||
case "mainEntry":
|
||||
case "referEntry": {
|
||||
return <EntryTitle entryId={block.value} fallback={block.value} />
|
||||
@@ -39,6 +45,7 @@ const getDisplayContent = (block: AIChatContextBlock): React.ReactNode => {
|
||||
}
|
||||
return getFileDisplayContent(block.attachment)
|
||||
}
|
||||
|
||||
default: {
|
||||
return ""
|
||||
}
|
||||
@@ -56,10 +63,7 @@ const BlockIcon: React.FC<{
|
||||
if (block.type === "fileAttachment" && block.attachment && isImageAttachment(block)) {
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
"flex size-5 flex-shrink-0 items-center justify-center rounded-md",
|
||||
styles.icon,
|
||||
)}
|
||||
className={cn("flex size-4 flex-shrink-0 items-center justify-center rounded", styles.icon)}
|
||||
>
|
||||
<ImageThumbnail attachment={block.attachment} />
|
||||
</div>
|
||||
@@ -70,12 +74,9 @@ const BlockIcon: React.FC<{
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
"flex size-5 flex-shrink-0 items-center justify-center rounded-md",
|
||||
styles.icon,
|
||||
)}
|
||||
className={cn("flex size-4 flex-shrink-0 items-center justify-center rounded", styles.icon)}
|
||||
>
|
||||
<i className={cn("size-3", iconClass)} />
|
||||
<i className={cn("size-2.5", iconClass)} />
|
||||
</div>
|
||||
)
|
||||
})
|
||||
@@ -94,7 +95,7 @@ export const AIDataBlockItem: React.FC<AIDataBlockItemProps> = React.memo(({ blo
|
||||
<div
|
||||
key={block.id}
|
||||
className={cn(
|
||||
"inline-flex items-center gap-1.5 rounded-lg px-2.5 py-1.5",
|
||||
"inline-flex items-center gap-1 rounded px-1.5 py-0.5",
|
||||
"border bg-gradient-to-r backdrop-blur-sm",
|
||||
styles.container,
|
||||
)}
|
||||
@@ -106,7 +107,7 @@ export const AIDataBlockItem: React.FC<AIDataBlockItemProps> = React.memo(({ blo
|
||||
<span className={cn("text-xs font-medium", styles.label)}>{label}</span>
|
||||
<span className="text-text-secondary text-xs">·</span>
|
||||
<span
|
||||
className="text-text max-w-32 truncate text-xs font-medium"
|
||||
className="text-text max-w-24 truncate text-xs font-medium"
|
||||
title={typeof displayContent === "string" ? displayContent : undefined}
|
||||
>
|
||||
{displayContent}
|
||||
|
||||
+18
-17
@@ -11,7 +11,7 @@ interface AIDataBlockPartProps {
|
||||
|
||||
/**
|
||||
* Main component for rendering AI chat context blocks
|
||||
* Displays various types of context (entries, feeds, text, files) with animations
|
||||
* Displays various types of context (entries, feeds, text, files) with compact styling
|
||||
*/
|
||||
export const AIDataBlockPart: React.FC<AIDataBlockPartProps> = React.memo(({ blocks }) => {
|
||||
// Early return for empty blocks
|
||||
@@ -20,23 +20,24 @@ export const AIDataBlockPart: React.FC<AIDataBlockPartProps> = React.memo(({ blo
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
"inline-flex flex-wrap items-center gap-2 rounded-lg p-1 pl-2",
|
||||
"bg-material-ultra-thick",
|
||||
"border-border border",
|
||||
)}
|
||||
>
|
||||
{/* Context indicator */}
|
||||
<div className="text-text-tertiary flex items-center gap-1.5">
|
||||
<i className="i-mgc-link-cute-re size-3.5" />
|
||||
<span className="text-xs font-medium">Context:</span>
|
||||
</div>
|
||||
<div className="min-w-0 max-w-full text-left">
|
||||
<div
|
||||
className={cn(
|
||||
"inline-flex flex-wrap items-center gap-1.5 rounded-lg py-1 pl-2 pr-1",
|
||||
"bg-fill-secondary border-border/50 border",
|
||||
)}
|
||||
>
|
||||
{/* Compact context indicator */}
|
||||
<div className="text-text-secondary flex items-center gap-1">
|
||||
<i className="i-mgc-link-cute-re size-3" />
|
||||
<span className="text-xs">Context:</span>
|
||||
</div>
|
||||
|
||||
{/* Render individual block items */}
|
||||
{blocks.map((block, index) => (
|
||||
<AIDataBlockItem key={block.id} block={block} index={index} />
|
||||
))}
|
||||
{/* Render individual block items */}
|
||||
{blocks.map((block, index) => (
|
||||
<AIDataBlockItem key={block.id} block={block} index={index} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
})
|
||||
|
||||
+13
-4
@@ -1,3 +1,7 @@
|
||||
/**
|
||||
* This AI Markdown Message use a optimize tokenization algorithm to render the streaming text.
|
||||
* But tokenization put into the server response, so we can disable it.
|
||||
*/
|
||||
import type { LinkProps } from "@follow/components/ui/link/LinkWithTooltip.js"
|
||||
import { parseMarkdown } from "@follow/components/utils/parse-markdown.js"
|
||||
import { cn, isBizId } from "@follow/utils"
|
||||
@@ -18,6 +22,7 @@ import { MarkdownLink } from "~/components/ui/markdown/renderers/MarkdownLink"
|
||||
import { usePeekModal } from "~/hooks/biz/usePeekModal"
|
||||
|
||||
import { animatedPlugin } from "./animatedPlugin"
|
||||
import { parseIncompleteMarkdown } from "./parse-incomplete-markdown"
|
||||
|
||||
// Buffer configuration interface
|
||||
interface BufferConfig {
|
||||
@@ -294,6 +299,7 @@ const useThrottledMarkdownParsing = (text: string, isProcessing: boolean) => {
|
||||
|
||||
const parseWithCache = useCallback(
|
||||
(content: string, shouldProcess: boolean) => {
|
||||
const parsedContent = parseIncompleteMarkdown(content)
|
||||
const now = Date.now()
|
||||
|
||||
// During streaming, throttle parsing
|
||||
@@ -306,14 +312,14 @@ const useThrottledMarkdownParsing = (text: string, isProcessing: boolean) => {
|
||||
}
|
||||
|
||||
// If content hasn't changed, return cached result
|
||||
if (content === lastParsedTextRef.current && cachedResultRef.current) {
|
||||
if (parsedContent === lastParsedTextRef.current && cachedResultRef.current) {
|
||||
return cachedResultRef.current
|
||||
}
|
||||
|
||||
// Parse and cache the result
|
||||
const result = baseAIMarkdownParser(content, isProcessing)
|
||||
const result = baseAIMarkdownParser(parsedContent, isProcessing)
|
||||
|
||||
lastParsedTextRef.current = content
|
||||
lastParsedTextRef.current = parsedContent
|
||||
cachedResultRef.current = result
|
||||
lastParseTimeRef.current = now
|
||||
return result
|
||||
@@ -332,6 +338,9 @@ const useThrottledMarkdownParsing = (text: string, isProcessing: boolean) => {
|
||||
}, [text, isProcessing, parseWithCache])
|
||||
}
|
||||
|
||||
/**
|
||||
* @deprecated
|
||||
*/
|
||||
export const AIMarkdownStreamingMessage = memo(
|
||||
({
|
||||
text,
|
||||
@@ -342,7 +351,7 @@ export const AIMarkdownStreamingMessage = memo(
|
||||
className?: string
|
||||
isProcessing?: boolean
|
||||
}) => {
|
||||
const className = `prose dark:prose-invert text-sm
|
||||
const className = `prose max-w-full dark:prose-invert text-sm
|
||||
prose-h1:text-2xl prose-h2:text-xl prose-h3:text-lg prose-h4:text-base prose-h5:text-base prose-h6:text-sm
|
||||
prose-li:list-disc prose-li:marker:text-accent prose-hr:border-border prose-hr:mx-8`
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user