-
Notifications
You must be signed in to change notification settings - Fork 138
/
NotificationProvider.tsx
252 lines (221 loc) Β· 8.01 KB
/
NotificationProvider.tsx
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
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
/**
* @license
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://github.com/IDuxFE/idux/blob/main/LICENSE
*/
import type {
NotificationOptions,
NotificationPlacement,
NotificationPlacementMap,
NotificationProviderProps,
NotificationRef,
} from './types'
import type { CommonConfig, NotificationConfig } from '@idux/components/config'
import { ComputedRef, Ref, TransitionGroup, cloneVNode, computed, defineComponent, isVNode, provide, ref } from 'vue'
import { isArray, isUndefined, pickBy } from 'lodash-es'
import { CdkPortal } from '@idux/cdk/portal'
import { VKey, callEmit, convertArray, convertCssPixel, uniqueId } from '@idux/cdk/utils'
import { useGlobalConfig } from '@idux/components/config'
import { useThemeToken } from '@idux/components/theme'
import { usePortalTarget } from '@idux/components/utils'
import Notification from './Notification'
import { NOTIFICATION_PROVIDER_TOKEN } from './token'
import { notificationPlacement, notificationProviderProps, notificationType } from './types'
import { getThemeTokens, transforms } from '../theme'
const groupPositions = {
topStart: ['top', 'left'],
topEnd: ['top', 'right'],
bottomStart: ['bottom', 'left'],
bottomEnd: ['bottom', 'right'],
} as const
export default defineComponent({
name: 'IxNotificationProvider',
inheritAttrs: false,
props: notificationProviderProps,
setup(props, { slots, expose }) {
const commonCfg = useGlobalConfig('common')
const { globalHashId, hashId, registerToken } = useThemeToken('notification')
registerToken(getThemeTokens, transforms)
const config = useGlobalConfig('notification')
const mergedPrefixCls = computed(() => `${commonCfg.prefixCls}-notification`)
const mergedPortalTarget = usePortalTarget(props, config, commonCfg, mergedPrefixCls)
const maxCount = computed(() => props.maxCount ?? config.maxCount)
const { notifications, loadContainer, open, info, success, warning, error, update, destroy, destroyAll } =
useNotification(maxCount)
const apis = { open, info, success, warning, error, update, destroy, destroyAll }
const placementNotifications = usePlacementNotifications(props, config, notifications)
provide(NOTIFICATION_PROVIDER_TOKEN, apis)
expose(apis)
return () => {
const getChild = (notifications: NotificationOptions[]) => {
return notifications.map(item => {
const { key, visible = true, content, contentProps, ...restProps } = item
const onClose = () => destroy(key!)
const mergedProps = { key, visible, onClose }
const contentNode = isVNode(content) ? cloneVNode(content, contentProps, true) : content
return (
<Notification {...mergedProps} {...restProps}>
{contentNode}
</Notification>
)
})
}
const placementGroup = Object.entries(placementNotifications.value).map(([key, notificationsRecord]) => {
const placement = key as NotificationPlacement
const child = getChild(notificationsRecord)
const moveName = getMoveName(placement, commonCfg)
const position = getGroupPosition(props, config, placement)
return (
<TransitionGroup
key={placement}
tag="div"
appear
name={moveName}
class={[
`${mergedPrefixCls.value}-wrapper`,
`${mergedPrefixCls.value}-wrapper-${placement}`,
globalHashId.value,
hashId.value,
]}
style={position}
>
{child}
</TransitionGroup>
)
})
return (
<>
{slots.default?.()}
<CdkPortal target={mergedPortalTarget.value} load={loadContainer.value}>
{placementGroup}
</CdkPortal>
</>
)
}
},
})
function usePlacementNotifications(
props: NotificationProviderProps,
config: NotificationConfig,
notifications: Ref<NotificationOptions[]>,
) {
return computed(() => {
const initValue = getPlacementInitValue<NotificationOptions[]>(() => []) as NotificationPlacementMap
const { destroyOnHover, duration, closeIcon, placement } = config
if (notifications.value.length === 0) {
return initValue
}
return notifications.value.reduce((acc, item) => {
const notificationProps = getRealObj({
destroyOnHover,
duration,
closeIcon,
placement,
...item,
}) as unknown as NotificationOptions
const curPlacement = notificationProps.placement!
acc[curPlacement].push(notificationProps)
return acc
}, initValue)
})
}
function useNotification(maxCount: ComputedRef<number>) {
const notifications = ref<NotificationOptions[]>([])
const getCurrIndex = (key: VKey) => {
return notifications.value.findIndex(notification => notification.key === key)
}
const add = (item: NotificationOptions) => {
const currIndex = item.key ? getCurrIndex(item.key) : -1
if (currIndex !== -1) {
notifications.value.splice(currIndex, 1, item)
return item.key!
}
if (notifications.value.length >= maxCount.value) {
notifications.value = notifications.value.slice(-maxCount.value + 1)
}
const key = item.key ?? uniqueId('ix-notification')
notifications.value.push({ ...item, key })
return key
}
const update = (key: VKey, item: Partial<NotificationOptions>) => {
const currIndex = getCurrIndex(key)
if (currIndex !== -1) {
const newItem = { ...notifications.value[currIndex], ...item }
notifications.value.splice(currIndex, 1, newItem)
}
}
const destroy = (key: VKey | VKey[]) => {
const keys = convertArray(key)
keys.forEach(key => {
const currIndex = getCurrIndex(key)
if (currIndex !== -1) {
const item = notifications.value.splice(currIndex, 1)
callEmit(item[0].onDestroy, key)
}
})
}
const destroyAll = () => {
notifications.value = []
}
const loadContainer = ref(false)
const open = (options: NotificationOptions): NotificationRef => {
const key = add(options)
const ref = {
key,
update: (options: Partial<NotificationOptions>) => update(key, options),
destroy: () => destroy(key),
}
if (!loadContainer.value) {
loadContainer.value = true
}
return ref
}
const [info, success, warning, error] = notificationType.map(
type => (options: Omit<NotificationOptions, 'type'>) => open({ ...options, type }),
)
return { notifications, loadContainer, open, info, success, warning, error, update, destroy, destroyAll }
}
function getGroupPosition(
props: NotificationProviderProps,
config: NotificationConfig,
placement: NotificationPlacement,
) {
const realPlacement = placement ?? config.placement
const realOffset = props.offset ?? config.offset
return getPosition(realOffset, realPlacement)
}
function getPosition(offset: NotificationProviderProps['offset'], placement: NotificationPlacement) {
const offsets = isArray(offset) ? offset : [offset, offset]
const [verticalOffset, horizontalOffset] = offsets.map(convertCssPixel)
const [verticalPosition, horizontalPosition] = groupPositions[placement]
return {
[verticalPosition]: verticalOffset,
[horizontalPosition]: horizontalOffset,
}
}
function getMoveName(placement: NotificationPlacement, commonCfg: CommonConfig) {
const prefixCls = commonCfg.prefixCls
const moveNameMap = {
topEnd: `${prefixCls}-move-end`,
bottomEnd: `${prefixCls}-move-end`,
topStart: `${prefixCls}-move-start`,
bottomStart: `${prefixCls}-move-start`,
} as const
return moveNameMap[placement]
}
function getRealObj<T>(obj: Record<string, T>) {
return pickBy<T>(obj, (val: T) => !isUndefined(val))
}
function getPlacementInitValue<T>(initValueFn: () => T) {
return notificationPlacement.reduce(
(acc, item) => {
const cloneValue = initValueFn()
return {
...acc,
[item]: cloneValue,
}
},
{} as Record<NotificationPlacement, T>,
)
}