diff --git a/.github/workflows/build-android.yml b/.github/workflows/build-android.yml index 2bd681eed..8c57a33ac 100644 --- a/.github/workflows/build-android.yml +++ b/.github/workflows/build-android.yml @@ -33,7 +33,7 @@ jobs: steps: - name: 📦 Checkout code - uses: actions/checkout@v5 + uses: actions/checkout@v6 - name: 📦 Setup pnpm uses: pnpm/action-setup@v4 diff --git a/.github/workflows/build-desktop.yml b/.github/workflows/build-desktop.yml index 2ec5c5139..7d003eae3 100644 --- a/.github/workflows/build-desktop.yml +++ b/.github/workflows/build-desktop.yml @@ -56,13 +56,13 @@ jobs: steps: - name: Check out Git repository Fully - uses: actions/checkout@v5 + uses: actions/checkout@v6 if: env.PROD == 'true' with: fetch-depth: 0 lfs: true - name: Check out Git repository - uses: actions/checkout@v5 + uses: actions/checkout@v6 if: env.PROD == 'false' with: fetch-depth: 1 diff --git a/.github/workflows/build-ios-development.yml b/.github/workflows/build-ios-development.yml index 65990d6a8..4e7312010 100644 --- a/.github/workflows/build-ios-development.yml +++ b/.github/workflows/build-ios-development.yml @@ -40,7 +40,7 @@ jobs: steps: - name: 📦 Checkout code - uses: actions/checkout@v5 + uses: actions/checkout@v6 - name: 📱 Setup EAS uses: expo/expo-github-action@v8 @@ -78,7 +78,7 @@ jobs: steps: - name: 📦 Checkout code - uses: actions/checkout@v5 + uses: actions/checkout@v6 - name: 🔧 Setup Xcode uses: ./.github/actions/setup-xcode @@ -122,7 +122,7 @@ jobs: steps: - name: 📦 Checkout code - uses: actions/checkout@v5 + uses: actions/checkout@v6 - name: 🔧 Setup Xcode uses: ./.github/actions/setup-xcode diff --git a/.github/workflows/build-ios.yml b/.github/workflows/build-ios.yml index 764f78906..1683ec286 100644 --- a/.github/workflows/build-ios.yml +++ b/.github/workflows/build-ios.yml @@ -47,7 +47,7 @@ jobs: steps: - name: 📦 Checkout code - uses: actions/checkout@v5 + uses: actions/checkout@v6 - name: 📱 Setup EAS uses: expo/expo-github-action@v8 @@ -90,7 +90,7 @@ jobs: steps: - name: 📦 Checkout code - uses: actions/checkout@v5 + uses: actions/checkout@v6 - name: 🔧 Setup Xcode uses: ./.github/actions/setup-xcode diff --git a/.github/workflows/build-web.yml b/.github/workflows/build-web.yml index 1b61f8d94..322f88c70 100644 --- a/.github/workflows/build-web.yml +++ b/.github/workflows/build-web.yml @@ -17,7 +17,7 @@ jobs: node-version: [lts/*] steps: - name: Checkout code - uses: actions/checkout@v5 + uses: actions/checkout@v6 with: lfs: true - name: Cache turbo build setup diff --git a/.github/workflows/issue-labeler.yml b/.github/workflows/issue-labeler.yml index 25450cbd9..ceaf0d184 100644 --- a/.github/workflows/issue-labeler.yml +++ b/.github/workflows/issue-labeler.yml @@ -19,7 +19,7 @@ jobs: contents: read steps: - - uses: actions/checkout@v5 + - uses: actions/checkout@v6 - name: Parse issue form uses: stefanbuck/github-issue-parser@v3 diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml index 20ed03eea..9f5b8ac68 100644 --- a/.github/workflows/lint.yml +++ b/.github/workflows/lint.yml @@ -22,7 +22,7 @@ jobs: node-version: [lts/*] steps: - name: Checkout code - uses: actions/checkout@v5 + uses: actions/checkout@v6 with: lfs: true - name: Cache turbo build setup diff --git a/.github/workflows/similar-issues.yml b/.github/workflows/similar-issues.yml index d7b60f318..b6bd67673 100644 --- a/.github/workflows/similar-issues.yml +++ b/.github/workflows/similar-issues.yml @@ -13,7 +13,7 @@ jobs: runs-on: ubuntu-latest steps: - name: Check out repository - uses: actions/checkout@v5 + uses: actions/checkout@v6 - name: Prepare prompt variables id: prepare_input diff --git a/.github/workflows/sync.yaml b/.github/workflows/sync.yaml index 983e179d9..ee0f9e36c 100644 --- a/.github/workflows/sync.yaml +++ b/.github/workflows/sync.yaml @@ -10,7 +10,7 @@ jobs: runs-on: ubuntu-latest steps: - name: Checkout repository - uses: actions/checkout@v5 + uses: actions/checkout@v6 with: fetch-depth: 0 diff --git a/.github/workflows/tag.yml b/.github/workflows/tag.yml index 99a62cc22..13da44f27 100644 --- a/.github/workflows/tag.yml +++ b/.github/workflows/tag.yml @@ -16,7 +16,7 @@ jobs: steps: - name: Checkout repository - uses: actions/checkout@v5 + uses: actions/checkout@v6 - name: Setup Node.js uses: actions/setup-node@v6 diff --git a/.github/workflows/translator.yml b/.github/workflows/translator.yml index c10438f96..dea91e207 100644 --- a/.github/workflows/translator.yml +++ b/.github/workflows/translator.yml @@ -17,7 +17,7 @@ jobs: pull-requests: write runs-on: ubuntu-latest steps: - - uses: actions/checkout@v5 + - uses: actions/checkout@v6 - uses: lizheming/github-translate-action@c55aac477e98562d4faed9f77c54ab8306ae6ebf env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 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 10ca607e7..f3f1b1a5f 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 @@ -171,7 +171,7 @@ const DropdownMenuItem = ({ ref={ref} className={cn( "relative flex cursor-menu select-none items-center rounded-[5px] px-2.5 py-1 outline-none focus:bg-accent/30 data-[disabled]:pointer-events-none data-[disabled]:opacity-50", - "focus-within:outline-transparent data-[highlighted]:bg-mix-background/accent-5/1", + "focus-within:outline-transparent data-[highlighted]:text-accent data-[highlighted]:bg-mix-background/accent-9/1", "h-[28px]", inset && "pl-8", className, diff --git a/apps/desktop/layer/renderer/src/initialize/analytics.ts b/apps/desktop/layer/renderer/src/initialize/analytics.ts index 6275eebee..d1c4d7c1d 100644 --- a/apps/desktop/layer/renderer/src/initialize/analytics.ts +++ b/apps/desktop/layer/renderer/src/initialize/analytics.ts @@ -1,5 +1,6 @@ import { env } from "@follow/shared/env.desktop" import { setFirebaseTracker, setPostHogTracker, tracker } from "@follow/tracker" +import { captureAttributionFromURL, getAttributionForAnalytics } from "@follow/utils" import type { AuthSessionResponse } from "@follow-app/client-sdk" import posthog from "posthog-js" @@ -8,11 +9,18 @@ import { QUERY_PERSIST_KEY } from "~/constants/app" import { ga4 } from "../lib/ga4" export const initAnalytics = async () => { + // Capture attribution data from URL (preserves first attribution) + captureAttributionFromURL() + + // Get attribution data for analytics + const attributionData = getAttributionForAnalytics() + tracker.manager.appendUserProperties({ build: ELECTRON ? "electron" : "web", version: APP_VERSION, hash: GIT_COMMIT_SHA, language: navigator.language, + ...attributionData, }) setFirebaseTracker(ga4) diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/parse-incomplete-markdown.ts b/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/parse-incomplete-markdown.ts index 44d7c1876..3216b9b80 100644 --- a/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/parse-incomplete-markdown.ts +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/parse-incomplete-markdown.ts @@ -1,6 +1,5 @@ // @copy https://github.com/vercel/streamdown/blob/main/packages/streamdown/lib/parse-incomplete-markdown.ts /* eslint-disable unicorn/prefer-string-slice */ -const linkImagePattern = /(!?\[)([^\]]*)$/ const boldPattern = /(\*\*)([^*]*)$/ const italicPattern = /(__)([^_]*)$/ const boldItalicPattern = /(\*\*\*)([^*]*)$/ @@ -8,156 +7,31 @@ const singleAsteriskPattern = /(\*)([^*]*)$/ const singleUnderscorePattern = /(_)([^_]*)$/ const inlineCodePattern = /(`)([^`]*)$/ const strikethroughPattern = /(~~)([^~]*)$/ +const whitespaceOrMarkersPattern = /^[\s_~*`]*$/ +const listItemPattern = /^\s*[-*+]\s+$/ +const letterNumberUnderscorePattern = /[\p{L}\p{N}_]/u +const inlineTripleBacktickPattern = /^```[^`\n]*```?$/ +const fourOrMoreAsterisksPattern = /^\*{4,}$/ -// Detect custom inline reference tags -const mentionTagStartPattern = /<\s*mention-(?:entry|feed)\b/gi -const mentionTagCompletePattern = /^<\s*(mention-(?:entry|feed))/i - -// Finds the end index of a mention tag (self-closing or paired) starting at `startIndex`. -// Returns the index of the closing `>` when found outside of quotes; otherwise -1. -const findMentionTagEnd = (text: string, startIndex: number): number => { - // Don't process if inside a complete code block - if (hasCompleteCodeBlock(text)) return -1 - - let inQuote: '"' | "'" | null = null - let openingTagEnd = -1 - for (let i = startIndex; i < text.length; i++) { - const char = text[i] - if (inQuote) { - if (char === inQuote && text[i - 1] !== "\\") { - inQuote = null - } - continue - } - if (char === '"' || char === "'") { - inQuote = char - continue - } - if (char === "/" && text[i + 1] === ">") { - return i + 1 // index of '>' in `/>` - } - if (char === ">") { - openingTagEnd = i - break - } +// OPTIMIZATION: Precompute which characters are word characters +// Using ASCII fast path before falling back to Unicode regex +const isWordChar = (char: string): boolean => { + if (!char) { + return false } - - if (openingTagEnd === -1) { - return -1 + // eslint-disable-next-line unicorn/prefer-code-point + const code = char.charCodeAt(0) + // ASCII optimization: a-z, A-Z, 0-9, _ + if ( + (code >= 48 && code <= 57) || // 0-9 + (code >= 65 && code <= 90) || // A-Z + (code >= 97 && code <= 122) || // a-z + code === 95 // _ + ) { + return true } - - const openingTag = text.substring(startIndex, openingTagEnd + 1) - const tagNameMatch = openingTag.match(mentionTagCompletePattern) - if (!tagNameMatch) { - return -1 - } - - // If the tag is already self-closing (allow whitespace before `/`) - if (/\/\s*>$/.test(openingTag)) { - return openingTagEnd - } - - const tagName = (tagNameMatch[1] ?? "").toLowerCase() - if (!tagName) { - return -1 - } - const afterOpening = text.substring(openingTagEnd + 1) - const closingTagPattern = new RegExp(`<\\s*/\\s*${tagName}\\s*>`, "i") - const closingMatch = closingTagPattern.exec(afterOpening) - - if (!closingMatch) { - return -1 - } - - return openingTagEnd + 1 + closingMatch.index + closingMatch[0].length - 1 -} - -// Trims trailing, incomplete `` or `` tags to avoid -// injecting broken raw HTML into markdown while streaming. -const handleIncompleteMentionTags = (text: string): string => { - // Don't process if inside a complete code block - if (hasCompleteCodeBlock(text)) { - return text - } - - let cutIndex: number | null = null - let match: RegExpExecArray | null - mentionTagStartPattern.lastIndex = 0 - while ((match = mentionTagStartPattern.exec(text))) { - const start = match.index - const end = findMentionTagEnd(text, start) - if (end === -1) { - cutIndex = start - break - } else { - // continue scanning after this complete tag - mentionTagStartPattern.lastIndex = end + 1 - } - } - - if (cutIndex !== null) { - const nextNewlineIndex = text.indexOf("\n", cutIndex) - if (nextNewlineIndex !== -1) { - // Remove only the incomplete tag segment and preserve following lines - return text.substring(0, cutIndex) + text.substring(nextNewlineIndex) - } - // No newline after the incomplete tag; drop the trailing incomplete segment - return text.substring(0, cutIndex) - } - return text -} - -// Handles `` wrappers that contain mention tags (self-closing or paired) by: -// - Replacing the whole wrapper with only the inner `` when complete -// - Trimming from ` { - // Don't process if inside a complete code block - if (hasCompleteCodeBlock(text)) return text - - const usePattern = /<\s*Use:\s*/gi - let result = text - let match: RegExpExecArray | null - usePattern.lastIndex = 0 - - // We rebuild iteratively in case of multiple occurrences - while ((match = usePattern.exec(result))) { - const useStart = match.index - const mentionStart = result.indexOf("` with `` - const before = result.substring(0, useStart) - const mentionTag = result.substring(mentionStart, mentionEnd + 1) - const after = result.substring(mentionEnd + 1) - result = before + mentionTag + after - - // Reset the regex lastIndex to continue scanning after the replaced tag - usePattern.lastIndex = before.length + mentionTag.length - } - - return result + // Fallback to regex for Unicode characters (less common) + return letterNumberUnderscorePattern.test(char) } // Helper function to check if we have a complete code block @@ -166,28 +40,143 @@ const hasCompleteCodeBlock = (text: string): boolean => { return tripleBackticks > 0 && tripleBackticks % 2 === 0 && text.includes("\n") } -// Handles incomplete links and images by preserving them with a special marker -const handleIncompleteLinksAndImages = (text: string): string => { - const linkMatch = text.match(linkImagePattern) +// Helper function to find the matching opening bracket for a closing bracket +// Handles nested brackets correctly by searching backwards +const findMatchingOpeningBracket = (text: string, closeIndex: number): number => { + let depth = 1 + for (let i = closeIndex - 1; i >= 0; i -= 1) { + if (text[i] === "]") { + depth += 1 + } else if (text[i] === "[") { + depth -= 1 + if (depth === 0) { + return i + } + } + } + return -1 // No matching bracket found +} - if (linkMatch) { - const isImage = linkMatch[1]?.startsWith("!") +// Helper function to find the matching closing bracket for an opening bracket +// Handles nested brackets correctly +const findMatchingClosingBracket = (text: string, openIndex: number): number => { + let depth = 1 + for (let i = openIndex + 1; i < text.length; i += 1) { + if (text[i] === "[") { + depth += 1 + } else if (text[i] === "]") { + depth -= 1 + if (depth === 0) { + return i + } + } + } + return -1 // No matching bracket found +} - // For images, we still remove them as they can't show skeleton - if (isImage) { - const startIndex = text.lastIndexOf(linkMatch[1]!) - return text.substring(0, startIndex) +// Check if a position is inside a code block (between ``` or `) +const isInsideCodeBlock = (text: string, position: number): boolean => { + // Check for inline code (backticks) + let inInlineCode = false + let inMultilineCode = false + + for (let i = 0; i < position; i += 1) { + // Check for triple backticks (multiline code blocks) + if (text.substring(i, i + 3) === "```") { + inMultilineCode = !inMultilineCode + i += 2 // Skip the next 2 backticks + continue } - // For links, preserve the text and close the link with a - // special placeholder URL that indicates it's incomplete - return `${text}](streamdown:incomplete-link)` + // Only check for inline code if not in multiline code + if (!inMultilineCode && text[i] === "`") { + inInlineCode = !inInlineCode + } + } + + return inInlineCode || inMultilineCode +} + +// Handles incomplete links and images by preserving them with a special marker +const handleIncompleteLinksAndImages = (text: string): string => { + // Look for patterns like [text]( or ![text]( at the end of text + // We need to handle nested brackets in the link text + + // Start from the end and look for ]( pattern + const lastParenIndex = text.lastIndexOf("](") + if (lastParenIndex !== -1 && !isInsideCodeBlock(text, lastParenIndex)) { + // Check if this ]( is not followed by a closing ) + const afterParen = text.substring(lastParenIndex + 2) + if (!afterParen.includes(")")) { + // We have an incomplete URL like [text](partial-url + // Now find the matching opening bracket for the ] before ( + const openBracketIndex = findMatchingOpeningBracket(text, lastParenIndex) + + if (openBracketIndex !== -1 && !isInsideCodeBlock(text, openBracketIndex)) { + // Check if there's a ! before the [ + const isImage = openBracketIndex > 0 && text[openBracketIndex - 1] === "!" + const startIndex = isImage ? openBracketIndex - 1 : openBracketIndex + + // Extract everything before this link/image + const beforeLink = text.substring(0, startIndex) + const linkText = text.substring(openBracketIndex + 1, lastParenIndex) + + if (isImage) { + // For images with incomplete URLs, remove them entirely + return beforeLink + } + + // For links with incomplete URLs, replace the URL with placeholder and close it + return `${beforeLink}[${linkText}](streamdown:incomplete-link)` + } + } + } + + // Then check for incomplete link text: [partial-text without closing ] + // Search backwards for an opening bracket that doesn't have a matching closing bracket + for (let i = text.length - 1; i >= 0; i -= 1) { + if (text[i] === "[" && !isInsideCodeBlock(text, i)) { + // Check if there's a ! before it + const isImage = i > 0 && text[i - 1] === "!" + const openIndex = isImage ? i - 1 : i + + // Check if we have a closing bracket after this + const afterOpen = text.substring(i + 1) + if (!afterOpen.includes("]")) { + // This is an incomplete link/image + const beforeLink = text.substring(0, openIndex) + + if (isImage) { + // For images, we remove them as they can't show skeleton + return beforeLink + } + + // For links, preserve the text and close the link with a + // special placeholder URL that indicates it's incomplete + return `${text}](streamdown:incomplete-link)` + } + + // If we found a closing bracket, we need to check if it's the matching one + // (accounting for nested brackets) + const closingIndex = findMatchingClosingBracket(text, i) + if (closingIndex === -1) { + // No matching closing bracket + const beforeLink = text.substring(0, openIndex) + + if (isImage) { + return beforeLink + } + + return `${text}](streamdown:incomplete-link)` + } + } } return text } // Completes incomplete bold formatting (**) +// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: "Complex markdown parsing logic with multiple edge cases" const handleIncompleteBold = (text: string): string => { // Don't process if inside a complete code block if (hasCompleteCodeBlock(text)) { @@ -201,7 +190,7 @@ const handleIncompleteBold = (text: string): string => { // boldMatch[2] contains the content after ** // Check if content is only whitespace or other emphasis markers const contentAfterMarker = boldMatch[2] - if (!contentAfterMarker || /^[\s_~*`]*$/.test(contentAfterMarker)) { + if (!contentAfterMarker || whitespaceOrMarkersPattern.test(contentAfterMarker)) { return text } @@ -214,7 +203,7 @@ const handleIncompleteBold = (text: string): string => { const lineBeforeMarker = text.substring(lineStart, markerIndex) // Check if this line is a list item with just the bold marker - if (/^\s*[-*+]\s+$/.test(lineBeforeMarker)) { + if (listItemPattern.test(lineBeforeMarker)) { // This is a list item with just emphasis markers // Check if content after marker spans multiple lines const hasNewlineInContent = contentAfterMarker.includes("\n") @@ -234,6 +223,7 @@ const handleIncompleteBold = (text: string): string => { } // Completes incomplete italic formatting with double underscores (__) +// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: "Complex markdown parsing logic with multiple edge cases" const handleIncompleteDoubleUnderscoreItalic = (text: string): string => { const italicMatch = text.match(italicPattern) @@ -242,7 +232,7 @@ const handleIncompleteDoubleUnderscoreItalic = (text: string): string => { // italicMatch[2] contains the content after __ // Check if content is only whitespace or other emphasis markers const contentAfterMarker = italicMatch[2] - if (!contentAfterMarker || /^[\s_~*`]*$/.test(contentAfterMarker)) { + if (!contentAfterMarker || whitespaceOrMarkersPattern.test(contentAfterMarker)) { return text } @@ -255,7 +245,7 @@ const handleIncompleteDoubleUnderscoreItalic = (text: string): string => { const lineBeforeMarker = text.substring(lineStart, markerIndex) // Check if this line is a list item with just the underscore marker - if (/^\s*[-*+]\s+$/.test(lineBeforeMarker)) { + if (listItemPattern.test(lineBeforeMarker)) { // This is a list item with just emphasis markers // Check if content after marker spans multiple lines const hasNewlineInContent = contentAfterMarker.includes("\n") @@ -274,44 +264,67 @@ const handleIncompleteDoubleUnderscoreItalic = (text: string): string => { return text } -// Counts single asterisks that are not part of double asterisks, not escaped, and not list markers +// OPTIMIZATION: Counts single asterisks without split("").reduce() +// Counts single asterisks that are not part of double asterisks, not escaped, not list markers, and not word-internal +// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: "Complex character counting logic with multiple edge cases" const countSingleAsterisks = (text: string): number => { - return text.split("").reduce((acc, char, index) => { - if (char === "*") { - const prevChar = text[index - 1] - const nextChar = text[index + 1] - // Skip if escaped with backslash - if (prevChar === "\\") { - return acc - } - // Check if this is a list marker (asterisk at start of line followed by space) - // Look backwards to find the start of the current line - let lineStartIndex = index - for (let i = index - 1; i >= 0; i--) { - if (text[i] === "\n") { - lineStartIndex = i + 1 - break - } - if (i === 0) { - lineStartIndex = 0 - break - } - } - // Check if this asterisk is at the beginning of a line (with optional whitespace) - const beforeAsterisk = text.substring(lineStartIndex, index) - if (beforeAsterisk.trim() === "" && (nextChar === " " || nextChar === "\t")) { - // This is likely a list marker, don't count it - return acc - } - if (prevChar !== "*" && nextChar !== "*") { - return acc + 1 + let count = 0 + const len = text.length + + for (let index = 0; index < len; index += 1) { + if (text[index] !== "*") { + continue + } + + const prevChar = index > 0 ? text[index - 1] : "" + const nextChar = index < len - 1 ? text[index + 1] : "" + + // Skip if escaped with backslash + if (prevChar === "\\") { + continue + } + + // Skip if part of ** or *** + if (prevChar === "*" || nextChar === "*") { + continue + } + + // Skip if asterisk is word-internal (between word characters) + if (prevChar && nextChar && isWordChar(prevChar) && isWordChar(nextChar)) { + continue + } + + // Check if this is a list marker (asterisk at start of line followed by space) + // Look backwards to find the start of the current line + let lineStartIndex = 0 + for (let i = index - 1; i >= 0; i -= 1) { + if (text[i] === "\n") { + lineStartIndex = i + 1 + break } } - return acc - }, 0) + + // Check if this asterisk is at the beginning of a line (with optional whitespace) + let isListMarker = true + for (let i = lineStartIndex; i < index; i += 1) { + if (text[i] !== " " && text[i] !== "\t") { + isListMarker = false + break + } + } + + if (isListMarker && (nextChar === " " || nextChar === "\t")) { + continue + } + + count += 1 + } + + return count } // Completes incomplete italic formatting with single asterisks (*) +// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: "Complex italic handling logic with multiple edge cases for markdown parsing" const handleIncompleteSingleAsteriskItalic = (text: string): string => { // Don't process if inside a complete code block if (hasCompleteCodeBlock(text)) { @@ -321,10 +334,17 @@ const handleIncompleteSingleAsteriskItalic = (text: string): string => { const singleAsteriskMatch = text.match(singleAsteriskPattern) if (singleAsteriskMatch) { - // Find the first single asterisk position (not part of **) + // Find the first single asterisk position (not part of ** and not word-internal) let firstSingleAsteriskIndex = -1 - for (let i = 0; i < text.length; i++) { - if (text[i] === "*" && text[i - 1] !== "*" && text[i + 1] !== "*") { + for (let i = 0; i < text.length; i += 1) { + if (text[i] === "*" && text[i - 1] !== "*" && text[i + 1] !== "*" && text[i - 1] !== "\\") { + // Check if asterisk is word-internal (between word characters) + const prevChar = i > 0 ? text[i - 1] : "" + const nextChar = i < text.length - 1 ? text[i + 1] : "" + if (prevChar && nextChar && isWordChar(prevChar) && isWordChar(nextChar)) { + continue + } + firstSingleAsteriskIndex = i break } @@ -339,7 +359,7 @@ const handleIncompleteSingleAsteriskItalic = (text: string): string => { // Check if there's meaningful content after the asterisk // Don't close if content is only whitespace or emphasis markers - if (!contentAfterFirstAsterisk || /^[\s_~*`]*$/.test(contentAfterFirstAsterisk)) { + if (!contentAfterFirstAsterisk || whitespaceOrMarkersPattern.test(contentAfterFirstAsterisk)) { return text } @@ -358,10 +378,10 @@ const isWithinMathBlock = (text: string, position: number): boolean => { let inInlineMath = false let inBlockMath = false - for (let i = 0; i < text.length && i < position; i++) { + for (let i = 0; i < text.length && i < position; i += 1) { // Skip escaped dollar signs if (text[i] === "\\" && text[i + 1] === "$") { - i++ // Skip the next character + i += 1 // Skip the next character continue } @@ -369,7 +389,7 @@ const isWithinMathBlock = (text: string, position: number): boolean => { // Check for block math ($$) if (text[i + 1] === "$") { inBlockMath = !inBlockMath - i++ // Skip the second $ + i += 1 // Skip the second $ inInlineMath = false // Block math takes precedence } else if (!inBlockMath) { // Only toggle inline math if not in block math @@ -381,38 +401,52 @@ const isWithinMathBlock = (text: string, position: number): boolean => { return inInlineMath || inBlockMath } +// OPTIMIZATION: Counts single underscores without split("").reduce() // Counts single underscores that are not part of double underscores, not escaped, and not in math blocks +// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: "Complex character counting logic with multiple edge cases" const countSingleUnderscores = (text: string): number => { - return text.split("").reduce((acc, char, index) => { - if (char === "_") { - const prevChar = text[index - 1] - const nextChar = text[index + 1] - // Skip if escaped with backslash - if (prevChar === "\\") { - return acc - } - // Skip if within math block - if (isWithinMathBlock(text, index)) { - return acc - } - // Skip if underscore is word-internal (between word characters) - if ( - prevChar && - nextChar && - /[\p{L}\p{N}_]/u.test(prevChar) && - /[\p{L}\p{N}_]/u.test(nextChar) - ) { - return acc - } - if (prevChar !== "_" && nextChar !== "_") { - return acc + 1 - } + // OPTIMIZATION: For large texts, if there are no dollar signs, skip math block checking entirely + const hasMathBlocks = text.includes("$") + + let count = 0 + const len = text.length + + for (let index = 0; index < len; index += 1) { + if (text[index] !== "_") { + continue } - return acc - }, 0) + + const prevChar = index > 0 ? text[index - 1] : "" + const nextChar = index < len - 1 ? text[index + 1] : "" + + // Skip if escaped with backslash + if (prevChar === "\\") { + continue + } + + // Skip if within math block (only check if text has dollar signs) + if (hasMathBlocks && isWithinMathBlock(text, index)) { + continue + } + + // Skip if part of __ + if (prevChar === "_" || nextChar === "_") { + continue + } + + // Skip if underscore is word-internal (between word characters) + if (prevChar && nextChar && isWordChar(prevChar) && isWordChar(nextChar)) { + continue + } + + count += 1 + } + + return count } // Completes incomplete italic formatting with single underscores (_) +// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: "Complex italic handling logic with multiple edge cases for markdown parsing" const handleIncompleteSingleUnderscoreItalic = (text: string): string => { // Don't process if inside a complete code block if (hasCompleteCodeBlock(text)) { @@ -424,7 +458,7 @@ const handleIncompleteSingleUnderscoreItalic = (text: string): string => { if (singleUnderscoreMatch) { // Find the first single underscore position (not part of __ and not word-internal) let firstSingleUnderscoreIndex = -1 - for (let i = 0; i < text.length; i++) { + for (let i = 0; i < text.length; i += 1) { if ( text[i] === "_" && text[i - 1] !== "_" && @@ -435,12 +469,7 @@ const handleIncompleteSingleUnderscoreItalic = (text: string): string => { // Check if underscore is word-internal (between word characters) const prevChar = i > 0 ? text[i - 1] : "" const nextChar = i < text.length - 1 ? text[i + 1] : "" - if ( - prevChar && - nextChar && - /[\p{L}\p{N}_]/u.test(prevChar) && - /[\p{L}\p{N}_]/u.test(nextChar) - ) { + if (prevChar && nextChar && isWordChar(prevChar) && isWordChar(nextChar)) { continue } @@ -458,17 +487,25 @@ const handleIncompleteSingleUnderscoreItalic = (text: string): string => { // Check if there's meaningful content after the underscore // Don't close if content is only whitespace or emphasis markers - if (!contentAfterFirstUnderscore || /^[\s_~*`]*$/.test(contentAfterFirstUnderscore)) { + if ( + !contentAfterFirstUnderscore || + whitespaceOrMarkersPattern.test(contentAfterFirstUnderscore) + ) { return text } const singleUnderscores = countSingleUnderscores(text) if (singleUnderscores % 2 === 1) { // If text ends with newline(s), insert underscore before them - const trailingNewlineMatch = text.match(/\n+$/) - if (trailingNewlineMatch) { - const textBeforeNewlines = text.slice(0, -trailingNewlineMatch[0].length) - return `${textBeforeNewlines}_${trailingNewlineMatch[0]}` + // Use string methods instead of regex to avoid ReDoS vulnerability + let endIndex = text.length + while (endIndex > 0 && text[endIndex - 1] === "\n") { + endIndex -= 1 + } + if (endIndex < text.length) { + const textBeforeNewlines = text.slice(0, endIndex) + const trailingNewlines = text.slice(endIndex) + return `${textBeforeNewlines}_${trailingNewlines}` } return `${text}_` } @@ -489,9 +526,9 @@ const isPartOfTripleBacktick = (text: string, i: number): boolean => { // Counts single backticks that are not part of triple backticks const countSingleBackticks = (text: string): number => { let count = 0 - for (let i = 0; i < text.length; i++) { + for (let i = 0; i < text.length; i += 1) { if (text[i] === "`" && !isPartOfTripleBacktick(text, i)) { - count++ + count += 1 } } return count @@ -499,11 +536,12 @@ const countSingleBackticks = (text: string): number => { // Completes incomplete inline code formatting (`) // Avoids completing if inside an incomplete code block +// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: "Complex inline code handling logic with multiple edge cases for markdown parsing" const handleIncompleteInlineCode = (text: string): string => { // Check if we have inline triple backticks (starts with ``` and should end with ```) // This pattern should ONLY match truly inline code (no newlines) // Examples: ```code``` or ```python code``` - const inlineTripleBacktickMatch = text.match(/^```[^`\n]*```?$/) + const inlineTripleBacktickMatch = text.match(inlineTripleBacktickPattern) if (inlineTripleBacktickMatch && !text.includes("\n")) { // Check if it ends with exactly 2 backticks (incomplete) if (text.endsWith("``") && !text.endsWith("```")) { @@ -525,10 +563,8 @@ const handleIncompleteInlineCode = (text: string): string => { // Special case: if text ends with ```\n (triple backticks followed by newline) // This is actually a complete code block, not incomplete - if ( - (text.endsWith("```\n") || text.endsWith("```")) && // Count all triple backticks - if even, it's complete - allTripleBackticks % 2 === 0 - ) { + if ((text.endsWith("```\n") || text.endsWith("```")) && allTripleBackticks % 2 === 0) { + // Count all triple backticks - if even, it's complete return text } @@ -539,7 +575,7 @@ const handleIncompleteInlineCode = (text: string): string => { // inlineCodeMatch[2] contains the content after ` // Check if content is only whitespace or other emphasis markers const contentAfterMarker = inlineCodeMatch[2] - if (!contentAfterMarker || /^[\s_~*`]*$/.test(contentAfterMarker)) { + if (!contentAfterMarker || whitespaceOrMarkersPattern.test(contentAfterMarker)) { return text } @@ -553,6 +589,7 @@ const handleIncompleteInlineCode = (text: string): string => { } // Completes incomplete strikethrough formatting (~~) +// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: "Complex markdown parsing logic with multiple edge cases" const handleIncompleteStrikethrough = (text: string): string => { const strikethroughMatch = text.match(strikethroughPattern) @@ -561,7 +598,7 @@ const handleIncompleteStrikethrough = (text: string): string => { // strikethroughMatch[2] contains the content after ~~ // Check if content is only whitespace or other emphasis markers const contentAfterMarker = strikethroughMatch[2] - if (!contentAfterMarker || /^[\s_~*`]*$/.test(contentAfterMarker)) { + if (!contentAfterMarker || whitespaceOrMarkersPattern.test(contentAfterMarker)) { return text } @@ -574,24 +611,6 @@ const handleIncompleteStrikethrough = (text: string): string => { return text } -// Counts single dollar signs that are not part of double dollar signs and not escaped -const _countSingleDollarSigns = (text: string): number => { - return text.split("").reduce((acc, char, index) => { - if (char === "$") { - const prevChar = text[index - 1] - const nextChar = text[index + 1] - // Skip if escaped with backslash - if (prevChar === "\\") { - return acc - } - if (prevChar !== "$" && nextChar !== "$") { - return acc + 1 - } - } - return acc - }, 0) -} - // Completes incomplete block KaTeX formatting ($$) const handleIncompleteBlockKatex = (text: string): string => { // Count all $$ pairs in the text @@ -617,19 +636,29 @@ const handleIncompleteBlockKatex = (text: string): string => { } // Counts triple asterisks that are not part of quadruple or more asterisks +// OPTIMIZATION: Count *** without regex to avoid allocation const countTripleAsterisks = (text: string): number => { let count = 0 - const matches = text.match(/\*+/g) || [] + let consecutiveAsterisks = 0 - for (const match of matches) { - // Count how many complete triple asterisks are in this sequence - const asteriskCount = match.length - if (asteriskCount >= 3) { - // Each group of exactly 3 asterisks counts as one triple asterisk marker - count += Math.floor(asteriskCount / 3) + // biome-ignore lint/style/useForOf: "Need index access to check character codes for performance" + for (const element of text) { + if (element === "*") { + consecutiveAsterisks += 1 + } else { + // End of asterisk sequence + if (consecutiveAsterisks >= 3) { + count += Math.floor(consecutiveAsterisks / 3) + } + consecutiveAsterisks = 0 } } + // Handle trailing asterisks + if (consecutiveAsterisks >= 3) { + count += Math.floor(consecutiveAsterisks / 3) + } + return count } @@ -642,7 +671,7 @@ const handleIncompleteBoldItalic = (text: string): string => { // Don't process if text is only asterisks and has 4 or more consecutive asterisks // This prevents cases like **** from being treated as incomplete *** - if (/^\*{4,}$/.test(text)) { + if (fourOrMoreAsterisksPattern.test(text)) { return text } @@ -653,7 +682,7 @@ const handleIncompleteBoldItalic = (text: string): string => { // boldItalicMatch[2] contains the content after *** // Check if content is only whitespace or other emphasis markers const contentAfterMarker = boldItalicMatch[2] - if (!contentAfterMarker || /^[\s_~*`]*$/.test(contentAfterMarker)) { + if (!contentAfterMarker || whitespaceOrMarkersPattern.test(contentAfterMarker)) { return text } @@ -688,10 +717,6 @@ export const parseIncompleteMarkdown = (text: string): string => { // Handle various formatting completions // Handle triple asterisks first (most specific) result = handleIncompleteBoldItalic(result) - // Normalize and guard the ` { @@ -38,6 +41,19 @@ const AIEnhancedTimelineLayoutImpl = () => { const aiPanelStyle = useAIChatPanelStyle() const isAIPanelVisible = useAIPanelVisibility() const hasSelectedEntry = Boolean(realEntryId) + const isMobile = useMobile() + + // Compute derived values first + const showEntryContentOnRight = showEntryDetailsColumn && hasSelectedEntry + const isFixedPanelStyle = aiPanelStyle === AIChatPanelStyle.Fixed + const shouldShowFixedAI = isFixedPanelStyle && isAIPanelVisible + const showEntryContentOnLeft = !showEntryDetailsColumn && hasSelectedEntry + const shouldRenderRightColumn = showEntryDetailsColumn || shouldShowFixedAI + const shouldShowEntryBorder = showEntryDetailsColumn || shouldShowFixedAI + + // Mobile-specific logic: disable resizing and hide splitters + const shouldDisableResize = isMobile + const shouldShowSplitter = !isMobile && shouldRenderRightColumn const layoutContainerRef = useRef(null) const feedColumnWidth = useUISettingKey("feedColWidth") @@ -62,6 +78,7 @@ const AIEnhancedTimelineLayoutImpl = () => { max: timelineMaxWidth, initial: entryColumnInitialWidth, containerRef: layoutContainerRef as React.RefObject, + disabled: shouldDisableResize, onResizeStart({ position }) { timelineStartDragPosition.current = position }, @@ -101,6 +118,7 @@ const AIEnhancedTimelineLayoutImpl = () => { initial: resolvePreferredWidth(), reverse: true, containerRef: layoutContainerRef as React.RefObject, + disabled: shouldDisableResize, onResizeStart({ position }) { aiPanelStartDragPosition.current = position }, @@ -117,32 +135,36 @@ const AIEnhancedTimelineLayoutImpl = () => { window.dispatchEvent(new Event("resize")) }, [resolvePreferredWidth, setAiPanelWidth]) - const showEntryContentOnRight = showEntryDetailsColumn && hasSelectedEntry - const isFixedPanelStyle = aiPanelStyle === AIChatPanelStyle.Fixed - const shouldShowFixedAI = isFixedPanelStyle && isAIPanelVisible - const showEntryContentOnLeft = !showEntryDetailsColumn && hasSelectedEntry - - const shouldRenderRightColumn = showEntryDetailsColumn || shouldShowFixedAI - const shouldShowEntryBorder = showEntryDetailsColumn || shouldShowFixedAI - - const entryColumnStyle: CSSProperties = showEntryDetailsColumn + const entryColumnStyle: CSSProperties = isMobile ? { - flexBasis: timelineColumnWidth, - minWidth: MIN_ENTRY_WIDTH, - } - : { - minWidth: MIN_ENTRY_WIDTH, + width: "100%", + minWidth: "100%", + flexBasis: "100%", } + : showEntryDetailsColumn + ? { + flexBasis: timelineColumnWidth, + minWidth: MIN_ENTRY_WIDTH, + } + : { + minWidth: MIN_ENTRY_WIDTH, + } - const rightColumnStyle: CSSProperties = showEntryDetailsColumn + const rightColumnStyle: CSSProperties = isMobile ? { - minWidth: 0, - } - : { - width: aiPanelWidth, - minWidth: 0, - flexBasis: aiPanelWidth, + width: "100%", + minWidth: "100%", + flexBasis: "100%", } + : showEntryDetailsColumn + ? { + minWidth: 0, + } + : { + width: aiPanelWidth, + minWidth: 0, + flexBasis: aiPanelWidth, + } const resetTimelineWidth = useCallback(() => { setUISetting("entryColWidth", defaultUISettings.entryColWidth) @@ -157,7 +179,7 @@ const AIEnhancedTimelineLayoutImpl = () => { window.dispatchEvent(new Event("resize")) }, [clampWidth, setAiPanelWidth]) - const splitter = + const splitter = shouldShowSplitter ? ( shouldRenderRightColumn && showEntryDetailsColumn ? ( { onDoubleClick={resetAiWidth} /> ) : null + ) : null + + // Mobile layout: stacked with view switching + if (isMobile) { + return + } return (
("list") + const navigate = useNavigateEntry() + const { view } = useRouteParamsSelector((state) => ({ + view: state.view, + })) + const showEntryDetailsColumn = useShowEntryDetailsColumn() + // Auto-switch to entry view when entry is selected + useEffect(() => { + if (hasSelectedEntry && mobileView === "list") { + setMobileView("entry") + } else if (!hasSelectedEntry && mobileView === "entry") { + setMobileView("list") + } + }, [hasSelectedEntry, mobileView]) + + return ( +
+ +
+ {/* List View */} + + {mobileView === "list" && ( + + + + )} + + {/* Entry View */} + {mobileView === "entry" && entryId && ( + +
+
+ {/* Mobile back button - only show when EntryHeaderBreadcrumb doesn't show close button */} + {showEntryDetailsColumn && ( + + )} +
+ +
+
+
+
+ +
+
+ )} +
+
+
+
+ ) +}) diff --git a/apps/desktop/layer/renderer/src/modules/auth/LoginModalContent.tsx b/apps/desktop/layer/renderer/src/modules/auth/LoginModalContent.tsx index 36979684c..e6f891e64 100644 --- a/apps/desktop/layer/renderer/src/modules/auth/LoginModalContent.tsx +++ b/apps/desktop/layer/renderer/src/modules/auth/LoginModalContent.tsx @@ -99,25 +99,44 @@ export const LoginModalContent = (props: LoginModalContentProps) => { )} {/* Header Section */} -
+
- - - - - {isRegister ? t("signin.sign_up_to") : t("signin.sign_in_to")} - - + + {isRegister ? ( + +

{t("login.title")}

+

+ {t("login.subtitle")} +

+ {/* Benefits - single line */} +
+ ✦ + {t("login.benefit_1")} + · + {t("login.benefit_2")} +
+
+ ) : ( + + {t("signin.sign_in_to")} + + + )}
{!IN_ELECTRON && ( ))} + {/* Quick start hint */} + {isRegister && providers.length > 0 && !isLoading && ( + + {t("login.quick_start")} + + )}
{/* Referral Form */} @@ -212,7 +240,7 @@ export const LoginModalContent = (props: LoginModalContentProps) => { )} {/* Footer Links */} -
+
+ ) +} + +export function UnifiedDiscoverForm() { + const [searchParams, setSearchParams] = useSearchParams() + const keywordFromSearch = searchParams.get("keyword") || "" + const { t } = useTranslation() + const isInMASReview = useIsInMASReview() + const { ensureLogin } = useRequireLogin() + const { present, dismissAll } = useModalStack() + const isMobile = useMobile() + + // Auto-detect input type based on current value + const detectedType = useMemo(() => { + if (keywordFromSearch) { + return detectInputType(keywordFromSearch) + } + return "search" + }, [keywordFromSearch]) + + // Use search form by default, but validate based on detected type + const form = useForm({ + resolver: zodResolver(searchSchema), + defaultValues: { + keyword: keywordFromSearch || "", + target: "feeds", + }, + mode: "all", + }) + + const { watch, trigger } = form + const target = watch("target") + const atomKey = useRef(keywordFromSearch + target) + + // Validate default value from search params + useEffect(() => { + if (!keywordFromSearch) { + return + } + trigger("keyword") + }, [trigger, keywordFromSearch]) + + const discoverSearchData = useDiscoverSearchData()?.[atomKey.current] || [] + + const mutation = useMutation({ + mutationFn: async ({ keyword, target }: { keyword: string; target: "feeds" | "lists" }) => { + const inputType = detectInputType(keyword) + + // For RSS/RSSHub, validate and show feed form modal directly + if (inputType === "rss") { + const validated = rssSchema.safeParse({ keyword }) + if (!validated.success) { + throw new Error("Invalid RSS URL") + } + present({ + title: t("feed_form.add_feed"), + content: () => , + }) + return [] + } + + if (inputType === "rsshub") { + const validated = rsshubSchema.safeParse({ keyword }) + if (!validated.success) { + throw new Error("Invalid RSSHub route") + } + present({ + title: t("feed_form.add_feed"), + content: () => , + }) + return [] + } + + // For search, perform discovery + let { data } = await followClient.api.discover.discover({ + keyword: keyword.trim(), + target, + }) + if (isInMASReview) { + data = data.filter((item) => !item.list?.fee) + } + + setDiscoverSearchData((prev) => ({ + ...prev, + [atomKey.current]: data, + })) + + return data + }, + }) + + const handleKeywordChange = useCallback( + (event: ChangeEvent) => { + const { value } = event.currentTarget + // During composition, update raw value without validation + if ((event.nativeEvent as InputEvent)?.isComposing) { + form.setValue("keyword", value, { shouldValidate: false }) + return + } + + startTransition(() => { + form.setValue("keyword", value, { shouldValidate: true }) + setSearchParams( + (prev) => { + const newParams = new URLSearchParams(prev) + if (value.trim()) { + newParams.set("keyword", value.trim()) + } else { + newParams.delete("keyword") + } + return newParams + }, + { + replace: true, + }, + ) + }) + }, + [form, setSearchParams], + ) + + const handleCompositionEnd = useCallback( + (event: CompositionEvent) => { + const { value } = event.currentTarget + form.setValue("keyword", value, { shouldValidate: true }) + setSearchParams( + (prev) => { + const newParams = new URLSearchParams(prev) + if (value.trim()) { + newParams.set("keyword", value.trim()) + } else { + newParams.delete("keyword") + } + return newParams + }, + { + replace: true, + }, + ) + }, + [form, setSearchParams], + ) + + const handleSuccess = useCallback( + (item: DiscoveryItem) => { + const currentData = getDiscoverSearchData() + if (!currentData) return + setDiscoverSearchData( + produce(currentData, (draft) => { + const sub = (draft[atomKey.current] || []).find((i) => { + if (item.feed) { + return i.feed?.id === item.feed.id + } + if (item.list) { + return i.list?.id === item.list.id + } + return false + }) + if (!sub) return + sub.subscriptionCount = -~(sub.subscriptionCount as number) + }), + ) + }, + [atomKey], + ) + + const handleUnSubscribed = useCallback( + (item: DiscoveryItem) => { + const currentData = getDiscoverSearchData() + if (!currentData) return + setDiscoverSearchData( + produce(currentData, (draft) => { + const sub = (draft[atomKey.current] || []).find( + (i) => i.feed?.id === item.feed?.id || i.list?.id === item.list?.id, + ) + if (!sub) return + sub.subscriptionCount = Number.isNaN(sub.subscriptionCount) + ? 0 + : (sub.subscriptionCount as number) - 1 + }), + ) + }, + [atomKey], + ) + + const handleTargetChange = useCallback( + (value: string) => { + form.setValue("target", value as "feeds" | "lists") + }, + [form], + ) + + function onSubmit(values: SearchFormData) { + if (!ensureLogin()) { + return + } + atomKey.current = values.keyword + values.target + mutation.mutate({ keyword: values.keyword, target: values.target }) + } + + const showTargetSelector = detectedType === "search" + + return ( + <> + + + + + + +
+ {(mutation.isSuccess || !!discoverSearchData?.length) && ( +
+ {t("discover.search.results", { count: discoverSearchData?.length || 0 })} + + {discoverSearchData && discoverSearchData.length > 0 && ( + { + setDiscoverSearchData({}) + mutation.reset() + }} + > + + + )} +
+ )} +
+ {discoverSearchData?.map((item) => ( + + ))} +
+
+ + ) +} diff --git a/apps/desktop/layer/renderer/src/modules/discover/atoms/discover.ts b/apps/desktop/layer/renderer/src/modules/discover/atoms/discover.ts new file mode 100644 index 000000000..93651ba20 --- /dev/null +++ b/apps/desktop/layer/renderer/src/modules/discover/atoms/discover.ts @@ -0,0 +1,15 @@ +import { createAtomHooks } from "@follow/utils" +import type { DiscoveryItem } from "@follow-app/client-sdk" +import { atom, useAtomValue } from "jotai" +import { selectAtom } from "jotai/utils" +import { useMemo } from "react" + +const internalAtom = atom>({}) +export const [, , useDiscoverSearchData, , getDiscoverSearchData, setDiscoverSearchData] = + createAtomHooks(internalAtom) + +export const useHasDiscoverSearchData = () => { + return useAtomValue( + useMemo(() => selectAtom(internalAtom, (data) => Object.keys(data).length > 0), []), + ) +} diff --git a/apps/desktop/layer/renderer/src/modules/discover/recommendations.tsx b/apps/desktop/layer/renderer/src/modules/discover/recommendations.tsx index d389532a8..bcb902d30 100644 --- a/apps/desktop/layer/renderer/src/modules/discover/recommendations.tsx +++ b/apps/desktop/layer/renderer/src/modules/discover/recommendations.tsx @@ -1,61 +1,13 @@ import { Card, CardContent } from "@follow/components/ui/card/index.jsx" -import { ResponsiveSelect } from "@follow/components/ui/select/responsive.js" import { CategoryMap, RSSHubCategories } from "@follow/constants" import { useTranslation } from "react-i18next" import { Link } from "react-router" -import { setUISetting, useUISettingKey } from "~/atoms/settings/ui" - -const LanguageOptions = [ - { - label: "words.all", - value: "all", - }, - { - label: "words.english", - value: "eng", - }, - { - label: "words.chinese", - value: "cmn", - }, -] - -type Language = "all" | "eng" | "cmn" - export function Recommendations() { const { t } = useTranslation() - const { t: tCommon } = useTranslation("common") - - const lang = useUISettingKey("discoverLanguage") - - const handleLangChange = (value: string) => { - setUISetting("discoverLanguage", value as Language) - } return (
-
-
- - {t("words.categories")} -
-
-
- {t("words.language")} - tCommon(item.label as any)} - renderValue={(item) => tCommon(item.label as any)} - /> -
-
-
-
{RSSHubCategories.map((cat) => ( diff --git a/apps/desktop/layer/renderer/src/modules/entry-column/Items/all-item.tsx b/apps/desktop/layer/renderer/src/modules/entry-column/Items/all-item.tsx index dae915cc6..0e7596855 100644 --- a/apps/desktop/layer/renderer/src/modules/entry-column/Items/all-item.tsx +++ b/apps/desktop/layer/renderer/src/modules/entry-column/Items/all-item.tsx @@ -299,6 +299,7 @@ function VideoIcon({ src }: { src: string }) {
{feedIcon && } diff --git a/apps/desktop/layer/renderer/src/modules/entry-content/EntryContent.tsx b/apps/desktop/layer/renderer/src/modules/entry-content/EntryContent.tsx index 643d90a31..8841b5cc3 100644 --- a/apps/desktop/layer/renderer/src/modules/entry-content/EntryContent.tsx +++ b/apps/desktop/layer/renderer/src/modules/entry-content/EntryContent.tsx @@ -18,8 +18,10 @@ import * as React from "react" import { memo, useEffect, useRef, useState } from "react" import { useEntryIsInReadability } from "~/atoms/readability" +import { AppErrorBoundary } from "~/components/common/AppErrorBoundary" import { Focusable } from "~/components/common/Focusable" import { m } from "~/components/common/Motion" +import { ErrorComponentType } from "~/components/errors/enum" import { GlassButton } from "~/components/ui/button/GlassButton" import { HotkeyScope } from "~/constants" import { useRouteParamsSelector } from "~/hooks/biz/useRouteParams" @@ -229,9 +231,11 @@ const EntryContentImpl: Component = ({ } export const EntryContent: Component = memo((props) => { return ( - - - + + + + + ) }) diff --git a/apps/desktop/layer/renderer/src/modules/entry-content/components/layouts/shared/VideoPlayer.tsx b/apps/desktop/layer/renderer/src/modules/entry-content/components/layouts/shared/VideoPlayer.tsx index f57744e14..176922e1a 100644 --- a/apps/desktop/layer/renderer/src/modules/entry-content/components/layouts/shared/VideoPlayer.tsx +++ b/apps/desktop/layer/renderer/src/modules/entry-content/components/layouts/shared/VideoPlayer.tsx @@ -134,11 +134,13 @@ export const VideoPlayer: React.FC = ({ {preferFullSize && iframeSrc ? ( ) : miniIframeSrc && showPreview ? ( ) : entry.firstMedia ? ( diff --git a/apps/desktop/layer/renderer/src/modules/settings/control.tsx b/apps/desktop/layer/renderer/src/modules/settings/control.tsx index 6a9e8d762..e6707d5a8 100644 --- a/apps/desktop/layer/renderer/src/modules/settings/control.tsx +++ b/apps/desktop/layer/renderer/src/modules/settings/control.tsx @@ -211,7 +211,7 @@ export const SettingActionItem = ({ action: () => void buttonText: string }) => ( -
+
{typeof label === "string" ? titleCase(label) : label}
diff --git a/apps/desktop/layer/renderer/src/modules/settings/tabs/appearance.tsx b/apps/desktop/layer/renderer/src/modules/settings/tabs/appearance.tsx index c791bb85b..862c79ba2 100644 --- a/apps/desktop/layer/renderer/src/modules/settings/tabs/appearance.tsx +++ b/apps/desktop/layer/renderer/src/modules/settings/tabs/appearance.tsx @@ -376,7 +376,7 @@ const CustomCSS = () => { }} buttonText={t("appearance.custom_css.button")} /> - + {t("appearance.custom_css.description")} 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 d820224a4..7d745c87a 100644 --- a/apps/desktop/layer/renderer/src/modules/settings/tabs/feeds.tsx +++ b/apps/desktop/layer/renderer/src/modules/settings/tabs/feeds.tsx @@ -6,6 +6,7 @@ import { LoadingCircle } from "@follow/components/ui/loading/index.jsx" import { RSSHubLogo } from "@follow/components/ui/platform-icon/icons.js" import { useScrollViewElement } from "@follow/components/ui/scroll-area/hooks.js" import { ScrollArea } from "@follow/components/ui/scroll-area/index.js" +import { ResponsiveSelect } from "@follow/components/ui/select/responsive.js" import { Table, TableBody, @@ -33,7 +34,7 @@ import { clsx, formatNumber, sortByAlphabet } from "@follow/utils/utils" import { useVirtualizer } from "@tanstack/react-virtual" import { AnimatePresence, m } from "motion/react" import type { FC } from "react" -import { memo, useCallback, useMemo, useState } from "react" +import { memo, useCallback, useEffect, useMemo, useState } from "react" import { useTranslation } from "react-i18next" import { useIsInMASReview } from "~/atoms/server-configs" @@ -56,6 +57,7 @@ import { Queries } from "~/queries" type SortField = "name" | "view" | "date" | "subscriptionCount" | "updatesPerWeek" type SortDirection = "asc" | "desc" +type FeedFilter = "all" | "rsshub" export const SettingFeeds = () => { const inMas = useIsInMASReview() @@ -75,6 +77,42 @@ const SubscriptionFeedsSection = () => { const [selectedFeeds, setSelectedFeeds] = useState>(() => new Set()) const [sortField, setSortField] = useState("name") const [sortDirection, setSortDirection] = useState("asc") + const [filter, setFilter] = useState("all") + + // Calculate RSSHub feeds count + const rsshubFeedsCount = useMemo(() => { + return allFeeds.filter((feedId) => { + const feed = getFeedById(feedId) + return Boolean(feed?.url?.startsWith("rsshub://")) + }).length + }, [allFeeds]) + + // Filter feeds based on selected filter + const filteredFeeds = useMemo(() => { + if (filter === "all") { + return allFeeds + } + return allFeeds.filter((feedId) => { + const feed = getFeedById(feedId) + return Boolean(feed?.url?.startsWith("rsshub://")) + }) + }, [allFeeds, filter]) + + // Clean up selectedFeeds when filter changes + const filteredFeedsSet = useMemo(() => new Set(filteredFeeds), [filteredFeeds]) + + // Clean selected feeds that are not in current filter + useEffect(() => { + setSelectedFeeds((prev) => { + const cleaned = new Set() + prev.forEach((feedId) => { + if (filteredFeedsSet.has(feedId)) { + cleaned.add(feedId) + } + }) + return cleaned + }) + }, [filteredFeedsSet]) const handleSort = useCallback( (field: SortField) => { @@ -91,12 +129,12 @@ const SubscriptionFeedsSection = () => { const handleSelectAll = useCallback( (checked: boolean) => { if (checked) { - setSelectedFeeds(new Set(allFeeds)) + setSelectedFeeds(new Set(filteredFeeds)) } else { setSelectedFeeds(new Set()) } }, - [allFeeds], + [filteredFeeds], ) const handleSelectFeed = useCallback((feedId: string, checked: boolean) => { @@ -111,7 +149,7 @@ const SubscriptionFeedsSection = () => { }) }, []) - const isAllSelected = allFeeds.length > 0 && selectedFeeds.size === allFeeds.length + const isAllSelected = filteredFeeds.length > 0 && selectedFeeds.size === filteredFeeds.length const presentDeleteSubscription = useConfirmUnsubscribeSubscriptionModal() const handleBatchUnsubscribe = useCallback(() => { @@ -121,9 +159,29 @@ const SubscriptionFeedsSection = () => { return (
-

{t("feeds.subscription")}

+
+

{t("feeds.subscription")}

+ {allFeeds.length > 0 && ( + setFilter(value as FeedFilter)} + items={[ + { + label: t("feeds.filter.all", { count: allFeeds.length }), + value: "all", + }, + { + label: t("feeds.filter.rsshub", { count: rsshubFeedsCount }), + value: "rsshub", + }, + ]} + /> + )} +
- {allFeeds.length > 0 && ( + {filteredFeeds.length > 0 && (
{/* Header - Sticky */}
{ {/* Feed List */}
{ + return {defaultResources[item.value].lang.name} + }, [])} renderItem={useTypeScriptHappyCallback((item) => { const lang = item.value const percent = I18N_COMPLETENESS_MAP[lang] 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 c38376104..91884f63b 100644 --- a/apps/desktop/layer/renderer/src/modules/subscription-column/FeedItem.tsx +++ b/apps/desktop/layer/renderer/src/modules/subscription-column/FeedItem.tsx @@ -9,7 +9,7 @@ import { TooltipTrigger, } from "@follow/components/ui/tooltip/index.jsx" import { EllipsisHorizontalTextWithTooltip } from "@follow/components/ui/typography/index.js" -import { FeedViewType } from "@follow/constants" +import { FeedViewType, getViewList } from "@follow/constants" import { isOnboardingFeedUrl } from "@follow/store/constants/onboarding" import { useFeedById } from "@follow/store/feed/hooks" import { useInboxById } from "@follow/store/inbox/hooks" @@ -30,6 +30,7 @@ import { useFeedActions, useInboxActions, useListActions } from "~/hooks/biz/use import { useFollow } from "~/hooks/biz/useFollow" import { useNavigateEntry } from "~/hooks/biz/useNavigateEntry" import { useRouteParamsSelector } from "~/hooks/biz/useRouteParams" +import { useBatchUpdateSubscription } from "~/hooks/biz/useSubscriptionActions" import { useContextMenu } from "~/hooks/common/useContextMenu" import { getNewIssueUrl } from "~/lib/issues" import { UrlBuilder } from "~/lib/url-builder" @@ -131,6 +132,8 @@ const FeedItemImpl = ({ view, feedId, className, isPreview }: FeedItemProps) => const whenTrigger = when && isActive useContextMenuActionShortCutTrigger(items, whenTrigger) + const { mutate: changeFeedView } = useBatchUpdateSubscription() + const [isContextMenuOpen, setIsContextMenuOpen] = useState(false) const showContextMenu = useShowContextMenu() const contextMenuProps = useContextMenu({ @@ -138,6 +141,8 @@ const FeedItemImpl = ({ view, feedId, className, isPreview }: FeedItemProps) => const nextItems = items.concat() if (!feed) return + + const isFeed = feed.type === "feed" || !feed.type if (isFeed && feed.errorAt && feed.errorMessage) { nextItems.push( MenuItemSeparator.default, @@ -159,6 +164,35 @@ const FeedItemImpl = ({ view, feedId, className, isPreview }: FeedItemProps) => }), ) } + + // Add "Switch to Another View" menu item + if (subscription && typeof subscription.view === "number") { + nextItems.push( + MenuItemSeparator.default, + new MenuItemText({ + label: t("sidebar.feed_column.context_menu.change_to_other_view"), + submenu: getViewList() + .filter((v) => v.view !== subscription.view && v.switchable) + .map( + (v) => + new MenuItemText({ + label: t(v.name, { ns: "common" }), + shortcut: (v.view + 1).toString(), + icon: v.icon, + click() { + return changeFeedView({ + feedIdList: [feedId], + view: v.view, + }) + }, + requiresLogin: true, + }), + ), + requiresLogin: true, + }), + ) + } + setIsContextMenuOpen(true) await showContextMenu(nextItems, e) setIsContextMenuOpen(false) 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 f047e8909..b787e03a7 100644 --- a/apps/desktop/layer/renderer/src/modules/subscription-column/index.tsx +++ b/apps/desktop/layer/renderer/src/modules/subscription-column/index.tsx @@ -327,7 +327,7 @@ const NotLoggedInNotice: FC = () => { onClick={() => { presentLoginModal() }} - className="my-1 flex items-start gap-2 border-blue/30 bg-blue/10 px-1.5 py-2 text-left text-xs leading-snug text-blue transition-colors hover:border-blue hover:bg-blue/15 focus:outline-none focus-visible:ring-2 focus-visible:ring-blue/40" + className="my-1 flex items-start gap-2 border-accent/30 bg-accent/10 px-1.5 py-2 text-left text-xs leading-snug text-accent transition-colors hover:border-accent hover:bg-accent/15 focus:outline-none focus-visible:ring-2 focus-visible:ring-accent/40" > 👤

diff --git a/apps/desktop/layer/renderer/src/modules/subscription-column/sort-by/SortByUnreadList.tsx b/apps/desktop/layer/renderer/src/modules/subscription-column/sort-by/SortByUnreadList.tsx index b0ae9a8c8..619b8d2e2 100644 --- a/apps/desktop/layer/renderer/src/modules/subscription-column/sort-by/SortByUnreadList.tsx +++ b/apps/desktop/layer/renderer/src/modules/subscription-column/sort-by/SortByUnreadList.tsx @@ -1,13 +1,13 @@ import { isOnboardingFeedUrl } from "@follow/store/constants/onboarding" import { useFeedStore } from "@follow/store/feed/store" import { useSortedCategoriesByUnread } from "@follow/store/unread/hooks" -import { Fragment, useCallback } from "react" +import { Fragment, memo, useCallback } from "react" import { useFeedListSortSelector } from "../atom" import { FeedCategoryAutoHideUnread } from "../FeedCategory" import type { FeedListProps } from "./types" -export const SortByUnreadFeedList = ({ view, data, categoryOpenStateData }: FeedListProps) => { +export const SortByUnreadFeedList = memo(({ view, data, categoryOpenStateData }: FeedListProps) => { const isDesc = useFeedListSortSelector((s) => s.order === "desc") const sortedByUnread = useSortedCategoriesByUnread(data, isDesc) @@ -26,9 +26,9 @@ export const SortByUnreadFeedList = ({ view, data, categoryOpenStateData }: Feed }) if (hasOnboardingFeed) { - onboardingCategories.push([category, ids]) + onboardingCategories.push([category, ids.concat()]) } else { - regularCategories.push([category, ids]) + regularCategories.push([category, ids.concat()]) } } @@ -50,4 +50,4 @@ export const SortByUnreadFeedList = ({ view, data, categoryOpenStateData }: Feed ))} ) -} +}) 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 f11a4915e..1b9902a8a 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 @@ -49,6 +49,7 @@ import type { SubscriptionProps } from "./SubscriptionListGuard" const SubscriptionImpl = ({ ref, className, view, isSubscriptionLoading }: SubscriptionProps) => { const autoGroup = useGeneralSettingKey("autoGroup") const feedsData = useFeedsGroupedData(view, autoGroup) + const listSubIds = useSubscriptionListIds(view) const inboxSubIds = useInboxList( useCallback( diff --git a/apps/desktop/layer/renderer/src/modules/trending/index.tsx b/apps/desktop/layer/renderer/src/modules/trending/index.tsx index bf94e89b4..9fccb5668 100644 --- a/apps/desktop/layer/renderer/src/modules/trending/index.tsx +++ b/apps/desktop/layer/renderer/src/modules/trending/index.tsx @@ -1,10 +1,10 @@ import { useScrollElementUpdate } from "@follow/components/ui/scroll-area/hooks.js" import { ResponsiveSelect } from "@follow/components/ui/select/responsive.js" import { Skeleton } from "@follow/components/ui/skeleton/index.jsx" -import { getViewList } from "@follow/constants" +import { FeedViewType, getView, getViewList } from "@follow/constants" import { cn } from "@follow/utils/utils" import { useQuery } from "@tanstack/react-query" -import { useEffect, useState } from "react" +import { cloneElement, useEffect, useMemo, useState } from "react" import { useTranslation } from "react-i18next" import { setUISetting, useUISettingKey } from "~/atoms/settings/ui" @@ -29,27 +29,36 @@ const LanguageOptions = [ type Language = "all" | "eng" | "cmn" -const viewOptions = [ - { - label: "words.all", - value: "all", - }, - ...getViewList().map((view) => ({ - label: view.name, - value: `${view.view}`, - })), -] +type View = "all" | string -type View = (typeof viewOptions)[number]["value"] +const buildViewOptions = () => { + const allView = getView(FeedViewType.All) + return [ + { + label: "words.all", + value: "all" as const, + icon: allView?.icon, + className: allView?.className, + }, + ...getViewList().map((view) => ({ + label: view.name, + value: `${view.view}`, + icon: view.icon, + className: view.className, + })), + ] +} export function Trending({ limit = 20, narrow, center, + hideHeader = false, }: { limit?: number narrow?: boolean center?: boolean + hideHeader?: boolean }) { const { t } = useTranslation() const { t: tCommon } = useTranslation("common") @@ -57,6 +66,7 @@ export function Trending({ const { onUpdateMaxScroll } = useScrollElementUpdate() const [selectedView, setSelectedView] = useState("all") + const viewOptions = useMemo(() => buildViewOptions(), []) const { data, isLoading } = useQuery({ queryKey: ["trending", lang, selectedView], @@ -80,53 +90,105 @@ export function Trending({ return (

-
+ {!hideHeader && (
- - {t("words.trending")} -
-
-
- {t("words.language")}: +
+ + {t("words.trending")} +
+
+
+ {t("words.language")}: - { - setUISetting("discoverLanguage", value as Language) - }} - triggerClassName="h-8 rounded border-0" - size="sm" - items={LanguageOptions} - renderItem={(item) => tCommon(item.label as any)} - renderValue={(item) => tCommon(item.label as any)} - /> -
-
- {t("words.view")}: - { - setSelectedView(value as View) - }} - triggerClassName="h-8 rounded border-0" - size="sm" - items={viewOptions} - renderItem={(item) => <>{tCommon(item.label as any)}} - /> + { + setUISetting("discoverLanguage", value as Language) + }} + triggerClassName="h-8 rounded border-0" + size="sm" + items={LanguageOptions} + renderItem={(item) => tCommon(item.label as any)} + renderValue={(item) => tCommon(item.label as any)} + /> +
+
+ {t("words.view")}: +
+ {viewOptions.map((option) => { + const isSelected = selectedView === option.value + return ( + + ) + })} +
+
-
+ )} + {hideHeader && ( +
+
+ {viewOptions.map((option) => { + const isSelected = selectedView === option.value + return ( + + ) + })} +
+
+ )}
{isLoading ? ( <> 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 ebe03351c..35cbae226 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 @@ -1,145 +1,62 @@ -import { Divider } from "@follow/components/ui/divider/Divider.js" -import { useScrollElementUpdate } from "@follow/components/ui/scroll-area/hooks.js" -import { ScrollArea } from "@follow/components/ui/scroll-area/index.js" -import { Tabs, TabsContent, TabsList, TabsTrigger } from "@follow/components/ui/tabs/index.jsx" -import { createElement } from "react" +import { cn } from "@follow/utils/utils" +import type { ReactNode } from "react" import { useTranslation } from "react-i18next" -import { useSearchParams } from "react-router" import { AppErrorBoundary } from "~/components/common/AppErrorBoundary" import { ErrorComponentType } from "~/components/errors/enum" import { useSubViewTitle } from "~/modules/app-layout/subview/hooks" -import { DiscoverForm } from "~/modules/discover/DiscoverForm" -import { DiscoverImport } from "~/modules/discover/DiscoverImport" -import { DiscoverInboxList } from "~/modules/discover/DiscoverInboxList" -import { DiscoverTransform } from "~/modules/discover/DiscoverTransform" -import { DiscoverUser } from "~/modules/discover/DiscoverUser" -import { Recommendations } from "~/modules/discover/recommendations" -import { Trending } from "~/modules/trending" +import { useHasDiscoverSearchData } from "~/modules/discover/atoms/discover" +import { DiscoveryContent } from "~/modules/discover/DiscoveryContent" +import { UnifiedDiscoverForm } from "~/modules/discover/UnifiedDiscoverForm" -const tabs: { - name: I18nKeys - value: string -}[] = [ - { - name: "words.search", - value: "search", - }, - { - name: "words.rss", - value: "rss", - }, - { - name: "words.rsshub", - value: "rsshub", - }, - { - name: "words.inbox", - value: "inbox", - }, - { - name: "words.user", - value: "user", - }, - { - name: "words.transform", - value: "transform", - }, - { - name: "words.import", - value: "import", - }, -] +// ============================================================================ +// Section Components +// ============================================================================ + +interface SectionProps { + children: ReactNode + className?: string +} + +function Section({ children, className }: SectionProps) { + return
{children}
+} + +// ============================================================================ +// Main Component +// ============================================================================ export function Component() { - const [search, setSearch] = useSearchParams() const { t } = useTranslation() - useSubViewTitle("words.discover") - const { onUpdateMaxScroll } = useScrollElementUpdate() + useSubViewTitle("words.discover") + const hasSearchData = useHasDiscoverSearchData() return (
- {/* Simple Header */} -
-

{t("words.discover")}

-
- -
- { - setSearch( - (search) => { - search.set("type", val) - search.delete("keyword") - return new URLSearchParams(search) - }, - { replace: true }, - ) - }} - className="w-full" - > - {/* Tab Navigation */} -
- - - {tabs.map((tab) => ( - { - onUpdateMaxScroll?.() - }} - > - {t(tab.name)} - - ))} - - -
- - {/* Tab Content */} -
- {tabs.map((tab) => ( - -
- {createElement(TabComponent[tab.value]! || TabComponent.default, { - type: tab.value, - })} -
-
- ))} -
-
- - {/* Additional Content Sections */} -
- - -
-

Trending

- -
- - - -
-

RSSHub

- - - -
+ {/* Hero Section */} +
+
+

{t("words.discover")}

+

{t("discover.tips.search_keyword")}

-
+
+ + {/* Search Section */} +
+
+ +
+
+ + {/* Discovery Section - Hide when searching */} + {!hasSearchData && ( +
+ + + +
+ )}
) } - -const TabComponent: Record> = { - import: DiscoverImport, - inbox: DiscoverInboxList, - user: DiscoverUser, - default: DiscoverForm, - transform: DiscoverTransform, -} diff --git a/apps/desktop/layer/renderer/src/pages/(main)/layout.tsx b/apps/desktop/layer/renderer/src/pages/(main)/layout.tsx index 60b62ca05..3b0263252 100644 --- a/apps/desktop/layer/renderer/src/pages/(main)/layout.tsx +++ b/apps/desktop/layer/renderer/src/pages/(main)/layout.tsx @@ -8,4 +8,5 @@ export const Component = withResponsiveComponent( const { default: DownloadPage } = await import("~/modules/download") return { default: DownloadPage } }, + (w) => w < 768, ) diff --git a/apps/desktop/layer/renderer/src/providers/setting-sync.tsx b/apps/desktop/layer/renderer/src/providers/setting-sync.tsx index d871f4034..42fb30fad 100644 --- a/apps/desktop/layer/renderer/src/providers/setting-sync.tsx +++ b/apps/desktop/layer/renderer/src/providers/setting-sync.tsx @@ -1,4 +1,4 @@ -import { isMobile } from "@follow/components/hooks/useMobile.js" +import { useMobile } from "@follow/components/hooks/useMobile.js" import { useIsDark } from "@follow/hooks" import { getAccentColorValue } from "@follow/shared/settings/constants" import type { UISettings } from "@follow/shared/settings/interface" @@ -47,12 +47,12 @@ const useUpdateDockBadge = (setting: UISettings) => { } const useUISettingSync = () => { const setting = useUISettingValue() - const mobile = isMobile() + const mobile = useMobile() useSyncTheme() useInsertionEffect(() => { const root = document.documentElement - root.style.fontSize = `${setting.uiTextSize * (mobile ? 1.125 : 1)}px` - }, [setting.uiTextSize]) + root.style.fontSize = `${setting.uiTextSize * (mobile ? 0.875 : 1)}px` + }, [setting.uiTextSize, mobile]) const isDark = useIsDark() useInsertionEffect(() => { diff --git a/apps/desktop/layer/renderer/src/workers/sw/index.ts b/apps/desktop/layer/renderer/src/workers/sw/index.ts index 5fe34af11..e91e4b328 100644 --- a/apps/desktop/layer/renderer/src/workers/sw/index.ts +++ b/apps/desktop/layer/renderer/src/workers/sw/index.ts @@ -1,7 +1,6 @@ /// import { CacheableResponsePlugin } from "workbox-cacheable-response" import { ExpirationPlugin } from "workbox-expiration" -import { precacheAndRoute } from "workbox-precaching" import { registerRoute } from "workbox-routing" import { CacheFirst } from "workbox-strategies" @@ -11,12 +10,6 @@ declare let self: ServiceWorkerGlobalScope registerPusher(self) -const preCacheExclude = new Set(["og-image.png", "opengraph-image.png"]) - -const precacheManifest = self.__WB_MANIFEST.filter((entry) => { - return typeof entry === "string" || !preCacheExclude.has(entry.url) -}) - registerRoute( ({ request }) => request.destination === "image", new CacheFirst({ @@ -33,5 +26,3 @@ registerRoute( ], }), ) - -precacheAndRoute(precacheManifest) diff --git a/apps/desktop/package.json b/apps/desktop/package.json index 5e2de2a6e..5154d6f70 100644 --- a/apps/desktop/package.json +++ b/apps/desktop/package.json @@ -1,7 +1,7 @@ { "name": "Folo", "type": "module", - "version": "1.2.3", + "version": "1.2.4", "private": true, "description": "Follow everything in one place", "author": "Folo Team", diff --git a/apps/desktop/vite.config.ts b/apps/desktop/vite.config.ts index 4439905f3..210e05483 100644 --- a/apps/desktop/vite.config.ts +++ b/apps/desktop/vite.config.ts @@ -153,6 +153,7 @@ export default ({ mode }) => { injectRegister: false, injectManifest: { + injectionPoint: undefined, globPatterns: [ "**/*.{js,json,css,html,txt,svg,png,ico,webp,woff,woff2,ttf,eot,otf,wasm}", ], diff --git a/locales/app/en.json b/locales/app/en.json index dbdad4060..44141cc77 100644 --- a/locales/app/en.json +++ b/locales/app/en.json @@ -102,6 +102,13 @@ "discover.target.feeds": "Feeds", "discover.target.label": "Search for", "discover.target.lists": "Lists", + "discover.tips.auto_detect": "Auto-detect input type", + "discover.tips.search_keyword": "Search by keyword, URL, RSS feed, or RSSHub route", + "discover.tools.description": "More Tools", + "discover.tools.import": "Import OPML", + "discover.tools.inbox": "Inbox", + "discover.tools.transform": "HTML to RSS", + "discover.tools.user": "Follow User", "entry.click_to_return": "Scroll up or click here to return", "entry.exit_detail": "Return to timeline", "entry.scroll_up_to_exit": "Scroll up to return to timeline", @@ -261,6 +268,9 @@ "feed_item.onboarding_feed": "This is an onboarding feed", "login.agree_to": "By continuing, you agree to our", "login.back": "Back", + "login.benefit_1": "Save 1–2 hours every day on reading", + "login.benefit_2": "Let AI highlight the most important updates", + "login.benefit_3": "Free plan available · No credit card required", "login.confirm_password.label": "Confirm Password", "login.continueWith": "Continue with {{provider}}", "login.email": "Email", @@ -274,10 +284,15 @@ "login.password": "Password", "login.password_optional": "Optional", "login.privacy": "Privacy Policy", + "login.quick_start": "Takes less than 30 seconds to get started.", "login.send_magic_link": "Send Magic Link", "login.signUp": "Sign up with email", "login.submit": "Submit", + "login.subtitle": "This AI RSS reader reads the internet for you, cutting through noise to surface the knowledge you actually care about.", + "login.subtitle_description": "Connect your RSS, newsletters and feeds. Let AI summarize and sort what really matters.", "login.terms": "Terms of Service", + "login.title": "Welcome to Folo", + "login.view_demo": "Or: View Demo →", "login.with_email.title": "Login with Email", "mark_all_read_button.auto_confirm_info": "Will be confirmed automatically after {{countdown}}s.", "mark_all_read_button.confirm": "Confirm", @@ -338,7 +353,7 @@ "new_user_guide.intro.title": "Vibe Reading with AI", "new_user_guide.selection.empty_description": "Describe what you're looking for in the AI chat and we'll recommend feeds for you.", "new_user_guide.selection.empty_title": "No feeds selected yet", - "not_logged_in_notice": "You are not logged in.
Please sign in to sync your subscriptions and settings across devices.", + "not_logged_in_notice": "Sign in to unlock AI-powered reading.
Save 1–2 hours daily with smart summaries and personalized feeds. Free to start.", "notify.store.default": "the store", "notify.store.mas": "App Store", "notify.store.mss": "Microsoft Store", diff --git a/locales/app/ja.json b/locales/app/ja.json index dcec5c342..13abfd3b7 100644 --- a/locales/app/ja.json +++ b/locales/app/ja.json @@ -101,6 +101,13 @@ "discover.target.feeds": "フィード", "discover.target.label": "検索対象", "discover.target.lists": "リスト", + "discover.tips.auto_detect": "入力タイプを自動検出", + "discover.tips.search_keyword": "キーワード、URL、RSS フィード、または RSSHub ルートで検索", + "discover.tools.description": "その他のツール", + "discover.tools.import": "OPML をインポート", + "discover.tools.inbox": "受信トレイ", + "discover.tools.transform": "HTML を RSS に変換", + "discover.tools.user": "ユーザーをフォロー", "entry.click_to_return": "上にスクロールまたはこの領域をクリックして戻る", "entry.exit_detail": "時間軸に戻る", "entry.scroll_up_to_exit": "上にスクロールして時間軸に戻る", @@ -258,6 +265,9 @@ "feed_item.onboarding_feed": "これはオンボーディングフィードです", "login.agree_to": " 続行することで、あなたは私たちの", "login.back": "戻る", + "login.benefit_1": "毎日 1–2 時間の読書時間を節約", + "login.benefit_2": "AI が最も重要な更新をハイライト", + "login.benefit_3": "無料プラン利用可能 · クレジットカード不要", "login.confirm_password.label": "パスワードの確認", "login.continueWith": "{{provider}} で続ける", "login.email": "Email", @@ -270,10 +280,15 @@ "login.password": "パスワード", "login.password_optional": "オプション", "login.privacy": "プライバシーポリシー", + "login.quick_start": "30 秒以内に始められます。", "login.send_magic_link": "マジックリンクを送信", "login.signUp": "メールでサインアップ", "login.submit": "ログイン", + "login.subtitle": "この AI RSS リーダーがインターネットを読み取り、ノイズを排除して、あなたが本当に気にかける知識を浮き彫りにします。", + "login.subtitle_description": "RSS、ニュースレター、フィードを接続。AI が要約し、本当に重要なものを整理します。", "login.terms": "利用規約", + "login.title": "Folo へようこそ", + "login.view_demo": "または:デモを見る →", "login.with_email.title": "メールでログイン", "mark_all_read_button.auto_confirm_info": "{{countdown}} 秒後に自動的に確認されます。", "mark_all_read_button.confirm": "確認", @@ -333,7 +348,7 @@ "new_user_guide.intro.title": "AI と楽しむ読書体験", "new_user_guide.selection.empty_description": "AI チャットで知りたいテーマを伝えると、おすすめのフィードを提案します。", "new_user_guide.selection.empty_title": "まだフィードが選択されていません", - "not_logged_in_notice": "ログインしていません。
デバイス間で購読と設定を同期するにはサインインしてください。", + "not_logged_in_notice": "サインインして AI 駆動の読書を解鎖。
スマートな要約とパーソナライズされたフィードで、毎日 1–2 時間を節約。無料で始める。", "notify.store.default": "ストア", "notify.store.mas": "App Store", "notify.store.mss": "Microsoft Store", diff --git a/locales/app/zh-CN.json b/locales/app/zh-CN.json index 8836e2097..f285a3c5f 100644 --- a/locales/app/zh-CN.json +++ b/locales/app/zh-CN.json @@ -101,6 +101,13 @@ "discover.target.feeds": "订阅源", "discover.target.label": "搜索", "discover.target.lists": "列表", + "discover.tips.auto_detect": "自动识别输入类型", + "discover.tips.search_keyword": "支持关键词、URL、RSS 订阅源或 RSSHub 路由", + "discover.tools.description": "更多工具", + "discover.tools.import": "导入 OPML", + "discover.tools.inbox": "收件箱", + "discover.tools.transform": "HTML 转 RSS", + "discover.tools.user": "关注用户", "entry.click_to_return": "向上滚动或点击此区域返回", "entry.exit_detail": "返回时间线", "entry.scroll_up_to_exit": "向上滚动返回时间线", @@ -260,6 +267,9 @@ "feed_item.onboarding_feed": "这是一个入门引导订阅源", "login.agree_to": "继续即表示您同意我们的", "login.back": "返回", + "login.benefit_1": "每天节省 1–2 小时阅读时间", + "login.benefit_2": "让 AI 突出显示最重要的更新", + "login.benefit_3": "提供免费计划 · 无需信用卡", "login.confirm_password.label": "确认密码", "login.continueWith": "使用 {{provider}} 继续", "login.email": "邮件地址", @@ -273,10 +283,15 @@ "login.password": "密码", "login.password_optional": "可选", "login.privacy": "隐私政策", + "login.quick_start": "不到 30 秒即可开始使用。", "login.send_magic_link": "发送魔法链接", "login.signUp": "使用邮件地址注册", "login.submit": "提交", + "login.subtitle": "这款 AI RSS 阅读器为您阅读互联网,过滤噪音,呈现您真正关心的知识。", + "login.subtitle_description": "连接您的 RSS、新闻通讯和订阅源。让 AI 总结和整理真正重要的内容。", "login.terms": "服务条款", + "login.title": "欢迎使用 Folo", + "login.view_demo": "或者:先看看 Demo →", "login.with_email.title": "使用邮件地址登录", "mark_all_read_button.auto_confirm_info": "{{countdown}} 秒后自动确认。", "mark_all_read_button.confirm": "确认", @@ -337,7 +352,7 @@ "new_user_guide.intro.title": "和 AI 一起沉浸式阅读", "new_user_guide.selection.empty_description": "在 AI 对话里描述你的需求,我们会为你推荐来源。", "new_user_guide.selection.empty_title": "还没有选择任何订阅源", - "not_logged_in_notice": "您尚未登录。
请登录以同步您的订阅和设置到其他设备。", + "not_logged_in_notice": "登录以解锁 AI 驱动阅读。
通过智能摘要和个性化订阅源,每天节省 1–2 小时。免费开始。", "notify.store.default": "商店", "notify.store.mas": "App Store", "notify.store.mss": "Microsoft Store", diff --git a/locales/app/zh-TW.json b/locales/app/zh-TW.json index 5c12063ce..343f474bb 100644 --- a/locales/app/zh-TW.json +++ b/locales/app/zh-TW.json @@ -254,8 +254,11 @@ "feed_item.claimed_list": "已認領列表", "feed_item.error_since": "RSS 摘要失效:", "feed_item.not_publicly_visible": "未公開顯示於您的個人頁面", - "login.agree_to": "繼續即表示你同意我們的", + "login.agree_to": "繼續即表示您同意我們的", "login.back": "返回", + "login.benefit_1": "每天節省 1–2 小時閱讀時間", + "login.benefit_2": "讓 AI 突出顯示最重要的更新", + "login.benefit_3": "提供免費方案 · 無需信用卡", "login.confirm_password.label": "確認密碼", "login.continueWith": "透過 {{provider}} 繼續", "login.email": "電子信箱", @@ -269,10 +272,15 @@ "login.password": "密碼", "login.password_optional": "可選", "login.privacy": "隱私政策", + "login.quick_start": "不到 30 秒即可開始使用。", "login.send_magic_link": "發送魔法連結", "login.signUp": "使用電子信箱註冊", "login.submit": "送出", + "login.subtitle": "這款 AI RSS 閱讀器為您閱讀網際網路,過濾噪音,呈現您真正關心的知識。", + "login.subtitle_description": "連接您的 RSS、新聞通訊和訂閱源。讓 AI 總結和整理真正重要的內容。", "login.terms": "服務條款", + "login.title": "歡迎使用 Folo", + "login.view_demo": "或者:先看看 Demo →", "login.with_email.title": "使用電子信箱登入", "mark_all_read_button.auto_confirm_info": "將在 {{countdown}} 秒後自動確認。", "mark_all_read_button.confirm": "確認", @@ -332,6 +340,7 @@ "new_user_guide.intro.title": "和 AI 一起沉浸式閱讀", "new_user_guide.selection.empty_description": "在 AI 對話中描述您的需求,我們會推薦合適的來源。", "new_user_guide.selection.empty_title": "尚未選擇任何來源", + "not_logged_in_notice": "登入以解鎖 AI 驅動閱讀。
透過智能摘要和個人化訂閱源,每天節省 1–2 小時。免費開始。", "notify.store.default": "商店", "notify.store.mas": "App Store", "notify.store.mss": "Microsoft Store", diff --git a/locales/settings/en.json b/locales/settings/en.json index 68a5546d2..dac7e3b5c 100644 --- a/locales/settings/en.json +++ b/locales/settings/en.json @@ -240,6 +240,8 @@ "discoverFilters.title": "Discover Filters", "feeds.claim": "Claim Feeds", "feeds.claimTips": "To claim your feeds and receive tips, right-click on the feed in your subscription list and select Claim.", + "feeds.filter.all": "All ({{count}})", + "feeds.filter.rsshub": "RSSHub ({{count}})", "feeds.noFeeds": "No claimed feeds", "feeds.subscription": "Subscribed Feeds", "feeds.tableHeaders.date": "Subscribed Date", diff --git a/locales/settings/ja.json b/locales/settings/ja.json index 869653624..ae231c4d5 100644 --- a/locales/settings/ja.json +++ b/locales/settings/ja.json @@ -236,6 +236,8 @@ "discoverFilters.title": "発見フィルタ", "feeds.claim": "フィードを認証", "feeds.claimTips": "フィードを認証してチップを受け取るには、購読リストのフィードを右クリックして「フィードをクレーム」を選択してください。", + "feeds.filter.all": "すべて ({{count}})", + "feeds.filter.rsshub": "RSSHub ({{count}})", "feeds.noFeeds": "認証されたフィードはありません", "feeds.subscription": "購読済みフィード", "feeds.tableHeaders.date": "購読日", diff --git a/locales/settings/zh-CN.json b/locales/settings/zh-CN.json index c5dab244a..c3817fea2 100644 --- a/locales/settings/zh-CN.json +++ b/locales/settings/zh-CN.json @@ -235,6 +235,8 @@ "discoverFilters.title": "发现筛选", "feeds.claim": "认证订阅源", "feeds.claimTips": "要认证你的订阅源并接收打赏,请在订阅列表中右键点击订阅源并选择「认证」。", + "feeds.filter.all": "全部 ({{count}})", + "feeds.filter.rsshub": "RSSHub ({{count}})", "feeds.noFeeds": "没有已认证的订阅源", "feeds.subscription": "已订阅的订阅源", "feeds.tableHeaders.date": "订阅日期", diff --git a/locales/settings/zh-TW.json b/locales/settings/zh-TW.json index 42be8ae47..371a1057e 100644 --- a/locales/settings/zh-TW.json +++ b/locales/settings/zh-TW.json @@ -240,6 +240,8 @@ "discoverFilters.title": "發現篩選", "feeds.claim": "認領 RSS 摘要", "feeds.claimTips": "要認領您的 RSS 摘要並接收贊助,請在您的訂閱列表中右鍵點擊該 RSS 摘要,然後選擇「認領」。", + "feeds.filter.all": "全部 ({{count}})", + "feeds.filter.rsshub": "RSSHub ({{count}})", "feeds.noFeeds": "沒有已認領的 RSS 摘要", "feeds.subscription": "已訂閱的 RSS 摘要", "feeds.tableHeaders.date": "訂閱日期", diff --git a/packages/internal/components/src/ui/context-menu/context-menu.tsx b/packages/internal/components/src/ui/context-menu/context-menu.tsx index e42e4256b..459d6601d 100644 --- a/packages/internal/components/src/ui/context-menu/context-menu.tsx +++ b/packages/internal/components/src/ui/context-menu/context-menu.tsx @@ -36,7 +36,8 @@ const ContextMenuSubTrigger = ({ ( desktopImport: () => Promise<{ default: ComponentType

}>, mobileImport: () => Promise<{ default: ComponentType

}>, fallbackElement?: ReactNode, +): ComponentType

+export function withResponsiveComponent

( + desktopImport: () => Promise<{ default: ComponentType

}>, + mobileImport: () => Promise<{ default: ComponentType

}>, + breakpointFn: (w: number) => boolean, + fallbackElement?: ReactNode, +): ComponentType

+export function withResponsiveComponent

( + desktopImport: () => Promise<{ default: ComponentType

}>, + mobileImport: () => Promise<{ default: ComponentType

}>, + fallbackElementOrBreakpointFn?: ReactNode | ((w: number) => boolean), + fallbackElement?: ReactNode, ) { const LazyDesktopLayout = lazy(desktopImport) as unknown as ComponentType

const LazyMobileLayout = lazy(mobileImport) as unknown as ComponentType

+ // Check if the third parameter is a function (breakpoint function) or ReactNode (fallback) + const isBreakpointFn = typeof fallbackElementOrBreakpointFn === "function" + const breakpointFn = isBreakpointFn ? fallbackElementOrBreakpointFn : undefined + const fallback = isBreakpointFn ? fallbackElement : fallbackElementOrBreakpointFn + return function ResponsiveLayout(props: P) { - const isMobile = useMobile() + const isMobile = useViewport(({ w: viewport }) => + breakpointFn ? breakpointFn(viewport) : viewport < 1024 && viewport !== 0, + ) return ( - + {isMobile ? : } ) diff --git a/packages/internal/store/src/modules/unread/hooks.ts b/packages/internal/store/src/modules/unread/hooks.ts index 66102e72b..e584f7dda 100644 --- a/packages/internal/store/src/modules/unread/hooks.ts +++ b/packages/internal/store/src/modules/unread/hooks.ts @@ -134,7 +134,7 @@ export const useSortedCategoriesByUnread = ( Object.keys(folderUnread) .sort((a, b) => folderUnread[b]! - folderUnread[a]!) .forEach((key) => { - sortedList.push([key, categories[key]!]) + sortedList.push([key, categories[key]!.concat()]) }) if (!isDesc) { diff --git a/packages/internal/utils/src/attribution.ts b/packages/internal/utils/src/attribution.ts new file mode 100644 index 000000000..f3eb160b2 --- /dev/null +++ b/packages/internal/utils/src/attribution.ts @@ -0,0 +1,143 @@ +import { getStorageNS } from "./ns" + +const ATTRIBUTION_STORAGE_KEY = getStorageNS("attribution") + +export interface AttributionData { + utm_source?: string + utm_medium?: string + utm_campaign?: string + utm_term?: string + utm_content?: string + + // First seen at timestamp, for recording first attribution + first_seen_at?: number +} + +/** + * Extract UTM parameters from URL search params + */ +export function extractUTMParams(searchParams: URLSearchParams): Partial { + const attribution: Partial = {} + + const utmSource = searchParams.get("utm_source") + const utmMedium = searchParams.get("utm_medium") + const utmCampaign = searchParams.get("utm_campaign") + const utmTerm = searchParams.get("utm_term") + const utmContent = searchParams.get("utm_content") + + if (utmSource) attribution.utm_source = utmSource + if (utmMedium) attribution.utm_medium = utmMedium + if (utmCampaign) attribution.utm_campaign = utmCampaign + if (utmTerm) attribution.utm_term = utmTerm + if (utmContent) attribution.utm_content = utmContent + + return attribution +} + +/** + * Get attribution data from storage + */ +export function getAttributionData(): AttributionData | null { + if (typeof window === "undefined") return null + + try { + const stored = localStorage.getItem(ATTRIBUTION_STORAGE_KEY) + if (!stored) return null + return JSON.parse(stored) as AttributionData + } catch { + return null + } +} + +/** + * Save attribution data to storage (only if not already set, to preserve first attribution) + */ +export function saveAttributionData(data: Partial): AttributionData | null { + if (typeof window === "undefined") return null + + try { + const existing = getAttributionData() + const now = Date.now() + + // If we already have attribution data, don't overwrite it (preserve first attribution) + if (existing && existing.first_seen_at) { + return existing + } + + // Merge with existing data, but set first_seen_at if not present + const merged: AttributionData = { + ...existing, + ...data, + first_seen_at: existing?.first_seen_at ?? now, + } + + localStorage.setItem(ATTRIBUTION_STORAGE_KEY, JSON.stringify(merged)) + return merged + } catch { + return null + } +} + +/** + * Capture attribution from current URL (browser only) + */ +export function captureAttributionFromURL(): AttributionData | null { + try { + const url = new URL(window.location.href) + const utmParams = extractUTMParams(url.searchParams) + + // Only save if we have at least one UTM parameter + if (Object.keys(utmParams).length > 0) { + return saveAttributionData(utmParams) + } + + return getAttributionData() + } catch { + return getAttributionData() + } +} + +/** + * Capture attribution from a URL string (for deep links, etc.) + */ +export function captureAttributionFromURLString(urlString: string): AttributionData | null { + if (typeof window === "undefined") return null + + try { + const url = new URL(urlString) + const utmParams = extractUTMParams(url.searchParams) + + // Only save if we have at least one UTM parameter + if (Object.keys(utmParams).length > 0) { + return saveAttributionData(utmParams) + } + + return getAttributionData() + } catch { + return getAttributionData() + } +} + +/** + * Get attribution data formatted for analytics (user properties) + */ +export function getAttributionForAnalytics(): Record { + const attribution = getAttributionData() + if (!attribution) return {} + + const result: Record = {} + + if (attribution.utm_source) result.utm_source = attribution.utm_source + if (attribution.utm_medium) result.utm_medium = attribution.utm_medium + if (attribution.utm_campaign) result.utm_campaign = attribution.utm_campaign + if (attribution.utm_term) result.utm_term = attribution.utm_term + if (attribution.utm_content) result.utm_content = attribution.utm_content + if (attribution.first_seen_at) result.first_seen_at = attribution.first_seen_at + + // Add a computed channel field for easier filtering + if (attribution.utm_source) { + result.channel = attribution.utm_source + } + + return result +} diff --git a/packages/internal/utils/src/index.ts b/packages/internal/utils/src/index.ts index 74537c38f..bc15c47e1 100644 --- a/packages/internal/utils/src/index.ts +++ b/packages/internal/utils/src/index.ts @@ -1,3 +1,4 @@ +export * from "./attribution" export * from "./bind-this" export * from "./cjk" export * from "./color"

+ ( + + + {t("discover.any_url_or_keyword")} + + + + + + + + )} + /> + {showTargetSelector && ( + ( + +
+ + {t("discover.target.label")} + + +
+ {isMobile ? ( + + ) : ( + + + + + )} +
+
+
+ +
+ )} + /> + )} +
+ + + {/* Compact Tools */} +
+ { + present({ + title: t("discover.tools.import"), + content: () => , + modalClassName: "max-w-2xl w-full", + }) + }} + /> + { + present({ + title: t("discover.tools.transform"), + content: () => , + modalClassName: "max-w-2xl w-full", + }) + }} + /> + { + present({ + title: t("words.inbox"), + content: () => , + modalClassName: "max-w-2xl w-full", + }) + }} + /> + { + present({ + title: t("words.user"), + content: () => , + modalClassName: "max-w-2xl w-full", + }) + }} + /> +
+
+