From dc14a6d87faf6455a370796dc511d1f57e95c873 Mon Sep 17 00:00:00 2001 From: Charis <26616127+charislam@users.noreply.github.com> Date: Thu, 5 Dec 2024 23:20:08 -0500 Subject: [PATCH] refactor(docs): guides toc headers (#30955) Remove the dangerouslySetInnerHTML which is prone to breakage --- .../docs/components/GuidesTableOfContents.tsx | 48 ++++++++++++------- 1 file changed, 31 insertions(+), 17 deletions(-) diff --git a/apps/docs/components/GuidesTableOfContents.tsx b/apps/docs/components/GuidesTableOfContents.tsx index 4b9a8f378e2..625028213bb 100644 --- a/apps/docs/components/GuidesTableOfContents.tsx +++ b/apps/docs/components/GuidesTableOfContents.tsx @@ -1,7 +1,7 @@ 'use client' import { usePathname } from 'next/navigation' -import { useEffect, useState } from 'react' +import { Fragment, useEffect, useState } from 'react' import { cn } from 'ui' import { ExpandableVideo } from 'ui-patterns/ExpandableVideo' import { proxy, useSnapshot } from 'valtio' @@ -20,27 +20,32 @@ const formatSlug = (slug: string) => { return slug } -const formatTOCHeader = (content: string) => { - let begin = false - const res: Array = [] +function formatTOCHeader(content: string) { + let insideInlineCode = false + const res: Array<{ type: 'text'; value: string } | { type: 'code'; value: string }> = [] + for (const x of content) { if (x === '`') { - if (!begin) { - begin = true - res.push(``) + if (!insideInlineCode) { + insideInlineCode = true + res.push({ type: 'code', value: '' }) } else { - begin = false - res.push(``) + insideInlineCode = false } - } else if (x === '<') { - res.push('<') - } else if (x === '>') { - res.push('>') } else { - res.push(x) + if (insideInlineCode) { + res[res.length - 1].value += x + } else { + if (res.length === 0 || res[res.length - 1].type === 'code') { + res.push({ type: 'text', value: x }) + } else { + res[res.length - 1].value += x + } + } } } - return res.join('') + + return res } const tocRenderSwitch = proxy({ @@ -144,8 +149,17 @@ const GuidesTableOfContents = ({ + > + {formatTOCHeader(removeAnchor(item.text)).map((x, index) => ( + + {x.type === 'code' ? ( + {x.value} + ) : ( + x.value + )} + + ))} + ))}