Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

WIP: clickable results #395

Open
wants to merge 4 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
109 changes: 103 additions & 6 deletions apps/masterbots.ai/app/globals.css
Original file line number Diff line number Diff line change
Expand Up @@ -263,15 +263,50 @@
}
}

/* Clickable text styles */
.text-link {
@apply text-accent hover:text-accent/90;
}

button.text-link {
@apply inline-block p-0 m-0 bg-transparent border-0;
/* Improved button styling for clickable text elements */
button.text-link,
button.clickable-text {
@apply inline-block p-0 m-0 bg-transparent border-0 cursor-pointer;
font-family: inherit;
font-size: inherit;
line-height: inherit;
text-align: left;
}

/* Clickable text hover effect */
button.clickable-text {
@apply transition-colors duration-200 text-accent hover:text-accent/90 hover:underline;
position: relative;
}

/* Enhanced hover effect for headings */
h1 button.clickable-text,
h2 button.clickable-text,
h3 button.clickable-text,
h4 button.clickable-text {
@apply hover:text-accent;
position: relative;
}

/* Special styling for clickable section titles */
.section-title.clickable-text,
button.section-title {
@apply font-semibold;
}

/* Bullet point-specific clickable styling */
li > button.clickable-text {
@apply font-medium hover:text-accent;
}

/* Focus styles for accessibility */
button.clickable-text:focus-visible {
@apply rounded outline-none ring-2 ring-accent ring-offset-2;
}

/* Prevent wrapping issues */
Expand All @@ -280,6 +315,21 @@ button.text-link {
vertical-align: baseline;
}

/* Special styling for markdown headers */
.markdown-header button.clickable-text {
@apply font-bold hover:text-accent;
}

/* Unique phrase highlighting */
.unique-phrase button.clickable-text {
@apply italic font-medium;
}

/* Styling for highlighted terms */
.highlighted-term button.clickable-text {
@apply bg-accent/10 py-0.5 px-1 rounded hover:bg-accent/20;
}

.scrollbar {
overflow: auto;
}
Expand Down Expand Up @@ -499,10 +549,6 @@ button.text-link {
background-image: var(--background-public-gradient);
}





/* Component route styles */

/* Avatar ring colors */
Expand Down Expand Up @@ -553,4 +599,55 @@ button.text-link {
background-image: var(--background-public-gradient);
}

/* Specific styles for markdown-generated sections */

/* Style for h2 headings */
h2 button.clickable-text {
@apply text-xl font-bold transition-colors duration-150 hover:text-accent;
}

/* Style for h3 headings */
h3 button.clickable-text {
@apply text-lg font-bold transition-colors duration-150 hover:text-accent;
}

/* Style for numbered sections */
[class*="section-number"] button.clickable-text {
@apply font-semibold hover:text-accent;
}

/* Style for bullet points */
li > p > button.clickable-text:first-child {
@apply font-medium hover:text-accent;
}

/* Style for "MacBook Pro M2" and "MacBook Air M2" sections */
p > button.clickable-text:first-child {
@apply font-medium hover:text-accent;
}

/* Style specifically for section titles with colons */
button.clickable-text[data-section-title="true"] {
@apply font-semibold hover:text-accent;
}

/* Style for "Unique Lesser-Known Solution" section */
.unique-solution button.clickable-text {
@apply italic font-medium hover:text-accent;
}

/* Indicator for clickable sections */
button.clickable-text::after {
content: '';
position: absolute;
bottom: -2px;
left: 0;
width: 0;
height: 1px;
background-color: currentColor;
transition: width 0.2s ease;
}

button.clickable-text:hover::after {
width: 100%;
}
227 changes: 227 additions & 0 deletions apps/masterbots.ai/components/routes/chat/chat-clickable-list.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,227 @@
import React, { type ReactNode, useState } from 'react'
import { cn } from '@/lib/utils'
import {
extractTextContent,
extractContextFromText,
extractTitleFromHeading,
formatFollowUpQuery,
safeInvoke
} from '@/lib/clickable-content-extraction'

interface EnhancedClickableTextProps {
children: ReactNode
sendMessageFromResponse?: (message: string) => void
}

/**
* EnhancedClickableText Component - Makes text elements clickable based on common AI generation patterns
*
* This component identifies and makes clickable:
* 1. Section headings (like "1. Architecture")
* 2. List items with bold/strong text as the first element
* 3. Text patterns with colons separating titles from content
*/
export function EnhancedClickableText({
children,
sendMessageFromResponse
}: EnhancedClickableTextProps) {
// Track hover state for enhanced visual cues
const [hoveredElement, setHoveredElement] = useState<string | null>(null)

// Check if an element is a list item (li)
const isListItem = (element: React.ReactElement): boolean => {
return element.type === 'li'
}

// Check if an element is a heading (h1, h2, h3, etc.)
const isHeading = (element: React.ReactElement): boolean => {
return typeof element.type === 'string' && /^h[1-6]$/.test(element.type)
}

// Check if an element is a strong/bold tag
const isStrong = (element: React.ReactElement): boolean => {
return element.type === 'strong' || element.type === 'b'
}

// Check if a text string matches a section heading pattern (e.g., "1. Architecture")
const isSectionHeading = (text: string): boolean => {
return /^\d+\.\s+[A-Z][a-zA-Z\s]+$/.test(text)
}

// Handle click events for clickable elements
// biome-ignore lint/suspicious/noExplicitAny: <explanation>
const handleClick = (text: string, contextText: any = '') => {
if (!sendMessageFromResponse) {
console.warn('sendMessageFromResponse function is not provided')
return
}

const query = formatFollowUpQuery(text, contextText)
safeInvoke(sendMessageFromResponse, query.trim())
}

// Process section headings (e.g., "1. Architecture")
const processSectionHeading = (element: React.ReactElement) => {
const headingText = extractTextContent(element.props.children)

if (isSectionHeading(headingText)) {
const title = extractTitleFromHeading(headingText)
const elementId = `heading-${title.replace(/\s+/g, '-').toLowerCase()}`
const isHovered = hoveredElement === elementId

return React.cloneElement(element, {
...element.props,
children: (
<button
className={cn(
'clickable-text p-0 m-0 font-bold text-left bg-transparent',
'border-none cursor-pointer relative transition-colors duration-200 w-full',
isHovered
? 'text-accent underline'
: 'hover:text-accent hover:underline'
)}
onClick={() => handleClick(title)}
onMouseEnter={() => setHoveredElement(elementId)}
onMouseLeave={() => setHoveredElement(null)}
aria-label={`Get more details about ${title}`}
type="button"
>
{element.props.children}
</button>
)
})
}

return element
}

// Process list items with bold text
const processListItemWithBold = (element: React.ReactElement) => {
// Check if this list item contains a strong/bold element
let hasStrongElement = false
let strongText = ''
let fullItemText = ''

// First, extract the full text of the list item
fullItemText = extractTextContent(element.props.children)

// Process the children to find strong elements
React.Children.forEach(element.props.children, (child: React.ReactNode) => {
if (React.isValidElement(child) && isStrong(child)) {
hasStrongElement = true
strongText = extractTextContent(
(child as React.ReactElement).props.children
)
}
})

if (hasStrongElement) {
// Extract context using our utility function
const contextText = extractContextFromText(fullItemText, strongText)

// Process the children to make the bold elements clickable
const processedChildren = React.Children.map(
element.props.children,
child => {
if (React.isValidElement(child) && isStrong(child)) {
const elementId = `strong-${strongText.replace(/\s+/g, '-').toLowerCase()}`
const isHovered = hoveredElement === elementId

return React.cloneElement(
// biome-ignore lint/complexity/noBannedTypes: <explanation>
child as React.ReactElement<React.PropsWithChildren<{}>>,
{
...(child as React.ReactElement).props,
children: (
<button
className={cn(
'clickable-text p-0 m-0 font-semibold text-left bg-transparent',
'border-none cursor-pointer relative transition-colors duration-200',
isHovered
? 'text-accent underline'
: 'hover:text-accent hover:underline'
)}
onClick={() => handleClick(strongText, contextText)}
onMouseEnter={() => setHoveredElement(elementId)}
onMouseLeave={() => setHoveredElement(null)}
aria-label={`Get more details about ${strongText}`}
type="button"
>
{(child as React.ReactElement).props.children}
</button>
)
}
)
}
return child
}
)

return React.cloneElement(element, {
...element.props,
children: processedChildren
})
}

return element
}

// Main processing function for React elements
const processContent = (content: ReactNode): ReactNode => {
// Handle string content directly
if (typeof content === 'string') {
return content
}

// Skip non-string/non-object content
if (typeof content !== 'object' || content === null) {
return content
}

// Process arrays of elements
if (Array.isArray(content)) {
return content.map((item, index) => (
<React.Fragment
key={`content-item-${
// biome-ignore lint/suspicious/noArrayIndexKey: <explanation>
index
}`}
>
{processContent(item)}
</React.Fragment>
))
}

// Process React elements
if (React.isValidElement(content)) {
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

issue (complexity): Consider using a configurable transformation list to handle different element types, reducing nested conditionals in processContent.

Consider abstracting the conditional branching into a configurable transformation list so that you avoid writing separate deep branches. For example, you could create an array of transformation objects that encapsulates the conditions and transformation functions. Then in your recursive processContent, check if any transformation applies before processing children. This keeps the recursion logic flatter and more declarative.

For instance, you can refactor like this:

// List your processors
const processors: {
  check: (element: React.ReactElement) => boolean;
  transform: (element: React.ReactElement) => React.ReactElement;
}[] = [
  {
    check: (element) => isHeading(element),
    transform: (element) => processSectionHeading(element),
  },
  {
    check: (element) => isListItem(element),
    transform: (element) => processListItemWithBold(element),
  },
  // add more processors as needed
];

const processContent = (content: React.ReactNode): React.ReactNode => {
  if (typeof content === 'string' || typeof content !== 'object' || content === null)
    return content;

  if (Array.isArray(content))
    return content.map((item, index) => (
      <React.Fragment key={`content-item-${index}`}>
        {processContent(item)}
      </React.Fragment>
    ));

  if (React.isValidElement(content)) {
    // Find the first matching processor
    for (const { check, transform } of processors) {
      if (check(content)) {
        return transform(content);
      }
    }

    // Process children if available
    if (content.props?.children) {
      return React.cloneElement(content, {
        ...content.props,
        children: processContent(content.props.children),
      });
    }
  }
  return content;
};

This approach maintains functionality while reducing nested conditional logic.

// Process headings
if (isHeading(content)) {
return processSectionHeading(content)
}

// Process list items
if (isListItem(content)) {
return processListItemWithBold(content)
}

// Process children of other elements
// biome-ignore lint/complexity/useOptionalChain: <explanation>
if (content.props && content.props.children) {
return React.cloneElement(
// biome-ignore lint/complexity/noBannedTypes: <explanation>
content as React.ReactElement<React.PropsWithChildren<{}>>,
{
...(content as React.ReactElement).props,
children: processContent(
(content as React.ReactElement).props.children
)
}
)
}
}

return content
}

return <>{processContent(children)}</>
}
Loading