From e921548abfb44c5b7e3015727c645720f7195c3d Mon Sep 17 00:00:00 2001 From: ldl <2510952840@qq.com> Date: Mon, 4 Jul 2022 18:53:23 +0800 Subject: [PATCH] refactor: code split --- README.md | 19 ++++------ package.json | 9 ++--- packages/core/image-utils/src/index.ts | 52 +++++++++++++------------- packages/core/storage/src/index.ts | 10 ++++- packages/shared/index.ts | 1 + packages/shared/libs/index.ts | 13 +++++++ packages/shared/utils/dev.ts | 3 ++ packages/shared/utils/error.ts | 7 ++++ packages/shared/utils/index.ts | 51 ++----------------------- packages/shared/utils/runtime.ts | 3 ++ test/core.test.ts | 14 ------- test/core/storage.test.ts | 16 ++++++++ test/{ => shared}/shared.test.ts | 6 +-- 13 files changed, 92 insertions(+), 112 deletions(-) create mode 100644 packages/shared/libs/index.ts create mode 100644 packages/shared/utils/dev.ts create mode 100644 packages/shared/utils/error.ts create mode 100644 packages/shared/utils/runtime.ts delete mode 100644 test/core.test.ts create mode 100644 test/core/storage.test.ts rename test/{ => shared}/shared.test.ts (59%) diff --git a/README.md b/README.md index b7faf68..3cb7dd0 100644 --- a/README.md +++ b/README.md @@ -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 @@ -40,18 +42,11 @@ initLFInstance(AppKey) baseStorage(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'] diff --git a/package.json b/package.json index 9ceeaea..540ee87 100644 --- a/package.json +++ b/package.json @@ -11,7 +11,6 @@ "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" }, @@ -19,20 +18,20 @@ "@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": { diff --git a/packages/core/image-utils/src/index.ts b/packages/core/image-utils/src/index.ts index f3daa98..1ecf8eb 100644 --- a/packages/core/image-utils/src/index.ts +++ b/packages/core/image-utils/src/index.ts @@ -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 @@ -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) @@ -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, + } } } diff --git a/packages/core/storage/src/index.ts b/packages/core/storage/src/index.ts index 457ceba..1f81760 100644 --- a/packages/core/storage/src/index.ts +++ b/packages/core/storage/src/index.ts @@ -1,4 +1,4 @@ -import { throwWarning } from '@fdutil/shared' +import { throwError, throwWarning } from '@fdutil/shared' import localforage from 'localforage' let lfInstance: LocalForage | null = null @@ -11,7 +11,7 @@ let lfInstance: LocalForage | null = null */ export function baseStorage(key: K, data?: T): Promise { 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 { @@ -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 +} diff --git a/packages/shared/index.ts b/packages/shared/index.ts index 9c56149..0ae83fd 100644 --- a/packages/shared/index.ts +++ b/packages/shared/index.ts @@ -1 +1,2 @@ export * from './utils' +export * from './libs' diff --git a/packages/shared/libs/index.ts b/packages/shared/libs/index.ts new file mode 100644 index 0000000..b4a0376 --- /dev/null +++ b/packages/shared/libs/index.ts @@ -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() +} diff --git a/packages/shared/utils/dev.ts b/packages/shared/utils/dev.ts new file mode 100644 index 0000000..94957ff --- /dev/null +++ b/packages/shared/utils/dev.ts @@ -0,0 +1,3 @@ +export function atDevelopingPage() { + return location.host.includes(':') +} diff --git a/packages/shared/utils/error.ts b/packages/shared/utils/error.ts new file mode 100644 index 0000000..e9f8a2f --- /dev/null +++ b/packages/shared/utils/error.ts @@ -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}`) +} diff --git a/packages/shared/utils/index.ts b/packages/shared/utils/index.ts index 962475b..ed67b30 100644 --- a/packages/shared/utils/index.ts +++ b/packages/shared/utils/index.ts @@ -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' diff --git a/packages/shared/utils/runtime.ts b/packages/shared/utils/runtime.ts new file mode 100644 index 0000000..46ae0ba --- /dev/null +++ b/packages/shared/utils/runtime.ts @@ -0,0 +1,3 @@ +export function atDomEnv() { + return Boolean(document) +} diff --git a/test/core.test.ts b/test/core.test.ts deleted file mode 100644 index 7d7edb1..0000000 --- a/test/core.test.ts +++ /dev/null @@ -1,14 +0,0 @@ -import { describe, expect, it, test } from 'vitest' -import { baseStorage, initLFInstance } from '../packages/core' - -describe('core package', () => { - it('error init lf', async () => { - expect((await baseStorage('test data', 'test key'))) - .equal(null) - }) -}) -test('inited if instance', () => { - expect(initLFInstance('lfName')).toHaveProperty('INDEXEDDB') - expect(initLFInstance('lfName')).toHaveProperty('WEBSQL') - expect(initLFInstance('lfName')).toHaveProperty('LOCALSTORAGE') -}) diff --git a/test/core/storage.test.ts b/test/core/storage.test.ts new file mode 100644 index 0000000..5cb34fc --- /dev/null +++ b/test/core/storage.test.ts @@ -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') +}) diff --git a/test/shared.test.ts b/test/shared/shared.test.ts similarity index 59% rename from test/shared.test.ts rename to test/shared/shared.test.ts index b6931fc..e022cde 100644 --- a/test/shared.test.ts +++ b/test/shared/shared.test.ts @@ -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 () => { @@ -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 }) - }) })