返回 slidev
RenderWhen.vue
根目录 / packages / client / builtin / RenderWhen.vue
1 <script setup lang="ts">
2 import type { RenderContext } from '@slidev/types'
3 import { useElementVisibility } from '@vueuse/core'
4 import { computed, ref } from 'vue'
5 import { useNav } from '../composables/useNav'
6 import { useSlideContext } from '../context'
7
8 type Context = 'main' | 'visible' | 'print' | RenderContext
9
10 const props = defineProps<{
11 context: Context | Context[]
12 }>()
13 const { context } = props
14 const target = ref(null)
15 const targetVisible = useElementVisibility(target)
16
17 // When context has `visible`, we need to wrap the content with a div to track the visibility
18 const needsDomWrapper = Array.isArray(context)
19 ? context.includes('visible')
20 : context === 'visible'
21
22 const { $renderContext: currentContext } = useSlideContext()
23 const { isPrintMode } = useNav()
24 const shouldRender = computed(() => {
25 const anyContext = Array.isArray(context)
26 ? context.some(contextMatch)
27 : contextMatch(context)
28 const allConditions = Array.isArray(context)
29 ? context.every(conditionsMatch)
30 : conditionsMatch(context)
31 return anyContext && allConditions
32 })
33
34 function contextMatch(context: Context) {
35 if (context === currentContext?.value)
36 return true
37 if (context === 'main' && (currentContext?.value === 'slide' || currentContext?.value === 'presenter'))
38 return true
39 if (context === 'visible')
40 return true
41 if (context === 'print' && isPrintMode.value)
42 return true
43 return false
44 }
45
46 function conditionsMatch(context: Context) {
47 if (context === 'visible')
48 return targetVisible.value
49 return true
50 }
51 </script>
52
53 <template>
54 <div v-if="needsDomWrapper" ref="target">
55 <slot v-if="shouldRender" />
56 <slot v-else name="fallback" />
57 </div>
58 <slot v-else-if="shouldRender" />
59 <slot v-else name="fallback" />
60 </template>
61
61 lines Plain Text