Skip to content

Commit df38033

Browse files
authored
Merge pull request #266 from dotCMS/fixing-anchor-links-in-info-boxes
Brings same-page anchor link styling into parity with other link styling in info boxes.
2 parents d36d092 + 0430897 commit df38033

1 file changed

Lines changed: 20 additions & 6 deletions

File tree

components/MarkdownContent.tsx

Lines changed: 20 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import SyntaxHighlighter from 'react-syntax-highlighter'
1010
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"
1111
import { Components } from 'react-markdown'
1212
import { smoothScroll } from '@/util/smoothScroll'
13+
import { cn } from '@/util/utils'
1314
import { CopyButton } from './chat/CopyButton'
1415
import { a11yLight, a11yDark } from 'react-syntax-highlighter/dist/cjs/styles/hljs'
1516
import { useTheme } from "next-themes"
@@ -35,6 +36,14 @@ type ExtendedComponents = Components & {
3536
const HEADER_HEIGHT = 80;
3637
const BREADCRUMB_HEIGHT = 48; // 24px height + 24px bottom margin
3738

39+
/** rehype-autolink-headings adds this class; only those # links should match heading chrome, not prose fragment links */
40+
function isHeadingAutolinkClass(className: unknown): boolean {
41+
if (!className) return false
42+
if (typeof className === 'string') return className.split(/\s+/).includes('anchor')
43+
if (Array.isArray(className)) return className.some((c) => isHeadingAutolinkClass(c))
44+
return false
45+
}
46+
3847
// Context to track if we're inside a list item
3948
const ListItemContext = createContext(false);
4049

@@ -194,16 +203,21 @@ const MarkdownContent: React.FC<MarkdownContentProps> = ({ content, className, d
194203
<li className="text-base leading-7 text-foreground mb-1">{children}</li>
195204
</ListItemContext.Provider>
196205
),
197-
a: ({ href, children, ...props }) => {
198-
const isInHeading = href?.startsWith('#');
206+
a: ({ href, children, className, ...props }) => {
207+
const isHashFragment = Boolean(href?.startsWith('#'))
208+
const isHeadingAutolink = isHashFragment && isHeadingAutolinkClass(className)
209+
const proseLinkClass =
210+
'text-primary-purple hover:opacity-80 underline hover:no-underline'
199211

200212
return (
201213
<a
202214
href={href}
203-
className={isInHeading
204-
? `text-foreground`
205-
: `text-primary-purple hover:opacity-80 underline hover:no-underline`}
206-
onClick={(e) => isInHeading ? smoothScroll(e) : undefined}
215+
className={cn(
216+
className,
217+
isHeadingAutolink ? 'text-foreground' : proseLinkClass
218+
)}
219+
onClick={(e) => (isHashFragment ? smoothScroll(e) : undefined)}
220+
{...props}
207221
>
208222
{children}
209223
</a>

0 commit comments

Comments
 (0)