Skip to content

Commit 4b8bdc8

Browse files
authored
Merge pull request #31 from vueComponent/feature-anchor
feat: add anchor component
2 parents c111330 + 4e21633 commit 4b8bdc8

File tree

18 files changed

+683
-2
lines changed

18 files changed

+683
-2
lines changed

components/anchor/Anchor.jsx

Lines changed: 251 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,251 @@
1+
import PropTypes from '../_util/vue-types'
2+
import classNames from 'classnames'
3+
import addEventListener from '../_util/Dom/addEventListener'
4+
import Affix from '../affix'
5+
import getScroll from '../_util/getScroll'
6+
import getRequestAnimationFrame from '../_util/getRequestAnimationFrame'
7+
import { initDefaultProps, getClass, getStyle } from '../_util/props-util'
8+
import BaseMixin from '../_util/BaseMixin'
9+
10+
function getDefaultContainer () {
11+
return window
12+
}
13+
14+
function getOffsetTop (element, container) {
15+
if (!element) {
16+
return 0
17+
}
18+
19+
if (!element.getClientRects().length) {
20+
return 0
21+
}
22+
23+
const rect = element.getBoundingClientRect()
24+
25+
if (rect.width || rect.height) {
26+
if (container === window) {
27+
container = element.ownerDocument.documentElement
28+
return rect.top - container.clientTop
29+
}
30+
return rect.top - container.getBoundingClientRect().top
31+
}
32+
33+
return rect.top
34+
}
35+
36+
function easeInOutCubic (t, b, c, d) {
37+
const cc = c - b
38+
t /= d / 2
39+
if (t < 1) {
40+
return cc / 2 * t * t * t + b
41+
}
42+
return cc / 2 * ((t -= 2) * t * t + 2) + b
43+
}
44+
45+
const reqAnimFrame = getRequestAnimationFrame()
46+
const sharpMatcherRegx = /#([^#]+)$/
47+
function scrollTo (href, offsetTop = 0, getContainer, callback = () => { }) {
48+
const container = getContainer()
49+
const scrollTop = getScroll(container, true)
50+
const sharpLinkMatch = sharpMatcherRegx.exec(href)
51+
if (!sharpLinkMatch) { return }
52+
const targetElement = document.getElementById(sharpLinkMatch[1])
53+
if (!targetElement) {
54+
return
55+
}
56+
const eleOffsetTop = getOffsetTop(targetElement, container)
57+
const targetScrollTop = scrollTop + eleOffsetTop - offsetTop
58+
const startTime = Date.now()
59+
const frameFunc = () => {
60+
const timestamp = Date.now()
61+
const time = timestamp - startTime
62+
const nextScrollTop = easeInOutCubic(time, scrollTop, targetScrollTop, 450)
63+
if (container === window) {
64+
window.scrollTo(window.pageXOffset, nextScrollTop)
65+
} else {
66+
container.scrollTop = nextScrollTop
67+
}
68+
if (time < 450) {
69+
reqAnimFrame(frameFunc)
70+
} else {
71+
callback()
72+
}
73+
}
74+
reqAnimFrame(frameFunc)
75+
history.pushState(null, '', href)
76+
}
77+
78+
export const AnchorProps = {
79+
prefixCls: PropTypes.string,
80+
offsetTop: PropTypes.number,
81+
bounds: PropTypes.number,
82+
affix: PropTypes.bool,
83+
showInkInFixed: PropTypes.bool,
84+
getContainer: PropTypes.func,
85+
}
86+
87+
export default {
88+
name: 'AAnchor',
89+
mixins: [BaseMixin],
90+
inheritAttrs: false,
91+
props: initDefaultProps(AnchorProps, {
92+
prefixCls: 'ant-anchor',
93+
affix: true,
94+
showInkInFixed: false,
95+
getContainer: getDefaultContainer,
96+
}),
97+
98+
data () {
99+
this.links = []
100+
return {
101+
activeLink: null,
102+
}
103+
},
104+
provide () {
105+
return {
106+
antAnchor: {
107+
registerLink: (link) => {
108+
if (!this.links.includes(link)) {
109+
this.links.push(link)
110+
}
111+
},
112+
unregisterLink: (link) => {
113+
const index = this.links.indexOf(link)
114+
if (index !== -1) {
115+
this.links.splice(index, 1)
116+
}
117+
},
118+
$data: this.$data,
119+
scrollTo: this.handleScrollTo,
120+
},
121+
}
122+
},
123+
124+
mount () {
125+
this.$nextTick(() => {
126+
const { getContainer } = this
127+
this.scrollEvent = addEventListener(getContainer(), 'scroll', this.handleScroll)
128+
this.handleScroll()
129+
})
130+
},
131+
132+
beforeDestroy () {
133+
if (this.scrollEvent) {
134+
this.scrollEvent.remove()
135+
}
136+
},
137+
138+
updated () {
139+
this.$nextTick(() => {
140+
this.updateInk()
141+
})
142+
},
143+
methods: {
144+
handleScroll () {
145+
if (this.animating) {
146+
return
147+
}
148+
const { offsetTop, bounds } = this
149+
this.setState({
150+
activeLink: this.getCurrentAnchor(offsetTop, bounds),
151+
})
152+
},
153+
154+
handleScrollTo (link) {
155+
const { offsetTop, getContainer } = this
156+
this.animating = true
157+
this.setState({ activeLink: link })
158+
scrollTo(link, offsetTop, getContainer, () => {
159+
this.animating = false
160+
})
161+
},
162+
163+
getCurrentAnchor (offsetTop = 0, bounds = 5) {
164+
const activeLink = ''
165+
if (typeof document === 'undefined') {
166+
return activeLink
167+
}
168+
169+
const linkSections = []
170+
const { getContainer } = this
171+
const container = getContainer()
172+
this.links.forEach(link => {
173+
const sharpLinkMatch = sharpMatcherRegx.exec(link.toString())
174+
if (!sharpLinkMatch) { return }
175+
const target = document.getElementById(sharpLinkMatch[1])
176+
if (target) {
177+
const top = getOffsetTop(target, container)
178+
if (top < offsetTop + bounds) {
179+
linkSections.push({
180+
link,
181+
top,
182+
})
183+
}
184+
}
185+
})
186+
187+
if (linkSections.length) {
188+
const maxSection = linkSections.reduce((prev, curr) => curr.top > prev.top ? curr : prev)
189+
return maxSection.link
190+
}
191+
return ''
192+
},
193+
194+
updateInk () {
195+
if (typeof document === 'undefined') {
196+
return
197+
}
198+
const { prefixCls } = this
199+
const linkNode = this.$el.getElementsByClassName(`${prefixCls}-link-title-active`)[0]
200+
if (linkNode) {
201+
this.$refs.linkNode.style.top = `${(linkNode).offsetTop + linkNode.clientHeight / 2 - 4.5}px`
202+
}
203+
},
204+
},
205+
206+
render () {
207+
const {
208+
prefixCls,
209+
offsetTop,
210+
affix,
211+
showInkInFixed,
212+
activeLink,
213+
$slots,
214+
} = this
215+
216+
const inkClass = classNames(`${prefixCls}-ink-ball`, {
217+
visible: activeLink,
218+
})
219+
220+
const wrapperClass = classNames(getClass(this), `${prefixCls}-wrapper`)
221+
222+
const anchorClass = classNames(prefixCls, {
223+
'fixed': !affix && !showInkInFixed,
224+
})
225+
226+
const wrapperStyle = {
227+
maxHeight: offsetTop ? `calc(100vh - ${offsetTop}px)` : '100vh',
228+
...getStyle(this, true),
229+
}
230+
231+
const anchorContent = (
232+
<div
233+
class={wrapperClass}
234+
style={wrapperStyle}
235+
>
236+
<div class={anchorClass}>
237+
<div class={`${prefixCls}-ink`} >
238+
<span class={inkClass} ref='linkNode' />
239+
</div>
240+
{$slots.default}
241+
</div>
242+
</div>
243+
)
244+
245+
return !affix ? anchorContent : (
246+
<Affix offsetTop={offsetTop}>
247+
{anchorContent}
248+
</Affix>
249+
)
250+
},
251+
}

components/anchor/AnchorLink.jsx

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
import PropTypes from '../_util/vue-types'
2+
import { initDefaultProps, getComponentFromProp } from '../_util/props-util'
3+
import classNames from 'classnames'
4+
5+
export const AnchorLinkProps = {
6+
prefixCls: PropTypes.string,
7+
href: PropTypes.string,
8+
title: PropTypes.any,
9+
}
10+
11+
export default {
12+
name: 'AAnchorLink',
13+
props: initDefaultProps(AnchorLinkProps, {
14+
prefixCls: 'ant-anchor',
15+
href: '#',
16+
}),
17+
inject: {
18+
antAnchor: { default: {}},
19+
},
20+
21+
mounted () {
22+
this.antAnchor.registerLink(this.href)
23+
},
24+
25+
beforeDestroy () {
26+
this.antAnchor.unregisterLink(this.href)
27+
},
28+
methods: {
29+
handleClick () {
30+
this.antAnchor.scrollTo(this.href)
31+
},
32+
},
33+
render () {
34+
const {
35+
prefixCls,
36+
href,
37+
$slots,
38+
} = this
39+
const title = getComponentFromProp(this, 'title')
40+
const active = this.antAnchor.$data.activeLink === href
41+
const wrapperClassName = classNames(`${prefixCls}-link`, {
42+
[`${prefixCls}-link-active`]: active,
43+
})
44+
const titleClassName = classNames(`${prefixCls}-link-title`, {
45+
[`${prefixCls}-link-title-active`]: active,
46+
})
47+
return (
48+
<div class={wrapperClassName}>
49+
<a
50+
class={titleClassName}
51+
href={href}
52+
title={typeof title === 'string' ? title : ''}
53+
onClick={this.handleClick}
54+
>
55+
{title}
56+
</a>
57+
{$slots.default}
58+
</div>
59+
)
60+
},
61+
}
Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
import { mount } from '@vue/test-utils'
2+
import Vue from 'vue'
3+
import Anchor from '..'
4+
5+
const { Link } = Anchor
6+
7+
describe('Anchor Render', () => {
8+
it('Anchor render perfectly', (done) => {
9+
const wrapper = mount({
10+
render () {
11+
return (
12+
<Anchor ref='anchor'>
13+
<Link href='#API' title='API' />
14+
</Anchor>
15+
)
16+
},
17+
}, { sync: false })
18+
Vue.nextTick(() => {
19+
wrapper.find('a[href="#API"]').trigger('click')
20+
wrapper.vm.$refs.anchor.handleScroll()
21+
expect(wrapper.vm.$refs.anchor.$data.activeLink).not.toBe(null)
22+
done()
23+
})
24+
})
25+
26+
it('Anchor render perfectly for complete href - click', (done) => {
27+
const wrapper = mount({
28+
render () {
29+
return (
30+
<Anchor ref='anchor'>
31+
<Link href='http://www.example.com/#API' title='API' />
32+
</Anchor>
33+
)
34+
},
35+
}, { sync: false })
36+
Vue.nextTick(() => {
37+
wrapper.find('a[href="http://www.example.com/#API"]').trigger('click')
38+
expect(wrapper.vm.$refs.anchor.$data.activeLink).toBe('http://www.example.com/#API')
39+
done()
40+
})
41+
})
42+
43+
it('Anchor render perfectly for complete href - scoll', (done) => {
44+
const wrapper = mount({
45+
render () {
46+
return (
47+
<div>
48+
<div id='API'>Hello</div>
49+
<Anchor ref='anchor'>
50+
<Link href='http://www.example.com/#API' title='API' />
51+
</Anchor>
52+
</div>
53+
)
54+
},
55+
}, { sync: false, attachToDocument: true })
56+
Vue.nextTick(() => {
57+
wrapper.vm.$refs.anchor.handleScroll()
58+
expect(wrapper.vm.$refs.anchor.$data.activeLink).toBe('http://www.example.com/#API')
59+
done()
60+
})
61+
})
62+
63+
it('Anchor render perfectly for complete href - scollTo', (done) => {
64+
const wrapper = mount({
65+
render () {
66+
return (
67+
<div>
68+
<div id='API'>Hello</div>
69+
<Anchor ref='anchor'>
70+
<Link href='##API' title='API' />
71+
</Anchor>
72+
</div>
73+
)
74+
},
75+
}, { sync: false, attachToDocument: true })
76+
Vue.nextTick(() => {
77+
wrapper.vm.$refs.anchor.handleScrollTo('##API')
78+
expect(wrapper.vm.$refs.anchor.$data.activeLink).toBe('##API')
79+
done()
80+
})
81+
})
82+
})

0 commit comments

Comments
 (0)