vuepress-plugin-photomap
Version:
VuePress2插件,用于在文章中插入照片地图组件,类似Apple相册的PhotoMap功能
128 lines (127 loc) • 4.12 kB
JavaScript
import { ref } from 'vue';
import PhotoSwipe from 'photoswipe';
export function usePhotoSwipe(options = {}) {
const photoSwipeInstance = ref();
const isOpen = ref(false);
// 默认配置
const config = {
enablePhotoSwipe: options.enablePhotoSwipe !== false,
photoSwipeOptions: {
// PhotoSwipe默认配置
bgOpacity: 0.8,
showHideOpacity: true,
closeOnVerticalDrag: true,
// 自定义选项
...options.photoSwipeOptions
}
};
// 准备PhotoSwipe数据格式
const preparePhotoSwipeData = (photos) => {
return photos.map(photo => ({
src: photo.src,
width: photo.width || 1200,
height: photo.height || 800,
alt: photo.alt,
// 添加GPS信息到metadata
gps: photo.gps
}));
};
// 打开PhotoSwipe画廊
const openPhotoSwipe = (photos, initialIndex = 0) => {
if (!config.enablePhotoSwipe) {
// 如果禁用PhotoSwipe,则在新窗口打开图片
window.open(photos[initialIndex]?.src, '_blank');
return;
}
const dataSource = preparePhotoSwipeData(photos);
if (dataSource.length === 0) {
console.warn('没有可显示的图片');
return;
}
// 确保索引在有效范围内
const safeIndex = Math.max(0, Math.min(initialIndex, dataSource.length - 1));
try {
photoSwipeInstance.value = new PhotoSwipe({
dataSource,
index: safeIndex,
...config.photoSwipeOptions
});
// 添加事件监听
photoSwipeInstance.value.on('openingAnimationStart', () => {
isOpen.value = true;
});
photoSwipeInstance.value.on('close', () => {
isOpen.value = false;
photoSwipeInstance.value = undefined;
});
// 添加键盘支持
photoSwipeInstance.value.on('keydown', (e) => {
// ESC键关闭
if (e.key === 'Escape') {
photoSwipeInstance.value?.close();
}
// 方向键导航
else if (e.key === 'ArrowLeft') {
photoSwipeInstance.value?.prev();
}
else if (e.key === 'ArrowRight') {
photoSwipeInstance.value?.next();
}
});
// 初始化并打开
photoSwipeInstance.value.init();
}
catch (err) {
console.error('PhotoSwipe初始化失败:', err);
// 降级处理:在新窗口打开图片
window.open(photos[safeIndex]?.src, '_blank');
}
};
// 关闭PhotoSwipe
const closePhotoSwipe = () => {
if (photoSwipeInstance.value) {
photoSwipeInstance.value.close();
}
};
// 导航到下一张图片
const nextPhoto = () => {
if (photoSwipeInstance.value) {
photoSwipeInstance.value.next();
}
};
// 导航到上一张图片
const prevPhoto = () => {
if (photoSwipeInstance.value) {
photoSwipeInstance.value.prev();
}
};
// 跳转到指定索引的图片
const goToSlide = (index) => {
if (photoSwipeInstance.value) {
photoSwipeInstance.value.goTo(index);
}
};
// 获取当前图片索引
const getCurrentIndex = () => {
return photoSwipeInstance.value?.currIndex || 0;
};
// 销毁PhotoSwipe实例
const destroyPhotoSwipe = () => {
if (photoSwipeInstance.value) {
photoSwipeInstance.value.close();
photoSwipeInstance.value = undefined;
}
isOpen.value = false;
};
return {
photoSwipeInstance,
isOpen,
openPhotoSwipe,
closePhotoSwipe,
nextPhoto,
prevPhoto,
goToSlide,
getCurrentIndex,
destroyPhotoSwipe
};
}