code.tsx 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  1. 'use client'
  2. import {
  3. Children,
  4. createContext,
  5. useContext,
  6. useEffect,
  7. useRef,
  8. useState,
  9. } from 'react'
  10. import { Tab } from '@headlessui/react'
  11. import { Tag } from './tag'
  12. import classNames from '@/utils/classnames'
  13. import { writeTextToClipboard } from '@/utils/clipboard'
  14. const languageNames = {
  15. js: 'JavaScript',
  16. ts: 'TypeScript',
  17. javascript: 'JavaScript',
  18. typescript: 'TypeScript',
  19. php: 'PHP',
  20. python: 'Python',
  21. ruby: 'Ruby',
  22. go: 'Go',
  23. } as { [key: string]: string }
  24. type IChildrenProps = {
  25. children: React.ReactElement
  26. [key: string]: any
  27. }
  28. function getPanelTitle({ className }: { className: string }) {
  29. const language = className.split('-')[1]
  30. return languageNames[language] ?? 'Code'
  31. }
  32. function ClipboardIcon(props: any) {
  33. return (
  34. <svg viewBox="0 0 20 20" aria-hidden="true" {...props}>
  35. <path
  36. strokeWidth="0"
  37. d="M5.5 13.5v-5a2 2 0 0 1 2-2l.447-.894A2 2 0 0 1 9.737 4.5h.527a2 2 0 0 1 1.789 1.106l.447.894a2 2 0 0 1 2 2v5a2 2 0 0 1-2 2h-5a2 2 0 0 1-2-2Z"
  38. />
  39. <path
  40. fill="none"
  41. strokeLinejoin="round"
  42. d="M12.5 6.5a2 2 0 0 1 2 2v5a2 2 0 0 1-2 2h-5a2 2 0 0 1-2-2v-5a2 2 0 0 1 2-2m5 0-.447-.894a2 2 0 0 0-1.79-1.106h-.527a2 2 0 0 0-1.789 1.106L7.5 6.5m5 0-1 1h-3l-1-1"
  43. />
  44. </svg>
  45. )
  46. }
  47. function CopyButton({ code }: { code: string }) {
  48. const [copyCount, setCopyCount] = useState(0)
  49. const copied = copyCount > 0
  50. useEffect(() => {
  51. if (copyCount > 0) {
  52. const timeout = setTimeout(() => setCopyCount(0), 1000)
  53. return () => {
  54. clearTimeout(timeout)
  55. }
  56. }
  57. }, [copyCount])
  58. return (
  59. <button
  60. type="button"
  61. className={classNames(
  62. 'group/button absolute top-3.5 right-4 overflow-hidden rounded-full py-1 pl-2 pr-3 text-2xs font-medium opacity-0 backdrop-blur transition focus:opacity-100 group-hover:opacity-100',
  63. copied
  64. ? 'bg-emerald-400/10 ring-1 ring-inset ring-emerald-400/20'
  65. : 'bg-white/5 hover:bg-white/7.5 dark:bg-white/2.5 dark:hover:bg-white/5',
  66. )}
  67. onClick={() => {
  68. writeTextToClipboard(code).then(() => {
  69. setCopyCount(count => count + 1)
  70. })
  71. }}
  72. >
  73. <span
  74. aria-hidden={copied}
  75. className={classNames(
  76. 'pointer-events-none flex items-center gap-0.5 text-zinc-400 transition duration-300',
  77. copied && '-translate-y-1.5 opacity-0',
  78. )}
  79. >
  80. <ClipboardIcon className="w-5 h-5 transition-colors fill-zinc-500/20 stroke-zinc-500 group-hover/button:stroke-zinc-400" />
  81. Copy
  82. </span>
  83. <span
  84. aria-hidden={!copied}
  85. className={classNames(
  86. 'pointer-events-none absolute inset-0 flex items-center justify-center text-emerald-400 transition duration-300',
  87. !copied && 'translate-y-1.5 opacity-0',
  88. )}
  89. >
  90. Copied!
  91. </span>
  92. </button>
  93. )
  94. }
  95. function CodePanelHeader({ tag, label }: { tag: string; label: string }) {
  96. if (!tag && !label)
  97. return null
  98. return (
  99. <div className="flex h-9 items-center gap-2 border-y border-t-transparent border-b-white/7.5 bg-zinc-900 bg-white/2.5 px-4 dark:border-b-white/5 dark:bg-white/1">
  100. {tag && (
  101. <div className="flex dark">
  102. <Tag variant="small">{tag}</Tag>
  103. </div>
  104. )}
  105. {tag && label && (
  106. <span className="h-0.5 w-0.5 rounded-full bg-zinc-500" />
  107. )}
  108. {label && (
  109. <span className="font-mono text-xs text-zinc-400">{label}</span>
  110. )}
  111. </div>
  112. )
  113. }
  114. type ICodePanelProps = {
  115. children: React.ReactElement
  116. tag?: string
  117. code?: string
  118. label?: string
  119. targetCode?: string
  120. }
  121. function CodePanel({ tag, label, code, children, targetCode }: ICodePanelProps) {
  122. const child = Children.only(children)
  123. return (
  124. <div className="group dark:bg-white/2.5">
  125. <CodePanelHeader
  126. tag={child.props.tag ?? tag}
  127. label={child.props.label ?? label}
  128. />
  129. <div className="relative">
  130. {/* <pre className="p-4 overflow-x-auto text-xs text-white">{children}</pre> */}
  131. {/* <CopyButton code={child.props.code ?? code} /> */}
  132. {/* <CopyButton code={child.props.children.props.children} /> */}
  133. <pre className="p-4 overflow-x-auto text-xs text-white">{targetCode || children}</pre>
  134. <CopyButton code={targetCode || child.props.children.props.children} />
  135. </div>
  136. </div>
  137. )
  138. }
  139. function CodeGroupHeader({ title, children, selectedIndex }: IChildrenProps) {
  140. const hasTabs = Children.count(children) > 1
  141. if (!title && !hasTabs)
  142. return null
  143. return (
  144. <div className="flex min-h-[calc(theme(spacing.12)+1px)] flex-wrap items-start gap-x-4 border-b border-zinc-700 bg-zinc-800 px-4 dark:border-zinc-800 dark:bg-transparent">
  145. {title && (
  146. <h3 className="pt-3 mr-auto text-xs font-semibold text-white">
  147. {title}
  148. </h3>
  149. )}
  150. {hasTabs && (
  151. <Tab.List className="flex gap-4 -mb-px text-xs font-medium">
  152. {Children.map(children, (child, childIndex) => (
  153. <Tab
  154. className={classNames(
  155. 'border-b py-3 transition focus:[&:not(:focus-visible)]:outline-none',
  156. childIndex === selectedIndex
  157. ? 'border-emerald-500 text-emerald-400'
  158. : 'border-transparent text-zinc-400 hover:text-zinc-300',
  159. )}
  160. >
  161. {getPanelTitle(child.props.children.props)}
  162. </Tab>
  163. ))}
  164. </Tab.List>
  165. )}
  166. </div>
  167. )
  168. }
  169. type ICodeGroupPanelsProps = {
  170. children: React.ReactElement
  171. [key: string]: any
  172. }
  173. function CodeGroupPanels({ children, targetCode, ...props }: ICodeGroupPanelsProps) {
  174. const hasTabs = Children.count(children) > 1
  175. if (hasTabs) {
  176. return (
  177. <Tab.Panels>
  178. {Children.map(children, child => (
  179. <Tab.Panel>
  180. <CodePanel {...props}>{child}</CodePanel>
  181. </Tab.Panel>
  182. ))}
  183. </Tab.Panels>
  184. )
  185. }
  186. return <CodePanel {...props} targetCode={targetCode}>{children}</CodePanel>
  187. }
  188. function usePreventLayoutShift() {
  189. const positionRef = useRef<any>()
  190. const rafRef = useRef<any>()
  191. useEffect(() => {
  192. return () => {
  193. window.cancelAnimationFrame(rafRef.current)
  194. }
  195. }, [])
  196. return {
  197. positionRef,
  198. preventLayoutShift(callback: () => {}) {
  199. const initialTop = positionRef.current.getBoundingClientRect().top
  200. callback()
  201. rafRef.current = window.requestAnimationFrame(() => {
  202. const newTop = positionRef.current.getBoundingClientRect().top
  203. window.scrollBy(0, newTop - initialTop)
  204. })
  205. },
  206. }
  207. }
  208. function useTabGroupProps(availableLanguages: string[]) {
  209. const [preferredLanguages, addPreferredLanguage] = useState<any>([])
  210. const [selectedIndex, setSelectedIndex] = useState(0)
  211. const activeLanguage = [...availableLanguages].sort(
  212. (a, z) => preferredLanguages.indexOf(z) - preferredLanguages.indexOf(a),
  213. )[0]
  214. const languageIndex = availableLanguages.indexOf(activeLanguage)
  215. const newSelectedIndex = languageIndex === -1 ? selectedIndex : languageIndex
  216. if (newSelectedIndex !== selectedIndex)
  217. setSelectedIndex(newSelectedIndex)
  218. const { positionRef, preventLayoutShift } = usePreventLayoutShift()
  219. return {
  220. as: 'div',
  221. ref: positionRef,
  222. selectedIndex,
  223. onChange: (newSelectedIndex: number) => {
  224. preventLayoutShift(() =>
  225. (addPreferredLanguage(availableLanguages[newSelectedIndex]) as any),
  226. )
  227. },
  228. }
  229. }
  230. const CodeGroupContext = createContext(false)
  231. export function CodeGroup({ children, title, inputs, targetCode, ...props }: IChildrenProps) {
  232. const languages = Children.map(children, child =>
  233. getPanelTitle(child.props.children.props),
  234. )
  235. const tabGroupProps = useTabGroupProps(languages)
  236. const hasTabs = Children.count(children) > 1
  237. const Container = hasTabs ? Tab.Group : 'div'
  238. const containerProps = hasTabs ? tabGroupProps : {}
  239. const headerProps = hasTabs
  240. ? { selectedIndex: tabGroupProps.selectedIndex }
  241. : {}
  242. return (
  243. <CodeGroupContext.Provider value={true}>
  244. <Container
  245. {...containerProps}
  246. className="my-6 overflow-hidden shadow-md not-prose rounded-2xl bg-zinc-900 dark:ring-1 dark:ring-white/10"
  247. >
  248. <CodeGroupHeader title={title} {...headerProps}>
  249. {children}
  250. </CodeGroupHeader>
  251. <CodeGroupPanels {...props} targetCode={targetCode}>{children}</CodeGroupPanels>
  252. </Container>
  253. </CodeGroupContext.Provider>
  254. )
  255. }
  256. type IChildProps = {
  257. children: string
  258. [key: string]: any
  259. }
  260. export function Code({ children, ...props }: IChildProps) {
  261. const isGrouped = useContext(CodeGroupContext)
  262. if (isGrouped)
  263. return <code {...props} dangerouslySetInnerHTML={{ __html: children }} />
  264. return <code {...props}>{children}</code>
  265. }
  266. export function Pre({ children, ...props }: IChildrenProps) {
  267. const isGrouped = useContext(CodeGroupContext)
  268. if (isGrouped)
  269. return children
  270. return <CodeGroup {...props}>{children}</CodeGroup>
  271. }