From cf47ef442f07a71e50c7f2198c2e735e7c4427f5 Mon Sep 17 00:00:00 2001 From: Innei Date: Fri, 1 Aug 2025 21:30:30 +0800 Subject: [PATCH] feat(ai): listen for user text selection add to ai block - Added text selection capabilities to ShadowDOM, allowing for text selection events to be captured and handled. - Introduced a new utility for managing text selection within ShadowDOM. - Updated ArticleLayout to support text selection events and integrate with AI chat block actions. - Refactored EntryContent components to improve error handling and streamline entry updates. - Implemented a new AIEntryLayout for better integration of AI chat features within entry content. Signed-off-by: Innei --- .../src/components/common/ShadowDOM.tsx | 51 +++++++++++-- .../src/components/ui/markdown/HTML.tsx | 22 +++++- .../renderer/src/lib/simple-text-selection.ts | 51 +++++++++++++ .../ai/chat/__internal__/AIChatContext.ts | 17 ----- .../__internal__/chat-core/chat-actions.ts | 6 +- .../chat/__internal__/slices/block.slice.ts | 47 ++++++------ .../modules/ai/chat/components/AIChatRoot.tsx | 45 +---------- .../ai/chat/components/layouts/ChatHeader.tsx | 7 +- .../components/layouts/ChatMoreDropdown.tsx | 9 +-- .../modules/app-layout/ai/AIChatLayout.tsx | 19 ++--- .../entry-content/EntryLayoutContent.tsx | 74 ++++++++---------- ...umnLayout.tsx => TimelineColumnLayout.tsx} | 2 +- .../app-layout/timeline-column/index.tsx | 2 +- ...ntryColumnLayout.tsx => AIEntryLayout.tsx} | 11 ++- .../entry-content/EntryContent.ai.tsx | 28 +++++-- .../entry-content/EntryContent.legacy.tsx | 9 ++- .../components/entry-content/EntryContent.tsx | 4 +- .../components/layouts/ArticleLayout.tsx | 29 ++++++- .../renderer/src/modules/settings/tabs/ai.tsx | 9 +-- .../timeline/[timelineId]/[feedId]/layout.tsx | 4 +- locales/ai/en.json | 2 - locales/ai/ja.json | 2 - packages/internal/utils/src/bind-this.ts | 76 +++++++++++++++++++ packages/internal/utils/src/index.ts | 3 + packages/internal/utils/src/noop.ts | 4 + packages/internal/utils/src/react.ts | 31 ++++++++ 26 files changed, 379 insertions(+), 185 deletions(-) create mode 100644 apps/desktop/layer/renderer/src/lib/simple-text-selection.ts rename apps/desktop/layer/renderer/src/modules/app-layout/timeline-column/{CenterColumnLayout.tsx => TimelineColumnLayout.tsx} (98%) rename apps/desktop/layer/renderer/src/modules/entry-column/{EntryColumnLayout.tsx => AIEntryLayout.tsx} (96%) create mode 100644 packages/internal/utils/src/bind-this.ts create mode 100644 packages/internal/utils/src/noop.ts create mode 100644 packages/internal/utils/src/react.ts diff --git a/apps/desktop/layer/renderer/src/components/common/ShadowDOM.tsx b/apps/desktop/layer/renderer/src/components/common/ShadowDOM.tsx index 6921015e3..fb40c1f01 100644 --- a/apps/desktop/layer/renderer/src/components/common/ShadowDOM.tsx +++ b/apps/desktop/layer/renderer/src/components/common/ShadowDOM.tsx @@ -4,16 +4,27 @@ import { getAccentColorValue } from "@follow/shared/settings/constants" import { hexToHslString } from "@follow/utils" import { nanoid } from "nanoid" import type { FC, PropsWithChildren, ReactNode } from "react" -import { createContext, createElement, use, useLayoutEffect, useMemo, useState } from "react" +import { + createContext, + createElement, + use, + useCallback, + useLayoutEffect, + useMemo, + useRef, + useState, +} from "react" import root from "react-shadow" import { useUISettingKeys } from "~/atoms/settings/ui" import { useReduceMotion } from "~/hooks/biz/useReduceMotion" +import type { TextSelectionEvent } from "~/lib/simple-text-selection" +import { addTextSelectionListener } from "~/lib/simple-text-selection" const ShadowDOMContext = createContext(false) const weakMapElementKey = new WeakMap() -const cloneStylesElement = (_mutationRecord?: MutationRecord) => { +const cloneStylesElement = () => { const $styles = document.head.querySelectorAll("style").values() const reactNodes = [] as ReactNode[] @@ -57,22 +68,39 @@ const cloneStylesElement = (_mutationRecord?: MutationRecord) => { export const ShadowDOM: FC< PropsWithChildren> & { injectHostStyles?: boolean + textSelectionEnabled?: boolean + onTextSelect?: (event: TextSelectionEvent) => void + onSelectionClear?: () => void } > & { useIsShadowDOM: () => boolean } = (props) => { - const { injectHostStyles = true, ...rest } = props + const { + injectHostStyles = true, + textSelectionEnabled = false, + onTextSelect, + onSelectionClear, + ...rest + } = props const [stylesElements, setStylesElements] = useState(() => injectHostStyles ? cloneStylesElement() : [], ) + const shadowRootRef = useRef(null) + + useLayoutEffect(() => { + if (!textSelectionEnabled || !shadowRootRef.current || !onTextSelect) return + + const cleanup = addTextSelectionListener(shadowRootRef.current, onTextSelect, onSelectionClear) + + return cleanup + }, [textSelectionEnabled, onTextSelect, onSelectionClear]) + useLayoutEffect(() => { if (!injectHostStyles) return - const mutationObserver = new MutationObserver((e) => { - const event = e[0] - - setStylesElements(cloneStylesElement(event)) + const mutationObserver = new MutationObserver(() => { + setStylesElements(cloneStylesElement()) }) mutationObserver.observe(document.head, { childList: true, @@ -95,7 +123,14 @@ export const ShadowDOM: FC< return ( // @ts-expect-error - + { + if (element) { + shadowRootRef.current = element.shadowRoot + } + }, [])} + >
= { renderInlineStyle: boolean }> const HTMLImpl = (props: HTMLProps) => { - const { children, renderInlineStyle, as = "div", accessory, noMedia, mediaInfo, ...rest } = props + const { + children, + renderInlineStyle, + as = "div", + accessory, + noMedia, + mediaInfo, + ref, + ...rest + } = props const [remarkOptions, setRemarkOptions] = useState({ renderInlineStyle, noMedia, @@ -43,6 +60,7 @@ const HTMLImpl = (props: HTMLProp }, [renderInlineStyle, noMedia]) const [refElement, setRefElement] = useState(null) + useImperativeHandle(ref as any, () => refElement) const markdownElement = useMemo( () => diff --git a/apps/desktop/layer/renderer/src/lib/simple-text-selection.ts b/apps/desktop/layer/renderer/src/lib/simple-text-selection.ts new file mode 100644 index 000000000..95853048c --- /dev/null +++ b/apps/desktop/layer/renderer/src/lib/simple-text-selection.ts @@ -0,0 +1,51 @@ +/** + * Simple text selection utilities for ShadowDOM + */ + +export interface TextSelectionEvent { + selectedText: string + timestamp: number +} + +/** + * Add text selection listener to ShadowDOM container + */ +export function addTextSelectionListener( + shadowRoot: ShadowRoot, + onTextSelect: (event: TextSelectionEvent) => void, + onSelectionClear?: () => void, +): () => void { + let debounceTimer: ReturnType | null = null + + const handleSelectionChange = () => { + if (debounceTimer) clearTimeout(debounceTimer) + + debounceTimer = setTimeout(() => { + const selection = (shadowRoot as unknown as Document).getSelection?.() + if (!selection) return + + // Check if selection is within our shadow root + 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(), + }) + } + } else { + onSelectionClear?.() + } + }, 200) + } + + document.addEventListener("selectionchange", handleSelectionChange) + + return () => { + if (debounceTimer) clearTimeout(debounceTimer) + document.removeEventListener("selectionchange", handleSelectionChange) + } +} diff --git a/apps/desktop/layer/renderer/src/modules/ai/chat/__internal__/AIChatContext.ts b/apps/desktop/layer/renderer/src/modules/ai/chat/__internal__/AIChatContext.ts index 81bae0ffb..39e51d9f3 100644 --- a/apps/desktop/layer/renderer/src/modules/ai/chat/__internal__/AIChatContext.ts +++ b/apps/desktop/layer/renderer/src/modules/ai/chat/__internal__/AIChatContext.ts @@ -22,20 +22,3 @@ export const useAIChatStore = () => { } return store } - -// Session methods context for managing chat session actions -export interface AIChatSessionMethods { - handleTitleGenerated: (title: string) => Promise - - handleNewChat: () => void -} - -export const AIChatSessionMethodsContext = createContext(null!) - -export const useAIChatSessionMethods = () => { - const context = use(AIChatSessionMethodsContext) - if (!context && import.meta.env.DEV) { - throw new Error("useAIChatSessionMethods must be used within a AIChatSessionMethodsContext") - } - return context -} diff --git a/apps/desktop/layer/renderer/src/modules/ai/chat/__internal__/chat-core/chat-actions.ts b/apps/desktop/layer/renderer/src/modules/ai/chat/__internal__/chat-core/chat-actions.ts index 62e2a1c59..94e93ae7d 100644 --- a/apps/desktop/layer/renderer/src/modules/ai/chat/__internal__/chat-core/chat-actions.ts +++ b/apps/desktop/layer/renderer/src/modules/ai/chat/__internal__/chat-core/chat-actions.ts @@ -1,3 +1,4 @@ +import { autoBindThis } from "@follow/utils/bind-this" import type { ChatStatus } from "ai" import { nanoid } from "nanoid" import type { StateCreator } from "zustand" @@ -12,7 +13,9 @@ export class ChatSliceActions { constructor( private params: Parameters>, private chatInstance: ZustandChat, - ) {} + ) { + return autoBindThis(this) + } get set() { return this.params[0] @@ -146,7 +149,6 @@ export class ChatSliceActions { newChat = () => { const newChatId = nanoid() - // Cleanup old chat instance this.chatInstance.destroy() diff --git a/apps/desktop/layer/renderer/src/modules/ai/chat/__internal__/slices/block.slice.ts b/apps/desktop/layer/renderer/src/modules/ai/chat/__internal__/slices/block.slice.ts index a5615b9ae..7f0162dfd 100644 --- a/apps/desktop/layer/renderer/src/modules/ai/chat/__internal__/slices/block.slice.ts +++ b/apps/desktop/layer/renderer/src/modules/ai/chat/__internal__/slices/block.slice.ts @@ -1,3 +1,4 @@ +import { autoBindThis } from "@follow/utils/bind-this" import { produce } from "immer" import { nanoid } from "nanoid" import type { StateCreator } from "zustand" @@ -22,9 +23,15 @@ export const createBlockSlice: ( } } -class BlockSliceAction { - constructor(private params: Parameters>) {} +export class BlockSliceAction { + constructor(private params: Parameters>) { + return autoBindThis(this) + } + static SPECIAL_TYPES = { + mainEntry: "mainEntry", + selectedText: "selectedText", + } get set() { return this.params[0] } @@ -35,36 +42,17 @@ class BlockSliceAction { addBlock(block: Omit) { const currentBlocks = this.get().blocks - // Only allow one mainEntry - if (block.type === "mainEntry" && currentBlocks.some((b) => b.type === "mainEntry")) { - return - } - - // Only allow one selectedText - if (block.type === "selectedText" && currentBlocks.some((b) => b.type === "selectedText")) { - return - } - - // Prevent duplicate referEntry or referFeed + // Only allow one SPECIAL_TYPES if ( - block.type === "referEntry" && - block.value && - currentBlocks.some((b) => b.type === "referEntry" && b.value === block.value) - ) { - return - } - - if ( - block.type === "referFeed" && - block.value && - currentBlocks.some((b) => b.type === "referFeed" && b.value === block.value) + Object.values(BlockSliceAction.SPECIAL_TYPES).includes(block.type) && + currentBlocks.some((b) => b.type === block.type) ) { return } this.set( produce((state: BlockSlice) => { - state.blocks.push({ ...block, id: nanoid(8) }) + state.blocks.push({ ...block, id: BlockSliceAction.SPECIAL_TYPES[block.type] || nanoid(8) }) }), ) } @@ -87,6 +75,15 @@ class BlockSliceAction { ) } + addOrUpdateBlock(block: AIChatContextBlock) { + const isExist = this.get().blocks.some((b) => b.id === block.id) + if (isExist) { + this.updateBlock(block.id, block) + } else { + this.addBlock(block) + } + } + clearBlocks() { this.set( produce((state: BlockSlice) => { diff --git a/apps/desktop/layer/renderer/src/modules/ai/chat/components/AIChatRoot.tsx b/apps/desktop/layer/renderer/src/modules/ai/chat/components/AIChatRoot.tsx index 30bc1aa4b..66b4d2761 100644 --- a/apps/desktop/layer/renderer/src/modules/ai/chat/components/AIChatRoot.tsx +++ b/apps/desktop/layer/renderer/src/modules/ai/chat/components/AIChatRoot.tsx @@ -1,18 +1,13 @@ import type { FC, PropsWithChildren } from "react" -import { useCallback, useMemo, useRef } from "react" +import { useMemo, useRef } from "react" import { Focusable } from "~/components/common/Focusable" import { HotkeyScope } from "~/constants" -import type { AIChatSessionMethods, AIPanelRefs } from "../__internal__/AIChatContext" -import { - AIChatSessionMethodsContext, - AIChatStoreContext, - AIPanelRefsContext, -} from "../__internal__/AIChatContext" +import type { AIPanelRefs } from "../__internal__/AIChatContext" +import { AIChatStoreContext, AIPanelRefsContext } from "../__internal__/AIChatContext" import { useChatActions, useCurrentChatId } from "../__internal__/hooks" import { createAIChatStore } from "../__internal__/store" -import { AIPersistService } from "../services" interface AIChatRootProps extends PropsWithChildren { wrapFocusable?: boolean @@ -33,38 +28,10 @@ const AIChatRootInner: FC = ({ children, chatId: externalChatId } }, [currentChatId, externalChatId, chatActions]) - const handleTitleGenerated = useCallback( - async (title: string) => { - if (currentChatId) { - try { - await AIPersistService.updateSessionTitle(currentChatId, title) - chatActions.setCurrentTitle(title) - } catch (error) { - console.error("Failed to update session title:", error) - } - } - }, - [currentChatId, chatActions], - ) - - const handleNewChat = useCallback(() => { - chatActions.newChat() - chatActions.setCurrentTitle(undefined) - }, [chatActions]) - const panelRef = useRef(null!) const inputRef = useRef(null!) const refsContext = useMemo(() => ({ panelRef, inputRef }), [panelRef, inputRef]) - // Provide session methods through context - const sessionMethods = useMemo( - () => ({ - handleTitleGenerated, - handleNewChat, - }), - [handleTitleGenerated, handleNewChat], - ) - if (!currentChatId) { return (
@@ -76,11 +43,7 @@ const AIChatRootInner: FC = ({ children, chatId: externalChatId ) } - return ( - - {children} - - ) + return {children} } export const AIChatRoot: FC = ({ diff --git a/apps/desktop/layer/renderer/src/modules/ai/chat/components/layouts/ChatHeader.tsx b/apps/desktop/layer/renderer/src/modules/ai/chat/components/layouts/ChatHeader.tsx index 3312b2099..07091e793 100644 --- a/apps/desktop/layer/renderer/src/modules/ai/chat/components/layouts/ChatHeader.tsx +++ b/apps/desktop/layer/renderer/src/modules/ai/chat/components/layouts/ChatHeader.tsx @@ -3,7 +3,6 @@ import { useCallback } from "react" import { useTranslation } from "react-i18next" import { useDialog } from "~/components/ui/modal/stacked/hooks" -import { useAIChatSessionMethods } from "~/modules/ai/chat/__internal__/AIChatContext" import { useChatActions, useCurrentTitle } from "~/modules/ai/chat/__internal__/hooks" import { useSettingModal } from "~/modules/settings/modal/use-setting-modal-hack" @@ -11,7 +10,7 @@ import { ChatMoreDropdown } from "./ChatMoreDropdown" export const ChatHeader = () => { const currentTitle = useCurrentTitle() - const { handleNewChat } = useAIChatSessionMethods() + const settingModalPresent = useSettingModal() const chatActions = useChatActions() const { ask } = useDialog() @@ -28,10 +27,10 @@ export const ChatHeader = () => { message: t("clear_chat_message"), variant: "danger", onConfirm: () => { - handleNewChat() + chatActions.newChat() }, }) - }, [chatActions, currentTitle, ask, t, handleNewChat]) + }, [chatActions, currentTitle, ask, t]) const maskImage = `linear-gradient(to bottom, black 0%, black 75%, transparent 100%)` return ( diff --git a/apps/desktop/layer/renderer/src/modules/ai/chat/components/layouts/ChatMoreDropdown.tsx b/apps/desktop/layer/renderer/src/modules/ai/chat/components/layouts/ChatMoreDropdown.tsx index 33125390b..167a2b947 100644 --- a/apps/desktop/layer/renderer/src/modules/ai/chat/components/layouts/ChatMoreDropdown.tsx +++ b/apps/desktop/layer/renderer/src/modules/ai/chat/components/layouts/ChatMoreDropdown.tsx @@ -15,7 +15,6 @@ import { DropdownMenuTrigger, } from "~/components/ui/dropdown-menu/dropdown-menu" import { useDialog } from "~/components/ui/modal/stacked/hooks" -import { useAIChatSessionMethods } from "~/modules/ai/chat/__internal__/AIChatContext" import { useChatActions, useCurrentChatId, @@ -28,7 +27,7 @@ import { downloadMarkdown, exportChatToMarkdown } from "~/modules/ai/chat/utils/ export const ChatMoreDropdown = () => { const currentTitle = useCurrentTitle() const currentChatId = useCurrentChatId() - const { handleNewChat } = useAIChatSessionMethods() + const chatActions = useChatActions() const { t } = useTranslation("ai") const { ask } = useDialog() @@ -64,7 +63,7 @@ export const ChatMoreDropdown = () => { toast.success(t("delete_chat_success")) if (chatId === currentChatId) { - handleNewChat() + chatActions.newChat() } loadHistory() @@ -75,7 +74,7 @@ export const ChatMoreDropdown = () => { setDeletingChatId(null) } }, - [sessions, ask, t, currentChatId, loadHistory, handleNewChat], + [sessions, ask, t, currentChatId, loadHistory, chatActions], ) const handleExport = useCallback(() => { @@ -154,7 +153,7 @@ export const ChatMoreDropdown = () => { ))} diff --git a/apps/desktop/layer/renderer/src/modules/app-layout/ai/AIChatLayout.tsx b/apps/desktop/layer/renderer/src/modules/app-layout/ai/AIChatLayout.tsx index 74f34eddc..0d0cdbb19 100644 --- a/apps/desktop/layer/renderer/src/modules/app-layout/ai/AIChatLayout.tsx +++ b/apps/desktop/layer/renderer/src/modules/app-layout/ai/AIChatLayout.tsx @@ -2,7 +2,6 @@ import type { FC } from "react" import { Focusable } from "~/components/common/Focusable" import { HotkeyScope } from "~/constants" -import { AIChatRoot } from "~/modules/ai/chat/components/AIChatRoot" import { ChatHeader } from "~/modules/ai/chat/components/layouts/ChatHeader" import { ChatInterface } from "~/modules/ai/chat/components/layouts/ChatInterface" @@ -10,15 +9,13 @@ export const AIChatLayout: FC< React.DetailedHTMLProps, HTMLDivElement> > = ({ ...props }) => { return ( - - - - - - + + + + ) } diff --git a/apps/desktop/layer/renderer/src/modules/app-layout/entry-content/EntryLayoutContent.tsx b/apps/desktop/layer/renderer/src/modules/app-layout/entry-content/EntryLayoutContent.tsx index eceed7ce8..624197fe2 100644 --- a/apps/desktop/layer/renderer/src/modules/app-layout/entry-content/EntryLayoutContent.tsx +++ b/apps/desktop/layer/renderer/src/modules/app-layout/entry-content/EntryLayoutContent.tsx @@ -16,11 +16,9 @@ import { ROUTE_ENTRY_PENDING } from "~/constants" import { useFeature } from "~/hooks/biz/useFeature" import { useNavigateEntry } from "~/hooks/biz/useNavigateEntry" import { useRouteParams } from "~/hooks/biz/useRouteParams" -import { AIChatRoot } from "~/modules/ai/chat/components/AIChatRoot" import { EntryContent } from "~/modules/entry-content/components/entry-content" import { AppLayoutGridContainerProvider } from "~/providers/app-grid-layout-container-provider" -import { AIChatLayout } from "../ai/AIChatLayout" import { EntryContentPlaceholder } from "./EntryContentPlaceholder" const EntryLayoutContentLegacy = () => { @@ -85,11 +83,7 @@ export const EntryLayoutContentWithAI = () => { onClick={() => navigate({ entryId: null })} /> )} - {realEntryId && !isWideView ? ( - - ) : ( - !isWideView && - )} + {realEntryId && !isWideView ? : null} ) @@ -120,42 +114,40 @@ const Grid = ({ entryId }) => { }) return ( - -
-
- { - return { - header: shouldHeaderPaddingLeft - ? "ml-[calc(theme(width.feed-col)+theme(width.8))]" - : wideMode - ? "ml-12" - : "", - } - }, [shouldHeaderPaddingLeft, wideMode])} +
+
+ { + return { + header: shouldHeaderPaddingLeft + ? "ml-[calc(theme(width.feed-col)+theme(width.8))]" + : wideMode + ? "ml-12" + : "", + } + }, [shouldHeaderPaddingLeft, wideMode])} + /> +
+ {aiPinned && ( +
+
- {aiPinned && ( -
- -
- )} -
- + )} +
) } diff --git a/apps/desktop/layer/renderer/src/modules/app-layout/timeline-column/CenterColumnLayout.tsx b/apps/desktop/layer/renderer/src/modules/app-layout/timeline-column/TimelineColumnLayout.tsx similarity index 98% rename from apps/desktop/layer/renderer/src/modules/app-layout/timeline-column/CenterColumnLayout.tsx rename to apps/desktop/layer/renderer/src/modules/app-layout/timeline-column/TimelineColumnLayout.tsx index 6cf5cc9ca..3b32a00f6 100644 --- a/apps/desktop/layer/renderer/src/modules/app-layout/timeline-column/CenterColumnLayout.tsx +++ b/apps/desktop/layer/renderer/src/modules/app-layout/timeline-column/TimelineColumnLayout.tsx @@ -16,7 +16,7 @@ import { useRouteParams } from "~/hooks/biz/useRouteParams" import { EntryColumn } from "~/modules/entry-column" import { AppLayoutGridContainerProvider } from "~/providers/app-grid-layout-container-provider" -export function CenterColumnLayout() { +export function TimelineColumnLayout() { const containerRef = useRef(null) // Memo this initial value to avoid re-render diff --git a/apps/desktop/layer/renderer/src/modules/app-layout/timeline-column/index.tsx b/apps/desktop/layer/renderer/src/modules/app-layout/timeline-column/index.tsx index c8c7a2c59..0b53adf4f 100644 --- a/apps/desktop/layer/renderer/src/modules/app-layout/timeline-column/index.tsx +++ b/apps/desktop/layer/renderer/src/modules/app-layout/timeline-column/index.tsx @@ -1 +1 @@ -export { CenterColumnLayout } from "./CenterColumnLayout" +export { TimelineColumnLayout as CenterColumnLayout } from "./TimelineColumnLayout" diff --git a/apps/desktop/layer/renderer/src/modules/entry-column/EntryColumnLayout.tsx b/apps/desktop/layer/renderer/src/modules/entry-column/AIEntryLayout.tsx similarity index 96% rename from apps/desktop/layer/renderer/src/modules/entry-column/EntryColumnLayout.tsx rename to apps/desktop/layer/renderer/src/modules/entry-column/AIEntryLayout.tsx index 88a234774..b203de708 100644 --- a/apps/desktop/layer/renderer/src/modules/entry-column/EntryColumnLayout.tsx +++ b/apps/desktop/layer/renderer/src/modules/entry-column/AIEntryLayout.tsx @@ -14,9 +14,10 @@ import { AIChatLayout } from "~/modules/app-layout/ai/AIChatLayout" import { EntryContent } from "~/modules/entry-content/components/entry-content" import { AppLayoutGridContainerProvider } from "~/providers/app-grid-layout-container-provider" +import { AIChatRoot } from "../ai/chat/components/AIChatRoot" import { EntryColumn } from "./index" -export const EntryColumnLayout = () => { +const AIEntryLayoutImpl = () => { const { entryId } = useParams() const navigate = useNavigateEntry() @@ -195,3 +196,11 @@ export const EntryColumnLayout = () => {
) } + +export const AIEntryLayout = () => { + return ( + + + + ) +} diff --git a/apps/desktop/layer/renderer/src/modules/entry-content/components/entry-content/EntryContent.ai.tsx b/apps/desktop/layer/renderer/src/modules/entry-content/components/entry-content/EntryContent.ai.tsx index ffeb6b5ff..74bb96717 100644 --- a/apps/desktop/layer/renderer/src/modules/entry-content/components/entry-content/EntryContent.ai.tsx +++ b/apps/desktop/layer/renderer/src/modules/entry-content/components/entry-content/EntryContent.ai.tsx @@ -8,6 +8,7 @@ import type { FeedModel } from "@follow/models/types" import { useEntry } from "@follow/store/entry/hooks" import { useFeedById } from "@follow/store/feed/hooks" import { useIsInbox } from "@follow/store/inbox/hooks" +import { thenable } from "@follow/utils" import { nextFrame, stopPropagation } from "@follow/utils/dom" import { EventBus } from "@follow/utils/event-bus" import { clsx, cn } from "@follow/utils/utils" @@ -23,6 +24,8 @@ import { useInPeekModal } from "~/components/ui/modal/inspire/InPeekModal" import { HotkeyScope } from "~/constants" import { useRouteParamsSelector } from "~/hooks/biz/useRouteParams" import { useFeedSafeUrl } from "~/hooks/common/useFeedSafeUrl" +import { useBlockActions } from "~/modules/ai/chat/__internal__/hooks" +import { BlockSliceAction } from "~/modules/ai/chat/__internal__/slices/block.slice" import { COMMAND_ID } from "~/modules/command/commands/id" import { ApplyEntryActions } from "../../ApplyEntryActions" @@ -56,12 +59,12 @@ const EntryContentImpl: Component = ({ return { feedId, inboxId: inboxHandle, title, url } }) - const entryExists = !!entry - useTitle(entry?.title) + if (!entry) throw thenable - const feed = useFeedById(entry?.feedId) + useTitle(entry.title) + const feed = useFeedById(entry.feedId) - const isInbox = useIsInbox(entry?.inboxId) + const isInbox = useIsInbox(entry.inboxId) const isInReadabilityMode = useEntryIsInReadability(entryId) const { error, content, isPending } = useEntryContent(entryId) @@ -79,7 +82,7 @@ const EntryContentImpl: Component = ({ const prevEntryId = useRef(undefined) const scrollAnimationRef = useRef | null>(null) useEffect(() => { - if (entryExists && prevEntryId.current !== entryId) { + if (prevEntryId.current !== entryId) { scrollAnimationRef.current?.stop() nextFrame(() => { scrollerRef.current?.scrollTo({ top: 0 }) @@ -89,14 +92,25 @@ const EntryContentImpl: Component = ({ }) prevEntryId.current = entryId } - }, [animationController, entryExists, entryId]) + }, [animationController, entryId]) const isInHasTimelineView = ![ FeedViewType.Pictures, FeedViewType.SocialMedia, FeedViewType.Videos, ].includes(view) - if (!entry) return null + + const { addOrUpdateBlock, removeBlock } = useBlockActions() + useEffect(() => { + addOrUpdateBlock({ + id: BlockSliceAction.SPECIAL_TYPES.mainEntry, + type: "mainEntry", + value: entryId, + }) + return () => { + removeBlock(BlockSliceAction.SPECIAL_TYPES.mainEntry) + } + }, [addOrUpdateBlock, entryId, removeBlock]) return (
diff --git a/apps/desktop/layer/renderer/src/modules/entry-content/components/entry-content/EntryContent.legacy.tsx b/apps/desktop/layer/renderer/src/modules/entry-content/components/entry-content/EntryContent.legacy.tsx index 9dedd0ab3..62ed62b44 100644 --- a/apps/desktop/layer/renderer/src/modules/entry-content/components/entry-content/EntryContent.legacy.tsx +++ b/apps/desktop/layer/renderer/src/modules/entry-content/components/entry-content/EntryContent.legacy.tsx @@ -9,6 +9,7 @@ import type { FeedModel } from "@follow/models/types" import { useEntry } from "@follow/store/entry/hooks" import { useFeedById } from "@follow/store/feed/hooks" import { useIsInbox } from "@follow/store/inbox/hooks" +import { thenable } from "@follow/utils" import { nextFrame, stopPropagation } from "@follow/utils/dom" import { EventBus } from "@follow/utils/event-bus" import { clsx, cn } from "@follow/utils/utils" @@ -70,7 +71,8 @@ const EntryContentImpl: Component = ({ return { feedId, inboxId: inboxHandle, title, url } }) - const entryExists = !!entry + if (!entry) throw thenable + useTitle(entry?.title) const feed = useFeedById(entry?.feedId) @@ -94,7 +96,7 @@ const EntryContentImpl: Component = ({ const prevEntryId = useRef(undefined) const scrollAnimationRef = useRef | null>(null) useEffect(() => { - if (entryExists && prevEntryId.current !== entryId) { + if (prevEntryId.current !== entryId) { scrollAnimationRef.current?.stop() nextFrame(() => { scrollerRef.current?.scrollTo({ top: 0 }) @@ -104,14 +106,13 @@ const EntryContentImpl: Component = ({ }) prevEntryId.current = entryId } - }, [animationController, entryExists, entryId]) + }, [animationController, entryId]) const isInHasTimelineView = ![ FeedViewType.Pictures, FeedViewType.SocialMedia, FeedViewType.Videos, ].includes(view) - if (!entry) return null return ( <> diff --git a/apps/desktop/layer/renderer/src/modules/entry-content/components/entry-content/EntryContent.tsx b/apps/desktop/layer/renderer/src/modules/entry-content/components/entry-content/EntryContent.tsx index 98a99a4b3..4eb7b61cb 100644 --- a/apps/desktop/layer/renderer/src/modules/entry-content/components/entry-content/EntryContent.tsx +++ b/apps/desktop/layer/renderer/src/modules/entry-content/components/entry-content/EntryContent.tsx @@ -1,6 +1,8 @@ +import { withSuspense } from "@follow/utils" + import { withFeature } from "~/lib/features" import { EntryContent as EntryContentAI } from "./EntryContent.ai" import { EntryContent as EntryContentLegacy } from "./EntryContent.legacy" -export const EntryContent = withFeature("ai")(EntryContentAI, EntryContentLegacy) +export const EntryContent = withSuspense(withFeature("ai")(EntryContentAI, EntryContentLegacy)) 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 015d273b1..567b1f0e1 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 @@ -5,7 +5,7 @@ import { useFeedById } from "@follow/store/feed/hooks" import { useIsInbox } from "@follow/store/inbox/hooks" import { cn } from "@follow/utils" import { ErrorBoundary } from "@sentry/react" -import { useMemo, useRef } from "react" +import { useCallback, useMemo, useRef } from "react" import { useUISettingKey } from "~/atoms/settings/ui" import { ShadowDOM } from "~/components/common/ShadowDOM" @@ -13,6 +13,9 @@ import type { TocRef } from "~/components/ui/markdown/components/Toc" 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/__internal__/hooks" +import { BlockSliceAction } from "~/modules/ai/chat/__internal__/slices/block.slice" import { EntryContentHTMLRenderer } from "~/modules/renderer/html" import { WrappedElementProvider } from "~/providers/wrapped-element-provider" @@ -52,6 +55,20 @@ export const ArticleLayout: React.FC = ({ 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 handleSelectionClear = useCallback(() => { + removeBlock(BlockSliceAction.SPECIAL_TYPES.selectedText) + }, [removeBlock]) if (!entry) return null return ( @@ -64,7 +81,12 @@ export const ArticleLayout: React.FC = ({ - + {!!customCSS && {customCSS}} void + onSelectionClear?: (entryId: string) => void + textSelectionEnabled?: boolean }> = ({ entryId, view, feedId, noMedia = false, content = "", translation }) => { const mediaInfo = useEntryMediaInfo(entryId) const readerRenderInlineStyle = useUISettingKey("readerRenderInlineStyle") 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 fa5c9080e..a8f881ed7 100644 --- a/apps/desktop/layer/renderer/src/modules/settings/tabs/ai.tsx +++ b/apps/desktop/layer/renderer/src/modules/settings/tabs/ai.tsx @@ -9,7 +9,6 @@ import { useTranslation } from "react-i18next" import { toast } from "sonner" import { setAISetting, useAISettingValue } from "~/atoms/settings/ai" -import { KeyRecorder } from "~/components/ui/keyboard-recorder" import { SettingActionItem, SettingDescription } from "../control" import { createSettingBuilder } from "../helper/setting-builder" @@ -279,9 +278,8 @@ const ShortcutEditor = ({ shortcut, onSave, onCancel }: ShortcutEditorProps) => const { t } = useTranslation("ai") const [name, setName] = useState(shortcut?.name || "") const [prompt, setPrompt] = useState(shortcut?.prompt || "") - const [hotkey, setHotkey] = useState(shortcut?.hotkey || "") + const [enabled, setEnabled] = useState(shortcut?.enabled ?? true) - const [isRecording, setIsRecording] = useState(false) const handleSave = () => { if (!name.trim() || !prompt.trim()) { @@ -292,7 +290,6 @@ const ShortcutEditor = ({ shortcut, onSave, onCancel }: ShortcutEditorProps) => onSave({ name: name.trim(), prompt: prompt.trim(), - hotkey: hotkey.trim() || undefined, enabled, }) } @@ -308,7 +305,7 @@ const ShortcutEditor = ({ shortcut, onSave, onCancel }: ShortcutEditorProps) => placeholder={t("shortcuts.name_placeholder")} />
-
+ {/*
)} -
+
*/}
diff --git a/apps/desktop/layer/renderer/src/pages/(main)/(layer)/timeline/[timelineId]/[feedId]/layout.tsx b/apps/desktop/layer/renderer/src/pages/(main)/(layer)/timeline/[timelineId]/[feedId]/layout.tsx index 0cbaccecb..0e1a2695d 100644 --- a/apps/desktop/layer/renderer/src/pages/(main)/(layer)/timeline/[timelineId]/[feedId]/layout.tsx +++ b/apps/desktop/layer/renderer/src/pages/(main)/(layer)/timeline/[timelineId]/[feedId]/layout.tsx @@ -1,5 +1,5 @@ import { withFeature } from "~/lib/features" import { CenterColumnLayout } from "~/modules/app-layout/timeline-column/index" -import { EntryColumnLayout } from "~/modules/entry-column/EntryColumnLayout" +import { AIEntryLayout } from "~/modules/entry-column/AIEntryLayout" -export const Component = withFeature("ai")(EntryColumnLayout, CenterColumnLayout) +export const Component = withFeature("ai")(AIEntryLayout, CenterColumnLayout) diff --git a/locales/ai/en.json b/locales/ai/en.json index b7d2ae5f1..de1fc40ac 100644 --- a/locales/ai/en.json +++ b/locales/ai/en.json @@ -24,8 +24,6 @@ "shortcuts.empty.description": "Create custom AI shortcuts to quickly perform common tasks and get instant AI assistance.", "shortcuts.empty.title": "No Shortcuts Yet", "shortcuts.enabled": "Enabled", - "shortcuts.hotkey": "Hotkey (Optional)", - "shortcuts.hotkey_placeholder": "e.g. Cmd+S", "shortcuts.name": "Name", "shortcuts.name_placeholder": "e.g. Summarize Article", "shortcuts.prompt": "Prompt", diff --git a/locales/ai/ja.json b/locales/ai/ja.json index d12128b75..658faa1a8 100644 --- a/locales/ai/ja.json +++ b/locales/ai/ja.json @@ -24,8 +24,6 @@ "shortcuts.empty.description": "一般的なタスクを迅速に実行し、即座にAIアシスタンスを得るためのカスタムAIショートカットを作成します。", "shortcuts.empty.title": "ショートカットはまだありません", "shortcuts.enabled": "有効", - "shortcuts.hotkey": "ホットキー(オプション)", - "shortcuts.hotkey_placeholder": "例:Cmd+S", "shortcuts.name": "名前", "shortcuts.name_placeholder": "例:記事を要約", "shortcuts.prompt": "プロンプト", diff --git a/packages/internal/utils/src/bind-this.ts b/packages/internal/utils/src/bind-this.ts new file mode 100644 index 000000000..12e513372 --- /dev/null +++ b/packages/internal/utils/src/bind-this.ts @@ -0,0 +1,76 @@ +/** + * 自动绑定类实例的所有方法到正确的 this 上下文 + * 防止在解构赋值时丢失 this 指向 + * + * @param instance 类实例 + * @param excludeMethods 要排除的方法名数组,默认排除 constructor + * @returns 绑定了 this 的实例 + * + * @example + * ```ts + * class MyClass { + * constructor() { + * return autoBindThis(this) + * } + * + * myMethod() { + * console.log(this) + * } + * } + * + * const instance = new MyClass() + * const { myMethod } = instance // 解构不会丢失 this + * myMethod() // this 仍然指向 instance + * ``` + */ +export function autoBindThis>( + instance: T, + excludeMethods: string[] = ["constructor"], +): T { + const prototype = Object.getPrototypeOf(instance) + const propertyNames = Object.getOwnPropertyNames(prototype) + + for (const name of propertyNames) { + if (excludeMethods.includes(name)) { + continue + } + + const descriptor = Object.getOwnPropertyDescriptor(prototype, name) + if (descriptor && typeof descriptor.value === "function") { + ;(instance as any)[name] = instance[name].bind(instance) + } + } + + return instance +} + +/** + * 创建一个自动绑定 this 的类装饰器 + * + * @param excludeMethods 要排除的方法名数组 + * @returns 类装饰器 + * + * @example + * ```ts + * @AutoBindThis() + * class MyClass { + * myMethod() { + * console.log(this) + * } + * } + * + * const instance = new MyClass() + * const { myMethod } = instance + * myMethod() // this 仍然指向 instance + * ``` + */ +export function AutoBindThis(excludeMethods: string[] = ["constructor"]) { + return function any>(constructor: T) { + return class extends constructor { + constructor(...args: any[]) { + super(...args) + autoBindThis(this, excludeMethods) + } + } + } +} diff --git a/packages/internal/utils/src/index.ts b/packages/internal/utils/src/index.ts index 88078a3ae..fd0df3473 100644 --- a/packages/internal/utils/src/index.ts +++ b/packages/internal/utils/src/index.ts @@ -1,9 +1,12 @@ +export * from "./bind-this" export * from "./cjk" export * from "./color" export * from "./data-structure/set" export * from "./dom" export * from "./duration" export * from "./jotai" +export * from "./noop" export * from "./path-parser" +export * from "./react" export * from "./url-for-video" export * from "./utils" diff --git a/packages/internal/utils/src/noop.ts b/packages/internal/utils/src/noop.ts new file mode 100644 index 000000000..2b49e954f --- /dev/null +++ b/packages/internal/utils/src/noop.ts @@ -0,0 +1,4 @@ +export const noop = () => {} +// eslint-disable-next-line unicorn/no-thenable +export const thenable: any = { then: noop } +export const emptyObject = {} diff --git a/packages/internal/utils/src/react.ts b/packages/internal/utils/src/react.ts new file mode 100644 index 000000000..8ea5b9d89 --- /dev/null +++ b/packages/internal/utils/src/react.ts @@ -0,0 +1,31 @@ +import type { ComponentType, ReactElement } from "react" +import { createElement, Suspense } from "react" + +type FallbackOptions = ReactElement | ComponentType + +interface WithSuspenseOptions { + fallback?: FallbackOptions +} + +/** + * Higher-order component that wraps a component with React Suspense + * @param Component - The component to wrap with Suspense + * @param options - Configuration options for the Suspense wrapper + * @returns A new component wrapped with Suspense + */ +export function withSuspense

( + Component: ComponentType

, + options: WithSuspenseOptions = {}, +): ComponentType

{ + const { fallback } = options + + const WrappedComponent = (props: P) => { + const fallbackElement = typeof fallback === "function" ? createElement(fallback) : fallback + + return createElement(Suspense, { fallback: fallbackElement }, createElement(Component, props)) + } + + WrappedComponent.displayName = `withSuspense(${Component.displayName || Component.name || "Component"})` + + return WrappedComponent +}