Skip to content

Commit

Permalink
refactor: code split
Browse files Browse the repository at this point in the history
  • Loading branch information
Senar369 committed Jul 4, 2022
1 parent 73618c5 commit e921548
Show file tree
Hide file tree
Showing 13 changed files with 92 additions and 112 deletions.
19 changes: 7 additions & 12 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,19 +10,21 @@ front end developer toolkit
![license](https://img.shields.io/github/license/luvletterldl/fdutil)
![download](https://img.shields.io/npm/dm/@fdutil/core)

## env
# env
browser

## install
# install
```bash
npm install @fdutil/core
yarn add @fdutil/core
pnpm install @fdutil/core
```

## usage
# usage

## core
```ts
import { baseStorage, getImgOpaqueOffsets, getImgOriginUrls, getRandomId, initLFInstance, initStorageData, isDeveloping, isEmptyObject, promiseDomEnv } from '@fdutil/core'
import { baseStorage, getImgOpaqueOffsets, getImgOriginUrls, getStorageData, initLFInstance } from '@fdutil/core'

interface UserInfoInterface {
name: string
Expand All @@ -40,18 +42,11 @@ initLFInstance(AppKey)

baseStorage<StorageKeys, UserInfoInterface>(storageKey, { name: 'Jeff', age: 18 })

if (isDeveloping())
console.log('developing')

getImgOpaqueOffsets(imgUrl).then(({ x, y, w, h }) => {
console.log('your img\'s opaque part offsets: ', x, y, w, h)
})

const randomId = getRandomId()

promiseDomEnv()

initStorageData('item', { default: true })
getStorageData('item', { default: true })

const urls = getImgOriginUrls('sadhihttp://a.g*o 32 \^!.webp*.jpg)w \\nebpd https:// sahttps://% ^& *.png(*&^')
console.log(urls) // ['http://a.g*o32^!.webp', 'https://%^&*.png']
Expand Down
9 changes: 4 additions & 5 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,28 +11,27 @@
"typecheck": "tsc --noEmit",
"test": "vitest",
"coverage": "vitest run --coverage",
"publish:ci": "esno scripts/publish.ts",
"publish": "pnpm build && pnpm -r publish",
"release": "bumpp package.json packages/*/package.json --commit --push --tag"
},
"devDependencies": {
"@antfu/eslint-config": "^0.25.2",
"@fdutil/core": "workspace:*",
"@fdutil/shared": "workspace:*",
"@types/node": "^18.0.0",
"@types/node": "^18.0.1",
"bumpp": "^8.2.1",
"c8": "^7.11.3",
"consola": "^2.15.3",
"eslint": "^8.18.0",
"eslint": "^8.19.0",
"esno": "^0.16.3",
"jsdom": "^20.0.0",
"localforage": "^1.10.0",
"nanoid": "^4.0.0",
"pnpm": "^7.4.0",
"pnpm": "^7.5.0",
"typescript": "^4.7.4",
"unbuild": "^0.7.4",
"vite": "^2.9.13",
"vitest": "^0.16.0"
"vitest": "^0.17.0"
},
"pnpm": {},
"simple-git-hooks": {
Expand Down
52 changes: 26 additions & 26 deletions packages/core/image-utils/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
import { getRandomId, promiseDomEnv } from '@fdutil/shared'
import { atDomEnv, getRandomId } from '@fdutil/shared'

/**
* Generate a unique id canvas dom element
* @returns
* Generate a unique id canvas dom element, append to Dom
* @returns canvas ref and canvas id
*/
function newCanvasCtx(width: number, height: number) {
promiseDomEnv()
const canvas = document.createElement('canvas')
canvas.width = width
canvas.height = height
Expand All @@ -24,7 +23,6 @@ function newCanvasCtx(width: number, height: number) {
* @param id canvas dom element id
*/
function removeCanvasCtx(id: string) {
promiseDomEnv()
const canvas = document.getElementById(id)
if (canvas)
document.body.removeChild(canvas)
Expand Down Expand Up @@ -56,29 +54,31 @@ function getImgInfo(src: string): Promise<{ width: number; height: number; img:
* @returns x: number y: number w: number h: number
*/
export async function getImgOpaqueOffsets(imgSrc: string) {
const { width, height, img } = await getImgInfo(imgSrc)
const { canvasCtx, id } = newCanvasCtx(width, height)
canvasCtx!.drawImage(img, 0, 0, width, height)
const imgData = canvasCtx!.getImageData(0, 0, width, height).data
let l = width; let r = 0; let t = height; let b = 0
for (let i = 0; i < width; i++) {
for (let j = 0; j < height; j++) {
const pos = (i + width * j) * 4
if (imgData[pos] > 0 || imgData[pos + 1] > 0 || imgData[pos + 2] || imgData[pos + 3] > 0) {
b = Math.max(j, b)
r = Math.max(i, r)
t = Math.min(j, t)
l = Math.min(i, l)
if (atDomEnv()) {
const { width, height, img } = await getImgInfo(imgSrc)
const { canvasCtx, id } = newCanvasCtx(width, height)
canvasCtx!.drawImage(img, 0, 0, width, height)
const imgData = canvasCtx!.getImageData(0, 0, width, height).data
let l = width; let r = 0; let t = height; let b = 0
for (let i = 0; i < width; i++) {
for (let j = 0; j < height; j++) {
const pos = (i + width * j) * 4
if (imgData[pos] > 0 || imgData[pos + 1] > 0 || imgData[pos + 2] || imgData[pos + 3] > 0) {
b = Math.max(j, b)
r = Math.max(i, r)
t = Math.min(j, t)
l = Math.min(i, l)
}
}
}
}
l++; r++; t++; b++
removeCanvasCtx(id)
return {
x: l,
y: t,
w: r - l,
h: b - t,
l++; r++; t++; b++
removeCanvasCtx(id)
return {
x: l,
y: t,
w: r - l,
h: b - t,
}
}
}

Expand Down
10 changes: 8 additions & 2 deletions packages/core/storage/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { throwWarning } from '@fdutil/shared'
import { throwError, throwWarning } from '@fdutil/shared'
import localforage from 'localforage'

let lfInstance: LocalForage | null = null
Expand All @@ -11,7 +11,7 @@ let lfInstance: LocalForage | null = null
*/
export function baseStorage<T, K extends string>(key: K, data?: T): Promise<T | null> {
if (!lfInstance) {
console.error('[fdutil] please init localforage instance first!, invoke initLFInstance()')
throwError('localforage', 'please init localforage instance first!, invoke initLFInstance()')
return Promise.resolve(null)
}
else {
Expand All @@ -33,3 +33,9 @@ export function initLFInstance(name: string): LocalForage {
lfInstance = localforage.createInstance({ name })
return lfInstance
}

/** get storageData */
export function getStorageData(key: string, defaultData: unknown, isSessionStorage = false) {
const storage = isSessionStorage ? sessionStorage.getItem(key) : localStorage.getItem(key)
return storage ? JSON.parse(storage) : defaultData
}
1 change: 1 addition & 0 deletions packages/shared/index.ts
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
export * from './utils'
export * from './libs'
13 changes: 13 additions & 0 deletions packages/shared/libs/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { nanoid } from 'nanoid'

export function isEmptyObject(obj: Object) {
// because Object.keys(new Date()).length === 0;
// we have to do some additional check
return obj // 👈 null and undefined check
&& Object.keys(obj).length === 0
&& Object.getPrototypeOf(obj) === Object.prototype
}

export function getRandomId() {
return nanoid()
}
3 changes: 3 additions & 0 deletions packages/shared/utils/dev.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export function atDevelopingPage() {
return location.host.includes(':')
}
7 changes: 7 additions & 0 deletions packages/shared/utils/error.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
export function throwError(type: string, message: string) {
throw new Error(`[fdutil]: ${type} ${message}`)
}

export function throwWarning(type: string, message: string) {
console.warn(`[fdutil]: ${type} ${message}`)
}
51 changes: 3 additions & 48 deletions packages/shared/utils/index.ts
Original file line number Diff line number Diff line change
@@ -1,48 +1,3 @@
import { nanoid } from 'nanoid'

/**
* is developing runtime
* @returns boolean
*/
export function isDeveloping() {
return location.host.includes(':')
}

/** 判断对象是否是空对象 */
export function isEmptyObject(obj: Object) {
// because Object.keys(new Date()).length === 0;
// we have to do some additional check
return obj // 👈 null and undefined check
&& Object.keys(obj).length === 0
&& Object.getPrototypeOf(obj) === Object.prototype
}

/**
* generate random id
* @returns string
*/
export function getRandomId() {
return nanoid()
}

/**
* promise at dom env
*/
export function promiseDomEnv() {
if (!document)
throw new Error('[fdutil error]: document is not defined, please use at browser, not node. dom is required')
}

/** get initStorageData */
export function initStorageData(key: string, defaultData: unknown, isSessionStorage = false) {
const storage = isSessionStorage ? sessionStorage.getItem(key) : localStorage.getItem(key)
return storage ? JSON.parse(storage) : defaultData
}

export function throwError(type: string, message: string) {
throw new Error(`[fdutil]: ${type} ${message}`)
}

export function throwWarning(type: string, message: string) {
console.warn(`[fdutil]: ${type} ${message}`)
}
export * from './dev'
export * from './error'
export * from './runtime'
3 changes: 3 additions & 0 deletions packages/shared/utils/runtime.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export function atDomEnv() {
return Boolean(document)
}
14 changes: 0 additions & 14 deletions test/core.test.ts

This file was deleted.

16 changes: 16 additions & 0 deletions test/core/storage.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { describe, expect, test } from 'vitest'
import { baseStorage, getStorageData, initLFInstance } from '../../packages/core'

describe('core package', () => {
test('error init lf', async () => {
expect(() => baseStorage('test data', 'test key')).toThrowError('localforage please init localforage instance first')
})
test('getInitStorageData', () => {
expect(getStorageData('test', { a: 1 })).toEqual({ a: 1 })
})
})
test('inited if instance', () => {
expect(initLFInstance('lfName')).toHaveProperty('INDEXEDDB')
expect(initLFInstance('lfName')).toHaveProperty('WEBSQL')
expect(initLFInstance('lfName')).toHaveProperty('LOCALSTORAGE')
})
6 changes: 1 addition & 5 deletions test/shared.test.ts → test/shared/shared.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { describe, expect, it } from 'vitest'
import { initStorageData, isEmptyObject } from '../packages/shared'
import { isEmptyObject } from '../../packages/shared/dist'

describe('shared package', () => {
it('is empty', async () => {
Expand All @@ -9,8 +9,4 @@ describe('shared package', () => {
it('isn\'t empty object', () => {
expect(isEmptyObject({ a: 1 }) === false)
})

it('init storage data', () => {
expect(initStorageData('test', { a: 1 })).toEqual({ a: 1 })
})
})

0 comments on commit e921548

Please sign in to comment.