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

lofter-utils

v3.8.12

Published

项目中常用的工具集

Downloads

129

Readme

lofter-utils

项目中常用的工具集

安装

npm i lofter-utils --save

开发指南

  • 直接在 src 下新建 ts 文件封装自己的工具即可
  • examples 可用来调试,直接新建文件即可

使用文档

策略模式校验表单的值

基础用法

import {
  validator
} from 'lofter-utils'

const name = '深渊巨口'
const phone = '123456'

const validate = () => {
  // 使用校验策略校验表单字段以及返回错误信息
  validator.add(name, [{
    strategy: 'isNonEmpty',
    errMsg: '请输入姓名!',
    key: 'isNonEmptyName'
  }])
  validator.add(phone, [{
    strategy: 'isNonEmpty',
    errMsg: '请输入手机号!',
    key: 'isNonEmptyPhone'
  }, {
    strategy: 'isMobile',
    errMsg: '请输入正确手机号!',
    key: 'isMobile'
  }])
  // 开始校验
  return validator.start()
}

const onSubmit = () => {
  const errMsg = validate()

  // 校验不通过,弹出toast提示
  if (errMsg) {
    return toast({
      text: errMsg
    })
  }

  // 校验通过逻辑
  request.post(xxxx)
}

查看已有的校验策略

import {
  strategies
} from 'lofter-utils'

strategies.getValues()
// 输出: [
  'isNonEmpty',
  'isMobile',
  'isPassword',
  'isChinese',
  '...后续持续添加'
]

注册校验策略(已有的策略不满足开发场景时使用)

import {
  strategies,
  validator,
} from 'lofter-utils'

// 注册
strategies.register({
  name: 'isTest',
  exec: (value: string, errMsg: string) => {
    if (/^\d+$/.test(value)) {
        return
    }
    return errMsg
  }
})

// 使用
validator.add(name, [{
  strategy: 'isTest',
  errMsg: '请输入数字作为姓名!',
  key: 'isTest'
}])

自定义 hooks

集合了nw-hooks,做原样导出

useAkModal(antdModal)

调用 showModal 方法就可以显示模态框,调用 hideModal 可关闭

example

./modal.js

import { useAkModal } from 'lofter-utils'
import {
  Modal,
  Button
} from 'antd'
import React from 'react'

// MyModal方法必须接收以下几个参数
- visible
- onCancel
- onOk

由use-ak-modal传入,用于Modal组件的显示,取消,确定

/**
* 如果需要传递其他参数,可以自行添加
* 比如initValues设置初始化数据
*/
interface Props {
  visible: boolean;
  onCancel: () => void;
  onOk?: (params?: any) => void;
  id?: number;
}

const MyModal = ({
  visible, // 必须
  onCancel, // 必须
  onOk, // 可选
  id // 通过show方法传入的,id等业务所需的其他参数,
}: Props) => {

  return (
    <Modal
     title="测试弹窗"
     visible={visible}
     onCancel={onCancel}
     onOk={() => {
       // 点击确定后的回调,可传入任意参数
       onOk?.('ok')
     }}
     id={id}
    >
      <AkRender
        form={form}
        schema={xxx}
      />
    </Modal>
  )
}

export default ModalForm

./index.js

function App() {
  // 返回show与hide方法,名字可以自己定
  const [showModal, hideModal] = useModal(MyModal)

  return (
    <>
      <Button onClick={() => {
        showModal({
          okCb: (params?: any) => { console.log('确定后的回调参数', params) }, // 点击确定后的回调,可选
          cancelCb: () => { console.log('我取消了') }, // 点击取消后的回调,可选
          id: 9527 //也可以传入其他参数,可选
        })
      }}>
        点我
      </Button>
      <Button
        onClick={() => {
          showModal()
        }}
      >
        编辑
      </Button>
    </>
  )
}

request

通用的请求库,使用文档与umi-request相同

import request form 'lofter-utils/lib/request'

// 给每个请求加前缀
request.extendOptions({
  prefix: '/api/newbackend',
})

// 接口报错使用定制的toast
request.extendOptions({
  errorHandler: (err) => {
    // 可以自行使用toast覆盖
    message.success('err', err)
    return Promise.reject(err)
  }
})

// 处理非200且正常状态码
request.get('/spread/cp/generateName', {
  params: {
    firstName,
    secondName,
  },
  codeErrorHandler: (res) => {
    if (res.code !== 200 && res.code !== 3001) {
      return false
    }
    return true
  }
}).then(({ data, code }) => {
  if (code === 3001) {
    showModal()
  }
  if (code === 200) {
    xxx
  }
})

utils

import {
  formatConsole,
  saveDecimalPoint,
  filterEmptyValue
} from 'lofter-utils'
  • formatImageSizeAndType

  • secondFormat

  • getBase64

  • addZero

  • formatImageType

  • formatImageSize

  • formatConsole(text: T) 绿底白字进行 console.log 输出

  • saveDecimalPoint(num: number, digits: number = 2) 保留几位小数

  • filterEmptyValue(obj: anyObj) 过滤空键值对的对象

  • escapeHtml(text: sting) 转义 html 标签

  • unescapeHTML

  • initShare({

    title: string; // 分享 title

    desc: string; // 分享描述

    url?: string; // 分享 url,默认 window.location.href

    weiboText?: string; // 分享到微博的文案,默认 title + desc + url

    shareImg?: string; // 分享小图

    appShareTitle?: string; // 转载到客户端标题,默认取 title

    appShareDesc?: string; // 转载到客户端描述,默认取 desc

    appShareImg?: string; // 转载到客户端图片,默认取 shareImg }) 同时配置客户端与微信分享

detect

平台检测组件

import { isWeixin } from 'lofter-utils'

更多使用文档

share

分享组件,原样导出 nw-share

import { setOrUpdate, share } from 'lofter-utils'

更多使用文档

log-distribution

打点分流组件,原样导出 nw-log-distribution

import {
  ENV,
  APP_KEY,
  HubLog as Log
} from 'lofter-utils';

更多使用文档

app-lofter

打开客户端页面或下载客户端

import { openAppLofter } from 'lofter-utils'

更多使用文档