-
Notifications
You must be signed in to change notification settings - Fork 19
[Draft] Add "Copy for LLM" button in docs pages #1007
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
Draft
alfondotnet
wants to merge
7
commits into
main
Choose a base branch
from
fon/add-llm-copy
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
dc50f1c
AI draft: add Copy for LLM button
alfondotnet 54f07eb
use CatIcon
alfondotnet 8f862ef
reduce margin
alfondotnet ed493af
refine copied content
alfondotnet 07afa32
not needed
alfondotnet 188b528
simplify
alfondotnet b91489a
bit more margin
alfondotnet File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -5,4 +5,6 @@ package-lock.json | |
build | ||
.idea | ||
|
||
scripts/image_analysis/ | ||
scripts/image_analysis/ | ||
|
||
.claude/settings.local.json |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,41 @@ | ||
import React, { useState } from 'react'; | ||
import { usePageCopyContent } from '@site/src/utils/copyPageContent'; | ||
import { CatIcon } from '@site/src/theme/CatIcon/CatIcon'; | ||
import styles from './styles.module.css'; | ||
|
||
export default function CopyForLLMButton() { | ||
const { copyToClipboard } = usePageCopyContent(); | ||
const [copyFeedback, setCopyFeedback] = useState<string>(''); | ||
|
||
const handleCopyPage = async () => { | ||
const success = await copyToClipboard(); | ||
if (success) { | ||
setCopyFeedback('Copied!'); | ||
setTimeout(() => setCopyFeedback(''), 2000); | ||
} else { | ||
setCopyFeedback('Failed to copy'); | ||
setTimeout(() => setCopyFeedback(''), 2000); | ||
} | ||
}; | ||
|
||
return ( | ||
<div className={styles.container}> | ||
<div className={styles.buttonWrapper}> | ||
<button | ||
className={styles.copyButton} | ||
onClick={handleCopyPage} | ||
aria-label="Copy page content for LLM" | ||
title="Copy for LLM" | ||
> | ||
<CatIcon name="copy" size={16} customColor="white" /> | ||
<span>Copy for LLM</span> | ||
</button> | ||
{copyFeedback && ( | ||
<span className={styles.copyFeedback}> | ||
{copyFeedback} | ||
</span> | ||
)} | ||
</div> | ||
</div> | ||
); | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,54 @@ | ||
.container { | ||
margin-bottom: 1.5rem; | ||
} | ||
|
||
.buttonWrapper { | ||
position: relative; | ||
display: inline-block; | ||
} | ||
|
||
.copyButton { | ||
display: inline-flex; | ||
align-items: center; | ||
gap: 0.5rem; | ||
padding: 0.5rem 1rem; | ||
border: 1px solid var(--ifm-color-emphasis-300); | ||
background: var(--ifm-background-color); | ||
cursor: pointer; | ||
border-radius: 0.375rem; | ||
transition: all var(--ifm-transition-fast); | ||
font-size: 0.875rem; | ||
color: var(--ifm-color-emphasis-700); | ||
user-select: none; | ||
} | ||
|
||
.copyButton svg { | ||
width: 1rem; | ||
height: 1rem; | ||
fill: var(--ifm-color-emphasis-600); | ||
} | ||
|
||
.copyButton:hover { | ||
background-color: var(--ifm-color-emphasis-100); | ||
border-color: var(--ifm-color-emphasis-400); | ||
color: var(--ifm-color-emphasis-800); | ||
} | ||
|
||
.copyButton:hover svg { | ||
fill: var(--ifm-color-emphasis-800); | ||
} | ||
|
||
.copyFeedback { | ||
position: absolute; | ||
left: calc(100% + 0.5rem); | ||
top: 50%; | ||
transform: translateY(-50%); | ||
padding: 0.25rem 0.5rem; | ||
background-color: var(--ifm-color-emphasis-800); | ||
color: var(--ifm-color-emphasis-100); | ||
border-radius: 0.25rem; | ||
font-size: 0.75rem; | ||
white-space: nowrap; | ||
pointer-events: none; | ||
z-index: 10; | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,18 @@ | ||
import React from 'react'; | ||
import Content from '@theme-original/DocItem/Content'; | ||
import type ContentType from '@theme/DocItem/Content'; | ||
import type { WrapperProps } from '@docusaurus/types'; | ||
import CopyForLLMButton from '@site/src/components/CopyForLLMButton'; | ||
|
||
type Props = WrapperProps<typeof ContentType>; | ||
|
||
export default function ContentWrapper(props: Props): JSX.Element { | ||
return ( | ||
<div style={{ position: 'relative' }}> | ||
<div className="theme-doc-markdown" style={{ marginTop: '2rem' }}> | ||
<CopyForLLMButton /> | ||
</div> | ||
<Content {...props} /> | ||
</div> | ||
); | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,150 @@ | ||
import { useDoc } from "@docusaurus/plugin-content-docs/client"; | ||
|
||
export function usePageCopyContent() { | ||
const doc = useDoc(); | ||
|
||
const extractPageContent = (): string => { | ||
try { | ||
// Get the main article content | ||
const articleElement = document.querySelector('article'); | ||
if (!articleElement) { | ||
return "Content not found"; | ||
} | ||
|
||
// Extract text content while preserving structure | ||
const content = extractStructuredContent(articleElement); | ||
|
||
// Format for LLM consumption | ||
const pageTitle = doc?.metadata?.title || document.title; | ||
const pageUrl = window.location.href; | ||
const frontMatter = doc?.frontMatter ? formatFrontMatter(doc.frontMatter) : ''; | ||
|
||
return formatForLLM(pageTitle, pageUrl, frontMatter, content); | ||
} catch (error) { | ||
console.error('Error extracting page content:', error); | ||
return "Error extracting page content"; | ||
} | ||
}; | ||
|
||
const copyToClipboard = async (): Promise<boolean> => { | ||
try { | ||
const content = extractPageContent(); | ||
await navigator.clipboard.writeText(content); | ||
return true; | ||
} catch (error) { | ||
console.error('Failed to copy content:', error); | ||
return false; | ||
} | ||
}; | ||
|
||
return { extractPageContent, copyToClipboard }; | ||
} | ||
|
||
function extractStructuredContent(element: Element): string { | ||
let content = ''; | ||
|
||
// Walk through the DOM and extract content with structure | ||
const walker = document.createTreeWalker( | ||
element, | ||
NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_TEXT, | ||
{ | ||
acceptNode: (node) => { | ||
// Skip navigation, TOC, and other non-content elements | ||
if (node.nodeType === Node.ELEMENT_NODE) { | ||
const el = node as Element; | ||
if (el.matches('nav, .table-of-contents, .navbar, .pagination-nav, .theme-doc-toc, .hash-link, .buttonWrapper, [aria-label*="Copy"]') || | ||
el.closest('.buttonWrapper') || | ||
el.textContent?.trim() === 'Copy for LLM' || | ||
el.textContent?.trim() === 'On this page') { | ||
return NodeFilter.FILTER_REJECT; | ||
} | ||
} | ||
// Skip text nodes that are inside anchor tags (we'll handle them when processing the anchor) | ||
if (node.nodeType === Node.TEXT_NODE && node.parentElement?.tagName === 'A') { | ||
return NodeFilter.FILTER_REJECT; | ||
} | ||
return NodeFilter.FILTER_ACCEPT; | ||
} | ||
} | ||
); | ||
|
||
let node; | ||
while ((node = walker.nextNode())) { | ||
if (node.nodeType === Node.TEXT_NODE) { | ||
const text = node.textContent?.trim(); | ||
if (text && text.length > 0) { | ||
content += text + ' '; | ||
} | ||
} else if (node.nodeType === Node.ELEMENT_NODE) { | ||
const el = node as Element; | ||
|
||
// Add markdown-style formatting for headings | ||
const headingMatch = el.tagName.match(/^H([1-6])$/); | ||
if (headingMatch) { | ||
const headingLevel = parseInt(headingMatch[1]); | ||
const headingText = el.textContent?.trim(); | ||
if (headingText) { | ||
const markdownPrefix = '#'.repeat(headingLevel); | ||
content += `\n${markdownPrefix} ${headingText}\n\n`; | ||
} | ||
} else if (el.matches('p')) { | ||
content += '\n\n'; | ||
} else if (el.matches('pre, code[class*="language-"]')) { | ||
// Extract code blocks | ||
const codeText = el.textContent?.trim(); | ||
if (codeText) { | ||
content += `\n\`\`\`\n${codeText}\n\`\`\`\n\n`; | ||
} | ||
} else if (el.matches('ul, ol')) { | ||
content += '\n'; | ||
} else if (el.matches('li')) { | ||
content += '\n- '; | ||
} else if (el.matches('a')) { | ||
const linkText = el.textContent?.trim(); | ||
const href = el.getAttribute('href'); | ||
if (linkText && href) { | ||
// Convert relative URLs to absolute URLs | ||
const absoluteUrl = href.startsWith('http') ? href : new URL(href, window.location.origin).href; | ||
content += `[${linkText}](${absoluteUrl})`; | ||
} | ||
} | ||
} | ||
} | ||
|
||
return content.replace(/\n\s*\n\s*\n/g, '\n\n').trim(); | ||
} | ||
|
||
function formatFrontMatter(frontMatter: Record<string, any>): string { | ||
// Whitelist of attributes to include in the copied content | ||
const allowedAttributes = [ | ||
'title', | ||
'description', | ||
'keywords', | ||
'tags', | ||
'author', | ||
'date', | ||
'updated', | ||
'category', | ||
'platform' | ||
]; | ||
|
||
const filtered = Object.entries(frontMatter) | ||
.filter(([key]) => allowedAttributes.includes(key)) | ||
.reduce((obj, [key, value]) => ({ ...obj, [key]: value }), {}); | ||
|
||
if (Object.keys(filtered).length === 0) { | ||
return ''; | ||
} | ||
|
||
return `---\n${Object.entries(filtered) | ||
.map(([key, value]) => `${key}: ${typeof value === 'string' ? value : JSON.stringify(value)}`) | ||
.join('\n')}\n---\n\n`; | ||
} | ||
|
||
function formatForLLM(title: string, url: string, frontMatter: string, content: string): string { | ||
return `# ${title} | ||
|
||
**Source URL:** ${url} | ||
|
||
${frontMatter}${content}`; | ||
} |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I was getting an error building with this config json