diff --git a/apps/desktop/changelog/1.2.1.md b/apps/desktop/changelog/1.2.1.md new file mode 100644 index 000000000..cf5454733 --- /dev/null +++ b/apps/desktop/changelog/1.2.1.md @@ -0,0 +1,40 @@ +# What's new in v1.2.1 + +## Shiny new things + +- **AI** + - Added **BYOK (Bring Your Own Key)** support — choose your own AI provider freely. + - Improved **AI Memory**: you can now update or refine past memories whenever you need. + - Reduced the “guiding tone” in **AI Summary** so summaries feel more natural and personal. + - Introduced **AI Timeline Sort (Beta)**: your timeline can now rearrange itself based on your reading preferences. + +![](https://cdn.follow.is/ai-memory.mp4) + +![](https://cdn.follow.is/share.mp4) + +- **UI** + - Several UI components have been refined with an improved design system for a cleaner, more consistent feel. + +- **Subscription** + - Added a new **Basic Plan (non-AI version)** for users who prefer a lighter subscription option. + +- **Selection** + - Added **underline sharing** and **Ask AI** directly from selected text to make reading actions smoother. + +## Improvements + +- **Feed** + - RSSHub subscriptions now include a clear identifier, making source management easier. + +- **Web** + - You can now browse recommended content without logging in — explore before committing. + +- **Onboarding** + - The onboarding flow has been fully redesigned for a smoother, more intuitive first-time experience. + +- **Entry** + - Entries now come with AI-generated labels to help you sort and revisit content effortlessly. + +## No longer broken + +We fixed several bugs to make everything feel more stable and reliable. diff --git a/apps/desktop/changelog/next.md b/apps/desktop/changelog/next.md index 78d6ab5b0..8f5eac449 100644 --- a/apps/desktop/changelog/next.md +++ b/apps/desktop/changelog/next.md @@ -2,9 +2,10 @@ ## Shiny new things -- Onboarding: Re-designed the onboarding flow -- AI: - - Supports BYOK (Bring Your Own Key) - - AI Memory tool has been improved, now can update your past memories -- UI: - - The design system of some UI components has been improved +## Improvements + +## No longer broken + +## Thanks + +Special thanks to volunteer contributors @ for their valuable contributions 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 94b0cc244..10ca607e7 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 @@ -18,7 +18,7 @@ const styles = { } as React.CSSProperties, innerGlow: { background: - "linear-gradient(to bottom right, hsl(var(--fo-a) / 0.05), transparent, hsl(var(--fo-a) / 0.05))", + "linear-gradient(to bottom right, hsl(var(--fo-a) / 0.01), transparent, hsl(var(--fo-a) / 0.01))", } as React.CSSProperties, } diff --git a/apps/desktop/layer/renderer/src/components/ui/media/Media.tsx b/apps/desktop/layer/renderer/src/components/ui/media/Media.tsx index c2f54629d..34ca3c3fb 100644 --- a/apps/desktop/layer/renderer/src/components/ui/media/Media.tsx +++ b/apps/desktop/layer/renderer/src/components/ui/media/Media.tsx @@ -1,5 +1,4 @@ import { nextFrame } from "@follow/utils/dom" -import { getImageProxyUrl } from "@follow/utils/img-proxy" import { cn } from "@follow/utils/utils" import { ErrorBoundary } from "@sentry/react" import { useForceUpdate } from "motion/react" @@ -9,6 +8,7 @@ import { memo, use, useEffect, useMemo, useRef, useState } from "react" import { Blurhash, BlurhashCanvas } from "react-blurhash" import { useEventCallback } from "usehooks-ts" +import { useGetImageProxyUrl } from "~/lib/img-proxy" import { saveImageDimensionsToDb } from "~/store/image/db" import { useMediaContainerWidth, usePreviewMedia } from "./hooks" @@ -77,6 +77,7 @@ const MediaImpl: FC = ({ videoClassName, ...rest } = props + const getImageProxyUrl = useGetImageProxyUrl() const ctxMediaInfo = use(MediaInfoRecordContext) const ctxHeight = ctxMediaInfo[src!]?.height @@ -121,7 +122,7 @@ const MediaImpl: FC = ({ } return sources - }, [src, proxy, preferOrigin]) + }, [src, proxy, preferOrigin, getImageProxyUrl]) const [currentSourceIndex, setCurrentSourceIndex] = useState(0) const [isError, setIsError] = useState(false) diff --git a/apps/desktop/layer/renderer/src/components/ui/media/PreviewMediaContent.tsx b/apps/desktop/layer/renderer/src/components/ui/media/PreviewMediaContent.tsx index b9237ac30..a85e576da 100644 --- a/apps/desktop/layer/renderer/src/components/ui/media/PreviewMediaContent.tsx +++ b/apps/desktop/layer/renderer/src/components/ui/media/PreviewMediaContent.tsx @@ -18,7 +18,7 @@ import { m } from "~/components/common/Motion" import { GlassButton } from "~/components/ui/button/GlassButton" import { COPY_MAP } from "~/constants" import { ipcServices } from "~/lib/client" -import { replaceImgUrlIfNeed } from "~/lib/img-proxy" +import { useReplaceImgUrlIfNeed } from "~/lib/img-proxy" import { useCurrentModal } from "../modal/stacked/hooks" import type { VideoPlayerRef } from "./VideoPlayer" @@ -421,6 +421,7 @@ const FallbackableImage: FC< onZoomChange?: (isZoomed: boolean) => void } > = ({ src, fallbackUrl, containerClassName, onZoomChange, loading }) => { + const replaceImgUrlIfNeed = useReplaceImgUrlIfNeed() const [currentSrc, setCurrentSrc] = useState(() => replaceImgUrlIfNeed(src)) const [isAllError, setIsAllError] = useState(false) diff --git a/apps/desktop/layer/renderer/src/components/ui/media/hooks.tsx b/apps/desktop/layer/renderer/src/components/ui/media/hooks.tsx index a0e6cfa51..236292374 100644 --- a/apps/desktop/layer/renderer/src/components/ui/media/hooks.tsx +++ b/apps/desktop/layer/renderer/src/components/ui/media/hooks.tsx @@ -1,8 +1,6 @@ import { isMobile } from "@follow/components/hooks/useMobile.js" import { use, useCallback } from "react" -import { replaceImgUrlIfNeed } from "~/lib/img-proxy" - import { PlainModal } from "../modal/stacked/custom-modal" import { useModalStack } from "../modal/stacked/hooks" import { MediaContainerWidthContext } from "./MediaContainerWidthContext" @@ -17,7 +15,7 @@ export const usePreviewMedia = (children?: React.ReactNode) => { return } if (isMobile()) { - window.open(replaceImgUrlIfNeed(media[initialIndex]!.url)) + window.open(media[initialIndex]!.url) return } present({ diff --git a/apps/desktop/layer/renderer/src/components/ui/modal/stacked/modal.tsx b/apps/desktop/layer/renderer/src/components/ui/modal/stacked/modal.tsx index 988ea6861..1201fc53a 100644 --- a/apps/desktop/layer/renderer/src/components/ui/modal/stacked/modal.tsx +++ b/apps/desktop/layer/renderer/src/components/ui/modal/stacked/modal.tsx @@ -369,14 +369,6 @@ export const ModalInternal = memo(function Modal({ cursor: "grabbing", }} > - {/* Inner glow layer */} -
{ - const virtualId = `integration:custom:${integration.id}` as FollowCommandId + const virtualId = `integration:custom:${integration.id}` as UnknownCommand["id"] return new EntryActionMenuItem({ id: virtualId, onClick: () => { diff --git a/apps/desktop/layer/renderer/src/hooks/biz/useFeedActions.tsx b/apps/desktop/layer/renderer/src/hooks/biz/useFeedActions.tsx index 6ea997819..7aeb473b8 100644 --- a/apps/desktop/layer/renderer/src/hooks/biz/useFeedActions.tsx +++ b/apps/desktop/layer/renderer/src/hooks/biz/useFeedActions.tsx @@ -331,6 +331,15 @@ export const useListActions = ({ listId, view }: { listId: string; view?: FeedVi if (!list) return [] const items: MenuItemInput[] = [ + new MenuItemText({ + label: t("sidebar.feed_actions.mark_all_as_read"), + shortcut: shortcuts[COMMAND_ID.subscription.markAllAsRead], + click: () => { + unreadSyncService.markFeedAsRead(list.feedIds) + }, + requiresLogin: true, + }), + MenuItemSeparator.default, new MenuItemText({ label: t("sidebar.feed_actions.edit"), shortcut: "E", @@ -349,15 +358,6 @@ export const useListActions = ({ listId, view }: { listId: string; view?: FeedVi requiresLogin: true, }), MenuItemSeparator.default, - new MenuItemText({ - label: t("sidebar.feed_actions.mark_all_as_read"), - shortcut: shortcuts[COMMAND_ID.subscription.markAllAsRead], - click: () => { - unreadSyncService.markFeedAsRead(list.feedIds) - }, - requiresLogin: true, - }), - MenuItemSeparator.default, ...(list.ownerUserId === whoami()?.id ? [ new MenuItemText({ diff --git a/apps/desktop/layer/renderer/src/lib/clipboard.ts b/apps/desktop/layer/renderer/src/lib/clipboard.ts index 4807060c2..33392f98d 100644 --- a/apps/desktop/layer/renderer/src/lib/clipboard.ts +++ b/apps/desktop/layer/renderer/src/lib/clipboard.ts @@ -22,3 +22,30 @@ export const readFromClipboard = async (): Promise => { throw new Error(message) } } + +export const copyImageToClipboard = async (canvas: HTMLCanvasElement): Promise => { + return new Promise((resolve, reject) => { + canvas.toBlob(async (blob) => { + if (!blob) { + const error = new Error("Failed to create image blob") + reject(error) + return + } + + try { + await navigator.clipboard.write([ + new ClipboardItem({ + [blob.type]: blob, + }), + ]) + resolve() + } catch (e) { + const message = + "Unable to copy image to clipboard. Please ensure clipboard permissions are granted." + console.error(e) + toast.error(message) + reject(new Error(message)) + } + }, "image/png") + }) +} diff --git a/apps/desktop/layer/renderer/src/lib/img-proxy.ts b/apps/desktop/layer/renderer/src/lib/img-proxy.ts index b186c51d0..273d53fc0 100644 --- a/apps/desktop/layer/renderer/src/lib/img-proxy.ts +++ b/apps/desktop/layer/renderer/src/lib/img-proxy.ts @@ -1,9 +1,40 @@ import { WEB_BUILD } from "@follow/shared/constants" -import { replaceImgUrlIfNeed as replaceImgUrlIfNeedUtils } from "@follow/utils/img-proxy" +import { useUserRole } from "@follow/store/user/hooks" +import { + getImageProxyUrl as getImageProxyUrlUtils, + replaceImgUrlIfNeed as replaceImgUrlIfNeedUtils, +} from "@follow/utils/img-proxy" -export const replaceImgUrlIfNeed = (url?: string) => { - return replaceImgUrlIfNeedUtils({ - url, - inBrowser: WEB_BUILD, - }) +import { useServerConfigs } from "~/atoms/server-configs" + +export const useCanUseImageProxy = () => { + const userRole = useUserRole() + const serverConfig = useServerConfigs() + const canUseProxy = + !userRole || + serverConfig?.PAYMENT_PLAN_LIST.find((i) => i.role === userRole)?.limit.SECURE_IMAGE_PROXY + return canUseProxy +} + +export const useReplaceImgUrlIfNeed = () => { + const canUseProxy = useCanUseImageProxy() + + return (url?: string) => { + return replaceImgUrlIfNeedUtils({ + url, + inBrowser: WEB_BUILD, + canUseProxy, + }) + } +} + +export const useGetImageProxyUrl = () => { + const canUseProxy = useCanUseImageProxy() + + return (params: Omit[0], "canUseProxy">) => { + return getImageProxyUrlUtils({ + canUseProxy, + ...params, + }) + } } diff --git a/apps/desktop/layer/renderer/src/lib/simple-text-selection.ts b/apps/desktop/layer/renderer/src/lib/simple-text-selection.ts index 57c3871a5..00328207e 100644 --- a/apps/desktop/layer/renderer/src/lib/simple-text-selection.ts +++ b/apps/desktop/layer/renderer/src/lib/simple-text-selection.ts @@ -2,9 +2,19 @@ * Simple text selection utilities for ShadowDOM */ +export interface SelectionRect { + top: number + right: number + bottom: number + left: number + width: number + height: number +} + export interface TextSelectionEvent { selectedText: string timestamp: number + rect: SelectionRect } /** @@ -28,21 +38,23 @@ export function addTextSelectionListener( try { const range = selection.getRangeAt(0) if (!shadowRoot.contains(range.commonAncestorContainer)) return + + if (!selection.isCollapsed) { + const selectedText = selection.toString().trim() + if (selectedText) { + onTextSelect({ + selectedText, + timestamp: Date.now(), + rect: normalizeRect(range.getBoundingClientRect()), + }) + } + return + } } catch { // Uncaught IndexSizeError: Failed to execute 'getRangeAt' on 'Selection': 0 is not a valid index. return } - if (!selection.isCollapsed) { - const selectedText = selection.toString().trim() - if (selectedText) { - onTextSelect({ - selectedText, - timestamp: Date.now(), - }) - } - } else { - onSelectionClear?.() - } + onSelectionClear?.() }, 200) } @@ -53,3 +65,14 @@ export function addTextSelectionListener( document.removeEventListener("selectionchange", handleSelectionChange) } } + +function normalizeRect(rect: DOMRect | DOMRectReadOnly): SelectionRect { + return { + top: rect.top, + right: rect.right, + bottom: rect.bottom, + left: rect.left, + width: rect.width, + height: rect.height, + } +} diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat-session/service.ts b/apps/desktop/layer/renderer/src/modules/ai-chat-session/service.ts index 3701d6246..1317f16e0 100644 --- a/apps/desktop/layer/renderer/src/modules/ai-chat-session/service.ts +++ b/apps/desktop/layer/renderer/src/modules/ai-chat-session/service.ts @@ -85,21 +85,23 @@ class AIChatSessionServiceStatic { force?: boolean }, ): Promise { - const [dbSession, hasPersistedMessages] = await Promise.all([ + const [dbSession, hasPersistedMessages, needsMetadataBackfill] = await Promise.all([ AIPersistService.getChatSession(session.chatId), AIPersistService.hasPersistedMessages(session.chatId), + AIPersistService.hasAssistantMessagesMissingMetadata(session.chatId), ]) const lastUpdatedAt = dbSession ? dbSession.updatedAt : new Date(0) const hasUpToDateSession = lastUpdatedAt >= new Date(session.updatedAt) - if (!options?.force && hasUpToDateSession && hasPersistedMessages) { + if (!options?.force && hasUpToDateSession && hasPersistedMessages && !needsMetadataBackfill) { // If local session is already up-to-date, skip fetching messages return } + const referenceLastSeenAt = session.lastSeenAt ? new Date(session.lastSeenAt) : new Date(0) const unseenMessages = await this.fetchUnseenRemoteMessages( session.chatId, - new Date(session.lastSeenAt), + needsMetadataBackfill ? new Date(0) : referenceLastSeenAt, ) const normalized = unseenMessages.map(this.normalizeRemoteMessage) diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/ChatHistoryDropdown.tsx b/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/ChatHistoryDropdown.tsx index ca21ddde9..5e3392922 100644 --- a/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/ChatHistoryDropdown.tsx +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/ChatHistoryDropdown.tsx @@ -160,8 +160,7 @@ export const ChatHistoryDropdown = ({ session={session} onClick={() => handleSessionSelect(session)} onDelete={(e) => { - setLoadingChatId(session.chatId) - handleDeleteSession(session.chatId, e).finally(() => { + handleDeleteSession(session.chatId, { event: e }).finally(() => { setLoadingChatId(null) }) }} @@ -183,8 +182,10 @@ export const ChatHistoryDropdown = ({ session={session} onClick={() => handleSessionSelect(session)} onDelete={(e) => { - setLoadingChatId(session.chatId) - handleDeleteSession(session.chatId, e).finally(() => { + handleDeleteSession(session.chatId, { + event: e, + onBeforeDelete: () => setLoadingChatId(session.chatId), + }).finally(() => { setLoadingChatId(null) }) }} diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/ChatInput.tsx b/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/ChatInput.tsx index 7ffa01060..3444267d3 100644 --- a/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/ChatInput.tsx +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/ChatInput.tsx @@ -15,7 +15,7 @@ import { COMMAND_ID } from "~/modules/command/commands/id" import { getCommand } from "~/modules/command/hooks/use-command" import { useCommandShortcut } from "~/modules/command/hooks/use-command-binding" -import { FileUploadPlugin, MentionPlugin, ShortcutPlugin } from "../../editor" +import { FileUploadPlugin, MentionPlugin, SelectedTextPlugin, ShortcutPlugin } from "../../editor" import { useMainEntryId } from "../../hooks/useMainEntryId" import { AIPanelRefsContext } from "../../store/AIChatContext" import { useChatActions, useChatScene, useChatStatus } from "../../store/hooks" @@ -173,7 +173,9 @@ export const ChatInput = memo( onKeyDown={handleKeyDown} autoFocus plugins={ - scene === "onboarding" ? [] : [MentionPlugin, ShortcutPlugin, FileUploadPlugin] + scene === "onboarding" + ? [] + : [MentionPlugin, ShortcutPlugin, FileUploadPlugin, SelectedTextPlugin] } namespace="AIChatRichEditor" /> diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/ChatInterface.tsx b/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/ChatInterface.tsx index fb9358d83..9c239170a 100644 --- a/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/ChatInterface.tsx +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/ChatInterface.tsx @@ -1,16 +1,21 @@ import { useFocusable } from "@follow/components/common/Focusable/hooks.js" +import type { LexicalRichEditorRef } from "@follow/components/ui/lexical-rich-editor/types.js" import { convertLexicalToMarkdown, getEditorStateJSONString, } from "@follow/components/ui/lexical-rich-editor/utils.js" +import { isFreeRole } from "@follow/constants" import { getCategoryFeedIds } from "@follow/store/subscription/getter" import { usePrefetchSummary } from "@follow/store/summary/hooks" +import { useUserRole } from "@follow/store/user/hooks" import { tracker } from "@follow/tracker" import { detectIsEditableElement, nextFrame } from "@follow/utils" +import type { ConfigResponse } from "@follow-app/client-sdk" import { ErrorBoundary } from "@sentry/react" import type { EditorState } from "lexical" import { createEditor } from "lexical" import { nanoid } from "nanoid" +import type { RefObject } from "react" import { use, useEffect, useMemo, useRef, useState } from "react" import { useEventCallback, useEventListener } from "usehooks-ts" @@ -56,31 +61,14 @@ const ChatInterfaceContent = ({ centerInputOnEmpty }: ChatInterfaceProps) => { const error = useChatError() const messages = useMessages() const { ensureLogin } = useRequireLogin() + const userRole = useUserRole() - const isFocusWithIn = useFocusable() + const isFocusWithin = useFocusable() const aiPanelRefs = use(AIPanelRefsContext) - useEventListener("keydown", (e) => { - if (isFocusWithIn) { - const currentActiveElement = document.activeElement - - if (detectIsEditableElement(currentActiveElement as HTMLElement)) { - return - } - - if (e.shiftKey || e.metaKey || e.ctrlKey) { - return - } - aiPanelRefs.inputRef?.current?.focus() - } - }) - - useEffect(() => { - if (error) { - console.error("AIChat Error:", error) - } - }, [error]) + useChatInputFocusHandler(isFocusWithin, aiPanelRefs.inputRef) + useLogChatError(error) const currentChatId = useCurrentChatId() const mainEntryId = useMainEntryId() @@ -93,15 +81,16 @@ const ChatInterfaceContent = ({ centerInputOnEmpty }: ChatInterfaceProps) => { enabled: !!mainEntryId && !hasMessages, }) - const [scrollAreaRef, setScrollAreaRef] = useState(null) - const [messageContainerMinHeight, setMessageContainerMinHeight] = useState() - const previousMinHeightRef = useRef(0) - const messagesContentRef = useRef(null) - - useEffect(() => { - setMessageContainerMinHeight(undefined) - previousMinHeightRef.current = 0 - }, [currentChatId]) + const { + scrollAreaRef, + setScrollAreaRef, + messageContainerMinHeight, + messagesContentRef, + scrollContainerParentRef, + captureContentHeightBeforeSend, + handleScrollPositioning, + updateContentHeightSnapshot, + } = useChatScroller(currentChatId) const { isLoading: isLoadingHistory, isSyncingRemote } = useLoadMessages(currentChatId || "", { onLoad: () => { @@ -120,27 +109,7 @@ const ChatInterfaceContent = ({ centerInputOnEmpty }: ChatInterfaceProps) => { const autoScrollWhenStreaming = useAISettingKey("autoScrollWhenStreaming") - const { shouldShowInterruptionNotice, lastUserMessage } = useMemo(() => { - if (messages.length === 0) { - return { - shouldShowInterruptionNotice: false, - lastUserMessage: null as BizUIMessage | null, - } - } - - const lastMessage = messages.at(-1)! - - const shouldShow = - lastMessage.role === "user" && - status !== "streaming" && - status !== "error" && - status !== "submitted" - - return { - shouldShowInterruptionNotice: shouldShow, - lastUserMessage: shouldShow ? lastMessage : null, - } - }, [messages, status]) + const { shouldShowInterruptionNotice, lastUserMessage } = useInterruptionNotice(messages, status) const { resetScrollState } = useAutoScroll( scrollAreaRef, @@ -149,32 +118,6 @@ const ChatInterfaceContent = ({ centerInputOnEmpty }: ChatInterfaceProps) => { const blockActions = useBlockActions() - const scrollHeightBeforeSendingRef = useRef(0) - const scrollContainerParentRef = useRef(null) - const handleScrollPositioning = useEventCallback(() => { - const $scrollContainerParent = scrollContainerParentRef.current - if (!scrollAreaRef || !$scrollContainerParent) return - - const parentClientHeight = $scrollContainerParent.clientHeight - // Use actual content height captured before send (messages container height), not inflated by minHeight - const currentScrollHeight = scrollHeightBeforeSendingRef.current - - // Calculate new minimum height based on actual content height - // Use previousMinHeightRef which tracks the real content height, not reserved space - const baseHeight = Math.max(previousMinHeightRef.current, currentScrollHeight) - const newMinHeight = baseHeight + parentClientHeight - 250 - - setMessageContainerMinHeight(newMinHeight) - - // Scroll to the end immediately to position user message at top - nextFrame(() => { - scrollAreaRef.scrollTo({ - top: scrollAreaRef.scrollHeight, - behavior: "instant", - }) - }) - }) - const staticEditor = useMemo(() => { return createEditor({ nodes: LexicalAIEditorNodes, @@ -244,8 +187,7 @@ const ChatInterfaceContent = ({ centerInputOnEmpty }: ChatInterfaceProps) => { }) } - // Capture actual content height (messages container), not including reserved minHeight - scrollHeightBeforeSendingRef.current = messagesContentRef.current?.scrollHeight ?? 0 + captureContentHeightBeforeSend() const messageId = prefixMessageIdWithShortcut(nanoid(), shortcutIdFromMessage) const sendMessage: SendingUIMessage = { parts, @@ -256,9 +198,7 @@ const ChatInterfaceContent = ({ centerInputOnEmpty }: ChatInterfaceProps) => { tracker.aiChatMessageSent() // Clear draft message after sending - if (currentChatId) { - draftMessages.delete(currentChatId) - } + clearDraft() nextFrame(() => { // Calculate and adjust scroll positioning immediately @@ -285,7 +225,7 @@ const ChatInterfaceContent = ({ centerInputOnEmpty }: ChatInterfaceProps) => { const retryShortcutId = extractShortcutIdFromMessageParts(retryMessage.parts) retryMessage.id = prefixMessageIdWithShortcut(retryMessage.id, retryShortcutId) - scrollHeightBeforeSendingRef.current = messagesContentRef.current?.scrollHeight ?? 0 + captureContentHeightBeforeSend() chatActions.popMessage() void chatActions.sendMessage(retryMessage) @@ -296,15 +236,7 @@ const ChatInterfaceContent = ({ centerInputOnEmpty }: ChatInterfaceProps) => { }) }) - // Save draft message when input changes - const handleDraftChange = useEventCallback((editorState: EditorState) => { - if (currentChatId) { - draftMessages.set(currentChatId, editorState) - } - }) - - // Get initial draft message for current chat - const initialDraft = currentChatId ? draftMessages.get(currentChatId) : undefined + const { handleDraftChange, initialDraft, clearDraft } = useChatDraft(currentChatId) const [bottomPanelHeight, setBottomPanelHeight] = useState(0) @@ -317,23 +249,20 @@ const ChatInterfaceContent = ({ centerInputOnEmpty }: ChatInterfaceProps) => { // This avoids CLS while ensuring next calculation is based on actual content if (status === "ready" && scrollAreaRef && messagesContentRef.current) { // Update the reference to actual content height for next calculation (use messages container) - previousMinHeightRef.current = messagesContentRef.current.scrollHeight + updateContentHeightSnapshot() // Keep the current minHeight unchanged to avoid CLS } - }, [status, resetScrollState, messageContainerMinHeight, scrollAreaRef]) + }, [status, resetScrollState, scrollAreaRef, updateContentHeightSnapshot, messagesContentRef]) const { handleScroll } = useAttachScrollBeyond() const { data: configuration } = useAIConfiguration() + const shouldHideResetDetails = userRole ? isFreeRole(userRole) : false - const isRateLimited = useMemo( - () => computeIsRateLimited(error, configuration), - [error, configuration], - ) - - const rateLimitMessage = useMemo( - () => computeRateLimitMessage(error, configuration), - [error, configuration], + const { isRateLimited, rateLimitMessage } = useRateLimitInfo( + error, + configuration, + shouldHideResetDetails, ) return ( @@ -381,3 +310,159 @@ export const ChatInterface = (props: ChatInterfaceProps) => ( ) + +const useChatInputFocusHandler = ( + isFocusWithin: boolean, + inputRef?: RefObject, +) => { + useEventListener("keydown", (event) => { + if (!isFocusWithin) { + return + } + const currentActiveElement = document.activeElement + + if (detectIsEditableElement(currentActiveElement as HTMLElement)) { + return + } + + if (event.shiftKey || event.metaKey || event.ctrlKey) { + return + } + + inputRef?.current?.focus() + }) +} + +const useLogChatError = (error: unknown) => { + useEffect(() => { + if (error) { + console.error("AIChat Error:", error) + } + }, [error]) +} + +const useInterruptionNotice = ( + messages: BizUIMessage[], + status: ReturnType, +) => { + return useMemo(() => { + if (messages.length === 0) { + return { + shouldShowInterruptionNotice: false, + lastUserMessage: null as BizUIMessage | null, + } + } + + const lastMessage = messages.at(-1)! + const shouldShow = + lastMessage.role === "user" && + status !== "streaming" && + status !== "error" && + status !== "submitted" + + return { + shouldShowInterruptionNotice: shouldShow, + lastUserMessage: shouldShow ? lastMessage : null, + } + }, [messages, status]) +} + +const useChatDraft = (currentChatId?: string | null) => { + const handleDraftChange = useEventCallback((editorState: EditorState) => { + if (currentChatId) { + draftMessages.set(currentChatId, editorState) + } + }) + + const clearDraft = useEventCallback(() => { + if (currentChatId) { + draftMessages.delete(currentChatId) + } + }) + + const initialDraft = currentChatId ? draftMessages.get(currentChatId) : undefined + + return { + handleDraftChange, + initialDraft, + clearDraft, + } +} + +const useRateLimitInfo = ( + error: Error | string | undefined, + configuration: ConfigResponse | undefined, + shouldHideResetDetails: boolean, +) => { + const isRateLimited = useMemo( + () => computeIsRateLimited(error, configuration), + [error, configuration], + ) + + const rateLimitMessage = useMemo( + () => + computeRateLimitMessage(error, configuration, { + hideResetDetails: shouldHideResetDetails, + }), + [error, configuration, shouldHideResetDetails], + ) + + return { + isRateLimited, + rateLimitMessage, + } +} + +const useChatScroller = (currentChatId?: string | null) => { + const [scrollAreaRef, setScrollAreaRef] = useState(null) + const [messageContainerMinHeight, setMessageContainerMinHeight] = useState() + const messagesContentRef = useRef(null) + const scrollContainerParentRef = useRef(null) + const scrollHeightBeforeSendingRef = useRef(0) + const previousMinHeightRef = useRef(0) + + useEffect(() => { + setMessageContainerMinHeight(undefined) + previousMinHeightRef.current = 0 + }, [currentChatId]) + + const captureContentHeightBeforeSend = useEventCallback(() => { + scrollHeightBeforeSendingRef.current = messagesContentRef.current?.scrollHeight ?? 0 + }) + + const handleScrollPositioning = useEventCallback(() => { + const $scrollContainerParent = scrollContainerParentRef.current + if (!scrollAreaRef || !$scrollContainerParent) return + + const parentClientHeight = $scrollContainerParent.clientHeight + const currentScrollHeight = scrollHeightBeforeSendingRef.current + const baseHeight = Math.max(previousMinHeightRef.current, currentScrollHeight) + const newMinHeight = baseHeight + parentClientHeight - 250 + + setMessageContainerMinHeight(newMinHeight) + + nextFrame(() => { + scrollAreaRef.scrollTo({ + top: scrollAreaRef.scrollHeight, + behavior: "instant", + }) + }) + }) + + const updateContentHeightSnapshot = useEventCallback(() => { + if (scrollAreaRef && messagesContentRef.current) { + previousMinHeightRef.current = messagesContentRef.current.scrollHeight + } + }) + + return { + scrollAreaRef, + setScrollAreaRef, + messageContainerMinHeight, + messagesContentRef, + scrollContainerParentRef, + captureContentHeightBeforeSend, + handleScrollPositioning, + updateContentHeightSnapshot, + } +} diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/TaskReportDropdown.tsx b/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/TaskReportDropdown.tsx index 62eb6d22a..01708df67 100644 --- a/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/TaskReportDropdown.tsx +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/TaskReportDropdown.tsx @@ -111,8 +111,10 @@ export const TaskReportDropdown = ({ triggerElement, asChild = true }: TaskRepor session={session} onClick={() => handleSessionSelect(session)} onDelete={(e) => { - setLoadingChatId(session.chatId) - handleDeleteSession(session.chatId, e).finally(() => { + handleDeleteSession(session.chatId, { + event: e, + onBeforeDelete: () => setLoadingChatId(session.chatId), + }).finally(() => { setLoadingChatId(null) }) }} diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/shared/ChatSessionComponents.tsx b/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/shared/ChatSessionComponents.tsx index 1d5d79d66..d20b831bb 100644 --- a/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/shared/ChatSessionComponents.tsx +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/components/layouts/shared/ChatSessionComponents.tsx @@ -21,12 +21,12 @@ export interface EmptyStateProps { icon?: ReactNode } -// Components export const SessionItem = ({ session, onClick, onDelete, - isLoading, + + isLoading = false, hasUnread = false, }: SessionItemProps) => { const hasUnreadMessages = isUnreadSession(session) @@ -56,8 +56,8 @@ export const SessionItem = ({ - {message.metadata && ( - - - - )} + + +
)}
diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/TokenUsagePill.tsx b/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/TokenUsagePill.tsx index 6e7bd5dfd..4a382e070 100644 --- a/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/TokenUsagePill.tsx +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/TokenUsagePill.tsx @@ -4,8 +4,11 @@ import { TooltipPortal, TooltipTrigger, } from "@follow/components/ui/tooltip/index.js" +import { isFreeRole } from "@follow/constants" +import { useUserRole } from "@follow/store/user/hooks" import type { BizUIMetadata } from "@folo-services/ai-tools" import * as React from "react" +import { useTranslation } from "react-i18next" import { formatTokenCountString } from "~/modules/settings/tabs/ai/usage/utils" @@ -20,100 +23,145 @@ const formatDuration = (ms: number): string => { return `${ms}ms` } -export const TokenUsagePill: React.FC = ({ metadata, children }) => { - if (!metadata) return null +interface ModelInfoSectionProps { + metadata: BizUIMetadata +} - const hasReasoningTokens = metadata.reasoningTokens != null && metadata.reasoningTokens > 0 - const hasCachedInputTokens = metadata.cachedInputTokens != null && metadata.cachedInputTokens > 0 +const ModelInfoSection: React.FC = ({ metadata }) => { + const { t } = useTranslation("ai") + const hasProviderInfo = metadata.provider != null || metadata.providerType != null + + return ( + <> +
+
{t("token_usage_pill.model_info")}
+
+ {metadata.modelUsed ?? t("token_usage_pill.unknown")} +
+
+ {hasProviderInfo && ( +
+
{t("token_usage_pill.provider_info")}
+
+ {metadata.provider ?? t("token_usage_pill.unknown")} + {metadata.providerType && ( + + ( + + {metadata.providerType === "byok" + ? t("token_usage_pill.byok") + : t("token_usage_pill.system")} + + ) + + )} +
+
+ )} + + ) +} + +interface FreeUserTokenUsageProps { + metadata: BizUIMetadata +} + +const FreeUserTokenUsage: React.FC = ({ metadata }) => { + const { t } = useTranslation("ai") + const summarizedTokens = + metadata.billedTokens ?? + metadata.totalTokens ?? + metadata.outputTokens ?? + metadata.contextTokens ?? + null + + return ( + <> + +
+
{t("token_usage_pill.credits_usage")}
+
+ {t("token_usage_pill.credits")}: + + {summarizedTokens != null ? formatTokenCountString(summarizedTokens) : "—"} + +
+
+ + ) +} + +interface NormalUserTokenUsageProps { + metadata: BizUIMetadata +} + +const NormalUserTokenUsage: React.FC = ({ metadata }) => { + const { t } = useTranslation("ai") const hasBillingMultiplier = metadata.billingMultiplier != null && metadata.billingMultiplier !== 1 const hasDuration = metadata.duration != null + return ( + <> + +
+
{t("token_usage_pill.credits_usage")}
+
+ {metadata.totalTokens != null && ( +
+ {t("token_usage_pill.total")}: + + {formatTokenCountString(metadata.totalTokens)} + +
+ )} + {metadata.billedTokens != null && ( +
+ {t("token_usage_pill.billed")}: + {formatTokenCountString(metadata.billedTokens)} +
+ )} +
+ {(hasDuration || hasBillingMultiplier) && ( + <> +
+
+ {hasDuration && ( +
+ {t("token_usage_pill.duration")}: + {formatDuration(metadata.duration!)} +
+ )} + {hasBillingMultiplier && ( +
+ {t("token_usage_pill.multiplier")}: + {metadata.billingMultiplier!}× +
+ )} +
+ + )} +
+ + ) +} + +export const TokenUsagePill: React.FC = ({ metadata, children }) => { + const userRole = useUserRole() + if (!metadata) return null + + const isFreeUser = userRole ? isFreeRole(userRole) : false + return ( {children} -
-
Model Info
-
- {metadata.modelUsed ?? "Unknown"} -
-
-
-
AI Credits Usage
-
- {metadata.totalTokens != null && ( -
- Total: - - {formatTokenCountString(metadata.totalTokens)} - -
- )} - {metadata.billedTokens != null && ( -
- Billed: - - {formatTokenCountString(metadata.billedTokens)} - -
- )} - {metadata.contextTokens != null && ( -
- Context: - - {formatTokenCountString(metadata.contextTokens)} - -
- )} - {metadata.outputTokens != null && ( -
- Output: - - {formatTokenCountString(metadata.outputTokens)} - -
- )} - {hasReasoningTokens && ( -
- Reasoning: - - {formatTokenCountString(metadata.reasoningTokens!)} - -
- )} - {hasCachedInputTokens && ( -
- Cached: - - {formatTokenCountString(metadata.cachedInputTokens!)} - -
- )} -
- {(hasDuration || hasBillingMultiplier) && ( - <> -
-
- {hasDuration && ( -
- Duration: - - {formatDuration(metadata.duration!)} - -
- )} - {hasBillingMultiplier && ( -
- Multiplier: - {metadata.billingMultiplier!}× -
- )} -
- - )} -
+ {isFreeUser ? ( + + ) : ( + + )}
diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/ai-block-constants.ts b/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/ai-block-constants.ts index 78fdda371..9a5845cdf 100644 --- a/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/ai-block-constants.ts +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/ai-block-constants.ts @@ -20,11 +20,6 @@ export const BLOCK_STYLES = { icon: "bg-orange/10 text-orange", label: "text-orange", }, - selectedText: { - container: "from-purple/5 to-purple/10 border-purple/20 hover:border-purple/30", - icon: "bg-purple/10 text-purple", - label: "text-purple", - }, fileAttachment: { container: "from-pink/5 to-pink/10 border-pink/20 hover:border-pink/30", icon: "bg-pink/10 text-pink", @@ -52,7 +47,6 @@ export const DEFAULT_BLOCK_STYLES = { export const BLOCK_ICONS = { mainEntry: "i-mgc-star-cute-fi", mainFeed: "i-mgc-rss-cute-fi", - selectedText: "i-mgc-quill-pen-cute-re", fileAttachment: "i-mgc-file-upload-cute-re", unreadOnly: "i-mgc-round-cute-fi", } as const @@ -63,7 +57,6 @@ export const BLOCK_ICONS = { export const BLOCK_LABELS = { mainEntry: "Current", mainFeed: "Current", - selectedText: "Text", fileAttachment: "File", mainView: "View", unreadOnly: "Filter", diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/useContextBlockPresentation.tsx b/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/useContextBlockPresentation.tsx index 65a020636..74ce9bdef 100644 --- a/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/useContextBlockPresentation.tsx +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/components/message/useContextBlockPresentation.tsx @@ -140,11 +140,6 @@ export function useContextBlockPresentation(block: AIChatContextBlock): ContextB ) break } - case "selectedText": { - displayContent = `"${block.value}"` - title = block.value - break - } case "unreadOnly": { displayContent = "Unread Only" title = "Unread Only" diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/editor/index.ts b/apps/desktop/layer/renderer/src/modules/ai-chat/editor/index.ts index 4e02f832c..147ce8175 100644 --- a/apps/desktop/layer/renderer/src/modules/ai-chat/editor/index.ts +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/editor/index.ts @@ -1,6 +1,6 @@ import { LexicalRichEditorNodes } from "@follow/components/ui/lexical-rich-editor/nodes.js" -import { FileAttachmentNode, MentionNode, ShortcutNode } from "./plugins" +import { FileAttachmentNode, MentionNode, SelectedTextNode, ShortcutNode } from "./plugins" export * from "./plugins" @@ -9,4 +9,5 @@ export const LexicalAIEditorNodes = [ MentionNode, ShortcutNode, FileAttachmentNode, + SelectedTextNode, ] diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/index.tsx b/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/index.tsx index 768bd804d..a0946d24b 100644 --- a/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/index.tsx +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/index.tsx @@ -1,3 +1,4 @@ export * from "./file-upload" export * from "./mention" +export * from "./selection" export * from "./shortcut" diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/selection/SelectedTextNode.tsx b/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/selection/SelectedTextNode.tsx new file mode 100644 index 000000000..17d5e8c60 --- /dev/null +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/selection/SelectedTextNode.tsx @@ -0,0 +1,135 @@ +import type { + DOMConversionMap, + DOMExportOutput, + LexicalEditor, + LexicalNode, + NodeKey, + SerializedLexicalNode, + Spread, +} from "lexical" +import { DecoratorNode } from "lexical" +import * as React from "react" + +import { SelectedTextNodeComponent } from "./SelectedTextNodeComponent" + +export type SelectedTextNodePayload = { + text: string + sourceEntryId?: string + timestamp?: number +} + +export type SerializedSelectedTextNode = Spread + +export class SelectedTextNode extends DecoratorNode { + __text: string + __sourceEntryId?: string + __timestamp?: number + + static override getType(): string { + return "selected-text" + } + + static override clone(node: SelectedTextNode): SelectedTextNode { + return new SelectedTextNode(node.__text, node.__sourceEntryId, node.__timestamp, node.__key) + } + + constructor(text: string, sourceEntryId?: string, timestamp?: number, key?: NodeKey) { + super(key) + this.__text = text + this.__sourceEntryId = sourceEntryId + this.__timestamp = timestamp + } + + getText(): string { + return this.__text + } + + setText(text: string): void { + const writable = this.getWritable() + writable.__text = text + } + + getSourceEntryId(): string | undefined { + return this.__sourceEntryId + } + + getTimestamp(): number | undefined { + return this.__timestamp + } + + override createDOM(): HTMLElement { + const div = document.createElement("div") + div.dataset.selectedTextNode = "true" + return div + } + + override updateDOM(): false { + return false + } + + static override importDOM(): DOMConversionMap | null { + return null + } + + static override importJSON(serializedNode: SerializedSelectedTextNode): SelectedTextNode { + const { text, sourceEntryId, timestamp } = serializedNode + return $createSelectedTextNode({ text, sourceEntryId, timestamp }) + } + + override exportJSON(): SerializedSelectedTextNode { + return { + text: this.__text, + sourceEntryId: this.__sourceEntryId, + timestamp: this.__timestamp, + type: "selected-text", + version: 1, + } + } + + override exportDOM(): DOMExportOutput { + const element = document.createElement("div") + element.dataset.selectedTextNode = "true" + element.textContent = this.__text + return { element } + } + + override decorate(_editor: LexicalEditor): React.JSX.Element { + return ( + + ) + } + + override isInline(): boolean { + return false + } + + override isKeyboardSelectable(): boolean { + return false + } + + override getTextContent(): string { + return `${escapeXML(this.__text)}` + } +} + +export function $createSelectedTextNode(payload: SelectedTextNodePayload): SelectedTextNode { + return new SelectedTextNode(payload.text, payload.sourceEntryId, payload.timestamp) +} + +export function $isSelectedTextNode( + node: LexicalNode | null | undefined, +): node is SelectedTextNode { + return node instanceof SelectedTextNode +} +function escapeXML(text: string): string { + return text + .replaceAll("&", "&") + .replaceAll("<", "<") + .replaceAll(">", ">") + .replaceAll('"', """) + .replaceAll("'", "'") +} diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/selection/SelectedTextNodeComponent.tsx b/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/selection/SelectedTextNodeComponent.tsx new file mode 100644 index 000000000..af92301b6 --- /dev/null +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/selection/SelectedTextNodeComponent.tsx @@ -0,0 +1,25 @@ +import { cn } from "@follow/utils" + +interface SelectedTextNodeComponentProps { + text: string + sourceEntryId?: string + timestamp?: number +} + +export function SelectedTextNodeComponent({ text }: SelectedTextNodeComponentProps) { + return ( + + + + "{text}" + + + ) +} diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/selection/SelectedTextPlugin.tsx b/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/selection/SelectedTextPlugin.tsx new file mode 100644 index 000000000..e3f80f27e --- /dev/null +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/selection/SelectedTextPlugin.tsx @@ -0,0 +1,22 @@ +import { useLexicalComposerContext } from "@lexical/react/LexicalComposerContext" +import { useEffect } from "react" + +import { insertSelectedTextNode } from "./insertSelectedTextNode" +import { subscribeSelectedTextInsertion } from "./selectedTextBridge" +import { SelectedTextNode } from "./SelectedTextNode" + +export function SelectedTextPlugin() { + const [editor] = useLexicalComposerContext() + + useEffect(() => { + return subscribeSelectedTextInsertion((payload) => { + editor.focus() + insertSelectedTextNode(editor, payload) + }) + }, [editor]) + + return null +} + +SelectedTextPlugin.id = "selected-text" +SelectedTextPlugin.nodes = [SelectedTextNode] diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/selection/index.ts b/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/selection/index.ts new file mode 100644 index 000000000..80372d449 --- /dev/null +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/selection/index.ts @@ -0,0 +1,5 @@ +export * from "./insertSelectedTextNode" +export * from "./selectedTextBridge" +export * from "./SelectedTextNode" +export * from "./SelectedTextNodeComponent" +export * from "./SelectedTextPlugin" diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/selection/insertSelectedTextNode.ts b/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/selection/insertSelectedTextNode.ts new file mode 100644 index 000000000..adbe779eb --- /dev/null +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/selection/insertSelectedTextNode.ts @@ -0,0 +1,29 @@ +import type { LexicalEditor } from "lexical" +import { + $createParagraphNode, + $createTextNode, + $getRoot, + $getSelection, + $isRangeSelection, +} from "lexical" + +import type { SelectedTextNodePayload } from "./SelectedTextNode" +import { $createSelectedTextNode } from "./SelectedTextNode" + +export function insertSelectedTextNode(editor: LexicalEditor, payload: SelectedTextNodePayload) { + editor.update(() => { + let selection = $getSelection() + + if (!$isRangeSelection(selection)) { + const root = $getRoot() + const paragraph = $createParagraphNode() + root.append(paragraph) + paragraph.selectEnd() + selection = $getSelection() + } + + if (!selection) return + const selectedNode = $createSelectedTextNode(payload) + selection.insertNodes([selectedNode, $createTextNode(" ")]) + }) +} diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/selection/selectedTextBridge.ts b/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/selection/selectedTextBridge.ts new file mode 100644 index 000000000..530a1cb53 --- /dev/null +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/editor/plugins/selection/selectedTextBridge.ts @@ -0,0 +1,29 @@ +import type { SelectedTextNodePayload } from "./SelectedTextNode" + +type Listener = (payload: SelectedTextNodePayload) => void + +const listeners = new Set() +let pendingPayload: SelectedTextNodePayload | null = null + +export function queueSelectedTextInsertion(payload: SelectedTextNodePayload) { + pendingPayload = payload + if (listeners.size === 0) return + + for (const listener of listeners) { + listener(payload) + } + pendingPayload = null +} + +export function subscribeSelectedTextInsertion(listener: Listener) { + listeners.add(listener) + + if (pendingPayload) { + listener(pendingPayload) + pendingPayload = null + } + + return () => { + listeners.delete(listener) + } +} diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/services/index.ts b/apps/desktop/layer/renderer/src/modules/ai-chat/services/index.ts index 6087c3800..407d17d07 100644 --- a/apps/desktop/layer/renderer/src/modules/ai-chat/services/index.ts +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/services/index.ts @@ -1,13 +1,13 @@ import { db } from "@follow/database/db" import type { AiChatMessagesModel } from "@follow/database/schemas/index" import { aiChatMessagesTable, aiChatTable } from "@follow/database/schemas/index" -import { asc, eq, inArray, sql } from "drizzle-orm" +import { and, asc, eq, inArray, isNull, sql } from "drizzle-orm" import { getI18n } from "~/i18n" import { followClient } from "~/lib/api-client" import { AI_CHAT_SPECIAL_ID_PREFIX } from "../constants" -import type { BizUIMessage, BizUIMessagePart } from "../store/types" +import type { BizUIMessage, BizUIMessagePart, BizUIMetadata } from "../store/types" import { isDataBlockPart, isFileAttachmentBlock } from "../utils/extractor" class AIPersistServiceStatic { @@ -49,6 +49,21 @@ class AIPersistServiceStatic { return Boolean(existingMessage?.id === chatId) } + async hasAssistantMessagesMissingMetadata(chatId: string): Promise { + const missingMetadataMessage = await db.query.aiChatMessagesTable.findFirst({ + where: and( + eq(aiChatMessagesTable.chatId, chatId), + eq(aiChatMessagesTable.role, "assistant"), + isNull(aiChatMessagesTable.metadata), + ), + columns: { + id: true, + }, + }) + + return Boolean(missingMetadataMessage?.id) + } + /** * Convert enhanced database message to BizUIMessage format for compatibility */ @@ -58,6 +73,7 @@ class AIPersistServiceStatic { role: dbMessage.role, createdAt: dbMessage.createdAt, parts: [], + metadata: (dbMessage.metadata ?? undefined) as BizUIMetadata | undefined, } if (dbMessage.messageParts && dbMessage.messageParts.length > 0) { diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/store/chat-core/chat-actions.ts b/apps/desktop/layer/renderer/src/modules/ai-chat/store/chat-core/chat-actions.ts index 535219dfa..1bb6e7c9d 100644 --- a/apps/desktop/layer/renderer/src/modules/ai-chat/store/chat-core/chat-actions.ts +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/store/chat-core/chat-actions.ts @@ -1,4 +1,6 @@ import { autoBindThis } from "@follow/utils/bind-this" +import { createDesktopAPIHeaders } from "@follow/utils/headers" +import PKG from "@pkg" import type { ChatRequestOptions, ChatStatus } from "ai" import { merge } from "es-toolkit/compat" import { nanoid } from "nanoid" @@ -217,6 +219,7 @@ export class ChatSliceActions { const finalOptions = merge( { body: { scene: this.get().scene }, + headers: createDesktopAPIHeaders({ version: PKG.version }), }, options, ) diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/store/slices/block.slice.ts b/apps/desktop/layer/renderer/src/modules/ai-chat/store/slices/block.slice.ts index 28a708368..2a034dba8 100644 --- a/apps/desktop/layer/renderer/src/modules/ai-chat/store/slices/block.slice.ts +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/store/slices/block.slice.ts @@ -33,7 +33,6 @@ export class BlockSliceAction { mainView: "mainView", mainEntry: "mainEntry", mainFeed: "mainFeed", - selectedText: "selectedText", unreadOnly: "unreadOnly", } get set() { diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/store/types.ts b/apps/desktop/layer/renderer/src/modules/ai-chat/store/types.ts index 6fbf54e1f..8745bae65 100644 --- a/apps/desktop/layer/renderer/src/modules/ai-chat/store/types.ts +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/store/types.ts @@ -20,12 +20,7 @@ interface BaseContextBlock { disabled?: boolean } -export type ValueContextBlockType = - | "mainView" - | "mainEntry" - | "mainFeed" - | "selectedText" - | "unreadOnly" +export type ValueContextBlockType = "mainView" | "mainEntry" | "mainFeed" | "unreadOnly" export interface AbstractValueContextBlock extends BaseContextBlock { type: T value: string diff --git a/apps/desktop/layer/renderer/src/modules/ai-chat/utils/rate-limit.ts b/apps/desktop/layer/renderer/src/modules/ai-chat/utils/rate-limit.ts index 6e3f6158f..fb36bddd6 100644 --- a/apps/desktop/layer/renderer/src/modules/ai-chat/utils/rate-limit.ts +++ b/apps/desktop/layer/renderer/src/modules/ai-chat/utils/rate-limit.ts @@ -9,6 +9,10 @@ export interface AIConfigLike { freeQuota?: FreeQuota } +export interface RateLimitMessageOptions { + hideResetDetails?: boolean +} + const formatResetTime = (windowResetTime: Date) => { const i18n = getI18n() const { t } = i18n @@ -56,9 +60,11 @@ export function computeIsRateLimited( export function computeRateLimitMessage( error: Error | string | undefined, configuration?: AIConfigLike | null, + options?: RateLimitMessageOptions, ): string | null { const i18n = getI18n() const { t } = i18n + const hideResetDetails = options?.hideResetDetails ?? false const aiNs = { ns: "ai" } as const if (error) { @@ -84,7 +90,7 @@ export function computeRateLimitMessage( parts.push(t("rate_limit.upgrade_to_get_more", aiNs)) } - if (resetText) { + if (resetText && !hideResetDetails) { parts.push(resetText) } @@ -101,11 +107,12 @@ export function computeRateLimitMessage( const monthly = configuration.freeQuota.remainingMonthlyRequests if (!daily || !monthly) { const parts: string[] = [] - parts.push(t("rate_limit.depleted", aiNs)) - if (!daily && monthly) { - parts.push(t("rate_limit.resets_tomorrow", aiNs)) - } else { - parts.push(t("rate_limit.resets_next_month", aiNs)) + if (!hideResetDetails) { + if (!daily && monthly) { + parts.push(t("rate_limit.resets_tomorrow", aiNs)) + } else { + parts.push(t("rate_limit.resets_next_month", aiNs)) + } } parts.push(t("rate_limit.upgrade_to_get_more", aiNs)) return parts.join(" · ") @@ -124,7 +131,7 @@ export function computeRateLimitMessage( } else { parts.push(t("rate_limit.credits_left", { ns: "ai", count: remaining })) } - if (formattedResetText) { + if (formattedResetText && !hideResetDetails) { parts.push(formattedResetText) } if (parts.length < 2) { diff --git a/apps/desktop/layer/renderer/src/modules/auth/LoginModalContent.tsx b/apps/desktop/layer/renderer/src/modules/auth/LoginModalContent.tsx index 56b492407..36979684c 100644 --- a/apps/desktop/layer/renderer/src/modules/auth/LoginModalContent.tsx +++ b/apps/desktop/layer/renderer/src/modules/auth/LoginModalContent.tsx @@ -4,6 +4,7 @@ import { Folo } from "@follow/components/icons/folo.js" import { Logo } from "@follow/components/icons/logo.js" import { MotionButtonBase } from "@follow/components/ui/button/index.js" import { useIsDark } from "@follow/hooks" +import { IN_ELECTRON } from "@follow/shared" import type { LoginRuntime } from "@follow/shared/auth" import { stopPropagation } from "@follow/utils/dom" import { cn } from "@follow/utils/utils" @@ -12,7 +13,6 @@ import { useEffect, useState } from "react" import { Trans, useTranslation } from "react-i18next" import { useServerConfigs } from "~/atoms/server-configs" -import { GlassButton } from "~/components/ui/button/GlassButton" import { useCurrentModal, useModalStack } from "~/components/ui/modal/stacked/hooks" import { authClient, loginHandler } from "~/lib/auth" import { useAuthProviders } from "~/queries/users" @@ -119,15 +119,15 @@ export const LoginModalContent = (props: LoginModalContentProps) => {
- - - - - + {!IN_ELECTRON && ( + + )} {isEmail ? ( export type FollowCommandId = FollowCommand["id"] -export type FollowCommand = BasicCommand // | UnknownCommand +export type FollowCommand = BasicCommand | UnknownCommand 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 9b81cf319..dae915cc6 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 @@ -38,7 +38,8 @@ const ViewTag = IN_ELECTRON ? "webview" : "iframe" const entrySelector = (state: EntryModel) => { /// keep-sorted - const { authorAvatar, authorUrl, description, feedId, inboxHandle, publishedAt, title } = state + const { authorAvatar, authorUrl, description, feedId, inboxHandle, publishedAt, tags, title } = + state const audios = state.attachments?.filter((a) => a.mime_type?.startsWith("audio") && a.url) const video = transformVideoUrl({ @@ -62,6 +63,7 @@ const entrySelector = (state: EntryModel) => { firstPhotoUrl, inboxId: inboxHandle, publishedAt, + tags: tags ?? null, title, video, } diff --git a/apps/desktop/layer/renderer/src/modules/entry-column/Items/media-gallery.tsx b/apps/desktop/layer/renderer/src/modules/entry-column/Items/media-gallery.tsx index a72b1a77b..6c9e8987e 100644 --- a/apps/desktop/layer/renderer/src/modules/entry-column/Items/media-gallery.tsx +++ b/apps/desktop/layer/renderer/src/modules/entry-column/Items/media-gallery.tsx @@ -1,10 +1,10 @@ import { useEntry } from "@follow/store/entry/hooks" -import { getImageProxyUrl } from "@follow/utils/img-proxy" import { cn } from "@follow/utils/utils" import { useMemo } from "react" import { usePreviewMedia } from "~/components/ui/media/hooks" import { Media } from "~/components/ui/media/Media" +import { useGetImageProxyUrl } from "~/lib/img-proxy" import { jotaiStore } from "~/lib/jotai" import { socialMediaContentWidthAtom } from "../atoms/social-media-content-width" @@ -16,6 +16,7 @@ export const MediaGallery = ({ entryId: string containerWidth?: number }) => { + const getImageProxyUrl = useGetImageProxyUrl() const entry = useEntry(entryId, (state) => ({ media: state.media })) const media = useMemo(() => entry?.media || [], [entry?.media]) diff --git a/apps/desktop/layer/renderer/src/modules/entry-column/atoms/ai-timeline.ts b/apps/desktop/layer/renderer/src/modules/entry-column/atoms/ai-timeline.ts new file mode 100644 index 000000000..36b0a017c --- /dev/null +++ b/apps/desktop/layer/renderer/src/modules/entry-column/atoms/ai-timeline.ts @@ -0,0 +1,3 @@ +import { atom } from "jotai" + +export const aiTimelineEnabledAtom = atom(false) diff --git a/apps/desktop/layer/renderer/src/modules/entry-column/components/ai-timeline-loading/AITimelineLoadingOverlay.css b/apps/desktop/layer/renderer/src/modules/entry-column/components/ai-timeline-loading/AITimelineLoadingOverlay.css new file mode 100644 index 000000000..a3df0b98a --- /dev/null +++ b/apps/desktop/layer/renderer/src/modules/entry-column/components/ai-timeline-loading/AITimelineLoadingOverlay.css @@ -0,0 +1,212 @@ +.ai-timeline-loading { + position: absolute; + inset: 0; + pointer-events: none; + overflow: hidden; + border-radius: inherit; +} + +.ai-timeline-loading__backdrop { + position: absolute; + inset: 0; + background: linear-gradient( + 135deg, + rgba(255, 255, 255, 0.02), + rgba(255, 92, 0, 0.08), + rgba(0, 0, 0, 0.1) + ); + opacity: 0.75; + animation: aiTimelineGlassPulse 2.6s ease-in-out infinite; +} + +.ai-timeline-loading__glow { + position: absolute; + inset: 10% 8% 16% 8%; + border-radius: 48px; + background: radial-gradient( + circle at 70% 25%, + rgba(255, 92, 0, 0.35), + rgba(255, 140, 0, 0.15), + transparent 65% + ); + filter: blur(42px); + opacity: 0.8; + animation: aiTimelineGlow 3.4s ease-in-out infinite; +} + +.ai-timeline-loading__beam { + position: absolute; + top: -5%; + bottom: -5%; + width: 32%; + border-radius: 999px; + background: linear-gradient( + 120deg, + rgba(255, 255, 255, 0.2), + rgba(255, 92, 0, 0.15), + rgba(255, 92, 0, 0) + ); + filter: blur(18px); + opacity: 0; + animation: aiTimelineBeam 2.8s cubic-bezier(0.4, 0, 0.2, 1) infinite; +} + +.ai-timeline-loading__beam--left { + left: -15%; + animation-delay: 0s; +} + +.ai-timeline-loading__beam--right { + right: -15%; + animation-delay: -1.2s; +} + +.ai-timeline-loading__sparkles { + position: absolute; + inset: 0; + filter: blur(0.5px); +} + +.ai-timeline-loading__sparkles span { + position: absolute; + width: 10px; + height: 10px; + border-radius: 999px; + background: rgba(255, 255, 255, 0.45); + box-shadow: + 0 0 18px rgba(255, 92, 0, 0.4), + 0 0 8px rgba(255, 255, 255, 0.3); + opacity: 0; + animation: aiTimelineSparkle 3s ease-in-out infinite; +} + +.ai-timeline-loading__sparkles span:nth-child(1) { + top: 25%; + left: 32%; + animation-delay: 0s; +} + +.ai-timeline-loading__sparkles span:nth-child(2) { + top: 55%; + left: 62%; + animation-delay: -0.9s; +} + +.ai-timeline-loading__sparkles span:nth-child(3) { + top: 38%; + left: 78%; + animation-delay: -1.8s; +} + +.ai-timeline-loading__badge { + position: absolute; + right: 1.25rem; + bottom: 1.5rem; + padding: 0.5rem 1rem; + border-radius: 999px; + background: linear-gradient( + 120deg, + rgba(16, 16, 16, 0.65), + rgba(32, 24, 20, 0.65), + rgba(255, 92, 0, 0.25) + ); + border: 1px solid rgba(255, 255, 255, 0.08); + box-shadow: + 0 15px 40px rgba(0, 0, 0, 0.35), + inset 0 1px 1px rgba(255, 255, 255, 0.15); + backdrop-filter: blur(12px) saturate(140%); + -webkit-backdrop-filter: blur(12px) saturate(140%); + animation: aiTimelineBadgePulse 2.2s ease-in-out infinite; +} + +.ai-timeline-loading__badge::before { + content: ""; + position: absolute; + inset: 0; + border-radius: inherit; + background: linear-gradient( + 120deg, + rgba(255, 255, 255, 0.05), + rgba(255, 92, 0, 0.35), + rgba(255, 255, 255, 0.05) + ); + opacity: 0.35; + pointer-events: none; +} + +.ai-timeline-loading__badge span { + color: rgba(255, 255, 255, 0.9); + text-shadow: 0 1px 8px rgba(0, 0, 0, 0.25); +} + +@keyframes aiTimelineGlassPulse { + 0%, + 100% { + opacity: 0.65; + } + 50% { + opacity: 0.85; + } +} + +@keyframes aiTimelineGlow { + 0%, + 100% { + transform: scale(0.95); + opacity: 0.6; + } + 50% { + transform: scale(1.05); + opacity: 0.85; + } +} + +@keyframes aiTimelineBeam { + 0% { + opacity: 0; + transform: translateX(-35%) scaleX(0.8); + } + 40% { + opacity: 0.4; + } + 70% { + opacity: 0.65; + transform: translateX(20%) scaleX(1.05); + } + 100% { + opacity: 0; + transform: translateX(30%) scaleX(1.2); + } +} + +@keyframes aiTimelineSparkle { + 0%, + 100% { + opacity: 0; + transform: scale(0.4) translate3d(0, 0, 0); + } + 35% { + opacity: 0.85; + transform: scale(1) translate3d(4px, -6px, 0); + } + 65% { + opacity: 0.35; + transform: scale(0.6) translate3d(-4px, 6px, 0); + } +} + +@keyframes aiTimelineBadgePulse { + 0%, + 100% { + transform: translateY(0); + box-shadow: + 0 15px 40px rgba(0, 0, 0, 0.35), + inset 0 1px 1px rgba(255, 255, 255, 0.15); + } + 50% { + transform: translateY(-3px); + box-shadow: + 0 20px 45px rgba(0, 0, 0, 0.4), + inset 0 1px 1px rgba(255, 255, 255, 0.25); + } +} diff --git a/apps/desktop/layer/renderer/src/modules/entry-column/components/ai-timeline-loading/AITimelineLoadingOverlay.tsx b/apps/desktop/layer/renderer/src/modules/entry-column/components/ai-timeline-loading/AITimelineLoadingOverlay.tsx new file mode 100644 index 000000000..1e89b0955 --- /dev/null +++ b/apps/desktop/layer/renderer/src/modules/entry-column/components/ai-timeline-loading/AITimelineLoadingOverlay.tsx @@ -0,0 +1,40 @@ +import "./AITimelineLoadingOverlay.css" + +import { Spring } from "@follow/components/constants/spring.js" +import { AnimatePresence, m } from "motion/react" +import type { FC } from "react" + +type Props = { + visible: boolean + label: string +} + +export const AITimelineLoadingOverlay: FC = ({ visible, label }) => ( + + {visible ? ( + +
+
+
+
+
+ + + +
+ +
+ + + {label} +
+ + ) : null} + +) diff --git a/apps/desktop/layer/renderer/src/modules/entry-column/hooks/useEntriesByView.ts b/apps/desktop/layer/renderer/src/modules/entry-column/hooks/useEntriesByView.ts index 3dea405c1..6e2e82852 100644 --- a/apps/desktop/layer/renderer/src/modules/entry-column/hooks/useEntriesByView.ts +++ b/apps/desktop/layer/renderer/src/modules/entry-column/hooks/useEntriesByView.ts @@ -18,14 +18,17 @@ import { nextFrame } from "@follow/utils" import { isBizId } from "@follow/utils/utils" import { useMutation } from "@tanstack/react-query" import { debounce } from "es-toolkit/compat" +import { useAtomValue } from "jotai" import { useCallback, useEffect, useMemo, useState } from "react" import { useGeneralSettingKey } from "~/atoms/settings/general" import { ROUTE_FEED_PENDING } from "~/constants/app" +import { useFeature } from "~/hooks/biz/useFeature" import { useRouteParams } from "~/hooks/biz/useRouteParams" import { useAuthQuery } from "~/hooks/common" import { entries } from "~/queries/entries" +import { aiTimelineEnabledAtom } from "../atoms/ai-timeline" import { useIsPreviewFeed } from "./useIsPreviewFeed" const useRemoteEntries = (): UseEntriesReturn => { @@ -36,6 +39,8 @@ const useRemoteEntries = (): UseEntriesReturn => { const hidePrivateSubscriptionsInTimeline = useGeneralSettingKey( "hidePrivateSubscriptionsInTimeline", ) + const aiTimelineEnabled = useAtomValue(aiTimelineEnabledAtom) + const aiEnabled = useFeature("ai") const folderIds = useFolderFeedsByFeedId({ feedId, @@ -53,6 +58,7 @@ const useRemoteEntries = (): UseEntriesReturn => { hidePrivateSubscriptionsInTimeline: true, }), ...(view === FeedViewType.All && { limit: 40 }), + ...(aiTimelineEnabled && aiEnabled && { aiSort: true }), } if (feedId && listId && isBizId(feedId)) { @@ -69,6 +75,8 @@ const useRemoteEntries = (): UseEntriesReturn => { isPreview, view, hidePrivateSubscriptionsInTimeline, + aiTimelineEnabled, + aiEnabled, ]) const query = useEntriesQuery(entriesOptions) diff --git a/apps/desktop/layer/renderer/src/modules/entry-column/index.tsx b/apps/desktop/layer/renderer/src/modules/entry-column/index.tsx index fd0a1ae87..6d02e4f81 100644 --- a/apps/desktop/layer/renderer/src/modules/entry-column/index.tsx +++ b/apps/desktop/layer/renderer/src/modules/entry-column/index.tsx @@ -7,8 +7,9 @@ import { unreadSyncService } from "@follow/store/unread/store" import { useIsLoggedIn } from "@follow/store/user/hooks" import { isBizId } from "@follow/utils/utils" import type { Range, Virtualizer } from "@tanstack/react-virtual" -import { atom } from "jotai" +import { atom, useAtomValue } from "jotai" import { memo, useCallback, useEffect, useMemo, useRef } from "react" +import { useTranslation } from "react-i18next" import { useGeneralSettingKey } from "~/atoms/settings/general" import { Focusable } from "~/components/common/Focusable" @@ -19,6 +20,8 @@ import { useRouteParams, useRouteParamsSelector } from "~/hooks/biz/useRoutePara import { useFeedQuery } from "~/queries/feed" import { useFeedHeaderTitle } from "~/store/feed/hooks" +import { aiTimelineEnabledAtom } from "./atoms/ai-timeline" +import { AITimelineLoadingOverlay } from "./components/ai-timeline-loading/AITimelineLoadingOverlay" import { EntryColumnWrapper } from "./components/entry-column-wrapper/EntryColumnWrapper" import { FooterMarkItem } from "./components/FooterMarkItem" import { useEntriesActions, useEntriesState } from "./context/EntriesContext" @@ -34,6 +37,7 @@ import { EntryRootStateContext } from "./store/EntryColumnContext" function EntryColumnContent() { const listRef = useRef>(undefined) + const { t } = useTranslation() const state = useEntriesState() const actions = useEntriesActions() @@ -111,6 +115,8 @@ function EntryColumnContent() { const rangeQueueRef = useRef([]) const isRefreshing = state.isFetching && !state.isFetchingNextPage + const aiTimelineEnabled = useAtomValue(aiTimelineEnabledAtom) + const showAiTimelineLoading = aiTimelineEnabled && state.isLoading && !state.isFetchingNextPage const renderAsRead = useGeneralSettingKey("renderMarkUnread") const handleRangeChange = useCallback( (e: Range) => { @@ -192,6 +198,11 @@ function EntryColumnContent() { /> )} + + ) } diff --git a/apps/desktop/layer/renderer/src/modules/entry-column/layouts/EntryItemWrapper.tsx b/apps/desktop/layer/renderer/src/modules/entry-column/layouts/EntryItemWrapper.tsx index 213b3c9d5..d6843fd42 100644 --- a/apps/desktop/layer/renderer/src/modules/entry-column/layouts/EntryItemWrapper.tsx +++ b/apps/desktop/layer/renderer/src/modules/entry-column/layouts/EntryItemWrapper.tsx @@ -41,6 +41,7 @@ export const EntryItemWrapper: FC< > = ({ entryId, view, children, itemClassName, style, isFirstItem }) => { const entry = useEntry(entryId, (state) => { const { feedId, inboxHandle } = state + const { id, url } = state return { feedId, id, inboxId: inboxHandle, url } }) diff --git a/apps/desktop/layer/renderer/src/modules/entry-column/layouts/EntryListHeader.tsx b/apps/desktop/layer/renderer/src/modules/entry-column/layouts/EntryListHeader.tsx index 47261d43a..40b5c07d9 100644 --- a/apps/desktop/layer/renderer/src/modules/entry-column/layouts/EntryListHeader.tsx +++ b/apps/desktop/layer/renderer/src/modules/entry-column/layouts/EntryListHeader.tsx @@ -10,7 +10,7 @@ import { useFeedById } from "@follow/store/feed/hooks" import { useIsLoggedIn, useWhoami } from "@follow/store/user/hooks" import { stopPropagation } from "@follow/utils/dom" import { clsx, cn, isBizId } from "@follow/utils/utils" -import { useAtomValue } from "jotai" +import { useAtom, useAtomValue } from "jotai" import type { FC } from "react" import { useCallback } from "react" import { useTranslation } from "react-i18next" @@ -33,6 +33,7 @@ import { FeedIcon } from "~/modules/feed/feed-icon" import { useRefreshFeedMutation } from "~/queries/feed" import { useFeedHeaderIcon, useFeedHeaderTitle } from "~/store/feed/hooks" +import { aiTimelineEnabledAtom } from "../atoms/ai-timeline" import { MarkAllReadButton } from "../components/mark-all-button" import { useIsPreviewFeed } from "../hooks/useIsPreviewFeed" import { useEntryRootState } from "../store/EntryColumnContext" @@ -48,6 +49,7 @@ export const EntryListHeader: FC<{ const { t } = useTranslation() const unreadOnly = useGeneralSettingKey("unreadOnly") + const [aiTimelineEnabled, setAiTimelineEnabled] = useAtom(aiTimelineEnabledAtom) const aiEnabled = useFeature("ai") const { feedId, entryId, view, isCollection } = routerParams @@ -102,6 +104,37 @@ export const EntryListHeader: FC<{ }, [sendAIShortcut]) const showEntryHeader = isWideMode && !!entryId && entryId !== ROUTE_ENTRY_PENDING const showTimelineSummaryButton = isWideMode && aiEnabled + const showAiTimelineToggle = aiEnabled + + const handleAiTimelineButtonClick = useCallback(() => { + setAiTimelineEnabled((prev) => !prev) + }, [setAiTimelineEnabled]) + + const renderAiTimelineButton = () => { + if (!showAiTimelineToggle) return null + return ( + + {aiTimelineEnabled ? ( + + ) : ( + + )} + + ) + } + + const renderTimelineSummaryButton = () => { + if (!showTimelineSummaryButton) return null + return ( + + + + ) + } return (
- {isWideMode && (showEntryHeader || showTimelineSummaryButton) && ( - <> - {showEntryHeader && } - {showTimelineSummaryButton && ( - - - - )} - - - )} + {isWideMode && + (showEntryHeader || showTimelineSummaryButton || showAiTimelineToggle) && ( + <> + {showEntryHeader && } + {(showAiTimelineToggle || showTimelineSummaryButton) && ( +
+ {aiTimelineEnabled && renderAiTimelineButton()} + {renderTimelineSummaryButton()} +
+ )} + + + )} + + {!isWideMode && aiTimelineEnabled && renderAiTimelineButton()} {view === FeedViewType.Pictures && } diff --git a/apps/desktop/layer/renderer/src/modules/entry-column/templates/list-item-template.tsx b/apps/desktop/layer/renderer/src/modules/entry-column/templates/list-item-template.tsx index a57015e34..acb971f58 100644 --- a/apps/desktop/layer/renderer/src/modules/entry-column/templates/list-item-template.tsx +++ b/apps/desktop/layer/renderer/src/modules/entry-column/templates/list-item-template.tsx @@ -17,6 +17,7 @@ import { Media } from "~/components/ui/media/Media" import { FEED_COLLECTION_LIST } from "~/constants" import { useEntryIsRead } from "~/hooks/biz/useAsRead" import { useRouteParamsSelector } from "~/hooks/biz/useRouteParams" +import { EntryTags } from "~/modules/entry/EntryTags" import { EntryTranslation } from "~/modules/entry-column/translation" import type { FeedIconEntry } from "~/modules/feed/feed-icon" import { FeedIcon } from "~/modules/feed/feed-icon" @@ -28,7 +29,8 @@ import type { UniversalItemProps } from "../types" const entrySelector = (state: EntryModel) => { /// keep-sorted - const { authorAvatar, authorUrl, description, feedId, inboxHandle, publishedAt, title } = state + const { authorAvatar, authorUrl, description, feedId, inboxHandle, publishedAt, tags, title } = + state const audios = state.attachments?.filter((a) => a.mime_type?.startsWith("audio") && a.url) const firstAudio = audios?.[0] @@ -48,6 +50,7 @@ const entrySelector = (state: EntryModel) => { firstPhotoUrl, inboxId: inboxHandle, publishedAt, + tags: tags ?? null, title, } } @@ -183,7 +186,7 @@ export function ListItem({ >
- · + · {!!displayTime && }
)} +
{hasAudio && entry.firstAudio && ( 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 3988db635..643d90a31 100644 --- a/apps/desktop/layer/renderer/src/modules/entry-content/EntryContent.tsx +++ b/apps/desktop/layer/renderer/src/modules/entry-content/EntryContent.tsx @@ -95,7 +95,6 @@ const EntryContentImpl: Component = ({ }) return () => { removeBlock(BlockSliceAction.SPECIAL_TYPES.mainEntry) - removeBlock(BlockSliceAction.SPECIAL_TYPES.selectedText) } }, [addOrUpdateBlock, entryId, removeBlock]) const animationController = useAnimationControls() diff --git a/apps/desktop/layer/renderer/src/modules/entry-content/actions/more-actions.tsx b/apps/desktop/layer/renderer/src/modules/entry-content/actions/more-actions.tsx index 839b25e2a..3b0db2320 100644 --- a/apps/desktop/layer/renderer/src/modules/entry-content/actions/more-actions.tsx +++ b/apps/desktop/layer/renderer/src/modules/entry-content/actions/more-actions.tsx @@ -179,39 +179,13 @@ export const CommandDropdownMenuItem = ({ asSubTrigger = false, disabled = false, }: { - commandId: FollowCommandId | string + commandId: FollowCommandId onClick: () => void active?: boolean asSubTrigger?: boolean disabled?: boolean }) => { - const command = useCommand(commandId as any) - - // For custom integration items - if (typeof commandId === "string" && commandId.startsWith("integration:custom:")) { - const content = ( - <> - - Custom Integration - - ) - - if (asSubTrigger) { - return content - } - - return ( - - {content} - - ) - } + const command = useCommand(commandId) if (!command) return null diff --git a/apps/desktop/layer/renderer/src/modules/entry-content/components/EntryPlaceholderLogo.tsx b/apps/desktop/layer/renderer/src/modules/entry-content/components/EntryPlaceholderLogo.tsx index 5e67bb1a2..03aa48c24 100644 --- a/apps/desktop/layer/renderer/src/modules/entry-content/components/EntryPlaceholderLogo.tsx +++ b/apps/desktop/layer/renderer/src/modules/entry-content/components/EntryPlaceholderLogo.tsx @@ -4,14 +4,16 @@ import { DEFAULT_SUMMARIZE_TIMELINE_SHORTCUT_ID, } from "@follow/shared/settings/defaults" import { stopPropagation } from "@follow/utils/dom" +import { useSetAtom } from "jotai" import { useCallback } from "react" -import { toast } from "sonner" import { useSendAIShortcut } from "~/modules/ai-chat/hooks/useSendAIShortcut" +import { aiTimelineEnabledAtom } from "~/modules/entry-column/atoms/ai-timeline" import { useSettingModal } from "~/modules/settings/modal/use-setting-modal-hack" export const EntryPlaceholderLogo = () => { const { sendAIShortcut } = useSendAIShortcut() + const setAiTimelineEnabled = useSetAtom(aiTimelineEnabledAtom) const settingModalPresent = useSettingModal() const handleSummarizeTimeline = useCallback(() => { void sendAIShortcut({ @@ -25,6 +27,9 @@ export const EntryPlaceholderLogo = () => { ensureNewChat: true, }) }, [sendAIShortcut]) + const handleToggleAiTimeline = useCallback(() => { + setAiTimelineEnabled((prev) => !prev) + }, [setAiTimelineEnabled]) const buttons = [ { @@ -39,9 +44,7 @@ export const EntryPlaceholderLogo = () => { }, { label: "Sort the timeline by importance", - onClick: () => { - toast.success("Coming soon!") - }, + onClick: handleToggleAiTimeline, icon: , }, { diff --git a/apps/desktop/layer/renderer/src/modules/entry-content/components/EntryTitle.tsx b/apps/desktop/layer/renderer/src/modules/entry-content/components/EntryTitle.tsx index ddffaecc4..2320098a7 100644 --- a/apps/desktop/layer/renderer/src/modules/entry-content/components/EntryTitle.tsx +++ b/apps/desktop/layer/renderer/src/modules/entry-content/components/EntryTitle.tsx @@ -17,6 +17,7 @@ import type { FeedIconEntry } from "~/modules/feed/feed-icon" import { FeedIcon } from "~/modules/feed/feed-icon" import { getPreferredTitle } from "~/store/feed/hooks" +import { EntryTags } from "../../entry/EntryTags" import { EntryTranslation } from "../../entry-column/translation" import { EntryReadHistory } from "./entry-read-history" @@ -37,7 +38,8 @@ export const EntryTitle = ({ entryId, useShallow((state) => { /// keep-sorted - const { author, authorAvatar, authorUrl, feedId, inboxHandle, publishedAt, title } = state + const { author, authorAvatar, authorUrl, feedId, inboxHandle, publishedAt, tags, title } = + state const attachments = state.attachments || [] const { duration_in_seconds } = @@ -59,6 +61,7 @@ export const EntryTitle = ({ firstPhotoUrl, inboxId: inboxHandle, publishedAt, + tags: tags ?? null, title, } }), @@ -183,6 +186,7 @@ export const EntryTitle = ({ )}
+ {/* Recent Readers */} {!noRecentReader && !hideRecentReader && }
diff --git a/apps/desktop/layer/renderer/src/modules/entry-content/components/layouts/ArticleLayout.tsx b/apps/desktop/layer/renderer/src/modules/entry-content/components/layouts/ArticleLayout.tsx index db9b1ceb8..ef4422295 100644 --- a/apps/desktop/layer/renderer/src/modules/entry-content/components/layouts/ArticleLayout.tsx +++ b/apps/desktop/layer/renderer/src/modules/entry-content/components/layouts/ArticleLayout.tsx @@ -8,7 +8,12 @@ import { cn } from "@follow/utils" import { ErrorBoundary } from "@sentry/react" import { useCallback, useEffect, useMemo, useRef, useState } from "react" -import { AIChatPanelStyle, useAIChatPanelStyle, useAIPanelVisibility } from "~/atoms/settings/ai" +import { + AIChatPanelStyle, + setAIPanelVisibility, + useAIChatPanelStyle, + useAIPanelVisibility, +} from "~/atoms/settings/ai" import { useUISettingKey } from "~/atoms/settings/ui" import { ShadowDOM } from "~/components/common/ShadowDOM" import type { TocRef } from "~/components/ui/markdown/components/Toc" @@ -16,8 +21,7 @@ import { useInPeekModal } from "~/components/ui/modal/inspire/InPeekModal" import { readableContentMaxWidthClassName } from "~/constants/ui" import { useRenderStyle } from "~/hooks/biz/useRenderStyle" import type { TextSelectionEvent } from "~/lib/simple-text-selection" -import { useBlockActions } from "~/modules/ai-chat/store/hooks" -import { BlockSliceAction } from "~/modules/ai-chat/store/slices/block.slice" +import { queueSelectedTextInsertion } from "~/modules/ai-chat/editor/plugins/selection/selectedTextBridge" import { EntryContentHTMLRenderer } from "~/modules/renderer/html" import { EntryContentMarkdownRenderer } from "~/modules/renderer/markdown" import { WrappedElementProvider } from "~/providers/wrapped-element-provider" @@ -29,6 +33,7 @@ import { EntryRenderError } from "../entry-content/EntryRenderError" import { ReadabilityNotice } from "../entry-content/ReadabilityNotice" import { EntryAttachments } from "../EntryAttachments" import { EntryTitle } from "../EntryTitle" +import { TextSelectionToolbar } from "../selection/TextSelectionToolbar" import { MediaTranscript, TranscriptToggle, useTranscription } from "./shared" import { ArticleAudioPlayer } from "./shared/AudioPlayer" import type { EntryLayoutProps } from "./types" @@ -48,30 +53,44 @@ export const ArticleLayout: React.FC = ({ const feed = useFeedById(entry?.feedId) const isInbox = useIsInbox(entry?.inboxId) const [showTranscript, setShowTranscript] = useState(false) + const [textSelection, setTextSelection] = useState(null) const { content } = useEntryContent(entryId) const customCSS = useUISettingKey("customCSS") - const { addOrUpdateBlock, removeBlock } = useBlockActions() - const handleTextSelect = useCallback( - (event: TextSelectionEvent) => { - addOrUpdateBlock({ - id: BlockSliceAction.SPECIAL_TYPES.selectedText, - type: "selectedText", - value: event.selectedText, - }) - }, - [addOrUpdateBlock], - ) + const handleTextSelect = useCallback((event: TextSelectionEvent) => { + setTextSelection(event) + }, []) const handleSelectionClear = useCallback(() => { - removeBlock(BlockSliceAction.SPECIAL_TYPES.selectedText) - }, [removeBlock]) + setTextSelection(null) + }, []) const aiChatPanelStyle = useAIChatPanelStyle() const isAIPanelVisible = useAIPanelVisibility() const shouldShowAISummary = aiChatPanelStyle === AIChatPanelStyle.Floating || !isAIPanelVisible + const handleAskAI = useCallback( + (selectionEvent?: TextSelectionEvent) => { + const pendingSelection = selectionEvent ?? textSelection + if (!pendingSelection?.selectedText) return + + queueSelectedTextInsertion({ + text: pendingSelection.selectedText, + sourceEntryId: entryId, + timestamp: pendingSelection.timestamp, + }) + setAIPanelVisibility(true) + handleSelectionClear() + }, + [entryId, handleSelectionClear, textSelection], + ) + + useEffect(() => { + if (!showTranscript) return + handleSelectionClear() + }, [showTranscript, handleSelectionClear]) + if (!entry) return null return ( @@ -120,6 +139,12 @@ export const ArticleLayout: React.FC = ({ )}
+ diff --git a/apps/desktop/layer/renderer/src/modules/entry-content/components/layouts/shared/AudioPlayer.tsx b/apps/desktop/layer/renderer/src/modules/entry-content/components/layouts/shared/AudioPlayer.tsx index 5f550bae4..1543f3338 100644 --- a/apps/desktop/layer/renderer/src/modules/entry-content/components/layouts/shared/AudioPlayer.tsx +++ b/apps/desktop/layer/renderer/src/modules/entry-content/components/layouts/shared/AudioPlayer.tsx @@ -1,9 +1,10 @@ import { Spring } from "@follow/components/constants/spring.js" import { useEntry } from "@follow/store/entry/hooks" import { cn } from "@follow/utils/utils" +import * as Slider from "@radix-ui/react-slider" import dayjs from "dayjs" import { AnimatePresence, m } from "motion/react" -import { useCallback, useMemo } from "react" +import { useCallback, useMemo, useState } from "react" import { AudioPlayer, useAudioPlayerAtomSelector } from "~/atoms/player" @@ -55,6 +56,10 @@ export const ArticleAudioPlayer: React.FC = ({ entryId, classN const isPlaying = isCurrentAudio && status === "playing" const isLoading = isCurrentAudio && status === "loading" + // Slider drag state + const [isDragging, setIsDragging] = useState(false) + const [dragValue, setDragValue] = useState(0) + const handlePlayAudio = useCallback(() => { if (!audioAttachment) return @@ -96,132 +101,202 @@ export const ArticleAudioPlayer: React.FC = ({ entryId, classN const displayHasValidDuration = displayDuration && displayDuration > 0 && displayDuration !== Infinity - const handleProgressClick = useCallback( - (event: React.MouseEvent) => { + const handleSliderValueChange = useCallback( + (value: number[]) => { if (!isCurrentAudio || !displayHasValidDuration) return - - const rect = event.currentTarget.getBoundingClientRect() - const clickX = event.clientX - rect.left - const progressPercent = clickX / rect.width - const newTime = progressPercent * displayDuration - - AudioPlayer.seek(newTime) + setDragValue(value[0]!) }, - [isCurrentAudio, displayHasValidDuration, displayDuration], + [isCurrentAudio, displayHasValidDuration], ) - const currentTimeDisplay = formatDuration(displayCurrentTime) - const durationDisplay = formatDuration(displayDuration) + const handleSliderValueCommit = useCallback( + (value: number[]) => { + if (!isCurrentAudio || !displayHasValidDuration) return + AudioPlayer.seek(value[0]!) + setIsDragging(false) + }, + [isCurrentAudio, displayHasValidDuration], + ) // Don't render if no audio attachment if (!audioAttachment) { return null } - const progressPercent = displayHasValidDuration ? (displayCurrentTime / displayDuration) * 100 : 0 + // Calculate slider value - use drag value when dragging, otherwise use current time + const sliderValue = isDragging ? dragValue : displayCurrentTime + const currentTimeDisplay = formatDuration(sliderValue) + const durationDisplay = formatDuration(displayDuration) return ( - {/* Control buttons and progress bar */} -
- {/* Control buttons */} -
- {/* Skip Back 10s */} - + {/* Inner glow layer */} +
- {/* Play/Pause Button */} - - - {/* Skip Forward 10s */} - -
- - {/* Progress Bar Container */} -
-
-
+ {/* Control buttons and progress bar */} +
+ {/* Control buttons */} +
+ {/* Skip Back 10s */} + + + {/* Play/Pause Button */} + + + {/* Skip Forward 10s */} + +
+ + {/* Progress Bar Container */} +
+ {displayHasValidDuration ? ( + { + if (isCurrentAudio) { + setIsDragging(true) + setDragValue(displayCurrentTime) + } + }} + onValueChange={handleSliderValueChange} + onValueCommit={handleSliderValueCommit} + > + + + + + + + ) : ( +
+ )} +
+ + {/* Time Display and Download */} +
+
+ {currentTimeDisplay} + / + {durationDisplay}
-
-
- {/* Time Display and Download */} -
-
- {currentTimeDisplay} - / - {durationDisplay} -
+ {/* Divider */} +
- {/* Download Button */} - + {/* Download Button */} + +
diff --git a/apps/desktop/layer/renderer/src/modules/entry-content/components/selection/GlassButton.tsx b/apps/desktop/layer/renderer/src/modules/entry-content/components/selection/GlassButton.tsx new file mode 100644 index 000000000..899116d8f --- /dev/null +++ b/apps/desktop/layer/renderer/src/modules/entry-content/components/selection/GlassButton.tsx @@ -0,0 +1,67 @@ +import { cn } from "@follow/utils" +import type { HTMLMotionProps } from "motion/react" +import { m } from "motion/react" + +interface GlassButtonProps extends HTMLMotionProps<"button"> { + variant?: "primary" | "secondary" + isLoading?: boolean + ref?: React.Ref +} + +export const GlassButton = ({ + className, + variant = "primary", + isLoading, + children, + disabled, + ref, + ...props +}: GlassButtonProps) => { + const isPrimary = variant === "primary" + + return ( + + {/* Hover shine effect for primary */} + {isPrimary && ( +
+ )} + {children as React.ReactNode} + + ) +} + +GlassButton.displayName = "GlassButton" diff --git a/apps/desktop/layer/renderer/src/modules/entry-content/components/selection/SharePosterModal.tsx b/apps/desktop/layer/renderer/src/modules/entry-content/components/selection/SharePosterModal.tsx new file mode 100644 index 000000000..de7bf7a6a --- /dev/null +++ b/apps/desktop/layer/renderer/src/modules/entry-content/components/selection/SharePosterModal.tsx @@ -0,0 +1,535 @@ +import { Spring } from "@follow/components/constants/spring.js" +import { useEntry } from "@follow/store/entry/hooks" +import { useFeedById } from "@follow/store/feed/hooks" +import { cn } from "@follow/utils" +import { m } from "motion/react" +import { useCallback, useEffect, useRef, useState } from "react" +import { useTranslation } from "react-i18next" +import { toast } from "sonner" + +import { useCurrentModal } from "~/components/ui/modal/stacked/hooks" +import { copyImageToClipboard } from "~/lib/clipboard" +import { UrlBuilder } from "~/lib/url-builder" + +import { GlassButton } from "./GlassButton" + +type SharePosterModalProps = { + selectedText: string + entryId: string +} + +type Mode = "light" | "dark" + +export function SharePosterModal({ selectedText, entryId }: SharePosterModalProps) { + const { t } = useTranslation() + const { dismiss } = useCurrentModal() + const canvasRef = useRef(null) + const [isCopying, setIsCopying] = useState(false) + const [authorAvatarImg, setAuthorAvatarImg] = useState(null) + const [mode, setMode] = useState( + document.documentElement.classList.contains("dark") ? "dark" : "light", + ) + + const entry = useEntry(entryId, (state) => ({ + title: state.title, + feedId: state.feedId, + author: state.author, + authorAvatar: state.authorAvatar, + publishedAt: state.publishedAt, + url: state.url, + })) + + const feed = useFeedById(entry?.feedId) + + // Load author avatar image + useEffect(() => { + if (entry?.authorAvatar) { + loadImage(entry.authorAvatar).then(setAuthorAvatarImg) + } else { + setAuthorAvatarImg(null) + } + }, [entry?.authorAvatar]) + + const draw = useCallback(() => { + const canvas = canvasRef.current + if (!canvas) return + + const ctx = canvas.getContext("2d", { + alpha: false, // Better performance for opaque backgrounds + desynchronized: false, // Better quality + }) + if (!ctx) return + + // High resolution for crisp text - use higher scale for better quality + // Scale 3 provides excellent quality for long text + const scale = 3 + const baseWidth = 720 + const width = baseWidth * scale + + // --- Config --- + const baseConfig = { + bg: mode === "dark" ? "#0f0f0f" : "#ffffff", + bgGradient: + mode === "dark" ? ["#1a1a1a", "#0f0f0f", "#0a0a0a"] : ["#fafafa", "#ffffff", "#f5f5f5"], + text: mode === "dark" ? "#f5f5f5" : "#1a1a1a", + textSecondary: mode === "dark" ? "#a3a3a3" : "#525252", + accent: mode === "dark" ? "#737373" : "#737373", + quoteColor: mode === "dark" ? "#404040" : "#e5e5e5", + logoColor: mode === "dark" ? "#ff5c00" : "#ff5c00", + fontFamilyTitle: "-apple-system, BlinkMacSystemFont, 'SF Pro Display', system-ui, sans-serif", + fontFamilyBody: "-apple-system, BlinkMacSystemFont, 'SF Pro Text', system-ui, sans-serif", + fontFamilyMeta: "-apple-system, BlinkMacSystemFont, 'SF Pro Text', system-ui, sans-serif", + sizeTitle: 36, + sizeBody: 26, + sizeMeta: 14, + lineHeight: 1.7, + titleLineHeight: 1.4, + maxBodyLines: 18, // Limit body text to 18 lines + } + + const config = { + ...baseConfig, + fontTitle: `600 ${baseConfig.sizeTitle}px ${baseConfig.fontFamilyTitle}`, + fontBody: `400 ${baseConfig.sizeBody}px ${baseConfig.fontFamilyBody}`, + fontMeta: `500 ${baseConfig.sizeMeta}px ${baseConfig.fontFamilyMeta}`, + } + + // --- Measure Height --- + const padding = 56 + const contentWidth = width / scale - padding * 2 + + // Measure Body - with truncation + ctx.font = config.fontBody + const allBodyLines = wrapText(ctx, selectedText, contentWidth) + const bodyLines = allBodyLines.slice(0, config.maxBodyLines) + const bodyHeight = bodyLines.length * (baseConfig.sizeBody * config.lineHeight) + + // Measure Title + let titleHeight = 0 + if (entry?.title) { + ctx.font = config.fontTitle + const titleLines = wrapText(ctx, entry.title, contentWidth) + titleHeight = titleLines.length * (baseConfig.sizeTitle * config.titleLineHeight) + 24 // + margin + } + + // Total Height Calculation + const headerHeight = 72 + const authorHeight = entry?.author ? 48 : 0 // Increased for avatar + const footerHeight = 80 // Increased for logo + const spacing = 48 + const quoteSpacing = 32 + + const totalContentHeight = + padding + + headerHeight + + quoteSpacing + + bodyHeight + + spacing + + titleHeight + + authorHeight + + footerHeight + + padding + const minHeight = 800 + const finalHeight = Math.max(minHeight, totalContentHeight) * scale + + // Resize canvas + canvas.width = width + canvas.height = finalHeight + + // Enable high-quality rendering + ctx.imageSmoothingEnabled = true + ctx.imageSmoothingQuality = "high" + + // Scale context for high DPI rendering + ctx.scale(scale, scale) + + const w = width / scale + const h = finalHeight / scale + + // --- Background with Gradient --- + const gradient = ctx.createLinearGradient(0, 0, 0, h) + const bgColors = config.bgGradient + gradient.addColorStop(0, bgColors[0] ?? config.bg) + gradient.addColorStop(0.5, bgColors[1] ?? config.bg) + gradient.addColorStop(1, bgColors[2] ?? config.bg) + ctx.fillStyle = gradient + ctx.fillRect(0, 0, w, h) + + // Subtle texture overlay + ctx.save() + ctx.globalAlpha = 0.03 + for (let i = 0; i < w; i += 4) { + for (let j = 0; j < h; j += 4) { + if ((i + j) % 8 === 0) { + ctx.fillStyle = mode === "dark" ? "#ffffff" : "#000000" + ctx.fillRect(i, j, 1, 1) + } + } + } + ctx.restore() + + // --- Layout Drawing --- + let currentY = padding + 24 + + // 1. Header (Feed Info) + ctx.fillStyle = config.textSecondary + ctx.globalAlpha = 0.7 + ctx.font = config.fontMeta + ctx.textAlign = "left" + ctx.textBaseline = "top" + + const dateStr = entry?.publishedAt + ? new Date(entry.publishedAt).toLocaleDateString(undefined, { + year: "numeric", + month: "short", + day: "numeric", + }) + : new Date().toLocaleDateString() + + const headerText = `${feed?.title || "Folo"} • ${dateStr}` + ctx.fillText(headerText, padding, currentY) + + currentY += headerHeight + + // 2. Quote Body with improved styling + ctx.save() + + // Decorative Quote Mark - larger and more refined + ctx.fillStyle = config.quoteColor + ctx.globalAlpha = 0.4 + ctx.font = "bold 64px Georgia, serif" + ctx.textAlign = "left" + ctx.textBaseline = "top" + ctx.fillText("\u201C", padding - 36, currentY - 24) + + ctx.restore() + + // Body text with better spacing + ctx.fillStyle = config.text + ctx.globalAlpha = 1 + ctx.font = config.fontBody + ctx.textAlign = "left" + ctx.textBaseline = "top" + + bodyLines.forEach((line, index) => { + // Add slight indentation for continuation lines + const indent = index === 0 ? 0 : 24 + ctx.fillText(line, padding + indent, currentY) + currentY += baseConfig.sizeBody * config.lineHeight + }) + + // Show truncation indicator if text was truncated + if (allBodyLines.length > config.maxBodyLines) { + currentY += 8 + ctx.fillStyle = config.textSecondary + ctx.globalAlpha = 0.6 + ctx.font = config.fontMeta + ctx.fillText("...", padding, currentY) + ctx.globalAlpha = 1 + } + + currentY += spacing + + // 3. Divider line + ctx.save() + ctx.strokeStyle = config.quoteColor + ctx.globalAlpha = 0.2 + ctx.lineWidth = 1 + ctx.beginPath() + ctx.moveTo(padding, currentY - spacing / 2) + ctx.lineTo(w - padding, currentY - spacing / 2) + ctx.stroke() + ctx.restore() + + // 4. Entry Title & Author + if (entry?.title) { + currentY += 8 + ctx.fillStyle = config.text + ctx.globalAlpha = 0.9 + ctx.font = config.fontTitle + const titleLines = wrapText(ctx, entry.title, contentWidth) + titleLines.forEach((line) => { + ctx.fillText(line, padding, currentY) + currentY += baseConfig.sizeTitle * config.titleLineHeight + }) + } + + if (entry?.author) { + currentY += 16 + + // Draw author avatar if available + const avatarSize = 32 + const avatarX = padding + const avatarY = currentY + + if (authorAvatarImg) { + // Draw circular avatar + ctx.save() + ctx.beginPath() + ctx.arc(avatarX + avatarSize / 2, avatarY + avatarSize / 2, avatarSize / 2, 0, Math.PI * 2) + ctx.clip() + ctx.drawImage(authorAvatarImg, avatarX, avatarY, avatarSize, avatarSize) + ctx.restore() + } + + // Draw author name + ctx.fillStyle = config.textSecondary + ctx.globalAlpha = 0.8 + ctx.font = config.fontMeta + const authorTextX = authorAvatarImg ? padding + avatarSize + 12 : padding + ctx.fillText(`By ${entry.author}`, authorTextX, avatarY + avatarSize / 2 - 7) + ctx.globalAlpha = 1 + } + + // 5. Footer / Branding - Draw Folo logo and text + const footerY = h - padding - 24 + const logoSize = 36 + const gap = 16 + const svgScale = logoSize / 24 + + // Calculate positions for [Logo] [Folo] aligned to right + // Total width = logoSize + gap + logoSize (assuming folo text is also 24x24 scaled) + const totalWidth = logoSize + gap + logoSize + const startX = w - padding - totalWidth + + const logoX = startX + const foloX = startX + logoSize + gap + const drawY = footerY - logoSize / 2 + + ctx.save() + + // Draw Logo + ctx.translate(logoX, drawY) + ctx.scale(svgScale, svgScale) + + // Logo Background + ctx.fillStyle = config.logoColor + const logoBgPath = new Path2D( + "M5.382 0h13.236A5.37 5.37 0 0 1 24 5.383v13.235A5.37 5.37 0 0 1 18.618 24H5.382A5.37 5.37 0 0 1 0 18.618V5.383A5.37 5.37 0 0 1 5.382.001Z", + ) + ctx.fill(logoBgPath) + + // Logo F + ctx.fillStyle = "#ffffff" + const logoFPath = new Path2D( + "M13.269 17.31a1.813 1.813 0 1 0-3.626.002 1.813 1.813 0 0 0 3.626-.002m-.535-6.527H7.213a1.813 1.813 0 1 0 0 3.624h5.521a1.813 1.813 0 1 0 0-3.624m4.417-4.712H8.87a1.813 1.813 0 1 0 0 3.625h8.283a1.813 1.813 0 1 0 0-3.624z", + ) + ctx.fill(logoFPath) + + ctx.restore() + + // Draw Folo Text + ctx.save() + ctx.translate(foloX, drawY) + ctx.scale(svgScale, svgScale) + + ctx.fillStyle = config.textSecondary + ctx.globalAlpha = 0.6 + const foloPath = new Path2D( + "M.899 16.997c-.567 0-.899-.358-.899-.994v-7.77c0-.637.36-.996 1.01-.996h4.34c.595 0 .927.29.927.788 0 .497-.332.774-.926.774H1.797v2.336H5.06c.595 0 .927.263.927.76 0 .512-.332.775-.927.775H1.797v3.332c0 .636-.318.996-.898.996m9.035.125c-2.101 0-3.553-1.52-3.553-3.664 0-2.17 1.438-3.705 3.553-3.705 2.13 0 3.567 1.534 3.567 3.705 0 2.143-1.452 3.664-3.567 3.664m0-1.493c1.134 0 1.825-.899 1.825-2.185 0-1.3-.691-2.198-1.825-2.198s-1.797.899-1.797 2.198c0 1.286.663 2.185 1.797 2.185m5.266 1.367c-.553 0-.857-.359-.857-.967V7.845c0-.608.304-.968.857-.968s.857.36.857.968v8.185c0 .608-.29.967-.857.967m5.234.125c-2.102 0-3.553-1.52-3.553-3.664 0-2.17 1.438-3.705 3.553-3.705 2.129 0 3.566 1.534 3.566 3.704 0 2.143-1.452 3.664-3.567 3.664m0-1.493c1.134 0 1.825-.899 1.825-2.185 0-1.3-.691-2.198-1.825-2.198s-1.797.899-1.797 2.198c0 1.286.663 2.185 1.797 2.185", + ) + ctx.fill(foloPath) + + ctx.restore() + }, [entry, feed, mode, selectedText, authorAvatarImg]) + + useEffect(() => { + draw() + }, [draw]) + + const handleCopy = useCallback(async () => { + if (!canvasRef.current || isCopying) return + + setIsCopying(true) + try { + await copyImageToClipboard(canvasRef.current) + toast.success(t("entry_content.selection_toolbar.poster_copied")) + dismiss() + } catch (error) { + console.error("Failed to copy image:", error) + toast.error(t("entry_content.selection_toolbar.poster_copy_failed")) + } finally { + setIsCopying(false) + } + }, [isCopying, t, dismiss]) + + const handleShareToX = useCallback(() => { + if (!entry) return + const text = selectedText.length > 200 ? `${selectedText.slice(0, 200)}...` : selectedText + const shareUrl = UrlBuilder.shareEntry(entryId) + const intentUrl = `https://x.com/intent/tweet?text=${encodeURIComponent(text)}&url=${encodeURIComponent(shareUrl)}` + window.open(intentUrl, "_blank") + }, [entry, selectedText, entryId]) + + return ( +
e.stopPropagation()}> +
+ {/* Preview Card */} + + + + + {/* Floating Toolbar - Glassmorphic Design */} + + {/* Inner glow layer */} +
+ + {/* Content */} +
+ {/* Mode Toggle - Glassmorphic Button */} + setMode(mode === "light" ? "dark" : "light")} + className={cn( + "relative flex size-8 items-center justify-center rounded-full", + "text-text-secondary transition-all duration-300", + "hover:bg-fill/20 hover:text-text", + )} + whileTap={{ scale: 0.95 }} + title="Toggle Appearance" + > + + + + {/* Share to X */} + + + + + {/* Divider */} +
+ + {/* Actions */} +
+ dismiss()}> + {t("words.close", { ns: "common" })} + + + {isCopying ? ( + + ) : ( + + )} + + {isCopying + ? t("entry_content.selection_toolbar.copying") + : t("entry_content.selection_toolbar.copy_image")} + + +
+
+ +
+
+ ) +} + +// Helper function to load image from URL +function loadImage(url: string): Promise { + return new Promise((resolve) => { + const img = new Image() + img.crossOrigin = "anonymous" + img.onload = () => resolve(img) + img.onerror = () => resolve(null) + img.src = url + }) +} + +function wrapText(ctx: CanvasRenderingContext2D, text: string, maxWidth: number): string[] { + const lines: string[] = [] + + // Check if text contains Chinese/Japanese/Korean characters + const hasCJK = /[\u4e00-\u9fff\u3040-\u309f\u30a0-\u30ff\uac00-\ud7af]/.test(text) + + if (hasCJK) { + // For CJK text, split by character and build lines + let currentLine = "" + + for (const char of text) { + const testLine = currentLine + char + const metrics = ctx.measureText(testLine) + + if (metrics.width > maxWidth && currentLine.length > 0) { + lines.push(currentLine) + currentLine = char + } else { + currentLine = testLine + } + } + + if (currentLine) { + lines.push(currentLine) + } + } else { + // For non-CJK text, split by words + const words = text.split(/\s+/) + let currentLine = words[0] || "" + + for (let i = 1; i < words.length; i++) { + const word = words[i] + if (!word) continue + const testLine = currentLine ? `${currentLine} ${word}` : word + const metrics = ctx.measureText(testLine) + + if (metrics.width > maxWidth && currentLine.length > 0) { + lines.push(currentLine) + currentLine = word + } else { + currentLine = testLine + } + } + + if (currentLine) { + lines.push(currentLine) + } + } + + return lines.length > 0 ? lines : [text] +} diff --git a/apps/desktop/layer/renderer/src/modules/entry-content/components/selection/TextSelectionToolbar.tsx b/apps/desktop/layer/renderer/src/modules/entry-content/components/selection/TextSelectionToolbar.tsx new file mode 100644 index 000000000..769cbf7f3 --- /dev/null +++ b/apps/desktop/layer/renderer/src/modules/entry-content/components/selection/TextSelectionToolbar.tsx @@ -0,0 +1,215 @@ +import { Spring } from "@follow/components/constants/spring.js" +import { RootPortal } from "@follow/components/ui/portal/index.js" +import { cn } from "@follow/utils" +import { m } from "motion/react" +import type { CSSProperties, MouseEventHandler } from "react" +import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react" +import { useTranslation } from "react-i18next" + +import { PlainModal } from "~/components/ui/modal/stacked/custom-modal" +import { useModalStack } from "~/components/ui/modal/stacked/hooks" +import { copyToClipboard } from "~/lib/clipboard" +import type { TextSelectionEvent } from "~/lib/simple-text-selection" + +import { SharePosterModal } from "./SharePosterModal" + +const styles = { + toolbar: { + backgroundImage: + "linear-gradient(to bottom right, rgba(var(--color-background) / 0.98), rgba(var(--color-background) / 0.95))", + boxShadow: + "0 8px 24px rgba(0, 0, 0, 0.12), 0 4px 12px rgba(0, 0, 0, 0.08), 0 2px 6px rgba(0, 0, 0, 0.06), 0 4px 16px hsl(var(--fo-a) / 0.08), 0 2px 8px hsl(var(--fo-a) / 0.06), 0 1px 3px rgba(0, 0, 0, 0.04)", + } as CSSProperties, + innerGlow: { + background: + "linear-gradient(to bottom right, hsl(var(--fo-a) / 0.02), transparent, hsl(var(--fo-a) / 0.02))", + } as CSSProperties, +} + +type TextSelectionToolbarProps = { + selection: TextSelectionEvent | null + onRequestClose: () => void + onAskAI?: (selection: TextSelectionEvent) => void + entryId?: string +} + +const DEFAULT_DIMENSIONS = { + width: 220, + height: 48, +} + +const VIEWPORT_PADDING = 12 + +export function TextSelectionToolbar({ + selection, + onRequestClose, + onAskAI, + entryId, +}: TextSelectionToolbarProps) { + const { t } = useTranslation() + const { present } = useModalStack() + const toolbarRef = useRef(null) + const [toolbarSize, setToolbarSize] = useState(DEFAULT_DIMENSIONS) + const [copied, setCopied] = useState(false) + const [viewport, setViewport] = useState(() => getViewport()) + + useEffect(() => { + const handleResize = () => setViewport(getViewport()) + window.addEventListener("resize", handleResize) + return () => { + window.removeEventListener("resize", handleResize) + } + }, []) + + useEffect(() => { + if (!selection) return + + const handleScroll = () => onRequestClose() + window.addEventListener("scroll", handleScroll, true) + return () => { + window.removeEventListener("scroll", handleScroll, true) + } + }, [selection, onRequestClose]) + + useLayoutEffect(() => { + if (!selection || !toolbarRef.current) return + const rect = toolbarRef.current.getBoundingClientRect() + setToolbarSize({ + width: rect.width || DEFAULT_DIMENSIONS.width, + height: rect.height || DEFAULT_DIMENSIONS.height, + }) + }, [selection, copied]) + + useEffect(() => { + if (!copied) return + const timer = setTimeout(() => setCopied(false), 1600) + return () => clearTimeout(timer) + }, [copied]) + + const position = useMemo(() => { + if (!selection) return null + const { rect } = selection + const toolbarHeight = toolbarSize.height || DEFAULT_DIMENSIONS.height + const toolbarWidth = toolbarSize.width || DEFAULT_DIMENSIONS.width + const viewportWidth = viewport.width || toolbarWidth + + let top = rect.top - toolbarHeight - VIEWPORT_PADDING + if (top < VIEWPORT_PADDING) { + top = rect.bottom + VIEWPORT_PADDING + } + + let left = rect.left + rect.width / 2 - toolbarWidth / 2 + const maxLeft = Math.max(VIEWPORT_PADDING, viewportWidth - toolbarWidth - VIEWPORT_PADDING) + left = clamp(left, VIEWPORT_PADDING, maxLeft) + + return { top, left } + }, [selection, toolbarSize, viewport]) + + const handleCopy = useCallback(async () => { + if (!selection) return + await copyToClipboard(selection.selectedText) + setCopied(true) + }, [selection]) + + const handleShare = useCallback(() => { + if (!selection || !entryId) return + present({ + CustomModalComponent: PlainModal, + title: t("entry_content.selection_toolbar.share_poster"), + id: "share-poster", + content: () => , + clickOutsideToDismiss: true, + }) + onRequestClose() + }, [selection, entryId, present, onRequestClose, t]) + + const handleMouseDown: MouseEventHandler = (event) => { + event.preventDefault() + } + + if (!selection || !position) return null + + return ( + + + {/* Inner glow layer */} +
+
+ + {entryId ? ( + + ) : null} + {onAskAI ? ( + onAskAI(selection)} + /> + ) : null} +
+ + + ) +} + +type ToolbarButtonProps = { + iconClassName: string + label: string + onClick?: () => void + active?: boolean +} + +function ToolbarButton({ iconClassName, label, onClick, active }: ToolbarButtonProps) { + return ( + + ) +} + +const clamp = (value: number, min: number, max: number) => Math.min(Math.max(value, min), max) + +function getViewport() { + if (typeof window === "undefined") { + return { width: 0, height: 0 } + } + + return { width: window.innerWidth, height: window.innerHeight } +} diff --git a/apps/desktop/layer/renderer/src/modules/entry/EntryTags.tsx b/apps/desktop/layer/renderer/src/modules/entry/EntryTags.tsx new file mode 100644 index 000000000..c520f3208 --- /dev/null +++ b/apps/desktop/layer/renderer/src/modules/entry/EntryTags.tsx @@ -0,0 +1,143 @@ +import { Button } from "@follow/components/ui/button/index.js" +import { ScrollArea } from "@follow/components/ui/scroll-area/ScrollArea.js" +import { FeedViewType } from "@follow/constants" +import type { EntryTagSummary } from "@follow/database/schemas/types" +import { useEntryTagsQuery } from "@follow/store/entry/hooks" +import { cn } from "@follow/utils" +import { useMemo } from "react" +import { titleCase } from "title-case" + +import { useModalStack } from "~/components/ui/modal/stacked/hooks" + +import { EntryItemSkeleton } from "../entry-column/EntryItemSkeleton" +import { EntryItem } from "../entry-column/item" + +type TagKind = "category" | "topic" + +interface EntryTagsProps { + tags?: EntryTagSummary | null + feedId?: string | null + size?: "sm" | "md" + className?: string +} + +const normalizeLabel = (label: string) => titleCase(label.replaceAll(/[_-]+/g, " ")) + +const chipClassName: Record, string> = { + sm: "px-2 py-0.5 text-[11px]", + md: "px-2.5 py-1 text-xs", +} + +type TagItem = { label: string; kind: TagKind } + +const TagEntriesModal = ({ tag, feedId }: { tag: TagItem; feedId?: string | null }) => { + const { data, isLoading, isFetching, refetch } = useEntryTagsQuery({ + feedId, + tag: + tag.kind === "category" + ? { kind: "schemaOrgCategory", value: tag.label } + : { kind: "mediaTopic", value: tag.label }, + }) + + const entryIds = data ?? [] + + return ( +
+
+
+ Entries tagged with {normalizeLabel(tag.label)} +
+ +
+ + {isLoading ? ( +
+ +
+ ) : entryIds.length === 0 ? ( +
+ + No entries found for this tag. +
+ ) : ( + + {entryIds.map((entryId) => ( + + ))} + + )} +
+ ) +} + +export const EntryTags = ({ + tags, + size = "md", + className, + + feedId, +}: EntryTagsProps) => { + const { present } = useModalStack() + + const items = useMemo(() => { + if (!tags) return [] + const list: TagItem[] = [] + if (tags.schemaOrgCategory) { + list.push({ label: tags.schemaOrgCategory, kind: "category" }) + } + if (Array.isArray(tags.mediaTopics)) { + for (const topic of tags.mediaTopics) { + if (topic) { + list.push({ label: topic, kind: "topic" }) + } + } + } + return list + }, [tags]) + if (!tags) return null + if (items.length === 0) return null + + const handleClick = (item: TagItem, event: React.MouseEvent) => { + event.stopPropagation() + event.preventDefault() + if (!feedId) return + present({ + title: `Tag · ${normalizeLabel(item.label)}`, + content: () => , + clickOutsideToDismiss: true, + overlay: true, + modal: true, + modalClassName: "max-w-[760px]", + }) + } + + return ( +
+ {items.map((item, index) => ( + + ))} +
+ ) +} diff --git a/apps/desktop/layer/renderer/src/modules/feed/feed-certification.tsx b/apps/desktop/layer/renderer/src/modules/feed/feed-certification.tsx index edd41757e..9c956951d 100644 --- a/apps/desktop/layer/renderer/src/modules/feed/feed-certification.tsx +++ b/apps/desktop/layer/renderer/src/modules/feed/feed-certification.tsx @@ -11,7 +11,7 @@ import { useUserById, useWhoami } from "@follow/store/user/hooks" import { cn } from "@follow/utils/utils" import { useTranslation } from "react-i18next" -import { replaceImgUrlIfNeed } from "~/lib/img-proxy" +import { useReplaceImgUrlIfNeed } from "~/lib/img-proxy" import { usePresentUserProfileModal } from "~/modules/profile/hooks" export const FeedCertification = ({ @@ -76,6 +76,7 @@ export const FeedCertification = ({ } const FeedCertificateAvatar = ({ userId }: { userId: string }) => { + const replaceImgUrlIfNeed = useReplaceImgUrlIfNeed() const user = useUserById(userId) const presentUserProfile = usePresentUserProfileModal("drawer") if (!user) return null diff --git a/apps/desktop/layer/renderer/src/modules/feed/feed-icon.tsx b/apps/desktop/layer/renderer/src/modules/feed/feed-icon.tsx index fd62bc16b..ed8106143 100644 --- a/apps/desktop/layer/renderer/src/modules/feed/feed-icon.tsx +++ b/apps/desktop/layer/renderer/src/modules/feed/feed-icon.tsx @@ -9,6 +9,8 @@ import { m } from "motion/react" import type { ReactNode } from "react" import { useMemo } from "react" +import { useCanUseImageProxy } from "~/lib/img-proxy" + const { Avatar, AvatarFallback, AvatarImage } = AvatarPrimitive // Size-responsive border radius utility function @@ -27,9 +29,19 @@ type GetIconPropsProps = { fallbackUrl?: string fallback?: boolean size?: number + canUseProxy?: boolean } function getIconProps(props: GetIconPropsProps) { - const { target, entry, useMedia, siteUrl: propSiteUrl, fallbackUrl, fallback, size = 20 } = props + const { + target, + entry, + useMedia, + siteUrl: propSiteUrl, + fallbackUrl, + fallback, + size = 20, + canUseProxy, + } = props const image = (useMedia ? entry?.firstPhotoUrl || entry?.authorAvatar : entry?.authorAvatar) || target?.image const siteUrl = (target as FeedModel)?.siteUrl || fallbackUrl @@ -37,6 +49,7 @@ function getIconProps(props: GetIconPropsProps) { if (propSiteUrl && !target) { const [src] = getFeedIconSrc({ siteUrl: propSiteUrl, + canUseProxy, }) return { type: "image" as const, @@ -52,6 +65,7 @@ function getIconProps(props: GetIconPropsProps) { url: image, width: size * 2, height: size * 2, + canUseProxy, }), platformUrl: image, fallbackSrc: "", @@ -66,6 +80,7 @@ function getIconProps(props: GetIconPropsProps) { width: size * 2, height: size * 2, }, + canUseProxy, }) return { type: "image" as const, @@ -96,11 +111,13 @@ const getFeedIconSrc = ({ siteUrl, fallback, proxy, + canUseProxy, }: { src?: string siteUrl?: string fallback?: boolean proxy?: { height: number; width: number } + canUseProxy?: boolean } = {}) => { if (src) { if (proxy) { @@ -109,6 +126,7 @@ const getFeedIconSrc = ({ url: src, width: proxy.width, height: proxy.height, + canUseProxy, }), "", ] @@ -200,7 +218,17 @@ export function FeedIcon({ noMargin?: boolean }) { const marginClassName = cn(noMargin ? "" : "mr-2", className) - const iconProps = getIconProps({ target, entry, useMedia, siteUrl, fallbackUrl, fallback, size }) + const canUseProxy = useCanUseImageProxy() + const iconProps = getIconProps({ + target, + entry, + useMedia, + siteUrl, + fallbackUrl, + fallback, + size, + canUseProxy, + }) const colors = useMemo( () => getBackgroundGradient(target?.title || (target as FeedModel)?.url || siteUrl || ""), diff --git a/apps/desktop/layer/renderer/src/modules/integration/custom-integration-manager.ts b/apps/desktop/layer/renderer/src/modules/integration/custom-integration-manager.ts index d780b4db8..86c54abf2 100644 --- a/apps/desktop/layer/renderer/src/modules/integration/custom-integration-manager.ts +++ b/apps/desktop/layer/renderer/src/modules/integration/custom-integration-manager.ts @@ -182,13 +182,13 @@ export class CustomIntegrationManager { const processedKey = this.replacePlaceholders(key, context) const processedValue = this.replacePlaceholders(value, context) // Field names are case-insensitive. - processedHeaders[processedKey.toLowerCase()] = processedValue + processedHeaders[processedKey.toLowerCase().trim()] = processedValue.trim() }) // Process body without URL encoding let processedBody: string | undefined if (fetchTemplate.body) { - const jsonEscape = fetchTemplate.headers["content-type"]?.toLowerCase() === "application/json" + const jsonEscape = processedHeaders["content-type"]?.toLowerCase() === "application/json" processedBody = this.replacePlaceholders(fetchTemplate.body, context, { jsonEscape }) } diff --git a/apps/desktop/layer/renderer/src/modules/profile/user-profile-modal/shared.tsx b/apps/desktop/layer/renderer/src/modules/profile/user-profile-modal/shared.tsx index be3f93fa0..7ac3af135 100644 --- a/apps/desktop/layer/renderer/src/modules/profile/user-profile-modal/shared.tsx +++ b/apps/desktop/layer/renderer/src/modules/profile/user-profile-modal/shared.tsx @@ -21,7 +21,7 @@ import { useEventCallback } from "usehooks-ts" import { m } from "~/components/common/Motion" import { useFollow } from "~/hooks/biz/useFollow" import { useI18n } from "~/hooks/common" -import { replaceImgUrlIfNeed } from "~/lib/img-proxy" +import { useReplaceImgUrlIfNeed } from "~/lib/img-proxy" import { FeedIcon } from "~/modules/feed/feed-icon" import { useUserSubscriptionsQuery } from "~/modules/profile/hooks" @@ -39,6 +39,7 @@ export const SubscriptionItems = ({ userId: string itemStyle: ItemVariant }) => { + const replaceImgUrlIfNeed = useReplaceImgUrlIfNeed() const profile = usePrefetchUser(userId) const userInfo = useUserById(userId) const subscriptions = useUserSubscriptionsQuery(userId) diff --git a/apps/desktop/layer/renderer/src/modules/settings/modal/SettingModalContent.tsx b/apps/desktop/layer/renderer/src/modules/settings/modal/SettingModalContent.tsx index 70c23e1eb..b12f6e2a8 100644 --- a/apps/desktop/layer/renderer/src/modules/settings/modal/SettingModalContent.tsx +++ b/apps/desktop/layer/renderer/src/modules/settings/modal/SettingModalContent.tsx @@ -137,7 +137,7 @@ const Content: FC<{ const elementTop = element.offsetTop const scrollerTop = scroller.scrollTop - const delta = elementTop - scrollerTop + const delta = elementTop - scrollerTop - 20 scroller.scrollTo({ top: delta, diff --git a/apps/desktop/layer/renderer/src/modules/settings/tabs/ai.tsx b/apps/desktop/layer/renderer/src/modules/settings/tabs/ai.tsx index 894dbad3a..d1cb7c823 100644 --- a/apps/desktop/layer/renderer/src/modules/settings/tabs/ai.tsx +++ b/apps/desktop/layer/renderer/src/modules/settings/tabs/ai.tsx @@ -20,6 +20,7 @@ const defineSettingItem = createDefineSettingItem("ai", useAISettingValue, setAI export const AI_SETTING_SECTION_IDS = { shortcuts: "settings-ai-shortcuts", tasks: "settings-ai-tasks", + timelinePrompt: "settings-ai-timeline-prompt", } as const export const SettingAI = () => { diff --git a/apps/desktop/layer/renderer/src/modules/settings/tabs/ai/TimelinePromptSection.tsx b/apps/desktop/layer/renderer/src/modules/settings/tabs/ai/TimelinePromptSection.tsx new file mode 100644 index 000000000..27af07d3c --- /dev/null +++ b/apps/desktop/layer/renderer/src/modules/settings/tabs/ai/TimelinePromptSection.tsx @@ -0,0 +1,143 @@ +import { Spring } from "@follow/components/constants/spring.js" +import { Button } from "@follow/components/ui/button/index.js" +import { TextArea } from "@follow/components/ui/input/index.js" +import { AnimatePresence } from "motion/react" +import { useEffect, useRef, useState } from "react" +import { useTranslation } from "react-i18next" +import { toast } from "sonner" + +import { setAISetting, useAISettingValue } from "~/atoms/settings/ai" +import { m } from "~/components/common/Motion" + +import { SettingDescription } from "../../control" +import { SettingModalContentPortal } from "../../modal/layout" + +export const TimelinePromptSection = () => { + const { t } = useTranslation("ai") + const aiSettings = useAISettingValue() + const promptRef = useRef("") + const [isSaving, setIsSaving] = useState(false) + const [currentLength, setCurrentLength] = useState(0) + const [hasChanges, setHasChanges] = useState(false) + const [promptValue, setPromptValue] = useState(aiSettings.aiTimelinePrompt) + + const MAX_CHARACTERS = 500 + const isOverLimit = currentLength > MAX_CHARACTERS + + useEffect(() => { + promptRef.current = aiSettings.aiTimelinePrompt + setPromptValue(aiSettings.aiTimelinePrompt) + setCurrentLength(aiSettings.aiTimelinePrompt.length) + setHasChanges(false) + }, [aiSettings.aiTimelinePrompt]) + + const handleEditorChange = (value: string) => { + promptRef.current = value + setPromptValue(value) + setCurrentLength(value.length) + setHasChanges(value !== aiSettings.aiTimelinePrompt) + } + + const handleSave = async () => { + if (isOverLimit) { + toast.error(`Prompt must be ${MAX_CHARACTERS} characters or less`) + return + } + + if (!promptRef.current) return + + setIsSaving(true) + try { + setAISetting("aiTimelinePrompt", promptRef.current) + toast.success(t("timeline_prompt.saved")) + setHasChanges(false) + } finally { + setIsSaving(false) + } + } + + return ( +
+
+
+