From 12e7667883d344c45c8a6d3cf2868c8f47751555 Mon Sep 17 00:00:00 2001 From: Ourai Lin Date: Tue, 14 Apr 2020 22:21:16 +0800 Subject: [PATCH 1/3] Fix issue's URL --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index faef77b..ef16f64 100644 --- a/README.md +++ b/README.md @@ -25,4 +25,4 @@ Handie 的目标不是统一技术栈,更不是统一界面风格,而是— ## 怎么反馈问题 -如果你有问题要反馈或什么好的建议,可以提交 [issue](https://github.com/anti-chaos/handie/issues) 或钉钉联系[欧雷](dingtalk://dingtalkclient/action/sendmsg?dingtalk_id=ourairyu)。 +如果你有问题要反馈或什么好的建议,可以提交 [issue](https://github.com/ourai/handie/issues) 或钉钉联系[欧雷](dingtalk://dingtalkclient/action/sendmsg?dingtalk_id=ourairyu)。 From 006ca882e06d2f1b55a9961330b91727d24cbc26 Mon Sep 17 00:00:00 2001 From: Ourai Lin Date: Tue, 2 Jun 2020 20:38:52 +0800 Subject: [PATCH 2/3] feat: use utils from ntks/toolbox instead --- package-lock.json | 5 + package.json | 3 + src/adapters/bridge/dingtalk/helper.ts | 8 +- src/adapters/bridge/dingtalk/notification.ts | 84 ++++--- src/adapters/bridge/dingtalk/previewer.ts | 10 +- src/adapters/bridge/helper.ts | 40 +-- src/adapters/bridge/index.ts | 6 +- src/adapters/flexible/index.ts | 20 +- src/utils/calc/index.ts | 123 ---------- src/utils/collection/index.ts | 242 ------------------- src/utils/common/helper.ts | 23 -- src/utils/common/index.ts | 1 - src/utils/common/supports.ts | 2 +- src/utils/data/index.ts | 37 --- src/utils/http/defaults.ts | 49 ++-- src/utils/http/helper.ts | 2 +- src/utils/http/index.ts | 4 +- src/utils/index.ts | 5 - src/utils/is/env.ts | 2 +- src/utils/is/format.ts | 28 --- src/utils/is/index.ts | 2 - src/utils/is/type.ts | 155 ------------ src/utils/notification/index.ts | 30 +-- src/utils/socket/index.ts | 30 ++- src/utils/storage/helper.ts | 149 ------------ src/utils/storage/index.ts | 1 - src/utils/text/index.ts | 18 +- src/utils/uploader/helper.ts | 2 +- src/utils/uploader/index.ts | 17 +- src/utils/url/helper.ts | 69 ------ src/utils/url/index.ts | 50 ---- 31 files changed, 178 insertions(+), 1039 deletions(-) delete mode 100644 src/utils/calc/index.ts delete mode 100644 src/utils/collection/index.ts delete mode 100644 src/utils/common/helper.ts delete mode 100644 src/utils/common/index.ts delete mode 100644 src/utils/data/index.ts delete mode 100644 src/utils/is/format.ts delete mode 100644 src/utils/is/type.ts delete mode 100644 src/utils/storage/helper.ts delete mode 100644 src/utils/storage/index.ts delete mode 100644 src/utils/url/helper.ts delete mode 100644 src/utils/url/index.ts diff --git a/package-lock.json b/package-lock.json index 68caa6c..4870a77 100644 --- a/package-lock.json +++ b/package-lock.json @@ -4,6 +4,11 @@ "lockfileVersion": 1, "requires": true, "dependencies": { + "@ntks/toolbox": { + "version": "0.0.3", + "resolved": "https://registry.npmjs.org/@ntks/toolbox/-/toolbox-0.0.3.tgz", + "integrity": "sha512-iN8aXp7+62GWJHf818ydBIKH3jMLyXDiM/r7A2s91HQlkKuPea/YKie7RfOL0K16G1NxcQTGUYXH34/XTsWp8g==" + }, "@types/estree": { "version": "0.0.44", "resolved": "https://registry.npm.taobao.org/@types/estree/download/@types/estree-0.0.44.tgz?cache=0&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2F%40types%2Festree%2Fdownload%2F%40types%2Festree-0.0.44.tgz", diff --git a/package.json b/package.json index c223a8c..a3bbb10 100644 --- a/package.json +++ b/package.json @@ -29,6 +29,9 @@ "release": "cd dist && npm publish", "start": "rollup -c rollup.config.ts -w" }, + "dependencies": { + "@ntks/toolbox": "0.0.3" + }, "devDependencies": { "@types/jquery": "^3.3.29", "@types/lodash": "^4.14.149", diff --git a/src/adapters/bridge/dingtalk/helper.ts b/src/adapters/bridge/dingtalk/helper.ts index 5afa701..009ff65 100644 --- a/src/adapters/bridge/dingtalk/helper.ts +++ b/src/adapters/bridge/dingtalk/helper.ts @@ -1,6 +1,4 @@ -import { isFunction } from '../../../utils/is/type'; -import { mixin } from '../../../utils/collection'; -import { retrieveData } from '../../../utils/storage/helper'; +import { isFunction, mixin, retrieveData } from '@ntks/toolbox'; /** * 调用钉钉 API @@ -8,12 +6,10 @@ import { retrieveData } from '../../../utils/storage/helper'; * @param {*} ref API 引用 * @param {*} opts 配置项 */ -export function invokeDingTalkApi( ref: string, opts?: any ): any { +export function invokeDingTalkApi(ref: string, opts?: any): any { // const handler = retrieveData(dd, ref); - // if ( !isFunction(handler) ) { // return; // } - // return handler(mixin({onFail: ( ...args: any[] ) => console.log(...args)}, opts)); } diff --git a/src/adapters/bridge/dingtalk/notification.ts b/src/adapters/bridge/dingtalk/notification.ts index 3721df2..2ce82fb 100644 --- a/src/adapters/bridge/dingtalk/notification.ts +++ b/src/adapters/bridge/dingtalk/notification.ts @@ -1,34 +1,45 @@ -import { isFunction, isPlainObject } from '../../../utils/is/type'; -import { map, mixin } from '../../../utils/collection'; +import { isFunction, isPlainObject, map, mixin } from '@ntks/toolbox'; import { invokeDingTalkApi } from './helper'; /** * 调用通知类 API - * + * * @param {*} shortcut API 简写 * @param {*} opts 配置项 */ -function invokeNotificationApi( shortcut: string, opts: any ): void { +function invokeNotificationApi(shortcut: string, opts: any): void { return invokeDingTalkApi(`device.notification.${shortcut}`, opts); } export default { - alert( message: any, callback: Function = function() {} ): void { - invokeNotificationApi('alert', mixin({ - title: '', - buttonName: '知道了', - onSuccess: callback - }, isPlainObject(message) ? message : {message})); + alert(message: any, callback: Function = function () {}): void { + invokeNotificationApi( + 'alert', + mixin( + { + title: '', + buttonName: '知道了', + onSuccess: callback, + }, + isPlainObject(message) ? message : { message }, + ), + ); }, - confirm( message: any, agreed: Function = function() {}, cancelled: Function = function() {} ): void { - invokeNotificationApi('confirm', mixin({ - title: '', - buttonLabels: ['确定', '取消'], - onSuccess: ( result: any ) => result.buttonIndex === 0 ? agreed() : cancelled() - }, isPlainObject(message) ? message : {message})); + confirm(message: any, agreed: Function = function () {}, cancelled: Function = function () {}): void { + invokeNotificationApi( + 'confirm', + mixin( + { + title: '', + buttonLabels: ['确定', '取消'], + onSuccess: (result: any) => (result.buttonIndex === 0 ? agreed() : cancelled()), + }, + isPlainObject(message) ? message : { message }, + ), + ); }, // prompt() {}, - toast( opts: any ): void { + toast(opts: any): void { const { text, icon, duration, callback: onSuccess } = opts; invokeNotificationApi('toast', { @@ -36,49 +47,48 @@ export default { icon: icon === 'fail' ? 'error' : icon, duration, delay: 0, - onSuccess + onSuccess, }); }, loading: { - show( opts: any ): void { + show(opts: any): void { const { text, callback: onSuccess } = opts; invokeNotificationApi('showPreloader', { text, showIcon: true, - onSuccess + onSuccess, }); }, - hide( callback: Function ): void { - invokeNotificationApi('hidePreloader', {onSuccess: callback}); - } + hide(callback: Function): void { + invokeNotificationApi('hidePreloader', { onSuccess: callback }); + }, }, - actionSheet( opts: any ): void { + actionSheet(opts: any): void { const { title, cancel, actions } = opts; invokeNotificationApi('actionSheet', { title, cancelButton: cancel.text, - otherButtons: map(actions, ( action: any ) => action.text), - onSuccess: ( result: any ) => { + otherButtons: map(actions, (action: any) => action.text), + onSuccess: (result: any) => { const { buttonIndex: idx } = result; - + let action, handler; - - if ( idx === -1 ) { + + if (idx === -1) { handler = cancel.handler; - } - else { + } else { action = actions[idx]; handler = action.handler; } - - if ( !isFunction(handler) ) { + + if (!isFunction(handler)) { handler = opts.handler; } - + return action ? handler(action) : handler(); - } + }, }); - } -} + }, +}; diff --git a/src/adapters/bridge/dingtalk/previewer.ts b/src/adapters/bridge/dingtalk/previewer.ts index 502da9f..5252928 100644 --- a/src/adapters/bridge/dingtalk/previewer.ts +++ b/src/adapters/bridge/dingtalk/previewer.ts @@ -1,13 +1,13 @@ -import { isNumeric } from '../../../utils/is/type'; +import { isNumeric } from '@ntks/toolbox'; import { invokeDingTalkApi } from './helper'; export default { - image( opts: any ): void { + image(opts: any): void { const { urls = [], current = 0 } = opts; invokeDingTalkApi('biz.util.previewImage', { urls, - current: isNumeric(current) ? urls[current * 1] : current + current: isNumeric(current) ? urls[current * 1] : current, }); - } -} + }, +}; diff --git a/src/adapters/bridge/helper.ts b/src/adapters/bridge/helper.ts index 3027f8d..0d93fdd 100644 --- a/src/adapters/bridge/helper.ts +++ b/src/adapters/bridge/helper.ts @@ -1,16 +1,26 @@ -import { isBoolean, isString, isFunction, isPlainObject } from '../../utils/is/type'; -import { each, keys } from '../../utils/collection'; -import { getDefaults, setPrivate, getPrivate } from '../../utils/storage/helper'; +import { + isBoolean, + isString, + isFunction, + isPlainObject, + each, + keys, + getDefaults, + setPrivate, + getPrivate, +} from '@ntks/toolbox'; /** * 是否优先使用 native 组件 * * @param {*} opts 包含抉择的配置项 */ -export function isNativeFlavor( opts: any ): boolean { - return isBoolean(opts) ? opts : - isPlainObject(opts) && isBoolean(opts.native) ? opts.native : - getDefaults('behavior') === 'native'; +export function isNativeFlavor(opts: any): boolean { + return isBoolean(opts) + ? opts + : isPlainObject(opts) && isBoolean(opts.native) + ? opts.native + : getDefaults('behavior') === 'native'; } /** @@ -19,7 +29,7 @@ export function isNativeFlavor( opts: any ): boolean { * @param {*} flag 标识符 * @param {*} apis API */ -export function setBridge( flag: string, apis: any ): any { +export function setBridge(flag: string, apis: any): any { return setPrivate(`bridge.${flag}`, apis); } @@ -29,7 +39,7 @@ export function setBridge( flag: string, apis: any ): any { * @param {*} flag 标识符 * @param {*} ref API 引用 */ -export function getBridge( flag: string, ref: string ): any { +export function getBridge(flag: string, ref: string): any { return getPrivate(`bridge.${flag}.${ref}`); } @@ -39,18 +49,18 @@ export function getBridge( flag: string, ref: string ): any { * @param {*} ref API 引用 * @param {*} isNativeFirst 是否 native 优先 */ -export function resolveBridge( ref: string, isNativeFirst: boolean ): any { - if ( !isString(ref) ) { +export function resolveBridge(ref: string, isNativeFirst: boolean): any { + if (!isString(ref)) { return; } let handler; - if ( isNativeFirst ) { + if (isNativeFirst) { const envs = getPrivate('env'); - each(keys(getPrivate('bridge')), ( k: string ) => { - if ( k !== 'fallback' && envs[k] === true ) { + each(keys(getPrivate('bridge')), (k: string) => { + if (k !== 'fallback' && envs[k] === true) { handler = getBridge(k, ref); return false; @@ -58,7 +68,7 @@ export function resolveBridge( ref: string, isNativeFirst: boolean ): any { }); } - if ( !isFunction(handler) ) { + if (!isFunction(handler)) { handler = getBridge('fallback', ref); } diff --git a/src/adapters/bridge/index.ts b/src/adapters/bridge/index.ts index 3d78bc7..f5800e2 100644 --- a/src/adapters/bridge/index.ts +++ b/src/adapters/bridge/index.ts @@ -1,4 +1,4 @@ -import { isFunction } from '../../utils/is/type'; +import { isFunction } from '@ntks/toolbox'; import { isNativeFlavor, resolveBridge } from './helper'; /** @@ -8,10 +8,10 @@ import { isNativeFlavor, resolveBridge } from './helper'; * @param {*} opts 处理函数的首个参数 * @param {*} rest 处理函数的其余参数 */ -export function invoke( ref: string, opts: any, ...rest: any[] ): any { +export function invoke(ref: string, opts: any, ...rest: any[]): any { const handler = resolveBridge(ref, isNativeFlavor(opts)); - if ( !isFunction(handler) ) { + if (!isFunction(handler)) { return false; } diff --git a/src/adapters/flexible/index.ts b/src/adapters/flexible/index.ts index 516f82e..5332190 100644 --- a/src/adapters/flexible/index.ts +++ b/src/adapters/flexible/index.ts @@ -1,7 +1,7 @@ -import { mixin } from '../../utils/collection'; +import { mixin } from '@ntks/toolbox'; const DEFAULT_FONT_BASELINE = 14; -const DEFAULT_DRAFT_BASELINE = 375; // iPhone 6/7 +const DEFAULT_DRAFT_BASELINE = 375; // iPhone 6/7 let flexibleAdaptorTimer: number; @@ -11,15 +11,15 @@ let flexibleAdaptorTimer: number; * @param {*} fontBaseline 字体大小基准值 * @param {*} draftBaseline 设计稿宽度基准值 */ -function setFontSize( fontBaseline: number, draftBaseline: number ): void { +function setFontSize(fontBaseline: number, draftBaseline: number): void { const rootEl = document.documentElement; const width = rootEl.clientWidth; - if ( !width ) { + if (!width) { return; } - rootEl.style.fontSize = `${fontBaseline * width / draftBaseline}px`; + rootEl.style.fontSize = `${(fontBaseline * width) / draftBaseline}px`; } /** @@ -28,7 +28,7 @@ function setFontSize( fontBaseline: number, draftBaseline: number ): void { * @param {*} name 事件名称 * @param {*} handler 事件处理函数 */ -function bindWindowEvent( name: string, handler: any ): void { +function bindWindowEvent(name: string, handler: any): void { window.addEventListener(name, handler, false); } @@ -38,19 +38,19 @@ function bindWindowEvent( name: string, handler: any ): void { * @param {*} handler 处理函数 * @param {*} timeout 延时时间 */ -function setFlexibleAdaptorTimer( handler: Function, timeout: number = 300 ): void { +function setFlexibleAdaptorTimer(handler: Function, timeout: number = 300): void { clearTimeout(flexibleAdaptorTimer); flexibleAdaptorTimer = setTimeout(handler, timeout); } -export default function( opts: any ) { - opts = mixin({font: DEFAULT_FONT_BASELINE, draft: DEFAULT_DRAFT_BASELINE}, opts); +export default function (opts: any) { + opts = mixin({ font: DEFAULT_FONT_BASELINE, draft: DEFAULT_DRAFT_BASELINE }, opts); const handler = () => setFontSize(opts.font, opts.draft); bindWindowEvent('resize', () => setFlexibleAdaptorTimer(handler)); - bindWindowEvent('pageshow', ( evt: any ) => evt.persisted && setFlexibleAdaptorTimer(handler)); + bindWindowEvent('pageshow', (evt: any) => evt.persisted && setFlexibleAdaptorTimer(handler)); handler(); } diff --git a/src/utils/calc/index.ts b/src/utils/calc/index.ts deleted file mode 100644 index 2532206..0000000 --- a/src/utils/calc/index.ts +++ /dev/null @@ -1,123 +0,0 @@ -// Copied from https://github.com/nefe/number-precision/blob/master/src/index.ts -// for fix TypeScript typing - -/** - * @desc 解决浮动运算问题,避免小数点后产生多位数和计算精度损失。 - * 问题示例:2.3 + 2.4 = 4.699999999999999,1.0 - 0.9 = 0.09999999999999998 - */ - -/** - * 把错误的数据转正 - * strip(0.09999999999999998)=0.1 - */ -function strip(num: number, precision = 12): number { - return +parseFloat(num.toPrecision(precision)); -} - -/** - * Return digits length of a number - * @param {*number} num Input number - */ -function digitLength(num: number): number { - // Get digit length of e - const eSplit = num.toString().split(/[eE]/); - const len = (eSplit[0].split('.')[1] || '').length - +(eSplit[1] || 0); - return len > 0 ? len : 0; -} - -/** - * 把小数转成整数,支持科学计数法。如果是小数则放大成整数 - * @param {*number} num 输入数 - */ -function float2Fixed(num: number): number { - if (num.toString().indexOf('e') === -1) { - return Number(num.toString().replace('.', '')); - } - const dLen = digitLength(num); - return dLen > 0 ? strip(num * Math.pow(10, dLen)) : num; -} - -/** - * 检测数字是否越界,如果越界给出提示 - * @param {*number} num 输入数 - */ -function checkBoundary(num: number) { - if (_boundaryCheckingState) { - if (num > Number.MAX_SAFE_INTEGER || num < Number.MIN_SAFE_INTEGER) { - console.warn(`${num} is beyond boundary when transfer to integer, the results may not be accurate`); - } - } -} - -/** - * 精确乘法 - */ -function times(num1: number, num2: number, ...others: number[]): number { - if (others.length > 0) { - return times(times(num1, num2), others[0], ...others.slice(1)); - } - const num1Changed = float2Fixed(num1); - const num2Changed = float2Fixed(num2); - const baseNum = digitLength(num1) + digitLength(num2); - const leftValue = num1Changed * num2Changed; - - checkBoundary(leftValue); - - return leftValue / Math.pow(10, baseNum); -} - -/** - * 精确加法 - */ -function plus(num1: number, num2: number, ...others: number[]): number { - if (others.length > 0) { - return plus(plus(num1, num2), others[0], ...others.slice(1)); - } - const baseNum = Math.pow(10, Math.max(digitLength(num1), digitLength(num2))); - return (times(num1, baseNum) + times(num2, baseNum)) / baseNum; -} - -/** - * 精确减法 - */ -function minus(num1: number, num2: number, ...others: number[]): number { - if (others.length > 0) { - return minus(minus(num1, num2), others[0], ...others.slice(1)); - } - const baseNum = Math.pow(10, Math.max(digitLength(num1), digitLength(num2))); - return (times(num1, baseNum) - times(num2, baseNum)) / baseNum; -} - -/** - * 精确除法 - */ -function divide(num1: number, num2: number, ...others: number[]): number { - if (others.length > 0) { - return divide(divide(num1, num2), others[0], ...others.slice(1)); - } - const num1Changed = float2Fixed(num1); - const num2Changed = float2Fixed(num2); - checkBoundary(num1Changed); - checkBoundary(num2Changed); - // fix: 类似 10 ** -4 为 0.00009999999999999999,strip 修正 - return times(num1Changed / num2Changed, strip(Math.pow(10, digitLength(num2) - digitLength(num1)))); -} - -/** - * 四舍五入 - */ -function round(num: number, ratio: number): number { - const base = Math.pow(10, ratio); - return divide(Math.round(times(num, base)), base); -} - -let _boundaryCheckingState = true; -/** - * 是否进行边界检查,默认开启 - * @param flag 标记开关,true 为开启,false 为关闭,默认为 true - */ -function enableBoundaryChecking(flag = true) { - _boundaryCheckingState = flag; -} - -export { plus, minus, times as multiply, divide as divided }; diff --git a/src/utils/collection/index.ts b/src/utils/collection/index.ts deleted file mode 100644 index 3c9121b..0000000 --- a/src/utils/collection/index.ts +++ /dev/null @@ -1,242 +0,0 @@ -import { - isBoolean, isString, isFunction, - isArray, isArrayLike, - isObject, isLooseObject, isPlainObject } from '../is/type'; - -/** - * 判断是否当作数组进行处理 - * - * @param {*} target 目标 - */ -function treatAsArray( target: any ): boolean { - return isString(target) || isArray(target) || isArrayLike(target); -} - -/** - * 遍历指定对象 - * - * 与 `jQuery.each()` 效果类似 - * - * 详见:http://api.jquery.com/jQuery.each/ - * - * @param {*} target 目标 - * @param {*} callback 应用到每个元素的处理函数 - */ -function eachItem( target: any, callback: Function ): void { - if ( treatAsArray(target) ) { - let idx = 0; - let ele; - - while ( idx < target.length ) { - ele = isString(target) ? target.charAt(idx) : target[idx]; - - if ( callback.apply(ele, [ele, idx++, target]) === false ) { - break; - } - } - } - else if ( isObject(target) || isFunction(target) ) { - let name, value; - - for ( name in target ) { - value = target[name]; - - if ( callback.apply(value, [value, name, target]) === false ) { - break; - } - } - } -} - -/** - * 扩展指定对象 - * - * 与 `jQuery.extend()` 效果一样 - * - * 详见:http://api.jquery.com/jQuery.extend/ - */ -function extendTarget( ...args: any[] ): object { - const length = args.length; - - let target = args[0] || {}; - let i = 1; - let deep = false; - let clone, copy, copyIsArray, name, opts, src; - - if ( isBoolean(target) ) { - deep = target; - target = args[1] || {}; - i = 2; - } - - if ( !isLooseObject(target) && !isFunction(target) ) { - target = {}; - } - - if ( length === 1 ) { - target = this; - i--; - } - - while ( i < length ) { - opts = args[i]; - - if ( opts != null ) { - for ( name in opts ) { - copy = opts[name]; - src = target[name]; - - if ( copy === target ) { - continue; - } - - if ( deep && copy && (isPlainObject(copy) || (copyIsArray = isArray(copy))) ) { - if ( copyIsArray ) { - copyIsArray = false; - clone = src && isArray(src) ? src : []; - } - else { - clone = src && isPlainObject(src) ? src : {}; - } - - target[name] = extendTarget(deep, clone, copy); - } - else if ( copy !== undefined ) { - target[name] = copy; - } - } - } - - i++; - } - - return target; -} - -/** - * 将目标转化为数组 - * - * @param {*} target 目标 - */ -function toArray( target: any ): any[] { - return treatAsArray(target) ? [].slice.call(target, 0) : []; -} - -/** - * 判断目标是否在集合中 - * - * @param {*} target 目标 - * @param {*} collection 集合 - */ -export function includes( target: any, collection: any ): boolean { - if ( isFunction(collection.includes) ) { - return collection.includes(target); - } - else if ( isFunction(collection.indexOf) ) { - return collection.indexOf(target) > -1; - } - else { - try { - return jQuery.inArray(target, toArray(collection)) > -1; - } - catch ( err ) { - return false; - } - } -} - -/** - * 对集合中的每个元素进行处理并返回一个新的集合 - * - * @param {*} target 目标 - * @param {*} callback 应用到每个元素的处理函数 - */ -export function map( target: any, callback: any ): any[] { - let result; - - if ( treatAsArray(target) ) { - if ( isFunction([].map) ) { - result = [].map.call(target, callback); - } - else { - try { - result = jQuery.map(toArray(target), callback); - } - catch ( err ) { - result = []; - } - } - } - - return result || []; -} - -/** - * 对集合中的每个元素进行过滤并返回一个新的集合 - * - * @param {*} target 目标 - * @param {*} callback 应用到每个元素的处理函数 - */ -export function filter( arr: any, callback: Function ): any[] { - let newArr: any[] = []; - - if ( isArray(arr) ) { - if ( isFunction(arr.filter) ) { - newArr = arr.filter(callback); - } - else if ( isFunction(callback) ) { - eachItem(arr, ( idx: number, val: any ) => { - if ( callback.apply(val, [val, idx, [].concat(arr)]) ) { - newArr.push(val); - } - }); - } - } - - return newArr || []; -} - -/** - * 获取集合中的最后一个元素 - * - * @param {*} target 目标 - */ -export function last( target: any ): any { - if ( treatAsArray(target) ) { - return target[target.length - 1]; - } -} - -/** - * 获取指定对象的所有键 - * - * @param {*} target 目标 - */ -export function keys( target: any ): string[] { - if ( isFunction(Object.keys) ) { - return Object.keys(target); - } - - let arr: string[] = []; - - if ( isPlainObject(target) ) { - eachItem(target, ( key: string ) => arr.push(key)); - } - - return arr; -} - -/** - * 克隆目标 - * - * @param {*} target 被克隆的对象 - */ -export function clone( target: any ): any { - return isArray(target) ? [].concat(target) : isPlainObject(target) ? extendTarget(true, {}, target) : target; -} - -export { - eachItem as each, - extendTarget as mixin, - toArray as arrayify -} diff --git a/src/utils/common/helper.ts b/src/utils/common/helper.ts deleted file mode 100644 index e59dd6f..0000000 --- a/src/utils/common/helper.ts +++ /dev/null @@ -1,23 +0,0 @@ -export function toString( target: any ): string { - return Object.prototype.toString.call(target); -} - -export function hasOwnProp( prop: string, obj: object ): boolean { - return obj != null && Object.prototype.hasOwnProperty.call(obj, prop); -} - -/** - * 使字符串首字母大写 - */ -export function capitalize( str: string ): string { - return `${str.charAt(0).toUpperCase()}${str.slice(1)}`; -} - -/** - * 生成随机 ID - * - * @param {*} prefix 随机 ID 的前缀 - */ -export function generateRandomId( prefix: string ): string { - return `${prefix}-${(new Date()).getTime().toString(32).toUpperCase()}`; -} diff --git a/src/utils/common/index.ts b/src/utils/common/index.ts deleted file mode 100644 index d6d6f05..0000000 --- a/src/utils/common/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './helper'; diff --git a/src/utils/common/supports.ts b/src/utils/common/supports.ts index 8560e60..682e0ad 100644 --- a/src/utils/common/supports.ts +++ b/src/utils/common/supports.ts @@ -1,4 +1,4 @@ -import { hasOwnProp } from './helper'; +import { hasOwnProp } from '@ntks/toolbox'; /** * 判断是否支持 CSS 的 `pointer-events` diff --git a/src/utils/data/index.ts b/src/utils/data/index.ts deleted file mode 100644 index bf2927a..0000000 --- a/src/utils/data/index.ts +++ /dev/null @@ -1,37 +0,0 @@ -import { isPlainObject, isArray } from '../is/type'; -import { includes, each } from '../collection'; - -/** - * 过滤掉不在排除列表之内的未修改数据 - * - * @param data - * @param raw - * @param excluded - * @returns {{}} - */ -function filterUnchanged( data: any, raw: any, excluded: string[] ): object { - let filtered: any = {}; - - if ( isPlainObject(data) ) { - if ( isPlainObject(raw) ) { - if ( !isArray(excluded) ) { - excluded = []; - } - - each(data, function( k: string, v: any ) { - if ( (excluded.length > 0 && includes(k, excluded)) || v !== raw[k] ) { - filtered[k] = v; - } - }); - } - else { - filtered = data; - } - } - - return filtered; -} - -export { - filterUnchanged as changed -} diff --git a/src/utils/http/defaults.ts b/src/utils/http/defaults.ts index 0c46e2a..cbce30d 100644 --- a/src/utils/http/defaults.ts +++ b/src/utils/http/defaults.ts @@ -1,6 +1,4 @@ -import { hasOwnProp } from '../common/helper'; -import { isString, isFunction, isPlainObject } from '../is/type'; -import { getDefaults } from '../storage/helper'; +import { hasOwnProp, isString, isFunction, isPlainObject, getDefaults } from '@ntks/toolbox'; import { invoke } from '../../adapters/bridge'; export default { @@ -13,7 +11,7 @@ export default { /** * 将请求参数转换为 JSON */ - jsonify( params: any ): any { + jsonify(params: any): any { return params; }, /** @@ -21,36 +19,37 @@ export default { * * @param {*} res 请求返回 */ - isRestful( res: any ): boolean { - return !(res !== undefined && hasOwnProp('success', res) && (hasOwnProp('message', res) || hasOwnProp('errorMsg', res))); + isRestful(res: any): boolean { + return !( + res !== undefined && + hasOwnProp('success', res) && + (hasOwnProp('message', res) || hasOwnProp('errorMsg', res)) + ); }, /** * 请求发生错误时的处理 */ - errorHandler( res: any ): void { + errorHandler(res: any): void { const code = res.status; - if ( code >= 500 ) { + if (code >= 500) { invoke('notice.alert', getDefaults('http.serverErrorText')); - } - else if ( code >= 400 ) { + } else if (code >= 400) { let resText = res.responseText; let resJson; - if ( hasOwnProp('responseJSON', res) ) { + if (hasOwnProp('responseJSON', res)) { resJson = res.responseJSON; - } - else { + } else { try { resJson = JSON.parse(resText); - } - catch ( err ) { + } catch (err) { resJson = null; } } // 支持 {"message": ""} 或 {"errorMsg": ""} 形式的错误信息 - if ( isPlainObject(resJson) && (hasOwnProp('message', resJson) || hasOwnProp('errorMsg', resJson)) ) { + if (isPlainObject(resJson) && (hasOwnProp('message', resJson) || hasOwnProp('errorMsg', resJson))) { resText = hasOwnProp('message', resJson) ? resJson.message : resJson.errorMsg; } @@ -60,24 +59,22 @@ export default { /** * 对请求返回数据的处理 */ - responseHandler( res: any, callback: Function ): void { + responseHandler(res: any, callback: Function): void { const hasCallback = isFunction(callback); // RESTful 请求的情况 - if ( getDefaults('http.isRestful')(res) ) { - if ( isString(res) && res !== '' ) { + if (getDefaults('http.isRestful')(res)) { + if (isString(res) && res !== '') { invoke('notice.alert', res); - } - else if ( hasCallback ) { + } else if (hasCallback) { callback.call(null, res); } } // 返回结构为 {success: true, message: ""} 或 {success: true, errorMsg: ""} 的情况 else { - if ( !res.success ) { + if (!res.success) { invoke('notice.alert', hasOwnProp('message', res) ? res.message : res.errorMsg); - } - else if ( hasCallback ) { + } else if (hasCallback) { callback.call(null, res.data); } } @@ -85,5 +82,5 @@ export default { /** * 请求完成时的处理 */ - completeHandler(): void {} -} + completeHandler(): void {}, +}; diff --git a/src/utils/http/helper.ts b/src/utils/http/helper.ts index 5822f3d..bad6933 100644 --- a/src/utils/http/helper.ts +++ b/src/utils/http/helper.ts @@ -1,4 +1,4 @@ -import { isFunction, isPlainObject } from '../is/type'; +import { isFunction, isPlainObject } from '@ntks/toolbox'; /** * 判断是否支持 jQuery diff --git a/src/utils/http/index.ts b/src/utils/http/index.ts index 1ee0e98..d2d9a6e 100644 --- a/src/utils/http/index.ts +++ b/src/utils/http/index.ts @@ -1,6 +1,4 @@ -import { isFunction, isPlainObject } from '../is/type'; -import { includes, map, keys, mixin } from '../collection'; -import { setDefaults, getDefaults } from '../storage/helper'; +import { isFunction, isPlainObject, includes, map, keys, mixin, setDefaults, getDefaults } from '@ntks/toolbox'; import { supportJquery, supportAxios } from './helper'; import HTTP_DEFAULTS from './defaults'; diff --git a/src/utils/index.ts b/src/utils/index.ts index 7f3c56c..1ff01cc 100644 --- a/src/utils/index.ts +++ b/src/utils/index.ts @@ -1,7 +1,2 @@ -export * from './common'; export * from './is'; -export * from './collection'; -export * from './calc'; -export * from './url'; export * from './text'; -export * from './storage'; diff --git a/src/utils/is/env.ts b/src/utils/is/env.ts index 79d0572..1337a55 100644 --- a/src/utils/is/env.ts +++ b/src/utils/is/env.ts @@ -1,4 +1,4 @@ -import { hasOwnProp } from '../common/helper'; +import { hasOwnProp } from '@ntks/toolbox'; /** * 获取用户代理字符串 diff --git a/src/utils/is/format.ts b/src/utils/is/format.ts deleted file mode 100644 index c239b14..0000000 --- a/src/utils/is/format.ts +++ /dev/null @@ -1,28 +0,0 @@ -/** - * 判断是否为一个 URL - * - * @param {*} target 目标 - */ -export function isUrl( target: string ): boolean { - return /^((http(s)?\:)?\/\/|\/[^\/]+).+/i.test(target); -} - -/** - * 判断是否为电子邮箱 - * - * 参考 https://html.spec.whatwg.org/multipage/forms.html#e-mail-state-(type=email) - * - * @param {*} target 目标 - */ -export function isEmail( target: string ): boolean { - return /^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/.test(target); -} - -/** - * 判断是否为手机号 - * - * @param {*} target 目标 - */ -export function isCellphone( target: string ): boolean { - return /^1[345789]\d{9}$/.test(target); -} diff --git a/src/utils/is/index.ts b/src/utils/is/index.ts index 086a76e..c1532d6 100644 --- a/src/utils/is/index.ts +++ b/src/utils/is/index.ts @@ -1,3 +1 @@ -export * from './type'; -export * from './format'; export * from './env'; diff --git a/src/utils/is/type.ts b/src/utils/is/type.ts deleted file mode 100644 index 6a6c31c..0000000 --- a/src/utils/is/type.ts +++ /dev/null @@ -1,155 +0,0 @@ -import { toString, hasOwnProp } from '../common/helper'; - -/** - * 判断是否为布尔类型 - * - * @param {*} target 目标 - */ -export function isBoolean( target: any ): boolean { - return toString(target) === '[object Boolean]'; -} - -/** - * 判断是否为数字类型 - * - * 如果是 `NaN` 的话则返回 `false` - * - * @param {*} target 目标 - */ -export function isNumber( target: any ): boolean { - return toString(target) === '[object Number]' && !isNaN(target); -} - -/** - * 判断是否为字符串类型 - * - * @param {*} target 目标 - */ -export function isString( target: any ): boolean { - return toString(target) === '[object String]'; -} - -/** - * 判断是否为函数类型 - * - * @param {*} target 目标 - */ -export function isFunction( target: any ): boolean { - return toString(target) === '[object Function]'; -} - -/** - * 判断是否为数组类型 - * - * @param {*} target 目标 - */ -export function isArray( target: any ): boolean { - return toString(target) === '[object Array]'; -} - -/** - * 判断是否为日期类型 - * - * @param {*} target 目标 - */ -export function isDate( target: any ): boolean { - return toString(target) === '[object Date]'; -} - -/** - * 判断是否为正则表达式类型 - * - * @param {*} target 目标 - */ -export function isRegExp( target: any ): boolean { - return toString(target) === '[object RegExp]'; -} - -/** - * 判断是否为对象类型 - * - * @param {*} target 目标 - */ -export function isObject( target: any ): boolean { - return toString(target) === '[object Object]'; -} - -/** - * 宽松地判断是否为对象类型 - * - * @param {*} target 目标 - */ -export function isLooseObject( target: any ): boolean { - return typeof target === 'object'; -} - -/** - * 判断是否为数字或类数字类型 - * - * 与 `jQuery.isNumeric()` 的实现方式一致 - * - * @param {*} target 目标 - */ -export function isNumeric( target: any ): boolean { - const realStringObj = target && target.toString(); - - return !isArray(target) && (realStringObj - parseFloat(realStringObj) + 1) >= 0; -} - -/** - * 判断是否为宿主环境全局对象 - * - * 在浏览器环境中就是 `window` 对象 - * - * @param {*} target 目标 - */ -export function isGlobal( target: any ): boolean { - return target && isLooseObject(target) && 'setInterval' in target; -} - -/** - * 判断是否为类数组对象 - * - * @param {*} target 目标 - */ -export function isArrayLike( target: any ): boolean { - let result = false; - - if ( isLooseObject(target) && !isGlobal(target) ) { - const length = target.length; - - if ( target.nodeType === 1 && length || !isArray(target) && !isFunction(target) && (length === 0 || isNumber(length) && length > 0 && (length - 1) in target) ) { - result = true; - } - } - - return result; -} - -/** - * 判断是否为纯对象 - * - * @param {*} target 目标 - */ -export function isPlainObject( target: any ): boolean { - if ( !target || !isLooseObject(target) || target.nodeType || isGlobal(target) ) { - return false; - } - - try { - if ( target.constructor && !hasOwnProp('constructor', target) && !hasOwnProp('isPrototypeOf', target.constructor.prototype) ) { - return false; - } - } - catch ( err ) { - return false; - } - - let key; - - for ( key in target ) { - key; - } - - return key === undefined || hasOwnProp(key, target); -} diff --git a/src/utils/notification/index.ts b/src/utils/notification/index.ts index 2564cc7..9d05220 100644 --- a/src/utils/notification/index.ts +++ b/src/utils/notification/index.ts @@ -1,20 +1,22 @@ -import { isString, isFunction, isPlainObject } from '../is/type'; -import { mixin } from '../collection'; -import { setDefaults, getDefaults } from '../storage/helper'; +import { isString, isFunction, isPlainObject, mixin, setDefaults, getDefaults } from '@ntks/toolbox'; import { invoke } from '../../adapters/bridge'; import NOTIFICATION_DEFAULTS from './defaults'; setDefaults('notification', NOTIFICATION_DEFAULTS); -function generateNoticeUtil( icon: string ): Function { - return ( text: any, callback: Function ) => { - const opts: any = mixin({ +function generateNoticeUtil(icon: string): Function { + return (text: any, callback: Function) => { + const opts: any = mixin( + { text: '', - duration: getDefaults('notification.duration') - }, isPlainObject(text) ? text : {text}, {icon, callback}); + duration: getDefaults('notification.duration'), + }, + isPlainObject(text) ? text : { text }, + { icon, callback }, + ); - if ( !isFunction(opts.callback) ) { + if (!isFunction(opts.callback)) { opts.callback = () => {}; } @@ -28,18 +30,18 @@ export const success = generateNoticeUtil('success'); export const fail = generateNoticeUtil('fail'); -export function loading( text: any, callback: Function ): any { - if ( isFunction(text) ) { +export function loading(text: any, callback: Function): any { + if (isFunction(text)) { callback = text; } - if ( !isString(text) ) { + if (!isString(text)) { text = '加载中...'; } - return invoke('notice.loading.show', {text, callback}); + return invoke('notice.loading.show', { text, callback }); } -export function hide( callback: Function ): any { +export function hide(callback: Function): any { return invoke('notice.loading.hide', callback); } diff --git a/src/utils/socket/index.ts b/src/utils/socket/index.ts index f75232a..8d74ca2 100644 --- a/src/utils/socket/index.ts +++ b/src/utils/socket/index.ts @@ -1,22 +1,20 @@ -import { hasOwnProp, capitalize } from '../common/helper'; +import { isString, isFunction, isPlainObject, isNumeric, hasOwnProp, capitalize, each } from '@ntks/toolbox'; import { supportWebSocket } from '../common/supports'; -import { isString, isFunction, isPlainObject, isNumeric } from '../is/type'; -import { each } from '../collection'; /** * 获取处理后的 WebSocket 连接地址 * * @param {*} url */ -function resolveSocketUrl( url: string ): string { +function resolveSocketUrl(url: string): string { const isNoProtocol = url.indexOf('//') === 0; // 本地开发时强制替换为 ws 协议 - if ( location.hostname === 'localhost' ) { - url = isNoProtocol ? `ws:${url}` : url.replace(/^ws(s)?\:\/\//, 'ws\:\/\/'); + if (location.hostname === 'localhost') { + url = isNoProtocol ? `ws:${url}` : url.replace(/^ws(s)?\:\/\//, 'ws://'); } // 其他环境中无协议时采用 wss 协议 - else if ( isNoProtocol ) { + else if (isNoProtocol) { url = `wss:${url}`; } @@ -29,7 +27,7 @@ function resolveSocketUrl( url: string ): string { * @param {*} ws 连接实例 * @param {*} interval 发送信息间隔 */ -function keepSocketAlive( ws: WebSocket, interval: number ): void { +function keepSocketAlive(ws: WebSocket, interval: number): void { setTimeout(() => { ws.send('使 WebSocket 连接保持活跃'); keepSocketAlive(ws, interval); @@ -48,36 +46,36 @@ function keepSocketAlive( ws: WebSocket, interval: number ): void { * onError: function() {} * } */ -export function init( opts: any ): void | WebSocket { - if ( isString(opts) ) { - opts = {url: opts}; +export function init(opts: any): void | WebSocket { + if (isString(opts)) { + opts = { url: opts }; } - if ( !(supportWebSocket() && isPlainObject(opts) && hasOwnProp('url', opts)) ) { + if (!(supportWebSocket() && isPlainObject(opts) && hasOwnProp('url', opts))) { return; } const ws = new WebSocket(resolveSocketUrl(opts.url)); // 页面卸载时关闭连接 - if ( opts.closeBeforeUnload !== false ) { + if (opts.closeBeforeUnload !== false) { window.addEventListener('beforeunload', () => { ws.close(); }); } // 保持连接处于活跃状态 - if ( isNumeric(opts.interval) && opts.interval * 1 > 0 ) { + if (isNumeric(opts.interval) && opts.interval * 1 > 0) { ws.addEventListener('open', () => { keepSocketAlive(ws, opts.interval); }); } // 绑定指定事件 - each(['open', 'close', 'message', 'error'], ( evtName: string ) => { + each(['open', 'close', 'message', 'error'], (evtName: string) => { const handler = opts[`on${capitalize(evtName)}`]; - if ( isFunction(handler) ) { + if (isFunction(handler)) { ws.addEventListener(evtName, handler); } }); diff --git a/src/utils/storage/helper.ts b/src/utils/storage/helper.ts deleted file mode 100644 index 012cc0a..0000000 --- a/src/utils/storage/helper.ts +++ /dev/null @@ -1,149 +0,0 @@ -import { hasOwnProp } from '../common/helper'; -import { each, mixin, clone } from '../collection'; -import { isString, isPlainObject } from '../is/type'; - -const APP_DEFAULTS = { - theme: { - color: '#ff8903' - }, - behavior: 'native', - flexible: false - }; - -const PRIVATE_DATA = {}; -const BIZ_DATA = {}; - -/** - * 获取引用的键 - * - * @param {*} ref 引用 - */ -export function resolveRefKeys( ref: string ): string[] { - return isString(ref) && (new RegExp('^[0-9a-z_]+(\.[0-9a-z_]+)*$', 'i')).test(ref) ? ref.split('.') : []; -} - -/** - * 存储数据 - * - * @param {*} storage 储存体 - * @param {*} ref 数据的引用 - * @param {*} val 数据的值 - * @param {*} merge 合并配置项 - */ -export function saveData( storage: object, ref: string, val: any, merge?: boolean ): any { - const refKeys = resolveRefKeys(ref); - - if ( arguments.length < 3 || refKeys.length === 0 ) { - return; - } - - const lastKey = refKeys.pop(); - - let tmp: any = storage; - - each(refKeys, ( k: string ) => { - if ( !hasOwnProp(k, tmp) ) { - tmp[k] = {}; - } - - tmp = tmp[k]; - }); - - if ( merge === true && isPlainObject(tmp[lastKey!]) && isPlainObject(val) ) { - mixin(true, tmp[lastKey!], val); - } - else { - tmp[lastKey!] = val; - } - - return val; -} - -/** - * 获取数据 - * - * @param {*} storage 储存体 - * @param {*} ref 数据的引用 - */ -export function retrieveData( storage: object, ref: string ): any { - const refKeys = resolveRefKeys(ref); - const keyLength = refKeys.length; - - if ( keyLength === 0 ) { - return; - } - - let idx = 0; - let tmp = clone(storage); - let val, k; - - for ( ; idx < keyLength; idx++ ) { - k = refKeys[idx]; - val = tmp[k]; - - if ( !hasOwnProp(k, tmp) ) { - break; - } - - tmp = val; - } - - return val; -} - -/** - * 设置应用配置信息 - * - * @param ref - * @param val - */ -export function setDefaults( ref: string, val: any ): any { - return saveData(APP_DEFAULTS, ref, val, true); -} - -/** - * 获取应用配置信息 - * - * @param ref - */ -export function getDefaults( ref: string ): any { - return retrieveData(APP_DEFAULTS, ref); -} - -/** - * 设置应用私有数据 - * - * @param ref - * @param val - */ -export function setPrivate( ref: string, val: any ): any { - return saveData(PRIVATE_DATA, ref, val, true); -} - -/** - * 获取应用私有数据 - * - * @param ref - */ -export function getPrivate( ref: string ): any { - return retrieveData(PRIVATE_DATA, ref); -} - -/** - * 设置应用业务数据 - * - * @param ref - * @param val - */ -export function setBizData( ref: string, val: any ): any { - return saveData(BIZ_DATA, ref, val); -} - -/** - * 获取应用业务数据 - * - * @param ref - */ -export function getBizData( ref: string ): any { - return retrieveData(BIZ_DATA, ref); -} diff --git a/src/utils/storage/index.ts b/src/utils/storage/index.ts deleted file mode 100644 index f61416c..0000000 --- a/src/utils/storage/index.ts +++ /dev/null @@ -1 +0,0 @@ -export { setBizData as set, getBizData as get } from './helper'; diff --git a/src/utils/text/index.ts b/src/utils/text/index.ts index e91fe3d..d1db4b3 100644 --- a/src/utils/text/index.ts +++ b/src/utils/text/index.ts @@ -1,7 +1,6 @@ -import { isString } from '../is/type'; -import { includes } from '../collection'; +import { isString, includes } from '@ntks/toolbox'; -function copyText( content: string ): string { +function copyText(content: string): string { const ipt = document.createElement('input'); ipt.setAttribute('value', content); @@ -13,22 +12,21 @@ function copyText( content: string ): string { return content; } -export function copy( content: any, keepSelected?: boolean ): void | string { +export function copy(content: any, keepSelected?: boolean): void | string { let $el; - if ( !isString(content) ) { + if (!isString(content)) { $el = $(content); const el = $el.get(0); - if ( el == null || el.nodeType !== 1 ) { + if (el == null || el.nodeType !== 1) { return; } - if ( includes(el.tagName.toLowerCase(), ['input', 'textarea']) ) { + if (includes(el.tagName.toLowerCase(), ['input', 'textarea'])) { content = $el.val(); - } - else { + } else { content = $el.text(); } } @@ -36,7 +34,7 @@ export function copy( content: any, keepSelected?: boolean ): void | string { copyText(content); // 将被复制文本的区域保持选中状态 - if ( $el && keepSelected === true ) { + if ($el && keepSelected === true) { $el.select(); } diff --git a/src/utils/uploader/helper.ts b/src/utils/uploader/helper.ts index c56d377..11e3a37 100644 --- a/src/utils/uploader/helper.ts +++ b/src/utils/uploader/helper.ts @@ -1,4 +1,4 @@ -import { hasOwnProp } from '../common/helper'; +import { hasOwnProp } from '@ntks/toolbox'; /** * 判断是否支持 Plupload diff --git a/src/utils/uploader/index.ts b/src/utils/uploader/index.ts index 7b1b392..6a96b2e 100644 --- a/src/utils/uploader/index.ts +++ b/src/utils/uploader/index.ts @@ -1,8 +1,15 @@ -import { hasOwnProp } from '../common/helper'; -import { isString, isFunction, isPlainObject } from '../is/type'; -import { isUrl } from '../is/format'; -import { each, last, mixin } from '../collection'; -import { setDefaults, getDefaults } from '../storage/helper'; +import { + isString, + isFunction, + isPlainObject, + isUrl, + hasOwnProp, + each, + last, + mixin, + setDefaults, + getDefaults, +} from '@ntks/toolbox'; import { supportPlupload, supportQiniu } from './helper'; import UPLOADER_DEFAULTS from './defaults'; diff --git a/src/utils/url/helper.ts b/src/utils/url/helper.ts deleted file mode 100644 index 495681b..0000000 --- a/src/utils/url/helper.ts +++ /dev/null @@ -1,69 +0,0 @@ -import { isString } from '../is/type'; -import { isUrl } from '../is/format'; -import { includes, each } from '../collection'; - -/** - * 创建一个临时 `` 用于获取 URL 信息 - * - * @param {*} url URL - */ -function createTemporaryLinkElement( url: string ): any { - const el = document.createElement('a'); - - el.setAttribute('href', url); - - return el; -} - -/** - * 获取指定 URL 片段 - * - * @param {*} part 目标片段 - * @param {*} url URL - */ -export function sliceUrlPart( part: string, url: string ): string { - if ( !isString(url) || !isUrl(url) && url.indexOf('URL_PLACEHOLDER') === -1 ) { - url = window.location.href; - } - - const result = createTemporaryLinkElement(url)[part]; - - return includes(part, ['hash', 'search']) ? result.slice(1) : result; -} - -/** - * 获取指定 URL 的文件扩展名 - * - * @param {*} url URL - */ -export function resolveFileExtension( url: string ): string { - const segments = sliceUrlPart('pathname', url).split('\/'); - const length = segments.length; - - let fileName = segments[length - 1]; - - if ( fileName === '' ) { - fileName = segments[length - 2]; - } - - const ext = fileName.match(/\.([^\.]+)$/); - - return ext ? ext[1].toUpperCase() : ''; -} - -/** - * 将查询字符串转换为 JSON 对象 - * - * @param {*} str - */ -export function jsonifyQueryString( str: string ): object { - const jsonData: any = {}; - - each(str.split('&'), ( seg: string ) => { - const pair = seg.split('='); - - jsonData[pair[0]] = decodeURIComponent(pair[1]); - }); - - return jsonData; -} diff --git a/src/utils/url/index.ts b/src/utils/url/index.ts deleted file mode 100644 index 2218e2b..0000000 --- a/src/utils/url/index.ts +++ /dev/null @@ -1,50 +0,0 @@ -import { isString } from '../is/type'; -import { sliceUrlPart, jsonifyQueryString } from './helper'; - -function generateUrlUtil( part: string ): Function { - return ( url: string ) => sliceUrlPart(part, url); -} - -const urlSearchUtil = generateUrlUtil('search'); - -export const href = generateUrlUtil('href'); - -export const protocol = generateUrlUtil('protocol'); - -export const host = generateUrlUtil('host'); - -export const hostname = generateUrlUtil('hostname'); - -export const port = generateUrlUtil('port'); - -export const pathname = generateUrlUtil('pathname'); - -export const hash = generateUrlUtil('hash'); - -export const username = generateUrlUtil('username'); - -export const password = generateUrlUtil('password'); - -export const origin = generateUrlUtil('origin'); - -export function query( url: string, key: string ): string { - const defaultUrl = window.location.href; - const length = arguments.length; - - if ( length === 1 && isString(url) && url.indexOf('http') === -1 ) { - key = url; - url = defaultUrl; - } - - if ( !isString(url) ) { - url = defaultUrl; - } - - const jsonified: any = jsonifyQueryString(urlSearchUtil(url)); - - return key == null ? jsonified : jsonified[key]; -} - -export { - urlSearchUtil as search -} From 1c8c42f1fe6f0827325e6261728223d67858891d Mon Sep 17 00:00:00 2001 From: Ourai Lin Date: Tue, 2 Jun 2020 20:39:14 +0800 Subject: [PATCH 3/3] 1.0.13 --- package-lock.json | 2 +- package.json | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/package-lock.json b/package-lock.json index 4870a77..7757b42 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,6 +1,6 @@ { "name": "handie", - "version": "1.0.12", + "version": "1.0.13", "lockfileVersion": 1, "requires": true, "dependencies": { diff --git a/package.json b/package.json index a3bbb10..ca66516 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "handie", - "version": "1.0.12", + "version": "1.0.13", "description": "为前端开发提供统一的布局、组件和工具方法", "main": "handie.esm.js", "typings": "typings/index.d.ts",