Skip to content

plugin-lightbox: fancybox -> @fancyapps/ui #1102

@MWTJC

Description

@MWTJC

fancybox repo所述,其已archive并合并进fancyui,故鄙人试图将文档此处描述的有关fancybox部分重新适配为使用@fancyapps/ui,但鄙人知识浅薄只会调试而无法解读源码,只能借ai临时拼凑了结果可用的代码,不敢贸然提pr
下面是在我的vitepress环境中实测可用的自定义插件代码,希望能有参考价值:
ArtalkFancyboxPlugin.ts(仿照plugin-lightbox/src/main.ts

import { ArtalkPlugin } from 'artalk'
import '@fancyapps/ui/dist/fancybox/fancybox.css'

const LOADED_ATTR = 'atk-lightbox-loaded'
const IMG_LINK_EL_CLASS = 'atk-lightbox-img'
const IMG_LINK_EL_SEL = `.${IMG_LINK_EL_CLASS}`

export interface ArtalkFancyboxPluginOptions {
    fancybox?: {
        lib?: () => Promise<any>
    }
    config?: any
}

export const ArtalkFancyboxPlugin: ArtalkPlugin<ArtalkFancyboxPluginOptions> = (ctx, opts) => {
    ctx.on('list-loaded', async () => {
        // 动态导入 Fancybox
        const { Fancybox } = await import('@fancyapps/ui')

        const $imgLinks: HTMLAnchorElement[] = []

        ctx.getCommentNodes().forEach((comment) => {
            const $content = comment.getRender().$content
            $content
                .querySelectorAll<HTMLImageElement>(`img:not([atk-emoticon]):not([${LOADED_ATTR}])`)
                .forEach(($img) => {
                    $img.setAttribute(LOADED_ATTR, '') // 标记为已加载

                    const $imgLink = document.createElement('a')
                    $imgLink.setAttribute('class', IMG_LINK_EL_CLASS)
                    $imgLink.setAttribute('href', $img.src)
                    $imgLink.setAttribute('data-fancybox', 'artalk-gallery')

                    // 如果图片有 alt 属性,设置为 caption
                    if ($img.alt) {
                        $imgLink.setAttribute('data-caption', $img.alt)
                    }

                    $imgLink.append($img.cloneNode())

                    $img.replaceWith($imgLink)
                    $imgLinks.push($imgLink)
                })
        })

        // 绑定 Fancybox
        if ($imgLinks.length > 0) {
            Fancybox.bind(`[data-fancybox="artalk-gallery"]`, {
                ...(opts?.config || {})
            })
        }
    })

    // 清理函数,在 Artalk 销毁时调用
    ctx.on('destroy', async () => {
        const { Fancybox } = await import('@fancyapps/ui')
        Fancybox.destroy()
    })
}

Artalk.vue

import Artalk from 'artalk'
// 导入自定义的 Fancybox 插件
import { ArtalkFancyboxPlugin } from './ArtalkFancyboxPlugin'

// 使用自定义的 Fancybox 插件
  Artalk.use(ArtalkFancyboxPlugin, {
    config: {
      Hash: false, 
      // ...其他Fancy配置
    }
  })

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions