@dropins/tools 1.4.0-alpha1 → 1.4.0-alpha3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/chunks/Image.js +1 -1
- package/chunks/icons/Add.js +1 -1
- package/chunks/initializer.js +3 -3
- package/chunks/initializer.js.map +1 -1
- package/chunks/locale-config.js +4 -0
- package/chunks/locale-config.js.map +1 -0
- package/components.js +1 -1
- package/components.js.map +1 -1
- package/initializer.js +3 -3
- package/lib/aem/assets.js +1 -1
- package/lib/aem/assets.js.map +1 -1
- package/lib.js +1 -1
- package/lib.js.map +1 -1
- package/package.json +1 -1
- package/preact-compat.js +1 -1
- package/preact-hooks.js +1 -1
- package/types/elsie/src/components/Price/Price.d.ts +1 -1
- package/types/elsie/src/lib/aem/assets.d.ts +77 -30
- package/types/elsie/src/lib/index.d.ts +1 -0
- package/types/elsie/src/lib/initializer.d.ts +6 -0
- package/types/elsie/src/lib/locale-config.d.ts +10 -0
- package/lib/aem/assets.test.d.ts +0 -1
- package/lib/aem/assets.test.js +0 -4
- package/lib/aem/assets.test.js.map +0 -1
- package/lib/aem/configs.test.d.ts +0 -1
- package/lib/aem/configs.test.js +0 -4
- package/lib/aem/configs.test.js.map +0 -1
package/lib.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"lib.js","sources":["/@dropins/tools/src/lib/form-values.ts","/@dropins/tools/src/lib/deepmerge.ts","/@dropins/tools/src/lib/i18n.ts","/@dropins/tools/src/lib/slot.tsx","/@dropins/tools/src/lib/get-cookie.ts"],"sourcesContent":["/********************************************************************\n * Copyright 2024 Adobe\n * All Rights Reserved.\n *\n * NOTICE: Adobe permits you to use, modify, and distribute this \n * file in accordance with the terms of the Adobe license agreement \n * accompanying it. \n *******************************************************************/\n\nexport const getFormValues = (form: HTMLFormElement) => {\n const formData: any = new FormData(form);\n const result = Object.fromEntries(formData);\n return result;\n};\n\nexport const getFormErrors = (form: HTMLFormElement) => {\n const formData: any = new FormData(form);\n\n const data = Object.fromEntries(formData);\n\n const result = Object.entries(data).reduce((result, [key]) => {\n // @ts-ignore\n const field = form.elements[key];\n\n return field?.validationMessage\n ? { ...result, [key]: field.validationMessage }\n : { ...result };\n }, {});\n\n return result;\n};\n","/********************************************************************\n * Copyright 2024 Adobe\n * All Rights Reserved.\n *\n * NOTICE: Adobe permits you to use, modify, and distribute this \n * file in accordance with the terms of the Adobe license agreement \n * accompanying it. \n *******************************************************************/\n\nimport deepmerge from 'deepmerge';\n\nexport { default as deepmerge } from 'deepmerge';\n\nconst mergeOptions = {\n arrayMerge: (target: any, source: any, options: any) => {\n const destination = target.slice();\n\n source.forEach((item: any, index: number) => {\n if (typeof destination[index] === 'undefined') {\n destination[index] = options.cloneUnlessOtherwiseSpecified(\n item,\n options\n );\n } else if (options.isMergeableObject(item)) {\n destination[index] = deepmerge(target[index], item, options);\n } else if (target.indexOf(item) === -1) {\n destination.push(item);\n }\n });\n return destination;\n },\n};\n\nexport function merge<T>(\n prev: T,\n next?: { [key: string]: any }\n) {\n if (!next) return prev;\n\n return deepmerge<T, { [key: string]: any }>(\n prev,\n next,\n mergeOptions\n );\n}\n","/********************************************************************\n * Copyright 2024 Adobe\n * All Rights Reserved.\n *\n * NOTICE: Adobe permits you to use, modify, and distribute this \n * file in accordance with the terms of the Adobe license agreement \n * accompanying it. \n *******************************************************************/\n\n/**\n * Convert locale from Magento standard to react-intl BCP 47 language tag\n *\n * @param {string} locale - A locale (e.g. `fr_FR`).\n * @returns {string} A BCP 47 language tag (e.g. `fr-FR`).\n */\nexport const toLanguageTag = (locale: string) => {\n return locale.replace('_', '-');\n};\n","/********************************************************************\n * Copyright 2024 Adobe\n * All Rights Reserved.\n *\n * NOTICE: Adobe permits you to use, modify, and distribute this \n * file in accordance with the terms of the Adobe license agreement \n * accompanying it. \n *******************************************************************/\n\nimport { cloneElement, ComponentChildren, RefObject, VNode, createElement } from 'preact';\nimport {\n StateUpdater,\n useContext,\n useState,\n useRef,\n useEffect,\n useMemo,\n useCallback,\n} from 'preact/hooks';\nimport { IntlContext, Lang } from '@adobe-commerce/elsie/i18n';\nimport { HTMLAttributes } from 'preact/compat';\nimport { SlotQueueContext } from './render';\n\nimport '@adobe-commerce/elsie/components/UIProvider/debugger.css';\n\ntype MutateElement = (elem: HTMLElement) => void;\n\n\ninterface State {\n get: (key: string) => void;\n set: (key: string, value: any) => void;\n}\n\ninterface SlotElement {\n appendChild: MutateElement;\n prependChild: MutateElement;\n appendSibling: MutateElement;\n prependSibling: MutateElement;\n}\n\ninterface PrivateContext<T> {\n _setProps: (s: StateUpdater<{}>) => void;\n _registerMethod: (\n cb: (next: T & DefaultSlotContext<T>, state: State) => void\n ) => void;\n // eslint-disable-next-line no-undef\n _htmlElementToVNode: (element: HTMLElement, tag: keyof HTMLElementTagNameMap) => VNode;\n}\n\ninterface DefaultSlotContext<T> extends PrivateContext<T> {\n dictionary: Lang;\n getSlotElement: (key: string) => SlotElement;\n replaceWith: MutateElement;\n appendChild: MutateElement;\n prependChild: MutateElement;\n appendSibling: MutateElement;\n prependSibling: MutateElement;\n onRender: (cb: (next: T & DefaultSlotContext<T>) => void) => void;\n onChange: (cb: (next: T & DefaultSlotContext<T>) => void) => void;\n}\n\ntype Context<T> = T & ThisType<DefaultSlotContext<T>>; // NOSONAR\n\nexport type SlotProps<T = any> = (\n ctx: T & DefaultSlotContext<T>,\n element: HTMLDivElement | null\n) => Promise<void> | void;\n\nexport type SlotMethod<P = any> = (\n callback: (next: unknown, state: State) => P\n) => void;\n\n// Slot Hook\nexport function useSlot<K, V extends HTMLElement>(\n name: string,\n // @ts-ignore\n context: Context<K> = {},\n callback?: SlotProps<K>,\n children?: ComponentChildren,\n render?: Function,\n // eslint-disable-next-line no-undef\n contentTag: keyof HTMLElementTagNameMap = 'div'\n): [RefObject<V>, Record<string, any>] {\n const slotsQueue = useContext(SlotQueueContext);\n\n // HTML Element\n const elementRef = useRef<V>(null);\n\n const status = useRef<'pending' | 'ready' | 'loading'>('pending');\n\n // Methods\n const methodsRef = useRef<any>([]);\n\n // Children VNodes\n const [props, _setProps] = useState<Record<string, any>>({\n children: [children],\n });\n\n // Attributes\n const [_state, setState] = useState<any>({});\n\n const state = useMemo(\n () => ({\n get: (key: string) => _state[key],\n set: (key: string, value: any) => {\n setState({ ...state, [key]: value });\n },\n }),\n [_state]\n );\n\n /** Internationalization */\n // @ts-ignore\n const { intl }: any = useContext(IntlContext);\n\n // @ts-ignore\n context.dictionary = intl.dictionary;\n\n /** Privates */\n // @ts-ignore\n context._setProps = (next: State<any>) => {\n _setProps((prev) => {\n // next props\n const _next = typeof next === 'function' ? next(prev) : next;\n\n // On render method...\n if (render) {\n const renderNode = cloneElement(render(prev), { key: 'render' });\n\n // find index of existing render node\n const index = prev.children.findIndex((n: any) => n?.key === 'render');\n\n // replace existing render node\n prev.children[index] = renderNode;\n }\n\n return _next;\n });\n };\n\n const _registerMethod = useCallback((cb: Function) => {\n if (typeof cb === 'function') {\n methodsRef.current.push(cb);\n } else {\n console.warn('Skipped: Invalid _registerMethod', cb);\n }\n }, []);\n\n // @ts-ignore\n context._registerMethod = _registerMethod;\n\n const _htmlElementToVNode = useCallback((elem: HTMLElement) => {\n return createElement(\n contentTag,\n {\n 'data-slot-html-element': elem.tagName.toLowerCase(),\n ref: (refElem: HTMLElement | null): void => {\n refElem?.appendChild(elem);\n }\n },\n null\n );\n }, [contentTag]);\n\n // @ts-ignore\n context._htmlElementToVNode = _htmlElementToVNode;\n\n /** Prebuilt Methods */\n // @ts-ignore\n context.getSlotElement = useCallback(\n (key: string) => {\n const element = elementRef.current?.querySelector(\n `[data-slot-key=\"${key}\"]`\n );\n\n log(\n `🟦 \"${name}\" Slot getSlotElement: ${key}`,\n elementRef.current?.cloneNode(true),\n element?.cloneNode(true)\n );\n\n if (!element) return;\n\n return {\n appendChild: (elem: HTMLElement) => {\n element.appendChild(elem);\n },\n\n prependChild: (elem: HTMLElement) => {\n element.insertBefore(elem, element.firstChild);\n },\n\n appendSibling: (elem: HTMLElement) => {\n const parent = element.parentNode;\n parent?.insertBefore(elem, element.nextSibling);\n },\n\n prependSibling: (elem: HTMLElement) => {\n const parent = element.parentNode;\n parent?.insertBefore(elem, element);\n },\n };\n },\n [name]\n );\n\n // @ts-ignore\n context.onRender = useCallback((cb: Function) => {\n methodsRef.current.push(cb);\n }, []);\n\n /**\n * @deprecated Use `onRender` instead.\n */\n // @ts-ignore\n context.onChange = context.onRender;\n\n // @ts-ignore\n context.replaceWith = useCallback(\n (elem: HTMLElement) => {\n // @ts-ignore\n _registerMethod((next) => {\n // @ts-ignore\n const children = _htmlElementToVNode(elem);\n\n next._setProps({ children: [children] });\n });\n },\n [_htmlElementToVNode, _registerMethod]\n );\n\n // @ts-ignore\n context.appendChild = useCallback(\n (elem: HTMLElement) => {\n // @ts-ignore\n _registerMethod((next) => {\n // @ts-ignore\n const vnode = _htmlElementToVNode(elem);\n\n next._setProps((prev: any) => {\n return {\n ...prev,\n children: [...prev.children, vnode],\n };\n });\n });\n },\n [_htmlElementToVNode, _registerMethod]\n );\n\n // @ts-ignore\n context.prependChild = useCallback(\n (elem: HTMLElement) => {\n // @ts-ignore\n _registerMethod((next) => {\n // @ts-ignore\n const vnode = _htmlElementToVNode(elem);\n\n next._setProps((prev: any) => {\n return {\n ...prev,\n children: [vnode, ...prev.children],\n };\n });\n });\n },\n [_htmlElementToVNode, _registerMethod]\n );\n\n // @ts-ignore\n context.appendSibling = useCallback(\n (elem: HTMLElement) => {\n // @ts-ignore\n _registerMethod(() => {\n const parent = elementRef.current?.parentNode;\n\n parent?.insertBefore(elem, elementRef.current?.nextSibling ?? null);\n });\n },\n [_registerMethod]\n );\n\n // @ts-ignore\n context.prependSibling = useCallback(\n (elem: HTMLElement) => {\n // @ts-ignore\n _registerMethod(() => {\n const parent = elementRef.current?.parentNode;\n\n parent?.insertBefore(elem, elementRef.current);\n });\n },\n [_registerMethod]\n );\n\n const handleLifeCycleRender = useCallback(async () => {\n if (status.current === 'loading') return;\n\n status.current = 'loading';\n\n log(`🟨 \"${name}\" Slot Rendered`);\n\n // Reset\n const renderNode = render\n ? cloneElement(render(props), { key: 'render' })\n : null;\n _setProps({ children: [renderNode ?? children] });\n\n // Run all registered methods\n methodsRef.current.forEach((method: any) => {\n method(context, state);\n });\n\n status.current = 'ready';\n }, [children, context, name, props, render, state]);\n\n // Initialization\n const handleLifeCycleInit = useCallback(async () => {\n if (!callback) return;\n\n try {\n status.current = 'loading';\n\n log(`🟩 \"${name}\" Slot Initialized`);\n await callback(context as K & DefaultSlotContext<K>, elementRef.current as HTMLDivElement | null);\n } catch (error) {\n console.error(`Error in \"${callback.name}\" Slot callback`, error);\n } finally {\n status.current = 'ready';\n\n // first render\n await handleLifeCycleRender();\n }\n }, [callback, context, handleLifeCycleRender, name]);\n\n // Initialization\n useEffect(() => {\n handleLifeCycleInit().finally(() => {\n if (slotsQueue) {\n slotsQueue.value.delete(name);\n slotsQueue.value = new Set(slotsQueue.value);\n }\n });\n\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n // Update\n useEffect(() => {\n handleLifeCycleRender();\n\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [JSON.stringify(context), JSON.stringify(_state)]);\n\n return [elementRef, props];\n}\n\n// Slot Component\ninterface SlotPropsComponent<T>\n extends Omit<HTMLAttributes<HTMLElement>, 'slot'> {\n name: string;\n slot?: SlotProps<T>;\n context?: Context<T>;\n render?: (props: Record<string, any>) => VNode | VNode[];\n // eslint-disable-next-line no-undef\n slotTag?: keyof HTMLElementTagNameMap; // The tag for the slot wrapper itself\n // eslint-disable-next-line no-undef\n contentTag?: keyof HTMLElementTagNameMap; // The tag for dynamically inserted content\n children?: ComponentChildren;\n}\n\nexport function Slot<T>({\n name,\n context,\n slot,\n children,\n render,\n slotTag = 'div',\n contentTag = 'div',\n ...props\n}: Readonly<SlotPropsComponent<T>>): VNode<{\n ref: RefObject<HTMLElement>;\n 'data-slot': string;\n [key: string]: any;\n}> {\n const slotsQueue = useContext(SlotQueueContext);\n\n const [elementRef, slotProps] = useSlot<T, HTMLElement>(\n name,\n context,\n slot,\n children,\n render,\n contentTag\n );\n\n useMemo(() => {\n if (!name) {\n return console.warn('Slot \"name\" is required');\n }\n\n // add slot to queue\n if (slotsQueue) {\n slotsQueue.value.add(name);\n slotsQueue.value = new Set(slotsQueue.value);\n }\n }, [name, slotsQueue]);\n\n return createElement(\n slotTag,\n {\n ...props,\n ref: elementRef,\n 'data-slot': name,\n },\n slotProps.children\n );\n}\n\n// Debugger\n\n// @ts-ignore\nwindow.DROPINS = window.DROPINS || {};\n\n// @ts-ignore\nwindow.DROPINS.showSlots = async (state) => {\n // cache state in session storage\n window.sessionStorage.setItem(\n 'dropin-debugger--show-slots',\n state.toString()\n );\n\n document.body.classList.toggle('dropin-debugger--show-slots', state);\n};\n\nlet log: (...attrs: any) => void = () => {};\n\n// @ts-ignore\nwindow.DROPINS.logSlots = async (state) => {\n // cache state in session storage\n window.sessionStorage.setItem('dropin-debugger--log-slots', state.toString());\n\n log = state ? (...attrs) => console.log(...attrs) : () => {};\n};\n\n/** Persistent Settings */\n\n// @ts-ignore\nwindow.DROPINS.showSlots(\n window.sessionStorage.getItem('dropin-debugger--show-slots') === 'true'\n);\n\n// @ts-ignore\nwindow.DROPINS.logSlots(\n window.sessionStorage.getItem('dropin-debugger--log-slots') === 'true'\n);\n","/**\n * Get cookie\n * @param {string} cookieName - The name of the cookie to get\n * @returns {string} - The value of the cookie\n */\nexport function getCookie(cookieName: string): string | undefined {\n const cookies = document.cookie.split(';');\n let foundValue;\n\n cookies.forEach((cookie) => {\n const [name, value] = cookie.trim().split('=');\n if (name === cookieName) {\n foundValue = decodeURIComponent(value);\n }\n });\n\n return foundValue;\n}\n"],"names":["getFormValues","form","formData","getFormErrors","data","result","key","field","mergeOptions","target","source","options","destination","item","index","deepmerge","merge","prev","next","toLanguageTag","locale","useSlot","name","context","callback","children","render","contentTag","slotsQueue","useContext","SlotQueueContext","elementRef","useRef","status","methodsRef","props","_setProps","useState","_state","setState","state","useMemo","value","intl","IntlContext","_next","renderNode","cloneElement","n","_registerMethod","useCallback","cb","_htmlElementToVNode","elem","createElement","refElem","element","_a","log","_b","parent","vnode","handleLifeCycleRender","method","handleLifeCycleInit","error","useEffect","Slot","slot","slotTag","slotProps","attrs","getCookie","cookieName","cookies","foundValue","cookie"],"mappings":"kjBASa,MAAAA,EAAiBC,GAA0B,CAChD,MAAAC,EAAgB,IAAI,SAASD,CAAI,EAEhC,OADQ,OAAO,YAAYC,CAAQ,CAE5C,EAEaC,EAAiBF,GAA0B,CAChD,MAAAC,EAAgB,IAAI,SAASD,CAAI,EAEjCG,EAAO,OAAO,YAAYF,CAAQ,EAWjC,OATQ,OAAO,QAAQE,CAAI,EAAE,OAAO,CAACC,EAAQ,CAACC,CAAG,IAAM,CAEtD,MAAAC,EAAQN,EAAK,SAASK,CAAG,EAE/B,OAAOC,GAAA,MAAAA,EAAO,kBACV,CAAE,GAAGF,EAAQ,CAACC,CAAG,EAAGC,EAAM,iBAAA,EAC1B,CAAE,GAAGF,CAAO,CAClB,EAAG,EAAE,CAGP,ECjBMG,EAAe,CACnB,WAAY,CAACC,EAAaC,EAAaC,IAAiB,CAChD,MAAAC,EAAcH,EAAO,MAAM,EAE1B,OAAAC,EAAA,QAAQ,CAACG,EAAWC,IAAkB,CACvC,OAAOF,EAAYE,CAAK,EAAM,IACpBF,EAAAE,CAAK,EAAIH,EAAQ,8BAC3BE,EACAF,CACF,EACSA,EAAQ,kBAAkBE,CAAI,EACvCD,EAAYE,CAAK,EAAIC,EAAUN,EAAOK,CAAK,EAAGD,EAAMF,CAAO,EAClDF,EAAO,QAAQI,CAAI,IAAM,IAClCD,EAAY,KAAKC,CAAI,CACvB,CACD,EACMD,CAAA,CAEX,EAEgB,SAAAI,EACdC,EACAC,EACA,CACI,OAACA,EAEEH,EACLE,EACAC,EACAV,CACF,EANkBS,CAOpB,CC7Ba,MAAAE,EAAiBC,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C,EAGpC,OAAO,QAAQ,UAAY,MAAO9B,GAAU,CAE1C,OAAO,eAAe,QACpB,8BACAA,EAAM,SAAS,CACjB,EAEA,SAAS,KAAK,UAAU,OAAO,8BAA+BA,CAAK,CACrE,EAEA,IAAIkB,EAA+B,IAAM,CAAC,EAG1C,OAAO,QAAQ,SAAW,MAAOlB,GAAU,CAEzC,OAAO,eAAe,QAAQ,6BAA8BA,EAAM,UAAU,EAEtEkB,EAAAlB,EAAQ,IAAI+B,IAAU,QAAQ,IAAI,GAAGA,CAAK,EAAI,IAAM,CAAC,CAC7D,EAKA,OAAO,QAAQ,UACb,OAAO,eAAe,QAAQ,6BAA6B,IAAM,MACnE,EAGA,OAAO,QAAQ,SACb,OAAO,eAAe,QAAQ,4BAA4B,IAAM,MAClE,EClcO,SAASC,EAAUC,EAAwC,CAChE,MAAMC,EAAU,SAAS,OAAO,MAAM,GAAG,EACrC,IAAAC,EAEI,OAAAD,EAAA,QAASE,GAAW,CACpB,KAAA,CAACtD,EAAMoB,CAAK,EAAIkC,EAAO,KAAK,EAAE,MAAM,GAAG,EACzCtD,IAASmD,IACXE,EAAa,mBAAmBjC,CAAK,EACvC,CACD,EAEMiC,CACT"}
|
|
1
|
+
{"version":3,"file":"lib.js","sources":["/@dropins/tools/src/lib/form-values.ts","/@dropins/tools/src/lib/deepmerge.ts","/@dropins/tools/src/lib/i18n.ts","/@dropins/tools/src/lib/slot.tsx","/@dropins/tools/src/lib/get-cookie.ts"],"sourcesContent":["/********************************************************************\n * Copyright 2024 Adobe\n * All Rights Reserved.\n *\n * NOTICE: Adobe permits you to use, modify, and distribute this \n * file in accordance with the terms of the Adobe license agreement \n * accompanying it. \n *******************************************************************/\n\nexport const getFormValues = (form: HTMLFormElement) => {\n const formData: any = new FormData(form);\n const result = Object.fromEntries(formData);\n return result;\n};\n\nexport const getFormErrors = (form: HTMLFormElement) => {\n const formData: any = new FormData(form);\n\n const data = Object.fromEntries(formData);\n\n const result = Object.entries(data).reduce((result, [key]) => {\n // @ts-ignore\n const field = form.elements[key];\n\n return field?.validationMessage\n ? { ...result, [key]: field.validationMessage }\n : { ...result };\n }, {});\n\n return result;\n};\n","/********************************************************************\n * Copyright 2024 Adobe\n * All Rights Reserved.\n *\n * NOTICE: Adobe permits you to use, modify, and distribute this \n * file in accordance with the terms of the Adobe license agreement \n * accompanying it. \n *******************************************************************/\n\nimport deepmerge from 'deepmerge';\n\nexport { default as deepmerge } from 'deepmerge';\n\nconst mergeOptions = {\n arrayMerge: (target: any, source: any, options: any) => {\n const destination = target.slice();\n\n source.forEach((item: any, index: number) => {\n if (typeof destination[index] === 'undefined') {\n destination[index] = options.cloneUnlessOtherwiseSpecified(\n item,\n options\n );\n } else if (options.isMergeableObject(item)) {\n destination[index] = deepmerge(target[index], item, options);\n } else if (target.indexOf(item) === -1) {\n destination.push(item);\n }\n });\n return destination;\n },\n};\n\nexport function merge<T>(\n prev: T,\n next?: { [key: string]: any }\n) {\n if (!next) return prev;\n\n return deepmerge<T, { [key: string]: any }>(\n prev,\n next,\n mergeOptions\n );\n}\n","/********************************************************************\n * Copyright 2024 Adobe\n * All Rights Reserved.\n *\n * NOTICE: Adobe permits you to use, modify, and distribute this \n * file in accordance with the terms of the Adobe license agreement \n * accompanying it. \n *******************************************************************/\n\n/**\n * Convert locale from Magento standard to react-intl BCP 47 language tag\n *\n * @param {string} locale - A locale (e.g. `fr_FR`).\n * @returns {string} A BCP 47 language tag (e.g. `fr-FR`).\n */\nexport const toLanguageTag = (locale: string) => {\n return locale.replace('_', '-');\n};\n","/********************************************************************\n * Copyright 2024 Adobe\n * All Rights Reserved.\n *\n * NOTICE: Adobe permits you to use, modify, and distribute this \n * file in accordance with the terms of the Adobe license agreement \n * accompanying it. \n *******************************************************************/\n\nimport { cloneElement, ComponentChildren, RefObject, VNode, createElement } from 'preact';\nimport {\n StateUpdater,\n useContext,\n useState,\n useRef,\n useEffect,\n useMemo,\n useCallback,\n} from 'preact/hooks';\nimport { IntlContext, Lang } from '@adobe-commerce/elsie/i18n';\nimport { HTMLAttributes } from 'preact/compat';\nimport { SlotQueueContext } from './render';\n\nimport '@adobe-commerce/elsie/components/UIProvider/debugger.css';\n\ntype MutateElement = (elem: HTMLElement) => void;\n\n\ninterface State {\n get: (key: string) => void;\n set: (key: string, value: any) => void;\n}\n\ninterface SlotElement {\n appendChild: MutateElement;\n prependChild: MutateElement;\n appendSibling: MutateElement;\n prependSibling: MutateElement;\n}\n\ninterface PrivateContext<T> {\n _setProps: (s: StateUpdater<{}>) => void;\n _registerMethod: (\n cb: (next: T & DefaultSlotContext<T>, state: State) => void\n ) => void;\n // eslint-disable-next-line no-undef\n _htmlElementToVNode: (element: HTMLElement, tag: keyof HTMLElementTagNameMap) => VNode;\n}\n\ninterface DefaultSlotContext<T> extends PrivateContext<T> {\n dictionary: Lang;\n getSlotElement: (key: string) => SlotElement;\n replaceWith: MutateElement;\n appendChild: MutateElement;\n prependChild: MutateElement;\n appendSibling: MutateElement;\n prependSibling: MutateElement;\n onRender: (cb: (next: T & DefaultSlotContext<T>) => void) => void;\n onChange: (cb: (next: T & DefaultSlotContext<T>) => void) => void;\n}\n\ntype Context<T> = T & ThisType<DefaultSlotContext<T>>; // NOSONAR\n\nexport type SlotProps<T = any> = (\n ctx: T & DefaultSlotContext<T>,\n element: HTMLDivElement | null\n) => Promise<void> | void;\n\nexport type SlotMethod<P = any> = (\n callback: (next: unknown, state: State) => P\n) => void;\n\n// Slot Hook\nexport function useSlot<K, V extends HTMLElement>(\n name: string,\n // @ts-ignore\n context: Context<K> = {},\n callback?: SlotProps<K>,\n children?: ComponentChildren,\n render?: Function,\n // eslint-disable-next-line no-undef\n contentTag: keyof HTMLElementTagNameMap = 'div'\n): [RefObject<V>, Record<string, any>] {\n const slotsQueue = useContext(SlotQueueContext);\n\n // HTML Element\n const elementRef = useRef<V>(null);\n\n const status = useRef<'pending' | 'ready' | 'loading'>('pending');\n\n // Methods\n const methodsRef = useRef<any>([]);\n\n // Children VNodes\n const [props, _setProps] = useState<Record<string, any>>({\n children: [children],\n });\n\n // Attributes\n const [_state, setState] = useState<any>({});\n\n const state = useMemo(\n () => ({\n get: (key: string) => _state[key],\n set: (key: string, value: any) => {\n setState({ ...state, [key]: value });\n },\n }),\n [_state]\n );\n\n /** Internationalization */\n // @ts-ignore\n const { intl }: any = useContext(IntlContext);\n\n // @ts-ignore\n context.dictionary = intl.dictionary;\n\n /** Privates */\n // @ts-ignore\n context._setProps = (next: State<any>) => {\n _setProps((prev) => {\n // next props\n const _next = typeof next === 'function' ? next(prev) : next;\n\n // On render method...\n if (render) {\n const renderNode = cloneElement(render(prev), { key: 'render' });\n\n // find index of existing render node\n const index = prev.children.findIndex((n: any) => n?.key === 'render');\n\n // replace existing render node\n prev.children[index] = renderNode;\n }\n\n return _next;\n });\n };\n\n const _registerMethod = useCallback((cb: Function) => {\n if (typeof cb === 'function') {\n methodsRef.current.push(cb);\n } else {\n console.warn('Skipped: Invalid _registerMethod', cb);\n }\n }, []);\n\n // @ts-ignore\n context._registerMethod = _registerMethod;\n\n const _htmlElementToVNode = useCallback((elem: HTMLElement) => {\n return createElement(\n contentTag,\n {\n 'data-slot-html-element': elem.tagName.toLowerCase(),\n ref: (refElem: HTMLElement | null): void => {\n refElem?.appendChild(elem);\n }\n },\n null\n );\n }, [contentTag]);\n\n // @ts-ignore\n context._htmlElementToVNode = _htmlElementToVNode;\n\n /** Prebuilt Methods */\n // @ts-ignore\n context.getSlotElement = useCallback(\n (key: string) => {\n const element = elementRef.current?.querySelector(\n `[data-slot-key=\"${key}\"]`\n );\n\n log(\n `🟦 \"${name}\" Slot getSlotElement: ${key}`,\n elementRef.current?.cloneNode(true),\n element?.cloneNode(true)\n );\n\n if (!element) return;\n\n return {\n appendChild: (elem: HTMLElement) => {\n element.appendChild(elem);\n },\n\n prependChild: (elem: HTMLElement) => {\n element.insertBefore(elem, element.firstChild);\n },\n\n appendSibling: (elem: HTMLElement) => {\n const parent = element.parentNode;\n parent?.insertBefore(elem, element.nextSibling);\n },\n\n prependSibling: (elem: HTMLElement) => {\n const parent = element.parentNode;\n parent?.insertBefore(elem, element);\n },\n };\n },\n [name]\n );\n\n // @ts-ignore\n context.onRender = useCallback((cb: Function) => {\n methodsRef.current.push(cb);\n }, []);\n\n /**\n * @deprecated Use `onRender` instead.\n */\n // @ts-ignore\n context.onChange = context.onRender;\n\n // @ts-ignore\n context.replaceWith = useCallback(\n (elem: HTMLElement) => {\n // @ts-ignore\n _registerMethod((next) => {\n // @ts-ignore\n const children = _htmlElementToVNode(elem);\n\n next._setProps({ children: [children] });\n });\n },\n [_htmlElementToVNode, _registerMethod]\n );\n\n // @ts-ignore\n context.appendChild = useCallback(\n (elem: HTMLElement) => {\n // @ts-ignore\n _registerMethod((next) => {\n // @ts-ignore\n const vnode = _htmlElementToVNode(elem);\n\n next._setProps((prev: any) => {\n return {\n ...prev,\n children: [...prev.children, vnode],\n };\n });\n });\n },\n [_htmlElementToVNode, _registerMethod]\n );\n\n // @ts-ignore\n context.prependChild = useCallback(\n (elem: HTMLElement) => {\n // @ts-ignore\n _registerMethod((next) => {\n // @ts-ignore\n const vnode = _htmlElementToVNode(elem);\n\n next._setProps((prev: any) => {\n return {\n ...prev,\n children: [vnode, ...prev.children],\n };\n });\n });\n },\n [_htmlElementToVNode, _registerMethod]\n );\n\n // @ts-ignore\n context.appendSibling = useCallback(\n (elem: HTMLElement) => {\n // @ts-ignore\n _registerMethod(() => {\n const parent = elementRef.current?.parentNode;\n\n parent?.insertBefore(elem, elementRef.current?.nextSibling ?? null);\n });\n },\n [_registerMethod]\n );\n\n // @ts-ignore\n context.prependSibling = useCallback(\n (elem: HTMLElement) => {\n // @ts-ignore\n _registerMethod(() => {\n const parent = elementRef.current?.parentNode;\n\n parent?.insertBefore(elem, elementRef.current);\n });\n },\n [_registerMethod]\n );\n\n const handleLifeCycleRender = useCallback(async () => {\n if (status.current === 'loading') return;\n\n status.current = 'loading';\n\n log(`🟨 \"${name}\" Slot Rendered`);\n\n // Reset\n const renderNode = render\n ? cloneElement(render(props), { key: 'render' })\n : null;\n _setProps({ children: [renderNode ?? children] });\n\n // Run all registered methods\n methodsRef.current.forEach((method: any) => {\n method(context, state);\n });\n\n status.current = 'ready';\n }, [children, context, name, props, render, state]);\n\n // Initialization\n const handleLifeCycleInit = useCallback(async () => {\n if (!callback) return;\n\n try {\n status.current = 'loading';\n\n log(`🟩 \"${name}\" Slot Initialized`);\n await callback(context as K & DefaultSlotContext<K>, elementRef.current as HTMLDivElement | null);\n } catch (error) {\n console.error(`Error in \"${callback.name}\" Slot callback`, error);\n } finally {\n status.current = 'ready';\n\n // first render\n await handleLifeCycleRender();\n }\n }, [callback, context, handleLifeCycleRender, name]);\n\n // Initialization\n useEffect(() => {\n handleLifeCycleInit().finally(() => {\n if (slotsQueue) {\n slotsQueue.value.delete(name);\n slotsQueue.value = new Set(slotsQueue.value);\n }\n });\n\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n // Update\n useEffect(() => {\n handleLifeCycleRender();\n\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [JSON.stringify(context), JSON.stringify(_state)]);\n\n return [elementRef, props];\n}\n\n// Slot Component\ninterface SlotPropsComponent<T>\n extends Omit<HTMLAttributes<HTMLElement>, 'slot'> {\n name: string;\n slot?: SlotProps<T>;\n context?: Context<T>;\n render?: (props: Record<string, any>) => VNode | VNode[];\n // eslint-disable-next-line no-undef\n slotTag?: keyof HTMLElementTagNameMap; // The tag for the slot wrapper itself\n // eslint-disable-next-line no-undef\n contentTag?: keyof HTMLElementTagNameMap; // The tag for dynamically inserted content\n children?: ComponentChildren;\n}\n\nexport function Slot<T>({\n name,\n context,\n slot,\n children,\n render,\n slotTag = 'div',\n contentTag = 'div',\n ...props\n}: Readonly<SlotPropsComponent<T>>): VNode<{\n ref: RefObject<HTMLElement>;\n 'data-slot': string;\n [key: string]: any;\n}> {\n const slotsQueue = useContext(SlotQueueContext);\n\n const [elementRef, slotProps] = useSlot<T, HTMLElement>(\n name,\n context,\n slot,\n children,\n render,\n contentTag\n );\n\n useMemo(() => {\n if (!name) {\n return console.warn('Slot \"name\" is required');\n }\n\n // add slot to queue\n if (slotsQueue) {\n slotsQueue.value.add(name);\n slotsQueue.value = new Set(slotsQueue.value);\n }\n }, [name, slotsQueue]);\n\n return createElement(\n slotTag,\n {\n ...props,\n ref: elementRef,\n 'data-slot': name,\n },\n slotProps.children\n );\n}\n\n// Debugger\n\n// @ts-ignore\nwindow.DROPINS = window.DROPINS || {};\n\n// @ts-ignore\nwindow.DROPINS.showSlots = async (state) => {\n // cache state in session storage\n window.sessionStorage.setItem(\n 'dropin-debugger--show-slots',\n state.toString()\n );\n\n document.body.classList.toggle('dropin-debugger--show-slots', state);\n};\n\nlet log: (...attrs: any) => void = () => {};\n\n// @ts-ignore\nwindow.DROPINS.logSlots = async (state) => {\n // cache state in session storage\n window.sessionStorage.setItem('dropin-debugger--log-slots', state.toString());\n\n log = state ? (...attrs) => console.log(...attrs) : () => {};\n};\n\n/** Persistent Settings */\n\n// @ts-ignore\nwindow.DROPINS.showSlots(\n window.sessionStorage.getItem('dropin-debugger--show-slots') === 'true'\n);\n\n// @ts-ignore\nwindow.DROPINS.logSlots(\n window.sessionStorage.getItem('dropin-debugger--log-slots') === 'true'\n);\n","/**\n * Get cookie\n * @param {string} cookieName - The name of the cookie to get\n * @returns {string} - The value of the cookie\n */\nexport function getCookie(cookieName: string): string | undefined {\n const cookies = document.cookie.split(';');\n let foundValue;\n\n cookies.forEach((cookie) => {\n const [name, value] = cookie.trim().split('=');\n if (name === cookieName) {\n foundValue = decodeURIComponent(value);\n }\n });\n\n return foundValue;\n}\n"],"names":["getFormValues","form","formData","getFormErrors","data","result","key","field","mergeOptions","target","source","options","destination","item","index","deepmerge","merge","prev","next","toLanguageTag","locale","useSlot","name","context","callback","children","render","contentTag","slotsQueue","useContext","SlotQueueContext","elementRef","useRef","status","methodsRef","props","_setProps","useState","_state","setState","state","useMemo","value","intl","IntlContext","_next","renderNode","cloneElement","n","_registerMethod","useCallback","cb","_htmlElementToVNode","elem","createElement","refElem","element","_a","log","_b","parent","vnode","handleLifeCycleRender","method","handleLifeCycleInit","error","useEffect","Slot","slot","slotTag","slotProps","attrs","getCookie","cookieName","cookies","foundValue","cookie"],"mappings":"ymBASa,MAAAA,EAAiBC,GAA0B,CAChD,MAAAC,EAAgB,IAAI,SAASD,CAAI,EAEhC,OADQ,OAAO,YAAYC,CAAQ,CAE5C,EAEaC,EAAiBF,GAA0B,CAChD,MAAAC,EAAgB,IAAI,SAASD,CAAI,EAEjCG,EAAO,OAAO,YAAYF,CAAQ,EAWjC,OATQ,OAAO,QAAQE,CAAI,EAAE,OAAO,CAACC,EAAQ,CAACC,CAAG,IAAM,CAEtD,MAAAC,EAAQN,EAAK,SAASK,CAAG,EAE/B,OAAOC,GAAA,MAAAA,EAAO,kBACV,CAAE,GAAGF,EAAQ,CAACC,CAAG,EAAGC,EAAM,iBAAA,EAC1B,CAAE,GAAGF,CAAO,CAClB,EAAG,EAAE,CAGP,ECjBMG,EAAe,CACnB,WAAY,CAACC,EAAaC,EAAaC,IAAiB,CAChD,MAAAC,EAAcH,EAAO,MAAM,EAE1B,OAAAC,EAAA,QAAQ,CAACG,EAAWC,IAAkB,CACvC,OAAOF,EAAYE,CAAK,EAAM,IACpBF,EAAAE,CAAK,EAAIH,EAAQ,8BAC3BE,EACAF,CACF,EACSA,EAAQ,kBAAkBE,CAAI,EACvCD,EAAYE,CAAK,EAAIC,EAAUN,EAAOK,CAAK,EAAGD,EAAMF,CAAO,EAClDF,EAAO,QAAQI,CAAI,IAAM,IAClCD,EAAY,KAAKC,CAAI,CACvB,CACD,EACMD,CAAA,CAEX,EAEgB,SAAAI,EACdC,EACAC,EACA,CACI,OAACA,EAEEH,EACLE,EACAC,EACAV,CACF,EANkBS,CAOpB,CC7Ba,MAAAE,EAAiBC,GACrBA,EAAO,QAAQ,IAAK,GAAG,ECyDhB,SAAAC,EACdC,EAEAC,EAAsB,GAC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ACAA,EAAM,SAAS,CACjB,EAEA,SAAS,KAAK,UAAU,OAAO,8BAA+BA,CAAK,CACrE,EAEA,IAAIkB,EAA+B,IAAM,CAAC,EAG1C,OAAO,QAAQ,SAAW,MAAOlB,GAAU,CAEzC,OAAO,eAAe,QAAQ,6BAA8BA,EAAM,UAAU,EAEtEkB,EAAAlB,EAAQ,IAAI+B,IAAU,QAAQ,IAAI,GAAGA,CAAK,EAAI,IAAM,CAAC,CAC7D,EAKA,OAAO,QAAQ,UACb,OAAO,eAAe,QAAQ,6BAA6B,IAAM,MACnE,EAGA,OAAO,QAAQ,SACb,OAAO,eAAe,QAAQ,4BAA4B,IAAM,MAClE,EClcO,SAASC,EAAUC,EAAwC,CAChE,MAAMC,EAAU,SAAS,OAAO,MAAM,GAAG,EACrC,IAAAC,EAEI,OAAAD,EAAA,QAASE,GAAW,CACpB,KAAA,CAACtD,EAAMoB,CAAK,EAAIkC,EAAO,KAAK,EAAE,MAAM,GAAG,EACzCtD,IAASmD,IACXE,EAAa,mBAAmBjC,CAAK,EACvC,CACD,EAEMiC,CACT"}
|
package/package.json
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"name": "@dropins/tools", "version": "1.4.0-
|
|
1
|
+
{"name": "@dropins/tools", "version": "1.4.0-alpha3", "license": "SEE LICENSE IN LICENSE.md"}
|
package/preact-compat.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
/*! Copyright 2025 Adobe
|
|
2
2
|
All Rights Reserved. */
|
|
3
|
-
import{N as a,b as t,k as n,C as r,e as u,L as o,U as d,o as l,f as c,G as i,_ as m,i as f,j as E,m as _,R as S,n as p,r as C,s as R,u as y,v as I,w as L,z as N,I as O,F as T,J as b,K as h,M as x,O as D,Q as F,q as M,x as g,P as U,V,y as v,
|
|
3
|
+
import{N as a,b as t,k as n,C as r,e as u,L as o,U as d,o as l,f as c,G as i,_ as m,i as f,j as E,m as _,R as S,n as p,r as C,s as R,u as y,v as I,w as L,z as N,I as O,F as T,J as b,K as h,M as x,O as D,Q as F,q as M,x as g,P as U,V,y as v,c as A,g as P,d as k,W as w,a as z,T as B,p as W,A as Y,h as j,X as q,Y as G,Z as H}from"./chunks/icons/Add.js";export{a as Children,t as Component,n as Fragment,r as PureComponent,u as StrictMode,o as Suspense,d as SuspenseList,l as __SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED,c as cloneElement,i as createContext,m as createElement,f as createFactory,E as createPortal,_ as createRef,S as default,p as findDOMNode,C as flushSync,R as forwardRef,y as hydrate,I as isElement,L as isFragment,N as isMemo,O as isValidElement,T as lazy,b as memo,h as render,x as startTransition,D as unmountComponentAtNode,F as unstable_batchedUpdates,M as useCallback,g as useContext,U as useDebugValue,V as useDeferredValue,v as useEffect,A as useErrorBoundary,P as useId,k as useImperativeHandle,w as useInsertionEffect,z as useLayoutEffect,B as useMemo,W as useReducer,Y as useRef,j as useState,q as useSyncExternalStore,G as useTransition,H as version};
|
|
4
4
|
//# sourceMappingURL=preact-compat.js.map
|
package/preact-hooks.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
/*! Copyright 2025 Adobe
|
|
2
2
|
All Rights Reserved. */
|
|
3
|
-
import{q as a,x as u,P as t,y as r,
|
|
3
|
+
import{q as a,x as u,P as t,y as r,c as o,g as f,d as c,a as d,T as l,p as m,A as n,h as p}from"./chunks/icons/Add.js";export{a as useCallback,u as useContext,t as useDebugValue,r as useEffect,o as useErrorBoundary,f as useId,c as useImperativeHandle,d as useLayoutEffect,l as useMemo,m as useReducer,n as useRef,p as useState};
|
|
4
4
|
//# sourceMappingURL=preact-hooks.js.map
|
|
@@ -1,44 +1,91 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
1
|
+
import { ImageProps } from '../../components';
|
|
2
|
+
|
|
3
|
+
declare const AEM_ASSETS_FORMATS: readonly ["gif", "jpg", "jpeg", "png", "webp"];
|
|
4
|
+
declare const AEM_ASSETS_ALLOWED_ROTATIONS: readonly [90, 180, 270];
|
|
5
|
+
declare const AEM_ASSETS_ALLOWED_FLIPS: readonly ["h", "v", "hv"];
|
|
6
|
+
/** The allowed formats for the `AEM Assets` image optimization API. */
|
|
7
|
+
export type AemAssetsFormat = (typeof AEM_ASSETS_FORMATS)[number];
|
|
8
|
+
/** The allowed rotations for the `AEM Assets` image optimization API. */
|
|
9
|
+
export type AemAssetsRotation = (typeof AEM_ASSETS_ALLOWED_ROTATIONS)[number];
|
|
10
|
+
/** The allowed flips for the `AEM Assets` image optimization API. */
|
|
11
|
+
export type AemAssetsFlip = (typeof AEM_ASSETS_ALLOWED_FLIPS)[number];
|
|
12
|
+
/**
|
|
13
|
+
* Defines a crop region of an image.
|
|
14
|
+
* @example
|
|
15
|
+
* ```ts
|
|
16
|
+
* // Crop the image to a 80% width and height, starting at 10% from the top and left.
|
|
17
|
+
* const cropSettings: AemAssetsCropSettings = {
|
|
18
|
+
* xOrigin: 10,
|
|
19
|
+
* yOrigin: 10,
|
|
20
|
+
* width: 80,
|
|
21
|
+
* height: 80,
|
|
22
|
+
* };
|
|
23
|
+
*/
|
|
24
|
+
export interface AemAssetsCropSettings {
|
|
25
|
+
/** The (relative) x origin of the crop (between 0 and 100) */
|
|
26
|
+
xOrigin?: number;
|
|
27
|
+
/** The (relative) y origin of the crop (between 0 and 100) */
|
|
28
|
+
yOrigin?: number;
|
|
29
|
+
/** The width of the crop (between 0 and 100) */
|
|
14
30
|
width?: number;
|
|
31
|
+
/** The height of the crop (between 0 and 100) */
|
|
15
32
|
height?: number;
|
|
16
|
-
[key: string]: any;
|
|
17
33
|
}
|
|
18
|
-
|
|
19
|
-
|
|
34
|
+
/**
|
|
35
|
+
* The parameters accepted by the `AEM Assets` image optimization API.
|
|
36
|
+
* @see https://adobe-aem-assets-delivery-experimental.redoc.ly/
|
|
37
|
+
*/
|
|
38
|
+
export interface AemAssetsParams {
|
|
39
|
+
format: AemAssetsFormat;
|
|
40
|
+
rotate?: AemAssetsRotation;
|
|
41
|
+
flip?: AemAssetsFlip;
|
|
42
|
+
crop?: AemAssetsCropSettings;
|
|
43
|
+
width?: number;
|
|
44
|
+
height?: number;
|
|
45
|
+
quality?: number;
|
|
46
|
+
attachment?: boolean;
|
|
47
|
+
sharpen?: boolean;
|
|
48
|
+
blur?: number;
|
|
49
|
+
dpr?: number;
|
|
50
|
+
smartCrop?: string;
|
|
51
|
+
[key: string]: unknown;
|
|
52
|
+
}
|
|
53
|
+
type WithRequired<T, K extends keyof T> = T & {
|
|
54
|
+
[P in K]-?: T[P];
|
|
55
|
+
};
|
|
56
|
+
/** The parameters to be applied to the asset (known width required when using a slot) */
|
|
57
|
+
export type AemAssetsImageSlotConfigParams = WithRequired<Partial<AemAssetsParams>, 'width'>;
|
|
58
|
+
/** The configuration for an image slot. */
|
|
59
|
+
export interface AemAssetsImageSlotConfig {
|
|
60
|
+
/** The alias (i.e. seoName) of the image */
|
|
20
61
|
alias: string;
|
|
21
|
-
|
|
22
|
-
imageProps: {
|
|
62
|
+
/** The props to be applied to the underlying {@link Image} component */
|
|
63
|
+
imageProps: Partial<Omit<ImageProps, 'params' | 'width' | 'height'>> & {
|
|
23
64
|
src: string;
|
|
24
|
-
width?: number;
|
|
25
|
-
height?: number;
|
|
26
|
-
[key: string]: any;
|
|
27
65
|
};
|
|
28
|
-
|
|
66
|
+
/** The parameters to be applied to the asset (known width required when using a slot) */
|
|
67
|
+
params: AemAssetsImageSlotConfigParams;
|
|
68
|
+
/** The element that will contain the image in the slot */
|
|
69
|
+
wrapper?: HTMLElement;
|
|
29
70
|
}
|
|
30
71
|
interface RenderContext {
|
|
31
72
|
replaceWith: (element: HTMLElement) => void;
|
|
32
73
|
}
|
|
74
|
+
/** Returns whether AEM Assets is enabled in the Storefront. */
|
|
33
75
|
export declare function isAemAssetsEnabled(): boolean;
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
};
|
|
76
|
+
/** The default optimization parameters used globally, unless overriden (per use). */
|
|
77
|
+
export declare function getDefaultAemAssetsOptimizationParams(): AemAssetsParams;
|
|
78
|
+
/** Returns true if the given URL is an AEM Assets URL. */
|
|
38
79
|
export declare function isAemAssetsUrl(url: string | URL): boolean;
|
|
39
|
-
|
|
40
|
-
export declare function
|
|
41
|
-
|
|
42
|
-
|
|
80
|
+
/** Generates an optimized URL for AEM Assets. */
|
|
81
|
+
export declare function generateAemAssetsOptimizedUrl(assetUrl: string, alias: string, params?: Partial<AemAssetsParams>): string;
|
|
82
|
+
/**
|
|
83
|
+
* Tries to generate an optimized URL for AEM Assets. Returns the given
|
|
84
|
+
* url if AEM Assets is not enabled or is not an AEM Assets URL.
|
|
85
|
+
*/
|
|
86
|
+
export declare function tryGenerateAemAssetsOptimizedUrl(assetUrl: string, alias: string, params?: Partial<AemAssetsParams>): string;
|
|
87
|
+
/** Creates a slot that renders an AEM Assets image. */
|
|
88
|
+
export declare function makeAemAssetsImageSlot(config: AemAssetsImageSlotConfig): (ctx: RenderContext) => void;
|
|
89
|
+
export declare function tryRenderAemAssetsImage(ctx: RenderContext, config: AemAssetsImageSlotConfig): void;
|
|
43
90
|
export {};
|
|
44
91
|
//# sourceMappingURL=assets.d.ts.map
|
|
@@ -19,6 +19,7 @@ export * from './types';
|
|
|
19
19
|
export * from './slot';
|
|
20
20
|
export * from './vcomponent';
|
|
21
21
|
export * from './image-params-keymap';
|
|
22
|
+
export * from './locale-config';
|
|
22
23
|
export * from './is-number';
|
|
23
24
|
export * from './deviceUtils';
|
|
24
25
|
export * from './get-path-value';
|
|
@@ -51,6 +51,7 @@ export declare class initializers {
|
|
|
51
51
|
static _imageParamsKeyMap: {
|
|
52
52
|
[key: string]: string;
|
|
53
53
|
} | undefined;
|
|
54
|
+
static _globalLocale: string | undefined;
|
|
54
55
|
/**
|
|
55
56
|
* Registers a new initializer. If the initializers have already been mounted,it immediately binds the event listeners and initializes the API for the new initializer.
|
|
56
57
|
* @param initializer - The initializer to register.
|
|
@@ -76,6 +77,11 @@ export declare class initializers {
|
|
|
76
77
|
static setImageParamKeys(params: {
|
|
77
78
|
[key: string]: any;
|
|
78
79
|
}): void;
|
|
80
|
+
/**
|
|
81
|
+
* Sets the global locale. This locale is used by components that need consistent formatting regardless of the user's browser locale.
|
|
82
|
+
* @param locale - The locale string (e.g., 'en-US', 'es-MX', 'fr-FR').
|
|
83
|
+
*/
|
|
84
|
+
static setGlobalLocale(locale: string): void;
|
|
79
85
|
}
|
|
80
86
|
export {};
|
|
81
87
|
//# sourceMappingURL=initializer.d.ts.map
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/********************************************************************
|
|
2
|
+
* Copyright 2024 Adobe
|
|
3
|
+
* All Rights Reserved.
|
|
4
|
+
*
|
|
5
|
+
* NOTICE: Adobe permits you to use, modify, and distribute this
|
|
6
|
+
* file in accordance with the terms of the Adobe license agreement
|
|
7
|
+
* accompanying it.
|
|
8
|
+
*******************************************************************/
|
|
9
|
+
export declare const setGlobalLocale: (value: typeof this._locale) => void, getGlobalLocale: () => string | undefined;
|
|
10
|
+
//# sourceMappingURL=locale-config.d.ts.map
|
package/lib/aem/assets.test.d.ts
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export * from '../../types/elsie/src/lib/aem/assets.test'
|
package/lib/aem/assets.test.js
DELETED
|
@@ -1,4 +0,0 @@
|
|
|
1
|
-
/*! Copyright 2025 Adobe
|
|
2
|
-
All Rights Reserved. */
|
|
3
|
-
import{isAemAssetsEnabled as m,getDefaultAemAssetsOptimizationParams as n,isAemAssetsUrl as l,generateAemAssetsOptimizedUrl as o,tryGenerateAemAssetsOptimizedUrl as i,makeAemAssetsImageSlot as c,tryRenderAemAssetsImage as p}from"./assets.js";import{getConfigValue as r}from"./configs.js";import"../../chunks/Image.js";import"../../preact-jsx-runtime.js";import"../../chunks/icons/Add.js";import"../../i18n.js";import"../../chunks/cjs.js";import"../../chunks/vcomponent.js";import"../../chunks/image-params-keymap.js";import"../../signals.js";import"../../chunks/get-path-value.js";jest.mock("./configs",()=>({getConfigValue:jest.fn().mockImplementation(e=>{if(e==="commerce-assets-enabled")return!0})}));Object.defineProperty(window,"location",{value:{pathname:"/",origin:"https://example.com",protocol:"https:"}});describe("AEM Assets",()=>{beforeEach(()=>{jest.clearAllMocks()}),test("should be enabled",()=>{expect(m()).toBe(!0),r.mockReturnValueOnce("true"),expect(m()).toBe(!0)}),test("should be disabled",()=>{r.mockReturnValueOnce(!1),expect(m()).toBe(!1)}),test("should return default optimization params",()=>{const e=n();expect(e).toEqual({quality:80,format:"webp"})}),test("should return true if url is aem assets url",()=>{expect(l("https://example.com/adobe/assets/urn:aaid:aem:1234567890")).toBe(!0)}),test("should return false if url is not aem assets url",()=>{expect(l("https://example.com/image.jpg")).toBe(!1)}),test("should return true if url is aem assets url with protocol relative path",()=>{expect(l("//example.com/adobe/assets/urn:aaid:aem:1234567890")).toBe(!0)}),test("should generate aem assets optimized url",()=>{const t=o("https://example.com/adobe/assets/urn:aaid:aem:1234567890","test",{quality:80,format:"webp"});expect(t).toBe("https://example.com/adobe/assets/urn:aaid:aem:1234567890/as/test.webp?quality=80")}),test("should generate aem assets optimized url with default params",()=>{const a=o("https://example.com/adobe/assets/urn:aaid:aem:1234567890","test");expect(a).toBe("https://example.com/adobe/assets/urn:aaid:aem:1234567890/as/test.webp?quality=80")}),test("should generate aem assets optimized url with crop",()=>{const t=o("https://example.com/adobe/assets/urn:aaid:aem:1234567890","test",{quality:80,format:"webp",crop:{xOrigin:0,yOrigin:0}});expect(t).toBe("https://example.com/adobe/assets/urn:aaid:aem:1234567890/as/test.webp?quality=80&crop=0p%2C0p%2C100p%2C100p")}),test("should generate aem assets optimized url with size",()=>{const t=o("https://example.com/adobe/assets/urn:aaid:aem:1234567890","test",{quality:80,format:"webp",size:{width:100,height:100}});expect(t).toBe("https://example.com/adobe/assets/urn:aaid:aem:1234567890/as/test.webp?quality=80&size=100%2C100")}),test("should generate aem assets optimized url with width and height",()=>{const t=o("https://example.com/adobe/assets/urn:aaid:aem:1234567890","test",{quality:80,format:"webp",width:100,height:100});expect(t).toBe("https://example.com/adobe/assets/urn:aaid:aem:1234567890/as/test.webp?quality=80&width=100&height=100")}),test("should try generate aem assets optimized url",()=>{const t=i("https://example.com/adobe/assets/urn:aaid:aem:1234567890","test",{quality:80,format:"webp",width:100,height:100});expect(t).toBe("https://example.com/adobe/assets/urn:aaid:aem:1234567890/as/test.webp?quality=80&width=100&height=100")}),test("should try generate aem assets optimized url with default params",()=>{const a=i("https://example.com/adobe/assets/urn:aaid:aem:1234567890","test");expect(a).toBe("https://example.com/adobe/assets/urn:aaid:aem:1234567890/as/test.webp?quality=80")}),test("should try generate aem assets optimized url with crop",()=>{const t=i("https://example.com/adobe/assets/urn:aaid:aem:1234567890","test",{quality:80,format:"webp",crop:{xOrigin:0,yOrigin:0,width:100,height:100}});expect(t).toBe("https://example.com/adobe/assets/urn:aaid:aem:1234567890/as/test.webp?quality=80&crop=0p%2C0p%2C100p%2C100p")}),test("should return original url if aem assets is disabled",()=>{r.mockReturnValueOnce(!1);const e="https://example.com/adobe/assets/urn:aaid:aem:1234567890",t=i(e,"test",{quality:80,format:"webp"});expect(t).toBe(e)}),test("should return original url if url is not aem assets url",()=>{const e="https://example.com/image.jpg",t=i(e,"test",{quality:80,format:"webp"});expect(t).toBe(e)}),test("should make aem assets image slot",()=>{const e=c({alias:"test",params:{},imageProps:{src:"https://example.com/adobe/assets/urn:aaid:aem:1234567890"}}),s=document.createElement("div");e({replaceWith:a=>{s.appendChild(a)}})}),test("should try render aem assets image",()=>{const e=document.createElement("div");p({replaceWith:t=>{e.appendChild(t)}},{alias:"test",params:{},imageProps:{src:"https://example.com/adobe/assets/urn:aaid:aem:1234567890"}})}),test("should render default image if aem assets is disabled",()=>{r.mockReturnValueOnce(!1);const e=document.createElement("div");p({replaceWith:t=>{e.appendChild(t)}},{alias:"test",params:{},imageProps:{src:"https://example.com/adobe/assets/urn:aaid:aem:1234567890"}})}),test("should render default image if url is not aem assets url",()=>{const e=document.createElement("div");p({replaceWith:t=>{e.appendChild(t)}},{alias:"test",params:{},imageProps:{src:"https://example.com/image.jpg"}})})});
|
|
4
|
-
//# sourceMappingURL=assets.test.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"assets.test.js","sources":["/@dropins/tools/src/lib/aem/assets.test.ts"],"sourcesContent":["import {\n isAemAssetsEnabled,\n getDefaultAemAssetsOptimizationParams,\n isAemAssetsUrl,\n generateAemAssetsOptimizedUrl,\n tryGenerateAemAssetsOptimizedUrl,\n makeAemAssetsImageSlot,\n tryRenderAemAssetsImage,\n} from './assets';\n\nimport { getConfigValue } from './configs';\n\n// Mock the config\njest.mock('./configs', () => ({\n getConfigValue: jest.fn().mockImplementation((key: string) => {\n if (key === 'commerce-assets-enabled') {\n return true;\n }\n return undefined;\n }),\n}));\n\n// Mock window.location\nObject.defineProperty(window, 'location', {\nvalue: {\n pathname: '/',\n origin: 'https://example.com',\n protocol: 'https:',\n},\n});\n\ndescribe('AEM Assets', () => {\n beforeEach(() => {\n jest.clearAllMocks();\n });\n\n test('should be enabled', () => {\n expect(isAemAssetsEnabled()).toBe(true);\n\n (getConfigValue as jest.Mock).mockReturnValueOnce('true');\n expect(isAemAssetsEnabled()).toBe(true);\n });\n\n test('should be disabled', () => {\n (getConfigValue as jest.Mock).mockReturnValueOnce(false);\n expect(isAemAssetsEnabled()).toBe(false);\n });\n\n test('should return default optimization params', () => {\n const params = getDefaultAemAssetsOptimizationParams();\n expect(params).toEqual({\n quality: 80,\n format: 'webp',\n });\n });\n\n test('should return true if url is aem assets url', () => {\n const url = 'https://example.com/adobe/assets/urn:aaid:aem:1234567890';\n expect(isAemAssetsUrl(url)).toBe(true);\n });\n\n test('should return false if url is not aem assets url', () => {\n const url = 'https://example.com/image.jpg';\n expect(isAemAssetsUrl(url)).toBe(false);\n });\n\n test('should return true if url is aem assets url with protocol relative path', () => {\n const url = '//example.com/adobe/assets/urn:aaid:aem:1234567890';\n expect(isAemAssetsUrl(url)).toBe(true);\n });\n\n test('should generate aem assets optimized url', () => {\n const url = 'https://example.com/adobe/assets/urn:aaid:aem:1234567890';\n const alias = 'test';\n const params = {\n quality: 80,\n format: 'webp',\n };\n const optimizedUrl = generateAemAssetsOptimizedUrl(url, alias, params);\n expect(optimizedUrl).toBe('https://example.com/adobe/assets/urn:aaid:aem:1234567890/as/test.webp?quality=80');\n });\n\n test('should generate aem assets optimized url with default params', () => {\n const url = 'https://example.com/adobe/assets/urn:aaid:aem:1234567890';\n const alias = 'test';\n const optimizedUrl = generateAemAssetsOptimizedUrl(url, alias);\n expect(optimizedUrl).toBe('https://example.com/adobe/assets/urn:aaid:aem:1234567890/as/test.webp?quality=80');\n });\n\n test('should generate aem assets optimized url with crop', () => {\n const url = 'https://example.com/adobe/assets/urn:aaid:aem:1234567890';\n const alias = 'test';\n const params = {\n quality: 80,\n format: 'webp',\n crop: {\n xOrigin: 0,\n yOrigin: 0,\n },\n };\n const optimizedUrl = generateAemAssetsOptimizedUrl(url, alias, params);\n expect(optimizedUrl).toBe('https://example.com/adobe/assets/urn:aaid:aem:1234567890/as/test.webp?quality=80&crop=0p%2C0p%2C100p%2C100p');\n });\n\n test('should generate aem assets optimized url with size', () => {\n const url = 'https://example.com/adobe/assets/urn:aaid:aem:1234567890';\n const alias = 'test';\n const params = {\n quality: 80,\n format: 'webp',\n size: {\n width: 100,\n height: 100,\n },\n };\n const optimizedUrl = generateAemAssetsOptimizedUrl(url, alias, params);\n expect(optimizedUrl).toBe('https://example.com/adobe/assets/urn:aaid:aem:1234567890/as/test.webp?quality=80&size=100%2C100');\n });\n\n test('should generate aem assets optimized url with width and height', () => {\n const url = 'https://example.com/adobe/assets/urn:aaid:aem:1234567890';\n const alias = 'test';\n const params = {\n quality: 80,\n format: 'webp',\n width: 100,\n height: 100,\n };\n const optimizedUrl = generateAemAssetsOptimizedUrl(url, alias, params);\n expect(optimizedUrl).toBe('https://example.com/adobe/assets/urn:aaid:aem:1234567890/as/test.webp?quality=80&width=100&height=100');\n });\n\n test('should try generate aem assets optimized url', () => {\n const url = 'https://example.com/adobe/assets/urn:aaid:aem:1234567890';\n const alias = 'test';\n const params = {\n quality: 80,\n format: 'webp',\n width: 100,\n height: 100,\n };\n const optimizedUrl = tryGenerateAemAssetsOptimizedUrl(url, alias, params);\n expect(optimizedUrl).toBe('https://example.com/adobe/assets/urn:aaid:aem:1234567890/as/test.webp?quality=80&width=100&height=100');\n });\n\n test('should try generate aem assets optimized url with default params', () => {\n const url = 'https://example.com/adobe/assets/urn:aaid:aem:1234567890';\n const alias = 'test';\n const optimizedUrl = tryGenerateAemAssetsOptimizedUrl(url, alias);\n expect(optimizedUrl).toBe('https://example.com/adobe/assets/urn:aaid:aem:1234567890/as/test.webp?quality=80');\n });\n\n test('should try generate aem assets optimized url with crop', () => {\n const url = 'https://example.com/adobe/assets/urn:aaid:aem:1234567890';\n const alias = 'test';\n const params = {\n quality: 80,\n format: 'webp',\n crop: {\n xOrigin: 0,\n yOrigin: 0,\n width: 100,\n height: 100,\n },\n };\n const optimizedUrl = tryGenerateAemAssetsOptimizedUrl(url, alias, params);\n expect(optimizedUrl).toBe('https://example.com/adobe/assets/urn:aaid:aem:1234567890/as/test.webp?quality=80&crop=0p%2C0p%2C100p%2C100p');\n }); \n\n test('should return original url if aem assets is disabled', () => {\n (getConfigValue as jest.Mock).mockReturnValueOnce(false);\n const url = 'https://example.com/adobe/assets/urn:aaid:aem:1234567890';\n const alias = 'test';\n const params = {\n quality: 80,\n format: 'webp',\n };\n const optimizedUrl = tryGenerateAemAssetsOptimizedUrl(url, alias, params); \n expect(optimizedUrl).toBe(url);\n });\n\n test('should return original url if url is not aem assets url', () => {\n const url = 'https://example.com/image.jpg';\n const alias = 'test';\n const params = {\n quality: 80,\n format: 'webp',\n };\n const optimizedUrl = tryGenerateAemAssetsOptimizedUrl(url, alias, params);\n expect(optimizedUrl).toBe(url);\n });\n\n test('should make aem assets image slot', () => {\n const slot = makeAemAssetsImageSlot({\n alias: 'test',\n params: {},\n imageProps: {\n src: 'https://example.com/adobe/assets/urn:aaid:aem:1234567890',\n },\n });\n const container = document.createElement('div');\n slot({ replaceWith: (element: HTMLElement) => {\n container.appendChild(element);\n } });\n });\n\n test('should try render aem assets image', () => {\n const container = document.createElement('div');\n const ctx = {\n replaceWith: (element: HTMLElement) => {\n container.appendChild(element);\n },\n };\n const config = {\n alias: 'test',\n params: {},\n imageProps: {\n src: 'https://example.com/adobe/assets/urn:aaid:aem:1234567890',\n },\n };\n tryRenderAemAssetsImage(ctx, config);\n });\n\n test('should render default image if aem assets is disabled', () => {\n (getConfigValue as jest.Mock).mockReturnValueOnce(false);\n const container = document.createElement('div');\n const ctx = {\n replaceWith: (element: HTMLElement) => {\n container.appendChild(element);\n },\n };\n const config = {\n alias: 'test',\n params: {},\n imageProps: {\n src: 'https://example.com/adobe/assets/urn:aaid:aem:1234567890',\n },\n };\n tryRenderAemAssetsImage(ctx, config);\n });\n\n test('should render default image if url is not aem assets url', () => {\n const container = document.createElement('div');\n const ctx = {\n replaceWith: (element: HTMLElement) => {\n container.appendChild(element);\n },\n };\n const config = {\n alias: 'test',\n params: {},\n imageProps: {\n src: 'https://example.com/image.jpg',\n },\n };\n tryRenderAemAssetsImage(ctx, config);\n });\n});"],"names":["key","isAemAssetsEnabled","getConfigValue","params","getDefaultAemAssetsOptimizationParams","isAemAssetsUrl","optimizedUrl","generateAemAssetsOptimizedUrl","tryGenerateAemAssetsOptimizedUrl","url","slot","makeAemAssetsImageSlot","container","element","tryRenderAemAssetsImage"],"mappings":"qkBAaA,KAAK,KAAK,YAAa,KAAO,CAC5B,eAAgB,KAAK,GAAK,EAAA,mBAAoBA,GAAgB,CAC5D,GAAIA,IAAQ,0BACH,MAAA,EAGV,CAAA,CACH,EAAE,EAGF,OAAO,eAAe,OAA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AAKG,CAAG,CAAA,CAC9B,EAED,KAAK,oCAAqC,IAAM,CAC9C,MAAMC,EAAOC,EAAuB,CAClC,MAAO,OACP,OAAQ,CAAC,EACT,WAAY,CACV,IAAK,0DAAA,CACP,CACD,EACKC,EAAY,SAAS,cAAc,KAAK,EACzCF,EAAA,CAAE,YAAcG,GAAyB,CAC5CD,EAAU,YAAYC,CAAO,CAAA,EAC5B,CAAA,CACJ,EAED,KAAK,qCAAsC,IAAM,CACzC,MAAAD,EAAY,SAAS,cAAc,KAAK,EAa9CE,EAZY,CACV,YAAcD,GAAyB,CACrCD,EAAU,YAAYC,CAAO,CAAA,CAEjC,EACe,CACb,MAAO,OACP,OAAQ,CAAC,EACT,WAAY,CACV,IAAK,0DAAA,CAET,CACmC,CAAA,CACpC,EAED,KAAK,wDAAyD,IAAM,CACjEX,EAA6B,oBAAoB,EAAK,EACjD,MAAAU,EAAY,SAAS,cAAc,KAAK,EAa9CE,EAZY,CACV,YAAcD,GAAyB,CACrCD,EAAU,YAAYC,CAAO,CAAA,CAEjC,EACe,CACb,MAAO,OACP,OAAQ,CAAC,EACT,WAAY,CACV,IAAK,0DAAA,CAET,CACmC,CAAA,CACpC,EAED,KAAK,2DAA4D,IAAM,CAC/D,MAAAD,EAAY,SAAS,cAAc,KAAK,EAa9CE,EAZY,CACV,YAAcD,GAAyB,CACrCD,EAAU,YAAYC,CAAO,CAAA,CAEjC,EACe,CACb,MAAO,OACP,OAAQ,CAAC,EACT,WAAY,CACV,IAAK,+BAAA,CAET,CACmC,CAAA,CACpC,CACH,CAAC"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export * from '../../types/elsie/src/lib/aem/configs.test'
|
package/lib/aem/configs.test.js
DELETED
|
@@ -1,4 +0,0 @@
|
|
|
1
|
-
/*! Copyright 2025 Adobe
|
|
2
|
-
All Rights Reserved. */
|
|
3
|
-
import{initializeConfig as o,getConfigValue as s,getRootPath as n,getListOfRootPaths as c,isMultistore as u,getHeaders as a,resetConfig as f}from"./configs.js";import"../../chunks/get-path-value.js";import"../../chunks/cjs.js";describe("AEM Config",()=>{const t={public:{default:{headers:{all:{"x-test":"test"},commerce:{"x-commerce":"commerce"}}}}};beforeEach(()=>{i("/"),f()}),afterEach(()=>{jest.clearAllMocks(),jest.restoreAllMocks()}),test("should initialize config (default)",()=>{const e={public:{default:{foo:"bar"}}},l=o(e);expect(l).toEqual(e.public.default)}),test("should initialize config with default config if root path is not found",()=>{i("/not-found/");const e=o(t);expect(e).toEqual(t.public.default)}),test("should initialize config with default config if root path is empty",()=>{i("/sub-path/");const e=o({...t,public:{...t.public,"/sub-path/":{}}});expect(e).toEqual(t.public.default)}),test("should initialize config with overrides if root path is not empty",()=>{i("/sub-path/");const e=o({...t,public:{...t.public,"/sub-path/":{headers:{all:{"x-test":"test2"}}}}});expect(e).toEqual({headers:{all:{"x-test":"test2"},commerce:{"x-commerce":"commerce"}}})}),test("should throw error if no config is initialized",async()=>{expect(()=>s("foo")).toThrow("Configuration not initialized. Call initializeConfig() first.")}),test("should get config value",async()=>{o({public:{default:{foo:"bar"}}}),expect(s("foo")).toBe("bar")}),test("should get config value from root path",()=>{i("/sub-path/"),o({...t,public:{...t.public,"/sub-path/":{foo:"baz",nested:{foo:"nested"}}}}),expect(s("headers.all.x-test")).toBe("test"),expect(s("foo")).toBe("baz"),expect(s("nested.foo")).toBe("nested")}),test("should warn if value is not found",async()=>{const e=jest.spyOn(console,"warn").mockImplementation(()=>{});o(t),s("foo.bar"),expect(e).toHaveBeenCalledWith("Property foo.bar does not exist in the object")}),test("should warn if the root path has no config",async()=>{const e=jest.spyOn(console,"warn").mockImplementation(()=>{}),l=n(null);expect(l).toBe("/"),expect(e).toHaveBeenCalledWith("No config found. Please call initializeConfig() first.")}),test("should warn if the root path is not found",async()=>{i("/no-found/");const e=n({public:{default:{}}});expect(e).toBe("/")}),test("should get default root path",async()=>{i("/path/"),o(t),expect(n()).toBe("/")}),test("should get root path from public config",async()=>{i("/test/"),o({...t,public:{...t.public,"/test/":{}}}),expect(n()).toBe("/test/")}),test("should get list of root paths",async()=>{o({...t,public:{...t.public,"/test/":{},"/test2/":{}}}),expect(c()).toEqual(["/test/","/test2/"])}),test("should warn if list of root paths has no config",async()=>{const e=jest.spyOn(console,"warn").mockImplementation(()=>{}),l=c();expect(e).toHaveBeenCalledWith("No config found. Please call initializeConfig() first."),expect(l).toEqual([])}),test("should check if multistore",async()=>{o(t),expect(u()).toBe(!1),o({...t,public:{...t.public,"/test/":{}}}),expect(u()).toBe(!0)}),test("should throw error if headers are not initialized",async()=>{expect(()=>a("all")).toThrow("Configuration not initialized. Call initializeConfig() first.")}),test("should get headers",async()=>{o(t),expect(a("all")).toEqual(t.public.default.headers.all),expect(a("commerce")).toEqual({...t.public.default.headers.all,...t.public.default.headers.commerce})}),test('should get "all" headers if no config is found',async()=>{o(t),expect(a("not-found")).toEqual({...t.public.default.headers.all})}),test("should get empty headers if no config is found",async()=>{o({public:{default:{}}}),expect(a("not-found")).toEqual({})})});function i(t){Object.defineProperty(window,"location",{value:{pathname:t,origin:"http://localhost"}})}
|
|
4
|
-
//# sourceMappingURL=configs.test.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"configs.test.js","sources":["/@dropins/tools/src/lib/aem/configs.test.ts"],"sourcesContent":["import {\n resetConfig,\n getRootPath,\n getListOfRootPaths,\n isMultistore,\n getConfigValue,\n getHeaders,\n initializeConfig,\n} from './configs';\n\ndescribe('AEM Config', () => {\n const mockConfig = {\n public: {\n default: {\n headers: {\n all: {\n 'x-test': 'test',\n },\n commerce: {\n 'x-commerce': 'commerce',\n },\n },\n },\n },\n };\n\n beforeEach(() => {\n mockLocation('/');\n resetConfig();\n });\n\n afterEach(() => {\n jest.clearAllMocks();\n jest.restoreAllMocks();\n });\n\n test('should initialize config (default)', () => {\n const mockConfig = {\n public: {\n default: {\n foo: 'bar',\n },\n },\n };\n\n const rootConfig = initializeConfig(mockConfig);\n\n // Test config value retrieval\n expect(rootConfig).toEqual(mockConfig.public.default);\n });\n\n test('should initialize config with default config if root path is not found', () => {\n mockLocation('/not-found/');\n\n const rootConfig = initializeConfig(mockConfig);\n\n // Test config value retrieval\n expect(rootConfig).toEqual(mockConfig.public.default);\n });\n\n test('should initialize config with default config if root path is empty', () => {\n mockLocation('/sub-path/');\n\n const rootConfig = initializeConfig({\n ...mockConfig,\n public: {\n ...mockConfig.public,\n '/sub-path/': {},\n },\n });\n\n // Test config value retrieval\n expect(rootConfig).toEqual(mockConfig.public.default);\n });\n\n test('should initialize config with overrides if root path is not empty', () => {\n mockLocation('/sub-path/');\n\n const rootConfig = initializeConfig({\n ...mockConfig,\n public: {\n ...mockConfig.public,\n '/sub-path/': {\n headers: {\n all: {\n 'x-test': 'test2',\n },\n },\n },\n },\n });\n\n // Test config value retrieval\n expect(rootConfig).toEqual({\n headers: {\n all: {\n 'x-test': 'test2',\n },\n commerce: {\n 'x-commerce': 'commerce',\n },\n },\n });\n });\n\n test('should throw error if no config is initialized', async () => {\n expect(() => getConfigValue('foo')).toThrow(\n 'Configuration not initialized. Call initializeConfig() first.'\n );\n });\n\n test('should get config value', async () => {\n initializeConfig({\n public: {\n default: {\n foo: 'bar',\n },\n },\n });\n\n expect(getConfigValue('foo')).toBe('bar');\n });\n\n test('should get config value from root path', () => {\n mockLocation('/sub-path/');\n\n initializeConfig({\n ...mockConfig,\n public: {\n ...mockConfig.public,\n '/sub-path/': {\n foo: 'baz',\n nested: {\n foo: 'nested',\n },\n },\n },\n });\n\n expect(getConfigValue('headers.all.x-test')).toBe('test');\n expect(getConfigValue('foo')).toBe('baz');\n expect(getConfigValue('nested.foo')).toBe('nested');\n });\n\n test('should warn if value is not found', async () => {\n const consoleSpy = jest.spyOn(console, 'warn').mockImplementation(() => {});\n initializeConfig(mockConfig);\n\n getConfigValue('foo.bar');\n\n expect(consoleSpy).toHaveBeenCalledWith(\n 'Property foo.bar does not exist in the object'\n );\n });\n\n test('should warn if the root path has no config', async () => {\n const consoleSpy = jest.spyOn(console, 'warn').mockImplementation(() => {});\n\n const rootPath = getRootPath(null);\n\n expect(rootPath).toBe('/');\n\n expect(consoleSpy).toHaveBeenCalledWith(\n 'No config found. Please call initializeConfig() first.'\n );\n });\n\n test('should warn if the root path is not found', async () => {\n mockLocation('/no-found/');\n\n const rootPath = getRootPath({\n public: {\n default: {},\n },\n });\n\n expect(rootPath).toBe('/');\n });\n\n test('should get default root path', async () => {\n mockLocation('/path/');\n\n initializeConfig(mockConfig);\n\n expect(getRootPath()).toBe('/');\n });\n\n test('should get root path from public config', async () => {\n mockLocation('/test/');\n\n initializeConfig({\n ...mockConfig,\n public: {\n ...mockConfig.public,\n '/test/': {},\n },\n });\n\n expect(getRootPath()).toBe('/test/');\n });\n\n test('should get list of root paths', async () => {\n initializeConfig({\n ...mockConfig,\n public: {\n ...mockConfig.public,\n '/test/': {},\n '/test2/': {},\n },\n });\n\n expect(getListOfRootPaths()).toEqual(['/test/', '/test2/']);\n });\n\n test('should warn if list of root paths has no config', async () => {\n const consoleSpy = jest.spyOn(console, 'warn').mockImplementation(() => {});\n\n const rootPaths = getListOfRootPaths();\n\n expect(consoleSpy).toHaveBeenCalledWith(\n 'No config found. Please call initializeConfig() first.'\n );\n\n expect(rootPaths).toEqual([]);\n });\n\n test('should check if multistore', async () => {\n initializeConfig(mockConfig);\n\n expect(isMultistore()).toBe(false);\n\n initializeConfig({\n ...mockConfig,\n public: {\n ...mockConfig.public,\n '/test/': {},\n },\n });\n\n expect(isMultistore()).toBe(true);\n });\n\n test('should throw error if headers are not initialized', async () => {\n expect(() => getHeaders('all')).toThrow(\n 'Configuration not initialized. Call initializeConfig() first.'\n );\n });\n\n test('should get headers', async () => {\n initializeConfig(mockConfig);\n\n // All headers\n expect(getHeaders('all')).toEqual(mockConfig.public.default.headers.all);\n expect(getHeaders('commerce')).toEqual({\n ...mockConfig.public.default.headers.all,\n ...mockConfig.public.default.headers.commerce,\n });\n });\n\n test('should get \"all\" headers if no config is found', async () => {\n initializeConfig(mockConfig);\n\n expect(getHeaders('not-found')).toEqual({\n ...mockConfig.public.default.headers.all,\n });\n });\n\n test('should get empty headers if no config is found', async () => {\n initializeConfig({\n public: {\n default: {},\n },\n });\n\n expect(getHeaders('not-found')).toEqual({});\n });\n});\n\nfunction mockLocation(pathname: string) {\n Object.defineProperty(window, 'location', {\n value: {\n pathname,\n origin: 'http://localhost',\n },\n });\n}\n"],"names":["mockConfig","mockLocation","resetConfig","rootConfig","initializeConfig","getConfigValue","consoleSpy","rootPath","getRootPath","getListOfRootPaths","rootPaths","isMultistore","getHeaders","pathname"],"mappings":"mOAUA,SAAS,aAAc,IAAM,CAC3B,MAAMA,EAAa,CACjB,OAAQ,CACN,QAAS,CACP,QAAS,CACP,IAAK,CACH,SAAU,MACZ,EACA,SAAU,CACR,aAAc,UAAA,CAChB,CACF,CACF,CAEJ,EAEA,WAAW,IAAM,CACfC,EAAa,GAAG,EACJC,EAAA,CAAA,CACb,EAED,UAAU,IAAM,CACd,KAAK,cAAc,EACnB,KAAK,gBAAgB,CAAA,CACtB,EAED,KAAK,qCAAsC,IAAM,CAC/C,MAAMF,EAAa,CACjB,OAAQ,CACN,QAAS,CACP,IAAK,KAAA,CACP,CAEJ,EAEMG,EAAaC,EAAiBJ,CAAU,EAG9C,OAAOG,CAAU,EAAE,QAAQH,EAAW,OAAO,OAAO,CAAA,CACrD,EAED,KAAK,yEAA0E,IAAM,CACnFC,EAAa,aAAa,EAEpB,MAAAE,EAAaC,EAAiBJ,CAAU,EAG9C,OAAOG,CAAU,EAAE,QAAQH,EAAW,OAAO,OAAO,CAAA,CACrD,EAED,KAAK,qEAAsE,IAAM,CAC/EC,EAAa,YAAY,EAEzB,MAAME,EAAaC,EAAiB,CAClC,GAAGJ,EACH,OAAQ,CACN,GAAGA,EAAW,OACd,aAAc,CAAA,CAAC,CACjB,CACD,EAGD,OAAOG,CAAU,EAAE,QAAQH,EAAW,OAAO,OAAO,CAAA,CACrD,EAED,KAAK,oEAAqE,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