From 170b0f61f27ec9cd2beb07d1f2391e8719c2653e Mon Sep 17 00:00:00 2001 From: lawvs <18554747+lawvs@users.noreply.github.com> Date: Fri, 11 Jul 2025 17:38:21 +0800 Subject: [PATCH 001/111] feat: add copy link functionality to MarkdownLink component --- .../ui/markdown/renderers/MarkdownLink.tsx | 30 +++++++++++++++++-- 1 file changed, 27 insertions(+), 3 deletions(-) diff --git a/apps/desktop/layer/renderer/src/components/ui/markdown/renderers/MarkdownLink.tsx b/apps/desktop/layer/renderer/src/components/ui/markdown/renderers/MarkdownLink.tsx index 83cf092f8..555bc5451 100644 --- a/apps/desktop/layer/renderer/src/components/ui/markdown/renderers/MarkdownLink.tsx +++ b/apps/desktop/layer/renderer/src/components/ui/markdown/renderers/MarkdownLink.tsx @@ -7,15 +7,32 @@ import { TooltipTrigger, } from "@follow/components/ui/tooltip/index.jsx" import { useCorrectZIndex } from "@follow/components/ui/z-index/ctx.js" -import { use } from "react" +import { use, useCallback } from "react" +import { useTranslation } from "react-i18next" +import { toast } from "sonner" + +import { copyToClipboard } from "~/lib/clipboard" import { MarkdownRenderActionContext } from "../context" export const MarkdownLink = (props: LinkProps) => { const { transformUrl, isAudio, ensureAndRenderTimeStamp } = use(MarkdownRenderActionContext) + const { t } = useTranslation() const populatedFullHref = transformUrl(props.href) + const handleCopyLink = useCallback(async () => { + try { + if (!populatedFullHref) { + throw new Error("No URL to copy") + } + await copyToClipboard(populatedFullHref) + toast.success(t("share.link_copied")) + } catch { + toast.error(t("share.copy_failed")) + } + }, [populatedFullHref, t]) + const parseTimeStamp = isAudio(populatedFullHref) const zIndex = useCorrectZIndex(0) if (parseTimeStamp) { @@ -46,10 +63,17 @@ export const MarkdownLink = (props: LinkProps) => { )} - {!!props.href && ( + {!!populatedFullHref && ( - {populatedFullHref} + {populatedFullHref} + )} From ef6f934714abbae15755d8562a488029961c0950 Mon Sep 17 00:00:00 2001 From: lawvs <18554747+lawvs@users.noreply.github.com> Date: Fri, 11 Jul 2025 18:50:18 +0800 Subject: [PATCH 002/111] fix: optimize mouse leave handler in SocialMediaItem component --- .../src/modules/entry-column/Items/social-media-item.tsx | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/apps/desktop/layer/renderer/src/modules/entry-column/Items/social-media-item.tsx b/apps/desktop/layer/renderer/src/modules/entry-column/Items/social-media-item.tsx index 74c8995f3..5dcb06567 100644 --- a/apps/desktop/layer/renderer/src/modules/entry-column/Items/social-media-item.tsx +++ b/apps/desktop/layer/renderer/src/modules/entry-column/Items/social-media-item.tsx @@ -76,10 +76,8 @@ export const SocialMediaItem: EntryListItemFC = ({ entryId, translation }) => { const handleMouseLeave = useMemo(() => { return (e: React.MouseEvent) => { // If the mouse is over the action bar, don't hide the action bar - const relatedTarget = e.relatedTarget as Element - const currentTarget = e.currentTarget as Element - - if (relatedTarget && currentTarget.contains(relatedTarget)) { + const { relatedTarget, currentTarget } = e + if (relatedTarget && relatedTarget instanceof Node && currentTarget.contains(relatedTarget)) { return } setShowAction(false) From f2ad2b911e7079399bdb12baf377e960d09b4a5b Mon Sep 17 00:00:00 2001 From: lawvs <18554747+lawvs@users.noreply.github.com> Date: Fri, 11 Jul 2025 18:52:38 +0800 Subject: [PATCH 003/111] fix: types --- .../src/modules/entry-column/layouts/EntryItemWrapper.tsx | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) 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 f38421e47..833aaab2c 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 { EventBus } from "@follow/utils/event-bus" import { cn } from "@follow/utils/utils" -import type { FC, PropsWithChildren } from "react" +import type { FC, MouseEvent, MouseEventHandler, PropsWithChildren, TouchEvent } from "react" import { useCallback, useMemo, useState } from "react" import { useTranslation } from "react-i18next" import { NavLink } from "react-router" @@ -85,7 +85,7 @@ export const EntryItemWrapper: FC< }) }, [entry?.id]) const handleClick = useCallback( - (e) => { + (e: TouchEvent | MouseEvent) => { e.preventDefault() e.stopPropagation() @@ -108,7 +108,7 @@ export const EntryItemWrapper: FC< }, [asRead, entry?.id, entry?.feedId, navigate], ) - const handleDoubleClick: React.MouseEventHandler = useCallback( + const handleDoubleClick: MouseEventHandler = useCallback( () => entry?.url && window.open(entry.url, "_blank"), [entry?.url], ) From ccae8cbaece75f2390c0c9e1a5ed224a21cd5e2c Mon Sep 17 00:00:00 2001 From: lawvs <18554747+lawvs@users.noreply.github.com> Date: Fri, 11 Jul 2025 18:58:48 +0800 Subject: [PATCH 004/111] fix: stopPropagation when clicking MarkdownLink --- .../src/components/ui/markdown/renderers/MarkdownLink.tsx | 2 ++ 1 file changed, 2 insertions(+) diff --git a/apps/desktop/layer/renderer/src/components/ui/markdown/renderers/MarkdownLink.tsx b/apps/desktop/layer/renderer/src/components/ui/markdown/renderers/MarkdownLink.tsx index 555bc5451..a93ea172a 100644 --- a/apps/desktop/layer/renderer/src/components/ui/markdown/renderers/MarkdownLink.tsx +++ b/apps/desktop/layer/renderer/src/components/ui/markdown/renderers/MarkdownLink.tsx @@ -7,6 +7,7 @@ import { TooltipTrigger, } from "@follow/components/ui/tooltip/index.jsx" import { useCorrectZIndex } from "@follow/components/ui/z-index/ctx.js" +import { stopPropagation } from "@follow/utils" import { use, useCallback } from "react" import { useTranslation } from "react-i18next" import { toast } from "sonner" @@ -55,6 +56,7 @@ export const MarkdownLink = (props: LinkProps) => { title={props.title} target="_blank" rel="noreferrer" + onClick={stopPropagation} > {props.children} From 0edf07a59a77b8ee140f01c58f5d85654e35be9f Mon Sep 17 00:00:00 2001 From: Innei Date: Sun, 13 Jul 2025 13:28:31 +0800 Subject: [PATCH 005/111] chore: add Claude Code GitHub Workflow (#4154) * Claude PR Assistant workflow * Claude Code Review workflow --- .github/workflows/claude-code-review.yml | 78 ++++++++++++++++++++++++ .github/workflows/claude.yml | 64 +++++++++++++++++++ 2 files changed, 142 insertions(+) create mode 100644 .github/workflows/claude-code-review.yml create mode 100644 .github/workflows/claude.yml diff --git a/.github/workflows/claude-code-review.yml b/.github/workflows/claude-code-review.yml new file mode 100644 index 000000000..5bf8ce595 --- /dev/null +++ b/.github/workflows/claude-code-review.yml @@ -0,0 +1,78 @@ +name: Claude Code Review + +on: + pull_request: + types: [opened, synchronize] + # Optional: Only run on specific file changes + # paths: + # - "src/**/*.ts" + # - "src/**/*.tsx" + # - "src/**/*.js" + # - "src/**/*.jsx" + +jobs: + claude-review: + # Optional: Filter by PR author + # if: | + # github.event.pull_request.user.login == 'external-contributor' || + # github.event.pull_request.user.login == 'new-developer' || + # github.event.pull_request.author_association == 'FIRST_TIME_CONTRIBUTOR' + + runs-on: ubuntu-latest + permissions: + contents: read + pull-requests: read + issues: read + id-token: write + + steps: + - name: Checkout repository + uses: actions/checkout@v4 + with: + fetch-depth: 1 + + - name: Run Claude Code Review + id: claude-review + uses: anthropics/claude-code-action@beta + with: + claude_code_oauth_token: ${{ secrets.CLAUDE_CODE_OAUTH_TOKEN }} + + # Optional: Specify model (defaults to Claude Sonnet 4, uncomment for Claude Opus 4) + # model: "claude-opus-4-20250514" + + # Direct prompt for automated review (no @claude mention needed) + direct_prompt: | + Please review this pull request and provide feedback on: + - Code quality and best practices + - Potential bugs or issues + - Performance considerations + - Security concerns + - Test coverage + + Be constructive and helpful in your feedback. + + # Optional: Use sticky comments to make Claude reuse the same comment on subsequent pushes to the same PR + # use_sticky_comment: true + + # Optional: Customize review based on file types + # direct_prompt: | + # Review this PR focusing on: + # - For TypeScript files: Type safety and proper interface usage + # - For API endpoints: Security, input validation, and error handling + # - For React components: Performance, accessibility, and best practices + # - For tests: Coverage, edge cases, and test quality + + # Optional: Different prompts for different authors + # direct_prompt: | + # ${{ github.event.pull_request.author_association == 'FIRST_TIME_CONTRIBUTOR' && + # 'Welcome! Please review this PR from a first-time contributor. Be encouraging and provide detailed explanations for any suggestions.' || + # 'Please provide a thorough code review focusing on our coding standards and best practices.' }} + + # Optional: Add specific tools for running tests or linting + # allowed_tools: "Bash(npm run test),Bash(npm run lint),Bash(npm run typecheck)" + + # Optional: Skip review for certain conditions + # if: | + # !contains(github.event.pull_request.title, '[skip-review]') && + # !contains(github.event.pull_request.title, '[WIP]') + diff --git a/.github/workflows/claude.yml b/.github/workflows/claude.yml new file mode 100644 index 000000000..64a3e5b14 --- /dev/null +++ b/.github/workflows/claude.yml @@ -0,0 +1,64 @@ +name: Claude Code + +on: + issue_comment: + types: [created] + pull_request_review_comment: + types: [created] + issues: + types: [opened, assigned] + pull_request_review: + types: [submitted] + +jobs: + claude: + if: | + (github.event_name == 'issue_comment' && contains(github.event.comment.body, '@claude')) || + (github.event_name == 'pull_request_review_comment' && contains(github.event.comment.body, '@claude')) || + (github.event_name == 'pull_request_review' && contains(github.event.review.body, '@claude')) || + (github.event_name == 'issues' && (contains(github.event.issue.body, '@claude') || contains(github.event.issue.title, '@claude'))) + runs-on: ubuntu-latest + permissions: + contents: read + pull-requests: read + issues: read + id-token: write + actions: read # Required for Claude to read CI results on PRs + steps: + - name: Checkout repository + uses: actions/checkout@v4 + with: + fetch-depth: 1 + + - name: Run Claude Code + id: claude + uses: anthropics/claude-code-action@beta + with: + claude_code_oauth_token: ${{ secrets.CLAUDE_CODE_OAUTH_TOKEN }} + + # This is an optional setting that allows Claude to read CI results on PRs + additional_permissions: | + actions: read + + # Optional: Specify model (defaults to Claude Sonnet 4, uncomment for Claude Opus 4) + # model: "claude-opus-4-20250514" + + # Optional: Customize the trigger phrase (default: @claude) + # trigger_phrase: "/claude" + + # Optional: Trigger when specific user is assigned to an issue + # assignee_trigger: "claude-bot" + + # Optional: Allow Claude to run specific commands + # allowed_tools: "Bash(npm install),Bash(npm run build),Bash(npm run test:*),Bash(npm run lint:*)" + + # Optional: Add custom instructions for Claude to customize its behavior for your project + # custom_instructions: | + # Follow our coding standards + # Ensure all new code has tests + # Use TypeScript for new files + + # Optional: Custom environment variables for Claude + # claude_env: | + # NODE_ENV: test + From b69800050e19ce71c57ec595b36234524ca0c060 Mon Sep 17 00:00:00 2001 From: Whitewater Date: Sun, 13 Jul 2025 13:29:52 +0800 Subject: [PATCH 006/111] fix: replace slugify with sanitizeFileName for file name processing (#4152) * refactor: replace slugify with sanitizeFileName for fileName processing * chore: remove unused slugify dependency --- apps/desktop/layer/main/package.json | 1 - .../main/src/ipc/services/integration.ts | 18 ++++++++++-- pnpm-lock.yaml | 28 +++---------------- 3 files changed, 20 insertions(+), 27 deletions(-) diff --git a/apps/desktop/layer/main/package.json b/apps/desktop/layer/main/package.json index 98a2feeb5..51e823f8f 100644 --- a/apps/desktop/layer/main/package.json +++ b/apps/desktop/layer/main/package.json @@ -28,7 +28,6 @@ "@follow/utils": "workspace:*", "@openpanel/web": "1.0.1", "@sentry/electron": "6.8.0", - "@sindresorhus/slugify": "2.2.1", "builder-util-runtime": "9.3.1", "electron-context-menu": "4.0.5", "electron-log": "5.4.1", diff --git a/apps/desktop/layer/main/src/ipc/services/integration.ts b/apps/desktop/layer/main/src/ipc/services/integration.ts index ff7780ea9..6381d7436 100644 --- a/apps/desktop/layer/main/src/ipc/services/integration.ts +++ b/apps/desktop/layer/main/src/ipc/services/integration.ts @@ -1,12 +1,26 @@ import { existsSync } from "node:fs" import fsp from "node:fs/promises" -import slugify from "@sindresorhus/slugify" import path from "pathe" import type { IpcContext } from "../base" import { IpcMethod, IpcService } from "../base" +// Taken from https://github.com/rollup/rollup/blob/4f69d33af3b2ec9320c43c9e6c65ea23a02bdde3/src/utils/sanitizeFileName.ts +// https://datatracker.ietf.org/doc/html/rfc2396 +// eslint-disable-next-line no-control-regex +const INVALID_CHAR_REGEX = /[\u0000-\u001F"#$%&*+,:;<=>?[\]^`{|}\u007F]/g +const DRIVE_LETTER_REGEX = /^[a-z]:/i + +function sanitizeFileName(name: string): string { + const match = DRIVE_LETTER_REGEX.exec(name) + const driveLetter = match ? match[0] : "" + + // A `:` is only allowed as part of a windows drive letter (ex: C:\foo) + // Otherwise, avoid them because they can refer to NTFS alternate data streams. + return driveLetter + name.slice(driveLetter.length).replaceAll(INVALID_CHAR_REGEX, "_") +} + // Input types interface SaveToEagleInput { url: string @@ -32,7 +46,7 @@ export class IntegrationService extends IpcService { try { const { url, title, content, author, publishedAt, vaultPath } = input - const fileName = `${slugify(title || publishedAt) + const fileName = `${sanitizeFileName(title || publishedAt) .trim() .slice(0, 20)}.md` const filePath = path.join(vaultPath, fileName) diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 255b454f0..f215bafd8 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -344,9 +344,6 @@ importers: '@sentry/electron': specifier: 6.8.0 version: 6.8.0(patch_hash=a5a19cbba4427bc1e6f675a47170c6e03adc0fcec259258bfa07288185b5a979) - '@sindresorhus/slugify': - specifier: 2.2.1 - version: 2.2.1 builder-util-runtime: specifier: 9.3.1 version: 9.3.1 @@ -1596,7 +1593,7 @@ importers: version: '@hyoban/sqlocal@0.14.1-fork.4(bufferutil@4.0.9)(drizzle-orm@0.44.2(@opentelemetry/api@1.9.0)(@types/pg@8.6.1)(expo-sqlite@15.2.12(expo@53.0.12(@babel/core@7.28.0)(@expo/metro-runtime@5.0.4(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0)))(bufferutil@4.0.9)(graphql@16.8.1)(react-native-webview@13.15.0(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(kysely@0.28.2))(kysely@0.28.2)' wa-sqlite: specifier: github:rhashimoto/wa-sqlite#v1.0.8 - version: https://codeload.github.com/rhashimoto/wa-sqlite/tar.gz/03c00ed67cd934bd664ae310234bba317928f851 + version: git+https://git@github.com:rhashimoto/wa-sqlite.git#03c00ed67cd934bd664ae310234bba317928f851 devDependencies: '@follow/configs': specifier: workspace:* @@ -6050,14 +6047,6 @@ packages: resolution: {integrity: sha512-t09vSN3MdfsyCHoFcTRCH/iUtG7OJ0CsjzB8cjAmKc/va/kIgeDI/TxsigdncE/4be734m0cvIYwNaV4i2XqAw==} engines: {node: '>=10'} - '@sindresorhus/slugify@2.2.1': - resolution: {integrity: sha512-MkngSCRZ8JdSOCHRaYd+D01XhvU3Hjy6MGl06zhOk614hp9EOAp5gIkBeQg7wtmxpitU6eAL4kdiRMcJa2dlrw==} - engines: {node: '>=12'} - - '@sindresorhus/transliterate@1.6.0': - resolution: {integrity: sha512-doH1gimEu3A46VX6aVxpHTeHrytJAG6HgdxntYnCFiIFHEM/ZGpG8KiZGBChchjQmG0XFIBL552kBTjVcMZXwQ==} - engines: {node: '>=12'} - '@sinonjs/commons@3.0.1': resolution: {integrity: sha512-K3mCHKQ9sVh8o1C9cxkwxaOmXoAMlDxC1mYyHrjqOWEcBjYr76t96zL2zlj5dUGZ3HSw240X1qgH3Mjf1yJWpQ==} @@ -15108,8 +15097,8 @@ packages: vscode-uri@3.1.0: resolution: {integrity: sha512-/BpdSx+yCQGnCvecbyXdxHDkuk55/G3xwnC0GqY4gmQ3j+A+g8kzzgB4Nk/SINjqn6+waqw3EgbVF2QKExkRxQ==} - wa-sqlite@https://codeload.github.com/rhashimoto/wa-sqlite/tar.gz/03c00ed67cd934bd664ae310234bba317928f851: - resolution: {tarball: https://codeload.github.com/rhashimoto/wa-sqlite/tar.gz/03c00ed67cd934bd664ae310234bba317928f851} + wa-sqlite@git+https://git@github.com:rhashimoto/wa-sqlite.git#03c00ed67cd934bd664ae310234bba317928f851: + resolution: {commit: 03c00ed67cd934bd664ae310234bba317928f851, repo: git@github.com:rhashimoto/wa-sqlite.git, type: git} version: 1.0.8 walker@1.0.8: @@ -21037,15 +21026,6 @@ snapshots: '@sindresorhus/is@4.6.0': {} - '@sindresorhus/slugify@2.2.1': - dependencies: - '@sindresorhus/transliterate': 1.6.0 - escape-string-regexp: 5.0.0 - - '@sindresorhus/transliterate@1.6.0': - dependencies: - escape-string-regexp: 5.0.0 - '@sinonjs/commons@3.0.1': dependencies: type-detect: 4.0.8 @@ -31694,7 +31674,7 @@ snapshots: vscode-uri@3.1.0: {} - wa-sqlite@https://codeload.github.com/rhashimoto/wa-sqlite/tar.gz/03c00ed67cd934bd664ae310234bba317928f851: {} + wa-sqlite@git+https://git@github.com:rhashimoto/wa-sqlite.git#03c00ed67cd934bd664ae310234bba317928f851: {} walker@1.0.8: dependencies: From b44bf710f2ae3766c2375160b4b0f26327c7e4d9 Mon Sep 17 00:00:00 2001 From: Innei Date: Sun, 13 Jul 2025 13:57:41 +0800 Subject: [PATCH 007/111] fix: right context menu shortcut can't trigger Signed-off-by: Innei --- .../renderer/src/providers/context-menu-provider.tsx | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/apps/desktop/layer/renderer/src/providers/context-menu-provider.tsx b/apps/desktop/layer/renderer/src/providers/context-menu-provider.tsx index 4661c657d..2803474b9 100644 --- a/apps/desktop/layer/renderer/src/providers/context-menu-provider.tsx +++ b/apps/desktop/layer/renderer/src/providers/context-menu-provider.tsx @@ -1,4 +1,7 @@ -import { useGlobalFocusableHasScope } from "@follow/components/common/Focusable/hooks.js" +import { + useGlobalFocusableHasScope, + useSetGlobalFocusableScope, +} from "@follow/components/common/Focusable/hooks.js" import { useMobile } from "@follow/components/hooks/useMobile.js" import { ContextMenu, @@ -53,15 +56,17 @@ const Handler = () => { }), ) }, [contextMenuState]) + const setGlobalFocusableScope = useSetGlobalFocusableScope() const handleOpenChange = useCallback( (state: boolean) => { + setGlobalFocusableScope(HotkeyScope.Menu, state ? "append" : "remove") if (state) return if (!contextMenuState.open) return setContextMenuState({ open: false }) contextMenuState.abortController.abort() }, - [contextMenuState, setContextMenuState], + [contextMenuState, setContextMenuState, setGlobalFocusableScope], ) return ( From 672978ca25bd7949f078f6c8ef4dc21c3ae0b1eb Mon Sep 17 00:00:00 2001 From: lawvs <18554747+lawvs@users.noreply.github.com> Date: Mon, 14 Jul 2025 05:03:33 +0800 Subject: [PATCH 008/111] fix: improve image size handling for Android, closes #4151 --- apps/mobile/src/components/ui/image/utils.ts | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) diff --git a/apps/mobile/src/components/ui/image/utils.ts b/apps/mobile/src/components/ui/image/utils.ts index 58224ee7d..0486cb78a 100644 --- a/apps/mobile/src/components/ui/image/utils.ts +++ b/apps/mobile/src/components/ui/image/utils.ts @@ -8,7 +8,7 @@ import * as Sharing from "expo-sharing" import { useCallback } from "react" import { Image } from "react-native" -import { isNative } from "@/src/lib/platform" +import { isAndroid, isNative } from "@/src/lib/platform" import { proxyEnv } from "@/src/lib/proxy-env" import { toast } from "@/src/lib/toast" @@ -71,7 +71,18 @@ export const getAllSources = ( } const getImageData = async (imageUrl: string) => { - const size = await Image.getSize(imageUrl) + let size = await Image.getSize(imageUrl) + + // Workaround for Android where the size returned by Image.getSize is not accurate for remote images + // https://github.com/facebook/react-native/issues/33498 + if (isAndroid) { + // If the image is not a remote URL, we can use the local file path directly + size = { + width: size.width * 10, + height: size.height * 10, + } + } + const croppedImage = await ImageEditor.cropImage(imageUrl, { offset: { x: 0, @@ -157,7 +168,7 @@ export function useSaveImageToMediaLibrary() { try { await saveImageToMediaLibrary({ uri }) toast.success("Image saved to library") - } catch (e: any) { + } catch (e) { toast.error(`Failed to save image: ${String(e)}`) } } From 946c103648bdf388d89051a13281d2222482fe55 Mon Sep 17 00:00:00 2001 From: Stephen Zhou <38493346+hyoban@users.noreply.github.com> Date: Mon, 14 Jul 2025 15:51:00 +0800 Subject: [PATCH 009/111] feat(desktop): persist discover search keyword state, close #4166 --- .../app-layout/subview/SubviewLayout.tsx | 5 +- .../src/modules/discover/DiscoverForm.tsx | 100 +++++++++++++----- .../(layer)/(subview)/discover/index.tsx | 1 + 3 files changed, 79 insertions(+), 27 deletions(-) diff --git a/apps/desktop/layer/renderer/src/modules/app-layout/subview/SubviewLayout.tsx b/apps/desktop/layer/renderer/src/modules/app-layout/subview/SubviewLayout.tsx index 075cfe5ef..1cf30128b 100644 --- a/apps/desktop/layer/renderer/src/modules/app-layout/subview/SubviewLayout.tsx +++ b/apps/desktop/layer/renderer/src/modules/app-layout/subview/SubviewLayout.tsx @@ -12,6 +12,7 @@ import { useCallback, useEffect, useRef, useState } from "react" import { useHotkeys } from "react-hotkeys-hook" import { useTranslation } from "react-i18next" import { NavigationType, Outlet, useLocation, useNavigate, useNavigationType } from "react-router" +import { parseQuery } from "ufo" import { Focusable } from "~/components/common/Focusable" import { HotkeyScope } from "~/constants" @@ -57,6 +58,8 @@ function SubviewLayoutInner() { return () => resizeObserver.disconnect() }, [scrollRef, updateMaxScroll]) + const discoverType = parseQuery(location.search).type + useEffect(() => { // Scroll to top search bar when re-navigating to Discover page while already on it if ( @@ -75,7 +78,7 @@ function SubviewLayoutInner() { ) { springScrollTo(0, scrollRef) } - }, [location, navigationType, scrollRef]) + }, [location.pathname, discoverType, scrollRef]) useEffect(() => { const $scroll = scrollRef diff --git a/apps/desktop/layer/renderer/src/modules/discover/DiscoverForm.tsx b/apps/desktop/layer/renderer/src/modules/discover/DiscoverForm.tsx index 38536b242..9c3e1b4ef 100644 --- a/apps/desktop/layer/renderer/src/modules/discover/DiscoverForm.tsx +++ b/apps/desktop/layer/renderer/src/modules/discover/DiscoverForm.tsx @@ -17,9 +17,10 @@ import { useMutation } from "@tanstack/react-query" import { produce } from "immer" import { atom, useAtomValue, useStore } from "jotai" import type { ChangeEvent } from "react" -import { useCallback, useState } from "react" +import { useCallback, useEffect } from "react" import { useForm } from "react-hook-form" import { useTranslation } from "react-i18next" +import { useSearchParams } from "react-router" import { z } from "zod" import { useIsInMASReview } from "~/atoms/server-configs" @@ -84,15 +85,32 @@ const info: Record< } type DiscoverSearchData = Awaited>["data"] + +const discoverSearchDataAtom = atom>() + export function DiscoverForm({ type = "search" }: { type?: string }) { const { prefix, default: defaultValue } = info[type]! + + const [searchParams, setSearchParams] = useSearchParams() + const keywordFromSearch = searchParams.get("keyword") || "" const form = useForm>({ resolver: zodResolver(formSchema), defaultValues: { - keyword: defaultValue || "", + keyword: defaultValue || keywordFromSearch || "", target: "feeds", }, }) + const { watch, trigger } = form + // validate default value from search params + useEffect(() => { + if (!keywordFromSearch) { + return + } + trigger("keyword") + }, [trigger]) + + const target = watch("target") + const atomKey = keywordFromSearch + target const { t } = useTranslation() const isInMASReview = useIsInMASReview() @@ -109,14 +127,16 @@ export function DiscoverForm({ type = "search" }: { type?: string }) { data = data.filter((item) => !item.list?.fee) } - jotaiStore.set(discoverSearchDataAtom, data) + jotaiStore.set(discoverSearchDataAtom, (prev) => ({ + ...prev, + [atomKey]: data, + })) return data }, }) - const discoverSearchDataAtom = useState(() => atom())[0] - const discoverSearchData = useAtomValue(discoverSearchDataAtom) + const discoverSearchData = useAtomValue(discoverSearchDataAtom)?.[atomKey] || [] const { present, dismissAll } = useModalStack() @@ -133,23 +153,44 @@ export function DiscoverForm({ type = "search" }: { type?: string }) { const handleKeywordChange = useCallback( (event: ChangeEvent) => { + const syncKeyword = (keyword: string) => { + setSearchParams( + (prev) => { + const newParams = new URLSearchParams(prev) + if (keyword) { + newParams.set("keyword", keyword) + } else { + newParams.delete("keyword") + } + return newParams + }, + { + replace: true, + }, + ) + } + const trimmedKeyword = event.target.value.trimStart() if (!prefix) { form.setValue("keyword", trimmedKeyword, { shouldValidate: true }) + syncKeyword(trimmedKeyword) return } const isValidPrefix = prefix.find((p) => trimmedKeyword.startsWith(p)) if (!isValidPrefix) { form.setValue("keyword", prefix[0]!) + syncKeyword(prefix[0]!) return } if (trimmedKeyword.startsWith(`${isValidPrefix}${isValidPrefix}`)) { form.setValue("keyword", trimmedKeyword.slice(isValidPrefix.length)) + syncKeyword(trimmedKeyword.slice(isValidPrefix.length)) return } form.setValue("keyword", trimmedKeyword) + syncKeyword(trimmedKeyword) }, - [form, prefix], + [form, prefix, setSearchParams], ) const handleSuccess = useCallback( @@ -159,7 +200,7 @@ export function DiscoverForm({ type = "search" }: { type?: string }) { jotaiStore.set( discoverSearchDataAtom, produce(currentData, (draft) => { - const sub = draft.find((i) => { + const sub = (draft[atomKey] || []).find((i) => { if (item.feed) { return i.feed?.id === item.feed.id } @@ -183,7 +224,7 @@ export function DiscoverForm({ type = "search" }: { type?: string }) { jotaiStore.set( discoverSearchDataAtom, produce(currentData, (draft) => { - const sub = draft.find( + const sub = (draft[atomKey] || []).find( (i) => i.feed?.id === item.feed?.id || i.list?.id === item.list?.id, ) if (!sub) return @@ -287,34 +328,41 @@ export function DiscoverForm({ type = "search" }: { type?: string }) { - {mutation.isSuccess && ( -
-
- {t("discover.search.results", { count: mutation.data?.length || 0 })} - {mutation.data?.length > 0 && ( +
+ {(mutation.isSuccess || !!discoverSearchData?.length) && ( +
+ {t("discover.search.results", { count: discoverSearchData?.length || 0 })} + + {discoverSearchData && discoverSearchData.length > 0 && ( { + jotaiStore.set(discoverSearchDataAtom, { + ...jotaiStore.get(discoverSearchDataAtom), + [atomKey]: [], + }) + mutation.reset() + }} > )}
-
- {discoverSearchData?.map((item) => ( - - ))} -
+ )} +
+ {discoverSearchData?.map((item) => ( + + ))}
- )} +
) } diff --git a/apps/desktop/layer/renderer/src/pages/(main)/(layer)/(subview)/discover/index.tsx b/apps/desktop/layer/renderer/src/pages/(main)/(layer)/(subview)/discover/index.tsx index 4423e2a15..a18cfd9c9 100644 --- a/apps/desktop/layer/renderer/src/pages/(main)/(layer)/(subview)/discover/index.tsx +++ b/apps/desktop/layer/renderer/src/pages/(main)/(layer)/(subview)/discover/index.tsx @@ -88,6 +88,7 @@ export function Component() { setSearch( (search) => { search.set("type", val) + search.delete("keyword") return new URLSearchParams(search) }, { replace: true }, From 584a5849d24630e9f927a80418066717733a32b2 Mon Sep 17 00:00:00 2001 From: DIYgod Date: Mon, 14 Jul 2025 16:07:44 +0800 Subject: [PATCH 010/111] fix: entry list loading status --- .../src/modules/entry-column/hooks/useEntriesByView.ts | 3 +++ .../layer/renderer/src/modules/entry-column/index.tsx | 5 ++++- 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/apps/desktop/layer/renderer/src/modules/entry-column/hooks/useEntriesByView.ts b/apps/desktop/layer/renderer/src/modules/entry-column/hooks/useEntriesByView.ts index 8cd81de7a..b25491f08 100644 --- a/apps/desktop/layer/renderer/src/modules/entry-column/hooks/useEntriesByView.ts +++ b/apps/desktop/layer/renderer/src/modules/entry-column/hooks/useEntriesByView.ts @@ -328,6 +328,9 @@ export const useEntriesByView = ({ onReset }: { onReset?: () => void }) => { }, [query]), entriesIds: entryIds, groupedCounts, + isFetching: remoteQuery.isFetching, + isFetchingNextPage: remoteQuery.isFetchingNextPage, + isLoading: remoteQuery.isLoading, } } diff --git a/apps/desktop/layer/renderer/src/modules/entry-column/index.tsx b/apps/desktop/layer/renderer/src/modules/entry-column/index.tsx index 221fbd78f..92842bd6a 100644 --- a/apps/desktop/layer/renderer/src/modules/entry-column/index.tsx +++ b/apps/desktop/layer/renderer/src/modules/entry-column/index.tsx @@ -20,6 +20,7 @@ import { useFeedHeaderTitle } from "~/store/feed/hooks" import { EntryColumnWrapper } from "./components/entry-column-wrapper/EntryColumnWrapper" import { FooterMarkItem } from "./components/FooterMarkItem" +import { EntryItemSkeleton } from "./EntryItemSkeleton" import { EntryColumnGrid } from "./grid" import { useEntriesByView } from "./hooks/useEntriesByView" import { useSnapEntryIdList } from "./hooks/useEntryIdListSnap" @@ -150,7 +151,9 @@ function EntryColumnImpl() { key={`${routeFeedId}-${view}`} > {entriesIds.length === 0 ? ( - entries.isLoading ? null : ( + entries.isLoading ? ( + + ) : ( ) ) : ( From 8162a6f26ea46533e8385636caa22c2a476397c5 Mon Sep 17 00:00:00 2001 From: DIYgod Date: Mon, 14 Jul 2025 16:23:56 +0800 Subject: [PATCH 011/111] fix: deps error in github actions --- packages/internal/database/package.json | 2 +- pnpm-lock.yaml | 10 +++++----- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/packages/internal/database/package.json b/packages/internal/database/package.json index 8f1162d94..666c3752f 100644 --- a/packages/internal/database/package.json +++ b/packages/internal/database/package.json @@ -38,7 +38,7 @@ "drizzle-orm": "0.44.2", "expo-sqlite": "15.2.12", "sqlocal": "npm:@hyoban/sqlocal@0.14.1-fork.4", - "wa-sqlite": "github:rhashimoto/wa-sqlite#v1.0.8" + "wa-sqlite": "git+https://github.com/rhashimoto/wa-sqlite.git#v1.0.8" }, "devDependencies": { "@follow/configs": "workspace:*", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index f215bafd8..288c4db22 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -1592,8 +1592,8 @@ importers: specifier: npm:@hyoban/sqlocal@0.14.1-fork.4 version: '@hyoban/sqlocal@0.14.1-fork.4(bufferutil@4.0.9)(drizzle-orm@0.44.2(@opentelemetry/api@1.9.0)(@types/pg@8.6.1)(expo-sqlite@15.2.12(expo@53.0.12(@babel/core@7.28.0)(@expo/metro-runtime@5.0.4(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0)))(bufferutil@4.0.9)(graphql@16.8.1)(react-native-webview@13.15.0(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(kysely@0.28.2))(kysely@0.28.2)' wa-sqlite: - specifier: github:rhashimoto/wa-sqlite#v1.0.8 - version: git+https://git@github.com:rhashimoto/wa-sqlite.git#03c00ed67cd934bd664ae310234bba317928f851 + specifier: git+https://github.com/rhashimoto/wa-sqlite.git#v1.0.8 + version: https://codeload.github.com/rhashimoto/wa-sqlite/tar.gz/03c00ed67cd934bd664ae310234bba317928f851 devDependencies: '@follow/configs': specifier: workspace:* @@ -15097,8 +15097,8 @@ packages: vscode-uri@3.1.0: resolution: {integrity: sha512-/BpdSx+yCQGnCvecbyXdxHDkuk55/G3xwnC0GqY4gmQ3j+A+g8kzzgB4Nk/SINjqn6+waqw3EgbVF2QKExkRxQ==} - wa-sqlite@git+https://git@github.com:rhashimoto/wa-sqlite.git#03c00ed67cd934bd664ae310234bba317928f851: - resolution: {commit: 03c00ed67cd934bd664ae310234bba317928f851, repo: git@github.com:rhashimoto/wa-sqlite.git, type: git} + wa-sqlite@https://codeload.github.com/rhashimoto/wa-sqlite/tar.gz/03c00ed67cd934bd664ae310234bba317928f851: + resolution: {tarball: https://codeload.github.com/rhashimoto/wa-sqlite/tar.gz/03c00ed67cd934bd664ae310234bba317928f851} version: 1.0.8 walker@1.0.8: @@ -31674,7 +31674,7 @@ snapshots: vscode-uri@3.1.0: {} - wa-sqlite@git+https://git@github.com:rhashimoto/wa-sqlite.git#03c00ed67cd934bd664ae310234bba317928f851: {} + wa-sqlite@https://codeload.github.com/rhashimoto/wa-sqlite/tar.gz/03c00ed67cd934bd664ae310234bba317928f851: {} walker@1.0.8: dependencies: From e81220de63ccd992acbb21029269ef80ded481c6 Mon Sep 17 00:00:00 2001 From: DIYgod Date: Mon, 14 Jul 2025 16:45:14 +0800 Subject: [PATCH 012/111] fix: subscription list loading status --- .../src/modules/subscription-column/index.tsx | 3 ++- .../subscription-list/SubscriptionList.tsx | 16 +++++++++++++++- .../subscription-list/SubscriptionListGuard.tsx | 5 +++-- 3 files changed, 20 insertions(+), 4 deletions(-) diff --git a/apps/desktop/layer/renderer/src/modules/subscription-column/index.tsx b/apps/desktop/layer/renderer/src/modules/subscription-column/index.tsx index fcea5a0ba..5aafc97d3 100644 --- a/apps/desktop/layer/renderer/src/modules/subscription-column/index.tsx +++ b/apps/desktop/layer/renderer/src/modules/subscription-column/index.tsx @@ -39,7 +39,7 @@ export function SubscriptionColumn({ children, className, }: PropsWithChildren<{ className?: string }>) { - usePrefetchSubscription() + const { isLoading: isSubscriptionLoading } = usePrefetchSubscription() usePrefetchUnread() const carouselRef = useRef(null) @@ -169,6 +169,7 @@ export function SubscriptionColumn({ 10, ) as FeedViewType } + isSubscriptionLoading={isSubscriptionLoading} /> ))} diff --git a/apps/desktop/layer/renderer/src/modules/subscription-column/subscription-list/SubscriptionList.tsx b/apps/desktop/layer/renderer/src/modules/subscription-column/subscription-list/SubscriptionList.tsx index 0a5b3e037..0926906a3 100644 --- a/apps/desktop/layer/renderer/src/modules/subscription-column/subscription-list/SubscriptionList.tsx +++ b/apps/desktop/layer/renderer/src/modules/subscription-column/subscription-list/SubscriptionList.tsx @@ -5,6 +5,7 @@ import { useGlobalFocusableScopeSelector, } from "@follow/components/common/Focusable/hooks.js" import { ScrollArea } from "@follow/components/ui/scroll-area/index.js" +import { Skeleton } from "@follow/components/ui/skeleton/index.jsx" import { FeedViewType } from "@follow/constants" import { useInboxList } from "@follow/store/inbox/hooks" import { useListById } from "@follow/store/list/hooks" @@ -45,7 +46,7 @@ import { ListHeader } from "./ListHeader" import { StarredItem } from "./StarredItem" import type { SubscriptionProps } from "./SubscriptionListGuard" -const SubscriptionImpl = ({ ref, className, view }: SubscriptionProps) => { +const SubscriptionImpl = ({ ref, className, view, isSubscriptionLoading }: SubscriptionProps) => { const autoGroup = useGeneralSettingKey("autoGroup") const feedsData = useFeedsGroupedData(view, autoGroup) const listSubIds = useSubscriptionListIds(view) @@ -293,6 +294,8 @@ const SubscriptionImpl = ({ ref, className, view }: SubscriptionProps) => { data={feedsData} categoryOpenStateData={categoryOpenStateData} /> + ) : isSubscriptionLoading ? ( + ) : ( )} @@ -411,3 +414,14 @@ const useRegisterCommand = () => { ) }, [focusableContainerRef, focusActions, getCurrentActiveSubscriptionElement]) } + +const SubscriptionListSkeleton = () => ( +
+ {Array.from({ length: 5 }).map((_, index) => ( +
+ + +
+ ))} +
+) diff --git a/apps/desktop/layer/renderer/src/modules/subscription-column/subscription-list/SubscriptionListGuard.tsx b/apps/desktop/layer/renderer/src/modules/subscription-column/subscription-list/SubscriptionListGuard.tsx index a34308d59..2b005cd19 100644 --- a/apps/desktop/layer/renderer/src/modules/subscription-column/subscription-list/SubscriptionListGuard.tsx +++ b/apps/desktop/layer/renderer/src/modules/subscription-column/subscription-list/SubscriptionListGuard.tsx @@ -4,7 +4,7 @@ import { cn } from "@follow/utils" import { SubscriptionList as FeedListDesktop } from "./SubscriptionList" export const SubscriptionListGuard = function SubscriptionListGuard(props: SubscriptionProps) { - const { ref, className, view } = props + const { ref, className, view, isSubscriptionLoading } = props if (typeof view !== "number") { return null @@ -14,12 +14,13 @@ export const SubscriptionListGuard = function SubscriptionListGuard(props: Subsc className={cn("flex size-full flex-col text-sm", className)} view={view} ref={ref} + isSubscriptionLoading={isSubscriptionLoading} /> ) } export type SubscriptionProps = ComponentType< - { className?: string; view: FeedViewType } & { + { className?: string; view: FeedViewType; isSubscriptionLoading: boolean } & { ref?: React.Ref | ((node: HTMLDivElement | null) => void) } > From 003ebde1c4f744736840439d41026fee724c1d09 Mon Sep 17 00:00:00 2001 From: DIYgod Date: Mon, 14 Jul 2025 16:49:59 +0800 Subject: [PATCH 013/111] chore: clean up whitespace in GitHub workflow files --- .github/workflows/claude-code-review.yml | 19 +++++++++---------- .github/workflows/claude.yml | 13 ++++++------- 2 files changed, 15 insertions(+), 17 deletions(-) diff --git a/.github/workflows/claude-code-review.yml b/.github/workflows/claude-code-review.yml index 5bf8ce595..2c3a718f8 100644 --- a/.github/workflows/claude-code-review.yml +++ b/.github/workflows/claude-code-review.yml @@ -17,14 +17,14 @@ jobs: # github.event.pull_request.user.login == 'external-contributor' || # github.event.pull_request.user.login == 'new-developer' || # github.event.pull_request.author_association == 'FIRST_TIME_CONTRIBUTOR' - + runs-on: ubuntu-latest permissions: contents: read pull-requests: read issues: read id-token: write - + steps: - name: Checkout repository uses: actions/checkout@v4 @@ -39,7 +39,7 @@ jobs: # Optional: Specify model (defaults to Claude Sonnet 4, uncomment for Claude Opus 4) # model: "claude-opus-4-20250514" - + # Direct prompt for automated review (no @claude mention needed) direct_prompt: | Please review this pull request and provide feedback on: @@ -48,12 +48,12 @@ jobs: - Performance considerations - Security concerns - Test coverage - + Be constructive and helpful in your feedback. # Optional: Use sticky comments to make Claude reuse the same comment on subsequent pushes to the same PR # use_sticky_comment: true - + # Optional: Customize review based on file types # direct_prompt: | # Review this PR focusing on: @@ -61,18 +61,17 @@ jobs: # - For API endpoints: Security, input validation, and error handling # - For React components: Performance, accessibility, and best practices # - For tests: Coverage, edge cases, and test quality - + # Optional: Different prompts for different authors # direct_prompt: | - # ${{ github.event.pull_request.author_association == 'FIRST_TIME_CONTRIBUTOR' && + # ${{ github.event.pull_request.author_association == 'FIRST_TIME_CONTRIBUTOR' && # 'Welcome! Please review this PR from a first-time contributor. Be encouraging and provide detailed explanations for any suggestions.' || # 'Please provide a thorough code review focusing on our coding standards and best practices.' }} - + # Optional: Add specific tools for running tests or linting # allowed_tools: "Bash(npm run test),Bash(npm run lint),Bash(npm run typecheck)" - + # Optional: Skip review for certain conditions # if: | # !contains(github.event.pull_request.title, '[skip-review]') && # !contains(github.event.pull_request.title, '[WIP]') - diff --git a/.github/workflows/claude.yml b/.github/workflows/claude.yml index 64a3e5b14..fab4b58bc 100644 --- a/.github/workflows/claude.yml +++ b/.github/workflows/claude.yml @@ -39,26 +39,25 @@ jobs: # This is an optional setting that allows Claude to read CI results on PRs additional_permissions: | actions: read - + # Optional: Specify model (defaults to Claude Sonnet 4, uncomment for Claude Opus 4) # model: "claude-opus-4-20250514" - + # Optional: Customize the trigger phrase (default: @claude) # trigger_phrase: "/claude" - + # Optional: Trigger when specific user is assigned to an issue # assignee_trigger: "claude-bot" - + # Optional: Allow Claude to run specific commands # allowed_tools: "Bash(npm install),Bash(npm run build),Bash(npm run test:*),Bash(npm run lint:*)" - + # Optional: Add custom instructions for Claude to customize its behavior for your project # custom_instructions: | # Follow our coding standards # Ensure all new code has tests # Use TypeScript for new files - + # Optional: Custom environment variables for Claude # claude_env: | # NODE_ENV: test - From 9a194e596458a5af43ff028b6f99ded3e72d81e3 Mon Sep 17 00:00:00 2001 From: lawvs <18554747+lawvs@users.noreply.github.com> Date: Mon, 14 Jul 2025 16:53:13 +0800 Subject: [PATCH 014/111] fix: improve image performance --- apps/mobile/src/components/ui/image/utils.ts | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/apps/mobile/src/components/ui/image/utils.ts b/apps/mobile/src/components/ui/image/utils.ts index 0486cb78a..1f10bb744 100644 --- a/apps/mobile/src/components/ui/image/utils.ts +++ b/apps/mobile/src/components/ui/image/utils.ts @@ -38,6 +38,7 @@ export const getAllSources = ( }, ) => { if (!isImageSourceWithUri(source)) { + console.warn("Invalid image source", source) return [undefined, undefined] as const } @@ -45,6 +46,8 @@ export const getAllSources = ( source.uri = source.uri.replace("http://", "https://") const safeSource: ImageProps["source"] = { + width: proxy?.width, + height: proxy?.height, ...source, headers: { ...buildSafeHeaders({ url: source.uri }), @@ -58,13 +61,15 @@ export const getAllSources = ( } return { + width: proxy?.width, + height: proxy?.height, ...safeSource, uri: getImageProxyUrl({ url: source.uri, width: proxy?.width ? proxy?.width * 3 : undefined, height: proxy?.height ? proxy?.height * 3 : undefined, }), - } + } satisfies ImageProps["source"] })() return [safeSource, proxiesSafeSource] as const @@ -74,9 +79,8 @@ const getImageData = async (imageUrl: string) => { let size = await Image.getSize(imageUrl) // Workaround for Android where the size returned by Image.getSize is not accurate for remote images - // https://github.com/facebook/react-native/issues/33498 + // Learn more https://github.com/facebook/react-native/issues/33498 if (isAndroid) { - // If the image is not a remote URL, we can use the local file path directly size = { width: size.width * 10, height: size.height * 10, From 2c579c1e830df192c6a93dc5c5c15694138adeee Mon Sep 17 00:00:00 2001 From: Stephen Zhou <38493346+hyoban@users.noreply.github.com> Date: Mon, 14 Jul 2025 16:55:08 +0800 Subject: [PATCH 015/111] fix(android): can not open video in external app (#4172) --- .../src/modules/entry-list/templates/EntryVideoItem.tsx | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/apps/mobile/src/modules/entry-list/templates/EntryVideoItem.tsx b/apps/mobile/src/modules/entry-list/templates/EntryVideoItem.tsx index b48c7beca..c4793bc8d 100644 --- a/apps/mobile/src/modules/entry-list/templates/EntryVideoItem.tsx +++ b/apps/mobile/src/modules/entry-list/templates/EntryVideoItem.tsx @@ -130,8 +130,7 @@ const openVideo = async (url: string) => { if (openLinksInExternalApp) { const schemeLink = parseSchemeLink(url) try { - const isInstalled = !!schemeLink && (await Linking.canOpenURL(schemeLink)) - if (schemeLink && isInstalled) { + if (schemeLink) { await Linking.openURL(schemeLink) return } @@ -141,6 +140,6 @@ const openVideo = async (url: string) => { } // Fallback to opening in in-app browser - const formattedUrl = transformVideoUrl({ url }) || url + const formattedUrl = openLinksInExternalApp ? url : transformVideoUrl({ url }) || url openLink(formattedUrl) } From e803fa3d210a7939462686c7fc57bb30a6e8170f Mon Sep 17 00:00:00 2001 From: Stephen Zhou <38493346+hyoban@users.noreply.github.com> Date: Mon, 14 Jul 2025 16:59:58 +0800 Subject: [PATCH 016/111] chore: remove unused patch for expo-image --- patches/expo-image.patch | 13 ------------- pnpm-lock.yaml | 7 ++----- pnpm-workspace.yaml | 1 - 3 files changed, 2 insertions(+), 19 deletions(-) delete mode 100644 patches/expo-image.patch diff --git a/patches/expo-image.patch b/patches/expo-image.patch deleted file mode 100644 index 32fa6bbc3..000000000 --- a/patches/expo-image.patch +++ /dev/null @@ -1,13 +0,0 @@ -diff --git a/ios/ImageView.swift b/ios/ImageView.swift -index 2ab4cba8309c79e1bff903766e0013d17a3f382e..a93991bc7358cc7f1f5bca2f5f1e9650e36a24db 100644 ---- a/ios/ImageView.swift -+++ b/ios/ImageView.swift -@@ -249,7 +249,7 @@ public final class ImageView: ExpoView { - return nil - }() - -- if let path, let local = UIImage(named: path) { -+ if let path, !path.isEmpty, let local = UIImage(named: path) { - renderSourceImage(local) - return true - } diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 288c4db22..5fa1c23d5 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -39,9 +39,6 @@ patchedDependencies: electron-context-menu@4.0.5: hash: 15ed04a0d246eb9e701f47314b91328c64a8a7374914ad58b4053a3f84075fab path: patches/electron-context-menu@4.0.5.patch - expo-image: - hash: 2b9c83844cf8c4240bda8315b7bbe20908929272eca362f1b7f52728071ae446 - path: patches/expo-image.patch hono: hash: 5c74c2d2afaa5880c13d75458dd26c84da568851691b1fb6de6d877c29936d05 path: patches/hono.patch @@ -885,7 +882,7 @@ importers: version: 2.5.0(expo@53.0.12(@babel/core@7.28.0)(@expo/metro-runtime@5.0.4(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0)))(bufferutil@4.0.9)(graphql@16.8.1)(react-native-webview@13.15.0(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0) expo-image: specifier: 2.3.2 - version: 2.3.2(patch_hash=2b9c83844cf8c4240bda8315b7bbe20908929272eca362f1b7f52728071ae446)(expo@53.0.12(@babel/core@7.28.0)(@expo/metro-runtime@5.0.4(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0)))(bufferutil@4.0.9)(graphql@16.8.1)(react-native-webview@13.15.0(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(react-native-web@0.20.0(encoding@0.1.13)(react-dom@19.0.0(react@19.0.0))(react@19.0.0))(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0) + version: 2.3.2(expo@53.0.12(@babel/core@7.28.0)(@expo/metro-runtime@5.0.4(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0)))(bufferutil@4.0.9)(graphql@16.8.1)(react-native-webview@13.15.0(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(react-native-web@0.20.0(encoding@0.1.13)(react-dom@19.0.0(react@19.0.0))(react@19.0.0))(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0) expo-image-manipulator: specifier: 13.1.7 version: 13.1.7(expo@53.0.12(@babel/core@7.28.0)(@expo/metro-runtime@5.0.4(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0)))(bufferutil@4.0.9)(graphql@16.8.1)(react-native-webview@13.15.0(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0)) @@ -24987,7 +24984,7 @@ snapshots: expo: 53.0.12(@babel/core@7.28.0)(@expo/metro-runtime@5.0.4(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0)))(bufferutil@4.0.9)(graphql@16.8.1)(react-native-webview@13.15.0(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0) expo-image-loader: 5.1.0(expo@53.0.12(@babel/core@7.28.0)(@expo/metro-runtime@5.0.4(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0)))(bufferutil@4.0.9)(graphql@16.8.1)(react-native-webview@13.15.0(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0)) - expo-image@2.3.2(patch_hash=2b9c83844cf8c4240bda8315b7bbe20908929272eca362f1b7f52728071ae446)(expo@53.0.12(@babel/core@7.28.0)(@expo/metro-runtime@5.0.4(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0)))(bufferutil@4.0.9)(graphql@16.8.1)(react-native-webview@13.15.0(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(react-native-web@0.20.0(encoding@0.1.13)(react-dom@19.0.0(react@19.0.0))(react@19.0.0))(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0): + expo-image@2.3.2(expo@53.0.12(@babel/core@7.28.0)(@expo/metro-runtime@5.0.4(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0)))(bufferutil@4.0.9)(graphql@16.8.1)(react-native-webview@13.15.0(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(react-native-web@0.20.0(encoding@0.1.13)(react-dom@19.0.0(react@19.0.0))(react@19.0.0))(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0): dependencies: expo: 53.0.12(@babel/core@7.28.0)(@expo/metro-runtime@5.0.4(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0)))(bufferutil@4.0.9)(graphql@16.8.1)(react-native-webview@13.15.0(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0))(react-native@0.79.1(@babel/core@7.28.0)(@types/react@19.1.8)(bufferutil@4.0.9)(react@19.0.0))(react@19.0.0) react: 19.0.0 diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml index f1e1888c8..17a57a945 100644 --- a/pnpm-workspace.yaml +++ b/pnpm-workspace.yaml @@ -39,7 +39,6 @@ patchedDependencies: react-native-track-player: "patches/react-native-track-player.patch" react-native-sheet-transitions: "patches/react-native-sheet-transitions.patch" react-native-screens: "patches/react-native-screens.patch" - expo-image: "patches/expo-image.patch" react-native-ios-utilities: "patches/react-native-ios-utilities.patch" "@sentry/electron": "patches/@sentry__electron.patch" overrides: From c3ed8eeb2df4ef9840ce9bc374b7a9b75ff3e9b6 Mon Sep 17 00:00:00 2001 From: Cason Kervis Date: Mon, 14 Jul 2025 17:08:38 +0800 Subject: [PATCH 017/111] feat: hide view count when hideRecentReader is on (#4167) --- .../modules/entry-content/components/EntryTitle.tsx | 4 +++- .../(stack)/entries/[entryId]/EntryDetailScreen.tsx | 11 ++++++++++- locales/settings/en.json | 4 ++-- locales/settings/zh-CN.json | 4 ++-- plugins/eslint/eslint-check-i18n-json.js | 6 ++++-- 5 files changed, 21 insertions(+), 8 deletions(-) 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 872f43dde..e5ddcac10 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 @@ -65,6 +65,8 @@ export const EntryTitle = ({ entryId, compact }: EntryLinkProps) => { const navigateEntry = useNavigateEntry() + const hideRecentReader = useUISettingKey("hideRecentReader") + if (!entry) return null return compact ? ( @@ -132,7 +134,7 @@ export const EntryTitle = ({ entryId, compact }: EntryLinkProps) => { (entryHistory?.readCount ?? 0) + (entryHistory?.userIds?.every((id) => id !== user?.id) ? 1 : 0) - return readCount > 0 ? ( + return readCount > 0 && !hideRecentReader ? (
{readCount.toLocaleString()} diff --git a/apps/mobile/src/screens/(stack)/entries/[entryId]/EntryDetailScreen.tsx b/apps/mobile/src/screens/(stack)/entries/[entryId]/EntryDetailScreen.tsx index 128923df4..2a753ab81 100644 --- a/apps/mobile/src/screens/(stack)/entries/[entryId]/EntryDetailScreen.tsx +++ b/apps/mobile/src/screens/(stack)/entries/[entryId]/EntryDetailScreen.tsx @@ -1,5 +1,5 @@ import { FeedViewType } from "@follow/constants" -import { useEntry, usePrefetchEntryDetail } from "@follow/store/entry/hooks" +import { useEntry, useEntryReadHistory, usePrefetchEntryDetail } from "@follow/store/entry/hooks" import { entrySyncServices } from "@follow/store/entry/store" import { useFeedById } from "@follow/store/feed/hooks" import { usePrefetchEntryTranslation } from "@follow/store/translation/hooks" @@ -12,6 +12,7 @@ import { useSafeAreaInsets } from "react-native-safe-area-context" import { useColor } from "react-native-uikit-colors" import { useActionLanguage, useGeneralSettingKey } from "@/src/atoms/settings/general" +import { useUISettingKey } from "@/src/atoms/settings/ui" import { BottomTabBarHeightContext } from "@/src/components/layouts/tabbar/contexts/BottomTabBarHeightContext" import { SafeNavigationScrollView } from "@/src/components/layouts/views/SafeNavigationScrollView" import { EntryContentWebView } from "@/src/components/native/webview/EntryContentWebView" @@ -181,6 +182,9 @@ const EntryInfo = ({ entryId }: { entryId: string }) => { const feed = useFeedById(entry?.feedId) const secondaryLabelColor = useColor("secondaryLabel") + const readCount = useEntryReadHistory(entryId)?.entryReadHistories?.readCount + const hideRecentReader = useUISettingKey("hideRecentReader") + if (!entry) return null const { publishedAt } = entry @@ -202,6 +206,11 @@ const EntryInfo = ({ entryId }: { entryId: string }) => { className="text-secondary-label text-sm leading-tight" /> + {!hideRecentReader && ( + + {readCount} + + )} ) } diff --git a/locales/settings/en.json b/locales/settings/en.json index 47d4602f0..d1083e9c0 100644 --- a/locales/settings/en.json +++ b/locales/settings/en.json @@ -120,8 +120,8 @@ "appearance.guess_code_language.label": "Guess Code Language", "appearance.hide_extra_badge.description": "Hide the Special Badge of the Feed in the Sidebar, e.g. Boost, Claimed", "appearance.hide_extra_badge.label": "Hide Special Badge", - "appearance.hide_recent_reader.description": "Hide the Recent Reader in the Entry Header.", - "appearance.hide_recent_reader.label": "Hide Recent Reader", + "appearance.hide_recent_reader.description": "Hide the Recent Reader and View Count in the Entry.", + "appearance.hide_recent_reader.label": "Hide Recent Readers & View Count", "appearance.interface_window.title": "Interface & Window", "appearance.misc": "Misc", "appearance.modal_overlay.description": "Show Modal Overlay", diff --git a/locales/settings/zh-CN.json b/locales/settings/zh-CN.json index 06c7c71ce..64a82612c 100644 --- a/locales/settings/zh-CN.json +++ b/locales/settings/zh-CN.json @@ -120,8 +120,8 @@ "appearance.guess_code_language.label": "代码语言检测", "appearance.hide_extra_badge.description": "将侧边栏中订阅源的特殊徽章隐藏,例如:已助力,已认证", "appearance.hide_extra_badge.label": "隐藏徽章", - "appearance.hide_recent_reader.description": "隐藏条目标题显示的最近阅读者。", - "appearance.hide_recent_reader.label": "隐藏最近阅读者", + "appearance.hide_recent_reader.description": "隐藏条目标题显示的最近阅读者与阅读数。", + "appearance.hide_recent_reader.label": "隐藏最近阅读者与阅读数", "appearance.interface_window.title": "界面与窗口", "appearance.misc": "杂项", "appearance.modal_overlay.description": "显示遮罩以获得更好的使用体验,推荐开启。", diff --git a/plugins/eslint/eslint-check-i18n-json.js b/plugins/eslint/eslint-check-i18n-json.js index 7b3496c19..71ec3e644 100644 --- a/plugins/eslint/eslint-check-i18n-json.js +++ b/plugins/eslint/eslint-check-i18n-json.js @@ -2,7 +2,7 @@ /** @type {import("eslint").ESLint.Plugin} */ import fs from "node:fs" -import path from "pathe" +import path, { normalize, sep } from "pathe" import { cleanJsonText } from "../utils.js" @@ -84,7 +84,8 @@ export default { if (!filename.endsWith(".json")) return - const parts = filename.split(path.sep) + const parts = normalize(filename).split(sep) + // @ts-ignore const lang = parts.at(-1).split(".")[0] const namespace = parts.at(-2) @@ -95,6 +96,7 @@ export default { try { currentJson = JSON.parse(sourceCode.text) + // @ts-ignore const englishFilePath = path.join(path.dirname(filename), "../", namespace, "en.json") englishJson = JSON.parse(fs.readFileSync(englishFilePath, "utf8")) } catch (error) { From 6d0f9ce6228023fd992c95128590fbc309cc3b3e Mon Sep 17 00:00:00 2001 From: Stephen Zhou <38493346+hyoban@users.noreply.github.com> Date: Mon, 14 Jul 2025 18:06:56 +0800 Subject: [PATCH 018/111] chore(desktop): allow delete user, close #4139 --- .../src/pages/settings/(settings)/profile.tsx | 62 +++++++++---------- 1 file changed, 29 insertions(+), 33 deletions(-) diff --git a/apps/desktop/layer/renderer/src/pages/settings/(settings)/profile.tsx b/apps/desktop/layer/renderer/src/pages/settings/(settings)/profile.tsx index 66df78868..10a1315df 100644 --- a/apps/desktop/layer/renderer/src/pages/settings/(settings)/profile.tsx +++ b/apps/desktop/layer/renderer/src/pages/settings/(settings)/profile.tsx @@ -2,7 +2,6 @@ import { Button } from "@follow/components/ui/button/index.js" import { Divider } from "@follow/components/ui/divider/Divider.js" import { Label } from "@follow/components/ui/label/index.js" -import { useIsInMASReview } from "~/atoms/server-configs" import { useModalStack } from "~/components/ui/modal/stacked/hooks" import { AccountManagement } from "~/modules/profile/account-management" import { EmailManagement } from "~/modules/profile/email-management" @@ -24,7 +23,6 @@ export const loader = defineSettingPageData({ export function Component() { const { present } = useModalStack() - const isInMASReview = useIsInMASReview() const preset = useTOTPModalWrapper(deleteUser, { force: true }) return ( <> @@ -39,37 +37,35 @@ export function Component() { - {isInMASReview && ( -
- - -
- ), - }) - }} - > - Delete - -
- )} +
+ + +
+ ), + }) + }} + > + Delete + +
From a8cfabc86976bed078e0a4284b40d7428dbff079 Mon Sep 17 00:00:00 2001 From: Innei Date: Mon, 14 Jul 2025 18:56:08 +0800 Subject: [PATCH 019/111] feat: add CLAUDE.md for project guidance and architecture details Signed-off-by: Innei --- CLAUDE.md | 234 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 234 insertions(+) create mode 100644 CLAUDE.md diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 000000000..6e91955f0 --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,234 @@ +# CLAUDE.md + +This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository. + +## Project Overview + +Follow (Folo) is a modern RSS aggregator and content management platform with multiple applications across different platforms. It's built as a monorepo using pnpm workspaces with Turbo for build orchestration. + +## Repository Structure + +### Applications (`apps/`) + +- **`apps/desktop/`** - Electron desktop application with main and renderer processes +- **`apps/mobile/`** - React Native mobile app for iOS and Android +- **`apps/ssr/`** - Server-side rendered web application +- **`apps/mobile/web-app/`** - HTML renderer for mobile web views + +### Packages (`packages/`) + +- **`packages/internal/`** - Internal shared packages (components, database, hooks, store, etc.) +- **`packages/configs/`** - Shared configuration files (Tailwind, TypeScript) +- **`packages/utils/`** - Utility functions and helpers +- **`packages/readability/`** - Content readability parsing +- **`packages/vite-plugin-route-builder/`** - Custom Vite plugin for route generation + +## Essential Commands + +### Development + +```bash +# Install dependencies (from root) +pnpm install + +# Desktop app development (browser - recommended) +cd apps/desktop && pnpm run dev:web + +# Desktop app development (Electron) +cd apps/desktop && pnpm run dev:electron + +# Mobile app development +cd apps/mobile && pnpm run dev + +# SSR development +cd apps/ssr && pnpm run dev + +# Build web version +pnpm run build:web +``` + +### Code Quality + +```bash +# Lint all code +pnpm run lint + +# Fix linting issues +pnpm run lint:fix + +# TypeScript linting +pnpm run lint:tsl + +# Format code +pnpm run format + +# Type checking +pnpm run typecheck + +# Run tests +pnpm run test +``` + +### Package Management + +```bash +# Build shared packages +pnpm run build:packages + +# Generate i18n templates +pnpm run generator:i18n-template + +# Sync icons from SVG to React Native +pnpm run icons:sync +``` + +## Architecture Guidelines + +### Multi-Platform Architecture + +- **Desktop**: Electron app with main/renderer processes, using Vite for both +- **Mobile**: React Native with Expo, shared UI components with web +- **Web/SSR**: Next.js-style SSR application for server-side rendering +- **Shared Logic**: Common business logic in `packages/internal/` + +### State Management + +- **Jotai** for atomic state management across all platforms +- **Zustand** for complex state stores (in `packages/internal/store/`) +- **React Query** for server state management + +### Styling + +- **Tailwind CSS** for styling across all platforms +- Platform-specific Tailwind configs in each app +- Shared Tailwind utilities in `packages/configs/tailwindcss/` +- **UI Design Style**: Follow Vercel and Linear SaaS UI aesthetics - clean, modern, minimal design with subtle shadows, rounded corners, and excellent typography + +#### UIKit Colors for Desktop Components + +For desktop components (`apps/desktop/**/*`) and shared UI components (`packages/internal/components/**/*`), use Apple UIKit color system with Tailwind classes. **Important**: Always use the correct Tailwind prefix for each color category: + +**System Colors**: `text-red`, `bg-red`, `border-red` (same for `orange`, `yellow`, `green`, `mint`, `teal`, `cyan`, `blue`, `indigo`, `purple`, `pink`, `brown`, `gray`) + +**Fill Colors**: + +- Background: `bg-fill`, `bg-fill-secondary`, `bg-fill-tertiary`, `bg-fill-quaternary`, `bg-fill-quinary`, `bg-fill-vibrant`, `bg-fill-vibrant-secondary`, `bg-fill-vibrant-tertiary`, `bg-fill-vibrant-quaternary`, `bg-fill-vibrant-quinary` +- Border: `border-fill`, `border-fill-secondary`, etc. + +**Text Colors**: `text-text`, `text-text-secondary`, `text-text-tertiary`, `text-text-quaternary`, `text-text-quinary`, `text-text-vibrant`, `text-text-vibrant-secondary`, `text-text-vibrant-tertiary`, `text-text-vibrant-quaternary`, `text-text-vibrant-quinary` + +**Material Colors**: `bg-material-ultra-thick`, `bg-material-thick`, `bg-material-medium`, `bg-material-thin`, `bg-material-ultra-thin`, `bg-material-opaque` + +**Control Colors**: `bg-control-enabled`, `bg-control-disabled` + +**Interface Colors**: `bg-menu`, `bg-popover`, `bg-titlebar`, `bg-sidebar`, `bg-selection-focused`, `bg-selection-focused-fill`, `bg-selection-unfocused`, `bg-selection-unfocused-fill`, `bg-header-view`, `bg-tooltip`, `bg-under-window-background` + +These colors automatically adapt to light/dark mode following Apple's design system. Remember to use the appropriate prefix (`text-`, `bg-`, `border-`) based on the CSS property you're styling. + +#### Icons + +For icon usage, prioritize the MingCute icon library with the `i-mgc-` prefix. Icons are available in the format `i-mgc-[icon-name]-[style]` where style can be `re` (regular), `fi` (filled), etc. + +**Important**: Always try to find an appropriate icon with the `i-mgc-` prefix first. Only use the `i-mingcute-` prefix as a fallback when no suitable `i-mgc-` icon exists. + +Examples: + +- Preferred: `i-mgc-copy-cute-re`, `i-mgc-external-link-cute-re` +- Fallback only: `i-mingcute-copy-line` (only if no mgc equivalent exists) + +### Database + +- **Drizzle ORM** with SQLite for local data storage +- Platform-specific database implementations in `packages/internal/database/` +- Migration system with versioned SQL files + +### Internationalization + +- **i18next** for internationalization +- Locale files in `locales/` directory organized by feature +- Custom ESLint rules for i18n validation + +#### i18n Writing Guidelines + +1. Follow [i18next formatting guidelines](https://www.i18next.com/translation-function/formatting) +2. **Use flat keys only** - Use `.` notation for separation, no nested objects +3. For plural-sensitive languages, use `_one` and `_other` suffixes +4. **Avoid conflicting flat keys** - During build, flat dot-separated keys (e.g., 'exif.custom.rendered.custom') are automatically converted to nested objects, which can cause conflicts. For example, 'exif.custom.rendered.custom' conflicts with 'exif.custom.rendered'. Avoid such patterns. + +Example: + +```json +{ + "personalize.title": "Personalization", + "personalize.prompt.label": "Personal Prompt", + "shortcuts.add": "Add Shortcut", + "shortcuts.validation.required": "Name and prompt are required" +} +``` + +## Development Setup Notes + +### Prerequisites + +- Enable Corepack: `corepack enable && corepack prepare` +- For mobile development: macOS with Xcode required + +### Environment Setup + +- Copy `.env.example` to `.env` in relevant app directories +- For development, use `VITE_API_URL=https://api.follow.is` +- Browser development uses `https://app.folo.is/__debug_proxy` for API access + +### Mobile Development + +- iOS development requires Xcode and iOS simulator +- Native module development in `apps/mobile/native/` +- Use `pnpm expo prebuild --clean` for clean builds + +## Code Organization Patterns + +### Import Conventions + +- Use `pathe` instead of `node:path` for cross-platform compatibility +- Shared utilities should be imported from `packages/internal/` +- Platform-specific code should be clearly separated + +### Component Structure + +- Shared UI components in `packages/internal/components/` +- Platform-specific components in respective app directories +- Use TypeScript interfaces for component props + +### Error Handling + +- Custom error parsing utilities in `packages/internal/utils/` +- Sentry integration for error reporting across platforms + +## Build and Deployment + +### Build Outputs + +- Desktop: `apps/desktop/out/` for packaged applications +- Web: `apps/desktop/out/web/` for static web assets +- Mobile: Platform-specific build directories + +### Turbo Configuration + +- Build orchestration via `turbo.json` +- Dependency-aware builds with output caching +- Parallel execution for independent packages + +## Testing Strategy + +- Vitest for unit testing across packages +- Platform-specific test configurations +- Test files co-located with source code + +## Key Dependencies + +- **Build**: Vite, Turbo, pnpm workspaces +- **Frontend**: React 19, Electron, React Native, Expo +- **State**: Jotai, Zustand, TanStack Query +- **Styling**: Tailwind CSS, Framer Motion +- **Database**: Drizzle ORM, SQLite +- **Utils**: Day.js, Zod, i18next From 4ebff4d35d683c1d3ae23623fb57799c251db901 Mon Sep 17 00:00:00 2001 From: DIYgod Date: Mon, 14 Jul 2025 18:59:41 +0800 Subject: [PATCH 020/111] feat(mobile): improve entry list loading states MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Add skeleton loading states for all entry list view types (Articles, Pictures, Social, Videos) - Show loading skeleton when entries are not ready and no data yet - Add proper padding to avoid overlap with header and tab bar - Create realistic skeletons that match actual entry item structures: - Articles: 7 items with title, description, and image placeholders - Pictures: 8 items (4 per column) with varied heights and footer content - Social: 5 items with social-specific layout - Videos: 6 items (3 per column) with video thumbnail and metadata - Improve UX by showing loading state instead of empty message during data fetch 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude --- .../entry-list/EntryListContentArticle.tsx | 18 ++++- .../entry-list/EntryListContentPicture.tsx | 66 +++++++++++++++++-- .../entry-list/EntryListContentSocial.tsx | 18 ++++- .../entry-list/EntryListContentVideo.tsx | 64 ++++++++++++++++-- apps/mobile/src/modules/screen/atoms.ts | 5 +- 5 files changed, 160 insertions(+), 11 deletions(-) diff --git a/apps/mobile/src/modules/entry-list/EntryListContentArticle.tsx b/apps/mobile/src/modules/entry-list/EntryListContentArticle.tsx index 14d5ef083..55161452f 100644 --- a/apps/mobile/src/modules/entry-list/EntryListContentArticle.tsx +++ b/apps/mobile/src/modules/entry-list/EntryListContentArticle.tsx @@ -6,8 +6,10 @@ import { useCallback, useImperativeHandle, useMemo } from "react" import { View } from "react-native" import { useActionLanguage, useGeneralSettingKey } from "@/src/atoms/settings/general" +import { useBottomTabBarHeight } from "@/src/components/layouts/tabbar/hooks" import { usePlayingUrl } from "@/src/lib/player" import { checkLanguage } from "@/src/lib/translation" +import { useHeaderHeight } from "@/src/modules/screen/hooks/useHeaderHeight" import { useEntries } from "../screen/atoms" import { TimelineSelectorList } from "../screen/TimelineSelectorList" @@ -31,7 +33,7 @@ export const EntryListContentArticle = ({ [playingAudioUrl, entryIds], ) - const { fetchNextPage, isFetching, refetch, isRefetching, hasNextPage, fetchedTime } = + const { fetchNextPage, isFetching, refetch, isRefetching, hasNextPage, fetchedTime, isReady } = useEntries() const renderItem = useCallback( @@ -64,6 +66,20 @@ export const EntryListContentArticle = ({ checkLanguage, }) + const headerHeight = useHeaderHeight() + const tabBarHeight = useBottomTabBarHeight() + + // Show loading skeleton when entries are not ready and no data yet + if (!isReady && (!entryIds || entryIds.length === 0)) { + return ( + + {Array.from({ length: 7 }).map((_, index) => ( + + ))} + + ) + } + return ( & { ref?: React.Ref | null> }) => { const { onScroll: hackOnScroll, ref, style: hackStyle } = usePagerListPerformanceHack() useImperativeHandle(forwardRef, () => ref.current!) - const { fetchNextPage, refetch, isRefetching, hasNextPage, isFetching } = useEntries() + const { fetchNextPage, refetch, isRefetching, hasNextPage, isFetching, isReady } = useEntries() const { onViewableItemsChanged, onScroll, viewableItems } = useOnViewableItemsChanged({ disabled: active === false || isFetching, onScroll: hackOnScroll, @@ -41,14 +43,42 @@ export const EntryListContentPicture = ({ translation, }) + const renderItem = useTypeScriptHappyCallback(({ item }: { item: string }) => { + return + }, []) + + const headerHeight = useHeaderHeight() + const tabBarHeight = useBottomTabBarHeight() + + // Show loading skeleton when entries are not ready and no data yet + if (!isReady && (!entryIds || entryIds.length === 0)) { + return ( + + + + {Array.from({ length: 4 }).map((_, index) => ( + + ))} + + + {Array.from({ length: 4 }).map((_, index) => ( + + ))} + + + + ) + } + return ( { - return - }, [])} + renderItem={renderItem} keyExtractor={defaultKeyExtractor} onViewableItemsChanged={onViewableItemsChanged} onScroll={onScroll} @@ -72,6 +102,34 @@ export const EntryListContentPicture = ({ ) } +function EntryPictureItemSkeleton() { + const heights = [120, 160, 140, 180, 100, 200] // Different heights for variety + const randomHeight = heights[Math.floor(Math.random() * heights.length)] + + return ( + + {/* Image placeholder */} + + + {/* Footer content */} + + {/* Title lines */} + + + + + + {/* Feed info */} + + + + + + + + ) +} + const styles = StyleSheet.create({ contentContainer: { paddingHorizontal: 8, diff --git a/apps/mobile/src/modules/entry-list/EntryListContentSocial.tsx b/apps/mobile/src/modules/entry-list/EntryListContentSocial.tsx index 721ef59e0..6799ba2d3 100644 --- a/apps/mobile/src/modules/entry-list/EntryListContentSocial.tsx +++ b/apps/mobile/src/modules/entry-list/EntryListContentSocial.tsx @@ -5,7 +5,9 @@ import { useCallback, useImperativeHandle, useMemo } from "react" import { View } from "react-native" import { useActionLanguage, useGeneralSettingKey } from "@/src/atoms/settings/general" +import { useBottomTabBarHeight } from "@/src/components/layouts/tabbar/hooks" import { checkLanguage } from "@/src/lib/translation" +import { useHeaderHeight } from "@/src/modules/screen/hooks/useHeaderHeight" import { useEntries } from "../screen/atoms" import { TimelineSelectorList } from "../screen/TimelineSelectorList" @@ -22,7 +24,7 @@ export const EntryListContentSocial = ({ }: { entryIds: string[] | null; active?: boolean } & { ref?: React.Ref | null> }) => { - const { fetchNextPage, isFetching, refetch, isRefetching, hasNextPage } = useEntries() + const { fetchNextPage, isFetching, refetch, isRefetching, hasNextPage, isReady } = useEntries() const extraData: EntryExtraData = useMemo(() => ({ playingAudioUrl: null, entryIds }), [entryIds]) const { onScroll: hackOnScroll, ref, style: hackStyle } = usePagerListPerformanceHack() @@ -54,6 +56,20 @@ export const EntryListContentSocial = ({ checkLanguage, }) + const headerHeight = useHeaderHeight() + const tabBarHeight = useBottomTabBarHeight() + + // Show loading skeleton when entries are not ready and no data yet + if (!isReady && (!entryIds || entryIds.length === 0)) { + return ( + + {Array.from({ length: 5 }).map((_, index) => ( + + ))} + + ) + } + return ( & { ref?: React.Ref | null> }) => { const { onScroll: hackOnScroll, ref, style: hackStyle } = usePagerListPerformanceHack() useImperativeHandle(forwardRef, () => ref.current!) - const { fetchNextPage, refetch, isRefetching, isFetching, hasNextPage } = useEntries() + const { fetchNextPage, refetch, isRefetching, isFetching, hasNextPage, isReady } = useEntries() const { onViewableItemsChanged, onScroll, viewableItems } = useOnViewableItemsChanged({ disabled: active === false || isFetching, onScroll: hackOnScroll, @@ -53,14 +55,42 @@ export const EntryListContentVideo = ({ [hasNextPage], ) + const renderItem = useTypeScriptHappyCallback(({ item }: { item: string }) => { + return + }, []) + + const headerHeight = useHeaderHeight() + const tabBarHeight = useBottomTabBarHeight() + + // Show loading skeleton when entries are not ready and no data yet + if (!isReady && (!entryIds || entryIds.length === 0)) { + return ( + + + + {Array.from({ length: 3 }).map((_, index) => ( + + ))} + + + {Array.from({ length: 3 }).map((_, index) => ( + + ))} + + + + ) + } + return ( { - return - }, [])} + renderItem={renderItem} keyExtractor={defaultKeyExtractor} onViewableItemsChanged={onViewableItemsChanged} onScroll={onScroll} @@ -86,6 +116,32 @@ const defaultKeyExtractor = (item: string) => { return item } +function EntryVideoItemSkeleton() { + return ( + + {/* Video thumbnail */} + + + {/* Description and footer */} + + {/* Description */} + + + + {/* Footer with feed icon and metadata */} + + + + + + + + ) +} + export function EntryItemSkeleton() { return ( diff --git a/apps/mobile/src/modules/screen/atoms.ts b/apps/mobile/src/modules/screen/atoms.ts index 384430f21..d8fc667aa 100644 --- a/apps/mobile/src/modules/screen/atoms.ts +++ b/apps/mobile/src/modules/screen/atoms.ts @@ -332,7 +332,10 @@ export function useEntries(props?: UseEntriesProps): UseEntriesReturn { const remoteQuery = useRemoteEntries({ viewId, active }) const localQuery = useLocalEntries({ viewId, active }) const query = remoteQuery.isReady ? remoteQuery : localQuery - return query + return { + ...query, + isReady: remoteQuery.isReady, + } } export const useSelectedFeedTitle = () => { From e7c8380647e2f9712a53dc1a68629f59091df26f Mon Sep 17 00:00:00 2001 From: DIYgod Date: Mon, 14 Jul 2025 19:37:00 +0800 Subject: [PATCH 021/111] fix(mobile): prevent incorrect read marking during pull-to-refresh MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The entry list was incorrectly marking entries as read during pull-to-refresh operations. This happened because when the refresh control rebounds from negative contentOffset back to 0, the scroll direction is detected as "down" causing entries to be mistakenly marked as read. The fix adds a condition to only mark entries as read when: 1. Scroll direction is down (user swiping up) 2. Current offset is greater than 0 (not at the top or rebounding) This ensures entries are only marked as read during genuine upward scrolling, not during pull-to-refresh rebounds. 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude --- apps/mobile/src/modules/entry-list/hooks.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/apps/mobile/src/modules/entry-list/hooks.ts b/apps/mobile/src/modules/entry-list/hooks.ts index 27b92e167..938846d94 100644 --- a/apps/mobile/src/modules/entry-list/hooks.ts +++ b/apps/mobile/src/modules/entry-list/hooks.ts @@ -47,7 +47,9 @@ export function useOnViewableItemsChanged({ ) const removed = changed.filter((item) => !item.isViewable) - if (orientation.current === "down") { + // Only when the scroll direction is down and the current offset is a positive number, is it marked as read. + // This can avoid misjudgment during the rebound of the pull-to-refresh (because the offset will change from negative to zero during the rebound). + if (orientation.current === "down" && lastOffset.current > 0) { setLastViewableItems(viewableItems) if (removed.length > 0) { setLastRemovedItems((prev) => { From 0f9aa59d6b3e6acc3e058405bc0eb015b8ea65b3 Mon Sep 17 00:00:00 2001 From: Cason Kervis Date: Mon, 14 Jul 2025 21:36:04 +0800 Subject: [PATCH 022/111] fix(icon): polished icon (#3956) * fix(icon): reoptimized icon * fix(compress): use svgo 4.0 compress * fix: add svg title * fix: update icon in Apps * fix: update icon in ssr * fix: optimize folo text svg * fix: optimize two icon * fix: optimize lots icons - change viewbox to 24 - merge path * fix: optimize many icon * fix: update mobile icons define * fix: optmize ArrowUndoCircle icon * fix: compress using svgo * fix: using icon in simple-icons * fix: optimize one icon * fix: change instapaper to vertical input * revert mgc icon compress * fix: fix style in ssr og * fix: change rss icon and folo icon same size --- apps/desktop/layer/renderer/public/icon.svg | 2 +- .../command/shortcuts/SettingShortcuts.tsx | 12 +- .../components/EntryPlaceholderLogo.tsx | 2 +- .../src/modules/settings/tabs/integration.tsx | 8 +- .../components/icons/OouiUserAnonymous.tsx | 11 +- .../src/components/icons/PhUsersBold.tsx | 4 +- apps/mobile/src/components/ui/logo/index.tsx | 50 ++---- apps/mobile/src/icons/add_cute_fi.tsx | 5 +- apps/ssr/public/icon.svg | 2 +- apps/ssr/src/router/og/__base.tsx | 46 ++--- .../src/icons/OouiUserAnonymous.tsx | 9 +- .../components/src/icons/PhCloudCheck.tsx | 10 +- .../components/src/icons/PhCloudWarning.tsx | 10 +- .../components/src/icons/PhCloudX.tsx | 10 +- .../internal/components/src/icons/empty.tsx | 28 +-- .../internal/components/src/icons/follow.tsx | 14 +- .../internal/components/src/icons/folo.tsx | 24 +-- .../components/src/icons/infinify.tsx | 4 +- .../internal/components/src/icons/logo.tsx | 34 ++-- .../internal/components/src/icons/resize.tsx | 5 +- .../internal/components/src/icons/user.tsx | 16 +- .../internal/components/src/icons/users.tsx | 10 +- .../ui/platform-icon/collections/cubox.tsx | 165 +----------------- .../ui/platform-icon/collections/eagle.tsx | 3 +- .../platform-icon/collections/instapaper.tsx | 5 +- .../ui/platform-icon/collections/obsidian.tsx | 11 +- .../ui/platform-icon/collections/outline.tsx | 3 +- .../ui/platform-icon/collections/readeck.tsx | 42 +---- .../ui/platform-icon/collections/readwise.tsx | 15 +- .../src/ui/platform-icon/collections/rss3.tsx | 4 +- .../ui/platform-icon/collections/zotero.tsx | 3 +- 31 files changed, 106 insertions(+), 461 deletions(-) diff --git a/apps/desktop/layer/renderer/public/icon.svg b/apps/desktop/layer/renderer/public/icon.svg index af834b050..b72ba156f 100644 --- a/apps/desktop/layer/renderer/public/icon.svg +++ b/apps/desktop/layer/renderer/public/icon.svg @@ -1 +1 @@ - +Folo \ No newline at end of file diff --git a/apps/desktop/layer/renderer/src/modules/command/shortcuts/SettingShortcuts.tsx b/apps/desktop/layer/renderer/src/modules/command/shortcuts/SettingShortcuts.tsx index b27175b31..6a7b49a74 100644 --- a/apps/desktop/layer/renderer/src/modules/command/shortcuts/SettingShortcuts.tsx +++ b/apps/desktop/layer/renderer/src/modules/command/shortcuts/SettingShortcuts.tsx @@ -326,19 +326,13 @@ const KeyRecorder: FC<{ ) } +// Icon from Famicons by Family - https://github.com/familyjs/famicons/blob/main/LICENSE function FamiconsArrowUndoCircle(props: SVGProps) { return ( - - {/* Icon from Famicons by Family - https://github.com/familyjs/famicons/blob/main/LICENSE */} + ) diff --git a/apps/desktop/layer/renderer/src/modules/entry-content/components/EntryPlaceholderLogo.tsx b/apps/desktop/layer/renderer/src/modules/entry-content/components/EntryPlaceholderLogo.tsx index 1768aed8d..329e07113 100644 --- a/apps/desktop/layer/renderer/src/modules/entry-content/components/EntryPlaceholderLogo.tsx +++ b/apps/desktop/layer/renderer/src/modules/entry-content/components/EntryPlaceholderLogo.tsx @@ -14,7 +14,7 @@ export const EntryPlaceholderLogo = () => { "text-text-secondary flex w-full min-w-0 flex-col items-center justify-center gap-1 px-12 pb-6 text-center text-lg font-medium duration-500" } > - +
{title}
) diff --git a/apps/desktop/layer/renderer/src/modules/settings/tabs/integration.tsx b/apps/desktop/layer/renderer/src/modules/settings/tabs/integration.tsx index 755e1495d..bb7b927de 100644 --- a/apps/desktop/layer/renderer/src/modules/settings/tabs/integration.tsx +++ b/apps/desktop/layer/renderer/src/modules/settings/tabs/integration.tsx @@ -107,16 +107,12 @@ export const SettingIntegration = () => { }), defineSettingItem("instapaperUsername", { label: t("integration.instapaper.username.label"), - componentProps: { - labelClassName: "w-[150px]", - }, + vertical: true, }), defineSettingItem("instapaperPassword", { label: t("integration.instapaper.password.label"), + vertical: true, type: "password", - componentProps: { - labelClassName: "w-[150px]", - }, }), { diff --git a/apps/mobile/src/components/icons/OouiUserAnonymous.tsx b/apps/mobile/src/components/icons/OouiUserAnonymous.tsx index d7a48d7b9..30675b983 100644 --- a/apps/mobile/src/components/icons/OouiUserAnonymous.tsx +++ b/apps/mobile/src/components/icons/OouiUserAnonymous.tsx @@ -1,14 +1,15 @@ import * as React from "react" import type { SvgProps } from "react-native-svg" -import Svg, { Circle, Path } from "react-native-svg" +import Svg, { Path } from "react-native-svg" export function OouiUserAnonymous(props: SvgProps & { size?: number; color?: string }) { const { size = 24, color = "currentColor", ...rest } = props return ( - - - - + + ) } diff --git a/apps/mobile/src/components/icons/PhUsersBold.tsx b/apps/mobile/src/components/icons/PhUsersBold.tsx index 0fe5581ad..6e10be33b 100644 --- a/apps/mobile/src/components/icons/PhUsersBold.tsx +++ b/apps/mobile/src/components/icons/PhUsersBold.tsx @@ -5,10 +5,10 @@ import Svg, { Path } from "react-native-svg" export function PhUsersBold(props: SvgProps & { size?: number; color?: string }) { const { size = 24, color = "currentColor", ...rest } = props return ( - + ) diff --git a/apps/mobile/src/components/ui/logo/index.tsx b/apps/mobile/src/components/ui/logo/index.tsx index a54b89f6c..2ba7e4e4a 100644 --- a/apps/mobile/src/components/ui/logo/index.tsx +++ b/apps/mobile/src/components/ui/logo/index.tsx @@ -1,35 +1,21 @@ import type { StyleProp, ViewStyle } from "react-native" import type { SvgProps } from "react-native-svg" -import Svg, { ClipPath, Defs, G, Mask, Path, Rect } from "react-native-svg" +import Svg, { Path } from "react-native-svg" import { accentColor } from "@/src/theme/colors" export const Logo: React.FC<{ color?: string } & SvgProps> = ({ color = accentColor, ...rest }) => { return ( - - - - - - - - - - + + Folo + + ) } @@ -38,14 +24,10 @@ export const FollowIcon: React.FC<{ color: string; style?: StyleProp color, style, }) => ( - - - - - - - - - + + ) diff --git a/apps/mobile/src/icons/add_cute_fi.tsx b/apps/mobile/src/icons/add_cute_fi.tsx index 71bd6081c..d52502e93 100644 --- a/apps/mobile/src/icons/add_cute_fi.tsx +++ b/apps/mobile/src/icons/add_cute_fi.tsx @@ -13,11 +13,10 @@ export const AddCuteFiIcon = ({ color = "#10161F", }: AddCuteFiIconProps) => { return ( - + ) diff --git a/apps/ssr/public/icon.svg b/apps/ssr/public/icon.svg index af834b050..b72ba156f 100644 --- a/apps/ssr/public/icon.svg +++ b/apps/ssr/public/icon.svg @@ -1 +1 @@ - +Folo \ No newline at end of file diff --git a/apps/ssr/src/router/og/__base.tsx b/apps/ssr/src/router/og/__base.tsx index ee58debb6..d5fd05762 100644 --- a/apps/ssr/src/router/og/__base.tsx +++ b/apps/ssr/src/router/og/__base.tsx @@ -75,7 +75,7 @@ export const OGCanvas = ({ children, seed }: { children: React.ReactNode; seed: {/* AI RSS */}
Follow everything in one place - +
@@ -98,11 +98,10 @@ export const OGCanvas = ({ children, seed }: { children: React.ReactNode; seed: function RSSIcon({ color }: { color: string }) { return ( - + ) @@ -110,19 +109,14 @@ function RSSIcon({ color }: { color: string }) { function FollowIcon() { return ( - - + - ) @@ -130,28 +124,10 @@ function FollowIcon() { function LogoText() { return ( - + - - - ) diff --git a/packages/internal/components/src/icons/OouiUserAnonymous.tsx b/packages/internal/components/src/icons/OouiUserAnonymous.tsx index 97608a8f7..a8d94db10 100644 --- a/packages/internal/components/src/icons/OouiUserAnonymous.tsx +++ b/packages/internal/components/src/icons/OouiUserAnonymous.tsx @@ -2,10 +2,11 @@ import type { SVGProps } from "react" export function OouiUserAnonymous(props: SVGProps) { return ( - - - - + + ) } diff --git a/packages/internal/components/src/icons/PhCloudCheck.tsx b/packages/internal/components/src/icons/PhCloudCheck.tsx index 39640f1f4..f8ccd9943 100644 --- a/packages/internal/components/src/icons/PhCloudCheck.tsx +++ b/packages/internal/components/src/icons/PhCloudCheck.tsx @@ -2,16 +2,10 @@ import type { SVGProps } from "react" export function PhCloudCheck(props: SVGProps) { return ( - + ) diff --git a/packages/internal/components/src/icons/PhCloudWarning.tsx b/packages/internal/components/src/icons/PhCloudWarning.tsx index e0b32c570..0353241c9 100644 --- a/packages/internal/components/src/icons/PhCloudWarning.tsx +++ b/packages/internal/components/src/icons/PhCloudWarning.tsx @@ -2,16 +2,10 @@ import type { SVGProps } from "react" export function PhCloudWarning(props: SVGProps) { return ( - + ) diff --git a/packages/internal/components/src/icons/PhCloudX.tsx b/packages/internal/components/src/icons/PhCloudX.tsx index 2abdaa7ac..e96718191 100644 --- a/packages/internal/components/src/icons/PhCloudX.tsx +++ b/packages/internal/components/src/icons/PhCloudX.tsx @@ -2,16 +2,10 @@ import type { SVGProps } from "react" export function PhCloudX(props: SVGProps) { return ( - + ) diff --git a/packages/internal/components/src/icons/empty.tsx b/packages/internal/components/src/icons/empty.tsx index 68facf3b4..d00115acb 100644 --- a/packages/internal/components/src/icons/empty.tsx +++ b/packages/internal/components/src/icons/empty.tsx @@ -2,32 +2,10 @@ import { cn } from "@follow/utils/utils" export const EmptyIcon: Component = ({ className }) => ( - - - - - + ) diff --git a/packages/internal/components/src/icons/follow.tsx b/packages/internal/components/src/icons/follow.tsx index 50310f552..3128b6f80 100644 --- a/packages/internal/components/src/icons/follow.tsx +++ b/packages/internal/components/src/icons/follow.tsx @@ -1,12 +1,8 @@ export const FollowIcon: Component = (props) => ( - - - - - - - - - + + ) diff --git a/packages/internal/components/src/icons/folo.tsx b/packages/internal/components/src/icons/folo.tsx index d818f6374..846fd11a1 100644 --- a/packages/internal/components/src/icons/folo.tsx +++ b/packages/internal/components/src/icons/folo.tsx @@ -2,30 +2,10 @@ export const Folo = ({ ref, ...props }: React.SVGProps & { ref?: React.Ref }) => ( - + - - - ) diff --git a/packages/internal/components/src/icons/infinify.tsx b/packages/internal/components/src/icons/infinify.tsx index 846ef0eb8..152ad8810 100644 --- a/packages/internal/components/src/icons/infinify.tsx +++ b/packages/internal/components/src/icons/infinify.tsx @@ -2,10 +2,10 @@ import type { SVGProps } from "react" export function CarbonInfinitySymbol(props: SVGProps) { return ( - + ) diff --git a/packages/internal/components/src/icons/logo.tsx b/packages/internal/components/src/icons/logo.tsx index c84939a7a..79051898d 100644 --- a/packages/internal/components/src/icons/logo.tsx +++ b/packages/internal/components/src/icons/logo.tsx @@ -2,29 +2,15 @@ export const Logo = ({ ref, ...props }: React.SVGProps & { ref?: React.Ref }) => ( - - - - - - - - - - + + Folo + + ) diff --git a/packages/internal/components/src/icons/resize.tsx b/packages/internal/components/src/icons/resize.tsx index dd8507a79..3566d5ad3 100644 --- a/packages/internal/components/src/icons/resize.tsx +++ b/packages/internal/components/src/icons/resize.tsx @@ -3,10 +3,7 @@ import type { SVGProps } from "react" export function LetsIconsResizeDownRightLight(props: SVGProps) { return ( - - - - + ) } diff --git a/packages/internal/components/src/icons/user.tsx b/packages/internal/components/src/icons/user.tsx index 926d681cd..9bdde42db 100644 --- a/packages/internal/components/src/icons/user.tsx +++ b/packages/internal/components/src/icons/user.tsx @@ -2,20 +2,10 @@ import type { SVGAttributes } from "react" export function UserArrowLeftIcon(props: SVGAttributes) { return ( - + ) diff --git a/packages/internal/components/src/icons/users.tsx b/packages/internal/components/src/icons/users.tsx index a6ce2a721..33de362cf 100644 --- a/packages/internal/components/src/icons/users.tsx +++ b/packages/internal/components/src/icons/users.tsx @@ -3,16 +3,10 @@ import * as React from "react" export function PhUsersBold(props: SVGProps) { return ( - + ) diff --git a/packages/internal/components/src/ui/platform-icon/collections/cubox.tsx b/packages/internal/components/src/ui/platform-icon/collections/cubox.tsx index 2373414e7..ea4264997 100644 --- a/packages/internal/components/src/ui/platform-icon/collections/cubox.tsx +++ b/packages/internal/components/src/ui/platform-icon/collections/cubox.tsx @@ -1,167 +1,12 @@ -import { cn } from "@follow/utils/utils" import type { SVGProps } from "react" export function SimpleIconsCubox({ className, ...props }: SVGProps) { return ( - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + ) } diff --git a/packages/internal/components/src/ui/platform-icon/collections/eagle.tsx b/packages/internal/components/src/ui/platform-icon/collections/eagle.tsx index fbaf07cc4..5b5e49725 100644 --- a/packages/internal/components/src/ui/platform-icon/collections/eagle.tsx +++ b/packages/internal/components/src/ui/platform-icon/collections/eagle.tsx @@ -3,9 +3,10 @@ import type { SVGProps } from "react" export function SimpleIconsEagle(props: SVGProps) { return ( + Eagle ) diff --git a/packages/internal/components/src/ui/platform-icon/collections/instapaper.tsx b/packages/internal/components/src/ui/platform-icon/collections/instapaper.tsx index d902c89c8..b78d222f7 100644 --- a/packages/internal/components/src/ui/platform-icon/collections/instapaper.tsx +++ b/packages/internal/components/src/ui/platform-icon/collections/instapaper.tsx @@ -2,10 +2,11 @@ import type { SVGProps } from "react" export function SimpleIconsInstapaper(props: SVGProps) { return ( - + + Instapaper ) diff --git a/packages/internal/components/src/ui/platform-icon/collections/obsidian.tsx b/packages/internal/components/src/ui/platform-icon/collections/obsidian.tsx index 0b90a91bb..27fd56df7 100644 --- a/packages/internal/components/src/ui/platform-icon/collections/obsidian.tsx +++ b/packages/internal/components/src/ui/platform-icon/collections/obsidian.tsx @@ -2,16 +2,11 @@ import type { SVGProps } from "react" export function SimpleIconsObsidian(props: SVGProps) { return ( - + + Obsidian ) diff --git a/packages/internal/components/src/ui/platform-icon/collections/outline.tsx b/packages/internal/components/src/ui/platform-icon/collections/outline.tsx index 7aae48eff..a5e042bd0 100644 --- a/packages/internal/components/src/ui/platform-icon/collections/outline.tsx +++ b/packages/internal/components/src/ui/platform-icon/collections/outline.tsx @@ -3,9 +3,10 @@ import type { SVGProps } from "react" export function SimpleIconsOutline(props: SVGProps) { return ( + Outline ) diff --git a/packages/internal/components/src/ui/platform-icon/collections/readeck.tsx b/packages/internal/components/src/ui/platform-icon/collections/readeck.tsx index 0f9ceb085..56453b981 100644 --- a/packages/internal/components/src/ui/platform-icon/collections/readeck.tsx +++ b/packages/internal/components/src/ui/platform-icon/collections/readeck.tsx @@ -2,48 +2,10 @@ import type { SVGProps } from "react" export function SimpleIconsReadeck(props: SVGProps) { return ( - + - - - - - ) diff --git a/packages/internal/components/src/ui/platform-icon/collections/readwise.tsx b/packages/internal/components/src/ui/platform-icon/collections/readwise.tsx index 4a2c7c3f5..baf5e9ea6 100644 --- a/packages/internal/components/src/ui/platform-icon/collections/readwise.tsx +++ b/packages/internal/components/src/ui/platform-icon/collections/readwise.tsx @@ -2,21 +2,10 @@ import type { SVGProps } from "react" export function SimpleIconsReadwise(props: SVGProps) { return ( - - + - ) diff --git a/packages/internal/components/src/ui/platform-icon/collections/rss3.tsx b/packages/internal/components/src/ui/platform-icon/collections/rss3.tsx index 53731ca17..cdf6e6781 100644 --- a/packages/internal/components/src/ui/platform-icon/collections/rss3.tsx +++ b/packages/internal/components/src/ui/platform-icon/collections/rss3.tsx @@ -4,8 +4,8 @@ export function TokenBrandedRss3(props: SVGProps) { return ( ) diff --git a/packages/internal/components/src/ui/platform-icon/collections/zotero.tsx b/packages/internal/components/src/ui/platform-icon/collections/zotero.tsx index 1698c2506..782625eb6 100644 --- a/packages/internal/components/src/ui/platform-icon/collections/zotero.tsx +++ b/packages/internal/components/src/ui/platform-icon/collections/zotero.tsx @@ -2,8 +2,7 @@ import type { SVGProps } from "react" export function SimpleIconsZotero(props: SVGProps) { return ( - // icon from https://simpleicons.org/?q=zotero - + Date: Tue, 15 Jul 2025 01:27:29 +0800 Subject: [PATCH 023/111] fix: replace TouchableOpacity with NativePressable for improved touch handling --- apps/mobile/src/components/ui/carousel/MediaCarousel.tsx | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/apps/mobile/src/components/ui/carousel/MediaCarousel.tsx b/apps/mobile/src/components/ui/carousel/MediaCarousel.tsx index eea79dc80..3f6342acc 100644 --- a/apps/mobile/src/components/ui/carousel/MediaCarousel.tsx +++ b/apps/mobile/src/components/ui/carousel/MediaCarousel.tsx @@ -3,7 +3,7 @@ import type { MediaModel } from "@follow/database/schemas/types" import type { ImageSource } from "expo-image" import type { Ref } from "react" import { useEffect, useState } from "react" -import { ScrollView, TouchableOpacity, View } from "react-native" +import { ScrollView, View } from "react-native" import Animated, { interpolateColor, useAnimatedStyle, @@ -16,6 +16,7 @@ import { EntryGridFooter } from "@/src/modules/entry-content/EntryGridFooter" import { Image } from "../image/Image" import { ImageContextMenu } from "../image/ImageContextMenu" import { getAllSources } from "../image/utils" +import { NativePressable } from "../pressable/NativePressable" import { VideoPlayer } from "../video/VideoPlayer" export const MediaCarousel = ({ @@ -70,7 +71,7 @@ export const MediaCarousel = ({ height: 400, } const ImageItem = ( - { const [placeholder] = getAllSources({ uri: imageUrl }, proxy) onPreview?.(index, { blurhash: m.blurhash, ...placeholder }) @@ -84,7 +85,7 @@ export const MediaCarousel = ({ aspectRatio={aspectRatio} placeholderContentFit="cover" /> - + ) if (m.type === "photo") { From a097112f5ea83e37c5df427fbb2f4a33121e2412 Mon Sep 17 00:00:00 2001 From: lawvs <18554747+lawvs@users.noreply.github.com> Date: Tue, 15 Jul 2025 02:51:54 +0800 Subject: [PATCH 024/111] chore: tweak pager selected logic --- apps/mobile/src/modules/screen/PagerList.tsx | 33 ++++++++++---------- 1 file changed, 16 insertions(+), 17 deletions(-) diff --git a/apps/mobile/src/modules/screen/PagerList.tsx b/apps/mobile/src/modules/screen/PagerList.tsx index 4007b14f1..9d2fb3fc5 100644 --- a/apps/mobile/src/modules/screen/PagerList.tsx +++ b/apps/mobile/src/modules/screen/PagerList.tsx @@ -2,7 +2,7 @@ import type { FeedViewType } from "@follow/constants" import { useViewWithSubscription } from "@follow/store/subscription/hooks" import { EventBus } from "@follow/utils/event-bus" import * as Haptics from "expo-haptics" -import { useEffect, useId, useMemo, useRef } from "react" +import { useCallback, useEffect, useId, useMemo, useRef } from "react" import type { StyleProp, ViewStyle } from "react-native" import { StyleSheet, View } from "react-native" import type { @@ -18,6 +18,10 @@ import { PagerListVisibleContext, PagerListWillVisibleContext } from "./PagerLis const AnimatedPagerView = Animated.createAnimatedComponent(PagerView) +const handlePageSelected = () => { + Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Light) +} + export function PagerList({ renderItem, style, @@ -47,6 +51,13 @@ export function PagerList({ }) }, [activeViews, pagerRef, rid]) + const onPageSelectedJS = useCallback( + (view: FeedViewType) => { + selectTimeline({ type: "view", viewId: view }, rid) + }, + [rid], + ) + const handlePageScroll = usePagerHandlers( { onPageScroll(e: PagerViewOnPageScrollEventData) { @@ -54,22 +65,9 @@ export function PagerList({ const { position, offset } = e dragProgress.set(offset + position) }, - onPageScrollStateChanged(e: PageScrollStateChangedNativeEventData) { - "worklet" - const { pageScrollState } = e - if (pageScrollState === "dragging") { - // setDragging(true) - } else if (pageScrollState === "idle") { - // setDragging(false) - } - - if (pageScrollState === "settling") { - runOnJS(Haptics.impactAsync)(Haptics.ImpactFeedbackStyle.Light) - } - }, onPageSelected(e: PagerViewOnPageSelectedEventData) { "worklet" - runOnJS(selectTimeline)({ type: "view", viewId: activeViews[e.position]! }, rid) + runOnJS(onPageSelectedJS)(activeViews[e.position]!) }, }, [], @@ -85,6 +83,7 @@ export function PagerList({ offscreenPageLimit={1} overdrag onPageScroll={handlePageScroll} + onPageSelected={handlePageSelected} orientation="horizontal" > {useMemo( @@ -116,7 +115,7 @@ export function PagerList({ function usePagerHandlers( handlers: { onPageScroll: (e: PagerViewOnPageScrollEventData) => void - onPageScrollStateChanged: (e: PageScrollStateChangedNativeEventData) => void + onPageScrollStateChanged?: (e: PageScrollStateChangedNativeEventData) => void onPageSelected?: (e: PagerViewOnPageSelectedEventData) => void }, dependencies: unknown[], @@ -130,7 +129,7 @@ function usePagerHandlers( if (event.eventName.endsWith("onPageScroll")) { onPageScroll(event as any as PagerViewOnPageScrollEventData) } else if (event.eventName.endsWith("onPageScrollStateChanged")) { - onPageScrollStateChanged(event as any as PageScrollStateChangedNativeEventData) + onPageScrollStateChanged?.(event as any as PageScrollStateChangedNativeEventData) } else if (event.eventName.endsWith("onPageSelected")) { onPageSelected?.(event as any as PagerViewOnPageSelectedEventData) } From 8e73438758847f8ab99303eb7695a5a9d1597e0f Mon Sep 17 00:00:00 2001 From: Stephen Zhou <38493346+hyoban@users.noreply.github.com> Date: Tue, 15 Jul 2025 10:23:49 +0800 Subject: [PATCH 025/111] feat: BitTorrent attachment and qBittorrent integration (#4173) --- .../main/src/ipc/services/integration.ts | 97 +++++++++++++++++++ apps/desktop/layer/main/src/lib/store.ts | 1 + .../src/hooks/biz/useEntryActions.tsx | 23 +++-- .../src/modules/command/commands/id.ts | 1 + .../modules/command/commands/integration.tsx | 87 +++++++++++++++++ .../src/modules/command/registry/command.ts | 7 +- .../renderer/src/modules/command/types.ts | 2 +- .../components/EntryAttachments.tsx | 44 +++++++++ .../components/entry-content/EntryContent.tsx | 2 + .../src/modules/settings/tabs/integration.tsx | 28 ++++++ locales/app/en.json | 5 + locales/settings/en.json | 7 ++ .../internal/shared/src/settings/defaults.ts | 6 ++ .../internal/shared/src/settings/interface.ts | 6 ++ 14 files changed, 307 insertions(+), 9 deletions(-) create mode 100644 apps/desktop/layer/renderer/src/modules/entry-content/components/EntryAttachments.tsx diff --git a/apps/desktop/layer/main/src/ipc/services/integration.ts b/apps/desktop/layer/main/src/ipc/services/integration.ts index 6381d7436..e969aad10 100644 --- a/apps/desktop/layer/main/src/ipc/services/integration.ts +++ b/apps/desktop/layer/main/src/ipc/services/integration.ts @@ -3,6 +3,8 @@ import fsp from "node:fs/promises" import path from "pathe" +import { store } from "~/lib/store" + import type { IpcContext } from "../base" import { IpcMethod, IpcService } from "../base" @@ -26,6 +28,22 @@ interface SaveToEagleInput { url: string mediaUrls: string[] } + +interface LoginToQBittorrentInput { + host: string + username: string + password: string +} + +interface CheckQBittorrentAuthInput { + host: string +} + +interface AddMagnetInput { + host: string + urls: string[] +} + export class IntegrationService extends IpcService { constructor() { super("integration") @@ -98,4 +116,83 @@ ${content} return null } } + + @IpcMethod() + async loginToQBittorrent(context: IpcContext, input: LoginToQBittorrentInput) { + const { host, username, password } = input + + const existingSID = store.get("qbittorrentSID") + if (existingSID) { + const errorMessage = await this.checkQBittorrentAuth(context, { host }) + if (!errorMessage) { + return + } + } + + const res = await fetch(`${host}/api/v2/auth/login`, { + method: "POST", + headers: { + "Content-Type": "application/x-www-form-urlencoded", + }, + body: `username=${encodeURIComponent(username)}&password=${encodeURIComponent(password)}`, + }) + + if (!res.ok) { + return `Failed to log in to qBittorrent: ${await res.text()}` + } + + const cookies = res.headers.get("set-cookie") || "" + const match = cookies.match(/SID=([^;]+)/) + if (!match || !match[1]) { + return "Failed to get SID from qBittorrent" + } + + store.set("qbittorrentSID", match[1]) + return + } + + async checkQBittorrentAuth(context: IpcContext, input: CheckQBittorrentAuthInput) { + const { host } = input + const sid = store.get("qbittorrentSID") + if (!sid) { + return "Not logged in to qBittorrent" + } + const res = await fetch(`${host}/api/v2/auth/check`, { + method: "GET", + headers: { + Cookie: `SID=${sid}`, + }, + credentials: "omit", + }) + + if (!res.ok) { + return await res.text() + } + } + + @IpcMethod() + async addMagnet(context: IpcContext, input: AddMagnetInput) { + const { host, urls } = input + const sid = store.get("qbittorrentSID") + if (!sid) { + return "Not logged in to qBittorrent" + } + const res = await fetch(`${host}/api/v2/torrents/add`, { + method: "POST", + headers: { + "Content-Type": "application/x-www-form-urlencoded", + Cookie: `SID=${sid}`, + }, + credentials: "omit", + body: `urls=${encodeURIComponent(urls.join("\n"))}`, + }) + + if (!res.ok) { + const text = await res.text() + return `Failed to add magnet links: ${text}` + } + + // eslint-disable-next-line no-console + console.log(`Added magnet links to qBittorrent: ${urls.join(", ")}`) + } } diff --git a/apps/desktop/layer/main/src/lib/store.ts b/apps/desktop/layer/main/src/lib/store.ts index b8423ad64..defb6d2d4 100644 --- a/apps/desktop/layer/main/src/lib/store.ts +++ b/apps/desktop/layer/main/src/lib/store.ts @@ -9,6 +9,7 @@ type StoreData = { cacheSizeLimit?: number | null minimizeToTray?: boolean | null proxy?: string | null + qbittorrentSID?: string | null user?: string | null windowState?: { height: number diff --git a/apps/desktop/layer/renderer/src/hooks/biz/useEntryActions.tsx b/apps/desktop/layer/renderer/src/hooks/biz/useEntryActions.tsx index a705e5f9d..2600b7830 100644 --- a/apps/desktop/layer/renderer/src/hooks/biz/useEntryActions.tsx +++ b/apps/desktop/layer/renderer/src/hooks/biz/useEntryActions.tsx @@ -124,6 +124,7 @@ const entrySelector = (state: EntryModel) => { const { summary, translation, readability } = state.settings || {} const media = state.media || [] + const attachments = state.attachments || [] const images = media.filter((a) => a.type === "photo") const imagesLength = images.length @@ -139,6 +140,7 @@ const entrySelector = (state: EntryModel) => { hasContent, doesContentContainsHTMLTags, imagesLength, + hasBitTorrent: attachments.some((a) => a.mime_type === "application/x-bittorrent"), } } @@ -222,6 +224,12 @@ export const useEntryActions = ({ onClick: runCmdFn(COMMAND_ID.integration.saveToZotero, [{ entryId }]), entryId, }), + new EntryActionMenuItem({ + id: COMMAND_ID.integration.saveToQBittorrent, + onClick: runCmdFn(COMMAND_ID.integration.saveToQBittorrent, [{ entryId }]), + hide: !IN_ELECTRON || !entry.hasBitTorrent, + entryId, + }), new EntryActionMenuItem({ id: COMMAND_ID.entry.tip, onClick: runCmdFn(COMMAND_ID.entry.tip, [ @@ -370,6 +378,14 @@ export const useEntryActions = ({ hasEntry, runCmdFn, entryId, + entry?.hasBitTorrent, + entry?.url, + entry?.imagesLength, + entry?.publishedAt, + entry?.read, + entry?.hasContent, + entry?.readability, + entry?.doesContentContainsHTMLTags, feed?.id, feed?.ownerUserId, feed?.siteUrl, @@ -377,12 +393,6 @@ export const useEntryActions = ({ shortcuts, view, isInCollection, - entry?.url, - entry?.publishedAt, - entry?.hasContent, - entry?.read, - entry?.readability, - entry?.imagesLength, isShowSourceContent, isShowAISummaryAuto, isShowAISummaryOnce, @@ -391,7 +401,6 @@ export const useEntryActions = ({ isShowAITranslationOnce, compact, isEntryInReadability, - entry?.doesContentContainsHTMLTags, ]) return actionConfigs diff --git a/apps/desktop/layer/renderer/src/modules/command/commands/id.ts b/apps/desktop/layer/renderer/src/modules/command/commands/id.ts index 91582e450..6c1d4ef75 100644 --- a/apps/desktop/layer/renderer/src/modules/command/commands/id.ts +++ b/apps/desktop/layer/renderer/src/modules/command/commands/id.ts @@ -27,6 +27,7 @@ export const COMMAND_ID = { saveToReadeck: "integration:save-to-readeck", saveToCubox: "integration:save-to-cubox", saveToZotero: "integration:save-to-zotero", + saveToQBittorrent: "integration:save-to-qbittorrent", }, list: { edit: "list:edit", diff --git a/apps/desktop/layer/renderer/src/modules/command/commands/integration.tsx b/apps/desktop/layer/renderer/src/modules/command/commands/integration.tsx index ea6bc95ee..091319b5c 100644 --- a/apps/desktop/layer/renderer/src/modules/command/commands/integration.tsx +++ b/apps/desktop/layer/renderer/src/modules/command/commands/integration.tsx @@ -40,6 +40,7 @@ export const useRegisterIntegrationCommands = () => { useRegisterReadeckCommands() useRegisterCuboxCommands() useRegisterZoteroCommands() + useRegisterQBittorrentCommands() } const category: CommandCategory = "category.integration" @@ -700,6 +701,86 @@ const buildMemoRequestBody = (entry: EntryModel, selectedText: string) => { } } +function extractQBittorrentUrls(entry: EntryModel) { + const attachments = entry.attachments?.filter( + (attachment) => attachment.mime_type === "application/x-bittorrent" && attachment.url, + ) + + if (!attachments || attachments.length === 0) { + return + } + + return attachments.map((attachment) => attachment.url) +} + +const useRegisterQBittorrentCommands = () => { + const { t } = useTranslation() + + const enableQBittorrent = useIntegrationSettingKey("enableQBittorrent") + const qbittorrentHost = useIntegrationSettingKey("qbittorrentHost") + const qbittorrentUsername = useIntegrationSettingKey("qbittorrentUsername") + const qbittorrentPassword = useIntegrationSettingKey("qbittorrentPassword") + const qbittorrentAvailable = + enableQBittorrent && !!qbittorrentHost && !!qbittorrentUsername && !!qbittorrentPassword + + useRegisterCommandEffect( + !qbittorrentAvailable + ? [] + : defineFollowCommand({ + id: COMMAND_ID.integration.saveToQBittorrent, + label: t("entry_actions.save_to_qbittorrent"), + icon: "i-simple-icons-qbittorrent", + category, + run: async ({ entryId }) => { + const entry = getEntry(entryId) + if (!entry) { + toast.error("Failed to save to qBittorrent: entry is not available") + return + } + try { + tracker.integration({ + type: "qbittorrent", + event: "save", + }) + + const urls = extractQBittorrentUrls(entry) + if (!urls) { + toast.error(t("entry_actions.no_bittorrent_urls_found")) + return + } + + let errorMessage = await ipcServices?.integration.loginToQBittorrent({ + host: qbittorrentHost, + username: qbittorrentUsername, + password: qbittorrentPassword, + }) + + if (errorMessage) { + toast.error(`${t("entry_actions.failed_to_login_to_qbittorrent")}: ${errorMessage}`) + return + } + + errorMessage = await ipcServices?.integration.addMagnet({ + host: qbittorrentHost, + urls, + }) + if (errorMessage) { + toast.error(`${t("entry_actions.failed_to_save_to_qbittorrent")}: ${errorMessage}`) + } else { + toast.success(t("entry_actions.saved_to_qbittorrent")) + } + } catch (error) { + const errorObj = error as Error + toast.error( + `${t("entry_actions.failed_to_save_to_qbittorrent")}: ${errorObj.message || ""}`, + ) + return + } + }, + }), + ) +} + export type SaveToEagleCommand = Command<{ id: typeof COMMAND_ID.integration.saveToEagle fn: (payload: { entryId: string }) => void @@ -740,6 +821,11 @@ export type SaveToZoteroCommand = Command<{ fn: (payload: { entryId: string }) => void }> +export type SaveToQBittorrentCommand = Command<{ + id: typeof COMMAND_ID.integration.saveToQBittorrent + fn: (payload: { entryId: string }) => void +}> + export type IntegrationCommand = | SaveToEagleCommand | SaveToReadwiseCommand @@ -749,3 +835,4 @@ export type IntegrationCommand = | SaveToReadeckCommand | SaveToCuboxCommand | SaveToZoteroCommand + | SaveToQBittorrentCommand diff --git a/apps/desktop/layer/renderer/src/modules/command/registry/command.ts b/apps/desktop/layer/renderer/src/modules/command/registry/command.ts index dbbe4a512..3b9ca39b9 100644 --- a/apps/desktop/layer/renderer/src/modules/command/registry/command.ts +++ b/apps/desktop/layer/renderer/src/modules/command/registry/command.ts @@ -1,3 +1,5 @@ +import { createElement } from "react" + import type { Command, CommandOptions, @@ -15,7 +17,10 @@ export function createCommand< return { id: options.id, run: options.run, - icon: options.icon, + icon: + typeof options.icon === "string" + ? createElement("i", { className: options.icon }) + : options.icon, category: options.category ?? "category.global", get label() { let { label } = options diff --git a/apps/desktop/layer/renderer/src/modules/command/types.ts b/apps/desktop/layer/renderer/src/modules/command/types.ts index 2e21a8576..3f8d03978 100644 --- a/apps/desktop/layer/renderer/src/modules/command/types.ts +++ b/apps/desktop/layer/renderer/src/modules/command/types.ts @@ -45,7 +45,7 @@ export interface CommandOptions< | (() => string) | { title: string; description?: string } | (() => { title: string; description?: string }) - icon?: ReactNode | ((props?: { isActive?: boolean }) => ReactNode) + icon?: string | ReactNode | ((props?: { isActive?: boolean }) => ReactNode) category?: CommandCategory run: T["fn"] diff --git a/apps/desktop/layer/renderer/src/modules/entry-content/components/EntryAttachments.tsx b/apps/desktop/layer/renderer/src/modules/entry-content/components/EntryAttachments.tsx new file mode 100644 index 000000000..34059a148 --- /dev/null +++ b/apps/desktop/layer/renderer/src/modules/entry-content/components/EntryAttachments.tsx @@ -0,0 +1,44 @@ +import { + Tooltip, + TooltipContent, + TooltipPortal, + TooltipTrigger, +} from "@follow/components/ui/tooltip/index.js" +import { useEntry } from "@follow/store/entry/hooks" +import { cn } from "@follow/utils" + +const SUPPORTED_MIME_TYPES = new Set(["application/x-bittorrent"]) + +export function EntryAttachments({ entryId }: { entryId: string }) { + const attachments = useEntry(entryId, (entry) => entry.attachments) + if (!attachments || attachments.length === 0) { + return null + } + return ( +
+ {attachments + .filter( + (attachment) => attachment.mime_type && SUPPORTED_MIME_TYPES.has(attachment.mime_type), + ) + .map((attachment) => ( + + + + + + {attachment.url} + + + ))} +
+ ) +} diff --git a/apps/desktop/layer/renderer/src/modules/entry-content/components/entry-content/EntryContent.tsx b/apps/desktop/layer/renderer/src/modules/entry-content/components/entry-content/EntryContent.tsx index 7b277b8f5..fe2a88107 100644 --- a/apps/desktop/layer/renderer/src/modules/entry-content/components/entry-content/EntryContent.tsx +++ b/apps/desktop/layer/renderer/src/modules/entry-content/components/entry-content/EntryContent.tsx @@ -36,6 +36,7 @@ import { AISummary } from "../../AISummary" import { ApplyEntryActions } from "../../ApplyEntryActions" import { useEntryContent, useEntryMediaInfo } from "../../hooks" import { EntryHeader } from "../entry-header" +import { EntryAttachments } from "../EntryAttachments" import { EntryTimelineSidebar } from "../EntryTimelineSidebar" import { EntryTitle } from "../EntryTitle" import { SourceContentPanel } from "../SourceContentView" @@ -226,6 +227,7 @@ export const EntryContent: Component = ({ )} + diff --git a/apps/desktop/layer/renderer/src/modules/settings/tabs/integration.tsx b/apps/desktop/layer/renderer/src/modules/settings/tabs/integration.tsx index bb7b927de..af71345aa 100644 --- a/apps/desktop/layer/renderer/src/modules/settings/tabs/integration.tsx +++ b/apps/desktop/layer/renderer/src/modules/settings/tabs/integration.tsx @@ -274,6 +274,34 @@ export const SettingIntegration = () => { type: "password", }), + { + type: "title", + value: ( + + + {t("integration.qbittorrent.title")} + + ), + }, + defineSettingItem("enableQBittorrent", { + label: t("integration.qbittorrent.enable.label"), + description: t("integration.qbittorrent.enable.description"), + }), + defineSettingItem("qbittorrentHost", { + label: t("integration.qbittorrent.host.label"), + vertical: true, + description: t("integration.qbittorrent.host.description"), + }), + defineSettingItem("qbittorrentUsername", { + label: t("integration.qbittorrent.username.label"), + vertical: true, + }), + defineSettingItem("qbittorrentPassword", { + label: t("integration.qbittorrent.password.label"), + vertical: true, + type: "password", + }), + BottomTip, ]} /> diff --git a/locales/app/en.json b/locales/app/en.json index df0ac11df..38e3674f4 100644 --- a/locales/app/en.json +++ b/locales/app/en.json @@ -118,11 +118,13 @@ "entry_actions.deleted": "Deleted.", "entry_actions.export_as_pdf": "Export as PDF", "entry_actions.failed_to_delete": "Failed to delete.", + "entry_actions.failed_to_login_to_qbittorrent": "Failed to login to qBittorrent", "entry_actions.failed_to_save_to_cubox": "Failed to save to Cubox.", "entry_actions.failed_to_save_to_eagle": "Failed to save to Eagle.", "entry_actions.failed_to_save_to_instapaper": "Failed to save to Instapaper.", "entry_actions.failed_to_save_to_obsidian": "Failed to save to Obsidian", "entry_actions.failed_to_save_to_outline": "Failed to save to Outline.", + "entry_actions.failed_to_save_to_qbittorrent": "Failed to download with qBittorrent", "entry_actions.failed_to_save_to_readeck": "Failed to save to Readeck.", "entry_actions.failed_to_save_to_readwise": "Failed to save to Readwise.", "entry_actions.failed_to_save_to_zotero": "Failed to save to Zotero.", @@ -132,6 +134,7 @@ "entry_actions.mark_as_read": "Mark as Read / UnRead", "entry_actions.mark_as_unread": "Mark as Unread", "entry_actions.mark_below_as_read": "Mark Below as Read", + "entry_actions.no_bittorrent_urls_found": "No BitTorrent URLs found in this entry.", "entry_actions.open_in_browser": "Open in {{which}}", "entry_actions.recent_reader": "Recent Reader:", "entry_actions.save_media_to_eagle": "Save Media to Eagle", @@ -139,6 +142,7 @@ "entry_actions.save_to_instapaper": "Save to Instapaper", "entry_actions.save_to_obsidian": "Save to Obsidian", "entry_actions.save_to_outline": "Save to Outline", + "entry_actions.save_to_qbittorrent": "Download with qBittorrent", "entry_actions.save_to_readeck": "Save to Readeck", "entry_actions.save_to_readwise": "Save to Readwise", "entry_actions.save_to_zotero": "Save to Zotero", @@ -147,6 +151,7 @@ "entry_actions.saved_to_instapaper": "Saved to Instapaper.", "entry_actions.saved_to_obsidian": "Saved to Obsidian", "entry_actions.saved_to_outline": "Saved to Outline.", + "entry_actions.saved_to_qbittorrent": "Torrents added to qBittorrent.", "entry_actions.saved_to_readeck": "Saved to Readeck.", "entry_actions.saved_to_readwise": "Saved to Readwise.", "entry_actions.saved_to_zotero": "Saved to Zotero", diff --git a/locales/settings/en.json b/locales/settings/en.json index d1083e9c0..f7fbfac64 100644 --- a/locales/settings/en.json +++ b/locales/settings/en.json @@ -323,6 +323,13 @@ "integration.outline.title": "Outline", "integration.outline.token.description": "You can get it from your Outline account settings.", "integration.outline.token.label": "Outline API Key", + "integration.qbittorrent.enable.description": "Display 'Download with qBittorrent' button when available.", + "integration.qbittorrent.enable.label": "Enable", + "integration.qbittorrent.host.description": "The URL of your qBittorrent WebUI, e.g. http://localhost:8080.", + "integration.qbittorrent.host.label": "qBittorrent Host", + "integration.qbittorrent.password.label": "qBittorrent Password", + "integration.qbittorrent.title": "qBittorrent", + "integration.qbittorrent.username.label": "qBittorrent Username", "integration.readeck.enable.description": "Display 'Save to Readeck' button when available.", "integration.readeck.enable.label": "Enable", "integration.readeck.endpoint.description": "The URL is 'https://'.", diff --git a/packages/internal/shared/src/settings/defaults.ts b/packages/internal/shared/src/settings/defaults.ts index db14e931a..b8d480d63 100644 --- a/packages/internal/shared/src/settings/defaults.ts +++ b/packages/internal/shared/src/settings/defaults.ts @@ -136,6 +136,12 @@ export const defaultIntegrationSettings: IntegrationSettings = { zoteroUserID: "", zoteroToken: "", + // qbittorrent + enableQBittorrent: false, + qbittorrentHost: "", + qbittorrentUsername: "", + qbittorrentPassword: "", + saveSummaryAsDescription: false, } diff --git a/packages/internal/shared/src/settings/interface.ts b/packages/internal/shared/src/settings/interface.ts index 7e23a4aa3..bfcee4ff4 100644 --- a/packages/internal/shared/src/settings/interface.ts +++ b/packages/internal/shared/src/settings/interface.ts @@ -131,5 +131,11 @@ export interface IntegrationSettings { zoteroUserID: string zoteroToken: string + // qbittorrent + enableQBittorrent: boolean + qbittorrentHost: string + qbittorrentUsername: string + qbittorrentPassword: string + saveSummaryAsDescription: boolean } From eedcf7bebc7d5fb809d337c7c072e85ca7bd98c3 Mon Sep 17 00:00:00 2001 From: Konv Suu <2583695112@qq.com> Date: Tue, 15 Jul 2025 10:24:55 +0800 Subject: [PATCH 026/111] feat(desktop): return to back path in preview mode (#4168) --- .../desktop/layer/renderer/src/hooks/biz/useFollow.tsx | 6 ++++++ .../src/modules/subscription-column/FeedItem.tsx | 10 ++++++---- .../subscription-list/EmptyFeedList.tsx | 4 +++- 3 files changed, 15 insertions(+), 5 deletions(-) diff --git a/apps/desktop/layer/renderer/src/hooks/biz/useFollow.tsx b/apps/desktop/layer/renderer/src/hooks/biz/useFollow.tsx index f560a7bba..26e821224 100644 --- a/apps/desktop/layer/renderer/src/hooks/biz/useFollow.tsx +++ b/apps/desktop/layer/renderer/src/hooks/biz/useFollow.tsx @@ -8,9 +8,11 @@ import { import { useUserRole } from "@follow/store/user/hooks" import { t } from "i18next" import { useCallback } from "react" +import { useNavigate } from "react-router" import { withoutTrailingSlash, withTrailingSlash } from "ufo" import { useEventCallback } from "usehooks-ts" +import { previewBackPath } from "~/atoms/preview" import { useServerConfigs } from "~/atoms/server-configs" import { useModalStack } from "~/components/ui/modal/stacked/hooks" import { CustomSafeError } from "~/errors/CustomSafeError" @@ -67,6 +69,7 @@ export interface FollowOptions { export const useFollow = () => { const { present } = useModalStack() const canFollowMoreInboxAndNotify = useCanFollowMoreInboxAndNotify() + const navigate = useNavigate() return useCallback( (options?: FollowOptions) => { @@ -92,6 +95,9 @@ export const useFollow = () => { content: ({ dismiss }) => { const onSuccess = () => { options?.onSuccess?.() + // If it's a preview, navigate to the back path + const backPath = previewBackPath() + backPath && navigate(backPath) dismiss() } return options?.isList ? ( diff --git a/apps/desktop/layer/renderer/src/modules/subscription-column/FeedItem.tsx b/apps/desktop/layer/renderer/src/modules/subscription-column/FeedItem.tsx index 422fc4234..33608a59a 100644 --- a/apps/desktop/layer/renderer/src/modules/subscription-column/FeedItem.tsx +++ b/apps/desktop/layer/renderer/src/modules/subscription-column/FeedItem.tsx @@ -207,7 +207,7 @@ const FeedItemImpl = ({ view, feedId, className, isPreview }: FeedItemProps) => )} - {isPreview && ( + {isPreview ? ( + ) : ( + )} - ) } @@ -325,7 +326,7 @@ const ListItemImpl: Component = ({ )} - {isPreview && ( + {isPreview ? ( + ) : ( + )} - ) } diff --git a/apps/desktop/layer/renderer/src/modules/subscription-column/subscription-list/EmptyFeedList.tsx b/apps/desktop/layer/renderer/src/modules/subscription-column/subscription-list/EmptyFeedList.tsx index 38194a14e..4eb4cc52e 100644 --- a/apps/desktop/layer/renderer/src/modules/subscription-column/subscription-list/EmptyFeedList.tsx +++ b/apps/desktop/layer/renderer/src/modules/subscription-column/subscription-list/EmptyFeedList.tsx @@ -35,7 +35,9 @@ export const EmptyFeedList = memo(({ onClick }: { onClick?: (e: React.MouseEvent onClick={handleClick} > - {t("sidebar.already_on_discover_page")} + + {t("sidebar.already_on_discover_page")} + ) : (
Date: Tue, 15 Jul 2025 14:43:45 +0800 Subject: [PATCH 027/111] fix(android): splash icon, close #4174 --- apps/mobile/app.config.ts | 7 ++----- apps/mobile/assets/splash-icon.png | Bin 0 -> 13927 bytes .../Contents.json | 18 ------------------ 3 files changed, 2 insertions(+), 23 deletions(-) create mode 100644 apps/mobile/assets/splash-icon.png diff --git a/apps/mobile/app.config.ts b/apps/mobile/app.config.ts index 598f273c4..308cd3b6a 100644 --- a/apps/mobile/app.config.ts +++ b/apps/mobile/app.config.ts @@ -13,6 +13,7 @@ const iconPathMap = { const iconPath = iconPathMap[process.env.PROFILE || "production"] || iconPathMap.production const adaptiveIconPath = resolve(__dirname, "./assets/adaptive-icon.png") +const splashIconPath = resolve(__dirname, "./assets/splash-icon.png") const isDev = process.env.NODE_ENV === "development" @@ -86,12 +87,8 @@ export default ({ config }: ConfigContext): ExpoConfig => { [ "expo-splash-screen", { - backgroundColor: "#ffffff", - dark: { - backgroundColor: "#000000", - }, android: { - image: iconPath, + image: splashIconPath, imageWidth: 200, }, }, diff --git a/apps/mobile/assets/splash-icon.png b/apps/mobile/assets/splash-icon.png new file mode 100644 index 0000000000000000000000000000000000000000..100d439df89e3fd074ddde0d476db15f9f99ab93 GIT binary patch literal 13927 zcmeHtd0fnW_xJhEv~Pn#DNVMdqG%hscxQGH6OjxX4ZFiLDY2AHL!Msqsf9nOe_OjhIQrfxfA5tH(*dsNcrmoJXIE!x3 z0(+*sb5&^m6H2odbI((Edw&Bz`6Khcxos=bb)tk0neXrHoB1{{e3j}h&utB(U;er{ z6&L*PpZ{{;KbQmTetp803{q(s=o@N`Y7N}qV$CX;?IRe;5GW@!2KSBj2>Qd@sJ3zH z)^)iHdELKC8>$|h-%~V@J2b3P&httO_%LBJwu+f50!+hZ`ql@gTKz}r{K~&Y53BR| zPa4I^ZPy|w`R4M1O{{|oep`(DHy#sH)FnXInCHp&I5)ONU=?!F-etZ0H==s&Oo~cc z6`j|eZS1LDB1XDQ0q`==`E_Lc@`PboBBM_PF5T%Wk`H{!?(155^E724k++uu&M6-k zjg;FMne86uYe2H8c~`!Ff~hpiCX8*T23aQo97=+6b$*mb?|8tF0(=$$q7hFB5%~uBCoy+ne7fXDmmG;wGe*>Wo!&MSdR7dqIQf zcM(Kw1i`kF1k!8k5S9Hxl1h4^%Gqw%#u2!iK5#nDfUGK)BCF)!sTZMGgaH3VJvR3n z+cs$NtXA6M2vR?EAzRoR6$4MSRbA}duOebALx4hR+n2WI z`F10CLu@NW1&MW2fjMU^lz(8rcsjp`3eM-frOCP8BJrgK-&l<4g52o>U~ef{8p|0m zFRz$VeMJtc9d`a~v!YkVJqu)k^R^NnA~9g25&Uf~4*N1}xHg=O@^(5nq!cptI2ggc z4fxru?3+Nl^n)yrhwEfv$6ErFuJ`?9O^?C}Bm${S`#@ldjY$gfw+S`_$ei~D#g(%` z*MHIG@>ZLX?Gscmd;iOPTDfQ6b7OLK9RbuUrc8PojU!G#{6+O!`a10{5Iz@3BB5wP zFzeSC75;d*0K}?hfa0|vo%MrPSQQM2&ut>v4ZNWB&QnA{S8Y(TB)3kyGYH`C+{bC7 z^@|8ynL=PgLC4Uiqwo8M>Egh=F6XM%YjDw6(s{86W&z6RybH^WsoF>o}~A!;l#V1DtSRJ@04PO)0DN9gD ziti0QJ!rCuHw%UDEv@FIu?%+&_B%EDrhNNO0Rdv&^9#pq)w)gM1+gY6W~M*f|@u4)%!Ky_x|T4MqHFlMbZL8&M`|&v$F?NCW$7@qv5p z6o@(?Y}r^R%6yCFEB7qENVs}en%rwZh|l?QQe2olvP_Zxs&=RlY(;wTUbJuez&>kn*#Cx4 z1NOrvF=i)nXZ1J(;H8@~T+bIJzk3LW?f0gtxvqffq+hs<{by}o@qL!Slq}ebTbSi1 z0)KA=CV%H_y#A~W@@=BR#`n#oWg~5Jc#N2y(N!Az%z@ck;Eeq}dsqK;0mu)b_@wi8 z3JF*E%ibim$2dkHi`@;XhzoOO!{6QSK57BHe_pDgG!5eOQ46wFfy*LD~h-pR9IegH@(haxeseo(jxl5jtfa=Suwqw8TnN;$L zkcwUm&|U9vX|4_h9&%z`7q0RV$M%MxaaWd~)Q%|-Pk&|)pcu7yIQ4Hce8i6X2vC$7 zPThyZiG&e#)G-n=l=<^0@PpHQKorNN<%QNn}{}obXh79uZ=@%wxgt))j8ao zOT&fQ+ogd0rr3OeJQ8&!#T3xh?cMy>DImQITxa5TBk%LxmTEp*2x|0L5CP|O!y6*( zepJQ)zMjwaPM>Uv#Mh;37b6FeHo!EM!4;g-KV)7Y2v~kT1E;j>-KMk>iGa;`j%&>$ zePozCn&Mmv&fn!nP*LR~9=VU~7EZUY5UGEU8TBtf$u;}D=dz51uvan#H~Q9c8y;R` zIAb3ZnAVPVNN5gc$lMZk08KUFzogVZ-H}Qsh2Q>vHtixH^N@niG5vwsA!F;@xDNeQ zD+JRQ*37r2RPRJt9XWE$`xV{l`@N)}H;1m4S;X}WDT;#E92AP>33jiFmRi-8SM4~) z_fpa7za27|G+4{eDq>XldZ(%-$Mn@1+&TVH4zA=#R${__!E$SSE#j(-NyuzT_RQJ=CazBf-N28@ zD3n0e+ttIGwQFFl7bDNT$2h1xi$+!Ll2V&VfymdtN2@9D*-?*uTg}d7Mm{0H?a=F5Z6Hi54%uf1}y}j)`P>}#Q3e!DDf?<1?-`vnV zCi2coXgm?y)eg)DO`%OGnPDnJTH-tOeDkQ(cZHmEa`0R6+Z^->a4&KQLtgv*+(pQ& z5zUwfps~AQOfXlSVEU<^F_k4>;M1^7{YmF?3fs?aCCFwW{l4;0wgBkeabkg*V5@`x z^M2h6`@v((#s)*S3BuN3-p8Pa4f8(wpoHU`efk zeELZwRxW(tVIa+YIJN{9QeZmzTbEMLnq3qSIq5N92wP)Z!Q;boiesz&N=fohJc;Ep zlQF+p;AnvsQCDV)#tocgzR$!AaJ0D_E~SwuB>hx);{HB~0g51s+WyiVFM(h|EQR!X zAPX9(<&stK(%igLC{n0RHLCguc8&gu`{Y64>;avr)48dg3-8|$VTR##>^FWOpgX%b z+Jw!;<`-PI>CORs36k<}V)H8kq!!>btCgz=_TBpav;GRS4ZRrwG2VkD#QWJ+mVMn;IlpyqI~b~OU2`M8lV`)%YpbcGZwggp(*q+rH6aj>0_ z(@GldRRHbv@@>D_vcTQ7>WwBDfo|7iXDPEx@YRmEZ_=3oDZ=x21cATafkHdtvyggr zYa5w3zT`Kjs;X6hR8|&c-p0Kz7_~Wv9yCIY0Y3r57QF|i5G+9PE%jb8=2PskA8(C2 zww{=5^RVt%4gL#y_I!BHr(LqfZO&Sp1>3(gOWGlqY!eDj*3%wRxLcY7c8>bt9u$OK zQq2kW=No^xQP7owOCBhP+?So1f{sarpX`X@SoZuI!*(jJ{YM}HA(8d0WJBcs!yQeO z;xkAr6B04#VuS;CRp{wU|N2yCFp%zdNR(@1wNiTWxx6Tvo#q=zyiTbXn0x$WEd))x z-t_QnfVVV$iRWR69xc-e6zdqx+Q>wSq_Zcpg1k?LyHpXoIs19Z7v972zFAmAXhXviR zAFtg)HdPus$0S_+rWI+0aHh}8HLb;@$cxQ?Ow zgU81#Orwkf>L%(0O15F6-}u%gVu4!YPAT1NjjSJA)d(>AB5P@gp_k;Gt;sPLhrZnt zgl2Aqs5e8Iqb*&*EiX(BgeO3F(EY>3g zc!W{1{NkH?J~k-9-)j&I|CX@hV;u6%tH@uo z^>y}6W2X%5Cej|zPl9u@2tpPkjixDJdn(oGGb_FSbho?+m@U9jh7|I1;&i_F10^Rd z{wKEt3zf9Q?*ZNwMSgK?5h$x(O2SJcs|Z19j=Q9@OI_`|&Bw+{TDu<;y=hfJ7{o#C zou{2ouxK31&xeJRnoLi$tHC$-Ud+Nu5MC&I7m7 z+667a$Cu@;2{mFqrL7;<2biKcdVzTrvvqD;tx@ z+QB$-SDIL}P!5Ee<%6Bk_gpPLE8q!T#)3}qmc)6`Msw9m+RK%HrH!0k{jI1&f`DY4 zqWEn7QTIl=Od?K+eiJm*r?$7fVC-9siVTK zLYKQkiuiN$O?YPx;6L4pu`Pr_dJ984V>?VSPH+xaeE51H-zH0CO>e?X-i%vm1Wccb zZt?p>xb(}$0w+bwcL<>xrGU8r z_vVC9$kI^xyGNloRNy&7tmUg>C&C{he!78OgeEyDO@ovgN~0)BNH9MkJ+sSR;PiYx zx#FJ>`D3){*J&a*#6SUq7X6Ft1-GrO5cg@IFmpLse6xtor%9N+(m<@qHEUJNt1*^I zwzr{9n&*+m0>%uPbPggR(1;gy$X>;^%?}1+gf+qg?{4iczv?@2`}CJ4*l3Jx&c~?2DSUsO?xsJLxi%}pK?7l*^ZEf=i1$_mD9iEm zdd(qWHdEy&lf%v>hH&TA%#X#BptJH--}gtDbg?Peq98ES4u{hmlk4Y*FqLo^B%xp= zOZ=lhk_RiL=(uTQd7!XaXwly^MG2kNlPD0_7kxeQdJl}~H;6-&+T`s0|6_IoDio95 zRER(!3v3?I1k*RM7=gZIhVJ8F5sbXKk5e5)iCdvOUP7Pu7w1%0&mS$ z6FFbiyFwN;gJ#50eoKSHky-3;@HCM6EexDqaod}}tk2!;DZ&c~KvpFcw$7w5eT3t+ zaeRdW#da!&#e}HI|Gb^VR|=US!2^v1T=r1&(eGoU^CluYCHX zYr(FM8LKx_GvSp9^ya9-VFZ$nwPjP_$1)whQ`0bwnT>~RC~D)c>J`&H%KI*dLC?!V z4YXEXeh$d&a+*lO@COr5yET6b7d_9x!V#MJQ3{EYIyK>_w>rqY45<}#+fGoKHW;um z7Nh>j95UxM4bq?w?@il&CgsVu?W$oy#W##1(~l60-5yiYewSy_vNUT;QCoSbd>rTH z!u!IAlQ7as?*D49YSjK{F_AZG@QR?J>p(5j8j6|n@n`KeJR+8Rwi_FE*y~x;ve(q4 zO|;qQ3{#zJ{tcVh4-dBjMg)IZuhdh984E?9-5tFo-~p6vz};#3oEvX~LQ!^1UB|ve7pY6jrki6`4 zmlQ8?G3DJ}(;C*1Jwt7UMfB?P|A3;5dLMcB4vkfUj|{(x^K!(&2L3gviR?12U`c82 z<1f3lc+B2^Ods1MK>-3?nD@TyVD{(oYuD(qx!%JOp~_Av!(W4(z9tEjm@e46)gI!L zb`0nzl*bO=ayj$b?`)|J;p~I>9AD*saxCW`4Tc;2KSrC_7&v>@@Z4hT=lo`4{;Rh9 ziziyGS+!`zLr`cj`gV^Zu-fE0kN-8A$1#o)L|t^N6NjsHh;aH@i)0$VQo~w@M$~zS zj&K;5kHG8?aov5mE?bM~QF57Q6mTu-XPc{@T<(^yPTQo!g4(s$cX_U`6qL6~iolG_ z;QM8J8-K@PG}d#9elTouW}f%-ooAo6=)gurd*KvIa?K><^e z0y)-<@^|gEqR*4Dev(@6lGjQ z$jhj%ZPONO)rRYin|^%`q%e?Vd-wh?fy*@(Jr*ZLlLkNE@)_D?bjU-52j4gj0jdgZ zG;lzK3iTd)ngxvcgMFtLD?#2qZ1>cYjr?ki{sWpF+eF66IX^-PashJK_Ue1fLA6Jn z$m@r~gG7fNdiGAj4V;_s`rdtxaXA!Tu;3a&3K5I#)$*Mlsv1vaK$ux2GxX&nI;V`5 z0sDt=?cbkLCE?Db8n_A7CEy ziWM6F-G&MY;eoRrW2zN{JY9i9Ahv~@g!=CNq&b(&ymDrXjR_T|0z{}82 zfH}6`-4D;Ao&34{kt`MLEpWn`Uh!^@y8sJHgtw936I81-)cxk8MW(=~93{vBQ9L~2 zh~}vxIC5AdB$OW=7kit1p`HZ}G^8D3_82(%fddtP2kwR=o9;P@A{NRs#hbns{4Unj z#35m{p#gzS)>*uZ6|EUV9xElTe9`aS#SSo`<;Hz0!6F}fsp3h z!O(8Ut%9Fkfm?xXi(J4+YexZ%P?0?<%WKGP8P3Jzp%}tcnAu{rE^GStZsX_!h%glq zq@(+x>}p2jrV5Td;(cU+GZTfce?k6jGVY{Kg3SaA6ZTx;lm~xBK$4MQ?7KMVZothH zKM8FiOnvx=n`o$$3Na)7q$!BJIV5>37gKn4IhbmjRi2vrQUl1<99(Dn5tG;Lhgq*f zE5-!;p~D+=5VcOGP;&0}M7M44xv6L#(OkMiqCK4f)u(~HVb|sL+sd zOF>9EtKnDqY`AeK_XSrHs?9s@NXgh6sr1uR{3JK5u5vH?)_0A8nbz$KsJKCgQ#s09 z{RlYHzQbcR+a!~pTY&hi4AWJ2FK1Ac++7{(yh&jp32%7fSq6hWvv_jc!S*{+e}4)w zWZx{C=d7aijbHkhB^df~wv-Q7+xJ|4+9FlGt|&J{mJE5-{Q0q3vhuW}QxXFjH$@%~ zZ+tXX<*{?XZ;SiwdOBc4R*mj6p#=x^X_R(t)f8Rlgj-35=vm6FWqim*R8-zz%nRDp zDCIBfqarSI1JCT9N%>(YO{skFwy1%g)^Pg%*Ar#2y2(0Y^U97tZqEHGUVOdscM=R^ z+{r5Wy4=-LRMl6{NRML^w#`9tP1%rF0V zdrx_vQ3mtuYZIzlE71yNzMX$=%;g&$l+SI^2xvgA)rCeX>CS9x+ zo?f}7prv)_Sdq@iV=s64s1xLVcW=UZ1X=m)ttNA^Tjt>1p_Rw_Y9HJ5aLPgju4x1O zv}4Dgdcl=vrJ73qGHRoZ7cww0=Rgr!zJI0AQnyBLlW~%dKObZ>PYVGI=ZW2}r6HK4 zjsB#Gr4BL2?Uu~}HJ$8eY@~LmUfv|kCNijK@zw%U9oJ6jseLX6&w*1frFJZ;D;Kh8C9VSQtKx6o{yT$XzHDnugXHlO)ZLr=2^{r$wOSz z%nQ^;F@u?8h<+(3o~&$F5R&s|?!Z<5EM0_wmiVN_LP`uNB@76?>#Y!^ruCq5{J9*h zVjE@IZ7R9aU@4*m2c1m8zIDL7B}2hPChr8T8q?~IR(OE-UbEs+(F8BU@GW`x&}6E2 z-+g>FjfXG|JEl_8XE6uEhX>tir(=${eb1%uc%CMG^fp$d3KM4Wxr=9_G5mLGIeYY0 zrU&X3&nAJ*7351V`hR5oLqU=@K9W`!Vap%l3pQFYJDW>K+J*{dqtOdlSo3mZ7c(*t z;>#;lkZtz&>iIVKI4*I~>m#={zL}){_T#KmM8(|nF4Phm_tgfFm}9QiZ#}L$nL$_D z*@9yo9;)9G-?s_tJ2tk8%#+lJT=6|E1Sj{P4ZwXH`#MWk3fNmZoN0M!Ffl4 zU@H(%k%!zOQ`|d@dIXoS(L)Yj?+lN5a#SfbNY>sJaOuP6Vk)MFE87A9;F!-|6I zepKCLxDnf&SnaqV7_*Wcu32Gjr=W8n}v?m5Py0dpCI!%QVzWkYmMXj<1VKqmmh4kq=z? zl2SntMGEQW4M7Bq#2;Uqfo##VMm^14WwmJ&KWzpsJpU8sy4^UXbADnl@MiFz-Dj|@ zr1@~B;G(fyI_B3`_*8^XLLl2T^;YSfyfjQjWL&!NF=vE@g+=e~$E4W{?#H;o{mDv( z=!UL#Vad|FyOTN4*|thp*OJ*saqrlJW>Yy^U}pi$dKGC2u)Xfv-xhsM#BKw?uF#oe z7>W4?-H|wiX6YY8MxurEXA}I8phS^4)U)S_wGF}vX0QyOIveYPPUG+E=*coaW7V4x zUBVr&i5XnLH*2IopGVb$*#`zzG&kby|492u|A;Zkz72o%TS&nPe4j6p@zXS5izhg> zYb>b1ARPQ{)6IDD3~Q#C|7LG>+ejnX*BUa?RdG#y4RT`DW{g~r1p@M#4LDxO3Z%j=KM|pRb>m2rEAGjv0 z3+t`O?dl4`mw3WT#ZYIgCxJZ^)6$vEQO9{rsEV?-AF(O)NK|*cf>N1Imui%~hKU!* zs?8cHuWw5vuI`lv$F1XAzo$xMo2dGm;Pc4N9xp6$|AnY*&7tt_?|_k&>jx`(8aOUhj8#!IdHfgq@&)|g-i73e5rYiW&QeLC(-%+d!qAb-CQgQ6)nb9JBL%9@Y{f6DJ@HE|@BKPw zHg-~KMdmu|dpu(0(}#{Iu(>`W@t1S5bAqQjrCmkt<(b-S9S~%<(|_Ei!m?Cll$Y=v zE~^n^*sudja*0>C@|B##{_tUW6nd#DOvNSeF znO%q%n_4o5g&z2$akHtIoJt=pB*(iRpds46)Nj}(lW$X(A+UgTIOwT2KA)VdvliZ! zW)X}_=E77p%FI<=t2k;8-*yQBcK2GNH@~u$#(EX@D}4pNttfu0PG$lYhuF@>-&r(D z^NC$-1fDxLnSG)Ok$#~VFlVRU?mwM@<<>>${gaf#TX`)8ihN$l@Nt?w4yGQ_5^~{1DeK;S3p{$u@r2OmoD0D=sY4;%cuilmPaNz{ULX3b#!P zJoYx+P{b7ETAjvNm@u*|J#4MmA6oJvu(kzDWM6yR2!h}GU2}ryxk9G5cAHR2f{8X^ z`V!~~sa15BczWJi3YM==zB;-@AT12NmKBz9ZFjXMiuQV5raK^m^6Uqh$ Date: Tue, 15 Jul 2025 16:36:51 +0800 Subject: [PATCH 028/111] ci: update Claude workflow to enhance PR assistance functionality - Renamed workflow from "Claude Code Review" to "Claude PR Assistant" - Updated event triggers to include issue comments, pull request review comments, and issues - Simplified job conditions for running the Claude action - Changed step name to "Run Claude PR Action" and adjusted parameters for improved integration Signed-off-by: Innei --- .github/workflows/claude-code-review.yml | 77 ++++++------------------ 1 file changed, 19 insertions(+), 58 deletions(-) diff --git a/.github/workflows/claude-code-review.yml b/.github/workflows/claude-code-review.yml index 2c3a718f8..20ac17a26 100644 --- a/.github/workflows/claude-code-review.yml +++ b/.github/workflows/claude-code-review.yml @@ -1,77 +1,38 @@ -name: Claude Code Review +name: Claude PR Assistant on: - pull_request: - types: [opened, synchronize] - # Optional: Only run on specific file changes - # paths: - # - "src/**/*.ts" - # - "src/**/*.tsx" - # - "src/**/*.js" - # - "src/**/*.jsx" + issue_comment: + types: [created] + pull_request_review_comment: + types: [created] + issues: + types: [opened, assigned] + pull_request_review: + types: [submitted] jobs: - claude-review: - # Optional: Filter by PR author - # if: | - # github.event.pull_request.user.login == 'external-contributor' || - # github.event.pull_request.user.login == 'new-developer' || - # github.event.pull_request.author_association == 'FIRST_TIME_CONTRIBUTOR' - + claude-code-action: + if: | + (github.event_name == 'issue_comment' && contains(github.event.comment.body, '@claude')) || + (github.event_name == 'pull_request_review_comment' && contains(github.event.comment.body, '@claude')) || + (github.event_name == 'pull_request_review' && contains(github.event.review.body, '@claude')) || + (github.event_name == 'issues' && contains(github.event.issue.body, '@claude')) runs-on: ubuntu-latest permissions: contents: read pull-requests: read issues: read id-token: write - steps: - name: Checkout repository uses: actions/checkout@v4 with: fetch-depth: 1 - - name: Run Claude Code Review - id: claude-review + - name: Run Claude PR Action uses: anthropics/claude-code-action@beta with: + # anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }} + # Or use OAuth token instead: claude_code_oauth_token: ${{ secrets.CLAUDE_CODE_OAUTH_TOKEN }} - - # Optional: Specify model (defaults to Claude Sonnet 4, uncomment for Claude Opus 4) - # model: "claude-opus-4-20250514" - - # Direct prompt for automated review (no @claude mention needed) - direct_prompt: | - Please review this pull request and provide feedback on: - - Code quality and best practices - - Potential bugs or issues - - Performance considerations - - Security concerns - - Test coverage - - Be constructive and helpful in your feedback. - - # Optional: Use sticky comments to make Claude reuse the same comment on subsequent pushes to the same PR - # use_sticky_comment: true - - # Optional: Customize review based on file types - # direct_prompt: | - # Review this PR focusing on: - # - For TypeScript files: Type safety and proper interface usage - # - For API endpoints: Security, input validation, and error handling - # - For React components: Performance, accessibility, and best practices - # - For tests: Coverage, edge cases, and test quality - - # Optional: Different prompts for different authors - # direct_prompt: | - # ${{ github.event.pull_request.author_association == 'FIRST_TIME_CONTRIBUTOR' && - # 'Welcome! Please review this PR from a first-time contributor. Be encouraging and provide detailed explanations for any suggestions.' || - # 'Please provide a thorough code review focusing on our coding standards and best practices.' }} - - # Optional: Add specific tools for running tests or linting - # allowed_tools: "Bash(npm run test),Bash(npm run lint),Bash(npm run typecheck)" - - # Optional: Skip review for certain conditions - # if: | - # !contains(github.event.pull_request.title, '[skip-review]') && - # !contains(github.event.pull_request.title, '[WIP]') + timeout_minutes: "60" From 18b7407534ce69712fc98a157e7df7b63050f6e4 Mon Sep 17 00:00:00 2001 From: Stephen Zhou <38493346+hyoban@users.noreply.github.com> Date: Tue, 15 Jul 2025 18:18:03 +0800 Subject: [PATCH 029/111] fix(mobile): remove text in Logo --- apps/mobile/src/components/ui/logo/index.tsx | 1 - 1 file changed, 1 deletion(-) diff --git a/apps/mobile/src/components/ui/logo/index.tsx b/apps/mobile/src/components/ui/logo/index.tsx index 2ba7e4e4a..0c7aa9659 100644 --- a/apps/mobile/src/components/ui/logo/index.tsx +++ b/apps/mobile/src/components/ui/logo/index.tsx @@ -7,7 +7,6 @@ import { accentColor } from "@/src/theme/colors" export const Logo: React.FC<{ color?: string } & SvgProps> = ({ color = accentColor, ...rest }) => { return ( - Folo Date: Wed, 16 Jul 2025 00:32:32 +0800 Subject: [PATCH 030/111] feat: sort feed by subscription count or update per week, persist analytics data, close #4140 --- .../src/modules/settings/tabs/feeds.tsx | 195 ++++++++---------- .../internal/database/src/services/feed.ts | 14 +- packages/internal/store/src/feed/hooks.ts | 8 + packages/internal/store/src/feed/store.ts | 55 ++++- 4 files changed, 157 insertions(+), 115 deletions(-) diff --git a/apps/desktop/layer/renderer/src/modules/settings/tabs/feeds.tsx b/apps/desktop/layer/renderer/src/modules/settings/tabs/feeds.tsx index 48942a40b..a71143c33 100644 --- a/apps/desktop/layer/renderer/src/modules/settings/tabs/feeds.tsx +++ b/apps/desktop/layer/renderer/src/modules/settings/tabs/feeds.tsx @@ -21,23 +21,17 @@ import { } from "@follow/components/ui/tooltip/index.js" import { EllipsisHorizontalTextWithTooltip } from "@follow/components/ui/typography/index.js" import { views } from "@follow/constants" -import type { ExtractBizResponse } from "@follow/models" import { getFeedById } from "@follow/store/feed/getter" -import { useFeedById } from "@follow/store/feed/hooks" +import { useFeedById, usePrefetchFeedAnalytics } from "@follow/store/feed/hooks" import { getSubscriptionByFeedId } from "@follow/store/subscription/getter" import { useAllFeedSubscriptionIds, useSubscriptionByFeedId, } from "@follow/store/subscription/hooks" -import { jotaiStore } from "@follow/utils/jotai" import { clsx, formatNumber, sortByAlphabet } from "@follow/utils/utils" -import { useSingleton } from "foxact/use-singleton" -import type { PrimitiveAtom } from "jotai" -import { atom, useAtomValue } from "jotai" -import { selectAtom } from "jotai/utils" import { AnimatePresence, m } from "motion/react" import type { FC } from "react" -import { memo, useCallback, useEffect, useMemo, useRef, useState } from "react" +import { memo, useCallback, useEffect, useMemo, useState } from "react" import { useTranslation } from "react-i18next" import { useIsInMASReview } from "~/atoms/server-configs" @@ -51,15 +45,13 @@ import { import { useDialog } from "~/components/ui/modal/stacked/hooks" import { useBatchUpdateSubscription } from "~/hooks/biz/useSubscriptionActions" import { useAuthQuery } from "~/hooks/common" -import { apiClient } from "~/lib/api-fetch" import { UrlBuilder } from "~/lib/url-builder" import { FeedIcon } from "~/modules/feed/feed-icon" import { useConfirmUnsubscribeSubscriptionModal } from "~/modules/modal/hooks/useConfirmUnsubscribeSubscriptionModal" import { Balance } from "~/modules/wallet/balance" import { Queries } from "~/queries" -type Analytics = ExtractBizResponse["data"]["analytics"] -type SortField = "name" | "view" | "date" +type SortField = "name" | "view" | "date" | "subscriptionCount" | "updatesPerWeek" type SortDirection = "asc" | "desc" export const SettingFeeds = () => { @@ -72,7 +64,7 @@ export const SettingFeeds = () => { ) } -const GRID_COLS_CLASSNAME = tw`grid-cols-[30px_auto_150px_150px_100px]` +const GRID_COLS_CLASSNAME = tw`grid-cols-[30px_auto_100px_150px_60px_60px]` const SubscriptionFeedsSection = () => { const { t } = useTranslation("settings") @@ -152,59 +144,7 @@ const SubscriptionFeedsSection = () => { } }, [scrollContainerElement]) - const isFetchedSetRef = useSingleton(() => new Set()) - const [analytics] = useState(() => atom({})) - - const pendingFetchIdsRef = useRef>(new Set()) - const timeoutRef = useRef>(undefined) - - useEffect(() => { - if (timeoutRef.current) { - clearTimeout(timeoutRef.current) - } - - visibleableFeedIds.forEach((id) => { - if (!isFetchedSetRef.current.has(id)) { - pendingFetchIdsRef.current.add(id) - } - }) - - timeoutRef.current = setTimeout(() => { - const fetchedIds = Array.from(pendingFetchIdsRef.current) - if (fetchedIds.length > 0) { - fetchedIds.forEach((id) => { - isFetchedSetRef.current.add(id) - }) - - // Clear pending batch - pendingFetchIdsRef.current.clear() - - apiClient.feeds.analytics - .$post({ - json: { - id: fetchedIds, - }, - }) - .then((res) => { - jotaiStore.set(analytics, { - ...jotaiStore.get(analytics), - ...res.data.analytics, - }) - }) - .catch((_error) => { - fetchedIds.forEach((id) => { - isFetchedSetRef.current.delete(id) - }) - }) - } - }, 200) - - return () => { - if (timeoutRef.current) { - clearTimeout(timeoutRef.current) - } - } - }, [analytics, isFetchedSetRef, visibleableFeedIds]) + usePrefetchFeedAnalytics(Array.from(visibleableFeedIds)) return (
@@ -252,7 +192,26 @@ const SubscriptionFeedsSection = () => {
{sortDirection === "asc" ? "↑" : "↓"} )} -
Analytics
+ +
{/* Feed List */} @@ -261,7 +220,6 @@ const SubscriptionFeedsSection = () => { sortField={sortField} sortDirection={sortDirection} selectedFeeds={selectedFeeds} - analyticsAtom={analytics} onSelect={handleSelectFeed} /> @@ -326,12 +284,11 @@ const SubscriptionFeedsSection = () => { const SortedFeedsList: FC<{ feeds: string[] - analyticsAtom: PrimitiveAtom sortField: SortField sortDirection: SortDirection selectedFeeds: Set onSelect: (feedId: string, checked: boolean) => void -}> = ({ feeds, sortField, sortDirection, selectedFeeds, onSelect, analyticsAtom }) => { +}> = ({ feeds, sortField, sortDirection, selectedFeeds, onSelect }) => { const sortedFeedIds = useMemo(() => { switch (sortField) { case "date": { @@ -372,6 +329,32 @@ const SortedFeedsList: FC<{ : sortByAlphabet(bCompareTitle, aCompareTitle) }) } + case "updatesPerWeek": { + return feeds.sort((a, b) => { + const aSubscription = getSubscriptionByFeedId(a) + const bSubscription = getSubscriptionByFeedId(b) + if (!aSubscription || !bSubscription) return 0 + const aFeed = getFeedById(a) + const bFeed = getFeedById(b) + if (!aFeed || !bFeed) return 0 + return sortDirection === "asc" + ? (aFeed.updatesPerWeek || 0) - (bFeed.updatesPerWeek || 0) + : (bFeed.updatesPerWeek || 0) - (aFeed.updatesPerWeek || 0) + }) + } + case "subscriptionCount": { + return feeds.sort((a, b) => { + const aSubscription = getSubscriptionByFeedId(a) + const bSubscription = getSubscriptionByFeedId(b) + if (!aSubscription || !bSubscription) return 0 + const aFeed = getFeedById(a) + const bFeed = getFeedById(b) + if (!aFeed || !bFeed) return 0 + return sortDirection === "asc" + ? (aFeed.subscriptionCount || 0) - (bFeed.subscriptionCount || 0) + : (bFeed.subscriptionCount || 0) - (aFeed.subscriptionCount || 0) + }) + } } }, [feeds, sortDirection, sortField]) @@ -381,7 +364,6 @@ const SortedFeedsList: FC<{ key={feedId} selected={selectedFeeds.has(feedId)} onSelect={onSelect} - analyticsAtom={analyticsAtom} /> )) } @@ -419,16 +401,11 @@ const FeedListItem = memo( id, selected, onSelect, - analyticsAtom, }: { id: string selected: boolean onSelect: (feedId: string, checked: boolean) => void - analyticsAtom: PrimitiveAtom }) => { - const analytics = useAtomValue( - useMemo(() => selectAtom(analyticsAtom, (a) => a[id]), [analyticsAtom, id]), - ) const subscription = useSubscriptionByFeedId(id) const feed = useFeedById(id) const isCustomizeName = subscription?.title && feed?.title !== subscription?.title @@ -490,43 +467,45 @@ const FeedListItem = memo( )}
- {analytics ? ( -
-
- - -
- - - {formatNumber(analytics.subscriptionCount || 0)} - -
-
- - Subscription Count - -
- - -
- - - {Math.round(analytics.updatesPerWeek || 0) || "0"} - {"/w"} - -
-
- - Updates Per Week - -
-
- {analytics.latestEntryPublishedAt && ( + {feed?.subscriptionCount ? ( + + +
+ + {formatNumber(feed.subscriptionCount)} +
+
+ + Subscription Count + +
+ ) : ( +
--
+ )} +
+
+ {feed?.updatesPerWeek ? ( +
+ + +
+ + + {Math.round(feed.updatesPerWeek)} + {"/w"} + +
+
+ + Updates Per Week + +
+ {feed.latestEntryPublishedAt && (
- +
Latest Entry Published diff --git a/packages/internal/database/src/services/feed.ts b/packages/internal/database/src/services/feed.ts index 8498163a5..93d7447f1 100644 --- a/packages/internal/database/src/services/feed.ts +++ b/packages/internal/database/src/services/feed.ts @@ -1,9 +1,17 @@ +import { eq } from "drizzle-orm" + import { db } from "../db" import { feedsTable } from "../schemas" import type { FeedSchema } from "../schemas/types" import type { Resetable } from "./internal/base" import { conflictUpdateAllExcept } from "./internal/utils" +export const FEED_EXTRA_DATA_KEYS = [ + "subscriptionCount", + "updatesPerWeek", + "latestEntryPublishedAt", +] as const + class FeedServiceStatic implements Resetable { async reset() { await db.delete(feedsTable).execute() @@ -15,13 +23,17 @@ class FeedServiceStatic implements Resetable { .values(feed) .onConflictDoUpdate({ target: [feedsTable.id], - set: conflictUpdateAllExcept(feedsTable, ["id"]), + set: conflictUpdateAllExcept(feedsTable, ["id", ...FEED_EXTRA_DATA_KEYS]), }) } getFeedAll() { return db.query.feedsTable.findMany() } + + async patch(feedId: string, patch: Partial) { + await db.update(feedsTable).set(patch).where(eq(feedsTable.id, feedId)).execute() + } } export const FeedService = new FeedServiceStatic() diff --git a/packages/internal/store/src/feed/hooks.ts b/packages/internal/store/src/feed/hooks.ts index b85e57cd0..db6c7f33f 100644 --- a/packages/internal/store/src/feed/hooks.ts +++ b/packages/internal/store/src/feed/hooks.ts @@ -65,3 +65,11 @@ export const usePrefetchFeedByUrl = (url: string, options?: GeneralQueryOptions) queryFn: () => feedSyncServices.fetchFeedByUrl({ url }), }) } + +export const usePrefetchFeedAnalytics = (id: string | string[], options?: GeneralQueryOptions) => { + return useQuery({ + ...options, + queryKey: ["feed", "analytics", id], + queryFn: () => feedSyncServices.fetchAnalytics(id), + }) +} diff --git a/packages/internal/store/src/feed/store.ts b/packages/internal/store/src/feed/store.ts index 7d2ab2a87..3fda0e2f1 100644 --- a/packages/internal/store/src/feed/store.ts +++ b/packages/internal/store/src/feed/store.ts @@ -1,5 +1,5 @@ import type { FeedSchema } from "@follow/database/schemas/types" -import { FeedService } from "@follow/database/services/feed" +import { FEED_EXTRA_DATA_KEYS, FeedService } from "@follow/database/services/feed" import { isBizId } from "@follow/utils" import { apiClient } from "../context" @@ -32,15 +32,23 @@ class FeedActions implements Hydratable, Resetable { upsertManyInSession(feeds: FeedSchema[]) { immerSet((draft) => { for (const feed of feeds) { + const data = Object.fromEntries( + FEED_EXTRA_DATA_KEYS.filter((key) => (draft.feeds[feed.id] || {})[key]).map((key) => [ + key, + draft.feeds[feed.id]?.[key], + ]), + ) + draft.feeds[feed.id] = { ...feed, + ...data, type: "feed", } } }) } - upsertMany(feeds: FeedSchema[]) { + async upsertMany(feeds: FeedSchema[]) { if (feeds.length === 0) return const tx = createTransaction() @@ -52,10 +60,10 @@ class FeedActions implements Hydratable, Resetable { await FeedService.upsertMany(feeds.filter((feed) => !("nonce" in feed))) }) - tx.run() + await tx.run() } - patch(feedId: string, patch: Partial) { + patchInSession(feedId: string, patch: Partial) { immerSet((state) => { const feed = state.feeds[feedId] if (!feed) return @@ -63,6 +71,17 @@ class FeedActions implements Hydratable, Resetable { }) } + async patch(feedId: string, patch: Partial) { + const tx = createTransaction() + tx.store(() => { + this.patchInSession(feedId, patch) + }) + tx.persist(() => { + return FeedService.patch(feedId, patch) + }) + await tx.run() + } + async reset() { const tx = createTransaction() tx.store(() => { @@ -146,7 +165,7 @@ class FeedSyncServices { const tx = createTransaction() tx.store(() => { - feedActions.patch(feedId, { + feedActions.patchInSession(feedId, { ownerUserId: whoami()?.id || null, }) }) @@ -166,13 +185,37 @@ class FeedSyncServices { }) tx.rollback(() => { - feedActions.patch(feedId, { + feedActions.patchInSession(feedId, { ownerUserId: curFeed.ownerUserId, }) }) await tx.run() } + + async fetchAnalytics(feedId: string | string[]) { + const feedIds = Array.isArray(feedId) ? feedId : [feedId] + const res = await apiClient().feeds.analytics.$post({ + json: { + id: feedIds, + }, + }) + + const { analytics } = res.data + + for (const id of feedIds) { + const feedAnalytics = analytics[id] + if (feedAnalytics) { + await feedActions.patch(id, { + subscriptionCount: feedAnalytics.subscriptionCount, + updatesPerWeek: feedAnalytics.updatesPerWeek, + latestEntryPublishedAt: feedAnalytics.latestEntryPublishedAt, + }) + } + } + + return analytics + } } export const feedSyncServices = new FeedSyncServices() export const feedActions = new FeedActions() From 3e8bc5840b93d4941a6e56da411000c3e7ea5209 Mon Sep 17 00:00:00 2001 From: Stephen Zhou <38493346+hyoban@users.noreply.github.com> Date: Wed, 16 Jul 2025 00:46:32 +0800 Subject: [PATCH 031/111] fix: allow mark read/unread for started entry, close #3514 --- .../layer/renderer/src/hooks/biz/useEntryActions.tsx | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/apps/desktop/layer/renderer/src/hooks/biz/useEntryActions.tsx b/apps/desktop/layer/renderer/src/hooks/biz/useEntryActions.tsx index 2600b7830..0efcd6c04 100644 --- a/apps/desktop/layer/renderer/src/hooks/biz/useEntryActions.tsx +++ b/apps/desktop/layer/renderer/src/hooks/biz/useEntryActions.tsx @@ -29,6 +29,8 @@ import { useCommandShortcuts } from "~/modules/command/hooks/use-command-binding import type { FollowCommandId } from "~/modules/command/types" import { useToolbarOrderMap } from "~/modules/customize-toolbar/hooks" +import { useRouteParams } from "./useRouteParams" + export const enableEntryReadability = async ({ id, url }: { id: string; url: string }) => { const status = getReadabilityStatus()[id] const isTurnOn = status !== ReadabilityStatus.INITIAL && !!status @@ -154,6 +156,7 @@ export const useEntryActions = ({ compact?: boolean }) => { const entry = useEntry(entryId, entrySelector) + const { isCollection } = useRouteParams() const isInCollection = useIsEntryStarred(entryId) const isEntryInReadability = useEntryIsInReadability(entryId) @@ -320,13 +323,13 @@ export const useEntryActions = ({ new EntryActionMenuItem({ id: COMMAND_ID.entry.readAbove, onClick: runCmdFn(COMMAND_ID.entry.readAbove, [{ publishedAt: entry.publishedAt }]), - hide: !!isInCollection, + hide: !!isCollection, entryId, }), new EntryActionMenuItem({ id: COMMAND_ID.entry.read, onClick: runCmdFn(COMMAND_ID.entry.read, [{ entryId }]), - hide: !!isInCollection, + hide: !!isCollection, active: !!entry.read, shortcut: shortcuts[COMMAND_ID.entry.read], entryId, @@ -334,7 +337,7 @@ export const useEntryActions = ({ new EntryActionMenuItem({ id: COMMAND_ID.entry.readBelow, onClick: runCmdFn(COMMAND_ID.entry.readBelow, [{ publishedAt: entry.publishedAt }]), - hide: !!isInCollection, + hide: !!isCollection, entryId, }), MENU_ITEM_SEPARATOR, @@ -392,6 +395,7 @@ export const useEntryActions = ({ isInbox, shortcuts, view, + isCollection, isInCollection, isShowSourceContent, isShowAISummaryAuto, From 694798c9d9d25208a64d2313a8c648f1b26860d3 Mon Sep 17 00:00:00 2001 From: Stephen Zhou <38493346+hyoban@users.noreply.github.com> Date: Wed, 16 Jul 2025 00:56:03 +0800 Subject: [PATCH 032/111] fix: can not view feed with invalid siteUrl, close #4032 --- packages/internal/store/src/subscription/utils.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/internal/store/src/subscription/utils.ts b/packages/internal/store/src/subscription/utils.ts index 2e7009653..8c7b58cf9 100644 --- a/packages/internal/store/src/subscription/utils.ts +++ b/packages/internal/store/src/subscription/utils.ts @@ -19,5 +19,5 @@ export const getDefaultCategory = (subscription?: SubscriptionModel) => { const siteUrl = getFeedById(feedId)?.siteUrl if (!siteUrl) return null const parsed = parseUrl(siteUrl) - return parsed?.domain ? capitalizeFirstLetter(parsed.domain) : null + return parsed?.domain ? capitalizeFirstLetter(parsed.domain) : siteUrl } From 943ef310850f219cc0f6f02b63dee7e044233395 Mon Sep 17 00:00:00 2001 From: DIYgod Date: Wed, 16 Jul 2025 12:13:59 +0800 Subject: [PATCH 033/111] feat(desktop): add custom AppX manifest generation for Microsoft Store MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Create AppX manifest generation script using template file - Add support for multiple languages (EN, ZH-CN, ZH-TW, JA) - Include protocol handlers for folo and follow schemes - Add OPML file type association - Update Electron Forge config to use custom manifest - Add build:electron-forge:ms script for Microsoft Store builds - Update GitHub Actions workflow to use custom build for store distribution 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude --- .github/workflows/build-desktop.yml | 15 +-- .gitignore | 4 +- apps/desktop/build/appxmanifest-template.xml | 43 +++++++ apps/desktop/forge.config.cts | 1 + apps/desktop/package.json | 1 + .../desktop/scripts/generate-appx-manifest.ts | 110 ++++++++++++++++++ 6 files changed, 166 insertions(+), 8 deletions(-) create mode 100644 apps/desktop/build/appxmanifest-template.xml create mode 100644 apps/desktop/scripts/generate-appx-manifest.ts diff --git a/.github/workflows/build-desktop.yml b/.github/workflows/build-desktop.yml index 0607e0910..235a6dd3b 100644 --- a/.github/workflows/build-desktop.yml +++ b/.github/workflows/build-desktop.yml @@ -32,6 +32,7 @@ env: VITE_OPENPANEL_CLIENT_ID: ${{ vars.VITE_OPENPANEL_CLIENT_ID }} VITE_OPENPANEL_API_URL: ${{ vars.VITE_OPENPANEL_API_URL }} VITE_FIREBASE_CONFIG: ${{ vars.VITE_FIREBASE_CONFIG }} + SENTRY_AUTH_TOKEN: ${{ secrets.SENTRY_AUTH_TOKEN }} NODE_OPTIONS: --max-old-space-size=8192 jobs: @@ -137,14 +138,11 @@ jobs: - name: Build - Vite working-directory: apps/desktop run: pnpm build:electron-vite ${{ env.PROD == 'false' && '--mode staging' || '' }} - env: - SENTRY_AUTH_TOKEN: ${{ secrets.SENTRY_AUTH_TOKEN }} + - name: Build - Windows and Linux - if: runner.os != 'macOS' + if: runner.os == 'Linux' || (runner.os == 'Windows' && github.event.inputs.store != 'true') working-directory: apps/desktop run: pnpm build:electron-forge ${{ env.PROD == 'false' && '--mode=staging' || '' }} - env: - SENTRY_AUTH_TOKEN: ${{ secrets.SENTRY_AUTH_TOKEN }} - name: Build - macOS if: runner.os == 'macOS' && github.event.inputs.store != 'true' @@ -174,12 +172,15 @@ jobs: working-directory: apps/desktop run: pnpm build:electron-forge:mas + - name: Build - Microsoft Store + if: runner.os == 'Windows' && github.event.inputs.store == 'true' + working-directory: apps/desktop + run: pnpm build:electron-forge:ms + - name: Build - Renderer if: runner.os == 'Linux' working-directory: apps/desktop run: pnpm build:render - env: - SENTRY_AUTH_TOKEN: ${{ secrets.SENTRY_AUTH_TOKEN }} - name: Upload file (macos-arm64-dmg) uses: actions/upload-artifact@v4 diff --git a/.gitignore b/.gitignore index e6b9088ef..625406b86 100644 --- a/.gitignore +++ b/.gitignore @@ -23,4 +23,6 @@ apps/desktop/src/renderer/dev-dist tsconfig.tsbuildinfo buildServer.json -**/**/generated-routes.ts \ No newline at end of file +**/**/generated-routes.ts + +apps/desktop/build/appxmanifest.xml diff --git a/apps/desktop/build/appxmanifest-template.xml b/apps/desktop/build/appxmanifest-template.xml new file mode 100644 index 000000000..a902bf35a --- /dev/null +++ b/apps/desktop/build/appxmanifest-template.xml @@ -0,0 +1,43 @@ + + + + + {packageDisplayName} + {publisherDisplayName} + No description entered + assets\SampleAppx.50x50.png + + + + + + + + + + + + + + + + + + + {protocol} + + + + diff --git a/apps/desktop/forge.config.cts b/apps/desktop/forge.config.cts index 88b5499e7..dca34077f 100644 --- a/apps/desktop/forge.config.cts +++ b/apps/desktop/forge.config.cts @@ -212,6 +212,7 @@ const config: ForgeConfig = { packageDisplayName: "Folo - Follow everything in one place", devCert: "build/dev.pfx", assets: "static/appx", + manifest: "build/appxmanifest.xml", // @ts-ignore publisherDisplayName: "Natural Selection Labs", identityName: "NaturalSelectionLabs.Follow-Yourfavoritesinoneinbo", diff --git a/apps/desktop/package.json b/apps/desktop/package.json index d5264b1dc..f1f22aa16 100644 --- a/apps/desktop/package.json +++ b/apps/desktop/package.json @@ -17,6 +17,7 @@ "build:electron-forge": "electron-forge make", "build:electron-forge:macos": "electron-forge make --arch=x64 --platform=darwin && electron-forge make --arch=arm64 --platform=darwin && tsx scripts/merge-yml.ts", "build:electron-forge:mas": "electron-forge make --arch=universal --platform=mas", + "build:electron-forge:ms": "tsx scripts/generate-appx-manifest.ts && electron-forge make --platform=win32", "build:electron-vite": "electron-vite build", "build:render": "vite build -c vite.config.electron-render.ts", "build:web": "rm -rf out/web && cross-env WEB_BUILD=1 vite build", diff --git a/apps/desktop/scripts/generate-appx-manifest.ts b/apps/desktop/scripts/generate-appx-manifest.ts new file mode 100644 index 000000000..6fcd511d6 --- /dev/null +++ b/apps/desktop/scripts/generate-appx-manifest.ts @@ -0,0 +1,110 @@ +#!/usr/bin/env tsx + +import fs from "node:fs" + +import path from "pathe" + +interface AppXManifestConfig { + packageName: string + packageDisplayName: string + publisherDisplayName: string + identityName: string + version: string + publisher: string + packageBackgroundColor: string + protocols: string[] + description: string + appBundleId: string +} + +function generateAppXManifest(config: AppXManifestConfig, templatePath: string): string { + // Read template file + const template = fs.readFileSync(templatePath, "utf-8") + + // Generate protocol extensions + const protocolExtensions = config.protocols + .map( + (protocol) => ` + + + `, + ) + .join("") + + // Replace template variables + const manifest = template + .replaceAll("{identityName}", config.identityName) + .replaceAll("{publisherName}", config.publisher) + .replaceAll("{packageVersion}", config.version) + .replaceAll("{packageDisplayName}", config.packageDisplayName) + .replaceAll("{publisherDisplayName}", config.publisherDisplayName) + .replaceAll("{packageName}", config.packageName) + .replaceAll("{packageExecutable}", `app\\${config.packageName}.exe`) + .replaceAll("{packageBackgroundColor}", config.packageBackgroundColor) + .replaceAll("{packageDescription}", config.description) + .replaceAll("{protocol}", protocolExtensions) + + return manifest +} + +async function main() { + try { + // Read package.json to get app information + const packageJsonPath = path.resolve(process.cwd(), "package.json") + const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, "utf-8")) + + // Get mode from command line arguments + const mode = process.argv.find((arg) => arg.startsWith("--mode"))?.split("=")[1] + const isStaging = mode === "staging" + + // Parse version for AppX format (must be x.x.x.x) + const { version } = packageJson + const versionParts = version.split(".") + // Ensure we have 4 parts for AppX version format + while (versionParts.length < 4) { + versionParts.push("0") + } + const appxVersion = versionParts.slice(0, 4).join(".") + + const config: AppXManifestConfig = { + packageName: "Folo", + packageDisplayName: isStaging + ? "Folo Staging - Follow everything in one place" + : "Folo - Follow everything in one place", + publisherDisplayName: "Natural Selection Labs", + identityName: "NaturalSelectionLabs.Follow-Yourfavoritesinoneinbo", + version: appxVersion, + publisher: "CN=7CBBEB6A-9B0E-4387-BAE3-576D0ACA279E", + packageBackgroundColor: "#FF5C00", + protocols: ["folo", "follow"], + description: "Follow everything in one place.", + appBundleId: "is.follow", + } + + // Template file path + const templatePath = path.resolve(process.cwd(), "build/appxmanifest-template.xml") + + if (!fs.existsSync(templatePath)) { + throw new Error(`Template file not found: ${templatePath}`) + } + + const manifest = generateAppXManifest(config, templatePath) + + // Ensure output directory exists + const outputDir = path.resolve(process.cwd(), "build") + if (!fs.existsSync(outputDir)) { + fs.mkdirSync(outputDir, { recursive: true }) + } + + // Write manifest file + const outputPath = path.resolve(outputDir, "appxmanifest.xml") + fs.writeFileSync(outputPath, manifest, "utf-8") + } catch (error) { + console.error("❌ Failed to generate AppX manifest:", error) + process.exit(1) + } +} + +main() + +export { type AppXManifestConfig, generateAppXManifest } From d05fb12cc66ccd16132c709caa116be7a21f449e Mon Sep 17 00:00:00 2001 From: DIYgod Date: Wed, 16 Jul 2025 12:32:40 +0800 Subject: [PATCH 034/111] feat(desktop): add preMake hook to clean temporary files before build - Implement preMake hook to remove temporary files in the output directory - Enhance build process by ensuring a clean state prior to execution --- apps/desktop/forge.config.cts | 3 +++ 1 file changed, 3 insertions(+) diff --git a/apps/desktop/forge.config.cts b/apps/desktop/forge.config.cts index dca34077f..f5f8e44b4 100644 --- a/apps/desktop/forge.config.cts +++ b/apps/desktop/forge.config.cts @@ -245,6 +245,9 @@ const config: ForgeConfig = { }, ], hooks: { + preMake: async () => { + await rimraf("out/**/*.tmp") + }, postMake: async (_config, makeResults) => { const yml: { version?: string From 451ed295c1188f8a5c3b54d7f7111ba8531d2b7a Mon Sep 17 00:00:00 2001 From: DIYgod Date: Wed, 16 Jul 2025 12:38:45 +0800 Subject: [PATCH 035/111] fix(desktop): improve Windows AppX build by cleaning temporary files MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Fixes ENOENT errors during AppX packaging by properly cleaning .tmp files before build starts. Replaces glob pattern with explicit file iteration to avoid "Illegal characters in path" errors. 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude --- apps/desktop/forge.config.cts | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/apps/desktop/forge.config.cts b/apps/desktop/forge.config.cts index f5f8e44b4..dfc69dc5e 100644 --- a/apps/desktop/forge.config.cts +++ b/apps/desktop/forge.config.cts @@ -246,7 +246,16 @@ const config: ForgeConfig = { ], hooks: { preMake: async () => { - await rimraf("out/**/*.tmp") + // Clean up possible temporary files + const outDir = path.resolve(process.cwd(), "out") + if (fs.existsSync(outDir)) { + const files = await readdir(outDir, { recursive: true }) + for (const file of files) { + if (file.toString().endsWith(".tmp")) { + await rimraf(path.join(outDir, file.toString())) + } + } + } }, postMake: async (_config, makeResults) => { const yml: { From ee52eec0b3c1a3f07a06677ce139c7e34e9456a0 Mon Sep 17 00:00:00 2001 From: DIYgod Date: Wed, 16 Jul 2025 13:01:22 +0800 Subject: [PATCH 036/111] feat(desktop): enhance build configuration for Microsoft Store support - Introduce a flag to determine if the build is for the Microsoft Store - Conditionally include AppX maker for Microsoft Store builds and Squirrel maker for others - Update build script to pass the new flag for Microsoft Store builds This change improves the flexibility of the build process by allowing for different packaging strategies based on the target platform. --- apps/desktop/forge.config.cts | 54 ++++++++++++++++------------------- apps/desktop/package.json | 2 +- 2 files changed, 26 insertions(+), 30 deletions(-) diff --git a/apps/desktop/forge.config.cts b/apps/desktop/forge.config.cts index dfc69dc5e..24df2f3d5 100644 --- a/apps/desktop/forge.config.cts +++ b/apps/desktop/forge.config.cts @@ -18,6 +18,8 @@ import { rimraf, rimrafSync } from "rimraf" const platform = process.argv.find((arg) => arg.startsWith("--platform"))?.split("=")[1] const mode = process.argv.find((arg) => arg.startsWith("--mode"))?.split("=")[1] +const isMicrosoftStore = + process.argv.find((arg) => arg.startsWith("--ms"))?.split("=")[1] === "true" const isStaging = mode === "staging" @@ -185,11 +187,6 @@ const config: ForgeConfig = { }, ["darwin", "mas"], ), - new MakerSquirrel({ - name: "Folo", - setupIcon: isStaging ? "resources/icon-staging.ico" : "resources/icon.ico", - iconUrl: "https://app.folo.is/favicon.ico", - }), new MakerAppImage({ config: { icons: [ @@ -207,18 +204,29 @@ const config: ForgeConfig = { }, ["mas"], ), - new MakerAppX({ - publisher: "CN=7CBBEB6A-9B0E-4387-BAE3-576D0ACA279E", - packageDisplayName: "Folo - Follow everything in one place", - devCert: "build/dev.pfx", - assets: "static/appx", - manifest: "build/appxmanifest.xml", - // @ts-ignore - publisherDisplayName: "Natural Selection Labs", - identityName: "NaturalSelectionLabs.Follow-Yourfavoritesinoneinbo", - packageBackgroundColor: "#FF5C00", - protocol: "folo", - }), + // Only include AppX maker for Microsoft Store builds + ...(isMicrosoftStore + ? [ + new MakerAppX({ + publisher: "CN=7CBBEB6A-9B0E-4387-BAE3-576D0ACA279E", + packageDisplayName: "Folo - Follow everything in one place", + devCert: "build/dev.pfx", + assets: "static/appx", + manifest: "build/appxmanifest.xml", + // @ts-ignore + publisherDisplayName: "Natural Selection Labs", + identityName: "NaturalSelectionLabs.Follow-Yourfavoritesinoneinbo", + packageBackgroundColor: "#FF5C00", + protocol: "folo", + }), + ] + : [ + new MakerSquirrel({ + name: "Folo", + setupIcon: isStaging ? "resources/icon-staging.ico" : "resources/icon.ico", + iconUrl: "https://app.folo.is/favicon.ico", + }), + ]), ], plugins: [ // Fuses are used to enable/disable various Electron functionality @@ -245,18 +253,6 @@ const config: ForgeConfig = { }, ], hooks: { - preMake: async () => { - // Clean up possible temporary files - const outDir = path.resolve(process.cwd(), "out") - if (fs.existsSync(outDir)) { - const files = await readdir(outDir, { recursive: true }) - for (const file of files) { - if (file.toString().endsWith(".tmp")) { - await rimraf(path.join(outDir, file.toString())) - } - } - } - }, postMake: async (_config, makeResults) => { const yml: { version?: string diff --git a/apps/desktop/package.json b/apps/desktop/package.json index f1f22aa16..4a5ee3bb2 100644 --- a/apps/desktop/package.json +++ b/apps/desktop/package.json @@ -17,7 +17,7 @@ "build:electron-forge": "electron-forge make", "build:electron-forge:macos": "electron-forge make --arch=x64 --platform=darwin && electron-forge make --arch=arm64 --platform=darwin && tsx scripts/merge-yml.ts", "build:electron-forge:mas": "electron-forge make --arch=universal --platform=mas", - "build:electron-forge:ms": "tsx scripts/generate-appx-manifest.ts && electron-forge make --platform=win32", + "build:electron-forge:ms": "tsx scripts/generate-appx-manifest.ts && electron-forge make --platform=win32 --ms=true", "build:electron-vite": "electron-vite build", "build:render": "vite build -c vite.config.electron-render.ts", "build:web": "rm -rf out/web && cross-env WEB_BUILD=1 vite build", From 4ee723675b765c8c8b7557c013424b21c070ab2c Mon Sep 17 00:00:00 2001 From: Stephen Zhou <38493346+hyoban@users.noreply.github.com> Date: Wed, 16 Jul 2025 15:57:40 +0800 Subject: [PATCH 037/111] fix: show custom feed title, close #4177 --- apps/mobile/src/modules/screen/atoms.ts | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/apps/mobile/src/modules/screen/atoms.ts b/apps/mobile/src/modules/screen/atoms.ts index d8fc667aa..4750cf3d5 100644 --- a/apps/mobile/src/modules/screen/atoms.ts +++ b/apps/mobile/src/modules/screen/atoms.ts @@ -20,7 +20,7 @@ import { useFeedById } from "@follow/store/feed/hooks" import { useInboxById } from "@follow/store/inbox/hooks" import { useListById } from "@follow/store/list/hooks" import { getSubscriptionByCategory } from "@follow/store/subscription/getter" -import { useViewWithSubscription } from "@follow/store/subscription/hooks" +import { useSubscriptionByFeedId, useViewWithSubscription } from "@follow/store/subscription/hooks" import { jotaiStore } from "@follow/utils" import { EventBus } from "@follow/utils/event-bus" import { debounce } from "es-toolkit" @@ -345,6 +345,9 @@ export const useSelectedFeedTitle = () => { selectedFeed && selectedFeed.type === "view" ? selectedFeed.viewId : undefined, ) const feed = useFeedById(selectedFeed && selectedFeed.type === "feed" ? selectedFeed.feedId : "") + const feedSubscription = useSubscriptionByFeedId( + selectedFeed && selectedFeed.type === "feed" ? selectedFeed.feedId : "", + ) const list = useListById(selectedFeed && selectedFeed.type === "list" ? selectedFeed.listId : "") const inbox = useInboxById( selectedFeed && selectedFeed.type === "inbox" ? selectedFeed.inboxId : "", @@ -360,7 +363,9 @@ export const useSelectedFeedTitle = () => { return viewDef?.name ? t(viewDef.name) : "" } case "feed": { - return selectedFeed.feedId === FEED_COLLECTION_LIST ? t("words.starred") : (feed?.title ?? "") + return selectedFeed.feedId === FEED_COLLECTION_LIST + ? t("words.starred") + : feedSubscription?.title || feed?.title || "" } case "category": { return selectedFeed.categoryName From be9506ac9cffd9584b0cda955561020670879a34 Mon Sep 17 00:00:00 2001 From: Stephen Zhou <38493346+hyoban@users.noreply.github.com> Date: Wed, 16 Jul 2025 16:13:33 +0800 Subject: [PATCH 038/111] fix: list with unread items being hidden, close #4178 --- packages/internal/store/src/subscription/hooks.ts | 4 ++-- packages/internal/store/src/unread/getters.ts | 10 +++++++++- 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/packages/internal/store/src/subscription/hooks.ts b/packages/internal/store/src/subscription/hooks.ts index fb9b328da..0c0a3faff 100644 --- a/packages/internal/store/src/subscription/hooks.ts +++ b/packages/internal/store/src/subscription/hooks.ts @@ -6,7 +6,7 @@ import { useCallback, useMemo } from "react" import { getFeedById } from "../feed/getter" import { getInboxList } from "../inbox/getters" import { getListById, getListFeedIds } from "../list/getters" -import { getUnreadById } from "../unread/getters" +import { getUnreadById, getUnreadByListId } from "../unread/getters" import { getSubscriptionByCategory, getSubscriptionById } from "./getter" import { folderFeedsByFeedIdSelector } from "./selectors" import { subscriptionSyncService, useSubscriptionStore } from "./store" @@ -359,7 +359,7 @@ export const useSortedListSubscription = ({ useCallback(() => { return ids .concat() - .filter((id) => !hideAllReadSubscriptions || getUnreadById(id) > 0) + .filter((id) => !hideAllReadSubscriptions || getUnreadByListId(id) > 0) .sort((a, b) => { const leftList = getListById(a) const rightList = getListById(b) diff --git a/packages/internal/store/src/unread/getters.ts b/packages/internal/store/src/unread/getters.ts index 026c67037..0e1932d57 100644 --- a/packages/internal/store/src/unread/getters.ts +++ b/packages/internal/store/src/unread/getters.ts @@ -1,4 +1,5 @@ -import { unreadCountAllSelector, unreadCountIdSelector } from "./selectors" +import { getListFeedIds } from "../list/getters" +import { unreadCountAllSelector, unreadCountIdSelector, unreadCountIdsSelector } from "./selectors" import { useUnreadStore } from "./store" import type { FeedIdOrInboxHandle } from "./types" @@ -7,6 +8,13 @@ export const getUnreadById = (id: FeedIdOrInboxHandle) => { return unreadCountIdSelector(id)(state) } +export const getUnreadByListId = (listId: string) => { + const state = useUnreadStore.getState() + const feedIds = getListFeedIds(listId) + if (!feedIds) return 0 + return unreadCountIdsSelector(feedIds)(state) +} + export const getUnreadAll = () => { const state = useUnreadStore.getState() return unreadCountAllSelector(state) From 341fd63bf5ad5bb3e0b9982f4eb6284ba45fad5d Mon Sep 17 00:00:00 2001 From: DIYgod Date: Wed, 16 Jul 2025 18:11:12 +0800 Subject: [PATCH 039/111] fix(desktop): microsoft store build check - Introduce MICROSOFT_STORE_BUILD constant to determine if the app is running from the Microsoft Store - Update appUpdaterConfig to conditionally enable core updates based on the new constant - Modify header creation logic to use MICROSOFT_STORE_BUILD for Windows platform detection This change enhances the application's compatibility with Microsoft Store by ensuring proper update handling and header configuration. --- apps/desktop/layer/main/src/updater/configs.ts | 4 ++-- packages/internal/shared/src/constants.ts | 6 ++++++ packages/internal/utils/src/headers.ts | 4 ++-- 3 files changed, 10 insertions(+), 4 deletions(-) diff --git a/apps/desktop/layer/main/src/updater/configs.ts b/apps/desktop/layer/main/src/updater/configs.ts index 9432099d3..b55ea71bc 100644 --- a/apps/desktop/layer/main/src/updater/configs.ts +++ b/apps/desktop/layer/main/src/updater/configs.ts @@ -1,4 +1,4 @@ -import { DEV, MODE, ModeEnum } from "@follow/shared/constants" +import { DEV, MICROSOFT_STORE_BUILD, MODE, ModeEnum } from "@follow/shared/constants" import path from "pathe" import { isWindows } from "../env" @@ -8,7 +8,7 @@ export const appUpdaterConfig = { enableRenderHotUpdate: !DEV && MODE !== ModeEnum.staging, enableCoreUpdate: !process.mas && - !process.windowsStore && + !MICROSOFT_STORE_BUILD && // Disable core update if platfrom is windows and application is't executing from default installion path. // If the process is not executed from the default installation path, // it is usually managed through a package manager like Scoop. diff --git a/packages/internal/shared/src/constants.ts b/packages/internal/shared/src/constants.ts index b2c0768df..2a9325916 100644 --- a/packages/internal/shared/src/constants.ts +++ b/packages/internal/shared/src/constants.ts @@ -37,3 +37,9 @@ declare const ELECTRON: boolean */ export const ELECTRON_BUILD = !!ELECTRON export const WEB_BUILD = !ELECTRON + +export const MICROSOFT_STORE_BUILD = + typeof process !== "undefined" + ? process.platform === "win32" && + (process.windowsStore || process.execPath.startsWith("C:\\Program Files\\WindowsApps")) + : false diff --git a/packages/internal/utils/src/headers.ts b/packages/internal/utils/src/headers.ts index 8e86a4a7b..e786fc650 100644 --- a/packages/internal/utils/src/headers.ts +++ b/packages/internal/utils/src/headers.ts @@ -1,4 +1,4 @@ -import { DEV, WEB_BUILD } from "@follow/shared/constants" +import { DEV, MICROSOFT_STORE_BUILD, WEB_BUILD } from "@follow/shared/constants" import { imageRefererMatches } from "./img-proxy" @@ -81,7 +81,7 @@ export const createDesktopAPIHeaders = ({ version }: { version: string }) => { break } case "win32": { - if (process.windowsStore) { + if (MICROSOFT_STORE_BUILD) { platform = DesktopPlatform.DesktopWindowsMS } else { platform = DesktopPlatform.DesktopWindowsEXE From e119ab640d5391b22df5a65edbf9fc106b97e902 Mon Sep 17 00:00:00 2001 From: Stephen Zhou <38493346+hyoban@users.noreply.github.com> Date: Wed, 16 Jul 2025 18:20:31 +0800 Subject: [PATCH 040/111] fix: bring action condition compatibility back --- packages/internal/store/src/action/store.ts | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/packages/internal/store/src/action/store.ts b/packages/internal/store/src/action/store.ts index 2e005c4ff..fd03c09c5 100644 --- a/packages/internal/store/src/action/store.ts +++ b/packages/internal/store/src/action/store.ts @@ -1,5 +1,6 @@ import type { ActionConditionIndex, + ActionFilter, ActionFilterItem, ActionId, ActionModel, @@ -27,7 +28,18 @@ class ActionSyncService { const res = await apiClient().actions.$get() if (res.data) { actionActions.updateRules( - (res.data.rules ?? []).map((rule, index) => ({ ...rule, index })) as any, + (res.data.rules ?? []).map((rule, index) => { + const { condition } = rule + // fix old data + const finalCondition = + condition.length === 0 || Array.isArray(condition[0]) ? condition : [condition] + + return { + ...rule, + condition: finalCondition as ActionFilter, + index, + } + }), ) actionActions.setDirty(false) From 1fdf482f3557767d844705dc8ee1a67bf5a2cc39 Mon Sep 17 00:00:00 2001 From: Konv Suu <2583695112@qq.com> Date: Wed, 16 Jul 2025 18:24:07 +0800 Subject: [PATCH 041/111] feat: add notification for timeline switch (#4176) --- .../entry-column/EntryColumnShortcutHandler.tsx | 11 +++++++++++ 1 file changed, 11 insertions(+) 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 1efdb3204..fe4eaa10f 100644 --- a/apps/desktop/layer/renderer/src/modules/entry-column/EntryColumnShortcutHandler.tsx +++ b/apps/desktop/layer/renderer/src/modules/entry-column/EntryColumnShortcutHandler.tsx @@ -8,6 +8,7 @@ import { nextFrame } from "@follow/utils/dom" import { EventBus } from "@follow/utils/event-bus" import type { FC } from "react" import { memo, useEffect } from "react" +import { toast } from "sonner" import { FocusablePresets } from "~/components/common/Focusable" import { useNavigateEntry } from "~/hooks/biz/useNavigateEntry" @@ -63,6 +64,11 @@ export const EntryColumnShortcutHandler: FC<{ const nextIndex = Math.min(currentActiveEntryIndex + 1, data.length - 1) + if (currentActiveEntryIndex === nextIndex) { + toast.info("You are already at the last entry") + return + } + handleScrollTo(nextIndex) const nextId = data![nextIndex] @@ -80,6 +86,11 @@ export const EntryColumnShortcutHandler: FC<{ const nextIndex = currentActiveEntryIndex === -1 ? data.length - 1 : Math.max(0, currentActiveEntryIndex - 1) + if (currentActiveEntryIndex === nextIndex) { + toast.info("You are already at the first entry") + return + } + handleScrollTo(nextIndex) const nextId = data![nextIndex] From 51a243eeea8e2746f2820baa8923ad202aa48ab4 Mon Sep 17 00:00:00 2001 From: Stephen Zhou <38493346+hyoban@users.noreply.github.com> Date: Wed, 16 Jul 2025 21:02:57 +0800 Subject: [PATCH 042/111] fix: toggle translation settings, close #4187 --- .../entry-column/Items/picture-masonry.tsx | 7 +++++- .../modules/entry-column/Items/video-item.tsx | 10 +++++--- .../src/modules/entry-column/item.tsx | 10 +++++--- .../entry-content/components/EntryTitle.tsx | 9 ++++++-- .../src/modules/entry-content/hooks.tsx | 13 +++++++---- .../native/webview/EntryContentWebView.tsx | 2 +- .../modules/entry-content/EntryGridFooter.tsx | 9 ++++++-- .../src/modules/entry-content/EntryTitle.tsx | 15 ++++++++---- .../entry-list/EntryListContentArticle.tsx | 2 +- .../entry-list/EntryListContentPicture.tsx | 2 +- .../entry-list/EntryListContentSocial.tsx | 2 +- .../entry-list/EntryListContentVideo.tsx | 2 +- .../entry-list/templates/EntryNormalItem.tsx | 9 ++++++-- .../entry-list/templates/EntrySocialItem.tsx | 7 +++++- .../entry-list/templates/EntryTranslation.tsx | 9 ++------ .../entries/[entryId]/EntryDetailScreen.tsx | 16 ++++++------- .../internal/store/src/translation/hooks.ts | 23 ++++++++++++++----- 17 files changed, 99 insertions(+), 48 deletions(-) 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 edf4677d4..213b3224a 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 @@ -283,8 +283,13 @@ const MasonryRender: React.ComponentType< }> > = ({ data, index }) => { const firstScreenReady = use(FirstScreenReadyContext) + const enableTranslation = useGeneralSettingKey("translation") const actionLanguage = useActionLanguage() - const translation = useEntryTranslation(data.entryId, actionLanguage) + const translation = useEntryTranslation({ + entryId: data.entryId, + language: actionLanguage, + setting: enableTranslation, + }) if (data.entryId.startsWith("placeholder")) { return diff --git a/apps/desktop/layer/renderer/src/modules/entry-column/Items/video-item.tsx b/apps/desktop/layer/renderer/src/modules/entry-column/Items/video-item.tsx index afe45c5ed..c520ad416 100644 --- a/apps/desktop/layer/renderer/src/modules/entry-column/Items/video-item.tsx +++ b/apps/desktop/layer/renderer/src/modules/entry-column/Items/video-item.tsx @@ -173,13 +173,17 @@ const PreviewVideoModalContent: ModalContentComponent<{ }> = ({ dismiss, src, entryId }) => { const entry = useEntry(entryId, (state) => ({ content: state.content })) - const actionLanguage = useActionLanguage() const enableTranslation = useGeneralSettingKey("translation") - const translation = useEntryTranslation(entryId, actionLanguage) + const actionLanguage = useActionLanguage() + const translation = useEntryTranslation({ + entryId, + language: actionLanguage, + setting: enableTranslation, + }) usePrefetchEntryTranslation({ entryIds: [entryId], checkLanguage, - translation: enableTranslation, + setting: enableTranslation, language: actionLanguage, withContent: true, }) 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 d813c8e42..8c45f2359 100644 --- a/apps/desktop/layer/renderer/src/modules/entry-column/item.tsx +++ b/apps/desktop/layer/renderer/src/modules/entry-column/item.tsx @@ -22,13 +22,17 @@ const EntryItemImpl = memo(function EntryItemImpl({ entryId: string view: FeedViewType }) { - const actionLanguage = useActionLanguage() const enableTranslation = useGeneralSettingKey("translation") - const translation = useEntryTranslation(entryId, actionLanguage) + const actionLanguage = useActionLanguage() + const translation = useEntryTranslation({ + entryId, + language: actionLanguage, + setting: enableTranslation, + }) usePrefetchEntryTranslation({ entryIds: [entryId], checkLanguage, - translation: enableTranslation, + setting: enableTranslation, language: actionLanguage, withContent: view === FeedViewType.SocialMedia, }) 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 e5ddcac10..26200ce19 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 @@ -6,6 +6,7 @@ import { useWhoami } from "@follow/store/user/hooks" import { formatEstimatedMins, formatTimeToSeconds } from "@follow/utils" import { titleCase } from "title-case" +import { useShowAITranslation } from "~/atoms/ai-translation" import { useActionLanguage } from "~/atoms/settings/general" import { useUISettingKey } from "~/atoms/settings/ui" import { RelativeTime } from "~/components/ui/datetime" @@ -57,9 +58,13 @@ export const EntryTitle = ({ entryId, compact }: EntryLinkProps) => { const data = useEntryReadHistory(entryId) const entryHistory = data?.entryReadHistories const populatedFullHref = useFeedSafeUrl(entryId) + const enableTranslation = useShowAITranslation() const actionLanguage = useActionLanguage() - - const translation = useEntryTranslation(entryId, actionLanguage) + const translation = useEntryTranslation({ + entryId, + language: actionLanguage, + setting: enableTranslation, + }) const dateFormat = useUISettingKey("dateFormat") diff --git a/apps/desktop/layer/renderer/src/modules/entry-content/hooks.tsx b/apps/desktop/layer/renderer/src/modules/entry-content/hooks.tsx index 5b898ceac..d5b5946d0 100644 --- a/apps/desktop/layer/renderer/src/modules/entry-content/hooks.tsx +++ b/apps/desktop/layer/renderer/src/modules/entry-content/hooks.tsx @@ -5,8 +5,9 @@ import { createElement, useCallback, useMemo } from "react" import { useTranslation } from "react-i18next" import { toast } from "sonner" +import { useShowAITranslation } from "~/atoms/ai-translation" import { useEntryIsInReadability, useEntryIsInReadabilitySuccess } from "~/atoms/readability" -import { useActionLanguage, useGeneralSettingKey } from "~/atoms/settings/general" +import { useActionLanguage } from "~/atoms/settings/general" import { useModalStack } from "~/components/ui/modal/stacked/hooks" import { checkLanguage } from "~/lib/translate" @@ -46,13 +47,17 @@ export const useEntryContent = (entryId: string) => { const isInReadabilityMode = useEntryIsInReadability(entryId) const isReadabilitySuccess = useEntryIsInReadabilitySuccess(entryId) + const enableTranslation = useShowAITranslation() const actionLanguage = useActionLanguage() - const enableTranslation = useGeneralSettingKey("translation") - const contentTranslated = useEntryTranslation(entryId, actionLanguage) + const contentTranslated = useEntryTranslation({ + entryId, + language: actionLanguage, + setting: enableTranslation, + }) usePrefetchEntryTranslation({ entryIds: [entryId], checkLanguage, - translation: enableTranslation, + setting: enableTranslation, language: actionLanguage, withContent: true, target: isReadabilitySuccess ? "readabilityContent" : "content", diff --git a/apps/mobile/src/components/native/webview/EntryContentWebView.tsx b/apps/mobile/src/components/native/webview/EntryContentWebView.tsx index 519a18fb5..aa9525c2e 100644 --- a/apps/mobile/src/components/native/webview/EntryContentWebView.tsx +++ b/apps/mobile/src/components/native/webview/EntryContentWebView.tsx @@ -60,7 +60,7 @@ export function EntryContentWebView(props: EntryContentWebViewProps) { const { entryId, noMedia, showReadability, showTranslation } = props const entry = useEntry(entryId, (state) => state) const language = useActionLanguage() - const translation = useEntryTranslation(entryId, language) + const translation = useEntryTranslation({ entryId, language, setting: showTranslation ?? false }) const [mode, setMode] = React.useState<"normal" | "debug">("normal") diff --git a/apps/mobile/src/modules/entry-content/EntryGridFooter.tsx b/apps/mobile/src/modules/entry-content/EntryGridFooter.tsx index 4e8c57950..ebda3b740 100644 --- a/apps/mobile/src/modules/entry-content/EntryGridFooter.tsx +++ b/apps/mobile/src/modules/entry-content/EntryGridFooter.tsx @@ -5,7 +5,7 @@ import { useEntryTranslation } from "@follow/store/translation/hooks" import { cn } from "@follow/utils" import { Text, View } from "react-native" -import { useActionLanguage } from "@/src/atoms/settings/general" +import { useActionLanguage, useGeneralSettingKey } from "@/src/atoms/settings/general" import { RelativeDateTime } from "@/src/components/ui/datetime/RelativeDateTime" import { FeedIcon } from "@/src/components/ui/icon/feed-icon" @@ -27,8 +27,13 @@ export const EntryGridFooter = ({ read: state.read, translation: state.settings?.translation, })) + const enableTranslation = useGeneralSettingKey("translation") const actionLanguage = useActionLanguage() - const translation = useEntryTranslation(entryId, actionLanguage) + const translation = useEntryTranslation({ + entryId, + language: actionLanguage, + setting: enableTranslation, + }) const feed = useFeedById(entry?.feedId || "") if (!entry) return null diff --git a/apps/mobile/src/modules/entry-content/EntryTitle.tsx b/apps/mobile/src/modules/entry-content/EntryTitle.tsx index 319bb7dc8..33e68f67a 100644 --- a/apps/mobile/src/modules/entry-content/EntryTitle.tsx +++ b/apps/mobile/src/modules/entry-content/EntryTitle.tsx @@ -1,20 +1,27 @@ import { useEntry } from "@follow/store/entry/hooks" import { useFeedById } from "@follow/store/feed/hooks" import { useEntryTranslation } from "@follow/store/translation/hooks" -import { useSetAtom } from "jotai" +import { useAtomValue, useSetAtom } from "jotai" import { use } from "react" import { Text, View } from "react-native" -import { useActionLanguage } from "@/src/atoms/settings/general" +import { useActionLanguage, useGeneralSettingKey } from "@/src/atoms/settings/general" import { UserAvatar } from "@/src/components/ui/avatar/UserAvatar" import { FeedIcon } from "@/src/components/ui/icon/feed-icon" -import { EntryContentContext } from "@/src/modules/entry-content/ctx" +import { EntryContentContext, useEntryContentContext } from "@/src/modules/entry-content/ctx" import { EntryTranslation } from "../entry-list/templates/EntryTranslation" export const EntryTitle = ({ title, entryId }: { title: string; entryId: string }) => { + const { showAITranslationAtom } = useEntryContentContext() + const showTranslationOnce = useAtomValue(showAITranslationAtom) + const enableTranslation = useGeneralSettingKey("translation") || showTranslationOnce const actionLanguage = useActionLanguage() - const translation = useEntryTranslation(entryId, actionLanguage) + const translation = useEntryTranslation({ + entryId, + language: actionLanguage, + setting: enableTranslation, + }) const { titleHeightAtom } = use(EntryContentContext) const setTitleHeight = useSetAtom(titleHeightAtom) diff --git a/apps/mobile/src/modules/entry-list/EntryListContentArticle.tsx b/apps/mobile/src/modules/entry-list/EntryListContentArticle.tsx index 55161452f..d5b6eda81 100644 --- a/apps/mobile/src/modules/entry-list/EntryListContentArticle.tsx +++ b/apps/mobile/src/modules/entry-list/EntryListContentArticle.tsx @@ -62,7 +62,7 @@ export const EntryListContentArticle = ({ usePrefetchEntryTranslation({ entryIds: active ? viewableItems.map((item) => item.key) : [], language: actionLanguage, - translation, + setting: translation, checkLanguage, }) diff --git a/apps/mobile/src/modules/entry-list/EntryListContentPicture.tsx b/apps/mobile/src/modules/entry-list/EntryListContentPicture.tsx index 32aafd64d..9f44768f0 100644 --- a/apps/mobile/src/modules/entry-list/EntryListContentPicture.tsx +++ b/apps/mobile/src/modules/entry-list/EntryListContentPicture.tsx @@ -40,7 +40,7 @@ export const EntryListContentPicture = ({ entryIds: active ? viewableItems.map((item) => item.key) : [], language: actionLanguage, checkLanguage, - translation, + setting: translation, }) const renderItem = useTypeScriptHappyCallback(({ item }: { item: string }) => { diff --git a/apps/mobile/src/modules/entry-list/EntryListContentSocial.tsx b/apps/mobile/src/modules/entry-list/EntryListContentSocial.tsx index 6799ba2d3..f71aabe8e 100644 --- a/apps/mobile/src/modules/entry-list/EntryListContentSocial.tsx +++ b/apps/mobile/src/modules/entry-list/EntryListContentSocial.tsx @@ -52,7 +52,7 @@ export const EntryListContentSocial = ({ usePrefetchEntryTranslation({ entryIds: active ? viewableItems.map((item) => item.key) : [], language: actionLanguage, - translation, + setting: translation, checkLanguage, }) diff --git a/apps/mobile/src/modules/entry-list/EntryListContentVideo.tsx b/apps/mobile/src/modules/entry-list/EntryListContentVideo.tsx index 18c8b7526..958c4d145 100644 --- a/apps/mobile/src/modules/entry-list/EntryListContentVideo.tsx +++ b/apps/mobile/src/modules/entry-list/EntryListContentVideo.tsx @@ -38,7 +38,7 @@ export const EntryListContentVideo = ({ usePrefetchEntryTranslation({ entryIds: active ? viewableItems.map((item) => item.key) : [], language: actionLanguage, - translation, + setting: translation, checkLanguage, }) diff --git a/apps/mobile/src/modules/entry-list/templates/EntryNormalItem.tsx b/apps/mobile/src/modules/entry-list/templates/EntryNormalItem.tsx index 5660efc47..601d4c371 100644 --- a/apps/mobile/src/modules/entry-list/templates/EntryNormalItem.tsx +++ b/apps/mobile/src/modules/entry-list/templates/EntryNormalItem.tsx @@ -11,7 +11,7 @@ import { memo, useCallback, useMemo, useRef, useState } from "react" import type { ImageErrorEventData } from "react-native" import { Text, View } from "react-native" -import { useActionLanguage } from "@/src/atoms/settings/general" +import { useActionLanguage, useGeneralSettingKey } from "@/src/atoms/settings/general" import { useUISettingKey } from "@/src/atoms/settings/ui" import { preloadWebViewEntry } from "@/src/components/native/webview/EntryContentWebView" import { RelativeDateTime } from "@/src/components/ui/datetime/RelativeDateTime" @@ -52,8 +52,13 @@ export const EntryNormalItem = memo( title: state.title, description: state.description, })) + const enableTranslation = useGeneralSettingKey("translation") const actionLanguage = useActionLanguage() - const translation = useEntryTranslation(entryId, actionLanguage) + const translation = useEntryTranslation({ + entryId, + language: actionLanguage, + setting: enableTranslation, + }) const from = getInboxFrom(entry) const feed = useFeedById(entry?.feedId as string) const navigation = useNavigation() diff --git a/apps/mobile/src/modules/entry-list/templates/EntrySocialItem.tsx b/apps/mobile/src/modules/entry-list/templates/EntrySocialItem.tsx index 7a3dbbcf7..83af3a604 100644 --- a/apps/mobile/src/modules/entry-list/templates/EntrySocialItem.tsx +++ b/apps/mobile/src/modules/entry-list/templates/EntrySocialItem.tsx @@ -44,8 +44,13 @@ export const EntrySocialItem = memo( author: state.author, translation: state.settings?.translation, })) + const enableTranslation = useGeneralSettingKey("translation") const actionLanguage = useActionLanguage() - const translation = useEntryTranslation(entryId, actionLanguage) + const translation = useEntryTranslation({ + entryId, + language: actionLanguage, + setting: enableTranslation, + }) const { openLightbox } = useLightboxControls() const feed = useFeedById(entry?.feedId || "") diff --git a/apps/mobile/src/modules/entry-list/templates/EntryTranslation.tsx b/apps/mobile/src/modules/entry-list/templates/EntryTranslation.tsx index 51b909d7e..6a3440f7b 100644 --- a/apps/mobile/src/modules/entry-list/templates/EntryTranslation.tsx +++ b/apps/mobile/src/modules/entry-list/templates/EntryTranslation.tsx @@ -20,7 +20,6 @@ export const EntryTranslation = ({ showTranslation?: boolean bilingual?: boolean } & TextProps) => { - const showTranslationFinal = useGeneralSettingKey("translation") || showTranslation const bilingualFinal = useGeneralSettingKey("translationMode") === "bilingual" || bilingual const nextSource = useMemo(() => { @@ -30,15 +29,11 @@ export const EntryTranslation = ({ return source.trim() }, [source]) const nextTarget = useMemo(() => { - if ( - !target || - !showTranslationFinal || - nextSource.replaceAll(/\s/g, "") === target.replaceAll(/\s/g, "") - ) { + if (!target || nextSource.replaceAll(/\s/g, "") === target.replaceAll(/\s/g, "")) { return "" } return target.trim() - }, [nextSource, target, showTranslationFinal]) + }, [nextSource, target]) if (!bilingualFinal) { return ( diff --git a/apps/mobile/src/screens/(stack)/entries/[entryId]/EntryDetailScreen.tsx b/apps/mobile/src/screens/(stack)/entries/[entryId]/EntryDetailScreen.tsx index 2a753ab81..802ec3c10 100644 --- a/apps/mobile/src/screens/(stack)/entries/[entryId]/EntryDetailScreen.tsx +++ b/apps/mobile/src/screens/(stack)/entries/[entryId]/EntryDetailScreen.tsx @@ -130,9 +130,9 @@ export const EntryDetailScreen: NavigationControllerView<{ const EntryContentWebViewWithContext = ({ entryId }: { entryId: string }) => { const { showReadabilityAtom, showAITranslationAtom } = useEntryContentContext() - const showReadability = useAtomValue(showReadabilityAtom) + const showReadabilityOnce = useAtomValue(showReadabilityAtom) const translationSetting = useGeneralSettingKey("translation") - const showTranslation = useAtomValue(showAITranslationAtom) + const showTranslationOnce = useAtomValue(showAITranslationAtom) const actionLanguage = useActionLanguage() const translation = useGeneralSettingKey("translation") @@ -144,10 +144,10 @@ const EntryContentWebViewWithContext = ({ entryId }: { entryId: string }) => { usePrefetchEntryTranslation({ entryIds: [entryId], withContent: true, - target: showReadability && entry?.readabilityContent ? "readabilityContent" : "content", + target: showReadabilityOnce && entry?.readabilityContent ? "readabilityContent" : "content", language: actionLanguage, checkLanguage, - translation, + setting: translation, }) // Auto toggle readability when content is empty @@ -160,16 +160,16 @@ const EntryContentWebViewWithContext = ({ entryId }: { entryId: string }) => { }, [isPending, entry?.content, setShowReadability]) useEffect(() => { - if (showReadability) { + if (showReadabilityOnce) { entrySyncServices.fetchEntryReadabilityContent(entryId) } - }, [showReadability, entryId]) + }, [showReadabilityOnce, entryId]) return ( ) } diff --git a/packages/internal/store/src/translation/hooks.ts b/packages/internal/store/src/translation/hooks.ts index 98a72c2bc..3bd955787 100644 --- a/packages/internal/store/src/translation/hooks.ts +++ b/packages/internal/store/src/translation/hooks.ts @@ -3,7 +3,7 @@ import type { SupportedActionLanguage } from "@follow/shared" import { useQueries } from "@tanstack/react-query" import { useCallback } from "react" -import { useEntryList } from "../entry/hooks" +import { useEntry, useEntryList } from "../entry/hooks" import type { EntryModel } from "../entry/types" import { translationSyncService, useTranslationStore } from "./store" @@ -11,19 +11,19 @@ export const usePrefetchEntryTranslation = ({ entryIds, withContent, target = "content", - translation, + setting, language, checkLanguage, }: { entryIds: string[] withContent?: boolean target?: "content" | "readabilityContent" - translation: boolean + setting: boolean language: SupportedActionLanguage checkLanguage: (params: { content: string; language: SupportedActionLanguage }) => boolean }) => { const entryList = (useEntryList(entryIds)?.filter( - (entry) => entry !== null && (translation || !!entry?.settings?.translation), + (entry) => entry !== null && (setting || !!entry?.settings?.translation), ) || []) as EntryModel[] return useQueries({ @@ -48,13 +48,24 @@ export const usePrefetchEntryTranslation = ({ }) } -export const useEntryTranslation = (entryId: string, language: SupportedLanguages) => { +export const useEntryTranslation = ({ + entryId, + language, + setting, +}: { + entryId: string + language: SupportedLanguages + setting: boolean +}) => { + const actionSetting = useEntry(entryId, (state) => state.settings?.translation) + return useTranslationStore( useCallback( (state) => { + if (!setting && !actionSetting) return return state.data[entryId]?.[language] }, - [entryId, language], + [actionSetting, entryId, language, setting], ), ) } From f6a64af4ebdde5eb3eccd4fb558d82b744826101 Mon Sep 17 00:00:00 2001 From: Innei Date: Wed, 16 Jul 2025 21:54:32 +0800 Subject: [PATCH 043/111] feat: ai features (#4040) * feat: ai panel * feat: ai settings * feat: ai entrances * feat: shortcuts setting * refactor: rename ai dialogue * feat: merge dialogue input and shortcuts * feat: textarea autoheight * feat: ai dialogue input auto shrink * feat: ai dialogue * feat: ai icon * feat: split text * feat: mockDialogues * feat: scrollable shortcuts * fix * feat: use vercel ai * feat: rename * feat: ai tool * refactor: update font settings and layout adjustments - Changed default font from "SN Pro" to "system-ui" in multiple components for consistency. - Updated layout styles by removing unnecessary class names to streamline the design. - Added a new translation key for "Follow System" to enhance localization support. Signed-off-by: Innei * refactor: reorganize dependencies and remove unused components - Moved several dependencies from the main package.json to the layer renderer's package.json for better modularity. - Removed the SplitText component and its associated files to streamline the codebase. - Added new utility animations in the Tailwind CSS configuration for enhanced UI effects. Signed-off-by: Innei * feat: implement AI chat components and context management - Added AIChatInput, AIChatPanel, AIChatRoot, AIMessageList, and AIChatShortcuts components to facilitate user interaction with AI chat functionality. - Introduced AIChatContext for managing chat state and interactions. - Updated entry content to integrate the new AI chat components, enhancing user experience with chat features. - Removed the legacy panel.tsx file to streamline the codebase. Signed-off-by: Innei * feat: add AIChat hotkey scope and integrate Focusable component - Introduced a new hotkey scope for AIChat in the constants file to support keyboard interactions. - Wrapped the AIChatContext in a Focusable component within AIChatRoot to enhance accessibility and focus management. Signed-off-by: Innei * refactor: update AIChatInput and AIChatPanel components - Replaced the Button component with a span in AIChatInput for improved styling consistency. - Removed commented-out code in AIChatPanel to clean up the component structure. - Adjusted layout in AIChatPanel for better organization of chat input and help sections. Signed-off-by: Innei * refactor: remove deprecated useGlobalFocusableScope hook and update TextArea styles - Removed the deprecated `useGlobalFocusableScope` hook in favor of `useGlobalFocusableScopeSelector` for improved performance. - Updated TextArea component styles to enhance visual consistency with new class names. Signed-off-by: Innei * feat: add SettingTextArea component and integrate into AI settings - Introduced a new SettingTextArea component for improved text input handling. - Updated the AI settings tab to utilize SettingTextArea for personalized prompts, enhancing user experience. - Refactored existing SettingInput usage for better layout and consistency. Signed-off-by: Innei * fix: import path * feat: optimzie ai displayFeeds * feat: enhance AIChatPanel with tooltips and improved suggestion display - Added tooltips for the "New Chat", "History", and "Personalize" buttons for better user guidance. - Updated suggestion display logic to show a limited number of suggestions initially, with an option to expand for more. - Changed icons in suggestions to use a consistent format and improved styling for better visual appeal. Signed-off-by: Innei * feat: integrate AIPanelRefsContext for improved reference management - Introduced AIPanelRefsContext to manage references for the chat input and panel components. - Updated AIChatInput to utilize the new context for textarea reference. - Modified AIChatPanel to use the panel reference from the context. - Enhanced AIChatRoot to provide the context with memoized references for better performance. Signed-off-by: Innei * feat: add EntryContentAccessories component for enhanced entry features - Introduced EntryContentAccessories to encapsulate the ContainerToc and EntryAIChatInput components. - Updated EntryContent to utilize EntryContentAccessories for improved layout and functionality. - Added new ContainerToc and AIChatInput components to support table of contents and AI chat features. Signed-off-by: Innei * refactor: update imports for useSettingModal and clean up unused components - Changed import path for useSettingModal to use a new hack version. - Removed the unused ContainerToc component. - Updated EntryContent to include AISmartSidebar. - Commented out the EntryAIChatInput in EntryContentAccessories. - Minor adjustments in use-register-hotkey for better readability. Signed-off-by: Innei * feat(ai-chat): implement AI chat components including message input, display, and demo functionality - Added AIChatContainer for managing chat messages and displaying a welcome screen. - Introduced AIChatInput for user message input with auto-resizing functionality. - Created AIChatMessage for rendering individual chat messages with formatting support. - Integrated AIChatDemo to showcase the chat functionality within the AIChatSidePanel. - Added a new SVG icon for the send button. Signed-off-by: Innei * feat(ai-chat): enhance chat functionality with auto-scroll and message formatting - Integrated auto-scroll feature in AIChatContainer to improve user experience during message updates. - Added AIChatTypingIndicator to display typing status in chat. - Updated AIChatMessage to support markdown parsing for better message formatting. - Enhanced AIChatInput to manage empty state and disable send button accordingly. - Refactored AIChat component structure for clarity and improved functionality. Signed-off-by: Innei * feat(ai-chat): add sending message animation and enhance chat input - Introduced SendingMessageOverlay component for animated feedback when sending messages. - Updated AIChatInput to trigger sending animation and manage input state. - Enhanced AIChatMessage with animation effects for message display. - Improved auto-scroll logic to handle programmatic scrolling more effectively. - Added new SVG icons for chat functionalities. Signed-off-by: Innei * feat(ai-chat): improve chat input and message handling with enhanced animations - Updated AIChatContainer to refine sending message animations and manage input states. - Enhanced AIChatInput to include a stop button for ongoing processing and improved message sending logic. - Refactored AIChatMessage to maintain animation consistency during message display. - Improved comments for clarity and code maintainability. Signed-off-by: Innei * feat(ai-chat): enhance AI chat context management and input handling - Introduced AIChatContextInfo for managing context information in AI chat. - Updated AIChatInput to utilize context for default selection and improved user experience. - Refactored AIChatRoot to manage context state and provide context information to child components. - Enhanced AIChatContainer with a welcome message and improved message handling logic. - Added EntryAIContext for managing entry-specific AI context, improving integration with chat functionalities. Signed-off-by: Innei * chore: hono update - Introduced optional context properties in the AI chat message structure to support entryId and selectedText. - Enhanced flexibility for managing chat context and improving user interactions. Signed-off-by: Innei * feat(ai-chat): enhance AI chat components with optional wrapping and improved styling - Added `wrapFocusable` prop to `AIChatRoot` for conditional wrapping of focusable elements. - Updated `AIChatMessage` to display a placeholder when the assistant is "thinking" and improved styling for message bubbles. - Refined `AIChatContainer` layout with adjusted border styles for better visual separation. - Enhanced `AIChatSidePanel` structure for improved component organization and functionality. Signed-off-by: Innei * feat(ai-chat): implement AI chat context store and enhance input handling - Introduced a new context store for managing AI chat state, allowing for better organization of context information. - Refactored AIChatInput and AIChatRoot components to utilize the new context store, improving state management and performance. - Added AIChatContextBar for displaying context blocks and managing references within the chat. - Enhanced input handling with improved styling and functionality, including dynamic resizing and context-aware features. Signed-off-by: Innei * feat(ai-chat): refactor message parts handling in AIChatMessage component - Replaced the existing MessageParts component with a new AIMessageParts component to improve code organization and readability. - Enhanced the rendering logic for message parts, including better handling of tool invocations and markdown parsing. - Introduced a more structured approach to displaying message content, including support for code highlighting. Signed-off-by: Innei * feat(diagrams): integrate Mermaid for diagram rendering in AI chat - Added Mermaid as a dependency to support diagram rendering within the AI chat interface. - Implemented the MermaidDiagram component for rendering Mermaid diagrams based on provided code. - Enhanced AIMarkdownMessage to parse and render Mermaid diagrams alongside other markdown content. - Refactored AIChatContainer and AIChatInput components to improve structure and maintainability. - Introduced AIPanelHeader for better management of the AI chat panel. Signed-off-by: Innei * feat(ai-chat): enhance AI message rendering and introduce ToolInvocationComponent - Updated AIMarkdownMessage to accept an optional className prop for better styling flexibility. - Refactored AIMessageParts to utilize the new ToolInvocationComponent for rendering tool invocation details, improving code organization and readability. - Adjusted AIChatMessage styles for user messages to enhance visual distinction. - Removed unused state management for tool expansion, simplifying the component logic. Signed-off-by: Innei * feat(ai-chat): integrate AIChatRoot and enhance auto-scroll functionality - Wrapped the main content in AIChatRoot for improved focus management. - Added auto-scroll behavior to the AIChatContainer for better user experience when new messages are loaded. - Refactored AIChatPanelContainer and AIChatSidePanel to streamline layout and improve code organization. - Updated styles and structure for better visual consistency and maintainability. Signed-off-by: Innei * feat(ai-chat): update AI SDK dependencies and enhance AI chat functionality - Upgraded dependencies for '@ai-sdk/openai', '@ai-sdk/react', and 'ai' to their latest beta versions for improved features and performance. - Introduced new utility functions for managing AI chat state, including getAIChatPinned. - Refactored AIChat components to utilize the updated SDK, enhancing message handling and tool invocation rendering. - Added global commands for toggling AI chat visibility and pinning, improving user interaction. Signed-off-by: Innei * feat(layout): implement resizable panel functionality and improve layout components - Added PanelSplitter component for dynamic resizing of the AI chat panel. - Integrated useResizable hook to manage panel dimensions in RightContent and SubscriptionColumn. - Refactored AIChatPanelContainer to accept an optional className prop for better styling. - Cleaned up unused refs and improved code organization in SubscriptionColumn. Signed-off-by: Innei * feat(ai-chat): update AI chat components and integrate new AI SDK features - Refactored AIChatInput and AIChatMessage components to utilize the new AISpline icon for improved visual consistency. - Enhanced AIChatRoot to accept a roomId prop for better context management. - Updated message handling in AIChatMessage to include metadata for improved message tracking. - Introduced AIChatBottom component for better organization of chat input and context display. - Integrated new AI SDK features for enhanced chat functionality and user experience. Signed-off-by: Innei * feat(ai-chat): integrate node polyfills and enhance chat functionality - Added vite-plugin-node-polyfills to support Node.js core modules in the chat application. - Updated AIChatRoot to utilize the new roomId prop for better context management. - Refactored message handling in AIChat components to improve user experience and maintainability. - Introduced new hooks for loading and saving messages, enhancing chat state management. - Updated database schema for ai_chat_messages to ensure message integrity and support new features. Signed-off-by: Innei * chore: update pnpm-lock and package.json to include @splinetool/react-spline and related dependencies - Added @splinetool/react-spline version 4.0.0 to package.json. - Updated pnpm-lock.yaml to reflect the addition of @splinetool/react-spline and its peer dependencies, including @splinetool/runtime and react-related packages. - Included new dependency on on-change version 4.0.2 and updated other related packages. This update enhances compatibility with the latest spline tool features. Signed-off-by: Innei * feat(ai): implement AI chat components and layout - Added AIChatContextBar for managing chat context and entries. - Introduced AIChatMessage and AIMessageParts for rendering chat messages. - Created ToolInvocationComponent to display tool invocation details. - Implemented auto-scrolling functionality with useAutoScroll hook. - Developed AIChatLayout to structure the chat interface, including a welcome screen and message input. - Integrated chat components into the entry content layout. This update enhances the AI chat experience with a structured layout and improved message handling. Signed-off-by: Innei * feat(ai): enhance AI chat functionality and localization - Added new AI namespace to constants for improved organization. - Integrated AI localization by importing AI English resources and updating default resources. - Enhanced AIChatLayout with translation support for chat-related prompts and messages. - Updated AIPanelHeader to utilize translations for chat clearing confirmation. - Introduced welcome message localization in the AI chat interface. This update improves the AI chat experience with better localization and user interaction features. Signed-off-by: Innei * feat(ai): enhance AI settings with personalized prompts and shortcuts management - Introduced PersonalizePromptSetting for customizing AI prompts with save functionality. - Added AIShortcutsSection for managing AI shortcuts, including add, update, delete, and toggle features. - Improved localization by updating translation keys for AI settings. - Refactored components for better organization and clarity. This update enhances user interaction with AI settings, allowing for personalized experiences and efficient shortcut management. Signed-off-by: Innei * feat(shortcuts): implement keyboard shortcut management and localization - Added KeyRecorder component for recording keyboard shortcuts. - Introduced ShortcutSetting for managing custom AI shortcuts, including add, update, and delete functionalities. - Enhanced AI settings with new localization keys for shortcuts. - Refactored existing components for improved organization and clarity. This update streamlines the process of creating and managing keyboard shortcuts, enhancing user experience in AI settings. Signed-off-by: Innei * feat: update ai robot model * feat(ai): introduce new analytics and display components - Added components for displaying analytics, entries, feeds, and subscriptions. - Implemented loading and error states for better user feedback. - Refactored existing components to integrate new display functionalities. - Introduced common state components for loading and error handling. This update enhances the AI chat experience by providing detailed analytics and improved data presentation. Signed-off-by: Innei * refactor(ai): consolidate shared components for analytics displays - Moved StatCard, ChartPlaceholder, and other common components to a shared module for reuse across analytics displays. - Updated AIDisplayAnalyticsPart, AIDisplayEntriesPart, AIDisplayFeedsPart, and AIDisplaySubscriptionsPart to utilize the new shared components. - Enhanced the layout and error handling for empty states in various display components. This refactor improves code maintainability and consistency in the analytics display components. Signed-off-by: Innei * feat(ui): introduce GlassButton component and refactor modal actions - Added a new GlassButton component with customizable styles and animations for enhanced UI consistency. - Replaced existing button implementations in modal components with the new GlassButton for improved visual coherence. - Updated PreviewMediaContent and other components to utilize GlassButton, enhancing user interaction and aesthetics. This update streamlines button usage across the application and enhances the overall user experience. Signed-off-by: Innei * refactor(ai): enhance auto-scroll functionality in chat component - Updated the useAutoScroll hook to improve user interaction handling and scrolling behavior. - Introduced a debounce mechanism for resize observer to optimize performance. - Modified the AIChatLayout to ensure proper scrolling to the bottom when new messages are loaded. - Improved state management for user interactions and auto-scrolling logic. These changes enhance the chat experience by ensuring smoother scrolling and better responsiveness to user actions. Signed-off-by: Innei * feat: add class-variance-authority for GlassButton variants - Updated pnpm-lock.yaml to include class-variance-authority version 0.7.1. - Modified GlassButton component to utilize class-variance-authority for managing size and color scheme variants. - Updated PreviewMediaContent and other components to use the new variant prop for GlassButton. - Removed the deprecated AIChatInput component and related references. - Fixed import path for PanelSplitter in entry content layout. Signed-off-by: Innei * feat: enhance AI chat functionality and UI components - Introduced AIChatSendButton component for improved send button functionality in AI chat. - Updated AIChatMessage and AIPanelHeader to use new icon styles. - Integrated AIChatSendButton into AIChatInput and AIChatLayout for consistent UI. - Added toggleAIChatPinned command and updated related commands for better AI chat management. - Refactored entry context menu to hide specific actions related to AI chat. - Fixed import paths and updated localization for AI chat commands. Signed-off-by: Innei * refactor: update layout components and improve conditional rendering - Refactored RightContent component to enhance conditional rendering logic for Grid and AIChatLayout based on realEntryId and isWideView. - Updated EntryHeader component styles to use new text color classes for better consistency. - Adjusted imports in hono.ts to reflect updated package versions for zod and drizzle-orm. Signed-off-by: Innei * feat: enhance AI chat features and session management - Updated AI chat components to support new session management features, including room switching and title generation. - Introduced session state management using Jotai for better handling of current room ID and title. - Added hooks for managing chat history and session persistence. - Implemented export functionality for chat sessions to Markdown format. - Enhanced UI with new components for chat input and welcome screen. - Updated localization for new chat features and actions. Signed-off-by: Innei * refactor: update AI chat components and improve styling - Enhanced AIChatMessage with additional styling for better layout. - Introduced MarkdownLink in AIMarkdownMessage for improved link rendering. - Removed unused "step-start" case in AIMessageParts for cleaner code. - Simplified ToolInvocationComponent by removing unnecessary div. - Refactored useSettingModal to avoid circular dependency and improve clarity. Signed-off-by: Innei * feat: implement chat title generation and error handling in AI chat components - Added title generation functionality in AIChatRoot, triggered by the first AI response. - Updated ChatInput to display error messages with a new UI component. - Refactored title generation logic to utilize the first user and AI messages. - Removed unused props and streamlined session management in ChatInterface. - Enhanced error handling in chat components for improved user experience. Signed-off-by: Innei * refactor: improve ChatHeader and ChatInterface components - Adjusted ChatHeader height and updated mask image styling for better visual consistency. - Enhanced ChatInterface with scroll detection and a "Scroll to Bottom" button for improved user experience. - Introduced state management for scroll position to optimize chat interaction. - Cleaned up event listeners and added necessary imports for new functionality. Signed-off-by: Innei * refactor: update layout styling in AI chat components - Modified div elements in ToolInvocationComponent, AIDisplayEntriesPart, AIDisplayFeedsPart, and AIDisplaySubscriptionsPart to include max-width for improved responsiveness. - Added a blank line in ChatInterface for better code readability. Signed-off-by: Innei * refactor: enhance AI settings and chat components - Updated AI settings management by introducing aiServerSyncWhiteListKeys and integrating AISettings into the sync queue. - Improved the PersonalizePromptSetting component with character limit validation and dynamic feedback for user input. - Removed error toast in AIChatRoot for cleaner error handling. - Added new suggestion to the WelcomeScreen for enhanced user experience. Signed-off-by: Innei * refactor: enhance ChatInput component functionality - Integrated useInputComposition hook for improved key handling in ChatInput. - Updated key event handling logic to ensure proper focus management based on user input. - Streamlined textarea props by spreading inputProps for cleaner code. Signed-off-by: Innei * refactor: update layout styling in AI display components - Removed max-width from div elements in AIDisplayEntriesPart, AIDisplayFeedsPart, and AIDisplaySubscriptionsPart for improved responsiveness. - Ensured consistent styling across AI display components. Signed-off-by: Innei * refactor: remove AIChatShortcuts component and enhance shortcut handling - Deleted the AIChatShortcuts component to streamline the codebase. - Integrated shortcut handling directly into the ChatInput and WelcomeScreen components for improved user experience. - Added functionality to process custom shortcuts and display them dynamically in the WelcomeScreen. Signed-off-by: Innei * refactor: implement CollapsibleError component for improved error display - Introduced a new CollapsibleError component to enhance error handling in the ChatInput. - Simplified error display logic by replacing inline error handling with the new component. - Updated common-states to maintain consistent error presentation across the application. Signed-off-by: Innei * refactor: re-organize AI components - Added AIChatContextBar, AIChatRoot, AIChatSendButton, and ToolInvocationComponent to improve chat interface. - Implemented displays for analytics, entries, feeds, and subscriptions, enhancing data presentation in chat. - Refactored ChatInput to integrate new components and streamline user interactions. - Enhanced message handling with AIChatMessage and AIMarkdownMessage for better content rendering. Signed-off-by: Innei * refactor: enhance dropdown menu layout and shortcut display - Updated DropdownMenuItem to improve spacing for shortcut display. - Adjusted AIChatContextBar to align dropdown menu content and ensure consistent presentation of shortcuts. - Removed redundant shortcut display logic for cleaner code. Signed-off-by: Innei * refactor: remove unused AI components and update imports - Deleted AISpline and mockShortcuts components to streamline the codebase. - Updated import paths for AISpline in WelcomeScreen and AIChatContainer to reflect the new structure. Signed-off-by: Innei * refactor: remove AI spline asset and update loader URL - Deleted the ai.splinecode asset file to streamline the project. - Updated AISplineLoader to use a direct URL for the AI spline asset, improving loading efficiency. Signed-off-by: Innei * refactor: enhance WelcomeScreen with settings modal integration - Added a button to edit the personal prompt in the WelcomeScreen, linking to the settings modal. - Improved layout for the personal prompt display by organizing elements within a flex container. Signed-off-by: Innei * refactor: streamline session state management and enhance UI components - Refactored session state management by creating reusable atom hooks for current room ID, title, and session persistence. - Updated AIChatRoot and related components to utilize the new hooks for improved state handling. - Enhanced ChatHeader to animate the display of the current title. - Adjusted ChatInterface to ensure proper state usage and maintain clean code structure. - Modified RightContent to remove unnecessary props for better clarity. Signed-off-by: Innei * refactor: implement message editing functionality in chat interface - Added EditableMessage component to allow users to edit their messages. - Integrated editing state management into AIChatMessage for seamless user experience. - Updated ChatInterface to handle error states and improve message display logic. - Enhanced user interaction with action buttons for editing, retrying, and copying messages. Signed-off-by: Innei * refactor: optimize AI chat components with memoization - Wrapped AIChatContextBar, ChatInput, and AIMessageParts components with memo for performance improvements. - Updated imports to include memo and adjusted component definitions accordingly. - Enhanced dropdown menu layout in ChatMoreDropdown for better usability and responsiveness. Signed-off-by: Innei * refactor: update MermaidDiagram and ChatInput components - Removed loading icon from MermaidDiagram to simplify the rendering process. - Added context menu propagation prevention in ChatInput to enhance user interaction and prevent unwanted actions. Signed-off-by: Innei * refactor: update GlassButton component and related usages - Renamed 'variant' prop to 'theme' for clarity and introduced a new 'variant' prop for visual styles (glass and flat). - Updated styles and default values in the GlassButton component to reflect the new structure. - Adjusted usages of GlassButton across various components to align with the new prop names and styles. - Modified ChatInput component to enhance shadow styles for the minimal variant. Signed-off-by: Innei * refactor: enhance ToolInvocationComponent and WelcomeScreen - Updated ToolInvocationComponent to include a max-width style for better layout control. - Introduced a DEFAULT_SHORTCUTS array in WelcomeScreen to streamline the management of default suggestions. - Refactored the rendering logic in WelcomeScreen to utilize the new DEFAULT_SHORTCUTS array for displaying suggestions. Signed-off-by: Innei * feat: implement thinking indicator in AIMessageParts component - Replaced the static "AI is thinking..." message with a dynamic ThinkingIndicator component that animates the text display. - Integrated motion effects using the 'motion/react' library for a smoother user experience. - Updated the ChatInterface to utilize the new ThinkingIndicator for better visual feedback during AI processing. Signed-off-by: Innei * feat: add RelatedEntryLink component for enhanced link handling in AIMarkdownMessage - Introduced RelatedEntryLink to handle business ID links with a modal preview. - Updated link rendering logic in AIMarkdownMessage to utilize RelatedEntryLink for improved user interaction. - Enhanced markdown link handling by integrating peek modal functionality for business IDs. Signed-off-by: Innei * feat: update GlassButton styles and introduce EntryLayoutContent component - Enhanced GlassButton component styles for light, dark, and auto themes, improving visual consistency. - Added new EntryLayoutContent component to manage entry content display, integrating AI chat and entry content seamlessly. - Updated EntryContentPlaceholder to utilize the new flat variant of GlassButton for better UI consistency. - Refactored index export to use EntryLayoutContent as RightContentLayout. Signed-off-by: Innei * feat: integrate AI chat functionality and enhance toolbar interactions - Added AI chat feature toggle in useEntryActions, controlling visibility based on server configurations. - Updated the customize toolbar to include a warning for the AI chat pinned action. - Wrapped AISmartSidebar in a React.Suspense component for improved loading behavior. - Implemented error handling in AISmartSidebar to manage AI feature availability. - Added localization for the AI chat pinned warning message. Signed-off-by: Innei * fix: update useEntryActions to streamline entry properties - Added entry?.imagesLength and entry?.hasContent to the dependencies of useEntryActions for improved data handling. - Removed entry?.hasContent from the previous dependencies to avoid redundancy. - Adjusted the order of entry properties for better clarity and organization. Signed-off-by: Innei * ci: update Claude workflow to enhance PR assistance functionality - Renamed workflow from "Claude Code Review" to "Claude PR Assistant" - Updated event triggers to include issue comments, pull request review comments, and issues - Simplified job conditions for running the Claude action - Changed step name to "Run Claude PR Action" and adjusted parameters for improved integration Signed-off-by: Innei * refactor(shortcuts): remove unused shortcut settings component - Deleted the `ShortcutSetting` component and its associated logic, including custom shortcut handling and reset functionality. - Cleaned up related components and interfaces to streamline the shortcuts management code. This change simplifies the shortcuts management by removing unnecessary complexity and unused code. Signed-off-by: Innei * Implement code changes to enhance functionality and improve performance Signed-off-by: Innei * fix: types --------- Signed-off-by: Innei Co-authored-by: DIYgod --- .cursor/rules/i18n.mdc | 17 + .cursorignore | 1 + .gitattributes | 1 + apps/desktop/layer/renderer/package.json | 6 + .../layer/renderer/src/@types/constants.ts | 2 +- .../renderer/src/@types/default-resource.ts | 2 + .../layer/renderer/src/atoms/settings/ai.ts | 27 + .../components/common/AppErrorBoundary.tsx | 21 +- .../src/components/common/Focusable.tsx | 1 + .../src/components/ui/button/GlassButton.tsx | 198 + .../components/ui/diagrams/MermaidDiagram.tsx | 191 + .../src/components/ui/diagrams/index.ts | 1 + .../ui/dropdown-menu/dropdown-menu.tsx | 9 +- .../ui/keyboard-recorder/KeyRecorder.tsx | 197 + .../components/ui/keyboard-recorder/index.ts | 1 + .../ui/media/PreviewMediaContent.tsx | 99 +- .../components/ui/modal/components/base.tsx | 32 - .../components/ui/modal/components/close.tsx | 19 +- .../components/ui/modal/inspire/PeekModal.tsx | 24 +- .../src/components/ui/modal/stacked/hooks.tsx | 8 +- .../layer/renderer/src/constants/hotkeys.ts | 1 + .../src/hooks/biz/useEntryActions.tsx | 28 +- .../renderer/src/hooks/biz/usePeekModal.tsx | 286 ++ .../layer/renderer/src/modules/ai/AISpline.ts | 14 + .../src/modules/ai/AISplineLoader.tsx | 141 + .../src/modules/ai/ai-daily/daily.tsx | 286 +- .../ai/chat/__internal__/AIChatContext.ts | 50 + .../src/modules/ai/chat/__internal__/store.ts | 203 + .../src/modules/ai/chat/__internal__/types.ts | 52 + .../src/modules/ai/chat/__internal__/utils.ts | 72 + .../src/modules/ai/chat/atoms/session.ts | 49 + .../ai/chat/components/AIChatContextBar.tsx | 439 ++ .../modules/ai/chat/components/AIChatRoot.tsx | 247 + .../ai/chat/components/AIChatSendButton.tsx | 40 + .../modules/ai/chat/components/ChatInput.tsx | 112 + .../ai/chat/components/CollapsibleError.tsx | 100 + .../components/ToolInvocationComponent.tsx | 62 + .../ai/chat/components/WelcomeScreen.tsx | 99 + .../ai/chat/components/common-states.tsx | 53 + .../displays/AIDisplayAnalyticsPart.tsx | 312 ++ .../displays/AIDisplayEntriesPart.tsx | 370 ++ .../displays/AIDisplayFeedsPart.tsx | 173 + .../displays/AIDisplaySubscriptionsPart.tsx | 286 ++ .../ai/chat/components/displays/index.ts | 4 + .../displays/shared/AnalyticsMetrics.tsx | 22 + .../displays/shared/CategoryTag.tsx | 19 + .../displays/shared/ChartPlaceholder.tsx | 32 + .../displays/shared/DisplayHeader.tsx | 20 + .../components/displays/shared/EmptyState.tsx | 14 + .../displays/shared/FeedItemCard.tsx | 42 + .../displays/shared/GridContainer.tsx | 33 + .../displays/shared/GroupedContent.tsx | 53 + .../components/displays/shared/StatCard.tsx | 29 + .../displays/shared/StatisticsOverview.tsx | 34 + .../chat/components/displays/shared/index.ts | 10 + .../chat/components/message/AIChatMessage.tsx | 237 + .../components/message/AIMarkdownMessage.tsx | 90 + .../components/message/AIMessageParts.tsx | 132 + .../components/message/EditableMessage.tsx | 141 + .../modules/ai/chat/hooks/useAutoScroll.tsx | 135 + .../modules/ai/chat/hooks/useChatHistory.ts | 47 + .../modules/ai/chat/hooks/useLoadMessages.ts | 47 + .../modules/ai/chat/hooks/useSaveMessages.ts | 32 + .../src/modules/ai/chat/services/index.ts | 104 + .../src/modules/ai/chat/types/ChatSession.ts | 6 + .../src/modules/ai/chat/utils/export.ts | 70 + .../modules/ai/chat/utils/titleGeneration.ts | 39 + .../modules/app-layout/ai/AIChatLayout.tsx | 20 + .../app-layout/ai/components/ChatHeader.tsx | 77 + .../ai/components/ChatInterface.tsx | 169 + .../ai/components/ChatMoreDropdown.tsx | 176 + .../entry-content/EntryContentPlaceholder.tsx | 14 +- .../entry-content/EntryLayoutContent.tsx | 194 + .../app-layout/entry-content/RightContent.tsx | 110 - .../app-layout/entry-content/index.tsx | 2 +- .../SubscriptionColumn.tsx | 10 +- .../timeline-column/CenterColumnLayout.tsx | 6 +- .../src/modules/command/commands/global.tsx | 53 +- .../src/modules/command/commands/id.ts | 2 + .../command/hooks/use-command-binding.ts | 4 + .../command/hooks/use-register-hotkey.ts | 1 + .../command/shortcuts/SettingShortcuts.tsx | 414 +- .../src/modules/customize-toolbar/constant.ts | 1 + .../src/modules/customize-toolbar/dnd.tsx | 4 + .../entry-column/layouts/EntryItemWrapper.tsx | 14 +- .../components/entry-content/EntryContent.tsx | 27 +- .../{ => accessories}/ContainerToc.tsx | 20 +- .../entry-content/accessories/index.tsx | 17 + .../entry-content/ai/AIChatBottom.tsx | 31 + .../entry-content/ai/AIChatContainer.tsx | 198 + .../entry-content/ai/AIChatInput.tsx | 128 + .../entry-content/ai/AIPanelHeader.tsx | 61 + .../components/entry-content/ai/context.ts | 13 + .../components/entry-content/ai/index.tsx | 324 ++ .../components/entry-content/index.ts | 1 - .../components/entry-header/EntryHeader.tsx | 4 +- .../renderer/src/modules/settings/control.tsx | 35 +- .../src/modules/settings/helper/sync-queue.ts | 9 +- .../src/modules/settings/modal/layout.tsx | 2 +- .../settings/modal/use-setting-modal-hack.ts | 6 +- .../src/modules/settings/sections/fonts.tsx | 20 +- .../renderer/src/modules/settings/tabs/ai.tsx | 370 ++ .../src/modules/settings/tabs/shortcut.tsx | 232 + .../SubscriptionColumnHeader.tsx | 2 +- .../src/pages/settings/(settings)/ai.tsx | 21 + .../pages/settings/(settings)/shortcuts.tsx | 2 +- .../renderer/src/providers/root-providers.tsx | 3 +- apps/desktop/plugins/vite/ast.ts | 1 + apps/desktop/plugins/vite/hmr.ts | 40 +- icons/mgc/ai_cute_fi.svg | 1 + icons/mgc/arrow_up_circle_cute_fi.svg | 1 + icons/mgc/comment_2_cute_re.svg | 1 + icons/mgc/comment_cute_fi.svg | 1 + icons/mgc/comment_cute_li.svg | 1 + icons/mgc/comment_cute_re.svg | 1 + icons/mgc/history_cute_re.svg | 1 + icons/mgc/mic_cute_re.svg | 1 + icons/mgc/mind_map_cute_re.svg | 1 + icons/mgc/send_plane_cute_fi.svg | 1 + locales/ai/en.json | 37 + locales/app/en.json | 1 + locales/errors/en.json | 3 +- locales/settings/en.json | 6 + locales/shortcuts/en.json | 4 + .../configs/tailwindcss/tailwind-extend.css | 15 + packages/configs/tailwindcss/web.ts | 1 - .../src/common/Focusable/Focusable.tsx | 2 + .../components/src/common/Focusable/hooks.ts | 8 - .../components/src/ui/accordion/index.tsx | 17 +- .../{PanelSpliter.tsx => PanelSplitter.tsx} | 3 +- .../components/src/ui/divider/index.ts | 2 +- .../components/src/ui/input/TextArea.tsx | 20 +- packages/internal/database/package.json | 1 + .../src/drizzle/0029_flaky_gorgon.sql | 14 + .../src/drizzle/0030_common_gabe_jones.sql | 14 + ...tain_universe.sql => 0031_kind_ikaris.sql} | 0 .../src/drizzle/meta/0029_snapshot.json | 96 +- .../src/drizzle/meta/0030_snapshot.json | 872 ++++ .../src/drizzle/meta/0031_snapshot.json | 879 ++++ .../database/src/drizzle/meta/_journal.json | 18 +- .../database/src/drizzle/migrations.js | 6 +- .../internal/database/src/schemas/index.ts | 27 + packages/internal/shared/src/hono.ts | 4145 +++++++++-------- .../internal/shared/src/settings/defaults.ts | 10 +- .../internal/shared/src/settings/interface.ts | 14 + pnpm-lock.yaml | 983 +++- 146 files changed, 12724 insertions(+), 3046 deletions(-) create mode 100644 .cursor/rules/i18n.mdc create mode 100644 .cursorignore create mode 100644 apps/desktop/layer/renderer/src/atoms/settings/ai.ts create mode 100644 apps/desktop/layer/renderer/src/components/ui/button/GlassButton.tsx create mode 100644 apps/desktop/layer/renderer/src/components/ui/diagrams/MermaidDiagram.tsx create mode 100644 apps/desktop/layer/renderer/src/components/ui/diagrams/index.ts create mode 100644 apps/desktop/layer/renderer/src/components/ui/keyboard-recorder/KeyRecorder.tsx create mode 100644 apps/desktop/layer/renderer/src/components/ui/keyboard-recorder/index.ts delete mode 100644 apps/desktop/layer/renderer/src/components/ui/modal/components/base.tsx create mode 100644 apps/desktop/layer/renderer/src/hooks/biz/usePeekModal.tsx create mode 100644 apps/desktop/layer/renderer/src/modules/ai/AISpline.ts create mode 100644 apps/desktop/layer/renderer/src/modules/ai/AISplineLoader.tsx create mode 100644 apps/desktop/layer/renderer/src/modules/ai/chat/__internal__/AIChatContext.ts create mode 100644 apps/desktop/layer/renderer/src/modules/ai/chat/__internal__/store.ts create mode 100644 apps/desktop/layer/renderer/src/modules/ai/chat/__internal__/types.ts create mode 100644 apps/desktop/layer/renderer/src/modules/ai/chat/__internal__/utils.ts create mode 100644 apps/desktop/layer/renderer/src/modules/ai/chat/atoms/session.ts create mode 100644 apps/desktop/layer/renderer/src/modules/ai/chat/components/AIChatContextBar.tsx create mode 100644 apps/desktop/layer/renderer/src/modules/ai/chat/components/AIChatRoot.tsx create mode 100644 apps/desktop/layer/renderer/src/modules/ai/chat/components/AIChatSendButton.tsx create mode 100644 apps/desktop/layer/renderer/src/modules/ai/chat/components/ChatInput.tsx create mode 100644 apps/desktop/layer/renderer/src/modules/ai/chat/components/CollapsibleError.tsx create mode 100644 apps/desktop/layer/renderer/src/modules/ai/chat/components/ToolInvocationComponent.tsx create mode 100644 apps/desktop/layer/renderer/src/modules/ai/chat/components/WelcomeScreen.tsx create mode 100644 apps/desktop/layer/renderer/src/modules/ai/chat/components/common-states.tsx create mode 100644 apps/desktop/layer/renderer/src/modules/ai/chat/components/displays/AIDisplayAnalyticsPart.tsx create mode 100644 apps/desktop/layer/renderer/src/modules/ai/chat/components/displays/AIDisplayEntriesPart.tsx create mode 100644 apps/desktop/layer/renderer/src/modules/ai/chat/components/displays/AIDisplayFeedsPart.tsx create mode 100644 apps/desktop/layer/renderer/src/modules/ai/chat/components/displays/AIDisplaySubscriptionsPart.tsx create mode 100644 apps/desktop/layer/renderer/src/modules/ai/chat/components/displays/index.ts create mode 100644 apps/desktop/layer/renderer/src/modules/ai/chat/components/displays/shared/AnalyticsMetrics.tsx create mode 100644 apps/desktop/layer/renderer/src/modules/ai/chat/components/displays/shared/CategoryTag.tsx create mode 100644 apps/desktop/layer/renderer/src/modules/ai/chat/components/displays/shared/ChartPlaceholder.tsx create mode 100644 apps/desktop/layer/renderer/src/modules/ai/chat/components/displays/shared/DisplayHeader.tsx create mode 100644 apps/desktop/layer/renderer/src/modules/ai/chat/components/displays/shared/EmptyState.tsx create mode 100644 apps/desktop/layer/renderer/src/modules/ai/chat/components/displays/shared/FeedItemCard.tsx create mode 100644 apps/desktop/layer/renderer/src/modules/ai/chat/components/displays/shared/GridContainer.tsx create mode 100644 apps/desktop/layer/renderer/src/modules/ai/chat/components/displays/shared/GroupedContent.tsx create mode 100644 apps/desktop/layer/renderer/src/modules/ai/chat/components/displays/shared/StatCard.tsx create mode 100644 apps/desktop/layer/renderer/src/modules/ai/chat/components/displays/shared/StatisticsOverview.tsx create mode 100644 apps/desktop/layer/renderer/src/modules/ai/chat/components/displays/shared/index.ts create mode 100644 apps/desktop/layer/renderer/src/modules/ai/chat/components/message/AIChatMessage.tsx create mode 100644 apps/desktop/layer/renderer/src/modules/ai/chat/components/message/AIMarkdownMessage.tsx create mode 100644 apps/desktop/layer/renderer/src/modules/ai/chat/components/message/AIMessageParts.tsx create mode 100644 apps/desktop/layer/renderer/src/modules/ai/chat/components/message/EditableMessage.tsx create mode 100644 apps/desktop/layer/renderer/src/modules/ai/chat/hooks/useAutoScroll.tsx create mode 100644 apps/desktop/layer/renderer/src/modules/ai/chat/hooks/useChatHistory.ts create mode 100644 apps/desktop/layer/renderer/src/modules/ai/chat/hooks/useLoadMessages.ts create mode 100644 apps/desktop/layer/renderer/src/modules/ai/chat/hooks/useSaveMessages.ts create mode 100644 apps/desktop/layer/renderer/src/modules/ai/chat/services/index.ts create mode 100644 apps/desktop/layer/renderer/src/modules/ai/chat/types/ChatSession.ts create mode 100644 apps/desktop/layer/renderer/src/modules/ai/chat/utils/export.ts create mode 100644 apps/desktop/layer/renderer/src/modules/ai/chat/utils/titleGeneration.ts create mode 100644 apps/desktop/layer/renderer/src/modules/app-layout/ai/AIChatLayout.tsx create mode 100644 apps/desktop/layer/renderer/src/modules/app-layout/ai/components/ChatHeader.tsx create mode 100644 apps/desktop/layer/renderer/src/modules/app-layout/ai/components/ChatInterface.tsx create mode 100644 apps/desktop/layer/renderer/src/modules/app-layout/ai/components/ChatMoreDropdown.tsx create mode 100644 apps/desktop/layer/renderer/src/modules/app-layout/entry-content/EntryLayoutContent.tsx delete mode 100644 apps/desktop/layer/renderer/src/modules/app-layout/entry-content/RightContent.tsx rename apps/desktop/layer/renderer/src/modules/entry-content/components/entry-content/{ => accessories}/ContainerToc.tsx (83%) create mode 100644 apps/desktop/layer/renderer/src/modules/entry-content/components/entry-content/accessories/index.tsx create mode 100644 apps/desktop/layer/renderer/src/modules/entry-content/components/entry-content/ai/AIChatBottom.tsx create mode 100644 apps/desktop/layer/renderer/src/modules/entry-content/components/entry-content/ai/AIChatContainer.tsx create mode 100644 apps/desktop/layer/renderer/src/modules/entry-content/components/entry-content/ai/AIChatInput.tsx create mode 100644 apps/desktop/layer/renderer/src/modules/entry-content/components/entry-content/ai/AIPanelHeader.tsx create mode 100644 apps/desktop/layer/renderer/src/modules/entry-content/components/entry-content/ai/context.ts create mode 100644 apps/desktop/layer/renderer/src/modules/entry-content/components/entry-content/ai/index.tsx create mode 100644 apps/desktop/layer/renderer/src/modules/settings/tabs/ai.tsx create mode 100644 apps/desktop/layer/renderer/src/modules/settings/tabs/shortcut.tsx create mode 100644 apps/desktop/layer/renderer/src/pages/settings/(settings)/ai.tsx create mode 100644 icons/mgc/ai_cute_fi.svg create mode 100644 icons/mgc/arrow_up_circle_cute_fi.svg create mode 100644 icons/mgc/comment_2_cute_re.svg create mode 100644 icons/mgc/comment_cute_fi.svg create mode 100644 icons/mgc/comment_cute_li.svg create mode 100644 icons/mgc/comment_cute_re.svg create mode 100644 icons/mgc/history_cute_re.svg create mode 100644 icons/mgc/mic_cute_re.svg create mode 100644 icons/mgc/mind_map_cute_re.svg create mode 100644 icons/mgc/send_plane_cute_fi.svg create mode 100644 locales/ai/en.json rename packages/internal/components/src/ui/divider/{PanelSpliter.tsx => PanelSplitter.tsx} (93%) create mode 100644 packages/internal/database/src/drizzle/0029_flaky_gorgon.sql create mode 100644 packages/internal/database/src/drizzle/0030_common_gabe_jones.sql rename packages/internal/database/src/drizzle/{0029_outstanding_captain_universe.sql => 0031_kind_ikaris.sql} (100%) create mode 100644 packages/internal/database/src/drizzle/meta/0030_snapshot.json create mode 100644 packages/internal/database/src/drizzle/meta/0031_snapshot.json diff --git a/.cursor/rules/i18n.mdc b/.cursor/rules/i18n.mdc new file mode 100644 index 000000000..74fec07a1 --- /dev/null +++ b/.cursor/rules/i18n.mdc @@ -0,0 +1,17 @@ +--- +description: +globs: locales/**/*.json +alwaysApply: false +--- + +i18n Coding Standards. + +1. Read and follow https://www.i18next.com/translation-function/formatting + +2. Use flat keys. Use `.` to separate. Do not use object form nesting. + +3. For languages sensitive to singular and plural, distinguish between them using the `_one` and `_other` forms. + +4. In the build stage, flattened dot-separated keys (such as 'exif.custom.rendered.custom') will be automatically converted to nested object objects, which may cause conflicts. For example, 'exif.custom.rendered.custom' may conflict with 'exif.custom.rendered'. Please avoid using such dot-separated flat keys. + +5. @locales is located at the root directory and needs to handle all existing languages at the same time. diff --git a/.cursorignore b/.cursorignore new file mode 100644 index 000000000..6f9f00ff4 --- /dev/null +++ b/.cursorignore @@ -0,0 +1 @@ +# Add directories or file patterns to ignore during indexing (e.g. foo/ or *.csv) diff --git a/.gitattributes b/.gitattributes index 6313b56c5..e8c09c27f 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1 +1,2 @@ * text=auto eol=lf +*.splinecode filter=lfs diff=lfs merge=lfs -text diff --git a/apps/desktop/layer/renderer/package.json b/apps/desktop/layer/renderer/package.json index bd3e1a205..4db300a89 100644 --- a/apps/desktop/layer/renderer/package.json +++ b/apps/desktop/layer/renderer/package.json @@ -12,6 +12,8 @@ "typecheck": "tsc --noEmit" }, "dependencies": { + "@ai-sdk/openai": "2.0.0-beta.5", + "@ai-sdk/react": "2.0.0-beta.11", "@dnd-kit/core": "6.3.1", "@dnd-kit/sortable": "10.0.0", "@electron-toolkit/preload": "3.0.2", @@ -37,6 +39,7 @@ "@radix-ui/react-slot": "1.2.3", "@sentry/react": "9.35.0", "@shikijs/transformers": "3.7.0", + "@splinetool/react-spline": "4.0.0", "@tanstack/query-sync-storage-persister": "5.81.5", "@tanstack/react-query": "5.81.5", "@tanstack/react-query-devtools": "5.81.5", @@ -45,7 +48,9 @@ "@use-gesture/react": "10.3.1", "@welldone-software/why-did-you-render": "10.0.1", "@yornaath/batshit": "0.10.1", + "ai": "5.0.0-beta.11", "camelcase-keys": "9.1.3", + "class-variance-authority": "0.7.1", "clsx": "2.1.1", "cmdk": "1.1.1", "cookie-es": "2.0.0", @@ -69,6 +74,7 @@ "masonic": "4.1.0", "mdast-util-gfm-table": "2.0.0", "mdast-util-to-markdown": "2.1.2", + "mermaid": "11.7.0", "motion": "12.23.0", "nanoid": "5.1.5", "ofetch": "1.4.1", diff --git a/apps/desktop/layer/renderer/src/@types/constants.ts b/apps/desktop/layer/renderer/src/@types/constants.ts index 6a6368494..2d5659421 100644 --- a/apps/desktop/layer/renderer/src/@types/constants.ts +++ b/apps/desktop/layer/renderer/src/@types/constants.ts @@ -9,5 +9,5 @@ export const dayjsLocaleImportMap = { ["ja"]: ["ja", () => import("dayjs/locale/ja")], ["zh-TW"]: ["zh-tw", () => import("dayjs/locale/zh-tw")], } -export const ns = ["common", "lang", "errors", "app", "settings", "shortcuts"] as const +export const ns = ["common", "lang", "errors", "app", "settings", "shortcuts", "ai"] as const export const defaultNS = "app" as const diff --git a/apps/desktop/layer/renderer/src/@types/default-resource.ts b/apps/desktop/layer/renderer/src/@types/default-resource.ts index 7d5008a83..946e97cdc 100644 --- a/apps/desktop/layer/renderer/src/@types/default-resource.ts +++ b/apps/desktop/layer/renderer/src/@types/default-resource.ts @@ -1,4 +1,5 @@ // DONT EDIT THIS FILE MANUALLY +import ai_en from "@locales/ai/en.json" import en from "@locales/app/en.json" import common_en from "@locales/common/en.json" import common_ja from "@locales/common/ja.json" @@ -29,6 +30,7 @@ export const defaultResources = { settings: settings_en, shortcuts: shortcuts_en, errors: errors_en, + ai: ai_en, }, "zh-CN": { lang: lang_zhCN, diff --git a/apps/desktop/layer/renderer/src/atoms/settings/ai.ts b/apps/desktop/layer/renderer/src/atoms/settings/ai.ts new file mode 100644 index 000000000..dad9bdc24 --- /dev/null +++ b/apps/desktop/layer/renderer/src/atoms/settings/ai.ts @@ -0,0 +1,27 @@ +import { createSettingAtom } from "@follow/atoms/helper/setting.js" +import { defaultAISettings } from "@follow/shared/settings/defaults" +import type { AISettings } from "@follow/shared/settings/interface" +import { jotaiStore } from "@follow/utils" +import { atom, useAtomValue } from "jotai" + +export const createDefaultSettings = (): AISettings => defaultAISettings + +export const { + useSettingKey: useAISettingKey, + useSettingSelector: useAISettingSelector, + setSetting: setAISetting, + clearSettings: clearAISettings, + initializeDefaultSettings: initializeDefaultAISettings, + getSettings: getAISettings, + useSettingValue: useAISettingValue, + settingAtom: __aiSettingAtom, +} = createSettingAtom("ai", createDefaultSettings) +export const aiServerSyncWhiteListKeys = [] +// Local Setting for ai + +const aiChatPinnedAtom = atom(false) +export const useAIChatPinned = () => useAtomValue(aiChatPinnedAtom) +export const setAIChatPinned = (pinned: boolean) => { + jotaiStore.set(aiChatPinnedAtom, pinned) +} +export const getAIChatPinned = () => jotaiStore.get(aiChatPinnedAtom) diff --git a/apps/desktop/layer/renderer/src/components/common/AppErrorBoundary.tsx b/apps/desktop/layer/renderer/src/components/common/AppErrorBoundary.tsx index fd5d8ea44..dc88723a4 100644 --- a/apps/desktop/layer/renderer/src/components/common/AppErrorBoundary.tsx +++ b/apps/desktop/layer/renderer/src/components/common/AppErrorBoundary.tsx @@ -5,6 +5,7 @@ import { createElement, Suspense, useCallback } from "react" import { getErrorFallback } from "../errors" import type { ErrorComponentType } from "../errors/enum" +import PageErrorFallback from "../errors/PageError" export interface AppErrorBoundaryProps extends PropsWithChildren { height?: number | string @@ -38,19 +39,15 @@ type ErrorFallbackProps = Parameters["0"] export type AppErrorFallbackProps = ErrorFallbackProps & {} const AppErrorBoundaryItem: FC = ({ errorType, children }) => { const fallbackRender = useCallback( - (fallbackProps: ErrorFallbackProps) => ( - {createElement(getErrorFallback(errorType), fallbackProps)} - ), + (fallbackProps: ErrorFallbackProps) => { + const errorElement = getErrorFallback(errorType) + if (!errorElement) { + return + } + return {createElement(getErrorFallback(errorType), fallbackProps)} + }, [errorType], ) - const onError = useCallback((error: unknown, componentStack?: string) => { - console.error("Uncaught error:", error, componentStack) - }, []) - - return ( - - {children} - - ) + return {children} } diff --git a/apps/desktop/layer/renderer/src/components/common/Focusable.tsx b/apps/desktop/layer/renderer/src/components/common/Focusable.tsx index 301f2b28d..7be2af85d 100644 --- a/apps/desktop/layer/renderer/src/components/common/Focusable.tsx +++ b/apps/desktop/layer/renderer/src/components/common/Focusable.tsx @@ -24,4 +24,5 @@ export const FocusablePresets = { }, isTimeline: (v) => v.has(HotkeyScope.Timeline) && !v.has(HotkeyScope.EntryRender), isEntryRender: (v) => v.has(HotkeyScope.EntryRender), + isAIChat: (v) => v.has(HotkeyScope.AIChat), } satisfies Record) => boolean> diff --git a/apps/desktop/layer/renderer/src/components/ui/button/GlassButton.tsx b/apps/desktop/layer/renderer/src/components/ui/button/GlassButton.tsx new file mode 100644 index 000000000..238848425 --- /dev/null +++ b/apps/desktop/layer/renderer/src/components/ui/button/GlassButton.tsx @@ -0,0 +1,198 @@ +import { Spring } from "@follow/components/constants/spring.js" +import { + Tooltip, + TooltipContent, + TooltipPortal, + TooltipTrigger, +} from "@follow/components/ui/tooltip/index.js" +import { cn } from "@follow/utils/utils" +import { cva } from "class-variance-authority" +import { m } from "motion/react" +import type { FC, ReactNode } from "react" + +export interface GlassButtonProps { + description?: string + onClick: () => void + className?: string + children: ReactNode + /** + * Custom animation variants for hover and tap states + */ + hoverScale?: number + tapScale?: number + /** + * Size variant + */ + size?: "sm" | "md" | "lg" + /** + * Color theme + */ + theme?: "light" | "dark" | "auto" + /** + * Visual variant + */ + variant?: "glass" | "flat" +} + +const glassButtonVariants = cva( + [ + // Base styles - perfect 1:1 circle + "pointer-events-auto relative flex items-center justify-center rounded-full", + "transition-all duration-300 ease-out", + ], + { + variants: { + size: { + sm: "size-8 text-sm", + md: "size-10 text-lg", + lg: "size-12 text-xl", + }, + theme: { + light: ["text-gray-700 hover:text-gray-900"], + dark: ["text-white hover:text-white"], + auto: ["text-text hover:text-text-vibrant"], + }, + variant: { + glass: ["backdrop-blur-md border shadow-lg"], + flat: ["border shadow-none"], + }, + }, + compoundVariants: [ + // Glass variant themes + { + variant: "glass", + theme: "light", + className: [ + "bg-material-thin hover:bg-material-medium", + "border-gray/30 hover:border-gray/40", + "shadow-gray/30", + ], + }, + { + variant: "glass", + theme: "dark", + className: [ + "bg-material-ultra-thin hover:bg-material-thin", + "border-gray/10 hover:border-gray/20", + "shadow-black/25", + ], + }, + { + variant: "glass", + theme: "auto", + className: [ + "bg-material-thin hover:bg-material-medium", + "border-gray/30 hover:border-gray/40", + "shadow-gray/30", + ], + }, + // Flat variant themes + { + variant: "flat", + theme: "light", + className: ["bg-white/80 hover:bg-white/90", "border-gray/20 hover:border-gray/30"], + }, + { + variant: "flat", + theme: "dark", + className: [ + "bg-fill-secondary hover:bg-fill-tertiary", + "border-gray/20 hover:border-gray/30", + ], + }, + { + variant: "flat", + theme: "auto", + className: [ + "bg-white/80 hover:bg-white/90 dark:bg-fill-secondary dark:hover:bg-fill-tertiary", + "border-gray/20 hover:border-gray/30", + ], + }, + ], + defaultVariants: { + size: "md", + theme: "auto", + variant: "glass", + }, + }, +) + +const glassOverlayVariants = cva( + "absolute inset-0 rounded-full bg-gradient-to-t opacity-0 transition-opacity duration-300 hover:opacity-100", + { + variants: { + theme: { + light: "from-material-opaque/10 to-material-opaque/30", + dark: "from-material-opaque/5 to-material-opaque/20", + auto: "from-material-opaque/10 to-material-opaque/30", + }, + }, + defaultVariants: { + theme: "auto", + }, + }, +) + +const glassInnerShadowVariants = cva("absolute inset-0 rounded-full shadow-inner", { + variants: { + theme: { + light: "shadow-gray/20", + dark: "shadow-black/10", + auto: "shadow-gray/20 dark:shadow-black/10", + }, + }, + defaultVariants: { + theme: "auto", + }, +}) + +export const GlassButton: FC = ({ + description, + onClick, + className, + children, + hoverScale = 1.1, + tapScale = 0.95, + size = "md", + theme = "auto", + variant = "glass", +}) => { + return ( + + + { + e.stopPropagation() + onClick() + }} + className={cn(glassButtonVariants({ size, theme, variant }), className)} + initial={{ scale: 1 }} + whileHover={ + variant === "flat" + ? undefined + : { + scale: hoverScale, + } + } + whileTap={{ scale: tapScale }} + transition={Spring.presets.snappy} + > + {/* Glass effect overlay - only for glass variant */} + {variant === "glass" &&
} + + {/* Icon container */} +
{children}
+ + {/* Subtle inner shadow for depth - only for glass variant */} + {variant === "glass" &&
} + + + {description && ( + + {description} + + )} + + ) +} diff --git a/apps/desktop/layer/renderer/src/components/ui/diagrams/MermaidDiagram.tsx b/apps/desktop/layer/renderer/src/components/ui/diagrams/MermaidDiagram.tsx new file mode 100644 index 000000000..3833725b8 --- /dev/null +++ b/apps/desktop/layer/renderer/src/components/ui/diagrams/MermaidDiagram.tsx @@ -0,0 +1,191 @@ +import { cn } from "@follow/utils" +import { memo, useCallback, useEffect, useRef, useState } from "react" + +import { usePreviewMedia } from "~/components/ui/media/hooks" + +interface MermaidDiagramProps { + code: string + className?: string + + shouldRender?: boolean +} + +export const MermaidDiagram = memo(({ code, className, shouldRender }) => { + const containerRef = useRef(null) + const [error, setError] = useState(null) + const [isLoading, setIsLoading] = useState(true) + + const [imageUrl, setImageUrl] = useState("") + const previewMedia = usePreviewMedia() + + const handleImagePreview = useCallback(() => { + if (imageUrl) { + previewMedia([{ url: imageUrl, type: "photo" }]) + } + }, [imageUrl, previewMedia]) + + useEffect(() => { + if (!shouldRender) return + + let mounted = true + + const renderDiagram = async () => { + if (!code.trim()) return + + try { + setIsLoading(true) + setError(null) + + // Dynamic import to avoid loading Mermaid on the main thread + const mermaid = await import("mermaid").then((m) => m.default) + + // Initialize mermaid with better spacing configuration + mermaid.initialize({ + startOnLoad: false, + theme: "default", + securityLevel: "loose", // Allow HTML in diagrams + fontFamily: "system-ui, sans-serif", + flowchart: { + htmlLabels: true, + curve: "basis", + nodeSpacing: 50, + rankSpacing: 80, + padding: 20, + }, + themeVariables: { + primaryColor: "#f0f0f0", + primaryTextColor: "#333", + primaryBorderColor: "#ccc", + lineColor: "#666", + background: "#fff", + secondaryColor: "#f9f9f9", + tertiaryColor: "#fafafa", + }, + }) + + // Generate unique ID for this diagram + const id = `mermaid-${Date.now()}-${Math.random().toString(36).slice(2, 11)}` + + if (!mounted) return + + // Render the diagram + const { svg } = await mermaid.render(id, code) + + if (!mounted) return + + if (containerRef.current) { + containerRef.current.innerHTML = svg + + // Apply theme-aware styling to the SVG with better spacing + const svgElement = containerRef.current.querySelector("svg") + if (svgElement) { + svgElement.style.maxWidth = "100%" + svgElement.style.height = "auto" + svgElement.style.minHeight = "200px" + svgElement.setAttribute("class", "dark:invert-[0.87] dark:hue-rotate-180") + + // Add padding and spacing styles + svgElement.style.padding = "20px" + + // Adjust node spacing through CSS + const style = document.createElement("style") + style.textContent = ` + .node { + margin: 10px !important; + } + .edgeLabel { + background-color: rgba(255, 255, 255, 0.8) !important; + padding: 4px 8px !important; + border-radius: 4px !important; + } + .cluster rect { + fill: rgba(0, 0, 0, 0.05) !important; + stroke: rgba(0, 0, 0, 0.2) !important; + stroke-width: 1px !important; + } + ` + svgElement.append(style) + } + } + + try { + const blob = new Blob([svg], { type: "image/svg+xml;charset=utf-8" }) + const url = URL.createObjectURL(blob) + + if (mounted) { + setImageUrl(url) + } + } catch (imgErr) { + console.warn("Failed to convert SVG to image:", imgErr) + } + + setIsLoading(false) + } catch (err) { + console.error("Mermaid rendering error:", err) + if (mounted) { + setError(err instanceof Error ? err.message : "Failed to render diagram") + setIsLoading(false) + } + } + } + renderDiagram() + return () => { + mounted = false + } + }, [code, shouldRender]) + + if (error) { + return ( +
+
+ + Failed to render Mermaid diagram +
+
+ + Show error details + +
+            {error}
+          
+
+
+ ) + } + + return ( +
+ {!isLoading && !error && imageUrl && ( +
+ Mermaid Diagram + +
+ )} + +
+ {isLoading && ( +
+ Rendering diagram... +
+ )} +
+
+
+ ) +}) + +MermaidDiagram.displayName = "MermaidDiagram" diff --git a/apps/desktop/layer/renderer/src/components/ui/diagrams/index.ts b/apps/desktop/layer/renderer/src/components/ui/diagrams/index.ts new file mode 100644 index 000000000..d1eff0348 --- /dev/null +++ b/apps/desktop/layer/renderer/src/components/ui/diagrams/index.ts @@ -0,0 +1 @@ +export { MermaidDiagram } from "./MermaidDiagram" 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 7166c218f..1177cd6dd 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 @@ -154,9 +154,12 @@ const DropdownMenuItem = ({ {/* Justify Fill */} {!!icon && } {!!shortcut && ( - - {shortcut} - + <> + + + {shortcut} + + )} ) diff --git a/apps/desktop/layer/renderer/src/components/ui/keyboard-recorder/KeyRecorder.tsx b/apps/desktop/layer/renderer/src/components/ui/keyboard-recorder/KeyRecorder.tsx new file mode 100644 index 000000000..6c212e057 --- /dev/null +++ b/apps/desktop/layer/renderer/src/components/ui/keyboard-recorder/KeyRecorder.tsx @@ -0,0 +1,197 @@ +import { useReplaceGlobalFocusableScope } from "@follow/components/common/Focusable/hooks.js" +import { KbdCombined } from "@follow/components/ui/kbd/Kbd.js" +import { Tooltip, TooltipContent, TooltipTrigger } from "@follow/components/ui/tooltip/index.js" +import { sortShortcutKeys } from "@follow/utils/utils" +import type { FC, RefObject, SVGProps } from "react" +import { useEffect, useRef, useState } from "react" +import { useTranslation } from "react-i18next" +import { useOnClickOutside } from "usehooks-ts" + +import { HotkeyScope } from "~/constants" + +export interface KeyRecorderProps { + onChange: (keys: string[] | null) => void + onBlur: () => void +} + +export const KeyRecorder: FC = ({ onChange, onBlur }) => { + const { t } = useTranslation("shortcuts") + const { currentKeys } = useShortcutRecorder() + const setGlobalScope = useReplaceGlobalFocusableScope() + + const ref = useRef(null) + useEffect(() => { + const { rollback } = setGlobalScope(HotkeyScope.Recording) + if (ref.current) { + ref.current.focus() + } + return () => { + rollback() + } + }, [setGlobalScope]) + useOnClickOutside(ref as RefObject, () => { + if (currentKeys.length > 0) { + onChange(currentKeys) + } + onBlur() + }) + return ( +
+ {currentKeys.length > 0 ? ( +
+ + {currentKeys.join("+")} + +
+ ) : ( + {t("settings.shortcuts.press_to_record")} + )} + + + + + + {currentKeys.length > 0 ? t("settings.shortcuts.undo") : t("settings.shortcuts.reset")} + + +
+ ) +} + +function FamiconsArrowUndoCircle(props: SVGProps) { + return ( + + {/* Icon from Famicons by Family - https://github.com/familyjs/famicons/blob/main/LICENSE */} + + + ) +} + +const MODIFIER_KEYS_MAP = { + Control: "Control", + Alt: "Alt", + Shift: "Shift", + Meta: "Meta", +} as const + +const MODIFIER_KEYS_SET = new Set(Object.values(MODIFIER_KEYS_MAP)) + +const F_KEY_REGEX = /^F(?:[1-9]|1[0-2])$/ + +const useShortcutRecorder = () => { + const [currentKeys, setCurrentKeys] = useState([]) + + useEffect(() => { + const handleKeyDown = (event: KeyboardEvent) => { + event.preventDefault() + event.stopPropagation() + event.stopImmediatePropagation() + + const { altKey, ctrlKey, metaKey, shiftKey, key: eventKey } = event + + let mainKeyPressed = eventKey + + if (mainKeyPressed.length === 1 && mainKeyPressed >= "a" && mainKeyPressed <= "z") { + mainKeyPressed = mainKeyPressed.toUpperCase() + } else if (mainKeyPressed === " ") { + mainKeyPressed = "Space" + } + + const pressedKeysSet = new Set() + + if (shiftKey) pressedKeysSet.add(MODIFIER_KEYS_MAP.Shift) + if (metaKey) pressedKeysSet.add(MODIFIER_KEYS_MAP.Meta) + if (ctrlKey) pressedKeysSet.add(MODIFIER_KEYS_MAP.Control) + if (altKey) pressedKeysSet.add(MODIFIER_KEYS_MAP.Alt) + + // If mainKeyPressed (from event.key) is not a modifier key, add it as the main key. + // If mainKeyPressed is a modifier key (e.g., user only pressed Shift key, event.key is "Shift"), + // it has already been handled and added to pressedKeysSet by the above if (shiftKey) logic, + // so we don't need to add it again here. + if (!MODIFIER_KEYS_SET.has(mainKeyPressed)) { + pressedKeysSet.add(mainKeyPressed) + } + + const currentCombination = Array.from(pressedKeysSet) + + // --- Start validation rules --- + const nonModifierKeysInCombo = currentCombination.filter((key) => !MODIFIER_KEYS_SET.has(key)) + + // Rule 2: Pure modifier key combinations are not allowed (e.g., just Shift, or Ctrl+Alt) + if (nonModifierKeysInCombo.length === 0) { + // When only modifier keys are pressed, currentCombination will still contain these modifiers. + // For example, pressing only Shift, currentCombination is ["Shift"] + // Here we don't update the state, indicating this is an invalid recording. + // You can provide temporary UI feedback here, e.g.: "Recording: Shift" + console.info( + "Recording (invalid - modifiers only):", + sortShortcutKeys(currentCombination).join(" + "), + ) + return + } + + // Typically shortcuts have only one "main" function key (e.g., Ctrl+A, Shift+F1) + // If multiple non-modifier keys are detected (e.g., theoretically user pressing A and B simultaneously), + // this is usually not a standard shortcut recording scenario + // This check is mainly for code robustness, as `keydown` events typically focus on one main key at a time. + if (nonModifierKeysInCombo.length > 1) { + console.warn( + "Recording (invalid - multiple main keys, this shouldn't normally happen):", + sortShortcutKeys(currentCombination).join(" + "), + ) + + return + } + + const primaryKey = nonModifierKeysInCombo[0] + + // Rule 3: Fn keys (F1-F12) can be single keys or modifier+Fn key combinations + if (F_KEY_REGEX.test(primaryKey ?? "")) { + setCurrentKeys(sortShortcutKeys(currentCombination)) + return + } + + // Rule 1: Single "ASCII" main keys are allowed (here referring to all non-modifier, non-F keys) + // Examples: A, 1, Space, Enter, ArrowUp, etc. They can be used alone or with modifiers. + // For these keys, as long as they're not pure modifier combinations, they're considered valid. + setCurrentKeys(sortShortcutKeys(currentCombination)) + } + + window.addEventListener("keydown", handleKeyDown) + return () => { + window.removeEventListener("keydown", handleKeyDown) + } + }, [setCurrentKeys]) + return { currentKeys } +} diff --git a/apps/desktop/layer/renderer/src/components/ui/keyboard-recorder/index.ts b/apps/desktop/layer/renderer/src/components/ui/keyboard-recorder/index.ts new file mode 100644 index 000000000..32362ebba --- /dev/null +++ b/apps/desktop/layer/renderer/src/components/ui/keyboard-recorder/index.ts @@ -0,0 +1 @@ +export * from "./KeyRecorder" diff --git a/apps/desktop/layer/renderer/src/components/ui/media/PreviewMediaContent.tsx b/apps/desktop/layer/renderer/src/components/ui/media/PreviewMediaContent.tsx index c5fd6543b..1e0c2e10c 100644 --- a/apps/desktop/layer/renderer/src/components/ui/media/PreviewMediaContent.tsx +++ b/apps/desktop/layer/renderer/src/components/ui/media/PreviewMediaContent.tsx @@ -1,11 +1,5 @@ import { Spring } from "@follow/components/constants/spring.js" import { MotionButtonBase } from "@follow/components/ui/button/index.js" -import { - Tooltip, - TooltipContent, - TooltipPortal, - TooltipTrigger, -} from "@follow/components/ui/tooltip/index.js" import { IN_ELECTRON } from "@follow/shared/constants" import type { MediaModel } from "@follow/shared/hono" import { stopPropagation } from "@follow/utils/dom" @@ -21,6 +15,7 @@ import type { ReactZoomPanPinchRef, ReactZoomPanPinchState } from "react-zoom-pa import { TransformComponent, TransformWrapper } from "react-zoom-pan-pinch" import { m } from "~/components/common/Motion" +import { GlassButton } from "~/components/ui/button/GlassButton" import { COPY_MAP } from "~/constants" import { ipcServices } from "~/lib/client" import { replaceImgUrlIfNeed } from "~/lib/img-proxy" @@ -193,6 +188,7 @@ const Wrapper: FC<{ ) } +const GLASS_BUTTON_CLASS = tw`group-hover/left:opacity-100 opacity-0` const HeaderActions: FC<{ src: string }> = ({ src }) => { @@ -201,89 +197,42 @@ const HeaderActions: FC<{ const { dismiss } = useCurrentModal() return (
- window.open(src)}> + window.open(src)} + > - + {IN_ELECTRON && ( - { ipcServices?.app.download(src) }} > - + )} - - +
) } -const HeaderButton: FC<{ - description?: string - onClick: () => void - className?: string - children: React.ReactNode -}> = ({ description, onClick, className, children }) => { - return ( - - - { - e.stopPropagation() - onClick() - }} - className={cn( - // Base styles with modern glass morphism - perfect 1:1 circle - "pointer-events-auto relative flex size-10 items-center justify-center rounded-full", - "bg-black/20 text-white backdrop-blur-md", - // Border and shadow for depth - "border border-white/10 shadow-lg shadow-black/25", - // Opacity and transition - "opacity-0 transition-all duration-300 ease-out group-hover/left:opacity-100", - // Text size - "text-lg", - className, - )} - initial={{ scale: 1 }} - whileHover={{ - scale: 1.1, - backgroundColor: "rgba(255, 255, 255, 0.15)", - borderColor: "rgba(255, 255, 255, 0.2)", - }} - whileTap={{ scale: 0.95 }} - transition={{ - type: "spring", - stiffness: 400, - damping: 30, - }} - > - {/* Glass effect overlay */} -
- - {/* Icon container */} -
{children}
- - {/* Subtle inner shadow for depth */} -
- - - {description && ( - - {description} - - )} - - ) -} export interface PreviewMediaProps extends MediaModel { fallbackUrl?: string } @@ -396,25 +345,25 @@ export const PreviewMediaContent: FC<{
{currentSlideIndex > 0 && ( - { emblaApi?.scrollPrev() }} > - + )} {currentSlideIndex < media.length - 1 && ( - { emblaApi?.scrollNext() }} > - + )}
, children, diff --git a/apps/desktop/layer/renderer/src/components/ui/modal/components/base.tsx b/apps/desktop/layer/renderer/src/components/ui/modal/components/base.tsx deleted file mode 100644 index c7813fe60..000000000 --- a/apps/desktop/layer/renderer/src/components/ui/modal/components/base.tsx +++ /dev/null @@ -1,32 +0,0 @@ -import { Tooltip, TooltipContent, TooltipTrigger } from "@follow/components/ui/tooltip/index.js" -import { cn } from "@follow/utils/utils" -import type { ReactNode } from "react" - -export const PeekModalBaseButton = ({ - onClick, - className, - label, - icon, -}: { - onClick: () => void - className?: string - label: string - icon: ReactNode -}) => { - return ( - - - {icon} - - {label} - - ) -} diff --git a/apps/desktop/layer/renderer/src/components/ui/modal/components/close.tsx b/apps/desktop/layer/renderer/src/components/ui/modal/components/close.tsx index ca360199a..83f22b73d 100644 --- a/apps/desktop/layer/renderer/src/components/ui/modal/components/close.tsx +++ b/apps/desktop/layer/renderer/src/components/ui/modal/components/close.tsx @@ -1,6 +1,7 @@ +import { cn } from "@follow/utils" import { useTranslation } from "react-i18next" -import { PeekModalBaseButton } from "./base" +import { GlassButton } from "~/components/ui/button/GlassButton" export const FixedModalCloseButton: Component<{ onClick: () => void @@ -8,11 +9,17 @@ export const FixedModalCloseButton: Component<{ }> = ({ onClick, className }) => { const { t } = useTranslation("common") return ( - } - /> + className={cn( + "!border-red-500/20 !bg-red-600/30 !opacity-100 hover:!bg-red-600/50", + className, + )} + description={t("words.close")} + size="md" + variant="flat" + > + + ) } diff --git a/apps/desktop/layer/renderer/src/components/ui/modal/inspire/PeekModal.tsx b/apps/desktop/layer/renderer/src/components/ui/modal/inspire/PeekModal.tsx index 96e8d4766..7de5e05a4 100644 --- a/apps/desktop/layer/renderer/src/components/ui/modal/inspire/PeekModal.tsx +++ b/apps/desktop/layer/renderer/src/components/ui/modal/inspire/PeekModal.tsx @@ -5,8 +5,8 @@ import { useState } from "react" import { useTranslation } from "react-i18next" import { m } from "~/components/common/Motion" +import { GlassButton } from "~/components/ui/button/GlassButton" -import { PeekModalBaseButton } from "../components/base" import { FixedModalCloseButton } from "../components/close" import { useCurrentModal, useModalStack } from "../stacked/hooks" import { InPeekModal } from "./InPeekModal" @@ -49,23 +49,29 @@ export const PeekModal = ( className="safe-inset-top-4 fixed right-4 flex items-center gap-4" > {props.rightActions?.map((action) => ( - + description={action.label} + size="md" + variant="flat" + > + {action.icon} + ))} {!!to && ( - { dismissAll() getStableRouterNavigate()?.(to) }} - label={t("words.expand")} - icon={} - /> + description={t("words.expand")} + size="md" + variant="flat" + > + + )} diff --git a/apps/desktop/layer/renderer/src/components/ui/modal/stacked/hooks.tsx b/apps/desktop/layer/renderer/src/components/ui/modal/stacked/hooks.tsx index 5f905de8d..4af26e5bd 100644 --- a/apps/desktop/layer/renderer/src/components/ui/modal/stacked/hooks.tsx +++ b/apps/desktop/layer/renderer/src/components/ui/modal/stacked/hooks.tsx @@ -144,14 +144,14 @@ export const useDialog = (): DialogInstance => { confirmClassName: "", }, warning: { - icon: , + icon: , confirmVariant: "primary" as const, - confirmClassName: "bg-yellow-600 hover:bg-yellow-700", + confirmClassName: "bg-yellow-500", }, danger: { - icon: , + icon: , confirmVariant: "primary" as const, - confirmClassName: "bg-red-600 hover:bg-red-700", + confirmClassName: "bg-red-500", }, } diff --git a/apps/desktop/layer/renderer/src/constants/hotkeys.ts b/apps/desktop/layer/renderer/src/constants/hotkeys.ts index b32cacc26..85205667f 100644 --- a/apps/desktop/layer/renderer/src/constants/hotkeys.ts +++ b/apps/desktop/layer/renderer/src/constants/hotkeys.ts @@ -11,6 +11,7 @@ export enum HotkeyScope { EntryRender = "entry-render", SubscriptionList = "subscription-list", SubLayer = "sub-layer", + AIChat = "ai-chat", } export const FloatingLayerScope = [ diff --git a/apps/desktop/layer/renderer/src/hooks/biz/useEntryActions.tsx b/apps/desktop/layer/renderer/src/hooks/biz/useEntryActions.tsx index 0efcd6c04..4c1e89c6c 100644 --- a/apps/desktop/layer/renderer/src/hooks/biz/useEntryActions.tsx +++ b/apps/desktop/layer/renderer/src/hooks/biz/useEntryActions.tsx @@ -21,6 +21,8 @@ import { setReadabilityStatus, useEntryIsInReadability, } from "~/atoms/readability" +import { useServerConfigs } from "~/atoms/server-configs" +import { useAIChatPinned } from "~/atoms/settings/ai" import { useShowSourceContent } from "~/atoms/source-content" import { ipcServices } from "~/lib/client" import { COMMAND_ID } from "~/modules/command/commands/id" @@ -145,7 +147,18 @@ const entrySelector = (state: EntryModel) => { hasBitTorrent: attachments.some((a) => a.mime_type === "application/x-bittorrent"), } } - +export const HIDE_ACTIONS_IN_ENTRY_CONTEXT_MENU = [ + COMMAND_ID.entry.viewSourceContent, + COMMAND_ID.entry.toggleAISummary, + COMMAND_ID.entry.toggleAITranslation, + COMMAND_ID.global.toggleAIChatPinned, + COMMAND_ID.settings.customizeToolbar, + COMMAND_ID.entry.readability, + COMMAND_ID.entry.exportAsPDF, + // Copy + COMMAND_ID.entry.copyTitle, + COMMAND_ID.entry.copyLink, +] export const useEntryActions = ({ entryId, view, @@ -175,7 +188,8 @@ export const useEntryActions = ({ const isShowAISummaryOnce = useShowAISummaryOnce() const isShowAITranslationAuto = useShowAITranslationAuto(!!entry?.translation) const isShowAITranslationOnce = useShowAITranslationOnce() - + const isShowAIChatPinned = useAIChatPinned() + const aiEnabled = useServerConfigs()?.AI_CHAT_ENABLED const runCmdFn = useRunCommandFn() const hasEntry = !!entry @@ -363,6 +377,14 @@ export const useEntryActions = ({ notice: !entry.doesContentContainsHTMLTags && !isEntryInReadability, entryId, }), + + new EntryActionMenuItem({ + id: COMMAND_ID.global.toggleAIChatPinned, + onClick: runCmdFn(COMMAND_ID.global.toggleAIChatPinned, [{ entryId }]), + entryId, + active: isShowAIChatPinned, + hide: !aiEnabled, + }), new EntryActionMenuItem({ id: COMMAND_ID.settings.customizeToolbar, onClick: runCmdFn(COMMAND_ID.settings.customizeToolbar, []), @@ -405,6 +427,8 @@ export const useEntryActions = ({ isShowAITranslationOnce, compact, isEntryInReadability, + isShowAIChatPinned, + aiEnabled, ]) return actionConfigs diff --git a/apps/desktop/layer/renderer/src/hooks/biz/usePeekModal.tsx b/apps/desktop/layer/renderer/src/hooks/biz/usePeekModal.tsx new file mode 100644 index 000000000..895ba7482 --- /dev/null +++ b/apps/desktop/layer/renderer/src/hooks/biz/usePeekModal.tsx @@ -0,0 +1,286 @@ +import { Spring } from "@follow/components/constants/spring.js" +import { RootPortal } from "@follow/components/ui/portal/index.js" +import { useIsEntryStarred } from "@follow/store/collection/hooks" +import { useEntry, usePrefetchEntryDetail } from "@follow/store/entry/hooks" +import { useFeedById } from "@follow/store/feed/hooks" +import { nextFrame, stopPropagation } from "@follow/utils/dom" +import { cn } from "@follow/utils/utils" +import type { Variant } from "motion/react" +import { m, useAnimationControls } from "motion/react" +import type { FC } from "react" +import { useCallback, useEffect, useMemo } from "react" + +import { MenuItemText } from "~/atoms/context-menu" +import { RelativeTime } from "~/components/ui/datetime" +import { + DropdownMenu, + DropdownMenuContent, + DropdownMenuTrigger, +} from "~/components/ui/dropdown-menu/dropdown-menu" +import { usePreviewMedia } from "~/components/ui/media/hooks" +import { Media } from "~/components/ui/media/Media" +import { PeekModal } from "~/components/ui/modal/inspire/PeekModal" +import { PlainModal } from "~/components/ui/modal/stacked/custom-modal" +import { useModalStack } from "~/components/ui/modal/stacked/hooks" +import { Paper } from "~/components/ui/paper" +import { useSortedEntryActions } from "~/hooks/biz/useEntryActions" +import { getRouteParams } from "~/hooks/biz/useRouteParams" +import { COMMAND_ID } from "~/modules/command/commands/id" +import { hasCommand } from "~/modules/command/hooks/use-command" +import { StarIcon } from "~/modules/entry-column/star-icon" +import { CommandDropdownMenuItem } from "~/modules/entry-content/actions/more-actions" +import { EntryContent } from "~/modules/entry-content/components/entry-content" +import type { FeedIconEntry } from "~/modules/feed/feed-icon" +import { FeedIcon } from "~/modules/feed/feed-icon" + +export const usePeekModal = () => { + const { present } = useModalStack() + return useCallback( + (entryId: string, variant: "toast" | "modal") => { + const basePresentProps = { + clickOutsideToDismiss: true, + title: "Entry Preview", + } + + if (variant === "toast") { + present({ + ...basePresentProps, + CustomModalComponent: PlainModal, + content: () => , + overlay: false, + modal: false, + modalContainerClassName: "right-0 left-[auto]", + }) + } else { + present({ + ...basePresentProps, + autoFocus: false, + modalClassName: + "relative mx-auto mt-[10vh] scrollbar-none max-w-full overflow-auto px-2 lg:max-w-[65rem] lg:p-0", + + CustomModalComponent: ({ children }) => { + const feedId = useEntry(entryId, (state) => state.feedId) + if (!feedId) return null + + return ( + {}, + label: "More Actions", + icon: , + }, + ]} + to={`/timeline/view-${getRouteParams().view}/${feedId}/${entryId}`} + > + {children} + + ) + }, + content: () => , + overlay: true, + }) + } + }, + [present], + ) +} + +const variants: Record = { + enter: { + x: 0, + opacity: 1, + }, + initial: { + x: 700, + opacity: 0.9, + }, + exit: { + x: 750, + opacity: 0, + }, +} +const EntryToastPreview = ({ entryId }: { entryId: string }) => { + usePrefetchEntryDetail(entryId) + + const entry = useEntry(entryId, (state) => { + const { feedId } = state + const { author, authorAvatar, description, publishedAt } = state + + const media = state.media || [] + const firstPhotoUrl = media.find((a) => a.type === "photo")?.url + const iconEntry: FeedIconEntry = { + firstPhotoUrl, + authorAvatar, + } + + return { + author, + description, + feedId, + iconEntry, + media, + publishedAt, + } + }) + const isInCollection = useIsEntryStarred(entryId) + + const feed = useFeedById(entry?.feedId) + const controller = useAnimationControls() + + const isDisplay = !!entry && !!feed + useEffect(() => { + if (isDisplay) { + nextFrame(() => controller.start("enter")) + } + }, [controller, isDisplay]) + + const previewMedia = usePreviewMedia() + + if (!isDisplay) return null + + return ( + +
+ +
+
+ {entry.author} + · + + + +
+
+
+ {entry.description} + + {!!entry.media?.length && ( +
+ {entry.media.map((media, i, mediaList) => ( + { + e.stopPropagation() + previewMedia(mediaList, i) + }} + /> + ))} +
+ )} +
+ {isInCollection && } +
+ + {/* End right column */} +
+
+
+ ) +} + +const EntryModalPreview = ({ entryId }: { entryId: string }) => ( + + + +) + +const EntryMoreActions: FC<{ entryId: string }> = ({ entryId }) => { + const { view } = getRouteParams() + const { moreAction, mainAction } = useSortedEntryActions({ entryId, view }) + + const actionConfigs = useMemo( + () => + [...moreAction, ...mainAction].filter( + (action) => action instanceof MenuItemText && hasCommand(action.id), + ), + [moreAction, mainAction], + ) + + const availableActions = useMemo( + () => + actionConfigs.filter( + (item) => item instanceof MenuItemText && item.id !== COMMAND_ID.settings.customizeToolbar, + ), + [actionConfigs], + ) + + const extraAction = useMemo( + () => + actionConfigs.filter( + (item) => item instanceof MenuItemText && item.id === COMMAND_ID.settings.customizeToolbar, + ), + [actionConfigs], + ) + + if (availableActions.length === 0 && extraAction.length === 0) { + return null + } + + return ( + + + + + + + {availableActions.map((config) => + config instanceof MenuItemText ? ( + + ) : null, + )} + + + + ) +} diff --git a/apps/desktop/layer/renderer/src/modules/ai/AISpline.ts b/apps/desktop/layer/renderer/src/modules/ai/AISpline.ts new file mode 100644 index 000000000..f61ef232f --- /dev/null +++ b/apps/desktop/layer/renderer/src/modules/ai/AISpline.ts @@ -0,0 +1,14 @@ +import { createElement, lazy, Suspense } from "react" + +const AISplineLoader = lazy(() => + import("./AISplineLoader").then((res) => ({ default: res.AISplineLoader })), +) +export const AISpline = () => { + return createElement( + Suspense, + { + fallback: createElement("div", { className: "size-16 mx-auto" }), + }, + createElement(AISplineLoader), + ) +} diff --git a/apps/desktop/layer/renderer/src/modules/ai/AISplineLoader.tsx b/apps/desktop/layer/renderer/src/modules/ai/AISplineLoader.tsx new file mode 100644 index 000000000..0df88c5ef --- /dev/null +++ b/apps/desktop/layer/renderer/src/modules/ai/AISplineLoader.tsx @@ -0,0 +1,141 @@ +import Spline from "@splinetool/react-spline" +import { useCallback, useRef } from "react" + +const resolvedAIIconUrl = "https://cdn.follow.is/ai.splinecode" + +export const AISplineLoader = () => { + const containerRef = useRef(null) + const headRef = useRef(null) + const bodyRef = useRef(null) + + // Angle conversion function: degrees to radians + const degToRad = (degrees: number) => degrees * (Math.PI / 180) + + // Calculate the angle the head should look at + const calculateHeadRotation = useCallback( + (mouseX: number, mouseY: number, containerRect: DOMRect) => { + const containerCenterX = containerRect.left + containerRect.width / 2 + const containerCenterY = containerRect.top + containerRect.height / 2 + + // Calculate mouse position relative to container center (-1 to 1) + const relativeX = (mouseX - containerCenterX) / (window.innerWidth / 2) + const relativeY = (mouseY - containerCenterY) / (window.innerHeight / 2) + + // Clamp range + const clampedX = Math.max(-1, Math.min(1, relativeX)) + const clampedY = Math.max(-1, Math.min(1, relativeY)) + + // Calculate head rotation angle based on relative position + // Y-axis rotation (left-right): -70 to 70 degrees + const headRotationY = clampedX * 70 + + // X-axis rotation (up-down): -60 to 60 degrees + const headRotationX = clampedY * 60 + + return { + x: degToRad(headRotationX), + y: degToRad(headRotationY), + } + }, + [], + ) + + // Calculate body rotation angle (horizontal rotation only) + const calculateBodyRotation = useCallback((mouseX: number, containerRect: DOMRect) => { + const containerCenterX = containerRect.left + containerRect.width / 2 + + // Calculate mouse X position relative to container center (-1 to 1) + const relativeX = (mouseX - containerCenterX) / (window.innerWidth / 2) + const clampedX = Math.max(-1, Math.min(1, relativeX)) + + // Body Y-axis rotation: -30 to 30 degrees (smaller range than head rotation) + const bodyRotationY = clampedX * 30 + + return { + x: 0, // Body doesn't rotate up-down + y: degToRad(bodyRotationY), + } + }, []) + + const handleLoad = useCallback( + (app: any) => { + const head = app.findObjectByName("Head") + const body = app.findObjectByName("Body") + + if (!head || !body) { + console.warn("Cannot find Head or Body object") + return + } + + headRef.current = head + bodyRef.current = body + + const onMove = (e: MouseEvent) => { + if (!containerRef.current || !headRef.current || !bodyRef.current) return + + const containerRect = containerRef.current.getBoundingClientRect() + + // Calculate head rotation + const headRotation = calculateHeadRotation(e.clientX, e.clientY, containerRect) + headRef.current.rotation.x = headRotation.x + headRef.current.rotation.y = headRotation.y + + // Calculate body rotation + const bodyRotation = calculateBodyRotation(e.clientX, containerRect) + bodyRef.current.rotation.x = bodyRotation.x + bodyRef.current.rotation.y = bodyRotation.y + } + + // Reset to default position when mouse leaves + const onMouseLeave = () => { + if (!headRef.current || !bodyRef.current) return + + // Smooth transition back to default position + const resetAnimation = () => { + if (!headRef.current || !bodyRef.current) return + + const currentHeadX = headRef.current.rotation.x + const currentHeadY = headRef.current.rotation.y + const currentBodyY = bodyRef.current.rotation.y + + // Simple linear interpolation to smoothly return rotation to 0 + headRef.current.rotation.x = currentHeadX * 0.9 + headRef.current.rotation.y = currentHeadY * 0.9 + bodyRef.current.rotation.y = currentBodyY * 0.9 + + // Continue animation if not fully returned to 0 + if ( + Math.abs(currentHeadX) > 0.01 || + Math.abs(currentHeadY) > 0.01 || + Math.abs(currentBodyY) > 0.01 + ) { + requestAnimationFrame(resetAnimation) + } else { + // Complete reset to 0 + headRef.current.rotation.x = 0 + headRef.current.rotation.y = 0 + bodyRef.current.rotation.x = 0 + bodyRef.current.rotation.y = 0 + } + } + + resetAnimation() + } + + window.addEventListener("pointermove", onMove) + document.addEventListener("mouseleave", onMouseLeave) + + return () => { + window.removeEventListener("pointermove", onMove) + document.removeEventListener("mouseleave", onMouseLeave) + } + }, + [calculateHeadRotation, calculateBodyRotation], + ) + + return ( +
+ +
+ ) +} diff --git a/apps/desktop/layer/renderer/src/modules/ai/ai-daily/daily.tsx b/apps/desktop/layer/renderer/src/modules/ai/ai-daily/daily.tsx index c92c6048c..66cabc2ed 100644 --- a/apps/desktop/layer/renderer/src/modules/ai/ai-daily/daily.tsx +++ b/apps/desktop/layer/renderer/src/modules/ai/ai-daily/daily.tsx @@ -3,7 +3,6 @@ import { EmptyIcon } from "@follow/components/icons/empty.jsx" import { CollapseControlled } from "@follow/components/ui/collapse/Collapse.js" import type { LinkProps } from "@follow/components/ui/link/LinkWithTooltip.js" import { LoadingCircle } from "@follow/components/ui/loading/index.jsx" -import { RootPortal } from "@follow/components/ui/portal/index.js" import { ScrollArea } from "@follow/components/ui/scroll-area/index.js" import { Tooltip, @@ -11,47 +10,20 @@ import { TooltipPortal, TooltipTrigger, } from "@follow/components/ui/tooltip/index.jsx" -import { useIsEntryStarred } from "@follow/store/collection/hooks" -import { useEntry, usePrefetchEntryDetail } from "@follow/store/entry/hooks" -import { useFeedById } from "@follow/store/feed/hooks" -import { nextFrame, stopPropagation } from "@follow/utils/dom" import { cn, isBizId } from "@follow/utils/utils" import { noop } from "foxact/noop" import type { Components } from "hast-util-to-jsx-runtime" -import type { Variant } from "motion/react" -import { m, useAnimationControls } from "motion/react" -import type { FC } from "react" -import { useCallback, useEffect, useMemo, useState } from "react" +import { m } from "motion/react" +import { useMemo, useState } from "react" import { Trans, useTranslation } from "react-i18next" -import { MenuItemText } from "~/atoms/context-menu" import { useGeneralSettingSelector } from "~/atoms/settings/general" -import { RelativeTime } from "~/components/ui/datetime" -import { - DropdownMenu, - DropdownMenuContent, - DropdownMenuTrigger, -} from "~/components/ui/dropdown-menu/dropdown-menu" import { Markdown } from "~/components/ui/markdown/Markdown" import { MarkdownLink } from "~/components/ui/markdown/renderers" -import { usePreviewMedia } from "~/components/ui/media/hooks" -import { Media } from "~/components/ui/media/Media" -import { PeekModal } from "~/components/ui/modal/inspire/PeekModal" -import { PlainModal } from "~/components/ui/modal/stacked/custom-modal" -import { useModalStack } from "~/components/ui/modal/stacked/hooks" -import { Paper } from "~/components/ui/paper" -import { useSortedEntryActions } from "~/hooks/biz/useEntryActions" -import { getRouteParams } from "~/hooks/biz/useRouteParams" +import { usePeekModal } from "~/hooks/biz/usePeekModal" import { useAuthQuery } from "~/hooks/common" import { apiClient } from "~/lib/api-fetch" import { defineQuery } from "~/lib/defineQuery" -import { COMMAND_ID } from "~/modules/command/commands/id" -import { hasCommand } from "~/modules/command/hooks/use-command" -import { StarIcon } from "~/modules/entry-column/star-icon" -import { CommandDropdownMenuItem } from "~/modules/entry-content/actions/more-actions" -import { EntryContent } from "~/modules/entry-content/components/entry-content" -import type { FeedIconEntry } from "~/modules/feed/feed-icon" -import { FeedIcon } from "~/modules/feed/feed-icon" import { remarkSnowflakeId } from "./plugins/parse-snowflake" import type { DailyItemProps, DailyView } from "./types" @@ -297,258 +269,6 @@ const createRelatedEntryLink = (variant: "toast" | "modal") => (props: LinkProps ) } -const usePeekModal = () => { - const { present } = useModalStack() - return useCallback( - (entryId: string, variant: "toast" | "modal") => { - const basePresentProps = { - clickOutsideToDismiss: true, - title: "Entry Preview", - } - - if (variant === "toast") { - present({ - ...basePresentProps, - CustomModalComponent: PlainModal, - content: () => , - overlay: false, - modal: false, - modalContainerClassName: "right-0 left-[auto]", - }) - } else { - present({ - ...basePresentProps, - autoFocus: false, - modalClassName: - "relative mx-auto mt-[10vh] scrollbar-none max-w-full overflow-auto px-2 lg:max-w-[65rem] lg:p-0", - - CustomModalComponent: ({ children }) => { - const feedId = useEntry(entryId, (state) => state.feedId) - if (!feedId) return null - - return ( - {}, - label: "More Actions", - icon: , - }, - ]} - to={`/timeline/view-${getRouteParams().view}/${feedId}/${entryId}`} - > - {children} - - ) - }, - content: () => , - overlay: true, - }) - } - }, - [present], - ) -} -const EntryToastPreview = ({ entryId }: { entryId: string }) => { - usePrefetchEntryDetail(entryId) - - const variants: Record = { - enter: { - x: 0, - opacity: 1, - }, - initial: { - x: 700, - opacity: 0.9, - }, - exit: { - x: 750, - opacity: 0, - }, - } - - const entry = useEntry(entryId, (state) => { - const { feedId } = state - const { author, authorAvatar, description, publishedAt } = state - - const media = state.media || [] - const firstPhotoUrl = media.find((a) => a.type === "photo")?.url - const iconEntry: FeedIconEntry = { - firstPhotoUrl, - authorAvatar, - } - - return { - author, - description, - feedId, - iconEntry, - media, - publishedAt, - } - }) - const isInCollection = useIsEntryStarred(entryId) - - const feed = useFeedById(entry?.feedId) - const controller = useAnimationControls() - - const isDisplay = !!entry && !!feed - useEffect(() => { - if (isDisplay) { - nextFrame(() => controller.start("enter")) - } - }, [controller, isDisplay]) - - const previewMedia = usePreviewMedia() - - if (!isDisplay) return null - - return ( - -
- -
-
- {entry.author} - · - - - -
-
-
- {entry.description} - - {!!entry.media?.length && ( -
- {entry.media.map((media, i, mediaList) => ( - { - e.stopPropagation() - previewMedia(mediaList, i) - }} - /> - ))} -
- )} -
- {isInCollection && } -
- - {/* End right column */} -
-
-
- ) -} - -const EntryModalPreview = ({ entryId }: { entryId: string }) => ( - - - -) - -const EntryMoreActions: FC<{ entryId: string }> = ({ entryId }) => { - const { view } = getRouteParams() - const { moreAction, mainAction } = useSortedEntryActions({ entryId, view }) - - const actionConfigs = useMemo( - () => - [...moreAction, ...mainAction].filter( - (action) => action instanceof MenuItemText && hasCommand(action.id), - ), - [moreAction, mainAction], - ) - - const availableActions = useMemo( - () => - actionConfigs.filter( - (item) => item instanceof MenuItemText && item.id !== COMMAND_ID.settings.customizeToolbar, - ), - [actionConfigs], - ) - - const extraAction = useMemo( - () => - actionConfigs.filter( - (item) => item instanceof MenuItemText && item.id === COMMAND_ID.settings.customizeToolbar, - ), - [actionConfigs], - ) - - if (availableActions.length === 0 && extraAction.length === 0) { - return null - } - - return ( - - - - - - - {availableActions.map((config) => - config instanceof MenuItemText ? ( - - ) : null, - )} - - - - ) -} - interface SnowflakeIdProps { id: string children?: React.ReactNode diff --git a/apps/desktop/layer/renderer/src/modules/ai/chat/__internal__/AIChatContext.ts b/apps/desktop/layer/renderer/src/modules/ai/chat/__internal__/AIChatContext.ts new file mode 100644 index 000000000..43ad7d9eb --- /dev/null +++ b/apps/desktop/layer/renderer/src/modules/ai/chat/__internal__/AIChatContext.ts @@ -0,0 +1,50 @@ +import type { UIMessage, UseChatHelpers } from "@ai-sdk/react" +import type { UIDataTypes } from "ai" +import { createContext, use } from "react" +import type { StoreApi } from "zustand" +import type { UseBoundStoreWithEqualityFn } from "zustand/traditional" + +import type { AiChatContextStore } from "./store" +import type { BizUIMetadata, BizUITools } from "./types" + +export const AIChatContext = createContext< + UseChatHelpers> +>(null!) + +export type AIPanelRefs = { + panelRef: React.RefObject + inputRef: React.RefObject +} + +export const AIPanelRefsContext = createContext(null!) + +export const AIChatContextStoreContext = createContext< + UseBoundStoreWithEqualityFn> +>(null!) + +// Hook to access AI chat context information +export const useAIChatStore = () => { + const store = use(AIChatContextStoreContext) + if (!store && import.meta.env.DEV) { + throw new Error("useAIChatStore must be used within a AIChatContextStoreContext") + } + return store +} + +// Session methods context for managing chat session actions +export interface AIChatSessionMethods { + handleTitleGenerated: (title: string) => Promise + handleFirstMessage: () => Promise + handleNewChat: () => void + handleSwitchRoom: (roomId: string) => Promise +} + +export const AIChatSessionMethodsContext = createContext(null!) + +export const useAIChatSessionMethods = () => { + const context = use(AIChatSessionMethodsContext) + if (!context && import.meta.env.DEV) { + throw new Error("useAIChatSessionMethods must be used within a AIChatSessionMethodsContext") + } + return context +} diff --git a/apps/desktop/layer/renderer/src/modules/ai/chat/__internal__/store.ts b/apps/desktop/layer/renderer/src/modules/ai/chat/__internal__/store.ts new file mode 100644 index 000000000..d623edfbb --- /dev/null +++ b/apps/desktop/layer/renderer/src/modules/ai/chat/__internal__/store.ts @@ -0,0 +1,203 @@ +import { produce } from "immer" +import { nanoid } from "nanoid" +import { createWithEqualityFn } from "zustand/traditional" + +import type { AIChatContextBlock, AIChatContextInfo } from "./types" +import { blocksToContextInfo, contextInfoToBlocks } from "./utils" + +export interface AiChatContextStore { + state: AIChatContextInfo + blocks: AIChatContextBlock[] + // Block management methods + addBlock: (block: Omit) => void + removeBlock: (id: string) => void + updateBlock: (id: string, updates: Partial) => void + clearBlocks: () => void + // Context info management methods + setMainEntryId: (entryId?: string) => void + addReferEntryId: (entryId: string) => void + removeReferEntryId: (entryId: string) => void + addReferFeedId: (feedId: string) => void + removeReferFeedId: (feedId: string) => void + setSelectedText: (selectedText?: string) => void + // Legacy compatibility + setEntryId: (entryId?: string) => void + setFeedId: (feedId?: string) => void + reset: () => void + // Sync methods + syncBlocksToContext: () => void + syncContextToBlocks: () => void +} + +export const createAIChatContextStore = (initialState?: Partial) => { + const defaultState: AIChatContextInfo = { + mainEntryId: undefined, + referEntryIds: [], + referFeedIds: [], + selectedText: undefined, + } + + const defaultBlocks: AIChatContextBlock[] = [] + + const state: AIChatContextInfo = { + mainEntryId: initialState?.mainEntryId, + referEntryIds: initialState?.referEntryIds || [], + referFeedIds: initialState?.referFeedIds || [], + selectedText: initialState?.selectedText, + } + + return createWithEqualityFn((set, get) => ({ + state, + blocks: defaultBlocks, + + // Block management methods + addBlock: (block: Omit) => { + // Check for uniqueness constraints + const currentBlocks = get().blocks + + // Only allow one mainEntry + if (block.type === "mainEntry" && currentBlocks.some((b) => b.type === "mainEntry")) { + return + } + + // Only allow one selectedText + if (block.type === "selectedText" && currentBlocks.some((b) => b.type === "selectedText")) { + return + } + + // Prevent duplicate referEntry or referFeed + if ( + block.type === "referEntry" && + block.value && + currentBlocks.some((b) => b.type === "referEntry" && b.value === block.value) + ) { + return + } + + if ( + block.type === "referFeed" && + block.value && + currentBlocks.some((b) => b.type === "referFeed" && b.value === block.value) + ) { + return + } + + set( + produce((s) => { + s.blocks.push({ ...block, id: nanoid(8) }) + }), + ) + + // Sync to context info + get().syncBlocksToContext() + }, + + removeBlock: (id: string) => { + set( + produce((s: AiChatContextStore) => { + s.blocks = s.blocks.filter((block) => block.id !== id) + }), + ) + + // Sync to context info + get().syncBlocksToContext() + }, + + updateBlock: (id: string, updates: Partial) => { + set( + produce((s: AiChatContextStore) => { + s.blocks = s.blocks.map((block) => (block.id === id ? { ...block, ...updates } : block)) + }), + ) + + // Sync to context info + get().syncBlocksToContext() + }, + + clearBlocks: () => { + set( + produce((s: AiChatContextStore) => { + s.blocks = defaultBlocks + }), + ) + get().syncBlocksToContext() + }, + + // Context info management methods + setMainEntryId: (entryId?: string) => { + set((s) => ({ state: { ...s.state, mainEntryId: entryId } })) + get().syncContextToBlocks() + }, + + addReferEntryId: (entryId: string) => { + set((s) => ({ + state: { + ...s.state, + referEntryIds: [...(s.state.referEntryIds || []), entryId], + }, + })) + get().syncContextToBlocks() + }, + + removeReferEntryId: (entryId: string) => { + set((s) => ({ + state: { + ...s.state, + referEntryIds: (s.state.referEntryIds || []).filter((id) => id !== entryId), + }, + })) + get().syncContextToBlocks() + }, + + addReferFeedId: (feedId: string) => { + set((s) => ({ + state: { + ...s.state, + referFeedIds: [...(s.state.referFeedIds || []), feedId], + }, + })) + get().syncContextToBlocks() + }, + + removeReferFeedId: (feedId: string) => { + set((s) => ({ + state: { + ...s.state, + referFeedIds: (s.state.referFeedIds || []).filter((id) => id !== feedId), + }, + })) + get().syncContextToBlocks() + }, + + setSelectedText: (selectedText?: string) => { + set((s) => ({ state: { ...s.state, selectedText } })) + get().syncContextToBlocks() + }, + + // Legacy compatibility + setEntryId: (entryId?: string) => { + get().setMainEntryId(entryId) + }, + + setFeedId: (feedId?: string) => { + if (feedId) { + get().addReferFeedId(feedId) + } + }, + + reset: () => { + set(() => ({ state: defaultState, blocks: defaultBlocks })) + }, + + // Sync methods + syncBlocksToContext: () => { + const contextInfo = blocksToContextInfo(get().blocks) + set((s) => ({ state: { ...s.state, ...contextInfo } })) + }, + + syncContextToBlocks: () => { + const blocks = contextInfoToBlocks(get().state) + set(() => ({ blocks })) + }, + })) +} diff --git a/apps/desktop/layer/renderer/src/modules/ai/chat/__internal__/types.ts b/apps/desktop/layer/renderer/src/modules/ai/chat/__internal__/types.ts new file mode 100644 index 000000000..84c7fcb7a --- /dev/null +++ b/apps/desktop/layer/renderer/src/modules/ai/chat/__internal__/types.ts @@ -0,0 +1,52 @@ +import type { tools as honoTools } from "@follow/shared/hono" +import type { Tool, UIDataTypes, UIMessage } from "ai" + +export interface AIChatContextBlock { + id: string + type: "mainEntry" | "referEntry" | "referFeed" | "selectedText" + value: string +} + +export interface AIChatContextInfo { + mainEntryId?: string + referEntryIds?: string[] + referFeedIds?: string[] + selectedText?: string +} + +export interface AIChatContextBlocks { + blocks: AIChatContextBlock[] +} + +// TypeScript utility to transform Tool to { input: Input, output: Output } +type TransformTool = + T extends Tool + ? { + input: Input + output: Output + } + : never + +// Transform the tools object to UITools format +type TransformTools = { + [K in keyof T]: TransformTool +} + +// Apply the transformation to the hono tools +export type BizUITools = TransformTools + +export type BizUIMetadata = { + startTime?: string + finishTime?: string + totalTokens?: number + duration?: number +} + +export type BizUIMessage = UIMessage +type ToolWithState = T & { + state: "input-streaming" | "input-available" | "output-available" | "output-error" +} +export type AIDisplayAnalyticsTool = ToolWithState +export type AIDisplayFeedsTool = ToolWithState +export type AIDisplayEntriesTool = ToolWithState +export type AIDisplaySubscriptionsTool = ToolWithState diff --git a/apps/desktop/layer/renderer/src/modules/ai/chat/__internal__/utils.ts b/apps/desktop/layer/renderer/src/modules/ai/chat/__internal__/utils.ts new file mode 100644 index 000000000..3b4bb7e28 --- /dev/null +++ b/apps/desktop/layer/renderer/src/modules/ai/chat/__internal__/utils.ts @@ -0,0 +1,72 @@ +import type { AIChatContextBlock, AIChatContextInfo } from "./types" + +export const contextInfoToBlocks = (contextInfo: AIChatContextInfo): AIChatContextBlock[] => { + const blocks: AIChatContextBlock[] = [] + + // Main entry (single) + if (contextInfo.mainEntryId) { + blocks.push({ + id: `main-entry-${contextInfo.mainEntryId}`, + type: "mainEntry", + value: contextInfo.mainEntryId, + }) + } + + // Reference entries (multiple) + contextInfo.referEntryIds?.forEach((entryId) => { + blocks.push({ + id: `refer-entry-${entryId}`, + type: "referEntry", + value: entryId, + }) + }) + + // Reference feeds (multiple) + contextInfo.referFeedIds?.forEach((feedId) => { + blocks.push({ + id: `refer-feed-${feedId}`, + type: "referFeed", + value: feedId, + }) + }) + + // Selected text (single, auto-detected) + if (contextInfo.selectedText) { + blocks.push({ + id: "selected-text", + type: "selectedText", + value: contextInfo.selectedText, + }) + } + + return blocks +} + +export const blocksToContextInfo = (blocks: AIChatContextBlock[]): AIChatContextInfo => { + const contextInfo: AIChatContextInfo = {} + + blocks.forEach((block) => { + switch (block.type) { + case "mainEntry": { + contextInfo.mainEntryId = block.value + break + } + case "referEntry": { + if (!contextInfo.referEntryIds) contextInfo.referEntryIds = [] + contextInfo.referEntryIds.push(block.value) + break + } + case "referFeed": { + if (!contextInfo.referFeedIds) contextInfo.referFeedIds = [] + contextInfo.referFeedIds.push(block.value) + break + } + case "selectedText": { + contextInfo.selectedText = block.value + break + } + } + }) + + return contextInfo +} diff --git a/apps/desktop/layer/renderer/src/modules/ai/chat/atoms/session.ts b/apps/desktop/layer/renderer/src/modules/ai/chat/atoms/session.ts new file mode 100644 index 000000000..b7f3e9502 --- /dev/null +++ b/apps/desktop/layer/renderer/src/modules/ai/chat/atoms/session.ts @@ -0,0 +1,49 @@ +import { atom } from "jotai" +import { useCallback } from "react" + +import { createAtomHooks } from "~/lib/jotai" + +// Session state atoms with hooks +export const [, , useCurrentRoomId, useSetCurrentRoomId, , setCurrentRoomId] = createAtomHooks( + atom(null), +) + +export const [, , useCurrentTitle, useSetCurrentTitle, , setCurrentTitle] = + createAtomHooks(atom()) + +export const [, , useSessionPersisted, useSetSessionPersisted, , setSessionPersisted] = + createAtomHooks(atom(false)) + +// Edit state management for messages +export const [, , useEditingMessageId, useSetEditingMessageId, , setEditingMessageId] = + createAtomHooks(atom(null)) + +// Combined hook for all session state +export const useSessionState = () => { + return { + currentRoomId: useCurrentRoomId(), + currentTitle: useCurrentTitle(), + sessionPersisted: useSessionPersisted(), + editingMessageId: useEditingMessageId(), + } +} + +// Hook for session state setters +export const useSessionSetters = () => { + const setCurrentRoomIdAtom = useSetCurrentRoomId() + const setCurrentTitleAtom = useSetCurrentTitle() + const setSessionPersistedAtom = useSetSessionPersisted() + + return useCallback( + (updates: { + currentRoomId?: string | null + currentTitle?: string | undefined + sessionPersisted?: boolean + }) => { + if (updates.currentRoomId !== undefined) setCurrentRoomIdAtom(updates.currentRoomId) + if (updates.currentTitle !== undefined) setCurrentTitleAtom(updates.currentTitle) + if (updates.sessionPersisted !== undefined) setSessionPersistedAtom(updates.sessionPersisted) + }, + [setCurrentRoomIdAtom, setCurrentTitleAtom, setSessionPersistedAtom], + ) +} diff --git a/apps/desktop/layer/renderer/src/modules/ai/chat/components/AIChatContextBar.tsx b/apps/desktop/layer/renderer/src/modules/ai/chat/components/AIChatContextBar.tsx new file mode 100644 index 000000000..c5fd372cf --- /dev/null +++ b/apps/desktop/layer/renderer/src/modules/ai/chat/components/AIChatContextBar.tsx @@ -0,0 +1,439 @@ +import { useEntry, useEntryIdsByFeedId, useEntryIdsByView } from "@follow/store/entry/hooks" +import { useEntryStore } from "@follow/store/entry/store" +import { getFeedById } from "@follow/store/feed/getter" +import { useFeedById } from "@follow/store/feed/hooks" +import { useAllFeedSubscription } from "@follow/store/subscription/hooks" +import { stopPropagation } from "@follow/utils" +import { cn } from "@follow/utils/utils" +import Fuse from "fuse.js" +import type { FC } from "react" +import { memo, useMemo, useState } from "react" +import { useDebounceCallback } from "usehooks-ts" + +import { useAISettingValue } from "~/atoms/settings/ai" +import { + DropdownMenu, + DropdownMenuContent, + DropdownMenuItem, + DropdownMenuSeparator, + DropdownMenuSub, + DropdownMenuSubContent, + DropdownMenuSubTrigger, + DropdownMenuTrigger, +} from "~/components/ui/dropdown-menu/dropdown-menu" +import { useRouteParamsSelector } from "~/hooks/biz/useRouteParams" +import { useAIChatStore } from "~/modules/ai/chat/__internal__/AIChatContext" +import type { AIChatContextBlock } from "~/modules/ai/chat/__internal__/types" + +export const AIChatContextBar: Component<{ onSendShortcut?: (prompt: string) => void }> = memo( + ({ className, onSendShortcut }) => { + const blocks = useAIChatStore()((s) => s.blocks) + const { addBlock } = useAIChatStore()() + const { shortcuts } = useAISettingValue() + + // Filter enabled shortcuts + const enabledShortcuts = useMemo( + () => shortcuts.filter((shortcut) => shortcut.enabled), + [shortcuts], + ) + + const contextMenuContent = ( + + + + + Current Feed Entries + + + + addBlock({ + type: "referEntry", + value: entryId, + }) + } + /> + + + + + + + + Reference Entry + + + + addBlock({ + type: "referEntry", + value: entryId, + }) + } + /> + + + + + + Reference Feed + + + + addBlock({ + type: "referFeed", + value: feedId, + }) + } + /> + + + + ) + + const shortcutsMenuContent = ( + + {enabledShortcuts.length === 0 ? ( +
No shortcuts configured
+ ) : ( + enabledShortcuts.map((shortcut) => ( + onSendShortcut?.(shortcut.prompt)} + className="text-xs" + shortcut={shortcut.hotkey} + > +
+
+ + {shortcut.name} +
+
+
+ )) + )} +
+ ) + + return ( +
+ {/* Add Context Button */} + + + + + {contextMenuContent} + + + {/* AI Shortcuts Button */} + {enabledShortcuts.length > 0 && ( + + + + + {shortcutsMenuContent} + + )} + + {/* Context Blocks */} + {blocks.map((block) => ( + + ))} +
+ ) + }, +) +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.state.mainEntryId) + 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 { removeBlock } = useAIChatStore()() + + const getBlockIcon = () => { + switch (block.type) { + case "mainEntry": { + return "i-mgc-star-cute-fi" + } + case "referEntry": { + return "i-mgc-paper-cute-fi" + } + case "referFeed": { + return "i-mgc-rss-cute-fi" + } + case "selectedText": { + return "i-mgc-quill-pen-cute-re" + } + + default: { + return "i-mgc-paper-cute-fi" + } + } + } + + const getDisplayContent = () => { + switch (block.type) { + case "mainEntry": + case "referEntry": { + return + } + 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/AIChatRoot.tsx b/apps/desktop/layer/renderer/src/modules/ai/chat/components/AIChatRoot.tsx new file mode 100644 index 000000000..ffbc0fc59 --- /dev/null +++ b/apps/desktop/layer/renderer/src/modules/ai/chat/components/AIChatRoot.tsx @@ -0,0 +1,247 @@ +import { Chat, useChat } from "@ai-sdk/react" +import { env } from "@follow/shared/env.desktop" +import type { UIDataTypes, UIMessage } from "ai" +import { DefaultChatTransport } from "ai" +import type { FC, PropsWithChildren } from "react" +import { useCallback, useMemo, useRef } from "react" +import { toast } from "sonner" +import { useEventCallback } from "usehooks-ts" + +import { Focusable } from "~/components/common/Focusable" +import { HotkeyScope } from "~/constants" + +import type { AIChatSessionMethods, AIPanelRefs } from "../__internal__/AIChatContext" +import { + AIChatContext, + AIChatContextStoreContext, + AIChatSessionMethodsContext, + AIPanelRefsContext, +} from "../__internal__/AIChatContext" +import { createAIChatContextStore } from "../__internal__/store" +import type { BizUIMetadata, BizUITools } from "../__internal__/types" +import { + useCurrentRoomId, + useSessionPersisted, + useSetCurrentRoomId, + useSetCurrentTitle, + useSetSessionPersisted, +} from "../atoms/session" +import { useChatHistory } from "../hooks/useChatHistory" +import { AIPersistService } from "../services" +import { generateChatTitle } from "../utils/titleGeneration" + +interface AIChatRootProps extends PropsWithChildren { + wrapFocusable?: boolean + roomId?: string +} + +export const AIChatRoot: FC = ({ + children, + wrapFocusable = true, + roomId: externalRoomId, +}) => { + const currentRoomId = useCurrentRoomId() + const sessionPersisted = useSessionPersisted() + const setCurrentRoomId = useSetCurrentRoomId() + const setCurrentTitle = useSetCurrentTitle() + const setSessionPersisted = useSetSessionPersisted() + + const { createNewSession } = useChatHistory() + const useAiContextStore = useMemo(createAIChatContextStore, []) + + // Initialize room ID on mount + useMemo(() => { + if (!currentRoomId && !externalRoomId) { + const newRoomId = createNewSession(false) + setCurrentRoomId(newRoomId) + } else if (externalRoomId && externalRoomId !== currentRoomId) { + setCurrentRoomId(externalRoomId) + } + }, [currentRoomId, externalRoomId, createNewSession, setCurrentRoomId]) + + const handleTitleGenerated = useCallback( + async (title: string) => { + if (currentRoomId) { + try { + await AIPersistService.updateSessionTitle(currentRoomId, title) + setCurrentTitle(title) + } catch (error) { + console.error("Failed to update session title:", error) + } + } + }, + [currentRoomId, setCurrentTitle], + ) + + const handleFirstMessage = useCallback(async () => { + if (!sessionPersisted && currentRoomId) { + try { + await AIPersistService.createSession(currentRoomId, "New Chat") + setSessionPersisted(true) + } catch (error) { + console.error("Failed to persist session:", error) + } + } + }, [sessionPersisted, currentRoomId, setSessionPersisted]) + + // Handle AI response completion - this is where we generate title + const handleChatFinish = useEventCallback( + async (options: { message: UIMessage }) => { + const { message } = options + + // Only trigger title generation for assistant messages (AI responses) + if (message.role !== "assistant") return + + // Get current messages to check if this is the first AI response + + const allMessages = chatInstance.messages + + // Check if we have exactly 2 messages (1 user + 1 assistant = first exchange) + // Or if we have 2+ messages and this is the first assistant message + const assistantMessages = allMessages.filter((m) => m.role === "assistant") + const isFirstAIResponse = assistantMessages.length === 1 + + if (isFirstAIResponse && allMessages.length >= 2) { + try { + // Generate title using the first user message and first AI response + const firstExchange = allMessages.slice(0, 2) + + const title = await generateChatTitle(firstExchange) + + if (title) { + await handleTitleGenerated(title) + } + } catch (error) { + console.error("Failed to generate chat title:", error) + } + } + }, + ) + const chatInstance = useMemo(() => { + return new Chat>({ + // FIXME: this id can't modify after init, so used a fixed id + id: "ai-room", + transport: new DefaultChatTransport({ + api: `${env.VITE_API_URL}/ai/chat`, + credentials: "include", + fetch: (url: string | Request | URL, options?: RequestInit) => { + if (!options?.body) return fetch(url, options) + try { + const state = useAiContextStore.getState() + state.syncBlocksToContext() + + options.body = JSON.stringify({ + ...JSON.parse(options.body as string), + context: state.state, + blocks: state.blocks, + }) + } catch (error) { + console.error(error) + } + + return fetch(url, options) + }, + }), + onError: (error) => { + console.error(error) + }, + onFinish: handleChatFinish, + }) + }, [useAiContextStore, handleChatFinish]) + + const ctx = useChat>({ + chat: chatInstance, + }) + + const handleNewChat = useCallback(() => { + // Create a new session without persistence initially + const newRoomId = createNewSession(false) + setCurrentRoomId(newRoomId) + setSessionPersisted(false) + setCurrentTitle(undefined) + // Clear messages + ctx.setMessages([]) + }, [createNewSession, ctx, setCurrentRoomId, setSessionPersisted, setCurrentTitle]) + + const handleSwitchRoom = useCallback( + async (roomId: string) => { + try { + // First check if we need to save current messages + if (sessionPersisted && currentRoomId && ctx.messages.length > 0) { + // Messages are automatically saved by useSaveMessages hook + } + + // Clear current messages before switching + ctx.setMessages([]) + + // Switch to new room + setCurrentRoomId(roomId) + + // Load session info + const sessionData = await AIPersistService.getChatSessions() + const session = sessionData.find((s) => s.roomId === roomId) + + if (session) { + setCurrentTitle(session.title || "New Chat") + setSessionPersisted(true) + } else { + setCurrentTitle(undefined) + setSessionPersisted(false) + } + + // Messages will be loaded automatically by useLoadMessages in ChatInterface + } catch (error) { + console.error("Failed to switch room:", error) + toast.error("Failed to switch chat session") + } + }, + [sessionPersisted, currentRoomId, ctx, setCurrentRoomId, setCurrentTitle, setSessionPersisted], + ) + + const panelRef = useRef(null!) + const inputRef = useRef(null!) + const refsContext = useMemo(() => ({ panelRef, inputRef }), [panelRef, inputRef]) + + // Provide session methods through context + const sessionMethods = useMemo( + () => ({ + handleTitleGenerated, + handleFirstMessage, + handleNewChat, + handleSwitchRoom, + }), + [handleTitleGenerated, handleFirstMessage, handleNewChat, handleSwitchRoom], + ) + + if (!currentRoomId || !ctx) { + return ( +
+
+ + Initializing chat... +
+
+ ) + } + + const Element = ( + + + + + {children} + + + + + ) + + if (wrapFocusable) { + return ( + + {Element} + + ) + } + return Element +} diff --git a/apps/desktop/layer/renderer/src/modules/ai/chat/components/AIChatSendButton.tsx b/apps/desktop/layer/renderer/src/modules/ai/chat/components/AIChatSendButton.tsx new file mode 100644 index 000000000..a4a58b0f0 --- /dev/null +++ b/apps/desktop/layer/renderer/src/modules/ai/chat/components/AIChatSendButton.tsx @@ -0,0 +1,40 @@ +import { Button } from "@follow/components/ui/button/index.js" +import { cn } from "@follow/utils" +import type { FC } from "react" + +interface AIChatSendButtonProps { + onClick: () => void + disabled?: boolean + isProcessing?: boolean + className?: string + size?: "sm" | "md" +} + +export const AIChatSendButton: FC = ({ + onClick, + disabled = false, + isProcessing = false, + className, +}) => { + return ( + + ) +} diff --git a/apps/desktop/layer/renderer/src/modules/ai/chat/components/ChatInput.tsx b/apps/desktop/layer/renderer/src/modules/ai/chat/components/ChatInput.tsx new file mode 100644 index 000000000..1f6eb7dce --- /dev/null +++ b/apps/desktop/layer/renderer/src/modules/ai/chat/components/ChatInput.tsx @@ -0,0 +1,112 @@ +import { useInputComposition } from "@follow/hooks" +import { cn, stopPropagation } from "@follow/utils" +import type { VariantProps } from "class-variance-authority" +import { cva } from "class-variance-authority" +import { memo, use, useCallback, useState } from "react" + +import { AIChatContext, AIPanelRefsContext } from "~/modules/ai/chat/__internal__/AIChatContext" +import { AIChatContextBar } from "~/modules/ai/chat/components/AIChatContextBar" +import { AIChatSendButton } from "~/modules/ai/chat/components/AIChatSendButton" + +import { CollapsibleError } from "./CollapsibleError" + +const chatInputVariants = cva( + [ + "bg-background/60 focus-within:ring-accent/20 focus-within:border-accent/80 border-border/80", + "relative overflow-hidden rounded-2xl border backdrop-blur-xl duration-200 focus-within:ring-2", + ], + { + variants: { + variant: { + default: "shadow-2xl shadow-black/5 dark:shadow-zinc-800", + minimal: "shadow shadow-zinc-100 dark:shadow-black/5", + }, + }, + defaultVariants: { + variant: "default", + }, + }, +) + +interface ChatInputProps extends VariantProps { + onSend: (message: string) => void +} + +export const ChatInput = memo(({ onSend, variant }: ChatInputProps) => { + const { inputRef } = use(AIPanelRefsContext) + const { status, stop, error } = use(AIChatContext) + const [isEmpty, setIsEmpty] = useState(true) + + const isProcessing = status === "submitted" || status === "streaming" + + const handleSend = useCallback(() => { + if (inputRef.current && inputRef.current.value.trim()) { + const message = inputRef.current.value.trim() + onSend(message) + inputRef.current.value = "" + setIsEmpty(true) + } + }, [onSend, inputRef]) + const handleKeyPress = useCallback( + (e: React.KeyboardEvent) => { + if (e.key === "Enter" && !e.shiftKey) { + e.preventDefault() + if (isProcessing) { + stop?.() + } else { + handleSend() + } + } + }, + [handleSend, isProcessing, stop], + ) + const inputProps = useInputComposition({ + onKeyDown: handleKeyPress, + }) + + const handleChange = useCallback((e: React.ChangeEvent) => { + setIsEmpty(e.target.value.trim() === "") + }, []) + + return ( +
+ {/* Error Display */} + {error && } + + {/* Integrated Input Container with Context Bar */} +
+ {/* Input Area */} +
+