Merge pull request #4235 from RSSNext/release/mobile/0.2.4
release(mobile): Release v0.2.4
This commit is contained in:
@@ -0,0 +1,17 @@
|
||||
---
|
||||
description:
|
||||
globs: locales/**/*.json
|
||||
alwaysApply: false
|
||||
---
|
||||
|
||||
i18n Coding Standards.
|
||||
|
||||
1. Read and follow https://www.i18next.com/translation-function/formatting
|
||||
|
||||
2. Use flat keys. Use `.` to separate. Do not use object form nesting.
|
||||
|
||||
3. For languages sensitive to singular and plural, distinguish between them using the `_one` and `_other` forms.
|
||||
|
||||
4. In the build stage, flattened dot-separated keys (such as 'exif.custom.rendered.custom') will be automatically converted to nested object objects, which may cause conflicts. For example, 'exif.custom.rendered.custom' may conflict with 'exif.custom.rendered'. Please avoid using such dot-separated flat keys.
|
||||
|
||||
5. @locales is located at the root directory and needs to handle all existing languages at the same time.
|
||||
@@ -0,0 +1 @@
|
||||
# Add directories or file patterns to ignore during indexing (e.g. foo/ or *.csv)
|
||||
@@ -1 +1,2 @@
|
||||
* text=auto eol=lf
|
||||
*.splinecode filter=lfs diff=lfs merge=lfs -text
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
name: "Setup Xcode"
|
||||
description: "Setup specific Xcode version for iOS builds"
|
||||
inputs:
|
||||
xcode-version:
|
||||
description: "Xcode version to use"
|
||||
required: false
|
||||
default: "16.4"
|
||||
|
||||
runs:
|
||||
using: "composite"
|
||||
steps:
|
||||
- uses: maxim-lobanov/setup-xcode@v1
|
||||
with:
|
||||
xcode-version: ${{ inputs.xcode-version }}
|
||||
@@ -1,4 +1,4 @@
|
||||
name: Build Android
|
||||
name: 🤖 Build Android
|
||||
|
||||
on:
|
||||
push:
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
name: Build Desktop
|
||||
name: 🖥️ Build Desktop
|
||||
|
||||
on:
|
||||
push:
|
||||
@@ -32,6 +32,7 @@ env:
|
||||
VITE_OPENPANEL_CLIENT_ID: ${{ vars.VITE_OPENPANEL_CLIENT_ID }}
|
||||
VITE_OPENPANEL_API_URL: ${{ vars.VITE_OPENPANEL_API_URL }}
|
||||
VITE_FIREBASE_CONFIG: ${{ vars.VITE_FIREBASE_CONFIG }}
|
||||
SENTRY_AUTH_TOKEN: ${{ secrets.SENTRY_AUTH_TOKEN }}
|
||||
NODE_OPTIONS: --max-old-space-size=8192
|
||||
|
||||
jobs:
|
||||
@@ -44,7 +45,7 @@ jobs:
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
os: [macos-latest, ubuntu-latest, windows-latest]
|
||||
os: [macos-16, ubuntu-latest, windows-latest]
|
||||
exclude:
|
||||
- os: ${{ github.event.inputs.store == 'true' && 'ubuntu-latest' }}
|
||||
|
||||
@@ -137,14 +138,11 @@ jobs:
|
||||
- name: Build - Vite
|
||||
working-directory: apps/desktop
|
||||
run: pnpm build:electron-vite ${{ env.PROD == 'false' && '--mode staging' || '' }}
|
||||
env:
|
||||
SENTRY_AUTH_TOKEN: ${{ secrets.SENTRY_AUTH_TOKEN }}
|
||||
|
||||
- name: Build - Windows and Linux
|
||||
if: runner.os != 'macOS'
|
||||
if: runner.os == 'Linux' || (runner.os == 'Windows' && github.event.inputs.store != 'true')
|
||||
working-directory: apps/desktop
|
||||
run: pnpm build:electron-forge ${{ env.PROD == 'false' && '--mode=staging' || '' }}
|
||||
env:
|
||||
SENTRY_AUTH_TOKEN: ${{ secrets.SENTRY_AUTH_TOKEN }}
|
||||
|
||||
- name: Build - macOS
|
||||
if: runner.os == 'macOS' && github.event.inputs.store != 'true'
|
||||
@@ -174,12 +172,15 @@ jobs:
|
||||
working-directory: apps/desktop
|
||||
run: pnpm build:electron-forge:mas
|
||||
|
||||
- name: Build - Microsoft Store
|
||||
if: runner.os == 'Windows' && github.event.inputs.store == 'true'
|
||||
working-directory: apps/desktop
|
||||
run: pnpm build:electron-forge:ms
|
||||
|
||||
- name: Build - Renderer
|
||||
if: runner.os == 'Linux'
|
||||
working-directory: apps/desktop
|
||||
run: pnpm build:render
|
||||
env:
|
||||
SENTRY_AUTH_TOKEN: ${{ secrets.SENTRY_AUTH_TOKEN }}
|
||||
|
||||
- name: Upload file (macos-arm64-dmg)
|
||||
uses: actions/upload-artifact@v4
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
name: Build iOS for development
|
||||
name: 📱 Build iOS for development
|
||||
|
||||
on:
|
||||
push:
|
||||
@@ -29,7 +29,7 @@ jobs:
|
||||
if [ -n "$available" ]; then
|
||||
echo "runner-label=self-hosted" >> $GITHUB_OUTPUT
|
||||
else
|
||||
echo "runner-label=macos-15" >> $GITHUB_OUTPUT
|
||||
echo "runner-label=macos-16" >> $GITHUB_OUTPUT
|
||||
fi
|
||||
|
||||
build-ipa-device-self-hosted:
|
||||
@@ -71,17 +71,17 @@ jobs:
|
||||
|
||||
build-ipa-device-github:
|
||||
name: Build iOS IPA for device (GitHub-hosted)
|
||||
if: github.secret_source != 'None' && needs.check-runner.outputs.runner-label == 'macos-15'
|
||||
if: github.secret_source != 'None' && needs.check-runner.outputs.runner-label == 'macos-16'
|
||||
needs: check-runner
|
||||
runs-on: macos-15
|
||||
runs-on: macos-16
|
||||
|
||||
steps:
|
||||
- name: Use Xcode 16.3
|
||||
run: sudo xcode-select -s /Applications/Xcode_16.3.app
|
||||
|
||||
- name: 📦 Checkout code
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: 🔧 Setup Xcode
|
||||
uses: ./.github/actions/setup-xcode
|
||||
|
||||
- name: 📦 Setup pnpm
|
||||
uses: pnpm/action-setup@v4
|
||||
|
||||
@@ -117,15 +117,15 @@ jobs:
|
||||
build-simulator:
|
||||
name: Build iOS IPA for simulator
|
||||
if: github.secret_source != 'None'
|
||||
runs-on: macos-15
|
||||
runs-on: macos-16
|
||||
|
||||
steps:
|
||||
- name: Use Xcode 16.3
|
||||
run: sudo xcode-select -s /Applications/Xcode_16.3.app
|
||||
|
||||
- name: 📦 Checkout code
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: 🔧 Setup Xcode
|
||||
uses: ./.github/actions/setup-xcode
|
||||
|
||||
- name: 📦 Setup pnpm
|
||||
uses: pnpm/action-setup@v4
|
||||
|
||||
|
||||
@@ -36,7 +36,7 @@ jobs:
|
||||
if [ -n "$available" ]; then
|
||||
echo "runner-label=self-hosted" >> $GITHUB_OUTPUT
|
||||
else
|
||||
echo "runner-label=macos-latest" >> $GITHUB_OUTPUT
|
||||
echo "runner-label=macos-16" >> $GITHUB_OUTPUT
|
||||
fi
|
||||
|
||||
build-ipa-self-hosted:
|
||||
@@ -83,9 +83,9 @@ jobs:
|
||||
|
||||
build-ipa-github:
|
||||
name: Build iOS IPA (GitHub)
|
||||
if: github.secret_source != 'None' && needs.check-runner.outputs.runner-label == 'macos-latest'
|
||||
if: github.secret_source != 'None' && needs.check-runner.outputs.runner-label == 'macos-16'
|
||||
needs: check-runner
|
||||
runs-on: macos-latest
|
||||
runs-on: macos-16
|
||||
|
||||
steps:
|
||||
- name: 📦 Checkout code
|
||||
|
||||
@@ -3,7 +3,7 @@ on:
|
||||
push:
|
||||
branches: [main, dev]
|
||||
|
||||
name: CI Build web and SSR server
|
||||
name: 🌐 CI Build web and SSR server
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.ref }}-ssr
|
||||
cancel-in-progress: ${{ github.ref != 'refs/heads/main' && github.ref != 'refs/heads/dev' }}
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
name: 🤖 Claude PR Assistant
|
||||
|
||||
on:
|
||||
issue_comment:
|
||||
types: [created]
|
||||
pull_request_review_comment:
|
||||
types: [created]
|
||||
issues:
|
||||
types: [opened, assigned]
|
||||
pull_request_review:
|
||||
types: [submitted]
|
||||
|
||||
jobs:
|
||||
claude-code-action:
|
||||
if: |
|
||||
(github.event_name == 'issue_comment' && contains(github.event.comment.body, '@claude')) ||
|
||||
(github.event_name == 'pull_request_review_comment' && contains(github.event.comment.body, '@claude')) ||
|
||||
(github.event_name == 'pull_request_review' && contains(github.event.review.body, '@claude')) ||
|
||||
(github.event_name == 'issues' && contains(github.event.issue.body, '@claude'))
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
pull-requests: read
|
||||
issues: read
|
||||
id-token: write
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 1
|
||||
|
||||
- name: Run Claude PR Action
|
||||
uses: anthropics/claude-code-action@beta
|
||||
with:
|
||||
# anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
|
||||
# Or use OAuth token instead:
|
||||
claude_code_oauth_token: ${{ secrets.CLAUDE_CODE_OAUTH_TOKEN }}
|
||||
timeout_minutes: "60"
|
||||
@@ -0,0 +1,63 @@
|
||||
name: 🧠 Claude Code
|
||||
|
||||
on:
|
||||
issue_comment:
|
||||
types: [created]
|
||||
pull_request_review_comment:
|
||||
types: [created]
|
||||
issues:
|
||||
types: [opened, assigned]
|
||||
pull_request_review:
|
||||
types: [submitted]
|
||||
|
||||
jobs:
|
||||
claude:
|
||||
if: |
|
||||
(github.event_name == 'issue_comment' && contains(github.event.comment.body, '@claude')) ||
|
||||
(github.event_name == 'pull_request_review_comment' && contains(github.event.comment.body, '@claude')) ||
|
||||
(github.event_name == 'pull_request_review' && contains(github.event.review.body, '@claude')) ||
|
||||
(github.event_name == 'issues' && (contains(github.event.issue.body, '@claude') || contains(github.event.issue.title, '@claude')))
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
pull-requests: read
|
||||
issues: read
|
||||
id-token: write
|
||||
actions: read # Required for Claude to read CI results on PRs
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 1
|
||||
|
||||
- name: Run Claude Code
|
||||
id: claude
|
||||
uses: anthropics/claude-code-action@beta
|
||||
with:
|
||||
claude_code_oauth_token: ${{ secrets.CLAUDE_CODE_OAUTH_TOKEN }}
|
||||
|
||||
# This is an optional setting that allows Claude to read CI results on PRs
|
||||
additional_permissions: |
|
||||
actions: read
|
||||
|
||||
# Optional: Specify model (defaults to Claude Sonnet 4, uncomment for Claude Opus 4)
|
||||
# model: "claude-opus-4-20250514"
|
||||
|
||||
# Optional: Customize the trigger phrase (default: @claude)
|
||||
# trigger_phrase: "/claude"
|
||||
|
||||
# Optional: Trigger when specific user is assigned to an issue
|
||||
# assignee_trigger: "claude-bot"
|
||||
|
||||
# Optional: Allow Claude to run specific commands
|
||||
# allowed_tools: "Bash(npm install),Bash(npm run build),Bash(npm run test:*),Bash(npm run lint:*)"
|
||||
|
||||
# Optional: Add custom instructions for Claude to customize its behavior for your project
|
||||
# custom_instructions: |
|
||||
# Follow our coding standards
|
||||
# Ensure all new code has tests
|
||||
# Use TypeScript for new files
|
||||
|
||||
# Optional: Custom environment variables for Claude
|
||||
# claude_env: |
|
||||
# NODE_ENV: test
|
||||
@@ -1,4 +1,4 @@
|
||||
name: Issue labeler
|
||||
name: 🏷️ Issue labeler
|
||||
on:
|
||||
issues:
|
||||
types: [opened]
|
||||
|
||||
@@ -8,7 +8,7 @@ env:
|
||||
VITE_WEB_URL: https://app.folo.is
|
||||
VITE_API_URL: https://api.follow.is
|
||||
|
||||
name: CI Format, Typecheck and Lint
|
||||
name: ✨ CI Format, Typecheck and Lint
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.ref }}-lint
|
||||
cancel-in-progress: ${{ github.ref != 'refs/heads/main' && github.ref != 'refs/heads/dev' }}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
name: PR Conventional Commit Validation
|
||||
name: ✅ PR Conventional Commit Validation
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
name: Branch Synchronization
|
||||
name: 🔄 Branch Synchronization
|
||||
|
||||
on:
|
||||
push:
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
name: Tag on SemVer Commit
|
||||
name: 🏷️ Tag on SemVer Commit
|
||||
|
||||
on:
|
||||
push:
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
name: "translator"
|
||||
name: "🌍 translator"
|
||||
on:
|
||||
issues:
|
||||
types: [opened, edited]
|
||||
|
||||
+6
-1
@@ -23,4 +23,9 @@ apps/desktop/src/renderer/dev-dist
|
||||
tsconfig.tsbuildinfo
|
||||
buildServer.json
|
||||
|
||||
**/**/generated-routes.ts
|
||||
**/**/generated-routes.ts
|
||||
|
||||
apps/desktop/build/appxmanifest.xml
|
||||
|
||||
.claude/settings.local.json
|
||||
PRPS/*
|
||||
|
||||
@@ -0,0 +1,234 @@
|
||||
# CLAUDE.md
|
||||
|
||||
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
|
||||
|
||||
## Project Overview
|
||||
|
||||
Follow (Folo) is a modern RSS aggregator and content management platform with multiple applications across different platforms. It's built as a monorepo using pnpm workspaces with Turbo for build orchestration.
|
||||
|
||||
## Repository Structure
|
||||
|
||||
### Applications (`apps/`)
|
||||
|
||||
- **`apps/desktop/`** - Electron desktop application with main and renderer processes
|
||||
- **`apps/mobile/`** - React Native mobile app for iOS and Android
|
||||
- **`apps/ssr/`** - Server-side rendered web application
|
||||
- **`apps/mobile/web-app/`** - HTML renderer for mobile web views
|
||||
|
||||
### Packages (`packages/`)
|
||||
|
||||
- **`packages/internal/`** - Internal shared packages (components, database, hooks, store, etc.)
|
||||
- **`packages/configs/`** - Shared configuration files (Tailwind, TypeScript)
|
||||
- **`packages/utils/`** - Utility functions and helpers
|
||||
- **`packages/readability/`** - Content readability parsing
|
||||
- **`packages/vite-plugin-route-builder/`** - Custom Vite plugin for route generation
|
||||
|
||||
## Essential Commands
|
||||
|
||||
### Development
|
||||
|
||||
```bash
|
||||
# Install dependencies (from root)
|
||||
pnpm install
|
||||
|
||||
# Desktop app development (browser - recommended)
|
||||
cd apps/desktop && pnpm run dev:web
|
||||
|
||||
# Desktop app development (Electron)
|
||||
cd apps/desktop && pnpm run dev:electron
|
||||
|
||||
# Mobile app development
|
||||
cd apps/mobile && pnpm run dev
|
||||
|
||||
# SSR development
|
||||
cd apps/ssr && pnpm run dev
|
||||
|
||||
# Build web version
|
||||
pnpm run build:web
|
||||
```
|
||||
|
||||
### Code Quality
|
||||
|
||||
```bash
|
||||
# Lint all code
|
||||
pnpm run lint
|
||||
|
||||
# Fix linting issues
|
||||
pnpm run lint:fix
|
||||
|
||||
# TypeScript linting
|
||||
pnpm run lint:tsl
|
||||
|
||||
# Format code
|
||||
pnpm run format
|
||||
|
||||
# Type checking
|
||||
pnpm run typecheck
|
||||
|
||||
# Run tests
|
||||
pnpm run test
|
||||
```
|
||||
|
||||
### Package Management
|
||||
|
||||
```bash
|
||||
# Build shared packages
|
||||
pnpm run build:packages
|
||||
|
||||
# Generate i18n templates
|
||||
pnpm run generator:i18n-template
|
||||
|
||||
# Sync icons from SVG to React Native
|
||||
pnpm run icons:sync
|
||||
```
|
||||
|
||||
## Architecture Guidelines
|
||||
|
||||
### Multi-Platform Architecture
|
||||
|
||||
- **Desktop**: Electron app with main/renderer processes, using Vite for both
|
||||
- **Mobile**: React Native with Expo, shared UI components with web
|
||||
- **Web/SSR**: Next.js-style SSR application for server-side rendering
|
||||
- **Shared Logic**: Common business logic in `packages/internal/`
|
||||
|
||||
### State Management
|
||||
|
||||
- **Jotai** for atomic state management across all platforms
|
||||
- **Zustand** for complex state stores (in `packages/internal/store/`)
|
||||
- **React Query** for server state management
|
||||
|
||||
### Styling
|
||||
|
||||
- **Tailwind CSS** for styling across all platforms
|
||||
- Platform-specific Tailwind configs in each app
|
||||
- Shared Tailwind utilities in `packages/configs/tailwindcss/`
|
||||
- **UI Design Style**: Follow Vercel and Linear SaaS UI aesthetics - clean, modern, minimal design with subtle shadows, rounded corners, and excellent typography
|
||||
|
||||
#### UIKit Colors for Desktop Components
|
||||
|
||||
For desktop components (`apps/desktop/**/*`) and shared UI components (`packages/internal/components/**/*`), use Apple UIKit color system with Tailwind classes. **Important**: Always use the correct Tailwind prefix for each color category:
|
||||
|
||||
**System Colors**: `text-red`, `bg-red`, `border-red` (same for `orange`, `yellow`, `green`, `mint`, `teal`, `cyan`, `blue`, `indigo`, `purple`, `pink`, `brown`, `gray`)
|
||||
|
||||
**Fill Colors**:
|
||||
|
||||
- Background: `bg-fill`, `bg-fill-secondary`, `bg-fill-tertiary`, `bg-fill-quaternary`, `bg-fill-quinary`, `bg-fill-vibrant`, `bg-fill-vibrant-secondary`, `bg-fill-vibrant-tertiary`, `bg-fill-vibrant-quaternary`, `bg-fill-vibrant-quinary`
|
||||
- Border: `border-fill`, `border-fill-secondary`, etc.
|
||||
|
||||
**Text Colors**: `text-text`, `text-text-secondary`, `text-text-tertiary`, `text-text-quaternary`, `text-text-quinary`, `text-text-vibrant`, `text-text-vibrant-secondary`, `text-text-vibrant-tertiary`, `text-text-vibrant-quaternary`, `text-text-vibrant-quinary`
|
||||
|
||||
**Material Colors**: `bg-material-ultra-thick`, `bg-material-thick`, `bg-material-medium`, `bg-material-thin`, `bg-material-ultra-thin`, `bg-material-opaque`
|
||||
|
||||
**Control Colors**: `bg-control-enabled`, `bg-control-disabled`
|
||||
|
||||
**Interface Colors**: `bg-menu`, `bg-popover`, `bg-titlebar`, `bg-sidebar`, `bg-selection-focused`, `bg-selection-focused-fill`, `bg-selection-unfocused`, `bg-selection-unfocused-fill`, `bg-header-view`, `bg-tooltip`, `bg-under-window-background`
|
||||
|
||||
These colors automatically adapt to light/dark mode following Apple's design system. Remember to use the appropriate prefix (`text-`, `bg-`, `border-`) based on the CSS property you're styling.
|
||||
|
||||
#### Icons
|
||||
|
||||
For icon usage, prioritize the MingCute icon library with the `i-mgc-` prefix. Icons are available in the format `i-mgc-[icon-name]-[style]` where style can be `re` (regular), `fi` (filled), etc.
|
||||
|
||||
**Important**: Always try to find an appropriate icon with the `i-mgc-` prefix first. Only use the `i-mingcute-` prefix as a fallback when no suitable `i-mgc-` icon exists.
|
||||
|
||||
Examples:
|
||||
|
||||
- Preferred: `i-mgc-copy-cute-re`, `i-mgc-external-link-cute-re`
|
||||
- Fallback only: `i-mingcute-copy-line` (only if no mgc equivalent exists)
|
||||
|
||||
### Database
|
||||
|
||||
- **Drizzle ORM** with SQLite for local data storage
|
||||
- Platform-specific database implementations in `packages/internal/database/`
|
||||
- Migration system with versioned SQL files
|
||||
|
||||
### Internationalization
|
||||
|
||||
- **i18next** for internationalization
|
||||
- Locale files in `locales/` directory organized by feature
|
||||
- Custom ESLint rules for i18n validation
|
||||
|
||||
#### i18n Writing Guidelines
|
||||
|
||||
1. Follow [i18next formatting guidelines](https://www.i18next.com/translation-function/formatting)
|
||||
2. **Use flat keys only** - Use `.` notation for separation, no nested objects
|
||||
3. For plural-sensitive languages, use `_one` and `_other` suffixes
|
||||
4. **Avoid conflicting flat keys** - During build, flat dot-separated keys (e.g., 'exif.custom.rendered.custom') are automatically converted to nested objects, which can cause conflicts. For example, 'exif.custom.rendered.custom' conflicts with 'exif.custom.rendered'. Avoid such patterns.
|
||||
|
||||
Example:
|
||||
|
||||
```json
|
||||
{
|
||||
"personalize.title": "Personalization",
|
||||
"personalize.prompt.label": "Personal Prompt",
|
||||
"shortcuts.add": "Add Shortcut",
|
||||
"shortcuts.validation.required": "Name and prompt are required"
|
||||
}
|
||||
```
|
||||
|
||||
## Development Setup Notes
|
||||
|
||||
### Prerequisites
|
||||
|
||||
- Enable Corepack: `corepack enable && corepack prepare`
|
||||
- For mobile development: macOS with Xcode required
|
||||
|
||||
### Environment Setup
|
||||
|
||||
- Copy `.env.example` to `.env` in relevant app directories
|
||||
- For development, use `VITE_API_URL=https://api.follow.is`
|
||||
- Browser development uses `https://app.folo.is/__debug_proxy` for API access
|
||||
|
||||
### Mobile Development
|
||||
|
||||
- iOS development requires Xcode and iOS simulator
|
||||
- Native module development in `apps/mobile/native/`
|
||||
- Use `pnpm expo prebuild --clean` for clean builds
|
||||
|
||||
## Code Organization Patterns
|
||||
|
||||
### Import Conventions
|
||||
|
||||
- Use `pathe` instead of `node:path` for cross-platform compatibility
|
||||
- Shared utilities should be imported from `packages/internal/`
|
||||
- Platform-specific code should be clearly separated
|
||||
|
||||
### Component Structure
|
||||
|
||||
- Shared UI components in `packages/internal/components/`
|
||||
- Platform-specific components in respective app directories
|
||||
- Use TypeScript interfaces for component props
|
||||
|
||||
### Error Handling
|
||||
|
||||
- Custom error parsing utilities in `packages/internal/utils/`
|
||||
- Sentry integration for error reporting across platforms
|
||||
|
||||
## Build and Deployment
|
||||
|
||||
### Build Outputs
|
||||
|
||||
- Desktop: `apps/desktop/out/` for packaged applications
|
||||
- Web: `apps/desktop/out/web/` for static web assets
|
||||
- Mobile: Platform-specific build directories
|
||||
|
||||
### Turbo Configuration
|
||||
|
||||
- Build orchestration via `turbo.json`
|
||||
- Dependency-aware builds with output caching
|
||||
- Parallel execution for independent packages
|
||||
|
||||
## Testing Strategy
|
||||
|
||||
- Vitest for unit testing across packages
|
||||
- Platform-specific test configurations
|
||||
- Test files co-located with source code
|
||||
|
||||
## Key Dependencies
|
||||
|
||||
- **Build**: Vite, Turbo, pnpm workspaces
|
||||
- **Frontend**: React 19, Electron, React Native, Expo
|
||||
- **State**: Jotai, Zustand, TanStack Query
|
||||
- **Styling**: Tailwind CSS, Framer Motion
|
||||
- **Database**: Drizzle ORM, SQLite
|
||||
- **Utils**: Day.js, Zod, i18next
|
||||
@@ -1,6 +1,6 @@
|
||||
<div align="center">
|
||||
<a href="https://github.com/RSSNext/Folo">
|
||||
<img src="https://github.com/RSSNext/follow/assets/41265413/c6c02ad5-cddc-46f5-8420-a47afe1c82fe" alt="Logo" width="80" height="80">
|
||||
<img src="https://github.com/RSSNext/Folo/raw/refs/heads/dev/apps/desktop/layer/renderer/public/icon.svg" alt="Logo" width="80" height="80">
|
||||
</a>
|
||||
|
||||
<h3>Folo</h3>
|
||||
@@ -17,12 +17,12 @@
|
||||
<a href="https://x.com/intent/follow?screen_name=folo_is"><img src="https://img.shields.io/badge/Follow-blue?color=1d9bf0&logo=x&labelColor=black&style=flat-square" /></a>
|
||||
<a href="https://discord.gg/followapp" target="_blank"><img src="https://img.shields.io/badge/dynamic/json?url=https%3A%2F%2Fdiscord.com%2Fapi%2Finvites%2Ffollowapp%3Fwith_counts%3Dtrue&query=approximate_member_count&color=5865F2&label=Discord&labelColor=black&logo=discord&logoColor=white&style=flat-square"/></a>
|
||||
<br />
|
||||
<a href="https://github.com/RSSNext/Folo/releases"><img src="https://img.shields.io/github/package-json/v/RSSNext/Folo?filename=%2Fapps%2Fmobile%2Fpackage.json&style=flat-square&logo=data%3Aimage%2Fsvg%2Bxml%3Bbase64%2CPHN2ZyB3aWR0aD0iNTUiIGhlaWdodD0iNTUiIHZpZXdCb3g9IjAgMCA1NSA1NSIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZD0iTTQxLjc5NDQgMTBIMTguNjc4NkMxNS44ODMzIDEwIDEzLjYxNzIgMTIuMTk2NSAxMy42MTcyIDE0LjkwNTlDMTMuNjE3MiAxNy42MTU0IDE1Ljg4MzMgMTkuODExOSAxOC42Nzg2IDE5LjgxMTlINDEuNzk0NEM0NC41ODk5IDE5LjgxMTkgNDYuODU1OSAxNy42MTU0IDQ2Ljg1NTkgMTQuOTA1OUM0Ni44NTU5IDEyLjE5NjUgNDQuNTg5OSAxMCA0MS43OTQ0IDEwWiIgZmlsbD0id2hpdGUiLz4KPHBhdGggZD0iTTI5LjQ2ODMgMjIuNzU1OUgxNC4wNjE1QzExLjI2NjEgMjIuNzU1OSA5IDI0Ljk1MjMgOSAyNy42NjE4QzkgMzAuMzcxMyAxMS4yNjYxIDMyLjU2NzcgMTQuMDYxNSAzMi41Njc3SDI5LjQ2ODNDMzIuMjYzNyAzMi41Njc3IDM0LjUyOTggMzAuMzcxMyAzNC41Mjk4IDI3LjY2MThDMzQuNTI5OCAyNC45NTIzIDMyLjI2MzcgMjIuNzU1OSAyOS40NjgzIDIyLjc1NTlaIiBmaWxsPSJ3aGl0ZSIvPgo8cGF0aCBkPSJNMzAuOTU4OSA0MC40MjcyQzMwLjk1ODkgMzcuNzE3OSAyOC42OTI4IDM1LjUyMTUgMjUuODk3NCAzNS41MjE1QzIzLjEwMjEgMzUuNTIxNSAyMC44MzU5IDM3LjcxNzkgMjAuODM1OSA0MC40MjcyQzIwLjgzNTkgNDMuMTM3MSAyMy4xMDIxIDQ1LjMzMzIgMjUuODk3NCA0NS4zMzMyQzI4LjY5MjggNDUuMzMzMiAzMC45NTg5IDQzLjEzNzEgMzAuOTU4OSA0MC40MjcyWiIgZmlsbD0id2hpdGUiLz4KPC9zdmc%2BCg%3D%3D&label=Mobile&labelColor=black&color=FF5E01" /></a>
|
||||
<a href="https://github.com/RSSNext/Folo/releases"><img src="https://img.shields.io/github/package-json/v/RSSNext/Folo?filename=%2Fapps%2Fmobile%2Fpackage.json&style=flat-square&logo=folo&logoColor=white&label=Mobile&labelColor=black&color=FF5C00" /></a>
|
||||
<a href="https://apps.apple.com/us/app/folo-follow-everything/id6739802604"><img src="https://img.shields.io/itunes/v/6739802604?style=flat-square&logo=apple&label=App%20Store&color=FF5C00&labelColor=black" /></a>
|
||||
<a href="https://play.google.com/store/apps/details?id=is.follow" target="_blank"><img src="https://img.shields.io/endpoint?url=https%3A%2F%2Fplay.cuzi.workers.dev%2Fplay%3Fi%3Dis.follow%26gl%3DUS%26hl%3Den%26l%3DAndroid%26m%3D%24version&style=flat-square&logo=google-play&label=Google%20Play&labelColor=black&color=FF5E01"/></a>
|
||||
<a href="https://github.com/RSSNext/Folo/releases"><img src="https://img.shields.io/github/package-json/v/RSSNext/Folo?filename=%2Fapps%2Fdesktop%2Fpackage.json&style=flat-square&logo=data%3Aimage%2Fsvg%2Bxml%3Bbase64%2CPHN2ZyB3aWR0aD0iNTUiIGhlaWdodD0iNTUiIHZpZXdCb3g9IjAgMCA1NSA1NSIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZD0iTTQxLjc5NDQgMTBIMTguNjc4NkMxNS44ODMzIDEwIDEzLjYxNzIgMTIuMTk2NSAxMy42MTcyIDE0LjkwNTlDMTMuNjE3MiAxNy42MTU0IDE1Ljg4MzMgMTkuODExOSAxOC42Nzg2IDE5LjgxMTlINDEuNzk0NEM0NC41ODk5IDE5LjgxMTkgNDYuODU1OSAxNy42MTU0IDQ2Ljg1NTkgMTQuOTA1OUM0Ni44NTU5IDEyLjE5NjUgNDQuNTg5OSAxMCA0MS43OTQ0IDEwWiIgZmlsbD0id2hpdGUiLz4KPHBhdGggZD0iTTI5LjQ2ODMgMjIuNzU1OUgxNC4wNjE1QzExLjI2NjEgMjIuNzU1OSA5IDI0Ljk1MjMgOSAyNy42NjE4QzkgMzAuMzcxMyAxMS4yNjYxIDMyLjU2NzcgMTQuMDYxNSAzMi41Njc3SDI5LjQ2ODNDMzIuMjYzNyAzMi41Njc3IDM0LjUyOTggMzAuMzcxMyAzNC41Mjk4IDI3LjY2MThDMzQuNTI5OCAyNC45NTIzIDMyLjI2MzcgMjIuNzU1OSAyOS40NjgzIDIyLjc1NTlaIiBmaWxsPSJ3aGl0ZSIvPgo8cGF0aCBkPSJNMzAuOTU4OSA0MC40MjcyQzMwLjk1ODkgMzcuNzE3OSAyOC42OTI4IDM1LjUyMTUgMjUuODk3NCAzNS41MjE1QzIzLjEwMjEgMzUuNTIxNSAyMC44MzU5IDM3LjcxNzkgMjAuODM1OSA0MC40MjcyQzIwLjgzNTkgNDMuMTM3MSAyMy4xMDIxIDQ1LjMzMzIgMjUuODk3NCA0NS4zMzMyQzI4LjY5MjggNDUuMzMzMiAzMC45NTg5IDQzLjEzNzEgMzAuOTU4OSA0MC40MjcyWiIgZmlsbD0id2hpdGUiLz4KPC9zdmc%2BCg%3D%3D&label=Desktop&labelColor=black&color=FF5E01" /></a>
|
||||
<a href="https://apps.apple.com/us/app/folo-follow-everything/id6739802604"><img src="https://img.shields.io/badge/dynamic/json?url=https%3A%2F%2Ffolo-mac-app-store-version.rss3.workers.dev%2F&query=version&prefix=v&style=flat-square&logo=apple&label=Mac%20App%20Store&labelColor=black&color=FF5E01&cacheSeconds=3600" /></a>
|
||||
<a href="https://apps.microsoft.com/detail/9nvfzpv0v0ht?mode=direct"><img src="https://img.shields.io/badge/dynamic/json?url=https%3A%2F%2Ffolo-microsoft-store-version.rss3.workers.dev%2F&query=version&style=flat-square&logo=data%3Aimage%2Fsvg%2Bxml%3Bbase64%2CPHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIyNCIgaGVpZ2h0PSIyNCIgdmlld0JveD0iMCAwIDI0IDI0IiBmaWxsPSJub25lIj48cGF0aCBmaWxsPSIjZmZmIiBkPSJNMyAzaDguNTN2OC41M0gzek0xMi40NjkgM2g4LjUzdjguNTNoLTguNTN6TTMgMTIuNDdoOC41M1YyMUgzek0xMi40NjkgMTIuNDdoOC41M1YyMWgtOC41M3oiLz48L3N2Zz4%3D&logoColor=white&label=Microsoft%20Store&labelColor=black&color=FF5E01&cacheSeconds=3600&prefix=v" /></a>
|
||||
<a href="https://play.google.com/store/apps/details?id=is.follow" target="_blank"><img src="https://img.shields.io/endpoint?url=https%3A%2F%2Fplay.cuzi.workers.dev%2Fplay%3Fi%3Dis.follow%26gl%3DUS%26hl%3Den%26l%3DAndroid%26m%3D%24version&style=flat-square&logo=google-play&label=Google%20Play&labelColor=black&color=FF5C00"/></a>
|
||||
<a href="https://github.com/RSSNext/Folo/releases"><img src="https://img.shields.io/github/package-json/v/RSSNext/Folo?filename=%2Fapps%2Fdesktop%2Fpackage.json&style=flat-square&logo=folo&logoColor=white&label=Desktop&labelColor=black&color=FF5C00" /></a>
|
||||
<a href="https://apps.apple.com/us/app/folo-follow-everything/id6739802604"><img src="https://img.shields.io/badge/dynamic/json?url=https%3A%2F%2Ffolo-mac-app-store-version.rss3.workers.dev%2F&query=version&prefix=v&style=flat-square&logo=apple&label=Mac%20App%20Store&labelColor=black&color=FF5C00&cacheSeconds=3600" /></a>
|
||||
<a href="https://apps.microsoft.com/detail/9nvfzpv0v0ht?mode=direct"><img src="https://img.shields.io/badge/dynamic/json?url=https%3A%2F%2Ffolo-microsoft-store-version.rss3.workers.dev%2F&query=version&style=flat-square&logo=data%3Aimage%2Fsvg%2Bxml%3Bbase64%2CPHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIyNCIgaGVpZ2h0PSIyNCIgdmlld0JveD0iMCAwIDI0IDI0IiBmaWxsPSJub25lIj48cGF0aCBmaWxsPSIjZmZmIiBkPSJNMyAzaDguNTN2OC41M0gzek0xMi40NjkgM2g4LjUzdjguNTNoLTguNTN6TTMgMTIuNDdoOC41M1YyMUgzek0xMi40NjkgMTIuNDdoOC41M1YyMWgtOC41M3oiLz48L3N2Zz4%3D&logoColor=white&label=Microsoft%20Store&labelColor=black&color=FF5C00&cacheSeconds=3600&prefix=v" /></a>
|
||||
<br />
|
||||
<br />
|
||||
<!-- <a href="https://github.com/RSSNext/Folo" target="_blank"><img src="https://github.com/user-attachments/assets/59b957fb-59ed-4ef0-994e-f6a402a6fe2b" alt="GitHub Trending" height="55"/></a>
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<Package
|
||||
xmlns="http://schemas.microsoft.com/appx/manifest/foundation/windows10"
|
||||
xmlns:uap="http://schemas.microsoft.com/appx/manifest/uap/windows10"
|
||||
xmlns:rescap="http://schemas.microsoft.com/appx/manifest/foundation/windows10/restrictedcapabilities"
|
||||
xmlns:mp="http://schemas.microsoft.com/appx/2014/phone/manifest">
|
||||
<Identity Name="{identityName}"
|
||||
ProcessorArchitecture="x64"
|
||||
Publisher="{publisherName}"
|
||||
Version="{packageVersion}" />
|
||||
<Properties>
|
||||
<DisplayName>{packageDisplayName}</DisplayName>
|
||||
<PublisherDisplayName>{publisherDisplayName}</PublisherDisplayName>
|
||||
<Description>No description entered</Description>
|
||||
<Logo>assets\SampleAppx.50x50.png</Logo>
|
||||
</Properties>
|
||||
<Resources>
|
||||
<Resource Language="en-us" />
|
||||
<Resource Language="zh-cn" />
|
||||
<Resource Language="zh-tw" />
|
||||
<Resource Language="ja" />
|
||||
</Resources>
|
||||
<Dependencies>
|
||||
<TargetDeviceFamily Name="Windows.Desktop" MinVersion="10.0.14316.0" MaxVersionTested="10.0.14316.0" />
|
||||
</Dependencies>
|
||||
<Capabilities>
|
||||
<rescap:Capability Name="runFullTrust"/>
|
||||
</Capabilities>
|
||||
<Applications>
|
||||
<Application Id="{packageName}" Executable="{packageExecutable}" EntryPoint="Windows.FullTrustApplication">
|
||||
<uap:VisualElements
|
||||
BackgroundColor="{packageBackgroundColor}"
|
||||
DisplayName="{packageDisplayName}"
|
||||
Square150x150Logo="assets\SampleAppx.150x150.png"
|
||||
Square44x44Logo="assets\SampleAppx.44x44.png"
|
||||
Description="{packageDescription}">
|
||||
<uap:DefaultTile Wide310x150Logo="assets\SampleAppx.310x150.png" />
|
||||
</uap:VisualElements>
|
||||
<Extensions>{protocol}
|
||||
</Extensions>
|
||||
</Application>
|
||||
</Applications>
|
||||
</Package>
|
||||
@@ -1,18 +1,13 @@
|
||||
import { fileURLToPath } from "node:url"
|
||||
|
||||
import { dirname, resolve } from "pathe"
|
||||
import { tsImport } from "tsx/esm/api"
|
||||
import type { UserConfig } from "vite"
|
||||
import { routeBuilderPlugin } from "vite-plugin-route-builder"
|
||||
|
||||
import { cleanupUnnecessaryFilesPlugin } from "../plugins/vite/cleanup"
|
||||
import { createPlatformSpecificImportPlugin } from "../plugins/vite/specific-import"
|
||||
import { viteRenderBaseConfig } from "./vite.render.config"
|
||||
|
||||
const routeBuilderPluginV2 = await tsImport(
|
||||
"@follow-app/vite-plugin-route-builder",
|
||||
import.meta.url,
|
||||
).then((m) => m.default)
|
||||
|
||||
const root = resolve(fileURLToPath(dirname(import.meta.url)), "..")
|
||||
|
||||
const VITE_ROOT = resolve(root, "layer/renderer")
|
||||
@@ -26,7 +21,7 @@ export default {
|
||||
plugins: [
|
||||
...viteRenderBaseConfig.plugins,
|
||||
createPlatformSpecificImportPlugin("electron"),
|
||||
routeBuilderPluginV2({
|
||||
routeBuilderPlugin({
|
||||
pagePattern: "src/pages/**/*.tsx",
|
||||
outputPath: "src/generated-routes.ts",
|
||||
enableInDev: true,
|
||||
|
||||
@@ -18,6 +18,8 @@ import { rimraf, rimrafSync } from "rimraf"
|
||||
|
||||
const platform = process.argv.find((arg) => arg.startsWith("--platform"))?.split("=")[1]
|
||||
const mode = process.argv.find((arg) => arg.startsWith("--mode"))?.split("=")[1]
|
||||
const isMicrosoftStore =
|
||||
process.argv.find((arg) => arg.startsWith("--ms"))?.split("=")[1] === "true"
|
||||
|
||||
const isStaging = mode === "staging"
|
||||
|
||||
@@ -185,11 +187,6 @@ const config: ForgeConfig = {
|
||||
},
|
||||
["darwin", "mas"],
|
||||
),
|
||||
new MakerSquirrel({
|
||||
name: "Folo",
|
||||
setupIcon: isStaging ? "resources/icon-staging.ico" : "resources/icon.ico",
|
||||
iconUrl: "https://app.folo.is/favicon.ico",
|
||||
}),
|
||||
new MakerAppImage({
|
||||
config: {
|
||||
icons: [
|
||||
@@ -207,17 +204,29 @@ const config: ForgeConfig = {
|
||||
},
|
||||
["mas"],
|
||||
),
|
||||
new MakerAppX({
|
||||
publisher: "CN=7CBBEB6A-9B0E-4387-BAE3-576D0ACA279E",
|
||||
packageDisplayName: "Folo - Follow everything in one place",
|
||||
devCert: "build/dev.pfx",
|
||||
assets: "static/appx",
|
||||
// @ts-ignore
|
||||
publisherDisplayName: "Natural Selection Labs",
|
||||
identityName: "NaturalSelectionLabs.Follow-Yourfavoritesinoneinbo",
|
||||
packageBackgroundColor: "#FF5C00",
|
||||
protocol: "folo",
|
||||
}),
|
||||
// Only include AppX maker for Microsoft Store builds
|
||||
...(isMicrosoftStore
|
||||
? [
|
||||
new MakerAppX({
|
||||
publisher: "CN=7CBBEB6A-9B0E-4387-BAE3-576D0ACA279E",
|
||||
packageDisplayName: "Folo - Follow everything in one place",
|
||||
devCert: "build/dev.pfx",
|
||||
assets: "static/appx",
|
||||
manifest: "build/appxmanifest.xml",
|
||||
// @ts-ignore
|
||||
publisherDisplayName: "Natural Selection Labs",
|
||||
identityName: "NaturalSelectionLabs.Follow-Yourfavoritesinoneinbo",
|
||||
packageBackgroundColor: "#FF5C00",
|
||||
protocol: "folo",
|
||||
}),
|
||||
]
|
||||
: [
|
||||
new MakerSquirrel({
|
||||
name: "Folo",
|
||||
setupIcon: isStaging ? "resources/icon-staging.ico" : "resources/icon.ico",
|
||||
iconUrl: "https://app.folo.is/favicon.ico",
|
||||
}),
|
||||
]),
|
||||
],
|
||||
plugins: [
|
||||
// Fuses are used to enable/disable various Electron functionality
|
||||
|
||||
@@ -28,7 +28,6 @@
|
||||
"@follow/utils": "workspace:*",
|
||||
"@openpanel/web": "1.0.1",
|
||||
"@sentry/electron": "6.8.0",
|
||||
"@sindresorhus/slugify": "2.2.1",
|
||||
"builder-util-runtime": "9.3.1",
|
||||
"electron-context-menu": "4.0.5",
|
||||
"electron-log": "5.4.1",
|
||||
|
||||
@@ -1,17 +1,49 @@
|
||||
import { existsSync } from "node:fs"
|
||||
import fsp from "node:fs/promises"
|
||||
|
||||
import slugify from "@sindresorhus/slugify"
|
||||
import path from "pathe"
|
||||
|
||||
import { store } from "~/lib/store"
|
||||
|
||||
import type { IpcContext } from "../base"
|
||||
import { IpcMethod, IpcService } from "../base"
|
||||
|
||||
// Taken from https://github.com/rollup/rollup/blob/4f69d33af3b2ec9320c43c9e6c65ea23a02bdde3/src/utils/sanitizeFileName.ts
|
||||
// https://datatracker.ietf.org/doc/html/rfc2396
|
||||
// eslint-disable-next-line no-control-regex
|
||||
const INVALID_CHAR_REGEX = /[\u0000-\u001F"#$%&*+,:;<=>?[\]^`{|}\u007F]/g
|
||||
const DRIVE_LETTER_REGEX = /^[a-z]:/i
|
||||
|
||||
function sanitizeFileName(name: string): string {
|
||||
const match = DRIVE_LETTER_REGEX.exec(name)
|
||||
const driveLetter = match ? match[0] : ""
|
||||
|
||||
// A `:` is only allowed as part of a windows drive letter (ex: C:\foo)
|
||||
// Otherwise, avoid them because they can refer to NTFS alternate data streams.
|
||||
return driveLetter + name.slice(driveLetter.length).replaceAll(INVALID_CHAR_REGEX, "_")
|
||||
}
|
||||
|
||||
// Input types
|
||||
interface SaveToEagleInput {
|
||||
url: string
|
||||
mediaUrls: string[]
|
||||
}
|
||||
|
||||
interface LoginToQBittorrentInput {
|
||||
host: string
|
||||
username: string
|
||||
password: string
|
||||
}
|
||||
|
||||
interface CheckQBittorrentAuthInput {
|
||||
host: string
|
||||
}
|
||||
|
||||
interface AddMagnetInput {
|
||||
host: string
|
||||
urls: string[]
|
||||
}
|
||||
|
||||
export class IntegrationService extends IpcService {
|
||||
constructor() {
|
||||
super("integration")
|
||||
@@ -32,7 +64,7 @@ export class IntegrationService extends IpcService {
|
||||
try {
|
||||
const { url, title, content, author, publishedAt, vaultPath } = input
|
||||
|
||||
const fileName = `${slugify(title || publishedAt)
|
||||
const fileName = `${sanitizeFileName(title || publishedAt)
|
||||
.trim()
|
||||
.slice(0, 20)}.md`
|
||||
const filePath = path.join(vaultPath, fileName)
|
||||
@@ -84,4 +116,83 @@ ${content}
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
@IpcMethod()
|
||||
async loginToQBittorrent(context: IpcContext, input: LoginToQBittorrentInput) {
|
||||
const { host, username, password } = input
|
||||
|
||||
const existingSID = store.get("qbittorrentSID")
|
||||
if (existingSID) {
|
||||
const errorMessage = await this.checkQBittorrentAuth(context, { host })
|
||||
if (!errorMessage) {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
const res = await fetch(`${host}/api/v2/auth/login`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/x-www-form-urlencoded",
|
||||
},
|
||||
body: `username=${encodeURIComponent(username)}&password=${encodeURIComponent(password)}`,
|
||||
})
|
||||
|
||||
if (!res.ok) {
|
||||
return `Failed to log in to qBittorrent: ${await res.text()}`
|
||||
}
|
||||
|
||||
const cookies = res.headers.get("set-cookie") || ""
|
||||
const match = cookies.match(/SID=([^;]+)/)
|
||||
if (!match || !match[1]) {
|
||||
return "Failed to get SID from qBittorrent"
|
||||
}
|
||||
|
||||
store.set("qbittorrentSID", match[1])
|
||||
return
|
||||
}
|
||||
|
||||
async checkQBittorrentAuth(context: IpcContext, input: CheckQBittorrentAuthInput) {
|
||||
const { host } = input
|
||||
const sid = store.get("qbittorrentSID")
|
||||
if (!sid) {
|
||||
return "Not logged in to qBittorrent"
|
||||
}
|
||||
const res = await fetch(`${host}/api/v2/auth/check`, {
|
||||
method: "GET",
|
||||
headers: {
|
||||
Cookie: `SID=${sid}`,
|
||||
},
|
||||
credentials: "omit",
|
||||
})
|
||||
|
||||
if (!res.ok) {
|
||||
return await res.text()
|
||||
}
|
||||
}
|
||||
|
||||
@IpcMethod()
|
||||
async addMagnet(context: IpcContext, input: AddMagnetInput) {
|
||||
const { host, urls } = input
|
||||
const sid = store.get("qbittorrentSID")
|
||||
if (!sid) {
|
||||
return "Not logged in to qBittorrent"
|
||||
}
|
||||
const res = await fetch(`${host}/api/v2/torrents/add`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/x-www-form-urlencoded",
|
||||
Cookie: `SID=${sid}`,
|
||||
},
|
||||
credentials: "omit",
|
||||
body: `urls=${encodeURIComponent(urls.join("\n"))}`,
|
||||
})
|
||||
|
||||
if (!res.ok) {
|
||||
const text = await res.text()
|
||||
return `Failed to add magnet links: ${text}`
|
||||
}
|
||||
|
||||
// eslint-disable-next-line no-console
|
||||
console.log(`Added magnet links to qBittorrent: ${urls.join(", ")}`)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,6 +9,7 @@ type StoreData = {
|
||||
cacheSizeLimit?: number | null
|
||||
minimizeToTray?: boolean | null
|
||||
proxy?: string | null
|
||||
qbittorrentSID?: string | null
|
||||
user?: string | null
|
||||
windowState?: {
|
||||
height: number
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { DEV, MODE, ModeEnum } from "@follow/shared/constants"
|
||||
import { DEV, MICROSOFT_STORE_BUILD, MODE, ModeEnum } from "@follow/shared/constants"
|
||||
import path from "pathe"
|
||||
|
||||
import { isWindows } from "../env"
|
||||
@@ -8,7 +8,7 @@ export const appUpdaterConfig = {
|
||||
enableRenderHotUpdate: !DEV && MODE !== ModeEnum.staging,
|
||||
enableCoreUpdate:
|
||||
!process.mas &&
|
||||
!process.windowsStore &&
|
||||
!MICROSOFT_STORE_BUILD &&
|
||||
// Disable core update if platfrom is windows and application is't executing from default installion path.
|
||||
// If the process is not executed from the default installation path,
|
||||
// it is usually managed through a package manager like Scoop.
|
||||
|
||||
@@ -12,14 +12,18 @@
|
||||
"typecheck": "tsc --noEmit"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ai-sdk/openai": "2.0.0-beta.11",
|
||||
"@ai-sdk/react": "2.0.0-beta.25",
|
||||
"@dnd-kit/core": "6.3.1",
|
||||
"@dnd-kit/sortable": "10.0.0",
|
||||
"@electron-toolkit/preload": "3.0.2",
|
||||
"@follow-app/client-sdk": "catalog:",
|
||||
"@follow/database": "workspace:*",
|
||||
"@follow/electron-main": "workspace:*",
|
||||
"@follow/shared": "workspace:*",
|
||||
"@follow/store": "workspace:*",
|
||||
"@follow/tracker": "workspace:*",
|
||||
"@folo-services/constants": "0.1.6",
|
||||
"@fontsource/sn-pro": "5.2.5",
|
||||
"@hcaptcha/react-hcaptcha": "1.12.0",
|
||||
"@headlessui/react": "2.2.4",
|
||||
@@ -37,6 +41,7 @@
|
||||
"@radix-ui/react-slot": "1.2.3",
|
||||
"@sentry/react": "9.35.0",
|
||||
"@shikijs/transformers": "3.7.0",
|
||||
"@splinetool/react-spline": "4.0.0",
|
||||
"@tanstack/query-sync-storage-persister": "5.81.5",
|
||||
"@tanstack/react-query": "5.81.5",
|
||||
"@tanstack/react-query-devtools": "5.81.5",
|
||||
@@ -45,7 +50,9 @@
|
||||
"@use-gesture/react": "10.3.1",
|
||||
"@welldone-software/why-did-you-render": "10.0.1",
|
||||
"@yornaath/batshit": "0.10.1",
|
||||
"ai": "5.0.0-beta.25",
|
||||
"camelcase-keys": "9.1.3",
|
||||
"class-variance-authority": "0.7.1",
|
||||
"clsx": "2.1.1",
|
||||
"cmdk": "1.1.1",
|
||||
"cookie-es": "2.0.0",
|
||||
@@ -69,6 +76,7 @@
|
||||
"masonic": "4.1.0",
|
||||
"mdast-util-gfm-table": "2.0.0",
|
||||
"mdast-util-to-markdown": "2.1.2",
|
||||
"mermaid": "11.7.0",
|
||||
"motion": "12.23.0",
|
||||
"nanoid": "5.1.5",
|
||||
"ofetch": "1.4.1",
|
||||
@@ -108,6 +116,7 @@
|
||||
"@follow/models": "workspace:*",
|
||||
"@follow/types": "workspace:*",
|
||||
"@follow/utils": "workspace:*",
|
||||
"@folo-services/ai-tools": "0.2.14",
|
||||
"@types/node": "24.0.10",
|
||||
"@vite-pwa/assets-generator": "1.0.0",
|
||||
"fake-indexeddb": "6.0.1",
|
||||
|
||||
@@ -1 +1 @@
|
||||
<svg viewBox="0 0 145 145" fill="none" xmlns="http://www.w3.org/2000/svg"><mask id="mask0_54_296" maskUnits="userSpaceOnUse" x="0" y="0" width="145" height="145"><path fill-rule="evenodd" clip-rule="evenodd" d="M144.491 45.4541C144.491 43.75 144.492 42.0456 144.481 40.3413C144.473 38.9056 144.456 37.4702 144.417 36.0352C144.333 32.9075 144.148 29.753 143.592 26.6601C143.028 23.5227 142.107 20.6027 140.655 17.752C139.228 14.9501 137.364 12.3862 135.139 10.1633C132.915 7.94053 130.351 6.07747 127.548 4.65117C124.694 3.19908 121.771 2.27818 118.63 1.71424C115.537 1.15884 112.381 0.974699 109.254 0.890204C107.818 0.851354 106.382 0.834978 104.945 0.826093C103.24 0.81564 101.535 0.816511 99.8296 0.816511L80.0305 0.745605H65.2222L45.7734 0.816511C44.0649 0.816511 42.3564 0.81564 40.6479 0.826093C39.2085 0.834978 37.7698 0.851354 36.331 0.890204C33.196 0.974699 30.0335 1.15902 26.933 1.71511C23.7879 2.27887 20.8604 3.19943 18.0029 4.65047C15.194 6.07694 12.6239 7.94018 10.3953 10.1633C8.1671 12.386 6.29934 14.9494 4.86956 17.7508C3.41382 20.6028 2.49083 23.5246 1.92533 26.6638C1.36854 29.7554 1.18405 32.9089 1.09921 36.0352C1.06053 37.4704 1.04381 38.9057 1.03509 40.3413C1.02464 42.0458 0.937012 44.163 0.937012 45.8674L0.937534 65.0468L0.937012 80.0136L1.02551 99.6005C1.02551 101.307 1.02482 103.014 1.03509 104.72C1.04381 106.158 1.06053 107.595 1.09938 109.032C1.18405 112.164 1.36889 115.323 1.9262 118.42C2.49153 121.562 3.41434 124.486 4.86886 127.34C6.29882 130.146 8.16692 132.713 10.3953 134.939C12.6237 137.165 15.1932 139.031 18.0015 140.459C20.8607 141.913 23.7896 142.835 26.9366 143.4C30.0357 143.956 33.1972 144.141 36.331 144.225C37.7698 144.264 39.2087 144.281 40.648 144.289C42.3566 144.3 44.0649 144.299 45.7734 144.299L65.398 144.3H80.243L99.8296 144.299C101.535 144.299 103.24 144.3 104.945 144.289C106.382 144.281 107.818 144.264 109.254 144.225C112.383 144.141 115.539 143.956 118.634 143.399C121.773 142.835 124.694 141.913 127.547 140.46C130.35 139.031 132.915 137.166 135.139 134.939C137.363 132.714 139.227 130.147 140.654 127.341C142.107 124.486 143.028 121.56 143.593 118.416C144.148 115.321 144.333 112.163 144.417 109.032C144.456 107.595 144.473 106.158 144.481 104.72C144.492 103.014 144.491 101.307 144.491 99.6005C144.491 99.6005 144.49 80.3594 144.49 80.0136V65.0311C144.49 64.7757 144.491 45.4541 144.491 45.4541Z" fill="white"></path></mask><g mask="url(#mask0_54_296)"><rect x="0.414551" y="-6.74585" width="149.477" height="158.537" fill="#FF5C00"></rect><path d="M103.609 36.6948H53.5823C47.5327 36.6948 42.6284 41.5946 42.6284 47.6388C42.6284 53.683 47.5327 58.5828 53.5823 58.5828H103.609C109.659 58.5828 114.563 53.683 114.563 47.6388C114.563 41.5946 109.659 36.6948 103.609 36.6948Z" fill="white"></path><path d="M76.9348 65.1489H43.5916C37.5419 65.1489 32.6377 70.0487 32.6377 76.0929C32.6377 82.1371 37.5419 87.0369 43.5916 87.0369H76.9348C82.9845 87.0369 87.8888 82.1371 87.8888 76.0929C87.8888 70.0487 82.9845 65.1489 76.9348 65.1489Z" fill="white"></path><path d="M80.1608 104.571C80.1608 98.5272 75.2565 93.6274 69.2068 93.6274C63.1572 93.6274 58.2529 98.5272 58.2529 104.571C58.2529 110.616 63.1572 115.515 69.2068 115.515C75.2565 115.515 80.1608 110.616 80.1608 104.571Z" fill="white"></path></g></svg>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><title>Folo</title><path fill="#ff5c00" d="M5.382 0h13.236A5.37 5.37 0 0 1 24 5.383v13.235A5.37 5.37 0 0 1 18.618 24H5.382A5.37 5.37 0 0 1 0 18.618V5.383A5.37 5.37 0 0 1 5.382.001Z"/><path fill="#fff" d="M13.269 17.31a1.813 1.813 0 1 0-3.626.002 1.813 1.813 0 0 0 3.626-.002m-.535-6.527H7.213a1.813 1.813 0 1 0 0 3.624h5.521a1.813 1.813 0 1 0 0-3.624m4.417-4.712H8.87a1.813 1.813 0 1 0 0 3.625h8.283a1.813 1.813 0 1 0 0-3.624z"/></svg>
|
||||
|
Before Width: | Height: | Size: 3.2 KiB After Width: | Height: | Size: 495 B |
@@ -9,5 +9,5 @@ export const dayjsLocaleImportMap = {
|
||||
["ja"]: ["ja", () => import("dayjs/locale/ja")],
|
||||
["zh-TW"]: ["zh-tw", () => import("dayjs/locale/zh-tw")],
|
||||
}
|
||||
export const ns = ["common", "lang", "errors", "app", "settings", "shortcuts"] as const
|
||||
export const ns = ["common", "lang", "errors", "app", "settings", "shortcuts", "ai"] as const
|
||||
export const defaultNS = "app" as const
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
// DONT EDIT THIS FILE MANUALLY
|
||||
import ai_en from "@locales/ai/en.json"
|
||||
import ai_ja from "@locales/ai/ja.json"
|
||||
import en from "@locales/app/en.json"
|
||||
import app_ja from "@locales/app/ja.json"
|
||||
import app_zhCN from "@locales/app/zh-CN.json"
|
||||
@@ -38,6 +40,7 @@ export const defaultResources = {
|
||||
settings: settings_en,
|
||||
shortcuts: shortcuts_en,
|
||||
errors: errors_en,
|
||||
ai: ai_en,
|
||||
},
|
||||
"zh-CN": {
|
||||
app: app_zhCN,
|
||||
@@ -46,6 +49,7 @@ export const defaultResources = {
|
||||
settings: settings_zhCN,
|
||||
shortcuts: shortcuts_zhCN,
|
||||
errors: errors_zhCN,
|
||||
ai: ai_en, // Fallback to English until Chinese translation is available
|
||||
},
|
||||
|
||||
ja: {
|
||||
@@ -55,6 +59,7 @@ export const defaultResources = {
|
||||
settings: settings_ja,
|
||||
shortcuts: shortcuts_ja,
|
||||
errors: errors_ja,
|
||||
ai: ai_ja,
|
||||
},
|
||||
"zh-TW": {
|
||||
app: app_zhTW,
|
||||
@@ -63,6 +68,7 @@ export const defaultResources = {
|
||||
settings: settings_zhTW,
|
||||
shortcuts: shortcuts_zhTW,
|
||||
errors: errors_zhTW,
|
||||
ai: ai_en, // Fallback to English until Traditional Chinese translation is available
|
||||
},
|
||||
} satisfies Record<
|
||||
RendererSupportedLanguages,
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
// DONT EDIT THIS FILE MANUALLY
|
||||
import ai_en from "@locales/ai/en.json"
|
||||
import en from "@locales/app/en.json"
|
||||
import common_en from "@locales/common/en.json"
|
||||
import common_ja from "@locales/common/ja.json"
|
||||
@@ -29,6 +30,7 @@ export const defaultResources = {
|
||||
settings: settings_en,
|
||||
shortcuts: shortcuts_en,
|
||||
errors: errors_en,
|
||||
ai: ai_en,
|
||||
},
|
||||
"zh-CN": {
|
||||
lang: lang_zhCN,
|
||||
|
||||
@@ -62,19 +62,15 @@ const AppLayer = () => {
|
||||
}
|
||||
|
||||
const AppSkeleton = () => {
|
||||
const entryColWidth = useUISettingKey("entryColWidth")
|
||||
const feedColWidth = useUISettingKey("feedColWidth")
|
||||
return (
|
||||
<div className="flex size-full">
|
||||
<div
|
||||
className="h-full shrink-0"
|
||||
className="bg-sidebar h-full shrink-0"
|
||||
style={{
|
||||
width: `${feedColWidth}px`,
|
||||
}}
|
||||
/>
|
||||
<div className="bg-theme-background relative size-full grow">
|
||||
<div className="bg-border absolute inset-y-0 w-px" style={{ left: entryColWidth }} />
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
import { createAtomHooks } from "@follow/utils/jotai"
|
||||
import { getStorageNS } from "@follow/utils/ns"
|
||||
import { atomWithStorage } from "jotai/utils"
|
||||
|
||||
export const [, , useDebugFeatureValue, getDebugFeatureValue, ,] = createAtomHooks(
|
||||
atomWithStorage(getStorageNS("debug-feature"), {}),
|
||||
)
|
||||
@@ -1,11 +1,11 @@
|
||||
import type { ServerConfigs } from "@follow/models/types"
|
||||
import type { ExtractResponseData, GetStatusConfigsResponse } from "@follow-app/client-sdk"
|
||||
import PKG from "@pkg"
|
||||
import { atom } from "jotai"
|
||||
|
||||
import { createAtomHooks } from "~/lib/jotai"
|
||||
|
||||
export const [, , useServerConfigs, , getServerConfigs, setServerConfigs] = createAtomHooks(
|
||||
atom<Nullable<ServerConfigs>>(null),
|
||||
atom<Nullable<ExtractResponseData<GetStatusConfigsResponse>>>(null),
|
||||
)
|
||||
|
||||
export const useIsInMASReview = () => {
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
import { createSettingAtom } from "@follow/atoms/helper/setting.js"
|
||||
import { defaultAISettings } from "@follow/shared/settings/defaults"
|
||||
import type { AISettings } from "@follow/shared/settings/interface"
|
||||
import { jotaiStore } from "@follow/utils"
|
||||
import { atom, useAtomValue } from "jotai"
|
||||
|
||||
export const createDefaultSettings = (): AISettings => defaultAISettings
|
||||
|
||||
export const {
|
||||
useSettingKey: useAISettingKey,
|
||||
useSettingSelector: useAISettingSelector,
|
||||
setSetting: setAISetting,
|
||||
clearSettings: clearAISettings,
|
||||
initializeDefaultSettings: initializeDefaultAISettings,
|
||||
getSettings: getAISettings,
|
||||
useSettingValue: useAISettingValue,
|
||||
settingAtom: __aiSettingAtom,
|
||||
} = createSettingAtom("ai", createDefaultSettings)
|
||||
export const aiServerSyncWhiteListKeys = []
|
||||
// Local Setting for ai
|
||||
|
||||
const aiChatPinnedAtom = atom<boolean>(false)
|
||||
export const useAIChatPinned = () => useAtomValue(aiChatPinnedAtom)
|
||||
export const setAIChatPinned = (pinned: boolean) => {
|
||||
jotaiStore.set(aiChatPinnedAtom, pinned)
|
||||
}
|
||||
export const getAIChatPinned = () => jotaiStore.get(aiChatPinnedAtom)
|
||||
@@ -5,6 +5,7 @@ import { createElement, Suspense, useCallback } from "react"
|
||||
|
||||
import { getErrorFallback } from "../errors"
|
||||
import type { ErrorComponentType } from "../errors/enum"
|
||||
import PageErrorFallback from "../errors/PageError"
|
||||
|
||||
export interface AppErrorBoundaryProps extends PropsWithChildren {
|
||||
height?: number | string
|
||||
@@ -38,19 +39,15 @@ type ErrorFallbackProps = Parameters<FallbackRender>["0"]
|
||||
export type AppErrorFallbackProps = ErrorFallbackProps & {}
|
||||
const AppErrorBoundaryItem: FC<AppErrorBoundaryProps> = ({ errorType, children }) => {
|
||||
const fallbackRender = useCallback(
|
||||
(fallbackProps: ErrorFallbackProps) => (
|
||||
<Suspense>{createElement(getErrorFallback(errorType), fallbackProps)}</Suspense>
|
||||
),
|
||||
(fallbackProps: ErrorFallbackProps) => {
|
||||
const errorElement = getErrorFallback(errorType)
|
||||
if (!errorElement) {
|
||||
return <PageErrorFallback {...fallbackProps} />
|
||||
}
|
||||
return <Suspense>{createElement(getErrorFallback(errorType), fallbackProps)}</Suspense>
|
||||
},
|
||||
[errorType],
|
||||
)
|
||||
|
||||
const onError = useCallback((error: unknown, componentStack?: string) => {
|
||||
console.error("Uncaught error:", error, componentStack)
|
||||
}, [])
|
||||
|
||||
return (
|
||||
<ErrorBoundary fallback={fallbackRender} onError={onError}>
|
||||
{children}
|
||||
</ErrorBoundary>
|
||||
)
|
||||
return <ErrorBoundary fallback={fallbackRender}>{children}</ErrorBoundary>
|
||||
}
|
||||
|
||||
@@ -24,4 +24,5 @@ export const FocusablePresets = {
|
||||
},
|
||||
isTimeline: (v) => v.has(HotkeyScope.Timeline) && !v.has(HotkeyScope.EntryRender),
|
||||
isEntryRender: (v) => v.has(HotkeyScope.EntryRender),
|
||||
isAIChat: (v) => v.has(HotkeyScope.AIChat),
|
||||
} satisfies Record<string, (v: Set<string>) => boolean>
|
||||
|
||||
@@ -0,0 +1,198 @@
|
||||
import { Spring } from "@follow/components/constants/spring.js"
|
||||
import {
|
||||
Tooltip,
|
||||
TooltipContent,
|
||||
TooltipPortal,
|
||||
TooltipTrigger,
|
||||
} from "@follow/components/ui/tooltip/index.js"
|
||||
import { cn } from "@follow/utils/utils"
|
||||
import { cva } from "class-variance-authority"
|
||||
import { m } from "motion/react"
|
||||
import type { FC, ReactNode } from "react"
|
||||
|
||||
export interface GlassButtonProps {
|
||||
description?: string
|
||||
onClick: () => void
|
||||
className?: string
|
||||
children: ReactNode
|
||||
/**
|
||||
* Custom animation variants for hover and tap states
|
||||
*/
|
||||
hoverScale?: number
|
||||
tapScale?: number
|
||||
/**
|
||||
* Size variant
|
||||
*/
|
||||
size?: "sm" | "md" | "lg"
|
||||
/**
|
||||
* Color theme
|
||||
*/
|
||||
theme?: "light" | "dark" | "auto"
|
||||
/**
|
||||
* Visual variant
|
||||
*/
|
||||
variant?: "glass" | "flat"
|
||||
}
|
||||
|
||||
const glassButtonVariants = cva(
|
||||
[
|
||||
// Base styles - perfect 1:1 circle
|
||||
"pointer-events-auto relative flex items-center justify-center rounded-full",
|
||||
"transition-all duration-300 ease-out",
|
||||
],
|
||||
{
|
||||
variants: {
|
||||
size: {
|
||||
sm: "size-8 text-sm",
|
||||
md: "size-10 text-lg",
|
||||
lg: "size-12 text-xl",
|
||||
},
|
||||
theme: {
|
||||
light: ["text-gray-700 hover:text-gray-900"],
|
||||
dark: ["text-white hover:text-white"],
|
||||
auto: ["text-text hover:text-text-vibrant"],
|
||||
},
|
||||
variant: {
|
||||
glass: ["backdrop-blur-md border shadow-lg"],
|
||||
flat: ["border shadow-none"],
|
||||
},
|
||||
},
|
||||
compoundVariants: [
|
||||
// Glass variant themes
|
||||
{
|
||||
variant: "glass",
|
||||
theme: "light",
|
||||
className: [
|
||||
"bg-material-thin hover:bg-material-medium",
|
||||
"border-gray/30 hover:border-gray/40",
|
||||
"shadow-gray/30",
|
||||
],
|
||||
},
|
||||
{
|
||||
variant: "glass",
|
||||
theme: "dark",
|
||||
className: [
|
||||
"bg-material-ultra-thin hover:bg-material-thin",
|
||||
"border-gray/10 hover:border-gray/20",
|
||||
"shadow-black/25",
|
||||
],
|
||||
},
|
||||
{
|
||||
variant: "glass",
|
||||
theme: "auto",
|
||||
className: [
|
||||
"bg-material-thin hover:bg-material-medium",
|
||||
"border-gray/30 hover:border-gray/40",
|
||||
"shadow-gray/30",
|
||||
],
|
||||
},
|
||||
// Flat variant themes
|
||||
{
|
||||
variant: "flat",
|
||||
theme: "light",
|
||||
className: ["bg-white/80 hover:bg-white/90", "border-gray/20 hover:border-gray/30"],
|
||||
},
|
||||
{
|
||||
variant: "flat",
|
||||
theme: "dark",
|
||||
className: [
|
||||
"bg-fill-secondary hover:bg-fill-tertiary",
|
||||
"border-gray/20 hover:border-gray/30",
|
||||
],
|
||||
},
|
||||
{
|
||||
variant: "flat",
|
||||
theme: "auto",
|
||||
className: [
|
||||
"bg-white/80 hover:bg-white/90 dark:bg-fill-secondary dark:hover:bg-fill-tertiary",
|
||||
"border-gray/20 hover:border-gray/30",
|
||||
],
|
||||
},
|
||||
],
|
||||
defaultVariants: {
|
||||
size: "md",
|
||||
theme: "auto",
|
||||
variant: "glass",
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
const glassOverlayVariants = cva(
|
||||
"absolute inset-0 rounded-full bg-gradient-to-t opacity-0 transition-opacity duration-300 hover:opacity-100",
|
||||
{
|
||||
variants: {
|
||||
theme: {
|
||||
light: "from-material-opaque/10 to-material-opaque/30",
|
||||
dark: "from-material-opaque/5 to-material-opaque/20",
|
||||
auto: "from-material-opaque/10 to-material-opaque/30",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
theme: "auto",
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
const glassInnerShadowVariants = cva("absolute inset-0 rounded-full shadow-inner", {
|
||||
variants: {
|
||||
theme: {
|
||||
light: "shadow-gray/20",
|
||||
dark: "shadow-black/10",
|
||||
auto: "shadow-gray/20 dark:shadow-black/10",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
theme: "auto",
|
||||
},
|
||||
})
|
||||
|
||||
export const GlassButton: FC<GlassButtonProps> = ({
|
||||
description,
|
||||
onClick,
|
||||
className,
|
||||
children,
|
||||
hoverScale = 1.1,
|
||||
tapScale = 0.95,
|
||||
size = "md",
|
||||
theme = "auto",
|
||||
variant = "glass",
|
||||
}) => {
|
||||
return (
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<m.button
|
||||
type="button"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
onClick()
|
||||
}}
|
||||
className={cn(glassButtonVariants({ size, theme, variant }), className)}
|
||||
initial={{ scale: 1 }}
|
||||
whileHover={
|
||||
variant === "flat"
|
||||
? undefined
|
||||
: {
|
||||
scale: hoverScale,
|
||||
}
|
||||
}
|
||||
whileTap={{ scale: tapScale }}
|
||||
transition={Spring.presets.snappy}
|
||||
>
|
||||
{/* Glass effect overlay - only for glass variant */}
|
||||
{variant === "glass" && <div className={glassOverlayVariants({ theme })} />}
|
||||
|
||||
{/* Icon container */}
|
||||
<div className="center relative z-10 flex">{children}</div>
|
||||
|
||||
{/* Subtle inner shadow for depth - only for glass variant */}
|
||||
{variant === "glass" && <div className={glassInnerShadowVariants({ theme })} />}
|
||||
</m.button>
|
||||
</TooltipTrigger>
|
||||
{description && (
|
||||
<TooltipPortal>
|
||||
<TooltipContent>{description}</TooltipContent>
|
||||
</TooltipPortal>
|
||||
)}
|
||||
</Tooltip>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,191 @@
|
||||
import { cn } from "@follow/utils"
|
||||
import { memo, useCallback, useEffect, useRef, useState } from "react"
|
||||
|
||||
import { usePreviewMedia } from "~/components/ui/media/hooks"
|
||||
|
||||
interface MermaidDiagramProps {
|
||||
code: string
|
||||
className?: string
|
||||
|
||||
shouldRender?: boolean
|
||||
}
|
||||
|
||||
export const MermaidDiagram = memo<MermaidDiagramProps>(({ code, className, shouldRender }) => {
|
||||
const containerRef = useRef<HTMLDivElement>(null)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const [isLoading, setIsLoading] = useState(true)
|
||||
|
||||
const [imageUrl, setImageUrl] = useState<string>("")
|
||||
const previewMedia = usePreviewMedia()
|
||||
|
||||
const handleImagePreview = useCallback(() => {
|
||||
if (imageUrl) {
|
||||
previewMedia([{ url: imageUrl, type: "photo" }])
|
||||
}
|
||||
}, [imageUrl, previewMedia])
|
||||
|
||||
useEffect(() => {
|
||||
if (!shouldRender) return
|
||||
|
||||
let mounted = true
|
||||
|
||||
const renderDiagram = async () => {
|
||||
if (!code.trim()) return
|
||||
|
||||
try {
|
||||
setIsLoading(true)
|
||||
setError(null)
|
||||
|
||||
// Dynamic import to avoid loading Mermaid on the main thread
|
||||
const mermaid = await import("mermaid").then((m) => m.default)
|
||||
|
||||
// Initialize mermaid with better spacing configuration
|
||||
mermaid.initialize({
|
||||
startOnLoad: false,
|
||||
theme: "default",
|
||||
securityLevel: "loose", // Allow HTML in diagrams
|
||||
fontFamily: "system-ui, sans-serif",
|
||||
flowchart: {
|
||||
htmlLabels: true,
|
||||
curve: "basis",
|
||||
nodeSpacing: 50,
|
||||
rankSpacing: 80,
|
||||
padding: 20,
|
||||
},
|
||||
themeVariables: {
|
||||
primaryColor: "#f0f0f0",
|
||||
primaryTextColor: "#333",
|
||||
primaryBorderColor: "#ccc",
|
||||
lineColor: "#666",
|
||||
background: "#fff",
|
||||
secondaryColor: "#f9f9f9",
|
||||
tertiaryColor: "#fafafa",
|
||||
},
|
||||
})
|
||||
|
||||
// Generate unique ID for this diagram
|
||||
const id = `mermaid-${Date.now()}-${Math.random().toString(36).slice(2, 11)}`
|
||||
|
||||
if (!mounted) return
|
||||
|
||||
// Render the diagram
|
||||
const { svg } = await mermaid.render(id, code)
|
||||
|
||||
if (!mounted) return
|
||||
|
||||
if (containerRef.current) {
|
||||
containerRef.current.innerHTML = svg
|
||||
|
||||
// Apply theme-aware styling to the SVG with better spacing
|
||||
const svgElement = containerRef.current.querySelector("svg")
|
||||
if (svgElement) {
|
||||
svgElement.style.maxWidth = "100%"
|
||||
svgElement.style.height = "auto"
|
||||
svgElement.style.minHeight = "200px"
|
||||
svgElement.setAttribute("class", "dark:invert-[0.87] dark:hue-rotate-180")
|
||||
|
||||
// Add padding and spacing styles
|
||||
svgElement.style.padding = "20px"
|
||||
|
||||
// Adjust node spacing through CSS
|
||||
const style = document.createElement("style")
|
||||
style.textContent = `
|
||||
.node {
|
||||
margin: 10px !important;
|
||||
}
|
||||
.edgeLabel {
|
||||
background-color: rgba(255, 255, 255, 0.8) !important;
|
||||
padding: 4px 8px !important;
|
||||
border-radius: 4px !important;
|
||||
}
|
||||
.cluster rect {
|
||||
fill: rgba(0, 0, 0, 0.05) !important;
|
||||
stroke: rgba(0, 0, 0, 0.2) !important;
|
||||
stroke-width: 1px !important;
|
||||
}
|
||||
`
|
||||
svgElement.append(style)
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
const blob = new Blob([svg], { type: "image/svg+xml;charset=utf-8" })
|
||||
const url = URL.createObjectURL(blob)
|
||||
|
||||
if (mounted) {
|
||||
setImageUrl(url)
|
||||
}
|
||||
} catch (imgErr) {
|
||||
console.warn("Failed to convert SVG to image:", imgErr)
|
||||
}
|
||||
|
||||
setIsLoading(false)
|
||||
} catch (err) {
|
||||
console.error("Mermaid rendering error:", err)
|
||||
if (mounted) {
|
||||
setError(err instanceof Error ? err.message : "Failed to render diagram")
|
||||
setIsLoading(false)
|
||||
}
|
||||
}
|
||||
}
|
||||
renderDiagram()
|
||||
return () => {
|
||||
mounted = false
|
||||
}
|
||||
}, [code, shouldRender])
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<div
|
||||
className={`rounded-lg border border-red-200 bg-red-50 p-4 dark:border-red-800 dark:bg-red-900/20 ${className}`}
|
||||
>
|
||||
<div className="flex items-center gap-2 text-sm text-red-600 dark:text-red-400">
|
||||
<i className="i-mgc-warning-cute-re size-4" />
|
||||
<span>Failed to render Mermaid diagram</span>
|
||||
</div>
|
||||
<details className="mt-2">
|
||||
<summary className="cursor-pointer text-xs text-red-500 dark:text-red-400">
|
||||
Show error details
|
||||
</summary>
|
||||
<pre className="mt-1 whitespace-pre-wrap text-xs text-red-600 dark:text-red-300">
|
||||
{error}
|
||||
</pre>
|
||||
</details>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={cn("bg-background relative my-4 overflow-auto rounded-lg border", className)}>
|
||||
{!isLoading && !error && imageUrl && (
|
||||
<div className="flex items-center justify-between border-b px-3 py-2">
|
||||
<span className="text-text-secondary text-xs">Mermaid Diagram</span>
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleImagePreview}
|
||||
className="hover:bg-fill-secondary flex items-center gap-1 rounded px-2 py-1 text-xs transition-colors"
|
||||
title="Preview diagram"
|
||||
>
|
||||
<i className="i-mgc-pic-cute-fi size-3" />
|
||||
<span>Preview</span>
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex justify-center p-6">
|
||||
{isLoading && (
|
||||
<div className="text-text-secondary flex items-center gap-2 text-sm">
|
||||
<span>Rendering diagram...</span>
|
||||
</div>
|
||||
)}
|
||||
<div
|
||||
ref={containerRef}
|
||||
className="w-full text-center [&_svg]:mx-auto"
|
||||
style={{ display: isLoading ? "none" : "block" }}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
})
|
||||
|
||||
MermaidDiagram.displayName = "MermaidDiagram"
|
||||
@@ -0,0 +1 @@
|
||||
export { MermaidDiagram } from "./MermaidDiagram"
|
||||
@@ -154,9 +154,12 @@ const DropdownMenuItem = ({
|
||||
{/* Justify Fill */}
|
||||
{!!icon && <span className="ml-1.5 size-4" />}
|
||||
{!!shortcut && (
|
||||
<Kbd wrapButton={false} className="ml-auto">
|
||||
{shortcut}
|
||||
</Kbd>
|
||||
<>
|
||||
<span className="ml-4" />
|
||||
<Kbd wrapButton={false} className="ml-auto">
|
||||
{shortcut}
|
||||
</Kbd>
|
||||
</>
|
||||
)}
|
||||
</DropdownMenuPrimitive.Item>
|
||||
)
|
||||
|
||||
@@ -0,0 +1,197 @@
|
||||
import { useReplaceGlobalFocusableScope } from "@follow/components/common/Focusable/hooks.js"
|
||||
import { KbdCombined } from "@follow/components/ui/kbd/Kbd.js"
|
||||
import { Tooltip, TooltipContent, TooltipTrigger } from "@follow/components/ui/tooltip/index.js"
|
||||
import { sortShortcutKeys } from "@follow/utils/utils"
|
||||
import type { FC, RefObject, SVGProps } from "react"
|
||||
import { useEffect, useRef, useState } from "react"
|
||||
import { useTranslation } from "react-i18next"
|
||||
import { useOnClickOutside } from "usehooks-ts"
|
||||
|
||||
import { HotkeyScope } from "~/constants"
|
||||
|
||||
export interface KeyRecorderProps {
|
||||
onChange: (keys: string[] | null) => void
|
||||
onBlur: () => void
|
||||
}
|
||||
|
||||
export const KeyRecorder: FC<KeyRecorderProps> = ({ onChange, onBlur }) => {
|
||||
const { t } = useTranslation("shortcuts")
|
||||
const { currentKeys } = useShortcutRecorder()
|
||||
const setGlobalScope = useReplaceGlobalFocusableScope()
|
||||
|
||||
const ref = useRef<HTMLDivElement>(null)
|
||||
useEffect(() => {
|
||||
const { rollback } = setGlobalScope(HotkeyScope.Recording)
|
||||
if (ref.current) {
|
||||
ref.current.focus()
|
||||
}
|
||||
return () => {
|
||||
rollback()
|
||||
}
|
||||
}, [setGlobalScope])
|
||||
useOnClickOutside(ref as RefObject<HTMLElement>, () => {
|
||||
if (currentKeys.length > 0) {
|
||||
onChange(currentKeys)
|
||||
}
|
||||
onBlur()
|
||||
})
|
||||
return (
|
||||
<div
|
||||
className="text-text-secondary relative flex size-full items-center justify-center px-1 text-xs"
|
||||
tabIndex={-1}
|
||||
role="textbox"
|
||||
ref={ref}
|
||||
>
|
||||
{currentKeys.length > 0 ? (
|
||||
<div className="pr-4">
|
||||
<KbdCombined kbdProps={{ wrapButton: false }} joint={false}>
|
||||
{currentKeys.join("+")}
|
||||
</KbdCombined>
|
||||
</div>
|
||||
) : (
|
||||
<span className="text-text-secondary pr-4">{t("settings.shortcuts.press_to_record")}</span>
|
||||
)}
|
||||
<Tooltip delayDuration={0}>
|
||||
<TooltipTrigger asChild>
|
||||
<button
|
||||
type="button"
|
||||
className="hover:text-text absolute inset-y-0 -right-1 z-[1] flex items-center justify-center px-1"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
if (currentKeys.length === 0) {
|
||||
onChange(null)
|
||||
} else {
|
||||
onBlur()
|
||||
}
|
||||
}}
|
||||
>
|
||||
{currentKeys.length > 0 ? (
|
||||
<FamiconsArrowUndoCircle className="size-4" />
|
||||
) : (
|
||||
<i className="i-mingcute-close-circle-fill size-4" />
|
||||
)}
|
||||
</button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>
|
||||
{currentKeys.length > 0 ? t("settings.shortcuts.undo") : t("settings.shortcuts.reset")}
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function FamiconsArrowUndoCircle(props: SVGProps<SVGSVGElement>) {
|
||||
return (
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
width="1em"
|
||||
height="1em"
|
||||
viewBox="0 0 512 512"
|
||||
{...props}
|
||||
>
|
||||
{/* Icon from Famicons by Family - https://github.com/familyjs/famicons/blob/main/LICENSE */}
|
||||
<path
|
||||
fill="currentColor"
|
||||
d="M256 48C141.13 48 48 141.13 48 256s93.13 208 208 208s208-93.13 208-208S370.87 48 256 48m97.67 281.1c-24.07-25.21-51.51-38.68-108.58-38.68v37.32a8.32 8.32 0 0 1-14.05 6L146.58 254a8.2 8.2 0 0 1 0-11.94L231 162.29a8.32 8.32 0 0 1 14.05 6v37.32c88.73 0 117.42 55.64 122.87 117.09c.73 7.72-8.85 12.05-14.25 6.4"
|
||||
/>
|
||||
</svg>
|
||||
)
|
||||
}
|
||||
|
||||
const MODIFIER_KEYS_MAP = {
|
||||
Control: "Control",
|
||||
Alt: "Alt",
|
||||
Shift: "Shift",
|
||||
Meta: "Meta",
|
||||
} as const
|
||||
|
||||
const MODIFIER_KEYS_SET = new Set<string>(Object.values(MODIFIER_KEYS_MAP))
|
||||
|
||||
const F_KEY_REGEX = /^F(?:[1-9]|1[0-2])$/
|
||||
|
||||
const useShortcutRecorder = () => {
|
||||
const [currentKeys, setCurrentKeys] = useState<string[]>([])
|
||||
|
||||
useEffect(() => {
|
||||
const handleKeyDown = (event: KeyboardEvent) => {
|
||||
event.preventDefault()
|
||||
event.stopPropagation()
|
||||
event.stopImmediatePropagation()
|
||||
|
||||
const { altKey, ctrlKey, metaKey, shiftKey, key: eventKey } = event
|
||||
|
||||
let mainKeyPressed = eventKey
|
||||
|
||||
if (mainKeyPressed.length === 1 && mainKeyPressed >= "a" && mainKeyPressed <= "z") {
|
||||
mainKeyPressed = mainKeyPressed.toUpperCase()
|
||||
} else if (mainKeyPressed === " ") {
|
||||
mainKeyPressed = "Space"
|
||||
}
|
||||
|
||||
const pressedKeysSet = new Set<string>()
|
||||
|
||||
if (shiftKey) pressedKeysSet.add(MODIFIER_KEYS_MAP.Shift)
|
||||
if (metaKey) pressedKeysSet.add(MODIFIER_KEYS_MAP.Meta)
|
||||
if (ctrlKey) pressedKeysSet.add(MODIFIER_KEYS_MAP.Control)
|
||||
if (altKey) pressedKeysSet.add(MODIFIER_KEYS_MAP.Alt)
|
||||
|
||||
// If mainKeyPressed (from event.key) is not a modifier key, add it as the main key.
|
||||
// If mainKeyPressed is a modifier key (e.g., user only pressed Shift key, event.key is "Shift"),
|
||||
// it has already been handled and added to pressedKeysSet by the above if (shiftKey) logic,
|
||||
// so we don't need to add it again here.
|
||||
if (!MODIFIER_KEYS_SET.has(mainKeyPressed)) {
|
||||
pressedKeysSet.add(mainKeyPressed)
|
||||
}
|
||||
|
||||
const currentCombination = Array.from(pressedKeysSet)
|
||||
|
||||
// --- Start validation rules ---
|
||||
const nonModifierKeysInCombo = currentCombination.filter((key) => !MODIFIER_KEYS_SET.has(key))
|
||||
|
||||
// Rule 2: Pure modifier key combinations are not allowed (e.g., just Shift, or Ctrl+Alt)
|
||||
if (nonModifierKeysInCombo.length === 0) {
|
||||
// When only modifier keys are pressed, currentCombination will still contain these modifiers.
|
||||
// For example, pressing only Shift, currentCombination is ["Shift"]
|
||||
// Here we don't update the state, indicating this is an invalid recording.
|
||||
// You can provide temporary UI feedback here, e.g.: "Recording: Shift"
|
||||
console.info(
|
||||
"Recording (invalid - modifiers only):",
|
||||
sortShortcutKeys(currentCombination).join(" + "),
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
// Typically shortcuts have only one "main" function key (e.g., Ctrl+A, Shift+F1)
|
||||
// If multiple non-modifier keys are detected (e.g., theoretically user pressing A and B simultaneously),
|
||||
// this is usually not a standard shortcut recording scenario
|
||||
// This check is mainly for code robustness, as `keydown` events typically focus on one main key at a time.
|
||||
if (nonModifierKeysInCombo.length > 1) {
|
||||
console.warn(
|
||||
"Recording (invalid - multiple main keys, this shouldn't normally happen):",
|
||||
sortShortcutKeys(currentCombination).join(" + "),
|
||||
)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
const primaryKey = nonModifierKeysInCombo[0]
|
||||
|
||||
// Rule 3: Fn keys (F1-F12) can be single keys or modifier+Fn key combinations
|
||||
if (F_KEY_REGEX.test(primaryKey ?? "")) {
|
||||
setCurrentKeys(sortShortcutKeys(currentCombination))
|
||||
return
|
||||
}
|
||||
|
||||
// Rule 1: Single "ASCII" main keys are allowed (here referring to all non-modifier, non-F keys)
|
||||
// Examples: A, 1, Space, Enter, ArrowUp, etc. They can be used alone or with modifiers.
|
||||
// For these keys, as long as they're not pure modifier combinations, they're considered valid.
|
||||
setCurrentKeys(sortShortcutKeys(currentCombination))
|
||||
}
|
||||
|
||||
window.addEventListener("keydown", handleKeyDown)
|
||||
return () => {
|
||||
window.removeEventListener("keydown", handleKeyDown)
|
||||
}
|
||||
}, [setCurrentKeys])
|
||||
return { currentKeys }
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
export * from "./KeyRecorder"
|
||||
@@ -1,3 +1,4 @@
|
||||
import { Button } from "@follow/components/ui/button/index.js"
|
||||
import { MagneticHoverEffect } from "@follow/components/ui/effect/MagneticHoverEffect.js"
|
||||
import type { LinkProps } from "@follow/components/ui/link/LinkWithTooltip.js"
|
||||
import {
|
||||
@@ -7,6 +8,7 @@ import {
|
||||
TooltipTrigger,
|
||||
} from "@follow/components/ui/tooltip/index.jsx"
|
||||
import { useCorrectZIndex } from "@follow/components/ui/z-index/ctx.js"
|
||||
import { cn, stopPropagation } from "@follow/utils"
|
||||
import { use, useCallback } from "react"
|
||||
import { useTranslation } from "react-i18next"
|
||||
import { toast } from "sonner"
|
||||
@@ -15,7 +17,7 @@ import { copyToClipboard } from "~/lib/clipboard"
|
||||
|
||||
import { MarkdownRenderActionContext } from "../context"
|
||||
|
||||
export const MarkdownLink = (props: LinkProps) => {
|
||||
export const MarkdownLink: Component<LinkProps> = (props) => {
|
||||
const { transformUrl, isAudio, ensureAndRenderTimeStamp } = use(MarkdownRenderActionContext)
|
||||
const { t } = useTranslation()
|
||||
|
||||
@@ -50,11 +52,12 @@ export const MarkdownLink = (props: LinkProps) => {
|
||||
<MagneticHoverEffect
|
||||
as="a"
|
||||
draggable="false"
|
||||
className="text-text font-semibold no-underline"
|
||||
className={cn("text-text font-semibold no-underline", props.className)}
|
||||
href={populatedFullHref}
|
||||
title={props.title}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
onClick={stopPropagation}
|
||||
>
|
||||
{props.children}
|
||||
|
||||
@@ -66,14 +69,23 @@ export const MarkdownLink = (props: LinkProps) => {
|
||||
{!!populatedFullHref && (
|
||||
<TooltipPortal>
|
||||
<TooltipContent align="start" className="break-all" style={{ zIndex }} side="bottom">
|
||||
<span>{populatedFullHref}</span>
|
||||
<button
|
||||
type="button"
|
||||
className="text-accent ml-2 cursor-pointer"
|
||||
onClick={handleCopyLink}
|
||||
<a
|
||||
className="follow-link--underline"
|
||||
href={populatedFullHref}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
>
|
||||
{t("share.copy_link")}
|
||||
</button>
|
||||
{populatedFullHref}
|
||||
</a>
|
||||
|
||||
<Button
|
||||
onClick={handleCopyLink}
|
||||
buttonClassName="p-1 cursor-link"
|
||||
variant={"ghost"}
|
||||
aria-label={t("share.copy_link")}
|
||||
>
|
||||
<i className="i-mgc-copy-2-cute-re ml-1 size-3" />
|
||||
</Button>
|
||||
</TooltipContent>
|
||||
</TooltipPortal>
|
||||
)}
|
||||
|
||||
@@ -1,11 +1,5 @@
|
||||
import { Spring } from "@follow/components/constants/spring.js"
|
||||
import { MotionButtonBase } from "@follow/components/ui/button/index.js"
|
||||
import {
|
||||
Tooltip,
|
||||
TooltipContent,
|
||||
TooltipPortal,
|
||||
TooltipTrigger,
|
||||
} from "@follow/components/ui/tooltip/index.js"
|
||||
import { IN_ELECTRON } from "@follow/shared/constants"
|
||||
import type { MediaModel } from "@follow/shared/hono"
|
||||
import { stopPropagation } from "@follow/utils/dom"
|
||||
@@ -21,6 +15,7 @@ import type { ReactZoomPanPinchRef, ReactZoomPanPinchState } from "react-zoom-pa
|
||||
import { TransformComponent, TransformWrapper } from "react-zoom-pan-pinch"
|
||||
|
||||
import { m } from "~/components/common/Motion"
|
||||
import { GlassButton } from "~/components/ui/button/GlassButton"
|
||||
import { COPY_MAP } from "~/constants"
|
||||
import { ipcServices } from "~/lib/client"
|
||||
import { replaceImgUrlIfNeed } from "~/lib/img-proxy"
|
||||
@@ -193,6 +188,7 @@ const Wrapper: FC<{
|
||||
)
|
||||
}
|
||||
|
||||
const GLASS_BUTTON_CLASS = tw`group-hover/left:opacity-100 opacity-0`
|
||||
const HeaderActions: FC<{
|
||||
src: string
|
||||
}> = ({ src }) => {
|
||||
@@ -201,89 +197,42 @@ const HeaderActions: FC<{
|
||||
const { dismiss } = useCurrentModal()
|
||||
return (
|
||||
<div className="pointer-events-none absolute inset-x-0 top-0 z-[100] flex h-16 items-center justify-end gap-2 px-3">
|
||||
<HeaderButton description={t(COPY_MAP.OpenInBrowser())} onClick={() => window.open(src)}>
|
||||
<GlassButton
|
||||
theme="dark"
|
||||
className={GLASS_BUTTON_CLASS}
|
||||
description={t(COPY_MAP.OpenInBrowser())}
|
||||
onClick={() => window.open(src)}
|
||||
>
|
||||
<i className="i-mgc-external-link-cute-re" />
|
||||
</HeaderButton>
|
||||
</GlassButton>
|
||||
{IN_ELECTRON && (
|
||||
<HeaderButton
|
||||
<GlassButton
|
||||
theme="dark"
|
||||
className={GLASS_BUTTON_CLASS}
|
||||
description={t("common:words.download")}
|
||||
onClick={() => {
|
||||
ipcServices?.app.download(src)
|
||||
}}
|
||||
>
|
||||
<i className="i-mgc-download-2-cute-re" />
|
||||
</HeaderButton>
|
||||
</GlassButton>
|
||||
)}
|
||||
|
||||
<HeaderButton
|
||||
<GlassButton
|
||||
theme="dark"
|
||||
description={t("common:words.close")}
|
||||
className="ml-3 !border-red-500/20 !bg-red-600/30 !opacity-100 hover:!bg-red-600/50"
|
||||
className={cn(
|
||||
GLASS_BUTTON_CLASS,
|
||||
"ml-3 !border-red-500/20 !bg-red-600/30 !opacity-100 hover:!bg-red-600/50",
|
||||
)}
|
||||
onClick={dismiss}
|
||||
>
|
||||
<i className="i-mgc-close-cute-re" />
|
||||
</HeaderButton>
|
||||
</GlassButton>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const HeaderButton: FC<{
|
||||
description?: string
|
||||
onClick: () => void
|
||||
className?: string
|
||||
children: React.ReactNode
|
||||
}> = ({ description, onClick, className, children }) => {
|
||||
return (
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<m.button
|
||||
type="button"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
onClick()
|
||||
}}
|
||||
className={cn(
|
||||
// Base styles with modern glass morphism - perfect 1:1 circle
|
||||
"pointer-events-auto relative flex size-10 items-center justify-center rounded-full",
|
||||
"bg-black/20 text-white backdrop-blur-md",
|
||||
// Border and shadow for depth
|
||||
"border border-white/10 shadow-lg shadow-black/25",
|
||||
// Opacity and transition
|
||||
"opacity-0 transition-all duration-300 ease-out group-hover/left:opacity-100",
|
||||
// Text size
|
||||
"text-lg",
|
||||
className,
|
||||
)}
|
||||
initial={{ scale: 1 }}
|
||||
whileHover={{
|
||||
scale: 1.1,
|
||||
backgroundColor: "rgba(255, 255, 255, 0.15)",
|
||||
borderColor: "rgba(255, 255, 255, 0.2)",
|
||||
}}
|
||||
whileTap={{ scale: 0.95 }}
|
||||
transition={{
|
||||
type: "spring",
|
||||
stiffness: 400,
|
||||
damping: 30,
|
||||
}}
|
||||
>
|
||||
{/* Glass effect overlay */}
|
||||
<div className="absolute inset-0 rounded-full bg-gradient-to-t from-white/5 to-white/20 opacity-0 transition-opacity duration-300 hover:opacity-100" />
|
||||
|
||||
{/* Icon container */}
|
||||
<div className="center relative z-10 flex">{children}</div>
|
||||
|
||||
{/* Subtle inner shadow for depth */}
|
||||
<div className="absolute inset-0 rounded-full shadow-inner shadow-black/10" />
|
||||
</m.button>
|
||||
</TooltipTrigger>
|
||||
{description && (
|
||||
<TooltipPortal>
|
||||
<TooltipContent>{description}</TooltipContent>
|
||||
</TooltipPortal>
|
||||
)}
|
||||
</Tooltip>
|
||||
)
|
||||
}
|
||||
export interface PreviewMediaProps extends MediaModel {
|
||||
fallbackUrl?: string
|
||||
}
|
||||
@@ -332,7 +281,7 @@ export const PreviewMediaContent: FC<{
|
||||
const { type } = media[0]!
|
||||
const isVideo = type === "video"
|
||||
return (
|
||||
<Wrapper src={src} onZoomChange={onZoomChange} canDragClose>
|
||||
<Wrapper src={src} onZoomChange={onZoomChange} canDragClose={!isVideo}>
|
||||
{(handleZoomChange) => [
|
||||
<Fragment key={src}>
|
||||
{isVideo ? (
|
||||
@@ -396,25 +345,25 @@ export const PreviewMediaContent: FC<{
|
||||
</div>
|
||||
|
||||
{currentSlideIndex > 0 && (
|
||||
<HeaderButton
|
||||
<GlassButton
|
||||
className={`absolute left-2 top-1/2 z-[100] flex size-8 -translate-y-1/2 items-center justify-center rounded-full text-white opacity-0 backdrop-blur-sm duration-200 hover:bg-black/40 group-hover:opacity-100 lg:left-4 lg:size-10`}
|
||||
onClick={() => {
|
||||
emblaApi?.scrollPrev()
|
||||
}}
|
||||
>
|
||||
<i className={`i-mingcute-left-line text-lg lg:text-xl`} />
|
||||
</HeaderButton>
|
||||
</GlassButton>
|
||||
)}
|
||||
|
||||
{currentSlideIndex < media.length - 1 && (
|
||||
<HeaderButton
|
||||
<GlassButton
|
||||
className={`absolute right-2 top-1/2 z-[100] flex size-8 -translate-y-1/2 items-center justify-center rounded-full text-white opacity-0 backdrop-blur-sm duration-200 hover:bg-black/40 group-hover:opacity-100 lg:right-4 lg:size-10`}
|
||||
onClick={() => {
|
||||
emblaApi?.scrollNext()
|
||||
}}
|
||||
>
|
||||
<i className={`i-mingcute-right-line text-lg lg:text-xl`} />
|
||||
</HeaderButton>
|
||||
</GlassButton>
|
||||
)}
|
||||
</div>,
|
||||
children,
|
||||
|
||||
@@ -27,7 +27,7 @@ export function SwipeMedia({
|
||||
proxySize?: {
|
||||
width: number
|
||||
height: number
|
||||
}
|
||||
} | null
|
||||
}) {
|
||||
const uniqMedia = media ? uniqBy(media, "url") : []
|
||||
|
||||
@@ -60,19 +60,21 @@ export function SwipeMedia({
|
||||
{uniqMedia?.slice(0, 5).map((med, i) => (
|
||||
<div className="mr-2 size-full flex-none" key={med.url}>
|
||||
<Media
|
||||
className={cn(imgClassName, "size-full rounded-none")}
|
||||
mediaContainerClassName="object-cover"
|
||||
className="size-full rounded-none"
|
||||
mediaContainerClassName={cn("object-cover", imgClassName)}
|
||||
alt="cover"
|
||||
cacheDimensions={med.type === "photo"}
|
||||
src={med.url}
|
||||
type={med.type}
|
||||
previewImageUrl={med.preview_image_url}
|
||||
loading="lazy"
|
||||
proxy={proxySize}
|
||||
proxy={proxySize || undefined}
|
||||
blurhash={med.blurhash}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
onPreview?.(uniqMedia, i)
|
||||
if (onPreview) {
|
||||
e.stopPropagation()
|
||||
onPreview(uniqMedia, i)
|
||||
}
|
||||
}}
|
||||
showFallback={true}
|
||||
fitContent
|
||||
|
||||
@@ -1,32 +0,0 @@
|
||||
import { Tooltip, TooltipContent, TooltipTrigger } from "@follow/components/ui/tooltip/index.js"
|
||||
import { cn } from "@follow/utils/utils"
|
||||
import type { ReactNode } from "react"
|
||||
|
||||
export const PeekModalBaseButton = ({
|
||||
onClick,
|
||||
className,
|
||||
label,
|
||||
icon,
|
||||
}: {
|
||||
onClick: () => void
|
||||
className?: string
|
||||
label: string
|
||||
icon: ReactNode
|
||||
}) => {
|
||||
return (
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
type="button"
|
||||
aria-label={label}
|
||||
className={cn(
|
||||
"no-drag-region center bg-background ring-border flex size-8 rounded-full p-1 shadow-sm ring-1 empty:hidden",
|
||||
className,
|
||||
)}
|
||||
onClick={onClick}
|
||||
>
|
||||
{icon}
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>{label}</TooltipContent>
|
||||
</Tooltip>
|
||||
)
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import { cn } from "@follow/utils"
|
||||
import { useTranslation } from "react-i18next"
|
||||
|
||||
import { PeekModalBaseButton } from "./base"
|
||||
import { GlassButton } from "~/components/ui/button/GlassButton"
|
||||
|
||||
export const FixedModalCloseButton: Component<{
|
||||
onClick: () => void
|
||||
@@ -8,11 +9,17 @@ export const FixedModalCloseButton: Component<{
|
||||
}> = ({ onClick, className }) => {
|
||||
const { t } = useTranslation("common")
|
||||
return (
|
||||
<PeekModalBaseButton
|
||||
<GlassButton
|
||||
onClick={onClick}
|
||||
className={className}
|
||||
label={t("words.close")}
|
||||
icon={<i className="i-mgc-close-cute-re text-lg" />}
|
||||
/>
|
||||
className={cn(
|
||||
"!border-red-500/20 !bg-red-600/30 !opacity-100 hover:!bg-red-600/50",
|
||||
className,
|
||||
)}
|
||||
description={t("words.close")}
|
||||
size="md"
|
||||
variant="flat"
|
||||
>
|
||||
<i className="i-mgc-close-cute-re text-lg" />
|
||||
</GlassButton>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -5,8 +5,8 @@ import { useState } from "react"
|
||||
import { useTranslation } from "react-i18next"
|
||||
|
||||
import { m } from "~/components/common/Motion"
|
||||
import { GlassButton } from "~/components/ui/button/GlassButton"
|
||||
|
||||
import { PeekModalBaseButton } from "../components/base"
|
||||
import { FixedModalCloseButton } from "../components/close"
|
||||
import { useCurrentModal, useModalStack } from "../stacked/hooks"
|
||||
import { InPeekModal } from "./InPeekModal"
|
||||
@@ -49,23 +49,29 @@ export const PeekModal = (
|
||||
className="safe-inset-top-4 fixed right-4 flex items-center gap-4"
|
||||
>
|
||||
{props.rightActions?.map((action) => (
|
||||
<PeekModalBaseButton
|
||||
<GlassButton
|
||||
key={action.label}
|
||||
onClick={action.onClick}
|
||||
label={action.label}
|
||||
icon={action.icon}
|
||||
/>
|
||||
description={action.label}
|
||||
size="md"
|
||||
variant="flat"
|
||||
>
|
||||
{action.icon}
|
||||
</GlassButton>
|
||||
))}
|
||||
{!!to && (
|
||||
<PeekModalBaseButton
|
||||
<GlassButton
|
||||
onClick={() => {
|
||||
dismissAll()
|
||||
|
||||
getStableRouterNavigate()?.(to)
|
||||
}}
|
||||
label={t("words.expand")}
|
||||
icon={<i className="i-mgc-fullscreen-2-cute-re text-lg" />}
|
||||
/>
|
||||
description={t("words.expand")}
|
||||
size="md"
|
||||
variant="flat"
|
||||
>
|
||||
<i className="i-mgc-fullscreen-2-cute-re text-lg" />
|
||||
</GlassButton>
|
||||
)}
|
||||
<FixedModalCloseButton onClick={dismiss} />
|
||||
</m.div>
|
||||
|
||||
@@ -144,14 +144,14 @@ export const useDialog = (): DialogInstance => {
|
||||
confirmClassName: "",
|
||||
},
|
||||
warning: {
|
||||
icon: <i className="i-mingcute-warning-fill size-5 text-yellow-500" />,
|
||||
icon: <i className="i-mingcute-warning-fill text-yellow size-5" />,
|
||||
confirmVariant: "primary" as const,
|
||||
confirmClassName: "bg-yellow-600 hover:bg-yellow-700",
|
||||
confirmClassName: "bg-yellow-500",
|
||||
},
|
||||
danger: {
|
||||
icon: <i className="i-mingcute-warning-fill size-5 text-red-500" />,
|
||||
icon: <i className="i-mingcute-warning-fill text-red size-5" />,
|
||||
confirmVariant: "primary" as const,
|
||||
confirmClassName: "bg-red-600 hover:bg-red-700",
|
||||
confirmClassName: "bg-red-500",
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
@@ -11,6 +11,7 @@ export enum HotkeyScope {
|
||||
EntryRender = "entry-render",
|
||||
SubscriptionList = "subscription-list",
|
||||
SubLayer = "sub-layer",
|
||||
AIChat = "ai-chat",
|
||||
}
|
||||
|
||||
export const FloatingLayerScope = [
|
||||
|
||||
@@ -1,2 +1,4 @@
|
||||
export const ElECTRON_CUSTOM_TITLEBAR_HEIGHT = 30
|
||||
// export const ELECTRON_WINDOWS_RADIUS = 12
|
||||
|
||||
export const readableContentMaxWidthClassName = "max-w-[clamp(45ch,60vw,65ch)]"
|
||||
|
||||
@@ -21,6 +21,7 @@ import {
|
||||
setReadabilityStatus,
|
||||
useEntryIsInReadability,
|
||||
} from "~/atoms/readability"
|
||||
import { useAIChatPinned } from "~/atoms/settings/ai"
|
||||
import { useShowSourceContent } from "~/atoms/source-content"
|
||||
import { ipcServices } from "~/lib/client"
|
||||
import { COMMAND_ID } from "~/modules/command/commands/id"
|
||||
@@ -29,6 +30,9 @@ import { useCommandShortcuts } from "~/modules/command/hooks/use-command-binding
|
||||
import type { FollowCommandId } from "~/modules/command/types"
|
||||
import { useToolbarOrderMap } from "~/modules/customize-toolbar/hooks"
|
||||
|
||||
import { useFeature } from "./useFeature"
|
||||
import { useRouteParams } from "./useRouteParams"
|
||||
|
||||
export const enableEntryReadability = async ({ id, url }: { id: string; url: string }) => {
|
||||
const status = getReadabilityStatus()[id]
|
||||
const isTurnOn = status !== ReadabilityStatus.INITIAL && !!status
|
||||
@@ -124,6 +128,7 @@ const entrySelector = (state: EntryModel) => {
|
||||
const { summary, translation, readability } = state.settings || {}
|
||||
|
||||
const media = state.media || []
|
||||
const attachments = state.attachments || []
|
||||
const images = media.filter((a) => a.type === "photo")
|
||||
const imagesLength = images.length
|
||||
|
||||
@@ -139,9 +144,21 @@ const entrySelector = (state: EntryModel) => {
|
||||
hasContent,
|
||||
doesContentContainsHTMLTags,
|
||||
imagesLength,
|
||||
hasBitTorrent: attachments.some((a) => a.mime_type === "application/x-bittorrent"),
|
||||
}
|
||||
}
|
||||
|
||||
export const HIDE_ACTIONS_IN_ENTRY_CONTEXT_MENU = [
|
||||
COMMAND_ID.entry.viewSourceContent,
|
||||
COMMAND_ID.entry.toggleAISummary,
|
||||
COMMAND_ID.entry.toggleAITranslation,
|
||||
COMMAND_ID.global.toggleAIChatPinned,
|
||||
COMMAND_ID.settings.customizeToolbar,
|
||||
COMMAND_ID.entry.readability,
|
||||
COMMAND_ID.entry.exportAsPDF,
|
||||
// Copy
|
||||
COMMAND_ID.entry.copyTitle,
|
||||
COMMAND_ID.entry.copyLink,
|
||||
]
|
||||
export const useEntryActions = ({
|
||||
entryId,
|
||||
view,
|
||||
@@ -152,6 +169,7 @@ export const useEntryActions = ({
|
||||
compact?: boolean
|
||||
}) => {
|
||||
const entry = useEntry(entryId, entrySelector)
|
||||
const { isCollection } = useRouteParams()
|
||||
const isInCollection = useIsEntryStarred(entryId)
|
||||
const isEntryInReadability = useEntryIsInReadability(entryId)
|
||||
|
||||
@@ -170,7 +188,8 @@ export const useEntryActions = ({
|
||||
const isShowAISummaryOnce = useShowAISummaryOnce()
|
||||
const isShowAITranslationAuto = useShowAITranslationAuto(!!entry?.translation)
|
||||
const isShowAITranslationOnce = useShowAITranslationOnce()
|
||||
|
||||
const isShowAIChatPinned = useAIChatPinned()
|
||||
const aiEnabled = useFeature("ai")
|
||||
const runCmdFn = useRunCommandFn()
|
||||
const hasEntry = !!entry
|
||||
|
||||
@@ -222,6 +241,12 @@ export const useEntryActions = ({
|
||||
onClick: runCmdFn(COMMAND_ID.integration.saveToZotero, [{ entryId }]),
|
||||
entryId,
|
||||
}),
|
||||
new EntryActionMenuItem({
|
||||
id: COMMAND_ID.integration.saveToQBittorrent,
|
||||
onClick: runCmdFn(COMMAND_ID.integration.saveToQBittorrent, [{ entryId }]),
|
||||
hide: !IN_ELECTRON || !entry.hasBitTorrent,
|
||||
entryId,
|
||||
}),
|
||||
new EntryActionMenuItem({
|
||||
id: COMMAND_ID.entry.tip,
|
||||
onClick: runCmdFn(COMMAND_ID.entry.tip, [
|
||||
@@ -312,13 +337,13 @@ export const useEntryActions = ({
|
||||
new EntryActionMenuItem({
|
||||
id: COMMAND_ID.entry.readAbove,
|
||||
onClick: runCmdFn(COMMAND_ID.entry.readAbove, [{ publishedAt: entry.publishedAt }]),
|
||||
hide: !!isInCollection,
|
||||
hide: !!isCollection,
|
||||
entryId,
|
||||
}),
|
||||
new EntryActionMenuItem({
|
||||
id: COMMAND_ID.entry.read,
|
||||
onClick: runCmdFn(COMMAND_ID.entry.read, [{ entryId }]),
|
||||
hide: !!isInCollection,
|
||||
hide: !!isCollection,
|
||||
active: !!entry.read,
|
||||
shortcut: shortcuts[COMMAND_ID.entry.read],
|
||||
entryId,
|
||||
@@ -326,7 +351,7 @@ export const useEntryActions = ({
|
||||
new EntryActionMenuItem({
|
||||
id: COMMAND_ID.entry.readBelow,
|
||||
onClick: runCmdFn(COMMAND_ID.entry.readBelow, [{ publishedAt: entry.publishedAt }]),
|
||||
hide: !!isInCollection,
|
||||
hide: !!isCollection,
|
||||
entryId,
|
||||
}),
|
||||
MENU_ITEM_SEPARATOR,
|
||||
@@ -352,6 +377,14 @@ export const useEntryActions = ({
|
||||
notice: !entry.doesContentContainsHTMLTags && !isEntryInReadability,
|
||||
entryId,
|
||||
}),
|
||||
|
||||
new EntryActionMenuItem({
|
||||
id: COMMAND_ID.global.toggleAIChatPinned,
|
||||
onClick: runCmdFn(COMMAND_ID.global.toggleAIChatPinned, [{ entryId }]),
|
||||
entryId,
|
||||
active: isShowAIChatPinned,
|
||||
hide: !aiEnabled,
|
||||
}),
|
||||
new EntryActionMenuItem({
|
||||
id: COMMAND_ID.settings.customizeToolbar,
|
||||
onClick: runCmdFn(COMMAND_ID.settings.customizeToolbar, []),
|
||||
@@ -370,19 +403,22 @@ export const useEntryActions = ({
|
||||
hasEntry,
|
||||
runCmdFn,
|
||||
entryId,
|
||||
entry?.hasBitTorrent,
|
||||
entry?.url,
|
||||
entry?.imagesLength,
|
||||
entry?.publishedAt,
|
||||
entry?.read,
|
||||
entry?.hasContent,
|
||||
entry?.readability,
|
||||
entry?.doesContentContainsHTMLTags,
|
||||
feed?.id,
|
||||
feed?.ownerUserId,
|
||||
feed?.siteUrl,
|
||||
isInbox,
|
||||
shortcuts,
|
||||
view,
|
||||
isCollection,
|
||||
isInCollection,
|
||||
entry?.url,
|
||||
entry?.publishedAt,
|
||||
entry?.hasContent,
|
||||
entry?.read,
|
||||
entry?.readability,
|
||||
entry?.imagesLength,
|
||||
isShowSourceContent,
|
||||
isShowAISummaryAuto,
|
||||
isShowAISummaryOnce,
|
||||
@@ -391,7 +427,8 @@ export const useEntryActions = ({
|
||||
isShowAITranslationOnce,
|
||||
compact,
|
||||
isEntryInReadability,
|
||||
entry?.doesContentContainsHTMLTags,
|
||||
isShowAIChatPinned,
|
||||
aiEnabled,
|
||||
])
|
||||
|
||||
return actionConfigs
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
import { useDebugFeatureValue } from "~/atoms/debug-feature"
|
||||
import { useServerConfigs } from "~/atoms/server-configs"
|
||||
import { featureConfigMap } from "~/lib/features"
|
||||
|
||||
export const useFeature = (feature: keyof typeof featureConfigMap) => {
|
||||
const debugFeatureValue = useDebugFeatureValue()
|
||||
const serverConfigs = useServerConfigs()
|
||||
const isEnabled =
|
||||
(featureConfigMap[feature] && serverConfigs?.[featureConfigMap[feature]]) ||
|
||||
debugFeatureValue[feature]
|
||||
return isEnabled
|
||||
}
|
||||
@@ -8,9 +8,11 @@ import {
|
||||
import { useUserRole } from "@follow/store/user/hooks"
|
||||
import { t } from "i18next"
|
||||
import { useCallback } from "react"
|
||||
import { useNavigate } from "react-router"
|
||||
import { withoutTrailingSlash, withTrailingSlash } from "ufo"
|
||||
import { useEventCallback } from "usehooks-ts"
|
||||
|
||||
import { previewBackPath } from "~/atoms/preview"
|
||||
import { useServerConfigs } from "~/atoms/server-configs"
|
||||
import { useModalStack } from "~/components/ui/modal/stacked/hooks"
|
||||
import { CustomSafeError } from "~/errors/CustomSafeError"
|
||||
@@ -67,6 +69,7 @@ export interface FollowOptions {
|
||||
export const useFollow = () => {
|
||||
const { present } = useModalStack()
|
||||
const canFollowMoreInboxAndNotify = useCanFollowMoreInboxAndNotify()
|
||||
const navigate = useNavigate()
|
||||
|
||||
return useCallback(
|
||||
(options?: FollowOptions) => {
|
||||
@@ -92,6 +95,9 @@ export const useFollow = () => {
|
||||
content: ({ dismiss }) => {
|
||||
const onSuccess = () => {
|
||||
options?.onSuccess?.()
|
||||
// If it's a preview, navigate to the back path
|
||||
const backPath = previewBackPath()
|
||||
backPath && navigate(backPath)
|
||||
dismiss()
|
||||
}
|
||||
return options?.isList ? (
|
||||
|
||||
@@ -0,0 +1,286 @@
|
||||
import { Spring } from "@follow/components/constants/spring.js"
|
||||
import { RootPortal } from "@follow/components/ui/portal/index.js"
|
||||
import { useIsEntryStarred } from "@follow/store/collection/hooks"
|
||||
import { useEntry, usePrefetchEntryDetail } from "@follow/store/entry/hooks"
|
||||
import { useFeedById } from "@follow/store/feed/hooks"
|
||||
import { nextFrame, stopPropagation } from "@follow/utils/dom"
|
||||
import { cn } from "@follow/utils/utils"
|
||||
import type { Variant } from "motion/react"
|
||||
import { m, useAnimationControls } from "motion/react"
|
||||
import type { FC } from "react"
|
||||
import { useCallback, useEffect, useMemo } from "react"
|
||||
|
||||
import { MenuItemText } from "~/atoms/context-menu"
|
||||
import { RelativeTime } from "~/components/ui/datetime"
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuTrigger,
|
||||
} from "~/components/ui/dropdown-menu/dropdown-menu"
|
||||
import { usePreviewMedia } from "~/components/ui/media/hooks"
|
||||
import { Media } from "~/components/ui/media/Media"
|
||||
import { PeekModal } from "~/components/ui/modal/inspire/PeekModal"
|
||||
import { PlainModal } from "~/components/ui/modal/stacked/custom-modal"
|
||||
import { useModalStack } from "~/components/ui/modal/stacked/hooks"
|
||||
import { Paper } from "~/components/ui/paper"
|
||||
import { useSortedEntryActions } from "~/hooks/biz/useEntryActions"
|
||||
import { getRouteParams } from "~/hooks/biz/useRouteParams"
|
||||
import { COMMAND_ID } from "~/modules/command/commands/id"
|
||||
import { hasCommand } from "~/modules/command/hooks/use-command"
|
||||
import { StarIcon } from "~/modules/entry-column/star-icon"
|
||||
import { CommandDropdownMenuItem } from "~/modules/entry-content/actions/more-actions"
|
||||
import { EntryContent } from "~/modules/entry-content/components/entry-content"
|
||||
import type { FeedIconEntry } from "~/modules/feed/feed-icon"
|
||||
import { FeedIcon } from "~/modules/feed/feed-icon"
|
||||
|
||||
export const usePeekModal = () => {
|
||||
const { present } = useModalStack()
|
||||
return useCallback(
|
||||
(entryId: string, variant: "toast" | "modal") => {
|
||||
const basePresentProps = {
|
||||
clickOutsideToDismiss: true,
|
||||
title: "Entry Preview",
|
||||
}
|
||||
|
||||
if (variant === "toast") {
|
||||
present({
|
||||
...basePresentProps,
|
||||
CustomModalComponent: PlainModal,
|
||||
content: () => <EntryToastPreview entryId={entryId} />,
|
||||
overlay: false,
|
||||
modal: false,
|
||||
modalContainerClassName: "right-0 left-[auto]",
|
||||
})
|
||||
} else {
|
||||
present({
|
||||
...basePresentProps,
|
||||
autoFocus: false,
|
||||
modalClassName:
|
||||
"relative mx-auto mt-[10vh] scrollbar-none max-w-full overflow-auto px-2 lg:max-w-[65rem] lg:p-0",
|
||||
|
||||
CustomModalComponent: ({ children }) => {
|
||||
const feedId = useEntry(entryId, (state) => state.feedId)
|
||||
if (!feedId) return null
|
||||
|
||||
return (
|
||||
<PeekModal
|
||||
rightActions={[
|
||||
{
|
||||
onClick: () => {},
|
||||
label: "More Actions",
|
||||
icon: <EntryMoreActions entryId={entryId} />,
|
||||
},
|
||||
]}
|
||||
to={`/timeline/view-${getRouteParams().view}/${feedId}/${entryId}`}
|
||||
>
|
||||
{children}
|
||||
</PeekModal>
|
||||
)
|
||||
},
|
||||
content: () => <EntryModalPreview entryId={entryId} />,
|
||||
overlay: true,
|
||||
})
|
||||
}
|
||||
},
|
||||
[present],
|
||||
)
|
||||
}
|
||||
|
||||
const variants: Record<string, Variant> = {
|
||||
enter: {
|
||||
x: 0,
|
||||
opacity: 1,
|
||||
},
|
||||
initial: {
|
||||
x: 700,
|
||||
opacity: 0.9,
|
||||
},
|
||||
exit: {
|
||||
x: 750,
|
||||
opacity: 0,
|
||||
},
|
||||
}
|
||||
const EntryToastPreview = ({ entryId }: { entryId: string }) => {
|
||||
usePrefetchEntryDetail(entryId)
|
||||
|
||||
const entry = useEntry(entryId, (state) => {
|
||||
const { feedId } = state
|
||||
const { author, authorAvatar, description, publishedAt } = state
|
||||
|
||||
const media = state.media || []
|
||||
const firstPhotoUrl = media.find((a) => a.type === "photo")?.url
|
||||
const iconEntry: FeedIconEntry = {
|
||||
firstPhotoUrl,
|
||||
authorAvatar,
|
||||
}
|
||||
|
||||
return {
|
||||
author,
|
||||
description,
|
||||
feedId,
|
||||
iconEntry,
|
||||
media,
|
||||
publishedAt,
|
||||
}
|
||||
})
|
||||
const isInCollection = useIsEntryStarred(entryId)
|
||||
|
||||
const feed = useFeedById(entry?.feedId)
|
||||
const controller = useAnimationControls()
|
||||
|
||||
const isDisplay = !!entry && !!feed
|
||||
useEffect(() => {
|
||||
if (isDisplay) {
|
||||
nextFrame(() => controller.start("enter"))
|
||||
}
|
||||
}, [controller, isDisplay])
|
||||
|
||||
const previewMedia = usePreviewMedia()
|
||||
|
||||
if (!isDisplay) return null
|
||||
|
||||
return (
|
||||
<m.div
|
||||
tabIndex={-1}
|
||||
initial="initial"
|
||||
animate={controller}
|
||||
onPointerDown={stopPropagation}
|
||||
onPointerDownCapture={stopPropagation}
|
||||
variants={variants}
|
||||
onWheel={stopPropagation}
|
||||
transition={Spring.presets.snappy}
|
||||
exit="exit"
|
||||
layout="size"
|
||||
className={cn(
|
||||
"shadow-perfect bg-theme-background relative flex flex-col items-center rounded-xl border p-8",
|
||||
"mr-4 mt-4 max-h-[500px] w-[60ch] max-w-full overflow-auto",
|
||||
)}
|
||||
>
|
||||
<div className="flex w-full gap-3">
|
||||
<FeedIcon
|
||||
fallback
|
||||
className="mask-squircle mask"
|
||||
feed={feed}
|
||||
entry={entry.iconEntry}
|
||||
size={36}
|
||||
/>
|
||||
<div className="flex min-w-0 grow flex-col">
|
||||
<div className="w-[calc(100%-10rem)] space-x-1">
|
||||
<span className="font-semibold">{entry.author}</span>
|
||||
<span className="text-zinc-500">·</span>
|
||||
<span className="text-zinc-500">
|
||||
<RelativeTime date={entry.publishedAt} />
|
||||
</span>
|
||||
</div>
|
||||
<div
|
||||
className={cn(
|
||||
"relative mt-0.5 whitespace-pre-line text-base",
|
||||
isInCollection && "pr-5",
|
||||
)}
|
||||
>
|
||||
<div
|
||||
className={cn(
|
||||
"rounded-xl p-3 align-middle text-[15px]",
|
||||
"rounded-tl-none bg-zinc-600/5 dark:bg-zinc-500/20",
|
||||
"mt-1 -translate-x-3",
|
||||
"break-words",
|
||||
)}
|
||||
>
|
||||
{entry.description}
|
||||
|
||||
{!!entry.media?.length && (
|
||||
<div className="mt-1 flex w-full gap-2 overflow-x-auto">
|
||||
{entry.media.map((media, i, mediaList) => (
|
||||
<Media
|
||||
key={media.url}
|
||||
src={media.url}
|
||||
type={media.type}
|
||||
previewImageUrl={media.preview_image_url}
|
||||
className="size-28 shrink-0 cursor-zoom-in"
|
||||
loading="lazy"
|
||||
proxy={{
|
||||
width: 224,
|
||||
height: 224,
|
||||
}}
|
||||
onClick={(e: React.MouseEvent) => {
|
||||
e.stopPropagation()
|
||||
previewMedia(mediaList, i)
|
||||
}}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
{isInCollection && <StarIcon />}
|
||||
</div>
|
||||
|
||||
{/* End right column */}
|
||||
</div>
|
||||
</div>
|
||||
</m.div>
|
||||
)
|
||||
}
|
||||
|
||||
const EntryModalPreview = ({ entryId }: { entryId: string }) => (
|
||||
<Paper className="p-0 !pt-16 empty:hidden">
|
||||
<EntryContent
|
||||
className="h-auto [&_#entry-action-header-bar]:!bg-transparent"
|
||||
entryId={entryId}
|
||||
/>
|
||||
</Paper>
|
||||
)
|
||||
|
||||
const EntryMoreActions: FC<{ entryId: string }> = ({ entryId }) => {
|
||||
const { view } = getRouteParams()
|
||||
const { moreAction, mainAction } = useSortedEntryActions({ entryId, view })
|
||||
|
||||
const actionConfigs = useMemo(
|
||||
() =>
|
||||
[...moreAction, ...mainAction].filter(
|
||||
(action) => action instanceof MenuItemText && hasCommand(action.id),
|
||||
),
|
||||
[moreAction, mainAction],
|
||||
)
|
||||
|
||||
const availableActions = useMemo(
|
||||
() =>
|
||||
actionConfigs.filter(
|
||||
(item) => item instanceof MenuItemText && item.id !== COMMAND_ID.settings.customizeToolbar,
|
||||
),
|
||||
[actionConfigs],
|
||||
)
|
||||
|
||||
const extraAction = useMemo(
|
||||
() =>
|
||||
actionConfigs.filter(
|
||||
(item) => item instanceof MenuItemText && item.id === COMMAND_ID.settings.customizeToolbar,
|
||||
),
|
||||
[actionConfigs],
|
||||
)
|
||||
|
||||
if (availableActions.length === 0 && extraAction.length === 0) {
|
||||
return null
|
||||
}
|
||||
|
||||
return (
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<i className="i-mgc-more-1-cute-re" />
|
||||
</DropdownMenuTrigger>
|
||||
<RootPortal>
|
||||
<DropdownMenuContent alignOffset={20} sideOffset={30}>
|
||||
{availableActions.map((config) =>
|
||||
config instanceof MenuItemText ? (
|
||||
<CommandDropdownMenuItem
|
||||
key={config.id}
|
||||
commandId={config.id}
|
||||
onClick={config.click!}
|
||||
active={config.active}
|
||||
/>
|
||||
) : null,
|
||||
)}
|
||||
</DropdownMenuContent>
|
||||
</RootPortal>
|
||||
</DropdownMenu>
|
||||
)
|
||||
}
|
||||
@@ -35,7 +35,6 @@ export const useDeleteSubscription = ({ onSuccess }: { onSuccess?: () => void }
|
||||
.unsubscribe([subscription.feedId, subscription.listId])
|
||||
.then(([feed]) => {
|
||||
subscriptionSyncService.fetch()
|
||||
unreadActions.updateById(subscription.feedId, 0)
|
||||
|
||||
if (!subscription) return
|
||||
if (!feed) return
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
import { env } from "@follow/shared/env.desktop"
|
||||
import { userActions } from "@follow/store/user/store"
|
||||
import { createDesktopAPIHeaders } from "@follow/utils/headers"
|
||||
import { FollowClient } from "@follow-app/client-sdk"
|
||||
import PKG from "@pkg"
|
||||
import { createElement } from "react"
|
||||
import { toast } from "sonner"
|
||||
|
||||
import { NetworkStatus, setApiStatus } from "~/atoms/network"
|
||||
import { setLoginModalShow } from "~/atoms/user"
|
||||
import { NeedActivationToast } from "~/modules/activation/NeedActivationToast"
|
||||
|
||||
import { getClientId, getSessionId } from "./client-session"
|
||||
|
||||
export const followClient = new FollowClient({
|
||||
credentials: "include",
|
||||
timeout: 10000,
|
||||
baseURL: env.VITE_API_URL,
|
||||
fetch: async (input, options = {}) =>
|
||||
fetch(input.toString(), {
|
||||
...options,
|
||||
cache: "no-store",
|
||||
}),
|
||||
})
|
||||
|
||||
export const followApi = followClient.api
|
||||
followClient.addRequestInterceptor(async (ctx) => {
|
||||
const { options } = ctx
|
||||
const header = options.headers || {}
|
||||
header["X-Client-Id"] = getClientId()
|
||||
header["X-Session-Id"] = getSessionId()
|
||||
|
||||
const apiHeader = createDesktopAPIHeaders({ version: PKG.version })
|
||||
|
||||
options.headers = {
|
||||
...header,
|
||||
...apiHeader,
|
||||
}
|
||||
return ctx
|
||||
})
|
||||
|
||||
followClient.addResponseInterceptor(({ response }) => {
|
||||
setApiStatus(NetworkStatus.ONLINE)
|
||||
return response
|
||||
})
|
||||
|
||||
followClient.addErrorInterceptor(async ({ error, response }) => {
|
||||
const { router } = window
|
||||
|
||||
// If api is down
|
||||
if ((!response || response.status === 0) && navigator.onLine) {
|
||||
setApiStatus(NetworkStatus.OFFLINE)
|
||||
} else {
|
||||
setApiStatus(NetworkStatus.ONLINE)
|
||||
}
|
||||
|
||||
if (!response) {
|
||||
return error
|
||||
}
|
||||
|
||||
if (response.status === 401) {
|
||||
// Or we can present LoginModal here.
|
||||
// router.navigate("/login")
|
||||
// If any response status is 401, we can set auth fail. Maybe some bug, but if navigate to login page, had same issues
|
||||
setLoginModalShow(true)
|
||||
userActions.removeCurrentUser()
|
||||
}
|
||||
try {
|
||||
const json = await response.clone().json()
|
||||
|
||||
if (response.status === 400 && json.code === 1003) {
|
||||
router.navigate("/invitation")
|
||||
}
|
||||
if (json.code.toString().startsWith("11")) {
|
||||
setTimeout(() => {
|
||||
const toastId = toast.error(
|
||||
createElement(NeedActivationToast, {
|
||||
dimiss: () => {
|
||||
toast.dismiss(toastId)
|
||||
},
|
||||
}),
|
||||
{
|
||||
closeButton: true,
|
||||
duration: 10e4,
|
||||
|
||||
classNames: {
|
||||
content: tw`w-full`,
|
||||
},
|
||||
},
|
||||
)
|
||||
}, 500)
|
||||
}
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
|
||||
return error
|
||||
})
|
||||
@@ -0,0 +1,21 @@
|
||||
import type { ExtractResponseData, GetStatusConfigsResponse } from "@follow-app/client-sdk"
|
||||
import type { FC } from "react"
|
||||
|
||||
import { useFeature } from "~/hooks/biz/useFeature"
|
||||
|
||||
export const featureConfigMap: Record<string, keyof ExtractResponseData<GetStatusConfigsResponse>> =
|
||||
{
|
||||
ai: "AI_CHAT_ENABLED",
|
||||
}
|
||||
|
||||
export const withFeature =
|
||||
(feature: keyof typeof featureConfigMap) =>
|
||||
<T extends object>(Component: FC<T>, FallbackComponent: FC<T>) => {
|
||||
const WithFeature = ({ ...props }: T) => {
|
||||
const isEnabled = useFeature(feature)
|
||||
|
||||
return isEnabled ? <Component {...props} /> : <FallbackComponent {...props} />
|
||||
}
|
||||
|
||||
return WithFeature
|
||||
}
|
||||
@@ -35,7 +35,7 @@ export const parseHtml = (
|
||||
components: {
|
||||
a: ({ node, ...props }) => {
|
||||
// markInlineImage(node)
|
||||
return createElement(MarkdownLink, { ...props } as any)
|
||||
return createElement(MarkdownLink, { ...props, className: "text-accent" } as any)
|
||||
},
|
||||
img: Img,
|
||||
|
||||
|
||||
@@ -4,9 +4,10 @@ import "./styles/main.css"
|
||||
|
||||
import { IN_ELECTRON, WEB_BUILD } from "@follow/shared/constants"
|
||||
import {
|
||||
apiClientSimpleContext,
|
||||
authClientSimpleContext,
|
||||
queryClientSimpleContext,
|
||||
apiClientContext,
|
||||
apiContext,
|
||||
authClientContext,
|
||||
queryClientContext,
|
||||
} from "@follow/store/context"
|
||||
import { getOS } from "@follow/utils/utils"
|
||||
import * as React from "react"
|
||||
@@ -20,12 +21,14 @@ import { setAppIsReady } from "./atoms/app"
|
||||
import { ElECTRON_CUSTOM_TITLEBAR_HEIGHT } from "./constants"
|
||||
import { initializeApp } from "./initialize"
|
||||
import { registerAppGlobalShortcuts } from "./initialize/global-shortcuts"
|
||||
import { followApi } from "./lib/api-client"
|
||||
import { queryClient } from "./lib/query-client"
|
||||
import { router } from "./router"
|
||||
|
||||
apiClientSimpleContext.provide(apiClient)
|
||||
authClientSimpleContext.provide(authClient)
|
||||
queryClientSimpleContext.provide(queryClient)
|
||||
apiClientContext.provide(apiClient)
|
||||
authClientContext.provide(authClient)
|
||||
queryClientContext.provide(queryClient)
|
||||
apiContext.provide(followApi)
|
||||
|
||||
initializeApp().finally(() => {
|
||||
import("./push-notification").then(({ registerWebPushNotifications }) => {
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
import { createElement, lazy, Suspense } from "react"
|
||||
|
||||
const AISplineLoader = lazy(() =>
|
||||
import("./AISplineLoader").then((res) => ({ default: res.AISplineLoader })),
|
||||
)
|
||||
export const AISpline = () => {
|
||||
return createElement(
|
||||
Suspense,
|
||||
{
|
||||
fallback: createElement("div", { className: "size-16 mx-auto" }),
|
||||
},
|
||||
createElement(AISplineLoader),
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
import Spline from "@splinetool/react-spline"
|
||||
import { useCallback, useRef } from "react"
|
||||
|
||||
const resolvedAIIconUrl = "https://cdn.follow.is/ai.splinecode"
|
||||
|
||||
export const AISplineLoader = () => {
|
||||
const containerRef = useRef<HTMLDivElement>(null)
|
||||
const headRef = useRef<any>(null)
|
||||
const bodyRef = useRef<any>(null)
|
||||
|
||||
// Angle conversion function: degrees to radians
|
||||
const degToRad = (degrees: number) => degrees * (Math.PI / 180)
|
||||
|
||||
// Calculate the angle the head should look at
|
||||
const calculateHeadRotation = useCallback(
|
||||
(mouseX: number, mouseY: number, containerRect: DOMRect) => {
|
||||
const containerCenterX = containerRect.left + containerRect.width / 2
|
||||
const containerCenterY = containerRect.top + containerRect.height / 2
|
||||
|
||||
// Calculate mouse position relative to container center (-1 to 1)
|
||||
const relativeX = (mouseX - containerCenterX) / (window.innerWidth / 2)
|
||||
const relativeY = (mouseY - containerCenterY) / (window.innerHeight / 2)
|
||||
|
||||
// Clamp range
|
||||
const clampedX = Math.max(-1, Math.min(1, relativeX))
|
||||
const clampedY = Math.max(-1, Math.min(1, relativeY))
|
||||
|
||||
// Calculate head rotation angle based on relative position
|
||||
// Y-axis rotation (left-right): -70 to 70 degrees
|
||||
const headRotationY = clampedX * 70
|
||||
|
||||
// X-axis rotation (up-down): -60 to 60 degrees
|
||||
const headRotationX = clampedY * 60
|
||||
|
||||
return {
|
||||
x: degToRad(headRotationX),
|
||||
y: degToRad(headRotationY),
|
||||
}
|
||||
},
|
||||
[],
|
||||
)
|
||||
|
||||
// Calculate body rotation angle (horizontal rotation only)
|
||||
const calculateBodyRotation = useCallback((mouseX: number, containerRect: DOMRect) => {
|
||||
const containerCenterX = containerRect.left + containerRect.width / 2
|
||||
|
||||
// Calculate mouse X position relative to container center (-1 to 1)
|
||||
const relativeX = (mouseX - containerCenterX) / (window.innerWidth / 2)
|
||||
const clampedX = Math.max(-1, Math.min(1, relativeX))
|
||||
|
||||
// Body Y-axis rotation: -30 to 30 degrees (smaller range than head rotation)
|
||||
const bodyRotationY = clampedX * 30
|
||||
|
||||
return {
|
||||
x: 0, // Body doesn't rotate up-down
|
||||
y: degToRad(bodyRotationY),
|
||||
}
|
||||
}, [])
|
||||
|
||||
const handleLoad = useCallback(
|
||||
(app: any) => {
|
||||
const head = app.findObjectByName("Head")
|
||||
const body = app.findObjectByName("Body")
|
||||
|
||||
if (!head || !body) {
|
||||
console.warn("Cannot find Head or Body object")
|
||||
return
|
||||
}
|
||||
|
||||
headRef.current = head
|
||||
bodyRef.current = body
|
||||
|
||||
const onMove = (e: MouseEvent) => {
|
||||
if (!containerRef.current || !headRef.current || !bodyRef.current) return
|
||||
|
||||
const containerRect = containerRef.current.getBoundingClientRect()
|
||||
|
||||
// Calculate head rotation
|
||||
const headRotation = calculateHeadRotation(e.clientX, e.clientY, containerRect)
|
||||
headRef.current.rotation.x = headRotation.x
|
||||
headRef.current.rotation.y = headRotation.y
|
||||
|
||||
// Calculate body rotation
|
||||
const bodyRotation = calculateBodyRotation(e.clientX, containerRect)
|
||||
bodyRef.current.rotation.x = bodyRotation.x
|
||||
bodyRef.current.rotation.y = bodyRotation.y
|
||||
}
|
||||
|
||||
// Reset to default position when mouse leaves
|
||||
const onMouseLeave = () => {
|
||||
if (!headRef.current || !bodyRef.current) return
|
||||
|
||||
// Smooth transition back to default position
|
||||
const resetAnimation = () => {
|
||||
if (!headRef.current || !bodyRef.current) return
|
||||
|
||||
const currentHeadX = headRef.current.rotation.x
|
||||
const currentHeadY = headRef.current.rotation.y
|
||||
const currentBodyY = bodyRef.current.rotation.y
|
||||
|
||||
// Simple linear interpolation to smoothly return rotation to 0
|
||||
headRef.current.rotation.x = currentHeadX * 0.9
|
||||
headRef.current.rotation.y = currentHeadY * 0.9
|
||||
bodyRef.current.rotation.y = currentBodyY * 0.9
|
||||
|
||||
// Continue animation if not fully returned to 0
|
||||
if (
|
||||
Math.abs(currentHeadX) > 0.01 ||
|
||||
Math.abs(currentHeadY) > 0.01 ||
|
||||
Math.abs(currentBodyY) > 0.01
|
||||
) {
|
||||
requestAnimationFrame(resetAnimation)
|
||||
} else {
|
||||
// Complete reset to 0
|
||||
headRef.current.rotation.x = 0
|
||||
headRef.current.rotation.y = 0
|
||||
bodyRef.current.rotation.x = 0
|
||||
bodyRef.current.rotation.y = 0
|
||||
}
|
||||
}
|
||||
|
||||
resetAnimation()
|
||||
}
|
||||
|
||||
window.addEventListener("pointermove", onMove)
|
||||
document.addEventListener("mouseleave", onMouseLeave)
|
||||
|
||||
return () => {
|
||||
window.removeEventListener("pointermove", onMove)
|
||||
document.removeEventListener("mouseleave", onMouseLeave)
|
||||
}
|
||||
},
|
||||
[calculateHeadRotation, calculateBodyRotation],
|
||||
)
|
||||
|
||||
return (
|
||||
<div ref={containerRef} className={"!size-16"}>
|
||||
<Spline scene={resolvedAIIconUrl} onLoad={handleLoad} className="size-full" />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -3,7 +3,6 @@ import { EmptyIcon } from "@follow/components/icons/empty.jsx"
|
||||
import { CollapseControlled } from "@follow/components/ui/collapse/Collapse.js"
|
||||
import type { LinkProps } from "@follow/components/ui/link/LinkWithTooltip.js"
|
||||
import { LoadingCircle } from "@follow/components/ui/loading/index.jsx"
|
||||
import { RootPortal } from "@follow/components/ui/portal/index.js"
|
||||
import { ScrollArea } from "@follow/components/ui/scroll-area/index.js"
|
||||
import {
|
||||
Tooltip,
|
||||
@@ -11,47 +10,20 @@ import {
|
||||
TooltipPortal,
|
||||
TooltipTrigger,
|
||||
} from "@follow/components/ui/tooltip/index.jsx"
|
||||
import { useIsEntryStarred } from "@follow/store/collection/hooks"
|
||||
import { useEntry, usePrefetchEntryDetail } from "@follow/store/entry/hooks"
|
||||
import { useFeedById } from "@follow/store/feed/hooks"
|
||||
import { nextFrame, stopPropagation } from "@follow/utils/dom"
|
||||
import { cn, isBizId } from "@follow/utils/utils"
|
||||
import { noop } from "foxact/noop"
|
||||
import type { Components } from "hast-util-to-jsx-runtime"
|
||||
import type { Variant } from "motion/react"
|
||||
import { m, useAnimationControls } from "motion/react"
|
||||
import type { FC } from "react"
|
||||
import { useCallback, useEffect, useMemo, useState } from "react"
|
||||
import { m } from "motion/react"
|
||||
import { useMemo, useState } from "react"
|
||||
import { Trans, useTranslation } from "react-i18next"
|
||||
|
||||
import { MenuItemText } from "~/atoms/context-menu"
|
||||
import { useGeneralSettingSelector } from "~/atoms/settings/general"
|
||||
import { RelativeTime } from "~/components/ui/datetime"
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuTrigger,
|
||||
} from "~/components/ui/dropdown-menu/dropdown-menu"
|
||||
import { Markdown } from "~/components/ui/markdown/Markdown"
|
||||
import { MarkdownLink } from "~/components/ui/markdown/renderers"
|
||||
import { usePreviewMedia } from "~/components/ui/media/hooks"
|
||||
import { Media } from "~/components/ui/media/Media"
|
||||
import { PeekModal } from "~/components/ui/modal/inspire/PeekModal"
|
||||
import { PlainModal } from "~/components/ui/modal/stacked/custom-modal"
|
||||
import { useModalStack } from "~/components/ui/modal/stacked/hooks"
|
||||
import { Paper } from "~/components/ui/paper"
|
||||
import { useSortedEntryActions } from "~/hooks/biz/useEntryActions"
|
||||
import { getRouteParams } from "~/hooks/biz/useRouteParams"
|
||||
import { usePeekModal } from "~/hooks/biz/usePeekModal"
|
||||
import { useAuthQuery } from "~/hooks/common"
|
||||
import { apiClient } from "~/lib/api-fetch"
|
||||
import { defineQuery } from "~/lib/defineQuery"
|
||||
import { COMMAND_ID } from "~/modules/command/commands/id"
|
||||
import { hasCommand } from "~/modules/command/hooks/use-command"
|
||||
import { StarIcon } from "~/modules/entry-column/star-icon"
|
||||
import { CommandDropdownMenuItem } from "~/modules/entry-content/actions/more-actions"
|
||||
import { EntryContent } from "~/modules/entry-content/components/entry-content"
|
||||
import type { FeedIconEntry } from "~/modules/feed/feed-icon"
|
||||
import { FeedIcon } from "~/modules/feed/feed-icon"
|
||||
|
||||
import { remarkSnowflakeId } from "./plugins/parse-snowflake"
|
||||
import type { DailyItemProps, DailyView } from "./types"
|
||||
@@ -297,258 +269,6 @@ const createRelatedEntryLink = (variant: "toast" | "modal") => (props: LinkProps
|
||||
)
|
||||
}
|
||||
|
||||
const usePeekModal = () => {
|
||||
const { present } = useModalStack()
|
||||
return useCallback(
|
||||
(entryId: string, variant: "toast" | "modal") => {
|
||||
const basePresentProps = {
|
||||
clickOutsideToDismiss: true,
|
||||
title: "Entry Preview",
|
||||
}
|
||||
|
||||
if (variant === "toast") {
|
||||
present({
|
||||
...basePresentProps,
|
||||
CustomModalComponent: PlainModal,
|
||||
content: () => <EntryToastPreview entryId={entryId} />,
|
||||
overlay: false,
|
||||
modal: false,
|
||||
modalContainerClassName: "right-0 left-[auto]",
|
||||
})
|
||||
} else {
|
||||
present({
|
||||
...basePresentProps,
|
||||
autoFocus: false,
|
||||
modalClassName:
|
||||
"relative mx-auto mt-[10vh] scrollbar-none max-w-full overflow-auto px-2 lg:max-w-[65rem] lg:p-0",
|
||||
|
||||
CustomModalComponent: ({ children }) => {
|
||||
const feedId = useEntry(entryId, (state) => state.feedId)
|
||||
if (!feedId) return null
|
||||
|
||||
return (
|
||||
<PeekModal
|
||||
rightActions={[
|
||||
{
|
||||
onClick: () => {},
|
||||
label: "More Actions",
|
||||
icon: <EntryMoreActions entryId={entryId} />,
|
||||
},
|
||||
]}
|
||||
to={`/timeline/view-${getRouteParams().view}/${feedId}/${entryId}`}
|
||||
>
|
||||
{children}
|
||||
</PeekModal>
|
||||
)
|
||||
},
|
||||
content: () => <EntryModalPreview entryId={entryId} />,
|
||||
overlay: true,
|
||||
})
|
||||
}
|
||||
},
|
||||
[present],
|
||||
)
|
||||
}
|
||||
const EntryToastPreview = ({ entryId }: { entryId: string }) => {
|
||||
usePrefetchEntryDetail(entryId)
|
||||
|
||||
const variants: Record<string, Variant> = {
|
||||
enter: {
|
||||
x: 0,
|
||||
opacity: 1,
|
||||
},
|
||||
initial: {
|
||||
x: 700,
|
||||
opacity: 0.9,
|
||||
},
|
||||
exit: {
|
||||
x: 750,
|
||||
opacity: 0,
|
||||
},
|
||||
}
|
||||
|
||||
const entry = useEntry(entryId, (state) => {
|
||||
const { feedId } = state
|
||||
const { author, authorAvatar, description, publishedAt } = state
|
||||
|
||||
const media = state.media || []
|
||||
const firstPhotoUrl = media.find((a) => a.type === "photo")?.url
|
||||
const iconEntry: FeedIconEntry = {
|
||||
firstPhotoUrl,
|
||||
authorAvatar,
|
||||
}
|
||||
|
||||
return {
|
||||
author,
|
||||
description,
|
||||
feedId,
|
||||
iconEntry,
|
||||
media,
|
||||
publishedAt,
|
||||
}
|
||||
})
|
||||
const isInCollection = useIsEntryStarred(entryId)
|
||||
|
||||
const feed = useFeedById(entry?.feedId)
|
||||
const controller = useAnimationControls()
|
||||
|
||||
const isDisplay = !!entry && !!feed
|
||||
useEffect(() => {
|
||||
if (isDisplay) {
|
||||
nextFrame(() => controller.start("enter"))
|
||||
}
|
||||
}, [controller, isDisplay])
|
||||
|
||||
const previewMedia = usePreviewMedia()
|
||||
|
||||
if (!isDisplay) return null
|
||||
|
||||
return (
|
||||
<m.div
|
||||
tabIndex={-1}
|
||||
initial="initial"
|
||||
animate={controller}
|
||||
onPointerDown={stopPropagation}
|
||||
onPointerDownCapture={stopPropagation}
|
||||
variants={variants}
|
||||
onWheel={stopPropagation}
|
||||
transition={Spring.presets.snappy}
|
||||
exit="exit"
|
||||
layout="size"
|
||||
className={cn(
|
||||
"shadow-perfect bg-theme-background relative flex flex-col items-center rounded-xl border p-8",
|
||||
"mr-4 mt-4 max-h-[500px] w-[60ch] max-w-full overflow-auto",
|
||||
)}
|
||||
>
|
||||
<div className="flex w-full gap-3">
|
||||
<FeedIcon
|
||||
fallback
|
||||
className="mask-squircle mask"
|
||||
feed={feed}
|
||||
entry={entry.iconEntry}
|
||||
size={36}
|
||||
/>
|
||||
<div className="flex min-w-0 grow flex-col">
|
||||
<div className="w-[calc(100%-10rem)] space-x-1">
|
||||
<span className="font-semibold">{entry.author}</span>
|
||||
<span className="text-zinc-500">·</span>
|
||||
<span className="text-zinc-500">
|
||||
<RelativeTime date={entry.publishedAt} />
|
||||
</span>
|
||||
</div>
|
||||
<div
|
||||
className={cn(
|
||||
"relative mt-0.5 whitespace-pre-line text-base",
|
||||
isInCollection && "pr-5",
|
||||
)}
|
||||
>
|
||||
<div
|
||||
className={cn(
|
||||
"rounded-xl p-3 align-middle text-[15px]",
|
||||
"rounded-tl-none bg-zinc-600/5 dark:bg-zinc-500/20",
|
||||
"mt-1 -translate-x-3",
|
||||
"break-words",
|
||||
)}
|
||||
>
|
||||
{entry.description}
|
||||
|
||||
{!!entry.media?.length && (
|
||||
<div className="mt-1 flex w-full gap-2 overflow-x-auto">
|
||||
{entry.media.map((media, i, mediaList) => (
|
||||
<Media
|
||||
key={media.url}
|
||||
src={media.url}
|
||||
type={media.type}
|
||||
previewImageUrl={media.preview_image_url}
|
||||
className="size-28 shrink-0 cursor-zoom-in"
|
||||
loading="lazy"
|
||||
proxy={{
|
||||
width: 224,
|
||||
height: 224,
|
||||
}}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
previewMedia(mediaList, i)
|
||||
}}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
{isInCollection && <StarIcon />}
|
||||
</div>
|
||||
|
||||
{/* End right column */}
|
||||
</div>
|
||||
</div>
|
||||
</m.div>
|
||||
)
|
||||
}
|
||||
|
||||
const EntryModalPreview = ({ entryId }: { entryId: string }) => (
|
||||
<Paper className="p-0 !pt-16 empty:hidden">
|
||||
<EntryContent
|
||||
className="h-auto [&_#entry-action-header-bar]:!bg-transparent"
|
||||
entryId={entryId}
|
||||
/>
|
||||
</Paper>
|
||||
)
|
||||
|
||||
const EntryMoreActions: FC<{ entryId: string }> = ({ entryId }) => {
|
||||
const { view } = getRouteParams()
|
||||
const { moreAction, mainAction } = useSortedEntryActions({ entryId, view })
|
||||
|
||||
const actionConfigs = useMemo(
|
||||
() =>
|
||||
[...moreAction, ...mainAction].filter(
|
||||
(action) => action instanceof MenuItemText && hasCommand(action.id),
|
||||
),
|
||||
[moreAction, mainAction],
|
||||
)
|
||||
|
||||
const availableActions = useMemo(
|
||||
() =>
|
||||
actionConfigs.filter(
|
||||
(item) => item instanceof MenuItemText && item.id !== COMMAND_ID.settings.customizeToolbar,
|
||||
),
|
||||
[actionConfigs],
|
||||
)
|
||||
|
||||
const extraAction = useMemo(
|
||||
() =>
|
||||
actionConfigs.filter(
|
||||
(item) => item instanceof MenuItemText && item.id === COMMAND_ID.settings.customizeToolbar,
|
||||
),
|
||||
[actionConfigs],
|
||||
)
|
||||
|
||||
if (availableActions.length === 0 && extraAction.length === 0) {
|
||||
return null
|
||||
}
|
||||
|
||||
return (
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<i className="i-mgc-more-1-cute-re" />
|
||||
</DropdownMenuTrigger>
|
||||
<RootPortal>
|
||||
<DropdownMenuContent alignOffset={20} sideOffset={30}>
|
||||
{availableActions.map((config) =>
|
||||
config instanceof MenuItemText ? (
|
||||
<CommandDropdownMenuItem
|
||||
key={config.id}
|
||||
commandId={config.id}
|
||||
onClick={config.click!}
|
||||
active={config.active}
|
||||
/>
|
||||
) : null,
|
||||
)}
|
||||
</DropdownMenuContent>
|
||||
</RootPortal>
|
||||
</DropdownMenu>
|
||||
)
|
||||
}
|
||||
|
||||
interface SnowflakeIdProps {
|
||||
id: string
|
||||
children?: React.ReactNode
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
import type { UIMessage, UseChatHelpers } from "@ai-sdk/react"
|
||||
import type { UIDataTypes } from "ai"
|
||||
import { createContext, use } from "react"
|
||||
import type { StoreApi } from "zustand"
|
||||
import type { UseBoundStoreWithEqualityFn } from "zustand/traditional"
|
||||
|
||||
import type { AiChatContextStore } from "./store"
|
||||
import type { BizUIMetadata, BizUITools } from "./types"
|
||||
|
||||
export const AIChatContext = createContext<
|
||||
UseChatHelpers<UIMessage<BizUIMetadata, UIDataTypes, BizUITools>>
|
||||
>(null!)
|
||||
|
||||
export type AIPanelRefs = {
|
||||
panelRef: React.RefObject<HTMLDivElement>
|
||||
inputRef: React.RefObject<HTMLTextAreaElement>
|
||||
}
|
||||
|
||||
export const AIPanelRefsContext = createContext<AIPanelRefs>(null!)
|
||||
|
||||
export const AIChatContextStoreContext = createContext<
|
||||
UseBoundStoreWithEqualityFn<StoreApi<AiChatContextStore>>
|
||||
>(null!)
|
||||
|
||||
// Hook to access AI chat context information
|
||||
export const useAIChatStore = () => {
|
||||
const store = use(AIChatContextStoreContext)
|
||||
if (!store && import.meta.env.DEV) {
|
||||
throw new Error("useAIChatStore must be used within a AIChatContextStoreContext")
|
||||
}
|
||||
return store
|
||||
}
|
||||
|
||||
// Session methods context for managing chat session actions
|
||||
export interface AIChatSessionMethods {
|
||||
handleTitleGenerated: (title: string) => Promise<void>
|
||||
handleFirstMessage: () => Promise<void>
|
||||
handleNewChat: () => void
|
||||
handleSwitchRoom: (roomId: string) => Promise<void>
|
||||
}
|
||||
|
||||
export const AIChatSessionMethodsContext = createContext<AIChatSessionMethods>(null!)
|
||||
|
||||
export const useAIChatSessionMethods = () => {
|
||||
const context = use(AIChatSessionMethodsContext)
|
||||
if (!context && import.meta.env.DEV) {
|
||||
throw new Error("useAIChatSessionMethods must be used within a AIChatSessionMethodsContext")
|
||||
}
|
||||
return context
|
||||
}
|
||||
@@ -0,0 +1,203 @@
|
||||
import { produce } from "immer"
|
||||
import { nanoid } from "nanoid"
|
||||
import { createWithEqualityFn } from "zustand/traditional"
|
||||
|
||||
import type { AIChatContextBlock, AIChatContextInfo } from "./types"
|
||||
import { blocksToContextInfo, contextInfoToBlocks } from "./utils"
|
||||
|
||||
export interface AiChatContextStore {
|
||||
state: AIChatContextInfo
|
||||
blocks: AIChatContextBlock[]
|
||||
// Block management methods
|
||||
addBlock: (block: Omit<AIChatContextBlock, "id">) => void
|
||||
removeBlock: (id: string) => void
|
||||
updateBlock: (id: string, updates: Partial<AIChatContextBlock>) => void
|
||||
clearBlocks: () => void
|
||||
// Context info management methods
|
||||
setMainEntryId: (entryId?: string) => void
|
||||
addReferEntryId: (entryId: string) => void
|
||||
removeReferEntryId: (entryId: string) => void
|
||||
addReferFeedId: (feedId: string) => void
|
||||
removeReferFeedId: (feedId: string) => void
|
||||
setSelectedText: (selectedText?: string) => void
|
||||
// Legacy compatibility
|
||||
setEntryId: (entryId?: string) => void
|
||||
setFeedId: (feedId?: string) => void
|
||||
reset: () => void
|
||||
// Sync methods
|
||||
syncBlocksToContext: () => void
|
||||
syncContextToBlocks: () => void
|
||||
}
|
||||
|
||||
export const createAIChatContextStore = (initialState?: Partial<AIChatContextInfo>) => {
|
||||
const defaultState: AIChatContextInfo = {
|
||||
mainEntryId: undefined,
|
||||
referEntryIds: [],
|
||||
referFeedIds: [],
|
||||
selectedText: undefined,
|
||||
}
|
||||
|
||||
const defaultBlocks: AIChatContextBlock[] = []
|
||||
|
||||
const state: AIChatContextInfo = {
|
||||
mainEntryId: initialState?.mainEntryId,
|
||||
referEntryIds: initialState?.referEntryIds || [],
|
||||
referFeedIds: initialState?.referFeedIds || [],
|
||||
selectedText: initialState?.selectedText,
|
||||
}
|
||||
|
||||
return createWithEqualityFn<AiChatContextStore>((set, get) => ({
|
||||
state,
|
||||
blocks: defaultBlocks,
|
||||
|
||||
// Block management methods
|
||||
addBlock: (block: Omit<AIChatContextBlock, "id">) => {
|
||||
// Check for uniqueness constraints
|
||||
const currentBlocks = get().blocks
|
||||
|
||||
// Only allow one mainEntry
|
||||
if (block.type === "mainEntry" && currentBlocks.some((b) => b.type === "mainEntry")) {
|
||||
return
|
||||
}
|
||||
|
||||
// Only allow one selectedText
|
||||
if (block.type === "selectedText" && currentBlocks.some((b) => b.type === "selectedText")) {
|
||||
return
|
||||
}
|
||||
|
||||
// Prevent duplicate referEntry or referFeed
|
||||
if (
|
||||
block.type === "referEntry" &&
|
||||
block.value &&
|
||||
currentBlocks.some((b) => b.type === "referEntry" && b.value === block.value)
|
||||
) {
|
||||
return
|
||||
}
|
||||
|
||||
if (
|
||||
block.type === "referFeed" &&
|
||||
block.value &&
|
||||
currentBlocks.some((b) => b.type === "referFeed" && b.value === block.value)
|
||||
) {
|
||||
return
|
||||
}
|
||||
|
||||
set(
|
||||
produce((s) => {
|
||||
s.blocks.push({ ...block, id: nanoid(8) })
|
||||
}),
|
||||
)
|
||||
|
||||
// Sync to context info
|
||||
get().syncBlocksToContext()
|
||||
},
|
||||
|
||||
removeBlock: (id: string) => {
|
||||
set(
|
||||
produce((s: AiChatContextStore) => {
|
||||
s.blocks = s.blocks.filter((block) => block.id !== id)
|
||||
}),
|
||||
)
|
||||
|
||||
// Sync to context info
|
||||
get().syncBlocksToContext()
|
||||
},
|
||||
|
||||
updateBlock: (id: string, updates: Partial<AIChatContextBlock>) => {
|
||||
set(
|
||||
produce((s: AiChatContextStore) => {
|
||||
s.blocks = s.blocks.map((block) => (block.id === id ? { ...block, ...updates } : block))
|
||||
}),
|
||||
)
|
||||
|
||||
// Sync to context info
|
||||
get().syncBlocksToContext()
|
||||
},
|
||||
|
||||
clearBlocks: () => {
|
||||
set(
|
||||
produce((s: AiChatContextStore) => {
|
||||
s.blocks = defaultBlocks
|
||||
}),
|
||||
)
|
||||
get().syncBlocksToContext()
|
||||
},
|
||||
|
||||
// Context info management methods
|
||||
setMainEntryId: (entryId?: string) => {
|
||||
set((s) => ({ state: { ...s.state, mainEntryId: entryId } }))
|
||||
get().syncContextToBlocks()
|
||||
},
|
||||
|
||||
addReferEntryId: (entryId: string) => {
|
||||
set((s) => ({
|
||||
state: {
|
||||
...s.state,
|
||||
referEntryIds: [...(s.state.referEntryIds || []), entryId],
|
||||
},
|
||||
}))
|
||||
get().syncContextToBlocks()
|
||||
},
|
||||
|
||||
removeReferEntryId: (entryId: string) => {
|
||||
set((s) => ({
|
||||
state: {
|
||||
...s.state,
|
||||
referEntryIds: (s.state.referEntryIds || []).filter((id) => id !== entryId),
|
||||
},
|
||||
}))
|
||||
get().syncContextToBlocks()
|
||||
},
|
||||
|
||||
addReferFeedId: (feedId: string) => {
|
||||
set((s) => ({
|
||||
state: {
|
||||
...s.state,
|
||||
referFeedIds: [...(s.state.referFeedIds || []), feedId],
|
||||
},
|
||||
}))
|
||||
get().syncContextToBlocks()
|
||||
},
|
||||
|
||||
removeReferFeedId: (feedId: string) => {
|
||||
set((s) => ({
|
||||
state: {
|
||||
...s.state,
|
||||
referFeedIds: (s.state.referFeedIds || []).filter((id) => id !== feedId),
|
||||
},
|
||||
}))
|
||||
get().syncContextToBlocks()
|
||||
},
|
||||
|
||||
setSelectedText: (selectedText?: string) => {
|
||||
set((s) => ({ state: { ...s.state, selectedText } }))
|
||||
get().syncContextToBlocks()
|
||||
},
|
||||
|
||||
// Legacy compatibility
|
||||
setEntryId: (entryId?: string) => {
|
||||
get().setMainEntryId(entryId)
|
||||
},
|
||||
|
||||
setFeedId: (feedId?: string) => {
|
||||
if (feedId) {
|
||||
get().addReferFeedId(feedId)
|
||||
}
|
||||
},
|
||||
|
||||
reset: () => {
|
||||
set(() => ({ state: defaultState, blocks: defaultBlocks }))
|
||||
},
|
||||
|
||||
// Sync methods
|
||||
syncBlocksToContext: () => {
|
||||
const contextInfo = blocksToContextInfo(get().blocks)
|
||||
set((s) => ({ state: { ...s.state, ...contextInfo } }))
|
||||
},
|
||||
|
||||
syncContextToBlocks: () => {
|
||||
const blocks = contextInfoToBlocks(get().state)
|
||||
set(() => ({ blocks }))
|
||||
},
|
||||
}))
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import type { BizUITools, ToolWithState } from "@folo-services/ai-tools"
|
||||
|
||||
export interface AIChatContextBlock {
|
||||
id: string
|
||||
type: "mainEntry" | "referEntry" | "referFeed" | "selectedText"
|
||||
value: string
|
||||
}
|
||||
|
||||
export interface AIChatContextInfo {
|
||||
mainEntryId?: string
|
||||
referEntryIds?: string[]
|
||||
referFeedIds?: string[]
|
||||
selectedText?: string
|
||||
}
|
||||
|
||||
export interface AIChatContextBlocks {
|
||||
blocks: AIChatContextBlock[]
|
||||
}
|
||||
|
||||
export type AIDisplayAnalyticsTool = ToolWithState<BizUITools["displayAnalytics"]>
|
||||
export type AIDisplayFeedsTool = ToolWithState<BizUITools["displayFeeds"]>
|
||||
export type AIDisplayEntriesTool = ToolWithState<BizUITools["displayEntries"]>
|
||||
export type AIDisplaySubscriptionsTool = ToolWithState<BizUITools["displaySubscriptions"]>
|
||||
|
||||
export { type BizUIMessage, type BizUIMetadata, type BizUITools } from "@folo-services/ai-tools"
|
||||
@@ -0,0 +1,72 @@
|
||||
import type { AIChatContextBlock, AIChatContextInfo } from "./types"
|
||||
|
||||
export const contextInfoToBlocks = (contextInfo: AIChatContextInfo): AIChatContextBlock[] => {
|
||||
const blocks: AIChatContextBlock[] = []
|
||||
|
||||
// Main entry (single)
|
||||
if (contextInfo.mainEntryId) {
|
||||
blocks.push({
|
||||
id: `main-entry-${contextInfo.mainEntryId}`,
|
||||
type: "mainEntry",
|
||||
value: contextInfo.mainEntryId,
|
||||
})
|
||||
}
|
||||
|
||||
// Reference entries (multiple)
|
||||
contextInfo.referEntryIds?.forEach((entryId) => {
|
||||
blocks.push({
|
||||
id: `refer-entry-${entryId}`,
|
||||
type: "referEntry",
|
||||
value: entryId,
|
||||
})
|
||||
})
|
||||
|
||||
// Reference feeds (multiple)
|
||||
contextInfo.referFeedIds?.forEach((feedId) => {
|
||||
blocks.push({
|
||||
id: `refer-feed-${feedId}`,
|
||||
type: "referFeed",
|
||||
value: feedId,
|
||||
})
|
||||
})
|
||||
|
||||
// Selected text (single, auto-detected)
|
||||
if (contextInfo.selectedText) {
|
||||
blocks.push({
|
||||
id: "selected-text",
|
||||
type: "selectedText",
|
||||
value: contextInfo.selectedText,
|
||||
})
|
||||
}
|
||||
|
||||
return blocks
|
||||
}
|
||||
|
||||
export const blocksToContextInfo = (blocks: AIChatContextBlock[]): AIChatContextInfo => {
|
||||
const contextInfo: AIChatContextInfo = {}
|
||||
|
||||
blocks.forEach((block) => {
|
||||
switch (block.type) {
|
||||
case "mainEntry": {
|
||||
contextInfo.mainEntryId = block.value
|
||||
break
|
||||
}
|
||||
case "referEntry": {
|
||||
if (!contextInfo.referEntryIds) contextInfo.referEntryIds = []
|
||||
contextInfo.referEntryIds.push(block.value)
|
||||
break
|
||||
}
|
||||
case "referFeed": {
|
||||
if (!contextInfo.referFeedIds) contextInfo.referFeedIds = []
|
||||
contextInfo.referFeedIds.push(block.value)
|
||||
break
|
||||
}
|
||||
case "selectedText": {
|
||||
contextInfo.selectedText = block.value
|
||||
break
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
return contextInfo
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
import { atom } from "jotai"
|
||||
import { useCallback } from "react"
|
||||
|
||||
import { createAtomHooks } from "~/lib/jotai"
|
||||
|
||||
// Session state atoms with hooks
|
||||
export const [, , useCurrentRoomId, useSetCurrentRoomId, , setCurrentRoomId] = createAtomHooks(
|
||||
atom<string | null>(null),
|
||||
)
|
||||
|
||||
export const [, , useCurrentTitle, useSetCurrentTitle, , setCurrentTitle] =
|
||||
createAtomHooks(atom<string | undefined>())
|
||||
|
||||
export const [, , useSessionPersisted, useSetSessionPersisted, , setSessionPersisted] =
|
||||
createAtomHooks(atom<boolean>(false))
|
||||
|
||||
// Edit state management for messages
|
||||
export const [, , useEditingMessageId, useSetEditingMessageId, , setEditingMessageId] =
|
||||
createAtomHooks(atom<string | null>(null))
|
||||
|
||||
// Combined hook for all session state
|
||||
export const useSessionState = () => {
|
||||
return {
|
||||
currentRoomId: useCurrentRoomId(),
|
||||
currentTitle: useCurrentTitle(),
|
||||
sessionPersisted: useSessionPersisted(),
|
||||
editingMessageId: useEditingMessageId(),
|
||||
}
|
||||
}
|
||||
|
||||
// Hook for session state setters
|
||||
export const useSessionSetters = () => {
|
||||
const setCurrentRoomIdAtom = useSetCurrentRoomId()
|
||||
const setCurrentTitleAtom = useSetCurrentTitle()
|
||||
const setSessionPersistedAtom = useSetSessionPersisted()
|
||||
|
||||
return useCallback(
|
||||
(updates: {
|
||||
currentRoomId?: string | null
|
||||
currentTitle?: string | undefined
|
||||
sessionPersisted?: boolean
|
||||
}) => {
|
||||
if (updates.currentRoomId !== undefined) setCurrentRoomIdAtom(updates.currentRoomId)
|
||||
if (updates.currentTitle !== undefined) setCurrentTitleAtom(updates.currentTitle)
|
||||
if (updates.sessionPersisted !== undefined) setSessionPersistedAtom(updates.sessionPersisted)
|
||||
},
|
||||
[setCurrentRoomIdAtom, setCurrentTitleAtom, setSessionPersistedAtom],
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,439 @@
|
||||
import { useEntry, useEntryIdsByFeedId, useEntryIdsByView } from "@follow/store/entry/hooks"
|
||||
import { useEntryStore } from "@follow/store/entry/store"
|
||||
import { getFeedById } from "@follow/store/feed/getter"
|
||||
import { useFeedById } from "@follow/store/feed/hooks"
|
||||
import { useAllFeedSubscription } from "@follow/store/subscription/hooks"
|
||||
import { stopPropagation } from "@follow/utils"
|
||||
import { cn } from "@follow/utils/utils"
|
||||
import Fuse from "fuse.js"
|
||||
import type { FC } from "react"
|
||||
import { memo, useMemo, useState } from "react"
|
||||
import { useDebounceCallback } from "usehooks-ts"
|
||||
|
||||
import { useAISettingValue } from "~/atoms/settings/ai"
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuSub,
|
||||
DropdownMenuSubContent,
|
||||
DropdownMenuSubTrigger,
|
||||
DropdownMenuTrigger,
|
||||
} from "~/components/ui/dropdown-menu/dropdown-menu"
|
||||
import { useRouteParamsSelector } from "~/hooks/biz/useRouteParams"
|
||||
import { useAIChatStore } from "~/modules/ai/chat/__internal__/AIChatContext"
|
||||
import type { AIChatContextBlock } from "~/modules/ai/chat/__internal__/types"
|
||||
|
||||
export const AIChatContextBar: Component<{ onSendShortcut?: (prompt: string) => void }> = memo(
|
||||
({ className, onSendShortcut }) => {
|
||||
const blocks = useAIChatStore()((s) => s.blocks)
|
||||
const { addBlock } = useAIChatStore()()
|
||||
const { shortcuts } = useAISettingValue()
|
||||
|
||||
// Filter enabled shortcuts
|
||||
const enabledShortcuts = useMemo(
|
||||
() => shortcuts.filter((shortcut) => shortcut.enabled),
|
||||
[shortcuts],
|
||||
)
|
||||
|
||||
const contextMenuContent = (
|
||||
<DropdownMenuContent align="start">
|
||||
<DropdownMenuSub>
|
||||
<DropdownMenuSubTrigger>
|
||||
<i className="i-mgc-paper-cute-fi mr-1.5 size-4" />
|
||||
Current Feed Entries
|
||||
</DropdownMenuSubTrigger>
|
||||
<DropdownMenuSubContent>
|
||||
<CurrentFeedEntriesPickerList
|
||||
onSelect={(entryId) =>
|
||||
addBlock({
|
||||
type: "referEntry",
|
||||
value: entryId,
|
||||
})
|
||||
}
|
||||
/>
|
||||
</DropdownMenuSubContent>
|
||||
</DropdownMenuSub>
|
||||
<DropdownMenuSeparator />
|
||||
|
||||
<DropdownMenuSub>
|
||||
<DropdownMenuSubTrigger>
|
||||
<i className="i-mgc-paper-cute-fi mr-1.5 size-4" />
|
||||
Reference Entry
|
||||
</DropdownMenuSubTrigger>
|
||||
<DropdownMenuSubContent>
|
||||
<RecentEntriesPickerList
|
||||
onSelect={(entryId) =>
|
||||
addBlock({
|
||||
type: "referEntry",
|
||||
value: entryId,
|
||||
})
|
||||
}
|
||||
/>
|
||||
</DropdownMenuSubContent>
|
||||
</DropdownMenuSub>
|
||||
<DropdownMenuSub>
|
||||
<DropdownMenuSubTrigger>
|
||||
<i className="i-mgc-rss-cute-fi mr-1.5 size-4" />
|
||||
Reference Feed
|
||||
</DropdownMenuSubTrigger>
|
||||
<DropdownMenuSubContent>
|
||||
<FeedPickerList
|
||||
onSelect={(feedId) =>
|
||||
addBlock({
|
||||
type: "referFeed",
|
||||
value: feedId,
|
||||
})
|
||||
}
|
||||
/>
|
||||
</DropdownMenuSubContent>
|
||||
</DropdownMenuSub>
|
||||
</DropdownMenuContent>
|
||||
)
|
||||
|
||||
const shortcutsMenuContent = (
|
||||
<DropdownMenuContent align="start">
|
||||
{enabledShortcuts.length === 0 ? (
|
||||
<div className="text-text-tertiary p-3 text-center text-xs">No shortcuts configured</div>
|
||||
) : (
|
||||
enabledShortcuts.map((shortcut) => (
|
||||
<DropdownMenuItem
|
||||
key={shortcut.id}
|
||||
onClick={() => onSendShortcut?.(shortcut.prompt)}
|
||||
className="text-xs"
|
||||
shortcut={shortcut.hotkey}
|
||||
>
|
||||
<div className="flex w-full items-center justify-between">
|
||||
<div className="flex items-center gap-2">
|
||||
<i className="i-mgc-magic-2-cute-re size-3.5" />
|
||||
<span className="truncate">{shortcut.name}</span>
|
||||
</div>
|
||||
</div>
|
||||
</DropdownMenuItem>
|
||||
))
|
||||
)}
|
||||
</DropdownMenuContent>
|
||||
)
|
||||
|
||||
return (
|
||||
<div className={cn("flex flex-wrap items-center gap-2 px-4 py-3", className)}>
|
||||
{/* Add Context Button */}
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<button
|
||||
type="button"
|
||||
className="bg-fill-secondary hover:bg-fill-tertiary border-border text-text-tertiary hover:text-text-secondary flex size-7 items-center justify-center rounded-md border transition-colors"
|
||||
>
|
||||
<i className="i-mgc-add-cute-re size-3.5" />
|
||||
</button>
|
||||
</DropdownMenuTrigger>
|
||||
{contextMenuContent}
|
||||
</DropdownMenu>
|
||||
|
||||
{/* AI Shortcuts Button */}
|
||||
{enabledShortcuts.length > 0 && (
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<button
|
||||
type="button"
|
||||
className="bg-fill-secondary hover:bg-fill-tertiary border-border text-text-tertiary hover:text-text-secondary flex size-7 items-center justify-center rounded-md border transition-colors"
|
||||
title="AI Shortcuts"
|
||||
>
|
||||
<i className="i-mgc-magic-2-cute-re size-3.5" />
|
||||
</button>
|
||||
</DropdownMenuTrigger>
|
||||
{shortcutsMenuContent}
|
||||
</DropdownMenu>
|
||||
)}
|
||||
|
||||
{/* Context Blocks */}
|
||||
{blocks.map((block) => (
|
||||
<ContextBlock key={block.id} block={block} />
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
},
|
||||
)
|
||||
AIChatContextBar.displayName = "AIChatContextBar"
|
||||
|
||||
// Generic Picker Component
|
||||
interface PickerItem {
|
||||
id: string
|
||||
title: string
|
||||
}
|
||||
|
||||
interface PickerListProps<T extends PickerItem> {
|
||||
items: T[]
|
||||
placeholder: string
|
||||
onSelect: (id: string) => void
|
||||
renderItem?: (item: T, onSelect: (id: string) => void) => React.ReactNode
|
||||
noResultsText?: string
|
||||
}
|
||||
|
||||
const PickerList = <T extends PickerItem>({
|
||||
items,
|
||||
placeholder,
|
||||
onSelect,
|
||||
renderItem,
|
||||
noResultsText = "No items found",
|
||||
}: PickerListProps<T>) => {
|
||||
const [searchTerm, setSearchTerm] = useState("")
|
||||
|
||||
const fuse = useMemo(() => {
|
||||
return new Fuse(items, {
|
||||
keys: ["title", "id"],
|
||||
threshold: 0.3,
|
||||
})
|
||||
}, [items])
|
||||
|
||||
const filteredItems = useMemo(() => {
|
||||
if (!searchTerm) return items
|
||||
const results = fuse.search(searchTerm)
|
||||
return results.map((result) => result.item)
|
||||
}, [items, fuse, searchTerm])
|
||||
|
||||
const debouncedSetSearchTerm = useDebounceCallback(setSearchTerm, 300)
|
||||
|
||||
const defaultRenderItem = (item: T, onSelect: (id: string) => void) => (
|
||||
<DropdownMenuItem key={item.id} onClick={() => onSelect(item.id)} className="text-xs">
|
||||
<span className="truncate">{item.title}</span>
|
||||
</DropdownMenuItem>
|
||||
)
|
||||
|
||||
return (
|
||||
<div className="max-h-64 w-56">
|
||||
<SearchInput
|
||||
placeholder={placeholder}
|
||||
onKeyDown={stopPropagation}
|
||||
onKeyUp={stopPropagation}
|
||||
onChange={(e) => {
|
||||
debouncedSetSearchTerm(e.target.value)
|
||||
}}
|
||||
/>
|
||||
<div className="max-h-48 overflow-y-auto pt-2">
|
||||
{filteredItems.length === 0 ? (
|
||||
<div className="text-text-tertiary p-2 text-xs">{noResultsText}</div>
|
||||
) : (
|
||||
filteredItems.map((item) =>
|
||||
renderItem ? renderItem(item, onSelect) : defaultRenderItem(item, onSelect),
|
||||
)
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const CurrentFeedEntriesPickerList: FC<{ onSelect: (entryId: string) => void }> = ({
|
||||
onSelect,
|
||||
}) => {
|
||||
const mainEntryId = useAIChatStore()((s) => s.state.mainEntryId)
|
||||
const feedId = useEntry(mainEntryId, (e) => e?.feedId)
|
||||
|
||||
const entryIds = useEntryIdsByFeedId(feedId!)
|
||||
|
||||
return <BaseEntryPickerList items={entryIds || []} onSelect={onSelect} />
|
||||
}
|
||||
|
||||
const RecentEntriesPickerList: FC<{ onSelect: (entryId: string) => void }> = ({ onSelect }) => {
|
||||
const view = useRouteParamsSelector((route) => route.view)
|
||||
const recentEntryIds = useEntryIdsByView(view, false)
|
||||
|
||||
return <BaseEntryPickerList items={(recentEntryIds || []).slice(0, 20)} onSelect={onSelect} />
|
||||
}
|
||||
|
||||
const BaseEntryPickerList: FC<{ items: string[]; onSelect: (entryId: string) => void }> = ({
|
||||
items,
|
||||
onSelect,
|
||||
}) => {
|
||||
const entryStore = useEntryStore((state) => state.data)
|
||||
const entries = useMemo(() => {
|
||||
return items
|
||||
.map((entryId) => {
|
||||
const entry = entryStore[entryId]
|
||||
return entry ? { id: entryId, title: entry.title || "Untitled" } : null
|
||||
})
|
||||
.filter(Boolean) as PickerItem[]
|
||||
}, [items, entryStore])
|
||||
|
||||
return (
|
||||
<PickerList
|
||||
items={entries}
|
||||
placeholder="Search entries..."
|
||||
onSelect={onSelect}
|
||||
noResultsText="No entries found"
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
const FeedPickerList: FC<{ onSelect: (feedId: string) => void }> = ({ onSelect }) => {
|
||||
const allSubscriptions = useAllFeedSubscription()
|
||||
|
||||
// Get feeds with their details
|
||||
const feeds = useMemo(() => {
|
||||
return allSubscriptions
|
||||
.filter((subscription) => subscription.feedId)
|
||||
.map((subscription) => {
|
||||
const customTitle = subscription.title
|
||||
|
||||
if (!subscription.feedId) return null
|
||||
const feed = getFeedById(subscription.feedId!)
|
||||
return {
|
||||
id: subscription.feedId!,
|
||||
title: customTitle || feed?.title || `Feed ${subscription.feedId}`,
|
||||
} as PickerItem
|
||||
})
|
||||
.filter(Boolean) as PickerItem[]
|
||||
}, [allSubscriptions])
|
||||
|
||||
return (
|
||||
<PickerList
|
||||
items={feeds}
|
||||
placeholder="Search feeds..."
|
||||
onSelect={onSelect}
|
||||
noResultsText="No feeds found"
|
||||
renderItem={(feed, onSelect) => (
|
||||
<FeedPickerItem key={feed.id} feedId={feed.id} title={feed.title} onSelect={onSelect} />
|
||||
)}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
const SearchInput: FC<React.ComponentProps<"input">> = (props) => {
|
||||
return (
|
||||
<div className="-mx-1 flex items-center border-b py-1">
|
||||
<i className="i-mgc-search-2-cute-re text-text-secondary ml-3 mr-1.5 size-4" />
|
||||
<input
|
||||
type="text"
|
||||
{...props}
|
||||
className="placeholder:text-text-tertiary w-full bg-transparent py-1 pl-0 pr-4 text-xs"
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// Individual Feed Picker Item that shows real feed title
|
||||
const FeedPickerItem: FC<{
|
||||
feedId: string
|
||||
title: string
|
||||
onSelect: (feedId: string) => void
|
||||
}> = ({ feedId, title, onSelect }) => {
|
||||
const feed = useFeedById(feedId, (feed) => ({ title: feed?.title }))
|
||||
const displayTitle = feed?.title || title || "Untitled Feed"
|
||||
|
||||
return (
|
||||
<DropdownMenuItem onClick={() => onSelect(feedId)} className="text-xs">
|
||||
<span className="truncate">{displayTitle}</span>
|
||||
</DropdownMenuItem>
|
||||
)
|
||||
}
|
||||
|
||||
const ContextBlock: FC<{ block: AIChatContextBlock }> = ({ block }) => {
|
||||
const { removeBlock } = useAIChatStore()()
|
||||
|
||||
const getBlockIcon = () => {
|
||||
switch (block.type) {
|
||||
case "mainEntry": {
|
||||
return "i-mgc-star-cute-fi"
|
||||
}
|
||||
case "referEntry": {
|
||||
return "i-mgc-paper-cute-fi"
|
||||
}
|
||||
case "referFeed": {
|
||||
return "i-mgc-rss-cute-fi"
|
||||
}
|
||||
case "selectedText": {
|
||||
return "i-mgc-quill-pen-cute-re"
|
||||
}
|
||||
|
||||
default: {
|
||||
return "i-mgc-paper-cute-fi"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const getDisplayContent = () => {
|
||||
switch (block.type) {
|
||||
case "mainEntry":
|
||||
case "referEntry": {
|
||||
return <EntryTitle entryId={block.value} fallback={block.value} />
|
||||
}
|
||||
case "referFeed": {
|
||||
return <FeedTitle feedId={block.value} fallback={block.value} />
|
||||
}
|
||||
case "selectedText": {
|
||||
return `"${block.value}"`
|
||||
}
|
||||
default: {
|
||||
return block.value
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const getBlockLabel = () => {
|
||||
switch (block.type) {
|
||||
case "mainEntry": {
|
||||
return "Current"
|
||||
}
|
||||
case "referEntry": {
|
||||
return "Ref"
|
||||
}
|
||||
case "referFeed": {
|
||||
return "Feed"
|
||||
}
|
||||
case "selectedText": {
|
||||
return "Text"
|
||||
}
|
||||
|
||||
default: {
|
||||
return ""
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const canRemove = block.type !== "mainEntry"
|
||||
|
||||
return (
|
||||
<div className="bg-fill-tertiary border-border group relative flex h-7 max-w-[calc(50%-0.5rem)] flex-shrink-0 items-center gap-2 rounded-lg border px-2.5">
|
||||
<div className="flex min-w-0 flex-1 items-center gap-1.5">
|
||||
<div className="flex items-center gap-1">
|
||||
<i className={cn("size-3.5 flex-shrink-0", getBlockIcon())} />
|
||||
<span className="text-text-tertiary text-xs font-medium">{getBlockLabel()}</span>
|
||||
</div>
|
||||
|
||||
<span className={cn("text-text min-w-0 flex-1 truncate text-xs")}>
|
||||
{getDisplayContent()}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{canRemove && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => removeBlock(block.id)}
|
||||
className="text-text-tertiary hover:text-text-secondary flex-shrink-0 opacity-0 transition-all group-hover:opacity-100"
|
||||
>
|
||||
<i className="i-mgc-close-cute-re size-3" />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const EntryTitle: FC<{ entryId?: string; fallback: string }> = ({ entryId, fallback }) => {
|
||||
const entryTitle = useEntry(entryId!, (e) => e?.title)
|
||||
|
||||
if (!entryId || !entryTitle) {
|
||||
return <span className="text-text-tertiary">{fallback}</span>
|
||||
}
|
||||
|
||||
return <span>{entryTitle}</span>
|
||||
}
|
||||
|
||||
const FeedTitle: FC<{ feedId?: string; fallback: string }> = ({ feedId, fallback }) => {
|
||||
const feed = useFeedById(feedId, (feed) => ({ title: feed?.title }))
|
||||
if (!feedId || !feed) {
|
||||
return <span className="text-text-tertiary">{fallback}</span>
|
||||
}
|
||||
|
||||
return <span>{feed.title}</span>
|
||||
}
|
||||
@@ -0,0 +1,247 @@
|
||||
import { Chat, useChat } from "@ai-sdk/react"
|
||||
import { env } from "@follow/shared/env.desktop"
|
||||
import type { UIDataTypes, UIMessage } from "ai"
|
||||
import { DefaultChatTransport } from "ai"
|
||||
import type { FC, PropsWithChildren } from "react"
|
||||
import { useCallback, useMemo, useRef } from "react"
|
||||
import { toast } from "sonner"
|
||||
import { useEventCallback } from "usehooks-ts"
|
||||
|
||||
import { Focusable } from "~/components/common/Focusable"
|
||||
import { HotkeyScope } from "~/constants"
|
||||
|
||||
import type { AIChatSessionMethods, AIPanelRefs } from "../__internal__/AIChatContext"
|
||||
import {
|
||||
AIChatContext,
|
||||
AIChatContextStoreContext,
|
||||
AIChatSessionMethodsContext,
|
||||
AIPanelRefsContext,
|
||||
} from "../__internal__/AIChatContext"
|
||||
import { createAIChatContextStore } from "../__internal__/store"
|
||||
import type { BizUIMetadata, BizUITools } from "../__internal__/types"
|
||||
import {
|
||||
useCurrentRoomId,
|
||||
useSessionPersisted,
|
||||
useSetCurrentRoomId,
|
||||
useSetCurrentTitle,
|
||||
useSetSessionPersisted,
|
||||
} from "../atoms/session"
|
||||
import { useChatHistory } from "../hooks/useChatHistory"
|
||||
import { AIPersistService } from "../services"
|
||||
import { generateChatTitle } from "../utils/titleGeneration"
|
||||
|
||||
interface AIChatRootProps extends PropsWithChildren {
|
||||
wrapFocusable?: boolean
|
||||
roomId?: string
|
||||
}
|
||||
|
||||
export const AIChatRoot: FC<AIChatRootProps> = ({
|
||||
children,
|
||||
wrapFocusable = true,
|
||||
roomId: externalRoomId,
|
||||
}) => {
|
||||
const currentRoomId = useCurrentRoomId()
|
||||
const sessionPersisted = useSessionPersisted()
|
||||
const setCurrentRoomId = useSetCurrentRoomId()
|
||||
const setCurrentTitle = useSetCurrentTitle()
|
||||
const setSessionPersisted = useSetSessionPersisted()
|
||||
|
||||
const { createNewSession } = useChatHistory()
|
||||
const useAiContextStore = useMemo(createAIChatContextStore, [])
|
||||
|
||||
// Initialize room ID on mount
|
||||
useMemo(() => {
|
||||
if (!currentRoomId && !externalRoomId) {
|
||||
const newRoomId = createNewSession(false)
|
||||
setCurrentRoomId(newRoomId)
|
||||
} else if (externalRoomId && externalRoomId !== currentRoomId) {
|
||||
setCurrentRoomId(externalRoomId)
|
||||
}
|
||||
}, [currentRoomId, externalRoomId, createNewSession, setCurrentRoomId])
|
||||
|
||||
const handleTitleGenerated = useCallback(
|
||||
async (title: string) => {
|
||||
if (currentRoomId) {
|
||||
try {
|
||||
await AIPersistService.updateSessionTitle(currentRoomId, title)
|
||||
setCurrentTitle(title)
|
||||
} catch (error) {
|
||||
console.error("Failed to update session title:", error)
|
||||
}
|
||||
}
|
||||
},
|
||||
[currentRoomId, setCurrentTitle],
|
||||
)
|
||||
|
||||
const handleFirstMessage = useCallback(async () => {
|
||||
if (!sessionPersisted && currentRoomId) {
|
||||
try {
|
||||
await AIPersistService.createSession(currentRoomId, "New Chat")
|
||||
setSessionPersisted(true)
|
||||
} catch (error) {
|
||||
console.error("Failed to persist session:", error)
|
||||
}
|
||||
}
|
||||
}, [sessionPersisted, currentRoomId, setSessionPersisted])
|
||||
|
||||
// Handle AI response completion - this is where we generate title
|
||||
const handleChatFinish = useEventCallback(
|
||||
async (options: { message: UIMessage<BizUIMetadata, UIDataTypes, BizUITools> }) => {
|
||||
const { message } = options
|
||||
|
||||
// Only trigger title generation for assistant messages (AI responses)
|
||||
if (message.role !== "assistant") return
|
||||
|
||||
// Get current messages to check if this is the first AI response
|
||||
|
||||
const allMessages = chatInstance.messages
|
||||
|
||||
// Check if we have exactly 2 messages (1 user + 1 assistant = first exchange)
|
||||
// Or if we have 2+ messages and this is the first assistant message
|
||||
const assistantMessages = allMessages.filter((m) => m.role === "assistant")
|
||||
const isFirstAIResponse = assistantMessages.length === 1
|
||||
|
||||
if (isFirstAIResponse && allMessages.length >= 2) {
|
||||
try {
|
||||
// Generate title using the first user message and first AI response
|
||||
const firstExchange = allMessages.slice(0, 2)
|
||||
|
||||
const title = await generateChatTitle(firstExchange)
|
||||
|
||||
if (title) {
|
||||
await handleTitleGenerated(title)
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Failed to generate chat title:", error)
|
||||
}
|
||||
}
|
||||
},
|
||||
)
|
||||
const chatInstance = useMemo(() => {
|
||||
return new Chat<UIMessage<BizUIMetadata, UIDataTypes, BizUITools>>({
|
||||
// FIXME: this id can't modify after init, so used a fixed id
|
||||
id: "ai-room",
|
||||
transport: new DefaultChatTransport({
|
||||
api: `${env.VITE_API_URL}/ai/chat`,
|
||||
credentials: "include",
|
||||
fetch: (url: string | Request | URL, options?: RequestInit) => {
|
||||
if (!options?.body) return fetch(url, options)
|
||||
try {
|
||||
const state = useAiContextStore.getState()
|
||||
state.syncBlocksToContext()
|
||||
|
||||
options.body = JSON.stringify({
|
||||
...JSON.parse(options.body as string),
|
||||
context: state.state,
|
||||
blocks: state.blocks,
|
||||
})
|
||||
} catch (error) {
|
||||
console.error(error)
|
||||
}
|
||||
|
||||
return fetch(url, options)
|
||||
},
|
||||
}),
|
||||
onError: (error) => {
|
||||
console.error(error)
|
||||
},
|
||||
onFinish: handleChatFinish,
|
||||
})
|
||||
}, [useAiContextStore, handleChatFinish])
|
||||
|
||||
const ctx = useChat<UIMessage<BizUIMetadata, UIDataTypes, BizUITools>>({
|
||||
chat: chatInstance,
|
||||
})
|
||||
|
||||
const handleNewChat = useCallback(() => {
|
||||
// Create a new session without persistence initially
|
||||
const newRoomId = createNewSession(false)
|
||||
setCurrentRoomId(newRoomId)
|
||||
setSessionPersisted(false)
|
||||
setCurrentTitle(undefined)
|
||||
// Clear messages
|
||||
ctx.setMessages([])
|
||||
}, [createNewSession, ctx, setCurrentRoomId, setSessionPersisted, setCurrentTitle])
|
||||
|
||||
const handleSwitchRoom = useCallback(
|
||||
async (roomId: string) => {
|
||||
try {
|
||||
// First check if we need to save current messages
|
||||
if (sessionPersisted && currentRoomId && ctx.messages.length > 0) {
|
||||
// Messages are automatically saved by useSaveMessages hook
|
||||
}
|
||||
|
||||
// Clear current messages before switching
|
||||
ctx.setMessages([])
|
||||
|
||||
// Switch to new room
|
||||
setCurrentRoomId(roomId)
|
||||
|
||||
// Load session info
|
||||
const sessionData = await AIPersistService.getChatSessions()
|
||||
const session = sessionData.find((s) => s.roomId === roomId)
|
||||
|
||||
if (session) {
|
||||
setCurrentTitle(session.title || "New Chat")
|
||||
setSessionPersisted(true)
|
||||
} else {
|
||||
setCurrentTitle(undefined)
|
||||
setSessionPersisted(false)
|
||||
}
|
||||
|
||||
// Messages will be loaded automatically by useLoadMessages in ChatInterface
|
||||
} catch (error) {
|
||||
console.error("Failed to switch room:", error)
|
||||
toast.error("Failed to switch chat session")
|
||||
}
|
||||
},
|
||||
[sessionPersisted, currentRoomId, ctx, setCurrentRoomId, setCurrentTitle, setSessionPersisted],
|
||||
)
|
||||
|
||||
const panelRef = useRef<HTMLDivElement>(null!)
|
||||
const inputRef = useRef<HTMLTextAreaElement>(null!)
|
||||
const refsContext = useMemo<AIPanelRefs>(() => ({ panelRef, inputRef }), [panelRef, inputRef])
|
||||
|
||||
// Provide session methods through context
|
||||
const sessionMethods = useMemo<AIChatSessionMethods>(
|
||||
() => ({
|
||||
handleTitleGenerated,
|
||||
handleFirstMessage,
|
||||
handleNewChat,
|
||||
handleSwitchRoom,
|
||||
}),
|
||||
[handleTitleGenerated, handleFirstMessage, handleNewChat, handleSwitchRoom],
|
||||
)
|
||||
|
||||
if (!currentRoomId || !ctx) {
|
||||
return (
|
||||
<div className="bg-background flex size-full items-center justify-center">
|
||||
<div className="flex items-center gap-2">
|
||||
<i className="i-mgc-loading-3-cute-re text-text size-6 animate-spin" />
|
||||
<span className="text-text-secondary">Initializing chat...</span>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const Element = (
|
||||
<AIChatContext value={ctx}>
|
||||
<AIPanelRefsContext value={refsContext}>
|
||||
<AIChatContextStoreContext value={useAiContextStore}>
|
||||
<AIChatSessionMethodsContext value={sessionMethods}>
|
||||
{children}
|
||||
</AIChatSessionMethodsContext>
|
||||
</AIChatContextStoreContext>
|
||||
</AIPanelRefsContext>
|
||||
</AIChatContext>
|
||||
)
|
||||
|
||||
if (wrapFocusable) {
|
||||
return (
|
||||
<Focusable scope={HotkeyScope.AIChat} className="size-full">
|
||||
{Element}
|
||||
</Focusable>
|
||||
)
|
||||
}
|
||||
return Element
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
import { Button } from "@follow/components/ui/button/index.js"
|
||||
import { cn } from "@follow/utils"
|
||||
import type { FC } from "react"
|
||||
|
||||
interface AIChatSendButtonProps {
|
||||
onClick: () => void
|
||||
disabled?: boolean
|
||||
isProcessing?: boolean
|
||||
className?: string
|
||||
size?: "sm" | "md"
|
||||
}
|
||||
|
||||
export const AIChatSendButton: FC<AIChatSendButtonProps> = ({
|
||||
onClick,
|
||||
disabled = false,
|
||||
isProcessing = false,
|
||||
className,
|
||||
}) => {
|
||||
return (
|
||||
<Button
|
||||
onClick={onClick}
|
||||
disabled={disabled}
|
||||
buttonClassName={cn(
|
||||
"size-8 rounded-xl p-0 transition-all duration-300 active:scale-95",
|
||||
isProcessing
|
||||
? "bg-red-500/90 hover:bg-red-500 shadow-lg shadow-red-500/25 backdrop-blur-sm"
|
||||
: disabled
|
||||
? "bg-gray-200/80 cursor-not-allowed backdrop-blur-sm"
|
||||
: "bg-gradient-to-r from-blue-500/90 to-blue-600/90 hover:from-blue-500 hover:to-blue-600 shadow-lg shadow-blue-500/25 backdrop-blur-sm hover:shadow-blue-500/35",
|
||||
className,
|
||||
)}
|
||||
>
|
||||
{isProcessing ? (
|
||||
<i className="i-mgc-stop-circle-cute-fi size-4 text-white" />
|
||||
) : (
|
||||
<i className="i-mgc-send-plane-cute-fi size-4 text-white" />
|
||||
)}
|
||||
</Button>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
import { useInputComposition } from "@follow/hooks"
|
||||
import { cn, stopPropagation } from "@follow/utils"
|
||||
import type { VariantProps } from "class-variance-authority"
|
||||
import { cva } from "class-variance-authority"
|
||||
import { memo, use, useCallback, useState } from "react"
|
||||
|
||||
import { AIChatContext, AIPanelRefsContext } from "~/modules/ai/chat/__internal__/AIChatContext"
|
||||
import { AIChatContextBar } from "~/modules/ai/chat/components/AIChatContextBar"
|
||||
import { AIChatSendButton } from "~/modules/ai/chat/components/AIChatSendButton"
|
||||
|
||||
import { CollapsibleError } from "./CollapsibleError"
|
||||
|
||||
const chatInputVariants = cva(
|
||||
[
|
||||
"bg-background/60 focus-within:ring-accent/20 focus-within:border-accent/80 border-border/80",
|
||||
"relative overflow-hidden rounded-2xl border backdrop-blur-xl duration-200 focus-within:ring-2",
|
||||
],
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default: "shadow-2xl shadow-black/5 dark:shadow-zinc-800",
|
||||
minimal: "shadow shadow-zinc-100 dark:shadow-black/5",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: "default",
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
interface ChatInputProps extends VariantProps<typeof chatInputVariants> {
|
||||
onSend: (message: string) => void
|
||||
}
|
||||
|
||||
export const ChatInput = memo(({ onSend, variant }: ChatInputProps) => {
|
||||
const { inputRef } = use(AIPanelRefsContext)
|
||||
const { status, stop, error } = use(AIChatContext)
|
||||
const [isEmpty, setIsEmpty] = useState(true)
|
||||
|
||||
const isProcessing = status === "submitted" || status === "streaming"
|
||||
|
||||
const handleSend = useCallback(() => {
|
||||
if (inputRef.current && inputRef.current.value.trim()) {
|
||||
const message = inputRef.current.value.trim()
|
||||
onSend(message)
|
||||
inputRef.current.value = ""
|
||||
setIsEmpty(true)
|
||||
}
|
||||
}, [onSend, inputRef])
|
||||
const handleKeyPress = useCallback(
|
||||
(e: React.KeyboardEvent) => {
|
||||
if (e.key === "Enter" && !e.shiftKey) {
|
||||
e.preventDefault()
|
||||
if (isProcessing) {
|
||||
stop?.()
|
||||
} else {
|
||||
handleSend()
|
||||
}
|
||||
}
|
||||
},
|
||||
[handleSend, isProcessing, stop],
|
||||
)
|
||||
const inputProps = useInputComposition<HTMLTextAreaElement>({
|
||||
onKeyDown: handleKeyPress,
|
||||
})
|
||||
|
||||
const handleChange = useCallback((e: React.ChangeEvent<HTMLTextAreaElement>) => {
|
||||
setIsEmpty(e.target.value.trim() === "")
|
||||
}, [])
|
||||
|
||||
return (
|
||||
<div className="w-full">
|
||||
{/* Error Display */}
|
||||
{error && <CollapsibleError error={error} />}
|
||||
|
||||
{/* Integrated Input Container with Context Bar */}
|
||||
<div className={cn(chatInputVariants({ variant }))}>
|
||||
{/* Input Area */}
|
||||
<div className="relative z-10 flex items-end">
|
||||
<textarea
|
||||
onContextMenu={stopPropagation}
|
||||
ref={inputRef}
|
||||
onChange={handleChange}
|
||||
{...inputProps}
|
||||
placeholder="Message AI assistant..."
|
||||
className="scrollbar-none text-text placeholder:text-text-secondary max-h-40 min-h-14 w-full resize-none bg-transparent px-5 py-3.5 pr-14 text-sm !outline-none transition-all duration-200"
|
||||
rows={1}
|
||||
autoFocus
|
||||
/>
|
||||
<div className="absolute right-3 top-1/2 -translate-y-1/2">
|
||||
<AIChatSendButton
|
||||
onClick={isProcessing ? stop : handleSend}
|
||||
disabled={!isProcessing && isEmpty}
|
||||
isProcessing={isProcessing}
|
||||
size="sm"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Context Bar - Always shown, positioned below the input area */}
|
||||
<div className="border-border/20 relative z-10 border-t bg-transparent">
|
||||
<AIChatContextBar
|
||||
className="border-0 bg-transparent px-4 py-2.5"
|
||||
onSendShortcut={onSend}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
})
|
||||
|
||||
ChatInput.displayName = "ChatInput"
|
||||
@@ -0,0 +1,100 @@
|
||||
import { Spring } from "@follow/components/constants/spring.js"
|
||||
import { cn } from "@follow/utils"
|
||||
import { m } from "motion/react"
|
||||
import * as React from "react"
|
||||
|
||||
interface CollapsibleErrorProps {
|
||||
error: Error | string
|
||||
title?: string
|
||||
className?: string
|
||||
collapsedHeight?: string
|
||||
icon?: string
|
||||
}
|
||||
|
||||
export const CollapsibleError: React.FC<CollapsibleErrorProps> = ({
|
||||
error,
|
||||
title = "Error occurred",
|
||||
className,
|
||||
collapsedHeight = "48px",
|
||||
icon = "i-mgc-alert-cute-fi",
|
||||
}) => {
|
||||
const [isExpanded, setIsExpanded] = React.useState(false)
|
||||
|
||||
const errorMessage = typeof error === "string" ? error : error.message
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
"animate-in slide-in-from-bottom-2 fade-in-0 group mb-3 duration-300",
|
||||
className,
|
||||
)}
|
||||
onMouseEnter={() => setIsExpanded(true)}
|
||||
onMouseLeave={() => setIsExpanded(false)}
|
||||
>
|
||||
<m.div
|
||||
initial={false}
|
||||
animate={{
|
||||
height: isExpanded ? "auto" : collapsedHeight,
|
||||
}}
|
||||
transition={Spring.presets.snappy}
|
||||
className="overflow-hidden"
|
||||
>
|
||||
<div
|
||||
className={cn(
|
||||
"bg-red/5 border-red/20 shadow-red/5 dark:shadow-red/10 relative overflow-hidden rounded-xl backdrop-blur-2xl transition-all duration-200",
|
||||
"group-hover:bg-red/10 group-hover:border-red/30",
|
||||
)}
|
||||
>
|
||||
{/* Glass effect overlay */}
|
||||
<div className="from-red/5 absolute inset-0 bg-gradient-to-r to-transparent" />
|
||||
|
||||
{/* Collapsed Content */}
|
||||
<div className="relative z-10 flex items-center gap-3 p-3">
|
||||
<m.div
|
||||
animate={{
|
||||
rotate: isExpanded ? 0 : -90,
|
||||
scale: isExpanded ? 1 : 0.8,
|
||||
}}
|
||||
transition={{ duration: 0.2 }}
|
||||
className="bg-red/20 flex size-6 flex-shrink-0 items-center justify-center rounded-full"
|
||||
>
|
||||
<i className={cn(icon, "text-red size-3")} />
|
||||
</m.div>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="text-red text-sm font-medium">{title}</div>
|
||||
</div>
|
||||
<m.span
|
||||
animate={{
|
||||
opacity: isExpanded ? 0 : 1,
|
||||
scale: isExpanded ? 0.8 : 1,
|
||||
}}
|
||||
transition={{ duration: 0.15 }}
|
||||
className="text-text-tertiary text-xs"
|
||||
>
|
||||
hover to expand
|
||||
</m.span>
|
||||
</div>
|
||||
|
||||
{/* Expanded Content */}
|
||||
<m.div
|
||||
animate={{
|
||||
opacity: isExpanded ? 1 : 0,
|
||||
height: isExpanded ? "auto" : 0,
|
||||
}}
|
||||
transition={{
|
||||
duration: 0.2,
|
||||
ease: "easeOut",
|
||||
}}
|
||||
className="overflow-hidden"
|
||||
>
|
||||
<div className="border-red/20 bg-red/5 border-t px-3 pb-3">
|
||||
<div className="text-red/80 bg-red/10 mt-2 rounded-md p-3 text-xs leading-relaxed">
|
||||
{errorMessage}
|
||||
</div>
|
||||
</div>
|
||||
</m.div>
|
||||
</div>
|
||||
</m.div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
+62
@@ -0,0 +1,62 @@
|
||||
import {
|
||||
Accordion,
|
||||
AccordionContent,
|
||||
AccordionItem,
|
||||
AccordionTrigger,
|
||||
} from "@follow/components/ui/accordion/index.js"
|
||||
import type { ToolUIPart } from "ai"
|
||||
import { getToolName } from "ai"
|
||||
import * as React from "react"
|
||||
|
||||
interface ToolInvocationComponentProps {
|
||||
part: ToolUIPart
|
||||
}
|
||||
|
||||
export const ToolInvocationComponent: React.FC<ToolInvocationComponentProps> = ({ part }) => {
|
||||
const toolName = getToolName(part)
|
||||
return (
|
||||
<div className="bg-material-medium border-border size-full min-w-0 max-w-prose rounded-lg border text-left">
|
||||
<div className="w-[9999px] max-w-prose" />
|
||||
<Accordion type="single" collapsible>
|
||||
<AccordionItem value="tool-invocation">
|
||||
<AccordionTrigger className="flex w-full cursor-pointer items-center gap-3 py-1 pl-4 pr-2 hover:no-underline">
|
||||
{/* Tool Info */}
|
||||
<div className="flex h-6 min-w-0 flex-1 items-center">
|
||||
<div className="flex items-center gap-2 text-xs">
|
||||
<i className="i-mingcute-tool-line" />
|
||||
<span className="text-text-secondary">Tool Calling:</span>
|
||||
<h4 className="text-text truncate font-medium">{toolName}</h4>
|
||||
</div>
|
||||
</div>
|
||||
</AccordionTrigger>
|
||||
|
||||
<AccordionContent className="min-w-0 border-t border-zinc-200/50 bg-zinc-50/50 p-4 dark:border-zinc-700/50 dark:bg-zinc-800/50">
|
||||
<div className="space-y-3">
|
||||
{"input" in part && (
|
||||
<div>
|
||||
<div className="text-text-tertiary mb-2 text-xs font-semibold uppercase tracking-wide">
|
||||
Arguments
|
||||
</div>
|
||||
<pre className="text-text-secondary max-h-32 overflow-auto rounded-lg bg-zinc-100/80 p-3 text-xs leading-relaxed dark:bg-zinc-900/80">
|
||||
{JSON.stringify(part.input, null, 2)}
|
||||
</pre>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{"output" in part && (
|
||||
<div>
|
||||
<div className="text-text-tertiary mb-2 text-xs font-semibold uppercase tracking-wide">
|
||||
Result
|
||||
</div>
|
||||
<pre className="text-text max-h-32 overflow-auto rounded-lg bg-zinc-100/80 p-3 text-xs leading-relaxed dark:bg-zinc-900/80">
|
||||
{JSON.stringify(part.output, null, 2)}
|
||||
</pre>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</AccordionContent>
|
||||
</AccordionItem>
|
||||
</Accordion>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
import { m } from "motion/react"
|
||||
import { useTranslation } from "react-i18next"
|
||||
|
||||
import { useAISettingValue } from "~/atoms/settings/ai"
|
||||
import { ChatInput } from "~/modules/ai/chat/components/ChatInput"
|
||||
import { useSettingModal } from "~/modules/settings/modal/use-setting-modal-hack"
|
||||
|
||||
import { AISpline } from "../../AISpline"
|
||||
|
||||
interface WelcomeScreenProps {
|
||||
onSend: (message: string) => void
|
||||
}
|
||||
const DEFAULT_SHORTCUTS = [
|
||||
"Generate today daily report",
|
||||
"Analyze my reading patterns",
|
||||
"Summarize recent articles",
|
||||
"What happened today",
|
||||
]
|
||||
|
||||
export const WelcomeScreen = ({ onSend }: WelcomeScreenProps) => {
|
||||
const { t } = useTranslation("ai")
|
||||
const aiSettings = useAISettingValue()
|
||||
const settingModalPresent = useSettingModal()
|
||||
|
||||
const hasCustomPrompt = aiSettings.personalizePrompt?.trim()
|
||||
const enabledShortcuts = aiSettings.shortcuts?.filter((shortcut) => shortcut.enabled) || []
|
||||
|
||||
return (
|
||||
<div className="flex flex-1 flex-col items-center justify-center px-6">
|
||||
<div className="w-full max-w-2xl space-y-8 text-center">
|
||||
<div className="space-y-6">
|
||||
<div className="mx-auto size-16">
|
||||
<AISpline />
|
||||
</div>
|
||||
<div className="flex flex-col gap-2">
|
||||
<h1 className="text-text text-2xl font-semibold">{APP_NAME} AI</h1>
|
||||
<p className="text-text-secondary text-sm">{t("welcome_description")}</p>
|
||||
{hasCustomPrompt && (
|
||||
<div className="bg-material-medium border-border mx-auto mt-2 w-full max-w-2xl rounded-lg border p-3 text-left">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="text-text-secondary mb-1 text-xs font-medium">
|
||||
Personal Prompt:
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => settingModalPresent("ai")}
|
||||
className="text-text-tertiary hover:text-text-secondary flex size-5 items-center justify-center rounded transition-colors"
|
||||
title="Edit in Settings"
|
||||
>
|
||||
<i className="i-mgc-edit-cute-re size-3.5" />
|
||||
</button>
|
||||
</div>
|
||||
<p className="text-text-secondary text-xs leading-relaxed">
|
||||
{aiSettings.personalizePrompt}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="relative mx-auto max-w-2xl">
|
||||
<ChatInput onSend={onSend} variant="minimal" />
|
||||
</div>
|
||||
|
||||
<div className="flex flex-wrap items-center justify-center gap-2">
|
||||
{/* Custom shortcuts first */}
|
||||
{enabledShortcuts.slice(0, 6).map((shortcut, index) => (
|
||||
<m.button
|
||||
key={shortcut.id}
|
||||
className="bg-material-medium hover:bg-material-thick border-border text-text-secondary hover:text-text whitespace-nowrap rounded-full border px-4 py-2 text-xs transition-colors"
|
||||
initial={{ opacity: 0, scale: 0.9 }}
|
||||
animate={{ opacity: 1, scale: 1 }}
|
||||
transition={{ delay: index * 0.1 }}
|
||||
onClick={() => onSend(shortcut.prompt)}
|
||||
title={shortcut.hotkey ? `${shortcut.name} (${shortcut.hotkey})` : shortcut.name}
|
||||
>
|
||||
{shortcut.name}
|
||||
</m.button>
|
||||
))}
|
||||
|
||||
{/* Default suggestions if no custom shortcuts or to fill remaining space */}
|
||||
{enabledShortcuts.length < 4 &&
|
||||
DEFAULT_SHORTCUTS.slice(0, 4 - enabledShortcuts.length).map((suggestion, index) => (
|
||||
<m.button
|
||||
key={suggestion}
|
||||
className="bg-material-medium hover:bg-material-thick border-border text-text-secondary hover:text-text whitespace-nowrap rounded-full border px-4 py-2 text-xs transition-colors"
|
||||
initial={{ opacity: 0, scale: 0.9 }}
|
||||
animate={{ opacity: 1, scale: 1 }}
|
||||
transition={{ delay: (enabledShortcuts.length + index) * 0.1 }}
|
||||
onClick={() => onSend(suggestion)}
|
||||
>
|
||||
{suggestion}
|
||||
</m.button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@follow/components/ui/card/index.js"
|
||||
|
||||
interface LoadingStateProps {
|
||||
title?: string
|
||||
description?: string
|
||||
maxWidth?: string
|
||||
}
|
||||
|
||||
interface ErrorStateProps {
|
||||
title?: string
|
||||
error?: string
|
||||
maxWidth?: string
|
||||
}
|
||||
|
||||
export const LoadingState = ({
|
||||
title = "Loading...",
|
||||
description = "Fetching data...",
|
||||
maxWidth = "max-w-4xl",
|
||||
}: LoadingStateProps) => (
|
||||
<Card className={`mx-auto mb-2 w-full ${maxWidth}`}>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-text flex items-center gap-2 text-xl font-semibold">
|
||||
<span className="text-lg">⏳</span>
|
||||
<span>{title}</span>
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="bg-material-medium text-text-tertiary flex h-32 animate-pulse items-center justify-center rounded-lg text-sm">
|
||||
{description}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)
|
||||
|
||||
export const ErrorState = ({
|
||||
title = "Error",
|
||||
error = "An error occurred. Please try again.",
|
||||
maxWidth = "max-w-4xl",
|
||||
}: ErrorStateProps) => {
|
||||
return (
|
||||
<Card className={`border-red mx-auto mb-2 w-full ${maxWidth}`}>
|
||||
<CardHeader className="py-4">
|
||||
<CardTitle className="text-red flex items-center gap-2 text-xl font-semibold">
|
||||
<span className="text-lg">⚠️</span>
|
||||
<span>{title}</span>
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="text-text-secondary text-sm">{error}</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)
|
||||
}
|
||||
+312
@@ -0,0 +1,312 @@
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
} from "@follow/components/ui/card/index.js"
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from "@follow/components/ui/table/index.js"
|
||||
import dayjs from "dayjs"
|
||||
|
||||
import type { AIDisplayAnalyticsTool } from "../../__internal__/types"
|
||||
import { ErrorState, LoadingState } from "../common-states"
|
||||
import { ChartPlaceholder, StatCard } from "./shared"
|
||||
|
||||
type AnalyticsData = AIDisplayAnalyticsTool["output"]["analyticsData"]
|
||||
|
||||
const formatTimeRange = (timeRange: string) => {
|
||||
const timeRangeMap = {
|
||||
"7d": "Last 7 days",
|
||||
"30d": "Last 30 days",
|
||||
"90d": "Last 90 days",
|
||||
"1y": "Last year",
|
||||
all: "All time",
|
||||
}
|
||||
return timeRangeMap[timeRange as keyof typeof timeRangeMap] || timeRange
|
||||
}
|
||||
|
||||
const FeedAnalytics = ({ data }: { data: AnalyticsData["feedData"] }) => {
|
||||
if (!data) return null
|
||||
|
||||
const { feed, analytics } = data
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div className="grid grid-cols-1 gap-4 md:grid-cols-3">
|
||||
<StatCard
|
||||
title="Feed Title"
|
||||
value={feed.title || "Untitled Feed"}
|
||||
description={feed.description || ""}
|
||||
emoji="📰"
|
||||
/>
|
||||
<StatCard title="Subscribers" value={analytics?.subscriptionCount || 0} emoji="👥" />
|
||||
<StatCard title="Updates per Week" value={analytics?.updatesPerWeek || 0} emoji="📅" />
|
||||
</div>
|
||||
|
||||
{analytics && (
|
||||
<div className="grid grid-cols-1 gap-4 md:grid-cols-2">
|
||||
<StatCard title="Views" value={analytics.view || 0} emoji="👀" />
|
||||
<StatCard
|
||||
title="Last Checked"
|
||||
value={feed.checkedAt ? dayjs(feed.checkedAt).format("MMM DD, YYYY") : "N/A"}
|
||||
emoji="🔄"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const SubscriptionAnalytics = ({ data }: { data: AnalyticsData["subscriptionStats"] }) => {
|
||||
if (!data?.length) return null
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div className="grid grid-cols-1 gap-4 md:grid-cols-3">
|
||||
<StatCard title="Total Subscriptions" value={data.length} emoji="📊" />
|
||||
<StatCard title="Active Feeds" value={data.filter((s) => s.feed).length} emoji="🟢" />
|
||||
<StatCard
|
||||
title="Average Subscribers"
|
||||
value={Math.round(
|
||||
data.reduce((acc, s) => acc + (s.analytics?.subscriptionCount || 0), 0) / data.length,
|
||||
)}
|
||||
emoji="📈"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-lg">Subscription Details</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Feed</TableHead>
|
||||
<TableHead>Category</TableHead>
|
||||
<TableHead>Subscribers</TableHead>
|
||||
<TableHead>Updates/Week</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{data.slice(0, 10).map((sub) => (
|
||||
<TableRow key={sub.subscription?.userId || sub.feed?.id}>
|
||||
<TableCell className="font-medium">{sub.feed?.title || "Unknown Feed"}</TableCell>
|
||||
<TableCell>{sub.subscription?.category || "No Category"}</TableCell>
|
||||
<TableCell>{sub.analytics?.subscriptionCount || 0}</TableCell>
|
||||
<TableCell>{sub.analytics?.updatesPerWeek || 0}</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
{data.length > 10 && (
|
||||
<div className="text-text-tertiary mt-2 text-sm">
|
||||
Showing 10 of {data.length} subscriptions
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const ReadingAnalytics = ({ data }: { data: AnalyticsData["readingStats"] }) => {
|
||||
if (!data?.length) return null
|
||||
|
||||
const totalReads = data.reduce((acc, stat) => acc + stat.count, 0)
|
||||
const averageReads = Math.round(totalReads / data.length)
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div className="grid grid-cols-1 gap-4 md:grid-cols-3">
|
||||
<StatCard title="Total Reads" value={totalReads} emoji="📖" />
|
||||
<StatCard title="Average Daily Reads" value={averageReads} emoji="📊" />
|
||||
<StatCard title="Active Days" value={data.length} emoji="🗓️" />
|
||||
</div>
|
||||
|
||||
<ChartPlaceholder title="Reading Activity Over Time" data={data} />
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-lg">Recent Reading Activity</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Date</TableHead>
|
||||
<TableHead>Reads</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{data.slice(0, 7).map((stat) => (
|
||||
<TableRow key={stat.date}>
|
||||
<TableCell className="font-medium">
|
||||
{dayjs(stat.date).format("MMM DD, YYYY")}
|
||||
</TableCell>
|
||||
<TableCell>{stat.count}</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const TrendingAnalytics = ({ data }: { data: AnalyticsData["trendingFeeds"] }) => {
|
||||
if (!data?.length) return null
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div className="grid grid-cols-1 gap-4 md:grid-cols-3">
|
||||
<StatCard title="Trending Feeds" value={data.length} emoji="🔥" />
|
||||
<StatCard
|
||||
title="Top Feed Subscribers"
|
||||
value={data[0]?.analytics?.subscriptionCount || 0}
|
||||
description={data[0]?.feed?.title || ""}
|
||||
emoji="👑"
|
||||
/>
|
||||
<StatCard
|
||||
title="Total Views"
|
||||
value={data.reduce((acc, feed) => acc + (feed.analytics?.view || 0), 0)}
|
||||
emoji="👀"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-lg">Trending Feeds</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Feed</TableHead>
|
||||
<TableHead>Subscribers</TableHead>
|
||||
<TableHead>Updates/Week</TableHead>
|
||||
<TableHead>Views</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{data.map((feed) => (
|
||||
<TableRow key={feed.feed?.id}>
|
||||
<TableCell className="font-medium">
|
||||
{feed.feed?.title || "Unknown Feed"}
|
||||
</TableCell>
|
||||
<TableCell>{feed.analytics?.subscriptionCount || 0}</TableCell>
|
||||
<TableCell>{feed.analytics?.updatesPerWeek || 0}</TableCell>
|
||||
<TableCell>{feed.analytics?.view || 0}</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const OverviewAnalytics = ({ data }: { data: AnalyticsData["overviewStats"] }) => {
|
||||
if (!data) return null
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div className="grid grid-cols-1 gap-4 md:grid-cols-3">
|
||||
<StatCard title="Total Feeds" value={data.totalFeeds || 0} emoji="📰" />
|
||||
<StatCard title="Total Subscriptions" value={data.totalSubscriptions || 0} emoji="📊" />
|
||||
<StatCard title="Total Reads" value={data.totalReads || 0} emoji="📖" />
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export const AIDisplayAnalyticsPart = ({ part }: { part: AIDisplayAnalyticsTool }) => {
|
||||
// Handle loading state
|
||||
if (part.state === "input-streaming" || part.state === "input-available") {
|
||||
return (
|
||||
<LoadingState
|
||||
title="Loading Analytics..."
|
||||
description="Fetching analytics data..."
|
||||
maxWidth="max-w-4xl"
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
// Handle error state
|
||||
if (part.state === "output-error") {
|
||||
return (
|
||||
<ErrorState
|
||||
title="Analytics Error"
|
||||
error={
|
||||
typeof part.output === "string"
|
||||
? part.output
|
||||
: "An error occurred while loading analytics"
|
||||
}
|
||||
maxWidth="max-w-4xl"
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
// Handle no output
|
||||
const { output } = part
|
||||
if (!output) {
|
||||
return (
|
||||
<LoadingState
|
||||
title="Loading Analytics..."
|
||||
description="Fetching analytics data..."
|
||||
maxWidth="max-w-4xl"
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
const { analyticsData, analyticsType, timeRange, displayType, title } = output
|
||||
|
||||
const renderAnalytics = () => {
|
||||
switch (analyticsType) {
|
||||
case "feed": {
|
||||
return <FeedAnalytics data={analyticsData.feedData} />
|
||||
}
|
||||
case "subscription": {
|
||||
return <SubscriptionAnalytics data={analyticsData.subscriptionStats} />
|
||||
}
|
||||
case "reading": {
|
||||
return <ReadingAnalytics data={analyticsData.readingStats} />
|
||||
}
|
||||
case "trending": {
|
||||
return <TrendingAnalytics data={analyticsData.trendingFeeds} />
|
||||
}
|
||||
case "overview": {
|
||||
return <OverviewAnalytics data={analyticsData.overviewStats} />
|
||||
}
|
||||
default: {
|
||||
return <div className="text-text-secondary">No analytics data available</div>
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Card className="mx-auto mb-2 w-full max-w-4xl">
|
||||
<CardHeader>
|
||||
<CardTitle className="text-text flex items-center gap-2 text-xl font-semibold">
|
||||
<span className="text-lg">📊</span>
|
||||
<span>
|
||||
{title || `${analyticsType.charAt(0).toUpperCase() + analyticsType.slice(1)} Analytics`}
|
||||
</span>
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
{formatTimeRange(timeRange)} • Display type: {displayType}
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>{renderAnalytics()}</CardContent>
|
||||
</Card>
|
||||
)
|
||||
}
|
||||
+370
@@ -0,0 +1,370 @@
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
} from "@follow/components/ui/card/index.js"
|
||||
import { entrySyncServices } from "@follow/store/entry/store"
|
||||
import dayjs from "dayjs"
|
||||
import { memo } from "react"
|
||||
|
||||
import { usePeekModal } from "~/hooks/biz/usePeekModal"
|
||||
import { FeedIcon } from "~/modules/feed/feed-icon"
|
||||
|
||||
import type { AIDisplayEntriesTool } from "../../__internal__/types"
|
||||
import { ErrorState, LoadingState } from "../common-states"
|
||||
import { CategoryTag, EmptyState, GridContainer, StatCard } from "./shared"
|
||||
|
||||
type EntryData = AIDisplayEntriesTool["output"]["entries"]
|
||||
type EntryItem = EntryData[number]
|
||||
|
||||
interface EntryCardProps {
|
||||
item: EntryItem
|
||||
showSummary: boolean
|
||||
showMetadata: boolean
|
||||
}
|
||||
|
||||
const formatDisplayType = (displayType: string) => {
|
||||
const displayTypeMap = {
|
||||
timeline: "Timeline View",
|
||||
list: "List View",
|
||||
grid: "Grid View",
|
||||
card: "Card View",
|
||||
magazine: "Magazine View",
|
||||
}
|
||||
return displayTypeMap[displayType as keyof typeof displayTypeMap] || displayType
|
||||
}
|
||||
|
||||
const formatGroupBy = (groupBy: string) => {
|
||||
const groupByMap = {
|
||||
date: "By Date",
|
||||
feed: "By Feed",
|
||||
none: "No Grouping",
|
||||
}
|
||||
return groupByMap[groupBy as keyof typeof groupByMap] || groupBy
|
||||
}
|
||||
|
||||
const EntriesGrid = ({
|
||||
data,
|
||||
showSummary,
|
||||
showMetadata,
|
||||
}: {
|
||||
data: EntryData
|
||||
showSummary: boolean
|
||||
showMetadata: boolean
|
||||
}) => {
|
||||
if (!data?.length) {
|
||||
return <EmptyState message="No entries found" />
|
||||
}
|
||||
|
||||
return (
|
||||
<GridContainer
|
||||
columns={{ base: 1, md: 2, lg: 3 }}
|
||||
className="@[600px]:grid-cols-2 @[900px]:grid-cols-3"
|
||||
>
|
||||
{data.map((item) => (
|
||||
<EntryCard
|
||||
key={item.entry.id}
|
||||
item={item}
|
||||
showSummary={showSummary}
|
||||
showMetadata={showMetadata}
|
||||
/>
|
||||
))}
|
||||
</GridContainer>
|
||||
)
|
||||
}
|
||||
|
||||
const EntryCard = memo(({ item, showSummary, showMetadata }: EntryCardProps) => {
|
||||
const peekModal = usePeekModal()
|
||||
return (
|
||||
<Card
|
||||
key={item.entry.id}
|
||||
className="cursor-pointer p-4"
|
||||
onMouseEnter={() => entrySyncServices.fetchEntryDetail(item.entry.id)}
|
||||
onClick={() => peekModal(item.entry.id, "modal")}
|
||||
>
|
||||
<CardHeader className="h-auto px-2 py-3">
|
||||
<div className="flex items-start gap-3">
|
||||
<FeedIcon
|
||||
feed={item.feed ? { ...item.feed, type: "feed" as const } : null}
|
||||
size={32}
|
||||
className="shrink-0"
|
||||
noMargin
|
||||
/>
|
||||
<div className="-mt-1 min-w-0 flex-1">
|
||||
<CardTitle className="line-clamp-2 text-base">
|
||||
{item.entry.title || "Untitled Entry"}
|
||||
</CardTitle>
|
||||
{item.feed?.title && (
|
||||
<CardDescription className="mt-1 text-xs">{item.feed.title}</CardDescription>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</CardHeader>
|
||||
|
||||
<CardContent className="space-y-3 p-0 px-2 pb-3">
|
||||
{showSummary && item.entry.description && (
|
||||
<div className="text-text-secondary line-clamp-3 text-sm">{item.entry.description}</div>
|
||||
)}
|
||||
|
||||
{showMetadata && (
|
||||
<div className="space-y-2">
|
||||
<div className="text-text-secondary text-xs">
|
||||
Published: {dayjs(item.entry.publishedAt).format("MMM DD, YYYY HH:mm")}
|
||||
</div>
|
||||
{item.entry.author && (
|
||||
<div className="text-text-secondary text-xs">By: {item.entry.author}</div>
|
||||
)}
|
||||
{item.entry.categories?.length && (
|
||||
<div className="flex flex-wrap gap-1">
|
||||
{item.entry.categories.slice(0, 3).map((category, index) => (
|
||||
<CategoryTag key={index} category={category} />
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
)
|
||||
})
|
||||
|
||||
const TimelineView = ({
|
||||
data,
|
||||
showSummary,
|
||||
showMetadata,
|
||||
}: {
|
||||
data: EntryData
|
||||
showSummary: boolean
|
||||
showMetadata: boolean
|
||||
}) => {
|
||||
if (!data?.length) {
|
||||
return <EmptyState message="No entries found" />
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{data.map((item) => (
|
||||
<Card key={item.entry.id} className="p-4">
|
||||
<div className="flex gap-4">
|
||||
<FeedIcon
|
||||
feed={item.feed ? { ...item.feed, type: "feed" as const } : null}
|
||||
size={40}
|
||||
className="shrink-0"
|
||||
noMargin
|
||||
/>
|
||||
<div className="min-w-0 flex-1">
|
||||
<CardHeader className="p-0">
|
||||
<CardTitle className="text-text line-clamp-2 text-lg">
|
||||
{item.entry.title || "Untitled Entry"}
|
||||
</CardTitle>
|
||||
<CardDescription className="flex items-center gap-2 text-sm">
|
||||
{item.feed?.title && <span>{item.feed.title}</span>}
|
||||
<span>•</span>
|
||||
<span>{dayjs(item.entry.publishedAt).format("MMM DD, YYYY HH:mm")}</span>
|
||||
{item.entry.author && (
|
||||
<>
|
||||
<span>•</span>
|
||||
<span>By {item.entry.author}</span>
|
||||
</>
|
||||
)}
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
|
||||
<CardContent className="mt-3 p-0">
|
||||
{showSummary && item.entry.description && (
|
||||
<div className="text-text-secondary mb-3 line-clamp-2">
|
||||
{item.entry.description}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{showMetadata && item.entry.categories?.length && (
|
||||
<div className="flex flex-wrap gap-1">
|
||||
{item.entry.categories.slice(0, 5).map((category, index) => (
|
||||
<CategoryTag key={index} category={category} />
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</div>
|
||||
</div>
|
||||
</Card>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const GroupedEntries = ({
|
||||
data,
|
||||
groupBy,
|
||||
displayType,
|
||||
showSummary,
|
||||
showMetadata,
|
||||
}: {
|
||||
data: EntryData
|
||||
groupBy: string
|
||||
displayType: string
|
||||
showSummary: boolean
|
||||
showMetadata: boolean
|
||||
}) => {
|
||||
if (!data?.length || groupBy === "none") {
|
||||
return null
|
||||
}
|
||||
|
||||
const groups = data.reduce(
|
||||
(acc, item) => {
|
||||
let key: string
|
||||
if (groupBy === "date") {
|
||||
key = dayjs(item.entry.publishedAt).format("YYYY-MM-DD")
|
||||
} else if (groupBy === "feed") {
|
||||
key = item.feed?.title || "Unknown Feed"
|
||||
} else {
|
||||
key = "All"
|
||||
}
|
||||
|
||||
if (!acc[key]) acc[key] = []
|
||||
acc[key]?.push(item)
|
||||
return acc
|
||||
},
|
||||
{} as Record<string, EntryData>,
|
||||
)
|
||||
|
||||
const renderGroup = (groupData: EntryData) => {
|
||||
switch (displayType) {
|
||||
case "timeline": {
|
||||
return (
|
||||
<TimelineView data={groupData} showSummary={showSummary} showMetadata={showMetadata} />
|
||||
)
|
||||
}
|
||||
default: {
|
||||
return (
|
||||
<EntriesGrid data={groupData} showSummary={showSummary} showMetadata={showMetadata} />
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{Object.entries(groups)
|
||||
.sort(([a], [b]) => {
|
||||
if (groupBy === "date") {
|
||||
return dayjs(b).isAfter(dayjs(a)) ? 1 : -1
|
||||
}
|
||||
return a.localeCompare(b)
|
||||
})
|
||||
.map(([groupName, groupData]) => (
|
||||
<div key={groupName}>
|
||||
<h3 className="text-text mb-4 text-lg font-semibold">
|
||||
{groupBy === "date" ? dayjs(groupName).format("MMMM DD, YYYY") : groupName}
|
||||
</h3>
|
||||
{renderGroup(groupData)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export const AIDisplayEntriesPart = ({ part }: { part: AIDisplayEntriesTool }) => {
|
||||
// Handle loading state
|
||||
if (part.state === "input-streaming" || part.state === "input-available") {
|
||||
return (
|
||||
<LoadingState
|
||||
title="Loading Entries..."
|
||||
description="Fetching entry data..."
|
||||
maxWidth="max-w-6xl"
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
// Handle error state
|
||||
if (part.state === "output-error") {
|
||||
return (
|
||||
<ErrorState
|
||||
title="Entries Error"
|
||||
error="An error occurred while loading entries"
|
||||
maxWidth="max-w-6xl"
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
// Handle no output or invalid state
|
||||
if (part.state !== "output-available" || !part.output) {
|
||||
return (
|
||||
<LoadingState
|
||||
title="Loading Entries..."
|
||||
description="Fetching entry data..."
|
||||
maxWidth="max-w-6xl"
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
// Extract output with proper typing
|
||||
const output = part.output as NonNullable<AIDisplayEntriesTool["output"]>
|
||||
|
||||
const {
|
||||
entries,
|
||||
displayType = "grid",
|
||||
showSummary = true,
|
||||
showMetadata = true,
|
||||
title,
|
||||
groupBy = "none",
|
||||
} = output
|
||||
|
||||
// Calculate statistics
|
||||
const totalEntries = entries.length
|
||||
const feedsCount = new Set(entries.map((e) => e.entry.feedId)).size
|
||||
const authorsCount = new Set(entries.map((e) => e.entry.author).filter(Boolean)).size
|
||||
const categoriesCount = new Set(entries.flatMap((e) => e.entry.categories || [])).size
|
||||
|
||||
const renderEntries = () => {
|
||||
if (groupBy !== "none") {
|
||||
return (
|
||||
<GroupedEntries
|
||||
data={entries}
|
||||
groupBy={groupBy}
|
||||
displayType={displayType}
|
||||
showSummary={showSummary}
|
||||
showMetadata={showMetadata}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
switch (displayType) {
|
||||
case "timeline": {
|
||||
return <TimelineView data={entries} showSummary={showSummary} showMetadata={showMetadata} />
|
||||
}
|
||||
default: {
|
||||
return <EntriesGrid data={entries} showSummary={showSummary} showMetadata={showMetadata} />
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Card className="mb-2 w-full min-w-0">
|
||||
<div className="w-[9999px]" />
|
||||
<CardHeader>
|
||||
<CardTitle className="text-text flex items-center gap-2 text-xl font-semibold">
|
||||
<span className="text-lg">📰</span>
|
||||
<span>{title || "Entries"}</span>
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
{formatDisplayType(displayType)} • {formatGroupBy(groupBy)} • {totalEntries} entries
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="@container space-y-6">
|
||||
{/* Statistics Overview */}
|
||||
<GridContainer columns={{ base: 2, md: 4 }} className="@[600px]:grid-cols-4">
|
||||
<StatCard title="Total Entries" value={totalEntries} emoji="📄" />
|
||||
<StatCard title="Feeds" value={feedsCount} emoji="📡" />
|
||||
<StatCard title="Authors" value={authorsCount} emoji="✍️" />
|
||||
<StatCard title="Categories" value={categoriesCount} emoji="🏷️" />
|
||||
</GridContainer>
|
||||
|
||||
{/* Entries Display */}
|
||||
{renderEntries()}
|
||||
</CardContent>
|
||||
</Card>
|
||||
)
|
||||
}
|
||||
+173
@@ -0,0 +1,173 @@
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
} from "@follow/components/ui/card/index.js"
|
||||
import dayjs from "dayjs"
|
||||
|
||||
import { FeedIcon } from "~/modules/feed/feed-icon"
|
||||
|
||||
import type { AIDisplayFeedsTool } from "../../__internal__/types"
|
||||
import { ErrorState, LoadingState } from "../common-states"
|
||||
import { AnalyticsMetrics, EmptyState, GridContainer, StatCard } from "./shared"
|
||||
|
||||
type FeedData = AIDisplayFeedsTool["output"]["feeds"]
|
||||
|
||||
const FeedsGrid = ({ data, showAnalytics }: { data: FeedData; showAnalytics: boolean }) => {
|
||||
if (!data?.length) {
|
||||
return <EmptyState message="No feeds found" />
|
||||
}
|
||||
|
||||
return (
|
||||
<GridContainer columns={{ base: 2, md: 3 }} className="@[600px]:grid-cols-3">
|
||||
{data.map((item) => (
|
||||
<Card key={item.feed.id} className="p-4">
|
||||
<CardHeader className="h-24 px-2 py-3">
|
||||
<div className="flex items-start gap-3">
|
||||
<FeedIcon
|
||||
feed={item.feed ? { ...item.feed, type: "feed" as const } : null}
|
||||
size={32}
|
||||
className="shrink-0"
|
||||
noMargin
|
||||
/>
|
||||
<div className="-mt-1 min-w-0 flex-1">
|
||||
<CardTitle className="line-clamp-2 text-base">
|
||||
{item.feed.title || "Unknown Feed"}
|
||||
</CardTitle>
|
||||
{item.feed.description && (
|
||||
<CardDescription className="mt-1 line-clamp-2 text-xs">
|
||||
{item.feed.description}
|
||||
</CardDescription>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</CardHeader>
|
||||
|
||||
<CardContent className="space-y-3 p-0 px-2 pb-3">
|
||||
{item.feed.errorMessage && (
|
||||
<div className="bg-red/10 text-red rounded px-2 py-1 text-xs">
|
||||
Error: {item.feed.errorMessage}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="text-text-secondary text-xs">
|
||||
Last checked: {dayjs(item.feed.checkedAt).format("MMM DD, YYYY HH:mm")}
|
||||
</div>
|
||||
|
||||
{item.feed.language && (
|
||||
<div className="text-text-secondary text-xs">Language: {item.feed.language}</div>
|
||||
)}
|
||||
|
||||
{showAnalytics && item.analytics && (
|
||||
<AnalyticsMetrics
|
||||
metrics={[
|
||||
{ label: "Updates/Week", value: item.analytics.updatesPerWeek || 0 },
|
||||
{ label: "Subscribers", value: item.analytics.subscriptionCount || 0 },
|
||||
{ label: "Views", value: item.analytics.view || 0 },
|
||||
]}
|
||||
/>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
))}
|
||||
</GridContainer>
|
||||
)
|
||||
}
|
||||
|
||||
export const AIDisplayFeedsPart = ({ part }: { part: AIDisplayFeedsTool }) => {
|
||||
// Handle loading state
|
||||
if (part.state === "input-streaming" || part.state === "input-available") {
|
||||
return (
|
||||
<LoadingState
|
||||
title="Loading Feeds..."
|
||||
description="Fetching feed data..."
|
||||
maxWidth="max-w-6xl"
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
// Handle error state
|
||||
if (part.state === "output-error") {
|
||||
return (
|
||||
<ErrorState
|
||||
title="Feeds Error"
|
||||
error="An error occurred while loading feeds"
|
||||
maxWidth="max-w-6xl"
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
// Handle no output or invalid state
|
||||
if (part.state !== "output-available" || !part.output) {
|
||||
return (
|
||||
<LoadingState
|
||||
title="Loading Feeds..."
|
||||
description="Fetching feed data..."
|
||||
maxWidth="max-w-6xl"
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
// Extract output with proper typing
|
||||
const output = part.output as NonNullable<AIDisplayFeedsTool["output"]>
|
||||
|
||||
const { feeds, displayType = "list", showAnalytics = true, title } = output
|
||||
|
||||
// Calculate statistics
|
||||
const totalFeeds = feeds.length
|
||||
const activeFeeds = feeds.filter((f) => !f.feed.errorMessage).length
|
||||
const errorFeeds = feeds.filter((f) => f.feed.errorMessage).length
|
||||
const totalSubscriptions = feeds.reduce(
|
||||
(acc, f) => acc + (f.analytics?.subscriptionCount || 0),
|
||||
0,
|
||||
)
|
||||
const totalViews = feeds.reduce((acc, f) => acc + (f.analytics?.view || 0), 0)
|
||||
|
||||
const renderFeeds = () => {
|
||||
switch (displayType) {
|
||||
default: {
|
||||
return <FeedsGrid data={feeds} showAnalytics={showAnalytics} />
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Card className="mb-2 w-full min-w-0">
|
||||
<div className="w-[9999px]" />
|
||||
<CardHeader>
|
||||
<CardTitle className="text-text flex items-center gap-2 text-xl font-semibold">
|
||||
<span className="text-lg">📡</span>
|
||||
<span>{title || "RSS Feeds"}</span>
|
||||
</CardTitle>
|
||||
<CardDescription>{totalFeeds} feeds</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="@container space-y-6">
|
||||
{/* Statistics Overview */}
|
||||
<GridContainer columns={{ base: 2, md: 4 }} className="@[600px]:grid-cols-4">
|
||||
<StatCard title="Total Feeds" value={totalFeeds} emoji="📊" />
|
||||
<StatCard
|
||||
title="Active Feeds"
|
||||
value={activeFeeds}
|
||||
description={`${errorFeeds} with errors`}
|
||||
emoji="🟢"
|
||||
/>
|
||||
{showAnalytics && (
|
||||
<>
|
||||
<StatCard
|
||||
title="Total Subscribers"
|
||||
value={totalSubscriptions.toLocaleString()}
|
||||
emoji="👥"
|
||||
/>
|
||||
<StatCard title="Total Views" value={totalViews.toLocaleString()} emoji="👀" />
|
||||
</>
|
||||
)}
|
||||
</GridContainer>
|
||||
|
||||
{/* Feeds Display */}
|
||||
{renderFeeds()}
|
||||
</CardContent>
|
||||
</Card>
|
||||
)
|
||||
}
|
||||
+286
@@ -0,0 +1,286 @@
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
} from "@follow/components/ui/card/index.js"
|
||||
import dayjs from "dayjs"
|
||||
|
||||
import { FeedIcon } from "~/modules/feed/feed-icon"
|
||||
|
||||
import type { AIDisplaySubscriptionsTool } from "../../__internal__/types"
|
||||
import { ErrorState, LoadingState } from "../common-states"
|
||||
import { AnalyticsMetrics, CategoryTag, EmptyState, GridContainer, StatCard } from "./shared"
|
||||
|
||||
type SubscriptionData = AIDisplaySubscriptionsTool["output"]["subscriptions"]
|
||||
|
||||
const formatDisplayType = (displayType: string) => {
|
||||
const displayTypeMap = {
|
||||
list: "List View",
|
||||
grid: "Grid View",
|
||||
card: "Card View",
|
||||
compact: "Compact View",
|
||||
}
|
||||
return displayTypeMap[displayType as keyof typeof displayTypeMap] || displayType
|
||||
}
|
||||
|
||||
const formatGroupBy = (groupBy: string) => {
|
||||
const groupByMap = {
|
||||
category: "By Category",
|
||||
status: "By Status",
|
||||
none: "No Grouping",
|
||||
}
|
||||
return groupByMap[groupBy as keyof typeof groupByMap] || groupBy
|
||||
}
|
||||
|
||||
const formatFilterBy = (filterBy: string) => {
|
||||
const filterByMap = {
|
||||
all: "All Subscriptions",
|
||||
active: "Active Only",
|
||||
inactive: "Inactive Only",
|
||||
recent: "Recent (30 days)",
|
||||
}
|
||||
return filterByMap[filterBy as keyof typeof filterByMap] || filterBy
|
||||
}
|
||||
|
||||
const SubscriptionsGrid = ({
|
||||
data,
|
||||
showAnalytics,
|
||||
showCategories,
|
||||
}: {
|
||||
data: SubscriptionData
|
||||
showAnalytics: boolean
|
||||
showCategories: boolean
|
||||
}) => {
|
||||
if (!data?.length) {
|
||||
return <EmptyState message="No subscriptions found" />
|
||||
}
|
||||
|
||||
return (
|
||||
<GridContainer columns={{ base: 2, md: 3 }} className="@[600px]:grid-cols-3">
|
||||
{data.map((sub) => (
|
||||
<Card key={`${sub.subscription?.userId}-${sub.subscription?.feedId}`} className="p-4">
|
||||
<CardHeader className="h-24 px-2 py-3">
|
||||
<div className="flex items-start gap-3">
|
||||
<FeedIcon
|
||||
feed={sub.feed ? { ...sub.feed, type: "feed" as const } : null}
|
||||
size={32}
|
||||
className="shrink-0"
|
||||
noMargin
|
||||
/>
|
||||
<div className="-mt-1 min-w-0 flex-1">
|
||||
<CardTitle className="line-clamp-2 text-base">
|
||||
{sub.feed?.title || sub.subscription?.title || "Unknown Feed"}
|
||||
</CardTitle>
|
||||
{sub.feed?.description && (
|
||||
<CardDescription className="mt-1 line-clamp-2 text-xs">
|
||||
{sub.feed.description}
|
||||
</CardDescription>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</CardHeader>
|
||||
|
||||
<CardContent className="space-y-3 p-0 px-2 pb-3">
|
||||
{showCategories && sub.subscription?.category && (
|
||||
<div>
|
||||
<CategoryTag category={sub.subscription.category} />
|
||||
</div>
|
||||
)}
|
||||
<div className="text-text-secondary text-xs">
|
||||
Subscribed:{" "}
|
||||
{sub.subscription?.createdAt
|
||||
? dayjs(sub.subscription.createdAt).format("MMM DD, YYYY")
|
||||
: "Unknown"}
|
||||
</div>
|
||||
{showAnalytics && (
|
||||
<AnalyticsMetrics
|
||||
metrics={[
|
||||
{ label: "Updates/Week", value: sub.analytics?.updatesPerWeek || 0 },
|
||||
{ label: "Views", value: sub.analytics?.view || sub.subscription?.view || 0 },
|
||||
]}
|
||||
/>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
))}
|
||||
</GridContainer>
|
||||
)
|
||||
}
|
||||
|
||||
const GroupedSubscriptions = ({
|
||||
data,
|
||||
groupBy,
|
||||
displayType,
|
||||
showAnalytics,
|
||||
showCategories,
|
||||
}: {
|
||||
data: SubscriptionData
|
||||
groupBy: string
|
||||
displayType: string
|
||||
showAnalytics: boolean
|
||||
showCategories: boolean
|
||||
}) => {
|
||||
if (!data?.length || groupBy === "none") {
|
||||
return null
|
||||
}
|
||||
|
||||
const groups = data.reduce(
|
||||
(acc, sub) => {
|
||||
let key: string
|
||||
if (groupBy === "category") {
|
||||
key = sub.subscription?.category || "No Category"
|
||||
} else if (groupBy === "status") {
|
||||
// Simple status based on error state
|
||||
key = sub.feed?.errorMessage ? "Inactive" : "Active"
|
||||
} else {
|
||||
key = "All"
|
||||
}
|
||||
|
||||
if (!acc[key]) acc[key] = []
|
||||
acc[key]?.push(sub)
|
||||
return acc
|
||||
},
|
||||
{} as Record<string, SubscriptionData>,
|
||||
)
|
||||
|
||||
const renderGroup = (groupData: SubscriptionData) => {
|
||||
switch (displayType) {
|
||||
default: {
|
||||
return (
|
||||
<SubscriptionsGrid
|
||||
data={groupData}
|
||||
showAnalytics={showAnalytics}
|
||||
showCategories={showCategories}
|
||||
/>
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{Object.entries(groups).map(([groupName, groupData]) => (
|
||||
<div key={groupName}>
|
||||
<h3 className="text-text mb-4 text-lg font-semibold">{groupName}</h3>
|
||||
{renderGroup(groupData)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export const AIDisplaySubscriptionsPart = ({ part }: { part: AIDisplaySubscriptionsTool }) => {
|
||||
// Handle loading state
|
||||
if (part.state === "input-streaming" || part.state === "input-available") {
|
||||
return (
|
||||
<LoadingState
|
||||
title="Loading Subscriptions..."
|
||||
description="Fetching subscription data..."
|
||||
maxWidth="max-w-6xl"
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
// Handle error state
|
||||
if (part.state === "output-error") {
|
||||
return (
|
||||
<ErrorState
|
||||
title="Subscriptions Error"
|
||||
error="An error occurred while loading subscriptions"
|
||||
maxWidth="max-w-6xl"
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
// Handle no output or invalid state
|
||||
if (part.state !== "output-available" || !part.output) {
|
||||
return (
|
||||
<LoadingState
|
||||
title="Loading Subscriptions..."
|
||||
description="Fetching subscription data..."
|
||||
maxWidth="max-w-6xl"
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
// Extract output with proper typing
|
||||
const output = part.output as NonNullable<AIDisplaySubscriptionsTool["output"]>
|
||||
|
||||
const {
|
||||
subscriptions,
|
||||
displayType = "list",
|
||||
showAnalytics = true,
|
||||
showCategories = true,
|
||||
title,
|
||||
groupBy = "none",
|
||||
filterBy = "all",
|
||||
} = output
|
||||
|
||||
// Calculate statistics
|
||||
const totalSubscriptions = subscriptions.length
|
||||
const categoriesCount = new Set(
|
||||
subscriptions.map((s) => s.subscription?.category).filter(Boolean),
|
||||
).size
|
||||
const activeSubscriptions = subscriptions.filter((s) => !s.feed?.errorMessage).length
|
||||
const totalViews = subscriptions.reduce((acc, s) => acc + (s.subscription?.view || 0), 0)
|
||||
|
||||
const renderSubscriptions = () => {
|
||||
if (groupBy !== "none") {
|
||||
return (
|
||||
<GroupedSubscriptions
|
||||
data={subscriptions}
|
||||
groupBy={groupBy}
|
||||
displayType={displayType}
|
||||
showAnalytics={showAnalytics}
|
||||
showCategories={showCategories}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
switch (displayType) {
|
||||
default: {
|
||||
return (
|
||||
<SubscriptionsGrid
|
||||
data={subscriptions}
|
||||
showAnalytics={showAnalytics}
|
||||
showCategories={showCategories}
|
||||
/>
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Card className="mb-2 w-full min-w-0">
|
||||
<div className="w-[9999px]" />
|
||||
<CardHeader>
|
||||
<CardTitle className="text-text flex items-center gap-2 text-xl font-semibold">
|
||||
<span className="text-lg">📋</span>
|
||||
<span>{title || "My Subscriptions"}</span>
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
{formatDisplayType(displayType)} • {formatFilterBy(filterBy)} • {formatGroupBy(groupBy)}
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="@container space-y-6">
|
||||
{/* Statistics Overview */}
|
||||
<GridContainer columns={{ base: 2, md: 4 }} className="@[600px]:grid-cols-4">
|
||||
<StatCard title="Total Subscriptions" value={totalSubscriptions} emoji="📊" />
|
||||
<StatCard
|
||||
title="Active Feeds"
|
||||
value={activeSubscriptions}
|
||||
description={`${totalSubscriptions - activeSubscriptions} inactive`}
|
||||
emoji="🟢"
|
||||
/>
|
||||
{showCategories && <StatCard title="Categories" value={categoriesCount} emoji="🏷️" />}
|
||||
<StatCard title="Total Views" value={totalViews.toLocaleString()} emoji="👀" />
|
||||
</GridContainer>
|
||||
|
||||
{/* Subscriptions Display */}
|
||||
{renderSubscriptions()}
|
||||
</CardContent>
|
||||
</Card>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
export { AIDisplayAnalyticsPart } from "./AIDisplayAnalyticsPart"
|
||||
export { AIDisplayEntriesPart } from "./AIDisplayEntriesPart"
|
||||
export { AIDisplayFeedsPart } from "./AIDisplayFeedsPart"
|
||||
export { AIDisplaySubscriptionsPart } from "./AIDisplaySubscriptionsPart"
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
import { cn } from "@follow/utils/utils"
|
||||
|
||||
export interface AnalyticsMetric {
|
||||
label: string
|
||||
value: string | number
|
||||
}
|
||||
|
||||
export interface AnalyticsMetricsProps {
|
||||
metrics: AnalyticsMetric[]
|
||||
className?: string
|
||||
}
|
||||
|
||||
export const AnalyticsMetrics = ({ metrics, className }: AnalyticsMetricsProps) => (
|
||||
<ul className={cn("space-y-1 text-xs", className)}>
|
||||
{metrics.map((metric, index) => (
|
||||
<li key={index} className="flex items-center justify-between">
|
||||
<span className="text-text-tertiary">{metric.label}</span>
|
||||
<span className="text-text font-medium">{metric.value}</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
import { cn } from "@follow/utils/utils"
|
||||
|
||||
export interface CategoryTagProps {
|
||||
category: string
|
||||
variant?: "default" | "small"
|
||||
className?: string
|
||||
}
|
||||
|
||||
export const CategoryTag = ({ category, variant = "default", className }: CategoryTagProps) => (
|
||||
<span
|
||||
className={cn(
|
||||
"bg-fill-tertiary text-text-secondary rounded px-2 py-1 text-xs",
|
||||
variant === "small" && "px-1 py-0.5 text-xs",
|
||||
className,
|
||||
)}
|
||||
>
|
||||
{category}
|
||||
</span>
|
||||
)
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@follow/components/ui/card/index.js"
|
||||
import { cn } from "@follow/utils/utils"
|
||||
|
||||
export interface ChartPlaceholderProps {
|
||||
title: string
|
||||
data: any[]
|
||||
height?: string
|
||||
className?: string
|
||||
}
|
||||
|
||||
export const ChartPlaceholder = ({
|
||||
title,
|
||||
data,
|
||||
height = "h-32",
|
||||
className,
|
||||
}: ChartPlaceholderProps) => (
|
||||
<Card className={cn("p-4", className)}>
|
||||
<CardHeader className="pb-2">
|
||||
<CardTitle className="text-text-secondary text-sm font-medium">{title}</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="pt-0">
|
||||
<div
|
||||
className={cn(
|
||||
"bg-material-medium text-text-tertiary flex items-center justify-center rounded-lg text-sm",
|
||||
height,
|
||||
)}
|
||||
>
|
||||
Chart visualization ({data.length} data points)
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
import { CardDescription, CardHeader, CardTitle } from "@follow/components/ui/card/index.js"
|
||||
import type { ReactNode } from "react"
|
||||
|
||||
export interface DisplayHeaderProps {
|
||||
title: string
|
||||
emoji: string
|
||||
description?: string
|
||||
children?: ReactNode
|
||||
}
|
||||
|
||||
export const DisplayHeader = ({ title, emoji, description, children }: DisplayHeaderProps) => (
|
||||
<CardHeader>
|
||||
<CardTitle className="text-text flex items-center gap-2 text-xl font-semibold">
|
||||
<span className="text-lg">{emoji}</span>
|
||||
<span>{title}</span>
|
||||
</CardTitle>
|
||||
{description && <CardDescription>{description}</CardDescription>}
|
||||
{children}
|
||||
</CardHeader>
|
||||
)
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
import { cn } from "@follow/utils/utils"
|
||||
|
||||
export interface EmptyStateProps {
|
||||
message: string
|
||||
icon?: string
|
||||
className?: string
|
||||
}
|
||||
|
||||
export const EmptyState = ({ message, icon, className }: EmptyStateProps) => (
|
||||
<div className={cn("text-text-secondary text-center text-sm", className)}>
|
||||
{icon && <span className="text-lg">{icon}</span>}
|
||||
{message}
|
||||
</div>
|
||||
)
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
} from "@follow/components/ui/card/index.js"
|
||||
import { cn } from "@follow/utils/utils"
|
||||
import type { ReactNode } from "react"
|
||||
|
||||
export interface FeedItemCardProps {
|
||||
title: string
|
||||
description?: string
|
||||
icon?: ReactNode
|
||||
headerHeight?: string
|
||||
className?: string
|
||||
children?: ReactNode
|
||||
}
|
||||
|
||||
export const FeedItemCard = ({
|
||||
title,
|
||||
description,
|
||||
icon,
|
||||
headerHeight = "h-24",
|
||||
className,
|
||||
children,
|
||||
}: FeedItemCardProps) => (
|
||||
<Card className={cn("p-4", className)}>
|
||||
<CardHeader className={cn("px-2 py-3", headerHeight)}>
|
||||
<div className="flex items-start gap-3">
|
||||
{icon && <div className="shrink-0">{icon}</div>}
|
||||
<div className="-mt-1 min-w-0 flex-1">
|
||||
<CardTitle className="line-clamp-2 text-base">{title}</CardTitle>
|
||||
{description && (
|
||||
<CardDescription className="mt-1 line-clamp-2 text-xs">{description}</CardDescription>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</CardHeader>
|
||||
{children && <CardContent className="space-y-3 p-0 px-2 pb-3">{children}</CardContent>}
|
||||
</Card>
|
||||
)
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
import { cn } from "@follow/utils/utils"
|
||||
import type { ReactNode } from "react"
|
||||
|
||||
export interface GridContainerProps {
|
||||
columns?: {
|
||||
base: number
|
||||
md: number
|
||||
lg?: number
|
||||
}
|
||||
gap?: number
|
||||
children: ReactNode
|
||||
className?: string
|
||||
}
|
||||
|
||||
export const GridContainer = ({
|
||||
columns = { base: 1, md: 2 },
|
||||
gap = 4,
|
||||
children,
|
||||
className,
|
||||
}: GridContainerProps) => (
|
||||
<div
|
||||
className={cn(
|
||||
"grid",
|
||||
`grid-cols-${columns.base}`,
|
||||
`md:grid-cols-${columns.md}`,
|
||||
columns.lg && `lg:grid-cols-${columns.lg}`,
|
||||
`gap-${gap}`,
|
||||
className,
|
||||
)}
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
)
|
||||
+53
@@ -0,0 +1,53 @@
|
||||
import type { ReactNode } from "react"
|
||||
|
||||
export interface GroupedContentProps<T> {
|
||||
data: T[]
|
||||
groupBy: string
|
||||
groupKeyExtractor: (item: T) => string
|
||||
renderGroup: (groupData: T[], groupName: string) => ReactNode
|
||||
sortGroups?: (a: string, b: string) => number
|
||||
className?: string
|
||||
}
|
||||
|
||||
export const GroupedContent = <T,>({
|
||||
data,
|
||||
groupBy,
|
||||
groupKeyExtractor,
|
||||
renderGroup,
|
||||
sortGroups,
|
||||
className,
|
||||
}: GroupedContentProps<T>) => {
|
||||
if (!data?.length || groupBy === "none") {
|
||||
return null
|
||||
}
|
||||
|
||||
const groups = data.reduce(
|
||||
(acc, item) => {
|
||||
const key = groupKeyExtractor(item)
|
||||
if (!acc[key]) acc[key] = []
|
||||
acc[key]?.push(item)
|
||||
return acc
|
||||
},
|
||||
{} as Record<string, T[]>,
|
||||
)
|
||||
|
||||
const sortedEntries = Object.entries(groups).sort(([a], [b]) => {
|
||||
if (sortGroups) {
|
||||
return sortGroups(a, b)
|
||||
}
|
||||
return a.localeCompare(b)
|
||||
})
|
||||
|
||||
return (
|
||||
<div className={className}>
|
||||
<div className="space-y-6">
|
||||
{sortedEntries.map(([groupName, groupData]) => (
|
||||
<div key={groupName}>
|
||||
<h3 className="text-text mb-4 text-lg font-semibold">{groupName}</h3>
|
||||
{renderGroup(groupData, groupName)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
} from "@follow/components/ui/card/index.js"
|
||||
|
||||
export interface StatCardProps {
|
||||
title: string
|
||||
value: string | number
|
||||
description?: string
|
||||
emoji?: string
|
||||
}
|
||||
|
||||
export const StatCard = ({ title, value, description, emoji }: StatCardProps) => (
|
||||
<Card className="p-4">
|
||||
<CardHeader className="p-2 pt-0">
|
||||
<CardTitle className="text-text-secondary flex items-center gap-2 text-sm font-medium">
|
||||
{emoji && <span className="text-base">{emoji}</span>}
|
||||
{title}
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="px-2 py-0">
|
||||
<div className="text-text text-2xl font-bold">{value}</div>
|
||||
{description && <CardDescription className="mt-1 text-xs">{description}</CardDescription>}
|
||||
</CardContent>
|
||||
</Card>
|
||||
)
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
import { cn } from "@follow/utils/utils"
|
||||
|
||||
import type { StatCardProps } from "./StatCard"
|
||||
import { StatCard } from "./StatCard"
|
||||
|
||||
export interface StatisticsOverviewProps {
|
||||
stats: StatCardProps[]
|
||||
columns?: {
|
||||
base: number
|
||||
md: number
|
||||
lg?: number
|
||||
}
|
||||
className?: string
|
||||
}
|
||||
|
||||
export const StatisticsOverview = ({
|
||||
stats,
|
||||
columns = { base: 2, md: 4 },
|
||||
className,
|
||||
}: StatisticsOverviewProps) => (
|
||||
<div
|
||||
className={cn(
|
||||
"grid gap-4",
|
||||
`grid-cols-${columns.base}`,
|
||||
`md:grid-cols-${columns.md}`,
|
||||
columns.lg && `lg:grid-cols-${columns.lg}`,
|
||||
className,
|
||||
)}
|
||||
>
|
||||
{stats.map((stat, index) => (
|
||||
<StatCard key={index} {...stat} />
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
@@ -0,0 +1,10 @@
|
||||
export * from "./AnalyticsMetrics"
|
||||
export * from "./CategoryTag"
|
||||
export * from "./ChartPlaceholder"
|
||||
export * from "./DisplayHeader"
|
||||
export * from "./EmptyState"
|
||||
export * from "./FeedItemCard"
|
||||
export * from "./GridContainer"
|
||||
export * from "./GroupedContent"
|
||||
export * from "./StatCard"
|
||||
export * from "./StatisticsOverview"
|
||||
@@ -0,0 +1,237 @@
|
||||
import { stopPropagation } from "@follow/utils"
|
||||
import type { UIDataTypes, UIMessage } from "ai"
|
||||
import { m } from "motion/react"
|
||||
import * as React from "react"
|
||||
import { toast } from "sonner"
|
||||
|
||||
import { copyToClipboard } from "~/lib/clipboard"
|
||||
import { AIChatContext } from "~/modules/ai/chat/__internal__/AIChatContext"
|
||||
import type { BizUIMetadata, BizUITools } from "~/modules/ai/chat/__internal__/types"
|
||||
import { useEditingMessageId, useSetEditingMessageId } from "~/modules/ai/chat/atoms/session"
|
||||
|
||||
import { AIMessageParts } from "./AIMessageParts"
|
||||
import { EditableMessage } from "./EditableMessage"
|
||||
|
||||
export interface ChatMessage {
|
||||
id: string
|
||||
role: "user" | "assistant"
|
||||
content: string
|
||||
timestamp: Date
|
||||
}
|
||||
|
||||
interface AIChatMessageProps {
|
||||
message: UIMessage<BizUIMetadata, UIDataTypes, BizUITools>
|
||||
onEdit?: (messageId: string) => void
|
||||
streaming?: boolean
|
||||
}
|
||||
|
||||
export const AIChatMessage: React.FC<AIChatMessageProps> = React.memo(({ message }) => {
|
||||
const { regenerate, sendMessage, setMessages, messages } = React.use(AIChatContext)
|
||||
const messageId = message.id
|
||||
const [isHovered, setIsHovered] = React.useState(false)
|
||||
const editingMessageId = useEditingMessageId()
|
||||
const setEditingMessageId = useSetEditingMessageId()
|
||||
|
||||
const isEditing = editingMessageId === messageId
|
||||
const isUserMessage = message.role === "user"
|
||||
|
||||
// Get message content for editing
|
||||
const messageContent = React.useMemo(() => {
|
||||
return (
|
||||
message.parts
|
||||
?.filter((part) => part.type === "text")
|
||||
.map((part) => part.text)
|
||||
.join(" ") || ""
|
||||
)
|
||||
}, [message.parts])
|
||||
|
||||
const handleEdit = React.useCallback(() => {
|
||||
if (isUserMessage) {
|
||||
setEditingMessageId(messageId)
|
||||
}
|
||||
}, [isUserMessage, messageId, setEditingMessageId])
|
||||
|
||||
const handleSaveEdit = React.useCallback(
|
||||
(newContent: string) => {
|
||||
if (newContent.trim() !== messageContent.trim()) {
|
||||
// Find the message index and remove all messages after it (including AI responses)
|
||||
const messageIndex = messages.findIndex((msg) => msg.id === messageId)
|
||||
if (messageIndex !== -1) {
|
||||
const messagesToKeep = messages.slice(0, messageIndex)
|
||||
setMessages(messagesToKeep)
|
||||
|
||||
// Send the edited message
|
||||
sendMessage({
|
||||
text: newContent,
|
||||
metadata: {
|
||||
finishTime: new Date().toISOString(),
|
||||
},
|
||||
})
|
||||
}
|
||||
}
|
||||
setEditingMessageId(null)
|
||||
},
|
||||
[messageContent, messageId, messages, setMessages, sendMessage, setEditingMessageId],
|
||||
)
|
||||
|
||||
const handleCancelEdit = React.useCallback(() => {
|
||||
setEditingMessageId(null)
|
||||
}, [setEditingMessageId])
|
||||
|
||||
const handleCopy = React.useCallback(async () => {
|
||||
try {
|
||||
await copyToClipboard(messageContent)
|
||||
toast.success("Message copied to clipboard")
|
||||
} catch {
|
||||
toast.error("Failed to copy message")
|
||||
}
|
||||
}, [messageContent])
|
||||
|
||||
const handleRetry = React.useCallback(() => {
|
||||
regenerate({ messageId })
|
||||
}, [regenerate, messageId])
|
||||
|
||||
return (
|
||||
<m.div
|
||||
onContextMenu={stopPropagation}
|
||||
className={`flex ${message.role === "user" ? "justify-end" : "justify-start"} group`}
|
||||
initial={{
|
||||
opacity: 0,
|
||||
y: 20,
|
||||
scale: 0.95,
|
||||
}}
|
||||
animate={{
|
||||
opacity: 1,
|
||||
y: 0,
|
||||
scale: 1,
|
||||
}}
|
||||
transition={{
|
||||
duration: 0.3,
|
||||
ease: [0.25, 0.46, 0.45, 0.94],
|
||||
delay: message.role === "user" ? 0.1 : 0.2,
|
||||
}}
|
||||
onMouseEnter={() => setIsHovered(true)}
|
||||
onMouseLeave={() => setIsHovered(false)}
|
||||
>
|
||||
<div className="flex max-w-[calc(100%-1rem)] flex-col gap-2">
|
||||
{/* Show editable message if editing */}
|
||||
{isEditing && isUserMessage ? (
|
||||
<EditableMessage
|
||||
messageId={messageId}
|
||||
initialContent={messageContent}
|
||||
onSave={handleSaveEdit}
|
||||
onCancel={handleCancelEdit}
|
||||
/>
|
||||
) : (
|
||||
<>
|
||||
{/* Normal message display */}
|
||||
<div
|
||||
className={`rounded-xl px-3 py-2.5 backdrop-blur-sm ${
|
||||
message.role === "user"
|
||||
? "dark:bg-accent/30 bg-accent/90 text-white"
|
||||
: "text-text border border-gray-200/60 bg-gradient-to-br from-white/80 to-gray-50/90 shadow-lg shadow-black/5 dark:border-zinc-700/60 dark:from-zinc-800/80 dark:to-zinc-900/90 dark:shadow-black/20"
|
||||
}`}
|
||||
>
|
||||
{message.role === "assistant" && (
|
||||
<div className="mb-2 flex items-center gap-2">
|
||||
<div className="from-folo flex size-5 items-center justify-center rounded-full bg-gradient-to-r to-red-500 shadow-sm">
|
||||
<i className="i-mgc-ai-cute-fi size-3 text-white" />
|
||||
</div>
|
||||
<span className="text-text-secondary text-xs font-medium">{APP_NAME} AI</span>
|
||||
</div>
|
||||
)}
|
||||
<div
|
||||
className={`select-text gap-2 text-[0.95rem] ${
|
||||
message.role === "user" ? "text-white" : "text-text"
|
||||
} flex flex-col`}
|
||||
>
|
||||
<AIMessageParts message={message} />
|
||||
</div>
|
||||
{message.metadata?.finishTime && (
|
||||
<div
|
||||
className={`mt-2 text-xs ${message.role === "user" ? "text-text-secondary-dark text-right" : "text-text-tertiary"}`}
|
||||
>
|
||||
{new Date(message.metadata.finishTime).toLocaleTimeString([], {
|
||||
hour: "2-digit",
|
||||
minute: "2-digit",
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Action buttons */}
|
||||
<m.div
|
||||
className={`flex ${message.role === "user" ? "justify-end" : "justify-start"} gap-1`}
|
||||
initial={{ opacity: 0, scale: 0.8 }}
|
||||
animate={{
|
||||
opacity: isHovered ? 1 : 0,
|
||||
scale: isHovered ? 1 : 0.8,
|
||||
}}
|
||||
transition={{ duration: 0.2, ease: "easeOut" }}
|
||||
>
|
||||
{message.role === "user" ? (
|
||||
<>
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleEdit}
|
||||
className="text-text-tertiary hover:bg-fill hover:text-text flex items-center gap-1 rounded-md px-2 py-1 text-xs transition-colors"
|
||||
title="Edit message"
|
||||
>
|
||||
<i className="i-mgc-edit-cute-re size-3" />
|
||||
<span>Edit</span>
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleRetry}
|
||||
className="text-text-tertiary hover:bg-fill hover:text-text flex items-center gap-1 rounded-md px-2 py-1 text-xs transition-colors"
|
||||
title="Retry"
|
||||
>
|
||||
<i className="i-mgc-refresh-2-cute-re size-3" />
|
||||
<span>Retry</span>
|
||||
</button>
|
||||
</>
|
||||
) : (
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleCopy}
|
||||
className="text-text-tertiary hover:bg-fill hover:text-text flex items-center gap-1 rounded-md px-2 py-1 text-xs transition-colors"
|
||||
title="Copy message"
|
||||
>
|
||||
<i className="i-mgc-copy-2-cute-re size-3" />
|
||||
<span>Copy</span>
|
||||
</button>
|
||||
)}
|
||||
</m.div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</m.div>
|
||||
)
|
||||
})
|
||||
|
||||
// Typing indicator component
|
||||
export const AIChatTypingIndicator: React.FC = () => {
|
||||
return (
|
||||
<m.div
|
||||
className="flex justify-start"
|
||||
initial={{ opacity: 0, y: 10 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
exit={{ opacity: 0, y: -10 }}
|
||||
transition={{ duration: 0.2 }}
|
||||
>
|
||||
<div className="max-w-[70%] rounded-xl border border-gray-200/60 bg-gradient-to-br from-white/80 to-gray-50/90 px-3 py-2.5 shadow-lg shadow-black/5 backdrop-blur-sm dark:border-zinc-700/60 dark:from-zinc-800/80 dark:to-zinc-900/90 dark:shadow-black/20">
|
||||
<div className="mb-2 flex items-center gap-2">
|
||||
<div className="from-orange flex size-5 items-center justify-center rounded-full bg-gradient-to-r to-red-500">
|
||||
<i className="i-mgc-ai-cute-re size-3 text-white" />
|
||||
</div>
|
||||
<span className="text-text-secondary text-xs font-medium">{APP_NAME} AI</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-1">
|
||||
<div className="bg-text-tertiary size-2 animate-bounce rounded-full [animation-delay:-0.3s]" />
|
||||
<div className="bg-text-tertiary size-2 animate-bounce rounded-full [animation-delay:-0.15s]" />
|
||||
<div className="bg-text-tertiary size-2 animate-bounce rounded-full" />
|
||||
</div>
|
||||
</div>
|
||||
</m.div>
|
||||
)
|
||||
}
|
||||
+90
@@ -0,0 +1,90 @@
|
||||
import type { LinkProps } from "@follow/components/ui/link/LinkWithTooltip.js"
|
||||
import { parseMarkdown } from "@follow/components/utils/parse-markdown.js"
|
||||
import { cn, isBizId } from "@follow/utils"
|
||||
import { createElement, isValidElement, memo, useMemo } from "react"
|
||||
|
||||
import { ShikiHighLighter } from "~/components/ui/code-highlighter"
|
||||
import { MermaidDiagram } from "~/components/ui/diagrams"
|
||||
import { MarkdownLink } from "~/components/ui/markdown/renderers/MarkdownLink"
|
||||
import { usePeekModal } from "~/hooks/biz/usePeekModal"
|
||||
|
||||
export const AIMarkdownMessage = memo(
|
||||
({
|
||||
text,
|
||||
className: classNameProp,
|
||||
isProcessing,
|
||||
}: {
|
||||
text: string
|
||||
className?: string
|
||||
isProcessing?: boolean
|
||||
}) => {
|
||||
const className = tw`prose dark:prose-invert text-sm
|
||||
prose-h1:text-2xl prose-h2:text-xl prose-h3:text-lg prose-h4:text-base prose-h5:text-base prose-h6:text-sm
|
||||
prose-li:list-disc prose-li:marker:text-accent prose-hr:border-border prose-hr:mx-8
|
||||
`
|
||||
|
||||
return (
|
||||
<div className={cn(className, classNameProp)}>
|
||||
{useMemo(
|
||||
() =>
|
||||
parseMarkdown(text, {
|
||||
components: {
|
||||
pre: ({ children }) => {
|
||||
// props
|
||||
const props = isValidElement(children) && "props" in children && children.props
|
||||
|
||||
if (props) {
|
||||
const { className, children } = props as any
|
||||
|
||||
if (
|
||||
className &&
|
||||
className.includes("language-") &&
|
||||
typeof children === "string"
|
||||
) {
|
||||
const language = className.replace("language-", "")
|
||||
const code = children
|
||||
|
||||
// Render Mermaid diagrams
|
||||
if (language === "mermaid") {
|
||||
return <MermaidDiagram code={code} shouldRender={!isProcessing} />
|
||||
}
|
||||
|
||||
return <ShikiHighLighter code={code} language={language} showCopy />
|
||||
}
|
||||
}
|
||||
|
||||
return <pre className="text-text-secondary">{children}</pre>
|
||||
},
|
||||
a: ({ node, ...props }) => {
|
||||
return createElement(RelatedEntryLink, { ...props } as any)
|
||||
},
|
||||
},
|
||||
}).content,
|
||||
[isProcessing, text],
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
},
|
||||
)
|
||||
|
||||
const RelatedEntryLink = (props: LinkProps) => {
|
||||
const { href, children } = props
|
||||
const entryId = isBizId(href) ? href : null
|
||||
|
||||
const peekModal = usePeekModal()
|
||||
if (!entryId) {
|
||||
return <MarkdownLink {...props} />
|
||||
}
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
className="follow-link--underline text-text cursor-pointer font-semibold no-underline"
|
||||
onClick={() => {
|
||||
peekModal(entryId, "modal")
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
<i className="i-mgc-arrow-right-up-cute-re size-[0.9em] translate-y-[2px] opacity-70" />
|
||||
</button>
|
||||
)
|
||||
}
|
||||
+132
@@ -0,0 +1,132 @@
|
||||
import type { ToolUIPart } from "ai"
|
||||
import { m } from "motion/react"
|
||||
import * as React from "react"
|
||||
|
||||
import type {
|
||||
AIDisplayAnalyticsTool,
|
||||
AIDisplayEntriesTool,
|
||||
AIDisplayFeedsTool,
|
||||
AIDisplaySubscriptionsTool,
|
||||
BizUIMessage,
|
||||
} from "~/modules/ai/chat/__internal__/types"
|
||||
|
||||
import {
|
||||
AIDisplayAnalyticsPart,
|
||||
AIDisplayEntriesPart,
|
||||
AIDisplayFeedsPart,
|
||||
AIDisplaySubscriptionsPart,
|
||||
} from "../displays"
|
||||
import { ToolInvocationComponent } from "../ToolInvocationComponent"
|
||||
import { AIMarkdownMessage } from "./AIMarkdownMessage"
|
||||
|
||||
interface MessagePartsProps {
|
||||
message: BizUIMessage
|
||||
}
|
||||
const ThinkingIndicator: React.FC = () => {
|
||||
const text = "Thinking..."
|
||||
const [displayedText, setDisplayedText] = React.useState("")
|
||||
const [currentIndex, setCurrentIndex] = React.useState(0)
|
||||
|
||||
React.useEffect(() => {
|
||||
if (currentIndex < text.length) {
|
||||
const timer = setTimeout(() => {
|
||||
setDisplayedText(text.slice(0, currentIndex + 1))
|
||||
setCurrentIndex(currentIndex + 1)
|
||||
}, 100)
|
||||
|
||||
return () => clearTimeout(timer)
|
||||
}
|
||||
}, [currentIndex, text])
|
||||
|
||||
return (
|
||||
<div className="flex items-center justify-center py-4">
|
||||
<m.div
|
||||
initial={{ opacity: 0, y: 10 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
className="text-text-secondary flex items-center gap-1"
|
||||
>
|
||||
<span className="text-sm font-medium">{displayedText}</span>
|
||||
<m.span
|
||||
animate={{ opacity: [1, 0.3, 1] }}
|
||||
transition={{
|
||||
duration: 1,
|
||||
repeat: Infinity,
|
||||
ease: "easeInOut",
|
||||
}}
|
||||
className="text-accent text-sm"
|
||||
>
|
||||
|
|
||||
</m.span>
|
||||
</m.div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
export const AIMessageParts: React.FC<MessagePartsProps> = React.memo(({ message }) => {
|
||||
if (!message.parts || message.parts.length === 0) {
|
||||
// In AI SDK v5, messages should always have parts
|
||||
if (message.role === "assistant") {
|
||||
return <ThinkingIndicator />
|
||||
}
|
||||
return null
|
||||
}
|
||||
const isUser = message.role === "user"
|
||||
|
||||
return (
|
||||
<>
|
||||
{message.parts.map((part, index) => {
|
||||
const partKey = `${message.id}-part-${index}`
|
||||
|
||||
switch (part.type) {
|
||||
case "text": {
|
||||
return (
|
||||
<AIMarkdownMessage
|
||||
isProcessing={message.metadata?.totalTokens === undefined}
|
||||
key={partKey}
|
||||
text={part.text}
|
||||
className={isUser ? "text-white" : "text-text"}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
case "tool-displayAnalytics": {
|
||||
return <AIDisplayAnalyticsPart key={partKey} part={part as AIDisplayAnalyticsTool} />
|
||||
}
|
||||
case "tool-displayEntries": {
|
||||
return <AIDisplayEntriesPart key={partKey} part={part as AIDisplayEntriesTool} />
|
||||
}
|
||||
case "tool-displaySubscriptions": {
|
||||
return (
|
||||
<AIDisplaySubscriptionsPart key={partKey} part={part as AIDisplaySubscriptionsTool} />
|
||||
)
|
||||
}
|
||||
case "tool-displayFeeds": {
|
||||
return <AIDisplayFeedsPart key={partKey} part={part as AIDisplayFeedsTool} />
|
||||
}
|
||||
|
||||
// case "reasoning": {
|
||||
// return (
|
||||
// <details key={partKey} className="my-2">
|
||||
// <summary className="text-text-tertiary hover:text-text cursor-pointer text-sm font-medium">
|
||||
// <i className="i-mgc-brain-cute-re mr-2 size-3" />
|
||||
// Show reasoning
|
||||
// </summary>
|
||||
// <div className="bg-fill-secondary border-purple/50 text-text-secondary mt-2 rounded border-l-4 p-3 text-sm">
|
||||
// {parseMarkdown(part.reasoning).content}
|
||||
// </div>
|
||||
// </details>
|
||||
// )
|
||||
// }
|
||||
|
||||
default: {
|
||||
if (part.type.startsWith("tool-")) {
|
||||
return <ToolInvocationComponent key={partKey} part={part as ToolUIPart} />
|
||||
}
|
||||
return null
|
||||
}
|
||||
}
|
||||
})}
|
||||
</>
|
||||
)
|
||||
})
|
||||
|
||||
AIMessageParts.displayName = "AIMessageParts"
|
||||
+141
@@ -0,0 +1,141 @@
|
||||
import { useInputComposition } from "@follow/hooks"
|
||||
import { cn } from "@follow/utils"
|
||||
import { use, useCallback, useEffect, useRef, useState } from "react"
|
||||
|
||||
import { AIChatContext } from "~/modules/ai/chat/__internal__/AIChatContext"
|
||||
import { useEditingMessageId, useSetEditingMessageId } from "~/modules/ai/chat/atoms/session"
|
||||
|
||||
interface EditableMessageProps {
|
||||
messageId: string
|
||||
initialContent: string
|
||||
onSave: (content: string) => void
|
||||
onCancel: () => void
|
||||
className?: string
|
||||
}
|
||||
|
||||
export const EditableMessage = ({
|
||||
messageId,
|
||||
initialContent,
|
||||
onSave,
|
||||
onCancel,
|
||||
className,
|
||||
}: EditableMessageProps) => {
|
||||
const { status } = use(AIChatContext)
|
||||
const editingMessageId = useEditingMessageId()
|
||||
const setEditingMessageId = useSetEditingMessageId()
|
||||
const [content, setContent] = useState(initialContent)
|
||||
const [isEmpty, setIsEmpty] = useState(false)
|
||||
const textareaRef = useRef<HTMLTextAreaElement>(null)
|
||||
|
||||
const isEditing = editingMessageId === messageId
|
||||
const isProcessing = status === "submitted" || status === "streaming"
|
||||
|
||||
// Auto-resize textarea and maintain minimum height to prevent CLS
|
||||
useEffect(() => {
|
||||
if (textareaRef.current && isEditing) {
|
||||
const textarea = textareaRef.current
|
||||
textarea.style.height = "auto"
|
||||
const newHeight = Math.max(56, textarea.scrollHeight) // Minimum height of 56px
|
||||
textarea.style.height = `${newHeight}px`
|
||||
}
|
||||
}, [content, isEditing])
|
||||
|
||||
// Focus on edit start
|
||||
useEffect(() => {
|
||||
if (isEditing && textareaRef.current) {
|
||||
textareaRef.current.focus()
|
||||
textareaRef.current.setSelectionRange(
|
||||
textareaRef.current.value.length,
|
||||
textareaRef.current.value.length,
|
||||
)
|
||||
}
|
||||
}, [isEditing])
|
||||
|
||||
const handleSave = useCallback(() => {
|
||||
if (content.trim() && content.trim() !== initialContent) {
|
||||
onSave(content.trim())
|
||||
}
|
||||
setEditingMessageId(null)
|
||||
}, [content, initialContent, onSave, setEditingMessageId])
|
||||
|
||||
const handleCancel = useCallback(() => {
|
||||
setContent(initialContent)
|
||||
setEditingMessageId(null)
|
||||
onCancel()
|
||||
}, [initialContent, onCancel, setEditingMessageId])
|
||||
|
||||
const handleKeyPress = useCallback(
|
||||
(e: React.KeyboardEvent) => {
|
||||
if (e.key === "Enter" && !e.shiftKey) {
|
||||
e.preventDefault()
|
||||
if (!isProcessing) {
|
||||
handleSave()
|
||||
}
|
||||
} else if (e.key === "Escape") {
|
||||
e.preventDefault()
|
||||
handleCancel()
|
||||
}
|
||||
},
|
||||
[handleSave, handleCancel, isProcessing],
|
||||
)
|
||||
|
||||
const handleChange = useCallback((e: React.ChangeEvent<HTMLTextAreaElement>) => {
|
||||
const newContent = e.target.value
|
||||
setContent(newContent)
|
||||
setIsEmpty(newContent.trim() === "")
|
||||
}, [])
|
||||
|
||||
const inputProps = useInputComposition<HTMLTextAreaElement>({
|
||||
onKeyDown: handleKeyPress,
|
||||
})
|
||||
|
||||
if (!isEditing) {
|
||||
return null
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={cn("relative", className)}>
|
||||
{/* Edit input */}
|
||||
<div className="bg-background/60 focus-within:ring-accent/20 focus-within:border-accent/80 border-border/80 relative overflow-hidden rounded-xl border backdrop-blur-xl duration-200 focus-within:ring-2">
|
||||
<textarea
|
||||
ref={textareaRef}
|
||||
value={content}
|
||||
onChange={handleChange}
|
||||
{...inputProps}
|
||||
placeholder="Edit your message..."
|
||||
className="scrollbar-none text-text placeholder:text-text-secondary max-h-40 min-h-14 w-full resize-none bg-transparent px-4 py-3 pr-20 text-sm !outline-none transition-all duration-200"
|
||||
rows={1}
|
||||
disabled={isProcessing}
|
||||
/>
|
||||
|
||||
{/* Action buttons */}
|
||||
<div className="absolute right-2 top-1/2 flex -translate-y-1/2 gap-1">
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleCancel}
|
||||
disabled={isProcessing}
|
||||
className="text-text-tertiary hover:text-text hover:bg-fill/50 flex size-8 items-center justify-center rounded-lg transition-colors disabled:opacity-50"
|
||||
title="Cancel (Esc)"
|
||||
>
|
||||
<i className="i-mgc-close-cute-re size-4" />
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleSave}
|
||||
disabled={isProcessing || isEmpty || content.trim() === initialContent}
|
||||
className="text-accent hover:text-accent hover:bg-accent/10 flex size-8 items-center justify-center rounded-lg transition-colors disabled:opacity-50"
|
||||
title="Save (Enter)"
|
||||
>
|
||||
<i className="i-mgc-send-plane-cute-fi size-4" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Helper text */}
|
||||
<div className="text-text-tertiary mt-2 text-xs">
|
||||
Press <kbd className="bg-fill text-text-secondary rounded px-1 py-0.5">Enter</kbd> to save,{" "}
|
||||
<kbd className="bg-fill text-text-secondary rounded px-1 py-0.5">Esc</kbd> to cancel
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
import { springScrollTo } from "@follow/utils/scroller"
|
||||
import { debounce } from "es-toolkit/compat"
|
||||
import { useCallback, useEffect, useRef, useState } from "react"
|
||||
|
||||
const BOTTOM_THRESHOLD = 50
|
||||
|
||||
export const useAutoScroll = (viewport: HTMLElement | null, enabled: boolean) => {
|
||||
const [isAtBottom, setIsAtBottom] = useState(true)
|
||||
const [isUserInteracting, setIsUserInteracting] = useState(false)
|
||||
const scrollAnimationRef = useRef<{ stop: () => void } | null>(null)
|
||||
const interactionTimeoutRef = useRef<number | null>(null)
|
||||
const isAutoScrollingRef = useRef(false)
|
||||
|
||||
const isUserInteractingRef = useRef(isUserInteracting)
|
||||
useEffect(() => {
|
||||
isUserInteractingRef.current = isUserInteracting
|
||||
}, [isUserInteracting])
|
||||
|
||||
const isAtBottomRef = useRef(isAtBottom)
|
||||
useEffect(() => {
|
||||
isAtBottomRef.current = isAtBottom
|
||||
}, [isAtBottom])
|
||||
|
||||
const scrollToBottom = useCallback(
|
||||
(force = false) => {
|
||||
if (!viewport) return
|
||||
|
||||
if (scrollAnimationRef.current) {
|
||||
scrollAnimationRef.current.stop()
|
||||
}
|
||||
|
||||
if (force || (!isUserInteractingRef.current && isAtBottomRef.current)) {
|
||||
isAutoScrollingRef.current = true
|
||||
const targetScrollTop = viewport.scrollHeight - viewport.clientHeight
|
||||
const animation = springScrollTo(targetScrollTop, viewport)
|
||||
|
||||
scrollAnimationRef.current = animation
|
||||
animation.then(() => {
|
||||
scrollAnimationRef.current = null
|
||||
isAutoScrollingRef.current = false
|
||||
// After animation, re-evaluate position
|
||||
const { scrollTop, scrollHeight, clientHeight } = viewport
|
||||
const atBottom = scrollHeight - scrollTop - clientHeight <= BOTTOM_THRESHOLD
|
||||
if (isAtBottomRef.current !== atBottom) {
|
||||
setIsAtBottom(atBottom)
|
||||
}
|
||||
})
|
||||
}
|
||||
},
|
||||
[viewport],
|
||||
)
|
||||
|
||||
useEffect(() => {
|
||||
if (!viewport) return
|
||||
|
||||
if (!enabled) {
|
||||
return
|
||||
}
|
||||
|
||||
const handleScroll = () => {
|
||||
if (isAutoScrollingRef.current) {
|
||||
return
|
||||
}
|
||||
|
||||
const { scrollTop, scrollHeight, clientHeight } = viewport
|
||||
const atBottom = scrollHeight - scrollTop - clientHeight <= BOTTOM_THRESHOLD
|
||||
|
||||
if (!isUserInteractingRef.current) {
|
||||
setIsAtBottom(atBottom)
|
||||
}
|
||||
}
|
||||
|
||||
const handleWheel = () => {
|
||||
isAutoScrollingRef.current = false
|
||||
setIsUserInteracting(true)
|
||||
|
||||
if (scrollAnimationRef.current) {
|
||||
scrollAnimationRef.current.stop()
|
||||
}
|
||||
if (interactionTimeoutRef.current) {
|
||||
window.clearTimeout(interactionTimeoutRef.current)
|
||||
}
|
||||
|
||||
interactionTimeoutRef.current = window.setTimeout(() => {
|
||||
setIsUserInteracting(false)
|
||||
handleScroll() // Re-check position after interaction ends
|
||||
}, 150)
|
||||
}
|
||||
|
||||
viewport.addEventListener("scroll", handleScroll, { passive: true })
|
||||
viewport.addEventListener("wheel", handleWheel, { passive: true })
|
||||
|
||||
return () => {
|
||||
viewport.removeEventListener("scroll", handleScroll)
|
||||
viewport.removeEventListener("wheel", handleWheel)
|
||||
if (interactionTimeoutRef.current) {
|
||||
window.clearTimeout(interactionTimeoutRef.current)
|
||||
}
|
||||
if (scrollAnimationRef.current) {
|
||||
scrollAnimationRef.current.stop()
|
||||
}
|
||||
}
|
||||
}, [viewport])
|
||||
|
||||
useEffect(() => {
|
||||
if (!viewport || !enabled) return
|
||||
|
||||
const content = viewport.firstElementChild as HTMLElement
|
||||
if (!content) return
|
||||
|
||||
const resizeObserver = new ResizeObserver(
|
||||
debounce(() => {
|
||||
if (!isUserInteractingRef.current && isAtBottomRef.current) {
|
||||
requestAnimationFrame(() => {
|
||||
scrollToBottom()
|
||||
})
|
||||
}
|
||||
}, 16),
|
||||
)
|
||||
|
||||
resizeObserver.observe(content)
|
||||
|
||||
return () => {
|
||||
resizeObserver.disconnect()
|
||||
}
|
||||
}, [viewport, enabled, scrollToBottom])
|
||||
|
||||
const resetScrollState = useCallback(() => {
|
||||
setIsUserInteracting(false)
|
||||
setIsAtBottom(true)
|
||||
scrollToBottom(true)
|
||||
}, [scrollToBottom])
|
||||
|
||||
return { resetScrollState, scrollToBottom }
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
import { nanoid } from "nanoid"
|
||||
import { useCallback, useState } from "react"
|
||||
|
||||
import { AIPersistService } from "~/modules/ai/chat/services/index"
|
||||
|
||||
import type { ChatSession } from "../types/ChatSession"
|
||||
|
||||
export const useChatHistory = () => {
|
||||
const [sessions, setSessions] = useState<ChatSession[]>([])
|
||||
const [loading, setLoading] = useState(false)
|
||||
|
||||
const loadHistory = useCallback(async () => {
|
||||
setLoading(true)
|
||||
try {
|
||||
const result = await AIPersistService.getChatSessions()
|
||||
const sessions: ChatSession[] = result.map((row) => ({
|
||||
roomId: row.roomId,
|
||||
title: row.title || "New Chat",
|
||||
createdAt: new Date(row.createdAt),
|
||||
messageCount: row.messageCount,
|
||||
}))
|
||||
|
||||
setSessions(sessions)
|
||||
} catch (error) {
|
||||
console.error("Failed to load chat history:", error)
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}, [])
|
||||
|
||||
const createNewSession = (shouldPersist = false) => {
|
||||
const roomId = nanoid()
|
||||
if (shouldPersist) {
|
||||
AIPersistService.createSession(roomId, "New Chat").catch((error) => {
|
||||
console.error("Failed to create new session:", error)
|
||||
})
|
||||
}
|
||||
return roomId
|
||||
}
|
||||
|
||||
return {
|
||||
sessions,
|
||||
loading,
|
||||
loadHistory,
|
||||
createNewSession,
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user