All files / src/components/chat/task-header FocusChain.tsx

0% Statements 0/154
0% Branches 0/1
0% Functions 0/1
0% Lines 0/154

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217                                                                                                                                                                                                                                                                                                                                                                                                                                                 
import { cn } from "@heroui/react"
import { isCompletedFocusChainItem, isFocusChainItem } from "@shared/focus-chain-utils"
import { StringRequest } from "@shared/proto/cline/common"
import { ChevronDownIcon, ChevronRightIcon } from "lucide-react"
import React, { memo, useCallback, useMemo, useState } from "react"
import ChecklistRenderer from "@/components/common/ChecklistRenderer"
import LightMarkdown from "@/components/common/LightMarkdown"
import { FileServiceClient } from "@/services/grpc-client"
 
// Optimized interface with readonly properties to prevent accidental mutations
interface TodoInfo {
	readonly currentTodo: { text: string; completed: boolean; index: number } | null
	readonly currentIndex: number
	readonly completedCount: number
	readonly totalCount: number
	readonly progressPercentage: number
}
 
interface FocusChainProps {
	readonly lastProgressMessageText?: string
	readonly currentTaskItemId?: string
}
 
// Static strings to avoid recreating them
const COMPLETED_MESSAGE = "All tasks have been completed!"
const TODO_LIST_LABEL = "To-Do list"
const NEW_STEPS_MESSAGE = "New steps will be generated if you continue the task"
const CLICK_TO_EDIT_TITLE = "Click to edit to-do list in file"
 
// Optimized header component with minimal re-renders
const ToDoListHeader = memo<{
	todoInfo: TodoInfo
	isExpanded: boolean
}>(({ todoInfo, isExpanded }) => {
	const { currentTodo, currentIndex, totalCount, completedCount, progressPercentage } = todoInfo
	const isCompleted = completedCount === totalCount
 
	// Pre-compute display text
	const displayText = isCompleted ? COMPLETED_MESSAGE : currentTodo?.text || TODO_LIST_LABEL
 
	return (
		<div
			className={cn("relative w-full h-full", {
				"text-success": isCompleted,
			})}>
			<div
				className={cn(
					"absolute bottom-0 left-0 transition-[width] duration-300 ease-in-out pointer-events-none z-1 h-1 bg-success",
					{
						"opacity-0": progressPercentage === 0 || progressPercentage === 100,
					},
				)}
				style={{
					width: `${progressPercentage}%`,
				}}
			/>
			<div className="flex items-center justify-between gap-2 z-10 py-2.5 px-1.5">
				<div className="flex items-center gap-1.5 flex-1 min-w-0">
					<span
						className={cn(
							"rounded-lg px-2 py-0.25 text-xs inline-block shrink-0 bg-badge-foreground/20 text-foreground",
							{
								"bg-success text-black": isCompleted,
							},
						)}>
						{currentIndex}/{totalCount}
					</span>
					<div className="header-text text-xs font-medium break-words overflow-hidden text-ellipsis whitespace-nowrap max-w-[calc(100%-60px)]">
						<LightMarkdown compact text={displayText} />
					</div>
				</div>
				<div className="flex items-center justify-between text-foreground">
					{isExpanded ? <ChevronDownIcon className="ml-0.25" size="16" /> : <ChevronRightIcon size="16" />}
				</div>
			</div>
		</div>
	)
})
 
ToDoListHeader.displayName = "ToDoListHeader"
 
// Cache for parsed todo info to avoid re-parsing identical text
const todoInfoCache = new Map<string, TodoInfo | null>()
const MAX_CACHE_SIZE = 100
 
// Highly optimized parsing with minimal allocations
const parseCurrentTodoInfo = (text: string): TodoInfo | null => {
	if (!text) {
		return null
	}
 
	// Check cache first
	const cached = todoInfoCache.get(text)
	if (cached !== undefined) {
		return cached
	}
 
	let completedCount = 0
	let totalCount = 0
	let firstIncompleteIndex = -1
	let firstIncompleteText: string | null = null
 
	// Process text line by line without creating intermediate arrays
	let lineStart = 0
	let lineEnd = text.indexOf("\n")
 
	while (lineStart < text.length) {
		const line = lineEnd === -1 ? text.substring(lineStart).trim() : text.substring(lineStart, lineEnd).trim()
 
		if (isFocusChainItem(line)) {
			const isCompleted = isCompletedFocusChainItem(line)
 
			if (isCompleted) {
				completedCount++
			} else if (firstIncompleteIndex === -1) {
				firstIncompleteIndex = totalCount
				// Extract text only for the first incomplete item
				firstIncompleteText = line.substring(5).trim()
			}
 
			totalCount++
		}
 
		if (lineEnd === -1) {
			break
		}
		lineStart = lineEnd + 1
		lineEnd = text.indexOf("\n", lineStart)
	}
 
	if (totalCount === 0) {
		todoInfoCache.set(text, null)
		return null
	}
 
	const currentTodo = firstIncompleteText ? { text: firstIncompleteText, completed: false, index: firstIncompleteIndex } : null
 
	const result: TodoInfo = {
		currentTodo,
		currentIndex: firstIncompleteIndex >= 0 ? firstIncompleteIndex + 1 : totalCount,
		completedCount,
		totalCount,
		progressPercentage: (completedCount / totalCount) * 100,
	}
 
	// Cache the result with size management
	if (todoInfoCache.size >= MAX_CACHE_SIZE) {
		// Remove oldest entry (first key)
		const firstKey = todoInfoCache.keys().next().value
		if (firstKey) {
			todoInfoCache.delete(firstKey)
		}
	}
	todoInfoCache.set(text, result)
	return result
}
 
// Main component with aggressive optimization
export const FocusChain: React.FC<FocusChainProps> = memo(
	({ currentTaskItemId, lastProgressMessageText }) => {
		const [isExpanded, setIsExpanded] = useState(false)
 
		// Parse todo info with caching
		const todoInfo = useMemo(
			() => (lastProgressMessageText ? parseCurrentTodoInfo(lastProgressMessageText) : null),
			[lastProgressMessageText],
		)
 
		// Static callbacks that don't change
		const handleToggle = useCallback(() => setIsExpanded((prev) => !prev), [])
 
		const handleEditClick = useCallback(
			(e: React.MouseEvent) => {
				e.preventDefault()
				e.stopPropagation()
				if (currentTaskItemId) {
					FileServiceClient.openFocusChainFile(StringRequest.create({ value: currentTaskItemId }))
				}
			},
			[currentTaskItemId],
		)
 
		// Early return for no content
		if (!todoInfo) {
			return null
		}
 
		const isCompleted = todoInfo.completedCount === todoInfo.totalCount
 
		return (
			<div
				className="relative rounded-sm bg-toolbar-hover/65 flex flex-col gap-1.5 select-none hover:bg-toolbar-hover overflow-hidden opacity-80 hover:opacity-100 transition-[transform,box-shadow] duration-200 cursor-pointer"
				onClick={handleToggle}
				title={CLICK_TO_EDIT_TITLE}>
				<ToDoListHeader isExpanded={isExpanded} todoInfo={todoInfo} />
				{isExpanded && (
					<div className="mx-1 pb-2 px-1 relative" onClick={handleEditClick}>
						<ChecklistRenderer text={lastProgressMessageText!} />
						{isCompleted && (
							<div className="mt-2 text-xs font-semibold text-muted-foreground">{NEW_STEPS_MESSAGE}</div>
						)}
					</div>
				)}
			</div>
		)
	},
	(prevProps, nextProps) => {
		// Custom comparison for better performance
		return (
			prevProps.lastProgressMessageText === nextProps.lastProgressMessageText &&
			prevProps.currentTaskItemId === nextProps.currentTaskItemId
		)
	},
)
 
FocusChain.displayName = "FocusChain"