UNPKG

@vuepress/plugin-watermark

Version:
49 lines (48 loc) 1.89 kB
import { wait } from '@vuepress/helper/client'; import { getCurrentInstance, isRef, nextTick, onMounted, toValue, watch, } from 'vue'; import { withBase } from 'vuepress/client'; import { Watermark } from 'watermark-js-plus'; export const setupWatermark = (options, enabled, delay = 500) => { onMounted(() => { const appContainer = getCurrentInstance()?.appContext.app._container; const watermark = new Watermark(); const isInsideApp = (target) => { const el = typeof target === 'string' ? document.querySelector(target) : target; return Boolean(el && appContainer?.contains(el)); }; const updateWaterMark = ( // shadow clone options object so that we can modify later { ...options }) => { // Blind mode default alpha is 0.005 if (options.mode === 'blind' && !options.globalAlpha) { options.globalAlpha = 0.005; } if (options.image?.startsWith('/')) { options.image = withBase(options.image); } if (toValue(enabled)) nextTick(() => watermark.changeOptions(options, 'overwrite')); else watermark.changeOptions(options, 'overwrite', false); }; if (isRef(options)) watch(options, updateWaterMark, { immediate: true }); else updateWaterMark(options); watch(enabled, () => nextTick(() => { if (enabled.value) { if (isInsideApp(toValue(options).parent)) { wait(delay).then(() => { watermark.create(); }); } else { watermark.create(); } } else { watermark.destroy(); } })); }); };