|
| 1 | +import type { PropType, Ref } from 'vue' |
| 2 | +import { defineComponent, h, toRefs, watch } from 'vue' |
| 3 | + |
| 4 | +import type { ElementType, MergeProps, PrimitiveProps } from '@oku-ui/primitive' |
| 5 | +import type { Measurable } from '@oku-ui/utils' |
| 6 | +import type { Scope } from '@oku-ui/provide' |
| 7 | +import { useRef } from '@oku-ui/use-composable' |
| 8 | +import { Primitive } from '@oku-ui/primitive' |
| 9 | +import { usePopperInject } from './popper' |
| 10 | + |
| 11 | +/* ------------------------------------------------------------------------------------------------- |
| 12 | + * PopperAnchor |
| 13 | + * ----------------------------------------------------------------------------------------------- */ |
| 14 | + |
| 15 | +const ANCHOR_NAME = 'PopperAnchor' |
| 16 | + |
| 17 | +type PopperAnchorElement = ElementType<'div'> |
| 18 | +interface PopperAnchorProps extends PrimitiveProps { |
| 19 | + virtualRef?: Ref<Measurable | null> |
| 20 | + scopeCheckbox?: Scope |
| 21 | +} |
| 22 | + |
| 23 | +const PopperAnchor = defineComponent({ |
| 24 | + name: ANCHOR_NAME, |
| 25 | + inheritAttrs: false, |
| 26 | + props: { |
| 27 | + virtualRef: { |
| 28 | + type: Object as unknown as PropType<Ref<Measurable | null>>, |
| 29 | + required: false, |
| 30 | + default: undefined, |
| 31 | + }, |
| 32 | + scopeCheckbox: { |
| 33 | + type: Object as unknown as PropType<Scope>, |
| 34 | + required: false, |
| 35 | + default: undefined, |
| 36 | + }, |
| 37 | + asChild: { |
| 38 | + type: Boolean, |
| 39 | + default: false, |
| 40 | + }, |
| 41 | + }, |
| 42 | + setup(props, { attrs, expose, slots }) { |
| 43 | + const { virtualRef, scopeCheckbox } = toRefs(props) |
| 44 | + const { ...attrsAnchor } = attrs as PopperAnchorElement |
| 45 | + const inject = usePopperInject(ANCHOR_NAME, scopeCheckbox.value) |
| 46 | + const { $el, newRef } = useRef<Measurable>() |
| 47 | + |
| 48 | + watch($el, () => { |
| 49 | + inject.value.anchor.value = virtualRef.value?.value || $el.value as Measurable |
| 50 | + }) |
| 51 | + |
| 52 | + const originalReturn = () => virtualRef.value |
| 53 | + ? null |
| 54 | + : h(Primitive.div, { |
| 55 | + ...attrsAnchor, |
| 56 | + asChild: props.asChild, |
| 57 | + ref: newRef, |
| 58 | + }, |
| 59 | + { |
| 60 | + default: () => slots.default && slots.default?.(), |
| 61 | + }, |
| 62 | + ) |
| 63 | + |
| 64 | + return originalReturn |
| 65 | + }, |
| 66 | +}) |
| 67 | + |
| 68 | +type _PopperAnchor = MergeProps<PopperAnchorProps, PopperAnchorElement> |
| 69 | + |
| 70 | +const OkuPopperAnchor = PopperAnchor as typeof PopperAnchor & (new () => { $props: _PopperAnchor }) |
| 71 | + |
| 72 | +export { |
| 73 | + OkuPopperAnchor, |
| 74 | +} |
| 75 | + |
| 76 | +export type { |
| 77 | + PopperAnchorProps, |
| 78 | + PopperAnchorElement, |
| 79 | +} |
0 commit comments