/**
 * 多行文本省略指令（悬浮显示完整内容)
 * @directive v-ellipsis
 * @param {number} [value=3] - 超过value行数时显示省略号,不传参数默认为3
 */

const applyStyles = (el, binding) => {
	const lines = typeof binding.value === 'number' && binding.value > 0 ? binding.value : 3

	el.style.display = '-webkit-box'
	el.style.webkitBoxOrient = 'vertical'
	el.style.overflow = 'hidden'
	el.style.webkitLineClamp = lines.toString()

	el.style.maxHeight = `${lines}lh`
}

const checkTruncated = (el) => {
	const isTruncated = el.scrollHeight > el.clientHeight + 1
	if (isTruncated) {
		el.title = el.textContent?.trim() || ''
	} else {
		el.removeAttribute('title')
	}
}

export default {
	name: 'ellipsis',
	mounted(el, binding) {
		applyStyles(el, binding)
		checkTruncated(el)

		const ro = new ResizeObserver(() => checkTruncated(el))
		ro.observe(el);
		el._ellipsisObserver = ro
	},

	updated(el, binding) {
		applyStyles(el, binding)
		checkTruncated(el)
	},

	unmounted(el) {
		const ro = el._ellipsisObserver
		if (ro) {
			ro.disconnect()
			delete el._ellipsisObserver
		}
	}
}
