UNPKG

@antdv/pro-utils

Version:

@antdv/pro-utils

116 lines (115 loc) 3.38 kB
import { get } from "@antdv/pro-provider"; import dayjs from "dayjs"; import quarterOfYear from "dayjs/plugin/quarterOfYear"; import { isNil, isObject } from "../is/index.mjs"; dayjs.extend(quarterOfYear); const dateFormatterMap = { time: "HH:mm:ss", timeRange: "HH:mm:ss", date: "YYYY-MM-DD", dateWeek: "YYYY-wo", dateMonth: "YYYY-MM", dateQuarter: "YYYY-[Q]Q", dateYear: "YYYY", dateRange: "YYYY-MM-DD", dateTime: "YYYY-MM-DD HH:mm:ss", dateTimeRange: "YYYY-MM-DD HH:mm:ss" }; function isPlainObject(o) { if (isObject(o) === false) return false; const ctor = o.constructor; if (ctor === void 0) return true; const prot = ctor.prototype; if (isObject(prot) === false) return false; if (prot.hasOwnProperty("isPrototypeOf") === false) { return false; } return true; } const isMoment = (value) => !!(value == null ? void 0 : value._isAMomentObject); function convertMoment(value, dateFormatter, valueType) { if (!dateFormatter) { return value; } if (dayjs.isDayjs(value) || isMoment(value)) { if (dateFormatter === "number") { return value.valueOf(); } if (dateFormatter === "string") { return value.format( dateFormatterMap[valueType] || "YYYY-MM-DD HH:mm:ss" ); } if (typeof dateFormatter === "string" && dateFormatter !== "string") { return value.format(dateFormatter); } if (typeof dateFormatter === "function") { return dateFormatter(value, valueType); } } return value; } function conversionMomentValue(value, dateFormatter, valueTypeMap, omitNil, parentKey) { const tmpValue = {}; if (typeof window === "undefined") return value; if (typeof value !== "object" || isNil(value) || value instanceof Blob || Array.isArray(value)) { return value; } Object.keys(value).forEach((valueKey) => { const namePath = parentKey ? [parentKey, valueKey].flat(1) : [valueKey]; const valueFormatMap = get(valueTypeMap, namePath) || "text"; let valueType = "text"; let dateFormat; if (typeof valueFormatMap === "string") { valueType = valueFormatMap; } else if (valueFormatMap) { valueType = valueFormatMap.valueType; dateFormat = valueFormatMap.dateFormat; } const itemValue = value[valueKey]; if (isNil(itemValue) && omitNil) { return; } if (isPlainObject(itemValue) && !Array.isArray(itemValue) && !dayjs.isDayjs(itemValue) && !isMoment(itemValue)) { tmpValue[valueKey] = conversionMomentValue( itemValue, dateFormatter, valueTypeMap, omitNil, namePath ); return; } if (Array.isArray(itemValue)) { tmpValue[valueKey] = itemValue.map((arrayValue, index) => { if (dayjs.isDayjs(arrayValue) || isMoment(arrayValue)) { return convertMoment( arrayValue, dateFormat || dateFormatter, valueType ); } return conversionMomentValue( arrayValue, dateFormatter, valueTypeMap, omitNil, [valueKey, `${index}`].flat(1) ); }); return; } tmpValue[valueKey] = convertMoment( itemValue, dateFormat || dateFormatter, valueType ); }); return tmpValue; } export { conversionMomentValue, convertMoment, dateFormatterMap, isPlainObject };