general.ts 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  1. import { makeMap } from './makeMap'
  2. export const EMPTY_OBJ: { readonly [key: string]: any } = __DEV__
  3. ? Object.freeze({})
  4. : {}
  5. export const EMPTY_ARR: readonly never[] = __DEV__ ? Object.freeze([]) : []
  6. export const NOOP = (): void => {}
  7. /**
  8. * Always return true.
  9. */
  10. export const YES = () => true
  11. /**
  12. * Always return false.
  13. */
  14. export const NO = () => false
  15. export const isOn = (key: string): boolean =>
  16. key.charCodeAt(0) === 111 /* o */ &&
  17. key.charCodeAt(1) === 110 /* n */ &&
  18. // uppercase letter
  19. (key.charCodeAt(2) > 122 || key.charCodeAt(2) < 97)
  20. export const isNativeOn = (key: string): boolean =>
  21. key.charCodeAt(0) === 111 /* o */ &&
  22. key.charCodeAt(1) === 110 /* n */ &&
  23. // lowercase letter
  24. key.charCodeAt(2) > 96 &&
  25. key.charCodeAt(2) < 123
  26. export const isModelListener = (key: string): boolean =>
  27. key.startsWith('onUpdate:')
  28. export const extend: typeof Object.assign = Object.assign
  29. export const remove = <T>(arr: T[], el: T): void => {
  30. const i = arr.indexOf(el)
  31. if (i > -1) {
  32. arr.splice(i, 1)
  33. }
  34. }
  35. const hasOwnProperty = Object.prototype.hasOwnProperty
  36. export const hasOwn = (
  37. val: object,
  38. key: string | symbol,
  39. ): key is keyof typeof val => hasOwnProperty.call(val, key)
  40. export const isArray: typeof Array.isArray = Array.isArray
  41. export const isMap = (val: unknown): val is Map<any, any> =>
  42. toTypeString(val) === '[object Map]'
  43. export const isSet = (val: unknown): val is Set<any> =>
  44. toTypeString(val) === '[object Set]'
  45. export const isDate = (val: unknown): val is Date =>
  46. toTypeString(val) === '[object Date]'
  47. export const isRegExp = (val: unknown): val is RegExp =>
  48. toTypeString(val) === '[object RegExp]'
  49. export const isFunction = (val: unknown): val is Function =>
  50. typeof val === 'function'
  51. export const isString = (val: unknown): val is string => typeof val === 'string'
  52. export const isSymbol = (val: unknown): val is symbol => typeof val === 'symbol'
  53. export const isObject = (val: unknown): val is Record<any, any> =>
  54. val !== null && typeof val === 'object'
  55. export const isPromise = <T = any>(val: unknown): val is Promise<T> => {
  56. return (
  57. (isObject(val) || isFunction(val)) &&
  58. isFunction((val as any).then) &&
  59. isFunction((val as any).catch)
  60. )
  61. }
  62. export const objectToString: typeof Object.prototype.toString =
  63. Object.prototype.toString
  64. export const toTypeString = (value: unknown): string =>
  65. objectToString.call(value)
  66. export const toRawType = (value: unknown): string => {
  67. // extract "RawType" from strings like "[object RawType]"
  68. return toTypeString(value).slice(8, -1)
  69. }
  70. export const isPlainObject = (val: unknown): val is object =>
  71. toTypeString(val) === '[object Object]'
  72. export const isIntegerKey = (key: unknown): boolean =>
  73. isString(key) &&
  74. key !== 'NaN' &&
  75. key[0] !== '-' &&
  76. '' + parseInt(key, 10) === key
  77. export const isReservedProp: (key: string) => boolean = /*@__PURE__*/ makeMap(
  78. // the leading comma is intentional so empty string "" is also included
  79. ',key,ref,ref_for,ref_key,' +
  80. 'onVnodeBeforeMount,onVnodeMounted,' +
  81. 'onVnodeBeforeUpdate,onVnodeUpdated,' +
  82. 'onVnodeBeforeUnmount,onVnodeUnmounted',
  83. )
  84. export const isBuiltInTag: (key: string) => boolean =
  85. /*#__PURE__*/ makeMap('slot,component')
  86. export const isBuiltInDirective: (key: string) => boolean =
  87. /*@__PURE__*/ makeMap(
  88. 'bind,cloak,else-if,else,for,html,if,model,on,once,pre,show,slot,text,memo',
  89. )
  90. const cacheStringFunction = <T extends (str: string) => string>(fn: T): T => {
  91. const cache: Record<string, string> = Object.create(null)
  92. return ((str: string) => {
  93. const hit = cache[str]
  94. return hit || (cache[str] = fn(str))
  95. }) as T
  96. }
  97. const camelizeRE = /-(\w)/g
  98. const camelizeReplacer = (_: any, c: string) => (c ? c.toUpperCase() : '')
  99. /**
  100. * @private
  101. */
  102. export const camelize: (str: string) => string = cacheStringFunction(
  103. (str: string): string => str.replace(camelizeRE, camelizeReplacer),
  104. )
  105. const hyphenateRE = /\B([A-Z])/g
  106. /**
  107. * @private
  108. */
  109. export const hyphenate: (str: string) => string = cacheStringFunction(
  110. (str: string) => str.replace(hyphenateRE, '-$1').toLowerCase(),
  111. )
  112. /**
  113. * @private
  114. */
  115. export const capitalize: <T extends string>(str: T) => Capitalize<T> =
  116. cacheStringFunction(<T extends string>(str: T) => {
  117. return (str.charAt(0).toUpperCase() + str.slice(1)) as Capitalize<T>
  118. })
  119. /**
  120. * @private
  121. */
  122. export const toHandlerKey: <T extends string>(
  123. str: T,
  124. ) => T extends '' ? '' : `on${Capitalize<T>}` = cacheStringFunction(
  125. <T extends string>(str: T) => {
  126. const s = str ? `on${capitalize(str)}` : ``
  127. return s as T extends '' ? '' : `on${Capitalize<T>}`
  128. },
  129. )
  130. /**
  131. * #13070 When v-model and v-model:model directives are used together,
  132. * they will generate the same modelModifiers prop,
  133. * so a `$` suffix is added to avoid conflicts.
  134. * @private
  135. */
  136. export const getModifierPropName = (name: string): string => {
  137. return `${
  138. name === 'modelValue' || name === 'model-value' ? 'model' : name
  139. }Modifiers${name === 'model' ? '$' : ''}`
  140. }
  141. // compare whether a value has changed, accounting for NaN.
  142. export const hasChanged = (value: any, oldValue: any): boolean =>
  143. !Object.is(value, oldValue)
  144. export const invokeArrayFns = (fns: Function[], ...arg: any[]): void => {
  145. for (let i = 0; i < fns.length; i++) {
  146. fns[i](...arg)
  147. }
  148. }
  149. export const def = (
  150. obj: object,
  151. key: string | symbol,
  152. value: any,
  153. writable = false,
  154. ): void => {
  155. Object.defineProperty(obj, key, {
  156. configurable: true,
  157. enumerable: false,
  158. writable,
  159. value,
  160. })
  161. }
  162. /**
  163. * "123-foo" will be parsed to 123
  164. * This is used for the .number modifier in v-model
  165. */
  166. export const looseToNumber = (val: any): any => {
  167. const n = parseFloat(val)
  168. return isNaN(n) ? val : n
  169. }
  170. /**
  171. * Only concerns number-like strings
  172. * "123-foo" will be returned as-is
  173. */
  174. export const toNumber = (val: any): any => {
  175. const n = isString(val) ? Number(val) : NaN
  176. return isNaN(n) ? val : n
  177. }
  178. // for typeof global checks without @types/node
  179. declare var global: {}
  180. let _globalThis: any
  181. export const getGlobalThis = (): any => {
  182. return (
  183. _globalThis ||
  184. (_globalThis =
  185. typeof globalThis !== 'undefined'
  186. ? globalThis
  187. : typeof self !== 'undefined'
  188. ? self
  189. : typeof window !== 'undefined'
  190. ? window
  191. : typeof global !== 'undefined'
  192. ? global
  193. : {})
  194. )
  195. }
  196. const identRE = /^[_$a-zA-Z\xA0-\uFFFF][_$a-zA-Z0-9\xA0-\uFFFF]*$/
  197. export function genPropsAccessExp(name: string): string {
  198. return identRE.test(name)
  199. ? `__props.${name}`
  200. : `__props[${JSON.stringify(name)}]`
  201. }
  202. export function genCacheKey(source: string, options: any): string {
  203. return (
  204. source +
  205. JSON.stringify(options, (_, val) =>
  206. typeof val === 'function' ? val.toString() : val,
  207. )
  208. )
  209. }
  210. export function canSetValueDirectly(tagName: string): boolean {
  211. return (
  212. tagName !== 'PROGRESS' &&
  213. // custom elements may use _value internally
  214. !tagName.includes('-')
  215. )
  216. }