code.tsx 8.8 KB

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