UNPKG

@korautils/forms

Version:

![image](https://github.com/user-attachments/assets/ccad1514-7b15-4952-9856-fd03b971403a)

1 lines 7.54 kB
{"version":3,"sources":["../src/modules/core/utils/index.ts"],"names":["ObjectUtils","obj","path","key","keysToRemove","newObj","delProp","getProp","object","defaultValue","getPropFn","isArrayEmpty","array"],"mappings":"kIA6CaA,IAAAA,CAAAA,CAAc,CACzB,GAAK,CAAA,CAACC,CAAUC,CAAAA,CAAAA,GACDA,EAAK,KAAM,CAAA,GAAG,EACf,KACTC,CAAAA,CAAAA,EAAaF,GAAO,IAAQA,EAAAA,CAAAA,CAAI,eAAeE,CAAG,CAAA,GAAMF,EAAMA,CAAIE,CAAAA,CAAG,EACxE,CAEF,CAAA,MAAA,CAAQ,CAACF,CAA0BG,CAAAA,CAAAA,GAA4B,CAC7D,IAAMC,EAAS,CAAE,GAAGJ,CAAI,CACxB,CAAA,OAAAG,EAAa,OAASD,CAAAA,CAAAA,EAAQ,CAC5BG,GAAQD,CAAAA,CAAAA,CAAQF,CAAG,EACrB,CAAC,EACME,CACT,CACF,EAEaE,CAAU,CAAA,CAACC,CAAaN,CAAAA,CAAAA,CAAcO,IAC5CD,CAIEE,CAAAA,GAAAA,CAAUF,EAAQN,CAAMO,CAAAA,CAAY,EAHlCA,EAsJJ,IAAME,EAAmBC,CACvB,EAAA,CAACA,GAASA,CAAM,CAAA,MAAA,GAAW,GAAK,CAAC,KAAA,CAAM,QAAQA,CAAK","file":"chunk-6DPEEXVJ.mjs","sourcesContent":["import metadata from 'libphonenumber-js/metadata.min.json'\nimport { CountryCode, parsePhoneNumber } from 'libphonenumber-js'\nimport { get as getPropFn, del as delProp } from 'object-path'\nimport { v4 as uuidv4 } from 'uuid'\nimport { KoraComponentProps } from '@/modules/builder/interfaces/elements/components'\n\ntype PathKey = string | number\n\nexport function countryToFlag(isoCode: string) {\n if (!isoCode) {\n return ''\n }\n const country =\n typeof String.fromCodePoint !== 'undefined'\n ? isoCode\n .toUpperCase()\n .replace(/./g, (char) =>\n String.fromCodePoint(char.charCodeAt(0) + 127397)\n )\n : isoCode\n return country\n}\n\nexport const getPrefix = (countryCode?: string) => {\n if (!countryCode) {\n return '1'\n }\n\n return metadata.countries[countryCode as CountryCode]?.[0]\n}\n\nexport const getParts = ({ geoip, value }: any) => {\n let codeNumber = getPrefix(geoip?.country),\n phone = ''\n try {\n if (value) {\n const parsedNumber = parsePhoneNumber(value)\n codeNumber = parsedNumber.countryCallingCode\n phone = parsedNumber.nationalNumber\n }\n } catch (error) {}\n\n return { codeNumber, phone }\n}\n\nexport const ObjectUtils = {\n has: (obj: any, path: any) => {\n const keys = path.split('.')\n return keys.every(\n (key: any) => obj != null && obj.hasOwnProperty(key) && (obj = obj[key])\n )\n },\n remove: (obj: Record<string, any>, keysToRemove: PathKey[]) => {\n const newObj = { ...obj }\n keysToRemove.forEach((key) => {\n delProp(newObj, key)\n })\n return newObj\n },\n}\n\nexport const getProp = (object: any, path: string, defaultValue?: any) => {\n if (!object) {\n return defaultValue\n }\n\n return getPropFn(object, path, defaultValue)\n}\n\nexport const getMany = (object: object | undefined, keyPaths: string[]) => {\n if (typeof object !== 'object' || Array.isArray(object)) {\n return []\n }\n\n const gotten = keyPaths.map((keyPath) => {\n const gottenValue = getProp(object, keyPath)\n return gottenValue\n })\n\n return gotten\n}\n\nexport const slugify = (str: string): string => {\n if (typeof str != 'string') {\n return ''\n }\n\n return str\n .toLowerCase() // Convertir a minúsculas\n .normalize('NFD') // Descomponer caracteres especiales\n .replace(/[\\u0300-\\u036f]/g, '') // Eliminar diacríticos\n .replace(/[^a-z0-9 ]/g, '') // Eliminar caracteres especiales excepto letras y números\n .trim() // Eliminar espacios en blanco al inicio y al final\n .replace(/\\s+/g, '-') // Reemplazar espacios con guiones\n .replace(/-+/g, '-') // Reemplazar guiones consecutivos con un solo guión\n}\n\nexport const pascalCaseToSnakeCase = (iconName: string | undefined) => {\n if (!iconName || typeof iconName !== 'string') {\n return iconName\n }\n\n return iconName\n .replace(/([a-z])([A-Z])/g, '$1_$2') // Inserta guión bajo entre minúscula y mayúscula\n .toLowerCase() // Convierte todo a minúsculas\n}\n\nexport interface NodeItem {\n id: number | string\n parent: number\n text: string\n droppable: boolean\n type: { id: string; label: string }\n url: string\n icon: any\n children?: NodeItem[]\n}\n\nexport const convertToTreeData = (flatData: any): NodeItem[] => {\n // Objeto para almacenar los nodos por id para un acceso rápido\n const nodesById: { [key: number]: NodeItem } = {}\n\n // Primero, creamos un objeto por id para acceder a los nodos de manera eficiente\n flatData.forEach((node: any) => {\n nodesById[node.id] = {\n ...node,\n children: [], // Inicializamos un array para los hijos de cada nodo\n }\n })\n\n // Luego, creamos la estructura de árbol\n const tree: NodeItem[] = []\n flatData.forEach((node: any) => {\n // Si el nodo tiene un parent diferente de sí mismo, lo agregamos como hijo del parent\n if (node.parent !== node.id) {\n const parentNode = nodesById[node.parent]\n if (parentNode) {\n parentNode.children?.push(nodesById[node.id])\n } else {\n // Si el parent no existe en nodesById, lo agregamos al árbol principal\n tree.push(nodesById[node.id])\n }\n } else {\n // Si el nodo no tiene parent (o parent igual a sí mismo), lo agregamos al árbol principal\n tree.push(nodesById[node.id])\n }\n })\n\n return tree\n}\n\nexport { uuidv4 }\n\nexport const getRandomDecimal = (\n min: number,\n max: number,\n decimalPlaces: number = 2\n): number => {\n const factor = Math.pow(10, decimalPlaces)\n return Math.floor((Math.random() * (max - min) + min) * factor) / factor\n}\n\nexport const removeBearer = (token: string): string => {\n return token.replace(/^Bearer\\s/, '')\n}\n\nexport const formatBearerToken = (token: string): string => {\n return `Bearer ${token}`\n}\n\nexport const isUUIDv4 = (id: string) => {\n const uuidv4Regex =\n /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i\n return uuidv4Regex.test(id)\n}\n\nexport const isMongoId = (id?: string) => {\n if (!id) {\n return false\n }\n\n const mongoObjectIdRegex = /^[0-9a-fA-F]{24}$/\n return mongoObjectIdRegex.test(id)\n}\n\nexport const getLocationPathname = (): any => {\n if (typeof window !== 'undefined') {\n const pathname = location?.pathname\n const replacedPathname = pathname.replace(/^\\/[^\\/]+\\//, '/')\n return replacedPathname\n }\n}\n\nexport const isJSON = (str: string) => {\n const jsonRegex = /^[\\],:{}\\s]*$/.test(\n str\n .replace(/\\\\[\"\\\\\\/bfnrtu]/g, '@')\n .replace(\n /\"[^\"\\\\\\n\\r]*\"|\\b(true|false|null|-?\\d+(?:\\.\\d*)?(?:[eE][+\\-]?\\d+)?)\\b/g,\n ']'\n )\n .replace(/(?:^|:|,)(?:\\s*\\[)+/g, '')\n )\n\n return jsonRegex\n}\n\nexport const orderComponents = (_listComponents: Array<KoraComponentProps>) => {\n return _listComponents.sort(\n (a, b) => getProp(a, 'order', 0) - getProp(b, 'order', 0)\n )\n}\n\nexport const isArrayEmpty = <T>(array: T[] | undefined): boolean => {\n return !array || array.length === 0 || !Array.isArray(array)\n}\n\nexport const isValidObject = (valor: string) => {\n try {\n // Primero verificamos si el valor es nulo o una cadena vacía\n if (valor === null || valor === '') {\n return false\n }\n\n // Intentamos parsear el valor como JSON\n const objeto = JSON.parse(valor)\n\n // Verificamos si el resultado es un objeto\n return objeto && typeof objeto === 'object' && !Array.isArray(objeto)\n } catch (e) {\n // Si ocurre un error en el parseo, no es un JSON válido\n return false\n }\n}\n"]}