UNPKG

@lobehub/ui

Version:

Lobe UI is an open-source UI component library for building AIGC web apps

1 lines 2.93 kB
{"version":3,"file":"useMarkdownContent.mjs","names":[],"sources":["../../../src/hooks/useMarkdown/useMarkdownContent.ts"],"sourcesContent":["'use client';\n\nimport { useMemo, useRef, useState } from 'react';\n\nimport { useMarkdownContext } from '@/Markdown/components/MarkdownProvider';\n\nimport { isLastFormulaRenderable } from './latex';\nimport { addToCache, contentCache, preprocessMarkdownContent } from './utils';\n\nexport const useMarkdownContent = (children: string): string | undefined => {\n const { animated, enableLatex = true, enableCustomFootnotes, citations } = useMarkdownContext();\n const [validContent, setValidContent] = useState<string>('');\n const prevProcessedContent = useRef<string>('');\n\n const citationsLength = citations?.length || 0;\n\n // Calculate cache key with fewer string concatenations and better performance\n const cacheKey = useMemo(\n () => `${children}|${enableLatex ? 1 : 0}|${enableCustomFootnotes ? 1 : 0}|${citationsLength}`,\n [children, enableLatex, enableCustomFootnotes, citationsLength],\n );\n\n // Process content and use cache to avoid repeated calculations\n return useMemo(() => {\n // Try to get from cache first for best performance\n if (contentCache.has(cacheKey)) {\n return contentCache.get(cacheKey);\n }\n\n // Process new content only if needed\n let processedContent = preprocessMarkdownContent(children, {\n citationsLength,\n enableCustomFootnotes,\n enableLatex,\n });\n\n // Special handling for LaTeX content when animated\n if (animated && enableLatex) {\n const isRenderable = isLastFormulaRenderable(processedContent);\n if (!isRenderable && validContent) {\n processedContent = validContent;\n }\n }\n\n // Only update state if content changed (prevents unnecessary re-renders)\n if (processedContent !== prevProcessedContent.current) {\n setValidContent(processedContent);\n prevProcessedContent.current = processedContent;\n }\n\n // Cache the processed result\n addToCache(cacheKey, processedContent);\n return processedContent;\n }, [\n cacheKey,\n children,\n enableLatex,\n enableCustomFootnotes,\n citationsLength,\n animated,\n validContent,\n ]);\n};\n"],"mappings":";;;;;;;;AASA,MAAa,sBAAsB,aAAyC;CAC1E,MAAM,EAAE,UAAU,cAAc,MAAM,uBAAuB,cAAc,oBAAoB;CAC/F,MAAM,CAAC,cAAc,mBAAmB,SAAiB,GAAG;CAC5D,MAAM,uBAAuB,OAAe,GAAG;CAE/C,MAAM,kBAAkB,WAAW,UAAU;CAG7C,MAAM,WAAW,cACT,GAAG,SAAS,GAAG,cAAc,IAAI,EAAE,GAAG,wBAAwB,IAAI,EAAE,GAAG,mBAC7E;EAAC;EAAU;EAAa;EAAuB;EAAgB,CAChE;AAGD,QAAO,cAAc;AAEnB,MAAI,aAAa,IAAI,SAAS,CAC5B,QAAO,aAAa,IAAI,SAAS;EAInC,IAAI,mBAAmB,0BAA0B,UAAU;GACzD;GACA;GACA;GACD,CAAC;AAGF,MAAI,YAAY,aAEd;OAAI,CADiB,wBAAwB,iBAAiB,IACzC,aACnB,oBAAmB;;AAKvB,MAAI,qBAAqB,qBAAqB,SAAS;AACrD,mBAAgB,iBAAiB;AACjC,wBAAqB,UAAU;;AAIjC,aAAW,UAAU,iBAAiB;AACtC,SAAO;IACN;EACD;EACA;EACA;EACA;EACA;EACA;EACA;EACD,CAAC"}