File size: 5,294 Bytes
f6c1709
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
<template>
  <div ref="root" class="relative">
    <button
      ref="trigger"
      type="button"
      class="ui-input-sm flex w-full items-center justify-between gap-2 text-foreground hover:border-primary"
      @click="toggle"
    >
      <span class="truncate">{{ currentLabel }}</span>
      <svg aria-hidden="true" viewBox="0 0 20 20" class="h-4 w-4" fill="currentColor">
        <path d="M5 7l5 6 5-6H5z" />
      </svg>
    </button>
  </div>

  <Teleport to="body">
    <div
      v-if="open"
      ref="menu"
      class="ui-floating-panel fixed z-[1000] space-y-1"
      :style="menuStyle"
    >
      <button
        v-for="option in normalizedOptions"
        :key="option.value"
        type="button"
        class="ui-menu-item"
        :class="isSelected(option.value) ? 'bg-accent text-accent-foreground' : 'text-muted-foreground'"
        @click="select(option.value)"
      >
        <span>{{ option.label }}</span>
        <span v-if="isSelected(option.value)" class="text-xs">OK</span>
      </button>
    </div>
  </Teleport>
</template>

<script setup lang="ts">
import { computed, nextTick, onBeforeUnmount, onMounted, ref } from 'vue'

type Option = { label: string; value: string }

const props = defineProps<{
  modelValue: string | string[]
  options: Array<string | Option>
  multiple?: boolean
  placeholder?: string
  placement?: 'up' | 'down'
}>()

const emit = defineEmits<{
  (e: 'update:modelValue', value: string | string[]): void
}>()

const open = ref(false)
const root = ref<HTMLElement | null>(null)
const trigger = ref<HTMLButtonElement | null>(null)
const menu = ref<HTMLElement | null>(null)
const menuPosition = ref({ top: 0, left: 0, width: 0 })

const normalizedOptions = computed<Option[]>(() =>
  props.options.map((option) =>
    typeof option === 'string' ? { label: option, value: option } : option
  )
)

const defaultPlaceholder = '\u8bf7\u9009\u62e9'

const currentLabel = computed(() => {
  if (props.multiple) {
    const values = Array.isArray(props.modelValue) ? props.modelValue : []
    if (!values.length) return props.placeholder || defaultPlaceholder
    if (values.length === 1) {
      const match = normalizedOptions.value.find((option) => option.value === values[0])
      return match?.label || values[0]
    }
    return `\u5df2\u9009 ${values.length} \u9879`
  }

  const rawValue = props.modelValue == null ? '' : String(props.modelValue)
  const match = normalizedOptions.value.find((option) => String(option.value) === rawValue)
  if (match) return match.label
  if (!rawValue.trim()) return props.placeholder || defaultPlaceholder
  return rawValue
})

const menuStyle = computed(() => ({
  top: `${menuPosition.value.top}px`,
  left: `${menuPosition.value.left}px`,
  width: `${menuPosition.value.width}px`,
}))

const updateMenuPosition = () => {
  if (!trigger.value) return

  const rect = trigger.value.getBoundingClientRect()
  const width = rect.width
  const spacing = 8
  const padding = 8

  let left = rect.left
  let top = rect.bottom + spacing

  if (props.placement === 'up' && menu.value) {
    top = rect.top - menu.value.offsetHeight - spacing
  }

  const maxLeft = window.innerWidth - width - padding
  left = Math.min(Math.max(left, padding), Math.max(padding, maxLeft))

  if (menu.value) {
    const maxTop = window.innerHeight - menu.value.offsetHeight - padding
    top = Math.min(Math.max(top, padding), Math.max(padding, maxTop))
  } else {
    top = Math.max(top, padding)
  }

  menuPosition.value = { top, left, width }
}

const openMenu = async () => {
  open.value = true
  await nextTick()
  updateMenuPosition()
  requestAnimationFrame(updateMenuPosition)
}

const closeMenu = () => {
  open.value = false
}

const toggle = () => {
  if (open.value) {
    closeMenu()
    return
  }
  void openMenu()
}

const isSelected = (value: string) => {
  if (props.multiple) {
    return Array.isArray(props.modelValue) && props.modelValue.includes(value)
  }
  return props.modelValue === value
}

const select = (value: string) => {
  if (props.multiple) {
    const current = Array.isArray(props.modelValue) ? props.modelValue : []
    const exists = current.includes(value)
    const next = exists ? current.filter((item) => item !== value) : [...current, value]
    emit('update:modelValue', next)
    return
  }

  emit('update:modelValue', value)
  closeMenu()
}

const handleClickOutside = (event: MouseEvent) => {
  const target = event.target as Node
  if (root.value?.contains(target)) return
  if (menu.value?.contains(target)) return
  closeMenu()
}

const handleViewportChange = () => {
  if (!open.value) return
  updateMenuPosition()
}

const handleKeyDown = (event: KeyboardEvent) => {
  if (event.key === 'Escape') {
    closeMenu()
  }
}

onMounted(() => {
  document.addEventListener('click', handleClickOutside)
  document.addEventListener('keydown', handleKeyDown)
  window.addEventListener('resize', handleViewportChange)
  window.addEventListener('scroll', handleViewportChange, true)
})

onBeforeUnmount(() => {
  document.removeEventListener('click', handleClickOutside)
  document.removeEventListener('keydown', handleKeyDown)
  window.removeEventListener('resize', handleViewportChange)
  window.removeEventListener('scroll', handleViewportChange, true)
})
</script>