0.0.17 • Published 1 year ago

@dhicn/helper v0.0.17

Weekly downloads
-
License
-
Repository
-
Last release
1 year ago

@dhicn/helper

generic

changeTheme

切换浅色深色主题

guid

生成 GUID

toFixed

数字取小数

logger

系统日志

  1. 构建日志方法

    具体引用了“debug”(https://github.com/debug-js/debug) 通过 namespace 进行隔离,结合浏览器的 developer-tool 的筛选功能可以 支持 语句格式化参数 "Debug uses printf-style formatting. Below are the officially supported formatters:"

    debug('this is hex: %0 and %0', 'a', 'b')
    //   foo this is hex: a and b +0ms

    保留 save 方法,可以通过 Logan 进行 IndexedDB 的日志存储,为后期日志上传预留接口

    export class Logger {
        debugger: debug.Debugger
        debuggerErr: debug.Debugger
        constructor(namespace: string) {
            this.debugger = debug(namespace)
            this.debugger.enabled = true
            this.debuggerErr = debug(namespace + ':err')
            this.debuggerErr.enabled = true
            this.debuggerErr.log = console.error
        }
    
        private getStack(first = 3) {
            const error = new Error('debug-log')
            const stack = error.stack?.split('\n')
            stack?.splice(0, first)
            return stack
        }
    
        private formatMsg(msg: string, argsCount: number) {
            let count = (msg.match(/%[Oosdj]/g) || []).length
            let logMsg = msg
            while (count < argsCount) {
                logMsg = logMsg + `\n args[${count}]: %o`
                count++
            }
            logMsg = `${logMsg} \n stack: %o`
            return logMsg
        }
    
        debug(msg: string, ...args: any[]) {
            const logMsg = this.formatMsg(msg, args.length)
            this.debugger(`${logMsg}`, ...args, this.getStack())
        }
    
        error(msg: string, ...args: any[]) {
            const logMsg = this.formatMsg(msg, args.length)
            this.debuggerErr(`${logMsg}`, ...args, this.getStack())
        }
    
        save() {
            // TODO Logan Report
            // const logObject = {
            //   msg: logMsg,
            //   args: args,
            //   stack: stack,
            // };
            // let logMsgSave = logObject.msg;
            // try {
            //   logMsgSave = JSON.stringify(logObject);
            // } catch (error: any) {
            //   console.error('[UnexpectedJSONParseError]: ' + error.message);
            // }
            // Logan.log(logMsgSave, 1);
        }
    }
  2. 为保证日志的唯一性,在 eslint 的规则中加入,也可通过函数进行重写处理

    eslint 的规则

        ./.eslintrc.js
        rules: {
            'no-console': 'error',
            ...other rules
        },

    对 console.log\error\ debug 这个函数进行重写

        ./main.ts
        const oldConsoleLogFunc = console.log;
        console.log = (...args) => {
        //可以先保证原来的浏览器输出依然存在
        oldConsoleLogFunc(…)
        // 在此调用你刚才提供的库
        ...
  3. 在 库 中应用

    定义一个 logger.ts 文件,实现一个 logger 的实例,namespace 为 'package.json'中 name,并且 export 出来

     ./logger.ts
     import { name } from '../../package.json';
     import { Helper } from 'dhi-dss-package-helper'
     export const logger = new Logger(name);
    
     其他文件应用
     logger.debug('当前日期', getCurrentDate())
     logger.debug('component doDownload url: %0, %0 ', url, json)
     logger.error('downloadHelper :>> ', error)
  4. 在 项目 中应用

    在项目的 main,实现一个 logger 的实例, 绑定到 window 对象上

     ./main.ts
     import { name } from '../package.json';
     import { Helper } from 'dhi-dss-package-helper';
     const logger = new Helper.Logger(name);
     window.logger = logger;

    修改全局定义 vite-env.d.ts

    ./vite-env.d.ts
    import { Helper } from 'dhi-dss-package-helper'
declare global {
  var logger: Helper.Logger
  interface Window {
      logger: Helper.Logger
  }
}
```

> 配置 eslint 检查和全局变量

```javascript
 ./.eslintrc.js
 rules: {
   'no-console': 'error',
   ...other rules
 },
 globals: {
   logger: true,
 },
```

html2canvas

将 Html 元素转换成 Canvas 对象

  • html2canvas: 将 HTML 元素转成 HtmlCanvas 对象
  • html2imageBlob:将 HTML 元素转成 HtmlCanvas 对象,再转成 Blob
  • html2imageBase64:将 HTML 元素转成 HtmlCanvas 对象,再转成 Base64 的 image 字符串
  • html2imageClipboard:将 HTML 元素转成转换成图片,并复制到系统粘贴板

storage

处理 多项目共享 localstorage 的方法包括读取和解析。

时间格式

通过 dayjs 进行时间格式化

已编写的格式

// 格式到日
export const DayFormat00 = 'YYYY-MM-DD'
export const DayFormat01 = 'yyyy-MM-dd'
export const DayFormat02 = 'YYYY/MM/DD'
export const DayFormat03 = 'MM.DD'

// 格式到分
export const minuteFormat01 = 'YYYY-MM-DD HH:mm'
export const minuteFormat02 = 'YYYY/MM/DD HH:mm'
export const minuteFormat03 = 'YYYY.MM.DD HH:mm'

// 格式到秒
export const SecondFormat01 = 'YYYY-MM-DD HH:mm:ss'
export const SecondFormat02 = 'YYYY/MM/DD HH:mm:ss'
export const SecondFormat03 = 'M/d/YYYY hh:mm:ss a'
export const SecondFormat04 = 'YYYY-MM-DD HH:mm:ss.SSS'
export const SecondFormat05 = 'YYYY-MM-DD HH:mm:ss.SSSS'

// 格式 HH:mm
export const HourMinuteFormat = 'HH:mm:ss'
export const HourMinuteFormat01 = 'HH:mm'

export const MonthMinuteFormat01 = 'MM/dd HH:mm'

export const MonthMinuteMask01 = 'MM/DD HH:mm'
export const MonthMinuteMask02 = 'YYYY/MM/DD HH:mm'
export const HourMinuteSecond = 'HH:mm:ss.SSSS'

// 只保留小时
export const HourFormat01 = 'H'

// 格式化为 2023/04/06 10:37AM
export const SecondFormat06 = 'YYYY/MM/DD hh:mma'
export const SecondFormat07 = 'YYYY-MM-DD hh:mmA'

时间格式示例

Get the formatted date according to the string of tokens passed in.

To escape characters, wrap them in square brackets (e.g. [MM]).

dayjs().format()
// current date in ISO8601, without fraction seconds e.g. '2020-04-02T08:02:17-05:00'

dayjs('2019-01-25').format('[YYYYescape] YYYY-MM-DDTHH:mm:ssZ[Z]')
// 'YYYYescape 2019-01-25T00:00:00-02:00Z'

dayjs('2019-01-25').format('DD/MM/YYYY') // '25/01/2019'

List of all available formats

FormatOutputDescription
YY18Two-digit year
YYYY2018Four-digit year
M1-12The month, beginning at 1
MM01-12The month, 2-digits
MMMJan-DecThe abbreviated month name
MMMMJanuary-DecemberThe full month name
D1-31The day of the month
DD01-31The day of the month, 2-digits
d0-6The day of the week, with Sunday as 0
ddSu-SaThe min name of the day of the week
dddSun-SatThe short name of the day of the week
ddddSunday-SaturdayThe name of the day of the week
H0-23The hour
HH00-23The hour, 2-digits
h1-12The hour, 12-hour clock
hh01-12The hour, 12-hour clock, 2-digits
m0-59The minute
mm00-59The minute, 2-digits
s0-59The second
ss00-59The second, 2-digits
SSS000-999The millisecond, 3-digits
Z+05:00The offset from UTC, ±HH:mm
ZZ+0500The offset from UTC, ±HHmm
AAM PM
aam pm
......Other formats @>>AdvancedFormat

Localized formats

Because preferred formatting differs based on locale, there are a few localized format tokens that can be used based on its locale.

@>LocalizedFormat

dayjs.extend(LocalizedFormat)
dayjs().format('L LT')

List of localized formats

FormatEnglish LocaleSample Output
LTh:mm A8:02 PM
LTSh:mm:ss A8:02:18 PM
LMM/DD/YYYY08/16/2018
LLMMMM D, YYYYAugust 16, 2018
LLLMMMM D, YYYY h:mm AAugust 16, 2018 8:02 PM
LLLLdddd, MMMM D, YYYY h:mm AThursday, August 16, 2018 8:02 PM
lM/D/YYYY8/16/2018
llMMM D, YYYYAug 16, 2018
lllMMM D, YYYY h:mm AAug 16, 2018 8:02 PM
llllddd, MMM D, YYYY h:mm AThu, Aug 16, 2018 8:02 PM
0.0.15

1 year ago

0.0.17

1 year ago

0.0.14

1 year ago

0.0.13

1 year ago

0.0.12

1 year ago

0.0.11

2 years ago

0.0.10

2 years ago

0.0.9

2 years ago

0.0.8

2 years ago

0.0.7

2 years ago

0.0.6

2 years ago

0.0.5

2 years ago

0.0.4

2 years ago

0.0.3

2 years ago

0.0.2

2 years ago

0.0.1

2 years ago