@v-c/collapse 0.0.1

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.
@@ -0,0 +1,218 @@
1
+ <script setup lang="ts">
2
+ import type { CollapseProps } from '../src/index'
3
+ import { h, ref, shallowRef, watch } from 'vue'
4
+ import Collapse from '../src/index'
5
+
6
+ const initLength = 3
7
+
8
+ const text = `
9
+ A dog is a type of domesticated animal.
10
+ Known for its loyalty and faithfulness,
11
+ it can be found as a welcome guest in many households across the world.
12
+ `
13
+
14
+ function random() {
15
+ return parseInt((Math.random() * 10).toString(), 10) + 1
16
+ }
17
+
18
+ const arrowPath
19
+ = 'M869 487.8L491.2 159.9c-2.9-2.5-6.6-3.9-10.5-3.9h-88'
20
+ + '.5c-7.4 0-10.8 9.2-5.2 14l350.2 304H152c-4.4 0-8 3.6-8 8v60c0 4.4 3.'
21
+ + '6 8 8 8h585.1L386.9 854c-5.6 4.9-2.2 14 5.2 14h91.5c1.9 0 3.8-0.7 5.'
22
+ + '2-2L869 536.2c14.7-12.8 14.7-35.6 0-48.4z'
23
+
24
+ function expandIcon({ isActive }: { isActive: boolean }) {
25
+ return h(
26
+ 'i',
27
+ {
28
+ style: {
29
+ 'margin-right': '.5rem',
30
+ },
31
+ },
32
+ [
33
+ h(
34
+ 'svg',
35
+ {
36
+ viewBox: '0 0 1024 1024',
37
+ width: '1em',
38
+ height: '1em',
39
+ fill: 'currentColor',
40
+ style: {
41
+ verticalAlign: '-.125em',
42
+ transition: 'transform .2s',
43
+ transform: `rotate(${isActive ? 90 : 0}deg)`,
44
+ },
45
+ },
46
+ [
47
+ h('path', {
48
+ d: arrowPath,
49
+ }),
50
+ ],
51
+ ),
52
+ ],
53
+ )
54
+ }
55
+
56
+ const rerender = ref(0)
57
+ const accordion = ref(false)
58
+ const activeKey = ref<Array<string | number | bigint>>(['4'])
59
+ const collapsible = ref<CollapseProps['collapsible']>()
60
+
61
+ const time = ref(random())
62
+ watch(
63
+ () => [rerender.value, accordion.value, activeKey.value],
64
+ () => {
65
+ time.value = random()
66
+ },
67
+ )
68
+
69
+ function handleSetActiveKey(e: Array<string | number | bigint>) {
70
+ activeKey.value = e
71
+ }
72
+
73
+ function getCollapsedHeight(el: HTMLDivElement) {
74
+ el.style.height = '0'
75
+ el.style.opacity = '0'
76
+ }
77
+ function getRealHeight(el: HTMLDivElement) {
78
+ console.log(el.scrollHeight)
79
+ el.style.height = `${el.scrollHeight}px`
80
+ el.style.opacity = '1'
81
+ }
82
+ function getCurrentHeight(el: HTMLDivElement) {
83
+ el.style.height = `${el.offsetHeight}px`
84
+ }
85
+
86
+ function skipOpacityTransition(el: HTMLDivElement) {
87
+ el.style.height = ''
88
+ }
89
+ const openMotion = {
90
+ name: 'vc-collapse',
91
+ onBeforeEnter: getCollapsedHeight,
92
+ onEnter: getRealHeight,
93
+ onAfterEnter: skipOpacityTransition,
94
+ onBeforeLeave: getCurrentHeight,
95
+ onLeave: getCollapsedHeight,
96
+ onAfterLeave: skipOpacityTransition,
97
+ }
98
+
99
+ const items = shallowRef<CollapseProps['items']>([])
100
+ function handleUpdateItems() {
101
+ items.value = Array.from({ length: initLength })
102
+ .map((_, i) => {
103
+ return {
104
+ label: `This is panel header ${i + 1}`,
105
+ key: i + 1,
106
+ children: h('p', {}, [text.repeat(time.value)]),
107
+ }
108
+ })
109
+
110
+ items.value = items.value.concat([
111
+ {
112
+ label: `This is panel header ${initLength + 1}`,
113
+ key: initLength + 1,
114
+ children: h(Collapse, {
115
+ defaultActiveKey: '1',
116
+ expandIcon,
117
+ items: [
118
+ {
119
+ label: 'This is panel nest panel',
120
+ key: '1',
121
+ children: h('p', {}, [text]),
122
+ },
123
+ ],
124
+ }),
125
+ },
126
+ {
127
+ label: `This is panel header ${initLength + 2}`,
128
+ key: initLength + 2,
129
+ children: h(Collapse, {
130
+ defaultActiveKey: '1',
131
+ items: [
132
+ {
133
+ label: 'This is panel nest panel',
134
+ children: h('form', {}, [
135
+ h(
136
+ 'label',
137
+ {
138
+ htmlFor: 'test',
139
+ },
140
+ ['Name:&nbsp;'],
141
+ ),
142
+ h('input', {
143
+ type: 'text',
144
+ id: 'test',
145
+ }),
146
+ ]),
147
+ },
148
+ ],
149
+ }),
150
+ },
151
+ {
152
+ label: `This is panel header ${initLength + 3}`,
153
+ key: initLength + 3,
154
+ extra: h('span', {}, ['Extra Node']),
155
+ children: h('p', {}, ['Panel with extra']),
156
+ },
157
+ ])
158
+ }
159
+ watch(
160
+ () => time.value,
161
+ () => {
162
+ handleUpdateItems()
163
+ },
164
+ { immediate: true },
165
+ )
166
+
167
+ function handleCollapsibleChange(e: Event) {
168
+ const values = [undefined, 'header', 'icon', 'disabled']
169
+ collapsible.value = Reflect.get(values, (e.target as HTMLSelectElement).value) as CollapseProps['collapsible']
170
+ console.log(collapsible.value)
171
+ }
172
+ </script>
173
+
174
+ <template>
175
+ <button type="button" @click="rerender += 1">
176
+ reRender
177
+ </button>
178
+ <br>
179
+ <br>
180
+ <button type="button" @click="accordion = !accordion">
181
+ {{ accordion ? "Mode: accordion" : "Mode: collapse" }}
182
+ </button>
183
+ <br>
184
+ <br>
185
+ <div>
186
+ collapsible:
187
+ <select @change="handleCollapsibleChange">
188
+ <option :value="0">
189
+ default
190
+ </option>
191
+ <option :value="1">
192
+ header
193
+ </option>
194
+ <option :value="2">
195
+ icon
196
+ </option>
197
+ <option :value="3">
198
+ disabled
199
+ </option>
200
+ </select>
201
+ </div>
202
+ <br>
203
+ <button type="button" @click="activeKey = ['2']">
204
+ active header 2
205
+ </button>
206
+ <br>
207
+ <br>
208
+
209
+ <Collapse
210
+ :accordion="accordion"
211
+ :active-key="activeKey"
212
+ :expand-icon="expandIcon"
213
+ :open-motion="openMotion"
214
+ :collapsible="collapsible"
215
+ :items="items"
216
+ @change="handleSetActiveKey"
217
+ />
218
+ </template>
package/package.json ADDED
@@ -0,0 +1,28 @@
1
+ {
2
+ "name": "@v-c/collapse",
3
+ "type": "module",
4
+ "version": "0.0.1",
5
+ "publishConfig": {
6
+ "access": "public"
7
+ },
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "import": "./dist/index.js",
12
+ "require": "./dist/index.cjs"
13
+ },
14
+ "./dist/*": "./dist/*",
15
+ "./package.json": "./package.json"
16
+ },
17
+ "main": "dist/index.js",
18
+ "peerDependencies": {
19
+ "vue": "^3.0.0"
20
+ },
21
+ "dependencies": {
22
+ "@v-c/util": "0.0.7"
23
+ },
24
+ "scripts": {
25
+ "build": "vite build",
26
+ "prepublish": "pnpm build"
27
+ }
28
+ }
@@ -0,0 +1,108 @@
1
+ import type { Ref } from 'vue'
2
+ import type { CollapseProps, Key } from './interface'
3
+ import { classNames as classnames } from '@v-c/util'
4
+ import useMergedState from '@v-c/util/dist/hooks/useMergedState'
5
+ import pickAttrs from '@v-c/util/dist/pickAttrs'
6
+ import { defineComponent, ref, toRef } from 'vue'
7
+ import { useItems } from './hooks/useItems'
8
+
9
+ function getActiveKeysArray(activeKey: Key | Array<Key>) {
10
+ let currentActiveKey = activeKey
11
+ if (!Array.isArray(currentActiveKey)) {
12
+ const activeKeyType = typeof currentActiveKey
13
+ currentActiveKey
14
+ = activeKeyType === 'number' || activeKeyType === 'string'
15
+ ? [currentActiveKey]
16
+ : []
17
+ }
18
+ return currentActiveKey.map(key => String(key))
19
+ }
20
+
21
+ const defaults = {
22
+ prefixCls: 'vc-collapse',
23
+ } as any
24
+
25
+ const Collapse = defineComponent<CollapseProps>({
26
+ name: 'VcCollapse',
27
+ inheritAttrs: false,
28
+ setup(props = defaults, { attrs, expose, slots }) {
29
+ const refWrapper = ref<HTMLDivElement>()
30
+
31
+ const [activeKey, setActiveKey] = useMergedState<
32
+ Key | Key[],
33
+ Ref<Array<Key>>
34
+ >([], {
35
+ value: toRef(props, 'activeKey') as Ref<Key | Key[]>,
36
+ onChange: v => props.onChange?.(v as Key[]),
37
+ defaultValue: props.defaultActiveKey,
38
+ postState: getActiveKeysArray,
39
+ })
40
+
41
+ const getActiveKey = (key: Key) => {
42
+ if (props.accordion) {
43
+ return activeKey.value[0] === key ? [] : [key]
44
+ }
45
+
46
+ const index = activeKey.value.indexOf(key)
47
+ const isActive = index > -1
48
+ if (isActive) {
49
+ return activeKey.value.filter(item => item !== key)
50
+ }
51
+
52
+ return [...activeKey.value, key]
53
+ }
54
+ const onItemClick = (key: Key) => {
55
+ activeKey.value = getActiveKey(key)
56
+ setActiveKey(activeKey.value)
57
+ }
58
+
59
+ expose({
60
+ ref: refWrapper,
61
+ })
62
+
63
+ return () => {
64
+ const {
65
+ prefixCls = 'vc-collapse',
66
+ className,
67
+ style,
68
+ openMotion,
69
+ expandIcon,
70
+ collapsible,
71
+ accordion,
72
+ classNames,
73
+ styles,
74
+ items,
75
+ } = props
76
+
77
+ const collapseClassName = classnames(prefixCls, className)
78
+
79
+ const mergedProps = { ...props, ...attrs }
80
+
81
+ const mergedChildren = useItems(items, slots.default, {
82
+ prefixCls,
83
+ accordion,
84
+ openMotion,
85
+ expandIcon,
86
+ collapsible,
87
+ onItemClick,
88
+ activeKey: activeKey.value,
89
+ classNames,
90
+ styles,
91
+ })
92
+
93
+ return (
94
+ <div
95
+ ref={refWrapper}
96
+ class={collapseClassName}
97
+ style={style as any}
98
+ role={accordion ? 'tablist' : undefined}
99
+ {...pickAttrs(mergedProps, { aria: true, data: true })}
100
+ >
101
+ {mergedChildren}
102
+ </div>
103
+ )
104
+ }
105
+ },
106
+ })
107
+
108
+ export default Collapse
package/src/Panel.tsx ADDED
@@ -0,0 +1,177 @@
1
+ import type { HTMLAttributes } from 'vue'
2
+ import type { CollapsePanelProps } from './interface'
3
+ import { classNames as classnames } from '@v-c/util'
4
+ import KeyCode from '@v-c/util/dist/KeyCode'
5
+ import omit from '@v-c/util/dist/omit.ts'
6
+ import { computed, defineComponent, ref, Transition } from 'vue'
7
+ import PanelContent from './PanelContent'
8
+
9
+ const defaults = {
10
+ showArrow: true,
11
+ classNames: {},
12
+ styles: {},
13
+ } as any
14
+
15
+ const CollapsePanel = defineComponent<CollapsePanelProps>({
16
+ name: 'CollapsePanel',
17
+ inheritAttrs: false,
18
+ setup(props = defaults, { attrs, expose }) {
19
+ const disabled = computed(() => props.collapsible === 'disabled')
20
+ const refWrapper = ref()
21
+ const ifExtraExist = computed(
22
+ () =>
23
+ props.extra !== null
24
+ && props.extra !== undefined
25
+ && typeof props.extra !== 'boolean',
26
+ )
27
+
28
+ const collapsibleProps = computed(() => {
29
+ return {
30
+ 'onClick': () => {
31
+ props.onItemClick?.(props.panelKey!)
32
+ },
33
+ 'onKeydown': (e: KeyboardEvent) => {
34
+ if (
35
+ e.key === 'Enter'
36
+ || e.keyCode === KeyCode.ENTER
37
+ || e.which === KeyCode.ENTER
38
+ ) {
39
+ props.onItemClick?.(props.panelKey!)
40
+ }
41
+ },
42
+ 'role': props.accordion ? 'tab' : 'button',
43
+ 'aria-expanded': props.isActive,
44
+ 'aria-disabled': disabled.value,
45
+ 'tabIndex': disabled.value ? -1 : 0,
46
+ }
47
+ })
48
+
49
+ expose({
50
+ ref: refWrapper,
51
+ })
52
+
53
+ return () => {
54
+ const {
55
+ extra,
56
+ prefixCls,
57
+ isActive,
58
+ className,
59
+ expandIcon,
60
+ forceRender,
61
+ headerClass,
62
+ collapsible,
63
+ accordion,
64
+ openMotion = {},
65
+ onItemClick,
66
+ classNames: customizeClassNames = {},
67
+ showArrow = true,
68
+ styles = {},
69
+ header,
70
+ panelKey,
71
+ children,
72
+ ...restProps
73
+ } = props
74
+
75
+ const collapsePanelClassNames = classnames(
76
+ `${prefixCls}-item`,
77
+ {
78
+ [`${prefixCls}-item-active`]: isActive,
79
+ [`${prefixCls}-item-disabled`]: disabled.value,
80
+ },
81
+ className,
82
+ )
83
+ const headerClassName = classnames(
84
+ headerClass,
85
+ `${prefixCls}-header`,
86
+ {
87
+ [`${prefixCls}-collapsible-${collapsible}`]: !!collapsible,
88
+ },
89
+ customizeClassNames.header,
90
+ )
91
+
92
+ const headerProps: HTMLAttributes = {
93
+ class: headerClassName,
94
+ style: styles.header,
95
+ ...(['header', 'icon'].includes(collapsible!)
96
+ ? {}
97
+ : collapsibleProps.value),
98
+ }
99
+
100
+ // ======================== Icon ========================
101
+ const iconNodeInner
102
+ = typeof expandIcon === 'function'
103
+ ? (
104
+ expandIcon(props)
105
+ )
106
+ : (
107
+ <i class="arrow" />
108
+ )
109
+ const iconNode = iconNodeInner && (
110
+ <div
111
+ class={classnames(`${prefixCls}-expand-icon`, customizeClassNames?.icon)}
112
+ style={styles?.icon}
113
+ {...(['header', 'icon'].includes(collapsible!)
114
+ ? collapsibleProps.value
115
+ : {})}
116
+ >
117
+ {iconNodeInner}
118
+ </div>
119
+ )
120
+
121
+ const panelContent = (
122
+ <PanelContent
123
+ v-show={isActive}
124
+ prefixCls={prefixCls}
125
+ classNames={customizeClassNames}
126
+ styles={styles}
127
+ isActive={isActive}
128
+ forceRender={forceRender}
129
+ role={accordion ? 'tabpanel' : undefined}
130
+ v-slots={{ default: () => children }}
131
+ />
132
+ )
133
+
134
+ const transitionProps = {
135
+ 'appear': false,
136
+ 'leave-to-class': `${prefixCls}-panel-hidden`,
137
+ ...openMotion,
138
+ }
139
+
140
+ const mergedRestProps = {
141
+ ...restProps,
142
+ ...omit(attrs, ['class']),
143
+ }
144
+
145
+ return (
146
+ <div
147
+ {...mergedRestProps as any}
148
+ ref={refWrapper}
149
+ class={collapsePanelClassNames}
150
+ >
151
+ <div {...headerProps}>
152
+ {showArrow && iconNode}
153
+ <span
154
+ class={classnames(
155
+ `${prefixCls}-title`,
156
+ customizeClassNames?.title,
157
+ )}
158
+ style={styles?.title}
159
+ {...(collapsible === 'header' ? collapsibleProps.value : {})}
160
+ >
161
+ {header}
162
+ </span>
163
+ {ifExtraExist.value && (
164
+ <div class={`${prefixCls}-extra`}>{extra}</div>
165
+ )}
166
+ </div>
167
+
168
+ <Transition {...transitionProps}>
169
+ {isActive ? panelContent : null}
170
+ </Transition>
171
+ </div>
172
+ )
173
+ }
174
+ },
175
+ })
176
+
177
+ export default CollapsePanel
@@ -0,0 +1,63 @@
1
+ import type { CollapsePanelProps } from './interface'
2
+ import { classNames as classnames } from '@v-c/util'
3
+ import { defineComponent, ref, watch } from 'vue'
4
+
5
+ const PanelContent = defineComponent<CollapsePanelProps>({
6
+ name: 'PanelContent',
7
+ inheritAttrs: false,
8
+ setup(props, { slots }) {
9
+ const rendered = ref(props.isActive || props.forceRender)
10
+
11
+ watch(
12
+ () => [props.isActive, props.forceRender],
13
+ () => {
14
+ if (props.isActive || props.forceRender) {
15
+ rendered.value = true
16
+ }
17
+ },
18
+ )
19
+
20
+ return () => {
21
+ if (!rendered.value) {
22
+ return null
23
+ }
24
+
25
+ const {
26
+ prefixCls,
27
+ isActive,
28
+ style,
29
+ role,
30
+ className,
31
+ classNames: customizeClassNames,
32
+ styles,
33
+ } = props
34
+
35
+ return (
36
+ <div
37
+ class={classnames(
38
+ `${prefixCls}-panel`,
39
+ {
40
+ [`${prefixCls}-panel-active`]: isActive,
41
+ [`${prefixCls}-panel-inactive`]: !isActive,
42
+ },
43
+ className,
44
+ )}
45
+ style={style as any}
46
+ role={role}
47
+ >
48
+ <div
49
+ class={classnames(
50
+ `${prefixCls}-body`,
51
+ customizeClassNames?.body,
52
+ )}
53
+ style={styles?.body}
54
+ >
55
+ {slots.default?.()}
56
+ </div>
57
+ </div>
58
+ )
59
+ }
60
+ },
61
+ })
62
+
63
+ export default PanelContent