forked from webfansplz/vite-plugin-vue-devtools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathIframeView.vue
85 lines (77 loc) · 2.06 KB
/
IframeView.vue
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
<script lang="ts">
const iframeCacheMap = new Map<string, HTMLIFrameElement>()
</script>
<script setup lang="ts">
const props = defineProps<{
src: string
}>()
const colorMode = useColorMode()
const anchor = ref<HTMLDivElement>()
const key = computed(() => props.src)
const iframeEl = ref<HTMLIFrameElement>()
const box = reactive(useElementBounding(anchor))
const iframeLoaded = ref(false)
onMounted(() => {
if (iframeCacheMap.get(key.value)) {
iframeEl.value = iframeCacheMap.get(key.value)!
iframeEl.value.style.visibility = 'visible'
iframeLoaded.value = true
}
else {
iframeEl.value = document.createElement('iframe')
iframeCacheMap.set(key.value, iframeEl.value)
iframeEl.value.src = props.src
// CORS
try {
iframeEl.value.style.opacity = '0.01'
iframeEl.value.onload = () => {
syncColorMode()
iframeEl.value!.style.opacity = '1'
iframeLoaded.value = true
}
}
catch (e) {
iframeEl.value.style.opacity = '1'
}
document.body.appendChild(iframeEl.value)
nextTick(updateIframeBox)
}
setTimeout(syncColorMode, 100)
})
watchEffect(updateIframeBox)
watchEffect(syncColorMode)
onUnmounted(() => {
if (iframeEl.value)
iframeEl.value.style.visibility = 'hidden'
})
function syncColorMode() {
if (!iframeEl.value || !iframeEl.value.contentWindow)
return
try {
const html = iframeEl.value.contentWindow.document.querySelector('html')
html?.classList.toggle('dark', colorMode.value === 'dark')
html?.classList.toggle('light', colorMode.value === 'dark')
}
catch (e) {
}
}
function updateIframeBox() {
if (!iframeEl.value)
return
Object.assign(iframeEl.value.style, {
position: 'fixed',
left: `${box.left}px`,
top: `${box.top}px`,
width: `${box.width}px`,
height: `${box.height}px`,
outline: 'none',
})
}
</script>
<template>
<div ref="anchor" h-full w-full>
<div v-if="!iframeLoaded" absolute inset-0 flex items-center justify-center>
<i class="mdi:loading animate-spin text-3xl" />
</div>
</div>
</template>