You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

73 lines
3.0 KiB
JavaScript

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

// 导出获取图片URL的函数
export const getImageUrl = (path) => {
// 如果path不存在或不是字符串直接返回空字符串
if (!path || typeof path !== 'string') {
console.error('getImageUrl: path 参数无效或为空', path);
return '';
}
// 如果是绝对URLhttp://或https://开头),直接返回
if (path.startsWith('http://') || path.startsWith('https://')) {
return path;
}
// 否则处理为本地资源
// 使用Vite支持的动态导入方式
try {
// 根据不同的图片路径返回对应的导入URL
// 注意:这种方式需要为每个图片路径单独添加映射
// 您可以根据实际需要扩展这个映射表
const imageMap = {
'img/honor1.png': new URL('../assets/img/honor1.png', import.meta.url).href,
'img/honor2.png': new URL('../assets/img/honor2.png', import.meta.url).href,
'img/honor3.png': new URL('../assets/img/honor3.png', import.meta.url).href,
'img/dynamic1.png': new URL('../assets/img/dynamic1.png', import.meta.url).href,
'img/dynamic2.png': new URL('../assets/img/dynamic2.png', import.meta.url).href,
// 可以根据需要添加更多图片路径映射
};
// 如果找到对应的映射返回映射的URL
if (imageMap[path]) {
return imageMap[path];
} else {
// 如果没有找到映射,尝试使用默认方式
console.warn('图片路径未在映射表中找到:', path);
return new URL(`../assets/${path}`, import.meta.url).href;
}
} catch (error) {
// 如果构建失败,打印错误信息并返回空字符串
console.error('图片加载失败:', error, '路径:', path);
return '';
}
}
export function highlightKeywords(text, keywords, options = {}) {
// 处理边界情况:文本或关键字为空时直接返回原文本
if (!text || !keywords || (Array.isArray(keywords) && keywords.length === 0)) {
return text;
}
// 合并默认配置
const {
color = '#2D00F5',
ignoreCase = true,
tag = 'span'
} = options;
// 统一将关键字转为数组格式(兼容单个关键字传入)
const keywordList = Array.isArray(keywords) ? keywords : [keywords];
// 过滤空关键字
const validKeywords = keywordList.filter(keyword => keyword && keyword.trim());
if (validKeywords.length === 0) return text;
// 构建正则表达式:转义特殊字符 + 忽略大小写 + 全局匹配
const escapeRegExp = (str) => str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
const regexStr = validKeywords.map(escapeRegExp).join('|');
const regex = new RegExp(regexStr, ignoreCase ? 'gi' : 'g');
// 替换匹配的关键字,用指定标签包裹并设置颜色
return text.replace(regex, (match) => {
return `<${tag} style="color: ${color};">${match}</${tag}>`;
});
}