@intlayer/editor-react 5.1.5 → 5.1.7

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.
Files changed (45) hide show
  1. package/dist/cjs/ConfigurationContext.cjs +1 -9
  2. package/dist/cjs/ConfigurationContext.cjs.map +1 -1
  3. package/dist/cjs/EditedContentContext.cjs +14 -11
  4. package/dist/cjs/EditedContentContext.cjs.map +1 -1
  5. package/dist/cjs/EditorEnabledContext.cjs +16 -12
  6. package/dist/cjs/EditorEnabledContext.cjs.map +1 -1
  7. package/dist/cjs/EditorProvider.cjs +29 -3
  8. package/dist/cjs/EditorProvider.cjs.map +1 -1
  9. package/dist/cjs/useCrossFrameMessageListener.cjs +6 -9
  10. package/dist/cjs/useCrossFrameMessageListener.cjs.map +1 -1
  11. package/dist/cjs/useCrossFrameState.cjs +28 -31
  12. package/dist/cjs/useCrossFrameState.cjs.map +1 -1
  13. package/dist/cjs/useCrossURLPathState.cjs +9 -7
  14. package/dist/cjs/useCrossURLPathState.cjs.map +1 -1
  15. package/dist/esm/ConfigurationContext.mjs +1 -9
  16. package/dist/esm/ConfigurationContext.mjs.map +1 -1
  17. package/dist/esm/EditedContentContext.mjs +12 -10
  18. package/dist/esm/EditedContentContext.mjs.map +1 -1
  19. package/dist/esm/EditorEnabledContext.mjs +13 -11
  20. package/dist/esm/EditorEnabledContext.mjs.map +1 -1
  21. package/dist/esm/EditorProvider.mjs +38 -5
  22. package/dist/esm/EditorProvider.mjs.map +1 -1
  23. package/dist/esm/useCrossFrameMessageListener.mjs +7 -10
  24. package/dist/esm/useCrossFrameMessageListener.mjs.map +1 -1
  25. package/dist/esm/useCrossFrameState.mjs +29 -37
  26. package/dist/esm/useCrossFrameState.mjs.map +1 -1
  27. package/dist/esm/useCrossURLPathState.mjs +8 -7
  28. package/dist/esm/useCrossURLPathState.mjs.map +1 -1
  29. package/dist/types/ConfigurationContext.d.ts +1 -1
  30. package/dist/types/ConfigurationContext.d.ts.map +1 -1
  31. package/dist/types/EditedContentContext.d.ts +2 -2
  32. package/dist/types/EditedContentContext.d.ts.map +1 -1
  33. package/dist/types/EditorEnabledContext.d.ts +3 -1
  34. package/dist/types/EditorEnabledContext.d.ts.map +1 -1
  35. package/dist/types/EditorProvider.d.ts +1 -3
  36. package/dist/types/EditorProvider.d.ts.map +1 -1
  37. package/dist/types/useCrossFrameMessageListener.d.ts +4 -3
  38. package/dist/types/useCrossFrameMessageListener.d.ts.map +1 -1
  39. package/dist/types/useCrossFrameState.d.ts +1 -1
  40. package/dist/types/useCrossFrameState.d.ts.map +1 -1
  41. package/dist/types/useCrossURLPathState.d.ts +2 -1
  42. package/dist/types/useCrossURLPathState.d.ts.map +1 -1
  43. package/dist/types/useIframeClickCommunicator.d.ts +1 -1
  44. package/dist/types/useIframeClickCommunicator.d.ts.map +1 -1
  45. package/package.json +9 -9
@@ -35,15 +35,7 @@ const useConfigurationState = () => (0, import_useCrossFrameState.useCrossFrameS
35
35
  emit: true
36
36
  });
37
37
  const ConfigurationProvider = ({ children, configuration }) => /* @__PURE__ */ (0, import_jsx_runtime.jsx)(ConfigurationStatesContext.Provider, { value: configuration, children });
38
- const useConfiguration = () => {
39
- const statesContext = (0, import_react.useContext)(ConfigurationStatesContext);
40
- if (!statesContext) {
41
- throw new Error(
42
- "useConfigurationStates must be used within a ConfigurationProvider"
43
- );
44
- }
45
- return statesContext;
46
- };
38
+ const useConfiguration = () => (0, import_react.useContext)(ConfigurationStatesContext);
47
39
  // Annotate the CommonJS export names for ESM import in node:
48
40
  0 && (module.exports = {
49
41
  ConfigurationProvider,
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/ConfigurationContext.tsx"],"sourcesContent":["'use client';\n\nimport { type IntlayerConfig } from '@intlayer/config/client';\nimport {\n type FC,\n type PropsWithChildren,\n createContext,\n useContext,\n} from 'react';\nimport { useCrossFrameState } from './useCrossFrameState';\n\nconst ConfigurationStatesContext = createContext<IntlayerConfig | undefined>(\n undefined\n);\n\nexport const useConfigurationState = () =>\n useCrossFrameState<IntlayerConfig>('INTLAYER_CONFIGURATION', undefined, {\n receive: false,\n emit: true,\n });\n\nexport type ConfigurationProviderProps = {\n configuration?: IntlayerConfig;\n};\n\nexport const ConfigurationProvider: FC<\n PropsWithChildren<ConfigurationProviderProps>\n> = ({ children, configuration }) => (\n <ConfigurationStatesContext.Provider value={configuration}>\n {children}\n </ConfigurationStatesContext.Provider>\n);\n\nexport const useConfiguration = () => {\n const statesContext = useContext(ConfigurationStatesContext);\n\n if (!statesContext) {\n throw new Error(\n 'useConfigurationStates must be used within a ConfigurationProvider'\n );\n }\n\n return statesContext;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA4BE;AAzBF,mBAKO;AACP,gCAAmC;AAEnC,MAAM,iCAA6B;AAAA,EACjC;AACF;AAEO,MAAM,wBAAwB,UACnC,8CAAmC,0BAA0B,QAAW;AAAA,EACtE,SAAS;AAAA,EACT,MAAM;AACR,CAAC;AAMI,MAAM,wBAET,CAAC,EAAE,UAAU,cAAc,MAC7B,4CAAC,2BAA2B,UAA3B,EAAoC,OAAO,eACzC,UACH;AAGK,MAAM,mBAAmB,MAAM;AACpC,QAAM,oBAAgB,yBAAW,0BAA0B;AAE3D,MAAI,CAAC,eAAe;AAClB,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EACF;AAEA,SAAO;AACT;","names":[]}
1
+ {"version":3,"sources":["../../src/ConfigurationContext.tsx"],"sourcesContent":["'use client';\n\nimport { type IntlayerConfig } from '@intlayer/config/client';\nimport {\n type FC,\n type PropsWithChildren,\n createContext,\n useContext,\n} from 'react';\nimport { useCrossFrameState } from './useCrossFrameState';\n\nconst ConfigurationStatesContext = createContext<IntlayerConfig | undefined>(\n undefined\n);\n\nexport const useConfigurationState = () =>\n useCrossFrameState<IntlayerConfig>('INTLAYER_CONFIGURATION', undefined, {\n receive: false,\n emit: true,\n });\n\nexport type ConfigurationProviderProps = {\n configuration?: IntlayerConfig;\n};\n\nexport const ConfigurationProvider: FC<\n PropsWithChildren<ConfigurationProviderProps>\n> = ({ children, configuration }) => (\n <ConfigurationStatesContext.Provider value={configuration}>\n {children}\n </ConfigurationStatesContext.Provider>\n);\n\nexport const useConfiguration = () => useContext(ConfigurationStatesContext);\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA4BE;AAzBF,mBAKO;AACP,gCAAmC;AAEnC,MAAM,iCAA6B;AAAA,EACjC;AACF;AAEO,MAAM,wBAAwB,UACnC,8CAAmC,0BAA0B,QAAW;AAAA,EACtE,SAAS;AAAA,EACT,MAAM;AACR,CAAC;AAMI,MAAM,wBAET,CAAC,EAAE,UAAU,cAAc,MAC7B,4CAAC,2BAA2B,UAA3B,EAAoC,OAAO,eACzC,UACH;AAGK,MAAM,mBAAmB,UAAM,yBAAW,0BAA0B;","names":[]}
@@ -22,7 +22,8 @@ __export(EditedContentContext_exports, {
22
22
  EditedContentProvider: () => EditedContentProvider,
23
23
  useEditedContent: () => useEditedContent,
24
24
  useEditedContentActions: () => useEditedContentActions,
25
- useEditedContentState: () => useEditedContentState
25
+ useGetEditedContentState: () => useGetEditedContentState,
26
+ usePostEditedContentState: () => usePostEditedContentState
26
27
  });
27
28
  module.exports = __toCommonJS(EditedContentContext_exports);
28
29
  var import_jsx_runtime = require("react/jsx-runtime");
@@ -30,20 +31,21 @@ var import_core = require("@intlayer/core");
30
31
  var import_react = require("react");
31
32
  var import_DictionariesRecordContext = require('./DictionariesRecordContext.cjs');
32
33
  var import_useCrossFrameState = require('./useCrossFrameState.cjs');
34
+ var import_useCrossFrameMessageListener = require('./useCrossFrameMessageListener.cjs');
33
35
  const EditedContentStateContext = (0, import_react.createContext)(void 0);
34
- const EditedContentActionsContext = (0, import_react.createContext)(void 0);
35
- const useEditedContentState = () => (0, import_useCrossFrameState.useCrossFrameState)(
36
- "INTLAYER_EDITED_CONTENT_CHANGED",
37
- void 0,
38
- { emit: true, receive: false }
36
+ const usePostEditedContentState = (onEventTriggered) => (0, import_useCrossFrameMessageListener.useCrossFrameMessageListener)(
37
+ "INTLAYER_EDITED_CONTENT_CHANGED/post",
38
+ onEventTriggered
39
+ );
40
+ const useGetEditedContentState = (onEventTriggered) => (0, import_useCrossFrameMessageListener.useCrossFrameMessageListener)(
41
+ "INTLAYER_EDITED_CONTENT_CHANGED/get",
42
+ onEventTriggered
39
43
  );
44
+ const EditedContentActionsContext = (0, import_react.createContext)(void 0);
40
45
  const resolveState = (state, prevState) => typeof state === "function" ? state(prevState) : state;
41
46
  const EditedContentProvider = ({ children }) => {
42
47
  const { localeDictionaries } = (0, import_DictionariesRecordContext.useDictionariesRecord)();
43
- const [editedContent, setEditedContentState] = (0, import_useCrossFrameState.useCrossFrameState)(
44
- "INTLAYER_EDITED_CONTENT_CHANGED",
45
- void 0
46
- );
48
+ const [editedContent, setEditedContentState] = (0, import_useCrossFrameState.useCrossFrameState)("INTLAYER_EDITED_CONTENT_CHANGED");
47
49
  const setEditedDictionary = (newValue) => {
48
50
  let updatedDictionaries = resolveState(newValue);
49
51
  setEditedContentState((prev) => {
@@ -219,6 +221,7 @@ const useEditedContent = () => {
219
221
  EditedContentProvider,
220
222
  useEditedContent,
221
223
  useEditedContentActions,
222
- useEditedContentState
224
+ useGetEditedContentState,
225
+ usePostEditedContentState
223
226
  });
224
227
  //# sourceMappingURL=EditedContentContext.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/EditedContentContext.tsx"],"sourcesContent":["'use client';\n\nimport {\n type Dictionary,\n type ContentNode,\n type KeyPath,\n editDictionaryByKeyPath,\n getContentNodeByKeyPath,\n renameContentNodeByKeyPath,\n} from '@intlayer/core';\nimport {\n type Dispatch,\n createContext,\n useContext,\n type SetStateAction,\n type FC,\n type PropsWithChildren,\n} from 'react';\nimport {\n useDictionariesRecord,\n type DictionaryContent,\n} from './DictionariesRecordContext';\nimport { useCrossFrameState } from './useCrossFrameState';\n\ntype EditedContentStateContextType = {\n editedContent: Record<Dictionary['key'], Dictionary> | undefined;\n};\n\nconst EditedContentStateContext = createContext<\n EditedContentStateContextType | undefined\n>(undefined);\n\ntype EditedContentActionsContextType = {\n setEditedContentState: (\n editedContent: Record<Dictionary['key'], Dictionary>\n ) => void;\n setEditedDictionary: Dispatch<SetStateAction<Dictionary>>;\n setEditedContent: (\n dictionaryKey: Dictionary['key'],\n newValue: Dictionary['content']\n ) => void;\n addEditedContent: (\n dictionaryKey: Dictionary['key'],\n newValue: ContentNode<any>,\n keyPath?: KeyPath[],\n overwrite?: boolean\n ) => void;\n renameEditedContent: (\n dictionaryKey: Dictionary['key'],\n newKey: KeyPath['key'],\n keyPath?: KeyPath[]\n ) => void;\n removeEditedContent: (\n dictionaryKey: Dictionary['key'],\n keyPath: KeyPath[]\n ) => void;\n restoreEditedContent: (dictionaryKey: Dictionary['key']) => void;\n clearEditedDictionaryContent: (dictionaryKey: Dictionary['key']) => void;\n clearEditedContent: () => void;\n getEditedContentValue: (\n dictionaryKey: Dictionary['key'],\n keyPath: KeyPath[]\n ) => ContentNode | undefined;\n};\n\nconst EditedContentActionsContext = createContext<\n EditedContentActionsContextType | undefined\n>(undefined);\n\nexport const useEditedContentState = () =>\n useCrossFrameState<DictionaryContent>(\n 'INTLAYER_EDITED_CONTENT_CHANGED',\n undefined,\n { emit: true, receive: false }\n );\n\nconst resolveState = <S,>(state?: SetStateAction<S>, prevState?: S): S =>\n typeof state === 'function'\n ? (state as (prevState?: S) => S)(prevState)\n : (state as S);\n\nexport const EditedContentProvider: FC<PropsWithChildren> = ({ children }) => {\n const { localeDictionaries } = useDictionariesRecord();\n\n const [editedContent, setEditedContentState] =\n useCrossFrameState<DictionaryContent>(\n 'INTLAYER_EDITED_CONTENT_CHANGED',\n undefined\n );\n\n const setEditedDictionary: Dispatch<SetStateAction<Dictionary>> = (\n newValue\n ) => {\n let updatedDictionaries: Dictionary = resolveState(newValue);\n\n setEditedContentState((prev) => {\n updatedDictionaries = resolveState(\n newValue,\n prev?.[updatedDictionaries.key]\n );\n\n return {\n ...prev,\n [updatedDictionaries.key]: updatedDictionaries,\n };\n });\n\n return updatedDictionaries;\n };\n\n const setEditedContent = (\n dictionaryKey: Dictionary['key'],\n newValue: Dictionary['content']\n ) => {\n setEditedContentState((prev) => ({\n ...prev,\n [dictionaryKey]: {\n ...prev?.[dictionaryKey],\n content: newValue,\n },\n }));\n };\n\n const addEditedContent = (\n dictionaryKey: Dictionary['key'],\n newValue: ContentNode,\n keyPath: KeyPath[] = [],\n overwrite: boolean = true\n ) => {\n setEditedContentState((prev) => {\n // Get the starting content: edited version if available, otherwise a deep copy of the original\n const originalContent = localeDictionaries[dictionaryKey]?.content;\n const currentContent = structuredClone(\n prev?.[dictionaryKey]?.content ?? originalContent\n );\n\n let newKeyPath = keyPath;\n if (!overwrite) {\n // Find a unique key based on the keyPath provided\n let index = 0;\n const otherKeyPath = keyPath.slice(0, -1);\n const lastKeyPath: KeyPath = keyPath[keyPath.length - 1];\n let finalKey = lastKeyPath.key;\n\n // Loop until we find a key that does not exist\n while (\n typeof getContentNodeByKeyPath(currentContent, newKeyPath) !==\n 'undefined'\n ) {\n index++;\n finalKey =\n index === 0 ? lastKeyPath.key : `${lastKeyPath.key} (${index})`;\n newKeyPath = [\n ...otherKeyPath,\n { ...lastKeyPath, key: finalKey } as KeyPath,\n ];\n }\n }\n\n const updatedContent = editDictionaryByKeyPath(\n currentContent,\n newKeyPath,\n newValue\n );\n\n return {\n ...prev,\n [dictionaryKey]: {\n ...prev?.[dictionaryKey],\n content: updatedContent as Dictionary['content'],\n },\n };\n });\n };\n\n const renameEditedContent = (\n dictionaryKey: Dictionary['key'],\n newKey: KeyPath['key'],\n keyPath: KeyPath[] = []\n ) => {\n setEditedContentState((prev) => {\n // Retrieve the base content: use edited version if available, otherwise deep copy of original\n const originalContent = localeDictionaries[dictionaryKey]?.content;\n const currentContent = structuredClone(\n prev?.[dictionaryKey]?.content ?? originalContent\n );\n\n const contentWithNewField = renameContentNodeByKeyPath(\n currentContent,\n newKey,\n keyPath\n );\n\n return {\n ...prev,\n [dictionaryKey]: {\n ...prev?.[dictionaryKey],\n content: contentWithNewField as Dictionary['content'],\n },\n };\n });\n };\n\n const removeEditedContent = (\n dictionaryKey: Dictionary['key'],\n keyPath: KeyPath[]\n ) => {\n setEditedContentState((prev) => {\n // Retrieve the original content as reference\n const originalContent = localeDictionaries[dictionaryKey]?.content;\n const currentContent = structuredClone(\n prev?.[dictionaryKey]?.content ?? originalContent\n );\n\n // Get the initial value from the original dictionary content\n const initialContent = getContentNodeByKeyPath(originalContent, keyPath);\n\n // Restore the value at the given keyPath\n const restoredContent = editDictionaryByKeyPath(\n currentContent,\n keyPath,\n initialContent\n );\n\n return {\n ...prev,\n [dictionaryKey]: {\n ...prev?.[dictionaryKey],\n content: restoredContent as Dictionary['content'],\n },\n };\n });\n };\n\n const restoreEditedContent = (dictionaryKey: Dictionary['key']) => {\n setEditedContentState((prev) => {\n const updated = { ...prev };\n delete updated[dictionaryKey];\n return updated;\n });\n };\n\n const clearEditedDictionaryContent = (dictionaryKey: Dictionary['key']) => {\n setEditedContentState((prev) => {\n const filtered = Object.entries(prev).reduce((acc, [key, value]) => {\n if (key === dictionaryKey) {\n return acc;\n }\n return { ...acc, [key]: value };\n }, {} as DictionaryContent);\n return filtered;\n });\n };\n\n const clearEditedContent = () => {\n setEditedContentState({});\n };\n\n const getEditedContentValue = (\n dictionaryKey: Dictionary['key'],\n keyPath: KeyPath[]\n ): ContentNode | undefined => {\n const currentContent = editedContent?.[dictionaryKey]?.content ?? {};\n return getContentNodeByKeyPath(currentContent, keyPath);\n };\n\n return (\n <EditedContentStateContext.Provider\n value={{\n editedContent,\n }}\n >\n <EditedContentActionsContext.Provider\n value={{\n setEditedContentState,\n setEditedDictionary,\n setEditedContent,\n addEditedContent,\n renameEditedContent,\n removeEditedContent,\n restoreEditedContent,\n clearEditedDictionaryContent,\n clearEditedContent,\n getEditedContentValue,\n }}\n >\n {children}\n </EditedContentActionsContext.Provider>\n </EditedContentStateContext.Provider>\n );\n};\n\nexport const useEditedContentActions = () => {\n const context = useContext(EditedContentActionsContext);\n\n if (!context) {\n throw new Error(\n 'useEditedContent must be used within an EditedContentProvider'\n );\n }\n\n return context;\n};\n\nexport const useEditedContent = () => {\n const stateContext = useContext(EditedContentStateContext);\n const actionContext = useEditedContentActions();\n\n if (!stateContext) {\n throw new Error(\n 'useEditedContent must be used within an EditedContentProvider'\n );\n }\n\n return { ...stateContext, ...actionContext };\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAgRM;AA9QN,kBAOO;AACP,mBAOO;AACP,uCAGO;AACP,gCAAmC;AAMnC,MAAM,gCAA4B,4BAEhC,MAAS;AAmCX,MAAM,kCAA8B,4BAElC,MAAS;AAEJ,MAAM,wBAAwB,UACnC;AAAA,EACE;AAAA,EACA;AAAA,EACA,EAAE,MAAM,MAAM,SAAS,MAAM;AAC/B;AAEF,MAAM,eAAe,CAAK,OAA2B,cACnD,OAAO,UAAU,aACZ,MAA+B,SAAS,IACxC;AAEA,MAAM,wBAA+C,CAAC,EAAE,SAAS,MAAM;AAC5E,QAAM,EAAE,mBAAmB,QAAI,wDAAsB;AAErD,QAAM,CAAC,eAAe,qBAAqB,QACzC;AAAA,IACE;AAAA,IACA;AAAA,EACF;AAEF,QAAM,sBAA4D,CAChE,aACG;AACH,QAAI,sBAAkC,aAAa,QAAQ;AAE3D,0BAAsB,CAAC,SAAS;AAC9B,4BAAsB;AAAA,QACpB;AAAA,QACA,OAAO,oBAAoB,GAAG;AAAA,MAChC;AAEA,aAAO;AAAA,QACL,GAAG;AAAA,QACH,CAAC,oBAAoB,GAAG,GAAG;AAAA,MAC7B;AAAA,IACF,CAAC;AAED,WAAO;AAAA,EACT;AAEA,QAAM,mBAAmB,CACvB,eACA,aACG;AACH,0BAAsB,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AAW,CAAC;AACnE,eAAO,qCAAwB,gBAAgB,OAAO;AAAA,EACxD;AAEA,SACE;AAAA,IAAC,0BAA0B;AAAA,IAA1B;AAAA,MACC,OAAO;AAAA,QACL;AAAA,MACF;AAAA,MAEA;AAAA,QAAC,4BAA4B;AAAA,QAA5B;AAAA,UACC,OAAO;AAAA,YACL;AAAA,YACA;AAAA,YACA;AAAA,YACA;AAAA,YACA;AAAA,YACA;AAAA,YACA;AAAA,YACA;AAAA,YACA;AAAA,YACA;AAAA,UACF;AAAA,UAEC;AAAA;AAAA,MACH;AAAA;AAAA,EACF;AAEJ;AAEO,MAAM,0BAA0B,MAAM;AAC3C,QAAM,cAAU,yBAAW,2BAA2B;AAEtD,MAAI,CAAC,SAAS;AACZ,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EACF;AAEA,SAAO;AACT;AAEO,MAAM,mBAAmB,MAAM;AACpC,QAAM,mBAAe,yBAAW,yBAAyB;AACzD,QAAM,gBAAgB,wBAAwB;AAE9C,MAAI,CAAC,cAAc;AACjB,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EACF;AAEA,SAAO,EAAE,GAAG,cAAc,GAAG,cAAc;AAC7C;","names":[]}
1
+ {"version":3,"sources":["../../src/EditedContentContext.tsx"],"sourcesContent":["'use client';\n\nimport {\n type Dictionary,\n type ContentNode,\n type KeyPath,\n editDictionaryByKeyPath,\n getContentNodeByKeyPath,\n renameContentNodeByKeyPath,\n} from '@intlayer/core';\nimport {\n type Dispatch,\n createContext,\n useContext,\n type SetStateAction,\n type FC,\n type PropsWithChildren,\n} from 'react';\nimport {\n useDictionariesRecord,\n type DictionaryContent,\n} from './DictionariesRecordContext';\nimport { useCrossFrameState } from './useCrossFrameState';\nimport { useCrossFrameMessageListener } from './useCrossFrameMessageListener';\n\ntype EditedContentStateContextType = {\n editedContent: Record<Dictionary['key'], Dictionary> | undefined;\n};\n\nconst EditedContentStateContext = createContext<\n EditedContentStateContextType | undefined\n>(undefined);\n\nexport const usePostEditedContentState = <S,>(\n onEventTriggered?: (data: S) => void\n) =>\n useCrossFrameMessageListener(\n 'INTLAYER_EDITED_CONTENT_CHANGED/post',\n onEventTriggered\n );\n\nexport const useGetEditedContentState = <S,>(\n onEventTriggered?: (data: S) => void\n) =>\n useCrossFrameMessageListener(\n 'INTLAYER_EDITED_CONTENT_CHANGED/get',\n onEventTriggered\n );\n\ntype EditedContentActionsContextType = {\n setEditedContentState: (\n editedContent: Record<Dictionary['key'], Dictionary>\n ) => void;\n setEditedDictionary: Dispatch<SetStateAction<Dictionary>>;\n setEditedContent: (\n dictionaryKey: Dictionary['key'],\n newValue: Dictionary['content']\n ) => void;\n addEditedContent: (\n dictionaryKey: Dictionary['key'],\n newValue: ContentNode<any>,\n keyPath?: KeyPath[],\n overwrite?: boolean\n ) => void;\n renameEditedContent: (\n dictionaryKey: Dictionary['key'],\n newKey: KeyPath['key'],\n keyPath?: KeyPath[]\n ) => void;\n removeEditedContent: (\n dictionaryKey: Dictionary['key'],\n keyPath: KeyPath[]\n ) => void;\n restoreEditedContent: (dictionaryKey: Dictionary['key']) => void;\n clearEditedDictionaryContent: (dictionaryKey: Dictionary['key']) => void;\n clearEditedContent: () => void;\n getEditedContentValue: (\n dictionaryKey: Dictionary['key'],\n keyPath: KeyPath[]\n ) => ContentNode | undefined;\n};\n\nconst EditedContentActionsContext = createContext<\n EditedContentActionsContextType | undefined\n>(undefined);\n\nconst resolveState = <S,>(state?: SetStateAction<S>, prevState?: S): S =>\n typeof state === 'function'\n ? (state as (prevState?: S) => S)(prevState)\n : (state as S);\n\nexport const EditedContentProvider: FC<PropsWithChildren> = ({ children }) => {\n const { localeDictionaries } = useDictionariesRecord();\n\n const [editedContent, setEditedContentState] =\n useCrossFrameState<DictionaryContent>('INTLAYER_EDITED_CONTENT_CHANGED');\n\n const setEditedDictionary: Dispatch<SetStateAction<Dictionary>> = (\n newValue\n ) => {\n let updatedDictionaries: Dictionary = resolveState(newValue);\n\n setEditedContentState((prev) => {\n updatedDictionaries = resolveState(\n newValue,\n prev?.[updatedDictionaries.key]\n );\n\n return {\n ...prev,\n [updatedDictionaries.key]: updatedDictionaries,\n };\n });\n\n return updatedDictionaries;\n };\n\n const setEditedContent = (\n dictionaryKey: Dictionary['key'],\n newValue: Dictionary['content']\n ) => {\n setEditedContentState((prev) => ({\n ...prev,\n [dictionaryKey]: {\n ...prev?.[dictionaryKey],\n content: newValue,\n },\n }));\n };\n\n const addEditedContent = (\n dictionaryKey: Dictionary['key'],\n newValue: ContentNode,\n keyPath: KeyPath[] = [],\n overwrite: boolean = true\n ) => {\n setEditedContentState((prev) => {\n // Get the starting content: edited version if available, otherwise a deep copy of the original\n const originalContent = localeDictionaries[dictionaryKey]?.content;\n const currentContent = structuredClone(\n prev?.[dictionaryKey]?.content ?? originalContent\n );\n\n let newKeyPath = keyPath;\n if (!overwrite) {\n // Find a unique key based on the keyPath provided\n let index = 0;\n const otherKeyPath = keyPath.slice(0, -1);\n const lastKeyPath: KeyPath = keyPath[keyPath.length - 1];\n let finalKey = lastKeyPath.key;\n\n // Loop until we find a key that does not exist\n while (\n typeof getContentNodeByKeyPath(currentContent, newKeyPath) !==\n 'undefined'\n ) {\n index++;\n finalKey =\n index === 0 ? lastKeyPath.key : `${lastKeyPath.key} (${index})`;\n newKeyPath = [\n ...otherKeyPath,\n { ...lastKeyPath, key: finalKey } as KeyPath,\n ];\n }\n }\n\n const updatedContent = editDictionaryByKeyPath(\n currentContent,\n newKeyPath,\n newValue\n );\n\n return {\n ...prev,\n [dictionaryKey]: {\n ...prev?.[dictionaryKey],\n content: updatedContent as Dictionary['content'],\n },\n };\n });\n };\n\n const renameEditedContent = (\n dictionaryKey: Dictionary['key'],\n newKey: KeyPath['key'],\n keyPath: KeyPath[] = []\n ) => {\n setEditedContentState((prev) => {\n // Retrieve the base content: use edited version if available, otherwise deep copy of original\n const originalContent = localeDictionaries[dictionaryKey]?.content;\n const currentContent = structuredClone(\n prev?.[dictionaryKey]?.content ?? originalContent\n );\n\n const contentWithNewField = renameContentNodeByKeyPath(\n currentContent,\n newKey,\n keyPath\n );\n\n return {\n ...prev,\n [dictionaryKey]: {\n ...prev?.[dictionaryKey],\n content: contentWithNewField as Dictionary['content'],\n },\n };\n });\n };\n\n const removeEditedContent = (\n dictionaryKey: Dictionary['key'],\n keyPath: KeyPath[]\n ) => {\n setEditedContentState((prev) => {\n // Retrieve the original content as reference\n const originalContent = localeDictionaries[dictionaryKey]?.content;\n const currentContent = structuredClone(\n prev?.[dictionaryKey]?.content ?? originalContent\n );\n\n // Get the initial value from the original dictionary content\n const initialContent = getContentNodeByKeyPath(originalContent, keyPath);\n\n // Restore the value at the given keyPath\n const restoredContent = editDictionaryByKeyPath(\n currentContent,\n keyPath,\n initialContent\n );\n\n return {\n ...prev,\n [dictionaryKey]: {\n ...prev?.[dictionaryKey],\n content: restoredContent as Dictionary['content'],\n },\n };\n });\n };\n\n const restoreEditedContent = (dictionaryKey: Dictionary['key']) => {\n setEditedContentState((prev) => {\n const updated = { ...prev };\n delete updated[dictionaryKey];\n return updated;\n });\n };\n\n const clearEditedDictionaryContent = (dictionaryKey: Dictionary['key']) => {\n setEditedContentState((prev) => {\n const filtered = Object.entries(prev).reduce((acc, [key, value]) => {\n if (key === dictionaryKey) {\n return acc;\n }\n return { ...acc, [key]: value };\n }, {} as DictionaryContent);\n return filtered;\n });\n };\n\n const clearEditedContent = () => {\n setEditedContentState({});\n };\n\n const getEditedContentValue = (\n dictionaryKey: Dictionary['key'],\n keyPath: KeyPath[]\n ): ContentNode | undefined => {\n const currentContent = editedContent?.[dictionaryKey]?.content ?? {};\n return getContentNodeByKeyPath(currentContent, keyPath);\n };\n\n return (\n <EditedContentStateContext.Provider\n value={{\n editedContent,\n }}\n >\n <EditedContentActionsContext.Provider\n value={{\n setEditedContentState,\n setEditedDictionary,\n setEditedContent,\n addEditedContent,\n renameEditedContent,\n removeEditedContent,\n restoreEditedContent,\n clearEditedDictionaryContent,\n clearEditedContent,\n getEditedContentValue,\n }}\n >\n {children}\n </EditedContentActionsContext.Provider>\n </EditedContentStateContext.Provider>\n );\n};\n\nexport const useEditedContentActions = () => {\n const context = useContext(EditedContentActionsContext);\n\n if (!context) {\n throw new Error(\n 'useEditedContent must be used within an EditedContentProvider'\n );\n }\n\n return context;\n};\n\nexport const useEditedContent = () => {\n const stateContext = useContext(EditedContentStateContext);\n const actionContext = useEditedContentActions();\n\n if (!stateContext) {\n throw new Error(\n 'useEditedContent must be used within an EditedContentProvider'\n );\n }\n\n return { ...stateContext, ...actionContext };\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAuRM;AArRN,kBAOO;AACP,mBAOO;AACP,uCAGO;AACP,gCAAmC;AACnC,0CAA6C;AAM7C,MAAM,gCAA4B,4BAEhC,MAAS;AAEJ,MAAM,4BAA4B,CACvC,yBAEA;AAAA,EACE;AAAA,EACA;AACF;AAEK,MAAM,2BAA2B,CACtC,yBAEA;AAAA,EACE;AAAA,EACA;AACF;AAmCF,MAAM,kCAA8B,4BAElC,MAAS;AAEX,MAAM,eAAe,CAAK,OAA2B,cACnD,OAAO,UAAU,aACZ,MAA+B,SAAS,IACxC;AAEA,MAAM,wBAA+C,CAAC,EAAE,SAAS,MAAM;AAC5E,QAAM,EAAE,mBAAmB,QAAI,wDAAsB;AAErD,QAAM,CAAC,eAAe,qBAAqB,QACzC,8CAAsC,iCAAiC;AAEzE,QAAM,sBAA4D,CAChE,aACG;AACH,QAAI,sBAAkC,aAAa,QAAQ;AAE3D,0BAAsB,CAAC,SAAS;AAC9B,4BAAsB;AAAA,QACpB;AAAA,QACA,OAAO,oBAAoB,GAAG;AAAA,MAChC;AAEA,aAAO;AAAA,QACL,GAAG;AAAA,QACH,CAAC,oBAAoB,GAAG,GAAG;AAAA,MAC7B;AAAA,IACF,CAAC;AAED,WAAO;AAAA,EACT;AAEA,QAAM,mBAAmB,CACvB,eACA,aACG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,aAAa,GAAG,WAAW,CAAC;AACnE,eAAO,qCAAwB,gBAAgB,OAAO;AAAA,EACxD;AAEA,SACE;AAAA,IAAC,0BAA0B;AAAA,IAA1B;AAAA,MACC,OAAO;AAAA,QACL;AAAA,MACF;AAAA,MAEA;AAAA,QAAC,4BAA4B;AAAA,QAA5B;AAAA,UACC,OAAO;AAAA,YACL;AAAA,YACA;AAAA,YACA;AAAA,YACA;AAAA,YACA;AAAA,YACA;AAAA,YACA;AAAA,YACA;AAAA,YACA;AAAA,YACA;AAAA,UACF;AAAA,UAEC;AAAA;AAAA,MACH;AAAA;AAAA,EACF;AAEJ;AAEO,MAAM,0BAA0B,MAAM;AAC3C,QAAM,cAAU,yBAAW,2BAA2B;AAEtD,MAAI,CAAC,SAAS;AACZ,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EACF;AAEA,SAAO;AACT;AAEO,MAAM,mBAAmB,MAAM;AACpC,QAAM,mBAAe,yBAAW,yBAAyB;AACzD,QAAM,gBAAgB,wBAAwB;AAE9C,MAAI,CAAC,cAAc;AACjB,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EACF;AAEA,SAAO,EAAE,GAAG,cAAc,GAAG,cAAc;AAC7C;","names":[]}
@@ -21,16 +21,24 @@ var EditorEnabledContext_exports = {};
21
21
  __export(EditorEnabledContext_exports, {
22
22
  EditorEnabledProvider: () => EditorEnabledProvider,
23
23
  useEditorEnabled: () => useEditorEnabled,
24
- useEditorEnabledState: () => useEditorEnabledState
24
+ useEditorEnabledState: () => useEditorEnabledState,
25
+ useGetEditorEnabledState: () => useGetEditorEnabledState,
26
+ usePostEditorEnabledState: () => usePostEditorEnabledState
25
27
  });
26
28
  module.exports = __toCommonJS(EditorEnabledContext_exports);
27
29
  var import_jsx_runtime = require("react/jsx-runtime");
28
30
  var import_react = require("react");
29
31
  var import_useCrossFrameState = require('./useCrossFrameState.cjs');
30
- const EditorEnabledContext = (0, import_react.createContext)(
31
- void 0
32
- );
32
+ var import_useCrossFrameMessageListener = require('./useCrossFrameMessageListener.cjs');
33
+ const EditorEnabledContext = (0, import_react.createContext)({
34
+ enabled: false
35
+ });
33
36
  const useEditorEnabledState = (options) => (0, import_useCrossFrameState.useCrossFrameState)("INTLAYER_EDITOR_ENABLED", false, options);
37
+ const usePostEditorEnabledState = (onEventTriggered) => (0, import_useCrossFrameMessageListener.useCrossFrameMessageListener)(
38
+ "INTLAYER_EDITOR_ENABLED/post",
39
+ onEventTriggered
40
+ );
41
+ const useGetEditorEnabledState = (onEventTriggered) => (0, import_useCrossFrameMessageListener.useCrossFrameMessageListener)("INTLAYER_EDITOR_ENABLED/get", onEventTriggered);
34
42
  const EditorEnabledProvider = ({ children }) => {
35
43
  const [isEnabled] = useEditorEnabledState({
36
44
  emit: false,
@@ -38,17 +46,13 @@ const EditorEnabledProvider = ({ children }) => {
38
46
  });
39
47
  return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(EditorEnabledContext.Provider, { value: { enabled: isEnabled }, children });
40
48
  };
41
- const useEditorEnabled = () => {
42
- const context = (0, import_react.useContext)(EditorEnabledContext);
43
- if (!context) {
44
- throw new Error("useEditorEnabled must be used within a EnabledProvider");
45
- }
46
- return context;
47
- };
49
+ const useEditorEnabled = () => (0, import_react.useContext)(EditorEnabledContext);
48
50
  // Annotate the CommonJS export names for ESM import in node:
49
51
  0 && (module.exports = {
50
52
  EditorEnabledProvider,
51
53
  useEditorEnabled,
52
- useEditorEnabledState
54
+ useEditorEnabledState,
55
+ useGetEditorEnabledState,
56
+ usePostEditorEnabledState
53
57
  });
54
58
  //# sourceMappingURL=EditorEnabledContext.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/EditorEnabledContext.tsx"],"sourcesContent":["'use client';\n\nimport {\n createContext,\n useContext,\n type FC,\n type PropsWithChildren,\n} from 'react';\nimport {\n type CrossFrameStateOptions,\n useCrossFrameState,\n} from './useCrossFrameState';\n\nexport type EditorEnabledStateProps = {\n enabled: boolean;\n};\n\nconst EditorEnabledContext = createContext<EditorEnabledStateProps | undefined>(\n undefined\n);\n\nexport const useEditorEnabledState = (options?: CrossFrameStateOptions) =>\n useCrossFrameState('INTLAYER_EDITOR_ENABLED', false, options);\n\nexport const EditorEnabledProvider: FC<PropsWithChildren> = ({ children }) => {\n const [isEnabled] = useEditorEnabledState({\n emit: false,\n receive: true,\n });\n\n return (\n <EditorEnabledContext.Provider value={{ enabled: isEnabled }}>\n {children}\n </EditorEnabledContext.Provider>\n );\n};\n\nexport const useEditorEnabled = () => {\n const context = useContext(EditorEnabledContext);\n\n if (!context) {\n throw new Error('useEditorEnabled must be used within a EnabledProvider');\n }\n return context;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA+BI;AA7BJ,mBAKO;AACP,gCAGO;AAMP,MAAM,2BAAuB;AAAA,EAC3B;AACF;AAEO,MAAM,wBAAwB,CAAC,gBACpC,8CAAmB,2BAA2B,OAAO,OAAO;AAEvD,MAAM,wBAA+C,CAAC,EAAE,SAAS,MAAM;AAC5E,QAAM,CAAC,SAAS,IAAI,sBAAsB;AAAA,IACxC,MAAM;AAAA,IACN,SAAS;AAAA,EACX,CAAC;AAED,SACE,4CAAC,qBAAqB,UAArB,EAA8B,OAAO,EAAE,SAAS,UAAU,GACxD,UACH;AAEJ;AAEO,MAAM,mBAAmB,MAAM;AACpC,QAAM,cAAU,yBAAW,oBAAoB;AAE/C,MAAI,CAAC,SAAS;AACZ,UAAM,IAAI,MAAM,wDAAwD;AAAA,EAC1E;AACA,SAAO;AACT;","names":[]}
1
+ {"version":3,"sources":["../../src/EditorEnabledContext.tsx"],"sourcesContent":["'use client';\n\nimport {\n createContext,\n useContext,\n type FC,\n type PropsWithChildren,\n} from 'react';\nimport {\n type CrossFrameStateOptions,\n useCrossFrameState,\n} from './useCrossFrameState';\nimport { useCrossFrameMessageListener } from './useCrossFrameMessageListener';\n\nexport type EditorEnabledStateProps = {\n enabled: boolean;\n};\n\nconst EditorEnabledContext = createContext<EditorEnabledStateProps>({\n enabled: false,\n});\n\nexport const useEditorEnabledState = (options?: CrossFrameStateOptions) =>\n useCrossFrameState('INTLAYER_EDITOR_ENABLED', false, options);\n\nexport const usePostEditorEnabledState = <S,>(\n onEventTriggered?: (data: S) => void\n) =>\n useCrossFrameMessageListener(\n 'INTLAYER_EDITOR_ENABLED/post',\n onEventTriggered\n );\n\nexport const useGetEditorEnabledState = <S,>(\n onEventTriggered?: (data: S) => void\n) =>\n useCrossFrameMessageListener('INTLAYER_EDITOR_ENABLED/get', onEventTriggered);\n\nexport const EditorEnabledProvider: FC<PropsWithChildren> = ({ children }) => {\n const [isEnabled] = useEditorEnabledState({\n emit: false,\n receive: true,\n });\n\n return (\n <EditorEnabledContext.Provider value={{ enabled: isEnabled }}>\n {children}\n </EditorEnabledContext.Provider>\n );\n};\n\nexport const useEditorEnabled = () => useContext(EditorEnabledContext);\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA6CI;AA3CJ,mBAKO;AACP,gCAGO;AACP,0CAA6C;AAM7C,MAAM,2BAAuB,4BAAuC;AAAA,EAClE,SAAS;AACX,CAAC;AAEM,MAAM,wBAAwB,CAAC,gBACpC,8CAAmB,2BAA2B,OAAO,OAAO;AAEvD,MAAM,4BAA4B,CACvC,yBAEA;AAAA,EACE;AAAA,EACA;AACF;AAEK,MAAM,2BAA2B,CACtC,yBAEA,kEAA6B,+BAA+B,gBAAgB;AAEvE,MAAM,wBAA+C,CAAC,EAAE,SAAS,MAAM;AAC5E,QAAM,CAAC,SAAS,IAAI,sBAAsB;AAAA,IACxC,MAAM;AAAA,IACN,SAAS;AAAA,EACX,CAAC;AAED,SACE,4CAAC,qBAAqB,UAArB,EAA8B,OAAO,EAAE,SAAS,UAAU,GACxD,UACH;AAEJ;AAEO,MAAM,mBAAmB,UAAM,yBAAW,oBAAoB;","names":[]}
@@ -23,6 +23,7 @@ __export(EditorProvider_exports, {
23
23
  });
24
24
  module.exports = __toCommonJS(EditorProvider_exports);
25
25
  var import_jsx_runtime = require("react/jsx-runtime");
26
+ var import_react = require("react");
26
27
  var import_ChangedContentContext = require('./ChangedContentContext.cjs');
27
28
  var import_CommunicatorContext = require('./CommunicatorContext.cjs');
28
29
  var import_ConfigurationContext = require('./ConfigurationContext.cjs');
@@ -30,15 +31,40 @@ var import_DictionariesRecordContext = require('./DictionariesRecordContext.cjs'
30
31
  var import_EditedContentContext = require('./EditedContentContext.cjs');
31
32
  var import_EditorEnabledContext = require('./EditorEnabledContext.cjs');
32
33
  var import_FocusDictionaryContext = require('./FocusDictionaryContext.cjs');
33
- const EditorProviderEnabled = ({ mode, children, ...props }) => {
34
+ const EditorProvidersWrapper = ({ children }) => {
35
+ const getEditedContentState = (0, import_EditedContentContext.useGetEditedContentState)();
36
+ (0, import_react.useEffect)(() => {
37
+ getEditedContentState();
38
+ }, []);
39
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_DictionariesRecordContext.DictionariesRecordProvider, { children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_EditedContentContext.EditedContentProvider, { children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_FocusDictionaryContext.FocusDictionaryProvider, { children }) }) });
40
+ };
41
+ const EditorEnabledCheckRenderer = ({
42
+ children,
43
+ fallback
44
+ }) => {
45
+ const getEditorEnabled = (0, import_EditorEnabledContext.useGetEditorEnabledState)();
34
46
  const { enabled } = (0, import_EditorEnabledContext.useEditorEnabled)();
35
- return enabled || mode === "editor" ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_CommunicatorContext.CommunicatorProvider, { ...props, children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_DictionariesRecordContext.DictionariesRecordProvider, { children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_EditedContentContext.EditedContentProvider, { children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_FocusDictionaryContext.FocusDictionaryProvider, { children }) }) }) }) : children;
47
+ (0, import_react.useEffect)(() => {
48
+ if (enabled) return;
49
+ getEditorEnabled();
50
+ }, [enabled]);
51
+ return enabled ? children : fallback;
52
+ };
53
+ const IframeCheckRenderer = ({
54
+ children,
55
+ fallback
56
+ }) => {
57
+ const [isInIframe, setIsInIframe] = (0, import_react.useState)(false);
58
+ (0, import_react.useEffect)(() => {
59
+ setIsInIframe(window.self !== window.top);
60
+ }, []);
61
+ return isInIframe ? children : fallback;
36
62
  };
37
63
  const EditorProvider = ({
38
64
  children,
39
65
  configuration,
40
66
  ...props
41
- }) => /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ChangedContentContext.ChangedContentProvider, { children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_EditorEnabledContext.EditorEnabledProvider, { children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ConfigurationContext.ConfigurationProvider, { configuration, children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(EditorProviderEnabled, { ...props, children }) }) }) });
67
+ }) => /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ChangedContentContext.ChangedContentProvider, { children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_EditorEnabledContext.EditorEnabledProvider, { children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_ConfigurationContext.ConfigurationProvider, { configuration, children: props.mode === "editor" ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_CommunicatorContext.CommunicatorProvider, { ...props, children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(EditorProvidersWrapper, { children }) }) : /* @__PURE__ */ (0, import_jsx_runtime.jsx)(IframeCheckRenderer, { fallback: children, children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_CommunicatorContext.CommunicatorProvider, { ...props, children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(EditorEnabledCheckRenderer, { fallback: children, children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(EditorProvidersWrapper, { children }) }) }) }) }) }) });
42
68
  // Annotate the CommonJS export names for ESM import in node:
43
69
  0 && (module.exports = {
44
70
  EditorProvider
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/EditorProvider.tsx"],"sourcesContent":["'use client';\n\nimport { type FC, type PropsWithChildren } from 'react';\nimport { ChangedContentProvider } from './ChangedContentContext';\nimport {\n type CommunicatorProviderProps,\n CommunicatorProvider,\n} from './CommunicatorContext';\nimport {\n type ConfigurationProviderProps,\n ConfigurationProvider,\n} from './ConfigurationContext';\nimport { DictionariesRecordProvider } from './DictionariesRecordContext';\nimport { EditedContentProvider } from './EditedContentContext';\nimport {\n EditorEnabledProvider,\n useEditorEnabled,\n} from './EditorEnabledContext';\nimport { FocusDictionaryProvider } from './FocusDictionaryContext';\n\ntype EditorProviderEnabledProps = CommunicatorProviderProps & {\n mode: 'editor' | 'client';\n};\n\nconst EditorProviderEnabled: FC<\n PropsWithChildren<EditorProviderEnabledProps>\n> = ({ mode, children, ...props }) => {\n const { enabled } = useEditorEnabled();\n\n return enabled || mode === 'editor' ? (\n <CommunicatorProvider {...props}>\n <DictionariesRecordProvider>\n <EditedContentProvider>\n <FocusDictionaryProvider>{children}</FocusDictionaryProvider>\n </EditedContentProvider>\n </DictionariesRecordProvider>\n </CommunicatorProvider>\n ) : (\n children\n );\n};\n\nexport type EditorProviderProps = EditorProviderEnabledProps &\n ConfigurationProviderProps;\n\nexport const EditorProvider: FC<PropsWithChildren<EditorProviderProps>> = ({\n children,\n configuration,\n ...props\n}) => (\n <ChangedContentProvider>\n <EditorEnabledProvider>\n <ConfigurationProvider configuration={configuration}>\n <EditorProviderEnabled {...props}>{children}</EditorProviderEnabled>\n </ConfigurationProvider>\n </EditorEnabledProvider>\n </ChangedContentProvider>\n);\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAiCU;AA9BV,mCAAuC;AACvC,iCAGO;AACP,kCAGO;AACP,uCAA2C;AAC3C,kCAAsC;AACtC,kCAGO;AACP,oCAAwC;AAMxC,MAAM,wBAEF,CAAC,EAAE,MAAM,UAAU,GAAG,MAAM,MAAM;AACpC,QAAM,EAAE,QAAQ,QAAI,8CAAiB;AAErC,SAAO,WAAW,SAAS,WACzB,4CAAC,mDAAsB,GAAG,OACxB,sDAAC,+DACC,sDAAC,qDACC,sDAAC,yDAAyB,UAAS,GACrC,GACF,GACF,IAEA;AAEJ;AAKO,MAAM,iBAA6D,CAAC;AAAA,EACzE;AAAA,EACA;AAAA,EACA,GAAG;AACL,MACE,4CAAC,uDACC,sDAAC,qDACC,sDAAC,qDAAsB,eACrB,sDAAC,yBAAuB,GAAG,OAAQ,UAAS,GAC9C,GACF,GACF;","names":[]}
1
+ {"version":3,"sources":["../../src/EditorProvider.tsx"],"sourcesContent":["'use client';\n\nimport {\n ReactNode,\n useEffect,\n useState,\n type FC,\n type PropsWithChildren,\n} from 'react';\nimport { ChangedContentProvider } from './ChangedContentContext';\nimport {\n type CommunicatorProviderProps,\n CommunicatorProvider,\n} from './CommunicatorContext';\nimport {\n type ConfigurationProviderProps,\n ConfigurationProvider,\n} from './ConfigurationContext';\nimport { DictionariesRecordProvider } from './DictionariesRecordContext';\nimport {\n EditedContentProvider,\n useGetEditedContentState,\n} from './EditedContentContext';\nimport {\n EditorEnabledProvider,\n useEditorEnabled,\n useGetEditorEnabledState,\n} from './EditorEnabledContext';\nimport { FocusDictionaryProvider } from './FocusDictionaryContext';\n\n/**\n * This component add all the providers needed by the editor.\n * It is used to wrap the application, or the editor to work together.\n */\nconst EditorProvidersWrapper: FC<PropsWithChildren> = ({ children }) => {\n const getEditedContentState = useGetEditedContentState();\n\n useEffect(() => {\n getEditedContentState();\n }, []);\n\n return (\n <DictionariesRecordProvider>\n <EditedContentProvider>\n <FocusDictionaryProvider>{children}</FocusDictionaryProvider>\n </EditedContentProvider>\n </DictionariesRecordProvider>\n );\n};\n\ntype FallbackProps = {\n fallback: ReactNode;\n};\n\n/**\n * This component check if the editor is enabled to render the editor providers.\n */\nconst EditorEnabledCheckRenderer: FC<PropsWithChildren<FallbackProps>> = ({\n children,\n fallback,\n}) => {\n const getEditorEnabled = useGetEditorEnabledState();\n\n const { enabled } = useEditorEnabled();\n\n useEffect(() => {\n if (enabled) return;\n\n // Check if the editor is wrapping the application\n getEditorEnabled();\n }, [enabled]);\n\n return enabled ? children : fallback;\n};\n\n/**\n * This component is used to check if the editor is wrapping the application.\n * It avoid to send window.postMessage to the application if the editor is not wrapping the application.\n */\nconst IframeCheckRenderer: FC<PropsWithChildren<FallbackProps>> = ({\n children,\n fallback,\n}) => {\n const [isInIframe, setIsInIframe] = useState(false);\n\n useEffect(() => {\n setIsInIframe(window.self !== window.top);\n }, []);\n\n return isInIframe ? children : fallback;\n};\n\nexport type EditorProviderProps = CommunicatorProviderProps &\n ConfigurationProviderProps & {\n mode: 'editor' | 'client';\n };\n\nexport const EditorProvider: FC<PropsWithChildren<EditorProviderProps>> = ({\n children,\n configuration,\n ...props\n}) => (\n <ChangedContentProvider>\n <EditorEnabledProvider>\n <ConfigurationProvider configuration={configuration}>\n {props.mode === 'editor' ? (\n <CommunicatorProvider {...props}>\n <EditorProvidersWrapper>{children}</EditorProvidersWrapper>\n </CommunicatorProvider>\n ) : (\n <IframeCheckRenderer fallback={children}>\n <CommunicatorProvider {...props}>\n <EditorEnabledCheckRenderer fallback={children}>\n <EditorProvidersWrapper>{children}</EditorProvidersWrapper>\n </EditorEnabledCheckRenderer>\n </CommunicatorProvider>\n </IframeCheckRenderer>\n )}\n </ConfigurationProvider>\n </EditorEnabledProvider>\n </ChangedContentProvider>\n);\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AA4CQ;AA1CR,mBAMO;AACP,mCAAuC;AACvC,iCAGO;AACP,kCAGO;AACP,uCAA2C;AAC3C,kCAGO;AACP,kCAIO;AACP,oCAAwC;AAMxC,MAAM,yBAAgD,CAAC,EAAE,SAAS,MAAM;AACtE,QAAM,4BAAwB,sDAAyB;AAEvD,8BAAU,MAAM;AACd,0BAAsB;AAAA,EACxB,GAAG,CAAC,CAAC;AAEL,SACE,4CAAC,+DACC,sDAAC,qDACC,sDAAC,yDAAyB,UAAS,GACrC,GACF;AAEJ;AASA,MAAM,6BAAmE,CAAC;AAAA,EACxE;AAAA,EACA;AACF,MAAM;AACJ,QAAM,uBAAmB,sDAAyB;AAElD,QAAM,EAAE,QAAQ,QAAI,8CAAiB;AAErC,8BAAU,MAAM;AACd,QAAI,QAAS;AAGb,qBAAiB;AAAA,EACnB,GAAG,CAAC,OAAO,CAAC;AAEZ,SAAO,UAAU,WAAW;AAC9B;AAMA,MAAM,sBAA4D,CAAC;AAAA,EACjE;AAAA,EACA;AACF,MAAM;AACJ,QAAM,CAAC,YAAY,aAAa,QAAI,uBAAS,KAAK;AAElD,8BAAU,MAAM;AACd,kBAAc,OAAO,SAAS,OAAO,GAAG;AAAA,EAC1C,GAAG,CAAC,CAAC;AAEL,SAAO,aAAa,WAAW;AACjC;AAOO,MAAM,iBAA6D,CAAC;AAAA,EACzE;AAAA,EACA;AAAA,EACA,GAAG;AACL,MACE,4CAAC,uDACC,sDAAC,qDACC,sDAAC,qDAAsB,eACpB,gBAAM,SAAS,WACd,4CAAC,mDAAsB,GAAG,OACxB,sDAAC,0BAAwB,UAAS,GACpC,IAEA,4CAAC,uBAAoB,UAAU,UAC7B,sDAAC,mDAAsB,GAAG,OACxB,sDAAC,8BAA2B,UAAU,UACpC,sDAAC,0BAAwB,UAAS,GACpC,GACF,GACF,GAEJ,GACF,GACF;","names":[]}
@@ -42,7 +42,7 @@ const compareUrls = (url1, url2) => {
42
42
  return false;
43
43
  }
44
44
  };
45
- const useCrossFrameMessageListener = (key, onEventTriggered) => {
45
+ const useCrossFrameMessageListener = (key, onEventTriggered, revalidator) => {
46
46
  const { allowedOrigins, postMessage, senderId } = (0, import_CommunicatorContext.useCommunicator)();
47
47
  (0, import_react.useEffect)(() => {
48
48
  if (onEventTriggered) {
@@ -57,14 +57,11 @@ const useCrossFrameMessageListener = (key, onEventTriggered) => {
57
57
  window.addEventListener("message", handleMessage);
58
58
  return () => window.removeEventListener("message", handleMessage);
59
59
  }
60
- }, [allowedOrigins, postMessage, senderId]);
61
- const postMessageWrapper = (0, import_react.useCallback)(
62
- (data) => {
63
- postMessage({ type: key, data, senderId });
64
- },
65
- [postMessage, key, senderId]
66
- );
67
- return (0, import_react.useMemo)(() => postMessageWrapper, [postMessageWrapper]);
60
+ }, [allowedOrigins, postMessage, senderId, revalidator]);
61
+ const postMessageWrapper = (data) => {
62
+ postMessage({ type: key, data, senderId });
63
+ };
64
+ return postMessageWrapper;
68
65
  };
69
66
  // Annotate the CommonJS export names for ESM import in node:
70
67
  0 && (module.exports = {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/useCrossFrameMessageListener.tsx"],"sourcesContent":["'use client';\n\nimport { useCallback, useEffect, useMemo } from 'react';\nimport { useCommunicator } from './CommunicatorContext';\nimport { type MessageKey } from './messageKey';\n\n/**\n * Compare two URLs for equality.\n * This function is used to determine if a message originates from the same origin.\n *\n * ```js\n * // Example usage\n * console.log(compareUrls(\"http://localhost:5173/\", \"http://localhost:5173\")); // true\n * console.log(compareUrls(\"http://localhost:5173\", \"http://localhost:5173?myParam=true\")); // true\n * console.log(compareUrls(\"http://localhost:5173/subpath\", \"http://localhost:5173\")); // true\n * console.log(compareUrls(\"http://localhost:5172\", \"http://localhost:5173\")); // false\n * ```\n *\n * @param url1 - The first URL to compare.\n * @param url2 - The second URL to compare.\n * @returns Whether the two URLs are equal.\n */\nconst compareUrls = (url1: string, url2: string): boolean => {\n try {\n const parsedUrl1 = new URL(url1);\n const parsedUrl2 = new URL(url2);\n\n // Compare protocol, hostname, and port\n if (\n parsedUrl1.protocol !== parsedUrl2.protocol ||\n parsedUrl1.hostname !== parsedUrl2.hostname ||\n parsedUrl1.port !== parsedUrl2.port\n ) {\n return false;\n }\n\n // One URL should not have a subpath while the other does\n const path1 = parsedUrl1.pathname.replace(/\\/$/, ''); // Remove trailing slash\n const path2 = parsedUrl2.pathname.replace(/\\/$/, '');\n\n if (path1 !== '' && path2 !== '' && path1 !== path2) {\n return false;\n }\n\n return true;\n } catch (error) {\n console.error('Invalid URL(s)', error);\n return false;\n }\n};\n\n/**\n * useCrossFrameMessageListener\n *\n * This React hook listens for messages sent via the `postMessage` API and triggers a callback\n * whenever a message of the specified type (`key`) is received. It is useful for synchronizing\n * state or events across different windows, iframes, or contexts.\n *\n * @template S - The type of the data payload in the message.\n * @param {`${MessageKey}` | `${MessageKey}/post` | `${MessageKey}/get`} key - A unique identifier for the message type to listen for.\n * @param {(data: S) => void} [onEventTriggered] - A callback function triggered when a message\n * with the specified key is received. The callback receives the message data as its argument.\n *\n * @returns {{ postMessage: (data: S) => void }} An object containing a `postMessage` function\n * that allows broadcasting messages with the specified key and data.\n */\nexport const useCrossFrameMessageListener = <S,>(\n key: `${MessageKey}` | `${MessageKey}/post` | `${MessageKey}/get`,\n onEventTriggered?: (data: S) => void\n) => {\n const { allowedOrigins, postMessage, senderId } = useCommunicator();\n\n useEffect(() => {\n if (onEventTriggered) {\n /**\n * Message handler to process incoming messages.\n *\n * - **Message Filtering:** Ensures only messages with the specified `key` are processed.\n * - **Origin Validation:** Checks that the origin of the message is within the allowed origins.\n *\n * @param {MessageEvent<{ type: string; data: S }>} event - The incoming message event object.\n */\n const handleMessage = (\n event: MessageEvent<{ type: string; data: S; senderId: string }>\n ) => {\n const { type, data, senderId: msgSenderId } = event.data;\n\n // Ignore messages that do not match the current key\n if (type !== key) return;\n\n // Ignore messages from myself\n if (msgSenderId === senderId) return;\n\n // Check if the message origin is allowed\n if (\n typeof allowedOrigins === 'undefined' ||\n allowedOrigins?.some((url) => compareUrls(url, event.origin)) ||\n allowedOrigins?.includes('*')\n ) {\n // Update the local state with the received data\n onEventTriggered(data);\n }\n };\n\n window.addEventListener('message', handleMessage);\n\n // Clean up the event listener on unmount\n return () => window.removeEventListener('message', handleMessage);\n }\n }, [allowedOrigins, postMessage, senderId]);\n\n /**\n * A wrapper function around the `postMessage` function to broadcast messages efficiently.\n *\n * - **Encapsulation:** Ensures the `postMessage` function is scoped to the provided key.\n * - **Ease of Use:** Simplifies broadcasting messages with consistent type and format.\n *\n * @param {S} data - The data payload to include in the message.\n * @returns {void}\n */\n const postMessageWrapper: (data: S) => void = useCallback(\n (data) => {\n postMessage({ type: key, data, senderId });\n },\n [postMessage, key, senderId]\n );\n\n return useMemo(() => postMessageWrapper, [postMessageWrapper]);\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAEA,mBAAgD;AAChD,iCAAgC;AAmBhC,MAAM,cAAc,CAAC,MAAc,SAA0B;AAC3D,MAAI;AACF,UAAM,aAAa,IAAI,IAAI,IAAI;AAC/B,UAAM,aAAa,IAAI,IAAI,IAAI;AAG/B,QACE,WAAW,aAAa,WAAW,YACnC,WAAW,aAAa,WAAW,YACnC,WAAW,SAAS,WAAW,MAC/B;AACA,aAAO;AAAA,IACT;AAGA,UAAM,QAAQ,WAAW,SAAS,QAAQ,OAAO,EAAE;AACnD,UAAM,QAAQ,WAAW,SAAS,QAAQ,OAAO,EAAE;AAEnD,QAAI,UAAU,MAAM,UAAU,MAAM,UAAU,OAAO;AACnD,aAAO;AAAA,IACT;AAEA,WAAO;AAAA,EACT,SAAS,OAAO;AACd,YAAQ,MAAM,kBAAkB,KAAK;AACrC,WAAO;AAAA,EACT;AACF;AAiBO,MAAM,+BAA+B,CAC1C,KACA,qBACG;AACH,QAAM,EAAE,gBAAgB,aAAa,SAAS,QAAI,4CAAgB;AAElE,8BAAU,MAAM;AACd,QAAI,kBAAkB;AASpB,YAAM,gBAAgB,CACpB,UACG;AACH,cAAM,EAAE,MAAM,MAAM,UAAU,YAAY,IAAI,MAAM;AAGpD,YAAI,SAAS,IAAK;AAGlB,YAAI,gBAAgB,SAAU;AAG9B,YACE,OAAO,mBAAmB,eAC1B,gBAAgB,KAAK,CAAC,QAAQ,YAAY,KAAK,MAAM,MAAM,CAAC,KAC5D,gBAAgB,SAAS,GAAG,GAC5B;AAEA,2BAAiB,IAAI;AAAA,QACvB;AAAA,MACF;AAEA,aAAO,iBAAiB,WAAW,aAAa;AAGhD,aAAO,MAAM,OAAO,oBAAoB,WAAW,aAAa;AAAA,IAClE;AAAA,EACF,GAAG,CAAC,gBAAgB,aAAa,QAAQ,CAAC;AAW1C,QAAM,yBAAwC;AAAA,IAC5C,CAAC,SAAS;AACR,kBAAY,EAAE,MAAM,KAAK,MAAM,SAAS,CAAC;AAAA,IAC3C;AAAA,IACA,CAAC,aAAa,KAAK,QAAQ;AAAA,EAC7B;AAEA,aAAO,sBAAQ,MAAM,oBAAoB,CAAC,kBAAkB,CAAC;AAC/D;","names":[]}
1
+ {"version":3,"sources":["../../src/useCrossFrameMessageListener.tsx"],"sourcesContent":["'use client';\n\nimport { useEffect } from 'react';\nimport { useCommunicator } from './CommunicatorContext';\nimport { type MessageKey } from './messageKey';\n\n/**\n * Compare two URLs for equality.\n * This function is used to determine if a message originates from the same origin.\n *\n * ```js\n * // Example usage\n * console.log(compareUrls(\"http://localhost:5173/\", \"http://localhost:5173\")); // true\n * console.log(compareUrls(\"http://localhost:5173\", \"http://localhost:5173?myParam=true\")); // true\n * console.log(compareUrls(\"http://localhost:5173/subpath\", \"http://localhost:5173\")); // true\n * console.log(compareUrls(\"http://localhost:5172\", \"http://localhost:5173\")); // false\n * ```\n *\n * @param url1 - The first URL to compare.\n * @param url2 - The second URL to compare.\n * @returns Whether the two URLs are equal.\n */\nconst compareUrls = (url1: string, url2: string): boolean => {\n try {\n const parsedUrl1 = new URL(url1);\n const parsedUrl2 = new URL(url2);\n\n // Compare protocol, hostname, and port\n if (\n parsedUrl1.protocol !== parsedUrl2.protocol ||\n parsedUrl1.hostname !== parsedUrl2.hostname ||\n parsedUrl1.port !== parsedUrl2.port\n ) {\n return false;\n }\n\n // One URL should not have a subpath while the other does\n const path1 = parsedUrl1.pathname.replace(/\\/$/, ''); // Remove trailing slash\n const path2 = parsedUrl2.pathname.replace(/\\/$/, '');\n\n if (path1 !== '' && path2 !== '' && path1 !== path2) {\n return false;\n }\n\n return true;\n } catch (error) {\n console.error('Invalid URL(s)', error);\n return false;\n }\n};\n\n/**\n * useCrossFrameMessageListener\n *\n * This React hook listens for messages sent via the `postMessage` API and triggers a callback\n * whenever a message of the specified type (`key`) is received. It is useful for synchronizing\n * state or events across different windows, iframes, or contexts.\n *\n * @template S - The type of the data payload in the message.\n * @param key - A unique identifier for the message type to listen for.\n * @param [onEventTriggered] - A callback function triggered when a message\n * @param [revalidator] - A function that re-suscribes the listener. Could be usefull if onEventTriggered depend of some state\n * with the specified key is received. The callback receives the message data as its argument.\n *\n * @returns {{ postMessage: (data: S) => void }} An object containing a `postMessage` function\n * that allows broadcasting messages with the specified key and data.\n */\nexport const useCrossFrameMessageListener = <S,>(\n key: `${MessageKey}` | `${MessageKey}/post` | `${MessageKey}/get`,\n onEventTriggered?: (data: S) => void,\n revalidator?: any\n) => {\n const { allowedOrigins, postMessage, senderId } = useCommunicator();\n\n useEffect(() => {\n if (onEventTriggered) {\n /**\n * Message handler to process incoming messages.\n *\n * - **Message Filtering:** Ensures only messages with the specified `key` are processed.\n * - **Origin Validation:** Checks that the origin of the message is within the allowed origins.\n *\n * @param {MessageEvent<{ type: string; data: S }>} event - The incoming message event object.\n */\n const handleMessage = (\n event: MessageEvent<{ type: string; data: S; senderId: string }>\n ) => {\n const { type, data, senderId: msgSenderId } = event.data;\n\n // Ignore messages that do not match the current key\n if (type !== key) return;\n\n // Ignore messages from myself\n if (msgSenderId === senderId) return;\n\n // Check if the message origin is allowed\n if (\n typeof allowedOrigins === 'undefined' ||\n allowedOrigins?.some((url) => compareUrls(url, event.origin)) ||\n allowedOrigins?.includes('*')\n ) {\n // Update the local state with the received data\n onEventTriggered(data);\n }\n };\n\n window.addEventListener('message', handleMessage);\n\n // Clean up the event listener on unmount\n return () => window.removeEventListener('message', handleMessage);\n }\n }, [allowedOrigins, postMessage, senderId, revalidator]);\n\n /**\n * A wrapper function around the `postMessage` function to broadcast messages efficiently.\n *\n * - **Encapsulation:** Ensures the `postMessage` function is scoped to the provided key.\n * - **Ease of Use:** Simplifies broadcasting messages with consistent type and format.\n *\n * @param {S} data - The data payload to include in the message.\n * @returns {void}\n */\n const postMessageWrapper: (data?: S) => void = (data) => {\n postMessage({ type: key, data, senderId });\n };\n\n return postMessageWrapper;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAEA,mBAA0B;AAC1B,iCAAgC;AAmBhC,MAAM,cAAc,CAAC,MAAc,SAA0B;AAC3D,MAAI;AACF,UAAM,aAAa,IAAI,IAAI,IAAI;AAC/B,UAAM,aAAa,IAAI,IAAI,IAAI;AAG/B,QACE,WAAW,aAAa,WAAW,YACnC,WAAW,aAAa,WAAW,YACnC,WAAW,SAAS,WAAW,MAC/B;AACA,aAAO;AAAA,IACT;AAGA,UAAM,QAAQ,WAAW,SAAS,QAAQ,OAAO,EAAE;AACnD,UAAM,QAAQ,WAAW,SAAS,QAAQ,OAAO,EAAE;AAEnD,QAAI,UAAU,MAAM,UAAU,MAAM,UAAU,OAAO;AACnD,aAAO;AAAA,IACT;AAEA,WAAO;AAAA,EACT,SAAS,OAAO;AACd,YAAQ,MAAM,kBAAkB,KAAK;AACrC,WAAO;AAAA,EACT;AACF;AAkBO,MAAM,+BAA+B,CAC1C,KACA,kBACA,gBACG;AACH,QAAM,EAAE,gBAAgB,aAAa,SAAS,QAAI,4CAAgB;AAElE,8BAAU,MAAM;AACd,QAAI,kBAAkB;AASpB,YAAM,gBAAgB,CACpB,UACG;AACH,cAAM,EAAE,MAAM,MAAM,UAAU,YAAY,IAAI,MAAM;AAGpD,YAAI,SAAS,IAAK;AAGlB,YAAI,gBAAgB,SAAU;AAG9B,YACE,OAAO,mBAAmB,eAC1B,gBAAgB,KAAK,CAAC,QAAQ,YAAY,KAAK,MAAM,MAAM,CAAC,KAC5D,gBAAgB,SAAS,GAAG,GAC5B;AAEA,2BAAiB,IAAI;AAAA,QACvB;AAAA,MACF;AAEA,aAAO,iBAAiB,WAAW,aAAa;AAGhD,aAAO,MAAM,OAAO,oBAAoB,WAAW,aAAa;AAAA,IAClE;AAAA,EACF,GAAG,CAAC,gBAAgB,aAAa,UAAU,WAAW,CAAC;AAWvD,QAAM,qBAAyC,CAAC,SAAS;AACvD,gBAAY,EAAE,MAAM,KAAK,MAAM,SAAS,CAAC;AAAA,EAC3C;AAEA,SAAO;AACT;","names":[]}
@@ -28,50 +28,47 @@ var import_useCrossFrameMessageListener = require('./useCrossFrameMessageListene
28
28
  const resolveState = (state, prevState) => typeof state === "function" ? state(prevState) : state;
29
29
  const useCrossFrameState = (key, initialState, options) => {
30
30
  const { postMessage, senderId } = (0, import_CommunicatorContext.useCommunicator)();
31
- const { emit, receive } = (0, import_react.useMemo)(
32
- () => options ?? { emit: true, receive: true },
33
- [options]
34
- );
35
- const handleStateChange = (0, import_react.useCallback)(
36
- (state2, prevState) => {
37
- const resolvedState = resolveState(state2, prevState);
38
- if (emit && typeof postMessage === "function" && typeof resolvedState !== "undefined" && JSON.stringify(resolvedState) !== JSON.stringify(prevState)) {
39
- postMessage({ type: `${key}/post`, data: resolvedState, senderId });
40
- }
41
- return resolvedState;
42
- },
43
- [key, postMessage, senderId]
44
- );
31
+ const { emit, receive } = options ?? { emit: true, receive: true };
32
+ const handleStateChange = (state2, prevState) => {
33
+ const resolvedState = resolveState(state2, prevState);
34
+ if (emit && typeof postMessage === "function" && typeof resolvedState !== "undefined") {
35
+ postMessage({ type: `${key}/post`, data: resolvedState, senderId });
36
+ }
37
+ return resolvedState;
38
+ };
39
+ const postState = () => {
40
+ if (typeof postMessage !== "function") return;
41
+ postMessage({ type: `${key}/post`, data: state, senderId });
42
+ };
45
43
  const [state, setState] = (0, import_react.useState)(() => handleStateChange(initialState));
46
- const setStateWrapper = (0, import_react.useCallback)(
47
- (valueOrUpdater) => setState((prevState) => handleStateChange(valueOrUpdater, prevState)),
48
- [handleStateChange]
49
- );
44
+ const setStateWrapper = (valueOrUpdater) => setState((prevState) => handleStateChange(valueOrUpdater, prevState));
50
45
  (0, import_useCrossFrameMessageListener.useCrossFrameMessageListener)(
51
46
  `${key}/post`,
52
47
  // Only activate the state listener if the `receive` option is true
53
- receive ? setState : void 0
54
- );
55
- const onGetMessage = (0, import_react.useCallback)(
56
- (_, originSenderId) => {
57
- if (!emit || typeof postMessage !== "function") return;
58
- if (originSenderId === senderId) return;
59
- if (typeof state === "undefined") return;
60
- postMessage({ type: `${key}/post`, data: state, senderId });
61
- },
62
- [emit, key, postMessage, senderId, state]
48
+ receive ? (data) => {
49
+ setState(data);
50
+ } : void 0
63
51
  );
52
+ const onGetMessage = (_, originSenderId) => {
53
+ if (!emit) return;
54
+ if (typeof postMessage !== "function") return;
55
+ if (originSenderId === senderId) return;
56
+ if (typeof state === "undefined") return;
57
+ postMessage({ type: `${key}/post`, data: state, senderId });
58
+ };
64
59
  (0, import_useCrossFrameMessageListener.useCrossFrameMessageListener)(
65
60
  `${key}/get`,
66
61
  // Only activate the state listener if the `emit` option is true
67
- emit ? onGetMessage : void 0
62
+ emit ? onGetMessage : void 0,
63
+ state
64
+ // Revalidate the listener if the state changes
68
65
  );
69
66
  (0, import_react.useEffect)(() => {
70
- if (receive && typeof postMessage === "function") {
67
+ if (receive && typeof postMessage === "function" && typeof state === "undefined") {
71
68
  postMessage({ type: `${key}/get`, senderId });
72
69
  }
73
70
  }, []);
74
- return (0, import_react.useMemo)(() => [state, setStateWrapper], [state, setStateWrapper]);
71
+ return [state, setStateWrapper, postState];
75
72
  };
76
73
  // Annotate the CommonJS export names for ESM import in node:
77
74
  0 && (module.exports = {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/useCrossFrameState.tsx"],"sourcesContent":["'use client';\n\nimport {\n useCallback,\n useEffect,\n useMemo,\n useState,\n type Dispatch,\n type SetStateAction,\n} from 'react';\nimport { useCommunicator } from './CommunicatorContext';\nimport { type MessageKey } from './messageKey';\nimport { useCrossFrameMessageListener } from './useCrossFrameMessageListener';\n\nexport type CrossFrameStateOptions = {\n emit?: boolean;\n receive?: boolean;\n};\n\nconst resolveState = <S,>(state?: SetStateAction<S>, prevState?: S): S =>\n typeof state === 'function'\n ? (state as (prevState?: S) => S)(prevState)\n : (state as S);\n\n/**\n * Configuration options for `useCrossFrameState`.\n * @typedef {Object} CrossFrameStateOptions\n * @property {boolean} [emit=true] - Whether to broadcast state changes to other instances.\n * @property {boolean} [receive=true] - Whether to listen for state updates from other instances.\n */\n\n/**\n * useCrossFrameState\n *\n * This React hook synchronizes state across multiple instances (e.g., different iframes or windows).\n * It uses the `postMessage` API to communicate state changes and updates between instances.\n *\n * @template S - The type of the state.\n * @param {`${MessageKey}`} key - A unique identifier for the state to synchronize.\n * @param {S | (() => S)} [initialState] - The initial state value or a function to compute it lazily.\n * @param {CrossFrameStateOptions} [options] - Configuration options to control emitting and receiving messages.\n * - `emit` (default: true): Whether to broadcast state changes to other instances.\n * - `receive` (default: true): Whether to listen for state updates from other instances.\n *\n * @returns {[S, Dispatch<SetStateAction<S>>]} An array containing the current state and a setter function.\n */\nexport const useCrossFrameState = <S,>(\n key: `${MessageKey}`,\n initialState?: S | (() => S),\n options?: CrossFrameStateOptions\n): [S, Dispatch<SetStateAction<S>>] => {\n const { postMessage, senderId } = useCommunicator();\n\n const { emit, receive } = useMemo(\n () => options ?? { emit: true, receive: true },\n [options]\n );\n\n const handleStateChange = useCallback(\n (state?: SetStateAction<S>, prevState?: S) => {\n // Initialize state from the provided initial value, if defined\n const resolvedState: S = resolveState(state, prevState);\n\n // Emit the initial state if `emit` is enabled and initial state is defined\n if (\n emit &&\n typeof postMessage === 'function' &&\n typeof resolvedState !== 'undefined' &&\n JSON.stringify(resolvedState) !== JSON.stringify(prevState)\n ) {\n postMessage({ type: `${key}/post`, data: resolvedState, senderId });\n }\n\n return resolvedState;\n },\n [key, postMessage, senderId]\n );\n\n const [state, setState] = useState<S>(() => handleStateChange(initialState));\n\n /**\n * A wrapper function around the `setState` function to handle messaging efficiently.\n *\n * This approach has several advantages over using an additional `useEffect`:\n * - **Avoid Redundant Re-renders:** By emitting the message directly within the `setState` logic,\n * it prevents the extra render cycle that would be triggered when using `useEffect`.\n * - **Consistency:** Ensures the message is emitted immediately when the state is updated,\n * avoiding potential delays caused by the asynchronous nature of `useEffect`.\n *\n * This function keeps the same API as `setState` and is memoized using `useCallback`\n * to prevent unnecessary re-renders of dependent components.\n *\n * @template S - The type of the state.\n * @param {SetStateAction<S>} valueOrUpdater - The new state or a function to produce it.\n * @returns {void}\n */\n const setStateWrapper: Dispatch<SetStateAction<S>> = useCallback(\n (valueOrUpdater) =>\n setState((prevState) => handleStateChange(valueOrUpdater, prevState)),\n [handleStateChange]\n );\n\n /**\n * Listen for messages with the specified key and update the state accordingly.\n */\n useCrossFrameMessageListener<S>(\n `${key}/post`,\n // Only activate the state listener if the `receive` option is true\n receive ? setState : undefined\n );\n\n const onGetMessage = useCallback(\n (_: unknown, originSenderId?: string) => {\n if (!emit || typeof postMessage !== 'function') return;\n if (originSenderId === senderId) return;\n if (typeof state === 'undefined') return;\n\n postMessage({ type: `${key}/post`, data: state, senderId });\n },\n [emit, key, postMessage, senderId, state]\n );\n\n /**\n * Listen for messages request to get the state content and send it back.\n */\n useCrossFrameMessageListener<S>(\n `${key}/get`,\n // Only activate the state listener if the `emit` option is true\n emit ? onGetMessage : undefined\n );\n\n useEffect(() => {\n // If the component is mounted and the hook in receive mode,\n // Request the state from the other instance\n if (receive && typeof postMessage === 'function') {\n postMessage({ type: `${key}/get`, senderId });\n }\n }, []);\n\n // Return the useState state and setter\n return useMemo(() => [state, setStateWrapper], [state, setStateWrapper]);\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAEA,mBAOO;AACP,iCAAgC;AAEhC,0CAA6C;AAO7C,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;AAAA;AAAA,IAEN,OAAO,eAAe;AAAA,EACxB;AAEA,8BAAU,MAAM;AAGd,QAAI,WAAW,OAAO,gBAAgB,YAAY;AAChD,kBAAY,EAAE,MAAM,GAAG,GAAG,QAAQ,SAAS,CAAC;AAAA,IAC9C;AAAA,EACF,GAAG,CAAC,CAAC;AAGL,aAAO,sBAAQ,MAAM,CAAC,OAAO,eAAe,GAAG,CAAC,OAAO,eAAe,CAAC;AACzE;","names":["state"]}
1
+ {"version":3,"sources":["../../src/useCrossFrameState.tsx"],"sourcesContent":["'use client';\n\nimport { useEffect, useState, type Dispatch, type SetStateAction } from 'react';\nimport { useCommunicator } from './CommunicatorContext';\nimport { type MessageKey } from './messageKey';\nimport { useCrossFrameMessageListener } from './useCrossFrameMessageListener';\n\nexport type CrossFrameStateOptions = {\n emit?: boolean;\n receive?: boolean;\n};\n\nconst resolveState = <S,>(state?: SetStateAction<S>, prevState?: S): S =>\n typeof state === 'function'\n ? (state as (prevState?: S) => S)(prevState)\n : (state as S);\n\n/**\n * Configuration options for `useCrossFrameState`.\n * @typedef {Object} CrossFrameStateOptions\n * @property {boolean} [emit=true] - Whether to broadcast state changes to other instances.\n * @property {boolean} [receive=true] - Whether to listen for state updates from other instances.\n */\n\n/**\n * useCrossFrameState\n *\n * This React hook synchronizes state across multiple instances (e.g., different iframes or windows).\n * It uses the `postMessage` API to communicate state changes and updates between instances.\n *\n * @template S - The type of the state.\n * @param {`${MessageKey}`} key - A unique identifier for the state to synchronize.\n * @param {S | (() => S)} [initialState] - The initial state value or a function to compute it lazily.\n * @param {CrossFrameStateOptions} [options] - Configuration options to control emitting and receiving messages.\n * - `emit` (default: true): Whether to broadcast state changes to other instances.\n * - `receive` (default: true): Whether to listen for state updates from other instances.\n *\n * @returns {[S, Dispatch<SetStateAction<S>>]} An array containing the current state and a setter function.\n */\nexport const useCrossFrameState = <S,>(\n key: `${MessageKey}`,\n initialState?: S | (() => S),\n options?: CrossFrameStateOptions\n): [S, Dispatch<SetStateAction<S>>, typeof postState] => {\n const { postMessage, senderId } = useCommunicator();\n\n const { emit, receive } = options ?? { emit: true, receive: true };\n\n const handleStateChange = (state?: SetStateAction<S>, prevState?: S) => {\n // Initialize state from the provided initial value, if defined\n const resolvedState: S = resolveState(state, prevState);\n\n // Emit the initial state if `emit` is enabled and initial state is defined\n if (\n emit &&\n typeof postMessage === 'function' &&\n typeof resolvedState !== 'undefined'\n ) {\n postMessage({ type: `${key}/post`, data: resolvedState, senderId });\n }\n\n return resolvedState;\n };\n\n const postState = () => {\n if (typeof postMessage !== 'function') return;\n postMessage({ type: `${key}/post`, data: state, senderId });\n };\n\n const [state, setState] = useState<S>(() => handleStateChange(initialState));\n\n /**\n * A wrapper function around the `setState` function to handle messaging efficiently.\n *\n * This approach has several advantages over using an additional `useEffect`:\n * - **Avoid Redundant Re-renders:** By emitting the message directly within the `setState` logic,\n * it prevents the extra render cycle that would be triggered when using `useEffect`.\n * - **Consistency:** Ensures the message is emitted immediately when the state is updated,\n * avoiding potential delays caused by the asynchronous nature of `useEffect`.\n *\n * This function keeps the same API as `setState` and is memoized using `useCallback`\n * to prevent unnecessary re-renders of dependent components.\n *\n * @template S - The type of the state.\n * @param {SetStateAction<S>} valueOrUpdater - The new state or a function to produce it.\n * @returns {void}\n */\n const setStateWrapper: Dispatch<SetStateAction<S>> = (valueOrUpdater) =>\n setState((prevState) => handleStateChange(valueOrUpdater, prevState));\n\n /**\n * Listen for messages with the specified key and update the state accordingly.\n */\n useCrossFrameMessageListener<S>(\n `${key}/post`,\n // Only activate the state listener if the `receive` option is true\n receive\n ? (data) => {\n setState(data);\n }\n : undefined\n );\n\n const onGetMessage = (_: unknown, originSenderId?: string) => {\n if (!emit) return;\n if (typeof postMessage !== 'function') return;\n if (originSenderId === senderId) return;\n if (typeof state === 'undefined') return;\n\n postMessage({ type: `${key}/post`, data: state, senderId });\n };\n\n /**\n * Listen for messages request to get the state content and send it back.\n */\n useCrossFrameMessageListener<S>(\n `${key}/get`,\n // Only activate the state listener if the `emit` option is true\n emit ? onGetMessage : undefined,\n state // Revalidate the listener if the state changes\n );\n\n useEffect(() => {\n // If the component is mounted and the hook in receive mode,\n // Request the state from the other instance\n if (\n receive &&\n typeof postMessage === 'function' &&\n typeof state === 'undefined'\n ) {\n postMessage({ type: `${key}/get`, senderId });\n }\n }, []);\n\n // Return the useState state and setter\n return [state, setStateWrapper, postState];\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAEA,mBAAwE;AACxE,iCAAgC;AAEhC,0CAA6C;AAO7C,MAAM,eAAe,CAAK,OAA2B,cACnD,OAAO,UAAU,aACZ,MAA+B,SAAS,IACxC;AAwBA,MAAM,qBAAqB,CAChC,KACA,cACA,YACuD;AACvD,QAAM,EAAE,aAAa,SAAS,QAAI,4CAAgB;AAElD,QAAM,EAAE,MAAM,QAAQ,IAAI,WAAW,EAAE,MAAM,MAAM,SAAS,KAAK;AAEjE,QAAM,oBAAoB,CAACA,QAA2B,cAAkB;AAEtE,UAAM,gBAAmB,aAAaA,QAAO,SAAS;AAGtD,QACE,QACA,OAAO,gBAAgB,cACvB,OAAO,kBAAkB,aACzB;AACA,kBAAY,EAAE,MAAM,GAAG,GAAG,SAAS,MAAM,eAAe,SAAS,CAAC;AAAA,IACpE;AAEA,WAAO;AAAA,EACT;AAEA,QAAM,YAAY,MAAM;AACtB,QAAI,OAAO,gBAAgB,WAAY;AACvC,gBAAY,EAAE,MAAM,GAAG,GAAG,SAAS,MAAM,OAAO,SAAS,CAAC;AAAA,EAC5D;AAEA,QAAM,CAAC,OAAO,QAAQ,QAAI,uBAAY,MAAM,kBAAkB,YAAY,CAAC;AAkB3E,QAAM,kBAA+C,CAAC,mBACpD,SAAS,CAAC,cAAc,kBAAkB,gBAAgB,SAAS,CAAC;AAKtE;AAAA,IACE,GAAG,GAAG;AAAA;AAAA,IAEN,UACI,CAAC,SAAS;AACR,eAAS,IAAI;AAAA,IACf,IACA;AAAA,EACN;AAEA,QAAM,eAAe,CAAC,GAAY,mBAA4B;AAC5D,QAAI,CAAC,KAAM;AACX,QAAI,OAAO,gBAAgB,WAAY;AACvC,QAAI,mBAAmB,SAAU;AACjC,QAAI,OAAO,UAAU,YAAa;AAElC,gBAAY,EAAE,MAAM,GAAG,GAAG,SAAS,MAAM,OAAO,SAAS,CAAC;AAAA,EAC5D;AAKA;AAAA,IACE,GAAG,GAAG;AAAA;AAAA,IAEN,OAAO,eAAe;AAAA,IACtB;AAAA;AAAA,EACF;AAEA,8BAAU,MAAM;AAGd,QACE,WACA,OAAO,gBAAgB,cACvB,OAAO,UAAU,aACjB;AACA,kBAAY,EAAE,MAAM,GAAG,GAAG,QAAQ,SAAS,CAAC;AAAA,IAC9C;AAAA,EACF,GAAG,CAAC,CAAC;AAGL,SAAO,CAAC,OAAO,iBAAiB,SAAS;AAC3C;","names":["state"]}
@@ -19,17 +19,18 @@ var __copyProps = (to, from, except, desc) => {
19
19
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
20
20
  var useCrossURLPathState_exports = {};
21
21
  __export(useCrossURLPathState_exports, {
22
+ useCrossURLPathSetter: () => useCrossURLPathSetter,
22
23
  useCrossURLPathState: () => useCrossURLPathState
23
24
  });
24
25
  module.exports = __toCommonJS(useCrossURLPathState_exports);
25
26
  var import_react = require("react");
26
27
  var import_useCrossFrameState = require('./useCrossFrameState.cjs');
27
- const useCrossURLPathState = (initialState, options) => {
28
- const states = (0, import_useCrossFrameState.useCrossFrameState)(
29
- "INTLAYER_URL_CHANGE",
30
- initialState,
31
- options
32
- );
28
+ const useCrossURLPathState = (initialState, options) => (0, import_useCrossFrameState.useCrossFrameState)("INTLAYER_URL_CHANGE", initialState, options);
29
+ const useCrossURLPathSetter = (initialState) => {
30
+ const states = useCrossURLPathState(initialState, {
31
+ emit: true,
32
+ receive: false
33
+ });
33
34
  const [_state, setState] = states;
34
35
  (0, import_react.useEffect)(() => {
35
36
  const originalPushState = history.pushState;
@@ -56,11 +57,12 @@ const useCrossURLPathState = (initialState, options) => {
56
57
  history.pushState = originalPushState;
57
58
  history.replaceState = originalReplaceState;
58
59
  };
59
- }, [setState]);
60
+ }, []);
60
61
  return states;
61
62
  };
62
63
  // Annotate the CommonJS export names for ESM import in node:
63
64
  0 && (module.exports = {
65
+ useCrossURLPathSetter,
64
66
  useCrossURLPathState
65
67
  });
66
68
  //# sourceMappingURL=useCrossURLPathState.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/useCrossURLPathState.tsx"],"sourcesContent":["'use client';\n\nimport { useEffect } from 'react';\nimport {\n useCrossFrameState,\n type CrossFrameStateOptions,\n} from './useCrossFrameState';\n\nexport const useCrossURLPathState = (\n initialState?: string,\n options?: CrossFrameStateOptions\n) => {\n const states = useCrossFrameState<string>(\n 'INTLAYER_URL_CHANGE',\n initialState,\n options\n );\n const [_state, setState] = states;\n\n useEffect(() => {\n /**\n * 1) Monkey patch history methods (pushState, replaceState)\n * to dispatch a custom event whenever they are called.\n */\n const originalPushState = history.pushState;\n const originalReplaceState = history.replaceState;\n\n const injectLocationChangeEvent = (method: (...args: any[]) => void) =>\n function (this: typeof history, ...args: [any, string, string?]) {\n method.apply(this, args);\n window.dispatchEvent(new Event('locationchange'));\n };\n\n history.pushState = injectLocationChangeEvent(originalPushState);\n history.replaceState = injectLocationChangeEvent(originalReplaceState);\n\n /**\n * 2) The callback to update our state whenever the URL changes.\n */\n const updateURLState = () => {\n setState(window.location.pathname);\n };\n\n /**\n * 3) Attach event listeners for locationchange, popstate, hashchange.\n * - 'locationchange' is our custom event triggered by push/replaceState overrides.\n * - 'popstate' is fired on back/forward navigation.\n * - 'hashchange' is for URL hash (#) changes.\n * - 'load' is when new page is loaded\n */\n window.addEventListener('locationchange', updateURLState);\n window.addEventListener('popstate', updateURLState);\n window.addEventListener('hashchange', updateURLState);\n window.addEventListener('load', updateURLState);\n\n // Initialize our state immediately on mount\n updateURLState();\n\n /**\n * 4) Cleanup when the component unmounts:\n * - Remove event listeners.\n * - Restore original pushState & replaceState to avoid side effects.\n */\n return () => {\n window.removeEventListener('locationchange', updateURLState);\n window.removeEventListener('popstate', updateURLState);\n window.removeEventListener('hashchange', updateURLState);\n window.removeEventListener('load', updateURLState);\n history.pushState = originalPushState;\n history.replaceState = originalReplaceState;\n };\n }, [setState]);\n\n return states;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAEA,mBAA0B;AAC1B,gCAGO;AAEA,MAAM,uBAAuB,CAClC,cACA,YACG;AACH,QAAM,aAAS;AAAA,IACb;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACA,QAAM,CAAC,QAAQ,QAAQ,IAAI;AAE3B,8BAAU,MAAM;AAKd,UAAM,oBAAoB,QAAQ;AAClC,UAAM,uBAAuB,QAAQ;AAErC,UAAM,4BAA4B,CAAC,WACjC,YAAmC,MAA8B;AAC/D,aAAO,MAAM,MAAM,IAAI;AACvB,aAAO,cAAc,IAAI,MAAM,gBAAgB,CAAC;AAAA,IAClD;AAEF,YAAQ,YAAY,0BAA0B,iBAAiB;AAC/D,YAAQ,eAAe,0BAA0B,oBAAoB;AAKrE,UAAM,iBAAiB,MAAM;AAC3B,eAAS,OAAO,SAAS,QAAQ;AAAA,IACnC;AASA,WAAO,iBAAiB,kBAAkB,cAAc;AACxD,WAAO,iBAAiB,YAAY,cAAc;AAClD,WAAO,iBAAiB,cAAc,cAAc;AACpD,WAAO,iBAAiB,QAAQ,cAAc;AAG9C,mBAAe;AAOf,WAAO,MAAM;AACX,aAAO,oBAAoB,kBAAkB,cAAc;AAC3D,aAAO,oBAAoB,YAAY,cAAc;AACrD,aAAO,oBAAoB,cAAc,cAAc;AACvD,aAAO,oBAAoB,QAAQ,cAAc;AACjD,cAAQ,YAAY;AACpB,cAAQ,eAAe;AAAA,IACzB;AAAA,EACF,GAAG,CAAC,QAAQ,CAAC;AAEb,SAAO;AACT;","names":[]}
1
+ {"version":3,"sources":["../../src/useCrossURLPathState.tsx"],"sourcesContent":["'use client';\n\nimport { useEffect } from 'react';\nimport {\n useCrossFrameState,\n type CrossFrameStateOptions,\n} from './useCrossFrameState';\n\nexport const useCrossURLPathState = (\n initialState?: string,\n options?: CrossFrameStateOptions\n) => useCrossFrameState('INTLAYER_URL_CHANGE', initialState, options);\n\nexport const useCrossURLPathSetter = (initialState?: string) => {\n const states = useCrossURLPathState(initialState, {\n emit: true,\n receive: false,\n });\n const [_state, setState] = states;\n\n useEffect(() => {\n /**\n * 1) Monkey patch history methods (pushState, replaceState)\n * to dispatch a custom event whenever they are called.\n */\n const originalPushState = history.pushState;\n const originalReplaceState = history.replaceState;\n\n const injectLocationChangeEvent = (method: (...args: any[]) => void) =>\n function (this: typeof history, ...args: [any, string, string?]) {\n method.apply(this, args);\n window.dispatchEvent(new Event('locationchange'));\n };\n\n history.pushState = injectLocationChangeEvent(originalPushState);\n history.replaceState = injectLocationChangeEvent(originalReplaceState);\n\n /**\n * 2) The callback to update our state whenever the URL changes.\n */\n const updateURLState = () => {\n setState(window.location.pathname);\n };\n\n /**\n * 3) Attach event listeners for locationchange, popstate, hashchange.\n * - 'locationchange' is our custom event triggered by push/replaceState overrides.\n * - 'popstate' is fired on back/forward navigation.\n * - 'hashchange' is for URL hash (#) changes.\n * - 'load' is when new page is loaded\n */\n window.addEventListener('locationchange', updateURLState);\n window.addEventListener('popstate', updateURLState);\n window.addEventListener('hashchange', updateURLState);\n window.addEventListener('load', updateURLState);\n\n // Initialize our state immediately on mount\n updateURLState();\n\n /**\n * 4) Cleanup when the component unmounts:\n * - Remove event listeners.\n * - Restore original pushState & replaceState to avoid side effects.\n */\n return () => {\n window.removeEventListener('locationchange', updateURLState);\n window.removeEventListener('popstate', updateURLState);\n window.removeEventListener('hashchange', updateURLState);\n window.removeEventListener('load', updateURLState);\n history.pushState = originalPushState;\n history.replaceState = originalReplaceState;\n };\n }, []);\n\n return states;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAEA,mBAA0B;AAC1B,gCAGO;AAEA,MAAM,uBAAuB,CAClC,cACA,gBACG,8CAAmB,uBAAuB,cAAc,OAAO;AAE7D,MAAM,wBAAwB,CAAC,iBAA0B;AAC9D,QAAM,SAAS,qBAAqB,cAAc;AAAA,IAChD,MAAM;AAAA,IACN,SAAS;AAAA,EACX,CAAC;AACD,QAAM,CAAC,QAAQ,QAAQ,IAAI;AAE3B,8BAAU,MAAM;AAKd,UAAM,oBAAoB,QAAQ;AAClC,UAAM,uBAAuB,QAAQ;AAErC,UAAM,4BAA4B,CAAC,WACjC,YAAmC,MAA8B;AAC/D,aAAO,MAAM,MAAM,IAAI;AACvB,aAAO,cAAc,IAAI,MAAM,gBAAgB,CAAC;AAAA,IAClD;AAEF,YAAQ,YAAY,0BAA0B,iBAAiB;AAC/D,YAAQ,eAAe,0BAA0B,oBAAoB;AAKrE,UAAM,iBAAiB,MAAM;AAC3B,eAAS,OAAO,SAAS,QAAQ;AAAA,IACnC;AASA,WAAO,iBAAiB,kBAAkB,cAAc;AACxD,WAAO,iBAAiB,YAAY,cAAc;AAClD,WAAO,iBAAiB,cAAc,cAAc;AACpD,WAAO,iBAAiB,QAAQ,cAAc;AAG9C,mBAAe;AAOf,WAAO,MAAM;AACX,aAAO,oBAAoB,kBAAkB,cAAc;AAC3D,aAAO,oBAAoB,YAAY,cAAc;AACrD,aAAO,oBAAoB,cAAc,cAAc;AACvD,aAAO,oBAAoB,QAAQ,cAAc;AACjD,cAAQ,YAAY;AACpB,cAAQ,eAAe;AAAA,IACzB;AAAA,EACF,GAAG,CAAC,CAAC;AAEL,SAAO;AACT;","names":[]}
@@ -13,15 +13,7 @@ const useConfigurationState = () => useCrossFrameState("INTLAYER_CONFIGURATION",
13
13
  emit: true
14
14
  });
15
15
  const ConfigurationProvider = ({ children, configuration }) => /* @__PURE__ */ jsx(ConfigurationStatesContext.Provider, { value: configuration, children });
16
- const useConfiguration = () => {
17
- const statesContext = useContext(ConfigurationStatesContext);
18
- if (!statesContext) {
19
- throw new Error(
20
- "useConfigurationStates must be used within a ConfigurationProvider"
21
- );
22
- }
23
- return statesContext;
24
- };
16
+ const useConfiguration = () => useContext(ConfigurationStatesContext);
25
17
  export {
26
18
  ConfigurationProvider,
27
19
  useConfiguration,
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/ConfigurationContext.tsx"],"sourcesContent":["'use client';\n\nimport { type IntlayerConfig } from '@intlayer/config/client';\nimport {\n type FC,\n type PropsWithChildren,\n createContext,\n useContext,\n} from 'react';\nimport { useCrossFrameState } from './useCrossFrameState';\n\nconst ConfigurationStatesContext = createContext<IntlayerConfig | undefined>(\n undefined\n);\n\nexport const useConfigurationState = () =>\n useCrossFrameState<IntlayerConfig>('INTLAYER_CONFIGURATION', undefined, {\n receive: false,\n emit: true,\n });\n\nexport type ConfigurationProviderProps = {\n configuration?: IntlayerConfig;\n};\n\nexport const ConfigurationProvider: FC<\n PropsWithChildren<ConfigurationProviderProps>\n> = ({ children, configuration }) => (\n <ConfigurationStatesContext.Provider value={configuration}>\n {children}\n </ConfigurationStatesContext.Provider>\n);\n\nexport const useConfiguration = () => {\n const statesContext = useContext(ConfigurationStatesContext);\n\n if (!statesContext) {\n throw new Error(\n 'useConfigurationStates must be used within a ConfigurationProvider'\n );\n }\n\n return statesContext;\n};\n"],"mappings":";AA4BE;AAzBF;AAAA,EAGE;AAAA,EACA;AAAA,OACK;AACP,SAAS,0BAA0B;AAEnC,MAAM,6BAA6B;AAAA,EACjC;AACF;AAEO,MAAM,wBAAwB,MACnC,mBAAmC,0BAA0B,QAAW;AAAA,EACtE,SAAS;AAAA,EACT,MAAM;AACR,CAAC;AAMI,MAAM,wBAET,CAAC,EAAE,UAAU,cAAc,MAC7B,oBAAC,2BAA2B,UAA3B,EAAoC,OAAO,eACzC,UACH;AAGK,MAAM,mBAAmB,MAAM;AACpC,QAAM,gBAAgB,WAAW,0BAA0B;AAE3D,MAAI,CAAC,eAAe;AAClB,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EACF;AAEA,SAAO;AACT;","names":[]}
1
+ {"version":3,"sources":["../../src/ConfigurationContext.tsx"],"sourcesContent":["'use client';\n\nimport { type IntlayerConfig } from '@intlayer/config/client';\nimport {\n type FC,\n type PropsWithChildren,\n createContext,\n useContext,\n} from 'react';\nimport { useCrossFrameState } from './useCrossFrameState';\n\nconst ConfigurationStatesContext = createContext<IntlayerConfig | undefined>(\n undefined\n);\n\nexport const useConfigurationState = () =>\n useCrossFrameState<IntlayerConfig>('INTLAYER_CONFIGURATION', undefined, {\n receive: false,\n emit: true,\n });\n\nexport type ConfigurationProviderProps = {\n configuration?: IntlayerConfig;\n};\n\nexport const ConfigurationProvider: FC<\n PropsWithChildren<ConfigurationProviderProps>\n> = ({ children, configuration }) => (\n <ConfigurationStatesContext.Provider value={configuration}>\n {children}\n </ConfigurationStatesContext.Provider>\n);\n\nexport const useConfiguration = () => useContext(ConfigurationStatesContext);\n"],"mappings":";AA4BE;AAzBF;AAAA,EAGE;AAAA,EACA;AAAA,OACK;AACP,SAAS,0BAA0B;AAEnC,MAAM,6BAA6B;AAAA,EACjC;AACF;AAEO,MAAM,wBAAwB,MACnC,mBAAmC,0BAA0B,QAAW;AAAA,EACtE,SAAS;AAAA,EACT,MAAM;AACR,CAAC;AAMI,MAAM,wBAET,CAAC,EAAE,UAAU,cAAc,MAC7B,oBAAC,2BAA2B,UAA3B,EAAoC,OAAO,eACzC,UACH;AAGK,MAAM,mBAAmB,MAAM,WAAW,0BAA0B;","names":[]}
@@ -13,20 +13,21 @@ import {
13
13
  useDictionariesRecord
14
14
  } from "./DictionariesRecordContext.mjs";
15
15
  import { useCrossFrameState } from "./useCrossFrameState.mjs";
16
+ import { useCrossFrameMessageListener } from "./useCrossFrameMessageListener.mjs";
16
17
  const EditedContentStateContext = createContext(void 0);
17
- const EditedContentActionsContext = createContext(void 0);
18
- const useEditedContentState = () => useCrossFrameState(
19
- "INTLAYER_EDITED_CONTENT_CHANGED",
20
- void 0,
21
- { emit: true, receive: false }
18
+ const usePostEditedContentState = (onEventTriggered) => useCrossFrameMessageListener(
19
+ "INTLAYER_EDITED_CONTENT_CHANGED/post",
20
+ onEventTriggered
21
+ );
22
+ const useGetEditedContentState = (onEventTriggered) => useCrossFrameMessageListener(
23
+ "INTLAYER_EDITED_CONTENT_CHANGED/get",
24
+ onEventTriggered
22
25
  );
26
+ const EditedContentActionsContext = createContext(void 0);
23
27
  const resolveState = (state, prevState) => typeof state === "function" ? state(prevState) : state;
24
28
  const EditedContentProvider = ({ children }) => {
25
29
  const { localeDictionaries } = useDictionariesRecord();
26
- const [editedContent, setEditedContentState] = useCrossFrameState(
27
- "INTLAYER_EDITED_CONTENT_CHANGED",
28
- void 0
29
- );
30
+ const [editedContent, setEditedContentState] = useCrossFrameState("INTLAYER_EDITED_CONTENT_CHANGED");
30
31
  const setEditedDictionary = (newValue) => {
31
32
  let updatedDictionaries = resolveState(newValue);
32
33
  setEditedContentState((prev) => {
@@ -201,6 +202,7 @@ export {
201
202
  EditedContentProvider,
202
203
  useEditedContent,
203
204
  useEditedContentActions,
204
- useEditedContentState
205
+ useGetEditedContentState,
206
+ usePostEditedContentState
205
207
  };
206
208
  //# sourceMappingURL=EditedContentContext.mjs.map