diff --git a/.github/actions/setup-xcode/action.yml b/.github/actions/setup-xcode/action.yml index e7b6280d8..f832ad9c3 100644 --- a/.github/actions/setup-xcode/action.yml +++ b/.github/actions/setup-xcode/action.yml @@ -4,7 +4,7 @@ inputs: xcode-version: description: "Xcode version to use" required: false - default: "16.2.0" + default: "16.4.0" runs: using: "composite" @@ -12,3 +12,7 @@ runs: - uses: maxim-lobanov/setup-xcode@v1 with: xcode-version: ${{ inputs.xcode-version }} + + - name: Download iOS Platform + run: xcodebuild -downloadPlatform iOS + shell: bash diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md index 3ae653d30..e27d54efa 100644 --- a/.github/copilot-instructions.md +++ b/.github/copilot-instructions.md @@ -1 +1 @@ -Before you start, you need to read and follow the rules in @claude.md +Before you start, you need to read and follow the rules in @../CLAUDE.md diff --git a/.github/workflows/build-android.yml b/.github/workflows/build-android.yml index c102ba4a7..73d89f2ff 100644 --- a/.github/workflows/build-android.yml +++ b/.github/workflows/build-android.yml @@ -33,7 +33,7 @@ jobs: steps: - name: 📦 Checkout code - uses: actions/checkout@v4 + uses: actions/checkout@v5 - name: 📦 Setup pnpm uses: pnpm/action-setup@v4 @@ -92,16 +92,15 @@ jobs: id: version uses: ./.github/actions/setup-version with: - # We don't want to create a new release for mobile - type: "desktop" + type: "mobile" - name: Create Release Draft if: github.event.inputs.release == 'true' uses: softprops/action-gh-release@v2 with: - name: v${{ steps.version.outputs.APP_VERSION }} + name: Mobile v${{ steps.version.outputs.APP_VERSION }} draft: false prerelease: true - tag_name: v${{ steps.version.outputs.APP_VERSION }} + tag_name: mobile/v${{ steps.version.outputs.APP_VERSION }} # .aab cannot be installed directly on your Android Emulator or device. files: ${{ github.workspace }}/build.apk diff --git a/.github/workflows/build-desktop.yml b/.github/workflows/build-desktop.yml index d13502e41..6e2df0edb 100644 --- a/.github/workflows/build-desktop.yml +++ b/.github/workflows/build-desktop.yml @@ -56,13 +56,13 @@ jobs: steps: - name: Check out Git repository Fully - uses: actions/checkout@v4 + uses: actions/checkout@v5 if: env.PROD == 'true' with: fetch-depth: 0 lfs: true - name: Check out Git repository - uses: actions/checkout@v4 + uses: actions/checkout@v5 if: env.PROD == 'false' with: fetch-depth: 1 @@ -222,7 +222,7 @@ jobs: apps/desktop/out/make/**/latest.yml retention-days: 90 - - uses: signpath/github-action-submit-signing-request@v1.2 + - uses: signpath/github-action-submit-signing-request@v1.3 continue-on-error: true if: runner.os == 'windows' && env.RELEASE == 'true' with: @@ -297,10 +297,10 @@ jobs: if: env.RELEASE == 'true' uses: softprops/action-gh-release@v2 with: - name: v${{ steps.version.outputs.APP_VERSION }} + name: Desktop v${{ steps.version.outputs.APP_VERSION }} draft: false prerelease: true - tag_name: v${{ steps.version.outputs.APP_VERSION }} + tag_name: desktop/v${{ steps.version.outputs.APP_VERSION }} files: | apps/desktop/out/make/**/Folo-*.dmg apps/desktop/out/make/**/Folo-*.zip diff --git a/.github/workflows/build-ios-development.yml b/.github/workflows/build-ios-development.yml index 2b62357fa..7af51eb41 100644 --- a/.github/workflows/build-ios-development.yml +++ b/.github/workflows/build-ios-development.yml @@ -40,7 +40,7 @@ jobs: steps: - name: 📦 Checkout code - uses: actions/checkout@v4 + uses: actions/checkout@v5 - name: 📱 Setup EAS uses: expo/expo-github-action@v8 @@ -77,7 +77,7 @@ jobs: steps: - name: 📦 Checkout code - uses: actions/checkout@v4 + uses: actions/checkout@v5 - name: 🔧 Setup Xcode uses: ./.github/actions/setup-xcode @@ -121,7 +121,7 @@ jobs: steps: - name: 📦 Checkout code - uses: actions/checkout@v4 + uses: actions/checkout@v5 - name: 🔧 Setup Xcode uses: ./.github/actions/setup-xcode diff --git a/.github/workflows/build-ios.yml b/.github/workflows/build-ios.yml index 24334ea0b..e138f04b4 100644 --- a/.github/workflows/build-ios.yml +++ b/.github/workflows/build-ios.yml @@ -1,4 +1,4 @@ -name: Build iOS +name: 🍎 Build iOS on: push: @@ -47,7 +47,7 @@ jobs: steps: - name: 📦 Checkout code - uses: actions/checkout@v4 + uses: actions/checkout@v5 - name: 📱 Setup EAS uses: expo/expo-github-action@v8 @@ -89,7 +89,10 @@ jobs: steps: - name: 📦 Checkout code - uses: actions/checkout@v4 + uses: actions/checkout@v5 + + - name: 🔧 Setup Xcode + uses: ./.github/actions/setup-xcode - name: 📦 Setup pnpm uses: pnpm/action-setup@v4 diff --git a/.github/workflows/build-web.yml b/.github/workflows/build-web.yml index 772efb3c8..54db6887e 100644 --- a/.github/workflows/build-web.yml +++ b/.github/workflows/build-web.yml @@ -17,7 +17,7 @@ jobs: node-version: [lts/*] steps: - name: Checkout code - uses: actions/checkout@v4 + uses: actions/checkout@v5 with: lfs: true - name: Cache turbo build setup diff --git a/.github/workflows/claude-code-review.yml b/.github/workflows/claude-code-review.yml index 8a2910f51..238062893 100644 --- a/.github/workflows/claude-code-review.yml +++ b/.github/workflows/claude-code-review.yml @@ -25,7 +25,7 @@ jobs: id-token: write steps: - name: Checkout repository - uses: actions/checkout@v4 + uses: actions/checkout@v5 with: fetch-depth: 1 diff --git a/.github/workflows/claude.yml b/.github/workflows/claude.yml index 9a8b4fd08..01f530f36 100644 --- a/.github/workflows/claude.yml +++ b/.github/workflows/claude.yml @@ -26,7 +26,7 @@ jobs: actions: read # Required for Claude to read CI results on PRs steps: - name: Checkout repository - uses: actions/checkout@v4 + uses: actions/checkout@v5 with: fetch-depth: 1 diff --git a/.github/workflows/issue-labeler.yml b/.github/workflows/issue-labeler.yml index 5f12f111c..25450cbd9 100644 --- a/.github/workflows/issue-labeler.yml +++ b/.github/workflows/issue-labeler.yml @@ -19,7 +19,7 @@ jobs: contents: read steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v5 - name: Parse issue form uses: stefanbuck/github-issue-parser@v3 diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml index a04e98366..114d87e3a 100644 --- a/.github/workflows/lint.yml +++ b/.github/workflows/lint.yml @@ -22,7 +22,7 @@ jobs: node-version: [lts/*] steps: - name: Checkout code - uses: actions/checkout@v4 + uses: actions/checkout@v5 with: lfs: true - name: Cache turbo build setup diff --git a/.github/workflows/sync.yaml b/.github/workflows/sync.yaml index 50a715a59..983e179d9 100644 --- a/.github/workflows/sync.yaml +++ b/.github/workflows/sync.yaml @@ -10,7 +10,7 @@ jobs: runs-on: ubuntu-latest steps: - name: Checkout repository - uses: actions/checkout@v4 + uses: actions/checkout@v5 with: fetch-depth: 0 diff --git a/.github/workflows/tag.yml b/.github/workflows/tag.yml index b2df7f891..c9c3450cf 100644 --- a/.github/workflows/tag.yml +++ b/.github/workflows/tag.yml @@ -4,55 +4,90 @@ on: push: branches: - main -env: - NODE_OPTIONS: --max-old-space-size=8192 + jobs: create_tag: + name: Create Release Tag runs-on: ubuntu-latest + outputs: + tag_version: ${{ env.tag_version }} + platform: ${{ env.platform }} + version: ${{ env.version }} + steps: - name: Checkout repository - uses: actions/checkout@v4 - - name: Use Node.js + uses: actions/checkout@v5 + + - name: Setup Node.js uses: actions/setup-node@v4 with: - node-version: 22 + node-version: lts/* - - name: Extract SemVer using Node.js - id: extract_semver + - name: Make script executable run: | - node -e ' - const execSync = require("child_process").execSync; - const fs = require("fs"); - const commitMessage = execSync("git log -1 --pretty=%B").toString("utf-8"); - const semverRegex = /release\(desktop\): Release (v[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z-.]+)?)/; - const match = commitMessage.match(semverRegex); - if (match) { - fs.appendFileSync(process.env.GITHUB_ENV, `tag_version=${match[1]}\n`); - } else { - console.log("No SemVer found in commit body."); - process.exit(0); - } - ' + chmod +x .github/scripts/extract-release-info.mjs - - name: Create a new tag - if: ${{ env.tag_version }} - run: | - git tag ${{ env.tag_version }} - git push origin ${{ env.tag_version }} - - name: Trigger Build Desktop Workflow - if: ${{ env.tag_version }} - run: | - curl -X POST \ - -H "Authorization: token ${{ secrets.GITHUB_TOKEN }}" \ - -H "Accept: application/vnd.github+json" \ - https://api.github.com/repos/${{ github.repository }}/actions/workflows/build-desktop.yml/dispatches \ - -d '{"ref":"main", "inputs": {"tag_version": "true"}}' + - name: Extract release information + id: extract_info + run: .github/scripts/extract-release-info.mjs + continue-on-error: false - - name: Trigger Build Android Workflow - if: ${{ env.tag_version }} + - name: Validate git configuration + if: env.tag_version run: | - curl -X POST \ - -H "Authorization: token ${{ secrets.GITHUB_TOKEN }}" \ - -H "Accept: application/vnd.github+json" \ - https://api.github.com/repos/${{ github.repository }}/actions/workflows/build-android.yml/dispatches \ - -d '{"ref":"main", "inputs": {"release": "true"}}' + git config --global user.name "github-actions[bot]" + git config --global user.email "github-actions[bot]@users.noreply.github.com" + + - name: Create and push tag + if: env.tag_version + run: | + echo "Creating tag: ${{ env.tag_version }}" + if git rev-parse "${{ env.tag_version }}" >/dev/null 2>&1; then + echo "Tag ${{ env.tag_version }} already exists, skipping creation" + exit 0 + fi + + git tag "${{ env.tag_version }}" + git push origin "${{ env.tag_version }}" + echo "Successfully created and pushed tag: ${{ env.tag_version }}" + + trigger_builds: + name: Trigger Platform Builds + needs: create_tag + if: needs.create_tag.outputs.tag_version + runs-on: ubuntu-latest + + steps: + - name: Trigger Desktop Build + if: needs.create_tag.outputs.platform == 'desktop' + uses: actions/github-script@v7 + with: + github-token: ${{ secrets.GITHUB_TOKEN }} + script: | + const response = await github.rest.actions.createWorkflowDispatch({ + owner: context.repo.owner, + repo: context.repo.repo, + workflow_id: 'build-desktop.yml', + ref: 'main', + inputs: { + tag_version: 'true' + } + }); + console.log('Desktop build triggered successfully'); + + - name: Trigger Mobile Build + if: needs.create_tag.outputs.platform == 'mobile' + uses: actions/github-script@v7 + with: + github-token: ${{ secrets.GITHUB_TOKEN }} + script: | + const response = await github.rest.actions.createWorkflowDispatch({ + owner: context.repo.owner, + repo: context.repo.repo, + workflow_id: 'build-android.yml', + ref: 'main', + inputs: { + release: 'true' + } + }); + console.log('Mobile build triggered successfully'); diff --git a/.github/workflows/translator.yml b/.github/workflows/translator.yml index 929f9d098..c10438f96 100644 --- a/.github/workflows/translator.yml +++ b/.github/workflows/translator.yml @@ -17,7 +17,7 @@ jobs: pull-requests: write runs-on: ubuntu-latest steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v5 - uses: lizheming/github-translate-action@c55aac477e98562d4faed9f77c54ab8306ae6ebf env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/CLAUDE.md b/CLAUDE.md index 4a91dad20..9279e1310 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -10,18 +10,49 @@ Follow (Folo) is a modern RSS aggregator and content management platform with mu ### Applications (`apps/`) -- **`apps/desktop/`** - Electron desktop application with main and renderer processes +- **`apps/desktop/`** - Electron desktop application + - `layer/main/` - Electron main process + - `layer/renderer/` - Vite + React renderer (primary web app) + - `plugins/` - Custom Electron plugins + - `resources/` - Application resources and assets - **`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 + - `src/` - React Native source code + - `native/` - Native module implementations + - `web-app/` - HTML renderer for mobile web views + - `android/` - Android-specific configuration + - `ios/` - iOS-specific configuration +- **`apps/ssr/`** - Server-side rendered web application (minimal, for external sharing) ### 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 +- **`packages/internal/`** - Core shared packages + - `atoms/` - Jotai atomic state definitions + - `components/` - Shared UI components + - `constants/` - Application constants + - `database/` - Drizzle ORM database layer + - `hooks/` - Shared React hooks + - `models/` - Data models and schemas + - `shared/` - Cross-platform shared utilities + - `store/` - Zustand stores + - `types/` - TypeScript type definitions + - `utils/` - Utility functions and helpers + - `tracker/` - Analytics and tracking + - `logger/` - Logging utilities + - `legal/` - Legal and compliance utilities +- **`packages/configs/`** - Shared configuration files + - `tailwindcss/` - Tailwind CSS configurations + - TypeScript and build configurations +- **`packages/readability/`** - Content readability parsing and extraction +- **`packages/changelog-cli/`** - CLI tool for changelog generation + +### Supporting Directories + +- **`scripts/`** - Build and development scripts +- **`plugins/`** - Custom development plugins +- **`locales/`** - Internationalization files organized by feature +- **`icons/`** - Icon assets (MingCute and custom icons) +- **`.github/`** - GitHub workflows, issue templates, and CI/CD +- **`patches/`** - Package patches for dependency modifications ## Essential Commands @@ -69,19 +100,6 @@ pnpm run typecheck 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 @@ -102,45 +120,9 @@ pnpm run icons:sync - **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 +For desktop, see @apps/desktop/CLAUDE.md +For mobile, see @apps/mobile/CLAUDE.md ### Internationalization @@ -154,6 +136,7 @@ Examples: 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. +5. **Never use `defaultValue` in translations** - Always add proper translations to all three required language files: `en.json`, `zh-CN.json`, and `ja.json` in the appropriate feature directories under `locales/` Example: @@ -166,25 +149,6 @@ Example: } ``` -## 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 @@ -198,26 +162,13 @@ Example: - Shared UI components in `packages/internal/components/` - Platform-specific components in respective app directories - Use TypeScript interfaces for component props +- **Detailed guidelines**: See @packages/internal/CLAUDE.md for component development patterns ### 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 @@ -348,7 +299,7 @@ Claude Code has access to specialized agents for different development tasks. ** ## Agent Usage Notes -- **Primary web app is at `@apps/desktop/layer/renderer`** - A Vite + React SPA, not full Electron features +- **Primary web app is at `apps/desktop/layer/renderer`** - A Vite + React SPA, not full Electron features - **SSR app is minimal** - Only for external sharing pages, not main development focus - **Mobile app** - React Native with Expo for iOS/Android - **Always use Task tool with appropriate agent** - Don't implement complex features directly, delegate to specialized agents diff --git a/apps/desktop/CLAUDE.md b/apps/desktop/CLAUDE.md new file mode 100644 index 000000000..0b3e5676e --- /dev/null +++ b/apps/desktop/CLAUDE.md @@ -0,0 +1,113 @@ +# Desktop App Development Guide + +This file provides specific guidance for developing the Electron desktop application. + +## Architecture + +- **Main Process** (`layer/main/`) - Electron main process handling system integration +- **Renderer Process** (`layer/renderer/`) - Vite + React renderer (primary web app) + +The renderer is the **primary web application** - a Vite + React SPA that can run both in Electron and as a standalone web app. + +## UI Style + +- **UI Design Style**: Follow Vercel and Linear SaaS UI aesthetics - clean, modern, minimal design with subtle shadows, rounded corners, and excellent typography +- **Tailwind CSS** for styling across all platforms +- Platform-specific Tailwind configs in each app + +## Development Commands + +```bash +# Recommended: Browser development (faster) +pnpm run dev:web + +# Full Electron development +pnpm run dev:electron + +# Build web version +pnpm run build:web +``` + +## 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) + +## Using Framer Motion + +- **LazyMotion Integration**: Project uses Framer Motion with LazyMotion for optimized bundle size +- **Usage Rule**: Always use `m.` instead of `motion.` when creating animated components +- **Import**: `import { m } from 'motion/react'` +- **Examples**: `m.div`, `m.button`, `m.span` (not `motion.div`, `motion.button`, etc.) +- **Benefits**: Reduces bundle size while maintaining all Framer Motion functionality +- **Prefer Spring Presets**: Use predefined spring animations from `@follow/components/constants/spring.js` +- **Available Presets Constants**: `Spring.presets.smooth`, `Spring.presets.snappy`, `Spring.presets.bouncy` (extracted from Apple's spring parameters) +- **Usage Example**: `transition={Spring.presets.smooth}` or `transition={Spring.snappy(0.3, 0.1)}` +- **Customization**: All presets accept optional `duration` and `extraBounce` parameters + +## Reusable UI Components + +When building UI components, follow this hierarchy: + +1. **Check Existing Components First**: Look in `apps/desktop/layer/renderer/src/modules/renderer/components` for app-specific components +2. **Create Reusable Components**: If the component doesn't exist and is **generic/reusable** (not tied to specific app business logic), create it in `packages/internal/components` + +### Guidelines for Reusable Components (`packages/internal/components`) + +- **Purpose**: Components should be generic and reusable across different apps/contexts +- **No Business Logic**: Avoid coupling with specific app business logic, APIs, or state management +- **Follow All Style Rules**: Must adhere to UIKit colors, MingCute icons (`i-mgc-` prefix), and Framer Motion (`m.` prefix) guidelines +- **Export Pattern**: Export components from appropriate index files for clean imports +- **TypeScript**: Use proper TypeScript interfaces for props and maintain type safety + +**Example Structure**: + +``` +packages/internal/components/ +├── ui/ # Basic UI primitives (Button, Input, Modal) +├── layout/ # Layout components (Grid, Stack, Container) +├── feedback/ # User feedback (Toast, Loading, Alert) +└── index.ts # Main exports +``` + +**Import Examples**: + +```tsx +// Correct - from shared components +import { Button, Modal } from "@follow/components" + +// App-specific components stay in name/components +import { FeedList } from "~/modules/name/components" +``` + +## Build Outputs + +- Desktop: `apps/desktop/out/` for packaged applications +- Web: `apps/desktop/out/web/` for static web assets diff --git a/apps/desktop/layer/main/src/manager/window.ts b/apps/desktop/layer/main/src/manager/window.ts index 286db9eb4..e214364e8 100644 --- a/apps/desktop/layer/main/src/manager/window.ts +++ b/apps/desktop/layer/main/src/manager/window.ts @@ -22,9 +22,13 @@ import { loadDynamicRenderEntry } from "~/updater/hot-updater" const __dirname = fileURLToPath(new URL(".", import.meta.url)) class WindowManagerStatic { - static readonly mainWindowDefaultSize = { - height: 900, - width: 1600, + static get mainWindowDefaultSize() { + const primaryDisplay = screen.getPrimaryDisplay() + const { workAreaSize } = primaryDisplay + return { + height: workAreaSize.height, + width: workAreaSize.width, + } } // Window configuration properties for better DX @@ -346,8 +350,10 @@ class WindowManagerStatic { const defaultSize = WindowManagerStatic.mainWindowDefaultSize - const width = Math.min(windowState?.width || defaultSize.width, maxWidth) - const height = Math.min(windowState?.height || defaultSize.height, maxHeight) + const width = windowState?.width ? Math.min(windowState.width, maxWidth) : defaultSize.width + const height = windowState?.height + ? Math.min(windowState.height, maxHeight) + : defaultSize.height const ensureInBounds = (value: number, min: number, max: number): number => { return Math.max(min, Math.min(value, max)) diff --git a/apps/desktop/layer/renderer/package.json b/apps/desktop/layer/renderer/package.json index 5312810f8..39e515511 100644 --- a/apps/desktop/layer/renderer/package.json +++ b/apps/desktop/layer/renderer/package.json @@ -118,7 +118,7 @@ "@follow/models": "workspace:*", "@follow/types": "workspace:*", "@follow/utils": "workspace:*", - "@folo-services/ai-tools": "0.2.19", + "@folo-services/ai-tools": "0.2.20", "@types/node": "24.0.10", "@vite-pwa/assets-generator": "1.0.0", "fake-indexeddb": "6.0.1", diff --git a/apps/desktop/layer/renderer/src/atoms/debug-feature.ts b/apps/desktop/layer/renderer/src/atoms/debug-feature.ts index 0e80022ab..74bd5eb6f 100644 --- a/apps/desktop/layer/renderer/src/atoms/debug-feature.ts +++ b/apps/desktop/layer/renderer/src/atoms/debug-feature.ts @@ -2,6 +2,14 @@ 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"), {}), -) +// Shape: { __override?: boolean, [featureKey: string]: boolean } +export const [ + , + , + useDebugFeatureValue, + useSetDebugFeatureValue, + getDebugFeatureValue, + setDebugFeatureValue, +] = createAtomHooks(atomWithStorage>(getStorageNS("debug-feature"), {})) + +export { useDebugFeatureValue as useDebugFeatures } diff --git a/apps/desktop/layer/renderer/src/atoms/server-configs.ts b/apps/desktop/layer/renderer/src/atoms/server-configs.ts index 312f7c253..8e1632785 100644 --- a/apps/desktop/layer/renderer/src/atoms/server-configs.ts +++ b/apps/desktop/layer/renderer/src/atoms/server-configs.ts @@ -1,11 +1,19 @@ +import { getStorageNS } from "@follow/utils/ns" import type { ExtractResponseData, GetStatusConfigsResponse } from "@follow-app/client-sdk" import PKG from "@pkg" -import { atom } from "jotai" +import { atomWithStorage } from "jotai/utils" import { createAtomHooks } from "~/lib/jotai" export const [, , useServerConfigs, , getServerConfigs, setServerConfigs] = createAtomHooks( - atom>>(null), + atomWithStorage>>( + getStorageNS("server-configs"), + null, + undefined, + { + getOnInit: true, + }, + ), ) export const useIsInMASReview = () => { diff --git a/apps/desktop/layer/renderer/src/atoms/settings/ai.ts b/apps/desktop/layer/renderer/src/atoms/settings/ai.ts index dad9bdc24..36318ff73 100644 --- a/apps/desktop/layer/renderer/src/atoms/settings/ai.ts +++ b/apps/desktop/layer/renderer/src/atoms/settings/ai.ts @@ -1,27 +1,114 @@ import { createSettingAtom } from "@follow/atoms/helper/setting.js" import { defaultAISettings } from "@follow/shared/settings/defaults" -import type { AISettings } from "@follow/shared/settings/interface" +import type { AISettings, MCPService } from "@follow/shared/settings/interface" import { jotaiStore } from "@follow/utils" +import { clamp } from "es-toolkit" import { atom, useAtomValue } from "jotai" -export const createDefaultSettings = (): AISettings => defaultAISettings +export interface WebAISettings extends AISettings { + panelStyle: AIChatPanelStyle +} + +export const createDefaultSettings = (): WebAISettings => ({ + ...defaultAISettings, + panelStyle: AIChatPanelStyle.Fixed, +}) export const { useSettingKey: useAISettingKey, useSettingSelector: useAISettingSelector, setSetting: setAISetting, clearSettings: clearAISettings, - initializeDefaultSettings: initializeDefaultAISettings, + initializeDefaultSettings, getSettings: getAISettings, useSettingValue: useAISettingValue, settingAtom: __aiSettingAtom, } = createSettingAtom("ai", createDefaultSettings) export const aiServerSyncWhiteListKeys = [] -// Local Setting for ai -const aiChatPinnedAtom = atom(false) -export const useAIChatPinned = () => useAtomValue(aiChatPinnedAtom) -export const setAIChatPinned = (pinned: boolean) => { - jotaiStore.set(aiChatPinnedAtom, pinned) +////////// AI Panel Style +export enum AIChatPanelStyle { + Fixed = "fixed", + Floating = "floating", +} + +export const useAIChatPanelStyle = () => useAISettingKey("panelStyle") +export const setAIChatPanelStyle = (style: AIChatPanelStyle) => { + setAISetting("panelStyle", style) +} +export const getAIChatPanelStyle = () => getAISettings().panelStyle + +// Floating panel state atoms +interface FloatingPanelState { + width: number + height: number + x: number + y: number +} + +const DEFAULT_FLOATING_PANEL_WIDTH = 500 +const DEFAULT_FLOATING_PANEL_HEIGHT = clamp(window.innerHeight * 0.9, 600, 1000) +const DEFAULT_FLOATING_PANEL_X = window.innerWidth - DEFAULT_FLOATING_PANEL_WIDTH - 20 +const DEFAULT_FLOATING_PANEL_Y = window.innerHeight - DEFAULT_FLOATING_PANEL_HEIGHT - 20 + +const defaultFloatingPanelState: FloatingPanelState = { + width: DEFAULT_FLOATING_PANEL_WIDTH, + height: DEFAULT_FLOATING_PANEL_HEIGHT, + x: DEFAULT_FLOATING_PANEL_X, + y: DEFAULT_FLOATING_PANEL_Y, +} + +const floatingPanelStateAtom = atom(defaultFloatingPanelState) + +export const useFloatingPanelState = () => useAtomValue(floatingPanelStateAtom) +export const setFloatingPanelState = (state: Partial) => { + const currentState = jotaiStore.get(floatingPanelStateAtom) + jotaiStore.set(floatingPanelStateAtom, { ...currentState, ...state }) +} +export const getFloatingPanelState = () => jotaiStore.get(floatingPanelStateAtom) + +////////// AI Panel Visibility + +const aiPanelVisibilityAtom = atom(false) +export const useAIPanelVisibility = () => useAtomValue(aiPanelVisibilityAtom) +export const setAIPanelVisibility = (visibility: boolean) => { + jotaiStore.set(aiPanelVisibilityAtom, visibility) +} +export const getAIPanelVisibility = () => jotaiStore.get(aiPanelVisibilityAtom) + +////////// MCP Services +export const useMCPEnabled = () => useAISettingKey("mcpEnabled") +export const setMCPEnabled = (enabled: boolean) => { + setAISetting("mcpEnabled", enabled) +} + +export const useMCPServices = () => useAISettingKey("mcpServices") +export const addMCPService = (service: Omit) => { + const services = getAISettings().mcpServices + const newService = { + ...service, + id: Date.now().toString(), + } + setAISetting("mcpServices", [...services, newService]) + return newService.id +} + +export const updateMCPService = (id: string, updates: Partial) => { + const services = getAISettings().mcpServices + const updatedServices = services.map((service) => + service.id === id ? { ...service, ...updates } : service, + ) + setAISetting("mcpServices", updatedServices) +} + +export const removeMCPService = (id: string) => { + const services = getAISettings().mcpServices + const filteredServices = services.filter((service) => service.id !== id) + setAISetting("mcpServices", filteredServices) +} + +//// Enhance Init Ai Settings +export const initializeDefaultAISettings = () => { + initializeDefaultSettings() + if (getAISettings().panelStyle === AIChatPanelStyle.Fixed) setAIPanelVisibility(true) } -export const getAIChatPinned = () => jotaiStore.get(aiChatPinnedAtom) diff --git a/apps/desktop/layer/renderer/src/components/common/LCPEndDetector.tsx b/apps/desktop/layer/renderer/src/components/common/LCPEndDetector.tsx new file mode 100644 index 000000000..8b1ae387c --- /dev/null +++ b/apps/desktop/layer/renderer/src/components/common/LCPEndDetector.tsx @@ -0,0 +1,120 @@ +import { jotaiStore } from "@follow/utils" +import { atom } from "jotai" +import { useEffect } from "react" + +const LCPEndAtom = atom(false) + +/** + * To skip page transition when first load, improve LCP + */ +export const LCPEndDetector = () => { + useEffect(() => { + let hasEnded = false + + const timeoutIds: Array> = [] + const rafIds: number[] = [] + const idleCallbackIds: number[] = [] + + const scheduleRaf = (cb: FrameRequestCallback) => { + if (typeof window !== "undefined" && window.requestAnimationFrame) { + const id = window.requestAnimationFrame(cb) + rafIds.push(id) + } else { + const id = setTimeout(() => cb(performance.now()), 16) + timeoutIds.push(id) + } + } + + const markEnded = () => { + if (hasEnded) return + hasEnded = true + + // Defer to ensure layout/paint and initial CSS transitions settle + scheduleRaf(() => { + scheduleRaf(() => { + // Prefer idle if available to avoid jank + const ric = (typeof window !== "undefined" && (window as any).requestIdleCallback) as + | ((cb: () => void, opts?: { timeout?: number }) => number) + | undefined + if (ric) { + const id = ric(() => jotaiStore.set(LCPEndAtom, true), { + timeout: 200, + }) as unknown as number + idleCallbackIds.push(id) + } else { + const id = setTimeout(() => jotaiStore.set(LCPEndAtom, true), 0) + timeoutIds.push(id) + } + }) + }) + } + + // If PerformanceObserver for LCP is available, prefer it + const supportsPO = typeof PerformanceObserver !== "undefined" + let po: PerformanceObserver | undefined + + const onHidden = () => markEnded() + const onVisibilityChange = () => { + if (document.visibilityState === "hidden") onHidden() + } + const onPageHide = onHidden + const onLoad = () => markEnded() + + let safetyTimer: ReturnType | undefined + let fallbackEndTimer: ReturnType | undefined + + if (supportsPO) { + try { + po = new PerformanceObserver((list) => { + const entries = list.getEntries() + if (entries && entries.length > 0) { + // Any LCP entry indicates a meaningful paint; we can mark end soon + markEnded() + } + }) + // buffered: true ensures we get entries that occurred before observer creation + po.observe({ type: "largest-contentful-paint", buffered: true } as PerformanceObserverInit) + } catch { + // Ignore observer errors and rely on fallback + } + + // When the page is hidden or unloaded, LCP is finalized + window.addEventListener("visibilitychange", onVisibilityChange, { once: true }) + window.addEventListener("pagehide", onPageHide, { once: true }) + window.addEventListener("load", onLoad, { once: true }) + + // Absolute safety net: if nothing fires, end after 3s + safetyTimer = setTimeout(() => markEnded(), 3000) + timeoutIds.push(safetyTimer) + } else { + // Ultimate fallback for environments without PO + fallbackEndTimer = setTimeout(() => { + jotaiStore.set(LCPEndAtom, true) + }, 2000) + timeoutIds.push(fallbackEndTimer) + } + + return () => { + if (po) po.disconnect() + const caf = typeof window !== "undefined" && window.cancelAnimationFrame + if (caf) { + rafIds.forEach((id) => (window.cancelAnimationFrame as (h: number) => void)(id)) + } + const cic = (typeof window !== "undefined" && (window as any).cancelIdleCallback) as + | ((id: number) => void) + | undefined + if (cic) idleCallbackIds.forEach((id) => cic(id)) + timeoutIds.forEach((id) => clearTimeout(id)) + if (safetyTimer) clearTimeout(safetyTimer) + if (fallbackEndTimer) clearTimeout(fallbackEndTimer) + + window.removeEventListener("visibilitychange", onVisibilityChange) + window.removeEventListener("pagehide", onPageHide) + window.removeEventListener("load", onLoad) + } + }, []) + return null +} + +// eslint-disable-next-line react-refresh/only-export-components +export const isLCPEnded = () => jotaiStore.get(LCPEndAtom) diff --git a/apps/desktop/layer/renderer/src/components/common/Motion.tsx b/apps/desktop/layer/renderer/src/components/common/Motion.tsx index 77330e1ba..0d2239616 100644 --- a/apps/desktop/layer/renderer/src/components/common/Motion.tsx +++ b/apps/desktop/layer/renderer/src/components/common/Motion.tsx @@ -4,15 +4,25 @@ import { createElement } from "react" import { useReduceMotion } from "~/hooks/biz/useReduceMotion" +import { isLCPEnded } from "./LCPEndDetector" + +type WithLCPOptimization

= P & { lcpOptimization?: boolean } +// Narrow exported proxy type so each motion component accepts `lcpOptimization` +export type MotionProxy = { + [K in keyof typeof M]: (typeof M)[K] extends React.ComponentType + ? React.ComponentType> + : (typeof M)[K] +} + const cacheMap = new Map() -export const m: typeof M = new Proxy(M, { +export const m: MotionProxy = new Proxy(M, { get(target, p: string) { const Component = target[p] if (cacheMap.has(p)) { return cacheMap.get(p) } - const MotionComponent = ({ ref, ...props }) => { + const MotionComponent = ({ ref, lcpOptimization, ...props }) => { const shouldReduceMotion = useReduceMotion() const nextProps = { ...props } if (shouldReduceMotion) { @@ -33,6 +43,11 @@ export const m: typeof M = new Proxy(M, { } } + // Disable initial animation before hydration ends to optimize LCP + if (lcpOptimization && !isLCPEnded()) { + nextProps.initial = false + } + return createElement(Component, { ...nextProps, ref }) } diff --git a/apps/desktop/layer/renderer/src/components/ui/button/GlassButton.tsx b/apps/desktop/layer/renderer/src/components/ui/button/GlassButton.tsx index 238848425..ab6d33327 100644 --- a/apps/desktop/layer/renderer/src/components/ui/button/GlassButton.tsx +++ b/apps/desktop/layer/renderer/src/components/ui/button/GlassButton.tsx @@ -155,7 +155,7 @@ export const GlassButton: FC = ({ tapScale = 0.95, size = "md", theme = "auto", - variant = "glass", + variant = "flat", }) => { return ( diff --git a/apps/desktop/layer/renderer/src/components/ui/code-highlighter/shiki/Shiki.tsx b/apps/desktop/layer/renderer/src/components/ui/code-highlighter/shiki/Shiki.tsx index 008bd2c5c..c5379cfc8 100644 --- a/apps/desktop/layer/renderer/src/components/ui/code-highlighter/shiki/Shiki.tsx +++ b/apps/desktop/layer/renderer/src/components/ui/code-highlighter/shiki/Shiki.tsx @@ -2,7 +2,7 @@ import { ELECTRON_BUILD } from "@follow/shared/constants" import { cn } from "@follow/utils/utils" import { useIsomorphicLayoutEffect } from "foxact/use-isomorphic-layout-effect" import type { FC } from "react" -import { useInsertionEffect, useMemo, useRef, useState } from "react" +import { memo, useInsertionEffect, useMemo, useRef, useState } from "react" import type { BundledLanguage, BundledTheme, @@ -155,6 +155,7 @@ export const ShikiHighLighter: FC = (props) => { return } +export const MemoizedShikiCode = memo(ShikiHighLighter) const ShikiCode: FC< ShikiProps & { codeTheme: string diff --git a/apps/desktop/layer/renderer/src/components/ui/crop/AvatarUploadModal.tsx b/apps/desktop/layer/renderer/src/components/ui/crop/AvatarUploadModal.tsx index 59c9223b6..00bdb3286 100644 --- a/apps/desktop/layer/renderer/src/components/ui/crop/AvatarUploadModal.tsx +++ b/apps/desktop/layer/renderer/src/components/ui/crop/AvatarUploadModal.tsx @@ -377,7 +377,12 @@ export const AvatarUploadModal = ({

{!selectedImage ? (
- +
diff --git a/apps/desktop/layer/renderer/src/components/ui/dropdown-menu/dropdown-menu.tsx b/apps/desktop/layer/renderer/src/components/ui/dropdown-menu/dropdown-menu.tsx index 1177cd6dd..9142adadd 100644 --- a/apps/desktop/layer/renderer/src/components/ui/dropdown-menu/dropdown-menu.tsx +++ b/apps/desktop/layer/renderer/src/components/ui/dropdown-menu/dropdown-menu.tsx @@ -121,6 +121,7 @@ const DropdownMenuItem = ({ active, highlightColor = "accent", shortcut, + checked, ...props }: React.ComponentPropsWithoutRef & { inset?: boolean @@ -128,6 +129,7 @@ const DropdownMenuItem = ({ active?: boolean highlightColor?: "accent" | "gray" shortcut?: string + checked?: boolean } & { ref?: React.Ref | null> }) => ( )} + {checked && !shortcut && ( + <> + + + + + + )} ) DropdownMenuItem.displayName = DropdownMenuPrimitive.Item.displayName diff --git a/apps/desktop/layer/renderer/src/components/ui/media/SwipeMedia.tsx b/apps/desktop/layer/renderer/src/components/ui/media/SwipeMedia.tsx index be7a75fb4..428fb9c62 100644 --- a/apps/desktop/layer/renderer/src/components/ui/media/SwipeMedia.tsx +++ b/apps/desktop/layer/renderer/src/components/ui/media/SwipeMedia.tsx @@ -35,13 +35,23 @@ export function SwipeMedia({ const [emblaRef, emblaApi] = useEmblaCarousel({ loop: true }, [WheelGesturesPlugin()]) - const scrollPrev = useCallback(() => { - if (emblaApi) emblaApi.scrollPrev() - }, [emblaApi]) + const scrollPrev = useCallback( + (e) => { + e.preventDefault() + e.stopPropagation() + if (emblaApi) emblaApi.scrollPrev() + }, + [emblaApi], + ) - const scrollNext = useCallback(() => { - if (emblaApi) emblaApi.scrollNext() - }, [emblaApi]) + const scrollNext = useCallback( + (e) => { + e.preventDefault() + e.stopPropagation() + if (emblaApi) emblaApi.scrollNext() + }, + [emblaApi], + ) if (!media) return null @@ -70,6 +80,8 @@ export function SwipeMedia({ loading="lazy" proxy={proxySize || undefined} blurhash={med.blurhash} + width={med.width} + height={med.height} onClick={(e) => { if (onPreview) { e.stopPropagation() diff --git a/apps/desktop/layer/renderer/src/hooks/biz/useEntryActions.tsx b/apps/desktop/layer/renderer/src/hooks/biz/useEntryActions.tsx index 9176c65f6..7b5e78bda 100644 --- a/apps/desktop/layer/renderer/src/hooks/biz/useEntryActions.tsx +++ b/apps/desktop/layer/renderer/src/hooks/biz/useEntryActions.tsx @@ -21,7 +21,6 @@ import { setReadabilityStatus, useEntryIsInReadability, } from "~/atoms/readability" -import { useAIChatPinned } from "~/atoms/settings/ai" import { useIntegrationSettingValue } from "~/atoms/settings/integration" import { useShowSourceContent } from "~/atoms/source-content" import { ipcServices } from "~/lib/client" @@ -31,7 +30,6 @@ 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 }) => { @@ -212,7 +210,7 @@ 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, @@ -249,8 +247,7 @@ 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 @@ -441,14 +438,6 @@ export const useEntryActions = ({ entryId, }), - new EntryActionMenuItem({ - id: COMMAND_ID.global.toggleAIChatPinned, - onClick: runCmdFn(COMMAND_ID.global.toggleAIChatPinned, [{ entryId }]), - entryId, - active: isShowAIChatPinned, - hide: !aiEnabled, - }), - // Custom Integration with sub-menu ...(() => { const customIntegrations = integrationSettings.customIntegration || [] @@ -513,8 +502,7 @@ export const useEntryActions = ({ isCollection, compact, isEntryInReadability, - isShowAIChatPinned, - aiEnabled, + integrationSettings.customIntegration, integrationSettings.enableCustomIntegration, ]) diff --git a/apps/desktop/layer/renderer/src/hooks/biz/useFeature.ts b/apps/desktop/layer/renderer/src/hooks/biz/useFeature.ts index aa73267b1..106e2d505 100644 --- a/apps/desktop/layer/renderer/src/hooks/biz/useFeature.ts +++ b/apps/desktop/layer/renderer/src/hooks/biz/useFeature.ts @@ -1,12 +1,58 @@ -import { useDebugFeatureValue } from "~/atoms/debug-feature" -import { useServerConfigs } from "~/atoms/server-configs" +import { getDebugFeatureValue, useDebugFeatureValue } from "~/atoms/debug-feature" +import { getServerConfigs, 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 +// Define debug feature value structure +interface DebugFeatureValue { + __override?: boolean + [key: string]: boolean | undefined +} + +// Define feature key type +export type FeatureKey = keyof typeof featureConfigMap + +/** + * Core feature checking logic to avoid code duplication + * @param feature - Feature key name + * @param debugFeatureValue - Debug feature values + * @param serverConfigs - Server configuration + * @returns Whether the feature is enabled + */ +const checkFeatureEnabled = ( + feature: FeatureKey, + debugFeatureValue: DebugFeatureValue, + serverConfigs: ReturnType, +): boolean => { + const override = !!debugFeatureValue.__override + + if (override) { + return !!debugFeatureValue[feature] + } + + const serverConfigKey = featureConfigMap[feature] + return !!(serverConfigKey && serverConfigs?.[serverConfigKey]) +} + +/** + * React Hook: Check if a specific feature is enabled + * @param feature - Feature key name + * @returns Whether the feature is enabled + */ +export const useFeature = (feature: FeatureKey): boolean => { + const debugFeatureValue = useDebugFeatureValue() as DebugFeatureValue + const serverConfigs = useServerConfigs() + + return checkFeatureEnabled(feature, debugFeatureValue, serverConfigs) +} + +/** + * Non-Hook function: Check if a specific feature is enabled + * @param feature - Feature key name + * @returns Whether the feature is enabled + */ +export const getFeature = (feature: FeatureKey): boolean => { + const debugFeatureValue = getDebugFeatureValue() as DebugFeatureValue + const serverConfigs = getServerConfigs() + + return checkFeatureEnabled(feature, debugFeatureValue, serverConfigs) } diff --git a/apps/desktop/layer/renderer/src/initialize/index.ts b/apps/desktop/layer/renderer/src/initialize/index.ts index cdad3c140..5490b53af 100644 --- a/apps/desktop/layer/renderer/src/initialize/index.ts +++ b/apps/desktop/layer/renderer/src/initialize/index.ts @@ -14,9 +14,9 @@ import { subscribeNetworkStatus } from "../atoms/network" import { appLog } from "../lib/log" import { initAnalytics } from "./analytics" import { registerHistoryStack } from "./history" -import { hydrateSettings } from "./hydrate" import { doMigration } from "./migrates" import { initSentry } from "./sentry" +import { initializeSettings } from "./settings" declare global { interface Window { @@ -80,7 +80,7 @@ export const initializeApp = async () => { subscribeNetworkStatus() - apm("hydrateSettings", hydrateSettings) + apm("initializeSettings", initializeSettings) initSentry() await apm("i18n", initI18n) diff --git a/apps/desktop/layer/renderer/src/initialize/hydrate.ts b/apps/desktop/layer/renderer/src/initialize/settings.ts similarity index 70% rename from apps/desktop/layer/renderer/src/initialize/hydrate.ts rename to apps/desktop/layer/renderer/src/initialize/settings.ts index 5e3a150c4..ef75d72c4 100644 --- a/apps/desktop/layer/renderer/src/initialize/hydrate.ts +++ b/apps/desktop/layer/renderer/src/initialize/settings.ts @@ -1,9 +1,11 @@ +import { initializeDefaultAISettings } from "~/atoms/settings/ai" import { initializeDefaultGeneralSettings } from "~/atoms/settings/general" import { initializeDefaultIntegrationSettings } from "~/atoms/settings/integration" import { initializeDefaultUISettings } from "~/atoms/settings/ui" -export const hydrateSettings = () => { +export const initializeSettings = () => { initializeDefaultUISettings() initializeDefaultGeneralSettings() initializeDefaultIntegrationSettings() + initializeDefaultAISettings() } diff --git a/apps/desktop/layer/renderer/src/lib/avatar-upload.ts b/apps/desktop/layer/renderer/src/lib/avatar-upload.ts index 2db9092f8..86788e989 100644 --- a/apps/desktop/layer/renderer/src/lib/avatar-upload.ts +++ b/apps/desktop/layer/renderer/src/lib/avatar-upload.ts @@ -1,6 +1,6 @@ import { toast } from "sonner" -import { apiClient, apiFetch } from "./api-fetch" +import { followApi } from "./api-client" import { getFetchErrorMessage } from "./error-parser" /** @@ -10,19 +10,14 @@ import { getFetchErrorMessage } from "./error-parser" * @returns Promise - The uploaded image URL */ export async function uploadAvatarBlob(blob: Blob): Promise { - const formData = new FormData() - formData.append("file", blob, "avatar.jpg") + const { url } = await followApi.upload + .uploadAvatar({ + file: blob, + }) + .catch((err) => { + toast.error(getFetchErrorMessage(err)) + throw err + }) - const res = await apiFetch<{ - url: string - }>(apiClient.upload.avatar.$url().toString(), { - method: "POST", - - body: formData, - }).catch((err) => { - toast.error(getFetchErrorMessage(err)) - throw err - }) - - return res.url + return url } diff --git a/apps/desktop/layer/renderer/src/lib/features.tsx b/apps/desktop/layer/renderer/src/lib/features.tsx index 7de933ade..f218f0a41 100644 --- a/apps/desktop/layer/renderer/src/lib/features.tsx +++ b/apps/desktop/layer/renderer/src/lib/features.tsx @@ -3,10 +3,9 @@ import type { FC } from "react" import { useFeature } from "~/hooks/biz/useFeature" -export const featureConfigMap: Record> = - { - ai: "AI_CHAT_ENABLED", - } +export const featureConfigMap = { + ai: "AI_CHAT_ENABLED", +} satisfies Record> export const withFeature = (feature: keyof typeof featureConfigMap) => diff --git a/apps/desktop/layer/renderer/src/lib/simple-text-selection.ts b/apps/desktop/layer/renderer/src/lib/simple-text-selection.ts index 95853048c..57c3871a5 100644 --- a/apps/desktop/layer/renderer/src/lib/simple-text-selection.ts +++ b/apps/desktop/layer/renderer/src/lib/simple-text-selection.ts @@ -25,9 +25,13 @@ export function addTextSelectionListener( if (!selection) return // Check if selection is within our shadow root - const range = selection.getRangeAt(0) - if (!shadowRoot.contains(range.commonAncestorContainer)) return - + try { + const range = selection.getRangeAt(0) + if (!shadowRoot.contains(range.commonAncestorContainer)) return + } catch { + // Uncaught IndexSizeError: Failed to execute 'getRangeAt' on 'Selection': 0 is not a valid index. + return + } if (!selection.isCollapsed) { const selectedText = selection.toString().trim() if (selectedText) { diff --git a/apps/desktop/layer/renderer/src/modules/activation/NeedActivationToast.tsx b/apps/desktop/layer/renderer/src/modules/activation/NeedActivationToast.tsx index c64af9b58..c9370c41b 100644 --- a/apps/desktop/layer/renderer/src/modules/activation/NeedActivationToast.tsx +++ b/apps/desktop/layer/renderer/src/modules/activation/NeedActivationToast.tsx @@ -3,7 +3,7 @@ import { stopPropagation } from "@follow/utils/dom" import { useCallback } from "react" import { useTranslation } from "react-i18next" -import { useSettingModal } from "../settings/modal/useSettingModal" +import { useSettingModal } from "../settings/modal/use-setting-modal-hack" export const NeedActivationToast = (props: { dimiss: () => void }) => { const settingModalPresent = useSettingModal() diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/components/context-bar/blocks/ContextBlock.tsx b/apps/desktop/layer/renderer/src/modules/ai-chat/components/context-bar/blocks/ContextBlock.tsx new file mode 100644 index 000000000..fc587a07f --- /dev/null +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/components/context-bar/blocks/ContextBlock.tsx @@ -0,0 +1,207 @@ +import { clsx, cn } from "@follow/utils/utils" +import type { FC } from "react" +import { memo } from "react" + +import { ImageThumbnail } from "~/modules/ai-chat/components/layouts/ImageThumbnail" +import { CircularProgress } from "~/modules/ai-chat/components/ui/UploadProgress" +import { useChatBlockActions } from "~/modules/ai-chat/store/hooks" +import type { AIChatContextBlock } from "~/modules/ai-chat/store/types" +import { + getFileCategoryFromMimeType, + getFileIconName, +} from "~/modules/ai-chat/utils/file-validation" + +import { EntryTitle, FeedTitle } from "./TitleComponents" + +export const ContextBlock: FC<{ block: AIChatContextBlock }> = memo(({ block }) => { + const blockActions = useChatBlockActions() + + 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" + } + case "fileAttachment": { + const { type, dataUrl, previewUrl } = block.attachment + const fileCategory = getFileCategoryFromMimeType(type) + + // Don't show icon for images with thumbnails, as the thumbnail serves as the icon + if (fileCategory === "image" && (dataUrl || previewUrl)) { + return null + } + + return getFileIconName(fileCategory) + } + + default: { + return "i-mgc-paper-cute-fi" + } + } + } + + const getDisplayContent = () => { + switch (block.type) { + case "mainEntry": + case "referEntry": { + return + } + case "referFeed": { + return + } + case "selectedText": { + return `"${block.value}"` + } + case "fileAttachment": { + const { type, name, dataUrl, previewUrl, uploadStatus, errorMessage, uploadProgress } = + block.attachment + + const fileCategory = getFileCategoryFromMimeType(type) + + if (fileCategory === "image" && (dataUrl || previewUrl)) { + return ( +
+
+ + {uploadStatus === "uploading" && uploadProgress !== undefined && ( +
+ +
+ )} + {uploadStatus === "error" && ( +
+ +
+ )} +
+ +
+ + {name}{" "} + {uploadStatus === "uploading" && uploadProgress !== undefined && ( +
+ ({Math.round(uploadProgress)}%) +
+ )} +
+ + {uploadStatus === "error" &&
Upload failed
} +
+
+ ) + } + + // For non-image files + return ( +
+ {name} + {uploadStatus === "uploading" && uploadProgress !== undefined && ( +
+ + {Math.round(uploadProgress)}% +
+ )} + {uploadStatus === "error" && ( + + )} +
+ ) + } + default: { + // This should never happen with proper discriminated union + return "" + } + } + } + + const getBlockLabel = () => { + switch (block.type) { + case "mainEntry": { + return "Current" + } + case "referEntry": { + return "Ref" + } + case "referFeed": { + return "Feed" + } + case "selectedText": { + return "Text" + } + case "fileAttachment": { + return "File" + } + + default: { + return "" + } + } + } + + const canRemove = block.type !== "mainEntry" + + return ( +
+
+
+
+ {getBlockIcon() && } + {getBlockLabel()} +
+ + {getDisplayContent()} +
+
+ + {canRemove && ( + + )} +
+ ) +}) diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/components/context-bar/blocks/TitleComponents.tsx b/apps/desktop/layer/renderer/src/modules/ai-chat/components/context-bar/blocks/TitleComponents.tsx new file mode 100644 index 000000000..5dae8b520 --- /dev/null +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/components/context-bar/blocks/TitleComponents.tsx @@ -0,0 +1,22 @@ +import { useEntry } from "@follow/store/entry/hooks" +import { useFeedById } from "@follow/store/feed/hooks" +import type { FC } from "react" + +export const EntryTitle: FC<{ entryId?: string; fallback: string }> = ({ entryId, fallback }) => { + const entryTitle = useEntry(entryId!, (e) => e?.title) + + if (!entryId || !entryTitle) { + return {fallback} + } + + return {entryTitle} +} + +export const FeedTitle: FC<{ feedId?: string; fallback: string }> = ({ feedId, fallback }) => { + const feed = useFeedById(feedId, (feed) => ({ title: feed?.title })) + if (!feedId || !feed) { + return {fallback} + } + + return {feed.title} +} diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/components/context-bar/blocks/index.ts b/apps/desktop/layer/renderer/src/modules/ai-chat/components/context-bar/blocks/index.ts new file mode 100644 index 000000000..a56ac358c --- /dev/null +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/components/context-bar/blocks/index.ts @@ -0,0 +1,2 @@ +export * from "./ContextBlock" +export * from "./TitleComponents" diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/components/context-bar/index.ts b/apps/desktop/layer/renderer/src/modules/ai-chat/components/context-bar/index.ts new file mode 100644 index 000000000..c738c4322 --- /dev/null +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/components/context-bar/index.ts @@ -0,0 +1,3 @@ +export * from "./blocks" +export * from "./menus" +export * from "./pickers" diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/components/context-bar/menus/ContextMenuContent.tsx b/apps/desktop/layer/renderer/src/modules/ai-chat/components/context-bar/menus/ContextMenuContent.tsx new file mode 100644 index 000000000..26e84e174 --- /dev/null +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/components/context-bar/menus/ContextMenuContent.tsx @@ -0,0 +1,71 @@ +import type { FC } from "react" + +import { + DropdownMenuContent, + DropdownMenuSeparator, + DropdownMenuSub, + DropdownMenuSubContent, + DropdownMenuSubTrigger, +} from "~/components/ui/dropdown-menu/dropdown-menu" +import { useChatBlockActions } from "~/modules/ai-chat/store/hooks" + +import { CurrentFeedEntriesPickerList, FeedPickerList, RecentEntriesPickerList } from "../pickers" + +export const ContextMenuContent: FC = () => { + const blockActions = useChatBlockActions() + + return ( + + + + + Current Feed Entries + + + + blockActions.addBlock({ + type: "referEntry", + value: entryId, + }) + } + /> + + + + + + + + Reference Entry + + + + blockActions.addBlock({ + type: "referEntry", + value: entryId, + }) + } + /> + + + + + + Reference Feed + + + + blockActions.addBlock({ + type: "referFeed", + value: feedId, + }) + } + /> + + + + ) +} diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/components/context-bar/menus/ShortcutsMenuContent.tsx b/apps/desktop/layer/renderer/src/modules/ai-chat/components/context-bar/menus/ShortcutsMenuContent.tsx new file mode 100644 index 000000000..60c8ce996 --- /dev/null +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/components/context-bar/menus/ShortcutsMenuContent.tsx @@ -0,0 +1,50 @@ +import type { FC } from "react" + +import { + DropdownMenuContent, + DropdownMenuItem, + DropdownMenuSeparator, +} from "~/components/ui/dropdown-menu/dropdown-menu" +import { useSettingModal } from "~/modules/settings/modal/use-setting-modal-hack" + +interface ShortcutsMenuContentProps { + shortcuts: Array<{ + id: string + name: string + prompt: string + enabled: boolean + }> + onSendShortcut?: (prompt: string) => void +} + +export const ShortcutsMenuContent: FC = ({ + shortcuts, + onSendShortcut, +}) => { + const showSettingModal = useSettingModal() + const enabledShortcuts = shortcuts.filter((shortcut) => shortcut.enabled) + + return ( + + {enabledShortcuts.length === 0 ? ( +
No shortcuts configured
+ ) : ( + enabledShortcuts.map((shortcut) => ( + onSendShortcut?.(shortcut.prompt)}> + + {shortcut.name} + + )) + )} + + { + showSettingModal("ai") + }} + > + + Manage Shortcut + +
+ ) +} diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/components/context-bar/menus/index.ts b/apps/desktop/layer/renderer/src/modules/ai-chat/components/context-bar/menus/index.ts new file mode 100644 index 000000000..40b4ecebe --- /dev/null +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/components/context-bar/menus/index.ts @@ -0,0 +1,2 @@ +export * from "./ContextMenuContent" +export * from "./ShortcutsMenuContent" diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/components/context-bar/pickers/EntryPickers.tsx b/apps/desktop/layer/renderer/src/modules/ai-chat/components/context-bar/pickers/EntryPickers.tsx new file mode 100644 index 000000000..e23e1e361 --- /dev/null +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/components/context-bar/pickers/EntryPickers.tsx @@ -0,0 +1,57 @@ +import { useEntry, useEntryIdsByFeedId, useEntryIdsByView } from "@follow/store/entry/hooks" +import { useEntryStore } from "@follow/store/entry/store" +import type { FC } from "react" +import { useMemo } from "react" + +import { useRouteParamsSelector } from "~/hooks/biz/useRouteParams" +import { useAIChatStore } from "~/modules/ai-chat/store/AIChatContext" + +import type { PickerItem } from "./PickerList" +import { PickerList } from "./PickerList" + +export const CurrentFeedEntriesPickerList: FC<{ onSelect: (entryId: string) => void }> = ({ + onSelect, +}) => { + const mainEntryId = useAIChatStore()((s) => { + const block = s.blocks.find((b) => b.type === "mainEntry") + return block && block.type === "mainEntry" ? block.value : undefined + }) + const feedId = useEntry(mainEntryId, (e) => e?.feedId) + + const entryIds = useEntryIdsByFeedId(feedId!) + + return +} + +export const RecentEntriesPickerList: FC<{ onSelect: (entryId: string) => void }> = ({ + onSelect, +}) => { + const view = useRouteParamsSelector((route) => route.view) + const recentEntryIds = useEntryIdsByView(view, false) + + return +} + +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 ( + + ) +} diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/components/context-bar/pickers/FeedPickers.tsx b/apps/desktop/layer/renderer/src/modules/ai-chat/components/context-bar/pickers/FeedPickers.tsx new file mode 100644 index 000000000..0fb147d92 --- /dev/null +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/components/context-bar/pickers/FeedPickers.tsx @@ -0,0 +1,59 @@ +import { getFeedById } from "@follow/store/feed/getter" +import { useFeedById } from "@follow/store/feed/hooks" +import { useAllFeedSubscription } from "@follow/store/subscription/hooks" +import type { FC } from "react" +import { useMemo } from "react" + +import { DropdownMenuItem } from "~/components/ui/dropdown-menu/dropdown-menu" + +import type { PickerItem } from "./PickerList" +import { PickerList } from "./PickerList" + +export 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 ( + ( + + )} + /> + ) +} + +// 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 ( + onSelect(feedId)} className="text-xs"> + {displayTitle} + + ) +} diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/components/context-bar/pickers/PickerList.tsx b/apps/desktop/layer/renderer/src/modules/ai-chat/components/context-bar/pickers/PickerList.tsx new file mode 100644 index 000000000..fc2902ae8 --- /dev/null +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/components/context-bar/pickers/PickerList.tsx @@ -0,0 +1,75 @@ +import { stopPropagation } from "@follow/utils" +import Fuse from "fuse.js" +import { useMemo, useState } from "react" +import { useDebounceCallback } from "usehooks-ts" + +import { DropdownMenuItem } from "~/components/ui/dropdown-menu/dropdown-menu" + +import { SearchInput } from "./SearchInput" + +// Generic Picker Component +export interface PickerItem { + id: string + title: string +} + +export interface PickerListProps { + items: T[] + placeholder: string + onSelect: (id: string) => void + renderItem?: (item: T, onSelect: (id: string) => void) => React.ReactNode + noResultsText?: string +} + +export const PickerList = ({ + items, + placeholder, + onSelect, + renderItem, + noResultsText = "No items found", +}: PickerListProps) => { + 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) => ( + onSelect(item.id)} className="text-xs"> + {item.title} + + ) + + return ( +
+ { + debouncedSetSearchTerm(e.target.value) + }} + /> +
+ {filteredItems.length === 0 ? ( +
{noResultsText}
+ ) : ( + filteredItems.map((item) => + renderItem ? renderItem(item, onSelect) : defaultRenderItem(item, onSelect), + ) + )} +
+
+ ) +} diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/components/context-bar/pickers/SearchInput.tsx b/apps/desktop/layer/renderer/src/modules/ai-chat/components/context-bar/pickers/SearchInput.tsx new file mode 100644 index 000000000..0ff5b2813 --- /dev/null +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/components/context-bar/pickers/SearchInput.tsx @@ -0,0 +1,14 @@ +import type { FC } from "react" + +export const SearchInput: FC> = (props) => { + return ( +
+ + +
+ ) +} diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/components/context-bar/pickers/index.ts b/apps/desktop/layer/renderer/src/modules/ai-chat/components/context-bar/pickers/index.ts new file mode 100644 index 000000000..58a4b8075 --- /dev/null +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/components/context-bar/pickers/index.ts @@ -0,0 +1,4 @@ +export * from "./EntryPickers" +export * from "./FeedPickers" +export * from "./PickerList" +export * from "./SearchInput" diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/components/displays/AIDisplayFlowPart.tsx b/apps/desktop/layer/renderer/src/modules/ai-chat/components/displays/AIDisplayFlowPart.tsx index b731e0f69..ed9e05a7c 100644 --- a/apps/desktop/layer/renderer/src/modules/ai-chat/components/displays/AIDisplayFlowPart.tsx +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/components/displays/AIDisplayFlowPart.tsx @@ -1,11 +1,46 @@ import "@xyflow/react/dist/style.css" import { useIsDark } from "@follow/hooks" -import { Background, ReactFlow } from "@xyflow/react" +import { cn } from "@follow/utils/utils" +import { Background, Controls, ReactFlow } from "@xyflow/react" +import { useCallback } from "react" + +import { useModalStack } from "~/components/ui/modal/stacked/hooks" import type { AIDisplayFlowTool } from "../../store/types" import { toolMemo } from "./share" +const FlowPreviewModal = ({ + nodes, + edges, + colorMode, +}: { + nodes: any[] + edges: any[] + colorMode: "light" | "dark" +}) => { + return ( +
+ + + + +
+ ) +} + export const AIDisplayFlowPart = toolMemo( ({ part, loadingElement }: { part: AIDisplayFlowTool; loadingElement: React.ReactNode }) => { if (!part.input) return loadingElement @@ -15,8 +50,22 @@ export const AIDisplayFlowPart = toolMemo( const { nodes, edges } = part.input.flowChart as any const colorMode = useIsDark() ? "dark" : "light" + const { present } = useModalStack() + + const handleOpenModal = useCallback(() => { + present({ + title: "Flow Chart Preview", + content: () => , + max: true, + canClose: true, + clickOutsideToDismiss: false, + modalContentClassName: "p-0 h-full", + modalClassName: "h-[90vh] w-[90vw]", + }) + }, [nodes, edges, colorMode, present]) + return ( -
+
+ + + {/* Expand/Preview button */} +
) }, diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/components/file/GlobalFileDropZone.tsx b/apps/desktop/layer/renderer/src/modules/ai-chat/components/file/GlobalFileDropZone.tsx new file mode 100644 index 000000000..7b126bdc0 --- /dev/null +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/components/file/GlobalFileDropZone.tsx @@ -0,0 +1,146 @@ +import { Spring } from "@follow/components/constants/spring.js" +import { cn } from "@follow/utils" +import { AnimatePresence, m } from "motion/react" +import type { FC, PropsWithChildren } from "react" +import { memo, useCallback, useRef, useState } from "react" + +import { useFileUploadWithDefaults } from "../../hooks/useFileUpload" + +interface GlobalFileDropZoneProps extends PropsWithChildren { + className?: string +} + +export const GlobalFileDropZone: FC = memo(({ children, className }) => { + const { handleFileDrop } = useFileUploadWithDefaults() + const [isDragOver, setIsDragOver] = useState(false) + const [isProcessing, setIsProcessing] = useState(false) + const dragCounterRef = useRef(0) + + const handleDragEnter = useCallback((e: React.DragEvent) => { + e.preventDefault() + e.stopPropagation() + + dragCounterRef.current += 1 + + if (e.dataTransfer.types.includes("Files")) { + setIsDragOver(true) + } + }, []) + + const handleDragLeave = useCallback((e: React.DragEvent) => { + e.preventDefault() + e.stopPropagation() + + dragCounterRef.current -= 1 + + if (dragCounterRef.current === 0) { + setIsDragOver(false) + } + }, []) + + const handleDragOver = useCallback((e: React.DragEvent) => { + e.preventDefault() + e.stopPropagation() + }, []) + + const handleDrop = useCallback( + async (e: React.DragEvent) => { + e.preventDefault() + e.stopPropagation() + + dragCounterRef.current = 0 + setIsDragOver(false) + + const { files } = e.dataTransfer + if (!files || files.length === 0) return + + setIsProcessing(true) + + try { + await handleFileDrop(files) + } catch (error) { + console.error("Error processing files:", error) + } finally { + setIsProcessing(false) + } + }, + [handleFileDrop], + ) + + return ( +
+ {children} + + {/* Global Drag Overlay */} + + {isDragOver && ( + + {/* Glass morphism backdrop */} + + + {/* Content */} + + {isProcessing ? ( + <> +
+
+

Processing files...

+

+ Please wait while we process your files +

+
+ + ) : ( + <> +
+ + + + +
+
+

Drop files to attach

+

+ Images, PDFs, text files, and audio files are supported +

+
+ + )} + + + )} + +
+ ) +}) + +GlobalFileDropZone.displayName = "GlobalFileDropZone" diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/AIChatContextBar.tsx b/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/AIChatContextBar.tsx index 0f15a9e66..814709fec 100644 --- a/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/AIChatContextBar.tsx +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/AIChatContextBar.tsx @@ -1,38 +1,21 @@ -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 { memo, useCallback, useMemo, useRef } from "react" 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 { DropdownMenu, DropdownMenuTrigger } from "~/components/ui/dropdown-menu/dropdown-menu" +import { useFileUploadWithDefaults } from "~/modules/ai-chat/hooks/useFileUpload" import { useAIChatStore } from "~/modules/ai-chat/store/AIChatContext" -import type { AIChatContextBlock } from "~/modules/ai-chat/store/types" -import { useSettingModal } from "~/modules/settings/modal/use-setting-modal-hack" +import { SUPPORTED_MIME_ACCEPT } from "~/modules/ai-chat/utils/file-validation" -import { useChatBlockActions } from "../../store/hooks" +import { ContextBlock } from "../context-bar/blocks" +import { ContextMenuContent, ShortcutsMenuContent } from "../context-bar/menus" export const AIChatContextBar: Component<{ onSendShortcut?: (prompt: string) => void }> = memo( ({ className, onSendShortcut }) => { const blocks = useAIChatStore()((s) => s.blocks) - const blockActions = useChatBlockActions() const { shortcuts } = useAISettingValue() + const fileInputRef = useRef(null) + const { handleFileInputChange } = useFileUploadWithDefaults() // Filter enabled shortcuts const enabledShortcuts = useMemo( @@ -40,85 +23,9 @@ export const AIChatContextBar: Component<{ onSendShortcut?: (prompt: string) => [shortcuts], ) - const showSettingModal = useSettingModal() - const contextMenuContent = ( - - - - - Current Feed Entries - - - - blockActions.addBlock({ - type: "referEntry", - value: entryId, - }) - } - /> - - - - - - - - Reference Entry - - - - blockActions.addBlock({ - type: "referEntry", - value: entryId, - }) - } - /> - - - - - - Reference Feed - - - - blockActions.addBlock({ - type: "referFeed", - value: feedId, - }) - } - /> - - - - ) - - const shortcutsMenuContent = ( - - {enabledShortcuts.length === 0 ? ( -
No shortcuts configured
- ) : ( - enabledShortcuts.map((shortcut) => ( - onSendShortcut?.(shortcut.prompt)}> - - {shortcut.name} - - )) - )} - - { - showSettingModal("ai") - }} - > - - Manage Shortcut - -
- ) + const handleAttachFile = useCallback(() => { + fileInputRef.current?.click() + }, []) return (
@@ -132,9 +39,29 @@ export const AIChatContextBar: Component<{ onSendShortcut?: (prompt: string) => - {contextMenuContent} + + {/* File Upload Button */} + + + {/* Hidden File Input */} + + {/* AI Shortcuts Button */} {enabledShortcuts.length > 0 && ( @@ -147,7 +74,7 @@ export const AIChatContextBar: Component<{ onSendShortcut?: (prompt: string) => - {shortcutsMenuContent} + )} @@ -160,284 +87,3 @@ export const AIChatContextBar: Component<{ onSendShortcut?: (prompt: string) => }, ) AIChatContextBar.displayName = "AIChatContextBar" - -// Generic Picker Component -interface PickerItem { - id: string - title: string -} - -interface PickerListProps { - items: T[] - placeholder: string - onSelect: (id: string) => void - renderItem?: (item: T, onSelect: (id: string) => void) => React.ReactNode - noResultsText?: string -} - -const PickerList = ({ - items, - placeholder, - onSelect, - renderItem, - noResultsText = "No items found", -}: PickerListProps) => { - 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) => ( - onSelect(item.id)} className="text-xs"> - {item.title} - - ) - - return ( -
- { - debouncedSetSearchTerm(e.target.value) - }} - /> -
- {filteredItems.length === 0 ? ( -
{noResultsText}
- ) : ( - filteredItems.map((item) => - renderItem ? renderItem(item, onSelect) : defaultRenderItem(item, onSelect), - ) - )} -
-
- ) -} - -const CurrentFeedEntriesPickerList: FC<{ onSelect: (entryId: string) => void }> = ({ - onSelect, -}) => { - const mainEntryId = useAIChatStore()((s) => s.blocks.find((b) => b.type === "mainEntry")?.value) - const feedId = useEntry(mainEntryId, (e) => e?.feedId) - - const entryIds = useEntryIdsByFeedId(feedId!) - - return -} - -const RecentEntriesPickerList: FC<{ onSelect: (entryId: string) => void }> = ({ onSelect }) => { - const view = useRouteParamsSelector((route) => route.view) - const recentEntryIds = useEntryIdsByView(view, false) - - return -} - -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 ( - - ) -} - -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 ( - ( - - )} - /> - ) -} - -const SearchInput: FC> = (props) => { - return ( -
- - -
- ) -} - -// 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 ( - onSelect(feedId)} className="text-xs"> - {displayTitle} - - ) -} - -const ContextBlock: FC<{ block: AIChatContextBlock }> = ({ block }) => { - const blockActions = useChatBlockActions() - - 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 - } - case "referFeed": { - return - } - 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 ( -
-
-
- - {getBlockLabel()} -
- - - {getDisplayContent()} - -
- - {canRemove && ( - - )} -
- ) -} - -const EntryTitle: FC<{ entryId?: string; fallback: string }> = ({ entryId, fallback }) => { - const entryTitle = useEntry(entryId!, (e) => e?.title) - - if (!entryId || !entryTitle) { - return {fallback} - } - - return {entryTitle} -} - -const FeedTitle: FC<{ feedId?: string; fallback: string }> = ({ feedId, fallback }) => { - const feed = useFeedById(feedId, (feed) => ({ title: feed?.title })) - if (!feedId || !feed) { - return {fallback} - } - - return {feed.title} -} diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/AIChatRoot.tsx b/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/AIChatRoot.tsx index ac8e01153..98d35da6d 100644 --- a/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/AIChatRoot.tsx +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/AIChatRoot.tsx @@ -14,14 +14,11 @@ interface AIChatRootProps extends PropsWithChildren { chatId?: string } -// Inner component that has access to the AI chat store context const AIChatRootInner: FC = ({ children, chatId: externalChatId }) => { - // Use the new internal hooks const currentChatId = useCurrentChatId() const chatActions = useChatActions() - // Initialize room ID on mount useMemo(() => { if (!currentChatId && !externalChatId) { chatActions.newChat() diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/AIModelIndicator.tsx b/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/AIModelIndicator.tsx new file mode 100644 index 000000000..623f04d21 --- /dev/null +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/AIModelIndicator.tsx @@ -0,0 +1,104 @@ +import { cn } from "@follow/utils" +import { memo, useMemo } from "react" + +import { + DropdownMenu, + DropdownMenuContent, + DropdownMenuItem, + DropdownMenuTrigger, +} from "~/components/ui/dropdown-menu/dropdown-menu" + +import { useAIModel } from "../../hooks/useAIModel" + +interface AIModelIndicatorProps { + className?: string + onModelChange?: (model: string) => void +} + +type ProviderType = "openai" | "anthropic" | "google" | "meta" + +const providerIcons: Record = { + openai: "i-simple-icons-openai", + anthropic: "i-simple-icons-anthropic", + google: "i-simple-icons-google", + meta: "i-simple-icons-meta", +} + +const parseModelString = (modelString: string) => { + if (!modelString || !modelString.includes("/")) { + return { provider: "openai" as ProviderType, modelName: modelString || "Unknown" } + } + + const [provider, ...modelParts] = modelString.split("/") + const modelName = modelParts.join("/") + + return { + provider: (provider as ProviderType) || "openai", + modelName: modelName || "Unknown", + } +} + +export const AIModelIndicator = memo(({ className, onModelChange }: AIModelIndicatorProps) => { + const { data } = useAIModel() + const { currentModel, availableModels = [] } = data || {} + + const { provider, modelName } = useMemo(() => { + return parseModelString(currentModel || "") + }, [currentModel]) + + const iconClass = providerIcons[provider] || providerIcons.openai + const hasMultipleModels = availableModels && availableModels.length > 1 + + const modelContent = ( +
+ + {modelName} + {hasMultipleModels && } +
+ ) + + if (!hasMultipleModels) { + return modelContent + } + + return ( + + {modelContent} + + {availableModels.map((model) => { + const { provider: itemProvider, modelName: itemModelName } = parseModelString(model) + const itemIconClass = providerIcons[itemProvider] || providerIcons.openai + const isSelected = model === currentModel + + return ( + onModelChange?.(model)} + checked={isSelected} + > + + {itemModelName} + {isSelected && } + + ) + })} + + + ) +}) + +AIModelIndicator.displayName = "AIModelIndicator" diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/ChatHeader.tsx b/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/ChatHeader.tsx index f9b92189a..c5eb60941 100644 --- a/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/ChatHeader.tsx +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/ChatHeader.tsx @@ -2,17 +2,20 @@ import { ActionButton } from "@follow/components/ui/button/index.js" import { useCallback } from "react" import { useTranslation } from "react-i18next" +import { AIChatPanelStyle, setAIPanelVisibility, useAIChatPanelStyle } from "~/atoms/settings/ai" import { useDialog } from "~/components/ui/modal/stacked/hooks" -import { useChatActions, useCurrentTitle } from "~/modules/ai-chat/store/hooks" +import { useBlockActions, useChatActions, useCurrentTitle } from "~/modules/ai-chat/store/hooks" import { useSettingModal } from "~/modules/settings/modal/use-setting-modal-hack" import { ChatMoreDropdown } from "./ChatMoreDropdown" +import { EditableTitle } from "./EditableTitle" export const ChatHeader = () => { const currentTitle = useCurrentTitle() const settingModalPresent = useSettingModal() const chatActions = useChatActions() + const blockActions = useBlockActions() const { ask } = useDialog() const { t } = useTranslation("ai") @@ -22,16 +25,18 @@ export const ChatHeader = () => { return } - ask({ - title: t("clear_chat"), - message: t("clear_chat_message"), - variant: "danger", - onConfirm: () => { - chatActions.newChat() - }, - }) - }, [chatActions, currentTitle, ask, t]) + chatActions.newChat() + blockActions.clearBlocks({ keepSpecialTypes: true }) + }, [chatActions, currentTitle, ask, t, blockActions]) + const handleTitleSave = useCallback( + async (newTitle: string) => { + await chatActions.editChatTitle(newTitle) + }, + [chatActions], + ) + + const panelStyle = useAIChatPanelStyle() const maskImage = `linear-gradient(to bottom, black 0%, black 75%, transparent 100%)` return (
@@ -44,15 +49,8 @@ export const ChatHeader = () => { />
- {/* Left side - Title */} -
- {currentTitle && ( -

- - {currentTitle} - -

- )} +
+
{/* Right side - Actions */} @@ -66,6 +64,15 @@ export const ChatHeader = () => { + + {panelStyle === AIChatPanelStyle.Floating && ( + <> +
+ setAIPanelVisibility(false)}> + + + + )}
diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/ChatInput.tsx b/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/ChatInput.tsx index cd782d48a..56a202383 100644 --- a/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/ChatInput.tsx +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/ChatInput.tsx @@ -4,19 +4,21 @@ import { ScrollArea } from "@follow/components/ui/scroll-area/ScrollArea.js" import { cn, stopPropagation } from "@follow/utils" import type { VariantProps } from "class-variance-authority" import { cva } from "class-variance-authority" +import { noop } from "es-toolkit" import type { EditorState, LexicalEditor } from "lexical" import { $getRoot } from "lexical" import { memo, useCallback, useRef, useState } from "react" import { AIChatContextBar } from "~/modules/ai-chat/components/layouts/AIChatContextBar" -import { MentionPlugin } from "../../editor" +import { FileUploadPlugin, MentionPlugin } from "../../editor" import { useChatActions, useChatStatus } from "../../store/hooks" import { AIChatSendButton } from "./AIChatSendButton" +import { AIModelIndicator } from "./AIModelIndicator" const chatInputVariants = cva( [ - "bg-background/60 focus-within:ring-accent/20 focus-within:border-accent/80 border-border/80", + "bg-background focus-within:ring-accent/20 focus-within:border-accent/80 border-border/80", "relative overflow-hidden rounded-2xl border backdrop-blur-xl duration-200 focus-within:ring-2", ], { @@ -95,7 +97,7 @@ export const ChatInput = memo(({ onSend, variant }: ChatInputProps) => { onChange={handleEditorChange} onKeyDown={handleKeyDown} autoFocus - plugins={[MentionPlugin]} + plugins={[MentionPlugin, FileUploadPlugin]} namespace="AIChatRichEditor" /> @@ -111,10 +113,19 @@ export const ChatInput = memo(({ onSend, variant }: ChatInputProps) => { {/* Context Bar - Always shown, positioned below the input area */}
- onSend(prompt, null)} - /> +
+
+ onSend(prompt, null)} + /> +
+ +
) diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/ChatInterface.tsx b/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/ChatInterface.tsx index b4cdce21b..fdbbbb9b8 100644 --- a/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/ChatInterface.tsx +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/ChatInterface.tsx @@ -1,22 +1,25 @@ import { ScrollArea } from "@follow/components/ui/scroll-area/ScrollArea.js" +import { usePrefetchSummary } from "@follow/store/summary/hooks" import { tracker } from "@follow/tracker" import { clsx, cn, nextFrame } from "@follow/utils" -import { springScrollTo } from "@follow/utils/scroller" import type { BizUIMessage } from "@folo-services/ai-tools" import { ErrorBoundary } from "@sentry/react" import type { EditorState, LexicalEditor } from "lexical" import { AnimatePresence } from "motion/react" import { nanoid } from "nanoid" import type { FC } from "react" -import { useCallback, useEffect, useState } from "react" +import { Suspense, useEffect, useState } from "react" import { useEventCallback } from "usehooks-ts" +import { useAISettingKey } from "~/atoms/settings/ai" +import { useActionLanguage } from "~/atoms/settings/general" import { AIChatMessage, AIChatWaitingIndicator, } from "~/modules/ai-chat/components/message/AIChatMessage" import { useAutoScroll } from "~/modules/ai-chat/hooks/useAutoScroll" import { useLoadMessages } from "~/modules/ai-chat/hooks/useLoadMessages" +import { useMainEntryId } from "~/modules/ai-chat/hooks/useMainEntryId" import { useBlockActions, useChatActions, @@ -28,12 +31,13 @@ import { } from "~/modules/ai-chat/store/hooks" import { convertLexicalToMarkdown } from "../../utils/lexical-markdown" +import { GlobalFileDropZone } from "../file/GlobalFileDropZone" import { AIErrorFallback } from "./AIErrorFallback" import { ChatInput } from "./ChatInput" import { CollapsibleError } from "./CollapsibleError" import { WelcomeScreen } from "./WelcomeScreen" -const SCROLL_BOTTOM_THRESHOLD = window.innerHeight / 2 +const SCROLL_BOTTOM_THRESHOLD = 100 const ChatInterfaceContent = () => { const hasMessages = useHasMessages() @@ -41,12 +45,26 @@ const ChatInterfaceContent = () => { const chatActions = useChatActions() const error = useChatError() + useEffect(() => { + if (error) { + console.error("AIChat Error:", error) + } + }, [error]) + const currentChatId = useCurrentChatId() + const mainEntryId = useMainEntryId() + const actionLanguage = useActionLanguage() + + usePrefetchSummary({ + entryId: mainEntryId || "", + target: "content", + actionLanguage, + enabled: !!mainEntryId && !hasMessages, + }) const [scrollAreaRef, setScrollAreaRef] = useState(null) const [isAtBottom, setIsAtBottom] = useState(true) - // Reset handlers when chatId changes useEffect(() => { setIsAtBottom(true) }, [currentChatId]) @@ -67,7 +85,12 @@ const ChatInterfaceContent = () => { }, }) - const { resetScrollState } = useAutoScroll(scrollAreaRef, status === "streaming") + const autoScrollWhenStreaming = useAISettingKey("autoScrollWhenStreaming") + + const { resetScrollState } = useAutoScroll( + scrollAreaRef, + autoScrollWhenStreaming && status === "streaming", + ) useEffect(() => { const scrollElement = scrollAreaRef @@ -90,25 +113,34 @@ const ChatInterfaceContent = () => { } }, [scrollAreaRef]) - const scrollToBottom = useCallback(() => { - const scrollElement = scrollAreaRef - if (!scrollElement) return - - springScrollTo(scrollElement.scrollHeight, scrollElement) - }, [scrollAreaRef]) - const blockActions = useBlockActions() const handleSendMessage = useEventCallback( (message: string | EditorState, editor: LexicalEditor | null) => { resetScrollState() + const blocks = [] as any[] + + for (const block of blockActions.getBlocks()) { + if (block.type === "fileAttachment" && block.attachment.serverUrl) { + blocks.push({ + ...block, + attachment: { + id: block.attachment.id, + name: block.attachment.name, + type: block.attachment.type, + size: block.attachment.size, + serverUrl: block.attachment.serverUrl, + }, + }) + } else { + blocks.push(block) + } + } + const parts: BizUIMessage["parts"] = [ { type: "data-block", - data: blockActions.getBlocks().map((b) => ({ - type: b.type, - value: b.value, - })), + data: blocks, }, ] @@ -121,7 +153,7 @@ const ChatInterfaceContent = () => { parts.push({ type: "data-rich-text", data: { - state: message.toJSON(), + state: JSON.stringify(message.toJSON()), text: convertLexicalToMarkdown(editor), }, }) @@ -145,13 +177,15 @@ const ChatInterfaceContent = () => { const shouldShowScrollToBottom = hasMessages && !isAtBottom && !isLoadingHistory return ( -
+
{!hasMessages && !isLoadingHistory ? ( ) : ( {
) : ( -
+
- {status === "submitted" && } + + {(status === "submitted" || status === "streaming") && }
)} @@ -172,24 +207,18 @@ const ChatInterfaceContent = () => {
{shouldShowScrollToBottom && ( -
-
- -
+
+
)} @@ -197,13 +226,13 @@ const ChatInterfaceContent = () => { className={clsx( "absolute mx-auto duration-200 ease-in-out", hasMessages && "inset-x-0 bottom-0 max-w-4xl px-6 pb-6", - !hasMessages && "inset-x-0 bottom-1/2 max-w-3xl translate-y-[calc(100%-2rem)] px-6 pb-6", + !hasMessages && "inset-x-0 bottom-0 max-w-3xl px-6 pb-6", )} > {error && }
-
+ ) } @@ -216,5 +245,13 @@ export const ChatInterface = () => ( const Messages: FC = () => { const messages = useMessages() - return messages.map((message) => ) + return ( +
+ {messages.map((message) => ( + + + + ))} +
+ ) } diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/ChatMoreDropdown.tsx b/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/ChatMoreDropdown.tsx index 5dd31dd74..5dc3497a1 100644 --- a/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/ChatMoreDropdown.tsx +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/ChatMoreDropdown.tsx @@ -3,6 +3,7 @@ import { useCallback, useState } from "react" import { useTranslation } from "react-i18next" import { toast } from "sonner" +import { AIChatPanelStyle, setAIChatPanelStyle, useAIChatPanelStyle } from "~/atoms/settings/ai" import { RelativeDay } from "~/components/ui/datetime" import { DropdownMenu, @@ -23,6 +24,7 @@ import { downloadMarkdown, exportChatToMarkdown } from "~/modules/ai-chat/utils/ export const ChatMoreDropdown = () => { const currentTitle = useCurrentTitle() const currentChatId = useCurrentChatId() + const panelStyle = useAIChatPanelStyle() const chatActions = useChatActions() const { t } = useTranslation("ai") @@ -91,6 +93,12 @@ export const ChatMoreDropdown = () => { } }, [chatActions, currentTitle, t]) + const handleToggleMode = useCallback(() => { + const newStyle = + panelStyle === AIChatPanelStyle.Fixed ? AIChatPanelStyle.Floating : AIChatPanelStyle.Fixed + setAIChatPanelStyle(newStyle) + }, [panelStyle]) + return ( @@ -129,8 +137,8 @@ export const ChatMoreDropdown = () => {

- - + +
))} - - - - New Chat - ) : (
@@ -169,6 +169,19 @@ export const ChatMoreDropdown = () => { Export Chat + + + + + + + {panelStyle === AIChatPanelStyle.Fixed + ? "Switch to Floating Panel" + : "Switch to Fixed Panel"} + + ) diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/EditableTitle.tsx b/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/EditableTitle.tsx new file mode 100644 index 000000000..63f01453a --- /dev/null +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/EditableTitle.tsx @@ -0,0 +1,139 @@ +import { Input } from "@follow/components/ui/input/Input.js" +import { cn } from "@follow/utils/utils" +import { useCallback, useEffect, useState } from "react" + +interface EditableTitleProps { + title?: string + onSave: (newTitle: string) => Promise + className?: string + placeholder?: string + maxLength?: number +} + +export const EditableTitle = ({ + title = "", + onSave, + className, + placeholder = "Untitled Chat", + maxLength = 100, +}: EditableTitleProps) => { + const [isEditing, setIsEditing] = useState(false) + const [editValue, setEditValue] = useState("") + const [isSaving, setIsSaving] = useState(false) + const [originalTitle, setOriginalTitle] = useState("") + const [saveSuccess, setSaveSuccess] = useState(false) + + const displayTitle = title || placeholder + + const handleStartEdit = useCallback(() => { + setOriginalTitle(title) + setEditValue(title) + setIsEditing(true) + }, [title]) + + const handleSave = useCallback(async () => { + if (isSaving) return + + const trimmedValue = editValue.trim() + + // If no changes, just exit edit mode + if (trimmedValue === originalTitle) { + setIsEditing(false) + return + } + + try { + setIsSaving(true) + await onSave(trimmedValue) + + // Show success feedback briefly + setSaveSuccess(true) + setTimeout(() => setSaveSuccess(false), 2000) + + setIsEditing(false) + } catch (error) { + console.error("Failed to save title:", error) + // Keep in edit mode on error to allow retry + } finally { + setIsSaving(false) + } + }, [editValue, originalTitle, onSave, isSaving]) + + const handleCancel = useCallback(() => { + setEditValue(originalTitle) + setIsEditing(false) + setIsSaving(false) + }, [originalTitle]) + + const handleKeyDown = useCallback( + (event: React.KeyboardEvent) => { + if (event.key === "Enter") { + event.preventDefault() + handleSave() + } else if (event.key === "Escape") { + event.preventDefault() + handleCancel() + } + }, + [handleSave, handleCancel], + ) + + const handleBlur = useCallback(() => { + if (!isSaving) { + handleSave() + } + }, [handleSave, isSaving]) + + // Auto-focus input when entering edit mode + useEffect(() => { + if (isEditing) { + const input = document.activeElement as HTMLInputElement + if (input?.select) { + input.select() + } + } + }, [isEditing]) + + if (isEditing) { + return ( +
+ ref?.focus()} + value={editValue} + onChange={(e) => setEditValue(e.target.value)} + onKeyDown={handleKeyDown} + onBlur={handleBlur} + maxLength={maxLength} + disabled={isSaving} + className={cn( + "text-text border-accent/50 focus:border-accent bg-transparent font-bold", + "h-auto p-2 text-base leading-none", + isSaving && "cursor-not-allowed opacity-60", + className, + )} + placeholder={placeholder} + /> + {isSaving && ( +
+ +
+ )} +
+ ) + } + + return ( +
+

+ {displayTitle} +

+ {saveSuccess && ( + + )} + +
+ ) +} diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/ImageThumbnail.tsx b/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/ImageThumbnail.tsx new file mode 100644 index 000000000..d19c3b9dc --- /dev/null +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/ImageThumbnail.tsx @@ -0,0 +1,120 @@ +import { cn } from "@follow/utils" +import * as HoverCard from "@radix-ui/react-hover-card" +import { m } from "motion/react" +import type { FC } from "react" +import * as React from "react" + +import { useModalStack } from "~/components/ui/modal/stacked/hooks" + +export const ImageThumbnail: FC<{ + previewUrl: string + originalUrl: string + alt: string + filename: string + className?: string +}> = ({ previewUrl, originalUrl, alt, filename, className }) => { + const [imageError, setImageError] = React.useState(false) + const { present } = useModalStack() + + return ( + + + present({ + max: true, + title: "Preview Image", + content: () => ( +
+ +
+ ), + }) + } + > + +
+ + +
+ {imageError ? ( +
+
+ + {filename} +
+
+ ) : ( + setImageError(true)} + initial={{ opacity: 0, scale: 0.95 }} + animate={{ opacity: 1, scale: 1 }} + transition={{ duration: 0.2 }} + className="max-h-[300px] max-w-[400px] rounded-md" + /> + )} +
+
+
+
+ ) +} + +export const ImageThumbnailInner: React.FC<{ + src: string + alt: string + className?: string +}> = ({ src, alt, className }) => { + const [imageError, setImageError] = React.useState(false) + const [imageLoaded, setImageLoaded] = React.useState(false) + + const handleError = React.useCallback(() => { + setImageError(true) + }, []) + + const handleLoad = React.useCallback(() => { + setImageLoaded(true) + }, []) + + if (imageError) { + return ( +
+ +
+ ) + } + + return ( +
+ {!imageLoaded && ( +
+ +
+ )} + +
+ ) +} diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/WelcomeScreen.tsx b/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/WelcomeScreen.tsx index ff25037c3..496fcef55 100644 --- a/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/WelcomeScreen.tsx +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/WelcomeScreen.tsx @@ -1,95 +1,66 @@ import type { EditorState, LexicalEditor } from "lexical" -import { m } from "motion/react" +import { AnimatePresence, m } from "motion/react" import { useTranslation } from "react-i18next" import { useAISettingValue } from "~/atoms/settings/ai" import { AISpline } from "~/modules/ai-chat/components/3d-models/AISpline" -import { useSettingModal } from "~/modules/settings/modal/use-setting-modal-hack" + +import { useMainEntryId } from "../../hooks/useMainEntryId" +import { DefaultWelcomeContent, EntrySummaryCard } from "../welcome" interface WelcomeScreenProps { onSend: (message: EditorState | string, editor: LexicalEditor | null) => 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 mainEntryId = useMainEntryId() - const hasCustomPrompt = aiSettings.personalizePrompt?.trim() + const hasEntryContext = !!mainEntryId const enabledShortcuts = aiSettings.shortcuts?.filter((shortcut) => shortcut.enabled) || [] return ( -
-
-
+
+
+ {/* Header Section - Always Present */} +

{APP_NAME} AI

-

{t("welcome_description")}

+

+ {hasEntryContext + ? t("welcome_description_contextual", { + defaultValue: "Let's discuss this entry together", + }) + : t("welcome_description")} +

-
+ -
- -
- {/* Custom shortcuts first */} - {enabledShortcuts.slice(0, 6).map((shortcut, index) => ( - onSend(shortcut.prompt, null)} - title={shortcut.hotkey ? `${shortcut.name} (${shortcut.hotkey})` : shortcut.name} - > - {shortcut.name} - - ))} - - {/* Default suggestions if no custom shortcuts or to fill remaining space */} - {enabledShortcuts.length < 4 && - DEFAULT_SHORTCUTS.slice(0, 4 - enabledShortcuts.length).map((suggestion, index) => ( - onSend(suggestion, null)} - > - {suggestion} - - ))} - - {hasCustomPrompt && ( -
-
-
Personal Prompt:
- -
-

- {aiSettings.personalizePrompt} -

-
- )} + {/* Dynamic Content Area */} +
+ + {hasEntryContext ? ( + onSend(message, null)} + /> + ) : ( + + )} +
diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/AIChatMessage.tsx b/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/AIChatMessage.tsx index 888dd4f24..741b13b99 100644 --- a/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/AIChatMessage.tsx +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/AIChatMessage.tsx @@ -1,5 +1,5 @@ import { createDefaultLexicalEditor } from "@follow/components/ui/lexical-rich-editor/editor.js" -import { stopPropagation } from "@follow/utils" +import { cn, stopPropagation, thenable } from "@follow/utils" import type { UIDataTypes, UIMessage } from "ai" import type { LexicalEditor, SerializedEditorState } from "lexical" import { m } from "motion/react" @@ -11,6 +11,7 @@ import { useEditingMessageId, useSetEditingMessageId } from "~/modules/ai-chat/a import { useChatActions } from "~/modules/ai-chat/store/hooks" import type { BizUIMetadata, BizUITools } from "~/modules/ai-chat/store/types" +import { MentionPlugin } from "../../editor" import type { RichTextPart } from "../../types/ChatSession" import { convertLexicalToMarkdown } from "../../utils/lexical-markdown" import { AIMessageParts } from "./AIMessageParts" @@ -30,6 +31,9 @@ interface AIChatMessageProps { } export const AIChatMessage: React.FC = React.memo(({ message }) => { + if (message.parts.length === 0) { + throw thenable + } const chatActions = useChatActions() const messageId = message.id @@ -56,7 +60,7 @@ export const AIChatMessage: React.FC = React.memo(({ message break } case "data-rich-text": { - lexicalEditor ||= createDefaultLexicalEditor() + lexicalEditor ||= createDefaultLexicalEditor([MentionPlugin]) lexicalEditor.setEditorState( lexicalEditor.parseEditorState((part as RichTextPart).data.state), ) @@ -122,28 +126,13 @@ export const AIChatMessage: React.FC = React.memo(({ message }, [chatActions, messageId]) return ( - setIsHovered(true)} onMouseLeave={() => setIsHovered(false)} > -
+
{/* Show editable message if editing */} {isEditing && isUserMessage ? ( = React.memo(({ message <> {/* Normal message display */}
- {message.role === "assistant" && ( -
-
- -
- {APP_NAME} AI -
+ className={cn( + `text-text backdrop-blur-sm`, + message.role === "user" && "rounded-2xl bg-gray-100 px-4 py-2.5 dark:bg-gray-800", )} -
+ > +
- {message.metadata?.finishTime && ( -
- {new Date(message.metadata.finishTime).toLocaleTimeString([], { - hour: "2-digit", - minute: "2-digit", - })} -
- )}
{/* Action buttons */} @@ -204,7 +169,7 @@ export const AIChatMessage: React.FC = React.memo(({ message
- +
) }) export const AIChatWaitingIndicator: React.FC = () => { return ( - - - + +
+ + Thinking… +
+
) } diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/AIDataBlockItem.tsx b/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/AIDataBlockItem.tsx new file mode 100644 index 000000000..a5f139dc1 --- /dev/null +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/AIDataBlockItem.tsx @@ -0,0 +1,119 @@ +import { cn } from "@follow/utils/utils" +import * as React from "react" + +import type { AIChatContextBlock } from "~/modules/ai-chat/store/types" + +import { + getBlockIcon, + getBlockLabel, + getBlockStyles, + getFileDisplayContent, + isImageAttachment, +} from "./ai-block-constants" +import { EntryTitle, FeedTitle } from "./BlockTitleComponents" +import { ImageThumbnail } from "./ImageThumbnail" + +interface AIDataBlockItemProps { + block: AIChatContextBlock + index: number +} + +/** + * Gets the display content for a context block + */ +const getDisplayContent = (block: AIChatContextBlock): React.ReactNode => { + switch (block.type) { + case "mainEntry": + case "referEntry": { + return + } + case "referFeed": { + return + } + case "selectedText": { + return `"${block.value}"` + } + case "fileAttachment": { + if (!block.attachment) { + return "[File: Unknown]" + } + return getFileDisplayContent(block.attachment) + } + default: { + return "" + } + } +} + +/** + * Renders the appropriate icon or image thumbnail for a block + */ +const BlockIcon: React.FC<{ + block: AIChatContextBlock + styles: ReturnType +}> = React.memo(({ block, styles }) => { + // Handle image thumbnails for file attachments + if (block.type === "fileAttachment" && block.attachment && isImageAttachment(block)) { + return ( +
+ +
+ ) + } + + const iconClass = getBlockIcon(block) + + return ( +
+ +
+ ) +}) + +BlockIcon.displayName = "BlockIcon" + +/** + * Individual block item component with optimized rendering and animations + */ +export const AIDataBlockItem: React.FC = React.memo(({ block }) => { + const styles = React.useMemo(() => getBlockStyles(block.type), [block.type]) + const label = React.useMemo(() => getBlockLabel(block.type), [block.type]) + const displayContent = React.useMemo(() => getDisplayContent(block), [block]) + + return ( +
+ + + {/* Label and content */} +
+ {label} + · + + {displayContent} + +
+
+ ) +}) + +AIDataBlockItem.displayName = "AIDataBlockItem" diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/AIDataBlockPart.tsx b/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/AIDataBlockPart.tsx index 511cc9b3e..edd09fc5f 100644 --- a/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/AIDataBlockPart.tsx +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/AIDataBlockPart.tsx @@ -1,136 +1,21 @@ -import { useEntry } from "@follow/store/entry/hooks" -import { useFeedById } from "@follow/store/feed/hooks" import { cn } from "@follow/utils/utils" -import { m } from "motion/react" import * as React from "react" import type { AIChatContextBlock } from "~/modules/ai-chat/store/types" +import { AIDataBlockItem } from "./AIDataBlockItem" + interface AIDataBlockPartProps { blocks: AIChatContextBlock[] } -// Helper components for displaying titles -const EntryTitle: React.FC<{ entryId?: string; fallback: string }> = ({ entryId, fallback }) => { - const entryTitle = useEntry(entryId!, (e) => e?.title) - - if (!entryId || !entryTitle) { - return {fallback} - } - - return {entryTitle} -} - -const FeedTitle: React.FC<{ feedId?: string; fallback: string }> = ({ feedId, fallback }) => { - const feed = useFeedById(feedId, (feed) => ({ title: feed?.title })) - if (!feedId || !feed) { - return {fallback} - } - - return {feed.title} -} - -// Data Block Component +/** + * Main component for rendering AI chat context blocks + * Displays various types of context (entries, feeds, text, files) with animations + */ export const AIDataBlockPart: React.FC = React.memo(({ blocks }) => { - const getBlockIcon = (type: AIChatContextBlock["type"]) => { - switch (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 getBlockLabel = (type: AIChatContextBlock["type"]) => { - switch (type) { - case "mainEntry": { - return "Current" - } - case "referEntry": { - return "Ref" - } - case "referFeed": { - return "Feed" - } - case "selectedText": { - return "Text" - } - default: { - return "" - } - } - } - - const getBlockStyles = (type: AIChatContextBlock["type"]) => { - switch (type) { - case "mainEntry": { - return { - container: "from-orange/5 to-orange/10 border-orange/20 hover:border-orange/30", - icon: "bg-orange/10 text-orange", - label: "text-orange", - } - } - case "referEntry": { - return { - container: "from-blue/5 to-blue/10 border-blue/20 hover:border-blue/30", - icon: "bg-blue/10 text-blue", - label: "text-blue", - } - } - case "referFeed": { - return { - container: "from-green/5 to-green/10 border-green/20 hover:border-green/30", - icon: "bg-green/10 text-green", - label: "text-green", - } - } - case "selectedText": { - return { - container: "from-purple/5 to-purple/10 border-purple/20 hover:border-purple/30", - icon: "bg-purple/10 text-purple", - label: "text-purple", - } - } - default: { - return { - container: "from-gray/5 to-gray/10 border-gray/20 hover:border-gray/30", - icon: "bg-gray/10 text-gray", - label: "text-gray", - } - } - } - } - - const getDisplayContent = (block: AIChatContextBlock) => { - switch (block.type) { - case "mainEntry": - case "referEntry": { - return - } - case "referFeed": { - return - } - case "selectedText": { - return `"${block.value}"` - } - default: { - return block.value - } - } - } - - if (!blocks || blocks.length === 0) { + // Early return for empty blocks + if (!blocks?.length) { return null } @@ -148,50 +33,10 @@ export const AIDataBlockPart: React.FC = React.memo(({ blo Context:
- {/* Blocks */} - {blocks.map((block, index) => { - const styles = getBlockStyles(block.type) - - return ( - - {/* Icon */} -
- -
- - {/* Label and content */} -
- - {getBlockLabel(block.type)} - - · - - {getDisplayContent(block)} - -
-
- ) - })} + {/* Render individual block items */} + {blocks.map((block, index) => ( + + ))}
) }) diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/AIMarkdownMessage.tsx b/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/AIMarkdownMessage.tsx index b32a20d72..d23f8d566 100644 --- a/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/AIMarkdownMessage.tsx +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/AIMarkdownMessage.tsx @@ -13,7 +13,7 @@ import { useSyncExternalStore, } from "react" -import { ShikiHighLighter } from "~/components/ui/code-highlighter" +import { MemoizedShikiCode } from "~/components/ui/code-highlighter" import { MarkdownLink } from "~/components/ui/markdown/renderers/MarkdownLink" import { usePeekModal } from "~/hooks/biz/usePeekModal" @@ -26,6 +26,11 @@ interface BufferConfig { maxBufferTime: number semanticTimeout: number emergencyTimeout: number + // Ensure a cool-down between flushes to avoid overlapping animations + minFlushInterval: number + // Initial burst controls for faster first paint + initialMinBufferSize: number + initialMaxWait: number } // Buffer endpoint patterns by priority @@ -118,12 +123,21 @@ class StreamingMessageBuffer { const now = Date.now() const timeSinceLastFlush = now - this.lastFlushTime + // Accelerate first paint: show something quickly at the very beginning + if (this.displayedText.length === 0) { + if (bufferedText.length >= this.config.initialMinBufferSize) return true + if (timeSinceLastFlush > this.config.initialMaxWait && bufferedText.length > 0) return true + } + // Emergency timeout - always flush if (timeSinceLastFlush > this.config.emergencyTimeout) return true // Buffer size limit - prevent OOM if (bufferedText.length > this.config.maxBufferSize) return true + // Avoid overlapping animations by enforcing a minimal interval between flushes + if (timeSinceLastFlush < this.config.minFlushInterval) return false + // Minimum buffer size not met if (bufferedText.length < this.config.minBufferSize) return false @@ -225,7 +239,13 @@ const BUFFER_CONFIG = { maxBufferSize: 10000, // Prevent OOM with 10KB limit maxBufferTime: 100, semanticTimeout: 300, - emergencyTimeout: 500, + // Keep emergency slightly larger than animation duration to prevent overlap + emergencyTimeout: 1200, + // Match animation duration in animatedPlugin (duration-1000) with a small buffer + minFlushInterval: 1000, + // Ensure very fast first paint + initialMinBufferSize: 2, + initialMaxWait: 80, } as const // Hook to use streaming text buffer @@ -327,15 +347,18 @@ export const AIMarkdownStreamingMessage = memo( prose-li:list-disc prose-li:marker:text-accent prose-hr:border-border prose-hr:mx-8` // Use intelligent streaming buffer for semantic text rendering - const bufferedText = useStreamingTextBuffer(text, isProcessing ?? false) + const bufferedTextRaw = useStreamingTextBuffer(text, isProcessing ?? false) // Use deferred value for lower priority rendering during streaming - const deferredText = useDeferredValue(bufferedText) + const deferredText = useDeferredValue(bufferedTextRaw) + + // For small snippets (common at the very beginning), avoid deferring so text appears instantly + const effectiveBufferedText = bufferedTextRaw.length < 20 ? bufferedTextRaw : deferredText // Use our optimized parsing hook with buffered text const parsedContent = useThrottledMarkdownParsing( - // During streaming, use deferred buffered text for optimal rendering - isProcessing ? deferredText : text, + // During streaming, use non-deferred value for tiny snippets to improve first paint + isProcessing ? effectiveBufferedText : text, isProcessing ?? false, ) @@ -363,7 +386,7 @@ export const AIMarkdownStreamingMessage = memo( } // Default comparison - return false + return prevProps === nextProps }, ) @@ -411,7 +434,7 @@ function baseAIMarkdownParser(content: string, isProcessing: boolean) { const language = className.replace("language-", "") const code = children - return + return } } diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/AIMessageParts.tsx b/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/AIMessageParts.tsx index 8e8f851ca..325c0d8bb 100644 --- a/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/AIMessageParts.tsx +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/AIMessageParts.tsx @@ -1,8 +1,6 @@ import "@xyflow/react/dist/style.css" import type { ToolUIPart } from "ai" -import type { SerializedEditorState } from "lexical" -import { m } from "motion/react" import * as React from "react" import type { @@ -21,7 +19,6 @@ import { AIDisplayFeedsPart, AIDisplaySubscriptionsPart, } from "../displays" -// import { AIDisplayFlowPart } from "../displays/AIDisplayFlowPart" import { AIDataBlockPart } from "./AIDataBlockPart" import { AIMarkdownMessage, AIMarkdownStreamingMessage } from "./AIMarkdownMessage" import { AIRichTextMessage } from "./AIRichTextMessage" @@ -34,32 +31,8 @@ const LazyAIDisplayFlowPart = React.lazy(() => interface MessagePartsProps { message: BizUIMessage } -const ThinkingIndicator: React.FC = () => { - return ( -
- - - Thinking... - - -
- ) -} export const AIMessageParts: React.FC = React.memo(({ message }) => { - if (!message.parts || message.parts.length === 0) { - // In AI SDK v5, messages should always have parts - if (message.role === "assistant") { - return - } - return null - } - const isUser = message.role === "user" - return message.parts.map((part, index) => { const partKey = `${message.id}-${index}` @@ -74,7 +47,7 @@ export const AIMessageParts: React.FC = React.memo(({ message className={"text-text"} /> ) - return + return } case "data-block": { @@ -85,8 +58,8 @@ export const AIMessageParts: React.FC = React.memo(({ message return ( ) } @@ -108,7 +81,7 @@ export const AIMessageParts: React.FC = React.memo(({ message case "tool-displayFlowChart": { const loadingElement = ( -
+
diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/AIRichTextMessage.tsx b/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/AIRichTextMessage.tsx index 3227f698b..ae4167ad6 100644 --- a/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/AIRichTextMessage.tsx +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/AIRichTextMessage.tsx @@ -9,6 +9,7 @@ import { RichTextPlugin } from "@lexical/react/LexicalRichTextPlugin" import type { SerializedEditorState } from "lexical" import * as React from "react" +import { FileAttachmentNode } from "../../editor" import { MentionNode } from "../../editor/plugins/mention/MentionNode" function onError(error: Error) { @@ -17,7 +18,7 @@ function onError(error: Error) { interface AIRichTextMessageProps { data: { - state: SerializedEditorState + state: SerializedEditorState | string // Serialized editor state as a JSON string text: string } className?: string @@ -25,15 +26,17 @@ interface AIRichTextMessageProps { export const AIRichTextMessage: React.FC = React.memo( ({ data, className }) => { - const initialConfig: InitialConfigType = { - namespace: "AIRichTextDisplay", - theme: defaultLexicalTheme, - onError, - editable: false, // Read-only mode - editorState: JSON.stringify(data.state), - nodes: [...LexicalRichEditorNodes, MentionNode], + let initialConfig: InitialConfigType = null! + if (!initialConfig) { + initialConfig = { + namespace: "AIRichTextDisplay", + theme: defaultLexicalTheme, + onError, + editable: false, + editorState: typeof data.state === "object" ? JSON.stringify(data.state) : data.state, + nodes: [...LexicalRichEditorNodes, MentionNode, FileAttachmentNode], + } } - return (
diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/BlockTitleComponents.tsx b/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/BlockTitleComponents.tsx new file mode 100644 index 000000000..27e93f959 --- /dev/null +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/BlockTitleComponents.tsx @@ -0,0 +1,45 @@ +import { useEntry } from "@follow/store/entry/hooks" +import { useFeedById } from "@follow/store/feed/hooks" +import * as React from "react" + +interface TitleProps { + fallback: string +} + +interface EntryTitleProps extends TitleProps { + entryId?: string +} + +interface FeedTitleProps extends TitleProps { + feedId?: string +} + +/** + * Displays entry title with fallback handling + */ +export const EntryTitle: React.FC = React.memo(({ entryId, fallback }) => { + const entryTitle = useEntry(entryId!, (e) => e?.title) + + if (!entryId || !entryTitle) { + return {fallback} + } + + return {entryTitle} +}) + +EntryTitle.displayName = "EntryTitle" + +/** + * Displays feed title with fallback handling + */ +export const FeedTitle: React.FC = React.memo(({ feedId, fallback }) => { + const feed = useFeedById(feedId, (feed) => ({ title: feed?.title })) + + if (!feedId || !feed?.title) { + return {fallback} + } + + return {feed.title} +}) + +FeedTitle.displayName = "FeedTitle" diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/ImageThumbnail.tsx b/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/ImageThumbnail.tsx new file mode 100644 index 000000000..b3326b453 --- /dev/null +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/ImageThumbnail.tsx @@ -0,0 +1,70 @@ +import { cn } from "@follow/utils/utils" +import * as React from "react" + +import type { FileAttachment } from "~/modules/ai-chat/store/types" + +import { getImageUrl } from "./ai-block-constants" + +interface ImageThumbnailProps { + attachment: FileAttachment + className?: string + fallbackIcon?: string +} + +/** + * A robust image thumbnail component with proper error handling and fallback states + */ +export const ImageThumbnail: React.FC = React.memo( + ({ + attachment, + className = "size-3 rounded object-cover", + fallbackIcon = "i-mgc-pic-cute-re", + }) => { + const [hasError, setHasError] = React.useState(false) + const [isLoading, setIsLoading] = React.useState(true) + + const imageUrl = React.useMemo(() => getImageUrl(attachment), [attachment]) + + const handleError = React.useCallback(() => { + setHasError(true) + setIsLoading(false) + }, []) + + const handleLoad = React.useCallback(() => { + setIsLoading(false) + }, []) + + // Reset error state when imageUrl changes + React.useEffect(() => { + if (imageUrl) { + setHasError(false) + setIsLoading(true) + } + }, [imageUrl]) + + // If no image URL or there was an error, show fallback icon + if (!imageUrl || hasError) { + return + } + + return ( +
+ {attachment.name} + {isLoading && ( +
+ +
+ )} +
+ ) + }, +) + +ImageThumbnail.displayName = "ImageThumbnail" diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/ThinkingIndicator.tsx b/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/ThinkingIndicator.tsx new file mode 100644 index 000000000..2a8d71027 --- /dev/null +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/ThinkingIndicator.tsx @@ -0,0 +1,17 @@ +import { m } from "motion/react" + +export const ThinkingIndicator: React.FC = () => { + return ( +
+ + + Thinking... + + +
+ ) +} diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/ToolInvocationComponent.tsx b/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/ToolInvocationComponent.tsx index f37b7e27e..7964ebc91 100644 --- a/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/ToolInvocationComponent.tsx +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/ToolInvocationComponent.tsx @@ -1,10 +1,3 @@ -import { - Accordion, - AccordionContent, - AccordionItem, - AccordionTrigger, -} from "@follow/components/ui/accordion/index.js" -import { JsonHighlighter } from "@follow/components/ui/json-highlighter/index.js" import type { ToolUIPart } from "ai" import { getToolName } from "ai" import * as React from "react" @@ -16,46 +9,24 @@ interface ToolInvocationComponentProps { export const ToolInvocationComponent: React.FC = React.memo( ({ part }) => { const toolName = getToolName(part) + const hasError = "errorText" in part && part.errorText return ( -
+
- - - - {/* Tool Info */} -
-
- - Tool Calling: -

{toolName}

-
-
-
- - -
- {"input" in part && ( -
-
- Arguments -
- -
- )} - - {"output" in part && ( -
-
- Result -
- -
- )} -
-
-
-
+
+
+ + + {hasError ? "Tool Failed:" : "Tool Calling:"} + +

+ {toolName} +

+
+
) }, diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/ai-block-constants.ts b/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/ai-block-constants.ts new file mode 100644 index 000000000..83fca3284 --- /dev/null +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/ai-block-constants.ts @@ -0,0 +1,128 @@ +import type { AIChatContextBlock, FileAttachment } from "~/modules/ai-chat/store/types" +import { + getFileCategoryFromMimeType, + getFileIconName, +} from "~/modules/ai-chat/utils/file-validation" + +/** + * Block style configurations for different context block types + */ +export const BLOCK_STYLES = { + mainEntry: { + container: "from-orange/5 to-orange/10 border-orange/20 hover:border-orange/30", + icon: "bg-orange/10 text-orange", + label: "text-orange", + }, + referEntry: { + container: "from-blue/5 to-blue/10 border-blue/20 hover:border-blue/30", + icon: "bg-blue/10 text-blue", + label: "text-blue", + }, + referFeed: { + container: "from-green/5 to-green/10 border-green/20 hover:border-green/30", + icon: "bg-green/10 text-green", + label: "text-green", + }, + selectedText: { + container: "from-purple/5 to-purple/10 border-purple/20 hover:border-purple/30", + icon: "bg-purple/10 text-purple", + label: "text-purple", + }, + fileAttachment: { + container: "from-pink/5 to-pink/10 border-pink/20 hover:border-pink/30", + icon: "bg-pink/10 text-pink", + label: "text-pink", + }, +} as const + +/** + * Default fallback styles for unknown block types + */ +export const DEFAULT_BLOCK_STYLES = { + container: "from-gray/5 to-gray/10 border-gray/20 hover:border-gray/30", + icon: "bg-gray/10 text-gray", + label: "text-gray", +} as const + +/** + * Block icons for different context block types + */ +export const BLOCK_ICONS = { + mainEntry: "i-mgc-star-cute-fi", + referEntry: "i-mgc-paper-cute-fi", + referFeed: "i-mgc-rss-cute-fi", + selectedText: "i-mgc-quill-pen-cute-re", + fileAttachment: "i-mgc-file-upload-cute-re", +} as const + +/** + * Block labels for different context block types + */ +export const BLOCK_LABELS = { + mainEntry: "Current", + referEntry: "Ref", + referFeed: "Feed", + selectedText: "Text", + fileAttachment: "File", +} as const + +/** + * File upload status labels + */ +export const FILE_STATUS_LABELS = { + uploading: "Uploading...", + error: "Failed", + processing: "Processing...", + completed: "", +} as const + +/** + * Gets the appropriate styles for a block type + */ +export function getBlockStyles(type: AIChatContextBlock["type"]) { + return BLOCK_STYLES[type] || DEFAULT_BLOCK_STYLES +} + +/** + * Gets the appropriate icon for a block + */ +export function getBlockIcon(block: AIChatContextBlock): string { + if (block.type === "fileAttachment" && block.attachment) { + const fileCategory = getFileCategoryFromMimeType(block.attachment.type) + return getFileIconName(fileCategory) + } + return BLOCK_ICONS[block.type] || BLOCK_ICONS.fileAttachment +} + +/** + * Gets the appropriate label for a block type + */ +export function getBlockLabel(type: AIChatContextBlock["type"]): string { + return BLOCK_LABELS[type] || "" +} + +/** + * Gets the best available image URL for a file attachment + */ +export function getImageUrl(attachment: FileAttachment): string | null { + return attachment.previewUrl || attachment.dataUrl || attachment.serverUrl || null +} + +/** + * Checks if a block represents an image attachment + */ +export function isImageAttachment(block: AIChatContextBlock): boolean { + return ( + block.type === "fileAttachment" && + !!block.attachment && + getFileCategoryFromMimeType(block.attachment.type) === "image" + ) +} + +/** + * Gets display content for file attachments based on upload status + */ +export function getFileDisplayContent(attachment: FileAttachment): string { + const statusLabel = FILE_STATUS_LABELS[attachment.uploadStatus] + return statusLabel || attachment.name +} diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/components/ui/UploadProgress.tsx b/apps/desktop/layer/renderer/src/modules/ai-chat/components/ui/UploadProgress.tsx new file mode 100644 index 000000000..8ddf0f395 --- /dev/null +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/components/ui/UploadProgress.tsx @@ -0,0 +1,154 @@ +import { cn } from "@follow/utils" +import { m } from "motion/react" +import type { FC } from "react" +import { memo } from "react" + +export interface UploadProgressProps { + /** Progress percentage (0-100) */ + progress: number + /** Progress bar size variant */ + size?: "sm" | "md" | "lg" + /** Show percentage text */ + showPercentage?: boolean + /** Custom className */ + className?: string + /** Progress bar color */ + variant?: "default" | "success" | "error" +} + +export const UploadProgress: FC = memo( + ({ progress, size = "md", showPercentage = false, className, variant = "default" }) => { + const progressValue = Math.max(0, Math.min(100, progress)) + + const sizeClasses = { + sm: "h-1", + md: "h-2", + lg: "h-3", + } + + const colorClasses = { + default: "bg-blue", + success: "bg-green", + error: "bg-red", + } + + return ( +
+ {/* Progress Bar */} +
+ +
+ + {/* Percentage Text */} + {showPercentage && ( +
+ {Math.round(progressValue)}% +
+ )} +
+ ) + }, +) + +UploadProgress.displayName = "UploadProgress" + +export interface CircularProgressProps { + /** Progress percentage (0-100) */ + progress: number + /** Circle size */ + size?: number + /** Stroke width */ + strokeWidth?: number + /** Show percentage text in center */ + showPercentage?: boolean + /** Custom className */ + className?: string + /** Progress color */ + variant?: "default" | "success" | "error" +} + +export const CircularProgress: FC = memo( + ({ + progress, + size = 20, + strokeWidth = 2, + showPercentage = false, + className, + variant = "default", + }) => { + const progressValue = Math.max(0, Math.min(100, progress)) + const radius = (size - strokeWidth) / 2 + const circumference = 2 * Math.PI * radius + const strokeDashoffset = circumference - (progressValue / 100) * circumference + + const colorClasses = { + default: "text-blue", + success: "text-green", + error: "text-red", + } + + return ( +
+ + {/* Background circle */} + + + {/* Progress circle */} + + + + {/* Percentage text */} + {showPercentage && ( +
+ {Math.round(progressValue)}% +
+ )} +
+ ) + }, +) + +CircularProgress.displayName = "CircularProgress" diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/components/welcome/DefaultWelcomeContent.tsx b/apps/desktop/layer/renderer/src/modules/ai-chat/components/welcome/DefaultWelcomeContent.tsx new file mode 100644 index 000000000..d6f596c0f --- /dev/null +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/components/welcome/DefaultWelcomeContent.tsx @@ -0,0 +1,67 @@ +import { AIShortcutButton } from "@follow/components/ui/ai-shortcut-button/index.js" +import type { EditorState, LexicalEditor } from "lexical" +import { m } from "motion/react" +import { useTranslation } from "react-i18next" + +import { useSettingModal } from "~/modules/settings/modal/use-setting-modal-hack" + +interface DefaultWelcomeContentProps { + onSend: (message: EditorState | string, editor: LexicalEditor | null) => void + shortcuts: Array<{ id: string; name: string; prompt: string; enabled: boolean; hotkey?: string }> +} + +const DEFAULT_SHORTCUTS = ["Generate today daily report"] + +export const DefaultWelcomeContent: React.FC = ({ + onSend, + shortcuts: enabledShortcuts, +}) => { + const { t } = useTranslation("ai") + const showSettings = useSettingModal() + return ( + +
+ {/* Custom shortcuts first */} + {enabledShortcuts.slice(0, 6).map((shortcut, index) => ( + onSend(shortcut.prompt, null)} + animationDelay={index * 0.1} + title={shortcut.hotkey ? `${shortcut.name} (${shortcut.hotkey})` : shortcut.name} + > + {shortcut.name} + + ))} + + {/* Show customize button when no shortcuts are available */} + {enabledShortcuts.length === 0 && ( + <> + {DEFAULT_SHORTCUTS.slice(0, 4 - enabledShortcuts.length).map((suggestion, index) => ( + onSend(suggestion, null)} + animationDelay={(enabledShortcuts.length + index) * 0.1} + > + {suggestion} + + ))} + showSettings("ai")} + animationDelay={0} + variant="outline" + title={t("customize_shortcuts_title")} + > + {t("customize_shortcuts")} + + + )} +
+
+ ) +} diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/components/welcome/EntrySummaryCard.tsx b/apps/desktop/layer/renderer/src/modules/ai-chat/components/welcome/EntrySummaryCard.tsx new file mode 100644 index 000000000..244e34b81 --- /dev/null +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/components/welcome/EntrySummaryCard.tsx @@ -0,0 +1,160 @@ +import { Spring } from "@follow/components/constants/spring.js" +import { AIShortcutButton } from "@follow/components/ui/ai-shortcut-button/index.js" +import { AutoResizeHeight } from "@follow/components/ui/auto-resize-height/index.js" +import { usePrefetchSummary } from "@follow/store/summary/hooks" +import { cn } from "@follow/utils/utils" +import { m } from "motion/react" +import { useTranslation } from "react-i18next" + +import { useEntryIsInReadabilitySuccess } from "~/atoms/readability" +import { useActionLanguage } from "~/atoms/settings/general" +import { CopyButton } from "~/components/ui/button/CopyButton" +import { Markdown } from "~/components/ui/markdown/Markdown" + +import { useSmartQuickActions } from "../../hooks/useSmartQuickActions" + +interface EntrySummaryCardProps { + entryId: string + onSend: (message: string) => void + className?: string +} + +const SummaryLoadingState = () => ( +
+
+
+
+
+) + +export const EntrySummaryCard: React.FC = ({ + entryId, + onSend, + className, +}) => { + const { t } = useTranslation("ai") + const actionLanguage = useActionLanguage() + const isInReadabilitySuccess = useEntryIsInReadabilitySuccess(entryId) + const summary = usePrefetchSummary({ + entryId, + target: isInReadabilitySuccess ? "readabilityContent" : "content", + actionLanguage, + enabled: true, + }) + + const quickActions = useSmartQuickActions(summary.data || null, entryId) + + return ( + + {/* Animated background gradient */} +
+ + {/* Header with entry context */} +
+
+
+ +
+
+ + {t("ai_summary", { defaultValue: "AI Summary" })} + +
+ + {summary.data && ( + + )} +
+ + {/* Summary Content */} + + {summary.isLoading ? ( + + ) : summary.data ? ( +
+ {String(summary.data)} +
+ ) : ( +
+ +

+ {t("summary_not_available", { defaultValue: "Summary not available" })} +

+
+ )} +
+ + {/* Smart Quick Actions */} + {summary.data && quickActions.length > 0 && ( +
+
+ {t("conversation_starters", { defaultValue: "Conversation starters" })} +
+
+ {quickActions.map((action, index) => ( + onSend(action.prompt)} + animationDelay={index * 0.1} + > + {action.label} + + ))} +
+
+ )} + + ) +} diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/components/welcome/index.ts b/apps/desktop/layer/renderer/src/modules/ai-chat/components/welcome/index.ts new file mode 100644 index 000000000..3291178a2 --- /dev/null +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/components/welcome/index.ts @@ -0,0 +1,2 @@ +export { DefaultWelcomeContent } from "./DefaultWelcomeContent" +export { EntrySummaryCard } from "./EntrySummaryCard" diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/file-upload/FileAttachmentNode.tsx b/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/file-upload/FileAttachmentNode.tsx new file mode 100644 index 000000000..adefffe4f --- /dev/null +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/file-upload/FileAttachmentNode.tsx @@ -0,0 +1,168 @@ +import type { + DOMConversionMap, + DOMConversionOutput, + DOMExportOutput, + LexicalNode, + NodeKey, + SerializedLexicalNode, + Spread, +} from "lexical" +import { DecoratorNode } from "lexical" +import * as React from "react" +import { useShallow } from "zustand/shallow" + +import { useAIChatStore } from "~/modules/ai-chat/store/AIChatContext" + +export type SerializedFileAttachmentNode = Spread< + { + attachmentId: string + }, + SerializedLexicalNode +> + +function convertFileAttachmentElement(domNode: Node): null | DOMConversionOutput { + const element = domNode as HTMLElement + const { attachmentId } = element.dataset + if (attachmentId) { + const node = $createFileAttachmentNode(attachmentId) + return { node } + } + return null +} + +export class FileAttachmentNode extends DecoratorNode { + __attachmentId: string + + static override getType(): string { + return "file-attachment" + } + + static override clone(node: FileAttachmentNode): FileAttachmentNode { + return new FileAttachmentNode(node.__attachmentId, node.__key) + } + + static override importJSON(serializedNode: SerializedFileAttachmentNode): FileAttachmentNode { + const { attachmentId } = serializedNode + const node = $createFileAttachmentNode(attachmentId) + return node + } + + static override importDOM(): DOMConversionMap | null { + return { + span: () => ({ + conversion: convertFileAttachmentElement, + priority: 1, + }), + } + } + + constructor(attachmentId: string, key?: NodeKey) { + super(key) + this.__attachmentId = attachmentId + } + + override exportJSON(): SerializedFileAttachmentNode { + return { + attachmentId: this.__attachmentId, + type: "file-attachment", + version: 1, + } + } + + override exportDOM(): DOMExportOutput { + const element = document.createElement("span") + element.dataset.attachmentId = this.__attachmentId + element.textContent = `[File: ${this.__attachmentId}]` + return { element } + } + + override createDOM(): HTMLElement { + const span = document.createElement("span") + span.style.display = "inline-block" + span.dataset.attachmentId = this.__attachmentId + return span + } + + override updateDOM(): false { + return false + } + + getAttachmentId(): string { + return this.__attachmentId + } + + setAttachmentId(attachmentId: string): void { + const writable = this.getWritable() + writable.__attachmentId = attachmentId + } + + override decorate(): React.ReactElement { + return + } + + override isInline(): boolean { + return true + } +} + +interface FileAttachmentComponentProps { + node: FileAttachmentNode +} + +function FileAttachmentComponent({ node }: FileAttachmentComponentProps) { + const attachmentId = node.getAttachmentId() + + const fileAttachment = useAIChatStore()( + useShallow((state) => { + const block = state.blocks.find( + (block) => block.type === "fileAttachment" && block.attachment.id === attachmentId, + ) + return block?.type === "fileAttachment" ? block.attachment : null + }), + ) + + if (!fileAttachment) { + return ( + + + File not found + + ) + } + + return ( + + + + {fileAttachment.name} + + {fileAttachment.uploadStatus === "uploading" && ( + + )} + {fileAttachment.uploadStatus === "processing" && ( + + )} + {fileAttachment.uploadStatus === "error" && } + {fileAttachment.uploadStatus === "completed" && ( + + )} + + ) +} + +export function $createFileAttachmentNode(attachmentId: string): FileAttachmentNode { + return new FileAttachmentNode(attachmentId) +} + +export function $isFileAttachmentNode( + node: LexicalNode | null | undefined, +): node is FileAttachmentNode { + return node instanceof FileAttachmentNode +} diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/file-upload/FileUploadPlugin.tsx b/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/file-upload/FileUploadPlugin.tsx new file mode 100644 index 000000000..db29fe467 --- /dev/null +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/file-upload/FileUploadPlugin.tsx @@ -0,0 +1,157 @@ +import type { LexicalPluginFC } from "@follow/components/ui/lexical-rich-editor/types.js" +import { useLexicalComposerContext } from "@lexical/react/LexicalComposerContext" +import type { RefObject } from "react" +import { useCallback, useEffect, useRef } from "react" + +import { FileAttachmentNode } from "./FileAttachmentNode" +import { useFileAttachmentBlockSync } from "./hooks/useFileAttachmentBlockSync" +import { useFileUploadIntegration } from "./hooks/useFileUploadIntegration" +import type { FileUploadPluginConfig } from "./types" +import { + clipboardEventHasFiles, + createDragCounter, + dragEventHasFiles, + getFilesFromDrop, + getFilesFromPaste, + preventDefaultDrag, +} from "./utils/file-handling" + +const defaultConfig: FileUploadPluginConfig = { + enableDragDrop: true, + enablePaste: true, +} + +export const FileUploadPlugin: LexicalPluginFC = () => { + const [editor] = useLexicalComposerContext() + + // Initialize file attachment block synchronization + const { handleFileAttachmentInsert } = useFileAttachmentBlockSync() + + // Initialize file upload integration with sync callback + const { handleFileDrop, handlePaste } = useFileUploadIntegration(handleFileAttachmentInsert) + + const dragCounterRef: RefObject> = useRef(undefined) as any + if (!dragCounterRef.current) { + dragCounterRef.current = createDragCounter() + } + + const finalConfig = defaultConfig + + // Handle drag enter + const handleDragEnter = useCallback( + (event: DragEvent) => { + if (!finalConfig.enableDragDrop || !dragEventHasFiles(event)) return + + preventDefaultDrag(event) + }, + [finalConfig.enableDragDrop], + ) + + // Handle drag over + const handleDragOver = useCallback( + (event: DragEvent) => { + if (!finalConfig.enableDragDrop || !dragEventHasFiles(event)) return + + preventDefaultDrag(event) + }, + [finalConfig.enableDragDrop], + ) + + // Handle drag leave + const handleDragLeave = useCallback( + (event: DragEvent) => { + if (!finalConfig.enableDragDrop) return + + preventDefaultDrag(event) + + const newCounter = dragCounterRef.current.decrement() + + if (newCounter <= 0) { + dragCounterRef.current.reset() + } + }, + [finalConfig.enableDragDrop], + ) + + // Handle drop + const handleDrop = useCallback( + async (event: DragEvent) => { + if (!finalConfig.enableDragDrop) return + + preventDefaultDrag(event) + + dragCounterRef.current.reset() + + const files = getFilesFromDrop(event) + + if (files && files.length > 0) { + await handleFileDrop(files) + } + }, + [finalConfig.enableDragDrop, handleFileDrop], + ) + + // Handle paste + const handlePasteEvent = useCallback( + async (event: ClipboardEvent) => { + if (!finalConfig.enablePaste || !clipboardEventHasFiles(event)) return + + event.preventDefault() + + const files = getFilesFromPaste(event) + + if (files && files.length > 0) { + await handlePaste(event.clipboardData!) + } + }, + [finalConfig.enablePaste, handlePaste], + ) + + // Set up event listeners + useEffect(() => { + const removeRootListener = editor.registerRootListener((rootElement, prevRootElement) => { + // Remove previous listeners + if (prevRootElement) { + if (finalConfig.enableDragDrop) { + prevRootElement.removeEventListener("dragenter", handleDragEnter) + prevRootElement.removeEventListener("dragover", handleDragOver) + prevRootElement.removeEventListener("dragleave", handleDragLeave) + prevRootElement.removeEventListener("drop", handleDrop) + } + + if (finalConfig.enablePaste) { + prevRootElement.removeEventListener("paste", handlePasteEvent) + } + } + + // Add new listeners + if (rootElement) { + if (finalConfig.enableDragDrop) { + rootElement.addEventListener("dragenter", handleDragEnter, { passive: false }) + rootElement.addEventListener("dragover", handleDragOver, { passive: false }) + rootElement.addEventListener("dragleave", handleDragLeave, { passive: false }) + rootElement.addEventListener("drop", handleDrop, { passive: false }) + } + + if (finalConfig.enablePaste) { + rootElement.addEventListener("paste", handlePasteEvent, { passive: false }) + } + } + }) + + return removeRootListener + }, [ + editor, + finalConfig, + handleDragEnter, + handleDragOver, + handleDragLeave, + handleDrop, + handlePasteEvent, + ]) + + return null +} + +FileUploadPlugin.id = "file-upload" +FileUploadPlugin.nodes = [FileAttachmentNode] diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/file-upload/components/FileDropZone.tsx b/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/file-upload/components/FileDropZone.tsx new file mode 100644 index 000000000..bb7a814a4 --- /dev/null +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/file-upload/components/FileDropZone.tsx @@ -0,0 +1,73 @@ +import { Spring } from "@follow/components/constants/spring.js" +import { cn } from "@follow/utils" +import { AnimatePresence, m } from "motion/react" +import { memo } from "react" + +interface FileDropZoneProps { + isVisible: boolean + isDragOver: boolean + className?: string +} + +export const FileDropZone = memo(({ isVisible, isDragOver, className }: FileDropZoneProps) => { + return ( + + {isVisible && ( + + {/* Backdrop */} + + + {/* Drop zone content */} + + + + + +

+ {isDragOver ? "Drop files to upload" : "Drag files here to upload"} +

+ +

+ Images, PDFs, and text files supported +

+
+
+ )} +
+ ) +}) + +FileDropZone.displayName = "FileDropZone" diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/file-upload/hooks/useFileAttachmentBlockSync.ts b/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/file-upload/hooks/useFileAttachmentBlockSync.ts new file mode 100644 index 000000000..fc4c6b8ae --- /dev/null +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/file-upload/hooks/useFileAttachmentBlockSync.ts @@ -0,0 +1,231 @@ +import { useLexicalComposerContext } from "@lexical/react/LexicalComposerContext" +import { $getNodeByKey } from "lexical" +import { useCallback, useEffect, useRef } from "react" + +import { useAIChatStore } from "~/modules/ai-chat/store/AIChatContext" +import { useChatBlockActions } from "~/modules/ai-chat/store/hooks" +import type { FileAttachmentContextBlock } from "~/modules/ai-chat/store/types" + +import { $isFileAttachmentNode, FileAttachmentNode } from "../FileAttachmentNode" + +interface FileAttachmentBlockReference { + fileNodeKey: string + blockId: string + fileId: string // unique identifier for the file +} + +/** + * Hook that manages bidirectional synchronization between file attachment nodes and context blocks + * - When a file attachment is added, corresponding block is created + * - When a block is removed, corresponding file nodes are removed + * - When a file node is removed, corresponding block is removed + */ +export const useFileAttachmentBlockSync = () => { + const [editor] = useLexicalComposerContext() + const blockActions = useChatBlockActions() + const blocks = useAIChatStore()((state) => state.blocks) + + // Reference tracking maps + const nodeToBlockRef = useRef>(undefined!) + if (!nodeToBlockRef.current) { + nodeToBlockRef.current = new Map() + } + + const fileToNodeRef = useRef>>(undefined!) + if (!fileToNodeRef.current) { + fileToNodeRef.current = new Map() + } + + const blockToFileRef = useRef>(undefined!) + if (!blockToFileRef.current) { + blockToFileRef.current = new Map() + } + + // Add file attachment reference + const addFileReference = useCallback( + (attachmentId: string, fileNodeKey: string, blockId: string) => { + const reference: FileAttachmentBlockReference = { + fileNodeKey, + blockId, + fileId: attachmentId, + } + + // Update tracking maps + nodeToBlockRef.current.set(fileNodeKey, reference) + + if (!fileToNodeRef.current.has(attachmentId)) { + fileToNodeRef.current.set(attachmentId, new Set()) + } + fileToNodeRef.current.get(attachmentId)!.add(fileNodeKey) + + blockToFileRef.current.set(blockId, attachmentId) + }, + [], + ) + + // Remove file attachment reference + const removeFileReference = useCallback((fileNodeKey: string) => { + const reference = nodeToBlockRef.current.get(fileNodeKey) + if (!reference) return null + + const { fileId, blockId } = reference + + // Clean up tracking maps + nodeToBlockRef.current.delete(fileNodeKey) + + const nodeSet = fileToNodeRef.current.get(fileId) + if (nodeSet) { + nodeSet.delete(fileNodeKey) + if (nodeSet.size === 0) { + fileToNodeRef.current.delete(fileId) + } + } + + blockToFileRef.current.delete(blockId) + + return reference + }, []) + + // Handle file attachment insertion - create block and track reference + const handleFileAttachmentInsert = useCallback( + (attachmentId: string, fileNodeKey: string) => { + // Check if block already exists for this file + const existingBlock = blocks.find( + (block): block is FileAttachmentContextBlock => + block.type === "fileAttachment" && + blockToFileRef.current.get(block.attachment.id) === attachmentId, + ) + + let blockId: string + if (existingBlock) { + // Use existing block + blockId = existingBlock.id + } else { + // Find the file attachment in the current blocks state + const currentBlocks = blockActions.getBlocks() + const addedBlock = currentBlocks.find( + (block): block is FileAttachmentContextBlock => + block.type === "fileAttachment" && block.attachment.id === attachmentId, + ) + + if (addedBlock) { + blockId = addedBlock.id + } else { + // Fallback to a predictable ID pattern + blockId = `fileAttachment-${attachmentId}-${fileNodeKey}` + } + } + + // Track the reference + addFileReference(attachmentId, fileNodeKey, blockId) + }, + [blocks, blockActions, addFileReference], + ) + + // Handle file attachment removal - remove block if no other nodes reference it + const handleFileAttachmentRemove = useCallback( + (fileNodeKey: string) => { + const reference = removeFileReference(fileNodeKey) + if (!reference) return + + const { fileId } = reference + + // Check if any other nodes still reference this file + const remainingNodes = fileToNodeRef.current.get(fileId) + if (!remainingNodes || remainingNodes.size === 0) { + // No more nodes reference this file, remove the block + blockActions.removeFileAttachment(fileId) + } + }, + [blockActions, removeFileReference], + ) + + // Handle block removal - remove corresponding file nodes + const handleBlockRemove = useCallback( + (blockId: string) => { + const fileId = blockToFileRef.current.get(blockId) + if (!fileId) return + + const nodeKeys = fileToNodeRef.current.get(fileId) + if (!nodeKeys) return + + // Remove all file attachment nodes for this file + editor.update(() => { + Array.from(nodeKeys).forEach((nodeKey) => { + const node = $getNodeByKey(nodeKey) + if (node && $isFileAttachmentNode(node)) { + node.remove() + } + }) + }) + + // Clean up references + Array.from(nodeKeys).forEach((nodeKey) => { + removeFileReference(nodeKey) + }) + }, + [editor, removeFileReference], + ) + + // Monitor block changes + useEffect(() => { + const currentBlockIds = new Set(blocks.map((block) => block.id)) + const trackedBlockIds = new Set(blockToFileRef.current.keys()) + + // Find removed blocks + for (const trackedBlockId of trackedBlockIds) { + if (!currentBlockIds.has(trackedBlockId)) { + handleBlockRemove(trackedBlockId) + } + } + }, [blocks, handleBlockRemove]) + + // Monitor file attachment node changes using mutation observer + useEffect(() => { + const removedNodeKeys = new Set() + + const unregisterMutationListener = editor.registerMutationListener( + FileAttachmentNode, + (mutatedNodes) => { + for (const [nodeKey, mutation] of mutatedNodes) { + // Only track destroyed mutations for nodes we're actually tracking + if (mutation === "destroyed" && nodeToBlockRef.current.has(nodeKey)) { + removedNodeKeys.add(nodeKey) + } + } + + // Process removed nodes in next tick to avoid state conflicts + if (removedNodeKeys.size > 0) { + const timeoutId = setTimeout(() => { + Array.from(removedNodeKeys).forEach((nodeKey) => { + handleFileAttachmentRemove(nodeKey) + }) + removedNodeKeys.clear() + }, 100) + + return () => clearTimeout(timeoutId) + } + }, + ) + + return unregisterMutationListener + }, [editor, handleFileAttachmentRemove]) + + // Cleanup on unmount + useEffect(() => { + const nodeToBlock = nodeToBlockRef.current + const fileToNode = fileToNodeRef.current + const blockToFile = blockToFileRef.current + + return () => { + nodeToBlock.clear() + fileToNode.clear() + blockToFile.clear() + } + }, []) + + return { + handleFileAttachmentInsert, + handleFileAttachmentRemove, + } +} diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/file-upload/hooks/useFileUploadIntegration.ts b/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/file-upload/hooks/useFileUploadIntegration.ts new file mode 100644 index 000000000..f638981bb --- /dev/null +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/file-upload/hooks/useFileUploadIntegration.ts @@ -0,0 +1,96 @@ +import { useLexicalComposerContext } from "@lexical/react/LexicalComposerContext" +import { + $createParagraphNode, + $getRoot, + $getSelection, + $insertNodes, + $isElementNode, +} from "lexical" +import { useCallback } from "react" + +import { useFileUploadWithDefaults } from "../../../../hooks/useFileUpload" +import { $createFileAttachmentNode } from "../FileAttachmentNode" + +export function useFileUploadIntegration( + onFileNodeInsert?: (attachmentId: string, nodeKey: string) => void, +) { + const [editor] = useLexicalComposerContext() + const { uploadFiles } = useFileUploadWithDefaults() + + const insertFileAttachmentNode = useCallback( + (attachmentId: string) => { + editor.update(() => { + const selection = $getSelection() + const root = $getRoot() + + const fileNode = $createFileAttachmentNode(attachmentId) + + if (selection) { + // Insert at current selection + $insertNodes([fileNode]) + } else { + // No selection - append to the end + const lastChild = root.getLastChild() + if (lastChild && $isElementNode(lastChild)) { + lastChild.append(fileNode) + } else { + // Create a paragraph and add the file node to it + const paragraph = $createParagraphNode() + paragraph.append(fileNode) + root.append(paragraph) + } + } + + // Notify the sync handler + const nodeKey = fileNode.getKey() + if (onFileNodeInsert) { + onFileNodeInsert(attachmentId, nodeKey) + } + }) + }, + [editor, onFileNodeInsert], + ) + + const handleMultipleFileUpload = useCallback( + async (files: File[] | FileList) => { + try { + const results = await uploadFiles(files) + + // Insert successful uploads into the editor + results.forEach((result) => { + if (result.success && result.fileAttachment) { + insertFileAttachmentNode(result.fileAttachment.id) + } + }) + } catch (error) { + console.error("Multiple file upload failed:", error) + } + }, + [uploadFiles, insertFileAttachmentNode], + ) + + const handleFileDrop = useCallback( + async (files: FileList) => { + if (files && files.length > 0) { + await handleMultipleFileUpload(files) + } + }, + [handleMultipleFileUpload], + ) + + const handlePaste = useCallback( + async (clipboardData: DataTransfer) => { + const files = Array.from(clipboardData.files) + if (files.length > 0) { + await handleMultipleFileUpload(files) + } + }, + [handleMultipleFileUpload], + ) + + return { + handleMultipleFileUpload, + handleFileDrop, + handlePaste, + } +} diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/file-upload/index.ts b/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/file-upload/index.ts new file mode 100644 index 000000000..555a0ecf6 --- /dev/null +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/file-upload/index.ts @@ -0,0 +1,3 @@ +export { FileAttachmentNode } from "./FileAttachmentNode" +export { FileUploadPlugin } from "./FileUploadPlugin" +export type * from "./types" diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/file-upload/types.ts b/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/file-upload/types.ts new file mode 100644 index 000000000..09c873121 --- /dev/null +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/file-upload/types.ts @@ -0,0 +1,15 @@ +export interface FileUploadPluginConfig { + /** + * Enable drag and drop file upload + */ + enableDragDrop?: boolean + /** + * Enable paste file upload + */ + enablePaste?: boolean +} + +export interface FileDropZoneState { + isDragOver: boolean + dragCounter: number +} diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/file-upload/utils/file-handling.ts b/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/file-upload/utils/file-handling.ts new file mode 100644 index 000000000..6f67d9838 --- /dev/null +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/file-upload/utils/file-handling.ts @@ -0,0 +1,52 @@ +/** + * Check if drag event contains files + */ +export function dragEventHasFiles(event: DragEvent): boolean { + return event.dataTransfer?.types.includes("Files") ?? false +} + +/** + * Check if clipboard event contains files + */ +export function clipboardEventHasFiles(event: ClipboardEvent): boolean { + return !!(event.clipboardData?.files && event.clipboardData.files.length > 0) +} + +/** + * Prevent default drag behaviors + */ +export function preventDefaultDrag(event: DragEvent): void { + event.preventDefault() + event.stopPropagation() +} + +/** + * Get files from drop event + */ +export function getFilesFromDrop(event: DragEvent): FileList | null { + return event.dataTransfer?.files ?? null +} + +/** + * Get files from paste event + */ +export function getFilesFromPaste(event: ClipboardEvent): FileList | null { + return event.clipboardData?.files ?? null +} + +/** + * Debounce drag counter for proper drag leave handling + */ +export function createDragCounter() { + let counter = 0 + + return { + increment: () => ++counter, + decrement: () => --counter, + get: () => counter, + reset: () => { + counter = 0 + return counter + }, + } +} diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/index.tsx b/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/index.tsx index 880d97c42..14a91d1b3 100644 --- a/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/index.tsx +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/index.tsx @@ -1 +1,2 @@ +export * from "./file-upload" export * from "./mention" diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/mention/hooks/useMentionBlockSync.ts b/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/mention/hooks/useMentionBlockSync.ts index f58d78eb4..cf75cb5cb 100644 --- a/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/mention/hooks/useMentionBlockSync.ts +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/mention/hooks/useMentionBlockSync.ts @@ -4,7 +4,7 @@ import { useCallback, useEffect, useRef } from "react" import { useAIChatStore } from "~/modules/ai-chat/store/AIChatContext" import { useChatBlockActions } from "~/modules/ai-chat/store/hooks" -import type { AIChatContextBlock } from "~/modules/ai-chat/store/types" +import type { AIChatContextBlock, ValueContextBlock } from "~/modules/ai-chat/store/types" import { $isMentionNode, MentionNode } from "../MentionNode" import type { MentionData } from "../types" @@ -18,7 +18,7 @@ interface MentionBlockReference { const getResourceId = (type: string, value: string) => `${type}:${value}` -const getBlockType = (mentionType: string): AIChatContextBlock["type"] => { +const getBlockType = (mentionType: string): ValueContextBlock["type"] => { return mentionType === "feed" ? "referFeed" : "referEntry" } @@ -34,9 +34,20 @@ export const useMentionBlockSync = () => { const blocks = useAIChatStore()((state) => state.blocks) // Reference tracking maps - const mentionToBlockRef = useRef(new Map()) // mentionNodeKey -> reference - const resourceToMentionsRef = useRef(new Map>()) // resourceId -> Set - const blockToResourceRef = useRef(new Map()) // blockId -> resourceId + const mentionToBlockRef = useRef>(undefined!) + if (!mentionToBlockRef.current) { + mentionToBlockRef.current = new Map() + } + + const resourceToMentionsRef = useRef>>(undefined!) + if (!resourceToMentionsRef.current) { + resourceToMentionsRef.current = new Map() + } + + const blockToResourceRef = useRef>(undefined!) + if (!blockToResourceRef.current) { + blockToResourceRef.current = new Map() + } // Add mention-block reference const addMentionReference = useCallback( @@ -105,7 +116,7 @@ export const useMentionBlockSync = () => { const blockType = getBlockType(mentionData.type) // Generate block ID (mimicking the block slice logic) - const newBlock: Omit = { + const newBlock: Omit = { type: blockType, value: mentionData.value as string, } @@ -115,7 +126,8 @@ export const useMentionBlockSync = () => { // Use current blocks state directly from store instead of stale closure const currentBlocks = blockActions.getBlocks() const addedBlock = currentBlocks.find( - (block) => block.type === blockType && block.value === mentionData.value, + (block): block is Extract => + block.type === blockType && block.value === mentionData.value, ) if (addedBlock) { @@ -239,11 +251,5 @@ export const useMentionBlockSync = () => { return { handleMentionInsert, handleMentionRemove, - // Debug helpers - getMentionReferences: () => ({ - mentionToBlock: new Map(mentionToBlockRef.current), - resourceToMentions: new Map(resourceToMentionsRef.current), - blockToResource: new Map(blockToResourceRef.current), - }), } } diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/mention/hooks/useMentionSearchService.ts b/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/mention/hooks/useMentionSearchService.ts index 91603a943..a9c7525d4 100644 --- a/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/mention/hooks/useMentionSearchService.ts +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/mention/hooks/useMentionSearchService.ts @@ -1,6 +1,6 @@ import { useMemo } from "react" -import { useFeedEntrySearchService } from "~/modules/ai-chat/services/feedEntrySearchService" +import { useFeedEntrySearchService } from "~/modules/ai-chat/hooks/useFeedEntrySearchService" import type { MentionData, MentionType } from "../types" diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/hooks/useAIModel.ts b/apps/desktop/layer/renderer/src/modules/ai-chat/hooks/useAIModel.ts new file mode 100644 index 000000000..ecaaea766 --- /dev/null +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/hooks/useAIModel.ts @@ -0,0 +1,26 @@ +import { useQuery } from "@tanstack/react-query" + +import { followApi } from "~/lib/api-client" + +const useAIConfiguration = () => { + return useQuery({ + queryKey: ["aiConfiguration"], + queryFn: async () => { + return followApi.ai.config() + }, + staleTime: 5 * 60 * 1000, + retry: false, + }) +} + +export const useAIModel = () => { + const { data: configuration, isLoading } = useAIConfiguration() + + return { + data: { + currentModel: configuration?.currentModel, + availableModels: configuration?.availableModels, + }, + isLoading, + } +} diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/hooks/useAutoScroll.tsx b/apps/desktop/layer/renderer/src/modules/ai-chat/hooks/useAutoScroll.tsx index 14435fb54..9f3b0ef5f 100644 --- a/apps/desktop/layer/renderer/src/modules/ai-chat/hooks/useAutoScroll.tsx +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/hooks/useAutoScroll.tsx @@ -1,26 +1,22 @@ import { springScrollTo } from "@follow/utils/scroller" -import { debounce } from "es-toolkit/compat" +import { debounce, throttle } 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(null) const isAutoScrollingRef = useRef(false) - - const isUserInteractingRef = useRef(isUserInteracting) - useEffect(() => { - isUserInteractingRef.current = isUserInteracting - }, [isUserInteracting]) + const isAutoScrollCancelledRef = useRef(false) const isAtBottomRef = useRef(isAtBottom) useEffect(() => { isAtBottomRef.current = isAtBottom }, [isAtBottom]) + // cancellation is tracked purely via ref to avoid re-renders while user interacts + const scrollToBottom = useCallback( (force = false) => { if (!viewport) return @@ -29,7 +25,7 @@ export const useAutoScroll = (viewport: HTMLElement | null, enabled: boolean) => scrollAnimationRef.current.stop() } - if (force || (!isUserInteractingRef.current && isAtBottomRef.current)) { + if (force || (isAtBottomRef.current && !isAutoScrollCancelledRef.current)) { isAutoScrollingRef.current = true const targetScrollTop = viewport.scrollHeight - viewport.clientHeight const animation = springScrollTo(targetScrollTop, viewport) @@ -52,55 +48,43 @@ export const useAutoScroll = (viewport: HTMLElement | null, enabled: boolean) => useEffect(() => { if (!viewport) return + if (!enabled) return - if (!enabled) { - return - } - - const handleScroll = () => { + const handleScroll = throttle(() => { if (isAutoScrollingRef.current) { return } + }, 100) - const { scrollTop, scrollHeight, clientHeight } = viewport - const atBottom = scrollHeight - scrollTop - clientHeight <= BOTTOM_THRESHOLD - - if (!isUserInteractingRef.current) { - setIsAtBottom(atBottom) - } - } - - const handleWheel = () => { + const cancelAutoScroll = () => { 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) + isAutoScrollCancelledRef.current = true + handleScroll() } + const handleWheel = throttle(cancelAutoScroll, 100) + const handleTouchStart = handleWheel + const handleTouchMove = handleWheel + viewport.addEventListener("scroll", handleScroll, { passive: true }) viewport.addEventListener("wheel", handleWheel, { passive: true }) + viewport.addEventListener("touchstart", handleTouchStart, { passive: true }) + viewport.addEventListener("touchmove", handleTouchMove, { passive: true }) return () => { viewport.removeEventListener("scroll", handleScroll) viewport.removeEventListener("wheel", handleWheel) - if (interactionTimeoutRef.current) { - window.clearTimeout(interactionTimeoutRef.current) - } + viewport.removeEventListener("touchstart", handleTouchStart) + viewport.removeEventListener("touchmove", handleTouchMove) if (scrollAnimationRef.current) { scrollAnimationRef.current.stop() } } - }, [viewport]) + }, [viewport, enabled]) useEffect(() => { if (!viewport || !enabled) return @@ -110,7 +94,7 @@ export const useAutoScroll = (viewport: HTMLElement | null, enabled: boolean) => const resizeObserver = new ResizeObserver( debounce(() => { - if (!isUserInteractingRef.current && isAtBottomRef.current) { + if (isAtBottomRef.current && !isAutoScrollCancelledRef.current) { requestAnimationFrame(() => { scrollToBottom() }) @@ -126,7 +110,7 @@ export const useAutoScroll = (viewport: HTMLElement | null, enabled: boolean) => }, [viewport, enabled, scrollToBottom]) const resetScrollState = useCallback(() => { - setIsUserInteracting(false) + isAutoScrollCancelledRef.current = false setIsAtBottom(true) scrollToBottom(true) }, [scrollToBottom]) diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/hooks/useChatHistory.ts b/apps/desktop/layer/renderer/src/modules/ai-chat/hooks/useChatHistory.ts index 129e4f6a5..abb9c2a96 100644 --- a/apps/desktop/layer/renderer/src/modules/ai-chat/hooks/useChatHistory.ts +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/hooks/useChatHistory.ts @@ -16,6 +16,7 @@ export const useChatHistory = () => { chatId: row.chatId, title: row.title || "New Chat", createdAt: new Date(row.createdAt), + updatedAt: new Date(row.updatedAt), messageCount: row.messageCount, })) diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/services/feedEntrySearchService.ts b/apps/desktop/layer/renderer/src/modules/ai-chat/hooks/useFeedEntrySearchService.ts similarity index 100% rename from apps/desktop/layer/renderer/src/modules/ai-chat/services/feedEntrySearchService.ts rename to apps/desktop/layer/renderer/src/modules/ai-chat/hooks/useFeedEntrySearchService.ts diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/hooks/useFileUpload.ts b/apps/desktop/layer/renderer/src/modules/ai-chat/hooks/useFileUpload.ts new file mode 100644 index 000000000..610d35ab4 --- /dev/null +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/hooks/useFileUpload.ts @@ -0,0 +1,215 @@ +import { nanoid } from "nanoid" +import { useCallback } from "react" +import { toast } from "sonner" + +import { useChatBlockActions } from "../store/hooks" +import type { FileAttachment } from "../store/types" +import type { ProcessFileOptions, ProcessFileResult } from "../utils/file-processing" +import { processAndUploadFile } from "../utils/file-processing" + +export interface UseFileUploadOptions extends ProcessFileOptions { + /** + * Show success toast on successful upload + */ + showSuccessToast?: boolean + /** + * Show error toast on upload failure + */ + showErrorToast?: boolean + /** + * Custom success message for toast + */ + successMessage?: string + /** + * Custom error message prefix for toast + */ + errorMessagePrefix?: string +} + +export interface FileUploadHandlers { + /** + * Upload a single file with progress tracking + */ + uploadFile: (file: File, id?: string) => Promise + /** + * Upload multiple files with progress tracking + */ + uploadFiles: (files: File[] | FileList) => Promise + /** + * Handle file input change event + */ + handleFileInputChange: (event: React.ChangeEvent) => Promise + /** + * Handle drag and drop files + */ + handleFileDrop: (files: FileList) => Promise +} + +/** + * Hook for handling file uploads with progress tracking and block management + */ +export function useFileUpload(options: UseFileUploadOptions = {}): FileUploadHandlers { + const { + showSuccessToast = false, + showErrorToast = true, + successMessage = "File uploaded successfully", + errorMessagePrefix = "File upload error", + ...processOptions + } = options + + const blockActions = useChatBlockActions() + + const uploadFile = useCallback( + async (file: File, id?: string): Promise => { + // Create initial file attachment for immediate UI feedback + const initialFileAttachment: FileAttachment = { + id: id || nanoid(), + name: file.name, + type: file.type, + size: file.size, + dataUrl: "", // Will be filled during processing + uploadStatus: "processing", + uploadProgress: 0, + } + + // Add the initial block immediately for real-time UI feedback + blockActions.addFileAttachment(initialFileAttachment) + + try { + const result = await processAndUploadFile(file, processOptions, (updatedAttachment) => { + // Update the attachment with the same ID to maintain consistency + const syncedAttachment = { + ...updatedAttachment, + id: initialFileAttachment.id, // Keep the same ID + } + blockActions.updateFileAttachment(initialFileAttachment.id, syncedAttachment) + }) + + if (result.success && result.fileAttachment) { + // Update the final completed state with the same ID + const finalAttachment = { + ...result.fileAttachment, + id: initialFileAttachment.id, // Keep the same ID + } + + blockActions.updateFileAttachment(initialFileAttachment.id, finalAttachment) + + if (showSuccessToast) { + toast.success(`${successMessage}: ${file.name}`) + } + + // Return result with consistent ID + return { + ...result, + fileAttachment: finalAttachment, + } + } else { + // Update to error state + const errorAttachment: FileAttachment = { + ...initialFileAttachment, + uploadStatus: "error", + errorMessage: result.error || "Upload failed", + uploadProgress: undefined, + } + + blockActions.updateFileAttachment(initialFileAttachment.id, errorAttachment) + + if (showErrorToast && result.error) { + toast.error(`${errorMessagePrefix}: ${result.error}`) + } + + return { + ...result, + fileAttachment: errorAttachment, + } + } + } catch (error) { + const errorMessage = error instanceof Error ? error.message : "Unknown error" + + // Update to error state + const errorAttachment: FileAttachment = { + ...initialFileAttachment, + uploadStatus: "error", + errorMessage, + uploadProgress: undefined, + } + + blockActions.updateFileAttachment(initialFileAttachment.id, errorAttachment) + + if (showErrorToast) { + toast.error(`${errorMessagePrefix}: ${errorMessage}`) + } + + console.error("File upload failed:", error) + + return { + success: false, + error: errorMessage, + fileAttachment: errorAttachment, + } + } + }, + [ + blockActions, + processOptions, + showSuccessToast, + showErrorToast, + successMessage, + errorMessagePrefix, + ], + ) + + const uploadFiles = useCallback( + async (files: File[] | FileList): Promise => { + const results: ProcessFileResult[] = [] + const fileArray = Array.from(files) + + // Process files sequentially to avoid overwhelming the server + for (const file of fileArray) { + const result = await uploadFile(file) + results.push(result) + } + + return results + }, + [uploadFile], + ) + + const handleFileInputChange = useCallback( + async (event: React.ChangeEvent) => { + const { files } = event.target + if (files && files.length > 0) { + await uploadFiles(files) + } + // Reset file input + event.target.value = "" + }, + [uploadFiles], + ) + + const handleFileDrop = useCallback( + async (files: FileList) => { + if (files && files.length > 0) { + await uploadFiles(files) + } + }, + [uploadFiles], + ) + + return { + uploadFile, + uploadFiles, + handleFileInputChange, + handleFileDrop, + } +} + +/** + * Convenience hook for file upload with default settings + */ +export function useFileUploadWithDefaults(): FileUploadHandlers { + return useFileUpload({ + showErrorToast: true, + showSuccessToast: false, + }) +} diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/hooks/useMainEntryId.ts b/apps/desktop/layer/renderer/src/modules/ai-chat/hooks/useMainEntryId.ts new file mode 100644 index 000000000..4f8faef9c --- /dev/null +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/hooks/useMainEntryId.ts @@ -0,0 +1,15 @@ +import { useAIChatStore } from "../store/AIChatContext" + +/** + * Hook to get the current main entry ID from the AI chat store. + * Returns undefined if no entry context is available. + * + * This hook accesses the mainEntry block that gets set when viewing an entry, + * enabling context-aware AI chat features. + */ +export const useMainEntryId = (): string | undefined => { + return useAIChatStore()((state) => { + const block = state.blocks.find((b) => b.type === "mainEntry") + return block && block.type === "mainEntry" ? block.value : undefined + }) +} diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/hooks/useSmartQuickActions.ts b/apps/desktop/layer/renderer/src/modules/ai-chat/hooks/useSmartQuickActions.ts new file mode 100644 index 000000000..984e7d368 --- /dev/null +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/hooks/useSmartQuickActions.ts @@ -0,0 +1,88 @@ +import { useEntry } from "@follow/store/entry/hooks" +import { useMemo } from "react" +import { useTranslation } from "react-i18next" + +interface QuickAction { + id: string + label: string + prompt: string + icon: string + priority: number +} + +const DEFAULT_ENTRY_ACTIONS: QuickAction[] = [ + { + id: "analyze", + label: "Analyze this entry", + prompt: "Can you analyze this entry and tell me what it's about?", + icon: "i-mgc-search-cute-re", + priority: 1, + }, + { + id: "explain", + label: "Explain key points", + prompt: "What are the key points I should understand from this entry?", + icon: "i-mgc-lightbulb-cute-re", + priority: 2, + }, +] + +/** + * Hook to generate contextual conversation starters based on summary content and entry metadata. + * Returns an array of quick actions that provide intelligent prompts for starting AI conversations. + */ +export const useSmartQuickActions = ( + summaryData: string | null, + entryId: string, +): QuickAction[] => { + const entry = useEntry(entryId, (state) => ({ url: state.url })) + const { t } = useTranslation("ai") + + return useMemo(() => { + if (!summaryData || !entry) return DEFAULT_ENTRY_ACTIONS + + const actions: QuickAction[] = [] + + // Content-based actions + if (summaryData.length > 500) { + actions.push({ + id: "simplify", + label: t("quick_actions.simplify") || "Simplify this", + prompt: `Can you simplify this summary in 2-3 sentences? Focus on the main points.`, + icon: "i-mgc-edit-cute-re", + priority: 1, + }) + } + + // Entry type-based actions + if (entry.url) { + actions.push({ + id: "discuss", + label: t("quick_actions.discuss") || "Discuss insights", + prompt: `What are the key insights from this article? What should I know?`, + icon: "i-mgc-chat-cute-re", + priority: 2, + }) + } + + // Always available actions + actions.push( + { + id: "questions", + label: t("quick_actions.questions") || "Ask questions", + prompt: `What questions should I be asking about this content?`, + icon: "i-mgc-question-cute-re", + priority: 3, + }, + { + id: "takeaways", + label: t("quick_actions.takeaways") || "Key takeaways", + prompt: `What are the most important takeaways from this entry?`, + icon: "i-mgc-star-cute-re", + priority: 4, + }, + ) + + return actions.sort((a, b) => a.priority - b.priority).slice(0, 4) + }, [summaryData, entry, t]) +} diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/services/contextBarSearchService.ts b/apps/desktop/layer/renderer/src/modules/ai-chat/services/contextBarSearchService.ts deleted file mode 100644 index 22b4b92b4..000000000 --- a/apps/desktop/layer/renderer/src/modules/ai-chat/services/contextBarSearchService.ts +++ /dev/null @@ -1,69 +0,0 @@ -import { useMemo } from "react" - -import type { SearchItem } from "./feedEntrySearchService" -import { useFeedEntrySearchService } from "./feedEntrySearchService" - -/** - * Picker item interface for context bar compatibility - */ -export interface PickerItem { - id: string - title: string -} - -/** - * Hook that provides search functionality for context bar - * Uses the shared feed/entry search service and converts results to PickerItem format - */ -export const useContextBarSearchService = () => { - const { search, feedItems, entryItems } = useFeedEntrySearchService({ - maxRecentEntries: 50, - fuseOptions: { - keys: ["title", "id"], - threshold: 0.3, - }, - }) - - // Convert search items to picker items - const convertToPickerItems = useMemo(() => { - return (items: SearchItem[]): PickerItem[] => { - return items.map((item) => ({ - id: item.id, - title: item.title, - })) - } - }, []) - - // Search function for feeds - const searchFeeds = useMemo(() => { - return (query: string): PickerItem[] => { - const results = search(query, "feed", 20) - return convertToPickerItems(results) - } - }, [search, convertToPickerItems]) - - // Search function for entries - const searchEntries = useMemo(() => { - return (query: string): PickerItem[] => { - const results = search(query, "entry", 20) - return convertToPickerItems(results) - } - }, [search, convertToPickerItems]) - - // Get all feeds as picker items - const allFeeds = useMemo(() => { - return convertToPickerItems(feedItems) - }, [feedItems, convertToPickerItems]) - - // Get all recent entries as picker items - const allRecentEntries = useMemo(() => { - return convertToPickerItems(entryItems) - }, [entryItems, convertToPickerItems]) - - return { - searchFeeds, - searchEntries, - allFeeds, - allRecentEntries, - } -} diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/services/index.ts b/apps/desktop/layer/renderer/src/modules/ai-chat/services/index.ts index 245ebf0a1..c7eb2414a 100644 --- a/apps/desktop/layer/renderer/src/modules/ai-chat/services/index.ts +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/services/index.ts @@ -74,7 +74,7 @@ class AIPersistServiceStatic { * Returns both session details and messages to avoid redundant queries */ async loadSessionWithMessages(chatId: string): Promise<{ - session: { chatId: string; title?: string; createdAt: Date } | null + session: { chatId: string; title?: string; createdAt: Date; updatedAt: Date } | null messages: BizUIMessage[] }> { // Load both session and messages in parallel @@ -154,23 +154,25 @@ class AIPersistServiceStatic { await db .insert(aiChatMessagesTable) .values( - messages.map((message) => { - const convertedParts = message.parts as any[] + messages + .filter((message) => message.parts.length > 0) + .map((message) => { + const convertedParts = message.parts as any[] - return { - id: message.id, - chatId, - role: message.role, - contentFormat: "plaintext" as const, - createdAt: new Date(), - status: "completed" as const, - finishedAt: message.metadata?.finishTime - ? new Date(message.metadata.finishTime) - : undefined, - messageParts: convertedParts, - metadata: message.metadata, - } as typeof aiChatMessagesTable.$inferInsert - }), + return { + id: message.id, + chatId, + role: message.role, + contentFormat: "plaintext" as const, + createdAt: new Date(), + status: "completed" as const, + finishedAt: message.metadata?.finishTime + ? new Date(message.metadata.finishTime) + : undefined, + messageParts: convertedParts, + metadata: message.metadata, + } as typeof aiChatMessagesTable.$inferInsert + }), ) .onConflictDoUpdate({ target: [aiChatMessagesTable.id], @@ -244,6 +246,7 @@ class AIPersistServiceStatic { chatId: true, title: true, createdAt: true, + updatedAt: true, }, }) @@ -265,8 +268,9 @@ class AIPersistServiceStatic { chatId: true, title: true, createdAt: true, + updatedAt: true, }, - orderBy: (t, { desc }) => desc(t.createdAt), + orderBy: (t, { desc }) => desc(t.updatedAt), limit, }) @@ -291,6 +295,7 @@ class AIPersistServiceStatic { chatId: chat.chatId, title: chat.title, createdAt: chat.createdAt, + updatedAt: chat.updatedAt, messageCount: messageCountMap.get(chat.chatId) || 0, })) .filter((chat) => chat.messageCount > 0) @@ -313,6 +318,15 @@ class AIPersistServiceStatic { .where(eq(aiChatTable.chatId, chatId)) } + async updateSessionTime(chatId: string) { + await db + .update(aiChatTable) + .set({ + updatedAt: new Date(Date.now()), + }) + .where(eq(aiChatTable.chatId, chatId)) + } + async cleanupEmptySessions() { const emptySessions = await db.values<[string]>( sql` diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/store/chat-core/chat-actions.ts b/apps/desktop/layer/renderer/src/modules/ai-chat/store/chat-core/chat-actions.ts index 94e93ae7d..c2f67fe79 100644 --- a/apps/desktop/layer/renderer/src/modules/ai-chat/store/chat-core/chat-actions.ts +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/store/chat-core/chat-actions.ts @@ -92,6 +92,35 @@ export class ChatSliceActions { return this.get().chatId } + // Edit chat title + editChatTitle = async (newTitle: string) => { + const currentChatId = this.getCurrentChatId() + if (!currentChatId) { + throw new Error("No active chat to edit title for") + } + + const trimmedTitle = newTitle.trim() + const currentTitle = this.getCurrentTitle() + + // If no changes, return early + if (trimmedTitle === currentTitle) { + return + } + + try { + // Optimistic update + this.setCurrentTitle(trimmedTitle) + + // Persist to database + await AIPersistService.updateSessionTitle(currentChatId, trimmedTitle) + } catch (error) { + // Rollback on error + this.setCurrentTitle(currentTitle) + console.error("Failed to update chat title:", error) + throw error + } + } + // Core chat actions using AI SDK AbstractChat methods sendMessage = async (message: string | BizUIMessage) => { try { diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/store/chat-core/chat-state.ts b/apps/desktop/layer/renderer/src/modules/ai-chat/store/chat-core/chat-state.ts index 03d546981..53a69c420 100644 --- a/apps/desktop/layer/renderer/src/modules/ai-chat/store/chat-core/chat-state.ts +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/store/chat-core/chat-state.ts @@ -145,6 +145,8 @@ export class ZustandChatState implements ChatSt await AIPersistService.ensureSession(this.chatId, "New Chat") // Save messages using incremental updates await AIPersistService.upsertMessages(this.chatId, this.#messages) + // Update session time after successfully saving messages + await AIPersistService.updateSessionTime(this.chatId) } catch (error) { console.error("Failed to persist messages:", error) } diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/store/hooks.ts b/apps/desktop/layer/renderer/src/modules/ai-chat/store/hooks.ts index b370e100c..70ea45817 100644 --- a/apps/desktop/layer/renderer/src/modules/ai-chat/store/hooks.ts +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/store/hooks.ts @@ -16,28 +16,6 @@ export const useCurrentTitle = () => { return store((state) => state.currentTitle) } -/** - * Hook to get the setter for current room ID - */ -export const useSetCurrentChatId = () => { - const store = useAIChatStore() - return (chatId: string | null) => { - const actions = store.getState().chatActions - if (chatId && chatId !== actions.getCurrentChatId()) { - // If we need to switch to a different room, create a new chat - actions.newChat() - } - } -} - -/** - * Hook to get the setter for current title - */ -export const useSetCurrentTitle = () => { - const store = useAIChatStore() - return store.getState().chatActions.setCurrentTitle -} - /** * Hook to get the chat actions */ @@ -54,14 +32,6 @@ export const useBlockActions = () => { return store((state) => state.blockActions) } -/** - * Hook to get the chat instance - */ -export const useChatInstance = () => { - const store = useAIChatStore() - return store((state) => state.chatInstance) -} - /** * Hook to get the current messages */ @@ -94,11 +64,3 @@ export const useChatError = () => { const store = useAIChatStore() return store((state) => state.error) } - -/** - * Hook to get the streaming status - */ -export const useIsStreaming = () => { - const store = useAIChatStore() - return store((state) => state.isStreaming) -} diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/store/slices/block.slice.ts b/apps/desktop/layer/renderer/src/modules/ai-chat/store/slices/block.slice.ts index 7f0162dfd..8a60c6691 100644 --- a/apps/desktop/layer/renderer/src/modules/ai-chat/store/slices/block.slice.ts +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/store/slices/block.slice.ts @@ -3,7 +3,8 @@ import { produce } from "immer" import { nanoid } from "nanoid" import type { StateCreator } from "zustand" -import type { AIChatContextBlock } from "../types" +import { cleanupFileAttachment } from "../../utils/file-processing" +import type { AIChatContextBlock, AIChatContextBlockInput, FileAttachment } from "../types" export interface BlockSlice { blocks: AIChatContextBlock[] @@ -39,7 +40,7 @@ export class BlockSliceAction { get get() { return this.params[1] } - addBlock(block: Omit) { + addBlock(block: AIChatContextBlockInput) { const currentBlocks = this.get().blocks // Only allow one SPECIAL_TYPES @@ -60,6 +61,10 @@ export class BlockSliceAction { removeBlock(id: string) { this.set( produce((state: BlockSlice) => { + const blockToRemove = state.blocks.find((block) => block.id === id) + if (blockToRemove && blockToRemove.type === "fileAttachment") { + cleanupFileAttachment(blockToRemove.attachment) + } state.blocks = state.blocks.filter((block) => block.id !== id) }), ) @@ -68,9 +73,18 @@ export class BlockSliceAction { updateBlock(id: string, updates: Partial) { this.set( produce((state: BlockSlice) => { - state.blocks = state.blocks.map((block) => - block.id === id ? { ...block, ...updates } : block, - ) + state.blocks = state.blocks.map((block) => { + if (block.id !== id) return block + + // Handle discriminated union updates carefully + if (updates.type && updates.type !== block.type) { + // Type change - need to replace the entire block + return { ...updates, id } as AIChatContextBlock + } else { + // Same type - safe to spread + return { ...block, ...updates } as AIChatContextBlock + } + }) }), ) } @@ -84,10 +98,20 @@ export class BlockSliceAction { } } - clearBlocks() { + clearBlocks({ keepSpecialTypes = false }: { keepSpecialTypes?: boolean } = {}) { this.set( produce((state: BlockSlice) => { - state.blocks = [] + // Clean up file attachments before clearing + state.blocks.forEach((block) => { + if (block.type === "fileAttachment") { + cleanupFileAttachment(block.attachment) + } + }) + state.blocks = keepSpecialTypes + ? state.blocks.filter((b) => + Object.values(BlockSliceAction.SPECIAL_TYPES).includes(b.type), + ) + : [] }), ) } @@ -95,6 +119,12 @@ export class BlockSliceAction { resetContext() { this.set( produce((state: BlockSlice) => { + // Clean up file attachments before resetting + state.blocks.forEach((block) => { + if (block.type === "fileAttachment") { + cleanupFileAttachment(block.attachment) + } + }) state.blocks = [] }), ) @@ -103,4 +133,49 @@ export class BlockSliceAction { getBlocks() { return this.get().blocks } + + // File attachment specific methods + addFileAttachment(fileAttachment: FileAttachment) { + const fileBlock: AIChatContextBlock = { + id: fileAttachment.id, + type: "fileAttachment", + attachment: fileAttachment, + } + this.addBlock(fileBlock) + } + + updateFileAttachment(attachmentId: string, updatedAttachment: FileAttachment) { + this.set( + produce((state: BlockSlice) => { + const block = state.blocks.find( + (b) => b.type === "fileAttachment" && b.attachment.id === attachmentId, + ) + if (block && block.type === "fileAttachment") { + block.attachment = updatedAttachment + } + }), + ) + } + + updateFileAttachmentStatus( + fileId: string, + status: FileAttachment["uploadStatus"], + errorMessage?: string, + ) { + this.set( + produce((state: BlockSlice) => { + const block = state.blocks.find((b) => b.id === fileId) + if (block && block.type === "fileAttachment") { + block.attachment.uploadStatus = status + if (errorMessage) { + block.attachment.errorMessage = errorMessage + } + } + }), + ) + } + + removeFileAttachment(fileId: string) { + this.removeBlock(fileId) + } } diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/store/types.ts b/apps/desktop/layer/renderer/src/modules/ai-chat/store/types.ts index b2d9a5adc..79567486f 100644 --- a/apps/desktop/layer/renderer/src/modules/ai-chat/store/types.ts +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/store/types.ts @@ -1,11 +1,40 @@ import type { BizUITools, ToolWithState } from "@folo-services/ai-tools" -export interface AIChatContextBlock { +export interface FileAttachment { id: string + name: string + type: string + size: number + dataUrl: string + previewUrl?: string + uploadStatus: "processing" | "uploading" | "completed" | "error" + serverUrl?: string + errorMessage?: string + /** Upload progress percentage (0-100) */ + uploadProgress?: number +} + +interface BaseContextBlock { + id: string +} + +export interface ValueContextBlock extends BaseContextBlock { type: "mainEntry" | "referEntry" | "referFeed" | "selectedText" value: string } +export interface FileAttachmentContextBlock extends BaseContextBlock { + type: "fileAttachment" + attachment: FileAttachment +} + +export type AIChatContextBlock = ValueContextBlock | FileAttachmentContextBlock + +// Helper type for creating new blocks without id +export type AIChatContextBlockInput = + | Omit + | Omit + export interface AIChatStoreInitial { blocks: AIChatContextBlock[] } diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/types/ChatSession.ts b/apps/desktop/layer/renderer/src/modules/ai-chat/types/ChatSession.ts index f145e48e8..60f422e8c 100644 --- a/apps/desktop/layer/renderer/src/modules/ai-chat/types/ChatSession.ts +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/types/ChatSession.ts @@ -4,6 +4,7 @@ export interface ChatSession { chatId: string title?: string createdAt: Date + updatedAt: Date messageCount: number } diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/utils/export.ts b/apps/desktop/layer/renderer/src/modules/ai-chat/utils/export.ts index c85bdb3c9..3367a50b6 100644 --- a/apps/desktop/layer/renderer/src/modules/ai-chat/utils/export.ts +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/utils/export.ts @@ -1,6 +1,7 @@ import type { UIDataTypes, UIMessage } from "ai" import type { BizUIMetadata, BizUITools } from "../store/types" +import type { RichTextPart } from "../types/ChatSession" export const exportChatToMarkdown = ( messages: UIMessage[], @@ -19,11 +20,17 @@ export const exportChatToMarkdown = ( markdown += `## 👤 User\n` if (timestamp) markdown += `*${timestamp}*\n\n` - // Extract text content from parts + // Extract text content from parts in single pass const textContent = message.parts - ?.filter((part) => part.type === "text") - .map((part) => part.text) + ?.reduce((acc, part) => { + if (part.type === "text") { + acc.push(part.text) + } else if (part.type === "data-rich-text") { + acc.push((part as RichTextPart).data.text) + } + return acc + }, [] as string[]) .join("\n") || "" markdown += `${textContent}\n\n` @@ -31,11 +38,17 @@ export const exportChatToMarkdown = ( markdown += `## 🤖 ${APP_NAME} AI\n` if (timestamp) markdown += `*${timestamp}*\n\n` - // Extract text content from parts + // Extract text content from parts in single pass const textContent = message.parts - ?.filter((part) => part.type === "text") - .map((part) => part.text) + ?.reduce((acc, part) => { + if (part.type === "text") { + acc.push(part.text) + } else if (part.type === "data-rich-text") { + acc.push((part as RichTextPart).data.text) + } + return acc + }, [] as string[]) .join("\n") || "" markdown += `${textContent}\n\n` diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/utils/file-processing.ts b/apps/desktop/layer/renderer/src/modules/ai-chat/utils/file-processing.ts new file mode 100644 index 000000000..3698546a5 --- /dev/null +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/utils/file-processing.ts @@ -0,0 +1,289 @@ +import { nanoid } from "nanoid" + +import { followApi } from "~/lib/api-client" + +import type { FileAttachment } from "../store/types" +import type { FileValidationResult } from "./file-validation" +import { validateFile } from "./file-validation" + +export interface ProcessFileOptions { + maxImageWidth?: number + maxImageHeight?: number + imageQuality?: number +} + +export interface ProcessFileResult { + success: boolean + fileAttachment?: FileAttachment + error?: string +} + +export async function processFile( + file: File, + options: ProcessFileOptions = {}, +): Promise { + const { maxImageWidth = 1920, maxImageHeight = 1080, imageQuality = 0.85 } = options + + // Validate file + const validation: FileValidationResult = validateFile(file) + if (!validation.isValid) { + return { + success: false, + error: validation.error?.message || "File validation failed", + } + } + + try { + const fileId = nanoid() + let dataUrl: string + let previewUrl: string | undefined + + if (validation.fileInfo?.category === "image") { + // Process image: compress and generate preview + const processedImage = await processImage(file, { + maxWidth: maxImageWidth, + maxHeight: maxImageHeight, + quality: imageQuality, + }) + + dataUrl = processedImage.dataUrl + previewUrl = processedImage.previewUrl + } else { + // For non-images, just convert to data URL + dataUrl = await fileToDataUrl(file) + } + + const fileAttachment: FileAttachment = { + id: fileId, + name: file.name, + type: file.type, + size: file.size, + dataUrl, + previewUrl, + uploadStatus: "completed", + } + + return { + success: true, + fileAttachment, + } + } catch (error) { + return { + success: false, + error: `Failed to process file: ${error instanceof Error ? error.message : "Unknown error"}`, + } + } +} + +interface ProcessImageResult { + dataUrl: string + previewUrl: string +} + +async function processImage( + file: File, + options: { maxWidth: number; maxHeight: number; quality: number }, +): Promise { + return new Promise((resolve, reject) => { + const img = new Image() + const canvas = document.createElement("canvas") + const ctx = canvas.getContext("2d") + + if (!ctx) { + reject(new Error("Could not get canvas context")) + return + } + + img.onload = () => { + // Calculate new dimensions + let { width, height } = img + const { maxWidth, maxHeight, quality } = options + + if (width > maxWidth || height > maxHeight) { + const ratio = Math.min(maxWidth / width, maxHeight / height) + width *= ratio + height *= ratio + } + + // Set canvas dimensions + canvas.width = width + canvas.height = height + + // Draw and compress image + ctx.drawImage(img, 0, 0, width, height) + + const dataUrl = canvas.toDataURL(file.type, quality) + + // Create smaller preview (thumbnail) + const previewCanvas = document.createElement("canvas") + const previewCtx = previewCanvas.getContext("2d") + + if (previewCtx) { + const previewSize = 150 + const previewRatio = Math.min(previewSize / width, previewSize / height) + previewCanvas.width = width * previewRatio + previewCanvas.height = height * previewRatio + + previewCtx.drawImage(img, 0, 0, previewCanvas.width, previewCanvas.height) + const previewUrl = previewCanvas.toDataURL(file.type, 0.7) + + resolve({ dataUrl, previewUrl }) + } else { + resolve({ dataUrl, previewUrl: dataUrl }) + } + } + + img.onerror = () => { + reject(new Error("Failed to load image")) + } + + img.src = URL.createObjectURL(file) + }) +} + +function fileToDataUrl(file: File): Promise { + return new Promise((resolve, reject) => { + const reader = new FileReader() + + reader.onload = () => { + resolve(reader.result as string) + } + + reader.onerror = () => { + reject(new Error("Failed to read file")) + } + + reader.readAsDataURL(file) + }) +} + +export async function processFileList( + files: FileList, + options?: ProcessFileOptions, +): Promise { + const results: ProcessFileResult[] = [] + + for (const file of files) { + if (file) { + const result = await processFile(file, options) + results.push(result) + } + } + + return results +} + +export function createFileAttachmentBlock(fileAttachment: FileAttachment) { + return { + id: fileAttachment.id, + type: "fileAttachment" as const, + attachment: fileAttachment, + } +} + +// Utility to clean up object URLs to prevent memory leaks +export function cleanupFileAttachment(fileAttachment: FileAttachment) { + if (fileAttachment.previewUrl?.startsWith("blob:")) { + URL.revokeObjectURL(fileAttachment.previewUrl) + } +} + +export async function uploadFileAttachment( + fileAttachment: FileAttachment, + onProgressUpdate?: (attachment: FileAttachment) => void, +): Promise { + try { + // Update status to uploading with 0% progress + let currentAttachment: FileAttachment = { + ...fileAttachment, + uploadStatus: "uploading" as const, + uploadProgress: 0, + } + onProgressUpdate?.(currentAttachment) + + const { dataUrl } = fileAttachment + const blob = await fetch(dataUrl).then((r) => r.blob()) + + // TODO: Replace with real progress tracking when followApi supports it + // Currently followApi.upload.uploadChatAttachment doesn't provide progress callbacks + // Future implementation could use XMLHttpRequest or a custom fetch wrapper + + // Simulate realistic progress updates during upload + // This mimics a realistic upload progression pattern + const progressInterval = setInterval(() => { + if (currentAttachment.uploadProgress! < 85) { + // Start faster, then slow down (realistic network behavior) + const currentProgress = currentAttachment.uploadProgress || 0 + const increment = + currentProgress < 50 + ? Math.random() * 20 + 5 // Fast initial progress + : Math.random() * 8 + 2 // Slower progress as it approaches completion + + currentAttachment = { + ...currentAttachment, + uploadProgress: Math.min(85, currentProgress + increment), + } + onProgressUpdate?.(currentAttachment) + } + }, 150) + + try { + // Actual upload + const response = await followApi.upload.uploadChatAttachment({ file: blob }) + const serverUrl = response.data.url + + // Update to 100% and completed status + const completedAttachment: FileAttachment = { + ...fileAttachment, + serverUrl, + uploadStatus: "completed", + uploadProgress: 100, + errorMessage: undefined, + } + + // Show 100% briefly before final callback + onProgressUpdate?.(completedAttachment) + + return completedAttachment + } finally { + // Clear progress interval + clearInterval(progressInterval) + } + } catch (error) { + // Return attachment with error status + const errorAttachment: FileAttachment = { + ...fileAttachment, + uploadStatus: "error", + uploadProgress: undefined, + errorMessage: error instanceof Error ? error.message : "Upload failed", + } + + return errorAttachment + } +} + +export async function processAndUploadFile( + file: File, + options: ProcessFileOptions = {}, + onProgressUpdate?: (attachment: FileAttachment) => void, +): Promise { + // First process the file locally + const localResult = await processFile(file, options) + + if (!localResult.success || !localResult.fileAttachment) { + return localResult + } + + // Then upload to server + const uploadedAttachment = await uploadFileAttachment( + localResult.fileAttachment, + onProgressUpdate, + ) + + return { + success: uploadedAttachment.uploadStatus === "completed", + fileAttachment: uploadedAttachment, + error: + uploadedAttachment.uploadStatus === "error" ? uploadedAttachment.errorMessage : undefined, + } +} diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/utils/file-validation.ts b/apps/desktop/layer/renderer/src/modules/ai-chat/utils/file-validation.ts new file mode 100644 index 000000000..3eb4372d2 --- /dev/null +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/utils/file-validation.ts @@ -0,0 +1,130 @@ +const MAX_IMAGE_ALLOWED_SIZE = 3 * 1024 * 1024 +const MAX_DOCUMENT_ALLOWED_SIZE = 1 * 1024 * 1024 +export const SUPPORTED_MIME_ACCEPT = "image/*,.pdf,.txt,.md" +export const SUPPORTED_FILE_TYPES = { + // Images + "image/png": { extension: "png", category: "image", maxSize: MAX_IMAGE_ALLOWED_SIZE }, + "image/jpeg": { extension: "jpg", category: "image", maxSize: MAX_IMAGE_ALLOWED_SIZE }, + "image/jpg": { extension: "jpg", category: "image", maxSize: MAX_IMAGE_ALLOWED_SIZE }, + "image/webp": { extension: "webp", category: "image", maxSize: MAX_IMAGE_ALLOWED_SIZE }, + "image/gif": { extension: "gif", category: "image", maxSize: MAX_IMAGE_ALLOWED_SIZE }, + + // Documents + "application/pdf": { extension: "pdf", category: "document", maxSize: MAX_DOCUMENT_ALLOWED_SIZE }, + "text/plain": { extension: "txt", category: "text", maxSize: MAX_DOCUMENT_ALLOWED_SIZE }, + "text/markdown": { extension: "md", category: "text", maxSize: MAX_DOCUMENT_ALLOWED_SIZE }, +} as const + +export type SupportedFileType = keyof typeof SUPPORTED_FILE_TYPES +export type FileCategory = (typeof SUPPORTED_FILE_TYPES)[SupportedFileType]["category"] + +export interface FileValidationError { + type: "unsupported" | "too_large" | "invalid" + message: string +} + +export interface FileValidationResult { + isValid: boolean + error?: FileValidationError + fileInfo?: { + type: SupportedFileType + category: FileCategory + extension: string + maxSize: number + } +} + +export function validateFile(file: File): FileValidationResult { + const fileType = file.type as SupportedFileType + const fileInfo = SUPPORTED_FILE_TYPES[fileType] + + if (!fileInfo) { + return { + isValid: false, + error: { + type: "unsupported", + message: `File type "${file.type}" is not supported. Supported types: images, PDFs, text files.`, + }, + } + } + + if (file.size > fileInfo.maxSize) { + const maxSizeMB = Math.round(fileInfo.maxSize / (1024 * 1024)) + const fileSizeMB = Math.round((file.size / (1024 * 1024)) * 100) / 100 + return { + isValid: false, + error: { + type: "too_large", + message: `File size (${fileSizeMB}MB) exceeds the maximum allowed size of ${maxSizeMB}MB for ${fileInfo.category} files.`, + }, + } + } + + if (file.size === 0) { + return { + isValid: false, + error: { + type: "invalid", + message: "File appears to be empty or corrupted.", + }, + } + } + + return { + isValid: true, + fileInfo: { + type: fileType, + category: fileInfo.category, + extension: fileInfo.extension, + maxSize: fileInfo.maxSize, + }, + } +} + +export function formatFileSize(bytes: number): string { + if (bytes === 0) return "0 Bytes" + + const k = 1024 + const sizes = ["Bytes", "KB", "MB", "GB"] + const i = Math.floor(Math.log(bytes) / Math.log(k)) + + return `${Number.parseFloat((bytes / Math.pow(k, i)).toFixed(1))} ${sizes[i]}` +} + +export function getFileCategoryFromMimeType(mimeType: string): FileCategory { + // Images + if (mimeType.startsWith("image/")) { + return "image" + } + + // Documents + if (mimeType === "application/pdf") { + return "document" + } + + // Text files + if (mimeType.startsWith("text/")) { + return "text" + } + + // Default fallback + return "image" +} + +export function getFileIconName(category: FileCategory): string { + switch (category) { + case "image": { + return "i-mgc-pic-cute-re" + } + case "document": { + return "i-mgc-file-cute-re" + } + case "text": { + return "i-mgc-document-cute-re" + } + + default: { + return "i-mgc-attachment-cute-re" + } + } +} diff --git a/apps/desktop/layer/renderer/src/modules/app-layout/ai/AIChatFixedPanel.tsx b/apps/desktop/layer/renderer/src/modules/app-layout/ai/AIChatFixedPanel.tsx new file mode 100644 index 000000000..dd88ef2f0 --- /dev/null +++ b/apps/desktop/layer/renderer/src/modules/app-layout/ai/AIChatFixedPanel.tsx @@ -0,0 +1,23 @@ +import { cn } from "@follow/utils" +import type { FC } from "react" + +import { Focusable } from "~/components/common/Focusable" +import { HotkeyScope } from "~/constants" +import { ChatHeader } from "~/modules/ai-chat/components/layouts/ChatHeader" +import { ChatInterface } from "~/modules/ai-chat/components/layouts/ChatInterface" + +export interface AIChatFixedPanelProps + extends React.DetailedHTMLProps, HTMLDivElement> {} + +export const AIChatFixedPanel: FC = ({ className, ...props }) => { + return ( + + + + + ) +} diff --git a/apps/desktop/layer/renderer/src/modules/app-layout/ai/AIChatFloatingPanel.tsx b/apps/desktop/layer/renderer/src/modules/app-layout/ai/AIChatFloatingPanel.tsx new file mode 100644 index 000000000..b47e9aefc --- /dev/null +++ b/apps/desktop/layer/renderer/src/modules/app-layout/ai/AIChatFloatingPanel.tsx @@ -0,0 +1,116 @@ +import { Spring } from "@follow/components/constants/spring.js" +import { cn, computeAdjustedTopLeftPosition } from "@follow/utils" +import { AnimatePresence, m } from "motion/react" +import type { ResizeDirection } from "re-resizable" +import { Resizable } from "re-resizable" +import type { FC } from "react" +import { useEffect, useRef } from "react" + +import { + getFloatingPanelState, + setFloatingPanelState, + useAIPanelVisibility, + useFloatingPanelState, +} from "~/atoms/settings/ai" +import { Focusable } from "~/components/common/Focusable" +import { HotkeyScope } from "~/constants" +import { ChatHeader } from "~/modules/ai-chat/components/layouts/ChatHeader" +import { ChatInterface } from "~/modules/ai-chat/components/layouts/ChatInterface" + +export interface AIChatFloatingPanelProps + extends React.DetailedHTMLProps, HTMLDivElement> {} + +const AIChatFloatingPanelInner: FC = ({ className, ...props }) => { + const floatingState = useFloatingPanelState() + + // Preserve right/bottom margins to keep panel anchored to bottom-right on window resize + const rightBottomMarginRef = useRef({ right: 0, bottom: 0 }) + useEffect(() => { + rightBottomMarginRef.current = { + right: Math.max(0, window.innerWidth - (floatingState.x + floatingState.width)), + bottom: Math.max(0, window.innerHeight - (floatingState.y + floatingState.height)), + } + }, [floatingState.x, floatingState.y, floatingState.width, floatingState.height]) + + const handleResize = useRef( + (_event: MouseEvent | TouchEvent, direction: ResizeDirection, ref: HTMLElement) => { + const prev = getFloatingPanelState() + const newWidth = ref.offsetWidth + const newHeight = ref.offsetHeight + const { x, y } = computeAdjustedTopLeftPosition( + { x: prev.x, y: prev.y, width: prev.width, height: prev.height }, + { width: newWidth, height: newHeight }, + direction, + ) + + setFloatingPanelState({ width: newWidth, height: newHeight, x, y }) + }, + ).current + + // Keep floating panel anchored to bottom-right on window resize + useEffect(() => { + const handleWindowResize = () => { + const { right, bottom } = rightBottomMarginRef.current + const newX = Math.max(0, window.innerWidth - floatingState.width - right) + const newY = Math.max(0, window.innerHeight - floatingState.height - bottom) + setFloatingPanelState({ x: newX, y: newY }) + } + + window.addEventListener("resize", handleWindowResize) + return () => window.removeEventListener("resize", handleWindowResize) + }, [floatingState.width, floatingState.height]) + + return ( + +
+ + + + + + +
+
+ ) +} + +export const AIChatFloatingPanel: FC = (props) => { + const visibility = useAIPanelVisibility() + return ( + + {visibility && } + + ) +} diff --git a/apps/desktop/layer/renderer/src/modules/app-layout/ai/AIChatLayout.tsx b/apps/desktop/layer/renderer/src/modules/app-layout/ai/AIChatLayout.tsx index d1cbf1dca..0c3af6174 100644 --- a/apps/desktop/layer/renderer/src/modules/app-layout/ai/AIChatLayout.tsx +++ b/apps/desktop/layer/renderer/src/modules/app-layout/ai/AIChatLayout.tsx @@ -1,21 +1,18 @@ import type { FC } from "react" -import { Focusable } from "~/components/common/Focusable" -import { HotkeyScope } from "~/constants" -import { ChatHeader } from "~/modules/ai-chat/components/layouts/ChatHeader" -import { ChatInterface } from "~/modules/ai-chat/components/layouts/ChatInterface" +import { AIChatPanelStyle, useAIChatPanelStyle } from "~/atoms/settings/ai" -export const AIChatLayout: FC< - React.DetailedHTMLProps, HTMLDivElement> -> = ({ ...props }) => { - return ( - - - - - ) +import { AIChatFixedPanel } from "./AIChatFixedPanel" +import { AIChatFloatingPanel } from "./AIChatFloatingPanel" + +export interface AIChatLayoutProps + extends React.DetailedHTMLProps, HTMLDivElement> {} + +export const AIChatLayout: FC = ({ ...props }) => { + const panelStyle = useAIChatPanelStyle() + + if (panelStyle === AIChatPanelStyle.Floating) { + return + } + return } diff --git a/apps/desktop/layer/renderer/src/modules/app-layout/ai/AISplineButton.tsx b/apps/desktop/layer/renderer/src/modules/app-layout/ai/AISplineButton.tsx new file mode 100644 index 000000000..a66216946 --- /dev/null +++ b/apps/desktop/layer/renderer/src/modules/app-layout/ai/AISplineButton.tsx @@ -0,0 +1,60 @@ +import { Spring } from "@follow/components/constants/spring.js" +import { cn } from "@follow/utils" +import { AnimatePresence, m } from "motion/react" +import type { FC } from "react" + +import { + AIChatPanelStyle, + setAIPanelVisibility, + useAIChatPanelStyle, + useAIPanelVisibility, +} from "~/atoms/settings/ai" +import { AISpline } from "~/modules/ai-chat/components/3d-models/AISpline" + +export interface AISplineButtonProps { + className?: string +} + +export const AISplineButton: FC = ({ className }) => { + const panelStyle = useAIChatPanelStyle() + const isVisible = useAIPanelVisibility() + + // Only show the spline button when: + // 1. Panel style is floating + // 2. Panel is currently not visible + const shouldShow = panelStyle === AIChatPanelStyle.Floating && !isVisible + + const handleClick = () => { + setAIPanelVisibility(true) + } + + return ( + + {shouldShow && ( + + + + )} + + ) +} diff --git a/apps/desktop/layer/renderer/src/modules/app-layout/entry-content/EntryLayoutContent.tsx b/apps/desktop/layer/renderer/src/modules/app-layout/entry-content/EntryLayoutContent.tsx index 624197fe2..4e85d6919 100644 --- a/apps/desktop/layer/renderer/src/modules/app-layout/entry-content/EntryLayoutContent.tsx +++ b/apps/desktop/layer/renderer/src/modules/app-layout/entry-content/EntryLayoutContent.tsx @@ -1,5 +1,6 @@ import { PanelSplitter } from "@follow/components/ui/divider/PanelSplitter.js" import { views } from "@follow/constants" +import { usePrefetchEntryDetail } from "@follow/store/entry/hooks" import { clsx, cn } from "@follow/utils/utils" import { easeOut } from "motion/react" import type { FC, PropsWithChildren } from "react" @@ -7,7 +8,7 @@ import { useMemo } from "react" import { useResizable } from "react-resizable-layout" import { useParams } from "react-router" -import { useAIChatPinned } from "~/atoms/settings/ai" +import { AIChatPanelStyle, useAIChatPanelStyle } from "~/atoms/settings/ai" import { useRealInWideMode } from "~/atoms/settings/ui" import { useTimelineColumnShow, useTimelineColumnTempShow } from "~/atoms/sidebar" import { m } from "~/components/common/Motion" @@ -28,6 +29,7 @@ const EntryLayoutContentLegacy = () => { const settingWideMode = useRealInWideMode() const realEntryId = entryId === ROUTE_ENTRY_PENDING ? "" : entryId + usePrefetchEntryDetail(realEntryId) const showEntryContent = !(views[view]!.wideMode || (settingWideMode && !realEntryId)) const wideMode = !!(settingWideMode && realEntryId) const feedColumnTempShow = useTimelineColumnTempShow() @@ -92,7 +94,7 @@ export const EntryLayoutContentWithAI = () => { export const EntryLayoutContent = () => { const aiEnabled = useFeature("ai") if (aiEnabled) { - return + return null } return } @@ -102,7 +104,8 @@ const Grid = ({ entryId }) => { const wideMode = !!(settingWideMode && entryId) const feedColumnTempShow = useTimelineColumnTempShow() const feedColumnShow = useTimelineColumnShow() - const aiPinned = useAIChatPinned() + const panelStyle = useAIChatPanelStyle() + const aiPinned = panelStyle === AIChatPanelStyle.Fixed const shouldHeaderPaddingLeft = feedColumnTempShow && !feedColumnShow && settingWideMode const { isDragging, position, separatorProps, separatorCursor } = useResizable({ @@ -174,6 +177,6 @@ const EntryGridContainer: FC< ) } else { - return
{children}
+ return
{children}
} } diff --git a/apps/desktop/layer/renderer/src/modules/app-layout/entry-content/index.tsx b/apps/desktop/layer/renderer/src/modules/app-layout/entry-content/index.tsx index bc18a3854..ef640226b 100644 --- a/apps/desktop/layer/renderer/src/modules/app-layout/entry-content/index.tsx +++ b/apps/desktop/layer/renderer/src/modules/app-layout/entry-content/index.tsx @@ -1 +1 @@ -export { EntryLayoutContent as RightContentLayout } from "./EntryLayoutContent" +export { EntryLayoutContent } from "./EntryLayoutContent" diff --git a/apps/desktop/layer/renderer/src/modules/app-layout/subscription-column/MainDestopLayout.tsx b/apps/desktop/layer/renderer/src/modules/app-layout/subscription-column/MainDestopLayout.tsx index 795346e0b..9d661421b 100644 --- a/apps/desktop/layer/renderer/src/modules/app-layout/subscription-column/MainDestopLayout.tsx +++ b/apps/desktop/layer/renderer/src/modules/app-layout/subscription-column/MainDestopLayout.tsx @@ -16,6 +16,7 @@ import { PlainModal } from "~/components/ui/modal/stacked/custom-modal" import { DeclarativeModal } from "~/components/ui/modal/stacked/declarative-modal" import { ROOT_CONTAINER_ID } from "~/constants/dom" import { EnvironmentIndicator } from "~/modules/app/EnvironmentIndicator" +import { AISplineButton } from "~/modules/app-layout/ai/AISplineButton" import { LoginModalContent } from "~/modules/auth/LoginModalContent" import { DebugRegistry } from "~/modules/debug/registry" import { CmdF } from "~/modules/panel/cmdf" @@ -79,7 +80,10 @@ export function MainDestopLayout() { - {ELECTRON && } + {IN_ELECTRON && } + + {/* AI Spline Button - available globally when floating AI chat is closed */} + ) } diff --git a/apps/desktop/layer/renderer/src/modules/app-layout/subscription-column/SubscriptionColumn.tsx b/apps/desktop/layer/renderer/src/modules/app-layout/subscription-column/SubscriptionColumn.tsx index 24a505812..4b20b60ae 100644 --- a/apps/desktop/layer/renderer/src/modules/app-layout/subscription-column/SubscriptionColumn.tsx +++ b/apps/desktop/layer/renderer/src/modules/app-layout/subscription-column/SubscriptionColumn.tsx @@ -22,6 +22,9 @@ import { useTimelineColumnTempShow, } from "~/atoms/sidebar" import { FloatingLayerScope } from "~/constants" +import { useFeature } from "~/hooks/biz/useFeature" +import { useNavigateEntry } from "~/hooks/biz/useNavigateEntry" +import { useRouteParams } from "~/hooks/biz/useRouteParams" import { useBatchUpdateSubscription } from "~/hooks/biz/useSubscriptionActions" import { useI18n } from "~/hooks/common" import { NetworkStatusIndicator } from "~/modules/app/NetworkStatusIndicator" @@ -101,8 +104,12 @@ const FeedResponsiveResizerContainer = ({ }, }) + const aiEnabled = useFeature("ai") const feedColumnShow = useTimelineColumnShow() const feedColumnTempShow = useTimelineColumnTempShow() + const { entryId, isPendingEntry } = useRouteParams() + const navigate = useNavigateEntry() + const t = useI18n() useEffect(() => { if (feedColumnShow) { @@ -165,7 +172,6 @@ const FeedResponsiveResizerContainer = ({ timer = clearTimeout(timer) } }, [feedColumnShow]) - const t = useI18n() return ( <> @@ -185,6 +191,24 @@ const FeedResponsiveResizerContainer = ({ }} > {children} + + {/* Semi-transparent overlay with exit hint when in wide mode with entry selected */} + {entryId && !isPendingEntry && aiEnabled && ( +
navigate({ entryId: null })} + > +
+
+
+ + {t("entry.exit_detail")} +
+ {t("entry.click_to_return")} +
+
+
+ )}
- {/* Enhanced Back Button - positioned on the left */} - - - - {t("words.back", { ns: "common" })} - - + {/* Left: Back button (circular, glass) */} + + + - {/* Enhanced Title - absolutely centered */} -
- {isTitleVisible && title ? ( -
+ {/* Center: Content area block (rounded, glass) */} +
+ {title ? ( +
{title}
) : null}
- {/* Action Area - positioned on the right */} -
- -
+ {/* Right: Button group block (rounded, glass) */} + +
@@ -188,9 +183,65 @@ function SubviewLayoutInner() { ) } -const SubViewHeaderRightView = () => { +const SubViewHeaderRightView = ({ isHeaderElevated }: { isHeaderElevated: boolean }) => { const rightView = useSubViewRightView() - return
{rightView}
+ + if (!rightView) return null + + if (isValidElement(rightView) && (rightView as any).type === HeaderActionGroup) { + const groupChildren = (rightView as any).props?.children + const childrenArray = Array.isArray(groupChildren) ? groupChildren : [groupChildren] + + const items = childrenArray + .map((child: any) => { + if (isValidElement(child) && (child as any).type === HeaderActionButton) { + const { onClick, disabled, loading, icon, children: label } = (child as any).props + const key = (child as any).key ?? icon ?? (typeof label === "string" ? label : undefined) + + return ( + { + if (!disabled && !loading) onClick?.() + }} + className={cn(disabled || loading ? "cursor-not-allowed opacity-50" : "")} + size="md" + theme="auto" + > + + + ) + } + return null + }) + .filter(Boolean) + + return ( +
1 ? "bg-material-ultra-thin" : "bg-material-medium", + )} + > + {items} +
+ ) + } + + return ( +
+
{rightView}
+
+ ) } const ScrollProgressFAB = ({ diff --git a/apps/desktop/layer/renderer/src/modules/app/EnvironmentIndicator.tsx b/apps/desktop/layer/renderer/src/modules/app/EnvironmentIndicator.tsx index 324e38228..c5c4fb9d1 100644 --- a/apps/desktop/layer/renderer/src/modules/app/EnvironmentIndicator.tsx +++ b/apps/desktop/layer/renderer/src/modules/app/EnvironmentIndicator.tsx @@ -1,5 +1,6 @@ /* eslint-disable @eslint-react/dom/no-missing-iframe-sandbox */ import { Button } from "@follow/components/ui/button/index.js" +import { Switch } from "@follow/components/ui/switch/index.jsx" import { Tooltip, TooltipContent, @@ -11,11 +12,74 @@ import { DEV, MODE } from "@follow/shared/constants" import { env } from "@follow/shared/env.desktop" import { useUserRole } from "@follow/store/user/hooks" +import { useDebugFeatureValue, useSetDebugFeatureValue } from "~/atoms/debug-feature" import { PlainModal } from "~/components/ui/modal/stacked/custom-modal" import { useModalStack } from "~/components/ui/modal/stacked/hooks" +import { featureConfigMap } from "~/lib/features" import { DebugRegistry } from "../debug/registry" +const EnvironmentDebugModalContent = () => { + const actionMap = DebugRegistry.getAll() + const debugValues = useDebugFeatureValue() as Record + const setDebugValues = useSetDebugFeatureValue() + + const overrideEnabled = !!debugValues.__override + + const handleToggleOverride = (checked: boolean) => { + setDebugValues((prev) => ({ ...(prev as Record), __override: checked })) + } + + const handleToggleFeature = (key: string, checked: boolean) => { + setDebugValues((prev) => ({ ...(prev as Record), [key]: checked })) + } + + const featureKeys = Object.keys(featureConfigMap) + + return ( +
+
+
+
Debug override features
+ +
+

+ When enabled, the switches below override server feature flags locally. +

+
+
+ {featureKeys.map((key) => ( +
+ {key} + handleToggleFeature(key, v)} + disabled={!overrideEnabled} + /> +
+ ))} +
+
+
+ +
+
Debug actions
+
+ {Object.entries(actionMap).map(([key, action]) => ( +
+ {key} + +
+ ))} +
+
+
+ ) +} + export const EnvironmentIndicator = () => { const role = useUserRole() const { present } = useModalStack() @@ -29,27 +93,9 @@ export const EnvironmentIndicator = () => { onClick={() => { if (!DEV) return - const actionMap = DebugRegistry.getAll() - present({ title: "Debug Actions", - content: () => { - return ( -
- {Object.entries(actionMap).map(([key, action]) => { - return ( -
- {key} - -
- ) - })} -
- ) - }, + content: EnvironmentDebugModalContent, }) }} > diff --git a/apps/desktop/layer/renderer/src/modules/command/commands/global.tsx b/apps/desktop/layer/renderer/src/modules/command/commands/global.tsx index b046c1f43..fe9da0826 100644 --- a/apps/desktop/layer/renderer/src/modules/command/commands/global.tsx +++ b/apps/desktop/layer/renderer/src/modules/command/commands/global.tsx @@ -12,7 +12,6 @@ declare module "@follow/utils/event-bus" { "global:toggle-corner-play": void "global:quick-add": void "global:toggle-ai-chat": void - "global:toggle-ai-chat-pinned": void } } @@ -72,18 +71,6 @@ export const useRegisterGlobalCommands = () => { icon: aiIcon, category, }, - { - id: COMMAND_ID.global.toggleAIChatPinned, - label: { - title: t("command.global.toggle_ai_chat_pinned.title"), - description: t("command.global.toggle_ai_chat_pinned.description"), - }, - run: () => { - EventBus.dispatch(COMMAND_ID.global.toggleAIChatPinned) - }, - icon: aiIcon, - category, - }, ]) } @@ -107,14 +94,8 @@ export type ToggleAIChatCommand = Command<{ fn: (ctx?: { entryId?: string }) => void }> -export type ToggleAIChatPinnedCommand = Command<{ - id: typeof COMMAND_ID.global.toggleAIChatPinned - fn: (ctx?: { entryId?: string }) => void -}> - export type GlobalCommand = | ShowShortcutsCommand | ToggleCornerPlayCommand | QuickAddCommand | ToggleAIChatCommand - | ToggleAIChatPinnedCommand diff --git a/apps/desktop/layer/renderer/src/modules/command/commands/id.ts b/apps/desktop/layer/renderer/src/modules/command/commands/id.ts index 853dc78c9..e1b03ccc6 100644 --- a/apps/desktop/layer/renderer/src/modules/command/commands/id.ts +++ b/apps/desktop/layer/renderer/src/modules/command/commands/id.ts @@ -50,7 +50,6 @@ export const COMMAND_ID = { toggleCornerPlay: "global:toggle-corner-play", quickAdd: "global:quick-add", toggleAIChat: "global:toggle-ai-chat", - toggleAIChatPinned: "global:toggle-ai-chat-pinned", }, layout: { toggleSubscriptionColumn: "layout:toggle-subscription-column", diff --git a/apps/desktop/layer/renderer/src/modules/command/hooks/use-command-binding.ts b/apps/desktop/layer/renderer/src/modules/command/hooks/use-command-binding.ts index 0fffde66b..f26dfc415 100644 --- a/apps/desktop/layer/renderer/src/modules/command/hooks/use-command-binding.ts +++ b/apps/desktop/layer/renderer/src/modules/command/hooks/use-command-binding.ts @@ -53,7 +53,6 @@ export const defaultCommandShortcuts = { [COMMAND_ID.global.quickAdd]: transformShortcut("$mod+N"), [COMMAND_ID.global.showShortcuts]: "?", [COMMAND_ID.global.toggleAIChat]: transformShortcut("$mod+I"), - [COMMAND_ID.global.toggleAIChatPinned]: transformShortcut("$mod+Shift+L"), } as const const overrideCommandShortcutsAtom = atomWithStorage< diff --git a/apps/desktop/layer/renderer/src/modules/customize-toolbar/constant.ts b/apps/desktop/layer/renderer/src/modules/customize-toolbar/constant.ts index 7e06fdab8..1a1ae4c7a 100644 --- a/apps/desktop/layer/renderer/src/modules/customize-toolbar/constant.ts +++ b/apps/desktop/layer/renderer/src/modules/customize-toolbar/constant.ts @@ -19,7 +19,6 @@ const MAIN_ACTIONS = [ COMMAND_ID.entry.toggleAISummary, COMMAND_ID.entry.readability, - COMMAND_ID.global.toggleAIChatPinned, COMMAND_ID.entry.viewSourceContent, COMMAND_ID.entry.share, diff --git a/apps/desktop/layer/renderer/src/modules/customize-toolbar/dnd.tsx b/apps/desktop/layer/renderer/src/modules/customize-toolbar/dnd.tsx index 41b9336e9..e89f3f3de 100644 --- a/apps/desktop/layer/renderer/src/modules/customize-toolbar/dnd.tsx +++ b/apps/desktop/layer/renderer/src/modules/customize-toolbar/dnd.tsx @@ -62,7 +62,7 @@ const warningActionButton: Partial< show: !IN_ELECTRON, info: "entry_actions.warn_info_for_desktop", }, - [COMMAND_ID.global.toggleAIChatPinned]: { + [COMMAND_ID.global.toggleAIChat]: { show: true, info: "entry_actions.warn_info_ai_chat_pinned_tip", }, diff --git a/apps/desktop/layer/renderer/src/modules/discover/DiscoverImport.tsx b/apps/desktop/layer/renderer/src/modules/discover/DiscoverImport.tsx index 479f7af13..010e18b88 100644 --- a/apps/desktop/layer/renderer/src/modules/discover/DiscoverImport.tsx +++ b/apps/desktop/layer/renderer/src/modules/discover/DiscoverImport.tsx @@ -6,14 +6,7 @@ import { } from "@follow/components/ui/accordion/index.js" import { Button } from "@follow/components/ui/button/index.js" import { DropZone } from "@follow/components/ui/drop-zone/index.js" -import { - Form, - FormControl, - FormField, - FormItem, - FormMessage, -} from "@follow/components/ui/form/index.jsx" -import { Input } from "@follow/components/ui/input/index.js" +import { Form, FormControl, FormField, FormItem } from "@follow/components/ui/form/index.jsx" import type { BizRespose } from "@follow/models" import { zodResolver } from "@hookform/resolvers/zod" import { useMutation } from "@tanstack/react-query" @@ -169,10 +162,14 @@ export function DiscoverImport() { ( + render={({ field: { value, onChange } }) => ( - onChange(fileList[0])}> + onChange(fileList[0])} + > {form.formState.dirtyFields.file ? ( @@ -188,15 +185,6 @@ export function DiscoverImport() { )} - onChange(event.target.files && event.target.files[0])} - /> - )} /> diff --git a/apps/desktop/layer/renderer/src/modules/entry-column/AIEntryLayout.tsx b/apps/desktop/layer/renderer/src/modules/entry-column/AIEntryLayout.tsx index 276df7b9a..6df558d37 100644 --- a/apps/desktop/layer/renderer/src/modules/entry-column/AIEntryLayout.tsx +++ b/apps/desktop/layer/renderer/src/modules/entry-column/AIEntryLayout.tsx @@ -1,13 +1,16 @@ +import { Spring } from "@follow/components/constants/spring.js" import { Button } from "@follow/components/ui/button/index.js" import { PanelSplitter } from "@follow/components/ui/divider/index.js" import { defaultUISettings } from "@follow/shared/settings/defaults" import { cn } from "@follow/utils" -import { AnimatePresence, m } from "motion/react" +import { AnimatePresence } from "motion/react" import { useCallback, useEffect, useMemo, useRef, useState } from "react" import { useResizable } from "react-resizable-layout" import { useParams } from "react-router" +import { AIChatPanelStyle, useAIChatPanelStyle } from "~/atoms/settings/ai" import { getUISettings, setUISetting } from "~/atoms/settings/ui" +import { m } from "~/components/common/Motion" import { ROUTE_ENTRY_PENDING } from "~/constants" import { useNavigateEntry } from "~/hooks/biz/useNavigateEntry" import { AIChatLayout } from "~/modules/app-layout/ai/AIChatLayout" @@ -20,6 +23,7 @@ import { EntryColumn } from "./index" const AIEntryLayoutImpl = () => { const { entryId } = useParams() const navigate = useNavigateEntry() + const panelStyle = useAIChatPanelStyle() const realEntryId = entryId === ROUTE_ENTRY_PENDING ? "" : entryId @@ -129,7 +133,7 @@ const AIEntryLayoutImpl = () => { return (
-
+
{/* Entry list - always rendered to prevent animation */} @@ -139,17 +143,13 @@ const AIEntryLayoutImpl = () => { {realEntryId && ( {/* Scroll hint indicator */} @@ -158,7 +158,7 @@ const AIEntryLayoutImpl = () => { variant="ghost" size="sm" onClick={() => navigate({ entryId: null })} - buttonClassName="transform cursor-pointer select-none" + buttonClassName="transform cursor-pointer select-none no-drag-region" aria-label="Scroll up or click to exit" >
@@ -179,20 +179,29 @@ const AIEntryLayoutImpl = () => {
- { - setUISetting("aiColWidth", defaultUISettings.aiColWidth) - setPosition(defaultUISettings.aiColWidth) - }} - /> - + + {/* Fixed panel layout */} + {panelStyle === AIChatPanelStyle.Fixed && ( + <> + { + setUISetting("aiColWidth", defaultUISettings.aiColWidth) + setPosition(defaultUISettings.aiColWidth) + }} + /> + + + )} + + {/* Floating panel - renders outside layout flow */} + {panelStyle === AIChatPanelStyle.Floating && }
) } diff --git a/apps/desktop/layer/renderer/src/modules/entry-column/EntryColumnShortcutHandler.tsx b/apps/desktop/layer/renderer/src/modules/entry-column/EntryColumnShortcutHandler.tsx index fe4eaa10f..623220367 100644 --- a/apps/desktop/layer/renderer/src/modules/entry-column/EntryColumnShortcutHandler.tsx +++ b/apps/desktop/layer/renderer/src/modules/entry-column/EntryColumnShortcutHandler.tsx @@ -27,6 +27,9 @@ export const EntryColumnShortcutHandler: FC<{ const when = useGlobalFocusableScopeSelector(FocusablePresets.isTimeline) + const currentEntryIdRef = useRefValue(useRouteEntryId()) + const navigate = useNavigateEntry() + useCommandBinding({ commandId: COMMAND_ID.timeline.switchToNext, when, @@ -54,9 +57,6 @@ export const EntryColumnShortcutHandler: FC<{ when, }) - const currentEntryIdRef = useRefValue(useRouteEntryId()) - const navigate = useNavigateEntry() - useEffect(() => { return EventBus.subscribe(COMMAND_ID.timeline.switchToNext, () => { const data = dataRef.current diff --git a/apps/desktop/layer/renderer/src/modules/entry-column/Items/picture-masonry.tsx b/apps/desktop/layer/renderer/src/modules/entry-column/Items/picture-masonry.tsx index d54148352..cf72e2b8e 100644 --- a/apps/desktop/layer/renderer/src/modules/entry-column/Items/picture-masonry.tsx +++ b/apps/desktop/layer/renderer/src/modules/entry-column/Items/picture-masonry.tsx @@ -1,4 +1,3 @@ -import { useMobile } from "@follow/components/hooks/useMobile.js" import { MasonryIntersectionContext, MasonryItemsAspectRatioContext, @@ -35,7 +34,6 @@ import { MediaContainerWidthProvider } from "~/components/ui/media/MediaContaine import type { StoreImageType } from "~/store/image" import { imageActions } from "~/store/image" -import { getMasonryColumnValue, setMasonryColumnValue, useMasonryColumnValue } from "../atoms" import { batchMarkRead } from "../hooks/useEntryMarkReadHandler" import { PictureWaterFallItem } from "./picture-item" @@ -48,7 +46,6 @@ const gutter = 24 export const PictureMasonry: FC = (props) => { const { data } = props - const isMobile = useMobile() const cacheMap = useState(() => new Map())[0] const [isInitDim, setIsInitDim] = useState(false) const [isInitLayout, setIsInitLayout] = useState(false) @@ -95,22 +92,9 @@ export const PictureMasonry: FC = (props) => { } }, [JSON.stringify(data)]) - const customizeColumn = useMasonryColumnValue() - const { containerRef, currentColumn, currentItemWidth, calcItemWidth } = useMasonryColumn( - gutter, - (column) => { - setIsInitLayout(true) - if (getMasonryColumnValue() === -1) { - setMasonryColumnValue(column) - } - }, - ) - - const finalColumn = customizeColumn !== -1 && !isMobile ? customizeColumn : currentColumn - const finalItemWidth = useMemo( - () => (customizeColumn !== -1 ? calcItemWidth(finalColumn) : currentItemWidth), - [calcItemWidth, currentItemWidth, customizeColumn, finalColumn], - ) + const { containerRef, currentColumn, currentItemWidth } = useMasonryColumn(gutter, () => { + setIsInitLayout(true) + }) const items = useMemo(() => { const result = data.map((entryId) => { @@ -240,18 +224,18 @@ export const PictureMasonry: FC = (props) => { return (
{isInitDim && deferIsInitLayout && ( - + {/* eslint-disable-next-line @eslint-react/no-context-provider */} - + - {ready && ( - - )} + + {ready && ( + + )} +
))} diff --git a/apps/desktop/layer/renderer/src/modules/entry-column/item.tsx b/apps/desktop/layer/renderer/src/modules/entry-column/item.tsx index 8c45f2359..649053ac5 100644 --- a/apps/desktop/layer/renderer/src/modules/entry-column/item.tsx +++ b/apps/desktop/layer/renderer/src/modules/entry-column/item.tsx @@ -1,5 +1,5 @@ import { FeedViewType } from "@follow/constants" -import { useEntry } from "@follow/store/entry/hooks" +import { useHasEntry } from "@follow/store/entry/hooks" import { useEntryTranslation, usePrefetchEntryTranslation } from "@follow/store/translation/hooks" import type { FC } from "react" import { memo } from "react" @@ -47,9 +47,9 @@ const EntryItemImpl = memo(function EntryItemImpl({ }) export const EntryItem: FC = memo(({ entryId, view }) => { - const entry = useEntry(entryId, () => ({})) + const hasEntry = useHasEntry(entryId) - if (!entry) return null + if (!hasEntry) return null return }) @@ -63,9 +63,9 @@ export const EntryVirtualListItem = ({ React.DetailedHTMLProps, HTMLDivElement> & { ref?: React.Ref }) => { - const entry = useEntry(entryId, () => ({})) + const hasEntry = useHasEntry(entryId) - if (!entry) return
+ if (!hasEntry) return
return (
diff --git a/apps/desktop/layer/renderer/src/modules/entry-column/layouts/EntryItemWrapper.tsx b/apps/desktop/layer/renderer/src/modules/entry-column/layouts/EntryItemWrapper.tsx index 85de56387..9ca779dc3 100644 --- a/apps/desktop/layer/renderer/src/modules/entry-column/layouts/EntryItemWrapper.tsx +++ b/apps/desktop/layer/renderer/src/modules/entry-column/layouts/EntryItemWrapper.tsx @@ -6,7 +6,7 @@ import { useEntry } from "@follow/store/entry/hooks" import { unreadSyncService } from "@follow/store/unread/store" import { cn } from "@follow/utils/utils" import { AnimatePresence, m } from "motion/react" -import type { FC, MouseEvent, MouseEventHandler, PropsWithChildren, TouchEvent } from "react" +import type { FC, MouseEvent, PropsWithChildren, TouchEvent } from "react" import { useCallback, useEffect, useMemo, useState } from "react" import { useTranslation } from "react-i18next" import { NavLink } from "react-router" @@ -146,10 +146,6 @@ export const EntryItemWrapper: FC< }, [asRead, entry?.id, entry?.feedId, navigate], ) - const handleDoubleClick: MouseEventHandler = useCallback( - () => entry?.url && window.open(entry.url, "_blank"), - [entry?.url], - ) const [isContextMenuOpen, setIsContextMenuOpen] = useState(false) const showContextMenu = useShowContextMenu() @@ -224,7 +220,6 @@ export const EntryItemWrapper: FC< onClick={handleClick} onMouseEnter={handleMouseEnter} onMouseLeave={handleMouseLeave} - onDoubleClick={handleDoubleClick} {...contextMenuProps} {...(!isMobile ? { onTouchStart: handleClick } : {})} > diff --git a/apps/desktop/layer/renderer/src/modules/entry-column/layouts/EntryListHeader.tsx b/apps/desktop/layer/renderer/src/modules/entry-column/layouts/EntryListHeader.tsx index 518887a04..85151f15f 100644 --- a/apps/desktop/layer/renderer/src/modules/entry-column/layouts/EntryListHeader.tsx +++ b/apps/desktop/layer/renderer/src/modules/entry-column/layouts/EntryListHeader.tsx @@ -17,6 +17,7 @@ import { previewBackPath } from "~/atoms/preview" import { useGeneralSettingKey } from "~/atoms/settings/general" import { useTimelineColumnShow } from "~/atoms/sidebar" import { ROUTE_ENTRY_PENDING } from "~/constants" +import { useFeature } from "~/hooks/biz/useFeature" import { useFollow } from "~/hooks/biz/useFollow" import { getRouteParams, useRouteParams } from "~/hooks/biz/useRouteParams" import { COMMAND_ID } from "~/modules/command/commands/id" @@ -66,6 +67,8 @@ export const EntryListHeader: FC<{ const feedColumnShow = useTimelineColumnShow() const commandShortcuts = useCommandShortcuts() const runCmdFn = useRunCommandFn() + + const aiEnabled = useFeature("ai") return (
- {views[view]!.wideMode && entryId && entryId !== ROUTE_ENTRY_PENDING && ( + {views[view]!.wideMode && entryId && entryId !== ROUTE_ENTRY_PENDING && !aiEnabled && ( <> - + )} - {!views[view]!.wideMode && } + {!views[view]!.wideMode && !aiEnabled && } {view === FeedViewType.SocialMedia && } {view === FeedViewType.Pictures && } diff --git a/apps/desktop/layer/renderer/src/modules/entry-column/layouts/buttons/SwitchToMasonryButton.tsx b/apps/desktop/layer/renderer/src/modules/entry-column/layouts/buttons/SwitchToMasonryButton.tsx index 4366f6e36..b568e0f88 100644 --- a/apps/desktop/layer/renderer/src/modules/entry-column/layouts/buttons/SwitchToMasonryButton.tsx +++ b/apps/desktop/layer/renderer/src/modules/entry-column/layouts/buttons/SwitchToMasonryButton.tsx @@ -2,7 +2,6 @@ import { useMobile } from "@follow/components/hooks/useMobile.js" import { AutoResizeHeight } from "@follow/components/ui/auto-resize-height/index.js" import { ActionButton } from "@follow/components/ui/button/index.js" import { SegmentGroup, SegmentItem } from "@follow/components/ui/segment/index.js" -import { Slider } from "@follow/components/ui/slider/index.js" import { clsx, cn } from "@follow/utils/utils" import { HoverCard, @@ -10,29 +9,20 @@ import { HoverCardPortal, HoverCardTrigger, } from "@radix-ui/react-hover-card" -import { debounce } from "es-toolkit/compat" -import * as React from "react" import { useTranslation } from "react-i18next" import { setUISetting, useUISettingKey } from "~/atoms/settings/ui" -import { setMasonryColumnValue, useMasonryColumnValue } from "../../atoms" - export const SwitchToMasonryButton = () => { const isMasonry = useUISettingKey("pictureViewMasonry") const { t } = useTranslation() const isMobile = useMobile() - const masonryColumnValue = useMasonryColumnValue() if (isMobile) return null return ( - + - { - setUISetting("pictureViewMasonry", !isMasonry) - }} - > + @@ -85,24 +75,6 @@ export const SwitchToMasonryButton = () => { />
- - {isMasonry && ( -
- - { - setMasonryColumnValue(value[0]!) - }, 300)} - /> -
- )}
diff --git a/apps/desktop/layer/renderer/src/modules/entry-column/templates/grid-item-template.tsx b/apps/desktop/layer/renderer/src/modules/entry-column/templates/grid-item-template.tsx index 3d41c89f1..50426dd73 100644 --- a/apps/desktop/layer/renderer/src/modules/entry-column/templates/grid-item-template.tsx +++ b/apps/desktop/layer/renderer/src/modules/entry-column/templates/grid-item-template.tsx @@ -1,6 +1,6 @@ import { TitleMarquee } from "@follow/components/ui/marquee/index.jsx" import { useIsEntryStarred } from "@follow/store/collection/hooks" -import { useEntry } from "@follow/store/entry/hooks" +import { useEntry, useHasEntry } from "@follow/store/entry/hooks" import { useFeedById } from "@follow/store/feed/hooks" import { cn } from "@follow/utils/utils" import dayjs from "dayjs" @@ -21,9 +21,9 @@ interface GridItemProps extends UniversalItemProps { } export function GridItem(props: GridItemProps) { const { entryId, entryPreview, wrapperClassName, children, translation } = props - const entry = useEntry(entryId, () => ({})) + const hasEntry = useHasEntry(entryId) - if (!entry) return null + if (!hasEntry) return null return (
{children} diff --git a/apps/desktop/layer/renderer/src/modules/entry-content/components/EntryTimelineSidebar.tsx b/apps/desktop/layer/renderer/src/modules/entry-content/components/EntryTimelineSidebar.tsx index 0b320c8f8..684f088b0 100644 --- a/apps/desktop/layer/renderer/src/modules/entry-content/components/EntryTimelineSidebar.tsx +++ b/apps/desktop/layer/renderer/src/modules/entry-content/components/EntryTimelineSidebar.tsx @@ -17,15 +17,18 @@ export const EntryTimelineSidebar = ({ entryId }: { entryId: string }) => { return null } - return + return } -const Timeline = ({ entryId }: { entryId: string }) => { +export const EntryTimeline = ({ entryId, className }: { entryId: string; className?: string }) => { const entryIds = useGetEntryIdInRange(entryId, [5, 5]) return ( diff --git a/apps/desktop/layer/renderer/src/modules/entry-content/components/EntryTitle.tsx b/apps/desktop/layer/renderer/src/modules/entry-content/components/EntryTitle.tsx index 26200ce19..f165eed76 100644 --- a/apps/desktop/layer/renderer/src/modules/entry-content/components/EntryTitle.tsx +++ b/apps/desktop/layer/renderer/src/modules/entry-content/components/EntryTitle.tsx @@ -5,6 +5,7 @@ import { useEntryTranslation } from "@follow/store/translation/hooks" import { useWhoami } from "@follow/store/user/hooks" import { formatEstimatedMins, formatTimeToSeconds } from "@follow/utils" import { titleCase } from "title-case" +import { useShallow } from "zustand/shallow" import { useShowAITranslation } from "~/atoms/ai-translation" import { useActionLanguage } from "~/atoms/settings/general" @@ -25,33 +26,37 @@ interface EntryLinkProps { export const EntryTitle = ({ entryId, compact }: EntryLinkProps) => { const user = useWhoami() - const entry = useEntry(entryId, (state) => { - const { feedId, inboxHandle } = state - const { author, authorAvatar, authorUrl, publishedAt, title } = state + const entry = useEntry( + entryId, + useShallow((state) => { + const { feedId, inboxHandle } = state + const { author, authorAvatar, authorUrl, publishedAt, title } = state - const attachments = state.attachments || [] - const { duration_in_seconds } = - attachments?.find((attachment) => attachment.duration_in_seconds) ?? {} - const seconds = duration_in_seconds ? formatTimeToSeconds(duration_in_seconds) : undefined - const estimatedMins = seconds ? formatEstimatedMins(Math.floor(seconds / 60)) : undefined + const attachments = state.attachments || [] + const { duration_in_seconds } = + attachments?.find((attachment) => attachment.duration_in_seconds) ?? {} + const seconds = duration_in_seconds ? formatTimeToSeconds(duration_in_seconds) : undefined + const estimatedMins = seconds ? formatEstimatedMins(Math.floor(seconds / 60)) : undefined - const media = state.media || [] - const firstPhoto = media.find((a) => a.type === "photo") - const firstPhotoUrl = firstPhoto?.url - const iconEntry: FeedIconEntry = { firstPhotoUrl, authorAvatar } - const titleEntry = { authorUrl } + const media = state.media || [] + const firstPhoto = media.find((a) => a.type === "photo") + const firstPhotoUrl = firstPhoto?.url + const iconEntry: FeedIconEntry = { firstPhotoUrl, authorAvatar } + const titleEntry = { authorUrl } - return { - author, - estimatedMins, - feedId, - iconEntry, - inboxId: inboxHandle, - publishedAt, - title, - titleEntry, - } - }) + return { + author, + authorUrl, + estimatedMins, + feedId, + iconEntry, + inboxId: inboxHandle, + publishedAt, + title, + titleEntry, + } + }), + ) const feed = useFeedById(entry?.feedId) const inbox = useInboxById(entry?.inboxId) @@ -89,22 +94,20 @@ export const EntryTitle = ({ entryId, compact }: EntryLinkProps) => { ) : (
-
- - - -
+ + + {/* Meta Information with improved layout */}
@@ -120,6 +123,25 @@ export const EntryTitle = ({ entryId, compact }: EntryLinkProps) => { {getPreferredTitle(feed || inbox, entry.titleEntry)}
+ + {entry.author && ( +
+ + {entry.authorUrl ? ( + + {entry.author} + + ) : ( + {entry.author} + )} +
+ )} +
diff --git a/apps/desktop/layer/renderer/src/modules/entry-content/components/entry-content/EntryContent.ai.tsx b/apps/desktop/layer/renderer/src/modules/entry-content/components/entry-content/EntryContent.ai.tsx index c4a98afff..a49d8e9af 100644 --- a/apps/desktop/layer/renderer/src/modules/entry-content/components/entry-content/EntryContent.ai.tsx +++ b/apps/desktop/layer/renderer/src/modules/entry-content/components/entry-content/EntryContent.ai.tsx @@ -9,17 +9,18 @@ import { useEntry } from "@follow/store/entry/hooks" import { useFeedById } from "@follow/store/feed/hooks" import { useIsInbox } from "@follow/store/inbox/hooks" import { thenable } from "@follow/utils" -import { nextFrame, stopPropagation } from "@follow/utils/dom" +import { stopPropagation } from "@follow/utils/dom" import { EventBus } from "@follow/utils/event-bus" -import { clsx, cn } from "@follow/utils/utils" -import type { JSAnimation, Variants } from "motion/react" -import { m, useAnimationControls } from "motion/react" +import { cn } from "@follow/utils/utils" +import type { JSAnimation } from "motion/react" +import { useAnimationControls } from "motion/react" import * as React from "react" import { memo, useEffect, useRef, useState } from "react" import { useEntryIsInReadability } from "~/atoms/readability" import { useIsZenMode } from "~/atoms/settings/ui" import { Focusable } from "~/components/common/Focusable" +import { m } from "~/components/common/Motion" import { useInPeekModal } from "~/components/ui/modal/inspire/InPeekModal" import { HotkeyScope } from "~/constants" import { useRouteParamsSelector } from "~/hooks/biz/useRouteParams" @@ -30,8 +31,7 @@ import { COMMAND_ID } from "~/modules/command/commands/id" import { ApplyEntryActions } from "../../ApplyEntryActions" import { useEntryContent } from "../../hooks" -import { EntryHeader } from "../entry-header" -import { EntryTimelineSidebar } from "../EntryTimelineSidebar" +import { AIEntryHeader } from "../entry-header" import { getEntryContentLayout } from "../layouts" import { SourceContentPanel } from "../SourceContentView" import { EntryCommandShortcutRegister } from "./EntryCommandShortcutRegister" @@ -40,12 +40,11 @@ import { EntryNoContent } from "./EntryNoContent" import { EntryScrollingAndNavigationHandler } from "./EntryScrollingAndNavigationHandler.js" import type { EntryContentProps } from "./types" -const pageMotionVariants = { - initial: { opacity: 0, y: 25 }, +const contentVariants = { + initial: { opacity: 0, y: 30 }, animate: { opacity: 1, y: 0 }, - exit: { opacity: 0, y: 25, transition: { duration: 0 } }, -} satisfies Variants - + exit: { opacity: 0, y: 30 }, +} const EntryContentImpl: Component = ({ entryId, noMedia, @@ -73,26 +72,11 @@ const EntryContentImpl: Component = ({ const scrollerRef = useRef(null) const safeUrl = useFeedSafeUrl(entryId) - const isInPeekModal = useInPeekModal() const isZenMode = useIsZenMode() const [panelPortalElement, setPanelPortalElement] = useState(null) - const animationController = useAnimationControls() - const prevEntryId = useRef(undefined) const scrollAnimationRef = useRef | null>(null) - useEffect(() => { - if (prevEntryId.current !== entryId) { - scrollAnimationRef.current?.stop() - nextFrame(() => { - scrollerRef.current?.scrollTo({ top: 0 }) - }) - animationController.start(pageMotionVariants.exit).then(() => { - animationController.start(pageMotionVariants.animate) - }) - prevEntryId.current = entryId - } - }, [animationController, entryId]) const isInHasTimelineView = ![ FeedViewType.Pictures, @@ -111,21 +95,30 @@ const EntryContentImpl: Component = ({ removeBlock(BlockSliceAction.SPECIAL_TYPES.mainEntry) } }, [addOrUpdateBlock, entryId, removeBlock]) + const animationController = useAnimationControls() + + const focusableRef = useRef(null) + useEffect(() => { + animationController.set(contentVariants.exit) + animationController.start(contentVariants.animate) + focusableRef.current?.focus() + return () => { + animationController.stop() + } + }, [animationController, entryId]) return (
- {!isInPeekModal && ( - - )} +
@@ -135,49 +128,46 @@ const EntryContentImpl: Component = ({ scrollerRef={scrollerRef} /> - + {/* */} {/* Indicator for the entry */} + {!isZenMode && isInHasTimelineView && ( + <> +
+ { + EventBus.dispatch(COMMAND_ID.timeline.switchToPrevious) + }} + > + + +
+ +
+ { + EventBus.dispatch(COMMAND_ID.timeline.switchToNext) + }} + > + + +
+ + )} - {!isZenMode && isInHasTimelineView && !isInPeekModal && ( - <> -
- { - EventBus.dispatch(COMMAND_ID.timeline.switchToPrevious) - }} - > - - -
- -
- { - EventBus.dispatch(COMMAND_ID.timeline.switchToNext) - }} - > - - -
- - )} -
@@ -231,10 +221,9 @@ const EntryScrollArea: Component<{ = ({ {!isInPeekModal && ( @@ -254,7 +253,9 @@ const EntryScrollArea: Component<{ (null) const contentAccessories = useMemo( - () => (isInPeekModal ? undefined : ), + () => (isInPeekModal ? undefined : ), [isInPeekModal], ) diff --git a/apps/desktop/layer/renderer/src/modules/entry-content/components/entry-content/EntryScrollingAndNavigationHandler.tsx b/apps/desktop/layer/renderer/src/modules/entry-content/components/entry-content/EntryScrollingAndNavigationHandler.tsx index a1bec41f9..e8572150a 100644 --- a/apps/desktop/layer/renderer/src/modules/entry-content/components/entry-content/EntryScrollingAndNavigationHandler.tsx +++ b/apps/desktop/layer/renderer/src/modules/entry-content/components/entry-content/EntryScrollingAndNavigationHandler.tsx @@ -2,19 +2,20 @@ import { useFocusActions, useGlobalFocusableScopeSelector, } from "@follow/components/common/Focusable/index.js" +import { Spring } from "@follow/components/constants/spring.js" import { useSmoothScroll } from "@follow/hooks" import { nextFrame } from "@follow/utils/dom" import { EventBus } from "@follow/utils/event-bus" -import { cn, combineCleanupFunctions } from "@follow/utils/utils" +import { clsx, combineCleanupFunctions } from "@follow/utils/utils" import type { JSAnimation } from "motion/react" import { AnimatePresence, m } from "motion/react" import * as React from "react" import { useEffect, useRef, useState } from "react" +import { useEventCallback } from "usehooks-ts" import { FocusablePresets } from "~/components/common/Focusable" import { COMMAND_ID } from "~/modules/command/commands/id" import { useCommandBinding } from "~/modules/command/hooks/use-command-binding" -import { useCommandHotkey } from "~/modules/command/hooks/use-register-hotkey" export const EntryScrollingAndNavigationHandler = ({ scrollerRef, @@ -48,24 +49,23 @@ export const EntryScrollingAndNavigationHandler = ({ when, }) - useCommandHotkey({ - commandId: COMMAND_ID.layout.focusToTimeline, - when, - shortcut: "Backspace, Escape", - }) - const { highlightBoundary } = useFocusActions() const smoothScrollTo = useSmoothScroll() + const navigateToNext = useEventCallback(() => { + EventBus.dispatch(COMMAND_ID.timeline.switchToNext) + setShowKeepScrollingPanel(false) + isAlreadyScrolledBottomRef.current = false + if (scrollerRef.current) { + smoothScrollTo(0, scrollerRef.current) + } + }) useEffect(() => { const checkScrollBottom = ($scroller: HTMLDivElement) => { const currentScroll = $scroller.scrollTop const { scrollHeight, clientHeight } = $scroller if (isAlreadyScrolledBottomRef.current) { - EventBus.dispatch(COMMAND_ID.timeline.switchToNext) - setShowKeepScrollingPanel(false) - isAlreadyScrolledBottomRef.current = false - smoothScrollTo(0, $scroller) + navigateToNext() return } @@ -140,42 +140,38 @@ export const EntryScrollingAndNavigationHandler = ({ }, ), ) - }, [highlightBoundary, scrollAnimationRef, scrollerRef, smoothScrollTo]) + }, [highlightBoundary, navigateToNext, scrollAnimationRef, scrollerRef, smoothScrollTo]) return ( {showKeepScrollingPanel && ( - - Already scrolled to the bottom. -
- Keep pressing to jump to the next article -
+ + + )}
) } - -const FloatPanel: React.FC<{ children: React.ReactNode; side: "bottom" | "top" }> = ({ - children, - side, -}) => ( - - {children} - -) diff --git a/apps/desktop/layer/renderer/src/modules/entry-content/components/entry-content/accessories/ContainerToc.tsx b/apps/desktop/layer/renderer/src/modules/entry-content/components/entry-content/accessories/ContainerToc.tsx index 640e33103..0974f46b7 100644 --- a/apps/desktop/layer/renderer/src/modules/entry-content/components/entry-content/accessories/ContainerToc.tsx +++ b/apps/desktop/layer/renderer/src/modules/entry-content/components/entry-content/accessories/ContainerToc.tsx @@ -3,13 +3,12 @@ import { CircleProgress } from "@follow/components/icons/Progress.js" import { MotionButtonBase } from "@follow/components/ui/button/index.js" import { RootPortal } from "@follow/components/ui/portal/index.jsx" import { useScrollViewElement } from "@follow/components/ui/scroll-area/hooks.js" -import { EventBus } from "@follow/utils/event-bus" import { springScrollTo } from "@follow/utils/scroller" import { cn } from "@follow/utils/utils" import { useStore } from "jotai" import { memo, useEffect, useMemo, useState } from "react" -import { useAIChatPinned } from "~/atoms/settings/ai" +import { AIChatPanelStyle, setAIPanelVisibility, useAIChatPanelStyle } from "~/atoms/settings/ai" import type { TocRef } from "~/components/ui/markdown/components/Toc" import { Toc } from "~/components/ui/markdown/components/Toc" import { useFeature } from "~/hooks/biz/useFeature" @@ -51,7 +50,8 @@ const BackTopIndicator: Component = memo(({ className }) => { const scrollElement = useScrollViewElement() const aiEnabled = useFeature("ai") - const isAiPanelOpen = useAIChatPinned() + const panelStyle = useAIChatPanelStyle() + const isAiPanelOpen = panelStyle === AIChatPanelStyle.Fixed return ( { {aiEnabled && !isAiPanelOpen && ( { - EventBus.dispatch("global:toggle-ai-chat-pinned") + setAIPanelVisibility(true) }} className={cn( "mt-1 flex flex-nowrap items-center gap-2 text-sm opacity-50 transition-all duration-500 hover:opacity-100", @@ -95,16 +95,27 @@ const BackTopIndicator: Component = memo(({ className }) => { }) export const ContainerToc = memo( - ({ ref, ..._ }: ComponentType & { ref?: React.Ref }) => { + ({ + ref, + className, + stickyClassName, + }: ComponentType & { + ref?: React.Ref + className?: string + stickyClassName?: string + }) => { const wrappedElement = useWrappedElement() return (