npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@zenview/micro-utils

v0.1.19

Published

[TOC]

Downloads

65

Readme

micro-utils

[TOC]

简介

描述:micro-utils 是通用抽象工具类,里面封装了如 "indexDB" 数据库使用、“SocketEmitter”消息订阅、“cache”前端本地存储...等常用公共方法,使用微应用脚手架构建项时目已默认安装,可直接使用。

Git 仓库地址:https://git.topvdn.com/micro-business/micro-utils

依赖安装:

//示例为yarn安装,也可以使用npm安装
yarn add @zenview/micro-utils

使用示例:

//使用示例
import { LM_DB, cache } from '@zenview/micro-utils';

const db = new LM_DB('functionCount');

const headers = {
  Authorization: cache.getCache('token', 'session'),
};

cache

前端缓存:封装了 sessionStorage、localStorage、Cookie 的读写方法。 注意:type 不传默认为“local”,存储对数据使用了 JSON.stringify 处理,引用类型无需再次转换。

代码演示


//使用示例
import {cache } from '@zenview/micro-utils';

cache.setCache('cache', data, 'session');

const data = cache.getCache('cache', 'session'),

API

type CacheType = 'session' | 'local' | 'cookie';

cache.getCache(key: string, type?: CacheType): any;
cache.setCache(key: string, value: any, type?: CacheType): any;
cache.getUserCache(key: string, type?: CacheType): any;
cache.setUserCache(key: string, value: any, type?: CacheType): any;

Params

| 参数 | 说明 | 类型 | | :---: | :------: | :----------------------: | | key | 唯一索引 | string | | value | 存储数据 | any | | type | 存储类型 | session / local / cookie |

LM_DB

前端数据库 indexDB 公共方法

代码演示

//使用示例
import { LM_DB } from '@zenview/micro-utils';
const db = new LM_DB('dbName');
//存储
db.put({ id: 123, ...data }).then((res) => {
  console.log(res);
});

//读取
const res = await db.get({ id: 123 });

API

class LM_DB implements LMDBInterface {
  constructor(schemaName: string);
  put(params: { [key: string]: any; id: string; expireTime?: number } & any): Promise<null>;
  get(params: { id: string }): Promise<{ [key: string]: any }>;
}

Params

| 参数 | 说明 | 类型 | | :--------: | :--: | :----: | | schemaName | 表名 | string | | id | 主键 | string |

SocketEmitter

前端消息事件订阅方法,包含 webSocket 使用

代码演示

//使用示例
import { SocketEmitter } from '@zenview/micro-utils';
const db = new LM_DB('dbName');
//发送消息
SocketEmitter.emit('emitterName', data);
//开启订阅接收消息
SocketEmitter.on('emitterName', (data) => {});
//关闭订阅
SocketEmitter.off('emitterName', (data) => {});
//开启webSocket
SocketEmitter.connect('/socket.io', null);

API

export default interface SocketEmitterInterface {
  connect(url: string, options: { [key]: any });
  disconnect(): void;
  subscribe<T>(eventName: string, listener: (e: T) => void): void;
  unsubscribe<T>(eventName: string, listener: (e: T) => void);
  on<T>(eventName: string, listener: (e: T) => void): void;
  off<T>(eventName: string, listener: (e: T) => void);
  emit<T>(eventName: string, data: T): void;
}

Params

| 参数 | 说明 | 类型 | | :-------: | :--------------: | :------: | | eventName | 事件名称 | string | | listener | 事件接收回调方法 | function |

uuid

通用唯一标识

代码演示

//使用示例
import { uuid } from '@zenview/micro-utils';
const id = uuid();

API

function uuid(): string;

formatTimeStamp

时间戳格式化 注意:默认格式 YYYY.MM.DD HH:mm:ss

代码演示

//使用示例
import { formatTimeStamp } from '@zenview/micro-utils';
const captureTime = formatTimeStamp(1617692139000);

API

function formatTimeStamp(value: number | string, fomart?: string): string;

Params

| 参数 | 说明 | 类型 | | :----: | :--------: | :-------------: | | value | 日期时间戳 | number / string | | fomart | 日期格式 | string |

queryHelper

url 方法 queryFormat:处理 location.search 的方法,将字符串转换成 json objectToQuery:对象转化为&连接符拼接

代码演示

//使用示例
import { queryHelper } from '@zenview/micro-utils';
const query = queryHelper.queryFormat(location.search);

API

interface QueryMethods {
  queryFormat(search: string): { [key: string]: string };
  objectToQuery(obj: { [key: string]: string | number | boolean }): string;
  /**
   * @desc 路由地址比对
   * @param pathname1 完整路由地址
   * @param pathname2 可为模糊路由地址匹配 /xxx/:id
   */
  comparisonPahtname(pathname1: string, pathname2: string): boolean;
}

treeHelper

computTreeList:一维数组转换树结构公共方法 computPlaceTree:业务方法,转换场所数据

代码演示

//使用示例
import { treeHelper } from '@zenview/micro-utils';
const tree = treeHelper.computTreeList(List);
const placeTree = treeHelper.computPlaceTree(place.placeListListWithCameraCount);

API

interface TreeMethods {
  computPlaceTree<T>(list: Array<T>, isNoDeep?: boolean): Array<T>;
  computTreeList<T>(list: Array<T>, id?: string, pid?: string, isNoDeep?: boolean): Array<T>;
}

Params

| 参数 | 说明 | 类型 | | :------: | :------------: | :-----: | | list | 原数据一维数组 | array | | isNoDeep | 是否深拷贝 | boolean | | id | 主键名 | string | | pid | 父主键名 | string |

resizeHelper

computTreeList:一维数组转换树结构公共方法 computPlaceTree:业务方法,转换场所数据

代码演示

dom元素大小调整事件

//使用示例
import { resizeHelper } from '@zenview/micro-utils';
  useEffect(() => {
    let timer = null;
    const fn = () => {
      clearTimeout(timer);
      timer = setTimeout(() => {
        setState((old) => ({ ...old, forceUpdateKey: Date.now() }));
      }, 200);
    };
    const dom = layoutRef.current;
    const resize = new resizeHelper(dom);
    resize.onResize(fn);
    return () => {
      resize.offResize(fn);
      resize.dispose();
    };
  }, []);

API

class ResizeMethods {
  constructor(ele: HTMLElement): void;
  onResize(handle: (e: MouseEvent) => void): void;
  offResize(handle: (e: MouseEvent) => void): void;
  dispose(): void;
}

download

创建 A 标签下载

代码演示

//使用示例
import { download } from '@zenview/micro-utils';
download({ url: path, title });

API

export function download(params: { url: string; title: string; target?: '_blank' | '_self' }): void;

imageMethods

图片转换方法

代码演示

//使用示例
import { imageMethods } from '@zenview/micro-utils';

//图片base64转换为blob
const oldFile = imageMethods.base64ToBlob(base64Url);
//转base64下载网络图片
imageMethods.downloadLocalImage(imgUrl, title);
//图片地址转base64
imageMethods.urlToBase64({ imgUrl, imgQuality: 0.8 }, (base64Url, err) => {});

API

interface ImageMethods {
  downloadLocalImage(imgUrl: string, title?: string): void;
  urlToBase64(opt: { imgUrl: string; imgQuality?: number; width?: number; height?: number }, callback: Function): void;
  drawImage(opt: { target: HTMLImageElement; width: number; height: number; imgType?: string; imgQuality?: number }): string;
  base64ToBlob(base64Url: string): Blob;
}

isEqual

数据深比较

代码演示

//使用示例
import { isEqual } from '@zenview/micro-utils';

const isBool = !isEqual(obj, obj2);

API

function isEqual(objValue: object, othValue: object): boolean;

fullScreenHelper

浏览器窗口全屏方法

代码演示

//使用示例
import { fullScreenHelper } from '@zenview/micro-utils';
//判断是否全屏
const fullScreenEle = fullScreenHelper.isFullscreen();
if (fullScreenEle) {
  //退出全屏
  fullScreenHelper.exitFullscreen();
} else {
  //进入全屏
  fullScreenHelper.fullscreen('dom');
}

API

interface FullScreenMethods {
  fullscreen(ele: HTMLElement): void;
  exitFullscreen(): void;
  fullscreenEnabled(): boolean;
  isFullscreen(): HTMLElement | boolean;
  fullScreenListener(type: 'addEventListener' | 'removeEventListener', fullscreenchange: (e: MouseEvent) => void);
}

thousand | submidstr | copy

thousand:千分号格式化数字 submidstr:文字中间省略号 copy:复制文字

API

function thousand(num: number): string;
function copy(text: string): void;
function submidstr(str: string, replaceLength: number): string;