@studio-west/component-sw 0.12.24 → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/README.md +143 -30
  2. package/dist/{SwAlert-CU7nEnO-.js → SwAlert-CKJhS25j.js} +2 -2
  3. package/dist/SwButton-B-Z8Fhdv.js +61 -0
  4. package/dist/{SwDropdownItem-CKOTwhTf.js → SwDropdownItem-9Bq9fExK.js} +1 -1
  5. package/dist/SwFile-CfoiKvHJ.js +497 -0
  6. package/dist/{SwGide-Ie6XCPUn.js → SwGide-C62de-t6.js} +2 -2
  7. package/dist/{SwIcon-D6FCTrgR.js → SwIcon-CyVWEZkk.js} +1 -1
  8. package/dist/{SwInput-u7kS3lQn.js → SwInput-BED_o0wD.js} +1 -1
  9. package/dist/{SwMessage-DRjFGSK3.js → SwMessage-CA8jo3G7.js} +2 -2
  10. package/dist/{SwSkeleton-Byvq4bjt.js → SwSkeleton-BIj8PPM_.js} +1 -1
  11. package/dist/component-sw.css +1 -1
  12. package/dist/index.cjs +6 -6
  13. package/dist/index.js +21 -20
  14. package/package.json +2 -5
  15. package/types/components.d.ts +3 -0
  16. package/types/index.d.ts +19 -0
  17. package/dist/SwButton-Bvn3JLcT.js +0 -61
  18. package/src/Alert.ts +0 -70
  19. package/src/components/SwAlert.vue +0 -70
  20. package/src/components/SwButton.vue +0 -57
  21. package/src/components/SwButtonGroup.vue +0 -68
  22. package/src/components/SwCollapse.vue +0 -13
  23. package/src/components/SwDatePicker.vue +0 -375
  24. package/src/components/SwDropdown.vue +0 -195
  25. package/src/components/SwDropdownItem.vue +0 -26
  26. package/src/components/SwDropdownNew.vue +0 -175
  27. package/src/components/SwFormItem.vue +0 -21
  28. package/src/components/SwGide.vue +0 -128
  29. package/src/components/SwIcon.vue +0 -36
  30. package/src/components/SwInput.vue +0 -106
  31. package/src/components/SwMenu.vue +0 -217
  32. package/src/components/SwMessage.vue +0 -53
  33. package/src/components/SwSection.vue +0 -17
  34. package/src/components/SwSelect.vue +0 -153
  35. package/src/components/SwSkeleton.vue +0 -13
  36. package/src/components/SwSkeletonItem.vue +0 -27
  37. package/src/components/SwSlider.vue +0 -281
  38. package/src/components/SwSwitch.vue +0 -53
  39. package/src/components/SwTable.vue +0 -481
  40. package/src/components/SwTableColumn.vue +0 -88
  41. package/src/components/SwTabs.vue +0 -42
  42. package/src/components/SwTabsPane.vue +0 -44
  43. package/src/index.ts +0 -38
  44. package/src/utils/index.ts +0 -149
  45. /package/dist/{SwFormItem-DQJohClb.js → SwFormItem-rn5iuIUv.js} +0 -0
  46. /package/dist/{SwMenu-eQSh_MlP.js → SwMenu-Bh4BtVif.js} +0 -0
  47. /package/dist/{SwSection-BN1U3KaZ.js → SwSection-Bl3H3D2G.js} +0 -0
  48. /package/dist/{SwSelect-CMDZWWEI.js → SwSelect-DyArzImF.js} +0 -0
  49. /package/dist/{SwSkeletonItem-BnXZXE54.js → SwSkeletonItem-BKeBIWXT.js} +0 -0
  50. /package/dist/{SwSlider-DrIc0Xna.js → SwSlider-4S5KNn6o.js} +0 -0
  51. /package/dist/{SwSwitch-BVbje0T9.js → SwSwitch-BqAIQmG3.js} +0 -0
  52. /package/dist/{SwTable-4kHapbYy.js → SwTable-BjYEVovB.js} +0 -0
  53. /package/dist/{SwTableColumn-DCxVGb9d.js → SwTableColumn-CpNTUOVF.js} +0 -0
  54. /package/dist/{SwTabs-x2bXZwz1.js → SwTabs-jUzYPw9X.js} +0 -0
  55. /package/dist/{SwTabsPane-DpkTKQH8.js → SwTabsPane-Bhi49paR.js} +0 -0
@@ -1,175 +0,0 @@
1
- <template>
2
- <div
3
- :class="style"
4
- @click="toggleClick()"
5
- @mouseover.stop="toggleHover()"
6
- @mouseleave.stop="toggleHover()"
7
- @contextmenu.stop="toggleContext()"
8
- ref="dropdownRef"
9
- >
10
- <slot></slot>
11
- <Teleport to="body">
12
- <ul
13
- popover
14
- ref="popupRef"
15
- :id ="id"
16
- class="sw-dropdown-popup"
17
- :class="props.class"
18
- v-if="manual || false"
19
- :style="popupStyle"
20
- tabindex="-1"
21
- >
22
- <slot name="dropdown"></slot>
23
- </ul>
24
- </Teleport>
25
- </div>
26
- </template>
27
-
28
- <script setup>
29
- import { computed, ref, onMounted, onUnmounted, watchEffect } from "vue"
30
-
31
- const props = defineProps({
32
- class: {type: String, default: ''},
33
- type: {type: String, default: ''},
34
- trigger: {type: String, default: "click"},
35
- placement: {type: String, default: 'bottom-left'},
36
- maxWidth: {type: Number, default: 0}
37
- })
38
- const manual = defineModel()
39
-
40
- const dropdownRef = ref(null)
41
- const popupRef = ref(null)
42
- const popupStyle = ref({})
43
- const id = Math.ceil(Math.random() * 1000)
44
- const repositionTrigger = ref(0)
45
- const style = computed(() =>{
46
- let s = ['sw-dropdown']
47
- if(props.type.length > 0) s.push('sw-' + props.type)
48
- return s
49
- }
50
- )
51
- const resizeObserver = new ResizeObserver(() => {
52
- if (manual.value) repositionTrigger.value++
53
- if(repositionTrigger.value > 99 ) repositionTrigger.value = 1
54
- })
55
-
56
- watchEffect( () => {
57
- // console.log('watchEffect', repositionTrigger.value)
58
- // Если popup не активен — ничего не делаем
59
- if (!manual.value || !popupRef.value || !dropdownRef.value) {
60
- return
61
- }
62
- if(repositionTrigger.value < 2) resizeObserver.observe(popupRef.value)
63
- let scrollTop = window.pageYOffset || document.documentElement.scrollTop
64
- let scrollLeft = window.pageXOffset || document.documentElement.scrollLeft
65
- document.body.style.position = 'fixed'
66
- document.body.style.top = `-${scrollTop}px`
67
- document.body.style.left = `-${scrollLeft}px`
68
- document.body.style.position = ''
69
- document.body.style.top = ''
70
- document.body.style.left = ''
71
- document.documentElement.scrollTop = scrollTop
72
- document.documentElement.scrollLeft = scrollLeft
73
- const buttonRect = dropdownRef.value.getBoundingClientRect()
74
- let viewportWidth = window.innerWidth
75
- let viewportHeight = window.innerHeight
76
- // Получаем высоту и ширину popup
77
- let popupHeight = popupRef.value.offsetHeight;
78
- let popupWidth = popupRef.value.offsetWidth;
79
- // Расчет позиции popup (например, снизу кнопки)
80
- // Центр по горизонтали
81
- let left = buttonRect.left + (buttonRect.width / 2) + scrollLeft
82
- // Центр по вертикали
83
- let top = buttonRect.top + (buttonRect.height / 2) + scrollTop
84
- let deltaTop = (buttonRect.height / 2) + 8
85
- const [mainPlacement, subPlacement] = props.placement.split('-', 2)
86
-
87
- // Основное позиционирование
88
- switch (mainPlacement) {
89
- case "bottom":
90
- top = (scrollTop + viewportHeight - popupHeight - deltaTop - 8 < top)? top - deltaTop - popupHeight : top + deltaTop
91
- if(subPlacement === undefined ) left -= popupWidth / 2
92
- break
93
- case "top":
94
- top = (scrollTop + popupHeight + deltaTop + 8 > top)? top + deltaTop : top - deltaTop - popupHeight
95
- if(subPlacement === undefined ) left -= popupWidth / 2
96
- break
97
- case "left":
98
- if(left - popupWidth - (buttonRect.width / 2) - 8 < 0) {
99
- if(left + (buttonRect.width / 2) + 8 + popupWidth < viewportWidth) { // справа
100
- left = left + (buttonRect.width / 2) + 8
101
- top = top - (popupHeight / 2)
102
- } else {
103
- top = (scrollTop + popupHeight + deltaTop + 8 > top)? top + deltaTop : top - deltaTop - popupHeight
104
- left = (left + (buttonRect.width / 2) < viewportWidth )? left + (buttonRect.width / 2) - popupWidth: left - (popupWidth / 2)
105
- }
106
- } else { // слева
107
- left = left - popupWidth - (buttonRect.width / 2) - 8
108
- top = top - (popupHeight / 2)
109
- }
110
- break
111
- case "right":
112
- if(left + (buttonRect.width / 2) + 8 + popupWidth > viewportWidth ) {
113
- if(left - popupWidth - (buttonRect.width / 2) - 8 > 0){
114
- left = left - popupWidth - (buttonRect.width / 2) - 8 // слева
115
- top = top - (popupHeight / 2)
116
- } else {
117
- top = (scrollTop + popupHeight + deltaTop + 8 > top)? top + deltaTop : top - deltaTop - popupHeight
118
- left = left - (buttonRect.width / 2) // влево
119
- }
120
- } else { // справа
121
- left = left + (buttonRect.width / 2) + 8
122
- top = top - (popupHeight / 2)
123
- }
124
- break
125
- }
126
- switch (subPlacement) {
127
- case 'left':
128
- left = (scrollLeft + viewportWidth - 8 > left - (buttonRect.width / 2) + popupWidth) ? left - (buttonRect.width / 2) : left - popupWidth + (buttonRect.width / 2)
129
- break
130
- case 'right':
131
- left = (8< left + (buttonRect.width / 2) - popupWidth) ? left - popupWidth + (buttonRect.width / 2) : left - (buttonRect.width / 2)
132
- break
133
- }
134
- // Убедимся, что попап не выходит за экран
135
- if (left < 0) left = 0
136
- if (top < 0) top = 0
137
-
138
- popupStyle.value = {
139
- position: 'absolute',
140
- top: `${top}px`,
141
- left: `${left}px`,
142
- maxWidth: props.maxWidth > 0 ? `${props.maxWidth}px` : ''
143
- }
144
- }, {flush: 'post'}
145
- )
146
-
147
- const toggleClick = () => {
148
- if(props.trigger === 'click') manual.value = !manual.value
149
- }
150
- const toggleHover = () => {
151
- if(props.trigger === 'hover') manual.value = !manual.value
152
- }
153
- const toggleContext = () => {
154
- if (props.trigger === 'context') manual.value = !manual.value
155
- }
156
- const handleResize = () => {
157
- if (manual.value) repositionTrigger.value++
158
- if(repositionTrigger.value > 99 ) repositionTrigger.value = 1
159
- }
160
- defineExpose({ handleResize })
161
-
162
- onMounted(() => {
163
- window.addEventListener("resize", handleResize)
164
- if (window.onscrollend !== undefined) window.addEventListener("scrollend", handleResize)
165
- else window.addEventListener("scroll", handleResize)
166
- })
167
-
168
- onUnmounted(() => {
169
- resizeObserver.disconnect()
170
- window.removeEventListener("resize", handleResize)
171
- if (window.onscrollend !== undefined) window.removeEventListener("scrollend", handleResize)
172
- else window.removeEventListener("scroll", handleResize)
173
- })
174
-
175
- </script>
@@ -1,21 +0,0 @@
1
- <template>
2
- <div :class="style">
3
- <slot></slot>
4
- </div>
5
- </template>
6
-
7
- <script setup>
8
- import {computed} from "vue"
9
-
10
- const props = defineProps({
11
- class: {type:String, default: ''},
12
- type: {type:String, default: ''},
13
- })
14
- const style = computed(() =>{
15
- let s = ['sw-form-item']
16
- if(props.type.length > 0) s.push('sw-' + props.type)
17
- if(props.class.length > 0) s.push(props.class)
18
- return s
19
- }
20
- )
21
- </script>
@@ -1,128 +0,0 @@
1
- <template>
2
- <div class="sw-gide" ref="swGide">
3
- <div class="overlay0"/>
4
- <div class="overlay1"/>
5
- <sw-dropdown
6
- class="gide"
7
- trigger="none"
8
- :placement="props.steps[step].placement"
9
- v-model="visual"
10
- :maxWidth='props.maxWidth'
11
- >
12
- <div class="hole"/>
13
- <template #dropdown>
14
- <header><slot name="header">{{ props.steps[step].header }} <sw-button type="primary" link @click="exitModule"><sw-icon :icon-class="props.iconClose" /></sw-button></slot></header>
15
- <slot>
16
- <div>{{ props.steps[step].text }}</div>
17
- <img :class="(/left/.test(props.steps[step]?.placement))? 'reflect': null" :src="props.steps[step].img" />
18
- </slot>
19
- <footer>
20
- <slot name="footer">
21
- <sw-button :type="(step === 0)? 'info': 'warning'" text link @click="walk(-1)"><slot name="arrow">‹</slot></sw-button>
22
- <sw-button type="success" @click="walk(1)" text link class="sw-revers"><slot name="arrow">‹</slot></sw-button>
23
- </slot>
24
- </footer>
25
- </template>
26
- </sw-dropdown>
27
- <div class="overlay2"/>
28
- <div class="overlay3"/>
29
- </div>
30
- </template>
31
-
32
- <script setup>
33
- import SwDropdown from "./SwDropdown.vue"
34
- import SwButton from "./SwButton.vue"
35
- import {watchEffect, ref, onMounted} from "vue"
36
- import SwIcon from "./SwIcon.vue"
37
- const swGide = ref(null)
38
- const visual = ref(true)
39
- const block = ref(null)
40
- const step = defineModel({ type: Number, default: 0 })
41
- const emit = defineEmits(['close'])
42
- const props = defineProps({
43
- steps: { type: Array, default: () => [] },
44
- iconClose: { type: String, default: '' },
45
- maxWidth: { type: Number, default: 250 }
46
- })
47
-
48
- const exitModule = () => emit('close')
49
-
50
- const walk = (e) => {
51
- const nextStep = step.value + e
52
- if (nextStep < 0) step.value = 0
53
- else if (nextStep >= props.steps.length) exitModule()
54
- else step.value = nextStep
55
- }
56
-
57
- // Флаг: игнорировать следующее событие скролла (после автопрокрутки)
58
- let ignoreNextScroll = false
59
-
60
- // Функция прокрутки к элементу
61
- const scrollToElement = (el) => {
62
- const rect = el.getBoundingClientRect()
63
- const viewportHeight = window.innerHeight
64
-
65
- if (rect.top < 5) {
66
- ignoreNextScroll = true
67
- document.documentElement.scrollTop += rect.top - 5
68
- } else if (rect.bottom > viewportHeight - 5) {
69
- ignoreNextScroll = true
70
- document.documentElement.scrollTop += rect.bottom - viewportHeight + 5
71
- }
72
- }
73
-
74
- // Обновление позиции оверлея (без прокрутки!)
75
- const update = () => {
76
- if (!block.value || !swGide.value) return
77
- const r = block.value.getBoundingClientRect()
78
- const sT = window.pageYOffset || document.documentElement.scrollTop
79
- const sL = window.pageXOffset || document.documentElement.scrollLeft
80
-
81
- swGide.value.style.gridTemplateRows = `${r.top + sT - 5}px ${r.height + 10}px 1fr`
82
- swGide.value.style.gridTemplateColumns = `${r.left + sL - 5}px ${r.width + 10}px 1fr`
83
- swGide.value.style.height = document.documentElement.scrollHeight + 'px'
84
- }
85
- watchEffect((onInvalidate) => {
86
- if (!swGide.value) return
87
- const selector = props.steps[step.value]?.tag
88
- if (!selector || !selector.trim()) {
89
- // Сброс стилей, если нет селектора
90
- swGide.value.style.gridTemplateRows = `40% 0 1fr`
91
- swGide.value.style.gridTemplateColumns = `1fr 0 1fr`
92
- swGide.value.style.height = document.documentElement.scrollHeight + 'px'
93
- return
94
- }
95
- block.value = document.querySelector(selector)
96
- if (!block.value) {
97
- console.warn(`[SwGuide] Элемент не найден: ${selector}`)
98
- return
99
- }
100
- // === Автопрокрутка при смене шага ===
101
- // Выполняем один раз после установки нового блока
102
- scrollToElement(block.value)
103
- // === Обновление оверлея при ресайзе/скролле ===
104
- const onResizeOrScroll = () => {
105
- if (ignoreNextScroll) {
106
- ignoreNextScroll = false // сброс флага
107
- return // игнорируем "нашу" прокрутку
108
- }
109
- update()
110
- }
111
- // Инициализация
112
- update()
113
- // Наблюдатели
114
- const observer = new ResizeObserver(update)
115
- observer.observe(block.value)
116
-
117
- window.addEventListener('resize', onResizeOrScroll)
118
- window.addEventListener('scroll', onResizeOrScroll, { passive: true })
119
-
120
- // Очистка
121
- onInvalidate(() => {
122
- observer.disconnect()
123
- window.removeEventListener('resize', onResizeOrScroll)
124
- window.removeEventListener('scroll', onResizeOrScroll)
125
- })
126
- })
127
- onMounted(()=> window.onload = () => block.value = document.querySelector(props.steps[step.value]?.tag))
128
- </script>
@@ -1,36 +0,0 @@
1
- <template>
2
- <div
3
- v-if="isExt"
4
- class="sw-external-icon svg-icon"
5
- :style="maskStyle"
6
- v-bind="$attrs"
7
- />
8
- <svg v-else :class="'sw-icon icon-' + (props.className || props.iconClass)" aria-hidden="true" v-bind="$attrs">
9
- <use :href="'#' + props.prefix +'-' + props.iconClass" />
10
- </svg>
11
- </template>
12
- <script setup>
13
- defineOptions({ inheritAttrs: false })
14
- import { computed } from 'vue'
15
- import { isExternal } from '../utils/index.ts'
16
-
17
- const props = defineProps({
18
- prefix: {type: String, default: 'icon'},
19
- iconClass: {type: String, required: true},
20
- className: {type: String, default: ''}
21
- })
22
- const isExt = isExternal(props.iconClass)
23
- const maskStyle = computed(() => {
24
- const url = `url("${props.iconClass.replace(/"/g, '\\"')}")`
25
- return {
26
- WebkitMaskImage: url,
27
- maskImage: url,
28
- WebkitMaskRepeat: 'no-repeat',
29
- maskRepeat: 'no-repeat',
30
- WebkitMaskPosition: 'center',
31
- maskPosition: 'center',
32
- WebkitMaskSize: 'contain',
33
- maskSize: 'contain'
34
- }
35
- })
36
- </script>
@@ -1,106 +0,0 @@
1
- <script setup lang="ts">
2
- import { computed, ref, watch } from "vue"
3
- import SwIcon from "./SwIcon.vue"
4
- import { formatPhoneNumber } from "../utils/index"
5
-
6
- // Define prop types - separate model from props
7
- interface InputProps {
8
- before?: string
9
- after?: string
10
- placeholder?: string
11
- label?: string
12
- name: string
13
- class?: string
14
- size?: string
15
- type?: string
16
- inputMode?: string
17
- required?: boolean
18
- maxlength?: number
19
- minlength?: number
20
- inputSize?: number
21
- autofocus?: boolean
22
- }
23
-
24
- // Use defineModel for the input value
25
- const modelValue = defineModel<string>()
26
-
27
- // Define props separately
28
- const props = withDefaults(defineProps<InputProps>(), {
29
- before: '',
30
- after: '',
31
- placeholder: '',
32
- label: '',
33
- class: '',
34
- size: '',
35
- type: 'text',
36
- inputMode: 'text',
37
- required: false,
38
- maxlength: 128,
39
- minlength: 1,
40
- inputSize: 60,
41
- autofocus: false
42
- })
43
-
44
- const emit = defineEmits(['suffix','prefix','focusInput'])
45
- const isFocused = ref(false)
46
-
47
- const hasValue = computed(() => (modelValue.value?.length ?? 0) > 0)
48
-
49
- const wrapperClass = computed(() => {
50
- const classes = ['sw-input']
51
- if (props.size.length > 0) classes.push('sw-' + props.size)
52
- if (props.class.length > 0) classes.push(props.class)
53
- if (isFocused.value || hasValue.value) classes.push('sw-input--active')
54
- return classes
55
- })
56
-
57
- const onfocus = (e: FocusEvent) => {
58
- isFocused.value = true
59
- emit('focusInput')
60
- const target = e.target as HTMLInputElement
61
- target.setSelectionRange(modelValue.value?.length || 0, modelValue.value?.length || 0)
62
- }
63
-
64
- const onblur = () => {
65
- isFocused.value = false
66
- }
67
-
68
- const suffix = () => { emit('suffix') }
69
- const prefix = () => { emit('prefix') }
70
-
71
- const formatPhone = (value: string | undefined, oldValue?: string) => {
72
- if (props.type !== 'phone' || value == null) return
73
- const formatted = formatPhoneNumber(value, oldValue)
74
- if (formatted !== value) modelValue.value = formatted
75
- }
76
-
77
- watch(modelValue, (newValue, oldValue) => {
78
- formatPhone(newValue, oldValue)
79
- })
80
- </script>
81
-
82
- <template>
83
- <div :class="wrapperClass">
84
- <sw-icon v-if="props.before.length > 0" :icon-class="props.before" @click="prefix"/>
85
- <slot v-else name="prefix"></slot>
86
- <label v-if="(props.label.length > 0)" :for="props.name">{{ props.label }}<span title="Это поле обязательно для заполнения." v-if="props.required">*</span></label>
87
- <input
88
- v-model="modelValue"
89
- :required="props.required"
90
- :placeholder="(props.required && props.label.length === 0)? props.placeholder + `*`: props.placeholder"
91
- :type="props.type"
92
- :inputmode="props.inputMode"
93
- :id="props.name"
94
- :name="props.name"
95
- :size="props.inputSize"
96
- @focus="onfocus"
97
- @blur="onblur"
98
- :maxlength="props.maxlength"
99
- :minlength="props.minlength"
100
- :autofocus="props.autofocus"
101
- v-bind="$attrs"
102
- >
103
- <sw-icon v-if="props.after.length > 0" :icon-class="props.after" @click="suffix"/>
104
- <slot v-else name="suffix"></slot>
105
- </div>
106
- </template>
@@ -1,217 +0,0 @@
1
- <script setup lang="ts">
2
- import { computed, h, resolveComponent, getCurrentInstance, type VNode, type Component } from 'vue'
3
-
4
- // Типы для конфигурации компонента
5
- interface ComponentConfig {
6
- [key: string]: any
7
- }
8
-
9
- interface MenuItemConfig {
10
- slot?: string | ComponentConfig | Array<any>
11
- [key: string]: any
12
- }
13
-
14
- interface MenuItemsObject {
15
- [componentName: string]: MenuItemConfig | MenuItemConfig[]
16
- }
17
-
18
- type MenuItems = MenuItemsObject | Array<{ [componentName: string]: MenuItemConfig }>
19
-
20
- interface Props {
21
- menuItems: MenuItems
22
- class?: string
23
- }
24
-
25
- const props = withDefaults(defineProps<Props>(), {
26
- class: ''
27
- })
28
-
29
- const model = defineModel<boolean[]>()
30
- const emit = defineEmits<{
31
- click: [{ index: number; componentName: string; event: Event; value?: boolean }]
32
- change: [{ index: number; componentName: string; event?: Event; value?: boolean }]
33
- }>()
34
-
35
- const instance = getCurrentInstance()
36
-
37
- // Рекурсивная функция для создания компонента со слотами
38
- const createComponentWithSlots = (
39
- componentName: string | Component,
40
- config: MenuItemConfig,
41
- index: number | null = null
42
- ): VNode => {
43
- let component: Component | string | undefined
44
- let resolvedComponent: any = null
45
-
46
- try {
47
- if (typeof componentName === 'string') {
48
- // Сначала ищем в глобально зарегистрированных компонентах
49
- component = instance?.appContext?.components?.[componentName]
50
- if (!component) {
51
- try {
52
- resolvedComponent = resolveComponent(componentName)
53
- // Если это async компонент, нужно получить его определение
54
- if (resolvedComponent && typeof resolvedComponent === 'object') {
55
- component = resolvedComponent as Component
56
- }
57
- } catch (e) {
58
- console.warn(`Failed to resolve component: ${componentName}`, e)
59
- }
60
- }
61
- if (!component || typeof component === 'string') {
62
- console.error(`Component "${componentName}" NOT FOUND`)
63
- return h('div', { class: 'error' }, `Component "${componentName}" not found`)
64
- }
65
- } else {
66
- component = componentName
67
- }
68
- } catch (e) {
69
- console.warn(`Component "${componentName}" not found`, e)
70
- return h('div', { class: 'error' }, `Component "${componentName}" not found`)
71
- }
72
-
73
- if (typeof config === 'object' && config !== null && !Array.isArray(config)) {
74
- const slots: Record<string, () => any> = {}
75
- const componentProps: Record<string, any> = {}
76
-
77
- for (const [key, value] of Object.entries(config)) {
78
- if (key === 'slot') {
79
- slots.default = () => {
80
- if (typeof value === 'object' && value !== null && !Array.isArray(value)) {
81
- if ('text' in value) {
82
- return h('span', { textContent: value.text })
83
- }
84
- if ('html' in value) {
85
- return h('span', { innerHTML: value.html })
86
- }
87
- return Object.entries(value).map(([compName, compConfig]) => {
88
- if (Array.isArray(compConfig)) {
89
- return compConfig.map(item => createComponentWithSlots(compName, item))
90
- } else {
91
- return createComponentWithSlots(compName, compConfig as MenuItemConfig)
92
- }
93
- }).flat()
94
- }
95
- if (Array.isArray(value)) {
96
- return value.map(item => {
97
- if (typeof item === 'object' && !Array.isArray(item)) {
98
- const [nestedComponentName, nestedConfig] = Object.entries(item)[0]
99
- return createComponentWithSlots(nestedComponentName, nestedConfig as MenuItemConfig)
100
- }
101
- return item
102
- })
103
- }
104
- return value
105
- }
106
- } else if (key.startsWith('slot.')) {
107
- const slotName = key.substring(5)
108
- slots[slotName] = () => {
109
- if (typeof value === 'object' && value !== null && !Array.isArray(value)) {
110
- if ('text' in value) {
111
- return h('span', { textContent: value.text })
112
- }
113
- if ('html' in value) {
114
- return h('span', { innerHTML: value.html })
115
- }
116
- return Object.entries(value).map(([compName, compConfig]) => {
117
- if (Array.isArray(compConfig)) {
118
- return compConfig.map(item => createComponentWithSlots(compName, item))
119
- } else {
120
- return createComponentWithSlots(compName, compConfig as MenuItemConfig)
121
- }
122
- }).flat()
123
- }
124
- if (Array.isArray(value)) {
125
- return value.map(item => {
126
- if (typeof item === 'object' && !Array.isArray(item)) {
127
- const [nestedComponentName, nestedConfig] = Object.entries(item)[0]
128
- return createComponentWithSlots(nestedComponentName, nestedConfig as MenuItemConfig)
129
- }
130
- return item
131
- })
132
- }
133
- return value
134
- }
135
- } else {
136
- componentProps[key] = value
137
- }
138
- }
139
-
140
- // Назначаем двустороннюю привязку (v-model) всем компонентам первого уровня
141
- if (index !== null) {
142
- // Добавляем обработчики событий click и change
143
- componentProps.onClick = (event: Event) => {
144
- emit('click', { index, componentName: String(componentName), event, value: model.value?.[index] })
145
- }
146
- componentProps.onChange = (event: Event) => {
147
- emit('change', { index, componentName: String(componentName), event, value: model.value?.[index] })
148
- }
149
- componentProps['onUpdate:modelValue'] = (value: boolean) => {
150
- // Инициализируем model.value если он undefined
151
- if (!model.value) {
152
- model.value = []
153
- }
154
- const newValues = [...model.value]
155
- // Расширяем массив если нужно
156
- while (newValues.length <= index) {
157
- newValues.push(false)
158
- }
159
- newValues[index] = value
160
- model.value = newValues
161
- // Эмитим событие change при изменении значения
162
- emit('change', { index, componentName: String(componentName), value })
163
- }
164
- // Используем значение из model или false по умолчанию
165
- const currentValue = model.value && index < model.value.length ? model.value[index] : false
166
- componentProps.modelValue = currentValue
167
- }
168
-
169
- if (Object.keys(slots).length > 0) {
170
- return h(component as Component, componentProps, slots)
171
- }
172
- return h(component as Component, componentProps)
173
- }
174
- return h(component as Component, config)
175
- }
176
-
177
- const menuComponents = computed(() => {
178
- const components: Array<{ render: () => VNode }> = []
179
-
180
- if (Array.isArray(props.menuItems)) {
181
- props.menuItems.forEach((item, index) => {
182
- if (typeof item === 'object' && item !== null) {
183
- const [componentName, config] = Object.entries(item)[0]
184
- components.push({
185
- render: () => createComponentWithSlots(componentName, config as MenuItemConfig, index)
186
- })
187
- }
188
- })
189
- } else {
190
- let index = 0
191
- for (const [componentName, params] of Object.entries(props.menuItems)) {
192
- if (Array.isArray(params)) {
193
- params.forEach((param) => {
194
- components.push({
195
- render: () => createComponentWithSlots(componentName, param, index++)
196
- })
197
- })
198
- } else if (typeof params === 'object' && params !== null) {
199
- components.push({
200
- render: () => createComponentWithSlots(componentName, params, index)
201
- })
202
- }
203
- }
204
- }
205
- return components
206
- })
207
- </script>
208
-
209
- <template>
210
- <nav :class="'sw-menu ' + props.class">
211
- <component
212
- v-for="(item, index) in menuComponents"
213
- :key="index"
214
- :is="item.render"
215
- />
216
- </nav>
217
- </template>