reactor: extract context block hook

Signed-off-by: Innei <tukon479@gmail.com>
This commit is contained in:
Innei
2025-10-17 23:11:09 +08:00
parent cf77555a3c
commit 2b902efff2
4 changed files with 253 additions and 269 deletions
@@ -4,26 +4,18 @@ import type { FC, ReactNode } from "react"
import { memo } from "react"
import { useTranslation } from "react-i18next"
import { ImageThumbnail } from "~/modules/ai-chat/components/message/ImageThumbnail"
import { CircularProgress } from "~/modules/ai-chat/components/ui/UploadProgress"
import { useContextBlockPresentation } from "~/modules/ai-chat/components/message/useContextBlockPresentation"
import { useChatBlockActions } from "~/modules/ai-chat/store/hooks"
import type { AIChatContextBlock, ValueContextBlock } from "~/modules/ai-chat/store/types"
import {
getFileCategoryFromMimeType,
getFileIconName,
} from "~/modules/ai-chat/utils/file-validation"
import type { AbstractValueContextBlock, AIChatContextBlock } from "~/modules/ai-chat/store/types"
import { EntryTitle, FeedTitle } from "./TitleComponents"
const blockTypeCanNotBeRemoved = new Set<string>([])
import { FeedTitle } from "./TitleComponents"
const BlockContainer: FC<{
icon: string | null | undefined
label?: string
canRemove: boolean
onRemove?: () => void
content: ReactNode
}> = memo(({ icon, label, canRemove, onRemove, content }) => {
}> = memo(({ icon, label, onRemove, content }) => {
const isStringContent = typeof content === "string"
return (
@@ -36,9 +28,7 @@ const BlockContainer: FC<{
<div
className={clsx(
"min-w-0",
canRemove
? "group-hover:[mask-image:linear-gradient(to_right,black_0%,black_calc(100%-3rem),rgba(0,0,0,0.8)_calc(100%-2rem),rgba(0,0,0,0.3)_calc(100%-1rem),transparent_100%)]"
: void 0,
"group-hover:[mask-image:linear-gradient(to_right,black_0%,black_calc(100%-3rem),rgba(0,0,0,0.8)_calc(100%-2rem),rgba(0,0,0,0.3)_calc(100%-1rem),transparent_100%)]",
)}
>
<div className="flex min-w-0 flex-1 items-center gap-1.5">
@@ -55,27 +45,21 @@ const BlockContainer: FC<{
</div>
</div>
{canRemove && (
<button
type="button"
onClick={onRemove}
className="text-text/90 cursor-button hover:text-text absolute inset-y-0 right-2 flex-shrink-0 opacity-0 transition-all ease-in group-hover:opacity-100"
>
<i className="i-mgc-close-cute-re size-3" />
</button>
)}
<button
type="button"
onClick={onRemove}
className="text-text/90 cursor-button hover:text-text absolute inset-y-0 right-2 flex-shrink-0 opacity-0 transition-all ease-in group-hover:opacity-100"
>
<i className="i-mgc-close-cute-re size-3" />
</button>
</div>
)
})
BlockContainer.displayName = "ContextBlockContainer"
type ValueBlockOf<Type extends ValueContextBlock["type"]> = Omit<ValueContextBlock, "type"> & {
type: Type
}
type MainViewBlock = ValueBlockOf<"mainView">
type MainFeedBlock = ValueBlockOf<"mainFeed">
type UnreadOnlyBlock = ValueBlockOf<"unreadOnly">
type MainViewBlock = AbstractValueContextBlock<"mainView">
type MainFeedBlock = AbstractValueContextBlock<"mainFeed">
type UnreadOnlyBlock = AbstractValueContextBlock<"unreadOnly">
export const CombinedContextBlock: FC<{
viewBlock?: MainViewBlock
@@ -88,15 +72,9 @@ export const CombinedContextBlock: FC<{
const viewIcon = viewBlock && getView(Number(viewBlock.value))?.icon.props.className
const handleRemove = () => {
if (viewBlock) {
blockActions.removeBlock(viewBlock.id)
}
if (feedBlock) {
blockActions.removeBlock(feedBlock.id)
}
if (unreadOnlyBlock) {
blockActions.removeBlock(unreadOnlyBlock.id)
}
viewBlock && blockActions.removeBlock(viewBlock.id)
feedBlock && blockActions.removeBlock(feedBlock.id)
unreadOnlyBlock && blockActions.removeBlock(unreadOnlyBlock.id)
}
// Determine what to display
@@ -116,190 +94,21 @@ export const CombinedContextBlock: FC<{
</span>
)
return (
<BlockContainer
icon={viewIcon}
canRemove={true}
onRemove={handleRemove}
content={displayContent}
/>
)
return <BlockContainer icon={viewIcon} onRemove={handleRemove} content={displayContent} />
})
CombinedContextBlock.displayName = "CombinedContextBlock"
export const ContextBlock: FC<{ block: AIChatContextBlock }> = memo(({ block }) => {
const { t } = useTranslation("common")
const blockActions = useChatBlockActions()
const getBlockIcon = () => {
switch (block.type) {
case "mainView": {
const viewIcon = getView(Number(block.value))?.icon.props.className
return viewIcon
}
case "mainEntry": {
return "i-mgc-star-cute-fi"
}
case "mainFeed": {
return "i-mgc-rss-cute-fi"
}
case "selectedText": {
return "i-mgc-quill-pen-cute-re"
}
case "unreadOnly": {
return "i-mgc-round-cute-fi"
}
case "fileAttachment": {
const { type, dataUrl, previewUrl } = block.attachment
const fileCategory = getFileCategoryFromMimeType(type)
// Don't show icon for images with thumbnails, as the thumbnail serves as the icon
if (fileCategory === "image" && (dataUrl || previewUrl)) {
return null
}
return getFileIconName(fileCategory)
}
default: {
return "i-mgc-paper-cute-fi"
}
}
}
const getDisplayContent = () => {
switch (block.type) {
case "mainView": {
const viewName = getView(Number(block.value))?.name
return viewName ? t(viewName) : block.value
}
case "mainEntry": {
return <EntryTitle entryId={block.value} fallback={block.value} />
}
case "mainFeed": {
return <FeedTitle feedId={block.value} fallback={block.value} />
}
case "selectedText": {
return `"${block.value}"`
}
case "unreadOnly": {
return "Unread Only"
}
case "fileAttachment": {
const { type, name, dataUrl, previewUrl, uploadStatus, errorMessage, uploadProgress } =
block.attachment
const fileCategory = getFileCategoryFromMimeType(type)
if (fileCategory === "image" && (dataUrl || previewUrl)) {
return (
<div className="flex items-center gap-1.5">
<div className="relative">
<ImageThumbnail
className={"m-0.5 size-5 rounded-md"}
attachment={block.attachment}
/>
{uploadStatus === "uploading" && uploadProgress !== undefined && (
<div className="absolute inset-0 flex items-center justify-center rounded-md bg-black/50">
<CircularProgress
progress={uploadProgress}
size={16}
strokeWidth={2}
variant="default"
className="text-white"
/>
</div>
)}
{uploadStatus === "error" && (
<div
className="bg-red/80 absolute inset-0 flex items-center justify-center rounded-md"
title={errorMessage}
>
<i className="i-mgc-close-cute-re size-3 text-white" />
</div>
)}
</div>
<div className="flex min-w-0 flex-1">
<span className="truncate">
{name}{" "}
{uploadStatus === "uploading" && uploadProgress !== undefined && (
<div className="text-text-tertiary text-xs">
({Math.round(uploadProgress)}%)
</div>
)}
</span>
{uploadStatus === "error" && <div className="text-red text-xs">Upload failed</div>}
</div>
</div>
)
}
// For non-image files
return (
<div className="flex items-center gap-1.5">
<span className="min-w-0 flex-1 truncate">{name}</span>
{uploadStatus === "uploading" && uploadProgress !== undefined && (
<div className="flex items-center gap-1">
<CircularProgress
progress={uploadProgress}
size={14}
strokeWidth={2}
variant="default"
/>
<span className="text-text-tertiary text-xs">{Math.round(uploadProgress)}%</span>
</div>
)}
{uploadStatus === "error" && (
<i className="i-mgc-close-cute-re text-red size-3" title={errorMessage} />
)}
</div>
)
}
default: {
// This should never happen with proper discriminated union
return ""
}
}
}
const getBlockLabel = () => {
switch (block.type) {
case "mainView": {
return ""
}
case "mainEntry": {
return "Current"
}
case "mainFeed": {
return "Current"
}
case "selectedText": {
return "Text"
}
case "unreadOnly": {
return "Filter"
}
case "fileAttachment": {
return "File"
}
default: {
return ""
}
}
}
const canRemove = !blockTypeCanNotBeRemoved.has(block.type)
const { icon, label, displayContent } = useContextBlockPresentation(block)
return (
<BlockContainer
icon={getBlockIcon()}
label={getBlockLabel()}
canRemove={canRemove}
onRemove={canRemove ? () => blockActions.removeBlock(block.id) : undefined}
content={getDisplayContent()}
icon={icon}
label={label}
onRemove={() => blockActions.removeBlock(block.id)}
content={displayContent}
/>
)
})
@@ -5,15 +5,10 @@ import * as React from "react"
import type { AIChatContextBlock, ValueContextBlock } from "~/modules/ai-chat/store/types"
import {
getBlockIcon,
getBlockLabel,
getBlockStyles,
getFileDisplayContent,
isImageAttachment,
} from "./ai-block-constants"
import { EntryTitle, FeedTitle } from "./BlockTitleComponents"
import { getBlockStyles } from "./ai-block-constants"
import { FeedTitle } from "./BlockTitleComponents"
import { ImageThumbnail } from "./ImageThumbnail"
import { useContextBlockPresentation } from "./useContextBlockPresentation"
interface AIDataBlockItemProps {
block: AIChatContextBlock
@@ -33,39 +28,6 @@ interface CombinedDataBlockItemProps {
/**
* Gets the display content for a context block
*/
const getDisplayContent = (block: AIChatContextBlock): React.ReactNode => {
switch (block.type) {
case "mainView": {
const viewName = getView(Number(block.value))?.name
return viewName ? t(viewName, { ns: "common" }) : block.value
}
case "mainEntry": {
return <EntryTitle entryId={block.value} fallback={block.value} />
}
case "mainFeed": {
return <FeedTitle feedId={block.value} fallback={block.value} />
}
case "selectedText": {
return `"${block.value}"`
}
case "unreadOnly": {
return "Unread Only"
}
case "fileAttachment": {
if (!block.attachment) {
return "[File: Unknown]"
}
if (block.attachment.name && !block.attachment.uploadStatus) {
return block.attachment.name
}
return getFileDisplayContent(block.attachment)
}
default: {
return ""
}
}
}
/**
* Renders the appropriate icon or image thumbnail for a block
@@ -73,19 +35,27 @@ const getDisplayContent = (block: AIChatContextBlock): React.ReactNode => {
const BlockIcon: React.FC<{
block: AIChatContextBlock
styles: ReturnType<typeof getBlockStyles>
}> = React.memo(({ block, styles }) => {
// Handle image thumbnails for file attachments
if (block.type === "fileAttachment" && block.attachment && isImageAttachment(block)) {
presentation: ReturnType<typeof useContextBlockPresentation>
}> = React.memo(({ block, styles, presentation }) => {
if (
block.type === "fileAttachment" &&
presentation.attachment &&
presentation.isImageAttachment
) {
return (
<div
className={cn("flex size-4 flex-shrink-0 items-center justify-center rounded", styles.icon)}
>
<ImageThumbnail attachment={block.attachment} />
<ImageThumbnail attachment={presentation.attachment} />
</div>
)
}
const iconClass = getBlockIcon(block)
const iconClass = presentation.icon
if (!iconClass) {
return null
}
return (
<div
@@ -107,7 +77,8 @@ const BlockContainer: React.FC<{
label?: string
displayContent: React.ReactNode
title?: string
}> = React.memo(({ styles, block, label, displayContent, title }) => {
presentation: ReturnType<typeof useContextBlockPresentation>
}> = React.memo(({ styles, block, label, displayContent, title, presentation }) => {
return (
<div
key={block.id}
@@ -117,7 +88,7 @@ const BlockContainer: React.FC<{
styles.container,
)}
>
<BlockIcon block={block} styles={styles} />
<BlockIcon block={block} styles={styles} presentation={presentation} />
{/* Label and content */}
<div className="flex min-w-0 items-center gap-1">
@@ -145,11 +116,17 @@ BlockContainer.displayName = "BlockContainer"
*/
export const AIDataBlockItem: React.FC<AIDataBlockItemProps> = React.memo(({ block }) => {
const styles = React.useMemo(() => getBlockStyles(block.type), [block.type])
const label = React.useMemo(() => getBlockLabel(block.type), [block.type])
const displayContent = React.useMemo(() => getDisplayContent(block), [block])
const presentation = useContextBlockPresentation(block)
return (
<BlockContainer styles={styles} block={block} label={label} displayContent={displayContent} />
<BlockContainer
styles={styles}
block={block}
label={presentation.label}
displayContent={presentation.displayContent}
title={presentation.title}
presentation={presentation}
/>
)
})
@@ -232,8 +209,17 @@ export const CombinedDataBlockItem: React.FC<CombinedDataBlockItemProps> = React
}
}, [viewBlock, feedBlock, unreadOnlyBlock])
const presentation = useContextBlockPresentation(block)
return (
<BlockContainer styles={styles} block={block} displayContent={displayContent} title={title} />
<BlockContainer
styles={styles}
block={block}
label={presentation.label}
displayContent={displayContent}
title={title}
presentation={presentation}
/>
)
},
)
@@ -0,0 +1,179 @@
import { getView } from "@follow/constants"
import type { ReactNode } from "react"
import { useMemo } from "react"
import { useTranslation } from "react-i18next"
import { ROUTE_FEED_IN_FOLDER } from "~/constants"
import type { AIChatContextBlock, FileAttachment } from "~/modules/ai-chat/store/types"
import { CircularProgress } from "../ui/UploadProgress"
import {
getBlockIcon,
getBlockLabel,
getFileDisplayContent,
isImageAttachment,
} from "./ai-block-constants"
import { EntryTitle, FeedTitle } from "./BlockTitleComponents"
import { ImageThumbnail } from "./ImageThumbnail"
export interface ContextBlockPresentation {
icon?: string | null
label?: string
displayContent: ReactNode
title?: string
attachment?: FileAttachment
isImageAttachment: boolean
}
export function useContextBlockPresentation(block: AIChatContextBlock): ContextBlockPresentation {
const { t } = useTranslation("common")
return useMemo(() => {
const label = block.type === "mainView" ? "" : getBlockLabel(block.type)
const isImage = isImageAttachment(block)
const icon = block.type === "fileAttachment" && isImage ? null : getBlockIcon(block)
const attachment = block.type === "fileAttachment" ? block.attachment : undefined
const buildFileContent = (): ReactNode => {
if (!attachment) {
return <span className="text-text-tertiary">[File: Unknown]</span>
}
const { dataUrl, previewUrl, uploadStatus, uploadProgress, errorMessage, name } = attachment
if (isImage && (dataUrl || previewUrl)) {
return (
<div className="flex items-center gap-1.5">
<div className="relative">
<ImageThumbnail className="m-0.5 size-5 rounded-md" attachment={attachment} />
{uploadStatus === "uploading" && uploadProgress !== undefined && (
<div className="absolute inset-0 flex items-center justify-center rounded-md bg-black/50">
<CircularProgress
progress={uploadProgress}
size={16}
strokeWidth={2}
variant="default"
className="text-white"
/>
</div>
)}
{uploadStatus === "error" && (
<div
className="bg-red/80 absolute inset-0 flex items-center justify-center rounded-md"
title={errorMessage}
>
<i className="i-mgc-close-cute-re size-3 text-white" />
</div>
)}
</div>
<div className="flex min-w-0 flex-1 items-center gap-1">
<span className="truncate" title={name}>
{name}
</span>
{uploadStatus === "uploading" && uploadProgress !== undefined && (
<span className="text-text-tertiary text-xs">{Math.round(uploadProgress)}%</span>
)}
{uploadStatus === "error" && (
<span className="text-red text-xs" title={errorMessage}>
Upload failed
</span>
)}
</div>
</div>
)
}
return (
<div className="flex items-center gap-1.5">
<span className="min-w-0 flex-1 truncate" title={name}>
{name}
</span>
{uploadStatus === "uploading" && uploadProgress !== undefined && (
<div className="flex items-center gap-1">
<CircularProgress
progress={uploadProgress}
size={14}
strokeWidth={2}
variant="default"
/>
<span className="text-text-tertiary text-xs">{Math.round(uploadProgress)}%</span>
</div>
)}
{uploadStatus === "error" && (
<i className="i-mgc-close-cute-re text-red size-3" title={errorMessage} />
)}
</div>
)
}
let displayContent: ReactNode
let title: string | undefined
switch (block.type) {
case "mainView": {
const viewName = getView(Number(block.value))?.name
const translated = viewName ? t(viewName) : block.value
displayContent = translated
title = typeof translated === "string" ? translated : undefined
break
}
case "mainEntry": {
displayContent = <EntryTitle entryId={block.value} fallback={block.value} />
break
}
case "mainFeed": {
const category = block.value?.startsWith(ROUTE_FEED_IN_FOLDER)
? block.value.slice(ROUTE_FEED_IN_FOLDER.length)
: undefined
displayContent = category ? (
<span>{category}</span>
) : (
<FeedTitle feedId={block.value} fallback={block.value} />
)
break
}
case "selectedText": {
displayContent = `"${block.value}"`
title = block.value
break
}
case "unreadOnly": {
displayContent = "Unread Only"
title = "Unread Only"
break
}
case "fileAttachment": {
displayContent = buildFileContent()
title = attachment
? attachment.name || getFileDisplayContent(attachment)
: "[File: Unknown]"
break
}
default: {
displayContent = ""
break
}
}
if (!title && typeof displayContent === "string") {
title = displayContent
}
return {
icon,
label,
displayContent,
title,
attachment,
isImageAttachment: isImage,
}
}, [block, t])
}
@@ -19,11 +19,19 @@ interface BaseContextBlock {
id: string
}
export interface ValueContextBlock extends BaseContextBlock {
type: "mainView" | "mainEntry" | "mainFeed" | "selectedText" | "unreadOnly"
export type ValueContextBlockType =
| "mainView"
| "mainEntry"
| "mainFeed"
| "selectedText"
| "unreadOnly"
export interface AbstractValueContextBlock<T extends string> extends BaseContextBlock {
type: T
value: string
}
export type ValueContextBlock = AbstractValueContextBlock<ValueContextBlockType>
export interface FileAttachmentContextBlock extends BaseContextBlock {
type: "fileAttachment"
attachment: FileAttachment
@@ -36,6 +44,8 @@ export type AIChatContextBlockInput =
| Omit<ValueContextBlock, "id">
| Omit<FileAttachmentContextBlock, "id">
export type AIChatContextBlockType = AIChatContextBlock["type"]
export interface AIChatStoreInitial {
blocks: AIChatContextBlock[]
chatId?: string