Skip to content

Commit

Permalink
feat: new copy code animate
Browse files Browse the repository at this point in the history
Signed-off-by: Innei <i@innei.in>
  • Loading branch information
Innei committed May 21, 2024
1 parent 54eaf32 commit 44033bf
Showing 1 changed file with 42 additions and 3 deletions.
45 changes: 42 additions & 3 deletions src/components/ui/code-highlighter/shiki/ShikiWrapper.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,12 @@ import {
useEffect,
useImperativeHandle,
useMemo,
useRef,
useState,
} from 'react'
import clsx from 'clsx'
import { AnimatePresence, m } from 'framer-motion'
import type { Variants } from 'framer-motion'
import type { PropsWithChildren } from 'react'

import { getViewport } from '~/atoms/hooks'
Expand All @@ -28,6 +31,20 @@ interface Props {
renderedHTML?: string
}

const copyIconVariants: Variants = {
initial: {
opacity: 1,
scale: 1,
},
animate: {
opacity: 1,
scale: 1,
},
exit: {
opacity: 0,
scale: 0,
},
}
export const ShikiHighLighterWrapper = forwardRef<
HTMLDivElement,
PropsWithChildren<
Expand All @@ -43,9 +60,16 @@ export const ShikiHighLighterWrapper = forwardRef<
attrs,
} = props

const [copied, setCopied] = useState(false)
const copiedTimerRef = useRef<any>()
const handleCopy = useCallback(() => {
navigator.clipboard.writeText(value)
toast.success('已复制到剪贴板')
setCopied(true)

clearTimeout(copiedTimerRef.current)
copiedTimerRef.current = setTimeout(() => {
setCopied(false)
}, 2000)
}, [value])

const [codeBlockRef, setCodeBlockRef] = useState<HTMLDivElement | null>(null)
Expand Down Expand Up @@ -122,16 +146,31 @@ export const ShikiHighLighterWrapper = forwardRef<
<MotionButtonBase
onClick={handleCopy}
className={clsx(
'center absolute right-2 top-2 z-[1] flex text-xs',
'absolute right-2 top-2 z-[1] flex text-xs center',
'rounded-md border border-accent/5 bg-accent/80 p-1.5 text-white backdrop-blur duration-200',
'opacity-0 group-hover:opacity-100',
filename && '!top-12',
)}
>
<i className="icon-[mingcute--copy-2-fill] size-4" />
<AnimatePresence mode="wait">
{copied ? (
<m.i
key={'copied'}
className="icon-[mingcute--check-line] size-4"
{...copyIconVariants}
/>
) : (
<m.i
key={'copy'}
className="icon-[mingcute--copy-2-fill] size-4"
{...copyIconVariants}
/>
)}
</AnimatePresence>
</MotionButtonBase>
<AutoResizeHeight spring className="relative">
<div
onCopy={stopPropagation}
ref={setCodeBlockRef}
className={clsxm(
'relative max-h-[50vh] w-full overflow-auto',
Expand Down

0 comments on commit 44033bf

Please sign in to comment.