1 "use client"
2
3 import React, { useEffect, useMemo, useRef, useState } from "react"
4 import clsx from "clsx"
5 import { Highlight, HighlightProps, themes, Token } from "prism-react-renderer"
6 import { ApiRunner } from "@/components/ApiRunner"
7 import { useAnalytics } from "@/providers/Analytics"
8 import { useColorMode } from "@/providers/ColorMode"
9 import { CodeBlockHeader, CodeBlockHeaderMeta } from "./Header"
10 import { CodeBlockLine } from "./Line"
11 import { ApiAuthType, ApiDataOptions, ApiMethod } from "types"
12 // @ts-expect-error can't install the types package because it doesn't support React v19
13 import { CSSTransition } from "react-transition-group"
14 import { DocsTrackingEvents } from "@/constants"
15 import { useCollapsibleCodeLines } from "@/hooks/use-collapsible-code-lines"
16 import { HighlightProps as CollapsibleHighlightProps } from "@/hooks/use-collapsible-code-lines"
17 import { CodeBlockActions, CodeBlockActionsProps } from "./Actions"
18 import { CodeBlockCollapsibleButton } from "./Collapsible/Button"
19 import { CodeBlockCollapsibleFade } from "./Collapsible/Fade"
20 import { CodeBlockInline } from "./Inline"
21
22 export type Highlight = {
23 line: number
24 text?: string
25 tooltipText?: string
26 }
27
28 export type CodeBlockMetaFields = {
29 title?: string
30 hasTabs?: boolean
31 npm2yarn?: boolean
32 npx2yarn?: boolean
33 npx2yarnExec?: boolean
34 highlights?: string[][]
35 apiTesting?: boolean
36 testApiMethod?: ApiMethod
37 testApiUrl?: string
38 testAuthType?: ApiAuthType
39 testPathParams?: ApiDataOptions
40 testQueryParams?: ApiDataOptions
41 testBodyParams?: ApiDataOptions
42 noCopy?: boolean
43 noReport?: boolean
44 noLineNumbers?: boolean
45 noAskAi?: boolean
46 collapsibleLines?: string
47 expandButtonLabel?: string
48 isTerminal?: boolean
49 forceNoTitle?: boolean
50 collapsed?: boolean
51 wrapperClassName?: string
52 } & CodeBlockHeaderMeta
53
54 export type CodeBlockStyle = "loud" | "subtle" | "inline"
55
56 export type CodeBlockProps = {
57 source: string
58 lang?: string
59 innerClassName?: string
60 className?: string
61 blockStyle?: CodeBlockStyle
62 children?: React.ReactNode
63 style?: React.HTMLAttributes<HTMLDivElement>["style"]
64 animateTokenHighlights?: boolean
65 overrideColors?: {
66 bg?: string
67 innerBg?: string
68 lineNumbersBg?: string
69 border?: string
70 innerBorder?: string
71 boxShadow?: string
72 }
73 } & CodeBlockMetaFields &
74 Omit<HighlightProps, "code" | "language" | "children">
75
76 export const CodeBlock = ({
77 source,
78 hasTabs = false,
79 lang = "",
80 wrapperClassName,
81 innerClassName,
82 className,
83 overrideColors = {},
84 collapsed = false,
85 title = "",
86 highlights = [],
87 apiTesting = false,
88 blockStyle = "loud",
89 noCopy = false,
90 noReport = false,
91 noLineNumbers = false,
92 children,
93 collapsibleLines,
94 expandButtonLabel,
95 isTerminal,
96 style,
97 forceNoTitle = false,
98 animateTokenHighlights,
99 noAskAi = false,
100 ...rest
101 }: CodeBlockProps) => {
102 if (!source && typeof children === "string") {
103 source = children
104 }
105 if (blockStyle === "inline") {
106 return <CodeBlockInline source={source} />
107 }
108
109 const { colorMode } = useColorMode()
110 const { track } = useAnalytics()
111 const [showTesting, setShowTesting] = useState(false)
112 const codeContainerRef = useRef<HTMLDivElement>(null)
113 const codeRef = useRef<HTMLElement>(null)
114 const apiRunnerRef = useRef<HTMLDivElement>(null)
115 const [scrollable, setScrollable] = useState(false)
116 const isTerminalCode = useMemo(() => {
117 return isTerminal === undefined
118 ? lang === "bash" && !source.startsWith("curl")
119 : isTerminal
120 }, [isTerminal, lang])
121 const codeTitle = useMemo(() => {
122 if (forceNoTitle) {
123 return ""
124 }
125
126 if (title) {
127 return title
128 }
129
130 if (hasTabs) {
131 return ""
132 }
133
134 if (isTerminalCode) {
135 return "Terminal"
136 }
137
138 return "Code"
139 }, [title, isTerminalCode, hasTabs, forceNoTitle])
140 const hasInnerCodeBlock = useMemo(
141 () => hasTabs || codeTitle.length > 0,
142 [hasTabs, codeTitle]
143 )
144 const canShowApiTesting = useMemo(
145 () =>
146 apiTesting !== undefined &&
147 rest.testApiMethod !== undefined &&
148 rest.testApiUrl !== undefined,
149 [apiTesting, rest]
150 )
151
152 const bgColor = useMemo(
153 () =>
154 clsx(
155 overrideColors.bg,
156 !overrideColors.bg && [
157 blockStyle === "loud" && "bg-medusa-contrast-bg-base",
158 blockStyle === "subtle" && "bg-medusa-bg-component",
159 ]
160 ),
161 [blockStyle, colorMode, overrideColors]
162 )
163
164 const lineNumbersColor = useMemo(
165 () =>
166 clsx(
167 overrideColors.lineNumbersBg,
168 !overrideColors.lineNumbersBg && [
169 blockStyle === "loud" && "text-medusa-contrast-fg-secondary",
170 blockStyle === "subtle" && "text-medusa-fg-muted",
171 ]
172 ),
173 [blockStyle, colorMode, overrideColors]
174 )
175
176 const borderColor = useMemo(
177 () => clsx(overrideColors.border, !overrideColors.border && "border-0"),
178 [blockStyle, colorMode, overrideColors]
179 )
180
181 const boxShadow = useMemo(
182 () =>
183 clsx(
184 overrideColors.boxShadow,
185 !overrideColors.boxShadow && [
186 blockStyle === "loud" &&
187 "shadow-elevation-code-block dark:shadow-elevation-code-block-dark",
188 blockStyle === "subtle" && "shadow-none",
189 ]
190 ),
191 [blockStyle, overrideColors]
192 )
193
194 const innerBgColor = useMemo(
195 () =>
196 clsx(
197 overrideColors.innerBg,
198 !overrideColors.innerBg && [
199 blockStyle === "loud" && [
200 hasInnerCodeBlock && "bg-medusa-contrast-bg-subtle",
201 !hasInnerCodeBlock && "bg-medusa-contrast-bg-base",
202 ],
203 blockStyle === "subtle" && bgColor,
204 ]
205 ),
206 [blockStyle, bgColor, hasInnerCodeBlock, overrideColors]
207 )
208
209 const innerBorderClasses = useMemo(
210 () =>
211 clsx(
212 overrideColors.innerBorder,
213 !overrideColors.innerBorder && [
214 blockStyle === "loud" && [
215 hasInnerCodeBlock &&
216 "border border-solid border-medusa-contrast-border-bot rounded-docs_DEFAULT",
217 !hasInnerCodeBlock && "border-transparent rounded-docs_DEFAULT",
218 ],
219 blockStyle === "subtle" && "border-transparent rounded-docs_DEFAULT",
220 ]
221 ),
222 [blockStyle, hasInnerCodeBlock, overrideColors]
223 )
224
225 const language = useMemo(() => {
226 const lowerLang = lang.toLowerCase()
227
228 // due to a hydration error in json, for now we just assign it to plain
229 return lowerLang === "json" ? "plain" : lowerLang
230 }, [lang])
231
232 const transformedHighlights: Highlight[] = highlights
233 .filter((highlight) => highlight.length !== 0)
234 .map((highlight) => ({
235 line: parseInt(highlight[0]),
236 text: highlight.length >= 2 ? highlight[1] : undefined,
237 tooltipText: highlight.length >= 3 ? highlight[2] : undefined,
238 }))
239
240 const getLines = (
241 tokens: Token[][],
242 highlightProps: CollapsibleHighlightProps,
243 lineNumberOffset = 0
244 ) =>
245 tokens.map((line, i) => {
246 const offsettedLineNumber = i + lineNumberOffset
247 const highlightedLines = transformedHighlights.filter(
248 (highlight) => highlight.line - 1 === offsettedLineNumber
249 )
250
251 return (
252 <CodeBlockLine
253 line={line}
254 lineNumber={offsettedLineNumber}
255 highlights={highlightedLines}
256 showLineNumber={!noLineNumbers && tokens.length > 1}
257 key={offsettedLineNumber}
258 lineNumberColorClassName={lineNumbersColor}
259 lineNumberBgClassName={innerBgColor}
260 isTerminal={isTerminalCode}
261 animateTokenHighlights={animateTokenHighlights}
262 codeBlockStyle={blockStyle}
263 {...highlightProps}
264 />
265 )
266 })
267
268 const {
269 getCollapsedLinesElm,
270 getNonCollapsedLinesElm,
271 type: collapsibleType,
272 isCollapsible,
273 ...collapsibleResult
274 } = useCollapsibleCodeLines({
275 collapsibleLinesStr: collapsibleLines,
276 getLines,
277 })
278
279 useEffect(() => {
280 if (!codeContainerRef.current || !codeRef.current) {
281 return
282 }
283
284 setScrollable(
285 codeContainerRef.current.scrollWidth < codeRef.current.clientWidth
286 )
287 }, [codeContainerRef.current, codeRef.current])
288
289 const trackCopy = () => {
290 track({
291 event: {
292 event: DocsTrackingEvents.CODE_BLOCK_COPY,
293 options: {
294 text: source.substring(0, 150),
295 },
296 },
297 })
298 }
299
300 const actionsProps: Omit<CodeBlockActionsProps, "inHeader"> = useMemo(
301 () => ({
302 source,
303 canShowApiTesting,
304 onApiTesting: setShowTesting,
305 blockStyle,
306 noReport,
307 noCopy,
308 isCollapsed: collapsibleType !== undefined && collapsibleResult.collapsed,
309 inInnerCode: hasInnerCodeBlock,
310 showGradientBg: scrollable,
311 noAskAi,
312 }),
313 [
314 source,
315 canShowApiTesting,
316 setShowTesting,
317 noReport,
318 noCopy,
319 collapsibleType,
320 collapsibleResult,
321 hasInnerCodeBlock,
322 scrollable,
323 noAskAi,
324 ]
325 )
326
327 const codeTheme = useMemo(() => {
328 const prismTheme =
329 blockStyle === "loud" || colorMode === "dark"
330 ? themes.vsDark
331 : themes.vsLight
332
333 if (blockStyle === "subtle") {
334 return prismTheme
335 }
336
337 return {
338 ...prismTheme,
339 plain: {
340 ...prismTheme,
341 color:
342 colorMode === "light"
343 ? "rgba(255, 255, 255, 0.88)"
344 : "rgba(250, 250, 250, 1)",
345 },
346 }
347 }, [blockStyle, colorMode])
348
349 if (!source.length) {
350 return <></>
351 }
352
353 return (
354 <>
355 <div
356 className={clsx(
357 hasInnerCodeBlock && "rounded-docs_lg",
358 !hasInnerCodeBlock && "rounded-docs_DEFAULT",
359 !hasTabs && boxShadow,
360 blockStyle === "loud" && "code-block-highlight",
361 blockStyle === "subtle" && "code-block-highlight-light",
362 wrapperClassName
363 )}
364 data-testid="code-block"
365 >
366 {codeTitle && (
367 <CodeBlockHeader
368 title={codeTitle}
369 blockStyle={blockStyle}
370 badgeLabel={rest.badgeLabel}
371 badgeColor={rest.badgeColor}
372 actionsProps={{
373 ...actionsProps,
374 inHeader: true,
375 }}
376 hideActions={hasTabs}
377 />
378 )}
379 <div
380 className={clsx(
381 "relative mb-docs_1",
382 "w-full max-w-full border code-block-elm",
383 bgColor,
384 borderColor,
385 collapsed && "max-h-[400px] overflow-auto",
386 hasInnerCodeBlock && "p-[5px] !pt-0 rounded-b-docs_lg",
387 !hasInnerCodeBlock && "rounded-docs_DEFAULT",
388 className
389 )}
390 style={style}
391 data-testid="code-block-inner"
392 >
393 <Highlight
394 theme={codeTheme}
395 code={source.trim()}
396 language={language}
397 {...rest}
398 >
399 {({
400 className: preClassName,
401 style: { backgroundColor: _, ...style },
402 tokens,
403 ...rest
404 }) => (
405 <div
406 className={clsx(
407 innerBorderClasses,
408 innerBgColor,
409 "relative",
410 innerClassName
411 )}
412 ref={codeContainerRef}
413 >
414 {collapsibleType === "start" && (
415 <>
416 <CodeBlockCollapsibleButton
417 type={collapsibleType}
418 expandButtonLabel={expandButtonLabel}
419 className={innerBorderClasses}
420 {...collapsibleResult}
421 />
422 <CodeBlockCollapsibleFade
423 type={collapsibleType}
424 collapsed={collapsibleResult.collapsed}
425 hasHeader={hasInnerCodeBlock}
426 />
427 </>
428 )}
429 <pre
430 style={{ ...style, fontStretch: "100%" }}
431 className={clsx(
432 "relative !my-0 break-words bg-transparent !outline-none",
433 "overflow-auto break-words p-0 pr-docs_0.25",
434 "rounded-docs_DEFAULT",
435 !hasInnerCodeBlock &&
436 tokens.length <= 1 &&
437 "px-docs_1 py-[6px]",
438 (noLineNumbers ||
439 (tokens.length <= 1 && !isTerminalCode)) &&
440 "pl-docs_1",
441 preClassName
442 )}
443 onCopy={trackCopy}
444 >
445 <code
446 className={clsx(
447 "text-code-body font-monospace table min-w-full print:whitespace-pre-wrap",
448 "py-docs_0.75"
449 )}
450 ref={codeRef}
451 >
452 {collapsibleType === "start" &&
453 getCollapsedLinesElm({
454 tokens,
455 highlightProps: rest,
456 })}
457 {getNonCollapsedLinesElm({
458 tokens,
459 highlightProps: rest,
460 })}
461 {collapsibleType === "end" &&
462 getCollapsedLinesElm({
463 tokens,
464 highlightProps: rest,
465 })}
466 </code>
467 </pre>
468 {!hasInnerCodeBlock &&
469 (!noCopy || !noReport || canShowApiTesting || !noAskAi) && (
470 <CodeBlockActions
471 {...actionsProps}
472 inHeader={false}
473 isSingleLine={tokens.length <= 1}
474 />
475 )}
476 {collapsibleType === "end" && isCollapsible(tokens) && (
477 <>
478 <CodeBlockCollapsibleFade
479 type={collapsibleType}
480 collapsed={collapsibleResult.collapsed}
481 hasHeader={hasInnerCodeBlock}
482 />
483 <CodeBlockCollapsibleButton
484 type={collapsibleType}
485 expandButtonLabel={expandButtonLabel}
486 className={innerBorderClasses}
487 {...collapsibleResult}
488 />
489 </>
490 )}
491 </div>
492 )}
493 </Highlight>
494 </div>
495 </div>
496 {canShowApiTesting && (
497 <CSSTransition
498 unmountOnExit
499 in={showTesting}
500 timeout={150}
501 classNames={{
502 enter: "animate-fadeIn animate-fastest",
503 exit: "animate-fadeOut animate-fastest",
504 }}
505 nodeRef={apiRunnerRef}
506 >
507 <ApiRunner
508 apiMethod={rest.testApiMethod!}
509 apiUrl={rest.testApiUrl!}
510 pathData={rest.testPathParams}
511 bodyData={rest.testBodyParams}
512 queryData={rest.testQueryParams}
513 ref={apiRunnerRef}
514 />
515 </CSSTransition>
516 )}
517 </>
518 )
519 }