-
-
Notifications
You must be signed in to change notification settings - Fork 6.9k
/
items.ts
105 lines (91 loc) 路 2.62 KB
/
items.ts
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
// Utilities
import { computed } from 'vue'
import { getPropertyFromItem, pick, propsFactory } from '@/util'
// Types
import type { PropType } from 'vue'
import type { SelectItemKey } from '@/util'
export interface InternalItem<T = any> {
title: string
value: any
props: {
[key: string]: any
title: string
value: any
}
children?: InternalItem[]
raw: T
}
export interface ItemProps {
items: any[]
itemTitle: SelectItemKey
itemValue: SelectItemKey
itemChildren: SelectItemKey
itemProps: SelectItemKey
returnObject: boolean
}
// Composables
export const makeItemsProps = propsFactory({
items: {
type: Array as PropType<ItemProps['items']>,
default: () => ([]),
},
itemTitle: {
type: [String, Array, Function] as PropType<SelectItemKey>,
default: 'title',
},
itemValue: {
type: [String, Array, Function] as PropType<SelectItemKey>,
default: 'value',
},
itemChildren: {
type: [Boolean, String, Array, Function] as PropType<SelectItemKey>,
default: 'children',
},
itemProps: {
type: [Boolean, String, Array, Function] as PropType<SelectItemKey>,
default: 'props',
},
returnObject: Boolean,
}, 'item')
export function transformItem (props: Omit<ItemProps, 'items'>, item: any) {
const title = getPropertyFromItem(item, props.itemTitle, item)
const value = getPropertyFromItem(item, props.itemValue, title)
const children = getPropertyFromItem(item, props.itemChildren)
const itemProps = props.itemProps === true
? typeof item === 'object' && item != null && !Array.isArray(item)
? 'children' in item
? pick(item, ['children'])[1]
: item
: undefined
: getPropertyFromItem(item, props.itemProps)
const _props = {
title,
value,
...itemProps,
}
return {
title: String(_props.title ?? ''),
value: _props.value,
props: _props,
children: Array.isArray(children) ? transformItems(props, children) : undefined,
raw: item,
}
}
export function transformItems (props: Omit<ItemProps, 'items'>, items: ItemProps['items']) {
const array: InternalItem[] = []
for (const item of items) {
array.push(transformItem(props, item))
}
return array
}
export function useItems (props: ItemProps) {
const items = computed(() => transformItems(props, props.items))
function transformIn (value: any[]): InternalItem[] {
return value.map(item => transformItem(props, item))
}
function transformOut (value: InternalItem[]) {
if (props.returnObject) return value.map(({ raw: item }) => item)
return value.map(({ props }) => props.value)
}
return { items, transformIn, transformOut }
}