2023-07-22 23:19:33 +08:00
|
|
|
import { computed, getCurrentInstance, inject, ref, unref } from 'vue'
|
2024-03-22 16:36:25 +08:00
|
|
|
import { debugWarn, isClient, isNumber } from '@element-plus/utils'
|
2023-02-28 10:35:56 +08:00
|
|
|
|
|
|
|
import type { InjectionKey, Ref } from 'vue'
|
2022-02-09 16:31:31 +08:00
|
|
|
|
2024-03-22 16:36:25 +08:00
|
|
|
export interface ElZIndexInjectionContext {
|
|
|
|
current: number
|
|
|
|
}
|
|
|
|
|
|
|
|
const initial: ElZIndexInjectionContext = {
|
|
|
|
current: 0,
|
|
|
|
}
|
|
|
|
|
2022-02-09 16:31:31 +08:00
|
|
|
const zIndex = ref(0)
|
2024-03-22 16:36:25 +08:00
|
|
|
|
2023-03-06 23:20:21 +08:00
|
|
|
export const defaultInitialZIndex = 2000
|
2023-02-28 10:35:56 +08:00
|
|
|
|
2024-03-22 16:36:25 +08:00
|
|
|
// For SSR
|
|
|
|
export const ZINDEX_INJECTION_KEY: InjectionKey<ElZIndexInjectionContext> =
|
|
|
|
Symbol('elZIndexContextKey')
|
|
|
|
|
2023-02-28 10:35:56 +08:00
|
|
|
export const zIndexContextKey: InjectionKey<Ref<number | undefined>> =
|
|
|
|
Symbol('zIndexContextKey')
|
2022-02-09 16:31:31 +08:00
|
|
|
|
2023-03-06 23:20:21 +08:00
|
|
|
export const useZIndex = (zIndexOverrides?: Ref<number>) => {
|
2024-03-22 16:36:25 +08:00
|
|
|
const increasingInjection = getCurrentInstance()
|
|
|
|
? inject(ZINDEX_INJECTION_KEY, initial)
|
|
|
|
: initial
|
|
|
|
|
2023-07-22 23:19:33 +08:00
|
|
|
const zIndexInjection =
|
|
|
|
zIndexOverrides ||
|
|
|
|
(getCurrentInstance() ? inject(zIndexContextKey, undefined) : undefined)
|
2024-03-22 16:36:25 +08:00
|
|
|
|
2023-02-28 10:35:56 +08:00
|
|
|
const initialZIndex = computed(() => {
|
|
|
|
const zIndexFromInjection = unref(zIndexInjection)
|
|
|
|
return isNumber(zIndexFromInjection)
|
|
|
|
? zIndexFromInjection
|
|
|
|
: defaultInitialZIndex
|
|
|
|
})
|
2024-03-22 16:36:25 +08:00
|
|
|
|
2022-02-09 16:31:31 +08:00
|
|
|
const currentZIndex = computed(() => initialZIndex.value + zIndex.value)
|
|
|
|
|
|
|
|
const nextZIndex = () => {
|
2024-03-22 16:36:25 +08:00
|
|
|
increasingInjection.current++
|
|
|
|
zIndex.value = increasingInjection.current
|
2022-02-09 16:31:31 +08:00
|
|
|
return currentZIndex.value
|
|
|
|
}
|
|
|
|
|
2024-03-22 16:36:25 +08:00
|
|
|
if (!isClient && !inject(ZINDEX_INJECTION_KEY)) {
|
|
|
|
debugWarn(
|
|
|
|
'ZIndexInjection',
|
|
|
|
`Looks like you are using server rendering, you must provide a z-index provider to ensure the hydration process to be succeed
|
|
|
|
usage: app.provide(ZINDEX_INJECTION_KEY, { current: 0 })`
|
|
|
|
)
|
|
|
|
}
|
|
|
|
|
2022-02-09 16:31:31 +08:00
|
|
|
return {
|
|
|
|
initialZIndex,
|
|
|
|
currentZIndex,
|
|
|
|
nextZIndex,
|
|
|
|
}
|
|
|
|
}
|
2023-03-06 23:20:21 +08:00
|
|
|
|
|
|
|
export type UseZIndexReturn = ReturnType<typeof useZIndex>
|