mirror of
https://github.com/zhigang1992/react.git
synced 2026-04-28 20:25:29 +08:00
docs: anchor each doc title
This commit is contained in:
14
lib/components/anchor/anchor-icon.tsx
Normal file
14
lib/components/anchor/anchor-icon.tsx
Normal file
@@ -0,0 +1,14 @@
|
||||
import React from 'react'
|
||||
|
||||
const AnchorIcon = () => {
|
||||
return (
|
||||
<svg viewBox="0 0 24 24" width="100%" height="100%" stroke="currentColor" strokeWidth="1.5"
|
||||
strokeLinecap="round" strokeLinejoin="round" fill="none"
|
||||
shapeRendering="geometricPrecision" style={{ color: 'currentColor' }}>
|
||||
<path d="M10 13a5 5 0 007.54.54l3-3a5 5 0 00-7.07-7.07l-1.72 1.71" />
|
||||
<path d="M14 11a5 5 0 00-7.54-.54l-3 3a5 5 0 007.07 7.07l1.71-1.71" />
|
||||
</svg>
|
||||
)
|
||||
}
|
||||
|
||||
export default AnchorIcon
|
||||
77
lib/components/anchor/index.tsx
Normal file
77
lib/components/anchor/index.tsx
Normal file
@@ -0,0 +1,77 @@
|
||||
import React, { useEffect, useRef, useState } from 'react'
|
||||
import { Link, useTheme } from 'components'
|
||||
import AnchorIcon from './anchor-icon'
|
||||
|
||||
export interface Props {
|
||||
pure?: boolean
|
||||
}
|
||||
|
||||
export const virtualAnchorEncode = (text?: string) => {
|
||||
if (!text) return undefined
|
||||
return text.toLowerCase().replace(/ /g, '-')
|
||||
}
|
||||
|
||||
const VirtualAnchor: React.FC<React.PropsWithChildren<Props>> = ({
|
||||
children, pure,
|
||||
}) => {
|
||||
const theme = useTheme()
|
||||
const ref = useRef<HTMLAnchorElement>(null)
|
||||
const [id, setId] = useState<string | undefined>()
|
||||
|
||||
useEffect(() => {
|
||||
if (!ref.current) return
|
||||
setId(virtualAnchorEncode(ref.current.textContent || undefined))
|
||||
}, [ref.current])
|
||||
|
||||
return (
|
||||
<span className="parent" ref={ref}>
|
||||
<Link pure href={`#${id}`}>{children}</Link>
|
||||
<span className="virtual" id={id} />
|
||||
{!pure && <span className="icon"><AnchorIcon /></span>}
|
||||
<style jsx>{`
|
||||
.parent {
|
||||
position: relative;
|
||||
color: inherit;
|
||||
}
|
||||
|
||||
.parent :global(a) {
|
||||
color: inherit;
|
||||
}
|
||||
|
||||
.virtual {
|
||||
position: absolute;
|
||||
top: -30px;
|
||||
left: 0;
|
||||
opacity: 0;
|
||||
pointer-events: none;
|
||||
visibility: hidden;
|
||||
}
|
||||
|
||||
.icon {
|
||||
display: inline-flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
overflow: hidden;
|
||||
left: -1.5em;
|
||||
top: 50%;
|
||||
transform: translateY(-50%);
|
||||
position: absolute;
|
||||
opacity: 0;
|
||||
visibility: hidden;
|
||||
font-size: inherit;
|
||||
width: .8em;
|
||||
height: .8em;
|
||||
margin-top: 1px;
|
||||
color: ${theme.palette.accents_5};
|
||||
}
|
||||
|
||||
.parent:hover > .icon {
|
||||
opacity: 1;
|
||||
visibility: visible;
|
||||
}
|
||||
`}</style>
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
export default VirtualAnchor
|
||||
Reference in New Issue
Block a user