<template>
    <div ref="htmlRef" v-html="context"></div>
</template>
  
<script lang="ts" setup>
import { shallowRef, onMounted, onUnmounted } from 'vue'
import plus from '@/utils/h5plus'
import PhotoSwipeLightbox, { SlideData } from 'photoswipe/lightbox'
import 'photoswipe/style.css'

defineProps({
    context: {
        type: String,
        default: ''
    }
})

let lightbox: PhotoSwipeLightbox = null
const htmlRef = shallowRef<HTMLElement>()

onMounted(() => {
    const el = htmlRef.value
    if (el) {
        el.querySelectorAll('a').forEach((e) => {
            const href = e.href
            e.onclick = () => plus.openURL(href)
            e.removeAttribute('href')
        })

        if (!lightbox) {
            lightbox = new PhotoSwipeLightbox({
                gallery: el,
                children: 'img',
                pswpModule: () => import('photoswipe'),
            })

            // https://photoswipe.com/data-sources/#custom-html-markup
            lightbox.addFilter('domItemData', (itemData: SlideData, el: HTMLImageElement) => {
                if (el) {
                    itemData.src = el.src
                    itemData.w = el.naturalWidth
                    itemData.h = el.naturalHeight
                    itemData.msrc = el.src
                }
                return itemData
            })

            lightbox.on('beforeOpen', () => plus.hideStatusBar())
            lightbox.on('close', () => plus.showStatusBar())
            lightbox.init()
        }
    }
})

onUnmounted(() => {
    if (lightbox) {
        lightbox.destroy()
        lightbox = null
    }
})
</script>
  