diff --git a/packages/vant/docs/site/use-translate.ts b/packages/vant/docs/site/use-translate.ts index ec122e425..7e7fd8ef1 100644 --- a/packages/vant/docs/site/use-translate.ts +++ b/packages/vant/docs/site/use-translate.ts @@ -1,7 +1,6 @@ import Locale from '../../src/locale'; import enUS from '../../src/locale/lang/en-US'; -import { camelize } from '../../src/utils/format/string'; -import { createTranslate } from '../../src/utils/create/translate'; +import { camelize, createTranslate } from '../../src/utils'; import type { App } from 'vue'; import type { Router } from 'vue-router'; diff --git a/packages/vant/src/address-edit/AddressEdit.tsx b/packages/vant/src/address-edit/AddressEdit.tsx index 328282d89..44b3fc9a9 100644 --- a/packages/vant/src/address-edit/AddressEdit.tsx +++ b/packages/vant/src/address-edit/AddressEdit.tsx @@ -50,9 +50,7 @@ const DEFAULT_DATA: AddressEditInfo = { addressDetail: '', }; -function isPostal(value: string) { - return /^\d{6}$/.test(value); -} +const isPostal = (value: string) => /^\d{6}$/.test(value); const props = { areaList: Object as PropType, diff --git a/packages/vant/src/area/Area.tsx b/packages/vant/src/area/Area.tsx index f000efe47..3c469ea2f 100644 --- a/packages/vant/src/area/Area.tsx +++ b/packages/vant/src/area/Area.tsx @@ -46,9 +46,7 @@ const INHERIT_PROPS = [ 'confirmButtonText', ] as const; -function isOverseaCode(code: string) { - return code[0] === '9'; -} +const isOverseaCode = (code: string) => code[0] === '9'; const props = extend({}, pickerProps, { value: String, diff --git a/packages/vant/src/calendar/utils.ts b/packages/vant/src/calendar/utils.ts index 29b198915..bfc8f58ad 100644 --- a/packages/vant/src/calendar/utils.ts +++ b/packages/vant/src/calendar/utils.ts @@ -4,9 +4,8 @@ const [name, bem, t] = createNamespace('calendar'); export { name, bem, t }; -export function formatMonthTitle(date: Date) { - return t('monthTitle', date.getFullYear(), date.getMonth() + 1); -} +export const formatMonthTitle = (date: Date) => + t('monthTitle', date.getFullYear(), date.getMonth() + 1); export function compareMonth(date1: Date, date2: Date) { const year1 = date1.getFullYear(); diff --git a/packages/vant/src/circle/Circle.tsx b/packages/vant/src/circle/Circle.tsx index 20d3747f9..fabaa70a1 100644 --- a/packages/vant/src/circle/Circle.tsx +++ b/packages/vant/src/circle/Circle.tsx @@ -6,9 +6,7 @@ const [name, bem] = createNamespace('circle'); let uid = 0; -function format(rate: string | number) { - return Math.min(Math.max(+rate, 0), 100); -} +const format = (rate: string | number) => Math.min(Math.max(+rate, 0), 100); function getPath(clockwise: boolean, viewBoxSize: number) { const sweepFlag = clockwise ? 1 : 0; diff --git a/packages/vant/src/composables/use-placeholder.tsx b/packages/vant/src/composables/use-placeholder.tsx index 70344d9cf..f2c70f2bc 100644 --- a/packages/vant/src/composables/use-placeholder.tsx +++ b/packages/vant/src/composables/use-placeholder.tsx @@ -1,6 +1,6 @@ import { Ref } from 'vue'; import { useHeight } from './use-height'; -import type { BEM } from '../utils/create/bem'; +import type { BEM } from '../utils/create'; export function usePlaceholder(contentRef: Ref, bem: BEM) { const height = useHeight(contentRef); diff --git a/packages/vant/src/coupon/Coupon.tsx b/packages/vant/src/coupon/Coupon.tsx index 1d68f8ad2..7ee657adb 100644 --- a/packages/vant/src/coupon/Coupon.tsx +++ b/packages/vant/src/coupon/Coupon.tsx @@ -27,15 +27,11 @@ function getDate(timeStamp: number) { )}`; } -function formatDiscount(discount: number) { - return (discount / 10).toFixed(discount % 10 === 0 ? 0 : 1); -} +const formatDiscount = (discount: number) => + (discount / 10).toFixed(discount % 10 === 0 ? 0 : 1); -function formatAmount(amount: number) { - return (amount / 100).toFixed( - amount % 100 === 0 ? 0 : amount % 10 === 0 ? 1 : 2 - ); -} +const formatAmount = (amount: number) => + (amount / 100).toFixed(amount % 100 === 0 ? 0 : amount % 10 === 0 ? 1 : 2); export default defineComponent({ name, diff --git a/packages/vant/src/datetime-picker/utils.ts b/packages/vant/src/datetime-picker/utils.ts index 4eb81ced2..e667adf8c 100644 --- a/packages/vant/src/datetime-picker/utils.ts +++ b/packages/vant/src/datetime-picker/utils.ts @@ -43,6 +43,5 @@ export function getTrueValue(value: string | undefined): number { return parseInt(value, 10); } -export function getMonthEndDay(year: number, month: number): number { - return 32 - new Date(year, month - 1, 32).getDate(); -} +export const getMonthEndDay = (year: number, month: number): number => + 32 - new Date(year, month - 1, 32).getDate(); diff --git a/packages/vant/src/icon/Icon.tsx b/packages/vant/src/icon/Icon.tsx index 8302d1f55..01c3aa7c3 100644 --- a/packages/vant/src/icon/Icon.tsx +++ b/packages/vant/src/icon/Icon.tsx @@ -5,9 +5,7 @@ import { CONFIG_PROVIDER_KEY } from '../config-provider/ConfigProvider'; const [name, bem] = createNamespace('icon'); -function isImage(name?: string) { - return name?.includes('/'); -} +const isImage = (name?: string) => name?.includes('/'); export default defineComponent({ name, diff --git a/packages/vant/src/image-preview/ImagePreviewItem.tsx b/packages/vant/src/image-preview/ImagePreviewItem.tsx index 89e5920cb..686b1b74e 100644 --- a/packages/vant/src/image-preview/ImagePreviewItem.tsx +++ b/packages/vant/src/image-preview/ImagePreviewItem.tsx @@ -11,12 +11,11 @@ import { Image } from '../image'; import { Loading } from '../loading'; import { SwipeItem } from '../swipe-item'; -function getDistance(touches: TouchList) { - return Math.sqrt( +const getDistance = (touches: TouchList) => + Math.sqrt( (touches[0].clientX - touches[1].clientX) ** 2 + (touches[0].clientY - touches[1].clientY) ** 2 ); -} const bem = createNamespace('image-preview')[1]; diff --git a/packages/vant/src/index-anchor/IndexAnchor.tsx b/packages/vant/src/index-anchor/IndexAnchor.tsx index 60fa97a49..4140b5122 100644 --- a/packages/vant/src/index-anchor/IndexAnchor.tsx +++ b/packages/vant/src/index-anchor/IndexAnchor.tsx @@ -8,7 +8,7 @@ import { createNamespace, } from '../utils'; import { INDEX_BAR_KEY } from '../index-bar/IndexBar'; -import { getScrollTop, getRootScrollTop } from '../utils/dom/scroll'; +import { getScrollTop, getRootScrollTop } from '../utils/dom'; // Composables import { useRect, useParent } from '@vant/use'; diff --git a/packages/vant/src/notify/function-call.tsx b/packages/vant/src/notify/function-call.tsx index 6da0e3f3b..4ba5e7371 100644 --- a/packages/vant/src/notify/function-call.tsx +++ b/packages/vant/src/notify/function-call.tsx @@ -13,9 +13,8 @@ import type { NotifyMessage, NotifyOptions } from './types'; let timer: number; let instance: ComponentInstance; -function parseOptions(message: NotifyMessage | NotifyOptions) { - return isObject(message) ? message : { message }; -} +const parseOptions = (message: NotifyMessage | NotifyOptions) => + isObject(message) ? message : { message }; function initInstance() { ({ instance } = mountComponent({ @@ -47,20 +46,18 @@ function Notify(options: NotifyMessage | NotifyOptions) { return instance; } -function defaultOptions() { - return { - type: 'danger', - color: undefined, - message: '', - onClose: undefined, - onClick: undefined, - onOpened: undefined, - duration: 3000, - className: '', - lockScroll: false, - background: undefined, - } as NotifyOptions; -} +const getDefaultOptions = (): NotifyOptions => ({ + type: 'danger', + color: undefined, + message: '', + onClose: undefined, + onClick: undefined, + onOpened: undefined, + duration: 3000, + className: '', + lockScroll: false, + background: undefined, +}); Notify.clear = () => { if (instance) { @@ -68,14 +65,14 @@ Notify.clear = () => { } }; -Notify.currentOptions = defaultOptions(); +Notify.currentOptions = getDefaultOptions(); Notify.setDefaultOptions = (options: NotifyOptions) => { extend(Notify.currentOptions, options); }; Notify.resetDefaultOptions = () => { - Notify.currentOptions = defaultOptions(); + Notify.currentOptions = getDefaultOptions(); }; Notify.Component = withInstall(VanNotify); diff --git a/packages/vant/src/pagination/Pagination.tsx b/packages/vant/src/pagination/Pagination.tsx index 617d78df3..0de4a48db 100644 --- a/packages/vant/src/pagination/Pagination.tsx +++ b/packages/vant/src/pagination/Pagination.tsx @@ -9,13 +9,11 @@ type PageItem = { active?: boolean; }; -function makePage( +const makePage = ( number: number, text: string | number, active?: boolean -): PageItem { - return { number, text, active }; -} +): PageItem => ({ number, text, active }); export type PaginationMode = 'simple' | 'multi'; diff --git a/packages/vant/src/picker/PickerColumn.tsx b/packages/vant/src/picker/PickerColumn.tsx index 5940fad2e..1e743dff6 100644 --- a/packages/vant/src/picker/PickerColumn.tsx +++ b/packages/vant/src/picker/PickerColumn.tsx @@ -36,9 +36,8 @@ function getElementTranslateY(element: Element) { export const PICKER_KEY = Symbol(name); -function isOptionDisabled(option: PickerOption) { - return isObject(option) && option.disabled; -} +const isOptionDisabled = (option: PickerOption) => + isObject(option) && option.disabled; export default defineComponent({ name, diff --git a/packages/vant/src/stepper/Stepper.tsx b/packages/vant/src/stepper/Stepper.tsx index d7c9c0ae8..d12bede4e 100644 --- a/packages/vant/src/stepper/Stepper.tsx +++ b/packages/vant/src/stepper/Stepper.tsx @@ -23,9 +23,8 @@ const [name, bem] = createNamespace('stepper'); const LONG_PRESS_INTERVAL = 200; const LONG_PRESS_START_TIME = 600; -function equal(value1?: string | number, value2?: string | number) { - return String(value1) === String(value2); -} +const isEqual = (value1?: string | number, value2?: string | number) => + String(value1) === String(value2); export type StepperTheme = 'default' | 'round'; @@ -107,7 +106,7 @@ export default defineComponent({ const defaultValue = props.modelValue ?? props.defaultValue; const value = format(defaultValue); - if (!equal(value, props.modelValue)) { + if (!isEqual(value, props.modelValue)) { emit('update:modelValue', value); } @@ -135,7 +134,7 @@ export default defineComponent({ const check = () => { const value = format(current.value); - if (!equal(value, current.value)) { + if (!isEqual(value, current.value)) { current.value = value; } }; @@ -185,7 +184,7 @@ export default defineComponent({ if (props.beforeChange) { input.value = String(current.value); - } else if (!equal(value, formatted)) { + } else if (!isEqual(value, formatted)) { input.value = formatted; } @@ -281,7 +280,7 @@ export default defineComponent({ watch( () => props.modelValue, (value) => { - if (!equal(value, current.value)) { + if (!isEqual(value, current.value)) { current.value = format(value!); } } diff --git a/packages/vant/src/uploader/utils.ts b/packages/vant/src/uploader/utils.ts index c15ad06a1..c98876fca 100644 --- a/packages/vant/src/uploader/utils.ts +++ b/packages/vant/src/uploader/utils.ts @@ -9,13 +9,8 @@ const [name, bem] = createNamespace('uploader'); export { name, bem }; -export function toArray(item: T | T[]): T[] { - if (Array.isArray(item)) { - return item; - } - - return [item]; -} +export const toArray = (item: T | T[]): T[] => + Array.isArray(item) ? item : [item]; export function readFileContent(file: File, resultType: UploaderResultType) { return new Promise((resolve) => { @@ -73,9 +68,7 @@ export function filterFiles( const IMAGE_REGEXP = /\.(jpeg|jpg|gif|png|svg|webp|jfif|bmp|dpg)/i; -export function isImageUrl(url: string): boolean { - return IMAGE_REGEXP.test(url); -} +export const isImageUrl = (url: string): boolean => IMAGE_REGEXP.test(url); export function isImageFile(item: UploaderFileListItem): boolean { // some special urls cannot be recognized diff --git a/packages/vant/src/utils/base.ts b/packages/vant/src/utils/basic.ts similarity index 100% rename from packages/vant/src/utils/base.ts rename to packages/vant/src/utils/basic.ts diff --git a/packages/vant/src/utils/create.ts b/packages/vant/src/utils/create.ts new file mode 100644 index 000000000..6295d0abc --- /dev/null +++ b/packages/vant/src/utils/create.ts @@ -0,0 +1,71 @@ +import { get } from './basic'; +import { camelize } from './format'; +import { isFunction } from './validate'; +import locale from '../locale'; + +export function createTranslate(name: string) { + const prefix = camelize(name) + '.'; + + return (path: string, ...args: any[]): any => { + const messages = locale.messages(); + const message = get(messages, prefix + path) || get(messages, path); + + return isFunction(message) ? message(...args) : message; + }; +} + +export type Translate = ReturnType; + +export type Mod = string | { [key: string]: any }; +export type Mods = Mod | Mod[]; + +function genBem(name: string, mods?: Mods): string { + if (!mods) { + return ''; + } + + if (typeof mods === 'string') { + return ` ${name}--${mods}`; + } + + if (Array.isArray(mods)) { + return mods.reduce((ret, item) => ret + genBem(name, item), ''); + } + + return Object.keys(mods).reduce( + (ret, key) => ret + (mods[key] ? genBem(name, key) : ''), + '' + ); +} + +/** + * bem helper + * b() // 'button' + * b('text') // 'button__text' + * b({ disabled }) // 'button button--disabled' + * b('text', { disabled }) // 'button__text button__text--disabled' + * b(['disabled', 'primary']) // 'button button--disabled button--primary' + */ +export function createBEM(name: string) { + return (el?: Mods, mods?: Mods): Mods => { + if (el && typeof el !== 'string') { + mods = el; + el = ''; + } + + el = el ? `${name}__${el}` : name; + + return `${el}${genBem(el, mods)}`; + }; +} + +export type BEM = ReturnType; + +export function createNamespace(name: string) { + const prefixedName = `van-${name}`; + return [ + prefixedName, + createBEM(prefixedName), + createTranslate(prefixedName), + ] as const; +} diff --git a/packages/vant/src/utils/create/bem.ts b/packages/vant/src/utils/create/bem.ts deleted file mode 100644 index 7d599680c..000000000 --- a/packages/vant/src/utils/create/bem.ts +++ /dev/null @@ -1,45 +0,0 @@ -/** - * bem helper - * b() // 'button' - * b('text') // 'button__text' - * b({ disabled }) // 'button button--disabled' - * b('text', { disabled }) // 'button__text button__text--disabled' - * b(['disabled', 'primary']) // 'button button--disabled button--primary' - */ - -export type Mod = string | { [key: string]: any }; -export type Mods = Mod | Mod[]; - -function gen(name: string, mods?: Mods): string { - if (!mods) { - return ''; - } - - if (typeof mods === 'string') { - return ` ${name}--${mods}`; - } - - if (Array.isArray(mods)) { - return mods.reduce((ret, item) => ret + gen(name, item), ''); - } - - return Object.keys(mods).reduce( - (ret, key) => ret + (mods[key] ? gen(name, key) : ''), - '' - ); -} - -export function createBEM(name: string) { - return function (el?: Mods, mods?: Mods): Mods { - if (el && typeof el !== 'string') { - mods = el; - el = ''; - } - - el = el ? `${name}__${el}` : name; - - return `${el}${gen(el, mods)}`; - }; -} - -export type BEM = ReturnType; diff --git a/packages/vant/src/utils/create/index.ts b/packages/vant/src/utils/create/index.ts deleted file mode 100644 index 1c5612771..000000000 --- a/packages/vant/src/utils/create/index.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { createBEM } from './bem'; -import { createTranslate } from './translate'; - -export function createNamespace(name: string) { - const prefixedName = `van-${name}`; - return [ - prefixedName, - createBEM(prefixedName), - createTranslate(prefixedName), - ] as const; -} diff --git a/packages/vant/src/utils/create/translate.ts b/packages/vant/src/utils/create/translate.ts deleted file mode 100644 index 264e065bd..000000000 --- a/packages/vant/src/utils/create/translate.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { get } from '../base'; -import { camelize } from '../format/string'; -import { isFunction } from '../validate'; -import locale from '../../locale'; - -export function createTranslate(name: string) { - const prefix = camelize(name) + '.'; - - return function (path: string, ...args: any[]): any { - const messages = locale.messages(); - const message = get(messages, prefix + path) || get(messages, path); - - return isFunction(message) ? message(...args) : message; - }; -} - -export type Translate = ReturnType; diff --git a/packages/vant/src/utils/dom/scroll.ts b/packages/vant/src/utils/dom.ts similarity index 55% rename from packages/vant/src/utils/dom/scroll.ts rename to packages/vant/src/utils/dom.ts index 2c2856d7c..71ae48d93 100644 --- a/packages/vant/src/utils/dom/scroll.ts +++ b/packages/vant/src/utils/dom.ts @@ -1,10 +1,9 @@ -import { isIOS as checkIsIOS } from '../validate'; +import { unref, Ref } from 'vue'; +import { isIOS as checkIsIOS } from './validate'; export type ScrollElement = Element | Window; -function isWindow(val: unknown): val is Window { - return val === window; -} +const isWindow = (val: unknown): val is Window => val === window; export function getScrollTop(el: ScrollElement): number { const top = 'scrollTop' in el ? el.scrollTop : el.pageYOffset; @@ -68,3 +67,41 @@ export function resetScroll() { setRootScrollTop(getRootScrollTop()); } } + +export const stopPropagation = (event: Event) => event.stopPropagation(); + +export function preventDefault(event: Event, isStopPropagation?: boolean) { + /* istanbul ignore else */ + if (typeof event.cancelable !== 'boolean' || event.cancelable) { + event.preventDefault(); + } + + if (isStopPropagation) { + stopPropagation(event); + } +} + +export function trigger(target: Element, type: string) { + const inputEvent = document.createEvent('HTMLEvents'); + inputEvent.initEvent(type, true, true); + target.dispatchEvent(inputEvent); +} + +export function isHidden( + elementRef: HTMLElement | Ref +) { + const el = unref(elementRef); + if (!el) { + return false; + } + + const style = window.getComputedStyle(el); + const hidden = style.display === 'none'; + + // offsetParent returns null in the following situations: + // 1. The element or its parent element has the display property set to none. + // 2. The element has the position property set to fixed + const parentHidden = el.offsetParent === null && style.position !== 'fixed'; + + return hidden || parentHidden; +} diff --git a/packages/vant/src/utils/dom/event.ts b/packages/vant/src/utils/dom/event.ts deleted file mode 100644 index 8f73fac5c..000000000 --- a/packages/vant/src/utils/dom/event.ts +++ /dev/null @@ -1,20 +0,0 @@ -export function stopPropagation(event: Event) { - event.stopPropagation(); -} - -export function preventDefault(event: Event, isStopPropagation?: boolean) { - /* istanbul ignore else */ - if (typeof event.cancelable !== 'boolean' || event.cancelable) { - event.preventDefault(); - } - - if (isStopPropagation) { - stopPropagation(event); - } -} - -export function trigger(target: Element, type: string) { - const inputEvent = document.createEvent('HTMLEvents'); - inputEvent.initEvent(type, true, true); - target.dispatchEvent(inputEvent); -} diff --git a/packages/vant/src/utils/dom/style.ts b/packages/vant/src/utils/dom/style.ts deleted file mode 100644 index 0c180497d..000000000 --- a/packages/vant/src/utils/dom/style.ts +++ /dev/null @@ -1,20 +0,0 @@ -import { unref, Ref } from 'vue'; - -export function isHidden( - elementRef: HTMLElement | Ref -) { - const el = unref(elementRef); - if (!el) { - return false; - } - - const style = window.getComputedStyle(el); - const hidden = style.display === 'none'; - - // offsetParent returns null in the following situations: - // 1. The element or its parent element has the display property set to none. - // 2. The element has the position property set to fixed - const parentHidden = el.offsetParent === null && style.position !== 'fixed'; - - return hidden || parentHidden; -} diff --git a/packages/vant/src/utils/format/unit.ts b/packages/vant/src/utils/format.ts similarity index 50% rename from packages/vant/src/utils/format/unit.ts rename to packages/vant/src/utils/format.ts index 36fabc2db..7d8877ec4 100644 --- a/packages/vant/src/utils/format/unit.ts +++ b/packages/vant/src/utils/format.ts @@ -1,6 +1,6 @@ import { CSSProperties } from 'vue'; -import { inBrowser } from '../base'; -import { isDef, isNumeric } from '../validate'; +import { inBrowser } from './basic'; +import { isDef, isNumeric } from './validate'; export function addUnit(value?: string | number): string | undefined { if (!isDef(value)) { @@ -79,3 +79,70 @@ export function unitToPx(value: string | number): number { return parseFloat(value); } + +const camelizeRE = /-(\w)/g; + +export const camelize = (str: string): string => + str.replace(camelizeRE, (_, c) => c.toUpperCase()); + +export const kebabCase = (str: string) => + str + .replace(/([A-Z])/g, '-$1') + .toLowerCase() + .replace(/^-/, ''); + +export function padZero(num: number | string, targetLength = 2): string { + let str = num + ''; + + while (str.length < targetLength) { + str = '0' + str; + } + + return str; +} + +/** clamps number within the inclusive lower and upper bounds */ +export const clamp = (num: number, min: number, max: number): number => + Math.min(Math.max(num, min), max); + +function trimExtraChar(value: string, char: string, regExp: RegExp) { + const index = value.indexOf(char); + + if (index === -1) { + return value; + } + + if (char === '-' && index !== 0) { + return value.slice(0, index); + } + + return value.slice(0, index + 1) + value.slice(index).replace(regExp, ''); +} + +export function formatNumber( + value: string, + allowDot = true, + allowMinus = true +) { + if (allowDot) { + value = trimExtraChar(value, '.', /\./g); + } else { + value = value.split('.')[0]; + } + + if (allowMinus) { + value = trimExtraChar(value, '-', /-/g); + } else { + value = value.replace(/-/, ''); + } + + const regExp = allowDot ? /[^-0-9.]/g : /[^-0-9]/g; + + return value.replace(regExp, ''); +} + +// add num and avoid float number +export function addNumber(num1: number, num2: number) { + const cardinal = 10 ** 10; + return Math.round((num1 + num2) * cardinal) / cardinal; +} diff --git a/packages/vant/src/utils/format/number.ts b/packages/vant/src/utils/format/number.ts deleted file mode 100644 index 30dfb3ee0..000000000 --- a/packages/vant/src/utils/format/number.ts +++ /dev/null @@ -1,46 +0,0 @@ -/** clamps number within the inclusive lower and upper bounds */ -export function clamp(num: number, min: number, max: number): number { - return Math.min(Math.max(num, min), max); -} - -function trimExtraChar(value: string, char: string, regExp: RegExp) { - const index = value.indexOf(char); - - if (index === -1) { - return value; - } - - if (char === '-' && index !== 0) { - return value.slice(0, index); - } - - return value.slice(0, index + 1) + value.slice(index).replace(regExp, ''); -} - -export function formatNumber( - value: string, - allowDot = true, - allowMinus = true -) { - if (allowDot) { - value = trimExtraChar(value, '.', /\./g); - } else { - value = value.split('.')[0]; - } - - if (allowMinus) { - value = trimExtraChar(value, '-', /-/g); - } else { - value = value.replace(/-/, ''); - } - - const regExp = allowDot ? /[^-0-9.]/g : /[^-0-9]/g; - - return value.replace(regExp, ''); -} - -// add num and avoid float number -export function addNumber(num1: number, num2: number) { - const cardinal = 10 ** 10; - return Math.round((num1 + num2) * cardinal) / cardinal; -} diff --git a/packages/vant/src/utils/format/string.ts b/packages/vant/src/utils/format/string.ts deleted file mode 100644 index e1a0cde9f..000000000 --- a/packages/vant/src/utils/format/string.ts +++ /dev/null @@ -1,22 +0,0 @@ -const camelizeRE = /-(\w)/g; - -export function camelize(str: string): string { - return str.replace(camelizeRE, (_, c) => c.toUpperCase()); -} - -export function kebabCase(str: string) { - return str - .replace(/([A-Z])/g, '-$1') - .toLowerCase() - .replace(/^-/, ''); -} - -export function padZero(num: number | string, targetLength = 2): string { - let str = num + ''; - - while (str.length < targetLength) { - str = '0' + str; - } - - return str; -} diff --git a/packages/vant/src/utils/index.ts b/packages/vant/src/utils/index.ts index d9670bc2c..4f2786237 100644 --- a/packages/vant/src/utils/index.ts +++ b/packages/vant/src/utils/index.ts @@ -1,12 +1,8 @@ -export * from './base'; +export * from './basic'; +export * from './dom'; export * from './create'; +export * from './format'; export * from './constant'; export * from './validate'; -export * from './dom/style'; -export * from './dom/event'; -export * from './dom/scroll'; export * from './interceptor'; export * from './with-install'; -export * from './format/unit'; -export * from './format/number'; -export * from './format/string'; diff --git a/packages/vant/src/utils/test/bem.spec.ts b/packages/vant/src/utils/test/bem.spec.ts index e495e6cd6..51301a8fc 100644 --- a/packages/vant/src/utils/test/bem.spec.ts +++ b/packages/vant/src/utils/test/bem.spec.ts @@ -1,4 +1,4 @@ -import { createBEM } from '../create/bem'; +import { createBEM } from '../create'; test('bem', () => { const bem = createBEM('button'); diff --git a/packages/vant/src/utils/test/index.spec.ts b/packages/vant/src/utils/test/index.spec.ts index e678677da..2f2bdc15b 100644 --- a/packages/vant/src/utils/test/index.spec.ts +++ b/packages/vant/src/utils/test/index.spec.ts @@ -1,10 +1,8 @@ +import { get, noop } from '../basic'; import { deepClone } from '../deep-clone'; import { deepAssign } from '../deep-assign'; -import { get, noop } from '..'; import { isDef, isMobile, isNumeric } from '../validate'; -import { camelize } from '../format/string'; -import { formatNumber } from '../format/number'; -import { addUnit, unitToPx } from '../format/unit'; +import { addUnit, unitToPx, camelize, formatNumber } from '../format'; test('deepClone', () => { const a = { foo: 0 }; diff --git a/packages/vant/src/utils/validate.ts b/packages/vant/src/utils/validate.ts index beca29cc1..e00be87e6 100644 --- a/packages/vant/src/utils/validate.ts +++ b/packages/vant/src/utils/validate.ts @@ -1,28 +1,21 @@ -import { inBrowser } from './base'; +import { inBrowser } from './basic'; -export function isDef(val: T): val is NonNullable { - return val !== undefined && val !== null; -} +export const isDef = (val: T): val is NonNullable => + val !== undefined && val !== null; // eslint-disable-next-line @typescript-eslint/ban-types -export function isFunction(val: unknown): val is Function { - return typeof val === 'function'; -} +export const isFunction = (val: unknown): val is Function => + typeof val === 'function'; -export function isObject(val: unknown): val is Record { - return val !== null && typeof val === 'object'; -} +export const isObject = (val: unknown): val is Record => + val !== null && typeof val === 'object'; -export function isPromise(val: unknown): val is Promise { - return isObject(val) && isFunction(val.then) && isFunction(val.catch); -} +export const isPromise = (val: unknown): val is Promise => + isObject(val) && isFunction(val.then) && isFunction(val.catch); -export function isDate(val: unknown): val is Date { - return ( - Object.prototype.toString.call(val) === '[object Date]' && - !Number.isNaN((val as Date).getTime()) - ); -} +export const isDate = (val: unknown): val is Date => + Object.prototype.toString.call(val) === '[object Date]' && + !Number.isNaN((val as Date).getTime()); export function isMobile(value: string): boolean { value = value.replace(/[^-|\d]/g, ''); @@ -31,12 +24,10 @@ export function isMobile(value: string): boolean { ); } -export function isNumeric(val: string | number): val is string { - return typeof val === 'number' || /^\d+(\.\d+)?$/.test(val); -} +export const isNumeric = (val: string | number): val is string => + typeof val === 'number' || /^\d+(\.\d+)?$/.test(val); -export function isIOS(): boolean { - return inBrowser +export const isIOS = (): boolean => + inBrowser ? /ios|iphone|ipad|ipod/.test(navigator.userAgent.toLowerCase()) : false; -} diff --git a/packages/vant/src/utils/with-install.ts b/packages/vant/src/utils/with-install.ts index f92840b22..48ecaf917 100644 --- a/packages/vant/src/utils/with-install.ts +++ b/packages/vant/src/utils/with-install.ts @@ -1,5 +1,5 @@ import { App } from 'vue'; -import { camelize } from './format/string'; +import { camelize } from './format'; // https://github.com/youzan/vant/issues/8302 type EventShim = {