import { defineComponent, h, inject, ref, watch, onMounted, onUpdated, onBeforeUnmount, nextTick, Fragment, } from 'vue' import {FormItemKey, FormKey} from './agent' import {addResizeListener, delResizeListener, ResizableElement} from '@roui/utils/resize-event' export default defineComponent({ name: 'RoLabelWrap', props: { judgeAutoWidth: Boolean, updateAll: Boolean }, setup(props, {slots}) { const el = ref>(null) const Form = inject(FormKey) const FormItem = inject(FormItemKey) const computedWidth = ref(0) watch(computedWidth, (nv, ov) => { if (props.updateAll) { Form.registerLabelWidth(nv, ov) FormItem.updateLabelWidth(nv) } }) const getLabelWidth = () => { if (el.value?.firstElementChild) { const width = window.getComputedStyle(el.value.firstElementChild).width return Math.ceil(parseFloat(width)) } else { return 0 } } const updateLabelWidth = (action = 'update') => { nextTick(() => { if (slots.default && props.judgeAutoWidth) { if (action === 'update') { computedWidth.value = getLabelWidth() } else if (action === 'remove') { Form.deregisterLabelWidth(computedWidth.value) } } }) } const updateLabelWidthFnc = () => updateLabelWidth('update') onMounted(() => { addResizeListener(el.value.firstElementChild as ResizableElement, updateLabelWidthFnc) updateLabelWidthFnc() }) onUpdated(updateLabelWidthFnc) onBeforeUnmount(() => { updateLabelWidth('remove') delResizeListener(el.value.firstElementChild as ResizableElement, updateLabelWidthFnc) }) function render() { if (!slots) return null if (props.judgeAutoWidth) { const autoLabelWidth = Form.autoLabelWidth const style = {} as CSSStyleDeclaration if (autoLabelWidth && autoLabelWidth !== 'auto') { const marginLeft = parseInt(autoLabelWidth, 10) - computedWidth.value if (marginLeft) { style.marginLeft = marginLeft + 'px' } } return h( 'div', { ref: el, class: ['ro-form-item_label-warp'], style }, slots.default?.() ) } else { return h(Fragment, {ref: el}, slots.default?.()) } } return render } })