File size: 6,934 Bytes
1b72d7e |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 |
// 封装异步加载资源的方法
import { memo } from 'react'
/**
* 判断是否客户端
* @returns {boolean}
*/
export const isBrowser = typeof window !== 'undefined'
/**
* google机器人
* @returns
*/
export const isSearchEngineBot = () => {
if (typeof navigator === 'undefined') {
return false
}
// 获取用户代理字符串
const userAgent = navigator.userAgent;
// 使用正则表达式检测是否包含搜索引擎爬虫关键字
return /Googlebot|bingbot|Baidu/.test(userAgent)
}
/**
* 组件持久化
*/
export const memorize = (Component) => {
const MemoizedComponent = (props) => {
return <Component {...props} />
}
return memo(MemoizedComponent)
}
// 转换外链
export function sliceUrlFromHttp(str) {
// 检查字符串是否包含http
if (str.includes('http:') || str.includes('https:')) {
// 如果包含,找到http的位置
const index = str.indexOf('http');
// 返回http之后的部分
return str.slice(index, str.length);
} else {
// 如果不包含,返回原字符串
return str;
}
}
// 检查是否外链
export function checkContainHttp(str) {
// 检查字符串是否包含http
if (str.includes('http:') || str.includes('https:')) {
// 如果包含,找到http的位置
return str.indexOf('http') > -1
} else {
// 不包含
return false;
}
}
/**
* 加载外部资源
* @param url 地址 例如 https://xx.com/xx.js
* @param type js 或 css
* @returns {Promise<unknown>}
*/
export function loadExternalResource(url, type) {
// 检查是否已存在
const elements = type === 'js' ? document.querySelectorAll(`[src='${url}']`) : document.querySelectorAll(`[href='${url}']`)
return new Promise((resolve, reject) => {
if (elements.length > 0 || !url) {
resolve(url)
return url
}
let tag
if (type === 'css') {
tag = document.createElement('link')
tag.rel = 'stylesheet'
tag.href = url
} else if (type === 'font') {
tag = document.createElement('link')
tag.rel = 'preload'
tag.as = 'font'
tag.href = url
} else if (type === 'js') {
tag = document.createElement('script')
tag.src = url
}
if (tag) {
tag.onload = () => {
console.log('Load Success', url)
resolve(url)
}
tag.onerror = () => {
console.log('Load Error', url)
reject(url)
}
document.head.appendChild(tag)
}
})
}
/**
* 查询url中的query参数
* @param {}} variable
* @returns
*/
export function getQueryVariable(key) {
const query = isBrowser ? window.location.search.substring(1) : ''
const vars = query.split('&')
for (let i = 0; i < vars.length; i++) {
const pair = vars[i].split('=')
if (pair[0] === key) { return pair[1] }
}
return (false)
}
/**
* 获取 URL 中指定参数的值
* @param {string} url
* @param {string} param
* @returns {string|null}
*/
export function getQueryParam(url, param) {
// 移除哈希部分
const urlWithoutHash = url.split('#')[0];
const searchParams = new URLSearchParams(urlWithoutHash.split('?')[1]);
return searchParams.get(param);
}
/**
* 深度合并两个对象
* @param target
* @param sources
*/
export function mergeDeep(target, ...sources) {
if (!sources.length) return target
const source = sources.shift()
if (isObject(target) && isObject(source)) {
for (const key in source) {
if (isObject(source[key])) {
if (!target[key]) Object.assign(target, { [key]: {} })
mergeDeep(target[key], source[key])
} else {
Object.assign(target, { [key]: source[key] })
}
}
}
return mergeDeep(target, ...sources)
}
/**
* 是否对象
* @param item
* @returns {boolean}
*/
export function isObject(item) {
return (item && typeof item === 'object' && !Array.isArray(item))
}
/**
* 是否可迭代
* @param {*} obj
* @returns
*/
export function isIterable(obj) {
return obj != null && typeof obj[Symbol.iterator] === 'function'
}
/**
* 深拷贝对象
* 根据源对象类型深度复制,支持object和array
* @param {*} obj
* @returns
*/
export function deepClone(obj) {
if (Array.isArray(obj)) {
// If obj is an array, create a new array and deep clone each element
return obj.map(item => deepClone(item))
} else if (obj && typeof obj === 'object') {
const newObj = {}
for (const key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
if (obj[key] instanceof Date) {
newObj[key] = new Date(obj[key].getTime()).toISOString()
} else {
newObj[key] = deepClone(obj[key])
}
}
}
return newObj
} else {
return obj
}
}
/**
* 延时
* @param {*} ms
* @returns
*/
export const delay = ms => new Promise(resolve => setTimeout(resolve, ms))
/**
* 获取从第1页到指定页码的文章
* @param pageIndex 第几页
* @param list 所有文章
* @param pageSize 每页文章数量
* @returns {*}
*/
export const getListByPage = function (list, pageIndex, pageSize) {
return list.slice(
0,
pageIndex * pageSize
)
}
/**
* 判断是否移动设备
*/
export const isMobile = () => {
let isMobile = false
if (!isBrowser) {
return isMobile
}
// 这个判断会引发 TypeError: navigator.userAgentData.mobile is undefined 问题,导致博客无法正常工作
// if (!isMobile && navigator.userAgentData.mobile) {
// isMobile = true
// }
if (!isMobile && (/Mobi|Android|iPhone/i.test(navigator.userAgent))) {
isMobile = true
}
if (/Android|iPhone|iPad|iPod/i.test(navigator.platform)) {
isMobile = true
}
if (typeof window.orientation !== 'undefined') {
isMobile = true
}
return isMobile
}
/**
* 扫描页面上的所有文本节点,将url格式的文本转为可点击链接
* @param {*} node
*/
export const scanAndConvertToLinks = (node) => {
if (node.nodeType === Node.TEXT_NODE) {
const text = node.textContent;
const urlRegex = /https?:\/\/[^\s]+/g;
let lastIndex = 0;
let match;
const newNode = document.createElement('span');
while ((match = urlRegex.exec(text)) !== null) {
const beforeText = text.substring(lastIndex, match.index);
const url = match[0];
if (beforeText) {
newNode.appendChild(document.createTextNode(beforeText));
}
const link = document.createElement('a');
link.href = url;
link.target = '_blank'
link.textContent = url;
newNode.appendChild(link);
lastIndex = urlRegex.lastIndex;
}
if (lastIndex < text.length) {
newNode.appendChild(document.createTextNode(text.substring(lastIndex)));
}
node.parentNode.replaceChild(newNode, node);
} else if (node.nodeType === Node.ELEMENT_NODE) {
for (const childNode of node.childNodes) {
scanAndConvertToLinks(childNode);
}
}
}
|