From e968b9d88bdfdf10d1f4addf09e19ebfee3c1ac7 Mon Sep 17 00:00:00 2001 From: lawvs <18554747+lawvs@users.noreply.github.com> Date: Thu, 24 Jul 2025 16:33:56 +0800 Subject: [PATCH 01/74] fix: adjust flex properties for GroupedInsetListCard component --- apps/mobile/src/components/ui/grouped/GroupedList.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/mobile/src/components/ui/grouped/GroupedList.tsx b/apps/mobile/src/components/ui/grouped/GroupedList.tsx index fc72a12c1..a2681b8a1 100644 --- a/apps/mobile/src/components/ui/grouped/GroupedList.tsx +++ b/apps/mobile/src/components/ui/grouped/GroupedList.tsx @@ -63,7 +63,7 @@ export const GroupedInsetListCard: FC< props.style, ]} className={cn( - "bg-secondary-system-grouped-background flex flex-col overflow-hidden rounded-[10px]", + "bg-secondary-system-grouped-background flex flex-1 flex-col overflow-hidden rounded-[10px]", className, )} > From 0c128d3e58ee9d4ced415d4acade0e790e2f9a24 Mon Sep 17 00:00:00 2001 From: Innei Date: Fri, 25 Jul 2025 00:09:11 +0800 Subject: [PATCH 02/74] feat(changelog-cli): implement AI-driven changelog generation with OpenAI integration - Added a new changelog CLI tool that analyzes git commits and generates user-friendly changelog entries. - Integrated OpenAI for AI-powered commit analysis and categorization. - Configurable AI model settings and support for custom endpoints. - Introduced a configuration file for internal team members and commit analysis categories. - Implemented fallback support for keyword-based analysis if AI is unavailable. - Updated package.json and README with usage instructions and examples. Signed-off-by: Innei --- apps/mobile/package.json | 1 + apps/mobile/scripts/changelog-cli/config.json | 54 +++ packages/changelog-cli/README.md | 186 ++++++++++ packages/changelog-cli/USAGE.md | 331 ++++++++++++++++++ packages/changelog-cli/ai-agent.ts | 250 +++++++++++++ packages/changelog-cli/bin/cli.js | 18 + packages/changelog-cli/config.json | 54 +++ packages/changelog-cli/git-tools.ts | 179 ++++++++++ packages/changelog-cli/index.ts | 224 ++++++++++++ packages/changelog-cli/openai-client.ts | 84 +++++ packages/changelog-cli/package.json | 35 ++ packages/changelog-cli/tsconfig.json | 17 + pnpm-lock.yaml | 22 ++ 13 files changed, 1455 insertions(+) create mode 100644 apps/mobile/scripts/changelog-cli/config.json create mode 100644 packages/changelog-cli/README.md create mode 100644 packages/changelog-cli/USAGE.md create mode 100644 packages/changelog-cli/ai-agent.ts create mode 100644 packages/changelog-cli/bin/cli.js create mode 100644 packages/changelog-cli/config.json create mode 100644 packages/changelog-cli/git-tools.ts create mode 100644 packages/changelog-cli/index.ts create mode 100644 packages/changelog-cli/openai-client.ts create mode 100644 packages/changelog-cli/package.json create mode 100644 packages/changelog-cli/tsconfig.json diff --git a/apps/mobile/package.json b/apps/mobile/package.json index b40a72211..934242515 100644 --- a/apps/mobile/package.json +++ b/apps/mobile/package.json @@ -6,6 +6,7 @@ "scripts": { "android": "expo run:android", "bump": "vv", + "changelog:generate": "tsx ../../packages/changelog-cli/index.ts", "dev": "npm run start", "eas-build-post-install": "rm -rf $TMPDIR/metro-cache", "eas-build-pre-install": "command -v pod >/dev/null 2>&1 && pod repo update || echo 'CocoaPods not found, skipping pod repo update'", diff --git a/apps/mobile/scripts/changelog-cli/config.json b/apps/mobile/scripts/changelog-cli/config.json new file mode 100644 index 000000000..57c8fea5d --- /dev/null +++ b/apps/mobile/scripts/changelog-cli/config.json @@ -0,0 +1,54 @@ +{ + "internalTeamMembers": [ + "Innei", + "DIYgod", + "hyoban", + "renovate[bot]", + "github-actions[bot]", + "dependabot[bot]", + "vercel[bot]", + "whitewater" + ], + "aiModel": { + "provider": "openai", + "model": "gpt-4o-mini", + "temperature": 0.3, + "maxTokens": 1000, + "apiKey": "", + "baseURL": "https://openrouter.ai/v1", + "customEndpoint": "" + }, + "commitAnalysis": { + "categories": { + "features": { + "keywords": ["feat", "feature", "add", "implement", "introduce"], + "section": "Shiny new things" + }, + "improvements": { + "keywords": ["improve", "enhance", "optimize", "refactor", "update", "perf"], + "section": "Improvements" + }, + "fixes": { + "keywords": ["fix", "bug", "patch", "resolve", "correct"], + "section": "No longer broken" + } + }, + "ignorePatterns": [ + "^chore:", + "^docs:", + "^test:", + "^ci:", + "^build:", + "Merge pull request", + "Merge branch", + "version bump", + "changelog", + "Update dependencies" + ] + }, + "changelog": { + "maxCommitsPerSection": 5, + "includeCommitHash": true, + "includePullRequestLinks": true + } +} diff --git a/packages/changelog-cli/README.md b/packages/changelog-cli/README.md new file mode 100644 index 000000000..24e2257e4 --- /dev/null +++ b/packages/changelog-cli/README.md @@ -0,0 +1,186 @@ +# @follow/changelog-cli + +AI-driven changelog generator for the Follow project. This package automatically analyzes git commits and generates user-friendly changelog entries using configurable AI models. + +## Features + +- šŸ¤– **AI-Powered Analysis**: Uses OpenAI GPT models to analyze commit messages +- šŸ“Š **Smart Categorization**: Automatically categorizes changes into sections +- šŸ‘„ **Contributor Recognition**: Identifies and thanks external contributors +- šŸ”§ **Configurable**: Supports custom AI endpoints and models +- šŸ”„ **Fallback Support**: Falls back to keyword-based analysis if AI is unavailable + +## Installation + +This package is part of the Follow monorepo and is not published to npm. It's designed to be used within the monorepo environment. + +## Usage + +### As a Workspace Script + +From the mobile app directory: + +```bash +npm run changelog:generate +``` + +### Direct Execution + +From the package directory: + +```bash +pnpm run generate +``` + +### CLI Command (after building) + +```bash +pnpm run build +./bin/cli.js +``` + +## Configuration + +Create or modify `config.json` in the package root: + +```json +{ + "internalTeamMembers": [ + "innei", + "DIYgod", + "hyoban", + "renovate[bot]", + "github-actions[bot]", + "dependabot[bot]", + "vercel[bot]" + ], + "aiModel": { + "provider": "openai", + "model": "gpt-4o-mini", + "temperature": 0.3, + "maxTokens": 1000, + "apiKey": "", + "baseURL": "https://api.openai.com/v1", + "customEndpoint": "" + }, + "commitAnalysis": { + "categories": { + "features": { + "keywords": ["feat", "feature", "add", "implement", "introduce"], + "section": "Shiny new things" + }, + "improvements": { + "keywords": ["improve", "enhance", "optimize", "refactor", "update", "perf"], + "section": "Improvements" + }, + "fixes": { + "keywords": ["fix", "bug", "patch", "resolve", "correct"], + "section": "No longer broken" + } + }, + "ignorePatterns": [ + "^chore:", + "^docs:", + "^test:", + "^ci:", + "^build:", + "Merge pull request", + "Merge branch", + "version bump", + "changelog", + "Update dependencies" + ] + }, + "changelog": { + "maxCommitsPerSection": 5, + "includeCommitHash": true, + "includePullRequestLinks": true + } +} +``` + +## Custom OpenAI Endpoints + +The tool supports custom OpenAI-compatible endpoints: + +### Environment Variables + +```bash +export OPENAI_API_KEY="your-api-key" +export OPENAI_BASE_URL="https://your-custom-endpoint.com/v1" +``` + +### Configuration File + +```json +{ + "aiModel": { + "apiKey": "your-api-key", + "customEndpoint": "https://your-custom-endpoint.com/v1" + } +} +``` + +### Supported Providers + +- OpenAI API +- Azure OpenAI +- Any OpenAI-compatible API (e.g., Claude via proxy, local models) + +## Requirements + +- Node.js >= 18.0.0 +- Git repository with proper tag structure (`mobile@x.y.z`) +- Must be run on a release branch (`release/mobile/*`) + +## How It Works + +1. **Branch Validation**: Ensures execution on a release branch +2. **Git Analysis**: Finds commits between latest mobile tag and current HEAD +3. **Commit Filtering**: Removes noise commits (merges, version bumps, etc.) +4. **AI Analysis**: Sends filtered commits to AI for categorization +5. **Contributor Detection**: Identifies external contributors from commit authors +6. **Changelog Generation**: Formats and writes changelog to target file + +## Files Structure + +- `index.ts` - Main entry point and orchestration logic +- `git-tools.ts` - Git command execution and analysis +- `ai-agent.ts` - AI-powered commit analysis and categorization +- `openai-client.ts` - OpenAI API client with custom endpoint support +- `config.json` - Configuration file +- `bin/cli.js` - CLI executable wrapper + +## Development + +```bash +# Install dependencies +pnpm install + +# Run in development mode +pnpm run dev + +# Type checking +pnpm run typecheck + +# Build for production +pnpm run build +``` + +## Integration + +This package is designed to integrate with the existing release workflow in the Follow monorepo. It can be called from other apps' package.json scripts or integrated into the bump configuration. + +Example integration in mobile app's `package.json`: + +```json +{ + "scripts": { + "changelog:generate": "tsx ../packages/changelog-cli/index.ts" + } +} +``` + +## License + +This package is part of the Follow project and follows the same license terms. diff --git a/packages/changelog-cli/USAGE.md b/packages/changelog-cli/USAGE.md new file mode 100644 index 000000000..248cd3271 --- /dev/null +++ b/packages/changelog-cli/USAGE.md @@ -0,0 +1,331 @@ +# Usage Examples + +This document provides practical examples of how to use the `@follow/changelog-cli` package in different scenarios. + +## Basic Usage + +### 1. Generate Changelog for Current Release + +Make sure you're on a release branch (e.g., `release/mobile/0.2.5`): + +```bash +# From mobile app directory +cd apps/mobile +npm run changelog:generate + +# Or from the package directory +cd packages/changelog-cli +pnpm run generate +``` + +### 2. Using with Custom OpenAI Endpoint + +If you're using a custom OpenAI-compatible endpoint (like Azure OpenAI or a local model): + +```bash +# Set environment variables +export OPENAI_API_KEY="your-api-key" +export OPENAI_BASE_URL="https://your-endpoint.openai.azure.com/v1" + +# Run the generator +npm run changelog:generate +``` + +### 3. Configuration for Different AI Providers + +#### Azure OpenAI + +```json +{ + "aiModel": { + "provider": "openai", + "model": "gpt-4", + "apiKey": "your-azure-key", + "customEndpoint": "https://your-resource.openai.azure.com/openai/deployments/gpt-4/chat/completions?api-version=2024-02-15-preview" + } +} +``` + +#### Local Model (Ollama) + +```json +{ + "aiModel": { + "provider": "openai", + "model": "llama2", + "apiKey": "not-needed", + "customEndpoint": "http://localhost:11434/v1" + } +} +``` + +#### Claude via Proxy + +```json +{ + "aiModel": { + "provider": "openai", + "model": "claude-3-sonnet-20240229", + "apiKey": "your-anthropic-key", + "customEndpoint": "https://api.anthropic.com/v1" + } +} +``` + +## Integration Examples + +### 1. Auto-generate during Release Process + +Add to `apps/mobile/bump.config.ts`: + +```typescript +export default defineConfig({ + leading: [ + "git pull --rebase", + "npm run changelog:generate", // Add this line + "tsx scripts/apply-changelog.ts ${NEW_VERSION}", + "git add changelog", + // ... rest of config + ], + // ... +}) +``` + +### 2. CI/CD Integration + +Example GitHub Actions workflow: + +```yaml +name: Generate Changelog +on: + push: + branches: + - "release/mobile/*" + +jobs: + changelog: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 # Important: fetch full history + + - name: Setup Node.js + uses: actions/setup-node@v4 + with: + node-version: "18" + cache: "pnpm" + + - name: Install dependencies + run: pnpm install + + - name: Generate changelog + env: + OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }} + run: | + cd apps/mobile + npm run changelog:generate + + - name: Commit changelog + run: | + git config --local user.email "action@github.com" + git config --local user.name "GitHub Action" + git add apps/mobile/changelog/next.md + git commit -m "chore: auto-generate changelog" || exit 0 + git push +``` + +### 3. Custom Script Integration + +Create a custom script that uses the changelog CLI: + +```typescript +// scripts/release-workflow.ts +import { execSync } from "node:child_process" + +async function releaseWorkflow() { + console.log("šŸš€ Starting release workflow...") + + // 1. Generate changelog + console.log("šŸ“ Generating changelog...") + execSync("npm run changelog:generate", { + cwd: "apps/mobile", + stdio: "inherit", + }) + + // 2. Review and edit if needed + console.log("šŸ“‹ Changelog generated. Please review before continuing.") + + // 3. Continue with release process... +} + +releaseWorkflow() +``` + +## Configuration Examples + +### 1. Team-specific Configuration + +For different teams with different internal members: + +```json +{ + "internalTeamMembers": [ + "innei", + "DIYgod", + "hyoban", + "team-lead-1", + "team-lead-2", + "renovate[bot]", + "dependabot[bot]" + ] +} +``` + +### 2. Project-specific Keywords + +Customize keywords for different types of projects: + +```json +{ + "commitAnalysis": { + "categories": { + "features": { + "keywords": ["feat", "feature", "add", "implement", "new"], + "section": "šŸŽ‰ New Features" + }, + "improvements": { + "keywords": ["improve", "enhance", "optimize", "perf", "refactor"], + "section": "⚔ Improvements" + }, + "fixes": { + "keywords": ["fix", "bug", "patch", "resolve", "hotfix"], + "section": "šŸ› Bug Fixes" + } + } + } +} +``` + +### 3. Strict Filtering + +For projects with very specific changelog requirements: + +```json +{ + "commitAnalysis": { + "ignorePatterns": [ + "^chore:", + "^docs:", + "^test:", + "^ci:", + "^build:", + "^style:", + "^refactor:", + "Merge pull request", + "Merge branch", + "version bump", + "changelog", + "Update dependencies", + "^deps:", + "^devDeps:" + ] + }, + "changelog": { + "maxCommitsPerSection": 3, + "includeCommitHash": false, + "includePullRequestLinks": true + } +} +``` + +## Troubleshooting Examples + +### 1. API Rate Limiting + +If you hit OpenAI API rate limits: + +```json +{ + "aiModel": { + "temperature": 0.1, + "maxTokens": 500 + } +} +``` + +Or process commits in smaller batches by modifying the batch size in `ai-agent.ts`. + +### 2. Custom Git Tag Format + +If your project uses a different tag format, modify `git-tools.ts`: + +```typescript +// In git-tools.ts, modify getLatestMobileTag() +getLatestMobileTag(): GitTag | null { + try { + // Change this line to match your tag format + const tags = this.exec('git tag --sort=-version:refname | grep "^v" | head -1') + // ... rest of the method + } +} +``` + +### 3. Working with Monorepos + +For complex monorepo setups, you might need to adjust the working directory: + +```typescript +// Create a custom git tools instance +const git = new GitTools("/path/to/your/specific/repo") +``` + +## Best Practices + +### 1. Review Before Committing + +Always review the generated changelog before committing: + +```bash +# Generate changelog +npm run changelog:generate + +# Review the changes +cat apps/mobile/changelog/next.md + +# Edit if necessary +vim apps/mobile/changelog/next.md + +# Commit when satisfied +git add apps/mobile/changelog/next.md +git commit -m "chore: update changelog" +``` + +### 2. Backup Configuration + +Keep your configuration in version control but sensitive data in environment variables: + +```json +{ + "aiModel": { + "apiKey": "", // Leave empty in version control + "customEndpoint": "" // Can be committed if not sensitive + } +} +``` + +### 3. Testing Configuration + +Test your configuration with a small batch first: + +```json +{ + "changelog": { + "maxCommitsPerSection": 1, // Start small + "includeCommitHash": true, + "includePullRequestLinks": true + } +} +``` + +This way you can verify the output format before processing many commits. diff --git a/packages/changelog-cli/ai-agent.ts b/packages/changelog-cli/ai-agent.ts new file mode 100644 index 000000000..3f1750665 --- /dev/null +++ b/packages/changelog-cli/ai-agent.ts @@ -0,0 +1,250 @@ +import type { GitCommit } from "./git-tools" +import OpenAIClient from "./openai-client" + +export interface ChangelogEntry { + section: "Shiny new things" | "Improvements" | "No longer broken" + description: string + commitHash?: string + pullRequest?: string +} + +export interface AIConfig { + provider: string + model: string + temperature: number + maxTokens: number + apiKey?: string +} + +export interface CommitCategory { + keywords: string[] + section: "Shiny new things" | "Improvements" | "No longer broken" +} + +export class AIAgent { + private config: AIConfig + private categories: Record + private openaiClient: OpenAIClient + + constructor(config: AIConfig, categories: Record) { + this.config = config + this.categories = categories + this.openaiClient = new OpenAIClient(config) + } + + /** + * Analyze commits and generate changelog entries using AI + */ + async analyzeCommits(commits: GitCommit[]): Promise { + console.info(`Analyzing ${commits.length} commits with AI...`) + + const filteredCommits = this.filterImportantCommits(commits) + console.info(`Selected ${filteredCommits.length} important commits`) + + const changelogEntries: ChangelogEntry[] = [] + + // Process commits in batches to avoid API limits + const batchSize = 10 + for (let i = 0; i < filteredCommits.length; i += batchSize) { + const batch = filteredCommits.slice(i, i + batchSize) + const batchEntries = await this.processBatch(batch) + changelogEntries.push(...batchEntries) + } + + return changelogEntries + } + + /** + * Filter commits to identify important ones + */ + private filterImportantCommits(commits: GitCommit[]): GitCommit[] { + return commits.filter((commit) => { + const message = `${commit.subject} ${commit.body}`.toLowerCase() + + // Skip ignored patterns + const shouldIgnore = [ + /^chore:/, + /^docs:/, + /^test:/, + /^ci:/, + /^build:/, + /merge pull request/, + /merge branch/, + /version bump/, + /changelog/, + /update dependencies/, + /^\d+\.\d+\.\d+/, // version numbers + /^bump /, + /^release\(/, + ].some((pattern) => pattern.test(message)) + + if (shouldIgnore) return false + + // Include commits with significant changes + const hasSignificantChange = [ + /\bfeat\b/, + /\bfeature\b/, + /\badd\b/, + /\bimplement\b/, + /\bintroduce\b/, + /\bfix\b/, + /\bbug\b/, + /\bpatch\b/, + /\bresolve\b/, + /\bcorrect\b/, + /\bimprove\b/, + /\benhance\b/, + /\boptimize\b/, + /\brefactor\b/, + /\bupdate\b/, + /\bperf\b/, + /\bbreaking\b/, + /\bmajor\b/, + /\bminor\b/, + /\bui\b/, + /\bux\b/, + /\bdesign\b/, + ].some((pattern) => pattern.test(message)) + + return hasSignificantChange || commit.pullRequest + }) + } + + /** + * Process a batch of commits using AI + */ + private async processBatch(commits: GitCommit[]): Promise { + const prompt = this.buildAnalysisPrompt(commits) + + try { + const aiResponse = await this.callAI(prompt) + return this.parseAIResponse(aiResponse, commits) + } catch (error) { + console.warn("AI analysis failed, falling back to keyword-based categorization:", error) + return this.fallbackCategorization(commits) + } + } + + /** + * Build the analysis prompt for AI + */ + private buildAnalysisPrompt(commits: GitCommit[]): string { + const commitsText = commits + .map( + (commit, index) => + `${index + 1}. [${commit.shortHash}] ${commit.subject}\n ${commit.body || "No description"}\n ${commit.pullRequest ? `PR #${commit.pullRequest}` : ""}`, + ) + .join("\n\n") + + return `You are a technical writer creating a changelog for a React Native RSS reader app called "Follow". + +Analyze these git commits and categorize the most important user-facing changes into these sections: + +**Shiny new things**: New features, major additions that users can see/use +**Improvements**: Enhancements, optimizations, better UX/UI, performance improvements +**No longer broken**: Bug fixes, crash fixes, issues resolved + +For each relevant commit, provide: +1. A user-friendly description (not technical jargon) +2. Which section it belongs to +3. Reference the commit hash or PR number if significant + +Focus on changes that impact the user experience. Skip internal refactoring, dependency updates, or development-only changes unless they significantly affect users. + +Commits to analyze: +${commitsText} + +Respond in this JSON format: +{ + "entries": [ + { + "section": "Shiny new things", + "description": "User-friendly description of what changed", + "commitHash": "abc123", + "pullRequest": "1234" + } + ] +} + +Only include meaningful user-facing changes. Be selective and focus on quality over quantity.` + } + + /** + * Call AI API (mock implementation - you need to implement the actual API call) + */ + private async callAI(prompt: string): Promise { + // This is a mock implementation. You need to implement the actual AI API call + // based on your chosen provider (OpenAI, Anthropic, etc.) + + if (this.config.provider === "openai") { + return this.callOpenAI(prompt) + } + + throw new Error(`AI provider "${this.config.provider}" not implemented`) + } + + /** + * OpenAI API call implementation + */ + private async callOpenAI(prompt: string): Promise { + if (!this.openaiClient.isAvailable()) { + throw new Error("OpenAI API not available") + } + + console.info("šŸ¤– Calling OpenAI API...") + return await this.openaiClient.chat(prompt) + } + + /** + * Parse AI response into changelog entries + */ + private parseAIResponse(response: string, commits: GitCommit[]): ChangelogEntry[] { + try { + const parsed = JSON.parse(response) + return parsed.entries || [] + } catch { + console.warn("Failed to parse AI response, using fallback") + return this.fallbackCategorization(commits) + } + } + + /** + * Fallback categorization using keywords when AI fails + */ + private fallbackCategorization(commits: GitCommit[]): ChangelogEntry[] { + return commits.map((commit) => { + const message = `${commit.subject} ${commit.body}`.toLowerCase() + + // Determine category based on keywords + let section: ChangelogEntry["section"] = "Improvements" + + if (this.categories.features?.keywords.some((keyword) => message.includes(keyword))) { + section = "Shiny new things" + } else if (this.categories.fixes?.keywords.some((keyword) => message.includes(keyword))) { + section = "No longer broken" + } + + // Clean up the description + let description = commit.subject + if ( + description.startsWith("feat:") || + description.startsWith("fix:") || + description.startsWith("chore:") + ) { + description = description.slice(Math.max(0, description.indexOf(":") + 1)).trim() + } + + // Capitalize first letter + description = description.charAt(0).toUpperCase() + description.slice(1) + + return { + section, + description, + commitHash: commit.shortHash, + pullRequest: commit.pullRequest, + } + }) + } +} + +export default AIAgent diff --git a/packages/changelog-cli/bin/cli.js b/packages/changelog-cli/bin/cli.js new file mode 100644 index 000000000..ea3a32dbe --- /dev/null +++ b/packages/changelog-cli/bin/cli.js @@ -0,0 +1,18 @@ +#!/usr/bin/env node + +import { execSync } from "node:child_process" +import { fileURLToPath } from "node:url" + +import { dirname, join } from "pathe" + +const __dirname = dirname(fileURLToPath(import.meta.url)) +const indexPath = join(__dirname, "..", "index.ts") + +try { + execSync(`tsx "${indexPath}"`, { + stdio: "inherit", + cwd: process.cwd(), + }) +} catch (error) { + process.exit(error.status || 1) +} diff --git a/packages/changelog-cli/config.json b/packages/changelog-cli/config.json new file mode 100644 index 000000000..35744beaf --- /dev/null +++ b/packages/changelog-cli/config.json @@ -0,0 +1,54 @@ +{ + "internalTeamMembers": [ + "Innei", + "DIYgod", + "hyoban", + "renovate[bot]", + "github-actions[bot]", + "dependabot[bot]", + "vercel[bot]", + "whitewater" + ], + "aiModel": { + "provider": "openai", + "model": "gpt-4o-mini", + "temperature": 0.3, + "maxTokens": 1000, + "apiKey": "", + "baseURL": "https://api.openai.com/v1", + "customEndpoint": "" + }, + "commitAnalysis": { + "categories": { + "features": { + "keywords": ["feat", "feature", "add", "implement", "introduce"], + "section": "Shiny new things" + }, + "improvements": { + "keywords": ["improve", "enhance", "optimize", "refactor", "update", "perf"], + "section": "Improvements" + }, + "fixes": { + "keywords": ["fix", "bug", "patch", "resolve", "correct"], + "section": "No longer broken" + } + }, + "ignorePatterns": [ + "^chore:", + "^docs:", + "^test:", + "^ci:", + "^build:", + "Merge pull request", + "Merge branch", + "version bump", + "changelog", + "Update dependencies" + ] + }, + "changelog": { + "maxCommitsPerSection": 5, + "includeCommitHash": true, + "includePullRequestLinks": true + } +} diff --git a/packages/changelog-cli/git-tools.ts b/packages/changelog-cli/git-tools.ts new file mode 100644 index 000000000..2d60efef8 --- /dev/null +++ b/packages/changelog-cli/git-tools.ts @@ -0,0 +1,179 @@ +import { execSync } from "node:child_process" +import { fileURLToPath } from "node:url" + +import { dirname, join } from "pathe" + +const __dirname = dirname(fileURLToPath(import.meta.url)) +const projectRoot = join(__dirname, "..", "..") + +export interface GitCommit { + hash: string + shortHash: string + subject: string + body: string + author: string + email: string + date: string + pullRequest?: string +} + +export interface GitTag { + name: string + hash: string + date: string +} + +export class GitTools { + private workingDir: string + + constructor(workingDir = projectRoot) { + this.workingDir = workingDir + } + + /** + * Execute git command and return output + */ + private exec(command: string): string { + try { + return execSync(command, { + cwd: this.workingDir, + encoding: "utf-8", + }).trim() + } catch (error) { + console.error(`Git command failed: ${command}`) + throw error + } + } + + /** + * Get the latest tag for mobile releases + */ + getLatestMobileTag(): GitTag | null { + try { + const tags = this.exec('git tag --sort=-version:refname | grep "^mobile@" | head -1') + if (!tags) return null + + const tagName = tags.trim() + const hash = this.exec(`git rev-list -n 1 ${tagName}`) + const date = this.exec(`git log -1 --format=%ai ${hash}`) + + return { + name: tagName, + hash, + date, + } + } catch { + return null + } + } + + /** + * Get current branch name + */ + getCurrentBranch(): string { + return this.exec("git rev-parse --abbrev-ref HEAD") + } + + /** + * Get the latest commit hash on current branch + */ + getLatestCommitHash(): string { + return this.exec("git rev-parse HEAD") + } + + /** + * Get commits between two references + */ + getCommitsBetween(fromRef: string, toRef: string): GitCommit[] { + const format = [ + "%H", // full hash + "%h", // short hash + "%s", // subject + "%b", // body + "%an", // author name + "%ae", // author email + "%ai", // author date + ].join("%x1f") // use ASCII unit separator + + const command = `git log --format="${format}%x1e" ${fromRef}..${toRef}` + const output = this.exec(command) + + if (!output) return [] + + return output + .split("\x1e") + .filter(Boolean) + .map((entry) => { + const parts = entry.split("\x1f") + const [hash, shortHash, subject, body, author, email, date] = parts + + // Ensure all required fields exist + if (!hash || !shortHash || !subject || !author || !email || !date) { + throw new Error("Invalid git log entry format") + } + + // Check if commit is related to a pull request + const pullRequest = this.extractPullRequestNumber(subject, body || "") + + return { + hash: hash.trim(), + shortHash: shortHash.trim(), + subject: subject.trim(), + body: (body || "").trim(), + author: author.trim(), + email: email.trim(), + date: date.trim(), + pullRequest, + } + }) + } + + /** + * Extract pull request number from commit message + */ + private extractPullRequestNumber(subject: string, body: string): string | undefined { + const text = `${subject} ${body}` + const prMatch = text.match(/#(\d+)/) + return prMatch ? prMatch[1] : undefined + } + + /** + * Get all unique authors from commits, excluding bots and internal members + */ + getUniqueAuthors(commits: GitCommit[], internalMembers: string[]): string[] { + const authors = new Set() + + commits.forEach((commit) => { + const author = commit.author.toLowerCase() + const isBotOrInternal = + author.includes("[bot]") || + author.includes("bot") || + internalMembers.some((member) => author.includes(member.toLowerCase())) + + if (!isBotOrInternal) { + authors.add(commit.author) + } + }) + + return Array.from(authors).sort() + } + + /** + * Check if we're on a release branch + */ + isOnReleaseBranch(): boolean { + const currentBranch = this.getCurrentBranch() + return currentBranch.startsWith("release/") + } + + /** + * Get the version from release branch name + */ + getVersionFromBranch(): string | null { + const currentBranch = this.getCurrentBranch() + const match = currentBranch.match(/release\/mobile\/(.+)/) + return match?.[1] ?? null + } +} + +export default GitTools diff --git a/packages/changelog-cli/index.ts b/packages/changelog-cli/index.ts new file mode 100644 index 000000000..d5ad7fb60 --- /dev/null +++ b/packages/changelog-cli/index.ts @@ -0,0 +1,224 @@ +#!/usr/bin/env tsx + +import "dotenv/config" + +import { readFileSync, writeFileSync } from "node:fs" +import { fileURLToPath } from "node:url" + +import { dirname, join } from "pathe" + +import type { ChangelogEntry } from "./ai-agent" +import AIAgent from "./ai-agent" +import GitTools from "./git-tools" + +// Get current directory +const __dirname = dirname(fileURLToPath(import.meta.url)) +const changelogDir = join(__dirname, "..", "..", "apps", "mobile", "changelog") +const configPath = join(__dirname, "config.json") + +interface Config { + internalTeamMembers: string[] + aiModel: { + provider: string + model: string + temperature: number + maxTokens: number + baseURL?: string + customEndpoint?: string + } + commitAnalysis: { + categories: Record< + string, + { + keywords: string[] + section: string + } + > + ignorePatterns: string[] + } + changelog: { + maxCommitsPerSection: number + includeCommitHash: boolean + includePullRequestLinks: boolean + } +} + +/** + * Load configuration from file + */ +function loadConfig(): Config { + try { + const configContent = readFileSync(configPath, "utf-8") + return JSON.parse(configContent) + } catch (error) { + console.error("Failed to load config file:", error) + process.exit(1) + } +} + +/** + * Format changelog entry for output + */ +function formatChangelogEntry(entry: ChangelogEntry, config: Config): string { + let line = `- ${entry.description}` + + if (config.changelog.includePullRequestLinks && entry.pullRequest) { + line += `(#${entry.pullRequest})` + } else if (config.changelog.includeCommitHash && entry.commitHash) { + line += `(${entry.commitHash})` + } + + return line +} + +/** + * Group changelog entries by section + */ +function groupEntriesBySection(entries: ChangelogEntry[]): Record { + const grouped: Record = { + "Shiny new things": [], + Improvements: [], + "No longer broken": [], + } + + entries.forEach((entry) => { + if (grouped[entry.section]) { + grouped[entry.section]!.push(entry) + } + }) + + return grouped +} + +/** + * Generate the changelog content + */ +function generateChangelogContent( + version: string, + entries: ChangelogEntry[], + contributors: string[], + config: Config, +): string { + const groupedEntries = groupEntriesBySection(entries) + + let content = `# What's New in v${version}\n\n` + + // Add sections with entries + Object.entries(groupedEntries).forEach(([section, sectionEntries]) => { + content += `## ${section}\n\n` + + if (sectionEntries.length > 0) { + // Limit entries per section + const limitedEntries = sectionEntries.slice(0, config.changelog.maxCommitsPerSection) + limitedEntries.forEach((entry) => { + content += `${formatChangelogEntry(entry, config)}\n` + }) + } + + content += "\n" + }) + + // Add contributors section + content += "## Thanks\n\n" + if (contributors.length > 0) { + const contributorList = contributors.map((name) => `@${name}`).join(" ") + content += `Special thanks to volunteer contributors ${contributorList} for their valuable contributions\n` + } else { + content += "Special thanks to volunteer contributors @ for their valuable contributions\n" + } + + return content +} + +/** + * Main function to generate changelog + */ +async function main() { + try { + console.info("šŸ¤– Starting AI-driven changelog generation...") + + // Load configuration + const config = loadConfig() + console.info("āœ… Configuration loaded") + + // Initialize Git tools + const git = new GitTools() + + // Check if we're on a release branch + if (!git.isOnReleaseBranch()) { + console.error("āŒ This script should only be run on a release branch (release/mobile/*)") + process.exit(1) + } + + // Get version from branch name + const version = git.getVersionFromBranch() + if (!version) { + console.error("āŒ Could not extract version from branch name") + process.exit(1) + } + + console.info(`šŸ“ Generating changelog for version: ${version}`) + + // Get the latest mobile tag + const latestTag = git.getLatestMobileTag() + if (!latestTag) { + console.error("āŒ No previous mobile tags found") + process.exit(1) + } + + console.info(`šŸ“Œ Latest tag: ${latestTag.name}`) + + // Get commits between latest tag and current HEAD + const currentCommit = git.getLatestCommitHash() + const commits = git.getCommitsBetween(latestTag.hash, currentCommit) + + console.info(`šŸ” Found ${commits.length} commits since last release`) + + if (commits.length === 0) { + console.warn("āš ļø No new commits found since last release") + return + } + + // Initialize AI agent + const aiAgent = new AIAgent(config.aiModel, config.commitAnalysis.categories as any) + + // Analyze commits with AI + const changelogEntries = await aiAgent.analyzeCommits(commits) + console.info(`✨ Generated ${changelogEntries.length} changelog entries`) + + // Get contributors + const contributors = git.getUniqueAuthors(commits, config.internalTeamMembers) + console.info(`šŸ‘„ Found ${contributors.length} external contributors`) + + // Generate changelog content + const changelogContent = generateChangelogContent( + version, + changelogEntries, + contributors, + config, + ) + + // Write to next.md + const nextFilePath = join(changelogDir, "next.md") + writeFileSync(nextFilePath, changelogContent, "utf-8") + + console.info("āœ… Changelog generated successfully!") + console.info(`šŸ“„ Updated: ${nextFilePath}`) + + // Show preview + console.info("\nšŸ“‹ Preview:") + console.info("─".repeat(50)) + console.info(changelogContent) + console.info("─".repeat(50)) + } catch (error) { + console.error("āŒ Failed to generate changelog:", error) + process.exit(1) + } +} + +// Run the script if called directly +if (import.meta.url === `file://${process.argv[1]}`) { + main() +} + +export default main diff --git a/packages/changelog-cli/openai-client.ts b/packages/changelog-cli/openai-client.ts new file mode 100644 index 000000000..5e26b43e5 --- /dev/null +++ b/packages/changelog-cli/openai-client.ts @@ -0,0 +1,84 @@ +export interface OpenAIConfig { + apiKey?: string + model: string + temperature: number + maxTokens: number + baseURL?: string + customEndpoint?: string +} + +export class OpenAIClient { + private config: OpenAIConfig + private apiKey: string + private baseURL: string + + constructor(config: OpenAIConfig) { + this.config = config + this.apiKey = config.apiKey || process.env.OPENAI_API_KEY || "" + + // Support custom endpoints + if (config.customEndpoint) { + this.baseURL = config.customEndpoint + } else if (config.baseURL) { + this.baseURL = config.baseURL + } else { + this.baseURL = process.env.OPENAI_BASE_URL || "https://api.openai.com/v1" + } + + if (!this.apiKey) { + console.warn("āš ļø No OpenAI API key provided. Using fallback analysis.") + } + + if (config.customEndpoint) { + console.info(`šŸ”— Using custom OpenAI endpoint: ${this.baseURL}`) + } + } + + async chat(prompt: string): Promise { + if (!this.apiKey) { + throw new Error("OpenAI API key not provided") + } + + try { + const response = await fetch(`${this.baseURL}/chat/completions`, { + method: "POST", + headers: { + "Content-Type": "application/json", + Authorization: `Bearer ${this.apiKey}`, + }, + body: JSON.stringify({ + model: this.config.model, + messages: [ + { + role: "user", + content: prompt, + }, + ], + temperature: this.config.temperature, + max_tokens: this.config.maxTokens, + }), + }) + + if (!response.ok) { + throw new Error(`OpenAI API error: ${response.status} ${response.statusText}`) + } + + const data = await response.json() + + if (!data.choices || data.choices.length === 0) { + throw new Error("No response from OpenAI API") + } + + return data.choices[0].message.content + } catch (error) { + console.error("OpenAI API call failed:", error) + throw error + } + } + + isAvailable(): boolean { + return Boolean(this.apiKey) + } +} + +export default OpenAIClient diff --git a/packages/changelog-cli/package.json b/packages/changelog-cli/package.json new file mode 100644 index 000000000..3354c071c --- /dev/null +++ b/packages/changelog-cli/package.json @@ -0,0 +1,35 @@ +{ + "name": "@follow/changelog-cli", + "type": "module", + "version": "1.0.0", + "private": true, + "description": "AI-driven changelog generator for Follow project", + "keywords": [ + "changelog", + "git", + "ai", + "cli", + "automation" + ], + "main": "./index.ts", + "bin": { + "changelog-cli": "./bin/cli.js" + }, + "engines": { + "node": ">=18.0.0" + }, + "scripts": { + "build": "tsc", + "dev": "tsx index.ts", + "generate": "tsx index.ts", + "typecheck": "tsc --noEmit" + }, + "dependencies": { + "dotenv": "17.2.0", + "pathe": "2.0.3" + }, + "devDependencies": { + "tsx": "4.20.3", + "typescript": "catalog:" + } +} diff --git a/packages/changelog-cli/tsconfig.json b/packages/changelog-cli/tsconfig.json new file mode 100644 index 000000000..5fd15f48a --- /dev/null +++ b/packages/changelog-cli/tsconfig.json @@ -0,0 +1,17 @@ +{ + "extends": "../configs/tsconfig.extend.json", + "compilerOptions": { + "outDir": "./dist", + "rootDir": "./", + "target": "ES2022", + "module": "ESNext", + "moduleResolution": "bundler", + "allowSyntheticDefaultImports": true, + "esModuleInterop": true, + "declaration": true, + "declarationMap": true, + "sourceMap": true + }, + "include": ["**/*.ts"], + "exclude": ["node_modules", "dist", "**/*.test.ts"] +} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 7c10cdb3b..00a31c89a 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -1338,6 +1338,22 @@ importers: specifier: 0.3.0 version: 0.3.0 + packages/changelog-cli: + dependencies: + dotenv: + specifier: 17.2.0 + version: 17.2.0 + pathe: + specifier: 2.0.3 + version: 2.0.3 + devDependencies: + tsx: + specifier: 4.20.3 + version: 4.20.3 + typescript: + specifier: 'catalog:' + version: 5.8.3 + packages/configs: dependencies: '@egoist/tailwindcss-icons': @@ -8690,6 +8706,10 @@ packages: resolution: {integrity: sha512-m/C+AwOAr9/W1UOIZUo232ejMNnJAJtYQjUbHoNTBNTJSvqzzDh7vnrei3o3r3m9blf6ZoDkvcw0VmozNRFJxg==} engines: {node: '>=12'} + dotenv@17.2.0: + resolution: {integrity: sha512-Q4sgBT60gzd0BB0lSyYD3xM4YxrXA9y4uBDof1JNYGzOXrQdQ6yX+7XIAqoFOGQFOTK1D3Hts5OllpxMDZFONQ==} + engines: {node: '>=12'} + dotenv@9.0.2: resolution: {integrity: sha512-I9OvvrHp4pIARv4+x9iuewrWycX6CcZtoAu1XrzPxc5UygMJXJZYmBsynku8IkrJwgypE5DGNjDPmPRhDCptUg==} engines: {node: '>=10'} @@ -24848,6 +24868,8 @@ snapshots: dotenv@16.5.0: {} + dotenv@17.2.0: {} + dotenv@9.0.2: {} drizzle-kit@0.31.4: From 5cf916e50f2ce8d1fb9fd72bbce628604aeaf00e Mon Sep 17 00:00:00 2001 From: Stephen Zhou <38493346+hyoban@users.noreply.github.com> Date: Fri, 25 Jul 2025 23:01:51 +0800 Subject: [PATCH 03/74] fix(desktop): load firebase app --- apps/desktop/layer/renderer/src/push-notification.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/apps/desktop/layer/renderer/src/push-notification.ts b/apps/desktop/layer/renderer/src/push-notification.ts index 96da3052e..78ad65049 100644 --- a/apps/desktop/layer/renderer/src/push-notification.ts +++ b/apps/desktop/layer/renderer/src/push-notification.ts @@ -1,5 +1,5 @@ import { env } from "@follow/shared/env.desktop" -import { getApp } from "firebase/app" +import { initializeApp } from "firebase/app" import { getMessaging, getToken } from "firebase/messaging" import { setAppMessagingToken } from "./atoms/app" @@ -31,7 +31,7 @@ export async function registerWebPushNotifications() { await navigator.serviceWorker.ready - const app = getApp() + const app = initializeApp(firebaseConfig) const messaging = getMessaging(app) const permission = await Notification.requestPermission() From 6e7b988e35c49675c55330cbde7a8d20cae80d70 Mon Sep 17 00:00:00 2001 From: Cason Kervis Date: Sat, 26 Jul 2025 16:08:30 +0800 Subject: [PATCH 04/74] Merge pull request #4217 from cscnk52/fix/layout fix: fix Audio item layout --- .../renderer/src/modules/entry-column/Items/audio-item.tsx | 3 +++ 1 file changed, 3 insertions(+) diff --git a/apps/desktop/layer/renderer/src/modules/entry-column/Items/audio-item.tsx b/apps/desktop/layer/renderer/src/modules/entry-column/Items/audio-item.tsx index 8d11b750a..0c598a4eb 100644 --- a/apps/desktop/layer/renderer/src/modules/entry-column/Items/audio-item.tsx +++ b/apps/desktop/layer/renderer/src/modules/entry-column/Items/audio-item.tsx @@ -5,12 +5,15 @@ import { Media } from "~/components/ui/media/Media" import { ListItem } from "~/modules/entry-column/templates/list-item-template" import { FeedTitle } from "~/modules/feed/feed-title" +import { readableContentMaxWidth } from "../styles" import type { EntryItemStatelessProps, UniversalItemProps } from "../types" export function AudioItem({ entryId, entryPreview, translation }: UniversalItemProps) { return } +AudioItem.wrapperClassName = readableContentMaxWidth + export function AudioItemStateLess({ entry, feed }: EntryItemStatelessProps) { return (
From 897186a4469e18e528d2b49907d2e0aebd2af0dd Mon Sep 17 00:00:00 2001 From: Stephen Zhou <38493346+hyoban@users.noreply.github.com> Date: Mon, 28 Jul 2025 10:18:19 +0800 Subject: [PATCH 05/74] fix: mark view as read for hideFromTimeline --- .../internal/store/src/subscription/getter.ts | 15 +++++++++++---- packages/internal/store/src/unread/store.ts | 6 +++++- 2 files changed, 16 insertions(+), 5 deletions(-) diff --git a/packages/internal/store/src/subscription/getter.ts b/packages/internal/store/src/subscription/getter.ts index b6950143a..1e7b54bdf 100644 --- a/packages/internal/store/src/subscription/getter.ts +++ b/packages/internal/store/src/subscription/getter.ts @@ -23,18 +23,25 @@ export const getSubscriptionByEntryId = (entryId: string | undefined) => { return possibleSource.map((id) => getSubscriptionByFeedId(id)).find((s) => !!s) } -export const getSubscribedFeedIdAndInboxHandlesByView = ( - view: FeedViewType | undefined, - excludePrivate: boolean, -): string[] => { +export const getSubscribedFeedIdAndInboxHandlesByView = ({ + view, + excludePrivate, + excludeHidden, +}: { + view: FeedViewType | undefined + excludePrivate: boolean + excludeHidden: boolean +}): string[] => { if (typeof view !== "number") return [] const state = useSubscriptionStore.getState() return Array.from(state.feedIdByView[view]) .filter((i) => !excludePrivate || !state.data[i]?.isPrivate) + .filter((i) => !excludeHidden || !state.data[i]?.hideFromTimeline) .concat(view === FeedViewType.Articles ? getInboxList().map((i) => i.id) : []) .concat( Array.from(state.listIdByView[view]) .filter((i) => !excludePrivate || !state.data[i]?.isPrivate) + .filter((i) => !excludeHidden || !state.data[i]?.hideFromTimeline) .flatMap((id) => getListFeedIds(id) ?? []), ) } diff --git a/packages/internal/store/src/unread/store.ts b/packages/internal/store/src/unread/store.ts index 46300587f..18f0b2334 100644 --- a/packages/internal/store/src/unread/store.ts +++ b/packages/internal/store/src/unread/store.ts @@ -150,7 +150,11 @@ class UnreadSyncService { } else if (filter?.inboxId) { await this.updateUnreadStatus({ ids: [filter.inboxId], time, request }) } else { - const feedIdAndInboxHandles = getSubscribedFeedIdAndInboxHandlesByView(view, excludePrivate) + const feedIdAndInboxHandles = getSubscribedFeedIdAndInboxHandlesByView({ + view, + excludePrivate, + excludeHidden: true, + }) await this.updateUnreadStatus({ ids: feedIdAndInboxHandles, time, request }) } } From d97b2ab7498450f77a99e2b8c146f0b22d628602 Mon Sep 17 00:00:00 2001 From: huanfei <41602338+huanfe1@users.noreply.github.com> Date: Mon, 28 Jul 2025 13:04:24 +0800 Subject: [PATCH 06/74] fix: resolve double-click issue for category collapse in user subscriptions (#4254) --- apps/ssr/client/pages/(main)/share/users/[id]/index.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/ssr/client/pages/(main)/share/users/[id]/index.tsx b/apps/ssr/client/pages/(main)/share/users/[id]/index.tsx index 99b148b59..e15b4d24f 100644 --- a/apps/ssr/client/pages/(main)/share/users/[id]/index.tsx +++ b/apps/ssr/client/pages/(main)/share/users/[id]/index.tsx @@ -249,7 +249,7 @@ const Subscriptions = ({ userId }: { userId: string }) => { const toggleCategory = (category: string) => { setExpandedCategories((prev) => ({ ...prev, - [category]: !prev[category], + [category]: !(prev[category] ?? true), })) } return ( From 1adf9420a904e713abf88660c34b8d779ea007bf Mon Sep 17 00:00:00 2001 From: Innei Date: Mon, 28 Jul 2025 17:55:36 +0800 Subject: [PATCH 07/74] feat: re-design integration settings UI with search functionality and new categories - Added a search input to filter integration categories and their respective settings. - Introduced new categories for integrations: Knowledge Management, Reading Services, Media Tools, and Download Tools. - Refactored integration settings structure to improve organization and clarity. - Created a new InputV2 component for enhanced input handling and user experience. Signed-off-by: Innei --- .claude/agents/react-architect.md | 68 ++ .claude/agents/tech-lead-orchestrator.md | 51 ++ .claude/agents/ui-design-engineer.md | 51 ++ CLAUDE.md | 7 + .../src/modules/settings/tabs/integration.tsx | 668 +++++++++++------- locales/settings/en.json | 7 + .../components/src/ui/input/InputV2.tsx | 83 +++ .../internal/components/src/ui/input/index.ts | 1 + 8 files changed, 662 insertions(+), 274 deletions(-) create mode 100644 .claude/agents/react-architect.md create mode 100644 .claude/agents/tech-lead-orchestrator.md create mode 100644 .claude/agents/ui-design-engineer.md create mode 100644 packages/internal/components/src/ui/input/InputV2.tsx diff --git a/.claude/agents/react-architect.md b/.claude/agents/react-architect.md new file mode 100644 index 000000000..a83f1eee7 --- /dev/null +++ b/.claude/agents/react-architect.md @@ -0,0 +1,68 @@ +--- +name: react-architect +description: Use this agent when you need expert guidance on React architecture, performance optimization, or developer experience improvements. Examples: Context: User is working on a React component that's causing performance issues. user: 'This component is re-rendering too often and causing lag' assistant: 'I'll use the react-architect agent to analyze the performance issues and provide optimization recommendations' Since the user has a React performance issue, use the react-architect agent to provide expert analysis and solutions. Context: User is designing the architecture for a new feature in their React application. user: 'I need to add a complex data visualization feature to our dashboard' assistant: 'Let me use the react-architect agent to help design the optimal architecture for this feature' Since this involves React architectural decisions, use the react-architect agent to provide expert guidance on component structure and data flow. Context: User has written some React code and wants architectural feedback. user: 'Here's my new component structure for the user profile section' assistant: 'I'll use the react-architect agent to review the architectural decisions and suggest improvements' Since the user wants architectural review of React code, use the react-architect agent to provide expert analysis. +tools: Task, Bash, Glob, Grep, LS, ExitPlanMode, Read, Edit, MultiEdit, Write, NotebookRead, NotebookEdit, WebFetch, TodoWrite, WebSearch, ListMcpResourcesTool, ReadMcpResourceTool, mcp__context7__resolve-library-id, mcp__context7__get-library-docs, mcp__ide__getDiagnostics, mcp__ide__executeCode +color: cyan +--- + +You are a React Architecture Expert, a seasoned front-end engineer with deep expertise in React philosophy, performance optimization, and developer experience (DX). You specialize in creating scalable, maintainable React applications and have extensive experience with modern React patterns, state management, and performance optimization techniques. + +Your core responsibilities: + +**Architectural Design & Review:** + +- Analyze existing React component structures and propose improvements +- Design optimal component hierarchies and data flow patterns +- Evaluate state management strategies (local state, context, external stores) +- Assess component composition vs inheritance patterns +- Review prop drilling issues and suggest solutions +- Recommend appropriate abstraction levels and separation of concerns + +**Performance Optimization:** + +- Identify and resolve unnecessary re-renders using React DevTools insights +- Implement memoization strategies (React.memo, useMemo, useCallback) +- Optimize bundle splitting and lazy loading patterns +- Analyze and improve Core Web Vitals metrics +- Implement efficient list rendering and virtualization when needed +- Optimize context usage to prevent performance bottlenecks +- Suggest code splitting strategies for better loading performance + +**Developer Experience Enhancement:** + +- Improve component APIs for better usability and type safety +- Design reusable component patterns and custom hooks +- Establish consistent naming conventions and file organization +- Recommend tooling improvements (ESLint rules, TypeScript configurations) +- Create developer-friendly error boundaries and debugging utilities +- Suggest testing strategies that improve confidence without hindering development speed + +**Project-Specific Considerations:** +Given this is a multi-platform monorepo (desktop, mobile, SSR) using modern React patterns: + +- Leverage shared components in `packages/internal/components/` effectively +- Optimize for cross-platform compatibility while maintaining performance +- Work within the existing Jotai/Zustand state management architecture +- Consider the implications of Electron, React Native, and SSR environments +- Align with the established Tailwind CSS and UIKit color system patterns +- Respect the existing build system (Vite, Turbo) and workspace structure + +**Code Review Approach:** + +1. **Analyze the current implementation** - Understand the existing patterns and constraints +2. **Identify architectural concerns** - Look for anti-patterns, performance issues, and maintainability problems +3. **Propose specific improvements** - Provide concrete, actionable suggestions with code examples +4. **Consider trade-offs** - Explain the benefits and potential drawbacks of each recommendation +5. **Prioritize changes** - Suggest which improvements should be tackled first based on impact and effort +6. **Validate against React principles** - Ensure suggestions align with React's declarative, component-based philosophy + +**Communication Style:** + +- Provide clear, actionable recommendations with reasoning +- Include code examples when suggesting changes +- Explain the 'why' behind architectural decisions +- Consider both immediate fixes and long-term architectural improvements +- Balance idealism with pragmatism based on project constraints +- Use performance metrics and concrete benefits to justify suggestions + +When reviewing code or designs, always consider the broader system impact, maintainability implications, and developer experience. Your goal is to help create React applications that are not only performant and scalable but also enjoyable to work with and extend. diff --git a/.claude/agents/tech-lead-orchestrator.md b/.claude/agents/tech-lead-orchestrator.md new file mode 100644 index 000000000..f60d8c060 --- /dev/null +++ b/.claude/agents/tech-lead-orchestrator.md @@ -0,0 +1,51 @@ +--- +name: tech-lead-orchestrator +description: Use this agent when you need comprehensive project management, quality oversight, or coordination of multiple development tasks. Examples: Context: User needs to implement a new feature that requires multiple components, testing, and documentation. user: 'I need to add a new RSS feed management system with UI components, API integration, and tests' assistant: 'I'll use the tech-lead-orchestrator agent to break this down into manageable tasks and coordinate the implementation across multiple areas.' Context: User wants to review overall project quality and identify areas for improvement. user: 'Can you review our current codebase and suggest improvements?' assistant: 'Let me use the tech-lead-orchestrator agent to conduct a comprehensive project quality assessment and provide strategic recommendations.' Context: User needs to coordinate multiple agents for a complex refactoring task. user: 'We need to refactor our state management across desktop and mobile apps' assistant: 'I'll engage the tech-lead-orchestrator agent to plan and coordinate this cross-platform refactoring effort.' +color: orange +--- + +You are a Tech Team Leader responsible for managing overall project quality and orchestrating sub-agents to complete complex development tasks. You have deep expertise in software architecture, project management, and quality assurance across the Follow RSS platform's multi-platform ecosystem (desktop Electron app, React Native mobile, SSR web application). + +Your core responsibilities: + +**Project Quality Management:** + +- Conduct comprehensive code quality assessments across all platforms +- Identify architectural inconsistencies and technical debt +- Ensure adherence to project coding standards and conventions +- Validate cross-platform compatibility and shared component usage +- Monitor performance implications of changes across desktop, mobile, and web + +**Task Orchestration:** + +- Break down complex features into manageable, coordinated tasks +- Identify dependencies between different components and platforms +- Delegate appropriate tasks to specialized sub-agents when available +- Ensure consistent implementation patterns across the monorepo +- Coordinate testing strategies for multi-platform features + +**Technical Leadership:** + +- Make architectural decisions that align with the project's Electron + React Native + SSR structure +- Ensure proper use of shared packages in `packages/internal/` +- Validate state management patterns using Jotai/Zustand across platforms +- Review database schema changes and migration strategies +- Oversee i18n implementation and maintain translation consistency + +**Quality Gates:** + +- Enforce the 500-line file limit rule through refactoring recommendations +- Ensure proper TypeScript usage and type safety +- Validate Tailwind CSS usage follows UIKit color system for desktop components +- Review error handling and logging strategies +- Confirm proper testing coverage and quality + +**Communication Style:** + +- Provide clear, actionable technical guidance +- Explain architectural decisions and their rationale +- Offer multiple solution approaches with trade-off analysis +- Create detailed implementation plans with clear milestones +- Proactively identify potential issues and mitigation strategies + +When coordinating tasks, always consider the project's unique multi-platform architecture, shared component strategy, and the need for consistency across desktop, mobile, and web experiences. Prioritize maintainability, performance, and user experience across all platforms. diff --git a/.claude/agents/ui-design-engineer.md b/.claude/agents/ui-design-engineer.md new file mode 100644 index 000000000..d92896d0e --- /dev/null +++ b/.claude/agents/ui-design-engineer.md @@ -0,0 +1,51 @@ +--- +name: ui-design-engineer +description: Use this agent when you need to create, modify, or enhance UI components and layouts that follow modern design principles and human-computer interaction guidelines. Examples include: building new React components with proper accessibility, implementing responsive layouts with Tailwind CSS, creating interactive elements with Framer Motion, designing component APIs that follow Radix UI patterns, refactoring existing UI to match Apple HIG or modern SaaS aesthetics (Vercel/Linear style), and ensuring UI components integrate seamlessly with the project's existing design system and UIKit color scheme. +tools: Task, Bash, Glob, Grep, LS, ExitPlanMode, Read, Edit, MultiEdit, Write, NotebookRead, NotebookEdit, WebFetch, TodoWrite, WebSearch, mcp__context7__resolve-library-id, mcp__context7__get-library-docs, mcp__ide__getDiagnostics, mcp__ide__executeCode +color: purple +--- + +You are an elite UI Design Engineer with deep expertise in modern front-end development and human-computer interaction design. You specialize in creating exceptional user interfaces using React, Tailwind CSS, Radix UI, and Framer Motion, with a strong foundation in the Apple Human Interface Guidelines and contemporary design systems like Vercel, Linear, and Apple's design language. + +**Core Responsibilities:** + +- Design and implement React components that prioritize usability, accessibility, and visual excellence +- Apply Tailwind CSS with precision, leveraging the project's UIKit color system (text-fill, bg-material, etc.) and design tokens +- Integrate Radix UI primitives for robust, accessible component foundations +- Implement smooth, purposeful animations using Framer Motion that enhance rather than distract from the user experience +- Ensure all UI adheres to Apple HIG principles: clarity, deference, and depth +- Create responsive designs that work seamlessly across desktop, tablet, and mobile viewports + +**Design Philosophy:** + +- Follow the project's established aesthetic: clean, modern, minimal design with subtle shadows, rounded corners, and excellent typography +- Prioritize user experience over visual complexity +- Implement progressive disclosure and intuitive information hierarchy +- Use consistent spacing, typography scales, and color relationships +- Design for accessibility first, ensuring proper contrast ratios, keyboard navigation, and screen reader compatibility + +**Technical Standards:** + +- Write semantic, well-structured React components with TypeScript interfaces +- Use proper Tailwind class organization and avoid arbitrary values unless absolutely necessary +- Implement Radix UI components correctly with proper ARIA attributes and keyboard interactions +- Create smooth, performance-optimized animations that respect user preferences (prefers-reduced-motion) +- Follow the project's import conventions and component organization patterns +- Ensure components are reusable, composable, and maintainable + +**Quality Assurance:** + +- Test components across different screen sizes and devices +- Validate accessibility using proper semantic HTML and ARIA attributes +- Ensure color contrast meets WCAG guidelines +- Verify animations perform smoothly and don't cause layout shifts +- Check that components integrate properly with the existing design system + +**Context Awareness:** + +- Always consider the component's role within the broader application architecture +- Maintain consistency with existing UI patterns and component APIs +- Respect the project's UIKit color system and design tokens +- Consider the user's workflow and how the component fits into their journey + +When implementing UI components, provide clear rationale for design decisions, explain accessibility considerations, and suggest improvements to enhance the overall user experience. Always prioritize user needs while maintaining technical excellence and design consistency. diff --git a/CLAUDE.md b/CLAUDE.md index 6e91955f0..1a6720f3b 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -232,3 +232,10 @@ Example: - **Styling**: Tailwind CSS, Framer Motion - **Database**: Drizzle ORM, SQLite - **Utils**: Day.js, Zod, i18next + +## Agent Guidelines + +- When performing tasks, you can call the corresponding sub agent to complete the specified task. + - tech-lead-orchestrator + - react-architect + - ui-design-engineer diff --git a/apps/desktop/layer/renderer/src/modules/settings/tabs/integration.tsx b/apps/desktop/layer/renderer/src/modules/settings/tabs/integration.tsx index af71345aa..9df2222cb 100644 --- a/apps/desktop/layer/renderer/src/modules/settings/tabs/integration.tsx +++ b/apps/desktop/layer/renderer/src/modules/settings/tabs/integration.tsx @@ -1,4 +1,6 @@ +import { Collapse, CollapseGroup } from "@follow/components/ui/collapse/index.js" import { Divider } from "@follow/components/ui/divider/index.js" +import { InputV2 } from "@follow/components/ui/input/index.js" import { SimpleIconsCubox, SimpleIconsEagle, @@ -9,7 +11,7 @@ import { SimpleIconsReadwise, SimpleIconsZotero, } from "@follow/components/ui/platform-icon/icons.js" -import { useEffect } from "react" +import { useEffect, useMemo, useState } from "react" import { useTranslation } from "react-i18next" import { setIntegrationSetting, useIntegrationSettingValue } from "~/atoms/settings/integration" @@ -24,287 +26,405 @@ const { defineSettingItem, SettingBuilder } = createSetting( export const SettingIntegration = () => { const { t } = useTranslation("settings") const setSync = useSetSettingCanSync() + const [searchQuery, setSearchQuery] = useState("") + const settings = useIntegrationSettingValue() + useEffect(() => { setSync(false) return () => { setSync(true) } }, [setSync]) + + const integrationCategories = useMemo(() => { + const knowledgeManagement = { + id: "knowledge", + title: t("integration.categories.knowledge_management"), + icon: , + integrations: [ + { + key: "cubox", + title: t("integration.cubox.title"), + icon: , + enabled: settings.enableCubox, + configured: Boolean(settings.cuboxToken), + settings: [ + defineSettingItem("enableCubox", { + label: t("integration.cubox.enable.label"), + description: t("integration.cubox.enable.description"), + }), + defineSettingItem("cuboxToken", { + label: t("integration.cubox.token.label"), + vertical: true, + type: "password", + description: ( + <> + {t("integration.cubox.token.description")}{" "} + + https://cubox.pro/my/settings/extensions + + + ), + }), + defineSettingItem("enableCuboxAutoMemo", { + label: t("integration.cubox.autoMemo.label"), + description: t("integration.cubox.autoMemo.description"), + }), + ], + }, + { + key: "obsidian", + title: t("integration.obsidian.title"), + icon: , + enabled: settings.enableObsidian, + configured: Boolean(settings.obsidianVaultPath), + settings: [ + defineSettingItem("enableObsidian", { + label: t("integration.obsidian.enable.label"), + description: t("integration.obsidian.enable.description"), + }), + defineSettingItem("obsidianVaultPath", { + label: t("integration.obsidian.vaultPath.label"), + vertical: true, + description: t("integration.obsidian.vaultPath.description"), + }), + ], + }, + { + key: "outline", + title: t("integration.outline.title"), + icon: , + enabled: settings.enableOutline, + configured: Boolean(settings.outlineEndpoint && settings.outlineToken), + settings: [ + defineSettingItem("enableOutline", { + label: t("integration.outline.enable.label"), + description: t("integration.outline.enable.description"), + }), + defineSettingItem("outlineEndpoint", { + label: t("integration.outline.endpoint.label"), + vertical: true, + description: t("integration.outline.endpoint.description"), + }), + defineSettingItem("outlineToken", { + label: t("integration.outline.token.label"), + vertical: true, + type: "password", + description: t("integration.outline.token.description"), + }), + defineSettingItem("outlineCollection", { + label: t("integration.outline.collection.label"), + vertical: true, + description: t("integration.outline.collection.description"), + }), + ], + }, + { + key: "readwise", + title: t("integration.readwise.title"), + icon: , + enabled: settings.enableReadwise, + configured: Boolean(settings.readwiseToken), + settings: [ + defineSettingItem("enableReadwise", { + label: t("integration.readwise.enable.label"), + description: t("integration.readwise.enable.description"), + }), + defineSettingItem("readwiseToken", { + label: t("integration.readwise.token.label"), + vertical: true, + type: "password", + description: ( + <> + {t("integration.readwise.token.description")}{" "} + + readwise.io/access_token + + . + + ), + }), + ], + }, + { + key: "zotero", + title: t("integration.zotero.title"), + icon: , + enabled: settings.enableZotero, + configured: Boolean(settings.zoteroUserID && settings.zoteroToken), + settings: [ + defineSettingItem("enableZotero", { + label: t("integration.zotero.enable.label"), + description: t("integration.zotero.enable.description"), + }), + defineSettingItem("zoteroUserID", { + label: t("integration.zotero.userID.label"), + description: ( + <> + {t("integration.zotero.userID.description")}{" "} + + https://www.zotero.org/settings/keys + + + ), + vertical: true, + type: "password", + }), + defineSettingItem("zoteroToken", { + label: t("integration.zotero.token.label"), + description: ( + <> + {t("integration.zotero.token.description")}{" "} + + https://www.zotero.org/settings/keys/new + + + ), + vertical: true, + type: "password", + }), + ], + }, + ], + } + + const readingServices = { + id: "reading", + title: t("integration.categories.reading_services"), + icon: , + integrations: [ + { + key: "instapaper", + title: t("integration.instapaper.title"), + icon: , + enabled: settings.enableInstapaper, + configured: Boolean(settings.instapaperUsername && settings.instapaperPassword), + settings: [ + defineSettingItem("enableInstapaper", { + label: t("integration.instapaper.enable.label"), + description: t("integration.instapaper.enable.description"), + }), + defineSettingItem("instapaperUsername", { + label: t("integration.instapaper.username.label"), + vertical: true, + }), + defineSettingItem("instapaperPassword", { + label: t("integration.instapaper.password.label"), + vertical: true, + type: "password", + }), + ], + }, + { + key: "readeck", + title: t("integration.readeck.title"), + icon: , + enabled: settings.enableReadeck, + configured: Boolean(settings.readeckEndpoint && settings.readeckToken), + settings: [ + defineSettingItem("enableReadeck", { + label: t("integration.readeck.enable.label"), + description: t("integration.readeck.enable.description"), + }), + defineSettingItem("readeckEndpoint", { + label: t("integration.readeck.endpoint.label"), + vertical: true, + description: t("integration.readeck.endpoint.description"), + }), + defineSettingItem("readeckToken", { + label: t("integration.readeck.token.label"), + vertical: true, + type: "password", + description: t("integration.readeck.token.description"), + }), + ], + }, + ], + } + + const mediaTools = { + id: "media", + title: t("integration.categories.media_tools"), + icon: , + integrations: [ + { + key: "eagle", + title: t("integration.eagle.title"), + icon: , + enabled: settings.enableEagle, + configured: settings.enableEagle, + settings: [ + defineSettingItem("enableEagle", { + label: t("integration.eagle.enable.label"), + description: t("integration.eagle.enable.description"), + }), + ], + }, + ], + } + + const downloadTools = { + id: "download", + title: t("integration.categories.download_tools"), + icon: , + integrations: [ + { + key: "qbittorrent", + title: t("integration.qbittorrent.title"), + icon: , + enabled: settings.enableQBittorrent, + configured: Boolean(settings.qbittorrentHost && settings.qbittorrentUsername), + settings: [ + defineSettingItem("enableQBittorrent", { + label: t("integration.qbittorrent.enable.label"), + description: t("integration.qbittorrent.enable.description"), + }), + defineSettingItem("qbittorrentHost", { + label: t("integration.qbittorrent.host.label"), + vertical: true, + description: t("integration.qbittorrent.host.description"), + }), + defineSettingItem("qbittorrentUsername", { + label: t("integration.qbittorrent.username.label"), + vertical: true, + }), + defineSettingItem("qbittorrentPassword", { + label: t("integration.qbittorrent.password.label"), + vertical: true, + type: "password", + }), + ], + }, + ], + } + + return [knowledgeManagement, readingServices, mediaTools, downloadTools] + }, [t, settings]) + + const filteredCategories = useMemo(() => { + if (!searchQuery) return integrationCategories + + return integrationCategories + .map((category) => ({ + ...category, + integrations: category.integrations.filter((integration) => { + const matchesSearch = searchQuery + ? (integration.title as string).toLowerCase().includes(searchQuery.toLowerCase()) || + integration.key.toString().toLowerCase().includes(searchQuery.toLowerCase()) + : true + return matchesSearch + }), + })) + .filter((category) => category.integrations.length > 0) + }, [integrationCategories, searchQuery]) + + const shouldDefaultOpen = (category: any) => { + return category.integrations.some((integration: any) => integration.configured) + } + return ( -
- +
+
+ } + canClear + placeholder={t("integration.search.placeholder")} + value={searchQuery} + onChange={(e) => setSearchQuery(e.target.value)} + className="h-9" + /> +
- { - type: "title", - value: ( - - - {t("integration.cubox.title")} - - ), - }, - defineSettingItem("enableCubox", { - label: t("integration.cubox.enable.label"), - description: t("integration.cubox.enable.description"), - }), - defineSettingItem("cuboxToken", { - label: t("integration.cubox.token.label"), - vertical: true, - type: "password", - description: ( - <> - {t("integration.cubox.token.description")}{" "} - - https://cubox.pro/my/settings/extensions - - - ), - }), - defineSettingItem("enableCuboxAutoMemo", { - label: t("integration.cubox.autoMemo.label"), - description: t("integration.cubox.autoMemo.description"), - }), + +
- { - type: "title", - value: ( - - - {t("integration.eagle.title")} - - ), - }, - defineSettingItem("enableEagle", { - label: t("integration.eagle.enable.label"), - description: t("integration.eagle.enable.description"), - }), - - { - type: "title", - value: ( - - - {t("integration.instapaper.title")} - - ), - }, - defineSettingItem("enableInstapaper", { - label: t("integration.instapaper.enable.label"), - description: t("integration.instapaper.enable.description"), - }), - defineSettingItem("instapaperUsername", { - label: t("integration.instapaper.username.label"), - vertical: true, - }), - defineSettingItem("instapaperPassword", { - label: t("integration.instapaper.password.label"), - vertical: true, - type: "password", - }), - - { - type: "title", - value: ( - - - {t("integration.readeck.title")} - - ), - }, - defineSettingItem("enableReadeck", { - label: t("integration.readeck.enable.label"), - description: t("integration.readeck.enable.description"), - }), - defineSettingItem("readeckEndpoint", { - label: t("integration.readeck.endpoint.label"), - vertical: true, - description: t("integration.readeck.endpoint.description"), - }), - defineSettingItem("readeckToken", { - label: t("integration.readeck.token.label"), - vertical: true, - type: "password", - description: t("integration.readeck.token.description"), - }), - - { - type: "title", - value: ( - - - {t("integration.readwise.title")} - - ), - }, - defineSettingItem("enableReadwise", { - label: t("integration.readwise.enable.label"), - description: t("integration.readwise.enable.description"), - }), - defineSettingItem("readwiseToken", { - label: t("integration.readwise.token.label"), - vertical: true, - type: "password", - description: ( - <> - {t("integration.readwise.token.description")}{" "} - - readwise.io/access_token - - . - - ), - }), - - { - type: "title", - value: ( - - - {t("integration.obsidian.title")} - - ), - }, - defineSettingItem("enableObsidian", { - label: t("integration.obsidian.enable.label"), - description: t("integration.obsidian.enable.description"), - }), - defineSettingItem("obsidianVaultPath", { - label: t("integration.obsidian.vaultPath.label"), - vertical: true, - description: t("integration.obsidian.vaultPath.description"), - }), - - { - type: "title", - value: ( - - - {t("integration.outline.title")} - - ), - }, - defineSettingItem("enableOutline", { - label: t("integration.outline.enable.label"), - description: t("integration.outline.enable.description"), - }), - defineSettingItem("outlineEndpoint", { - label: t("integration.outline.endpoint.label"), - vertical: true, - description: t("integration.outline.endpoint.description"), - }), - defineSettingItem("outlineToken", { - label: t("integration.outline.token.label"), - vertical: true, - type: "password", - description: t("integration.outline.token.description"), - }), - defineSettingItem("outlineCollection", { - label: t("integration.outline.collection.label"), - vertical: true, - description: t("integration.outline.collection.description"), - }), - - { - type: "title", - value: ( - - - {t("integration.zotero.title")} - - ), - }, - defineSettingItem("enableZotero", { - label: t("integration.zotero.enable.label"), - description: t("integration.zotero.enable.description"), - }), - defineSettingItem("zoteroUserID", { - // https://www.zotero.org/settings/keys - label: t("integration.zotero.userID.label"), - description: ( - <> - {t("integration.zotero.userID.description")}{" "} - - https://www.zotero.org/settings/keys - - - ), - vertical: true, - type: "password", - }), - defineSettingItem("zoteroToken", { - // https://www.zotero.org/settings/keys/new - label: t("integration.zotero.token.label"), - description: ( - <> - {t("integration.zotero.token.description")}{" "} - - https://www.zotero.org/settings/keys/new - - - ), - vertical: true, - type: "password", - }), - - { - type: "title", - value: ( - - - {t("integration.qbittorrent.title")} - - ), - }, - defineSettingItem("enableQBittorrent", { - label: t("integration.qbittorrent.enable.label"), - description: t("integration.qbittorrent.enable.description"), - }), - defineSettingItem("qbittorrentHost", { - label: t("integration.qbittorrent.host.label"), - vertical: true, - description: t("integration.qbittorrent.host.description"), - }), - defineSettingItem("qbittorrentUsername", { - label: t("integration.qbittorrent.username.label"), - vertical: true, - }), - defineSettingItem("qbittorrentPassword", { - label: t("integration.qbittorrent.password.label"), - vertical: true, - type: "password", - }), - - BottomTip, - ]} - /> + + <> + {filteredCategories.map((category) => ( + + + + {category.icon} + + {category.title as string} + + + {category.integrations.filter((i) => i.configured).length}/ + {category.integrations.length} + +
+ } + defaultOpen={shouldDefaultOpen(category)} + className="border-border bg-background rounded-lg border px-4 py-2 shadow-sm" + contentClassName="px-4 pb-4 pt-8" + > +
+ {category.integrations.map((integration) => ( +
+
+ + {integration.icon} + +

{integration.title}

+
+ {integration.configured && ( + + + {t("integration.status.configured")} + + )} + {integration.enabled && ( + + + {t("integration.status.enabled")} + + )} +
+
+
+ +
+
+ ))} +
+ + + ))} + +
) } @@ -314,7 +434,7 @@ const BottomTip = () => { return (
-

+

{t("integration.tip")}

diff --git a/locales/settings/en.json b/locales/settings/en.json index 7d770b4a1..3435ded83 100644 --- a/locales/settings/en.json +++ b/locales/settings/en.json @@ -318,6 +318,10 @@ "general.translation_mode.label": "AI Translation Mode", "general.translation_mode.translation-only": "Only the translation", "general.voices": "Voices", + "integration.categories.download_tools": "Download Tools", + "integration.categories.knowledge_management": "Knowledge Management", + "integration.categories.media_tools": "Media Tools", + "integration.categories.reading_services": "Reading Services", "integration.cubox.autoMemo.description": "Automatically use Memo mode when text is selected to save to Cubox.", "integration.cubox.autoMemo.label": "Auto Memo Mode", "integration.cubox.enable.description": "Show 'Save to Cubox' button if available.", @@ -368,7 +372,10 @@ "integration.readwise.token.description": "You can get it here: ", "integration.readwise.token.label": "Readwise Access Token", "integration.save_ai_summary_as_description.label": "Save AI Summary as description", + "integration.search.placeholder": "Search integrations...", "integration.sidebar_title": "Integration", + "integration.status.configured": "Configured", + "integration.status.enabled": "Enabled", "integration.tip": "Tip: Your sensitive data is stored locally and is not uploaded to the server.", "integration.title": "Integration", "integration.zotero.enable.description": "Show 'Save to Zotero' button if avilable.", diff --git a/packages/internal/components/src/ui/input/InputV2.tsx b/packages/internal/components/src/ui/input/InputV2.tsx new file mode 100644 index 000000000..3898b54f1 --- /dev/null +++ b/packages/internal/components/src/ui/input/InputV2.tsx @@ -0,0 +1,83 @@ +import { useInputComposition } from "@follow/hooks" +import { cn, stopPropagation } from "@follow/utils" +import type { DetailedHTMLProps, InputHTMLAttributes, ReactNode } from "react" +import { useState } from "react" + +export const InputV2 = ({ + ref, + className, + icon, + canClear, + ...props +}: Omit, HTMLInputElement>, "ref"> & { + icon?: ReactNode + canClear?: boolean +} & { ref?: React.RefObject }) => { + const [internalValue, setInternalValue] = useState(props.value || props.defaultValue || "") + + const inputProps = useInputComposition(props) + + const handleClear = () => { + setInternalValue("") + + if (props.onChange) { + const event = { + target: { value: "" }, + currentTarget: { value: "" }, + } as React.ChangeEvent + props.onChange(event) + } + } + + const handleChange = (e: React.ChangeEvent) => { + setInternalValue(e.target.value) + if (props.onChange) { + props.onChange(e) + } + } + + const showClearButton = canClear && internalValue + + return ( +
+ {icon && ( +
+ {icon} +
+ )} + + {showClearButton && ( + + )} +
+ ) +} diff --git a/packages/internal/components/src/ui/input/index.ts b/packages/internal/components/src/ui/input/index.ts index dc78a9b80..59f250887 100644 --- a/packages/internal/components/src/ui/input/index.ts +++ b/packages/internal/components/src/ui/input/index.ts @@ -1,3 +1,4 @@ export * from "./Input" +export * from "./InputV2" export * from "./OTP" export * from "./TextArea" From 7dd80f0a137486057d00c6fd2676d2b17faefe16 Mon Sep 17 00:00:00 2001 From: Innei Date: Mon, 28 Jul 2025 18:06:15 +0800 Subject: [PATCH 08/74] feat: add import/export functionality for integration settings - Implemented export feature to download integration settings as a JSON file. - Added import feature to upload and apply integration settings from a JSON file. - Enhanced user feedback with success and error notifications during import/export processes. - Updated localization files to include new strings for import/export actions. Signed-off-by: Innei --- apps/desktop/changelog/next.md | 2 + .../src/modules/settings/tabs/integration.tsx | 96 +++++++++++++++++-- locales/settings/en.json | 7 ++ locales/settings/ja.json | 7 ++ locales/settings/zh-CN.json | 7 ++ 5 files changed, 113 insertions(+), 6 deletions(-) diff --git a/apps/desktop/changelog/next.md b/apps/desktop/changelog/next.md index 8f5eac449..2f6b4e0f1 100644 --- a/apps/desktop/changelog/next.md +++ b/apps/desktop/changelog/next.md @@ -4,6 +4,8 @@ ## Improvements +- Redesign integration settings page for better user experience and support integration settings export and import. + ## No longer broken ## Thanks diff --git a/apps/desktop/layer/renderer/src/modules/settings/tabs/integration.tsx b/apps/desktop/layer/renderer/src/modules/settings/tabs/integration.tsx index 9df2222cb..de1026009 100644 --- a/apps/desktop/layer/renderer/src/modules/settings/tabs/integration.tsx +++ b/apps/desktop/layer/renderer/src/modules/settings/tabs/integration.tsx @@ -1,3 +1,4 @@ +import { Button } from "@follow/components/ui/button/index.js" import { Collapse, CollapseGroup } from "@follow/components/ui/collapse/index.js" import { Divider } from "@follow/components/ui/divider/index.js" import { InputV2 } from "@follow/components/ui/input/index.js" @@ -13,8 +14,14 @@ import { } from "@follow/components/ui/platform-icon/icons.js" import { useEffect, useMemo, useState } from "react" import { useTranslation } from "react-i18next" +import { toast } from "sonner" -import { setIntegrationSetting, useIntegrationSettingValue } from "~/atoms/settings/integration" +import { + getIntegrationSettings, + setIntegrationSetting, + useIntegrationSettingValue, +} from "~/atoms/settings/integration" +import { downloadJsonFile, selectJsonFile } from "~/lib/export" import { createSetting } from "../helper/builder" import { useSetSettingCanSync } from "../modal/hooks" @@ -380,7 +387,7 @@ export const SettingIntegration = () => { {category.icon} {category.title as string} - + {category.integrations.filter((i) => i.configured).length}/ {category.integrations.length} @@ -431,12 +438,89 @@ export const SettingIntegration = () => { const BottomTip = () => { const { t } = useTranslation("settings") + + const handleExport = () => { + try { + const settings = getIntegrationSettings() + const jsonData = JSON.stringify(settings, null, 2) + const filename = `follow-integration-settings-${new Date().toISOString().split("T")[0]}.json` + downloadJsonFile(jsonData, filename) + toast.success(t("integration.export.success")) + } catch (error) { + console.error("Failed to export integration settings:", error) + toast.error(t("integration.export.error")) + } + } + + const handleImport = async () => { + try { + const jsonData = await selectJsonFile() + const settings = JSON.parse(jsonData) + + // Validate the imported settings structure + if (typeof settings !== "object" || settings === null) { + throw new Error("Invalid settings format") + } + + // Get current settings to use as a base for validation + const currentSettings = getIntegrationSettings() + + // Only apply settings that exist in the current schema + let importCount = 0 + Object.entries(settings).forEach(([key, value]) => { + if (key in currentSettings) { + setIntegrationSetting(key as any, value) + importCount++ + } + }) + + if (importCount === 0) { + throw new Error("No valid settings found in the imported file") + } + + toast.success(t("integration.import.success")) + } catch (error) { + if (error instanceof Error && error.message === "No file selected") { + // User cancelled file selection, don't show error + return + } + console.error("Failed to import integration settings:", error) + if (error instanceof SyntaxError) { + toast.error(t("integration.import.invalid")) + } else { + toast.error(t("integration.import.error")) + } + } + } + return ( -
+
-

- {t("integration.tip")} -

+
+

+ {t("integration.tip")} +

+
+ + +
+
) } diff --git a/locales/settings/en.json b/locales/settings/en.json index 3435ded83..a43b85dda 100644 --- a/locales/settings/en.json +++ b/locales/settings/en.json @@ -332,7 +332,14 @@ "integration.eagle.enable.description": "Display 'Save media to Eagle' button when available.", "integration.eagle.enable.label": "Enable", "integration.eagle.title": "Eagle", + "integration.export.button": "Export Settings", + "integration.export.error": "Failed to export integration settings", + "integration.export.success": "Integration settings exported successfully", "integration.general": "General", + "integration.import.button": "Import Settings", + "integration.import.error": "Failed to import integration settings", + "integration.import.invalid": "Invalid integration settings file", + "integration.import.success": "Integration settings imported successfully", "integration.instapaper.enable.description": "Display 'Save to Instapaper' button when available.", "integration.instapaper.enable.label": "Enable", "integration.instapaper.password.label": "Instapaper Password", diff --git a/locales/settings/ja.json b/locales/settings/ja.json index d7bfe1580..e4fe6df97 100644 --- a/locales/settings/ja.json +++ b/locales/settings/ja.json @@ -328,7 +328,14 @@ "integration.eagle.enable.description": "åˆ©ē”ØåÆčƒ½ćŖå “åˆć€'Eagle ć«ćƒ”ćƒ‡ć‚£ć‚¢ć‚’äæå­˜' ćƒœć‚æćƒ³ć‚’č”Øē¤ŗć—ć¾ć™ć€‚", "integration.eagle.enable.label": "ęœ‰åŠ¹åŒ–", "integration.eagle.title": "Eagle", + "integration.export.button": "čØ­å®šć‚’ć‚Øć‚Æć‚¹ćƒćƒ¼ćƒˆ", + "integration.export.error": "ēµ±åˆčØ­å®šć®ć‚Øć‚Æć‚¹ćƒćƒ¼ćƒˆć«å¤±ę•—ć—ć¾ć—ćŸ", + "integration.export.success": "ēµ±åˆčØ­å®šć®ć‚Øć‚Æć‚¹ćƒćƒ¼ćƒˆćŒęˆåŠŸć—ć¾ć—ćŸ", "integration.general": "äø€čˆ¬", + "integration.import.button": "čØ­å®šć‚’ć‚¤ćƒ³ćƒćƒ¼ćƒˆ", + "integration.import.error": "ēµ±åˆčØ­å®šć®ć‚¤ćƒ³ćƒćƒ¼ćƒˆć«å¤±ę•—ć—ć¾ć—ćŸ", + "integration.import.invalid": "ē„”åŠ¹ćŖēµ±åˆčØ­å®šćƒ•ć‚”ć‚¤ćƒ«ć§ć™", + "integration.import.success": "ēµ±åˆčØ­å®šć®ć‚¤ćƒ³ćƒćƒ¼ćƒˆćŒęˆåŠŸć—ć¾ć—ćŸ", "integration.instapaper.enable.description": "åˆ©ē”ØåÆčƒ½ćŖå “åˆć€'Instapaper ć«äæå­˜' ćƒœć‚æćƒ³ć‚’č”Øē¤ŗć—ć¾ć™ć€‚", "integration.instapaper.enable.label": "ęœ‰åŠ¹åŒ–", "integration.instapaper.password.label": "Instapaper ćƒ‘ć‚¹ćƒÆćƒ¼ćƒ‰", diff --git a/locales/settings/zh-CN.json b/locales/settings/zh-CN.json index 768a45d3c..450b438b7 100644 --- a/locales/settings/zh-CN.json +++ b/locales/settings/zh-CN.json @@ -323,7 +323,14 @@ "integration.eagle.enable.description": "ę˜¾ē¤ŗć€Œäæå­˜åˆ° Eagleć€ęŒ‰é’®ļ¼ˆå¦‚ęžœåÆē”Øļ¼‰ć€‚", "integration.eagle.enable.label": "启用", "integration.eagle.title": "Eagle", + "integration.export.button": "导出设置", + "integration.export.error": "åÆ¼å‡ŗé›†ęˆč®¾ē½®å¤±č“„", + "integration.export.success": "é›†ęˆč®¾ē½®åÆ¼å‡ŗęˆåŠŸ", "integration.general": "é€šē”Ø", + "integration.import.button": "导兄设置", + "integration.import.error": "åÆ¼å…„é›†ęˆč®¾ē½®å¤±č“„", + "integration.import.invalid": "ę— ę•ˆēš„é›†ęˆč®¾ē½®ę–‡ä»¶", + "integration.import.success": "é›†ęˆč®¾ē½®åÆ¼å…„ęˆåŠŸ", "integration.instapaper.enable.description": "ę˜¾ē¤ŗć€Œäæå­˜åˆ° Instapaperć€ęŒ‰é’®ļ¼ˆå¦‚ęžœåÆē”Øļ¼‰ć€‚", "integration.instapaper.enable.label": "启用", "integration.instapaper.password.label": "密码", From 913ea3bc0dd5870c04518ba8a9e93ff79e087032 Mon Sep 17 00:00:00 2001 From: Stephen Zhou <38493346+hyoban@users.noreply.github.com> Date: Mon, 28 Jul 2025 23:57:58 +0800 Subject: [PATCH 09/74] fix: update subscription --- .../src/hooks/biz/useSubscriptionActions.tsx | 24 ++++------ .../src/modules/discover/FeedForm.tsx | 40 ++++++---------- .../src/modules/discover/ListForm.tsx | 46 ++++++------------- .../entry-column/hooks/useEntriesByView.ts | 1 + packages/internal/store/src/entry/hooks.ts | 2 +- .../internal/store/src/subscription/store.ts | 12 +++-- pnpm-lock.yaml | 20 ++++---- pnpm-workspace.yaml | 2 +- 8 files changed, 56 insertions(+), 91 deletions(-) diff --git a/apps/desktop/layer/renderer/src/hooks/biz/useSubscriptionActions.tsx b/apps/desktop/layer/renderer/src/hooks/biz/useSubscriptionActions.tsx index 7a3096fc9..d6958f9fd 100644 --- a/apps/desktop/layer/renderer/src/hooks/biz/useSubscriptionActions.tsx +++ b/apps/desktop/layer/renderer/src/hooks/biz/useSubscriptionActions.tsx @@ -1,14 +1,11 @@ import { Kbd } from "@follow/components/ui/kbd/Kbd.js" import { subscriptionSyncService } from "@follow/store/subscription/store" import type { SubscriptionModel } from "@follow/store/subscription/types" -import { unreadActions } from "@follow/store/unread/store" import { useMutation } from "@tanstack/react-query" import { useHotkeys } from "react-hotkeys-hook" import { Trans, useTranslation } from "react-i18next" import { toast } from "sonner" -import { apiClient } from "~/lib/api-fetch" - import { navigateEntry } from "./useNavigateEntry" import { getRouteParams } from "./useRouteParams" @@ -39,19 +36,16 @@ export const useDeleteSubscription = ({ onSuccess }: { onSuccess?: () => void } if (!subscription) return if (!feed) return const undo = async () => { - // TODO store action - const { unread } = await apiClient.subscriptions.$post({ - json: { - url: feed.type === "feed" ? feed.url : undefined, - listId: feed.type === "list" ? feed.id : undefined, - view: subscription.view, - category: subscription.category, - isPrivate: subscription.isPrivate, - }, + await subscriptionSyncService.subscribe({ + url: feed.type === "feed" ? feed.url : undefined, + listId: feed.type === "list" ? feed.id : undefined, + view: subscription.view, + category: subscription.category, + isPrivate: subscription.isPrivate, + feedId: feed.id, + title: feed.title, + hideFromTimeline: subscription.hideFromTimeline, }) - unreadActions.upsertMany(unread) - - subscriptionSyncService.fetch() toast.dismiss(toastId) } diff --git a/apps/desktop/layer/renderer/src/modules/discover/FeedForm.tsx b/apps/desktop/layer/renderer/src/modules/discover/FeedForm.tsx index 2b3e7948e..5e9c82ae0 100644 --- a/apps/desktop/layer/renderer/src/modules/discover/FeedForm.tsx +++ b/apps/desktop/layer/renderer/src/modules/discover/FeedForm.tsx @@ -15,11 +15,10 @@ import { ScrollArea } from "@follow/components/ui/scroll-area/index.js" import { Switch } from "@follow/components/ui/switch/index.jsx" import { FeedViewType } from "@follow/constants" import type { EntryModelSimple, FeedAnalyticsModel, FeedModel } from "@follow/models/types" -import { invalidateEntriesQuery } from "@follow/store/entry/hooks" import { useFeedByIdOrUrl } from "@follow/store/feed/hooks" import { useCategories, useSubscriptionByFeedId } from "@follow/store/subscription/hooks" import { subscriptionSyncService } from "@follow/store/subscription/store" -import { unreadActions } from "@follow/store/unread/store" +import { whoami } from "@follow/store/user/getters" import { tracker } from "@follow/tracker" import { cn } from "@follow/utils/utils" import { zodResolver } from "@hookform/resolvers/zod" @@ -30,12 +29,10 @@ import { useTranslation } from "react-i18next" import { toast } from "sonner" import { z } from "zod" -import { getGeneralSettings } from "~/atoms/settings/general" import { Autocomplete } from "~/components/ui/auto-completion" import { useCurrentModal, useIsInModal } from "~/components/ui/modal/stacked/hooks" import { getRouteParams } from "~/hooks/biz/useRouteParams" import { useI18n } from "~/hooks/common" -import { apiClient } from "~/lib/api-fetch" import { toastFetchError } from "~/lib/error-parser" import { feed as feedQuery, useFeedQuery } from "~/queries/feed" @@ -239,34 +236,27 @@ const FeedInnerForm = ({ const followMutation = useMutation({ mutationFn: async (values: z.infer) => { + const userId = whoami()?.id || "" const body = { url: feed.url, view: Number.parseInt(values.view), category: values.category, - isPrivate: values.isPrivate, + isPrivate: values.isPrivate || false, hideFromTimeline: values.hideFromTimeline, title: values.title, feedId: feed.id, - } - const $method = isSubscribed ? apiClient.subscriptions.$patch : apiClient.subscriptions.$post + userId, + type: "feed", + listId: undefined, + } as const - return $method({ - json: body, - }) as unknown as Promise< - | ReturnType - | ReturnType - > + if (isSubscribed) { + return subscriptionSyncService.edit(body) + } else { + return subscriptionSyncService.subscribe(body) + } }, - onSuccess: (data, variables) => { - if (getGeneralSettings().hidePrivateSubscriptionsInTimeline) { - invalidateEntriesQuery({ views: [Number(variables.view)] }) - } - - if ("unread" in data) { - unreadActions.upsertMany(data.unread) - } - subscriptionSyncService.fetch() - + onSuccess: () => { const feedId = feed.id if (feedId) { feedQuery.byId({ id: feedId }).invalidate() @@ -275,10 +265,6 @@ const FeedInnerForm = ({ duration: 1000, }) - if (!isSubscribed) { - tracker.subscribe({ feedId: feed.id, view: Number.parseInt(variables.view) }) - } - onSuccess?.() }, onError(err) { diff --git a/apps/desktop/layer/renderer/src/modules/discover/ListForm.tsx b/apps/desktop/layer/renderer/src/modules/discover/ListForm.tsx index 5708842d1..e1499a4d5 100644 --- a/apps/desktop/layer/renderer/src/modules/discover/ListForm.tsx +++ b/apps/desktop/layer/renderer/src/modules/discover/ListForm.tsx @@ -13,12 +13,11 @@ import { LoadingCircle } from "@follow/components/ui/loading/index.jsx" import { Switch } from "@follow/components/ui/switch/index.jsx" import { FeedViewType } from "@follow/constants" import type { ListAnalyticsModel } from "@follow/models/types" -import { invalidateEntriesQuery } from "@follow/store/entry/hooks" import { useListById, usePrefetchListById } from "@follow/store/list/hooks" import type { ListModel } from "@follow/store/list/types" import { useSubscriptionByFeedId } from "@follow/store/subscription/hooks" import { subscriptionSyncService } from "@follow/store/subscription/store" -import { unreadActions } from "@follow/store/unread/store" +import { whoami } from "@follow/store/user/getters" import { tracker } from "@follow/tracker" import { cn } from "@follow/utils/utils" import { zodResolver } from "@hookform/resolvers/zod" @@ -29,10 +28,8 @@ import { useTranslation } from "react-i18next" import { toast } from "sonner" import { z } from "zod" -import { getGeneralSettings } from "~/atoms/settings/general" import { useCurrentModal } from "~/components/ui/modal/stacked/hooks" import { useI18n } from "~/hooks/common" -import { apiClient } from "~/lib/api-fetch" import { getFetchErrorMessage, toastFetchError } from "~/lib/error-parser" import { getNewIssueUrl } from "~/lib/issues" @@ -213,47 +210,32 @@ const ListInnerForm = ({ const followMutation = useMutation({ mutationFn: async (values: z.infer & { TOTPCode?: string }) => { + const userId = whoami()?.id || "" const body = { listId: list.id, view: Number.parseInt(values.view), category: values.category, - isPrivate: values.isPrivate, + isPrivate: values.isPrivate || false, hideFromTimeline: values.hideFromTimeline, title: values.title, TOTPCode: values.TOTPCode, - } - const $method = isSubscribed ? apiClient.subscriptions.$patch : apiClient.subscriptions.$post + userId, + type: "list", + url: undefined, + feedId: undefined, + } as const - return $method({ - json: body, - }) as unknown as Promise< - | ReturnType - | ReturnType - > + if (isSubscribed) { + return subscriptionSyncService.edit(body) + } else { + return subscriptionSyncService.subscribe(body) + } }, - onSuccess: (data, variables) => { - if (getGeneralSettings().hidePrivateSubscriptionsInTimeline) { - invalidateEntriesQuery({ views: [Number(variables.view)] }) - } - - if ("unread" in data) { - const { unread } = data - unreadActions.upsertMany(unread) - } - subscriptionSyncService.fetch() - - const listId = list.id - if (listId) { - // listsQuery.byId({ id: listId }).invalidate() - } + onSuccess: () => { toast(isSubscribed ? t("feed_form.updated") : t("feed_form.followed"), { duration: 1000, }) - if (!isSubscribed) { - tracker.subscribe({ listId: list.id, view: Number.parseInt(variables.view) }) - } - onSuccess?.() }, async onError(err) { diff --git a/apps/desktop/layer/renderer/src/modules/entry-column/hooks/useEntriesByView.ts b/apps/desktop/layer/renderer/src/modules/entry-column/hooks/useEntriesByView.ts index ce5e8de04..384e280ad 100644 --- a/apps/desktop/layer/renderer/src/modules/entry-column/hooks/useEntriesByView.ts +++ b/apps/desktop/layer/renderer/src/modules/entry-column/hooks/useEntriesByView.ts @@ -182,6 +182,7 @@ const useLocalEntries = (): UseEntriesReturn => { entryIdsByInboxId, entryIdsByListId, entryIdsByView, + isCollection, showEntriesByView, unreadOnly, ], diff --git a/packages/internal/store/src/entry/hooks.ts b/packages/internal/store/src/entry/hooks.ts index 79935d395..60b23e25a 100644 --- a/packages/internal/store/src/entry/hooks.ts +++ b/packages/internal/store/src/entry/hooks.ts @@ -172,7 +172,7 @@ export const useEntryIdsByView = (view: FeedViewType, excludePrivate: boolean | return Array.from(ids) .filter((id) => { const subscription = getSubscriptionByEntryId(id) - if (excludePrivate && subscription?.isPrivate) { + if ((excludePrivate && subscription?.isPrivate) || subscription?.hideFromTimeline) { return false } return true diff --git a/packages/internal/store/src/subscription/store.ts b/packages/internal/store/src/subscription/store.ts index ebbc1f4c3..09c34760d 100644 --- a/packages/internal/store/src/subscription/store.ts +++ b/packages/internal/store/src/subscription/store.ts @@ -243,12 +243,9 @@ class SubscriptionSyncService { }) tx.request(async () => { await api().subscriptions.update({ - view: subscription.view, + ...subscription, feedId: subscription.feedId ?? undefined, - isPrivate: subscription.isPrivate ?? undefined, listId: subscription.listId ?? undefined, - category: subscription.category ?? undefined, - title: subscription.title ?? undefined, }) }) @@ -257,6 +254,8 @@ class SubscriptionSyncService { }) await tx.run() + + invalidateEntriesQuery({ views: [subscription.view] }) } async subscribe(subscription: SubscriptionForm) { @@ -283,8 +282,9 @@ class SubscriptionSyncService { if (data.unread) { unreadActions.upsertMany(data.unread) } + // Insert to subscription - subscriptionActions.upsertMany([ + await subscriptionActions.upsertMany([ { ...subscription, title: subscription.title ?? null, @@ -298,6 +298,8 @@ class SubscriptionSyncService { userId: whoami()?.id ?? "", }, ]) + + invalidateEntriesQuery({ views: [subscription.view] }) } async unsubscribe(id: string | undefined | null | (string | undefined | null)[]) { diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 13e4cf434..58c94f4a0 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -7,8 +7,8 @@ settings: catalogs: default: '@follow-app/client-sdk': - specifier: 0.3.24 - version: 0.3.24 + specifier: 0.3.25 + version: 0.3.25 typescript: specifier: 5.8.3 version: 5.8.3 @@ -461,7 +461,7 @@ importers: version: 3.0.2(electron@37.2.0) '@follow-app/client-sdk': specifier: 'catalog:' - version: 0.3.24(@opentelemetry/api@1.9.0)(@types/pg@8.6.1)(expo-sqlite@15.2.12(expo@53.0.12(@babel/core@7.28.0)(@expo/metro-runtime@5.0.4(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0)))(bufferutil@4.0.9)(graphql@16.8.1)(react-native-webview@13.15.0(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(kysely@0.28.2)(pg@8.16.3) + version: 0.3.25(@opentelemetry/api@1.9.0)(@types/pg@8.6.1)(expo-sqlite@15.2.12(expo@53.0.12(@babel/core@7.28.0)(@expo/metro-runtime@5.0.4(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0)))(bufferutil@4.0.9)(graphql@16.8.1)(react-native-webview@13.15.0(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(kysely@0.28.2)(pg@8.16.3) '@follow/database': specifier: workspace:* version: link:../../../../packages/internal/database @@ -1627,7 +1627,7 @@ importers: dependencies: '@follow-app/client-sdk': specifier: 'catalog:' - version: 0.3.24(@opentelemetry/api@1.9.0)(@types/pg@8.6.1)(expo-sqlite@15.2.12(expo@53.0.12(@babel/core@7.28.0)(@expo/metro-runtime@5.0.4(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0)))(bufferutil@4.0.9)(graphql@16.8.1)(react-native-webview@13.15.0(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(kysely@0.28.2)(pg@8.16.3) + version: 0.3.25(@opentelemetry/api@1.9.0)(@types/pg@8.6.1)(expo-sqlite@15.2.12(expo@53.0.12(@babel/core@7.28.0)(@expo/metro-runtime@5.0.4(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0)))(bufferutil@4.0.9)(graphql@16.8.1)(react-native-webview@13.15.0(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(kysely@0.28.2)(pg@8.16.3) '@follow/configs': specifier: workspace:* version: link:../../configs @@ -1639,7 +1639,7 @@ importers: dependencies: '@follow-app/client-sdk': specifier: 'catalog:' - version: 0.3.24(@opentelemetry/api@1.9.0)(@types/pg@8.6.1)(expo-sqlite@15.2.12(expo@53.0.12(@babel/core@7.28.0)(@expo/metro-runtime@5.0.4(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0)))(bufferutil@4.0.9)(graphql@16.8.1)(react-native-webview@13.15.0(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(kysely@0.28.2)(pg@8.16.3) + version: 0.3.25(@opentelemetry/api@1.9.0)(@types/pg@8.6.1)(expo-sqlite@15.2.12(expo@53.0.12(@babel/core@7.28.0)(@expo/metro-runtime@5.0.4(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0)))(bufferutil@4.0.9)(graphql@16.8.1)(react-native-webview@13.15.0(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(kysely@0.28.2)(pg@8.16.3) '@follow/constants': specifier: workspace:* version: link:../constants @@ -1717,7 +1717,7 @@ importers: dependencies: '@follow-app/client-sdk': specifier: 'catalog:' - version: 0.3.24(@opentelemetry/api@1.9.0)(@types/pg@8.6.1)(expo-sqlite@15.2.12(expo@53.0.12(@babel/core@7.28.0)(@expo/metro-runtime@5.0.4(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0)))(bufferutil@4.0.9)(graphql@16.8.1)(react-native-webview@13.15.0(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(kysely@0.28.2)(pg@8.16.3) + version: 0.3.25(@opentelemetry/api@1.9.0)(@types/pg@8.6.1)(expo-sqlite@15.2.12(expo@53.0.12(@babel/core@7.28.0)(@expo/metro-runtime@5.0.4(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0)))(bufferutil@4.0.9)(graphql@16.8.1)(react-native-webview@13.15.0(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(kysely@0.28.2)(pg@8.16.3) '@follow/constants': specifier: workspace:* version: link:../constants @@ -1781,7 +1781,7 @@ importers: dependencies: '@follow-app/client-sdk': specifier: 'catalog:' - version: 0.3.24(@opentelemetry/api@1.9.0)(@types/pg@8.6.1)(expo-sqlite@15.2.12(expo@53.0.12(@babel/core@7.28.0)(@expo/metro-runtime@5.0.4(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0)))(bufferutil@4.0.9)(graphql@16.8.1)(react-native-webview@13.15.0(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(kysely@0.28.2)(pg@8.16.3) + version: 0.3.25(@opentelemetry/api@1.9.0)(@types/pg@8.6.1)(expo-sqlite@15.2.12(expo@53.0.12(@babel/core@7.28.0)(@expo/metro-runtime@5.0.4(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0)))(bufferutil@4.0.9)(graphql@16.8.1)(react-native-webview@13.15.0(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(kysely@0.28.2)(pg@8.16.3) '@follow/configs': specifier: workspace:* version: link:../../configs @@ -4039,8 +4039,8 @@ packages: '@floating-ui/utils@0.2.9': resolution: {integrity: sha512-MDWhGtE+eHw5JW7lq4qhc5yRLS11ERl1c7Z6Xd0a58DozHES6EnNNwUWbMiG4J9Cgj053Bhk8zvlhFYKVhULwg==} - '@follow-app/client-sdk@0.3.24': - resolution: {integrity: sha512-lR22RZrhXrHoHRz+C8/9ccU8vl9kaMq83NaeSNQq6TfJU645TiA/GQu2pHE0H8N9KRUPzE/P82bAnye59dyBUA==} + '@follow-app/client-sdk@0.3.25': + resolution: {integrity: sha512-+x9x3bvcCedkqH2ypw1ae2zYySzT70FniC9LH8/TdqpYKIUzQZaMSZxGNIA9KaAQT1EtvL9e7lO07/zpQiEPSw==} '@folo-services/ai-tools@0.2.14': resolution: {integrity: sha512-3DG/FqGqNvpCUtq1WMwzMYW6XuhQQfRfIGyZbokJ+XgbyR4YO3Jtz9T5fluINy+Q9iQSRyZSLyhMxe4Evsj5Hg==} @@ -19175,7 +19175,7 @@ snapshots: '@floating-ui/utils@0.2.9': {} - '@follow-app/client-sdk@0.3.24(@opentelemetry/api@1.9.0)(@types/pg@8.6.1)(expo-sqlite@15.2.12(expo@53.0.12(@babel/core@7.28.0)(@expo/metro-runtime@5.0.4(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0)))(bufferutil@4.0.9)(graphql@16.8.1)(react-native-webview@13.15.0(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(kysely@0.28.2)(pg@8.16.3)': + '@follow-app/client-sdk@0.3.25(@opentelemetry/api@1.9.0)(@types/pg@8.6.1)(expo-sqlite@15.2.12(expo@53.0.12(@babel/core@7.28.0)(@expo/metro-runtime@5.0.4(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0)))(bufferutil@4.0.9)(graphql@16.8.1)(react-native-webview@13.15.0(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(kysely@0.28.2)(pg@8.16.3)': dependencies: '@folo-services/constants': 0.1.15 '@folo-services/drizzle': 0.1.10(@opentelemetry/api@1.9.0)(@types/pg@8.6.1)(expo-sqlite@15.2.12(expo@53.0.12(@babel/core@7.28.0)(@expo/metro-runtime@5.0.4(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0)))(bufferutil@4.0.9)(graphql@16.8.1)(react-native-webview@13.15.0(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(kysely@0.28.2) diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml index 87cc5f3a4..76ee0a4d7 100644 --- a/pnpm-workspace.yaml +++ b/pnpm-workspace.yaml @@ -53,4 +53,4 @@ overrides: catalog: typescript: "5.8.3" - "@follow-app/client-sdk": "0.3.24" + "@follow-app/client-sdk": "0.3.25" From 008902758699bece5d6ac517831434bebe8e2a3b Mon Sep 17 00:00:00 2001 From: Innei Date: Tue, 29 Jul 2025 00:08:40 +0800 Subject: [PATCH 10/74] feat: add custom integration configurations to adapt to more apps, resolves FOL-2287 Signed-off-by: Innei --- .../src/atoms/settings/integration.ts | 23 +- .../src/hooks/biz/useEntryActions.tsx | 101 ++++- .../src/modules/command/commands/id.ts | 2 + .../modules/command/commands/integration.tsx | 69 +++- .../src/modules/customize-toolbar/constant.ts | 2 +- .../entry-content/actions/header-actions.tsx | 70 +++- .../entry-content/actions/more-actions.tsx | 128 +++++-- .../integration/CustomIntegrationPreview.tsx | 139 +++++++ .../CustomIntegrationValidator.tsx | 48 +++ .../modules/integration/PlaceholderHelp.tsx | 90 +++++ .../integration/custom-integration-manager.ts | 324 ++++++++++++++++ .../integration/CustomIntegrationModal.tsx | 346 ++++++++++++++++++ .../integration/CustomIntegrationSection.tsx | 291 +++++++++++++++ .../index.tsx} | 182 +++++---- icons/mgc/bookmark_cute_re.svg | 1 + icons/mgc/documents_cute_re.svg | 1 + icons/mgc/pic_cute_re.svg | 1 + icons/mgc/save_cute_re.svg | 1 + icons/mgc/search_cute_re.svg | 1 + icons/mgc/send_plane_cute_re.svg | 1 + locales/settings/en.json | 63 ++++ .../components/src/ui/input/TextArea.tsx | 2 +- .../src/ui/key-value-editor/index.tsx | 163 +++++++++ .../internal/shared/src/settings/defaults.ts | 4 + .../internal/shared/src/settings/interface.ts | 19 + 25 files changed, 1958 insertions(+), 114 deletions(-) create mode 100644 apps/desktop/layer/renderer/src/modules/integration/CustomIntegrationPreview.tsx create mode 100644 apps/desktop/layer/renderer/src/modules/integration/CustomIntegrationValidator.tsx create mode 100644 apps/desktop/layer/renderer/src/modules/integration/PlaceholderHelp.tsx create mode 100644 apps/desktop/layer/renderer/src/modules/integration/custom-integration-manager.ts create mode 100644 apps/desktop/layer/renderer/src/modules/settings/tabs/integration/CustomIntegrationModal.tsx create mode 100644 apps/desktop/layer/renderer/src/modules/settings/tabs/integration/CustomIntegrationSection.tsx rename apps/desktop/layer/renderer/src/modules/settings/tabs/{integration.tsx => integration/index.tsx} (76%) create mode 100644 icons/mgc/bookmark_cute_re.svg create mode 100644 icons/mgc/documents_cute_re.svg create mode 100644 icons/mgc/pic_cute_re.svg create mode 100644 icons/mgc/save_cute_re.svg create mode 100644 icons/mgc/search_cute_re.svg create mode 100644 icons/mgc/send_plane_cute_re.svg create mode 100644 packages/internal/components/src/ui/key-value-editor/index.tsx diff --git a/apps/desktop/layer/renderer/src/atoms/settings/integration.ts b/apps/desktop/layer/renderer/src/atoms/settings/integration.ts index 02895ca53..0e590b37b 100644 --- a/apps/desktop/layer/renderer/src/atoms/settings/integration.ts +++ b/apps/desktop/layer/renderer/src/atoms/settings/integration.ts @@ -2,7 +2,28 @@ import { createSettingAtom } from "@follow/atoms/helper/setting.js" import { defaultIntegrationSettings } from "@follow/shared/settings/defaults" import type { IntegrationSettings } from "@follow/shared/settings/interface" -export const createDefaultSettings = (): IntegrationSettings => defaultIntegrationSettings +export const createDefaultSettings = (): IntegrationSettings => { + const defaultSettings = defaultIntegrationSettings + + // Check if we have stored settings that might need migration + const storedSettings = (() => { + try { + const stored = localStorage.getItem("follow:integration") + return stored ? JSON.parse(stored) : null + } catch { + return null + } + })() + + if (storedSettings?.customIntegration) { + return { + ...defaultSettings, + ...storedSettings, + } + } + + return defaultSettings +} export const { useSettingKey: useIntegrationSettingKey, diff --git a/apps/desktop/layer/renderer/src/hooks/biz/useEntryActions.tsx b/apps/desktop/layer/renderer/src/hooks/biz/useEntryActions.tsx index 464ee5d33..931059d01 100644 --- a/apps/desktop/layer/renderer/src/hooks/biz/useEntryActions.tsx +++ b/apps/desktop/layer/renderer/src/hooks/biz/useEntryActions.tsx @@ -22,6 +22,7 @@ import { useEntryIsInReadability, } from "~/atoms/readability" import { useAIChatPinned } from "~/atoms/settings/ai" +import { useIntegrationSettingValue } from "~/atoms/settings/integration" import { useShowSourceContent } from "~/atoms/source-content" import { ipcServices } from "~/lib/client" import { COMMAND_ID } from "~/modules/command/commands/id" @@ -118,7 +119,67 @@ export class EntryActionMenuItem extends MenuItemText { }) } } -export type EntryActionItem = EntryActionMenuItem | MenuItemSeparator + +export class EntryActionDropdownItem extends MenuItemText { + protected privateConfig: EntryActionMenuItemConfig + public children: EntryActionMenuItem[] + + constructor(config: EntryActionMenuItemConfig & { children?: EntryActionMenuItem[] }) { + const cmd = getCommand(config.id) || null + super({ + ...config, + label: cmd?.label.title || "", + click: () => config.onClick?.(), + hide: !cmd || config.hide, + }) + + this.privateConfig = config + this.children = config.children || [] + } + + public get id() { + return this.privateConfig.id + } + + public get active() { + return this.privateConfig.active + } + + public get notice() { + return this.privateConfig.notice + } + + public get entryId() { + return this.privateConfig.entryId + } + + public get hasChildren() { + return this.children.length > 0 + } + + public get enabledChildren() { + return this.children.filter((child) => !child.hide) + } + + public addChild(child: EntryActionMenuItem) { + this.children.push(child) + } + + public removeChild(childId: string) { + this.children = this.children.filter((child) => child.id !== childId) + } + + public override extend( + config: Partial, + ) { + return new EntryActionDropdownItem({ + ...this.privateConfig, + ...config, + children: config.children || this.children, + }) + } +} +export type EntryActionItem = EntryActionMenuItem | EntryActionDropdownItem | MenuItemSeparator const entrySelector = (state: EntryModel) => { const content = state.content || "" @@ -194,6 +255,7 @@ export const useEntryActions = ({ const hasEntry = !!entry const userRole = useUserRole() + const integrationSettings = useIntegrationSettingValue() const shortcuts = useCommandShortcuts() @@ -385,11 +447,34 @@ export const useEntryActions = ({ active: isShowAIChatPinned, hide: !aiEnabled, }), - new EntryActionMenuItem({ - id: COMMAND_ID.settings.customizeToolbar, - onClick: runCmdFn(COMMAND_ID.settings.customizeToolbar, []), - entryId, - }), + + // Custom Integration with sub-menu + ...(() => { + const customIntegrations = integrationSettings.customIntegration || [] + const enabledIntegrations = customIntegrations.filter((integration) => integration.enabled) + + if (!integrationSettings.enableCustomIntegration || enabledIntegrations.length === 0) { + return [] + } + + return [ + new EntryActionDropdownItem({ + id: COMMAND_ID.integration.custom, + onClick: runCmdFn(COMMAND_ID.integration.custom, [{ entryId }]), + entryId, + children: enabledIntegrations.map((integration) => { + const virtualId = `integration:custom:${integration.id}` as FollowCommandId + return new EntryActionMenuItem({ + id: virtualId, + onClick: () => { + runCmdFn(virtualId, [{ entryId }])() + }, + entryId, + }) + }), + }), + ] + })(), ].filter((config) => { if (config === MENU_ITEM_SEPARATOR) { return config @@ -417,7 +502,6 @@ export const useEntryActions = ({ isInbox, shortcuts, view, - isCollection, isInCollection, isShowSourceContent, isShowAISummaryAuto, @@ -425,10 +509,13 @@ export const useEntryActions = ({ userRole, isShowAITranslationAuto, isShowAITranslationOnce, + isCollection, compact, isEntryInReadability, isShowAIChatPinned, aiEnabled, + integrationSettings.customIntegration, + integrationSettings.enableCustomIntegration, ]) return actionConfigs diff --git a/apps/desktop/layer/renderer/src/modules/command/commands/id.ts b/apps/desktop/layer/renderer/src/modules/command/commands/id.ts index 8293ca0dd..853dc78c9 100644 --- a/apps/desktop/layer/renderer/src/modules/command/commands/id.ts +++ b/apps/desktop/layer/renderer/src/modules/command/commands/id.ts @@ -28,6 +28,8 @@ export const COMMAND_ID = { saveToCubox: "integration:save-to-cubox", saveToZotero: "integration:save-to-zotero", saveToQBittorrent: "integration:save-to-qbittorrent", + + custom: "integration:custom", }, list: { edit: "list:edit", diff --git a/apps/desktop/layer/renderer/src/modules/command/commands/integration.tsx b/apps/desktop/layer/renderer/src/modules/command/commands/integration.tsx index 091319b5c..b52c894e1 100644 --- a/apps/desktop/layer/renderer/src/modules/command/commands/integration.tsx +++ b/apps/desktop/layer/renderer/src/modules/command/commands/integration.tsx @@ -16,6 +16,7 @@ import { tracker } from "@follow/tracker" import { useMutation, useQuery } from "@tanstack/react-query" import type { FetchError } from "ofetch" import { ofetch } from "ofetch" +import { useMemo } from "react" import { useTranslation } from "react-i18next" import { toast } from "sonner" @@ -25,10 +26,11 @@ import { getIntegrationSettings, useIntegrationSettingKey } from "~/atoms/settin import { useRouteParams } from "~/hooks/biz/useRouteParams" import { ipcServices } from "~/lib/client" import { parseHtml } from "~/lib/parse-html" +import { CustomIntegrationManager } from "~/modules/integration/custom-integration-manager" import { useRegisterCommandEffect } from "../hooks/use-register-command" import { defineFollowCommand } from "../registry/command" -import type { Command, CommandCategory } from "../types" +import type { Command, CommandCategory, FollowCommandId } from "../types" import { COMMAND_ID } from "./id" export const useRegisterIntegrationCommands = () => { @@ -41,6 +43,7 @@ export const useRegisterIntegrationCommands = () => { useRegisterCuboxCommands() useRegisterZoteroCommands() useRegisterQBittorrentCommands() + useRegisterCustomIntegrationCommands() } const category: CommandCategory = "category.integration" @@ -781,6 +784,64 @@ const useRegisterQBittorrentCommands = () => { ) } +const useRegisterCustomIntegrationCommands = () => { + const customIntegrations = useIntegrationSettingKey("customIntegration") + const enableCustomIntegration = useIntegrationSettingKey("enableCustomIntegration") + + // Register main custom integration command + useRegisterCommandEffect( + !enableCustomIntegration || !customIntegrations || customIntegrations.length === 0 + ? [] + : defineFollowCommand({ + id: COMMAND_ID.integration.custom, + label: "Custom Integration", + icon: , + category, + run: async () => {}, + }), + { + deps: [customIntegrations, enableCustomIntegration], + }, + ) + + useRegisterCustomIntegrationVisualCommands() +} + +const useRegisterCustomIntegrationVisualCommands = () => { + const customIntegrations = useIntegrationSettingKey("customIntegration") + const enableCustomIntegration = useIntegrationSettingKey("enableCustomIntegration") + + const visualCommands = useMemo(() => { + if (!enableCustomIntegration || !customIntegrations || customIntegrations.length === 0) { + return [] + } + return customIntegrations.map((integration) => { + return defineFollowCommand({ + id: `integration:custom:${integration.id}` as FollowCommandId, + label: integration.name, + icon: , + + category, + run: async ({ entryId }: { entryId: string }) => { + const entry = getEntry(entryId) + if (!entry) { + toast.error(`Failed to save to ${integration.name}: entry is not available`, { + duration: 3000, + }) + return + } + + await CustomIntegrationManager.executeWithToast(integration, entry) + }, + }) + }) + }, [customIntegrations, enableCustomIntegration]) + + useRegisterCommandEffect(visualCommands, { + deps: [visualCommands], + }) +} + export type SaveToEagleCommand = Command<{ id: typeof COMMAND_ID.integration.saveToEagle fn: (payload: { entryId: string }) => void @@ -826,6 +887,11 @@ export type SaveToQBittorrentCommand = Command<{ fn: (payload: { entryId: string }) => void }> +export type CustomIntegrationCommand = Command<{ + id: typeof COMMAND_ID.integration.custom + fn: (payload: { entryId: string }) => void +}> + export type IntegrationCommand = | SaveToEagleCommand | SaveToReadwiseCommand @@ -836,3 +902,4 @@ export type IntegrationCommand = | SaveToCuboxCommand | SaveToZoteroCommand | SaveToQBittorrentCommand + | CustomIntegrationCommand diff --git a/apps/desktop/layer/renderer/src/modules/customize-toolbar/constant.ts b/apps/desktop/layer/renderer/src/modules/customize-toolbar/constant.ts index c7c397626..7e06fdab8 100644 --- a/apps/desktop/layer/renderer/src/modules/customize-toolbar/constant.ts +++ b/apps/desktop/layer/renderer/src/modules/customize-toolbar/constant.ts @@ -10,6 +10,7 @@ export interface ToolbarActionOrder { export const ENTRY_ITEM_HIDE_IN_HEADER = new Set([ COMMAND_ID.entry.readAbove, COMMAND_ID.entry.readBelow, + COMMAND_ID.settings.customizeToolbar, ]) const MAIN_ACTIONS = [ @@ -30,6 +31,5 @@ export const DEFAULT_ACTION_ORDER: ToolbarActionOrder = { more: [ ...Object.values(COMMAND_ID.integration), ...Object.values(COMMAND_ID.entry).filter((id) => !MAIN_ACTIONS_SET.has(id)), - COMMAND_ID.settings.customizeToolbar, ], } diff --git a/apps/desktop/layer/renderer/src/modules/entry-content/actions/header-actions.tsx b/apps/desktop/layer/renderer/src/modules/entry-content/actions/header-actions.tsx index 8e5c0dc8e..e96b0f827 100644 --- a/apps/desktop/layer/renderer/src/modules/entry-content/actions/header-actions.tsx +++ b/apps/desktop/layer/renderer/src/modules/entry-content/actions/header-actions.tsx @@ -1,8 +1,18 @@ +import { RootPortal } from "@follow/components/ui/portal/index.js" import type { FeedViewType } from "@follow/constants" +import { memo } from "react" import { MenuItemText } from "~/atoms/context-menu" import { CommandActionButton } from "~/components/ui/button/CommandActionButton" -import { useSortedEntryActions } from "~/hooks/biz/useEntryActions" +import { + DropdownMenu, + DropdownMenuContent, + DropdownMenuItem, + DropdownMenuTrigger, +} from "~/components/ui/dropdown-menu/dropdown-menu" +import { EntryActionDropdownItem, useSortedEntryActions } from "~/hooks/biz/useEntryActions" +import { useCommand } from "~/modules/command/hooks/use-command" +import type { FollowCommandId } from "~/modules/command/types" export const EntryHeaderActions = ({ entryId, @@ -16,9 +26,9 @@ export const EntryHeaderActions = ({ const { mainAction: actionConfigs } = useSortedEntryActions({ entryId, view, compact }) return actionConfigs - .filter((item) => item instanceof MenuItemText) + .filter((item) => item instanceof MenuItemText || item instanceof EntryActionDropdownItem) .map((config) => { - return ( + const baseTrigger = ( ) + + if (config instanceof EntryActionDropdownItem && config.hasChildren) { + return ( + + {baseTrigger} + + + {config.enabledChildren.map((child) => ( + + ))} + + + + ) + } + + if (config instanceof MenuItemText) { + return baseTrigger + } + + return null }) } + +const CommandDropdownMenuItem = memo( + ({ + commandId, + onClick, + active, + }: { + commandId: FollowCommandId + onClick: () => void + active?: boolean + }) => { + const command = useCommand(commandId) + + if (!command) return null + + return ( + + {command.label.title} + + ) + }, +) diff --git a/apps/desktop/layer/renderer/src/modules/entry-content/actions/more-actions.tsx b/apps/desktop/layer/renderer/src/modules/entry-content/actions/more-actions.tsx index 6a1280c6e..849a41c6b 100644 --- a/apps/desktop/layer/renderer/src/modules/entry-content/actions/more-actions.tsx +++ b/apps/desktop/layer/renderer/src/modules/entry-content/actions/more-actions.tsx @@ -9,11 +9,18 @@ import { DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, + DropdownMenuSub, + DropdownMenuSubContent, + DropdownMenuSubTrigger, DropdownMenuTrigger, } from "~/components/ui/dropdown-menu/dropdown-menu" -import { useSortedEntryActions } from "~/hooks/biz/useEntryActions" +import { + EntryActionDropdownItem, + EntryActionMenuItem, + useSortedEntryActions, +} from "~/hooks/biz/useEntryActions" import { COMMAND_ID } from "~/modules/command/commands/id" -import { hasCommand, useCommand } from "~/modules/command/hooks/use-command" +import { hasCommand, useCommand, useRunCommandFn } from "~/modules/command/hooks/use-command" import type { FollowCommandId } from "~/modules/command/types" export const MoreActions = ({ @@ -28,24 +35,35 @@ export const MoreActions = ({ const { moreAction } = useSortedEntryActions({ entryId, view }) const actionConfigs = useMemo( - () => moreAction.filter((action) => action instanceof MenuItemText && hasCommand(action.id)), + () => + moreAction.filter( + (action) => + (action instanceof MenuItemText || action instanceof EntryActionDropdownItem) && + hasCommand(action.id), + ), [moreAction], ) const availableActions = useMemo( () => actionConfigs.filter( - (item) => item instanceof MenuItemText && item.id !== COMMAND_ID.settings.customizeToolbar, + (item) => + (item instanceof MenuItemText || item instanceof EntryActionDropdownItem) && + item.id !== COMMAND_ID.settings.customizeToolbar, ), [actionConfigs], ) - const extraAction = useMemo( - () => - actionConfigs.filter( - (item) => item instanceof MenuItemText && item.id === COMMAND_ID.settings.customizeToolbar, - ), - [actionConfigs], + const runCmdFn = useRunCommandFn() + const extraAction: EntryActionMenuItem[] = useMemo( + () => [ + new EntryActionMenuItem({ + id: COMMAND_ID.settings.customizeToolbar, + onClick: runCmdFn(COMMAND_ID.settings.customizeToolbar, []), + entryId, + }), + ], + [entryId, runCmdFn], ) if (availableActions.length === 0 && extraAction.length === 0) { @@ -62,16 +80,47 @@ export const MoreActions = ({ - {availableActions - .filter((item) => item instanceof MenuItemText) - .map((config) => ( - - ))} + {availableActions.map((config) => { + // Handle EntryActionI with sub-menu + if (config instanceof EntryActionDropdownItem && config.hasChildren) { + return ( + + + + + + {config.enabledChildren.map((child) => ( + + ))} + + + ) + } + + // Handle regular MenuItemText + if (config instanceof MenuItemText) { + return ( + + ) + } + + return null + })} {availableActions.length > 0 && } {extraAction .filter((item) => item instanceof MenuItemText) @@ -93,13 +142,48 @@ export const CommandDropdownMenuItem = ({ commandId, onClick, active, + asSubTrigger = false, }: { - commandId: FollowCommandId + commandId: FollowCommandId | string onClick: () => void active?: boolean + asSubTrigger?: boolean }) => { - const command = useCommand(commandId) + const command = useCommand(commandId as any) + + // For custom integration items + if (typeof commandId === "string" && commandId.startsWith("integration:custom:")) { + const content = ( + <> + + Custom Integration + + ) + + if (asSubTrigger) { + return content + } + + return ( + + {content} + + ) + } + if (!command) return null + + const content = ( + <> + {command.icon} + {command.label.title} + + ) + + if (asSubTrigger) { + return content + } + return ( { + const { t } = useTranslation("settings") + const [preview, setPreview] = useState<{ + url: string + headers: Record + body?: string + method: string + } | null>(null) + const [isOpen, setIsOpen] = useState(false) + const [isLoading, setIsLoading] = useState(false) + + const generatePreview = async (fetchTemplate: FetchTemplate) => { + setIsLoading(true) + try { + const previewData = await CustomIntegrationManager.getTemplatePreview(fetchTemplate) + + setPreview(previewData) + } catch (error) { + console.error("Failed to generate preview:", error) + setPreview(null) + } finally { + setIsLoading(false) + } + } + + return ( +
+ + + {isOpen && ( +
+ {isLoading ? ( +
+
+ + Generating preview... +
+
+ ) : preview ? ( +
+ {/* Method and URL */} +
+

Request

+
+ + {preview.method} + + {preview.url} +
+
+ + {/* Headers */} + {Object.keys(preview.headers).length > 0 && ( +
+

Headers

+
+ {Object.entries(preview.headers).map(([key, value]) => ( +
+ + {key}: + + {value} +
+ ))} +
+
+ )} + + {/* Body */} + {preview.body && ( +
+

Request Body

+
+
+                      {preview.body}
+                    
+
+
+ )} + + {/* Placeholders Info */} +
+

+ Available Placeholders +

+
+ {CustomIntegrationManager.getAvailablePlaceholders().map((placeholder) => ( +
+ {placeholder.key} +
{placeholder.description}
+
+ ))} +
+
+
+ ) : ( +
+ Failed to generate preview +
+ )} +
+ )} +
+ ) +} diff --git a/apps/desktop/layer/renderer/src/modules/integration/CustomIntegrationValidator.tsx b/apps/desktop/layer/renderer/src/modules/integration/CustomIntegrationValidator.tsx new file mode 100644 index 000000000..86cc5d574 --- /dev/null +++ b/apps/desktop/layer/renderer/src/modules/integration/CustomIntegrationValidator.tsx @@ -0,0 +1,48 @@ +import type { FetchTemplate } from "@follow/shared/settings/interface" +import { cn } from "@follow/utils" +import { useTranslation } from "react-i18next" + +import { CustomIntegrationManager } from "./custom-integration-manager" + +interface CustomIntegrationValidatorProps { + fetchTemplate: FetchTemplate + className?: string +} + +export const CustomIntegrationValidator = ({ + fetchTemplate, + className, +}: CustomIntegrationValidatorProps) => { + const { t } = useTranslation("settings") + + const validation = CustomIntegrationManager.validateFetchTemplate(fetchTemplate) + + if (validation.valid) { + return ( +
+ + + {t("integration.custom_integrations.validation.valid", "Template is valid")} + +
+ ) + } + + return ( +
+
+ + + {t("integration.custom_integrations.validation.invalid", "Template has errors")} + +
+
    + {validation.errors.map((error, index) => ( +
  • + {error} +
  • + ))} +
+
+ ) +} diff --git a/apps/desktop/layer/renderer/src/modules/integration/PlaceholderHelp.tsx b/apps/desktop/layer/renderer/src/modules/integration/PlaceholderHelp.tsx new file mode 100644 index 000000000..d72a11a84 --- /dev/null +++ b/apps/desktop/layer/renderer/src/modules/integration/PlaceholderHelp.tsx @@ -0,0 +1,90 @@ +import { Tooltip, TooltipContent, TooltipTrigger } from "@follow/components/ui/tooltip/index.js" +import { cn } from "@follow/utils" +import { useState } from "react" +import { useTranslation } from "react-i18next" + +import { CustomIntegrationManager } from "./custom-integration-manager" + +interface PlaceholderHelpProps { + className?: string + onPlaceholderClick?: (placeholder: string) => void +} + +export const PlaceholderHelp = ({ className, onPlaceholderClick }: PlaceholderHelpProps) => { + const { t } = useTranslation("settings") + const [isOpen, setIsOpen] = useState(false) + + const placeholders = CustomIntegrationManager.getAvailablePlaceholders() + + return ( +
+ + + {isOpen && ( +
+
+

+ {t( + "integration.custom_integrations.placeholders.description", + "Click on any placeholder to copy it to your clipboard", + )} +

+ +
+ {placeholders.map((placeholder) => ( + + + + + +

+ {t( + "integration.custom_integrations.placeholders.click_to_copy", + "Click to copy", + )} +

+
+
+ ))} +
+
+
+ )} +
+ ) +} diff --git a/apps/desktop/layer/renderer/src/modules/integration/custom-integration-manager.ts b/apps/desktop/layer/renderer/src/modules/integration/custom-integration-manager.ts new file mode 100644 index 000000000..767634024 --- /dev/null +++ b/apps/desktop/layer/renderer/src/modules/integration/custom-integration-manager.ts @@ -0,0 +1,324 @@ +import type { CustomIntegration, FetchTemplate } from "@follow/shared/settings/interface" +import type { EntryModel } from "@follow/store/entry/types" +import { getSummary } from "@follow/store/summary/getters" +import { tracker } from "@follow/tracker" +import type { FetchError } from "ofetch" +import { ofetch } from "ofetch" +import { toast } from "sonner" + +import { getActionLanguage } from "~/atoms/settings/general" +import { getIntegrationSettings } from "~/atoms/settings/integration" +import { parseHtml } from "~/lib/parse-html" + +/** + * Placeholder values that can be used in custom integration templates + */ +export interface PlaceholderContext { + title: string + url: string + contentHtml: string + contentMarkdown: string + summary: string + author: string + publishedAt: string + description: string + [key: string]: string +} + +/** + * Manager class for handling custom integrations + */ +export class CustomIntegrationManager { + /** + * Get entry content as markdown + */ + private static async getEntryContentAsMarkdown(entry: EntryModel): Promise { + const content = entry.content || "" + if (!content) return "" + + try { + const [toMarkdown, toMdast, gfmTableToMarkdown] = await Promise.all([ + import("mdast-util-to-markdown").then((m) => m.toMarkdown), + import("hast-util-to-mdast").then((m) => m.toMdast), + import("mdast-util-gfm-table").then((m) => m.gfmTableToMarkdown), + ]) + return toMarkdown(toMdast(parseHtml(content).hastTree), { + extensions: [gfmTableToMarkdown()], + }) + } catch { + return content + } + } + + /** + * Get description with optional summary + */ + private static getDescription(entry: EntryModel): string { + const { saveSummaryAsDescription } = getIntegrationSettings() + const actionLanguage = getActionLanguage() + + if (!saveSummaryAsDescription) { + return entry.description || "" + } + const summary = getSummary(entry.id, actionLanguage) + return summary?.readabilitySummary || summary?.summary || entry.description || "" + } + + /** + * Build placeholder context from entry + */ + static async buildPlaceholderContext(entry: EntryModel): Promise { + const markdownContent = await this.getEntryContentAsMarkdown(entry) + + return { + title: entry.title || "", + url: entry.url || "", + contentHtml: entry.content || "", + contentMarkdown: markdownContent, + summary: this.getDescription(entry), + author: entry.author || "", + publishedAt: entry.publishedAt?.toISOString() || "", + description: entry.description || "", + } + } + + /** + * Get all available placeholders with their descriptions + */ + static getAvailablePlaceholders(): Array<{ key: string; description: string; example?: string }> { + return [ + { key: "[title]", description: "Entry title", example: "Example Article Title" }, + { key: "[url]", description: "Entry URL", example: "https://example.com/article" }, + { key: "[content_html]", description: "Entry content in HTML format" }, + { key: "[content_markdown]", description: "Entry content in Markdown format" }, + { key: "[summary]", description: "Entry summary or description" }, + { key: "[author]", description: "Entry author", example: "John Doe" }, + { + key: "[published_at]", + description: "Publication date in ISO format", + example: "2024-01-01T12:00:00.000Z", + }, + { key: "[description]", description: "Entry description" }, + ] + } + + /** + * Replace placeholders in a string with actual values + */ + static replacePlaceholders( + template: string, + context: PlaceholderContext, + options: { + urlEncode?: boolean + htmlEscape?: boolean + } = {}, + ): string { + let result = template + + // Define placeholder mapping + const placeholders: Record = { + "[title]": context.title, + "[url]": context.url, + "[content_html]": context.contentHtml, + "[content_markdown]": context.contentMarkdown, + "[summary]": context.summary, + "[author]": context.author, + "[published_at]": context.publishedAt, + "[description]": context.description, + } + + // Replace each placeholder + Object.entries(placeholders).forEach(([placeholder, value]) => { + let processedValue = value + + if (options.urlEncode) { + processedValue = encodeURIComponent(processedValue) + } + + if (options.htmlEscape) { + processedValue = processedValue + .replaceAll("&", "&") + .replaceAll("<", "<") + .replaceAll(">", ">") + .replaceAll('"', """) + .replaceAll("'", "'") + } + + result = result.replaceAll(placeholder, processedValue) + }) + + return result + } + + /** + * Process a fetch template with placeholder replacement + */ + static async processFetchTemplate( + fetchTemplate: FetchTemplate, + context: PlaceholderContext, + ): Promise<{ + url: string + headers: Record + body?: string + method: string + }> { + // Process URL with URL encoding for placeholder values + const processedUrl = this.replacePlaceholders(fetchTemplate.url, context, { urlEncode: true }) + + // Process headers without URL encoding + const processedHeaders: Record = {} + Object.entries(fetchTemplate.headers).forEach(([key, value]) => { + const processedKey = this.replacePlaceholders(key, context) + const processedValue = this.replacePlaceholders(value, context) + processedHeaders[processedKey] = processedValue + }) + + // Process body without URL encoding + let processedBody: string | undefined + if (fetchTemplate.body) { + processedBody = this.replacePlaceholders(fetchTemplate.body, context) + } + + return { + url: processedUrl, + headers: processedHeaders, + body: processedBody, + method: fetchTemplate.method, + } + } + + /** + * Execute a custom integration + */ + static async executeIntegration( + integration: CustomIntegration, + entry: EntryModel, + ): Promise<{ success: boolean; error?: string }> { + if (!integration.enabled) { + return { success: false, error: `${integration.name} is disabled` } + } + + try { + // Track integration usage + tracker.integration({ + type: "custom", + event: "save", + }) + + // Build placeholder context + const context = await this.buildPlaceholderContext(entry) + + // Process fetch template + const { url, headers, body, method } = await this.processFetchTemplate( + integration.fetchTemplate, + context, + ) + + // Prepare request options + const requestOptions: Parameters[1] = { + method: method as any, + headers, + } + + // Add body for methods that support it + if (body && ["POST", "PUT", "PATCH"].includes(method)) { + requestOptions.body = body + + // Set content-type if not already set + if (!Object.keys(headers).some((key) => key.toLowerCase() === "content-type")) { + requestOptions.headers = { + ...headers, + "Content-Type": "application/json", + } + } + } + + // Execute the HTTP request + await ofetch(url, requestOptions) + + return { success: true } + } catch (error) { + const errorMessage = (error as FetchError)?.message || "Unknown error" + return { success: false, error: errorMessage } + } + } + + /** + * Execute integration with toast notifications + */ + static async executeWithToast(integration: CustomIntegration, entry: EntryModel): Promise { + const result = await this.executeIntegration(integration, entry) + + if (result.success) { + toast.success(`Saved to ${integration.name} successfully`, { + duration: 3000, + }) + } else { + toast.error(`Failed to save to ${integration.name}: ${result.error}`, { + duration: 3000, + }) + } + } + + /** + * Validate a fetch template + */ + static validateFetchTemplate(fetchTemplate: FetchTemplate): { valid: boolean; errors: string[] } { + const errors: string[] = [] + + if (!fetchTemplate.url?.trim()) { + errors.push("URL is required") + } + + if (!fetchTemplate.method) { + errors.push("HTTP method is required") + } + + if ( + fetchTemplate.method && + !["GET", "POST", "PUT", "PATCH", "DELETE"].includes(fetchTemplate.method) + ) { + errors.push("Invalid HTTP method") + } + + try { + if (fetchTemplate.url) { + new URL(fetchTemplate.url.replaceAll(/\[.*?\]/g, "https://example.com")) + } + } catch { + errors.push("Invalid URL format") + } + + return { + valid: errors.length === 0, + errors, + } + } + + /** + * Get template preview with sample data + */ + static async getTemplatePreview( + fetchTemplate: FetchTemplate, + sampleEntry?: Partial, + ): Promise<{ + url: string + headers: Record + body?: string + method: string + }> { + // Create sample context + const sampleContext: PlaceholderContext = { + title: sampleEntry?.title || "Sample Article Title", + url: sampleEntry?.url || "https://example.com/article", + contentHtml: sampleEntry?.content || "

This is sample HTML content

", + contentMarkdown: "# Sample Article\n\nThis is sample markdown content.", + summary: "This is a sample summary of the article content.", + author: sampleEntry?.author || "John Doe", + publishedAt: sampleEntry?.publishedAt?.toISOString() || new Date().toISOString(), + description: sampleEntry?.description || "Sample article description", + } + + return this.processFetchTemplate(fetchTemplate, sampleContext) + } +} diff --git a/apps/desktop/layer/renderer/src/modules/settings/tabs/integration/CustomIntegrationModal.tsx b/apps/desktop/layer/renderer/src/modules/settings/tabs/integration/CustomIntegrationModal.tsx new file mode 100644 index 000000000..2435cf421 --- /dev/null +++ b/apps/desktop/layer/renderer/src/modules/settings/tabs/integration/CustomIntegrationModal.tsx @@ -0,0 +1,346 @@ +import { Button } from "@follow/components/ui/button/index.js" +import { + Form, + FormControl, + FormDescription, + FormField, + FormItem, + FormLabel, + FormMessage, +} from "@follow/components/ui/form/index.jsx" +import { Input, TextArea } from "@follow/components/ui/input/index.js" +import { KeyValueEditor } from "@follow/components/ui/key-value-editor/index.js" +import { ResponsiveSelect } from "@follow/components/ui/select/responsive.js" +import type { CustomIntegration } from "@follow/shared/settings/interface" +import { nextFrame } from "@follow/utils" +import { zodResolver } from "@hookform/resolvers/zod" +import { useEffect } from "react" +import { useForm } from "react-hook-form" +import { useTranslation } from "react-i18next" +import { toast } from "sonner" +import { z } from "zod" + +import { useCurrentModal } from "~/components/ui/modal/stacked/hooks" +import { CustomIntegrationPreview } from "~/modules/integration/CustomIntegrationPreview" +import { PlaceholderHelp } from "~/modules/integration/PlaceholderHelp" + +const formSchema = z.object({ + name: z.string().min(1, "Name is required"), + icon: z.string().min(1, "Icon is required"), + fetchTemplate: z.object({ + method: z.enum(["GET", "POST", "PUT", "PATCH", "DELETE"]), + url: z.string().min(1, "URL is required"), + headers: z.record(z.string()), + body: z.string().optional(), + }), + enabled: z.boolean(), +}) + +interface CustomIntegrationModalProps { + integration?: CustomIntegration + onSave: (integration: Omit & { id?: string }) => void +} + +const getCommonIcons = (t: any) => + [ + { + value: "i-mgc-bookmark-cute-re", + label: t("integration.custom_integrations.icons.bookmark"), + icon: "i-mgc-bookmark-cute-re", + }, + { + value: "i-mgc-pic-cute-re", + label: t("integration.custom_integrations.icons.picture"), + icon: "i-mgc-pic-cute-re", + }, + { + value: "i-mgc-share-forward-cute-re", + label: t("integration.custom_integrations.icons.share"), + icon: "i-mgc-share-forward-cute-re", + }, + { + value: "i-mgc-external-link-cute-re", + label: t("integration.custom_integrations.icons.external_link"), + icon: "i-mgc-external-link-cute-re", + }, + { + value: "i-mgc-save-cute-re", + label: t("integration.custom_integrations.icons.save"), + icon: "i-mgc-save-cute-re", + }, + { + value: "i-mgc-documents-cute-re", + label: t("integration.custom_integrations.icons.document"), + icon: "i-mgc-documents-cute-re", + }, + { + value: "i-mgc-link-cute-re", + label: t("integration.custom_integrations.icons.link"), + icon: "i-mgc-link-cute-re", + }, + { + value: "i-mgc-star-cute-re", + label: t("integration.custom_integrations.icons.star"), + icon: "i-mgc-star-cute-re", + }, + { + value: "i-mgc-download-2-cute-re", + label: t("integration.custom_integrations.icons.download"), + icon: "i-mgc-download-2-cute-re", + }, + { + value: "i-mgc-send-plane-cute-re", + label: t("integration.custom_integrations.icons.send"), + icon: "i-mgc-send-plane-cute-re", + }, + ] as const + +export const CustomIntegrationModalContent = ({ + integration, + onSave, +}: CustomIntegrationModalProps) => { + const { dismiss } = useCurrentModal() + const { t } = useTranslation("settings") + const commonIcons = getCommonIcons(t) + + const form = useForm>({ + resolver: zodResolver(formSchema), + defaultValues: { + name: integration?.name || "", + icon: integration?.icon || getCommonIcons(() => "")[0].value, + fetchTemplate: integration?.fetchTemplate || { + method: "GET", + url: "", + headers: {}, + body: "", + }, + enabled: integration?.enabled ?? true, + }, + }) + + const onSubmit = (values: z.infer) => { + try { + onSave({ + id: integration?.id, + ...values, + }) + toast.success( + integration + ? t("integration.custom_integrations.edit.success") + : t("integration.custom_integrations.create.success"), + ) + dismiss() + } catch { + toast.error( + integration + ? t("integration.custom_integrations.edit.error") + : t("integration.custom_integrations.create.error"), + ) + } + } + + const selectedMethod = form.watch("fetchTemplate.method") + const showBodyField = selectedMethod && ["POST", "PUT", "PATCH"].includes(selectedMethod) + + // Watch the entire fetchTemplate for preview + const watchedFetchTemplate = form.watch("fetchTemplate") + + useEffect(() => { + nextFrame(() => { + form.setFocus("name") + }) + }, []) + + return ( +
+
+

+ {t("integration.custom_integrations.modal.description")} +

+ +
+ +
+ + ( + + + {t("integration.custom_integrations.form.name.label")} + + + + + + + )} + /> + + ( + + + {t("integration.custom_integrations.form.icon.label")} + + + ({ + label: icon.label, + value: icon.value, + }))} + renderItem={(item) => ( +
+ + {item.label} +
+ )} + /> +
+ + {t("integration.custom_integrations.form.icon.description")} + + +
+ )} + /> + + {/* HTTP Method */} + ( + + + {t("integration.custom_integrations.form.method.label")} + + + ({ + label: method, + value: method, + }))} + /> + + + {t("integration.custom_integrations.form.method.description")} + + + + )} + /> + + {/* URL */} + ( + + + {t("integration.custom_integrations.form.url.label")} + + + + + + {t("integration.custom_integrations.form.url.description")} + + + + )} + /> + + {/* Headers */} + ( + + + {t("integration.custom_integrations.form.headers.label")} + + + + + + {t("integration.custom_integrations.form.headers.description")} + + + + )} + /> + + {/* Request Body (conditional) */} + {showBodyField && ( + ( + + + {t("integration.custom_integrations.form.body.label")} + + +