diff --git a/apps/desktop/src/renderer/src/lib/translate.ts b/apps/desktop/src/renderer/src/lib/translate.ts index 383ff68dd..bcf602b8d 100644 --- a/apps/desktop/src/renderer/src/lib/translate.ts +++ b/apps/desktop/src/renderer/src/lib/translate.ts @@ -1,6 +1,6 @@ import { parseHtml } from "@follow/components/ui/markdown/parse-html.js" import { views } from "@follow/constants" -import type { SupportedLanguages } from "@follow/models/types" +import type { SupportedActionLanguage } from "@follow/shared" import { ACTION_LANGUAGE_MAP } from "@follow/shared" import { franc } from "franc-min" @@ -17,7 +17,7 @@ export const checkLanguage = ({ language, }: { content: string - language: SupportedLanguages + language: SupportedActionLanguage }) => { if (!content) return true const pureContent = parseHtml(content) @@ -44,7 +44,7 @@ export async function translate({ }: { entry?: FlatEntryModel | null view?: number - language?: SupportedLanguages + language?: SupportedActionLanguage extraFields?: string[] part?: string }) { diff --git a/apps/mobile/package.json b/apps/mobile/package.json index f6c604efd..ef07c517b 100644 --- a/apps/mobile/package.json +++ b/apps/mobile/package.json @@ -81,6 +81,7 @@ "expo-task-manager": "12.0.6", "expo-updates": "0.27.4", "expo-web-browser": "14.0.2", + "franc-min": "6.2.0", "hono": "4.7.5", "i18next": "24.2.3", "immer": "10.1.1", diff --git a/apps/mobile/src/lib/translation.ts b/apps/mobile/src/lib/translation.ts new file mode 100644 index 000000000..e966b633a --- /dev/null +++ b/apps/mobile/src/lib/translation.ts @@ -0,0 +1,31 @@ +import { parseHtml } from "@follow/components/src/ui/markdown/parse-html" +import type { SupportedActionLanguage } from "@follow/shared" +import { ACTION_LANGUAGE_MAP } from "@follow/shared" +import { franc } from "franc-min" + +function duplicateIfLengthLessThan(text: string, length: number) { + return text.length < length ? text.repeat(Math.ceil(length / text.length)) : text +} + +export const checkLanguage = ({ + content, + language, +}: { + content: string + language: SupportedActionLanguage +}) => { + if (!content) return true + const pureContent = parseHtml(content) + .toText() + .replaceAll(/https?:\/\/\S+|www\.\S+/g, " ") + const { code } = ACTION_LANGUAGE_MAP[language] + if (!code) { + return false + } + + const sourceLanguage = franc(duplicateIfLengthLessThan(pureContent, 20), { + only: [code], + }) + + return sourceLanguage === code +} diff --git a/apps/mobile/src/modules/entry-content/EntryContentHeaderRightActions.tsx b/apps/mobile/src/modules/entry-content/EntryContentHeaderRightActions.tsx index 97af210ad..e4f52ca91 100644 --- a/apps/mobile/src/modules/entry-content/EntryContentHeaderRightActions.tsx +++ b/apps/mobile/src/modules/entry-content/EntryContentHeaderRightActions.tsx @@ -123,10 +123,11 @@ const HeaderRightActionsImpl = ({ } const toggleAITranslation = () => { - translationSyncService.generateTranslation( + translationSyncService.generateTranslation({ entryId, - getGeneralSettings().actionLanguage as SupportedLanguages, - ) + language: getGeneralSettings().actionLanguage as SupportedLanguages, + withContent: true, + }) setShowTranslation((prev) => !prev) } diff --git a/apps/mobile/src/modules/entry-list/EntryListContentArticle.tsx b/apps/mobile/src/modules/entry-list/EntryListContentArticle.tsx index 9c5fa9249..adf98c24b 100644 --- a/apps/mobile/src/modules/entry-list/EntryListContentArticle.tsx +++ b/apps/mobile/src/modules/entry-list/EntryListContentArticle.tsx @@ -4,6 +4,7 @@ import { forwardRef, useCallback, useMemo } from "react" import { View } from "react-native" import { usePlayingUrl } from "@/src/lib/player" +import { usePrefetchEntryTranslation } from "@/src/store/translation/hooks" import { useFetchEntriesControls } from "../screen/atoms" import { TimelineSelectorList } from "../screen/TimelineSelectorList" @@ -33,10 +34,12 @@ export const EntryListContentArticle = forwardRef< [hasNextPage], ) - const { onViewableItemsChanged, onScroll } = useOnViewableItemsChanged({ + const { onViewableItemsChanged, onScroll, viewableItems } = useOnViewableItemsChanged({ disabled: active === false || isFetching, }) + usePrefetchEntryTranslation(active ? viewableItems.map((item) => item.key) : []) + return ( (({ entryIds, active, ...rest }, ref) => { const { fetchNextPage, refetch, isRefetching, hasNextPage, isFetching } = useFetchEntriesControls() - const { onViewableItemsChanged, onScroll } = useOnViewableItemsChanged({ + const { onViewableItemsChanged, onScroll, viewableItems } = useOnViewableItemsChanged({ disabled: active === false || isFetching, }) + usePrefetchEntryTranslation(active ? viewableItems.map((item) => item.key) : []) + return ( item.key) : []) + return ( (({ entryIds, active, ...rest }, ref) => { const { fetchNextPage, refetch, isRefetching, isFetching, hasNextPage } = useFetchEntriesControls() - const { onViewableItemsChanged, onScroll } = useOnViewableItemsChanged({ + const { onViewableItemsChanged, onScroll, viewableItems } = useOnViewableItemsChanged({ disabled: active === false || isFetching, }) + usePrefetchEntryTranslation(active ? viewableItems.map((item) => item.key) : []) + const ListFooterComponent = useMemo( () => hasNextPage ? ( diff --git a/apps/mobile/src/modules/entry-list/hooks.ts b/apps/mobile/src/modules/entry-list/hooks.ts index 32aceb5cf..96ce3ed64 100644 --- a/apps/mobile/src/modules/entry-list/hooks.ts +++ b/apps/mobile/src/modules/entry-list/hooks.ts @@ -19,6 +19,7 @@ export function useOnViewableItemsChanged({ const markAsReadWhenScrolling = useGeneralSettingKey("scrollMarkUnread") const markAsReadWhenRendering = useGeneralSettingKey("renderMarkUnread") + const [viewableItems, setViewableItems] = useState([]) const [lastViewableItems, setLastViewableItems] = useState() const [lastRemovedItems, setLastRemovedItems] = useState(null) @@ -28,6 +29,8 @@ export function useOnViewableItemsChanged({ viewableItems: ViewToken[] changed: ViewToken[] }) => void = useNonReactiveCallback(({ viewableItems, changed }) => { + setViewableItems(viewableItems) + debouncedFetchEntryContentByStream(viewableItems.map((item) => stableIdExtractor(item))) const removed = changed.filter((item) => !item.isViewable) @@ -86,7 +89,10 @@ export function useOnViewableItemsChanged({ lastOffset.current = currentOffset }, []) - return useMemo(() => ({ onViewableItemsChanged, onScroll }), [onScroll, onViewableItemsChanged]) + return useMemo( + () => ({ onViewableItemsChanged, onScroll, viewableItems }), + [onScroll, onViewableItemsChanged, viewableItems], + ) } function useNonReactiveCallback any>(fn: T): T { diff --git a/apps/mobile/src/screens/(stack)/entries/[entryId]/index.tsx b/apps/mobile/src/screens/(stack)/entries/[entryId]/index.tsx index cc1af2d1a..9e7ddcd20 100644 --- a/apps/mobile/src/screens/(stack)/entries/[entryId]/index.tsx +++ b/apps/mobile/src/screens/(stack)/entries/[entryId]/index.tsx @@ -18,7 +18,7 @@ import { useEntry, usePrefetchEntryDetail } from "@/src/store/entry/hooks" import { entrySyncServices } from "@/src/store/entry/store" import type { EntryWithTranslation } from "@/src/store/entry/types" import { useFeed } from "@/src/store/feed/hooks" -import { useEntryTranslation } from "@/src/store/translation/hooks" +import { useEntryTranslation, usePrefetchEntryTranslation } from "@/src/store/translation/hooks" import { useAutoMarkAsRead } from "@/src/store/unread/hooks" import { EntrySocialTitle, EntryTitle } from "../../../../modules/entry-content/EntryTitle" @@ -28,6 +28,7 @@ export const EntryDetailScreen: NavigationControllerView<{ view: FeedViewType }> = ({ entryId, view: viewType }) => { usePrefetchEntryDetail(entryId) + usePrefetchEntryTranslation([entryId], true) useAutoMarkAsRead(entryId) const entry = useEntry(entryId) const translation = useEntryTranslation(entryId) diff --git a/apps/mobile/src/store/entry/hooks.ts b/apps/mobile/src/store/entry/hooks.ts index 3bd0bc324..6b0c256b4 100644 --- a/apps/mobile/src/store/entry/hooks.ts +++ b/apps/mobile/src/store/entry/hooks.ts @@ -43,6 +43,21 @@ export function useEntry( }) } +export function useEntryList(ids: string[]): Array +export function useEntryList(ids: string[], selector: (state: EntryModel) => T): T[] | undefined +export function useEntryList( + ids: string[], + selector: (state: EntryModel) => EntryModel = defaultSelector, +) { + return useEntryStore((state) => { + return ids.map((id) => { + const entry = state.data[id] + if (!entry) return null + return selector(entry) + }) + }) +} + function sortEntryIdsByPublishDate(a: string, b: string) { const entryA = getEntry(a) const entryB = getEntry(b) diff --git a/apps/mobile/src/store/translation/hooks.ts b/apps/mobile/src/store/translation/hooks.ts index 350ebc539..4861f711d 100644 --- a/apps/mobile/src/store/translation/hooks.ts +++ b/apps/mobile/src/store/translation/hooks.ts @@ -1,20 +1,31 @@ -import { useQuery } from "@tanstack/react-query" +import { useQueries } from "@tanstack/react-query" import { useCallback } from "react" import { useGeneralSettingKey } from "@/src/atoms/settings/general" import type { SupportedLanguages } from "@/src/lib/language" -import { useEntry } from "../entry/hooks" +import { useEntryList } from "../entry/hooks" import { translationSyncService, useTranslationStore } from "./store" -export const usePrefetchEntryTranslation = (entryId: string) => { - const entry = useEntry(entryId) - const translation = useGeneralSettingKey("translation") || !!entry?.settings?.translation +export const usePrefetchEntryTranslation = (entryIds: string[], withContent?: boolean) => { + const translation = useGeneralSettingKey("translation") + const entryList = + useEntryList(entryIds) + ?.filter((entry) => entry !== null && (translation || !!entry?.settings?.translation)) + .map((entry) => entry!.id) || [] + const actionLanguage = useGeneralSettingKey("actionLanguage") as SupportedLanguages - return useQuery({ - queryKey: ["entry-translation", entryId, actionLanguage], - queryFn: () => translationSyncService.generateTranslation(entryId, actionLanguage), - enabled: translation, + + return useQueries({ + queries: entryList.map((entryId) => ({ + queryKey: ["translation", entryId, actionLanguage, withContent], + queryFn: () => + translationSyncService.generateTranslation({ + entryId, + language: actionLanguage, + withContent, + }), + })), }) } diff --git a/apps/mobile/src/store/translation/store.ts b/apps/mobile/src/store/translation/store.ts index ec3e5c1a3..0fb48895c 100644 --- a/apps/mobile/src/store/translation/store.ts +++ b/apps/mobile/src/store/translation/store.ts @@ -1,6 +1,7 @@ import type { TranslationSchema } from "@/src/database/schemas/types" import { apiClient } from "@/src/lib/api-fetch" import type { SupportedLanguages } from "@/src/lib/language" +import { checkLanguage } from "@/src/lib/translation" import { TranslationService } from "@/src/services/translation" import { getEntry } from "../entry/getter" @@ -56,15 +57,39 @@ class TranslationActions { export const translationActions = new TranslationActions() class TranslationSyncService { - async generateTranslation(entryId: string, language: SupportedLanguages) { + async generateTranslation({ + entryId, + language, + withContent, + }: { + entryId: string + language: SupportedLanguages + withContent?: boolean + }) { const entry = getEntry(entryId) if (!entry) return - const translationSession = translationActions.getTranslation(entryId, language) - if (translationSession) return translationSession + + const fields = ( + ["title", "description", ...(withContent ? ["content"] : [])] as Array< + "title" | "description" | "content" + > + ).filter((field) => { + const content = entry[field] + if (!content) return false + + if (translationSession?.[field]) return false + + return !checkLanguage({ + content, + language, + }) + }) + + if (fields.length === 0) return null const res = await apiClient.ai.translation.$get({ - query: { id: entryId, language, fields: ["title", "description", "content"].join(",") }, + query: { id: entryId, language, fields: fields.join(",") }, }) if (!res.data) return null diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 762a08389..66f96c3a2 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -943,6 +943,9 @@ importers: expo-web-browser: specifier: 14.0.2 version: 14.0.2(expo@52.0.44(@babel/core@7.26.10)(@babel/preset-env@7.26.9(@babel/core@7.26.10))(@expo/metro-runtime@4.0.1(react-native@0.77.2(@babel/core@7.26.10)(@babel/preset-env@7.26.9(@babel/core@7.26.10))(@types/react@18.3.12)(bufferutil@4.0.9)(react@18.3.1)(utf-8-validate@6.0.5)))(bufferutil@4.0.9)(encoding@0.1.13)(graphql@16.8.1)(react-native-webview@13.13.5(react-native@0.77.2(@babel/core@7.26.10)(@babel/preset-env@7.26.9(@babel/core@7.26.10))(@types/react@18.3.12)(bufferutil@4.0.9)(react@18.3.1)(utf-8-validate@6.0.5))(react@18.3.1))(react-native@0.77.2(@babel/core@7.26.10)(@babel/preset-env@7.26.9(@babel/core@7.26.10))(@types/react@18.3.12)(bufferutil@4.0.9)(react@18.3.1)(utf-8-validate@6.0.5))(react@18.3.1)(utf-8-validate@6.0.5))(react-native@0.77.2(@babel/core@7.26.10)(@babel/preset-env@7.26.9(@babel/core@7.26.10))(@types/react@18.3.12)(bufferutil@4.0.9)(react@18.3.1)(utf-8-validate@6.0.5)) + franc-min: + specifier: 6.2.0 + version: 6.2.0 hono: specifier: 4.7.5 version: 4.7.5(patch_hash=5c74c2d2afaa5880c13d75458dd26c84da568851691b1fb6de6d877c29936d05)