Raw
1 import React, { useMemo } from "react"
2 import { CodeBlockStyle, Highlight } from "../../CodeBlock"
3 import { RenderProps, Token } from "prism-react-renderer"
4 import clsx from "clsx"
5 import { Tooltip } from "@/components/Tooltip"
6 import dynamic from "next/dynamic"
7
8 const MarkdownContent = dynamic(
9 async () =>
10 import("@/components/MarkdownContent").then((mod) => mod.MarkdownContent),
11 {
12 ssr: false,
13 }
14 )
15
16 type HighlightedTokens = {
17 start: number
18 end: number
19 highlight: Highlight
20 }
21
22 type TokensWithHighlights = {
23 tokens: Token[]
24 type: "default" | "highlighted"
25 highlight?: Highlight
26 }
27
28 type CodeBlockLineProps = {
29 line: Token[]
30 highlights?: Highlight[]
31 lineNumber: number
32 showLineNumber: boolean
33 lineNumberColorClassName: string
34 lineNumberBgClassName: string
35 isTerminal: boolean
36 animateTokenHighlights?: boolean
37 codeBlockStyle: CodeBlockStyle
38 } & Pick<RenderProps, "getLineProps" | "getTokenProps">
39
40 export const CodeBlockLine = ({
41 line,
42 highlights = [],
43 lineNumber,
44 getLineProps,
45 getTokenProps,
46 showLineNumber,
47 lineNumberColorClassName,
48 lineNumberBgClassName,
49 isTerminal,
50 animateTokenHighlights = false,
51 codeBlockStyle,
52 }: CodeBlockLineProps) => {
53 const lineProps = getLineProps({ line, key: lineNumber })
54
55 // collect highlighted tokens, if there are any
56 const highlightedTokens: HighlightedTokens[] = useMemo(() => {
57 const highlightedTokensArr: HighlightedTokens[] = []
58 highlights.forEach((highlight) => {
59 if (!highlight.text) {
60 return
61 }
62 let startIndex: number | undefined = undefined
63 let currentPositionInHighlightedText = 0
64 let endIndex = 0
65 const found = line.some((token, tokenIndex) => {
66 if (token.empty || !token.content.length) {
67 startIndex = undefined
68 currentPositionInHighlightedText = 0
69 return false
70 }
71 const startNotSet = startIndex === undefined
72 // trim the start of the script if the start
73 // of the highlight hasn't been found yet
74 const tokenContent = startNotSet
75 ? token.content.trimStart()
76 : token.content
77 if (!tokenContent.length && startNotSet) {
78 return false
79 }
80 const comparisonLength = Math.min(
81 tokenContent.length,
82 highlight.text!.substring(currentPositionInHighlightedText).length
83 )
84 const nextPositionInHighlightedText =
85 currentPositionInHighlightedText + comparisonLength
86
87 const canHighlight =
88 !highlightedTokensArr.length ||
89 !highlightedTokensArr.some(
90 (token) => tokenIndex >= token.start && tokenIndex <= token.end
91 )
92
93 const isMatching =
94 tokenContent.substring(0, comparisonLength) ===
95 highlight.text?.substring(
96 currentPositionInHighlightedText,
97 nextPositionInHighlightedText
98 )
99
100 if (isMatching && canHighlight) {
101 if (startNotSet) {
102 startIndex = tokenIndex
103 }
104 currentPositionInHighlightedText = nextPositionInHighlightedText
105 }
106
107 if (currentPositionInHighlightedText === highlight.text!.length) {
108 // matching text was found, break loop
109 endIndex = tokenIndex
110 const trimmedContent = token.content.trimEnd()
111 const endingSpacesLength =
112 token.content.length - trimmedContent.length
113 if (endingSpacesLength) {
114 line.splice(tokenIndex + 1, 0, {
115 content: new Array(endingSpacesLength).fill(" ").join(""),
116 types: ["plain"],
117 })
118 token.content = trimmedContent
119 }
120 return true
121 }
122 })
123
124 if (found && startIndex !== undefined) {
125 highlightedTokensArr.push({
126 start: startIndex,
127 end: endIndex,
128 highlight,
129 })
130 }
131 })
132
133 // sort highlighted tokens by their start position
134 highlightedTokensArr.sort((tokensA, tokensB) => {
135 if (tokensA.start < tokensB.start) {
136 return -1
137 }
138
139 return tokensA.start > tokensB.start ? 1 : 0
140 })
141
142 return highlightedTokensArr
143 }, [highlights, line])
144
145 // if there are highlighted tokens, split tokens in the
146 // line by segments of not highlighted and highlighted token
147 // if there are no highlighted tokens, the line is used as-is.
148 const transformedLine: TokensWithHighlights[] = useMemo(() => {
149 if (!highlightedTokens.length) {
150 return [
151 {
152 tokens: line,
153 type: "default",
154 },
155 ]
156 }
157 const transformedLineArr: TokensWithHighlights[] = []
158
159 let lastIndex = 0
160 // go through highlighted tokens to add the segments before/after to the
161 // transformLineArr array
162 highlightedTokens.forEach((highlightedTokensItem, index) => {
163 if (lastIndex < highlightedTokensItem.start) {
164 transformedLineArr.push({
165 tokens: line.slice(lastIndex, highlightedTokensItem.start),
166 type: "default",
167 })
168 }
169 // check if the start text should be trimmed
170 const token = Object.assign({}, line[highlightedTokensItem.start])
171 if (
172 token.content.startsWith(" ") &&
173 !highlightedTokensItem.highlight.text?.startsWith(" ")
174 ) {
175 const originalLength = token.content.length
176 token.content = token.content.trimStart()
177 // push the spaces as a separate token
178 // so that they won't be highlighted.
179 transformedLineArr.push({
180 tokens: [
181 {
182 content: " ".repeat(originalLength - token.content.length),
183 types: ["plain"],
184 },
185 ],
186 type: "default",
187 })
188 }
189 transformedLineArr.push({
190 tokens: [
191 token,
192 ...line.slice(
193 highlightedTokensItem.start + 1,
194 highlightedTokensItem.end + 1
195 ),
196 ],
197 type: "highlighted",
198 highlight: highlightedTokensItem.highlight,
199 })
200 lastIndex = highlightedTokensItem.end + 1
201
202 // if this is the last item in `highlightedTokens` and
203 // its end index is less than the line's length, that means
204 // there are tokens at the end of the line that aren't highlighted
205 // and should be pushed as-is to the `transformLineArr` array.
206 if (
207 index === highlightedTokens.length - 1 &&
208 lastIndex < line.length - 1
209 ) {
210 transformedLineArr.push({
211 tokens: line.slice(lastIndex),
212 type: "default",
213 })
214 }
215 })
216
217 return transformedLineArr
218 }, [highlightedTokens])
219
220 const getTokensElm = ({
221 tokens,
222 isTokenHighlighted,
223 offset,
224 }: {
225 tokens: Token[]
226 isTokenHighlighted: boolean
227 offset: number
228 }) => (
229 <span
230 className={clsx(isTokenHighlighted && "relative group")}
231 data-testid="code-block-line-tokens"
232 >
233 {isTokenHighlighted && (
234 <span
235 className={clsx(
236 "absolute left-0 z-0",
237 codeBlockStyle === "loud" && [
238 "top-0 h-full",
239 "lg:bg-medusa-alpha-white-alpha-6 lg:border lg:border-medusa-alpha-white-alpha-12",
240 "lg:rounded-docs_xs scale-x-[1.05]",
241 animateTokenHighlights && [
242 "animate-fast animate-growWidth animation-fill-forwards",
243 ],
244 !animateTokenHighlights && "w-full",
245 ],
246 codeBlockStyle === "subtle" && [
247 "bottom-0 w-full h-full scale-y-[0.1] transition-transform origin-bottom",
248 "group-hover:scale-y-100 bg-medusa-fg-base",
249 ]
250 )}
251 data-testid="code-block-line-highlight"
252 />
253 )}
254 {tokens.map((token, key) => {
255 const tokenKey = offset + key
256 const { className: tokenClassName, ...rest } = getTokenProps({
257 token,
258 key: tokenKey,
259 })
260 return (
261 <span
262 key={tokenKey}
263 className={clsx(
264 tokenClassName,
265 isTokenHighlighted && [
266 "relative z-[1]",
267 codeBlockStyle === "subtle" &&
268 "group-hover:!text-medusa-fg-on-color group-hover:dark:!text-medusa-fg-on-inverted",
269 ]
270 )}
271 data-testid="code-block-line-token"
272 {...rest}
273 />
274 )
275 })}
276 </span>
277 )
278
279 const isHighlightedLine = useMemo(
280 () => highlights.length !== 0 && highlightedTokens.length === 0,
281 [highlights, highlightedTokens]
282 )
283
284 return (
285 <span
286 key={lineNumber}
287 {...lineProps}
288 className={clsx(
289 "table-row",
290 isHighlightedLine && "bg-medusa-alpha-white-alpha-6",
291 lineProps.className
292 )}
293 data-testid="code-block-line"
294 >
295 {(showLineNumber || isTerminal) && (
296 <span
297 className={clsx(
298 "mr-docs_1 table-cell select-none",
299 "sticky left-0 w-[1%] px-docs_1 text-right",
300 lineNumberColorClassName,
301 lineNumberBgClassName
302 )}
303 data-testid="line-number"
304 >
305 {isTerminal ? "❯" : showLineNumber ? lineNumber + 1 : ""}
306 </span>
307 )}
308 <span>
309 {transformedLine.map(({ tokens, type, highlight }, index) => {
310 const offset =
311 index === 0 ? 0 : transformedLine[index - 1].tokens.length
312 const tooltipText =
313 highlight?.tooltipText ||
314 (isHighlightedLine
315 ? highlights.find((h) => h.tooltipText !== undefined)?.tooltipText
316 : undefined)
317 const isHighlighted = type === "highlighted"
318 return (
319 <React.Fragment key={index}>
320 {tooltipText && (
321 <Tooltip
322 text={tooltipText}
323 tooltipClassName="font-base"
324 render={({ content }) => (
325 <MarkdownContent
326 allowedElements={["a", "strong", "code", "br"]}
327 unwrapDisallowed={true}
328 >
329 {content || ""}
330 </MarkdownContent>
331 )}
332 >
333 {getTokensElm({
334 tokens,
335 isTokenHighlighted: isHighlighted,
336 offset,
337 })}
338 </Tooltip>
339 )}
340 {!tooltipText &&
341 getTokensElm({
342 tokens,
343 isTokenHighlighted: isHighlighted,
344 offset,
345 })}
346 </React.Fragment>
347 )
348 })}
349 </span>
350 </span>
351 )
352 }