You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
ant-design-vue/components/align/Align.vue

122 lines
2.9 KiB

7 years ago
<script>
import PropTypes from 'vue-types'
import align from 'dom-align'
7 years ago
import clonedeep from 'lodash.clonedeep'
7 years ago
import addEventListener from '../_util/Dom/addEventListener'
7 years ago
import { cloneElement } from '../_util/vnode.js'
7 years ago
import isWindow from './isWindow'
7 years ago
function noop () {
}
function buffer (fn, ms) {
let timer
function clear () {
if (timer) {
clearTimeout(timer)
timer = null
}
}
function bufferFn () {
clear()
timer = setTimeout(fn, ms)
}
bufferFn.clear = clear
return bufferFn
}
export default {
props: {
childrenProps: PropTypes.object,
align: PropTypes.object.isRequired,
target: PropTypes.func.def(noop),
monitorBufferTime: PropTypes.number.def(50),
monitorWindowResize: PropTypes.bool.def(false),
disabled: PropTypes.bool.def(false),
},
7 years ago
watch: {
'$props': {
7 years ago
handler: function (props) {
const prevProps = this.prevProps
7 years ago
this.$nextTick(() => {
let reAlign = false
if (!props.disabled) {
if (prevProps.disabled || prevProps.align !== props.align) {
reAlign = true
} else {
const lastTarget = prevProps.target()
const currentTarget = props.target()
if (isWindow(lastTarget) && isWindow(currentTarget)) {
reAlign = false
} else if (lastTarget !== currentTarget) {
reAlign = true
}
}
}
7 years ago
7 years ago
if (reAlign) {
this.forceAlign()
}
if (props.monitorWindowResize && !props.disabled) {
this.startMonitorWindowResize()
} else {
this.stopMonitorWindowResize()
}
})
},
deep: true,
},
},
7 years ago
mounted () {
const props = this.$props
// if parent ref not attached .... use document.getElementById
this.forceAlign()
if (!props.disabled && props.monitorWindowResize) {
this.startMonitorWindowResize()
}
},
7 years ago
beforeDestroy () {
7 years ago
this.stopMonitorWindowResize()
},
methods: {
startMonitorWindowResize () {
if (!this.resizeHandler) {
this.bufferMonitor = buffer(this.forceAlign, this.$props.monitorBufferTime)
this.resizeHandler = addEventListener(window, 'resize', this.bufferMonitor)
}
},
stopMonitorWindowResize () {
if (this.resizeHandler) {
this.bufferMonitor.clear()
this.resizeHandler.remove()
this.resizeHandler = null
}
},
forceAlign () {
const props = this.$props
if (!props.disabled) {
const source = this.$el
this.$emit('align', source, align(source, props.target(), props.align))
}
},
},
render () {
7 years ago
this.prevProps = clonedeep(this.$props)
7 years ago
const { childrenProps } = this.$props
const child = this.$slots.default[0]
if (childrenProps) {
7 years ago
return cloneElement(child, { props: childrenProps })
7 years ago
}
return child
},
}
</script>