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 <tukon479@gmail.com>
This commit is contained in:
@@ -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<HTMLStyleElement | HTMLLinkElement, string>()
|
||||
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<React.HTMLProps<HTMLElement>> & {
|
||||
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<ReactNode[]>(() =>
|
||||
injectHostStyles ? cloneStylesElement() : [],
|
||||
)
|
||||
|
||||
const shadowRootRef = useRef<ShadowRoot | null>(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
|
||||
<root.div {...rest}>
|
||||
<root.div
|
||||
{...rest}
|
||||
ref={useCallback((element) => {
|
||||
if (element) {
|
||||
shadowRootRef.current = element.shadowRoot
|
||||
}
|
||||
}, [])}
|
||||
>
|
||||
<ShadowDOMContext value={true}>
|
||||
<div
|
||||
style={useMemo(
|
||||
|
||||
@@ -1,6 +1,14 @@
|
||||
import { MemoedDangerousHTMLStyle } from "@follow/components/common/MemoedDangerousHTMLStyle.js"
|
||||
import katexStyle from "katex/dist/katex.min.css?raw"
|
||||
import { createElement, Fragment, memo, useEffect, useMemo, useState } from "react"
|
||||
import {
|
||||
createElement,
|
||||
Fragment,
|
||||
memo,
|
||||
useEffect,
|
||||
useImperativeHandle,
|
||||
useMemo,
|
||||
useState,
|
||||
} from "react"
|
||||
import type { JSX } from "react/jsx-runtime"
|
||||
|
||||
import { ENTRY_CONTENT_RENDER_CONTAINER_ID } from "~/constants/dom"
|
||||
@@ -24,7 +32,16 @@ export type HTMLProps<A extends keyof JSX.IntrinsicElements = "div"> = {
|
||||
renderInlineStyle: boolean
|
||||
}>
|
||||
const HTMLImpl = <A extends keyof JSX.IntrinsicElements = "div">(props: HTMLProps<A>) => {
|
||||
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 = <A extends keyof JSX.IntrinsicElements = "div">(props: HTMLProp
|
||||
}, [renderInlineStyle, noMedia])
|
||||
|
||||
const [refElement, setRefElement] = useState<HTMLElement | null>(null)
|
||||
useImperativeHandle(ref as any, () => refElement)
|
||||
|
||||
const markdownElement = useMemo(
|
||||
() =>
|
||||
|
||||
@@ -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<typeof setTimeout> | 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)
|
||||
}
|
||||
}
|
||||
@@ -22,20 +22,3 @@ export const useAIChatStore = () => {
|
||||
}
|
||||
return store
|
||||
}
|
||||
|
||||
// Session methods context for managing chat session actions
|
||||
export interface AIChatSessionMethods {
|
||||
handleTitleGenerated: (title: string) => Promise<void>
|
||||
|
||||
handleNewChat: () => void
|
||||
}
|
||||
|
||||
export const AIChatSessionMethodsContext = createContext<AIChatSessionMethods>(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
|
||||
}
|
||||
|
||||
+4
-2
@@ -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<StateCreator<ChatSlice, [], [], ChatSlice>>,
|
||||
private chatInstance: ZustandChat<BizUIMessage>,
|
||||
) {}
|
||||
) {
|
||||
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()
|
||||
|
||||
|
||||
+22
-25
@@ -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<StateCreator<BlockSlice, [], [], BlockSlice>>) {}
|
||||
export class BlockSliceAction {
|
||||
constructor(private params: Parameters<StateCreator<BlockSlice, [], [], BlockSlice>>) {
|
||||
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<AIChatContextBlock, "id">) {
|
||||
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) => {
|
||||
|
||||
@@ -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<AIChatRootProps> = ({ 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<HTMLDivElement>(null!)
|
||||
const inputRef = useRef<HTMLTextAreaElement>(null!)
|
||||
const refsContext = useMemo<AIPanelRefs>(() => ({ panelRef, inputRef }), [panelRef, inputRef])
|
||||
|
||||
// Provide session methods through context
|
||||
const sessionMethods = useMemo<AIChatSessionMethods>(
|
||||
() => ({
|
||||
handleTitleGenerated,
|
||||
handleNewChat,
|
||||
}),
|
||||
[handleTitleGenerated, handleNewChat],
|
||||
)
|
||||
|
||||
if (!currentChatId) {
|
||||
return (
|
||||
<div className="bg-background flex size-full items-center justify-center">
|
||||
@@ -76,11 +43,7 @@ const AIChatRootInner: FC<AIChatRootProps> = ({ children, chatId: externalChatId
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<AIPanelRefsContext value={refsContext}>
|
||||
<AIChatSessionMethodsContext value={sessionMethods}>{children}</AIChatSessionMethodsContext>
|
||||
</AIPanelRefsContext>
|
||||
)
|
||||
return <AIPanelRefsContext value={refsContext}>{children}</AIPanelRefsContext>
|
||||
}
|
||||
|
||||
export const AIChatRoot: FC<AIChatRootProps> = ({
|
||||
|
||||
@@ -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 (
|
||||
|
||||
+4
-5
@@ -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 = () => {
|
||||
))}
|
||||
<DropdownMenuSeparator className="my-1.5" />
|
||||
<DropdownMenuItem
|
||||
onClick={handleNewChat}
|
||||
onClick={chatActions.newChat}
|
||||
className="flex cursor-pointer items-center gap-2 rounded-md px-1 py-2.5"
|
||||
>
|
||||
<i className="i-mgc-add-cute-re size-4" />
|
||||
|
||||
@@ -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<React.HTMLAttributes<HTMLDivElement>, HTMLDivElement>
|
||||
> = ({ ...props }) => {
|
||||
return (
|
||||
<AIChatRoot wrapFocusable={false}>
|
||||
<Focusable
|
||||
scope={HotkeyScope.AIChat}
|
||||
className="bg-background relative flex h-full flex-col overflow-hidden"
|
||||
{...props}
|
||||
>
|
||||
<ChatHeader />
|
||||
<ChatInterface />
|
||||
</Focusable>
|
||||
</AIChatRoot>
|
||||
<Focusable
|
||||
scope={HotkeyScope.AIChat}
|
||||
className="bg-background relative flex h-full flex-col overflow-hidden"
|
||||
{...props}
|
||||
>
|
||||
<ChatHeader />
|
||||
<ChatInterface />
|
||||
</Focusable>
|
||||
)
|
||||
}
|
||||
|
||||
+33
-41
@@ -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 ? (
|
||||
<Grid entryId={realEntryId} />
|
||||
) : (
|
||||
!isWideView && <AIChatLayout />
|
||||
)}
|
||||
{realEntryId && !isWideView ? <Grid entryId={realEntryId} /> : null}
|
||||
</EntryGridContainer>
|
||||
</AppLayoutGridContainerProvider>
|
||||
)
|
||||
@@ -120,42 +114,40 @@ const Grid = ({ entryId }) => {
|
||||
})
|
||||
|
||||
return (
|
||||
<AIChatRoot wrapFocusable={false}>
|
||||
<div
|
||||
className={clsx(
|
||||
aiPinned && "grid grid-cols-[1fr_400px]",
|
||||
"flex min-h-0 grow flex-col overflow-hidden",
|
||||
)}
|
||||
style={{
|
||||
gridTemplateColumns: `1fr ${position}px`,
|
||||
}}
|
||||
>
|
||||
<div className="flex min-h-0 grow flex-col overflow-hidden">
|
||||
<EntryContent
|
||||
entryId={entryId}
|
||||
classNames={useMemo(() => {
|
||||
return {
|
||||
header: shouldHeaderPaddingLeft
|
||||
? "ml-[calc(theme(width.feed-col)+theme(width.8))]"
|
||||
: wideMode
|
||||
? "ml-12"
|
||||
: "",
|
||||
}
|
||||
}, [shouldHeaderPaddingLeft, wideMode])}
|
||||
<div
|
||||
className={clsx(
|
||||
aiPinned && "grid grid-cols-[1fr_400px]",
|
||||
"flex min-h-0 grow flex-col overflow-hidden",
|
||||
)}
|
||||
style={{
|
||||
gridTemplateColumns: `1fr ${position}px`,
|
||||
}}
|
||||
>
|
||||
<div className="flex min-h-0 grow flex-col overflow-hidden">
|
||||
<EntryContent
|
||||
entryId={entryId}
|
||||
classNames={useMemo(() => {
|
||||
return {
|
||||
header: shouldHeaderPaddingLeft
|
||||
? "ml-[calc(theme(width.feed-col)+theme(width.8))]"
|
||||
: wideMode
|
||||
? "ml-12"
|
||||
: "",
|
||||
}
|
||||
}, [shouldHeaderPaddingLeft, wideMode])}
|
||||
/>
|
||||
</div>
|
||||
{aiPinned && (
|
||||
<div className="relative flex min-h-0 grow flex-col border-l">
|
||||
<PanelSplitter
|
||||
className="absolute inset-y-0 left-0"
|
||||
isDragging={isDragging}
|
||||
cursor={separatorCursor}
|
||||
{...separatorProps}
|
||||
/>
|
||||
</div>
|
||||
{aiPinned && (
|
||||
<div className="relative flex min-h-0 grow flex-col border-l">
|
||||
<PanelSplitter
|
||||
className="absolute inset-y-0 left-0"
|
||||
isDragging={isDragging}
|
||||
cursor={separatorCursor}
|
||||
{...separatorProps}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</AIChatRoot>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
+1
-1
@@ -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<HTMLDivElement>(null)
|
||||
|
||||
// Memo this initial value to avoid re-render
|
||||
@@ -1 +1 @@
|
||||
export { CenterColumnLayout } from "./CenterColumnLayout"
|
||||
export { TimelineColumnLayout as CenterColumnLayout } from "./TimelineColumnLayout"
|
||||
|
||||
+10
-1
@@ -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 = () => {
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export const AIEntryLayout = () => {
|
||||
return (
|
||||
<AIChatRoot wrapFocusable={false}>
|
||||
<AIEntryLayoutImpl />
|
||||
</AIChatRoot>
|
||||
)
|
||||
}
|
||||
+21
-7
@@ -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<EntryContentProps> = ({
|
||||
|
||||
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<EntryContentProps> = ({
|
||||
const prevEntryId = useRef<string | undefined>(undefined)
|
||||
const scrollAnimationRef = useRef<JSAnimation<any> | 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<EntryContentProps> = ({
|
||||
})
|
||||
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 (
|
||||
<div className={cn(className, "@container flex flex-col")}>
|
||||
|
||||
+5
-4
@@ -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<EntryContentProps> = ({
|
||||
|
||||
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<EntryContentProps> = ({
|
||||
const prevEntryId = useRef<string | undefined>(undefined)
|
||||
const scrollAnimationRef = useRef<JSAnimation<any> | 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<EntryContentProps> = ({
|
||||
})
|
||||
prevEntryId.current = entryId
|
||||
}
|
||||
}, [animationController, entryExists, entryId])
|
||||
}, [animationController, entryId])
|
||||
|
||||
const isInHasTimelineView = ![
|
||||
FeedViewType.Pictures,
|
||||
FeedViewType.SocialMedia,
|
||||
FeedViewType.Videos,
|
||||
].includes(view)
|
||||
if (!entry) return null
|
||||
|
||||
return (
|
||||
<>
|
||||
|
||||
+3
-1
@@ -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))
|
||||
|
||||
+27
-2
@@ -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<ArticleLayoutProps> = ({
|
||||
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<ArticleLayoutProps> = ({
|
||||
<AISummary entryId={entryId} />
|
||||
<ErrorBoundary fallback={EntryRenderError}>
|
||||
<ReadabilityNotice entryId={entryId} />
|
||||
<ShadowDOM injectHostStyles={!isInbox}>
|
||||
<ShadowDOM
|
||||
injectHostStyles={!isInbox}
|
||||
textSelectionEnabled
|
||||
onTextSelect={handleTextSelect}
|
||||
onSelectionClear={handleSelectionClear}
|
||||
>
|
||||
{!!customCSS && <MemoedDangerousHTMLStyle>{customCSS}</MemoedDangerousHTMLStyle>}
|
||||
|
||||
<Renderer
|
||||
@@ -96,6 +118,9 @@ const Renderer: React.FC<{
|
||||
content?: string
|
||||
title?: string
|
||||
}
|
||||
onTextSelect?: (event: TextSelectionEvent) => void
|
||||
onSelectionClear?: (entryId: string) => void
|
||||
textSelectionEnabled?: boolean
|
||||
}> = ({ entryId, view, feedId, noMedia = false, content = "", translation }) => {
|
||||
const mediaInfo = useEntryMediaInfo(entryId)
|
||||
const readerRenderInlineStyle = useUISettingKey("readerRenderInlineStyle")
|
||||
|
||||
@@ -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")}
|
||||
/>
|
||||
</div>
|
||||
<div className="col-span-2 space-y-2">
|
||||
{/* <div className="col-span-2 space-y-2">
|
||||
<Label className="text-text text-xs">{t("shortcuts.hotkey")}</Label>
|
||||
<button
|
||||
type="button"
|
||||
@@ -337,7 +334,7 @@ const ShortcutEditor = ({ shortcut, onSave, onCancel }: ShortcutEditorProps) =>
|
||||
</div>
|
||||
)}
|
||||
</button>
|
||||
</div>
|
||||
</div> */}
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
|
||||
+2
-2
@@ -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)
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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": "プロンプト",
|
||||
|
||||
@@ -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<T extends Record<string, any>>(
|
||||
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 <T extends new (...args: any[]) => any>(constructor: T) {
|
||||
return class extends constructor {
|
||||
constructor(...args: any[]) {
|
||||
super(...args)
|
||||
autoBindThis(this, excludeMethods)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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"
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
export const noop = () => {}
|
||||
// eslint-disable-next-line unicorn/no-thenable
|
||||
export const thenable: any = { then: noop }
|
||||
export const emptyObject = {}
|
||||
@@ -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<P extends object>(
|
||||
Component: ComponentType<P>,
|
||||
options: WithSuspenseOptions = {},
|
||||
): ComponentType<P> {
|
||||
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
|
||||
}
|
||||
Reference in New Issue
Block a user