Commit 04f9c204 authored by haiyoucuv's avatar haiyoucuv

内置工具包built-in

埋点
parent 1010727d
...@@ -27,8 +27,6 @@ class App extends Component { ...@@ -27,8 +27,6 @@ class App extends Component {
async componentDidMount() { async componentDidMount() {
await store.getFrontVariable(); await store.getFrontVariable();
store.initRule();
API.index({aaaa: "啊实打实"});
} }
render() { render() {
......
import { loadSvga } from '@spark/svgaplayer'
// import * as FYGE from 'fyge';
// import { Howl } from 'howler';
import { RES_PATH } from '../../sparkrc'
/**
* 预加载资源(/png|jpg|jpeg|svga|spi|json|mp3|wav/)
* @param {string[]} urlList 资源地址列表
* @param {number} batchNum 每批并行加载的资源个数(一般来说该数字越大整体加载速度越快,但加载前期会更卡顿)
* @param {Function} [onProgress] 加载进度回调,每加载完一个资源回调一次,入参为进度值(0,1]
* @returns {Promise} 返回一个只会resolve(loadedData)的promise,loadedData保存了所有预加载好的资源,可通过相对路径索引
* @example
* //例
* const loadedData = await PreloadAsset(urlList, 10, onProgress);
* const image = loadedData['image/fish.png'];
* const svgaData = loadedData['svga/fish.svga'];
* const spiData = loadedData['spine/fish.spi'];
* const lottieData = loadedData['lottie/fish.json'];
*/
export function preloadAsset(urlList, batchNum, onProgress) {
return new Promise((resolve) => {
/** 要加载资源总数 */
const totalNum = urlList.length;
/** 要加载的资源索引 */
let assetIndex = -1;
/** 已加载完毕的资源个数 */
let loadedNum = 0;
/** 存放加载好的数据,用地址索引 */
const loadedData = {};
/** 加载逻辑 */
const doLoad = async () => {
if (loadedNum >= totalNum) {
totalNum == 0 && onProgress && onProgress(1); // 无加载资源时,即为假loading
resolve(loadedData); // 加载完毕
} else {
assetIndex++;
if (assetIndex >= totalNum) return
const key = urlList[assetIndex];
const url = RES_PATH + urlList[assetIndex];
const result = await loadOneAsset(url);
if (!result) {
console.warn('加载异常', url);
}
loadedData[key] = result;
loadedNum++;
onProgress && onProgress(loadedNum / totalNum);
doLoad();
}
}
batchNum = batchNum || 1;
for (let index = 0; index < batchNum; index++) {
doLoad();
}
})
}
/**
* 加载一个资源
* @param {string} url 地址
*/
async function loadOneAsset(url) {
const fileType = url.split('.').pop();
switch (true) {
case (/png|jpg|jpeg/).test(fileType):
return await loadOneImg(url);
case (/svga/).test(fileType):
return await loadOneSvga(url);
// case (/spi/).test(fileType):
// return await loadOneSpi(url);
// case (/json/).test(fileType):
// return await loadOneJson(url);
// case (/mp3|wav/).test(fileType):
// return await loadOneAudio(url);
default:
console.warn('非法资源', url);
return false;
}
}
/**
* 加载一张图片
* @param {string} url 地址
*/
function loadOneImg(url) {
const isWebp = localStorage.isWebp;
return new Promise(resolve => {
const img = new Image();
img.onload = () => resolve(img);
img.onerror = err => {
console.warn('load', url, err);
resolve(false)
};
img.crossOrigin = 'Anonymous'
img.src = url + (isWebp ? '?x-oss-process=image/format,webp' : '');
})
}
/**
* 加载一个svga
* @param {string} url 地址
*/
function loadOneSvga(url) {
return new Promise(resolve => {
loadSvga(url).then((data) => resolve(data[0])).catch(err => {
console.warn('load', url, err);
resolve(false)
});
})
}
// /**
// * 加载一个spine
// * @param {string} url 地址
// */
// function loadOneSpi(url) {
// return new Promise(resolve => {
// FYGE.loadSpine(url, spineData => {
// resolve(spineData);
// }, err => {
// console.warn('load', url, err);
// resolve(false);
// })
// })
// }
// /**
// * 加载一个Json
// * @param {string} url 地址
// */
// function loadOneJson(url) {
// return new Promise(resolve => {
// FYGE.GlobalLoader.loadJson((result, res) => {
// if (result) {
// resolve(res);
// } else {
// console.warn('load fail', url);
// resolve(false);
// }
// }, url)
// })
// }
// /**
// * 加载一个音频
// * @param {string} url 地址
// */
// function loadOneAudio(url) {
// return new Promise(resolve => {
// const sound = new Howl({
// src: url,
// onload: () => resolve(sound),
// onloaderror: err => {
// console.warn('load fail', url, err);
// resolve(false);
// },
// });
// })
// }
/**
* @description: 小程序跳转
* @param {*}
* @return {*}
*/
export const miniGoUrl = (url) => {
wx.miniProgram.navigateTo({ url: url });
}
/**
* 判断是否为ios系统
*/
export function isIos() {
return navigator.userAgent.match(/iphone|ipod|ipad/gi)
}
/** 判断微信环境 */
export function isWeChat() {
const ua = window.navigator.userAgent.toLowerCase()
return ua.match(/MicroMessenger/i) == 'micromessenger'
}
/**
* 判断是否为ios系统
*/
export function isIos() {
return navigator.userAgent.match(/iphone|ipod|ipad/gi)
}
...@@ -9,36 +9,13 @@ export function getQueryString(params) { ...@@ -9,36 +9,13 @@ export function getQueryString(params) {
return paramArr.join("&"); return paramArr.join("&");
} }
export {
_throttle, // 节流
useThrottle, // 节流,函数组件
_debounce, // 防抖
getCookie, // 获取cookie的值
getUrlParam, // 获取url参数
delUrlParam, // 删除url中的参数
subStringCE, // 截取字符串 中2英1
check2Object, // 判断两个对象相等
getThousandToK, // 转换k
dateFormatter, // 日期格式化
dealTime, // 时间格式化
second2Date, // 秒转时间对象
waitTime, // 等待一段时间再执行
randomNum, // 获取区间随机数 [min,max)
shuffleArr, // 随机打乱数组
flatten, // 数据扁平化
onCtrScroll, // 控制滚动--兼容ios
trimSpace, // 去除字符串空格
GetCurrSkinId, // 获取当前链接皮肤id
windowJumpUrl // window的跳转链接
}
/** /**
* @description: 函数节流,普通防连点 * @description: 函数节流,普通防连点
* @param {(Function, number?)}
* @return {Function} * @return {Function}
* @param fun
* @param delay
*/ */
const _throttle = (fun, delay = 2000) => { export const _throttle = (fun, delay = 2000) => {
let last: number; let last: number;
return function () { return function () {
const now = +new Date(); const now = +new Date();
...@@ -87,7 +64,7 @@ export const _asyncThrottle = (fun, delay = 2000) => { ...@@ -87,7 +64,7 @@ export const _asyncThrottle = (fun, delay = 2000) => {
}; };
function useThrottle(fn, delay = 2000, dep = []) { export function useThrottle(fn, delay = 2000, dep = []) {
const {current} = useRef({fn, timer: null}); const {current} = useRef({fn, timer: null});
useEffect(function () { useEffect(function () {
current.fn = fn; current.fn = fn;
...@@ -105,10 +82,12 @@ function useThrottle(fn, delay = 2000, dep = []) { ...@@ -105,10 +82,12 @@ function useThrottle(fn, delay = 2000, dep = []) {
/** /**
* @description: 函数防抖 * @description: 函数防抖
* @param {(Function, number?, boolean? )}
* @return {Function} * @return {Function}
* @param fn
* @param wait
* @param immediate
*/ */
const _debounce = (fn, wait = 2000, immediate = false) => { export const _debounce = (fn, wait = 2000, immediate = false) => {
let timer = null let timer = null
return function () { return function () {
const later = function () { const later = function () {
...@@ -126,7 +105,7 @@ const _debounce = (fn, wait = 2000, immediate = false) => { ...@@ -126,7 +105,7 @@ const _debounce = (fn, wait = 2000, immediate = false) => {
* 获取cookie的值 * 获取cookie的值
* @param {*} cookieName * @param {*} cookieName
*/ */
function getCookie(cookieName) { export function getCookie(cookieName) {
const strCookie = document.cookie; const strCookie = document.cookie;
const arrCookie = strCookie.split('; '); const arrCookie = strCookie.split('; ');
for (let i = 0; i < arrCookie.length; i++) { for (let i = 0; i < arrCookie.length; i++) {
...@@ -142,7 +121,7 @@ function getCookie(cookieName) { ...@@ -142,7 +121,7 @@ function getCookie(cookieName) {
* 获取url参数 * 获取url参数
* @param {string} name * @param {string} name
*/ */
function getUrlParam(name) { export function getUrlParam(name) {
const search = window.location.search; const search = window.location.search;
const matched = search const matched = search
.slice(1) .slice(1)
...@@ -155,7 +134,7 @@ function getUrlParam(name) { ...@@ -155,7 +134,7 @@ function getUrlParam(name) {
* @param {*} url * @param {*} url
* @param {*} arg * @param {*} arg
*/ */
function delUrlParam(url, paramKey) { export function delUrlParam(url, paramKey) {
const _url = new URL(url) const _url = new URL(url)
const search = new URLSearchParams(_url.search) const search = new URLSearchParams(_url.search)
search.delete(paramKey) search.delete(paramKey)
...@@ -169,7 +148,7 @@ function delUrlParam(url, paramKey) { ...@@ -169,7 +148,7 @@ function delUrlParam(url, paramKey) {
* @param format 字符串,需要的格式例如:'yyyy/MM/dd hh:mm:ss' * @param format 字符串,需要的格式例如:'yyyy/MM/dd hh:mm:ss'
* @returns {String} * @returns {String}
*/ */
const dateFormatter = (date, format = "yyyy/MM/dd") => { export const dateFormatter = (date, format = "yyyy/MM/dd") => {
if (!date) return "-"; if (!date) return "-";
date = new Date( date = new Date(
// @ts-ignore // @ts-ignore
...@@ -204,7 +183,7 @@ const dateFormatter = (date, format = "yyyy/MM/dd") => { ...@@ -204,7 +183,7 @@ const dateFormatter = (date, format = "yyyy/MM/dd") => {
}; };
/** 时间格式化 */ /** 时间格式化 */
const dealTime = (msTime) => { export const dealTime = (msTime) => {
const time = msTime / 1000; const time = msTime / 1000;
let hour: number | string = Math.floor(time / 60 / 60) % 24; let hour: number | string = Math.floor(time / 60 / 60) % 24;
let minute: number | string = Math.floor(time / 60) % 60; let minute: number | string = Math.floor(time / 60) % 60;
...@@ -219,7 +198,7 @@ const dealTime = (msTime) => { ...@@ -219,7 +198,7 @@ const dealTime = (msTime) => {
* 转换k * 转换k
* @param {*} num * @param {*} num
*/ */
function getThousandToK(num) { export function getThousandToK(num) {
let s_x; let s_x;
if (num >= 1000) { if (num >= 1000) {
let result = num / 1000; let result = num / 1000;
...@@ -245,7 +224,7 @@ function getThousandToK(num) { ...@@ -245,7 +224,7 @@ function getThousandToK(num) {
* @param {*} str * @param {*} str
* @param {*} sub_length * @param {*} sub_length
*/ */
function subStringCE(str, sub_length) { export function subStringCE(str, sub_length) {
const temp1 = str.replace(/[^\x20-\xff]/g, "**"); const temp1 = str.replace(/[^\x20-\xff]/g, "**");
const temp2 = temp1.substring(0, sub_length); const temp2 = temp1.substring(0, sub_length);
const x_length = temp2.split("*").length - 1; const x_length = temp2.split("*").length - 1;
...@@ -266,7 +245,7 @@ function subStringCE(str, sub_length) { ...@@ -266,7 +245,7 @@ function subStringCE(str, sub_length) {
* @param {*} arr * @param {*} arr
* @returns * @returns
*/ */
function shuffleArr(arr) { export function shuffleArr(arr) {
for (let i = arr.length - 1; i >= 0; i--) { for (let i = arr.length - 1; i >= 0; i--) {
const randomIndex = Math.floor(Math.random() * (i + 1)) const randomIndex = Math.floor(Math.random() * (i + 1))
const itemAtIndex = arr[randomIndex] const itemAtIndex = arr[randomIndex]
...@@ -283,7 +262,7 @@ function shuffleArr(arr) { ...@@ -283,7 +262,7 @@ function shuffleArr(arr) {
* @param {*} max * @param {*} max
* @return {*} * @return {*}
*/ */
function randomNum(min, max) { export function randomNum(min, max) {
return Math.floor(Math.random() * (max - min)) + min return Math.floor(Math.random() * (max - min)) + min
} }
...@@ -293,14 +272,14 @@ function randomNum(min, max) { ...@@ -293,14 +272,14 @@ function randomNum(min, max) {
* @param {*} arr * @param {*} arr
* @return {*} * @return {*}
*/ */
function flatten(arr) { export function flatten(arr) {
return arr.reduce((result, item) => { return arr.reduce((result, item) => {
return result.concat(Array.isArray(item) ? flatten(item) : item) return result.concat(Array.isArray(item) ? flatten(item) : item)
}, []) }, [])
} }
/** 判断两个对象相等 */ /** 判断两个对象相等 */
const check2Object = (obj1, obj2) => { export const check2Object = (obj1, obj2) => {
const o1 = obj1 instanceof Object const o1 = obj1 instanceof Object
const o2 = obj2 instanceof Object const o2 = obj2 instanceof Object
if (!o1 || !o2) { /* 判断不是对象 */ if (!o1 || !o2) { /* 判断不是对象 */
...@@ -331,7 +310,7 @@ const check2Object = (obj1, obj2) => { ...@@ -331,7 +310,7 @@ const check2Object = (obj1, obj2) => {
* second: String * second: String
* }} * }}
*/ */
const second2Date = (totalSecond) => { export const second2Date = (totalSecond) => {
const millisecond = totalSecond % 1000 const millisecond = totalSecond % 1000
totalSecond = totalSecond / 1000 totalSecond = totalSecond / 1000
...@@ -378,15 +357,15 @@ const second2Date = (totalSecond) => { ...@@ -378,15 +357,15 @@ const second2Date = (totalSecond) => {
* 等待一段时间再执行 * 等待一段时间再执行
* @param {number} time 等待的时间ms * @param {number} time 等待的时间ms
*/ */
function waitTime(time) { export function waitTime(time) {
return new Promise(resolve => setTimeout(resolve, time)) return new Promise(resolve => setTimeout(resolve, time))
} }
/** 控制滚动--兼容ios */ /** 控制滚动--兼容ios */
const bodyScroll = (event) => { export const bodyScroll = (event) => {
event.preventDefault(); event.preventDefault();
} }
const onCtrScroll = (flag = true) => { export const onCtrScroll = (flag = true) => {
if (flag) { // 禁止滚动 if (flag) { // 禁止滚动
document.body.addEventListener('touchmove', bodyScroll, {passive: false}); document.body.addEventListener('touchmove', bodyScroll, {passive: false});
} else { // 开启滚动 } else { // 开启滚动
...@@ -399,7 +378,7 @@ const onCtrScroll = (flag = true) => { ...@@ -399,7 +378,7 @@ const onCtrScroll = (flag = true) => {
* @param {string} str * @param {string} str
* @returns * @returns
*/ */
const trimSpace = (str) => { export const trimSpace = (str) => {
let result; let result;
result = str.replace(/(^\s+)|(\s+$)/g, ""); result = str.replace(/(^\s+)|(\s+$)/g, "");
result = result.replace(/\s/g, ""); result = result.replace(/\s/g, "");
...@@ -411,7 +390,7 @@ const trimSpace = (str) => { ...@@ -411,7 +390,7 @@ const trimSpace = (str) => {
* 获取当前皮肤id * 获取当前皮肤id
* @returns * @returns
*/ */
const GetCurrSkinId = () => { export const GetCurrSkinId = () => {
// eslint-disable-next-line no-useless-escape // eslint-disable-next-line no-useless-escape
const matched = location.pathname.match(/\/([^\/]*).html/); const matched = location.pathname.match(/\/([^\/]*).html/);
const currSkinId = matched ? matched && matched[1] : '' const currSkinId = matched ? matched && matched[1] : ''
...@@ -425,10 +404,3 @@ export const getCustomShareId = () => { ...@@ -425,10 +404,3 @@ export const getCustomShareId = () => {
console.log('自定义活动页id', shareId); console.log('自定义活动页id', shareId);
return shareId; return shareId;
}; };
/** 跳转 */
const windowJumpUrl = (url: string) => {
if (url) {
location.href = url;
}
};
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment