@domql/utils
Advanced tools
Comparing version
39
array.js
@@ -23,4 +23,2 @@ 'use strict' | ||
arr.splice(index, 1) | ||
} else if (isArray(index)) { | ||
index.forEach(idx => removeFromArray(arr, idx)) | ||
} else { | ||
@@ -33,3 +31,3 @@ throw new Error('Invalid index') | ||
export const swapItemsInArray = (arr, i, j) => { | ||
[arr[i], arr[j]] = [arr[j], arr[i]] | ||
;[arr[i], arr[j]] = [arr[j], arr[i]] | ||
} | ||
@@ -44,13 +42,9 @@ | ||
*/ | ||
export const mergeArray = (arr, exclude = []) => { | ||
return arr.reduce((a, c) => deepMerge(a, deepClone(c, { exclude }), exclude), {}) | ||
export const unstackArrayOfObjects = (arr, exclude = []) => { | ||
return arr.reduce( | ||
(a, c) => deepMerge(a, deepClone(c, { exclude }), exclude), | ||
{} | ||
) | ||
} | ||
/** | ||
* Merges array extends | ||
*/ | ||
export const mergeAndCloneIfArray = obj => { | ||
return isArray(obj) ? mergeArray(obj) : deepClone(obj) | ||
} | ||
export const cutArrayBeforeValue = (arr, value) => { | ||
@@ -111,3 +105,6 @@ const index = arr.indexOf(value) | ||
const removedItem = newArray.splice(indexToMove, 1)[0] // Remove the item to move | ||
const insertIndex = indexToInsertBefore < indexToMove ? indexToInsertBefore : indexToInsertBefore + 1 // Adjust insert index | ||
const insertIndex = | ||
indexToInsertBefore < indexToMove | ||
? indexToInsertBefore | ||
: indexToInsertBefore + 1 // Adjust insert index | ||
newArray.splice(insertIndex, 0, removedItem) // Insert the removed item before the specified value | ||
@@ -147,1 +144,17 @@ } | ||
} | ||
export const removeDuplicatesInArray = arr => { | ||
if (!isArray(arr)) return arr | ||
return [...new Set(arr)] | ||
} | ||
export const addProtoToArray = (state, proto) => { | ||
for (const key in proto) { | ||
Object.defineProperty(state, key, { | ||
value: proto[key], | ||
enumerable: false, // Set this to true if you want the method to appear in for...in loops | ||
configurable: true, // Set this to true if you want to allow redefining/removing the property later | ||
writable: true // Set this to true if you want to allow changing the function later | ||
}) | ||
} | ||
} |
237
component.js
'use strict' | ||
import { joinArrays } from './array.js' | ||
import { deepClone, exec } from './object.js' | ||
import { isArray, isFunction, isObject, isString } from './types.js' | ||
import { createExtendsFromKeys } from './extends.js' | ||
import { isString } from './types.js' | ||
const ENV = process.env.NODE_ENV | ||
export const checkIfKeyIsComponent = (key) => { | ||
export const matchesComponentNaming = key => { | ||
const isFirstKeyString = isString(key) | ||
@@ -16,98 +13,2 @@ if (!isFirstKeyString) return | ||
export const checkIfKeyIsProperty = (key) => { | ||
const isFirstKeyString = isString(key) | ||
if (!isFirstKeyString) return | ||
const firstCharKey = key.slice(0, 1) | ||
return /^[a-z]*$/.test(firstCharKey) | ||
} | ||
export const addAdditionalExtend = (newExtend, element) => { | ||
if (!newExtend) return element | ||
const { extend: elementExtend } = element | ||
const originalArray = isArray(elementExtend) ? elementExtend : [elementExtend] | ||
const receivedArray = isArray(newExtend) ? newExtend : [newExtend] | ||
const extend = joinArrays(receivedArray, originalArray) | ||
return { ...element, extend } | ||
} | ||
export const checkIfSugar = (element, parent, key) => { | ||
const { | ||
extend, | ||
props, | ||
childExtend, | ||
extends: extendProps, | ||
childExtends, | ||
childProps, | ||
children, | ||
on, | ||
$collection, | ||
$stateCollection, | ||
$propsCollection | ||
} = element | ||
const hasComponentAttrs = extend || childExtend || props || on || $collection || $stateCollection || $propsCollection | ||
if (hasComponentAttrs && (childProps || extendProps || children || childExtends)) { | ||
const logErr = (parent || element)?.error | ||
if (logErr) logErr.call(element, 'Sugar component includes params for builtin components', { verbose: true }) | ||
} | ||
return !hasComponentAttrs || childProps || extendProps || children || childExtends | ||
} | ||
export const extractComponentKeyFromKey = (key) => { | ||
return key.includes('+') | ||
? key.split('+') // get array of componentKeys | ||
: key.includes('_') | ||
? [key.split('_')[0]] // get component key split _ | ||
: key.includes('.') && !checkIfKeyIsComponent(key.split('.')[1]) | ||
? [key.split('.')[0]] // get component key split . | ||
: [key] | ||
} | ||
export const extendizeByKey = (element, parent, key) => { | ||
const { context } = parent | ||
const { tag, extend, childExtends } = element | ||
const isSugar = checkIfSugar(element, parent, key) | ||
const extendFromKey = extractComponentKeyFromKey(key) | ||
const isExtendKeyComponent = context && context.components[extendFromKey] | ||
if (element === isExtendKeyComponent) return element | ||
else if (isSugar) { | ||
const newElem = addAdditionalExtend(element.extends, { | ||
extend: extendFromKey, | ||
tag, | ||
props: { ...element } | ||
}) | ||
if (newElem.props.data) { | ||
newElem.data = newElem.props.data | ||
delete newElem.props.data | ||
} | ||
if (newElem.props.state) { | ||
newElem.state = newElem.props.state | ||
delete newElem.props.state | ||
} | ||
if (newElem.props.attr) { | ||
newElem.attr = newElem.props.attr | ||
delete newElem.props.attr | ||
} | ||
if (newElem.props.if) { | ||
newElem.if = newElem.props.if | ||
delete newElem.props.if | ||
} | ||
if (childExtends) newElem.childExtend = childExtends | ||
return newElem | ||
} else if (!extend || extend === true) { | ||
return { | ||
...element, | ||
tag, | ||
extend: extendFromKey | ||
} | ||
} else if (extend) { | ||
return addAdditionalExtend(extendFromKey, element) | ||
} else if (isFunction(element)) { | ||
return { | ||
extend: extendFromKey, | ||
tag, | ||
props: { ...exec(element, parent) } | ||
} | ||
} | ||
} | ||
export function getCapitalCaseKeys (obj) { | ||
@@ -117,129 +18,11 @@ return Object.keys(obj).filter(key => /^[A-Z]/.test(key)) | ||
export const addChildrenIfNotInOriginal = (element, parent, key) => { | ||
const childElems = getCapitalCaseKeys(element.props) | ||
if (!childElems.length) return element | ||
for (const i in childElems) { | ||
const childKey = childElems[i] | ||
const childElem = element[childKey] | ||
const newChild = element.props[childKey] | ||
const assignChild = (val) => { | ||
element[childKey] = val | ||
delete element.props[childKey] | ||
} | ||
if (newChild?.ignoreExtend) continue | ||
if (newChild === null) assignChild(null) | ||
else if (!childElem) assignChild(deepClone(newChild)) | ||
else { | ||
const isSugarChildElem = checkIfSugar(childElem, parent, key) | ||
if (isSugarChildElem) continue | ||
assignChild({ | ||
extend: element[childKey], | ||
props: newChild | ||
}) | ||
} | ||
} | ||
export function getSpreadChildren (obj) { | ||
return Object.keys(obj).filter(key => /^\d+$/.test(key)) | ||
} | ||
export const applyKeyComponentAsExtend = (element, parent, key) => { | ||
return extendizeByKey(element, parent, key) || element | ||
export function isContextComponent (element, parent, passedKey) { | ||
const { context } = parent || {} | ||
const [extendsKey] = createExtendsFromKeys(passedKey) | ||
const key = passedKey || extendsKey | ||
return context?.components?.[key] || context?.pages?.[key] | ||
} | ||
export const applyComponentFromContext = (element, parent, options) => { | ||
const { context } = element | ||
if (!context || !context.components) return | ||
const { components } = context | ||
const { extend } = element | ||
const execExtend = exec(extend, element) | ||
if (isString(execExtend)) { | ||
const componentExists = components[execExtend] || components['smbls.' + execExtend] | ||
if (componentExists) element.extend = componentExists | ||
else { | ||
if ((ENV === 'test' || ENV === 'development') && options.verbose) { | ||
console.warn(execExtend, 'is not in library', components, element) | ||
console.warn('replacing with ', {}) | ||
} | ||
element.extend = {} | ||
} | ||
} | ||
} | ||
export const isVariant = (param) => { | ||
if (!isString(param)) return | ||
const firstCharKey = param.slice(0, 1) | ||
// return (firstCharKey === '.' || firstCharKey === '$') | ||
return (firstCharKey === '.') | ||
} | ||
export const hasVariantProp = (element) => { | ||
const { props } = element | ||
if (isObject(props) && isString(props.variant)) return true | ||
} | ||
export const getChildrenComponentsByKey = (key, el) => { | ||
if (key === el.key || el.__ref.__componentKey === key) { | ||
return el | ||
} | ||
// Check if the prop is "extend" and it's either a string or an array | ||
if (el.extend) { | ||
// Add the value of the extend key to the result array | ||
const foundString = isString(el.extend) && el.extend === key | ||
const foundInArray = isArray(el.extend) && el.extend.filter(v => v === key).length | ||
if (foundString || foundInArray) return el | ||
} | ||
if (el.parent && el.parent.childExtend) { | ||
// Add the value of the extend key to the result array | ||
const foundString = isString(el.parent.childExtend) && el.parent.childExtend === key | ||
const foundInArray = isArray(el.parent.childExtend) && el.parent.childExtend.filter(v => v === key).length | ||
if (foundString || foundInArray) return el | ||
} | ||
} | ||
export const getExtendsInElement = (obj) => { | ||
let result = [] | ||
function traverse (o) { | ||
for (const key in o) { | ||
if (Object.hasOwnProperty.call(o, key)) { | ||
// Check if the key starts with a capital letter and exclude keys like @mobileL, $propsCollection | ||
if (checkIfKeyIsComponent(key)) { | ||
result.push(key) | ||
} | ||
// Check if the key is "extend" and it's either a string or an array | ||
if (key === 'extend' || key === 'extends') { | ||
// Add the value of the extend key to the result array | ||
if (typeof o[key] === 'string') { | ||
result.push(o[key]) | ||
} else if (Array.isArray(o[key])) { | ||
result = result.concat(o[key]) | ||
} | ||
} | ||
// If the property is an object, traverse it | ||
if (typeof o[key] === 'object' && o[key] !== null) { | ||
traverse(o[key]) | ||
} | ||
} | ||
} | ||
} | ||
traverse(obj) | ||
return result | ||
} | ||
export const setContentKey = (el, opts = {}) => { | ||
const { __ref: ref } = el | ||
const contentElementKey = opts.contentElementKey | ||
if ((contentElementKey !== 'content' && contentElementKey !== ref.contentElementKey) || !ref.contentElementKey) { | ||
ref.contentElementKey = contentElementKey || 'content' | ||
} else ref.contentElementKey = 'content' | ||
if (contentElementKey !== 'content') opts.contentElementKey = 'content' | ||
return ref.contentElementKey | ||
} |
@@ -6,5 +6,4 @@ 'use strict' | ||
export const isMobile = (() => typeof navigator === 'undefined' | ||
? false | ||
: /Mobi/.test(navigator.userAgent))() | ||
export const isMobile = (() => | ||
typeof navigator === 'undefined' ? false : /Mobi/.test(navigator.userAgent))() | ||
@@ -14,3 +13,3 @@ export const setCookie = (cname, cvalue, exdays = 365) => { | ||
const d = new Date() | ||
d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000)) | ||
d.setTime(d.getTime() + exdays * 24 * 60 * 60 * 1000) | ||
const expires = `expires=${d.toUTCString()}` | ||
@@ -20,3 +19,3 @@ document.cookie = `${cname}=${cvalue};${expires};path=/` | ||
export const getCookie = (cname) => { | ||
export const getCookie = cname => { | ||
if (isUndefined(document) || isUndefined(document.cookie)) return | ||
@@ -34,25 +33,30 @@ const name = `${cname}=` | ||
export const removeCookie = (cname) => { | ||
export const removeCookie = cname => { | ||
if (isUndefined(document) || isUndefined(document.cookie)) return | ||
document.cookie = cname + '=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;' | ||
} | ||
/** | ||
* Load item from the localStorage | ||
* | ||
* @param key -- string to identify the storage item | ||
*/ | ||
* Load item from the localStorage | ||
* | ||
* @param key -- string to identify the storage item | ||
* @returns {*} -- parsed data or undefined | ||
*/ | ||
export function getLocalStorage (key) { | ||
let savedJSON | ||
if (!window.localStorage) { | ||
return undefined | ||
} | ||
if (window.localStorage) { | ||
try { | ||
savedJSON = JSON.parse(window.localStorage.getItem(key)) | ||
} catch (e) {} | ||
const item = window.localStorage.getItem(key) | ||
if (item === null) { | ||
return undefined | ||
} | ||
if (typeof savedJSON !== 'undefined') { | ||
return savedJSON | ||
try { | ||
return JSON.parse(item) | ||
} catch (e) { | ||
return undefined | ||
} | ||
} | ||
/** | ||
@@ -65,9 +69,8 @@ * Save the data to window.localStorage | ||
export function setLocalStorage (key, data) { | ||
if (data && window.localStorage) { | ||
if (typeof data === 'object') { | ||
window.localStorage.setItem(key, JSON.stringify(data)) | ||
} else { | ||
window.localStorage.setItem(key, data) | ||
} | ||
if (!window.localStorage || data === undefined || data === null) { | ||
return | ||
} | ||
const value = typeof data === 'object' ? JSON.stringify(data) : data | ||
window.localStorage.setItem(key, value) | ||
} |
@@ -22,2 +22,3 @@ "use strict"; | ||
addItemAfterEveryElement: () => addItemAfterEveryElement, | ||
addProtoToArray: () => addProtoToArray, | ||
arrayContainsOtherArray: () => arrayContainsOtherArray, | ||
@@ -32,4 +33,3 @@ arraysEqual: () => arraysEqual, | ||
joinArrays: () => joinArrays, | ||
mergeAndCloneIfArray: () => mergeAndCloneIfArray, | ||
mergeArray: () => mergeArray, | ||
removeDuplicatesInArray: () => removeDuplicatesInArray, | ||
removeFromArray: () => removeFromArray, | ||
@@ -39,3 +39,4 @@ removeValueFromArray: () => removeValueFromArray, | ||
reorderArrayByValues: () => reorderArrayByValues, | ||
swapItemsInArray: () => swapItemsInArray | ||
swapItemsInArray: () => swapItemsInArray, | ||
unstackArrayOfObjects: () => unstackArrayOfObjects | ||
}); | ||
@@ -60,4 +61,2 @@ module.exports = __toCommonJS(array_exports); | ||
arr.splice(index, 1); | ||
} else if ((0, import_types.isArray)(index)) { | ||
index.forEach((idx) => removeFromArray(arr, idx)); | ||
} else { | ||
@@ -69,2 +68,3 @@ throw new Error("Invalid index"); | ||
const swapItemsInArray = (arr, i, j) => { | ||
; | ||
[arr[i], arr[j]] = [arr[j], arr[i]]; | ||
@@ -75,8 +75,8 @@ }; | ||
}; | ||
const mergeArray = (arr, exclude = []) => { | ||
return arr.reduce((a, c) => (0, import_object.deepMerge)(a, (0, import_object.deepClone)(c, { exclude }), exclude), {}); | ||
const unstackArrayOfObjects = (arr, exclude = []) => { | ||
return arr.reduce( | ||
(a, c) => (0, import_object.deepMerge)(a, (0, import_object.deepClone)(c, { exclude }), exclude), | ||
{} | ||
); | ||
}; | ||
const mergeAndCloneIfArray = (obj) => { | ||
return (0, import_types.isArray)(obj) ? mergeArray(obj) : (0, import_object.deepClone)(obj); | ||
}; | ||
const cutArrayBeforeValue = (arr, value) => { | ||
@@ -152,1 +152,18 @@ const index = arr.indexOf(value); | ||
}; | ||
const removeDuplicatesInArray = (arr) => { | ||
if (!(0, import_types.isArray)(arr)) return arr; | ||
return [...new Set(arr)]; | ||
}; | ||
const addProtoToArray = (state, proto) => { | ||
for (const key in proto) { | ||
Object.defineProperty(state, key, { | ||
value: proto[key], | ||
enumerable: false, | ||
// Set this to true if you want the method to appear in for...in loops | ||
configurable: true, | ||
// Set this to true if you want to allow redefining/removing the property later | ||
writable: true | ||
// Set this to true if you want to allow changing the function later | ||
}); | ||
} | ||
}; |
@@ -21,24 +21,11 @@ "use strict"; | ||
__export(component_exports, { | ||
addAdditionalExtend: () => addAdditionalExtend, | ||
addChildrenIfNotInOriginal: () => addChildrenIfNotInOriginal, | ||
applyComponentFromContext: () => applyComponentFromContext, | ||
applyKeyComponentAsExtend: () => applyKeyComponentAsExtend, | ||
checkIfKeyIsComponent: () => checkIfKeyIsComponent, | ||
checkIfKeyIsProperty: () => checkIfKeyIsProperty, | ||
checkIfSugar: () => checkIfSugar, | ||
extendizeByKey: () => extendizeByKey, | ||
extractComponentKeyFromKey: () => extractComponentKeyFromKey, | ||
getCapitalCaseKeys: () => getCapitalCaseKeys, | ||
getChildrenComponentsByKey: () => getChildrenComponentsByKey, | ||
getExtendsInElement: () => getExtendsInElement, | ||
hasVariantProp: () => hasVariantProp, | ||
isVariant: () => isVariant, | ||
setContentKey: () => setContentKey | ||
getSpreadChildren: () => getSpreadChildren, | ||
isContextComponent: () => isContextComponent, | ||
matchesComponentNaming: () => matchesComponentNaming | ||
}); | ||
module.exports = __toCommonJS(component_exports); | ||
var import_array = require("./array.js"); | ||
var import_object = require("./object.js"); | ||
var import_extends = require("./extends.js"); | ||
var import_types = require("./types.js"); | ||
const ENV = "development"; | ||
const checkIfKeyIsComponent = (key) => { | ||
const matchesComponentNaming = (key) => { | ||
const isFirstKeyString = (0, import_types.isString)(key); | ||
@@ -49,192 +36,14 @@ if (!isFirstKeyString) return; | ||
}; | ||
const checkIfKeyIsProperty = (key) => { | ||
const isFirstKeyString = (0, import_types.isString)(key); | ||
if (!isFirstKeyString) return; | ||
const firstCharKey = key.slice(0, 1); | ||
return /^[a-z]*$/.test(firstCharKey); | ||
}; | ||
const addAdditionalExtend = (newExtend, element) => { | ||
if (!newExtend) return element; | ||
const { extend: elementExtend } = element; | ||
const originalArray = (0, import_types.isArray)(elementExtend) ? elementExtend : [elementExtend]; | ||
const receivedArray = (0, import_types.isArray)(newExtend) ? newExtend : [newExtend]; | ||
const extend = (0, import_array.joinArrays)(receivedArray, originalArray); | ||
return { ...element, extend }; | ||
}; | ||
const checkIfSugar = (element, parent, key) => { | ||
var _a; | ||
const { | ||
extend, | ||
props, | ||
childExtend, | ||
extends: extendProps, | ||
childExtends, | ||
childProps, | ||
children, | ||
on, | ||
$collection, | ||
$stateCollection, | ||
$propsCollection | ||
} = element; | ||
const hasComponentAttrs = extend || childExtend || props || on || $collection || $stateCollection || $propsCollection; | ||
if (hasComponentAttrs && (childProps || extendProps || children || childExtends)) { | ||
const logErr = (_a = parent || element) == null ? void 0 : _a.error; | ||
if (logErr) logErr.call(element, "Sugar component includes params for builtin components", { verbose: true }); | ||
} | ||
return !hasComponentAttrs || childProps || extendProps || children || childExtends; | ||
}; | ||
const extractComponentKeyFromKey = (key) => { | ||
return key.includes("+") ? key.split("+") : key.includes("_") ? [key.split("_")[0]] : key.includes(".") && !checkIfKeyIsComponent(key.split(".")[1]) ? [key.split(".")[0]] : [key]; | ||
}; | ||
const extendizeByKey = (element, parent, key) => { | ||
const { context } = parent; | ||
const { tag, extend, childExtends } = element; | ||
const isSugar = checkIfSugar(element, parent, key); | ||
const extendFromKey = extractComponentKeyFromKey(key); | ||
const isExtendKeyComponent = context && context.components[extendFromKey]; | ||
if (element === isExtendKeyComponent) return element; | ||
else if (isSugar) { | ||
const newElem = addAdditionalExtend(element.extends, { | ||
extend: extendFromKey, | ||
tag, | ||
props: { ...element } | ||
}); | ||
if (newElem.props.data) { | ||
newElem.data = newElem.props.data; | ||
delete newElem.props.data; | ||
} | ||
if (newElem.props.state) { | ||
newElem.state = newElem.props.state; | ||
delete newElem.props.state; | ||
} | ||
if (newElem.props.attr) { | ||
newElem.attr = newElem.props.attr; | ||
delete newElem.props.attr; | ||
} | ||
if (newElem.props.if) { | ||
newElem.if = newElem.props.if; | ||
delete newElem.props.if; | ||
} | ||
if (childExtends) newElem.childExtend = childExtends; | ||
return newElem; | ||
} else if (!extend || extend === true) { | ||
return { | ||
...element, | ||
tag, | ||
extend: extendFromKey | ||
}; | ||
} else if (extend) { | ||
return addAdditionalExtend(extendFromKey, element); | ||
} else if ((0, import_types.isFunction)(element)) { | ||
return { | ||
extend: extendFromKey, | ||
tag, | ||
props: { ...(0, import_object.exec)(element, parent) } | ||
}; | ||
} | ||
}; | ||
function getCapitalCaseKeys(obj) { | ||
return Object.keys(obj).filter((key) => /^[A-Z]/.test(key)); | ||
} | ||
const addChildrenIfNotInOriginal = (element, parent, key) => { | ||
const childElems = getCapitalCaseKeys(element.props); | ||
if (!childElems.length) return element; | ||
for (const i in childElems) { | ||
const childKey = childElems[i]; | ||
const childElem = element[childKey]; | ||
const newChild = element.props[childKey]; | ||
const assignChild = (val) => { | ||
element[childKey] = val; | ||
delete element.props[childKey]; | ||
}; | ||
if (newChild == null ? void 0 : newChild.ignoreExtend) continue; | ||
if (newChild === null) assignChild(null); | ||
else if (!childElem) assignChild((0, import_object.deepClone)(newChild)); | ||
else { | ||
const isSugarChildElem = checkIfSugar(childElem, parent, key); | ||
if (isSugarChildElem) continue; | ||
assignChild({ | ||
extend: element[childKey], | ||
props: newChild | ||
}); | ||
} | ||
} | ||
}; | ||
const applyKeyComponentAsExtend = (element, parent, key) => { | ||
return extendizeByKey(element, parent, key) || element; | ||
}; | ||
const applyComponentFromContext = (element, parent, options) => { | ||
const { context } = element; | ||
if (!context || !context.components) return; | ||
const { components } = context; | ||
const { extend } = element; | ||
const execExtend = (0, import_object.exec)(extend, element); | ||
if ((0, import_types.isString)(execExtend)) { | ||
const componentExists = components[execExtend] || components["smbls." + execExtend]; | ||
if (componentExists) element.extend = componentExists; | ||
else { | ||
if ((ENV === "test" || ENV === "development") && options.verbose) { | ||
console.warn(execExtend, "is not in library", components, element); | ||
console.warn("replacing with ", {}); | ||
} | ||
element.extend = {}; | ||
} | ||
} | ||
}; | ||
const isVariant = (param) => { | ||
if (!(0, import_types.isString)(param)) return; | ||
const firstCharKey = param.slice(0, 1); | ||
return firstCharKey === "."; | ||
}; | ||
const hasVariantProp = (element) => { | ||
const { props } = element; | ||
if ((0, import_types.isObject)(props) && (0, import_types.isString)(props.variant)) return true; | ||
}; | ||
const getChildrenComponentsByKey = (key, el) => { | ||
if (key === el.key || el.__ref.__componentKey === key) { | ||
return el; | ||
} | ||
if (el.extend) { | ||
const foundString = (0, import_types.isString)(el.extend) && el.extend === key; | ||
const foundInArray = (0, import_types.isArray)(el.extend) && el.extend.filter((v) => v === key).length; | ||
if (foundString || foundInArray) return el; | ||
} | ||
if (el.parent && el.parent.childExtend) { | ||
const foundString = (0, import_types.isString)(el.parent.childExtend) && el.parent.childExtend === key; | ||
const foundInArray = (0, import_types.isArray)(el.parent.childExtend) && el.parent.childExtend.filter((v) => v === key).length; | ||
if (foundString || foundInArray) return el; | ||
} | ||
}; | ||
const getExtendsInElement = (obj) => { | ||
let result = []; | ||
function traverse(o) { | ||
for (const key in o) { | ||
if (Object.hasOwnProperty.call(o, key)) { | ||
if (checkIfKeyIsComponent(key)) { | ||
result.push(key); | ||
} | ||
if (key === "extend" || key === "extends") { | ||
if (typeof o[key] === "string") { | ||
result.push(o[key]); | ||
} else if (Array.isArray(o[key])) { | ||
result = result.concat(o[key]); | ||
} | ||
} | ||
if (typeof o[key] === "object" && o[key] !== null) { | ||
traverse(o[key]); | ||
} | ||
} | ||
} | ||
} | ||
traverse(obj); | ||
return result; | ||
}; | ||
const setContentKey = (el, opts = {}) => { | ||
const { __ref: ref } = el; | ||
const contentElementKey = opts.contentElementKey; | ||
if (contentElementKey !== "content" && contentElementKey !== ref.contentElementKey || !ref.contentElementKey) { | ||
ref.contentElementKey = contentElementKey || "content"; | ||
} else ref.contentElementKey = "content"; | ||
if (contentElementKey !== "content") opts.contentElementKey = "content"; | ||
return ref.contentElementKey; | ||
}; | ||
function getSpreadChildren(obj) { | ||
return Object.keys(obj).filter((key) => /^\d+$/.test(key)); | ||
} | ||
function isContextComponent(element, parent, passedKey) { | ||
var _a, _b; | ||
const { context } = parent || {}; | ||
const [extendsKey] = (0, import_extends.createExtendsFromKeys)(passedKey); | ||
const key = passedKey || extendsKey; | ||
return ((_a = context == null ? void 0 : context.components) == null ? void 0 : _a[key]) || ((_b = context == null ? void 0 : context.pages) == null ? void 0 : _b[key]); | ||
} |
@@ -56,21 +56,21 @@ "use strict"; | ||
function getLocalStorage(key) { | ||
let savedJSON; | ||
if (window.localStorage) { | ||
try { | ||
savedJSON = JSON.parse(window.localStorage.getItem(key)); | ||
} catch (e) { | ||
} | ||
if (!window.localStorage) { | ||
return void 0; | ||
} | ||
if (typeof savedJSON !== "undefined") { | ||
return savedJSON; | ||
const item = window.localStorage.getItem(key); | ||
if (item === null) { | ||
return void 0; | ||
} | ||
try { | ||
return JSON.parse(item); | ||
} catch (e) { | ||
return void 0; | ||
} | ||
} | ||
function setLocalStorage(key, data) { | ||
if (data && window.localStorage) { | ||
if (typeof data === "object") { | ||
window.localStorage.setItem(key, JSON.stringify(data)); | ||
} else { | ||
window.localStorage.setItem(key, data); | ||
} | ||
if (!window.localStorage || data === void 0 || data === null) { | ||
return; | ||
} | ||
const value = typeof data === "object" ? JSON.stringify(data) : data; | ||
window.localStorage.setItem(key, value); | ||
} |
@@ -25,2 +25,3 @@ "use strict"; | ||
__reExport(index_exports, require("./node.js"), module.exports); | ||
__reExport(index_exports, require("./if.js"), module.exports); | ||
__reExport(index_exports, require("./log.js"), module.exports); | ||
@@ -32,1 +33,10 @@ __reExport(index_exports, require("./string.js"), module.exports); | ||
__reExport(index_exports, require("./component.js"), module.exports); | ||
__reExport(index_exports, require("./props.js"), module.exports); | ||
__reExport(index_exports, require("./extends.js"), module.exports); | ||
__reExport(index_exports, require("./element.js"), module.exports); | ||
__reExport(index_exports, require("./state.js"), module.exports); | ||
__reExport(index_exports, require("./keys.js"), module.exports); | ||
__reExport(index_exports, require("./scope.js"), module.exports); | ||
__reExport(index_exports, require("./methods.js"), module.exports); | ||
__reExport(index_exports, require("./cache.js"), module.exports); | ||
__reExport(index_exports, require("./update.js"), module.exports); |
@@ -21,2 +21,3 @@ "use strict"; | ||
__export(key_exports, { | ||
createKey: () => createKey, | ||
createSnapshotId: () => createSnapshotId, | ||
@@ -26,2 +27,3 @@ generateKey: () => generateKey | ||
module.exports = __toCommonJS(key_exports); | ||
var import_object = require("./object.js"); | ||
const generateKey = /* @__PURE__ */ function() { | ||
@@ -36,1 +38,4 @@ let index = 0; | ||
const createSnapshotId = generateKey; | ||
const createKey = (element, parent, key) => { | ||
return ((0, import_object.exec)(key, element) || key || element.key || generateKey()).toString(); | ||
}; |
@@ -27,14 +27,8 @@ "use strict"; | ||
deepDestringify: () => deepDestringify, | ||
deepDiff: () => deepDiff, | ||
deepMerge: () => deepMerge, | ||
deepStringify: () => deepStringify, | ||
deepStringifyWithMaxDepth: () => deepStringifyWithMaxDepth, | ||
detachFunctionsFromObject: () => detachFunctionsFromObject, | ||
detectInfiniteLoop: () => detectInfiniteLoop, | ||
diff: () => diff, | ||
diffArrays: () => diffArrays, | ||
diffObjects: () => diffObjects, | ||
excludeKeysFromObject: () => excludeKeysFromObject, | ||
exec: () => exec, | ||
flattenRecursive: () => flattenRecursive, | ||
execPromise: () => execPromise, | ||
getInObjectByPath: () => getInObjectByPath, | ||
@@ -50,4 +44,2 @@ hasFunction: () => hasFunction, | ||
merge: () => merge, | ||
mergeArrayExclude: () => mergeArrayExclude, | ||
mergeIfExisted: () => mergeIfExisted, | ||
objectToString: () => objectToString, | ||
@@ -68,2 +60,3 @@ overwrite: () => overwrite, | ||
var import_node = require("./node.js"); | ||
var import_keys = require("./keys.js"); | ||
const ENV = "development"; | ||
@@ -81,2 +74,13 @@ const exec = (param, element, state, context) => { | ||
}; | ||
const execPromise = async (param, element, state, context) => { | ||
if ((0, import_types.isFunction)(param)) { | ||
return await param.call( | ||
element, | ||
element, | ||
state || element.state, | ||
context || element.context | ||
); | ||
} | ||
return param; | ||
}; | ||
const map = (obj, extention, element) => { | ||
@@ -90,3 +94,5 @@ for (const e in extention) { | ||
const hasOwnProperty2 = Object.prototype.hasOwnProperty.call(obj, e); | ||
if (!hasOwnProperty2 || excludeFrom.includes(e) || e.startsWith("__")) continue; | ||
if (!hasOwnProperty2 || excludeFrom.includes(e) || e.startsWith("__")) { | ||
continue; | ||
} | ||
const elementProp = element[e]; | ||
@@ -100,6 +106,8 @@ const objProp = obj[e]; | ||
}; | ||
const deepMerge = (element, extend, excludeFrom = []) => { | ||
const deepMerge = (element, extend, excludeFrom = import_keys.METHODS_EXL) => { | ||
for (const e in extend) { | ||
const hasOwnProperty2 = Object.prototype.hasOwnProperty.call(extend, e); | ||
if (!hasOwnProperty2 || excludeFrom.includes(e) || e.startsWith("__")) continue; | ||
if (!hasOwnProperty2 || excludeFrom.includes(e) || e.startsWith("__")) { | ||
continue; | ||
} | ||
const elementProp = element[e]; | ||
@@ -119,3 +127,5 @@ const extendProp = extend[e]; | ||
const hasOwnProperty2 = Object.prototype.hasOwnProperty.call(obj, prop); | ||
if (!hasOwnProperty2 || excludeFrom.includes(prop) || prop.startsWith("__")) continue; | ||
if (!hasOwnProperty2 || excludeFrom.includes(prop) || prop.startsWith("__")) { | ||
continue; | ||
} | ||
o[prop] = obj[prop]; | ||
@@ -125,5 +135,2 @@ } | ||
}; | ||
const mergeArrayExclude = (arr, exclude = []) => { | ||
return arr.reduce((acc, curr) => deepMerge(acc, deepClone(curr, { exclude })), {}); | ||
}; | ||
const deepClone = (obj, options = {}) => { | ||
@@ -136,3 +143,3 @@ const { | ||
visited = /* @__PURE__ */ new WeakMap(), | ||
handleExtend = false | ||
handleExtends = false | ||
} = options; | ||
@@ -149,5 +156,9 @@ if (!(0, import_types.isObjectLike)(obj) || (0, import_node.isDOMNode)(obj)) { | ||
if (!Object.prototype.hasOwnProperty.call(obj, key)) continue; | ||
if (exclude.includes(key) || key.startsWith("__") || key === "__proto__") continue; | ||
if (exclude.includes(key) || key.startsWith("__") || key === "__proto__") { | ||
continue; | ||
} | ||
const value = obj[key]; | ||
if (cleanUndefined && (0, import_types.isUndefined)(value) || cleanNull && (0, import_types.isNull)(value)) continue; | ||
if (cleanUndefined && (0, import_types.isUndefined)(value) || cleanNull && (0, import_types.isNull)(value)) { | ||
continue; | ||
} | ||
if ((0, import_node.isDOMNode)(value)) { | ||
@@ -157,4 +168,4 @@ clone2[key] = value; | ||
} | ||
if (handleExtend && key === "extend" && (0, import_types.isArray)(value)) { | ||
clone2[key] = (0, import_array.mergeArray)(value, exclude); | ||
if (handleExtends && key === "extends" && (0, import_types.isArray)(value)) { | ||
clone2[key] = (0, import_array.unstackArrayOfObjects)(value, exclude); | ||
continue; | ||
@@ -180,3 +191,7 @@ } | ||
if (obj.node || obj.__ref || obj.parent || obj.__element || obj.parse) { | ||
(obj.__element || ((_a = obj.parent) == null ? void 0 : _a.__element)).warn("Trying to clone element or state at", obj); | ||
; | ||
(obj.__element || ((_a = obj.parent) == null ? void 0 : _a.__element)).warn( | ||
"Trying to clone element or state at", | ||
obj | ||
); | ||
obj = (_b = obj.parse) == null ? void 0 : _b.call(obj); | ||
@@ -209,35 +224,2 @@ } | ||
}; | ||
const MAX_DEPTH = 100; | ||
const deepStringifyWithMaxDepth = (obj, stringified = {}, depth = 0, path = "") => { | ||
if (depth > MAX_DEPTH) { | ||
console.warn(`Maximum depth exceeded at path: ${path}. Possible circular reference.`); | ||
return "[MAX_DEPTH_EXCEEDED]"; | ||
} | ||
for (const prop in obj) { | ||
const currentPath = path ? `${path}.${prop}` : prop; | ||
const objProp = obj[prop]; | ||
if ((0, import_types.isFunction)(objProp)) { | ||
stringified[prop] = objProp.toString(); | ||
} else if ((0, import_types.isObject)(objProp)) { | ||
stringified[prop] = {}; | ||
deepStringifyWithMaxDepth(objProp, stringified[prop], depth + 1, currentPath); | ||
} else if ((0, import_types.isArray)(objProp)) { | ||
stringified[prop] = []; | ||
objProp.forEach((v, i) => { | ||
const itemPath = `${currentPath}[${i}]`; | ||
if ((0, import_types.isObject)(v)) { | ||
stringified[prop][i] = {}; | ||
deepStringifyWithMaxDepth(v, stringified[prop][i], depth + 1, itemPath); | ||
} else if ((0, import_types.isFunction)(v)) { | ||
stringified[prop][i] = v.toString(); | ||
} else { | ||
stringified[prop][i] = v; | ||
} | ||
}); | ||
} else { | ||
stringified[prop] = objProp; | ||
} | ||
} | ||
return stringified; | ||
}; | ||
const objectToString = (obj = {}, indent = 0) => { | ||
@@ -253,3 +235,18 @@ if (obj === null || typeof obj !== "object") { | ||
for (const [key, value] of Object.entries(obj)) { | ||
const keyNotAllowdChars = (0, import_string.stringIncludesAny)(key, ["&", "*", "-", ":", "%", "{", "}", ">", "<", "@", ".", "/", "!", " "]); | ||
const keyNotAllowdChars = (0, import_string.stringIncludesAny)(key, [ | ||
"&", | ||
"*", | ||
"-", | ||
":", | ||
"%", | ||
"{", | ||
"}", | ||
">", | ||
"<", | ||
"@", | ||
".", | ||
"/", | ||
"!", | ||
" " | ||
]); | ||
const stringedKey = keyNotAllowdChars ? `'${key}'` : key; | ||
@@ -284,26 +281,2 @@ str += `${spaces} ${stringedKey}: `; | ||
}; | ||
const detachFunctionsFromObject = (obj, detached = {}) => { | ||
for (const prop in obj) { | ||
const objProp = obj[prop]; | ||
if ((0, import_types.isFunction)(objProp)) continue; | ||
else if ((0, import_types.isObject)(objProp)) { | ||
detached[prop] = {}; | ||
deepStringify(objProp, detached[prop]); | ||
} else if ((0, import_types.isArray)(objProp)) { | ||
detached[prop] = []; | ||
objProp.forEach((v, i) => { | ||
if ((0, import_types.isFunction)(v)) return; | ||
if ((0, import_types.isObject)(v)) { | ||
detached[prop][i] = {}; | ||
detachFunctionsFromObject(v, detached[prop][i]); | ||
} else { | ||
detached[prop][i] = v; | ||
} | ||
}); | ||
} else { | ||
detached[prop] = objProp; | ||
} | ||
} | ||
return detached; | ||
}; | ||
const hasFunction = (str) => { | ||
@@ -380,42 +353,2 @@ if (!str) return false; | ||
}; | ||
const diffObjects = (original, objToDiff, cache) => { | ||
for (const e in objToDiff) { | ||
if (e === "ref") continue; | ||
const originalProp = original[e]; | ||
const objToDiffProp = objToDiff[e]; | ||
if ((0, import_types.isObject)(originalProp) && (0, import_types.isObject)(objToDiffProp)) { | ||
cache[e] = {}; | ||
diff(originalProp, objToDiffProp, cache[e]); | ||
} else if (objToDiffProp !== void 0) { | ||
cache[e] = objToDiffProp; | ||
} | ||
} | ||
return cache; | ||
}; | ||
const diffArrays = (original, objToDiff, cache) => { | ||
if (original.length !== objToDiff.length) { | ||
cache = objToDiff; | ||
} else { | ||
const diffArr = []; | ||
for (let i = 0; i < original.length; i++) { | ||
const diffObj = diff(original[i], objToDiff[i]); | ||
if (Object.keys(diffObj).length > 0) { | ||
diffArr.push(diffObj); | ||
} | ||
} | ||
if (diffArr.length > 0) { | ||
cache = diffArr; | ||
} | ||
} | ||
return cache; | ||
}; | ||
const diff = (original, objToDiff, cache = {}) => { | ||
if ((0, import_types.isArray)(original) && (0, import_types.isArray)(objToDiff)) { | ||
cache = []; | ||
diffArrays(original, objToDiff, cache); | ||
} else { | ||
diffObjects(original, objToDiff, cache); | ||
} | ||
return cache; | ||
}; | ||
const hasOwnProperty = (o, ...args) => Object.prototype.hasOwnProperty.call(o, ...args); | ||
@@ -425,45 +358,10 @@ const isEmpty = (o) => Object.keys(o).length === 0; | ||
const makeObjectWithoutPrototype = () => /* @__PURE__ */ Object.create(null); | ||
const deepDiff = (lhs, rhs) => { | ||
if (lhs === rhs) return {}; | ||
if (!(0, import_types.isObjectLike)(lhs) || !(0, import_types.isObjectLike)(rhs)) return rhs; | ||
const deletedValues = Object.keys(lhs).reduce((acc, key) => { | ||
if (!hasOwnProperty(rhs, key)) { | ||
acc[key] = void 0; | ||
} | ||
return acc; | ||
}, makeObjectWithoutPrototype()); | ||
if ((0, import_types.isDate)(lhs) || (0, import_types.isDate)(rhs)) { | ||
if (lhs.valueOf() === rhs.valueOf()) return {}; | ||
return rhs; | ||
} | ||
return Object.keys(rhs).reduce((acc, key) => { | ||
if (!hasOwnProperty(lhs, key)) { | ||
acc[key] = rhs[key]; | ||
return acc; | ||
} | ||
const difference = diff(lhs[key], rhs[key]); | ||
if (isEmptyObject(difference) && !(0, import_types.isDate)(difference) && (isEmptyObject(lhs[key]) || !isEmptyObject(rhs[key]))) { | ||
return acc; | ||
} | ||
acc[key] = difference; | ||
return acc; | ||
}, deletedValues); | ||
}; | ||
const overwrite = (element, params, opts = {}) => { | ||
const { __ref: ref } = element; | ||
const excl = opts.exclude || []; | ||
const allowUnderscore = opts.preventUnderscore; | ||
const preventCaching = opts.preventCaching; | ||
for (const e in params) { | ||
if (excl.includes(e) || !allowUnderscore && e.startsWith("__")) continue; | ||
const elementProp = element[e]; | ||
const paramsProp = params[e]; | ||
if (paramsProp !== void 0) { | ||
element[e] = paramsProp; | ||
if (ref && !preventCaching) { | ||
ref.__cache[e] = elementProp; | ||
} | ||
if ((0, import_types.isObject)(opts.diff)) { | ||
diff[e] = elementProp; | ||
} | ||
} | ||
@@ -503,14 +401,2 @@ } | ||
}; | ||
const mergeIfExisted = (a, b) => { | ||
if ((0, import_types.isObjectLike)(a) && (0, import_types.isObjectLike)(b)) return deepMerge(a, b); | ||
return a || b; | ||
}; | ||
const flattenRecursive = (param, prop, stack = []) => { | ||
const objectized = (0, import_array.mergeAndCloneIfArray)(param); | ||
stack.push(objectized); | ||
const extendOfExtend = objectized[prop]; | ||
if (extendOfExtend) flattenRecursive(extendOfExtend, prop, stack); | ||
delete objectized[prop]; | ||
return stack; | ||
}; | ||
const isEqualDeep = (param, element, visited = /* @__PURE__ */ new Set()) => { | ||
@@ -544,29 +430,25 @@ if (typeof param !== "object" || typeof element !== "object" || param === null || element === null) { | ||
if (obj1 === obj2) return true; | ||
if (!(0, import_types.isObjectLike)(obj1) || !(0, import_types.isObjectLike)(obj2)) return false; | ||
if (!(0, import_types.isObjectLike)(obj1) || !(0, import_types.isObjectLike)(obj2)) return obj1 === obj2; | ||
if ((0, import_node.isDOMNode)(obj1) || (0, import_node.isDOMNode)(obj2)) return obj1 === obj2; | ||
const stack = [[obj1, obj2]]; | ||
const visited = /* @__PURE__ */ new WeakSet(); | ||
while (stack.length > 0) { | ||
const [current1, current2] = stack.pop(); | ||
if (visited.has(current1)) continue; | ||
visited.add(current1); | ||
const keys1 = Object.keys(current1).filter((key) => !ignoredKeys.includes(key)); | ||
const keys2 = Object.keys(current2).filter((key) => !ignoredKeys.includes(key)); | ||
if (keys1.length !== keys2.length) return false; | ||
for (const key of keys1) { | ||
if (!Object.prototype.hasOwnProperty.call(current2, key)) return false; | ||
const value1 = current1[key]; | ||
const value2 = current2[key]; | ||
if ((0, import_node.isDOMNode)(value1) || (0, import_node.isDOMNode)(value2)) { | ||
if (value1 !== value2) return false; | ||
} else if ((0, import_types.isObjectLike)(value1) && (0, import_types.isObjectLike)(value2)) { | ||
if (value1 !== value2) { | ||
stack.push([value1, value2]); | ||
} | ||
} else if (value1 !== value2) { | ||
function checkContains(target, source) { | ||
if (visited.has(source)) return true; | ||
visited.add(source); | ||
for (const key in source) { | ||
if (!Object.prototype.hasOwnProperty.call(source, key)) continue; | ||
if (ignoredKeys.includes(key)) continue; | ||
if (!Object.prototype.hasOwnProperty.call(target, key)) return false; | ||
const sourceValue = source[key]; | ||
const targetValue = target[key]; | ||
if ((0, import_node.isDOMNode)(sourceValue) || (0, import_node.isDOMNode)(targetValue)) { | ||
if (sourceValue !== targetValue) return false; | ||
} else if ((0, import_types.isObjectLike)(sourceValue) && (0, import_types.isObjectLike)(targetValue)) { | ||
if (!checkContains(targetValue, sourceValue)) return false; | ||
} else if (sourceValue !== targetValue) { | ||
return false; | ||
} | ||
} | ||
return true; | ||
} | ||
return true; | ||
return checkContains(obj1, obj2); | ||
}; | ||
@@ -580,3 +462,5 @@ const removeFromObject = (obj, props) => { | ||
} else { | ||
throw new Error("Invalid input: props must be a string or an array of strings"); | ||
throw new Error( | ||
"Invalid input: props must be a string or an array of strings" | ||
); | ||
} | ||
@@ -606,3 +490,3 @@ return obj; | ||
} | ||
if (index === arr.length - 1 && lastValue !== void 0) { | ||
if (index === arr.length - 1 && lastValue) { | ||
obj[value] = lastValue; | ||
@@ -674,3 +558,6 @@ } | ||
if (ENV === "test" || ENV === "development") { | ||
console.warn("Warning: Potential infinite loop detected due to repeated sequence:", pattern); | ||
console.warn( | ||
"Warning: Potential infinite loop detected due to repeated sequence:", | ||
pattern | ||
); | ||
} | ||
@@ -677,0 +564,0 @@ return true; |
@@ -46,24 +46,33 @@ "use strict"; | ||
const brackRegex = { | ||
2: /\{\{\s*((?:\.\.\/)+)?([^}\s]+)\s*\}\}/g, | ||
3: /\{\{\{\s*((?:\.\.\/)+)?([^}\s]+)\s*\}\}\}/g | ||
2: /{{\s*((?:\.\.\/)*)([\w\d.]+)\s*}}/g, | ||
3: /{{{(\s*(?:\.\.\/)*)([\w\d.]+)\s*}}}/g | ||
}; | ||
function replaceLiteralsWithObjectFields(str, options = {}, forcedState) { | ||
if (!str.includes(options.bracketsLength === 3 ? "{{{" : "{{")) return str; | ||
const reg = brackRegex[options.bracketsLength || 2]; | ||
const obj = forcedState || (this == null ? void 0 : this.state) || {}; | ||
const getNestedValue = (obj, path) => { | ||
return path.split(".").reduce((acc, part) => { | ||
return acc && acc[part] !== void 0 ? acc[part] : void 0; | ||
}, obj); | ||
}; | ||
function replaceLiteralsWithObjectFields(str, state = {}, options = {}) { | ||
const { bracketsLength = 2 } = options; | ||
const bracketPattern = bracketsLength === 3 ? "{{{" : "{{"; | ||
if (!str.includes(bracketPattern)) return str; | ||
const reg = brackRegex[bracketsLength]; | ||
const obj = state || {}; | ||
return str.replace(reg, (_, parentPath, variable) => { | ||
if (parentPath) { | ||
const parentLevels = parentPath.match(options.bracketsLength === 3 ? /\.\.\.\//g : /\.\.\//g).length; | ||
const parentLevels = (parentPath.match(/\.\.\//g) || []).length; | ||
let parentState = obj; | ||
for (let i = 0; i < parentLevels; i++) { | ||
if (!parentState || !parentState.parent) return ""; | ||
parentState = parentState.parent; | ||
if (!parentState) { | ||
return ""; | ||
} | ||
} | ||
const value = parentState[variable.trim()]; | ||
return value !== void 0 ? `${value}` : ""; | ||
const key = variable.trim(); | ||
if (key === "parent") { | ||
return parentState.value !== void 0 ? String(parentState.value) : ""; | ||
} | ||
const value = getNestedValue(parentState, key); | ||
return value !== void 0 ? String(value) : ""; | ||
} else { | ||
const value = obj[variable.trim()]; | ||
return value !== void 0 ? `${value}` : ""; | ||
const value = getNestedValue(obj, variable.trim()); | ||
return value !== void 0 ? String(value) : ""; | ||
} | ||
@@ -144,3 +153,6 @@ }); | ||
const customDecodeURIComponent = (encodedStr) => { | ||
return encodedStr.replace(/%[0-9A-Fa-f]{2}/g, (match) => String.fromCharCode(parseInt(match.slice(1), 16))); | ||
return encodedStr.replace( | ||
/%[0-9A-Fa-f]{2}/g, | ||
(match) => String.fromCharCode(parseInt(match.slice(1), 16)) | ||
); | ||
}; |
@@ -18,4 +18,2 @@ import { deepClone, deepMerge } from "./object.js"; | ||
arr.splice(index, 1); | ||
} else if (isArray(index)) { | ||
index.forEach((idx) => removeFromArray(arr, idx)); | ||
} else { | ||
@@ -27,2 +25,3 @@ throw new Error("Invalid index"); | ||
const swapItemsInArray = (arr, i, j) => { | ||
; | ||
[arr[i], arr[j]] = [arr[j], arr[i]]; | ||
@@ -33,8 +32,8 @@ }; | ||
}; | ||
const mergeArray = (arr, exclude = []) => { | ||
return arr.reduce((a, c) => deepMerge(a, deepClone(c, { exclude }), exclude), {}); | ||
const unstackArrayOfObjects = (arr, exclude = []) => { | ||
return arr.reduce( | ||
(a, c) => deepMerge(a, deepClone(c, { exclude }), exclude), | ||
{} | ||
); | ||
}; | ||
const mergeAndCloneIfArray = (obj) => { | ||
return isArray(obj) ? mergeArray(obj) : deepClone(obj); | ||
}; | ||
const cutArrayBeforeValue = (arr, value) => { | ||
@@ -110,4 +109,22 @@ const index = arr.indexOf(value); | ||
}; | ||
const removeDuplicatesInArray = (arr) => { | ||
if (!isArray(arr)) return arr; | ||
return [...new Set(arr)]; | ||
}; | ||
const addProtoToArray = (state, proto) => { | ||
for (const key in proto) { | ||
Object.defineProperty(state, key, { | ||
value: proto[key], | ||
enumerable: false, | ||
// Set this to true if you want the method to appear in for...in loops | ||
configurable: true, | ||
// Set this to true if you want to allow redefining/removing the property later | ||
writable: true | ||
// Set this to true if you want to allow changing the function later | ||
}); | ||
} | ||
}; | ||
export { | ||
addItemAfterEveryElement, | ||
addProtoToArray, | ||
arrayContainsOtherArray, | ||
@@ -122,4 +139,3 @@ arraysEqual, | ||
joinArrays, | ||
mergeAndCloneIfArray, | ||
mergeArray, | ||
removeDuplicatesInArray, | ||
removeFromArray, | ||
@@ -129,3 +145,4 @@ removeValueFromArray, | ||
reorderArrayByValues, | ||
swapItemsInArray | ||
swapItemsInArray, | ||
unstackArrayOfObjects | ||
}; |
@@ -1,25 +0,4 @@ | ||
var __defProp = Object.defineProperty; | ||
var __defProps = Object.defineProperties; | ||
var __getOwnPropDescs = Object.getOwnPropertyDescriptors; | ||
var __getOwnPropSymbols = Object.getOwnPropertySymbols; | ||
var __hasOwnProp = Object.prototype.hasOwnProperty; | ||
var __propIsEnum = Object.prototype.propertyIsEnumerable; | ||
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; | ||
var __spreadValues = (a, b) => { | ||
for (var prop in b || (b = {})) | ||
if (__hasOwnProp.call(b, prop)) | ||
__defNormalProp(a, prop, b[prop]); | ||
if (__getOwnPropSymbols) | ||
for (var prop of __getOwnPropSymbols(b)) { | ||
if (__propIsEnum.call(b, prop)) | ||
__defNormalProp(a, prop, b[prop]); | ||
} | ||
return a; | ||
}; | ||
var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b)); | ||
import { joinArrays } from "./array.js"; | ||
import { deepClone, exec } from "./object.js"; | ||
import { isArray, isFunction, isObject, isString } from "./types.js"; | ||
const ENV = "development"; | ||
const checkIfKeyIsComponent = (key) => { | ||
import { createExtendsFromKeys } from "./extends.js"; | ||
import { isString } from "./types.js"; | ||
const matchesComponentNaming = (key) => { | ||
const isFirstKeyString = isString(key); | ||
@@ -30,208 +9,20 @@ if (!isFirstKeyString) return; | ||
}; | ||
const checkIfKeyIsProperty = (key) => { | ||
const isFirstKeyString = isString(key); | ||
if (!isFirstKeyString) return; | ||
const firstCharKey = key.slice(0, 1); | ||
return /^[a-z]*$/.test(firstCharKey); | ||
}; | ||
const addAdditionalExtend = (newExtend, element) => { | ||
if (!newExtend) return element; | ||
const { extend: elementExtend } = element; | ||
const originalArray = isArray(elementExtend) ? elementExtend : [elementExtend]; | ||
const receivedArray = isArray(newExtend) ? newExtend : [newExtend]; | ||
const extend = joinArrays(receivedArray, originalArray); | ||
return __spreadProps(__spreadValues({}, element), { extend }); | ||
}; | ||
const checkIfSugar = (element, parent, key) => { | ||
var _a; | ||
const { | ||
extend, | ||
props, | ||
childExtend, | ||
extends: extendProps, | ||
childExtends, | ||
childProps, | ||
children, | ||
on, | ||
$collection, | ||
$stateCollection, | ||
$propsCollection | ||
} = element; | ||
const hasComponentAttrs = extend || childExtend || props || on || $collection || $stateCollection || $propsCollection; | ||
if (hasComponentAttrs && (childProps || extendProps || children || childExtends)) { | ||
const logErr = (_a = parent || element) == null ? void 0 : _a.error; | ||
if (logErr) logErr.call(element, "Sugar component includes params for builtin components", { verbose: true }); | ||
} | ||
return !hasComponentAttrs || childProps || extendProps || children || childExtends; | ||
}; | ||
const extractComponentKeyFromKey = (key) => { | ||
return key.includes("+") ? key.split("+") : key.includes("_") ? [key.split("_")[0]] : key.includes(".") && !checkIfKeyIsComponent(key.split(".")[1]) ? [key.split(".")[0]] : [key]; | ||
}; | ||
const extendizeByKey = (element, parent, key) => { | ||
const { context } = parent; | ||
const { tag, extend, childExtends } = element; | ||
const isSugar = checkIfSugar(element, parent, key); | ||
const extendFromKey = extractComponentKeyFromKey(key); | ||
const isExtendKeyComponent = context && context.components[extendFromKey]; | ||
if (element === isExtendKeyComponent) return element; | ||
else if (isSugar) { | ||
const newElem = addAdditionalExtend(element.extends, { | ||
extend: extendFromKey, | ||
tag, | ||
props: __spreadValues({}, element) | ||
}); | ||
if (newElem.props.data) { | ||
newElem.data = newElem.props.data; | ||
delete newElem.props.data; | ||
} | ||
if (newElem.props.state) { | ||
newElem.state = newElem.props.state; | ||
delete newElem.props.state; | ||
} | ||
if (newElem.props.attr) { | ||
newElem.attr = newElem.props.attr; | ||
delete newElem.props.attr; | ||
} | ||
if (newElem.props.if) { | ||
newElem.if = newElem.props.if; | ||
delete newElem.props.if; | ||
} | ||
if (childExtends) newElem.childExtend = childExtends; | ||
return newElem; | ||
} else if (!extend || extend === true) { | ||
return __spreadProps(__spreadValues({}, element), { | ||
tag, | ||
extend: extendFromKey | ||
}); | ||
} else if (extend) { | ||
return addAdditionalExtend(extendFromKey, element); | ||
} else if (isFunction(element)) { | ||
return { | ||
extend: extendFromKey, | ||
tag, | ||
props: __spreadValues({}, exec(element, parent)) | ||
}; | ||
} | ||
}; | ||
function getCapitalCaseKeys(obj) { | ||
return Object.keys(obj).filter((key) => /^[A-Z]/.test(key)); | ||
} | ||
const addChildrenIfNotInOriginal = (element, parent, key) => { | ||
const childElems = getCapitalCaseKeys(element.props); | ||
if (!childElems.length) return element; | ||
for (const i in childElems) { | ||
const childKey = childElems[i]; | ||
const childElem = element[childKey]; | ||
const newChild = element.props[childKey]; | ||
const assignChild = (val) => { | ||
element[childKey] = val; | ||
delete element.props[childKey]; | ||
}; | ||
if (newChild == null ? void 0 : newChild.ignoreExtend) continue; | ||
if (newChild === null) assignChild(null); | ||
else if (!childElem) assignChild(deepClone(newChild)); | ||
else { | ||
const isSugarChildElem = checkIfSugar(childElem, parent, key); | ||
if (isSugarChildElem) continue; | ||
assignChild({ | ||
extend: element[childKey], | ||
props: newChild | ||
}); | ||
} | ||
} | ||
}; | ||
const applyKeyComponentAsExtend = (element, parent, key) => { | ||
return extendizeByKey(element, parent, key) || element; | ||
}; | ||
const applyComponentFromContext = (element, parent, options) => { | ||
const { context } = element; | ||
if (!context || !context.components) return; | ||
const { components } = context; | ||
const { extend } = element; | ||
const execExtend = exec(extend, element); | ||
if (isString(execExtend)) { | ||
const componentExists = components[execExtend] || components["smbls." + execExtend]; | ||
if (componentExists) element.extend = componentExists; | ||
else { | ||
if ((ENV === "test" || ENV === "development") && options.verbose) { | ||
console.warn(execExtend, "is not in library", components, element); | ||
console.warn("replacing with ", {}); | ||
} | ||
element.extend = {}; | ||
} | ||
} | ||
}; | ||
const isVariant = (param) => { | ||
if (!isString(param)) return; | ||
const firstCharKey = param.slice(0, 1); | ||
return firstCharKey === "."; | ||
}; | ||
const hasVariantProp = (element) => { | ||
const { props } = element; | ||
if (isObject(props) && isString(props.variant)) return true; | ||
}; | ||
const getChildrenComponentsByKey = (key, el) => { | ||
if (key === el.key || el.__ref.__componentKey === key) { | ||
return el; | ||
} | ||
if (el.extend) { | ||
const foundString = isString(el.extend) && el.extend === key; | ||
const foundInArray = isArray(el.extend) && el.extend.filter((v) => v === key).length; | ||
if (foundString || foundInArray) return el; | ||
} | ||
if (el.parent && el.parent.childExtend) { | ||
const foundString = isString(el.parent.childExtend) && el.parent.childExtend === key; | ||
const foundInArray = isArray(el.parent.childExtend) && el.parent.childExtend.filter((v) => v === key).length; | ||
if (foundString || foundInArray) return el; | ||
} | ||
}; | ||
const getExtendsInElement = (obj) => { | ||
let result = []; | ||
function traverse(o) { | ||
for (const key in o) { | ||
if (Object.hasOwnProperty.call(o, key)) { | ||
if (checkIfKeyIsComponent(key)) { | ||
result.push(key); | ||
} | ||
if (key === "extend" || key === "extends") { | ||
if (typeof o[key] === "string") { | ||
result.push(o[key]); | ||
} else if (Array.isArray(o[key])) { | ||
result = result.concat(o[key]); | ||
} | ||
} | ||
if (typeof o[key] === "object" && o[key] !== null) { | ||
traverse(o[key]); | ||
} | ||
} | ||
} | ||
} | ||
traverse(obj); | ||
return result; | ||
}; | ||
const setContentKey = (el, opts = {}) => { | ||
const { __ref: ref } = el; | ||
const contentElementKey = opts.contentElementKey; | ||
if (contentElementKey !== "content" && contentElementKey !== ref.contentElementKey || !ref.contentElementKey) { | ||
ref.contentElementKey = contentElementKey || "content"; | ||
} else ref.contentElementKey = "content"; | ||
if (contentElementKey !== "content") opts.contentElementKey = "content"; | ||
return ref.contentElementKey; | ||
}; | ||
function getSpreadChildren(obj) { | ||
return Object.keys(obj).filter((key) => /^\d+$/.test(key)); | ||
} | ||
function isContextComponent(element, parent, passedKey) { | ||
var _a, _b; | ||
const { context } = parent || {}; | ||
const [extendsKey] = createExtendsFromKeys(passedKey); | ||
const key = passedKey || extendsKey; | ||
return ((_a = context == null ? void 0 : context.components) == null ? void 0 : _a[key]) || ((_b = context == null ? void 0 : context.pages) == null ? void 0 : _b[key]); | ||
} | ||
export { | ||
addAdditionalExtend, | ||
addChildrenIfNotInOriginal, | ||
applyComponentFromContext, | ||
applyKeyComponentAsExtend, | ||
checkIfKeyIsComponent, | ||
checkIfKeyIsProperty, | ||
checkIfSugar, | ||
extendizeByKey, | ||
extractComponentKeyFromKey, | ||
getCapitalCaseKeys, | ||
getChildrenComponentsByKey, | ||
getExtendsInElement, | ||
hasVariantProp, | ||
isVariant, | ||
setContentKey | ||
getSpreadChildren, | ||
isContextComponent, | ||
matchesComponentNaming | ||
}; |
@@ -28,21 +28,21 @@ import { isUndefined } from "./types.js"; | ||
function getLocalStorage(key) { | ||
let savedJSON; | ||
if (window.localStorage) { | ||
try { | ||
savedJSON = JSON.parse(window.localStorage.getItem(key)); | ||
} catch (e) { | ||
} | ||
if (!window.localStorage) { | ||
return void 0; | ||
} | ||
if (typeof savedJSON !== "undefined") { | ||
return savedJSON; | ||
const item = window.localStorage.getItem(key); | ||
if (item === null) { | ||
return void 0; | ||
} | ||
try { | ||
return JSON.parse(item); | ||
} catch (e) { | ||
return void 0; | ||
} | ||
} | ||
function setLocalStorage(key, data) { | ||
if (data && window.localStorage) { | ||
if (typeof data === "object") { | ||
window.localStorage.setItem(key, JSON.stringify(data)); | ||
} else { | ||
window.localStorage.setItem(key, data); | ||
} | ||
if (!window.localStorage || data === void 0 || data === null) { | ||
return; | ||
} | ||
const value = typeof data === "object" ? JSON.stringify(data) : data; | ||
window.localStorage.setItem(key, value); | ||
} | ||
@@ -49,0 +49,0 @@ export { |
@@ -8,2 +8,3 @@ export * from "./key.js"; | ||
export * from "./node.js"; | ||
export * from "./if.js"; | ||
export * from "./log.js"; | ||
@@ -15,1 +16,10 @@ export * from "./string.js"; | ||
export * from "./component.js"; | ||
export * from "./props.js"; | ||
export * from "./extends.js"; | ||
export * from "./element.js"; | ||
export * from "./state.js"; | ||
export * from "./keys.js"; | ||
export * from "./scope.js"; | ||
export * from "./methods.js"; | ||
export * from "./cache.js"; | ||
export * from "./update.js"; |
@@ -0,1 +1,2 @@ | ||
import { exec } from "./object.js"; | ||
const generateKey = /* @__PURE__ */ function() { | ||
@@ -10,5 +11,9 @@ let index = 0; | ||
const createSnapshotId = generateKey; | ||
const createKey = (element, parent, key) => { | ||
return (exec(key, element) || key || element.key || generateKey()).toString(); | ||
}; | ||
export { | ||
createKey, | ||
createSnapshotId, | ||
generateKey | ||
}; |
@@ -29,8 +29,8 @@ var __defProp = Object.defineProperty; | ||
isUndefined, | ||
isDate, | ||
isNull | ||
} from "./types.js"; | ||
import { mergeAndCloneIfArray, mergeArray } from "./array.js"; | ||
import { unstackArrayOfObjects } from "./array.js"; | ||
import { stringIncludesAny } from "./string.js"; | ||
import { isDOMNode } from "./node.js"; | ||
import { METHODS_EXL } from "./keys.js"; | ||
const ENV = "development"; | ||
@@ -48,2 +48,13 @@ const exec = (param, element, state, context) => { | ||
}; | ||
const execPromise = async (param, element, state, context) => { | ||
if (isFunction(param)) { | ||
return await param.call( | ||
element, | ||
element, | ||
state || element.state, | ||
context || element.context | ||
); | ||
} | ||
return param; | ||
}; | ||
const map = (obj, extention, element) => { | ||
@@ -57,3 +68,5 @@ for (const e in extention) { | ||
const hasOwnProperty2 = Object.prototype.hasOwnProperty.call(obj, e); | ||
if (!hasOwnProperty2 || excludeFrom.includes(e) || e.startsWith("__")) continue; | ||
if (!hasOwnProperty2 || excludeFrom.includes(e) || e.startsWith("__")) { | ||
continue; | ||
} | ||
const elementProp = element[e]; | ||
@@ -67,6 +80,8 @@ const objProp = obj[e]; | ||
}; | ||
const deepMerge = (element, extend, excludeFrom = []) => { | ||
const deepMerge = (element, extend, excludeFrom = METHODS_EXL) => { | ||
for (const e in extend) { | ||
const hasOwnProperty2 = Object.prototype.hasOwnProperty.call(extend, e); | ||
if (!hasOwnProperty2 || excludeFrom.includes(e) || e.startsWith("__")) continue; | ||
if (!hasOwnProperty2 || excludeFrom.includes(e) || e.startsWith("__")) { | ||
continue; | ||
} | ||
const elementProp = element[e]; | ||
@@ -86,3 +101,5 @@ const extendProp = extend[e]; | ||
const hasOwnProperty2 = Object.prototype.hasOwnProperty.call(obj, prop); | ||
if (!hasOwnProperty2 || excludeFrom.includes(prop) || prop.startsWith("__")) continue; | ||
if (!hasOwnProperty2 || excludeFrom.includes(prop) || prop.startsWith("__")) { | ||
continue; | ||
} | ||
o[prop] = obj[prop]; | ||
@@ -92,5 +109,2 @@ } | ||
}; | ||
const mergeArrayExclude = (arr, exclude = []) => { | ||
return arr.reduce((acc, curr) => deepMerge(acc, deepClone(curr, { exclude })), {}); | ||
}; | ||
const deepClone = (obj, options = {}) => { | ||
@@ -103,3 +117,3 @@ const { | ||
visited = /* @__PURE__ */ new WeakMap(), | ||
handleExtend = false | ||
handleExtends = false | ||
} = options; | ||
@@ -116,5 +130,9 @@ if (!isObjectLike(obj) || isDOMNode(obj)) { | ||
if (!Object.prototype.hasOwnProperty.call(obj, key)) continue; | ||
if (exclude.includes(key) || key.startsWith("__") || key === "__proto__") continue; | ||
if (exclude.includes(key) || key.startsWith("__") || key === "__proto__") { | ||
continue; | ||
} | ||
const value = obj[key]; | ||
if (cleanUndefined && isUndefined(value) || cleanNull && isNull(value)) continue; | ||
if (cleanUndefined && isUndefined(value) || cleanNull && isNull(value)) { | ||
continue; | ||
} | ||
if (isDOMNode(value)) { | ||
@@ -124,4 +142,4 @@ clone2[key] = value; | ||
} | ||
if (handleExtend && key === "extend" && isArray(value)) { | ||
clone2[key] = mergeArray(value, exclude); | ||
if (handleExtends && key === "extends" && isArray(value)) { | ||
clone2[key] = unstackArrayOfObjects(value, exclude); | ||
continue; | ||
@@ -146,3 +164,7 @@ } | ||
if (obj.node || obj.__ref || obj.parent || obj.__element || obj.parse) { | ||
(obj.__element || ((_a = obj.parent) == null ? void 0 : _a.__element)).warn("Trying to clone element or state at", obj); | ||
; | ||
(obj.__element || ((_a = obj.parent) == null ? void 0 : _a.__element)).warn( | ||
"Trying to clone element or state at", | ||
obj | ||
); | ||
obj = (_b = obj.parse) == null ? void 0 : _b.call(obj); | ||
@@ -175,35 +197,2 @@ } | ||
}; | ||
const MAX_DEPTH = 100; | ||
const deepStringifyWithMaxDepth = (obj, stringified = {}, depth = 0, path = "") => { | ||
if (depth > MAX_DEPTH) { | ||
console.warn(`Maximum depth exceeded at path: ${path}. Possible circular reference.`); | ||
return "[MAX_DEPTH_EXCEEDED]"; | ||
} | ||
for (const prop in obj) { | ||
const currentPath = path ? `${path}.${prop}` : prop; | ||
const objProp = obj[prop]; | ||
if (isFunction(objProp)) { | ||
stringified[prop] = objProp.toString(); | ||
} else if (isObject(objProp)) { | ||
stringified[prop] = {}; | ||
deepStringifyWithMaxDepth(objProp, stringified[prop], depth + 1, currentPath); | ||
} else if (isArray(objProp)) { | ||
stringified[prop] = []; | ||
objProp.forEach((v, i) => { | ||
const itemPath = `${currentPath}[${i}]`; | ||
if (isObject(v)) { | ||
stringified[prop][i] = {}; | ||
deepStringifyWithMaxDepth(v, stringified[prop][i], depth + 1, itemPath); | ||
} else if (isFunction(v)) { | ||
stringified[prop][i] = v.toString(); | ||
} else { | ||
stringified[prop][i] = v; | ||
} | ||
}); | ||
} else { | ||
stringified[prop] = objProp; | ||
} | ||
} | ||
return stringified; | ||
}; | ||
const objectToString = (obj = {}, indent = 0) => { | ||
@@ -219,3 +208,18 @@ if (obj === null || typeof obj !== "object") { | ||
for (const [key, value] of Object.entries(obj)) { | ||
const keyNotAllowdChars = stringIncludesAny(key, ["&", "*", "-", ":", "%", "{", "}", ">", "<", "@", ".", "/", "!", " "]); | ||
const keyNotAllowdChars = stringIncludesAny(key, [ | ||
"&", | ||
"*", | ||
"-", | ||
":", | ||
"%", | ||
"{", | ||
"}", | ||
">", | ||
"<", | ||
"@", | ||
".", | ||
"/", | ||
"!", | ||
" " | ||
]); | ||
const stringedKey = keyNotAllowdChars ? `'${key}'` : key; | ||
@@ -250,26 +254,2 @@ str += `${spaces} ${stringedKey}: `; | ||
}; | ||
const detachFunctionsFromObject = (obj, detached = {}) => { | ||
for (const prop in obj) { | ||
const objProp = obj[prop]; | ||
if (isFunction(objProp)) continue; | ||
else if (isObject(objProp)) { | ||
detached[prop] = {}; | ||
deepStringify(objProp, detached[prop]); | ||
} else if (isArray(objProp)) { | ||
detached[prop] = []; | ||
objProp.forEach((v, i) => { | ||
if (isFunction(v)) return; | ||
if (isObject(v)) { | ||
detached[prop][i] = {}; | ||
detachFunctionsFromObject(v, detached[prop][i]); | ||
} else { | ||
detached[prop][i] = v; | ||
} | ||
}); | ||
} else { | ||
detached[prop] = objProp; | ||
} | ||
} | ||
return detached; | ||
}; | ||
const hasFunction = (str) => { | ||
@@ -346,42 +326,2 @@ if (!str) return false; | ||
}; | ||
const diffObjects = (original, objToDiff, cache) => { | ||
for (const e in objToDiff) { | ||
if (e === "ref") continue; | ||
const originalProp = original[e]; | ||
const objToDiffProp = objToDiff[e]; | ||
if (isObject(originalProp) && isObject(objToDiffProp)) { | ||
cache[e] = {}; | ||
diff(originalProp, objToDiffProp, cache[e]); | ||
} else if (objToDiffProp !== void 0) { | ||
cache[e] = objToDiffProp; | ||
} | ||
} | ||
return cache; | ||
}; | ||
const diffArrays = (original, objToDiff, cache) => { | ||
if (original.length !== objToDiff.length) { | ||
cache = objToDiff; | ||
} else { | ||
const diffArr = []; | ||
for (let i = 0; i < original.length; i++) { | ||
const diffObj = diff(original[i], objToDiff[i]); | ||
if (Object.keys(diffObj).length > 0) { | ||
diffArr.push(diffObj); | ||
} | ||
} | ||
if (diffArr.length > 0) { | ||
cache = diffArr; | ||
} | ||
} | ||
return cache; | ||
}; | ||
const diff = (original, objToDiff, cache = {}) => { | ||
if (isArray(original) && isArray(objToDiff)) { | ||
cache = []; | ||
diffArrays(original, objToDiff, cache); | ||
} else { | ||
diffObjects(original, objToDiff, cache); | ||
} | ||
return cache; | ||
}; | ||
const hasOwnProperty = (o, ...args) => Object.prototype.hasOwnProperty.call(o, ...args); | ||
@@ -391,45 +331,10 @@ const isEmpty = (o) => Object.keys(o).length === 0; | ||
const makeObjectWithoutPrototype = () => /* @__PURE__ */ Object.create(null); | ||
const deepDiff = (lhs, rhs) => { | ||
if (lhs === rhs) return {}; | ||
if (!isObjectLike(lhs) || !isObjectLike(rhs)) return rhs; | ||
const deletedValues = Object.keys(lhs).reduce((acc, key) => { | ||
if (!hasOwnProperty(rhs, key)) { | ||
acc[key] = void 0; | ||
} | ||
return acc; | ||
}, makeObjectWithoutPrototype()); | ||
if (isDate(lhs) || isDate(rhs)) { | ||
if (lhs.valueOf() === rhs.valueOf()) return {}; | ||
return rhs; | ||
} | ||
return Object.keys(rhs).reduce((acc, key) => { | ||
if (!hasOwnProperty(lhs, key)) { | ||
acc[key] = rhs[key]; | ||
return acc; | ||
} | ||
const difference = diff(lhs[key], rhs[key]); | ||
if (isEmptyObject(difference) && !isDate(difference) && (isEmptyObject(lhs[key]) || !isEmptyObject(rhs[key]))) { | ||
return acc; | ||
} | ||
acc[key] = difference; | ||
return acc; | ||
}, deletedValues); | ||
}; | ||
const overwrite = (element, params, opts = {}) => { | ||
const { __ref: ref } = element; | ||
const excl = opts.exclude || []; | ||
const allowUnderscore = opts.preventUnderscore; | ||
const preventCaching = opts.preventCaching; | ||
for (const e in params) { | ||
if (excl.includes(e) || !allowUnderscore && e.startsWith("__")) continue; | ||
const elementProp = element[e]; | ||
const paramsProp = params[e]; | ||
if (paramsProp !== void 0) { | ||
element[e] = paramsProp; | ||
if (ref && !preventCaching) { | ||
ref.__cache[e] = elementProp; | ||
} | ||
if (isObject(opts.diff)) { | ||
diff[e] = elementProp; | ||
} | ||
} | ||
@@ -469,14 +374,2 @@ } | ||
}; | ||
const mergeIfExisted = (a, b) => { | ||
if (isObjectLike(a) && isObjectLike(b)) return deepMerge(a, b); | ||
return a || b; | ||
}; | ||
const flattenRecursive = (param, prop, stack = []) => { | ||
const objectized = mergeAndCloneIfArray(param); | ||
stack.push(objectized); | ||
const extendOfExtend = objectized[prop]; | ||
if (extendOfExtend) flattenRecursive(extendOfExtend, prop, stack); | ||
delete objectized[prop]; | ||
return stack; | ||
}; | ||
const isEqualDeep = (param, element, visited = /* @__PURE__ */ new Set()) => { | ||
@@ -510,29 +403,25 @@ if (typeof param !== "object" || typeof element !== "object" || param === null || element === null) { | ||
if (obj1 === obj2) return true; | ||
if (!isObjectLike(obj1) || !isObjectLike(obj2)) return false; | ||
if (!isObjectLike(obj1) || !isObjectLike(obj2)) return obj1 === obj2; | ||
if (isDOMNode(obj1) || isDOMNode(obj2)) return obj1 === obj2; | ||
const stack = [[obj1, obj2]]; | ||
const visited = /* @__PURE__ */ new WeakSet(); | ||
while (stack.length > 0) { | ||
const [current1, current2] = stack.pop(); | ||
if (visited.has(current1)) continue; | ||
visited.add(current1); | ||
const keys1 = Object.keys(current1).filter((key) => !ignoredKeys.includes(key)); | ||
const keys2 = Object.keys(current2).filter((key) => !ignoredKeys.includes(key)); | ||
if (keys1.length !== keys2.length) return false; | ||
for (const key of keys1) { | ||
if (!Object.prototype.hasOwnProperty.call(current2, key)) return false; | ||
const value1 = current1[key]; | ||
const value2 = current2[key]; | ||
if (isDOMNode(value1) || isDOMNode(value2)) { | ||
if (value1 !== value2) return false; | ||
} else if (isObjectLike(value1) && isObjectLike(value2)) { | ||
if (value1 !== value2) { | ||
stack.push([value1, value2]); | ||
} | ||
} else if (value1 !== value2) { | ||
function checkContains(target, source) { | ||
if (visited.has(source)) return true; | ||
visited.add(source); | ||
for (const key in source) { | ||
if (!Object.prototype.hasOwnProperty.call(source, key)) continue; | ||
if (ignoredKeys.includes(key)) continue; | ||
if (!Object.prototype.hasOwnProperty.call(target, key)) return false; | ||
const sourceValue = source[key]; | ||
const targetValue = target[key]; | ||
if (isDOMNode(sourceValue) || isDOMNode(targetValue)) { | ||
if (sourceValue !== targetValue) return false; | ||
} else if (isObjectLike(sourceValue) && isObjectLike(targetValue)) { | ||
if (!checkContains(targetValue, sourceValue)) return false; | ||
} else if (sourceValue !== targetValue) { | ||
return false; | ||
} | ||
} | ||
return true; | ||
} | ||
return true; | ||
return checkContains(obj1, obj2); | ||
}; | ||
@@ -546,3 +435,5 @@ const removeFromObject = (obj, props) => { | ||
} else { | ||
throw new Error("Invalid input: props must be a string or an array of strings"); | ||
throw new Error( | ||
"Invalid input: props must be a string or an array of strings" | ||
); | ||
} | ||
@@ -572,3 +463,3 @@ return obj; | ||
} | ||
if (index === arr.length - 1 && lastValue !== void 0) { | ||
if (index === arr.length - 1 && lastValue) { | ||
obj[value] = lastValue; | ||
@@ -640,3 +531,6 @@ } | ||
if (ENV === "test" || ENV === "development") { | ||
console.warn("Warning: Potential infinite loop detected due to repeated sequence:", pattern); | ||
console.warn( | ||
"Warning: Potential infinite loop detected due to repeated sequence:", | ||
pattern | ||
); | ||
} | ||
@@ -679,14 +573,8 @@ return true; | ||
deepDestringify, | ||
deepDiff, | ||
deepMerge, | ||
deepStringify, | ||
deepStringifyWithMaxDepth, | ||
detachFunctionsFromObject, | ||
detectInfiniteLoop, | ||
diff, | ||
diffArrays, | ||
diffObjects, | ||
excludeKeysFromObject, | ||
exec, | ||
flattenRecursive, | ||
execPromise, | ||
getInObjectByPath, | ||
@@ -702,4 +590,2 @@ hasFunction, | ||
merge, | ||
mergeArrayExclude, | ||
mergeIfExisted, | ||
objectToString, | ||
@@ -706,0 +592,0 @@ overwrite, |
@@ -14,24 +14,33 @@ const stringIncludesAny = (str, characters) => { | ||
const brackRegex = { | ||
2: /\{\{\s*((?:\.\.\/)+)?([^}\s]+)\s*\}\}/g, | ||
3: /\{\{\{\s*((?:\.\.\/)+)?([^}\s]+)\s*\}\}\}/g | ||
2: /{{\s*((?:\.\.\/)*)([\w\d.]+)\s*}}/g, | ||
3: /{{{(\s*(?:\.\.\/)*)([\w\d.]+)\s*}}}/g | ||
}; | ||
function replaceLiteralsWithObjectFields(str, options = {}, forcedState) { | ||
if (!str.includes(options.bracketsLength === 3 ? "{{{" : "{{")) return str; | ||
const reg = brackRegex[options.bracketsLength || 2]; | ||
const obj = forcedState || (this == null ? void 0 : this.state) || {}; | ||
const getNestedValue = (obj, path) => { | ||
return path.split(".").reduce((acc, part) => { | ||
return acc && acc[part] !== void 0 ? acc[part] : void 0; | ||
}, obj); | ||
}; | ||
function replaceLiteralsWithObjectFields(str, state = {}, options = {}) { | ||
const { bracketsLength = 2 } = options; | ||
const bracketPattern = bracketsLength === 3 ? "{{{" : "{{"; | ||
if (!str.includes(bracketPattern)) return str; | ||
const reg = brackRegex[bracketsLength]; | ||
const obj = state || {}; | ||
return str.replace(reg, (_, parentPath, variable) => { | ||
if (parentPath) { | ||
const parentLevels = parentPath.match(options.bracketsLength === 3 ? /\.\.\.\//g : /\.\.\//g).length; | ||
const parentLevels = (parentPath.match(/\.\.\//g) || []).length; | ||
let parentState = obj; | ||
for (let i = 0; i < parentLevels; i++) { | ||
if (!parentState || !parentState.parent) return ""; | ||
parentState = parentState.parent; | ||
if (!parentState) { | ||
return ""; | ||
} | ||
} | ||
const value = parentState[variable.trim()]; | ||
return value !== void 0 ? `${value}` : ""; | ||
const key = variable.trim(); | ||
if (key === "parent") { | ||
return parentState.value !== void 0 ? String(parentState.value) : ""; | ||
} | ||
const value = getNestedValue(parentState, key); | ||
return value !== void 0 ? String(value) : ""; | ||
} else { | ||
const value = obj[variable.trim()]; | ||
return value !== void 0 ? `${value}` : ""; | ||
const value = getNestedValue(obj, variable.trim()); | ||
return value !== void 0 ? String(value) : ""; | ||
} | ||
@@ -112,3 +121,6 @@ }); | ||
const customDecodeURIComponent = (encodedStr) => { | ||
return encodedStr.replace(/%[0-9A-Fa-f]{2}/g, (match) => String.fromCharCode(parseInt(match.slice(1), 16))); | ||
return encodedStr.replace( | ||
/%[0-9A-Fa-f]{2}/g, | ||
(match) => String.fromCharCode(parseInt(match.slice(1), 16)) | ||
); | ||
}; | ||
@@ -115,0 +127,0 @@ export { |
@@ -5,7 +5,10 @@ 'use strict' | ||
export const isProduction = (env = NODE_ENV) => (env === 'production' || env === 'prod') || | ||
export const isProduction = (env = NODE_ENV) => | ||
env === 'production' || | ||
env === 'prod' || | ||
(env !== 'development' && env !== 'dev' && env !== 'test') | ||
export const isTest = (env = NODE_ENV) => env === 'test' | ||
export const isDevelopment = (env = NODE_ENV) => env === 'development' || env === 'dev' | ||
export const isDevelopment = (env = NODE_ENV) => | ||
env === 'development' || env === 'dev' | ||
export const getNev = (key, env = NODE_ENV) => env[key] |
10
index.js
@@ -10,2 +10,3 @@ 'use strict' | ||
export * from './node.js' | ||
export * from './if.js' | ||
export * from './log.js' | ||
@@ -17,1 +18,10 @@ export * from './string.js' | ||
export * from './component.js' | ||
export * from './props.js' | ||
export * from './extends.js' | ||
export * from './element.js' | ||
export * from './state.js' | ||
export * from './keys.js' | ||
export * from './scope.js' | ||
export * from './methods.js' | ||
export * from './cache.js' | ||
export * from './update.js' |
'use strict' | ||
import { exec } from './object.js' | ||
export const generateKey = (function () { | ||
@@ -15,1 +17,5 @@ let index = 0 | ||
export const createSnapshotId = generateKey | ||
export const createKey = (element, parent, key) => { | ||
return (exec(key, element) || key || element.key || generateKey()).toString() | ||
} |
'use strict' | ||
export const logIf = (bool, ...arg) => { if (bool) arg.map(v => console.log(v)) } | ||
export const logIf = (bool, ...arg) => { | ||
if (bool) arg.map(v => console.log(v)) | ||
} | ||
export const logGroupIf = (bool, key, ...arg) => { | ||
@@ -5,0 +8,0 @@ if (bool) { |
34
node.js
@@ -5,8 +5,11 @@ 'use strict' | ||
export const isNode = (obj) => { | ||
export const isNode = obj => { | ||
return ( | ||
typeof Node === 'object' | ||
(typeof Node === 'object' | ||
? obj instanceof window.Node | ||
: obj && typeof obj === 'object' && typeof obj.nodeType === 'number' && typeof obj.nodeName === 'string' | ||
) || false | ||
: obj && | ||
typeof obj === 'object' && | ||
typeof obj.nodeType === 'number' && | ||
typeof obj.nodeName === 'string') || false | ||
) | ||
} | ||
@@ -17,15 +20,20 @@ | ||
return ( | ||
typeof HTMLElement === 'object' | ||
(typeof HTMLElement === 'object' | ||
? obj instanceof window.HTMLElement // DOM2 | ||
: obj && typeof obj === 'object' && obj !== null && obj.nodeType === 1 && typeof obj.nodeName === 'string' | ||
) || false | ||
: obj && | ||
typeof obj === 'object' && | ||
obj !== null && | ||
obj.nodeType === 1 && | ||
typeof obj.nodeName === 'string') || false | ||
) | ||
} | ||
export const isDOMNode = (obj) => { | ||
return typeof window !== 'undefined' && ( | ||
obj instanceof window.Node || | ||
obj instanceof window.Window || | ||
obj === window || | ||
obj === document | ||
export const isDOMNode = obj => { | ||
return ( | ||
typeof window !== 'undefined' && | ||
(obj instanceof window.Node || | ||
obj instanceof window.Window || | ||
obj === window || | ||
obj === document) | ||
) | ||
} |
358
object.js
@@ -12,8 +12,8 @@ 'use strict' | ||
isUndefined, | ||
isDate, | ||
isNull | ||
} from './types.js' | ||
import { mergeAndCloneIfArray, mergeArray } from './array.js' | ||
import { unstackArrayOfObjects } from './array.js' | ||
import { stringIncludesAny } from './string.js' | ||
import { isDOMNode } from './node.js' | ||
import { METHODS_EXL } from './keys.js' | ||
@@ -34,2 +34,14 @@ const ENV = process.env.NODE_ENV | ||
export const execPromise = async (param, element, state, context) => { | ||
if (isFunction(param)) { | ||
return await param.call( | ||
element, | ||
element, | ||
state || element.state, | ||
context || element.context | ||
) | ||
} | ||
return param | ||
} | ||
export const map = (obj, extention, element) => { | ||
@@ -44,3 +56,5 @@ for (const e in extention) { | ||
const hasOwnProperty = Object.prototype.hasOwnProperty.call(obj, e) | ||
if (!hasOwnProperty || excludeFrom.includes(e) || e.startsWith('__')) continue | ||
if (!hasOwnProperty || excludeFrom.includes(e) || e.startsWith('__')) { | ||
continue | ||
} | ||
const elementProp = element[e] | ||
@@ -55,6 +69,8 @@ const objProp = obj[e] | ||
export const deepMerge = (element, extend, excludeFrom = []) => { | ||
export const deepMerge = (element, extend, excludeFrom = METHODS_EXL) => { | ||
for (const e in extend) { | ||
const hasOwnProperty = Object.prototype.hasOwnProperty.call(extend, e) | ||
if (!hasOwnProperty || excludeFrom.includes(e) || e.startsWith('__')) continue | ||
if (!hasOwnProperty || excludeFrom.includes(e) || e.startsWith('__')) { | ||
continue | ||
} | ||
const elementProp = element[e] | ||
@@ -75,3 +91,9 @@ const extendProp = extend[e] | ||
const hasOwnProperty = Object.prototype.hasOwnProperty.call(obj, prop) | ||
if (!hasOwnProperty || excludeFrom.includes(prop) || prop.startsWith('__')) continue | ||
if ( | ||
!hasOwnProperty || | ||
excludeFrom.includes(prop) || | ||
prop.startsWith('__') | ||
) { | ||
continue | ||
} | ||
o[prop] = obj[prop] | ||
@@ -82,6 +104,2 @@ } | ||
// Merge array, but exclude keys listed in 'excl'z | ||
export const mergeArrayExclude = (arr, exclude = []) => { | ||
return arr.reduce((acc, curr) => deepMerge(acc, deepClone(curr, { exclude })), {}) | ||
} | ||
/** | ||
@@ -96,3 +114,3 @@ * Enhanced deep clone function that combines features from multiple implementations | ||
* @param {WeakMap} options.visited - WeakMap for tracking circular references | ||
* @param {boolean} options.handleExtend - Whether to handle 'extend' arrays specially | ||
* @param {boolean} options.handleExtends - Whether to handle 'extends' arrays specially | ||
* @returns {any} Cloned object | ||
@@ -107,3 +125,3 @@ */ | ||
visited = new WeakMap(), | ||
handleExtend = false | ||
handleExtends = false | ||
} = options | ||
@@ -127,4 +145,4 @@ | ||
: isArray(obj) | ||
? [] | ||
: {} | ||
? [] | ||
: {} | ||
@@ -139,3 +157,5 @@ // Store the clone to handle circular references | ||
// Skip excluded properties | ||
if (exclude.includes(key) || key.startsWith('__') || key === '__proto__') continue | ||
if (exclude.includes(key) || key.startsWith('__') || key === '__proto__') { | ||
continue | ||
} | ||
@@ -145,3 +165,8 @@ const value = obj[key] | ||
// Skip based on cleanup options | ||
if ((cleanUndefined && isUndefined(value)) || (cleanNull && isNull(value))) continue | ||
if ( | ||
(cleanUndefined && isUndefined(value)) || | ||
(cleanNull && isNull(value)) | ||
) { | ||
continue | ||
} | ||
@@ -154,5 +179,5 @@ // Handle special cases | ||
// Handle 'extend' array if enabled | ||
if (handleExtend && key === 'extend' && isArray(value)) { | ||
clone[key] = mergeArray(value, exclude) | ||
// Handle 'extends' array if enabled | ||
if (handleExtends && key === 'extends' && isArray(value)) { | ||
clone[key] = unstackArrayOfObjects(value, exclude) | ||
continue | ||
@@ -186,3 +211,6 @@ } | ||
if (obj.node || obj.__ref || obj.parent || obj.__element || obj.parse) { | ||
(obj.__element || obj.parent?.__element).warn('Trying to clone element or state at', obj) | ||
;(obj.__element || obj.parent?.__element).warn( | ||
'Trying to clone element or state at', | ||
obj | ||
) | ||
obj = obj.parse?.() | ||
@@ -217,38 +245,2 @@ } | ||
const MAX_DEPTH = 100 // Adjust this value as needed | ||
export const deepStringifyWithMaxDepth = (obj, stringified = {}, depth = 0, path = '') => { | ||
if (depth > MAX_DEPTH) { | ||
console.warn(`Maximum depth exceeded at path: ${path}. Possible circular reference.`) | ||
return '[MAX_DEPTH_EXCEEDED]' | ||
} | ||
for (const prop in obj) { | ||
const currentPath = path ? `${path}.${prop}` : prop | ||
const objProp = obj[prop] | ||
if (isFunction(objProp)) { | ||
stringified[prop] = objProp.toString() | ||
} else if (isObject(objProp)) { | ||
stringified[prop] = {} | ||
deepStringifyWithMaxDepth(objProp, stringified[prop], depth + 1, currentPath) | ||
} else if (isArray(objProp)) { | ||
stringified[prop] = [] | ||
objProp.forEach((v, i) => { | ||
const itemPath = `${currentPath}[${i}]` | ||
if (isObject(v)) { | ||
stringified[prop][i] = {} | ||
deepStringifyWithMaxDepth(v, stringified[prop][i], depth + 1, itemPath) | ||
} else if (isFunction(v)) { | ||
stringified[prop][i] = v.toString() | ||
} else { | ||
stringified[prop][i] = v | ||
} | ||
}) | ||
} else { | ||
stringified[prop] = objProp | ||
} | ||
} | ||
return stringified | ||
} | ||
export const objectToString = (obj = {}, indent = 0) => { | ||
@@ -269,3 +261,18 @@ // Handle empty object case | ||
for (const [key, value] of Object.entries(obj)) { | ||
const keyNotAllowdChars = stringIncludesAny(key, ['&', '*', '-', ':', '%', '{', '}', '>', '<', '@', '.', '/', '!', ' ']) | ||
const keyNotAllowdChars = stringIncludesAny(key, [ | ||
'&', | ||
'*', | ||
'-', | ||
':', | ||
'%', | ||
'{', | ||
'}', | ||
'>', | ||
'<', | ||
'@', | ||
'.', | ||
'/', | ||
'!', | ||
' ' | ||
]) | ||
const stringedKey = keyNotAllowdChars ? `'${key}'` : key | ||
@@ -289,3 +296,5 @@ str += `${spaces} ${stringedKey}: ` | ||
} else if (isString(value)) { | ||
str += stringIncludesAny(value, ['\n', '\'']) ? `\`${value}\`` : `'${value}'` | ||
str += stringIncludesAny(value, ['\n', "'"]) | ||
? `\`${value}\`` | ||
: `'${value}'` | ||
} else { | ||
@@ -302,31 +311,3 @@ str += value | ||
/** | ||
* Stringify object | ||
*/ | ||
export const detachFunctionsFromObject = (obj, detached = {}) => { | ||
for (const prop in obj) { | ||
const objProp = obj[prop] | ||
if (isFunction(objProp)) continue | ||
else if (isObject(objProp)) { | ||
detached[prop] = {} | ||
deepStringify(objProp, detached[prop]) | ||
} else if (isArray(objProp)) { | ||
detached[prop] = [] | ||
objProp.forEach((v, i) => { | ||
if (isFunction(v)) return | ||
if (isObject(v)) { | ||
detached[prop][i] = {} | ||
detachFunctionsFromObject(v, detached[prop][i]) | ||
} else { | ||
detached[prop][i] = v | ||
} | ||
}) | ||
} else { | ||
detached[prop] = objProp | ||
} | ||
} | ||
return detached | ||
} | ||
export const hasFunction = (str) => { | ||
export const hasFunction = str => { | ||
if (!str) return false | ||
@@ -377,3 +358,3 @@ | ||
destringified[prop] = [] | ||
objProp.forEach((arrProp) => { | ||
objProp.forEach(arrProp => { | ||
if (isString(arrProp)) { | ||
@@ -408,96 +389,16 @@ if (hasFunction(arrProp)) { | ||
return str ? window.eval('(' + str + ')') : {} // eslint-disable-line | ||
} catch (e) { if (opts.verbose) console.warn(e) } | ||
} | ||
export const diffObjects = (original, objToDiff, cache) => { | ||
for (const e in objToDiff) { | ||
if (e === 'ref') continue | ||
const originalProp = original[e] | ||
const objToDiffProp = objToDiff[e] | ||
if (isObject(originalProp) && isObject(objToDiffProp)) { | ||
cache[e] = {} | ||
diff(originalProp, objToDiffProp, cache[e]) | ||
} else if (objToDiffProp !== undefined) { | ||
cache[e] = objToDiffProp | ||
} | ||
} catch (e) { | ||
if (opts.verbose) console.warn(e) | ||
} | ||
return cache | ||
} | ||
export const diffArrays = (original, objToDiff, cache) => { | ||
if (original.length !== objToDiff.length) { | ||
cache = objToDiff | ||
} else { | ||
const diffArr = [] | ||
for (let i = 0; i < original.length; i++) { | ||
const diffObj = diff(original[i], objToDiff[i]) | ||
if (Object.keys(diffObj).length > 0) { | ||
diffArr.push(diffObj) | ||
} | ||
} | ||
if (diffArr.length > 0) { | ||
cache = diffArr | ||
} | ||
} | ||
return cache | ||
} | ||
export const hasOwnProperty = (o, ...args) => | ||
Object.prototype.hasOwnProperty.call(o, ...args) | ||
export const diff = (original, objToDiff, cache = {}) => { | ||
if (isArray(original) && isArray(objToDiff)) { | ||
cache = [] | ||
diffArrays(original, objToDiff, cache) | ||
} else { | ||
diffObjects(original, objToDiff, cache) | ||
} | ||
return cache | ||
} | ||
export const hasOwnProperty = (o, ...args) => Object.prototype.hasOwnProperty.call(o, ...args) | ||
export const isEmpty = o => Object.keys(o).length === 0 | ||
export const isEmptyObject = (o) => isObject(o) && isEmpty(o) | ||
export const isEmptyObject = o => isObject(o) && isEmpty(o) | ||
export const makeObjectWithoutPrototype = () => Object.create(null) | ||
// by mattphillips | ||
// https://github.com/mattphillips/deep-object-diff/blob/main/src/diff.js | ||
export const deepDiff = (lhs, rhs) => { | ||
if (lhs === rhs) return {} | ||
if (!isObjectLike(lhs) || !isObjectLike(rhs)) return rhs | ||
const deletedValues = Object.keys(lhs).reduce((acc, key) => { | ||
if (!hasOwnProperty(rhs, key)) { | ||
acc[key] = undefined | ||
} | ||
return acc | ||
}, makeObjectWithoutPrototype()) | ||
if (isDate(lhs) || isDate(rhs)) { | ||
if (lhs.valueOf() === rhs.valueOf()) return {} | ||
return rhs | ||
} | ||
return Object.keys(rhs).reduce((acc, key) => { | ||
if (!hasOwnProperty(lhs, key)) { | ||
acc[key] = rhs[key] | ||
return acc | ||
} | ||
const difference = diff(lhs[key], rhs[key]) | ||
if (isEmptyObject(difference) && !isDate(difference) && (isEmptyObject(lhs[key]) || !isEmptyObject(rhs[key]))) { | ||
return acc | ||
} | ||
acc[key] = difference | ||
return acc | ||
}, deletedValues) | ||
} | ||
/** | ||
@@ -507,6 +408,4 @@ * Overwrites object properties with another | ||
export const overwrite = (element, params, opts = {}) => { | ||
const { __ref: ref } = element | ||
const excl = opts.exclude || [] | ||
const allowUnderscore = opts.preventUnderscore | ||
const preventCaching = opts.preventCaching | ||
@@ -516,3 +415,2 @@ for (const e in params) { | ||
const elementProp = element[e] | ||
const paramsProp = params[e] | ||
@@ -522,8 +420,2 @@ | ||
element[e] = paramsProp | ||
if (ref && !preventCaching) { | ||
ref.__cache[e] = elementProp | ||
} | ||
if (isObject(opts.diff)) { | ||
diff[e] = elementProp | ||
} | ||
} | ||
@@ -546,7 +438,17 @@ } | ||
*/ | ||
export const overwriteDeep = (obj, params, opts = {}, visited = new WeakMap()) => { | ||
export const overwriteDeep = ( | ||
obj, | ||
params, | ||
opts = {}, | ||
visited = new WeakMap() | ||
) => { | ||
const excl = opts.exclude || [] | ||
const forcedExclude = opts.preventForce ? [] : ['node', 'window'] | ||
if (!isObjectLike(obj) || !isObjectLike(params) || isDOMNode(obj) || isDOMNode(params)) { | ||
if ( | ||
!isObjectLike(obj) || | ||
!isObjectLike(params) || | ||
isDOMNode(obj) || | ||
isDOMNode(params) | ||
) { | ||
return params | ||
@@ -578,25 +480,2 @@ } | ||
/** | ||
* Overwrites object properties with another | ||
*/ | ||
export const mergeIfExisted = (a, b) => { | ||
if (isObjectLike(a) && isObjectLike(b)) return deepMerge(a, b) | ||
return a || b | ||
} | ||
/** | ||
* Overwrites object properties with another | ||
*/ | ||
export const flattenRecursive = (param, prop, stack = []) => { | ||
const objectized = mergeAndCloneIfArray(param) | ||
stack.push(objectized) | ||
const extendOfExtend = objectized[prop] | ||
if (extendOfExtend) flattenRecursive(extendOfExtend, prop, stack) | ||
delete objectized[prop] | ||
return stack | ||
} | ||
/** | ||
* Recursively compares two values to determine if they are deeply equal. | ||
@@ -637,3 +516,8 @@ * | ||
// Check if both values are non-null objects | ||
if (typeof param !== 'object' || typeof element !== 'object' || param === null || element === null) { | ||
if ( | ||
typeof param !== 'object' || | ||
typeof element !== 'object' || | ||
param === null || | ||
element === null | ||
) { | ||
return param === element // Compare non-object values directly | ||
@@ -678,38 +562,35 @@ } | ||
if (obj1 === obj2) return true | ||
if (!isObjectLike(obj1) || !isObjectLike(obj2)) return false | ||
if (!isObjectLike(obj1) || !isObjectLike(obj2)) return obj1 === obj2 | ||
if (isDOMNode(obj1) || isDOMNode(obj2)) return obj1 === obj2 | ||
const stack = [[obj1, obj2]] | ||
const visited = new WeakSet() | ||
while (stack.length > 0) { | ||
const [current1, current2] = stack.pop() | ||
function checkContains (target, source) { | ||
if (visited.has(source)) return true | ||
visited.add(source) | ||
if (visited.has(current1)) continue | ||
visited.add(current1) | ||
// Check each property in source | ||
for (const key in source) { | ||
if (!Object.prototype.hasOwnProperty.call(source, key)) continue | ||
if (ignoredKeys.includes(key)) continue | ||
const keys1 = Object.keys(current1).filter(key => !ignoredKeys.includes(key)) | ||
const keys2 = Object.keys(current2).filter(key => !ignoredKeys.includes(key)) | ||
// If key doesn't exist in target, return false | ||
if (!Object.prototype.hasOwnProperty.call(target, key)) return false | ||
if (keys1.length !== keys2.length) return false | ||
const sourceValue = source[key] | ||
const targetValue = target[key] | ||
for (const key of keys1) { | ||
if (!Object.prototype.hasOwnProperty.call(current2, key)) return false | ||
const value1 = current1[key] | ||
const value2 = current2[key] | ||
if (isDOMNode(value1) || isDOMNode(value2)) { | ||
if (value1 !== value2) return false | ||
} else if (isObjectLike(value1) && isObjectLike(value2)) { | ||
if (value1 !== value2) { | ||
stack.push([value1, value2]) | ||
} | ||
} else if (value1 !== value2) { | ||
if (isDOMNode(sourceValue) || isDOMNode(targetValue)) { | ||
if (sourceValue !== targetValue) return false | ||
} else if (isObjectLike(sourceValue) && isObjectLike(targetValue)) { | ||
if (!checkContains(targetValue, sourceValue)) return false | ||
} else if (sourceValue !== targetValue) { | ||
return false | ||
} | ||
} | ||
return true | ||
} | ||
return true | ||
return checkContains(obj1, obj2) | ||
} | ||
@@ -724,3 +605,5 @@ | ||
} else { | ||
throw new Error('Invalid input: props must be a string or an array of strings') | ||
throw new Error( | ||
'Invalid input: props must be a string or an array of strings' | ||
) | ||
} | ||
@@ -730,3 +613,3 @@ return obj | ||
export const createObjectWithoutPrototype = (obj) => { | ||
export const createObjectWithoutPrototype = obj => { | ||
if (obj === null || typeof obj !== 'object') { | ||
@@ -758,3 +641,3 @@ return obj // Return the value if obj is not an object | ||
} | ||
if (index === arr.length - 1 && lastValue !== undefined) { | ||
if (index === arr.length - 1 && lastValue) { | ||
obj[value] = lastValue | ||
@@ -848,3 +731,6 @@ } | ||
if (ENV === 'test' || ENV === 'development') { | ||
console.warn('Warning: Potential infinite loop detected due to repeated sequence:', pattern) | ||
console.warn( | ||
'Warning: Potential infinite loop detected due to repeated sequence:', | ||
pattern | ||
) | ||
} | ||
@@ -857,3 +743,3 @@ return true | ||
export const isCyclic = (obj) => { | ||
export const isCyclic = obj => { | ||
const seenObjects = [] | ||
@@ -860,0 +746,0 @@ |
{ | ||
"name": "@domql/utils", | ||
"version": "2.5.200", | ||
"version": "3.0.0", | ||
"license": "MIT", | ||
@@ -10,3 +10,3 @@ "type": "module", | ||
".": { | ||
"default": "./dist/esm/index.js", | ||
"default": "./index.js", | ||
"import": "./dist/esm/index.js", | ||
@@ -28,3 +28,3 @@ "require": "./dist/cjs/index.js" | ||
}, | ||
"gitHead": "0afb63ec375f0526f47ff300885de393138b01e8", | ||
"gitHead": "bcbdc271a602b958de6a60ab387ea7715a935dc1", | ||
"devDependencies": { | ||
@@ -31,0 +31,0 @@ "@babel/core": "^7.12.0" |
@@ -28,25 +28,41 @@ 'use strict' | ||
const brackRegex = { | ||
2: /\{\{\s*((?:\.\.\/)+)?([^}\s]+)\s*\}\}/g, | ||
3: /\{\{\{\s*((?:\.\.\/)+)?([^}\s]+)\s*\}\}\}/g | ||
2: /{{\s*((?:\.\.\/)*)([\w\d.]+)\s*}}/g, | ||
3: /{{{(\s*(?:\.\.\/)*)([\w\d.]+)\s*}}}/g | ||
} | ||
export function replaceLiteralsWithObjectFields (str, options = {}, forcedState) { | ||
if (!str.includes(options.bracketsLength === 3 ? '{{{' : '{{')) return str | ||
const reg = brackRegex[options.bracketsLength || 2] | ||
const obj = forcedState || this?.state || {} | ||
const getNestedValue = (obj, path) => { | ||
return path.split('.').reduce((acc, part) => { | ||
return acc && acc[part] !== undefined ? acc[part] : undefined | ||
}, obj) | ||
} | ||
export function replaceLiteralsWithObjectFields (str, state = {}, options = {}) { | ||
const { bracketsLength = 2 } = options | ||
const bracketPattern = bracketsLength === 3 ? '{{{' : '{{' | ||
if (!str.includes(bracketPattern)) return str | ||
const reg = brackRegex[bracketsLength] | ||
const obj = state || {} | ||
return str.replace(reg, (_, parentPath, variable) => { | ||
if (parentPath) { | ||
const parentLevels = parentPath.match(options.bracketsLength === 3 ? /\.\.\.\//g : /\.\.\//g).length | ||
const parentLevels = (parentPath.match(/\.\.\//g) || []).length | ||
let parentState = obj | ||
for (let i = 0; i < parentLevels; i++) { | ||
if (!parentState || !parentState.parent) return '' | ||
parentState = parentState.parent | ||
if (!parentState) { | ||
return '' // Return an empty string if the parent level doesn't exist | ||
} | ||
} | ||
const value = parentState[variable.trim()] | ||
return value !== undefined ? `${value}` : '' | ||
// If the variable is 'parent', return the value property | ||
const key = variable.trim() | ||
if (key === 'parent') { | ||
return parentState.value !== undefined ? String(parentState.value) : '' | ||
} | ||
const value = getNestedValue(parentState, key) | ||
return value !== undefined ? String(value) : '' | ||
} else { | ||
const value = obj[variable.trim()] | ||
return value !== undefined ? `${value}` : '' | ||
const value = getNestedValue(obj, variable.trim()) | ||
return value !== undefined ? String(value) : '' | ||
} | ||
@@ -56,3 +72,3 @@ }) | ||
export const lowercaseFirstLetter = (inputString) => { | ||
export const lowercaseFirstLetter = inputString => { | ||
return `${inputString.charAt(0).toLowerCase()}${inputString.slice(1)}` | ||
@@ -103,3 +119,6 @@ } | ||
endLineNumber = i + 1 | ||
endColumn = lines[i].lastIndexOf('}') !== -1 ? lines[i].lastIndexOf('}') + 2 : lines[i].length + 1 | ||
endColumn = | ||
lines[i].lastIndexOf('}') !== -1 | ||
? lines[i].lastIndexOf('}') + 2 | ||
: lines[i].length + 1 | ||
break | ||
@@ -118,3 +137,3 @@ } | ||
export const replaceOctalEscapeSequences = (str) => { | ||
export const replaceOctalEscapeSequences = str => { | ||
// Regex to match octal escape sequences | ||
@@ -133,21 +152,38 @@ const octalRegex = /\\([0-7]{1,3})/g | ||
export const encodeNewlines = (str) => { | ||
return str.split('\n').join('/////n').split('`').join('/////tilde').split('$').join('/////dlrsgn') | ||
export const encodeNewlines = str => { | ||
return str | ||
.split('\n') | ||
.join('/////n') | ||
.split('`') | ||
.join('/////tilde') | ||
.split('$') | ||
.join('/////dlrsgn') | ||
} | ||
export const decodeNewlines = (encodedStr) => { | ||
return encodedStr.split('/////n').join('\n').split('/////tilde').join('`').split('/////dlrsgn').join('$') | ||
export const decodeNewlines = encodedStr => { | ||
return encodedStr | ||
.split('/////n') | ||
.join('\n') | ||
.split('/////tilde') | ||
.join('`') | ||
.split('/////dlrsgn') | ||
.join('$') | ||
} | ||
export const customEncodeURIComponent = (str) => { | ||
return str.split('').map(char => { | ||
if (/[^a-zA-Z0-9\s]/.test(char)) { | ||
return '%' + char.charCodeAt(0).toString(16).toUpperCase() | ||
} | ||
return char | ||
}).join('') | ||
export const customEncodeURIComponent = str => { | ||
return str | ||
.split('') | ||
.map(char => { | ||
if (/[^a-zA-Z0-9\s]/.test(char)) { | ||
return '%' + char.charCodeAt(0).toString(16).toUpperCase() | ||
} | ||
return char | ||
}) | ||
.join('') | ||
} | ||
export const customDecodeURIComponent = (encodedStr) => { | ||
return encodedStr.replace(/%[0-9A-Fa-f]{2}/g, match => String.fromCharCode(parseInt(match.slice(1), 16))) | ||
export const customDecodeURIComponent = encodedStr => { | ||
return encodedStr.replace(/%[0-9A-Fa-f]{2}/g, match => | ||
String.fromCharCode(parseInt(match.slice(1), 16)) | ||
) | ||
} |
267068
67.42%78
73.33%8489
70.6%5
66.67%