Merge pull request #31 from vueComponent/feature-anchor

feat: add anchor component
pull/165/head
tangjinzhou 2018-06-04 17:46:53 +08:00 committed by GitHub
commit 4b8bdc85d2
18 changed files with 683 additions and 2 deletions

View File

@ -0,0 +1,251 @@
import PropTypes from '../_util/vue-types'
import classNames from 'classnames'
import addEventListener from '../_util/Dom/addEventListener'
import Affix from '../affix'
import getScroll from '../_util/getScroll'
import getRequestAnimationFrame from '../_util/getRequestAnimationFrame'
import { initDefaultProps, getClass, getStyle } from '../_util/props-util'
import BaseMixin from '../_util/BaseMixin'
function getDefaultContainer () {
return window
}
function getOffsetTop (element, container) {
if (!element) {
return 0
}
if (!element.getClientRects().length) {
return 0
}
const rect = element.getBoundingClientRect()
if (rect.width || rect.height) {
if (container === window) {
container = element.ownerDocument.documentElement
return rect.top - container.clientTop
}
return rect.top - container.getBoundingClientRect().top
}
return rect.top
}
function easeInOutCubic (t, b, c, d) {
const cc = c - b
t /= d / 2
if (t < 1) {
return cc / 2 * t * t * t + b
}
return cc / 2 * ((t -= 2) * t * t + 2) + b
}
const reqAnimFrame = getRequestAnimationFrame()
const sharpMatcherRegx = /#([^#]+)$/
function scrollTo (href, offsetTop = 0, getContainer, callback = () => { }) {
const container = getContainer()
const scrollTop = getScroll(container, true)
const sharpLinkMatch = sharpMatcherRegx.exec(href)
if (!sharpLinkMatch) { return }
const targetElement = document.getElementById(sharpLinkMatch[1])
if (!targetElement) {
return
}
const eleOffsetTop = getOffsetTop(targetElement, container)
const targetScrollTop = scrollTop + eleOffsetTop - offsetTop
const startTime = Date.now()
const frameFunc = () => {
const timestamp = Date.now()
const time = timestamp - startTime
const nextScrollTop = easeInOutCubic(time, scrollTop, targetScrollTop, 450)
if (container === window) {
window.scrollTo(window.pageXOffset, nextScrollTop)
} else {
container.scrollTop = nextScrollTop
}
if (time < 450) {
reqAnimFrame(frameFunc)
} else {
callback()
}
}
reqAnimFrame(frameFunc)
history.pushState(null, '', href)
}
export const AnchorProps = {
prefixCls: PropTypes.string,
offsetTop: PropTypes.number,
bounds: PropTypes.number,
affix: PropTypes.bool,
showInkInFixed: PropTypes.bool,
getContainer: PropTypes.func,
}
export default {
name: 'AAnchor',
mixins: [BaseMixin],
inheritAttrs: false,
props: initDefaultProps(AnchorProps, {
prefixCls: 'ant-anchor',
affix: true,
showInkInFixed: false,
getContainer: getDefaultContainer,
}),
data () {
this.links = []
return {
activeLink: null,
}
},
provide () {
return {
antAnchor: {
registerLink: (link) => {
if (!this.links.includes(link)) {
this.links.push(link)
}
},
unregisterLink: (link) => {
const index = this.links.indexOf(link)
if (index !== -1) {
this.links.splice(index, 1)
}
},
$data: this.$data,
scrollTo: this.handleScrollTo,
},
}
},
mount () {
this.$nextTick(() => {
const { getContainer } = this
this.scrollEvent = addEventListener(getContainer(), 'scroll', this.handleScroll)
this.handleScroll()
})
},
beforeDestroy () {
if (this.scrollEvent) {
this.scrollEvent.remove()
}
},
updated () {
this.$nextTick(() => {
this.updateInk()
})
},
methods: {
handleScroll () {
if (this.animating) {
return
}
const { offsetTop, bounds } = this
this.setState({
activeLink: this.getCurrentAnchor(offsetTop, bounds),
})
},
handleScrollTo (link) {
const { offsetTop, getContainer } = this
this.animating = true
this.setState({ activeLink: link })
scrollTo(link, offsetTop, getContainer, () => {
this.animating = false
})
},
getCurrentAnchor (offsetTop = 0, bounds = 5) {
const activeLink = ''
if (typeof document === 'undefined') {
return activeLink
}
const linkSections = []
const { getContainer } = this
const container = getContainer()
this.links.forEach(link => {
const sharpLinkMatch = sharpMatcherRegx.exec(link.toString())
if (!sharpLinkMatch) { return }
const target = document.getElementById(sharpLinkMatch[1])
if (target) {
const top = getOffsetTop(target, container)
if (top < offsetTop + bounds) {
linkSections.push({
link,
top,
})
}
}
})
if (linkSections.length) {
const maxSection = linkSections.reduce((prev, curr) => curr.top > prev.top ? curr : prev)
return maxSection.link
}
return ''
},
updateInk () {
if (typeof document === 'undefined') {
return
}
const { prefixCls } = this
const linkNode = this.$el.getElementsByClassName(`${prefixCls}-link-title-active`)[0]
if (linkNode) {
this.$refs.linkNode.style.top = `${(linkNode).offsetTop + linkNode.clientHeight / 2 - 4.5}px`
}
},
},
render () {
const {
prefixCls,
offsetTop,
affix,
showInkInFixed,
activeLink,
$slots,
} = this
const inkClass = classNames(`${prefixCls}-ink-ball`, {
visible: activeLink,
})
const wrapperClass = classNames(getClass(this), `${prefixCls}-wrapper`)
const anchorClass = classNames(prefixCls, {
'fixed': !affix && !showInkInFixed,
})
const wrapperStyle = {
maxHeight: offsetTop ? `calc(100vh - ${offsetTop}px)` : '100vh',
...getStyle(this, true),
}
const anchorContent = (
<div
class={wrapperClass}
style={wrapperStyle}
>
<div class={anchorClass}>
<div class={`${prefixCls}-ink`} >
<span class={inkClass} ref='linkNode' />
</div>
{$slots.default}
</div>
</div>
)
return !affix ? anchorContent : (
<Affix offsetTop={offsetTop}>
{anchorContent}
</Affix>
)
},
}

View File

@ -0,0 +1,61 @@
import PropTypes from '../_util/vue-types'
import { initDefaultProps, getComponentFromProp } from '../_util/props-util'
import classNames from 'classnames'
export const AnchorLinkProps = {
prefixCls: PropTypes.string,
href: PropTypes.string,
title: PropTypes.any,
}
export default {
name: 'AAnchorLink',
props: initDefaultProps(AnchorLinkProps, {
prefixCls: 'ant-anchor',
href: '#',
}),
inject: {
antAnchor: { default: {}},
},
mounted () {
this.antAnchor.registerLink(this.href)
},
beforeDestroy () {
this.antAnchor.unregisterLink(this.href)
},
methods: {
handleClick () {
this.antAnchor.scrollTo(this.href)
},
},
render () {
const {
prefixCls,
href,
$slots,
} = this
const title = getComponentFromProp(this, 'title')
const active = this.antAnchor.$data.activeLink === href
const wrapperClassName = classNames(`${prefixCls}-link`, {
[`${prefixCls}-link-active`]: active,
})
const titleClassName = classNames(`${prefixCls}-link-title`, {
[`${prefixCls}-link-title-active`]: active,
})
return (
<div class={wrapperClassName}>
<a
class={titleClassName}
href={href}
title={typeof title === 'string' ? title : ''}
onClick={this.handleClick}
>
{title}
</a>
{$slots.default}
</div>
)
},
}

View File

@ -0,0 +1,82 @@
import { mount } from '@vue/test-utils'
import Vue from 'vue'
import Anchor from '..'
const { Link } = Anchor
describe('Anchor Render', () => {
it('Anchor render perfectly', (done) => {
const wrapper = mount({
render () {
return (
<Anchor ref='anchor'>
<Link href='#API' title='API' />
</Anchor>
)
},
}, { sync: false })
Vue.nextTick(() => {
wrapper.find('a[href="#API"]').trigger('click')
wrapper.vm.$refs.anchor.handleScroll()
expect(wrapper.vm.$refs.anchor.$data.activeLink).not.toBe(null)
done()
})
})
it('Anchor render perfectly for complete href - click', (done) => {
const wrapper = mount({
render () {
return (
<Anchor ref='anchor'>
<Link href='http://www.example.com/#API' title='API' />
</Anchor>
)
},
}, { sync: false })
Vue.nextTick(() => {
wrapper.find('a[href="http://www.example.com/#API"]').trigger('click')
expect(wrapper.vm.$refs.anchor.$data.activeLink).toBe('http://www.example.com/#API')
done()
})
})
it('Anchor render perfectly for complete href - scoll', (done) => {
const wrapper = mount({
render () {
return (
<div>
<div id='API'>Hello</div>
<Anchor ref='anchor'>
<Link href='http://www.example.com/#API' title='API' />
</Anchor>
</div>
)
},
}, { sync: false, attachToDocument: true })
Vue.nextTick(() => {
wrapper.vm.$refs.anchor.handleScroll()
expect(wrapper.vm.$refs.anchor.$data.activeLink).toBe('http://www.example.com/#API')
done()
})
})
it('Anchor render perfectly for complete href - scollTo', (done) => {
const wrapper = mount({
render () {
return (
<div>
<div id='API'>Hello</div>
<Anchor ref='anchor'>
<Link href='##API' title='API' />
</Anchor>
</div>
)
},
}, { sync: false, attachToDocument: true })
Vue.nextTick(() => {
wrapper.vm.$refs.anchor.handleScrollTo('##API')
expect(wrapper.vm.$refs.anchor.$data.activeLink).toBe('##API')
done()
})
})
})

View File

@ -0,0 +1,51 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`renders ./components/anchor/demo/basic.md correctly 1`] = `
<div>
<div class="">
<div class="ant-anchor-wrapper" style="max-height: 100vh;">
<div class="ant-anchor">
<div class="ant-anchor-ink"><span class="ant-anchor-ink-ball"></span></div>
<div class="ant-anchor-link">
<a href="#components-anchor-demo-basic" title="Basic demo" class="ant-anchor-link-title">Basic demo</a>
</div>
<div class="ant-anchor-link">
<a href="#components-anchor-demo-static-anchor" title="Fixed demo" class="ant-anchor-link-title">Fixed demo</a>
</div>
<div class="ant-anchor-link">
<a href="#API" title="API" class="ant-anchor-link-title">API</a>
<div class="ant-anchor-link">
<a href="#Anchor-Props" title="Anchor Props" class="ant-anchor-link-title">Anchor Props</a>
</div>
<div class="ant-anchor-link">
<a href="#Link-Props" title="Link Props" class="ant-anchor-link-title">Link Props</a>
</div>
</div>
</div>
</div>
</div>
</div>
`;
exports[`renders ./components/anchor/demo/static.md correctly 1`] = `
<div class="ant-anchor-wrapper" style="max-height: 100vh;">
<div class="ant-anchor fixed">
<div class="ant-anchor-ink"><span class="ant-anchor-ink-ball"></span></div>
<div class="ant-anchor-link">
<a href="#components-anchor-demo-basic" title="Basic demo" class="ant-anchor-link-title">Basic demo</a>
</div>
<div class="ant-anchor-link">
<a href="#components-anchor-demo-static-anchor" title="Fixed demo" class="ant-anchor-link-title">Fixed demo</a>
</div>
<div class="ant-anchor-link">
<a href="#API" title="API" class="ant-anchor-link-title">API</a>
<div class="ant-anchor-link">
<a href="#Anchor-Props" title="Anchor Props" class="ant-anchor-link-title">Anchor Props</a>
</div>
<div class="ant-anchor-link">
<a href="#Link-Props" title="Link Props" class="ant-anchor-link-title">Link Props</a>
</div>
</div>
</div>
</div>
`;

View File

@ -0,0 +1,3 @@
import demoTest from '../../../tests/shared/demoTest'
demoTest('anchor')

View File

@ -0,0 +1,22 @@
<cn>
#### 基本
最简单的用法。
</cn>
<us>
#### basic
The simplest usage.
</us>
```html
<template>
<a-anchor>
<a-anchor-link href="#components-anchor-demo-basic" title="Basic demo" />
<a-anchor-link href="#components-anchor-demo-static-anchor" title="Fixed demo" />
<a-anchor-link href="#API" title="API">
<a-anchor-link href="#Anchor-Props" title="Anchor Props" />
<a-anchor-link href="#Link-Props" title="Link Props" />
</a-anchor-link>
</a-anchor>
</template>
```

View File

@ -0,0 +1,50 @@
<script>
import Basic from './basic'
import Static from './static'
import CN from '../index.zh-CN.md'
import US from '../index.en-US.md'
const md = {
cn: `# Anchor 锚点
用于跳转到页面指定位置
## 何时使用
需要展现当前页面上可供跳转的锚点链接以及快速在锚点之间跳转
## 代码演示`,
us: `# Anchor
Hyperlinks to scroll on one page.
## When To Use
For displaying anchor hyperlinks on page and jumping between them.
## Examples
`,
}
export default {
category: 'Components',
subtitle: '锚点',
cols: 2,
type: 'Other',
title: 'Anchor',
render () {
return (
<div id='components-anchor-demo'>
<md cn={md.cn} us={md.us}/>
<Basic/>
<Static/>
<api>
<CN slot='cn' />
<US/>
</api>
</div>
)
},
}
</script>
<style>
#components-anchor-demo .ant-affix {
z-index: 11;
}
</style>

View File

@ -0,0 +1,22 @@
<cn>
#### 静态位置
不浮动,状态不随页面滚动变化。
</cn>
<us>
#### Static Anchor
Do not change state when page is scrolling.
</us>
```html
<template>
<a-anchor :affix="false">
<a-anchor-link href="#components-anchor-demo-basic" title="Basic demo" />
<a-anchor-link href="#components-anchor-demo-static-anchor" title="Fixed demo" />
<a-anchor-link href="#API" title="API">
<a-anchor-link href="#Anchor-Props" title="Anchor Props" />
<a-anchor-link href="#Link-Props" title="Link Props" />
</a-anchor-link>
</a-anchor>
</template>
```

View File

@ -0,0 +1,20 @@
## API
### Anchor Props
| Property | Description | Type | Default |
| -------- | ----------- | ---- | ------- |
| affix | Fixed mode of Anchor | boolean | true |
| bounds | Bounding distance of anchor area | number | 5(px) |
| getContainer | Scrolling container | () => HTMLElement | () => window |
| offsetBottom | Pixels to offset from bottom when calculating position of scroll | number | - |
| offsetTop | Pixels to offset from top when calculating position of scroll | number | 0 |
| showInkInFixed | Whether show ink-balls in Fixed mode | boolean | false |
### Link Props
| Property | Description | Type | Default |
| -------- | ----------- | ---- | ------- |
| href | target of hyperlink | string | |
| title | content of hyperlink | string\|slot | |

View File

@ -0,0 +1,8 @@
import Anchor from './Anchor'
import AnchorLink from './AnchorLink'
export { AnchorProps } from './Anchor'
export { AnchorLinkProps } from './AnchorLink'
Anchor.Link = AnchorLink
export default Anchor

View File

@ -0,0 +1,20 @@
## API
### Anchor Props
| 成员 | 说明 | 类型 | 默认值 |
| --- | --- | --- | --- |
| affix | 固定模式 | boolean | true |
| bounds | 锚点区域边界 | number | 5(px) |
| getContainer | 指定滚动的容器 | () => HTMLElement | () => window |
| offsetBottom | 距离窗口底部达到指定偏移量后触发 | number | |
| offsetTop | 距离窗口顶部达到指定偏移量后触发 | number | |
| showInkInFixed | 固定模式是否显示小圆点 | boolean | false |
### Link Props
| 成员 | 说明 | 类型 | 默认值 |
| --- | --- | --- | --- |
| href | 锚点链接 | string | |
| title | 文字内容 | string\|slot | |

View File

@ -0,0 +1,2 @@
import '../../style/index.less'
import './index.less'

View File

@ -0,0 +1,81 @@
@import "../../style/themes/default";
@import "../../style/mixins/index";
@anchor-border-width: 2px;
.@{ant-prefix}-anchor {
.reset-component;
position: relative;
padding-left: @anchor-border-width;
&-wrapper {
background-color: @component-background;
overflow: auto;
padding-left: 4px;
margin-left: -4px;
}
&-ink {
position: absolute;
height: 100%;
left: 0;
top: 0;
&:before {
content: ' ';
position: relative;
width: @anchor-border-width;
height: 100%;
display: block;
background-color: @border-color-split;
margin: 0 auto;
}
&-ball {
display: none;
position: absolute;
width: 8px;
height: 8px;
border-radius: 8px;
border: 2px solid @primary-color;
background-color: @component-background;
left: 50%;
transition: top .3s ease-in-out;
transform: translateX(-50%);
&.visible {
display: inline-block;
}
}
}
&.fixed &-ink &-ink-ball {
display: none;
}
&-link {
padding: 8px 0 8px 16px;
line-height: 1;
&-title {
display: block;
position: relative;
transition: all .3s;
color: @text-color;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
margin-bottom: 8px;
&:only-child {
margin-bottom: 0;
}
}
&-active > &-title {
color: @primary-color;
}
}
&-link &-link {
padding-top: 6px;
padding-bottom: 6px;
}
}

View File

@ -14,7 +14,7 @@ if (ENV !== 'production' && ENV !== 'test' &&
import { default as Affix } from './affix'
// import { default as Anchor } from './anchor'
import { default as Anchor } from './anchor'
import { default as AutoComplete } from './auto-complete'
@ -122,6 +122,8 @@ import { default as version } from './version'
const components = [
Affix,
Anchor,
Anchor.Link,
AutoComplete,
Alert,
Avatar,
@ -223,6 +225,7 @@ export {
message,
notification,
Affix,
Anchor,
AutoComplete,
Alert,
Avatar,

View File

@ -44,3 +44,4 @@ import './tree/style'
import './upload/style'
import './layout/style'
import './form/style'
import './anchor/style'

View File

@ -1,7 +1,7 @@
import Vue from 'vue'
import {
Affix,
// Anchor,
Anchor,
AutoComplete,
Alert,
Avatar,
@ -57,6 +57,8 @@ import {
} from 'antd'
Vue.component(Affix.name, Affix) // a-affix
Vue.component(Anchor.name, Anchor)
Vue.component(Anchor.Link.name, Anchor.Link)
Vue.component(AutoComplete.name, AutoComplete)
Vue.component(Alert.name, Alert)
Vue.component(Avatar.name, Avatar)

View File

@ -45,3 +45,4 @@ export { default as upload } from 'antd/upload/demo/index.vue'
export { default as tree } from 'antd/tree/demo/index.vue'
export { default as layout } from 'antd/layout/demo/index.vue'
export { default as form } from 'antd/form/demo/index.vue'
export { default as anchor } from 'antd/anchor/demo/index.vue'

View File

@ -7,6 +7,7 @@ Array [
"message",
"notification",
"Affix",
"Anchor",
"AutoComplete",
"Alert",
"Avatar",