🎩 You're Invited:Meet the Socket team at Black Hat in Las Vegas, August 3-6.RSVP
Sign In

lofter-utils

Package Overview
Dependencies
Maintainers
11
Versions
112
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

lofter-utils

项目中常用的工具集

latest
npmnpm
Version
3.8.14
Version published
Maintainers
11
Created
Source

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'

更多使用文档

FAQs

Package last updated on 02 Sep 2024

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts