@empathyco/x-components 6.0.0-alpha.54 → 6.0.0-alpha.56
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/CHANGELOG.md +17 -0
- package/design-system/deprecated-full-theme.css +614 -614
- package/docs/API-reference/api/x-components.globalxbus.md +2 -0
- package/docs/API-reference/api/x-components.hierarchicalfilter.md +1 -0
- package/docs/API-reference/api/x-components.md +1 -0
- package/docs/API-reference/api/x-components.relatedpromptsactions.md +1 -0
- package/docs/API-reference/api/x-components.relatedpromptsactions.seturlparams.md +24 -0
- package/docs/API-reference/api/x-components.relatedpromptstaglist.md +2 -3
- package/docs/API-reference/api/x-components.relatedpromptsxevents.md +1 -0
- package/docs/API-reference/api/x-components.relatedpromptsxevents.selectedrelatedpromptchanged.md +13 -0
- package/docs/API-reference/api/x-components.seturlprompt.md +13 -0
- package/docs/API-reference/api/x-components.simplefilter.md +1 -0
- package/docs/API-reference/api/x-components.snippetcallbacks.md +1 -0
- package/docs/API-reference/api/x-components.urlmutations.md +1 -0
- package/docs/API-reference/api/x-components.urlmutations.setprompt.md +24 -0
- package/docs/API-reference/api/x-components.urlparams.md +1 -0
- package/docs/API-reference/api/x-components.urlparams.prompt.md +11 -0
- package/js/index.js +1 -1
- package/js/x-modules/related-prompts/components/related-prompts-tag-list.vue.js +6 -3
- package/js/x-modules/related-prompts/components/related-prompts-tag-list.vue.js.map +1 -1
- package/js/x-modules/related-prompts/components/related-prompts-tag-list.vue2.js +9 -14
- package/js/x-modules/related-prompts/components/related-prompts-tag-list.vue2.js.map +1 -1
- package/js/x-modules/related-prompts/store/actions/set-url-params.action.js +15 -0
- package/js/x-modules/related-prompts/store/actions/set-url-params.action.js.map +1 -0
- package/js/x-modules/related-prompts/store/emitters.js +2 -1
- package/js/x-modules/related-prompts/store/emitters.js.map +1 -1
- package/js/x-modules/related-prompts/store/module.js +4 -7
- package/js/x-modules/related-prompts/store/module.js.map +1 -1
- package/js/x-modules/related-prompts/wiring.js +43 -65
- package/js/x-modules/related-prompts/wiring.js.map +1 -1
- package/js/x-modules/tagging/wiring.js +8 -4
- package/js/x-modules/tagging/wiring.js.map +1 -1
- package/js/x-modules/url/components/url-handler.vue.js.map +1 -1
- package/js/x-modules/url/components/url-handler.vue2.js +2 -4
- package/js/x-modules/url/components/url-handler.vue2.js.map +1 -1
- package/js/x-modules/url/store/getters/url-params.getter.js +2 -3
- package/js/x-modules/url/store/getters/url-params.getter.js.map +1 -1
- package/js/x-modules/url/store/initial-state.js +2 -1
- package/js/x-modules/url/store/initial-state.js.map +1 -1
- package/js/x-modules/url/store/module.js +3 -0
- package/js/x-modules/url/store/module.js.map +1 -1
- package/js/x-modules/url/wiring.js +10 -1
- package/js/x-modules/url/wiring.js.map +1 -1
- package/package.json +3 -3
- package/report/x-components.api.json +211 -7
- package/report/x-components.api.md +35 -18
- package/types/components/global-x-bus.vue.d.ts +2 -0
- package/types/components/global-x-bus.vue.d.ts.map +1 -1
- package/types/components/snippet-callbacks.vue.d.ts +1 -0
- package/types/components/snippet-callbacks.vue.d.ts.map +1 -1
- package/types/types/url-params.d.ts +1 -0
- package/types/types/url-params.d.ts.map +1 -1
- package/types/x-modules/facets/components/filters/hierarchical-filter.vue.d.ts +1 -0
- package/types/x-modules/facets/components/filters/hierarchical-filter.vue.d.ts.map +1 -1
- package/types/x-modules/facets/components/filters/simple-filter.vue.d.ts +1 -0
- package/types/x-modules/facets/components/filters/simple-filter.vue.d.ts.map +1 -1
- package/types/x-modules/related-prompts/components/related-prompts-tag-list.vue.d.ts +3 -4
- package/types/x-modules/related-prompts/components/related-prompts-tag-list.vue.d.ts.map +1 -1
- package/types/x-modules/related-prompts/events.types.d.ts +5 -0
- package/types/x-modules/related-prompts/events.types.d.ts.map +1 -1
- package/types/x-modules/related-prompts/store/actions/set-url-params.action.d.ts +11 -0
- package/types/x-modules/related-prompts/store/actions/set-url-params.action.d.ts.map +1 -0
- package/types/x-modules/related-prompts/store/emitters.d.ts +1 -0
- package/types/x-modules/related-prompts/store/emitters.d.ts.map +1 -1
- package/types/x-modules/related-prompts/store/module.d.ts.map +1 -1
- package/types/x-modules/related-prompts/store/types.d.ts +7 -0
- package/types/x-modules/related-prompts/store/types.d.ts.map +1 -1
- package/types/x-modules/related-prompts/wiring.d.ts +15 -14
- package/types/x-modules/related-prompts/wiring.d.ts.map +1 -1
- package/types/x-modules/tagging/wiring.d.ts.map +1 -1
- package/types/x-modules/url/components/url-handler.vue.d.ts.map +1 -1
- package/types/x-modules/url/store/getters/url-params.getter.d.ts +2 -3
- package/types/x-modules/url/store/getters/url-params.getter.d.ts.map +1 -1
- package/types/x-modules/url/store/initial-state.d.ts.map +1 -1
- package/types/x-modules/url/store/module.d.ts.map +1 -1
- package/types/x-modules/url/store/types.d.ts +6 -0
- package/types/x-modules/url/store/types.d.ts.map +1 -1
- package/types/x-modules/url/wiring.d.ts +9 -0
- package/types/x-modules/url/wiring.d.ts.map +1 -1
- package/url/index.js +1 -1
|
@@ -1,62 +1,37 @@
|
|
|
1
1
|
import { namespacedWireCommit, namespacedWireCommitWithoutPayload, namespacedWireDispatch, namespacedWireDispatchWithoutPayload } from '../../wiring/namespaced-wires.factory.js';
|
|
2
2
|
import { createWiring } from '../../wiring/wiring.utils.js';
|
|
3
|
+
import { filter } from '../../wiring/wires.operators.js';
|
|
3
4
|
|
|
4
|
-
/**
|
|
5
|
-
* `relatedPrompts` {@link XModuleName | XModule name}.
|
|
6
|
-
*/
|
|
5
|
+
/** `relatedPrompts` XModule name. */
|
|
7
6
|
const moduleName = 'relatedPrompts';
|
|
8
|
-
/**
|
|
9
|
-
* WireCommit for {@link RelatedPromptsXModule}.
|
|
10
|
-
*/
|
|
7
|
+
/** WireCommit for RelatedPromptsXModule. */
|
|
11
8
|
const wireCommit = namespacedWireCommit(moduleName);
|
|
12
|
-
/**
|
|
13
|
-
* WireCommitWithoutPayload for {@link RelatedPromptsXModule}.
|
|
14
|
-
*/
|
|
9
|
+
/** WireCommitWithoutPayload for RelatedPromptsXModule. */
|
|
15
10
|
const wireCommitWithoutPayload = namespacedWireCommitWithoutPayload(moduleName);
|
|
16
|
-
/**
|
|
17
|
-
* WireDispatch for {@link RelatedPromptsXModule}.
|
|
18
|
-
*/
|
|
11
|
+
/** WireDispatch for RelatedPromptsXModule.*/
|
|
19
12
|
const wireDispatch = namespacedWireDispatch(moduleName);
|
|
20
|
-
/**
|
|
21
|
-
* WireDispatchWithoutPayload for {@link RelatedPromptsXModule}.
|
|
22
|
-
*/
|
|
13
|
+
/** WireDispatchWithoutPayload for RelatedPromptsXModule. */
|
|
23
14
|
const wireDispatchWithoutPayload = namespacedWireDispatchWithoutPayload(moduleName);
|
|
24
|
-
/**
|
|
25
|
-
|
|
26
|
-
*/
|
|
15
|
+
/** Sets the related prompts state from URL data. */
|
|
16
|
+
const setUrlParams = wireDispatch('setUrlParams');
|
|
17
|
+
/** Sets the related prompts state `params`. */
|
|
18
|
+
const setExtraParams = wireCommit('setParams');
|
|
19
|
+
/** Sets the related prompts state `query`. */
|
|
27
20
|
const setRelatedPromptsQuery = wireCommit('setQuery');
|
|
28
|
-
/**
|
|
29
|
-
|
|
30
|
-
*/
|
|
31
|
-
const
|
|
32
|
-
/**
|
|
33
|
-
|
|
34
|
-
*/
|
|
35
|
-
const
|
|
36
|
-
/**
|
|
37
|
-
|
|
38
|
-
*/
|
|
39
|
-
const
|
|
40
|
-
/**
|
|
41
|
-
|
|
42
|
-
*/
|
|
43
|
-
const setRelatedPromptsExtraParams = wireCommit('setParams');
|
|
44
|
-
/**
|
|
45
|
-
* Resets the related prompts state.
|
|
46
|
-
*/
|
|
47
|
-
const resetRelatedPromptsStateWire = wireCommitWithoutPayload('resetRelatedPromptsState');
|
|
48
|
-
/**
|
|
49
|
-
* Resets the selected related prompt number.
|
|
50
|
-
*/
|
|
51
|
-
const resetSelectedPromptWire = wireCommitWithoutPayload('resetSelectedPrompt');
|
|
52
|
-
/**
|
|
53
|
-
* Fetches and saves the related prompts response.
|
|
54
|
-
*/
|
|
55
|
-
const fetchAndSaveRelatedPromptsResponseWire = wireDispatch('fetchAndSaveRelatedPrompts');
|
|
56
|
-
/**
|
|
57
|
-
* Cancels the fetch and save related prompts response.
|
|
58
|
-
*/
|
|
59
|
-
const cancelFetchAndSaveSearchResponseWire = wireDispatchWithoutPayload('cancelFetchAndSaveRelatedPrompts');
|
|
21
|
+
/** Sets the related prompts state `query` from the payload. */
|
|
22
|
+
const setRelatedPromptsQueryFromPreview = wireCommit('setQuery', ({ eventPayload: { query } }) => query);
|
|
23
|
+
/** Sets the related prompts state `selectedQuery`. */
|
|
24
|
+
const setRelatedPromptQuery = wireCommit('setSelectedQuery');
|
|
25
|
+
/** Sets the related prompts state `selectedPrompt`. */
|
|
26
|
+
const setRelatedPrompt = wireCommit('setSelectedPrompt');
|
|
27
|
+
/** Fetches and saves the related prompts response. */
|
|
28
|
+
const fetchAndSaveRelatedPrompts = wireDispatch('fetchAndSaveRelatedPrompts');
|
|
29
|
+
/** Cancels the fetch and save related prompts response. */
|
|
30
|
+
const cancelFetchAndSaveRelatedPrompts = wireDispatchWithoutPayload('cancelFetchAndSaveRelatedPrompts');
|
|
31
|
+
/** Resets the related prompts state. */
|
|
32
|
+
const resetRelatedPromptsState = wireCommitWithoutPayload('resetRelatedPromptsState');
|
|
33
|
+
/** Resets the selected related prompt number. */
|
|
34
|
+
const resetRelatedPrompt = wireCommitWithoutPayload('resetSelectedPrompt');
|
|
60
35
|
/**
|
|
61
36
|
* Wiring configuration for the {@link RelatedPromptsXModule | related prompts module}.
|
|
62
37
|
*
|
|
@@ -64,34 +39,37 @@ const cancelFetchAndSaveSearchResponseWire = wireDispatchWithoutPayload('cancelF
|
|
|
64
39
|
*/
|
|
65
40
|
const relatedPromptsWiring = createWiring({
|
|
66
41
|
ParamsLoadedFromUrl: {
|
|
67
|
-
|
|
42
|
+
setUrlParams
|
|
43
|
+
},
|
|
44
|
+
ExtraParamsChanged: {
|
|
45
|
+
setExtraParams
|
|
68
46
|
},
|
|
69
47
|
UserAcceptedAQuery: {
|
|
70
|
-
setRelatedPromptsQuery
|
|
48
|
+
setRelatedPromptsQuery,
|
|
49
|
+
resetRelatedPrompt
|
|
50
|
+
},
|
|
51
|
+
UserAcceptedAQueryPreview: {
|
|
52
|
+
setRelatedPromptsQueryFromPreview,
|
|
53
|
+
resetRelatedPrompt
|
|
71
54
|
},
|
|
72
55
|
UserClearedQuery: {
|
|
73
|
-
|
|
74
|
-
|
|
56
|
+
cancelFetchAndSaveRelatedPrompts,
|
|
57
|
+
resetRelatedPromptsState,
|
|
75
58
|
setRelatedPromptsQuery
|
|
76
59
|
},
|
|
77
60
|
RelatedPromptsRequestUpdated: {
|
|
78
|
-
|
|
79
|
-
},
|
|
80
|
-
ExtraParamsChanged: {
|
|
81
|
-
setRelatedPromptsExtraParams
|
|
61
|
+
fetchAndSaveRelatedPrompts
|
|
82
62
|
},
|
|
83
63
|
UserSelectedARelatedPrompt: {
|
|
84
|
-
|
|
64
|
+
setRelatedPrompt
|
|
85
65
|
},
|
|
86
66
|
UserSelectedARelatedPromptQuery: {
|
|
87
|
-
|
|
88
|
-
},
|
|
89
|
-
UserAcceptedAQueryPreview: {
|
|
90
|
-
setRelatedPromptsQueryFromPayload,
|
|
91
|
-
resetSelectedPromptWire
|
|
67
|
+
setRelatedPromptQuery
|
|
92
68
|
},
|
|
93
69
|
SearchRequestChanged: {
|
|
94
|
-
|
|
70
|
+
resetRelatedPrompt: filter(resetRelatedPrompt,
|
|
71
|
+
// Avoid reset selected prompt just after restored from URL with ParamsLoadedFromUrl event
|
|
72
|
+
({ store }) => store.state.x.search.origin !== 'url:external')
|
|
95
73
|
}
|
|
96
74
|
});
|
|
97
75
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"wiring.js","sources":["../../../../src/x-modules/related-prompts/wiring.ts"],"sourcesContent":["import {\n namespacedWireCommit,\n namespacedWireCommitWithoutPayload,\n namespacedWireDispatch,\n namespacedWireDispatchWithoutPayload\n} from '../../wiring/namespaced-wires.factory';\nimport {
|
|
1
|
+
{"version":3,"file":"wiring.js","sources":["../../../../src/x-modules/related-prompts/wiring.ts"],"sourcesContent":["import {\n namespacedWireCommit,\n namespacedWireCommitWithoutPayload,\n namespacedWireDispatch,\n namespacedWireDispatchWithoutPayload\n} from '../../wiring/namespaced-wires.factory';\nimport { createWiring } from '../../wiring/wiring.utils';\nimport { filter } from '../../wiring/wires.operators';\n\n/** `relatedPrompts` XModule name. */\nconst moduleName = 'relatedPrompts';\n/** WireCommit for RelatedPromptsXModule. */\nconst wireCommit = namespacedWireCommit(moduleName);\n/** WireCommitWithoutPayload for RelatedPromptsXModule. */\nconst wireCommitWithoutPayload = namespacedWireCommitWithoutPayload(moduleName);\n/** WireDispatch for RelatedPromptsXModule.*/\nconst wireDispatch = namespacedWireDispatch(moduleName);\n/** WireDispatchWithoutPayload for RelatedPromptsXModule. */\nconst wireDispatchWithoutPayload = namespacedWireDispatchWithoutPayload(moduleName);\n\n/** Sets the related prompts state from URL data. */\nconst setUrlParams = wireDispatch('setUrlParams');\n/** Sets the related prompts state `params`. */\nconst setExtraParams = wireCommit('setParams');\n\n/** Sets the related prompts state `query`. */\nconst setRelatedPromptsQuery = wireCommit('setQuery');\n/** Sets the related prompts state `query` from the payload. */\nconst setRelatedPromptsQueryFromPreview = wireCommit(\n 'setQuery',\n ({ eventPayload: { query } }) => query\n);\n/** Sets the related prompts state `selectedQuery`. */\nconst setRelatedPromptQuery = wireCommit('setSelectedQuery');\n/** Sets the related prompts state `selectedPrompt`. */\nconst setRelatedPrompt = wireCommit('setSelectedPrompt');\n\n/** Fetches and saves the related prompts response. */\nconst fetchAndSaveRelatedPrompts = wireDispatch('fetchAndSaveRelatedPrompts');\n/** Cancels the fetch and save related prompts response. */\nconst cancelFetchAndSaveRelatedPrompts = wireDispatchWithoutPayload(\n 'cancelFetchAndSaveRelatedPrompts'\n);\n\n/** Resets the related prompts state. */\nconst resetRelatedPromptsState = wireCommitWithoutPayload('resetRelatedPromptsState');\n/** Resets the selected related prompt number. */\nconst resetRelatedPrompt = wireCommitWithoutPayload('resetSelectedPrompt');\n\n/**\n * Wiring configuration for the {@link RelatedPromptsXModule | related prompts module}.\n *\n * @internal\n */\nexport const relatedPromptsWiring = createWiring({\n ParamsLoadedFromUrl: {\n setUrlParams\n },\n ExtraParamsChanged: {\n setExtraParams\n },\n UserAcceptedAQuery: {\n setRelatedPromptsQuery,\n resetRelatedPrompt\n },\n UserAcceptedAQueryPreview: {\n setRelatedPromptsQueryFromPreview,\n resetRelatedPrompt\n },\n UserClearedQuery: {\n cancelFetchAndSaveRelatedPrompts,\n resetRelatedPromptsState,\n setRelatedPromptsQuery\n },\n RelatedPromptsRequestUpdated: {\n fetchAndSaveRelatedPrompts\n },\n UserSelectedARelatedPrompt: {\n setRelatedPrompt\n },\n UserSelectedARelatedPromptQuery: {\n setRelatedPromptQuery\n },\n SearchRequestChanged: {\n resetRelatedPrompt: filter(\n resetRelatedPrompt,\n // Avoid reset selected prompt just after restored from URL with ParamsLoadedFromUrl event\n ({ store }) => store.state.x.search.origin !== 'url:external'\n )\n }\n});\n"],"names":[],"mappings":";;;;AASA;AACA,MAAM,UAAU,GAAG,gBAAgB,CAAC;AACpC;AACA,MAAM,UAAU,GAAG,oBAAoB,CAAC,UAAU,CAAC,CAAC;AACpD;AACA,MAAM,wBAAwB,GAAG,kCAAkC,CAAC,UAAU,CAAC,CAAC;AAChF;AACA,MAAM,YAAY,GAAG,sBAAsB,CAAC,UAAU,CAAC,CAAC;AACxD;AACA,MAAM,0BAA0B,GAAG,oCAAoC,CAAC,UAAU,CAAC,CAAC;AAEpF;AACA,MAAM,YAAY,GAAG,YAAY,CAAC,cAAc,CAAC,CAAC;AAClD;AACA,MAAM,cAAc,GAAG,UAAU,CAAC,WAAW,CAAC,CAAC;AAE/C;AACA,MAAM,sBAAsB,GAAG,UAAU,CAAC,UAAU,CAAC,CAAC;AACtD;AACA,MAAM,iCAAiC,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
|
@@ -220,7 +220,7 @@ function createTrackDisplayWire(property) {
|
|
|
220
220
|
});
|
|
221
221
|
taggingInfo.params.q = metadata.displayOriginalQuery;
|
|
222
222
|
return taggingInfo;
|
|
223
|
-
}), ({ eventPayload: { tagging } }) => !!tagging?.[property]);
|
|
223
|
+
}), ({ eventPayload: { tagging } }) => !!tagging?.[property]?.url);
|
|
224
224
|
}
|
|
225
225
|
/**
|
|
226
226
|
* Update the tooling tagging params with the result information.
|
|
@@ -277,13 +277,17 @@ function createTrackToolingAdd2CartWire() {
|
|
|
277
277
|
function createTrackRelatedPromptToolingDisplayClickWire() {
|
|
278
278
|
return filter(wireDispatch('track', ({ metadata }) => {
|
|
279
279
|
const relatedPrompt = metadata.relatedPrompt;
|
|
280
|
-
const taggingInfo = relatedPrompt.tagging
|
|
281
|
-
?.toolingDisplayClickTagging;
|
|
280
|
+
const taggingInfo = relatedPrompt.tagging.toolingDisplayClickTagging;
|
|
282
281
|
taggingInfo.params.productId = 'EXPAND';
|
|
283
282
|
taggingInfo.params.title = relatedPrompt.suggestionText;
|
|
284
283
|
taggingInfo.params.url = 'none';
|
|
285
284
|
return taggingInfo;
|
|
286
|
-
}), ({ metadata }) =>
|
|
285
|
+
}), ({ metadata }) => {
|
|
286
|
+
const relatedPrompt = metadata.relatedPrompt;
|
|
287
|
+
const isUnselected = metadata?.selectedPrompt === -1;
|
|
288
|
+
const taggingInfo = relatedPrompt?.tagging?.toolingDisplayClickTagging;
|
|
289
|
+
return isUnselected && !!taggingInfo;
|
|
290
|
+
});
|
|
287
291
|
}
|
|
288
292
|
/**
|
|
289
293
|
* Factory helper to create a wire to set the queryTagging.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"wiring.js","sources":["../../../../src/x-modules/tagging/wiring.ts"],"sourcesContent":["import {\n RelatedPrompt,\n Result,\n SemanticQuery,\n Taggable,\n Tagging,\n TaggingRequest\n} from '@empathyco/x-types';\nimport { DefaultSessionService } from '@empathyco/x-utils';\nimport {\n namespacedWireCommit,\n namespacedWireDispatch\n} from '../../wiring/namespaced-wires.factory';\nimport { namespacedDebounce } from '../../wiring/namespaced-wires.operators';\nimport { wireService, wireServiceWithoutPayload } from '../../wiring/wires.factory';\nimport { filter, mapWire } from '../../wiring/wires.operators';\nimport { DisplayWireMetadata, Wire } from '../../wiring/wiring.types';\nimport { createWiring } from '../../wiring/wiring.utils';\nimport { createOrigin } from '../../utils/index';\nimport { FeatureLocation } from '../../types/index';\nimport { DefaultExternalTaggingService } from './service/external-tagging.service';\n\n/**\n * `tagging` {@link XModuleName | XModule name}.\n *\n * @internal\n */\nconst moduleName = 'tagging';\n\n/**\n * Debounce function for the module.\n */\nconst moduleDebounce = namespacedDebounce(moduleName);\n\n/**\n * WireCommit for {@link TaggingXModule}.\n *\n * @internal\n */\nconst wireCommit = namespacedWireCommit(moduleName);\n\n/**\n * WireDispatch for {@link TaggingXModule}.\n *\n * @internal\n */\nconst wireDispatch = namespacedWireDispatch(moduleName);\n\n/**\n * Wires without payload factory for {@link DefaultSessionService}.\n */\nconst wireSessionServiceWithoutPayload = wireServiceWithoutPayload(DefaultSessionService.instance);\n\n/**\n * Wires factory for {@link DefaultExternalTaggingService}.\n */\nconst wireExternalTaggingService = wireService(DefaultExternalTaggingService.instance);\n\n/**\n * Stores the given result on the local storage.\n *\n * @public\n */\nconst storeClickedResultWire = wireExternalTaggingService('storeResultClicked');\n\n/**\n * Stores the result added to cart on the local storage.\n *\n * @public\n */\nconst storeAddToCartWire = wireExternalTaggingService('storeAddToCart');\n\n/**\n * Moves the result information from the local storage to session storage.\n *\n * @public\n */\nconst moveClickedResultToSessionWire = mapWire(\n wireExternalTaggingService('moveToSessionStorage'),\n (payload: string) => {\n return payload === 'url' ? undefined : payload;\n }\n);\n\n/**\n * Triggers the add to cart tracking.\n *\n * @public\n */\nconst trackAddToCartFromSessionStorage = wireExternalTaggingService('trackAddToCart');\n\n/**\n * Clears the session id.\n *\n * @public\n */\nconst clearSessionWire = filter(\n wireSessionServiceWithoutPayload('clearSessionId'),\n ({ eventPayload: consent }) => !consent\n);\n\n/**\n * Sets the tagging state `consent`.\n *\n * @public\n */\nexport const setConsent = wireCommit('setConsent');\n\n/**\n * Sets the tagging state `noResultsTaggingEnabled`.\n *\n * @public\n */\nexport const setNoResultsTaggingEnabledWire = wireCommit('setNoResultsTaggingEnabled');\n\n/**\n * Sets the tagging config state.\n *\n * @public\n */\nexport const setTaggingConfig = wireCommit('mergeConfig');\n\n/**\n * Tracks the tagging of the query.\n *\n * @public\n */\nexport const trackQueryWire = filter(\n wireDispatch('track'),\n ({ eventPayload, store }) =>\n ((eventPayload as TaggingRequest).params.totalHits as number) > 0 ||\n !store.state.x.tagging.noResultsTaggingEnabled\n);\n\n/**\n * Sets the tagging state of the query tagging info using a debounce which ends if the user\n * accepts a query.\n *\n * @public\n */\nexport const setQueryTaggingInfo = moduleDebounce(\n wireCommit('setQueryTaggingInfo'),\n ({ state }) => state.config.queryTaggingDebounceMs,\n {\n cancelOn: 'UserClearedQuery',\n forceOn: [\n 'UserClickedAResult',\n 'UserClickedAPromoted',\n 'UserClickedABanner',\n 'UserClickedARedirection',\n 'UserReachedResultsListEnd'\n ]\n }\n);\n\n/**\n * Sets the tagging state of the query tagging info using.\n *\n * @public\n */\nexport const setQueryTaggingFromQueryPreview = createSetQueryTaggingFromQueryPreview();\n\n/**\n * Tracks the tagging of the result.\n *\n * @public\n */\nexport const trackResultClickedWire = createTrackWire('click');\n\n/**\n * Tracks the tagging of the banner.\n *\n * @public\n */\nexport const trackBannerClickedWire = createTrackWire('click');\n\n/**\n * Performs a track of a result added to the cart.\n *\n * @public\n */\nexport const trackAddToCartWire = createTrackWire('add2cart');\n\n/**\n * Performs a track of a display result being clicked.\n *\n * @public\n */\nexport const trackDisplayClickedWire = createTrackDisplayWire('displayClick');\n\n/**\n * Performs a track of a display result being clicked.\n *\n * @public\n */\nexport const trackToolingDisplayClickedWire = createTrackToolingDisplayWire();\n\n/**\n * Performs a track of a display result being clicked.\n *\n * @public\n */\nexport const trackToolingAdd2CartWire = createTrackToolingAdd2CartWire();\n\n/**\n * Performs a track of a clicked related prompt.\n *\n * @public\n */\nexport const trackRelatedPromptToolingDisplayClickWire =\n createTrackRelatedPromptToolingDisplayClickWire();\n\n/**\n * Performs a track of a display element appearing.\n *\n * @public\n */\nexport const trackElementDisplayedWire = createTrackDisplayWire('display');\n\n/**\n * Factory helper to create a wire for the track of a taggable element.\n *\n * @param property - Key of the tagging object to track.\n * @returns A new wire for the given property of the taggable element.\n *\n * @public\n */\nexport function createTrackWire(property: keyof Tagging): Wire<Taggable> {\n return filter(\n wireDispatch('track', ({ eventPayload: { tagging }, metadata: { location } }) => {\n const taggingInfo: TaggingRequest = tagging[property];\n taggingInfo.params.location = location as string;\n return taggingInfo;\n }),\n ({ eventPayload: { tagging }, metadata: { ignoreInModules } }) =>\n !!tagging?.[property] && !ignoreInModules?.includes(moduleName)\n );\n}\n\n/**\n * Performs a track of a query with no results that used semantics as fallback.\n * The totalHits will be changed to -1 if semantic queries are found in order to differentiate\n * it from scenarios where the user encounters a no-results page without any semantic queries.\n *\n * @public\n */\nexport const trackNoResultsQueryWithSemanticsWire = filter(\n wireDispatch('track', ({ eventPayload, state }) => {\n const { queryTaggingInfo } = state;\n const totalHits = (eventPayload as SemanticQuery[]).length > 0 ? -1 : 0;\n return {\n params: { ...queryTaggingInfo?.params, totalHits },\n url: queryTaggingInfo?.url ?? ''\n };\n }),\n ({ store }) => Number(store.state.x.tagging.queryTaggingInfo?.params.totalHits)! === 0\n);\n\n/**.\n * Debounced version of {@link trackNoResultsQueryWithSemanticsWire}\n *\n * @public\n */\nexport const trackNoResultsQueryWithSemanticsWireDebounced = moduleDebounce(\n trackNoResultsQueryWithSemanticsWire,\n ({ state }) => state.config.queryTaggingDebounceMs,\n { cancelOn: 'QueryPreviewUnmounted' }\n);\n\n/**\n * Factory helper to create a wire for the track of the display click.\n *\n * @param property - Key of the tagging object to track.\n * @returns A new wire for the display click of the taggable element.\n *\n * @public\n */\nexport function createTrackDisplayWire(property: keyof Tagging): Wire<Taggable> {\n return filter(\n wireDispatch('track', ({ eventPayload: { tagging }, metadata }) => {\n const taggingInfo: TaggingRequest = tagging[property];\n const location = metadata.location as FeatureLocation;\n\n taggingInfo.params.location = location;\n taggingInfo.params.displayFamily = createOrigin({\n feature: metadata.feature,\n location\n })!;\n taggingInfo.params.q = (metadata as DisplayWireMetadata).displayOriginalQuery;\n\n return taggingInfo;\n }),\n ({ eventPayload: { tagging } }) => !!tagging?.[property]\n );\n}\n\n/**\n * Update the tooling tagging params with the result information.\n *\n * @param taggingRequest - The tooling tagging request to be updated.\n * @param result - The clicked result.\n * @returns The tagging request updated.\n *\n * @internal\n */\nfunction updateToolingTaggingWithResult(\n taggingRequest: TaggingRequest,\n result: Result\n): TaggingRequest {\n taggingRequest.params.productId = result.id;\n taggingRequest.params.title = result.name!;\n taggingRequest.params.url = result.url!;\n\n return taggingRequest;\n}\n\n/**\n * Factory helper to create a wire for the track of the tooling display click.\n *\n * @returns A new wire for the tooling display click of the taggable element.\n *\n * @public\n */\nexport function createTrackToolingDisplayWire(): Wire<Taggable> {\n return filter(\n wireDispatch('track', ({ eventPayload, metadata }) => {\n const taggingInfo: TaggingRequest = metadata.toolingTagging as TaggingRequest;\n const resultInfo = eventPayload as Result;\n\n updateToolingTaggingWithResult(taggingInfo, resultInfo);\n\n return taggingInfo;\n }),\n ({ metadata }) => !!metadata?.toolingTagging\n );\n}\n\n/**\n * Factory helper to create a wire for the track of the tooling display add to cart.\n *\n * @returns A new wire for the tooling display add to cart of the taggable element.\n *\n * @public\n */\nexport function createTrackToolingAdd2CartWire(): Wire<Taggable> {\n return filter(\n wireDispatch('track', ({ eventPayload, metadata }) => {\n const taggingInfo: TaggingRequest = metadata.toolingAdd2CartTagging as TaggingRequest;\n const resultInfo = eventPayload as Result;\n\n updateToolingTaggingWithResult(taggingInfo, resultInfo);\n\n return taggingInfo;\n }),\n ({ metadata }) => !!metadata?.toolingAdd2CartTagging\n );\n}\n\n/**\n * Factory helper to create a wire for the track of the tooling display click in a related prompt.\n *\n * @returns A new wire for the tooling display click of the taggable element.\n *\n * @public\n */\nexport function createTrackRelatedPromptToolingDisplayClickWire() {\n return filter(\n wireDispatch('track', ({ metadata }) => {\n const relatedPrompt = metadata.relatedPrompt as RelatedPrompt;\n const taggingInfo: TaggingRequest = relatedPrompt.tagging\n ?.toolingDisplayClickTagging as TaggingRequest;\n\n taggingInfo.params.productId = 'EXPAND';\n taggingInfo.params.title = relatedPrompt.suggestionText;\n taggingInfo.params.url = 'none';\n\n return taggingInfo;\n }),\n ({ metadata }) => metadata?.selectedPrompt === -1\n );\n}\n\n/**\n * Factory helper to create a wire to set the queryTagging.\n *\n * @returns A new wire for the query of a result of a queryPreview.\n *\n * @public\n */\nexport function createSetQueryTaggingFromQueryPreview(): Wire<Taggable> {\n return filter(\n wireCommit(\n 'setQueryTaggingInfo',\n ({ metadata: { queryTagging } }) => queryTagging as TaggingRequest\n ),\n ({ metadata: { queryTagging } }) => !!queryTagging\n );\n}\n\n/**\n * Wiring configuration for the {@link TaggingXModule | tagging module}.\n *\n * @internal\n */\nexport const taggingWiring = createWiring({\n ConsentProvided: {\n setConsent\n },\n ConsentChanged: {\n clearSessionWire\n },\n PDPIsLoaded: {\n moveClickedResultToSessionWire\n },\n ResultURLTrackingEnabled: {\n moveClickedResultToSessionWire\n },\n SearchTaggingChanged: {\n setQueryTaggingInfo\n },\n SearchTaggingReceived: {\n trackQueryWire\n },\n TrackableElementDisplayed: {\n trackElementDisplayedWire\n },\n TaggingConfigProvided: {\n setTaggingConfig\n },\n UserClickedAResult: {\n trackResultClickedWire,\n storeClickedResultWire\n },\n UserClickedResultAddToCart: {\n trackAddToCartWire,\n trackResultClickedWire,\n storeAddToCartWire\n },\n UserClickedPDPAddToCart: {\n trackAddToCartFromSessionStorage\n },\n UserClickedABanner: {\n trackBannerClickedWire\n },\n UserClickedADisplayResult: {\n trackDisplayClickedWire,\n setQueryTaggingFromQueryPreview\n },\n SemanticQueriesResponseChanged: {\n trackNoResultsQueryWithSemanticsWireDebounced\n },\n ModuleRegistered: {\n setNoResultsTaggingEnabledWire\n },\n UserClickedARelatedPromptResult: {\n trackToolingDisplayClickedWire\n },\n UserClickedARelatedPromptAdd2Cart: {\n trackToolingAdd2CartWire\n },\n UserSelectedARelatedPrompt: {\n trackRelatedPromptToolingDisplayClickWire\n }\n});\n"],"names":[],"mappings":";;;;;;;;;;AAsBA;;;;AAIG;AACH,MAAM,UAAU,GAAG,SAAS,CAAC;AAE7B;;AAEG;AACH,MAAM,cAAc,GAAG,kBAAkB,CAAC,UAAU,CAAC,CAAC;AAEtD;;;;AAIG;AACH,MAAM,UAAU,GAAG,oBAAoB,CAAC,UAAU,CAAC,CAAC;AAEpD;;;;AAIG;AACH,MAAM,YAAY,GAAG,sBAAsB,CAAC,UAAU,CAAC,CAAC;AAExD;;AAEG;AACH,MAAM,gCAAgC,GAAG,yBAAyB,CAAC,qBAAqB,CAAC,QAAQ,CAAC,CAAC;AAEnG;;AAEG;AACH,MAAM,0BAA0B,GAAG,WAAW,CAAC,6BAA6B,CAAC,QAAQ,CAAC,CAAC;AAEvF;;;;AAIG;AACH,MAAM,sBAAsB,GAAG,0BAA0B,CAAC,oBAAoB,CAAC,CAAC;AAEhF;;;;AAIG;AACH,MAAM,kBAAkB,GAAG,0BAA0B,CAAC,gBAAgB,CAAC,CAAC;AAExE;;;;AAIG;AACH,MAAM,8BAA8B,GAAG,OAAO,CAC5C,0BAA0B,CAAC,sBAAsB,CAAC,EAClD,CAAC,OAAe,KAAI;IAClB,OAAO,OAAO,KAAK,KAAK,GAAG,SAAS,GAAG,OAAO,CAAC;AACjD,CAAC,CACF,CAAC;AAEF;;;;AAIG;AACH,MAAM,gCAAgC,GAAG,0BAA0B,CAAC,gBAAgB,CAAC,CAAC;AAEtF;;;;AAIG;AACH,MAAM,gBAAgB,GAAG,MAAM,CAC7B,gCAAgC,CAAC,gBAAg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AE;QACzB,uBAAuB;QACvB,+BAA+B;AAChC,KAAA;AACD,IAAA,8BAA8B,EAAE;QAC9B,6CAA6C;AAC9C,KAAA;AACD,IAAA,gBAAgB,EAAE;QAChB,8BAA8B;AAC/B,KAAA;AACD,IAAA,+BAA+B,EAAE;QAC/B,8BAA8B;AAC/B,KAAA;AACD,IAAA,iCAAiC,EAAE;QACjC,wBAAwB;AACzB,KAAA;AACD,IAAA,0BAA0B,EAAE;QAC1B,yCAAyC;AAC1C,KAAA;AACF,CAAA;;;;"}
|
|
1
|
+
{"version":3,"file":"wiring.js","sources":["../../../../src/x-modules/tagging/wiring.ts"],"sourcesContent":["import {\n RelatedPrompt,\n Result,\n SemanticQuery,\n Taggable,\n Tagging,\n TaggingRequest\n} from '@empathyco/x-types';\nimport { DefaultSessionService } from '@empathyco/x-utils';\nimport {\n namespacedWireCommit,\n namespacedWireDispatch\n} from '../../wiring/namespaced-wires.factory';\nimport { namespacedDebounce } from '../../wiring/namespaced-wires.operators';\nimport { wireService, wireServiceWithoutPayload } from '../../wiring/wires.factory';\nimport { filter, mapWire } from '../../wiring/wires.operators';\nimport { DisplayWireMetadata, Wire } from '../../wiring/wiring.types';\nimport { createWiring } from '../../wiring/wiring.utils';\nimport { createOrigin } from '../../utils/index';\nimport { FeatureLocation } from '../../types/index';\nimport { DefaultExternalTaggingService } from './service/external-tagging.service';\n\n/**\n * `tagging` {@link XModuleName | XModule name}.\n *\n * @internal\n */\nconst moduleName = 'tagging';\n\n/**\n * Debounce function for the module.\n */\nconst moduleDebounce = namespacedDebounce(moduleName);\n\n/**\n * WireCommit for {@link TaggingXModule}.\n *\n * @internal\n */\nconst wireCommit = namespacedWireCommit(moduleName);\n\n/**\n * WireDispatch for {@link TaggingXModule}.\n *\n * @internal\n */\nconst wireDispatch = namespacedWireDispatch(moduleName);\n\n/**\n * Wires without payload factory for {@link DefaultSessionService}.\n */\nconst wireSessionServiceWithoutPayload = wireServiceWithoutPayload(DefaultSessionService.instance);\n\n/**\n * Wires factory for {@link DefaultExternalTaggingService}.\n */\nconst wireExternalTaggingService = wireService(DefaultExternalTaggingService.instance);\n\n/**\n * Stores the given result on the local storage.\n *\n * @public\n */\nconst storeClickedResultWire = wireExternalTaggingService('storeResultClicked');\n\n/**\n * Stores the result added to cart on the local storage.\n *\n * @public\n */\nconst storeAddToCartWire = wireExternalTaggingService('storeAddToCart');\n\n/**\n * Moves the result information from the local storage to session storage.\n *\n * @public\n */\nconst moveClickedResultToSessionWire = mapWire(\n wireExternalTaggingService('moveToSessionStorage'),\n (payload: string) => {\n return payload === 'url' ? undefined : payload;\n }\n);\n\n/**\n * Triggers the add to cart tracking.\n *\n * @public\n */\nconst trackAddToCartFromSessionStorage = wireExternalTaggingService('trackAddToCart');\n\n/**\n * Clears the session id.\n *\n * @public\n */\nconst clearSessionWire = filter(\n wireSessionServiceWithoutPayload('clearSessionId'),\n ({ eventPayload: consent }) => !consent\n);\n\n/**\n * Sets the tagging state `consent`.\n *\n * @public\n */\nexport const setConsent = wireCommit('setConsent');\n\n/**\n * Sets the tagging state `noResultsTaggingEnabled`.\n *\n * @public\n */\nexport const setNoResultsTaggingEnabledWire = wireCommit('setNoResultsTaggingEnabled');\n\n/**\n * Sets the tagging config state.\n *\n * @public\n */\nexport const setTaggingConfig = wireCommit('mergeConfig');\n\n/**\n * Tracks the tagging of the query.\n *\n * @public\n */\nexport const trackQueryWire = filter(\n wireDispatch('track'),\n ({ eventPayload, store }) =>\n ((eventPayload as TaggingRequest).params.totalHits as number) > 0 ||\n !store.state.x.tagging.noResultsTaggingEnabled\n);\n\n/**\n * Sets the tagging state of the query tagging info using a debounce which ends if the user\n * accepts a query.\n *\n * @public\n */\nexport const setQueryTaggingInfo = moduleDebounce(\n wireCommit('setQueryTaggingInfo'),\n ({ state }) => state.config.queryTaggingDebounceMs,\n {\n cancelOn: 'UserClearedQuery',\n forceOn: [\n 'UserClickedAResult',\n 'UserClickedAPromoted',\n 'UserClickedABanner',\n 'UserClickedARedirection',\n 'UserReachedResultsListEnd'\n ]\n }\n);\n\n/**\n * Sets the tagging state of the query tagging info using.\n *\n * @public\n */\nexport const setQueryTaggingFromQueryPreview = createSetQueryTaggingFromQueryPreview();\n\n/**\n * Tracks the tagging of the result.\n *\n * @public\n */\nexport const trackResultClickedWire = createTrackWire('click');\n\n/**\n * Tracks the tagging of the banner.\n *\n * @public\n */\nexport const trackBannerClickedWire = createTrackWire('click');\n\n/**\n * Performs a track of a result added to the cart.\n *\n * @public\n */\nexport const trackAddToCartWire = createTrackWire('add2cart');\n\n/**\n * Performs a track of a display result being clicked.\n *\n * @public\n */\nexport const trackDisplayClickedWire = createTrackDisplayWire('displayClick');\n\n/**\n * Performs a track of a display result being clicked.\n *\n * @public\n */\nexport const trackToolingDisplayClickedWire = createTrackToolingDisplayWire();\n\n/**\n * Performs a track of a display result being clicked.\n *\n * @public\n */\nexport const trackToolingAdd2CartWire = createTrackToolingAdd2CartWire();\n\n/**\n * Performs a track of a clicked related prompt.\n *\n * @public\n */\nexport const trackRelatedPromptToolingDisplayClickWire =\n createTrackRelatedPromptToolingDisplayClickWire();\n\n/**\n * Performs a track of a display element appearing.\n *\n * @public\n */\nexport const trackElementDisplayedWire = createTrackDisplayWire('display');\n\n/**\n * Factory helper to create a wire for the track of a taggable element.\n *\n * @param property - Key of the tagging object to track.\n * @returns A new wire for the given property of the taggable element.\n *\n * @public\n */\nexport function createTrackWire(property: keyof Tagging): Wire<Taggable> {\n return filter(\n wireDispatch('track', ({ eventPayload: { tagging }, metadata: { location } }) => {\n const taggingInfo: TaggingRequest = tagging[property];\n taggingInfo.params.location = location as string;\n return taggingInfo;\n }),\n ({ eventPayload: { tagging }, metadata: { ignoreInModules } }) =>\n !!tagging?.[property] && !ignoreInModules?.includes(moduleName)\n );\n}\n\n/**\n * Performs a track of a query with no results that used semantics as fallback.\n * The totalHits will be changed to -1 if semantic queries are found in order to differentiate\n * it from scenarios where the user encounters a no-results page without any semantic queries.\n *\n * @public\n */\nexport const trackNoResultsQueryWithSemanticsWire = filter(\n wireDispatch('track', ({ eventPayload, state }) => {\n const { queryTaggingInfo } = state;\n const totalHits = (eventPayload as SemanticQuery[]).length > 0 ? -1 : 0;\n return {\n params: { ...queryTaggingInfo?.params, totalHits },\n url: queryTaggingInfo?.url ?? ''\n };\n }),\n ({ store }) => Number(store.state.x.tagging.queryTaggingInfo?.params.totalHits)! === 0\n);\n\n/**.\n * Debounced version of {@link trackNoResultsQueryWithSemanticsWire}\n *\n * @public\n */\nexport const trackNoResultsQueryWithSemanticsWireDebounced = moduleDebounce(\n trackNoResultsQueryWithSemanticsWire,\n ({ state }) => state.config.queryTaggingDebounceMs,\n { cancelOn: 'QueryPreviewUnmounted' }\n);\n\n/**\n * Factory helper to create a wire for the track of the display click.\n *\n * @param property - Key of the tagging object to track.\n * @returns A new wire for the display click of the taggable element.\n *\n * @public\n */\nexport function createTrackDisplayWire(property: keyof Tagging): Wire<Taggable> {\n return filter(\n wireDispatch('track', ({ eventPayload: { tagging }, metadata }) => {\n const taggingInfo: TaggingRequest = tagging[property];\n const location = metadata.location as FeatureLocation;\n\n taggingInfo.params.location = location;\n taggingInfo.params.displayFamily = createOrigin({\n feature: metadata.feature,\n location\n })!;\n taggingInfo.params.q = (metadata as DisplayWireMetadata).displayOriginalQuery;\n\n return taggingInfo;\n }),\n ({ eventPayload: { tagging } }) => !!tagging?.[property]?.url\n );\n}\n\n/**\n * Update the tooling tagging params with the result information.\n *\n * @param taggingRequest - The tooling tagging request to be updated.\n * @param result - The clicked result.\n * @returns The tagging request updated.\n *\n * @internal\n */\nfunction updateToolingTaggingWithResult(\n taggingRequest: TaggingRequest,\n result: Result\n): TaggingRequest {\n taggingRequest.params.productId = result.id;\n taggingRequest.params.title = result.name!;\n taggingRequest.params.url = result.url!;\n\n return taggingRequest;\n}\n\n/**\n * Factory helper to create a wire for the track of the tooling display click.\n *\n * @returns A new wire for the tooling display click of the taggable element.\n *\n * @public\n */\nexport function createTrackToolingDisplayWire(): Wire<Taggable> {\n return filter(\n wireDispatch('track', ({ eventPayload, metadata }) => {\n const taggingInfo: TaggingRequest = metadata.toolingTagging as TaggingRequest;\n const resultInfo = eventPayload as Result;\n\n updateToolingTaggingWithResult(taggingInfo, resultInfo);\n\n return taggingInfo;\n }),\n ({ metadata }) => !!metadata?.toolingTagging\n );\n}\n\n/**\n * Factory helper to create a wire for the track of the tooling display add to cart.\n *\n * @returns A new wire for the tooling display add to cart of the taggable element.\n *\n * @public\n */\nexport function createTrackToolingAdd2CartWire(): Wire<Taggable> {\n return filter(\n wireDispatch('track', ({ eventPayload, metadata }) => {\n const taggingInfo: TaggingRequest = metadata.toolingAdd2CartTagging as TaggingRequest;\n const resultInfo = eventPayload as Result;\n\n updateToolingTaggingWithResult(taggingInfo, resultInfo);\n\n return taggingInfo;\n }),\n ({ metadata }) => !!metadata?.toolingAdd2CartTagging\n );\n}\n\n/**\n * Factory helper to create a wire for the track of the tooling display click in a related prompt.\n *\n * @returns A new wire for the tooling display click of the taggable element.\n *\n * @public\n */\nexport function createTrackRelatedPromptToolingDisplayClickWire() {\n return filter(\n wireDispatch('track', ({ metadata }) => {\n const relatedPrompt = metadata.relatedPrompt as RelatedPrompt;\n const taggingInfo = relatedPrompt.tagging!.toolingDisplayClickTagging as TaggingRequest;\n\n taggingInfo.params.productId = 'EXPAND';\n taggingInfo.params.title = relatedPrompt.suggestionText;\n taggingInfo.params.url = 'none';\n\n return taggingInfo;\n }),\n ({ metadata }) => {\n const relatedPrompt = metadata.relatedPrompt as RelatedPrompt | undefined;\n const isUnselected = metadata?.selectedPrompt === -1;\n const taggingInfo = relatedPrompt?.tagging?.toolingDisplayClickTagging;\n return isUnselected && !!taggingInfo;\n }\n );\n}\n\n/**\n * Factory helper to create a wire to set the queryTagging.\n *\n * @returns A new wire for the query of a result of a queryPreview.\n *\n * @public\n */\nexport function createSetQueryTaggingFromQueryPreview(): Wire<Taggable> {\n return filter(\n wireCommit(\n 'setQueryTaggingInfo',\n ({ metadata: { queryTagging } }) => queryTagging as TaggingRequest\n ),\n ({ metadata: { queryTagging } }) => !!queryTagging\n );\n}\n\n/**\n * Wiring configuration for the {@link TaggingXModule | tagging module}.\n *\n * @internal\n */\nexport const taggingWiring = createWiring({\n ConsentProvided: {\n setConsent\n },\n ConsentChanged: {\n clearSessionWire\n },\n PDPIsLoaded: {\n moveClickedResultToSessionWire\n },\n ResultURLTrackingEnabled: {\n moveClickedResultToSessionWire\n },\n SearchTaggingChanged: {\n setQueryTaggingInfo\n },\n SearchTaggingReceived: {\n trackQueryWire\n },\n TrackableElementDisplayed: {\n trackElementDisplayedWire\n },\n TaggingConfigProvided: {\n setTaggingConfig\n },\n UserClickedAResult: {\n trackResultClickedWire,\n storeClickedResultWire\n },\n UserClickedResultAddToCart: {\n trackAddToCartWire,\n trackResultClickedWire,\n storeAddToCartWire\n },\n UserClickedPDPAddToCart: {\n trackAddToCartFromSessionStorage\n },\n UserClickedABanner: {\n trackBannerClickedWire\n },\n UserClickedADisplayResult: {\n trackDisplayClickedWire,\n setQueryTaggingFromQueryPreview\n },\n SemanticQueriesResponseChanged: {\n trackNoResultsQueryWithSemanticsWireDebounced\n },\n ModuleRegistered: {\n setNoResultsTaggingEnabledWire\n },\n UserClickedARelatedPromptResult: {\n trackToolingDisplayClickedWire\n },\n UserClickedARelatedPromptAdd2Cart: {\n trackToolingAdd2CartWire\n },\n UserSelectedARelatedPrompt: {\n trackRelatedPromptToolingDisplayClickWire\n }\n});\n"],"names":[],"mappings":";;;;;;;;;;AAsBA;;;;AAIG;AACH,MAAM,UAAU,GAAG,SAAS,CAAC;AAE7B;;AAEG;AACH,MAAM,cAAc,GAAG,kBAAkB,CAAC,UAAU,CAAC,CAAC;AAEtD;;;;AAIG;AACH,MAAM,UAAU,GAAG,oBAAoB,CAAC,UAAU,CAAC,CAAC;AAEpD;;;;AAIG;AACH,MAAM,YAAY,GAAG,sBAAsB,CAAC,UAAU,CAAC,CAAC;AAExD;;AAEG;AACH,MAAM,gCAAgC,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"file":"url-handler.vue.js","sources":["../../../../../src/x-modules/url/components/url-handler.vue"],"sourcesContent":["<template>\n <GlobalEvents @pageshow=\"onPageShow\" @popstate=\"emitEvents\" target=\"window\" />\n</template>\n\n<script lang=\"ts\">\n import { Dictionary, objectFilter } from '@empathyco/x-utils';\n import { computed, defineComponent, inject, onMounted, ref } from 'vue';\n import { GlobalEvents } from 'vue-global-events';\n import { FeatureLocation } from '../../../types/origin';\n import { UrlParams } from '../../../types/url-params';\n import { isArrayEmpty } from '../../../utils/array';\n import { WireMetadata } from '../../../wiring/wiring.types';\n import { SnippetConfig } from '../../../x-installer/api/api.types';\n import { initialUrlState } from '../store/initial-state';\n import { UrlParamValue } from '../store/types';\n import { urlXModule } from '../x-module';\n import { use$x } from '../../../composables/use-$x';\n import { useState } from '../../../composables/use-state';\n\n interface ParsedUrlParams {\n all: UrlParams;\n extra: Dictionary<unknown>;\n }\n\n /**\n * This component manages the browser URL parameters to preserve them through reloads and browser\n * history navigation. It allow to configure the default url parameter names using its attributes.\n * This component doesn't render elements to the DOM.\n *\n * @public\n */\n export default defineComponent({\n name: 'UrlHandler',\n components: {\n GlobalEvents\n },\n xModule: urlXModule.name,\n setup: function (props, { attrs }) {\n const $x = use$x();\n\n const initialExtraParams = useState('url', ['initialExtraParams']).initialExtraParams;\n\n /**\n * The {@link SnippetConfig} provided by an ancestor.\n *\n * @internal\n */\n const snippetConfig = inject<SnippetConfig | undefined>('snippetConfig');\n\n /**\n * Flag to know if the params were already loaded from the URL.\n *\n * @internal\n */\n const urlLoaded = ref(false);\n\n /**\n * The page URL. It is used to compare against the current URL to check navigation state.\n *\n * @internal\n */\n const url = ref<URL | undefined>(undefined);\n\n /**\n * Flag to know if the page has been persisted by the browser's back-forward cache.\n *\n * @internal\n */\n const isPagePersisted = ref(false);\n\n /**\n * Computed to know which params we must get from URL. It gets the params names from the initial\n * state, to get all default params names, and also from the `$attrs` to get the extra params\n * names to take into account.\n *\n * @returns An array with the name of the params.\n *\n * @internal\n */\n const managedParamsNames = computed(() => {\n return Object.keys({ ...initialUrlState, ...attrs });\n });\n\n /**\n * Returns the mapping of the param keys used in the URL is configured through $attrs. This way\n * we can support any param and extra param, no matters its name.\n *\n * @param paramName - The param name to get the Url key.\n * @returns The key used in the URL for the `paramName` passed.\n *\n * @internal\n */\n const getUrlKey = (paramName: string): string => {\n const paramValue = attrs[paramName];\n return typeof paramValue === 'string' ? paramValue : paramName;\n };\n\n /**\n * Deletes all the parameters in the passed URL.\n *\n * @param url - The URL to remove parameters from.\n * @internal\n */\n const deleteUrlParameters = (url: URL): void => {\n managedParamsNames.value.forEach(paramName =>\n url.searchParams.delete(getUrlKey(paramName))\n );\n };\n\n /**\n * Sorts the params in a tuple array [key,value] to generate always the same URL with the params\n * in the same order.\n *\n * @param urlParams - The {@link UrlParams} to sort.\n * @returns An array of tuples with the key-value of each paramter, sorted by key.\n * @internal\n */\n const sortParams = (urlParams: UrlParams): Array<[string, unknown]> => {\n return Object.entries(urlParams).sort(([param1], [param2]) => {\n return param1 < param2 ? -1 : 1;\n });\n };\n\n /**\n * Set all the provided parameters to the url with the mapped key.\n *\n * @param url - The current URL.\n * @param urlParams - The list of parameters to add.\n * @remarks The params are filtered because there maybe received extra params which will not be\n * managed by URL. This is defined by the `managedParamsNames` computed. Also, the parameters\n * are sorted Alphabetically to produce always the same URL with the same parameters.This is\n * important for SEO purposes.\n *\n * @internal\n */\n const setUrlParameters = (url: URL, urlParams: UrlParams): void => {\n // Only when there is a query the rest of the parameters are valid.\n if (!urlParams.query) {\n return;\n }\n const filteredParams = objectFilter(urlParams, paramName =>\n managedParamsNames.value.includes(paramName as string)\n );\n const sortedParameters = sortParams(filteredParams);\n sortedParameters.forEach(([paramName, paramValue]) => {\n const urlParamKey = getUrlKey(paramName);\n if (Array.isArray(paramValue)) {\n paramValue.forEach(value => {\n url.searchParams.append(urlParamKey, String(value));\n });\n } else {\n url.searchParams.set(urlParamKey, String(paramValue));\n }\n });\n };\n\n /**\n * Updates the browser URL with the passed `newUrlParams` and using the browser history method\n * passed as `historyMethod`. It only updates the browser history if the new URL is different\n * from the current.\n *\n * @param newUrlParams - The new params to add to the browser URL.\n * @param historyMethod - The browser history method used to add the new URL.\n *\n * @internal\n */\n const updateUrl = (\n newUrlParams: UrlParams,\n historyMethod: History['pushState'] | History['replaceState']\n ): void => {\n if (urlLoaded.value) {\n const newUrl = new URL(window.location.href);\n deleteUrlParameters(newUrl);\n setUrlParameters(newUrl, newUrlParams);\n\n // Normalize '+' characters into '%20' for spaces in url params.\n newUrl.search = newUrl.search.replace(/\\+/g, '%20');\n\n if (newUrl.href !== window.location.href) {\n historyMethod({ ...window.history.state }, document.title, newUrl.href);\n }\n url.value = newUrl;\n }\n };\n\n /**\n * Updates the browser URL with the new {@link UrlParams} using the history `pushState` method.\n *\n * @param newUrlParams - The new params to update browser URL.\n */\n $x.on('PushableUrlStateUpdated', false).subscribe((newUrlParams: UrlParams) => {\n updateUrl(newUrlParams, window.history.pushState.bind(window.history));\n });\n\n /**\n * Updates the browser URL with the new {@link UrlParams} using the history `replaceState`\n * method.\n *\n * @param newUrlParams - The new params to update browser URL.\n */\n $x.on('ReplaceableUrlStateUpdated', false).subscribe((newUrlParams: UrlParams) => {\n updateUrl(newUrlParams, window.history.replaceState.bind(window.history));\n });\n\n /**\n * Handler of the\n * [pageshow](https://developer.mozilla.org/en-US/docs/Web/API/Window/pageshow_event)\n * event.\n *\n * @remarks The pageshow event is listened to check if the browser has performed a navigation\n * using the back-forward cache. This information is available in the\n * PageTransitionEvent.persisted property.\n *\n * @param event - The page transition event.\n * @internal\n */\n const onPageShow = (event: PageTransitionEvent) => {\n isPagePersisted.value = event.persisted;\n if (event.persisted) {\n // The internal url is reset due to the back-forward cache storing the previous value which\n // is no longer valid.\n url.value = undefined;\n }\n };\n\n /**\n * Returns the URL param value parsed depending on its type in the initial store state. As we\n * can not know what type can have an extra param, all extra params are parsed as strings. We\n * know if it is an extra param because it is not in the initial state.\n *\n * @param name - The name of the param in {@link UrlParams}.\n * @param value - The `URLSearchParams` value as an arry of strings.\n * @returns The parsed value.\n *\n * @internal\n */\n const parseUrlParam = (name: string, value: string[]): UrlParamValue => {\n switch (typeof initialUrlState[name]) {\n case 'number':\n return Number(value[0]);\n case 'boolean':\n return value[0].toLowerCase() === 'true';\n case 'string':\n return value[0];\n default:\n // array\n return value;\n }\n };\n\n /**\n * Gets the {@link UrlParams} from the URL, including only the params defined by `paramsNames`.\n *\n * @returns ParsedUrlParams obtained from URL.\n * @internal\n */\n const parseUrlParams = (): ParsedUrlParams => {\n const urlSearchParams = new URL(window.location.href).searchParams;\n return managedParamsNames.value.reduce<ParsedUrlParams>(\n (params, name) => {\n const urlKey = getUrlKey(name);\n if (urlSearchParams.has(urlKey)) {\n if (name in initialUrlState) {\n const urlValue = urlSearchParams.getAll(urlKey);\n params.all[name] = parseUrlParam(name, urlValue);\n } else {\n params.all[name] = params.extra[name] = urlSearchParams.get(urlKey);\n }\n }\n return params;\n },\n { all: { ...initialUrlState }, extra: { ...initialExtraParams.value } }\n );\n };\n\n /**\n * Check if the navigation is from a product page.\n *\n * @remarks Due to Safari 14 not supporting the new and standard PerformanceNavigationTiming\n * API, we are falling back to the deprecated one, PerformanceNavigation. We also fallback to\n * this API whenever we get a navigationType equal to reload, because Safari has a bug that the\n * navigationType is permanently set to reload after you have reload the page and it never\n * resets. As some browsers have a back-forward cache implemented, we also take into account if\n * the page is persisted.\n *\n * @returns True if the navigation is from a product page, false otherwise.\n * @internal\n */\n const isNavigatingFromPdp = (): boolean => {\n const isPagePersistedValue = isPagePersisted.value;\n const navigationEntries = window.performance.getEntriesByType('navigation');\n const navigationType = (navigationEntries[0] as PerformanceNavigationTiming)?.type;\n const useFallbackStrategy =\n !navigationEntries.length &&\n (isArrayEmpty(navigationEntries) || navigationType === 'reload');\n\n // Reset internal isPagePersisted property value\n isPagePersisted.value = false;\n\n if (useFallbackStrategy) {\n const isNavigatingInSpa = !!snippetConfig?.isSpa && navigationType === 'navigate';\n return navigationType === 'back_forward' || isNavigatingInSpa || isPagePersistedValue;\n } else {\n const isNavigatingInSpa = !!snippetConfig?.isSpa && navigationType === 'navigate';\n return navigationType === 'back_forward' || isNavigatingInSpa || isPagePersistedValue;\n }\n };\n\n /**\n * Detects the {@link FeatureLocation} used to build the\n * {@link QueryOriginInit} data.\n *\n * @returns The {@link FeatureLocation}.\n * @internal\n */\n const detectLocation = (): FeatureLocation => {\n const currentUrl = new URL(window.location.href);\n const previousUrl = url.value;\n url.value = currentUrl;\n\n const isInternalNavigation =\n previousUrl?.search !== currentUrl.search &&\n previousUrl?.pathname === currentUrl.pathname;\n if (isInternalNavigation) {\n return 'url_history';\n }\n\n if (isNavigatingFromPdp()) {\n return 'url_history_pdp';\n }\n\n return 'external';\n };\n\n /**\n * Creates the wire metadata to include in every emitted {@link XEvent}.\n *\n * @returns The {@link WireMetadata}.\n * @internal\n */\n const createWireMetadata = (): Pick<WireMetadata, 'feature' | 'location'> => {\n return {\n feature: 'url',\n location: detectLocation()\n };\n };\n\n /**\n * Emits the {@link UrlXEvents.ParamsLoadedFromUrl} XEvent,\n * the {@link UrlXEvents.ExtraParamsLoadedFromUrl} XEvent and, if there is query, also emits\n * the {@link XEventsTypes.UserOpenXProgrammatically}.\n *\n * @internal\n */\n const emitEvents = () => {\n const { all, extra } = parseUrlParams();\n const metadata = createWireMetadata();\n $x.emit('ParamsLoadedFromUrl', all, metadata);\n $x.emit('ExtraParamsLoadedFromUrl', extra, metadata);\n if (all.query) {\n $x.emit('UserOpenXProgrammatically', undefined, metadata);\n }\n urlLoaded.value = true;\n };\n\n /**\n * To emit the Url events just when the URL is load, and before the components mounted events\n * and state changes, we do it in the created of this component.\n */\n onMounted(() => {\n emitEvents();\n });\n\n return {\n onPageShow,\n emitEvents\n };\n }\n });\n</script>\n\n<docs lang=\"mdx\">\n## Events\n\nThis component emits the following events:\n\n- [`ParamsLoadedFromUrl`](https://github.com/empathyco/x/blob/main/packages/x-components/src/wiring/events.types.ts)\n- [`ExtraParamsLoadedFromUrl`](https://github.com/empathyco/x/blob/main/packages/x-components/src/wiring/events.types.ts)\n- [`UserOpenXProgrammatically`](https://github.com/empathyco/x/blob/main/packages/x-components/src/wiring/events.types.ts)\n\n## See it in action\n\nThis component manages the browser URL parameters to preserve them through reloads and browser\nhistory navigation. It allow to configure the default url parameter names using its attributes. This\ncomponent doesn't render elements to the DOM.\n\n_Try to make some requests and take a look to the url!_\n\n```vue\n<template>\n <UrlHandler />\n</template>\n\n<script>\n import { UrlHandler } from '@empathyco/x-components/url-handler';\n\n export default {\n name: 'UrlHandlerDemo',\n components: {\n UrlHandler\n }\n };\n</script>\n```\n\n### Play with props\n\nIn this example, the `UrlHandler` component changes the following query parameter names:\n\n- `query` to be `q`.\n- `page` to be `p`.\n- `filter` to be `f`\n- `sort` to be `s`\n\n_Try to make some requests and take a look to the url!_\n\n```vue\n<template>\n <UrlHandler query=\"q\" page=\"p\" filter=\"f\" sort=\"s\" />\n</template>\n\n<script>\n import { UrlHandler } from '@empathyco/x-components/url-handler';\n\n export default {\n name: 'UrlHandlerDemo',\n components: {\n UrlHandler\n }\n };\n</script>\n```\n\n### Play with events\n\nThe `UrlHandler` will emit the `ParamsLoadedFromUrl` when the page is loaded.\n\nThe `UrlHandler` will emit the `ExtraParamsLoadedFromUrl` when the page is loaded with an extra\nparam configured and with a value in URL.\n\nThe `UrlHandler` will emit the `UserOpenXProgrammatically` when the page is loaded with a query in\nthe URL.\n</docs>\n"],"names":["_resolveComponent","_openBlock","_createBlock"],"mappings":";;;;;kCACEA,gBAA8E,CAAA,cAAA,CAAA,CAAA;AAAxC,EAAA,OAAAC,SAAA,EAAoB,EAAAC,WAAA,CAAA,uBAAA,EAAA;AAAA,IAAE,YAAO,IAAQ,CAAA,UAAA;AAAA,IAAA,UAAA,EAAA,IAAA,CAAA,UAAA;;;;;;;;"}
|
|
1
|
+
{"version":3,"file":"url-handler.vue.js","sources":["../../../../../src/x-modules/url/components/url-handler.vue"],"sourcesContent":["<template>\n <GlobalEvents @pageshow=\"onPageShow\" @popstate=\"emitEvents\" target=\"window\" />\n</template>\n\n<script lang=\"ts\">\n import { Dictionary, objectFilter } from '@empathyco/x-utils';\n import { computed, defineComponent, inject, onMounted, ref } from 'vue';\n import { GlobalEvents } from 'vue-global-events';\n import { FeatureLocation } from '../../../types/origin';\n import { UrlParams } from '../../../types/url-params';\n import { isArrayEmpty } from '../../../utils/array';\n import { WireMetadata } from '../../../wiring/wiring.types';\n import { SnippetConfig } from '../../../x-installer/api/api.types';\n import { initialUrlState } from '../store/initial-state';\n import { UrlParamValue } from '../store/types';\n import { urlXModule } from '../x-module';\n import { use$x } from '../../../composables/use-$x';\n import { useState } from '../../../composables/use-state';\n\n interface ParsedUrlParams {\n all: UrlParams;\n extra: Dictionary<unknown>;\n }\n\n /**\n * This component manages the browser URL parameters to preserve them through reloads and browser\n * history navigation. It allow to configure the default url parameter names using its attributes.\n * This component doesn't render elements to the DOM.\n *\n * @public\n */\n export default defineComponent({\n name: 'UrlHandler',\n components: {\n GlobalEvents\n },\n xModule: urlXModule.name,\n setup: function (_, { attrs }) {\n const $x = use$x();\n\n const initialExtraParams = useState('url', ['initialExtraParams']).initialExtraParams;\n\n /**\n * The {@link SnippetConfig} provided by an ancestor.\n *\n * @internal\n */\n const snippetConfig = inject<SnippetConfig | undefined>('snippetConfig');\n\n /**\n * Flag to know if the params were already loaded from the URL.\n *\n * @internal\n */\n const urlLoaded = ref(false);\n\n /**\n * The page URL. It is used to compare against the current URL to check navigation state.\n *\n * @internal\n */\n const url = ref<URL | undefined>(undefined);\n\n /**\n * Flag to know if the page has been persisted by the browser's back-forward cache.\n *\n * @internal\n */\n const isPagePersisted = ref(false);\n\n /**\n * Computed to know which params we must get from URL. It gets the params names from the initial\n * state, to get all default params names, and also from the `$attrs` to get the extra params\n * names to take into account.\n *\n * @returns An array with the name of the params.\n *\n * @internal\n */\n const managedParamsNames = computed(() => Object.keys({ ...initialUrlState, ...attrs }));\n\n /**\n * Returns the mapping of the param keys used in the URL is configured through $attrs. This way\n * we can support any param and extra param, no matters its name.\n *\n * @param paramName - The param name to get the Url key.\n * @returns The key used in the URL for the `paramName` passed.\n *\n * @internal\n */\n const getUrlKey = (paramName: string) => {\n const paramValue = attrs[paramName];\n return typeof paramValue === 'string' ? paramValue : paramName;\n };\n\n /**\n * Deletes all the parameters in the passed URL.\n *\n * @param url - The URL to remove parameters from.\n * @internal\n */\n const deleteUrlParameters = (url: URL) => {\n managedParamsNames.value.forEach(paramName =>\n url.searchParams.delete(getUrlKey(paramName))\n );\n };\n\n /**\n * Sorts the params in a tuple array [key,value] to generate always the same URL with the params\n * in the same order.\n *\n * @param urlParams - The {@link UrlParams} to sort.\n * @returns An array of tuples with the key-value of each paramter, sorted by key.\n * @internal\n */\n const sortParams = (urlParams: UrlParams): Array<[string, unknown]> => {\n return Object.entries(urlParams).sort(([param1], [param2]) => {\n return param1 < param2 ? -1 : 1;\n });\n };\n\n /**\n * Set all the provided parameters to the url with the mapped key.\n *\n * @param url - The current URL.\n * @param urlParams - The list of parameters to add.\n * @remarks The params are filtered because there maybe received extra params which will not be\n * managed by URL. This is defined by the `managedParamsNames` computed. Also, the parameters\n * are sorted Alphabetically to produce always the same URL with the same parameters.This is\n * important for SEO purposes.\n *\n * @internal\n */\n const setUrlParameters = (url: URL, urlParams: UrlParams): void => {\n // Only when there is a query the rest of the parameters are valid.\n if (!urlParams.query) {\n return;\n }\n const filteredParams = objectFilter(urlParams, paramName =>\n managedParamsNames.value.includes(paramName as string)\n );\n const sortedParameters = sortParams(filteredParams);\n sortedParameters.forEach(([paramName, paramValue]) => {\n const urlParamKey = getUrlKey(paramName);\n if (Array.isArray(paramValue)) {\n paramValue.forEach(value => {\n url.searchParams.append(urlParamKey, String(value));\n });\n } else {\n url.searchParams.set(urlParamKey, String(paramValue));\n }\n });\n };\n\n /**\n * Updates the browser URL with the passed `newUrlParams` and using the browser history method\n * passed as `historyMethod`. It only updates the browser history if the new URL is different\n * from the current.\n *\n * @param newUrlParams - The new params to add to the browser URL.\n * @param historyMethod - The browser history method used to add the new URL.\n *\n * @internal\n */\n const updateUrl = (\n newUrlParams: UrlParams,\n historyMethod: History['pushState'] | History['replaceState']\n ): void => {\n if (urlLoaded.value) {\n const newUrl = new URL(window.location.href);\n deleteUrlParameters(newUrl);\n setUrlParameters(newUrl, newUrlParams);\n\n // Normalize '+' characters into '%20' for spaces in url params.\n newUrl.search = newUrl.search.replace(/\\+/g, '%20');\n\n if (newUrl.href !== window.location.href) {\n historyMethod({ ...window.history.state }, document.title, newUrl.href);\n }\n url.value = newUrl;\n }\n };\n\n /**\n * Updates the browser URL with the new {@link UrlParams} using the history `pushState` method.\n *\n * @param newUrlParams - The new params to update browser URL.\n */\n $x.on('PushableUrlStateUpdated', false).subscribe((newUrlParams: UrlParams) => {\n updateUrl(newUrlParams, window.history.pushState.bind(window.history));\n });\n\n /**\n * Updates the browser URL with the new {@link UrlParams} using the history `replaceState`\n * method.\n *\n * @param newUrlParams - The new params to update browser URL.\n */\n $x.on('ReplaceableUrlStateUpdated', false).subscribe((newUrlParams: UrlParams) => {\n updateUrl(newUrlParams, window.history.replaceState.bind(window.history));\n });\n\n /**\n * Handler of the\n * [pageshow](https://developer.mozilla.org/en-US/docs/Web/API/Window/pageshow_event)\n * event.\n *\n * @remarks The pageshow event is listened to check if the browser has performed a navigation\n * using the back-forward cache. This information is available in the\n * PageTransitionEvent.persisted property.\n *\n * @param event - The page transition event.\n * @internal\n */\n const onPageShow = (event: PageTransitionEvent) => {\n isPagePersisted.value = event.persisted;\n if (event.persisted) {\n // The internal url is reset due to the back-forward cache storing the previous value which\n // is no longer valid.\n url.value = undefined;\n }\n };\n\n /**\n * Returns the URL param value parsed depending on its type in the initial store state. As we\n * can not know what type can have an extra param, all extra params are parsed as strings. We\n * know if it is an extra param because it is not in the initial state.\n *\n * @param name - The name of the param in {@link UrlParams}.\n * @param value - The `URLSearchParams` value as an arry of strings.\n * @returns The parsed value.\n *\n * @internal\n */\n const parseUrlParam = (name: string, value: string[]): UrlParamValue => {\n switch (typeof initialUrlState[name]) {\n case 'number':\n return Number(value[0]);\n case 'boolean':\n return value[0].toLowerCase() === 'true';\n case 'string':\n return value[0];\n default:\n // array\n return value;\n }\n };\n\n /**\n * Gets the {@link UrlParams} from the URL, including only the params defined by `paramsNames`.\n *\n * @returns ParsedUrlParams obtained from URL.\n * @internal\n */\n const parseUrlParams = (): ParsedUrlParams => {\n const urlSearchParams = new URL(window.location.href).searchParams;\n return managedParamsNames.value.reduce<ParsedUrlParams>(\n (params, name) => {\n const urlKey = getUrlKey(name);\n if (urlSearchParams.has(urlKey)) {\n if (name in initialUrlState) {\n const urlValue = urlSearchParams.getAll(urlKey);\n params.all[name] = parseUrlParam(name, urlValue);\n } else {\n params.all[name] = params.extra[name] = urlSearchParams.get(urlKey);\n }\n }\n return params;\n },\n { all: { ...initialUrlState }, extra: { ...initialExtraParams.value } }\n );\n };\n\n /**\n * Check if the navigation is from a product page.\n *\n * @remarks Due to Safari 14 not supporting the new and standard PerformanceNavigationTiming\n * API, we are falling back to the deprecated one, PerformanceNavigation. We also fallback to\n * this API whenever we get a navigationType equal to reload, because Safari has a bug that the\n * navigationType is permanently set to reload after you have reload the page and it never\n * resets. As some browsers have a back-forward cache implemented, we also take into account if\n * the page is persisted.\n *\n * @returns True if the navigation is from a product page, false otherwise.\n * @internal\n */\n const isNavigatingFromPdp = (): boolean => {\n const isPagePersistedValue = isPagePersisted.value;\n const navigationEntries = window.performance.getEntriesByType('navigation');\n const navigationType = (navigationEntries[0] as PerformanceNavigationTiming)?.type;\n const useFallbackStrategy =\n !navigationEntries.length &&\n (isArrayEmpty(navigationEntries) || navigationType === 'reload');\n\n // Reset internal isPagePersisted property value\n isPagePersisted.value = false;\n\n if (useFallbackStrategy) {\n const isNavigatingInSpa = !!snippetConfig?.isSpa && navigationType === 'navigate';\n return navigationType === 'back_forward' || isNavigatingInSpa || isPagePersistedValue;\n } else {\n const isNavigatingInSpa = !!snippetConfig?.isSpa && navigationType === 'navigate';\n return navigationType === 'back_forward' || isNavigatingInSpa || isPagePersistedValue;\n }\n };\n\n /**\n * Detects the {@link FeatureLocation} used to build the\n * {@link QueryOriginInit} data.\n *\n * @returns The {@link FeatureLocation}.\n * @internal\n */\n const detectLocation = (): FeatureLocation => {\n const currentUrl = new URL(window.location.href);\n const previousUrl = url.value;\n url.value = currentUrl;\n\n const isInternalNavigation =\n previousUrl?.search !== currentUrl.search &&\n previousUrl?.pathname === currentUrl.pathname;\n if (isInternalNavigation) {\n return 'url_history';\n }\n\n if (isNavigatingFromPdp()) {\n return 'url_history_pdp';\n }\n\n return 'external';\n };\n\n /**\n * Creates the wire metadata to include in every emitted {@link XEvent}.\n *\n * @returns The {@link WireMetadata}.\n * @internal\n */\n const createWireMetadata = (): Pick<WireMetadata, 'feature' | 'location'> => {\n return {\n feature: 'url',\n location: detectLocation()\n };\n };\n\n /**\n * Emits the {@link UrlXEvents.ParamsLoadedFromUrl} XEvent,\n * the {@link UrlXEvents.ExtraParamsLoadedFromUrl} XEvent and, if there is query, also emits\n * the {@link XEventsTypes.UserOpenXProgrammatically}.\n *\n * @internal\n */\n const emitEvents = () => {\n const { all, extra } = parseUrlParams();\n const metadata = createWireMetadata();\n $x.emit('ParamsLoadedFromUrl', all, metadata);\n $x.emit('ExtraParamsLoadedFromUrl', extra, metadata);\n if (all.query) {\n $x.emit('UserOpenXProgrammatically', undefined, metadata);\n }\n urlLoaded.value = true;\n };\n\n /**\n * To emit the Url events just when the URL is load, and before the components mounted events\n * and state changes, we do it in the created of this component.\n */\n onMounted(() => {\n emitEvents();\n });\n\n return {\n onPageShow,\n emitEvents\n };\n }\n });\n</script>\n\n<docs lang=\"mdx\">\n## Events\n\nThis component emits the following events:\n\n- [`ParamsLoadedFromUrl`](https://github.com/empathyco/x/blob/main/packages/x-components/src/wiring/events.types.ts)\n- [`ExtraParamsLoadedFromUrl`](https://github.com/empathyco/x/blob/main/packages/x-components/src/wiring/events.types.ts)\n- [`UserOpenXProgrammatically`](https://github.com/empathyco/x/blob/main/packages/x-components/src/wiring/events.types.ts)\n\n## See it in action\n\nThis component manages the browser URL parameters to preserve them through reloads and browser\nhistory navigation. It allow to configure the default url parameter names using its attributes. This\ncomponent doesn't render elements to the DOM.\n\n_Try to make some requests and take a look to the url!_\n\n```vue\n<template>\n <UrlHandler />\n</template>\n\n<script>\n import { UrlHandler } from '@empathyco/x-components/url-handler';\n\n export default {\n name: 'UrlHandlerDemo',\n components: {\n UrlHandler\n }\n };\n</script>\n```\n\n### Play with props\n\nIn this example, the `UrlHandler` component changes the following query parameter names:\n\n- `query` to be `q`.\n- `page` to be `p`.\n- `filter` to be `f`\n- `sort` to be `s`\n\n_Try to make some requests and take a look to the url!_\n\n```vue\n<template>\n <UrlHandler query=\"q\" page=\"p\" filter=\"f\" sort=\"s\" />\n</template>\n\n<script>\n import { UrlHandler } from '@empathyco/x-components/url-handler';\n\n export default {\n name: 'UrlHandlerDemo',\n components: {\n UrlHandler\n }\n };\n</script>\n```\n\n### Play with events\n\nThe `UrlHandler` will emit the `ParamsLoadedFromUrl` when the page is loaded.\n\nThe `UrlHandler` will emit the `ExtraParamsLoadedFromUrl` when the page is loaded with an extra\nparam configured and with a value in URL.\n\nThe `UrlHandler` will emit the `UserOpenXProgrammatically` when the page is loaded with a query in\nthe URL.\n</docs>\n"],"names":["_resolveComponent","_openBlock","_createBlock"],"mappings":";;;;;kCACEA,gBAA8E,CAAA,cAAA,CAAA,CAAA;AAAxC,EAAA,OAAAC,SAAA,EAAoB,EAAAC,WAAA,CAAA,uBAAA,EAAA;AAAA,IAAE,YAAO,IAAQ,CAAA,UAAA;AAAA,IAAA,UAAA,EAAA,IAAA,CAAA,UAAA;;;;;;;;"}
|
|
@@ -20,7 +20,7 @@ var _sfc_main = defineComponent({
|
|
|
20
20
|
GlobalEvents
|
|
21
21
|
},
|
|
22
22
|
xModule: urlXModule.name,
|
|
23
|
-
setup: function (
|
|
23
|
+
setup: function (_, { attrs }) {
|
|
24
24
|
const $x = use$x();
|
|
25
25
|
const initialExtraParams = useState('url', ['initialExtraParams']).initialExtraParams;
|
|
26
26
|
/**
|
|
@@ -56,9 +56,7 @@ var _sfc_main = defineComponent({
|
|
|
56
56
|
*
|
|
57
57
|
* @internal
|
|
58
58
|
*/
|
|
59
|
-
const managedParamsNames = computed(() => {
|
|
60
|
-
return Object.keys({ ...initialUrlState, ...attrs });
|
|
61
|
-
});
|
|
59
|
+
const managedParamsNames = computed(() => Object.keys({ ...initialUrlState, ...attrs }));
|
|
62
60
|
/**
|
|
63
61
|
* Returns the mapping of the param keys used in the URL is configured through $attrs. This way
|
|
64
62
|
* we can support any param and extra param, no matters its name.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"url-handler.vue2.js","sources":["../../../../../src/x-modules/url/components/url-handler.vue"],"sourcesContent":["<template>\n <GlobalEvents @pageshow=\"onPageShow\" @popstate=\"emitEvents\" target=\"window\" />\n</template>\n\n<script lang=\"ts\">\n import { Dictionary, objectFilter } from '@empathyco/x-utils';\n import { computed, defineComponent, inject, onMounted, ref } from 'vue';\n import { GlobalEvents } from 'vue-global-events';\n import { FeatureLocation } from '../../../types/origin';\n import { UrlParams } from '../../../types/url-params';\n import { isArrayEmpty } from '../../../utils/array';\n import { WireMetadata } from '../../../wiring/wiring.types';\n import { SnippetConfig } from '../../../x-installer/api/api.types';\n import { initialUrlState } from '../store/initial-state';\n import { UrlParamValue } from '../store/types';\n import { urlXModule } from '../x-module';\n import { use$x } from '../../../composables/use-$x';\n import { useState } from '../../../composables/use-state';\n\n interface ParsedUrlParams {\n all: UrlParams;\n extra: Dictionary<unknown>;\n }\n\n /**\n * This component manages the browser URL parameters to preserve them through reloads and browser\n * history navigation. It allow to configure the default url parameter names using its attributes.\n * This component doesn't render elements to the DOM.\n *\n * @public\n */\n export default defineComponent({\n name: 'UrlHandler',\n components: {\n GlobalEvents\n },\n xModule: urlXModule.name,\n setup: function (props, { attrs }) {\n const $x = use$x();\n\n const initialExtraParams = useState('url', ['initialExtraParams']).initialExtraParams;\n\n /**\n * The {@link SnippetConfig} provided by an ancestor.\n *\n * @internal\n */\n const snippetConfig = inject<SnippetConfig | undefined>('snippetConfig');\n\n /**\n * Flag to know if the params were already loaded from the URL.\n *\n * @internal\n */\n const urlLoaded = ref(false);\n\n /**\n * The page URL. It is used to compare against the current URL to check navigation state.\n *\n * @internal\n */\n const url = ref<URL | undefined>(undefined);\n\n /**\n * Flag to know if the page has been persisted by the browser's back-forward cache.\n *\n * @internal\n */\n const isPagePersisted = ref(false);\n\n /**\n * Computed to know which params we must get from URL. It gets the params names from the initial\n * state, to get all default params names, and also from the `$attrs` to get the extra params\n * names to take into account.\n *\n * @returns An array with the name of the params.\n *\n * @internal\n */\n const managedParamsNames = computed(() => {\n return Object.keys({ ...initialUrlState, ...attrs });\n });\n\n /**\n * Returns the mapping of the param keys used in the URL is configured through $attrs. This way\n * we can support any param and extra param, no matters its name.\n *\n * @param paramName - The param name to get the Url key.\n * @returns The key used in the URL for the `paramName` passed.\n *\n * @internal\n */\n const getUrlKey = (paramName: string): string => {\n const paramValue = attrs[paramName];\n return typeof paramValue === 'string' ? paramValue : paramName;\n };\n\n /**\n * Deletes all the parameters in the passed URL.\n *\n * @param url - The URL to remove parameters from.\n * @internal\n */\n const deleteUrlParameters = (url: URL): void => {\n managedParamsNames.value.forEach(paramName =>\n url.searchParams.delete(getUrlKey(paramName))\n );\n };\n\n /**\n * Sorts the params in a tuple array [key,value] to generate always the same URL with the params\n * in the same order.\n *\n * @param urlParams - The {@link UrlParams} to sort.\n * @returns An array of tuples with the key-value of each paramter, sorted by key.\n * @internal\n */\n const sortParams = (urlParams: UrlParams): Array<[string, unknown]> => {\n return Object.entries(urlParams).sort(([param1], [param2]) => {\n return param1 < param2 ? -1 : 1;\n });\n };\n\n /**\n * Set all the provided parameters to the url with the mapped key.\n *\n * @param url - The current URL.\n * @param urlParams - The list of parameters to add.\n * @remarks The params are filtered because there maybe received extra params which will not be\n * managed by URL. This is defined by the `managedParamsNames` computed. Also, the parameters\n * are sorted Alphabetically to produce always the same URL with the same parameters.This is\n * important for SEO purposes.\n *\n * @internal\n */\n const setUrlParameters = (url: URL, urlParams: UrlParams): void => {\n // Only when there is a query the rest of the parameters are valid.\n if (!urlParams.query) {\n return;\n }\n const filteredParams = objectFilter(urlParams, paramName =>\n managedParamsNames.value.includes(paramName as string)\n );\n const sortedParameters = sortParams(filteredParams);\n sortedParameters.forEach(([paramName, paramValue]) => {\n const urlParamKey = getUrlKey(paramName);\n if (Array.isArray(paramValue)) {\n paramValue.forEach(value => {\n url.searchParams.append(urlParamKey, String(value));\n });\n } else {\n url.searchParams.set(urlParamKey, String(paramValue));\n }\n });\n };\n\n /**\n * Updates the browser URL with the passed `newUrlParams` and using the browser history method\n * passed as `historyMethod`. It only updates the browser history if the new URL is different\n * from the current.\n *\n * @param newUrlParams - The new params to add to the browser URL.\n * @param historyMethod - The browser history method used to add the new URL.\n *\n * @internal\n */\n const updateUrl = (\n newUrlParams: UrlParams,\n historyMethod: History['pushState'] | History['replaceState']\n ): void => {\n if (urlLoaded.value) {\n const newUrl = new URL(window.location.href);\n deleteUrlParameters(newUrl);\n setUrlParameters(newUrl, newUrlParams);\n\n // Normalize '+' characters into '%20' for spaces in url params.\n newUrl.search = newUrl.search.replace(/\\+/g, '%20');\n\n if (newUrl.href !== window.location.href) {\n historyMethod({ ...window.history.state }, document.title, newUrl.href);\n }\n url.value = newUrl;\n }\n };\n\n /**\n * Updates the browser URL with the new {@link UrlParams} using the history `pushState` method.\n *\n * @param newUrlParams - The new params to update browser URL.\n */\n $x.on('PushableUrlStateUpdated', false).subscribe((newUrlParams: UrlParams) => {\n updateUrl(newUrlParams, window.history.pushState.bind(window.history));\n });\n\n /**\n * Updates the browser URL with the new {@link UrlParams} using the history `replaceState`\n * method.\n *\n * @param newUrlParams - The new params to update browser URL.\n */\n $x.on('ReplaceableUrlStateUpdated', false).subscribe((newUrlParams: UrlParams) => {\n updateUrl(newUrlParams, window.history.replaceState.bind(window.history));\n });\n\n /**\n * Handler of the\n * [pageshow](https://developer.mozilla.org/en-US/docs/Web/API/Window/pageshow_event)\n * event.\n *\n * @remarks The pageshow event is listened to check if the browser has performed a navigation\n * using the back-forward cache. This information is available in the\n * PageTransitionEvent.persisted property.\n *\n * @param event - The page transition event.\n * @internal\n */\n const onPageShow = (event: PageTransitionEvent) => {\n isPagePersisted.value = event.persisted;\n if (event.persisted) {\n // The internal url is reset due to the back-forward cache storing the previous value which\n // is no longer valid.\n url.value = undefined;\n }\n };\n\n /**\n * Returns the URL param value parsed depending on its type in the initial store state. As we\n * can not know what type can have an extra param, all extra params are parsed as strings. We\n * know if it is an extra param because it is not in the initial state.\n *\n * @param name - The name of the param in {@link UrlParams}.\n * @param value - The `URLSearchParams` value as an arry of strings.\n * @returns The parsed value.\n *\n * @internal\n */\n const parseUrlParam = (name: string, value: string[]): UrlParamValue => {\n switch (typeof initialUrlState[name]) {\n case 'number':\n return Number(value[0]);\n case 'boolean':\n return value[0].toLowerCase() === 'true';\n case 'string':\n return value[0];\n default:\n // array\n return value;\n }\n };\n\n /**\n * Gets the {@link UrlParams} from the URL, including only the params defined by `paramsNames`.\n *\n * @returns ParsedUrlParams obtained from URL.\n * @internal\n */\n const parseUrlParams = (): ParsedUrlParams => {\n const urlSearchParams = new URL(window.location.href).searchParams;\n return managedParamsNames.value.reduce<ParsedUrlParams>(\n (params, name) => {\n const urlKey = getUrlKey(name);\n if (urlSearchParams.has(urlKey)) {\n if (name in initialUrlState) {\n const urlValue = urlSearchParams.getAll(urlKey);\n params.all[name] = parseUrlParam(name, urlValue);\n } else {\n params.all[name] = params.extra[name] = urlSearchParams.get(urlKey);\n }\n }\n return params;\n },\n { all: { ...initialUrlState }, extra: { ...initialExtraParams.value } }\n );\n };\n\n /**\n * Check if the navigation is from a product page.\n *\n * @remarks Due to Safari 14 not supporting the new and standard PerformanceNavigationTiming\n * API, we are falling back to the deprecated one, PerformanceNavigation. We also fallback to\n * this API whenever we get a navigationType equal to reload, because Safari has a bug that the\n * navigationType is permanently set to reload after you have reload the page and it never\n * resets. As some browsers have a back-forward cache implemented, we also take into account if\n * the page is persisted.\n *\n * @returns True if the navigation is from a product page, false otherwise.\n * @internal\n */\n const isNavigatingFromPdp = (): boolean => {\n const isPagePersistedValue = isPagePersisted.value;\n const navigationEntries = window.performance.getEntriesByType('navigation');\n const navigationType = (navigationEntries[0] as PerformanceNavigationTiming)?.type;\n const useFallbackStrategy =\n !navigationEntries.length &&\n (isArrayEmpty(navigationEntries) || navigationType === 'reload');\n\n // Reset internal isPagePersisted property value\n isPagePersisted.value = false;\n\n if (useFallbackStrategy) {\n const isNavigatingInSpa = !!snippetConfig?.isSpa && navigationType === 'navigate';\n return navigationType === 'back_forward' || isNavigatingInSpa || isPagePersistedValue;\n } else {\n const isNavigatingInSpa = !!snippetConfig?.isSpa && navigationType === 'navigate';\n return navigationType === 'back_forward' || isNavigatingInSpa || isPagePersistedValue;\n }\n };\n\n /**\n * Detects the {@link FeatureLocation} used to build the\n * {@link QueryOriginInit} data.\n *\n * @returns The {@link FeatureLocation}.\n * @internal\n */\n const detectLocation = (): FeatureLocation => {\n const currentUrl = new URL(window.location.href);\n const previousUrl = url.value;\n url.value = currentUrl;\n\n const isInternalNavigation =\n previousUrl?.search !== currentUrl.search &&\n previousUrl?.pathname === currentUrl.pathname;\n if (isInternalNavigation) {\n return 'url_history';\n }\n\n if (isNavigatingFromPdp()) {\n return 'url_history_pdp';\n }\n\n return 'external';\n };\n\n /**\n * Creates the wire metadata to include in every emitted {@link XEvent}.\n *\n * @returns The {@link WireMetadata}.\n * @internal\n */\n const createWireMetadata = (): Pick<WireMetadata, 'feature' | 'location'> => {\n return {\n feature: 'url',\n location: detectLocation()\n };\n };\n\n /**\n * Emits the {@link UrlXEvents.ParamsLoadedFromUrl} XEvent,\n * the {@link UrlXEvents.ExtraParamsLoadedFromUrl} XEvent and, if there is query, also emits\n * the {@link XEventsTypes.UserOpenXProgrammatically}.\n *\n * @internal\n */\n const emitEvents = () => {\n const { all, extra } = parseUrlParams();\n const metadata = createWireMetadata();\n $x.emit('ParamsLoadedFromUrl', all, metadata);\n $x.emit('ExtraParamsLoadedFromUrl', extra, metadata);\n if (all.query) {\n $x.emit('UserOpenXProgrammatically', undefined, metadata);\n }\n urlLoaded.value = true;\n };\n\n /**\n * To emit the Url events just when the URL is load, and before the components mounted events\n * and state changes, we do it in the created of this component.\n */\n onMounted(() => {\n emitEvents();\n });\n\n return {\n onPageShow,\n emitEvents\n };\n }\n });\n</script>\n\n<docs lang=\"mdx\">\n## Events\n\nThis component emits the following events:\n\n- [`ParamsLoadedFromUrl`](https://github.com/empathyco/x/blob/main/packages/x-components/src/wiring/events.types.ts)\n- [`ExtraParamsLoadedFromUrl`](https://github.com/empathyco/x/blob/main/packages/x-components/src/wiring/events.types.ts)\n- [`UserOpenXProgrammatically`](https://github.com/empathyco/x/blob/main/packages/x-components/src/wiring/events.types.ts)\n\n## See it in action\n\nThis component manages the browser URL parameters to preserve them through reloads and browser\nhistory navigation. It allow to configure the default url parameter names using its attributes. This\ncomponent doesn't render elements to the DOM.\n\n_Try to make some requests and take a look to the url!_\n\n```vue\n<template>\n <UrlHandler />\n</template>\n\n<script>\n import { UrlHandler } from '@empathyco/x-components/url-handler';\n\n export default {\n name: 'UrlHandlerDemo',\n components: {\n UrlHandler\n }\n };\n</script>\n```\n\n### Play with props\n\nIn this example, the `UrlHandler` component changes the following query parameter names:\n\n- `query` to be `q`.\n- `page` to be `p`.\n- `filter` to be `f`\n- `sort` to be `s`\n\n_Try to make some requests and take a look to the url!_\n\n```vue\n<template>\n <UrlHandler query=\"q\" page=\"p\" filter=\"f\" sort=\"s\" />\n</template>\n\n<script>\n import { UrlHandler } from '@empathyco/x-components/url-handler';\n\n export default {\n name: 'UrlHandlerDemo',\n components: {\n UrlHandler\n }\n };\n</script>\n```\n\n### Play with events\n\nThe `UrlHandler` will emit the `ParamsLoadedFromUrl` when the page is loaded.\n\nThe `UrlHandler` will emit the `ExtraParamsLoadedFromUrl` when the page is loaded with an extra\nparam configured and with a value in URL.\n\nThe `UrlHandler` will emit the `UserOpenXProgrammatically` when the page is loaded with a query in\nthe URL.\n</docs>\n"],"names":[],"mappings":";;;;;;;;;AAwBE;;;;;;AAME;AACF,gBAAe,eAAe,CAAC;AAC7B,IAAA,IAAI,EAAE,YAAY;AAClB,IAAA,UAAU,EAAE;QACV,YAAW;AACZ,KAAA;IACD,OAAO,EAAE,UAAU,CAAC,IAAI;AACxB,IAAA,KAAK,EAAE,UAAU,KAAK,EAAE,EAAE,KAAM,EAAC,EAAA;AAC/B,QAAA,MAAM,EAAC,GAAI,KAAK,EAAE,CAAA;AAElB,QAAA,MAAM,kBAAmB,GAAE,QAAQ,CAAC,KAAK,EAAE,CAAC,oBAAoB,CAAC,CAAC,CAAC,kBAAkB,CAAA;AAErF;;;;AAIE;AACF,QAAA,MAAM,aAAY,GAAI,MAAM,CAA4B,eAAe,CAAC,CAAA;AAExE;;;;AAIE;AACF,QAAA,MAAM,SAAU,GAAE,GAAG,CAAC,KAAK,CAAC,CAAA;AAE5B;;;;AAIE;AACF,QAAA,MAAM,GAAI,GAAE,GAAG,CAAkB,SAAS,CAAC,CAAA;AAE3C;;;;AAIE;AACF,QAAA,MAAM,eAAgB,GAAE,GAAG,CAAC,KAAK,CAAC,CAAA;AAElC;;;;;;;;AAQE;AACF,QAAA,MAAM,kBAAiB,GAAI,QAAQ,CAAC,MAAM;AACxC,YAAA,OAAO,MAAM,CAAC,IAAI,CAAC,EAAE,GAAG,eAAe,EAAE,GAAG,KAAM,EAAC,CAAC,CAAA;AACtD,SAAC,CAAC,CAAA;AAEF;;;;;;;;AAQE;AACF,QAAA,MAAM,SAAU,GAAE,CAAC,SAAiB,KAAa;AAC/C,YAAA,MAAM,UAAW,GAAE,KAAK,CAAC,SAAS,CAAC,CAAA;AACnC,YAAA,OAAO,OAAO,UAAW,KAAI,QAAS,G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,0BAA0B,EAAE,KAAK,EAAE,QAAQ,CAAC,CAAA;YACpD,IAAI,GAAG,CAAC,KAAK,EAAE;gBACb,EAAE,CAAC,IAAI,CAAC,2BAA2B,EAAE,SAAS,EAAE,QAAQ,CAAC,CAAA;AAC3D,aAAA;AACA,YAAA,SAAS,CAAC,KAAI,GAAI,IAAI,CAAA;AACxB,SAAC,CAAA;AAED;;;AAGE;QACF,SAAS,CAAC,MAAM;AACd,YAAA,UAAU,EAAE,CAAA;AACd,SAAC,CAAC,CAAA;QAEF,OAAO;YACL,UAAU;YACV,UAAS;SACV,CAAA;KACH;AACD,CAAA,CAAC;;;;"}
|
|
1
|
+
{"version":3,"file":"url-handler.vue2.js","sources":["../../../../../src/x-modules/url/components/url-handler.vue"],"sourcesContent":["<template>\n <GlobalEvents @pageshow=\"onPageShow\" @popstate=\"emitEvents\" target=\"window\" />\n</template>\n\n<script lang=\"ts\">\n import { Dictionary, objectFilter } from '@empathyco/x-utils';\n import { computed, defineComponent, inject, onMounted, ref } from 'vue';\n import { GlobalEvents } from 'vue-global-events';\n import { FeatureLocation } from '../../../types/origin';\n import { UrlParams } from '../../../types/url-params';\n import { isArrayEmpty } from '../../../utils/array';\n import { WireMetadata } from '../../../wiring/wiring.types';\n import { SnippetConfig } from '../../../x-installer/api/api.types';\n import { initialUrlState } from '../store/initial-state';\n import { UrlParamValue } from '../store/types';\n import { urlXModule } from '../x-module';\n import { use$x } from '../../../composables/use-$x';\n import { useState } from '../../../composables/use-state';\n\n interface ParsedUrlParams {\n all: UrlParams;\n extra: Dictionary<unknown>;\n }\n\n /**\n * This component manages the browser URL parameters to preserve them through reloads and browser\n * history navigation. It allow to configure the default url parameter names using its attributes.\n * This component doesn't render elements to the DOM.\n *\n * @public\n */\n export default defineComponent({\n name: 'UrlHandler',\n components: {\n GlobalEvents\n },\n xModule: urlXModule.name,\n setup: function (_, { attrs }) {\n const $x = use$x();\n\n const initialExtraParams = useState('url', ['initialExtraParams']).initialExtraParams;\n\n /**\n * The {@link SnippetConfig} provided by an ancestor.\n *\n * @internal\n */\n const snippetConfig = inject<SnippetConfig | undefined>('snippetConfig');\n\n /**\n * Flag to know if the params were already loaded from the URL.\n *\n * @internal\n */\n const urlLoaded = ref(false);\n\n /**\n * The page URL. It is used to compare against the current URL to check navigation state.\n *\n * @internal\n */\n const url = ref<URL | undefined>(undefined);\n\n /**\n * Flag to know if the page has been persisted by the browser's back-forward cache.\n *\n * @internal\n */\n const isPagePersisted = ref(false);\n\n /**\n * Computed to know which params we must get from URL. It gets the params names from the initial\n * state, to get all default params names, and also from the `$attrs` to get the extra params\n * names to take into account.\n *\n * @returns An array with the name of the params.\n *\n * @internal\n */\n const managedParamsNames = computed(() => Object.keys({ ...initialUrlState, ...attrs }));\n\n /**\n * Returns the mapping of the param keys used in the URL is configured through $attrs. This way\n * we can support any param and extra param, no matters its name.\n *\n * @param paramName - The param name to get the Url key.\n * @returns The key used in the URL for the `paramName` passed.\n *\n * @internal\n */\n const getUrlKey = (paramName: string) => {\n const paramValue = attrs[paramName];\n return typeof paramValue === 'string' ? paramValue : paramName;\n };\n\n /**\n * Deletes all the parameters in the passed URL.\n *\n * @param url - The URL to remove parameters from.\n * @internal\n */\n const deleteUrlParameters = (url: URL) => {\n managedParamsNames.value.forEach(paramName =>\n url.searchParams.delete(getUrlKey(paramName))\n );\n };\n\n /**\n * Sorts the params in a tuple array [key,value] to generate always the same URL with the params\n * in the same order.\n *\n * @param urlParams - The {@link UrlParams} to sort.\n * @returns An array of tuples with the key-value of each paramter, sorted by key.\n * @internal\n */\n const sortParams = (urlParams: UrlParams): Array<[string, unknown]> => {\n return Object.entries(urlParams).sort(([param1], [param2]) => {\n return param1 < param2 ? -1 : 1;\n });\n };\n\n /**\n * Set all the provided parameters to the url with the mapped key.\n *\n * @param url - The current URL.\n * @param urlParams - The list of parameters to add.\n * @remarks The params are filtered because there maybe received extra params which will not be\n * managed by URL. This is defined by the `managedParamsNames` computed. Also, the parameters\n * are sorted Alphabetically to produce always the same URL with the same parameters.This is\n * important for SEO purposes.\n *\n * @internal\n */\n const setUrlParameters = (url: URL, urlParams: UrlParams): void => {\n // Only when there is a query the rest of the parameters are valid.\n if (!urlParams.query) {\n return;\n }\n const filteredParams = objectFilter(urlParams, paramName =>\n managedParamsNames.value.includes(paramName as string)\n );\n const sortedParameters = sortParams(filteredParams);\n sortedParameters.forEach(([paramName, paramValue]) => {\n const urlParamKey = getUrlKey(paramName);\n if (Array.isArray(paramValue)) {\n paramValue.forEach(value => {\n url.searchParams.append(urlParamKey, String(value));\n });\n } else {\n url.searchParams.set(urlParamKey, String(paramValue));\n }\n });\n };\n\n /**\n * Updates the browser URL with the passed `newUrlParams` and using the browser history method\n * passed as `historyMethod`. It only updates the browser history if the new URL is different\n * from the current.\n *\n * @param newUrlParams - The new params to add to the browser URL.\n * @param historyMethod - The browser history method used to add the new URL.\n *\n * @internal\n */\n const updateUrl = (\n newUrlParams: UrlParams,\n historyMethod: History['pushState'] | History['replaceState']\n ): void => {\n if (urlLoaded.value) {\n const newUrl = new URL(window.location.href);\n deleteUrlParameters(newUrl);\n setUrlParameters(newUrl, newUrlParams);\n\n // Normalize '+' characters into '%20' for spaces in url params.\n newUrl.search = newUrl.search.replace(/\\+/g, '%20');\n\n if (newUrl.href !== window.location.href) {\n historyMethod({ ...window.history.state }, document.title, newUrl.href);\n }\n url.value = newUrl;\n }\n };\n\n /**\n * Updates the browser URL with the new {@link UrlParams} using the history `pushState` method.\n *\n * @param newUrlParams - The new params to update browser URL.\n */\n $x.on('PushableUrlStateUpdated', false).subscribe((newUrlParams: UrlParams) => {\n updateUrl(newUrlParams, window.history.pushState.bind(window.history));\n });\n\n /**\n * Updates the browser URL with the new {@link UrlParams} using the history `replaceState`\n * method.\n *\n * @param newUrlParams - The new params to update browser URL.\n */\n $x.on('ReplaceableUrlStateUpdated', false).subscribe((newUrlParams: UrlParams) => {\n updateUrl(newUrlParams, window.history.replaceState.bind(window.history));\n });\n\n /**\n * Handler of the\n * [pageshow](https://developer.mozilla.org/en-US/docs/Web/API/Window/pageshow_event)\n * event.\n *\n * @remarks The pageshow event is listened to check if the browser has performed a navigation\n * using the back-forward cache. This information is available in the\n * PageTransitionEvent.persisted property.\n *\n * @param event - The page transition event.\n * @internal\n */\n const onPageShow = (event: PageTransitionEvent) => {\n isPagePersisted.value = event.persisted;\n if (event.persisted) {\n // The internal url is reset due to the back-forward cache storing the previous value which\n // is no longer valid.\n url.value = undefined;\n }\n };\n\n /**\n * Returns the URL param value parsed depending on its type in the initial store state. As we\n * can not know what type can have an extra param, all extra params are parsed as strings. We\n * know if it is an extra param because it is not in the initial state.\n *\n * @param name - The name of the param in {@link UrlParams}.\n * @param value - The `URLSearchParams` value as an arry of strings.\n * @returns The parsed value.\n *\n * @internal\n */\n const parseUrlParam = (name: string, value: string[]): UrlParamValue => {\n switch (typeof initialUrlState[name]) {\n case 'number':\n return Number(value[0]);\n case 'boolean':\n return value[0].toLowerCase() === 'true';\n case 'string':\n return value[0];\n default:\n // array\n return value;\n }\n };\n\n /**\n * Gets the {@link UrlParams} from the URL, including only the params defined by `paramsNames`.\n *\n * @returns ParsedUrlParams obtained from URL.\n * @internal\n */\n const parseUrlParams = (): ParsedUrlParams => {\n const urlSearchParams = new URL(window.location.href).searchParams;\n return managedParamsNames.value.reduce<ParsedUrlParams>(\n (params, name) => {\n const urlKey = getUrlKey(name);\n if (urlSearchParams.has(urlKey)) {\n if (name in initialUrlState) {\n const urlValue = urlSearchParams.getAll(urlKey);\n params.all[name] = parseUrlParam(name, urlValue);\n } else {\n params.all[name] = params.extra[name] = urlSearchParams.get(urlKey);\n }\n }\n return params;\n },\n { all: { ...initialUrlState }, extra: { ...initialExtraParams.value } }\n );\n };\n\n /**\n * Check if the navigation is from a product page.\n *\n * @remarks Due to Safari 14 not supporting the new and standard PerformanceNavigationTiming\n * API, we are falling back to the deprecated one, PerformanceNavigation. We also fallback to\n * this API whenever we get a navigationType equal to reload, because Safari has a bug that the\n * navigationType is permanently set to reload after you have reload the page and it never\n * resets. As some browsers have a back-forward cache implemented, we also take into account if\n * the page is persisted.\n *\n * @returns True if the navigation is from a product page, false otherwise.\n * @internal\n */\n const isNavigatingFromPdp = (): boolean => {\n const isPagePersistedValue = isPagePersisted.value;\n const navigationEntries = window.performance.getEntriesByType('navigation');\n const navigationType = (navigationEntries[0] as PerformanceNavigationTiming)?.type;\n const useFallbackStrategy =\n !navigationEntries.length &&\n (isArrayEmpty(navigationEntries) || navigationType === 'reload');\n\n // Reset internal isPagePersisted property value\n isPagePersisted.value = false;\n\n if (useFallbackStrategy) {\n const isNavigatingInSpa = !!snippetConfig?.isSpa && navigationType === 'navigate';\n return navigationType === 'back_forward' || isNavigatingInSpa || isPagePersistedValue;\n } else {\n const isNavigatingInSpa = !!snippetConfig?.isSpa && navigationType === 'navigate';\n return navigationType === 'back_forward' || isNavigatingInSpa || isPagePersistedValue;\n }\n };\n\n /**\n * Detects the {@link FeatureLocation} used to build the\n * {@link QueryOriginInit} data.\n *\n * @returns The {@link FeatureLocation}.\n * @internal\n */\n const detectLocation = (): FeatureLocation => {\n const currentUrl = new URL(window.location.href);\n const previousUrl = url.value;\n url.value = currentUrl;\n\n const isInternalNavigation =\n previousUrl?.search !== currentUrl.search &&\n previousUrl?.pathname === currentUrl.pathname;\n if (isInternalNavigation) {\n return 'url_history';\n }\n\n if (isNavigatingFromPdp()) {\n return 'url_history_pdp';\n }\n\n return 'external';\n };\n\n /**\n * Creates the wire metadata to include in every emitted {@link XEvent}.\n *\n * @returns The {@link WireMetadata}.\n * @internal\n */\n const createWireMetadata = (): Pick<WireMetadata, 'feature' | 'location'> => {\n return {\n feature: 'url',\n location: detectLocation()\n };\n };\n\n /**\n * Emits the {@link UrlXEvents.ParamsLoadedFromUrl} XEvent,\n * the {@link UrlXEvents.ExtraParamsLoadedFromUrl} XEvent and, if there is query, also emits\n * the {@link XEventsTypes.UserOpenXProgrammatically}.\n *\n * @internal\n */\n const emitEvents = () => {\n const { all, extra } = parseUrlParams();\n const metadata = createWireMetadata();\n $x.emit('ParamsLoadedFromUrl', all, metadata);\n $x.emit('ExtraParamsLoadedFromUrl', extra, metadata);\n if (all.query) {\n $x.emit('UserOpenXProgrammatically', undefined, metadata);\n }\n urlLoaded.value = true;\n };\n\n /**\n * To emit the Url events just when the URL is load, and before the components mounted events\n * and state changes, we do it in the created of this component.\n */\n onMounted(() => {\n emitEvents();\n });\n\n return {\n onPageShow,\n emitEvents\n };\n }\n });\n</script>\n\n<docs lang=\"mdx\">\n## Events\n\nThis component emits the following events:\n\n- [`ParamsLoadedFromUrl`](https://github.com/empathyco/x/blob/main/packages/x-components/src/wiring/events.types.ts)\n- [`ExtraParamsLoadedFromUrl`](https://github.com/empathyco/x/blob/main/packages/x-components/src/wiring/events.types.ts)\n- [`UserOpenXProgrammatically`](https://github.com/empathyco/x/blob/main/packages/x-components/src/wiring/events.types.ts)\n\n## See it in action\n\nThis component manages the browser URL parameters to preserve them through reloads and browser\nhistory navigation. It allow to configure the default url parameter names using its attributes. This\ncomponent doesn't render elements to the DOM.\n\n_Try to make some requests and take a look to the url!_\n\n```vue\n<template>\n <UrlHandler />\n</template>\n\n<script>\n import { UrlHandler } from '@empathyco/x-components/url-handler';\n\n export default {\n name: 'UrlHandlerDemo',\n components: {\n UrlHandler\n }\n };\n</script>\n```\n\n### Play with props\n\nIn this example, the `UrlHandler` component changes the following query parameter names:\n\n- `query` to be `q`.\n- `page` to be `p`.\n- `filter` to be `f`\n- `sort` to be `s`\n\n_Try to make some requests and take a look to the url!_\n\n```vue\n<template>\n <UrlHandler query=\"q\" page=\"p\" filter=\"f\" sort=\"s\" />\n</template>\n\n<script>\n import { UrlHandler } from '@empathyco/x-components/url-handler';\n\n export default {\n name: 'UrlHandlerDemo',\n components: {\n UrlHandler\n }\n };\n</script>\n```\n\n### Play with events\n\nThe `UrlHandler` will emit the `ParamsLoadedFromUrl` when the page is loaded.\n\nThe `UrlHandler` will emit the `ExtraParamsLoadedFromUrl` when the page is loaded with an extra\nparam configured and with a value in URL.\n\nThe `UrlHandler` will emit the `UserOpenXProgrammatically` when the page is loaded with a query in\nthe URL.\n</docs>\n"],"names":[],"mappings":";;;;;;;;;AAwBE;;;;;;AAME;AACF,gBAAe,eAAe,CAAC;AAC7B,IAAA,IAAI,EAAE,YAAY;AAClB,IAAA,UAAU,EAAE;QACV,YAAW;AACZ,KAAA;IACD,OAAO,EAAE,UAAU,CAAC,IAAI;AACxB,IAAA,KAAK,EAAE,UAAU,CAAC,EAAE,EAAE,KAAM,EAAC,EAAA;AAC3B,QAAA,MAAM,EAAC,GAAI,KAAK,EAAE,CAAA;AAElB,QAAA,MAAM,kBAAmB,GAAE,QAAQ,CAAC,KAAK,EAAE,CAAC,oBAAoB,CAAC,CAAC,CAAC,kBAAkB,CAAA;AAErF;;;;AAIE;AACF,QAAA,MAAM,aAAY,GAAI,MAAM,CAA4B,eAAe,CAAC,CAAA;AAExE;;;;AAIE;AACF,QAAA,MAAM,SAAU,GAAE,GAAG,CAAC,KAAK,CAAC,CAAA;AAE5B;;;;AAIE;AACF,QAAA,MAAM,GAAI,GAAE,GAAG,CAAkB,SAAS,CAAC,CAAA;AAE3C;;;;AAIE;AACF,QAAA,MAAM,eAAgB,GAAE,GAAG,CAAC,KAAK,CAAC,CAAA;AAElC;;;;;;;;AAQE;QACF,MAAM,kBAAmB,GAAE,QAAQ,CAAC,MAAM,MAAM,CAAC,IAAI,CAAC,EAAE,GAAG,eAAe,EAAE,GAAG,KAAM,EAAC,CAAC,CAAC,CAAA;AAExF;;;;;;;;AAQE;AACF,QAAA,MAAM,SAAQ,GAAI,CAAC,SAAiB,KAAK;AACvC,YAAA,MAAM,UAAW,GAAE,KAAK,CAAC,SAAS,CAAC,CAAA;AACnC,YAAA,OAAO,OAAO,UAAW,KAAI,QAAS,GAAE,UAAS,GAAI,SAAS,CAAA;AAChE,SAAC,CAAA;AAED;;;;;AAKE;AACF,QAAA,MAAM,mBAAkB,GAAI,CAAC,GAAQ,KAAK;Y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AA2B,EAAE,SAAS,EAAE,QAAQ,CAAC,CAAA;AAC3D,aAAA;AACA,YAAA,SAAS,CAAC,KAAI,GAAI,IAAI,CAAA;AACxB,SAAC,CAAA;AAED;;;AAGE;QACF,SAAS,CAAC,MAAM;AACd,YAAA,UAAU,EAAE,CAAA;AACd,SAAC,CAAC,CAAA;QAEF,OAAO;YACL,UAAU;YACV,UAAS;SACV,CAAA;KACH;AACD,CAAA,CAAC;;;;"}
|
|
@@ -2,12 +2,11 @@ import { objectFilter } from '@empathyco/x-utils';
|
|
|
2
2
|
import { initialUrlState } from '../initial-state.js';
|
|
3
3
|
|
|
4
4
|
/**
|
|
5
|
-
* Default implementation for the
|
|
5
|
+
* Default implementation for the getter.
|
|
6
6
|
*
|
|
7
|
-
* @param state - Current
|
|
7
|
+
* @param state - Current state of the url module.
|
|
8
8
|
*
|
|
9
9
|
* @returns The url params.
|
|
10
|
-
*
|
|
11
10
|
* @public
|
|
12
11
|
*/
|
|
13
12
|
const urlParams = ({ initialExtraParams, ...params }) => objectFilter(params, (paramKey, paramValue) => {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"url-params.getter.js","sources":["../../../../../../src/x-modules/url/store/getters/url-params.getter.ts"],"sourcesContent":["import { objectFilter } from '@empathyco/x-utils';\nimport { initialUrlState } from '../initial-state';\nimport { UrlParamValue, UrlXStoreModule } from '../types';\n\n/**\n * Default implementation for the
|
|
1
|
+
{"version":3,"file":"url-params.getter.js","sources":["../../../../../../src/x-modules/url/store/getters/url-params.getter.ts"],"sourcesContent":["import { objectFilter } from '@empathyco/x-utils';\nimport { initialUrlState } from '../initial-state';\nimport { UrlParamValue, UrlXStoreModule } from '../types';\n\n/**\n * Default implementation for the getter.\n *\n * @param state - Current state of the url module.\n *\n * @returns The url params.\n * @public\n */\nexport const urlParams: UrlXStoreModule['getters']['urlParams'] = ({\n initialExtraParams,\n ...params\n}) =>\n objectFilter(params, (paramKey, paramValue) => {\n return paramKey in initialUrlState\n ? isNotDefaultValue(paramKey, paramValue, initialUrlState)\n : isNotEmptyParam(paramValue) && isNotDefaultValue(paramKey, paramValue, initialExtraParams);\n });\n\n/**\n * Checks if a parameter is not empty to avoid adding it to the URL.\n *\n * @param value - The value of the key parameter.\n *\n * @returns True if is not empty, False otherwise.\n */\nfunction isNotEmptyParam(value: UrlParamValue | unknown): boolean {\n return Array.isArray(value) ? value.length > 0 : value != null && value !== '';\n}\n\n/**\n * Checks if a parameter is not the default state value to avoid adding it to the URL.\n *\n * @param key - The key parameter.\n * @param value - The value of the key parameter.\n * @param defaultValues - The default values to compare.\n *\n * @returns True if is not the default state value, False otherwise.\n */\nfunction isNotDefaultValue<Key extends string | number, Value extends UrlParamValue | unknown>(\n key: Key,\n value: Value,\n defaultValues: Record<Key, Value>\n): boolean {\n return Array.isArray(value) ? value.length > 0 : defaultValues[key] !== value;\n}\n"],"names":[],"mappings":";;;AAIA;;;;;;;AAOG;MACU,SAAS,GAA4C,CAAC,EACjE,kBAAkB,EAClB,GAAG,MAAM,EACV,KACC,YAAY,CAAC,MAAM,EAAE,CAAC,QAAQ,EAAE,UAAU,KAAI;IAC5C,OAAO,QAAQ,IAAI,eAAe;UAC9B,iBAAiB,CAAC,QAAQ,EAAE,UAAU,EAAE,eAAe,CAAC;AAC1D,UAAE,eAAe,CAAC,UAAU,CAAC,IAAI,iBAAiB,CAAC,QAAQ,EAAE,UAAU,EAAE,kBAAkB,CAAC,CAAC;AACjG,CAAC,EAAE;AAEL;;;;;;AAMG;AACH,SAAS,eAAe,CAAC,KAA8B,EAAA;IACrD,OAAO,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,GAAG,KAAK,CAAC,MAAM,GAAG,CAAC,GAAG,KAAK,IAAI,IAAI,IAAI,KAAK,KAAK,EAAE,CAAC;AACjF,CAAC;AAED;;;;;;;;AAQG;AACH,SAAS,iBAAiB,CACxB,GAAQ,EACR,KAAY,EACZ,aAAiC,EAAA;IAEjC,OAAO,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,GAAG,KAAK,CAAC,MAAM,GAAG,CAAC,GAAG,aAAa,CAAC,GAAG,CAAC,KAAK,KAAK,CAAC;AAChF;;;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"initial-state.js","sources":["../../../../../src/x-modules/url/store/initial-state.ts"],"sourcesContent":["import { UrlParams } from '../../../types/url-params';\n\n/**\n * The initial state of the Url store module. This is exported and used in other parts of the code\n * to use as default values for {@link UrlState}.\n *\n * @internal\n */\nexport const initialUrlState: Readonly<UrlParams> = {\n query: '',\n page: 1,\n filter: [],\n sort: '',\n scroll: '',\n tag: []\n};\n"],"names":[],"mappings":"AAEA;;;;;AAKG;AACU,MAAA,eAAe,GAAwB;AAClD,IAAA,KAAK,EAAE,EAAE;AACT,IAAA,IAAI,EAAE,CAAC;AACP,IAAA,MAAM,EAAE,EAAE;AACV,IAAA,IAAI,EAAE,EAAE;AACR,IAAA,MAAM,EAAE,EAAE;AACV,IAAA,GAAG,EAAE,EAAE;;;;;"}
|
|
1
|
+
{"version":3,"file":"initial-state.js","sources":["../../../../../src/x-modules/url/store/initial-state.ts"],"sourcesContent":["import { UrlParams } from '../../../types/url-params';\n\n/**\n * The initial state of the Url store module. This is exported and used in other parts of the code\n * to use as default values for {@link UrlState}.\n *\n * @internal\n */\nexport const initialUrlState: Readonly<UrlParams> = {\n query: '',\n page: 1,\n filter: [],\n sort: '',\n scroll: '',\n tag: [],\n prompt: -1\n};\n"],"names":[],"mappings":"AAEA;;;;;AAKG;AACU,MAAA,eAAe,GAAwB;AAClD,IAAA,KAAK,EAAE,EAAE;AACT,IAAA,IAAI,EAAE,CAAC;AACP,IAAA,MAAM,EAAE,EAAE;AACV,IAAA,IAAI,EAAE,EAAE;AACR,IAAA,MAAM,EAAE,EAAE;AACV,IAAA,GAAG,EAAE,EAAE;IACP,MAAM,EAAE,CAAC,CAAC;;;;;"}
|
|
@@ -22,6 +22,9 @@ const urlXStoreModule = {
|
|
|
22
22
|
setRelatedTags(state, relatedTags) {
|
|
23
23
|
state.tag = relatedTags.map(relatedTag => relatedTag.tag);
|
|
24
24
|
},
|
|
25
|
+
setPrompt(state, prompt) {
|
|
26
|
+
state.prompt = prompt;
|
|
27
|
+
},
|
|
25
28
|
setFilters(state, newFilters) {
|
|
26
29
|
state.filter = newFilters.map(filter => filter.id);
|
|
27
30
|
},
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"module.js","sources":["../../../../../src/x-modules/url/store/module.ts"],"sourcesContent":["import { setQuery } from '../../../store/utils/query.utils';\nimport { urlParams } from './getters/url-params.getter';\nimport { initialUrlState } from './initial-state';\nimport { setParams } from './mutations/set-params.mutation';\nimport { UrlXStoreModule } from './types';\n\n/**\n * {@link XStoreModule} For the URL module.\n *\n * @internal\n */\nexport const urlXStoreModule: UrlXStoreModule = {\n state: () => ({\n ...initialUrlState,\n initialExtraParams: {}\n }),\n getters: {\n urlParams\n },\n mutations: {\n setParams,\n setQuery,\n setRelatedTags(state, relatedTags) {\n state.tag = relatedTags.map(relatedTag => relatedTag.tag);\n },\n setFilters(state, newFilters) {\n state.filter = newFilters.map(filter => filter.id as string);\n },\n setPage(state, page) {\n state.page = page;\n },\n setSort(state, sort) {\n state.sort = sort;\n },\n setInitialExtraParams(state, extraParams) {\n state.initialExtraParams = extraParams;\n },\n setScroll(state, scroll) {\n state.scroll = scroll;\n }\n },\n actions: {}\n};\n"],"names":[],"mappings":";;;;;AAMA;;;;AAIG;AACU,MAAA,eAAe,GAAoB;AAC9C,IAAA,KAAK,EAAE,OAAO;AACZ,QAAA,GAAG,eAAe;AAClB,QAAA,kBAAkB,EAAE,EAAE;KACvB,CAAC;AACF,IAAA,OAAO,EAAE;QACP,SAAS;AACV,KAAA;AACD,IAAA,SAAS,EAAE;QACT,SAAS;QACT,QAAQ;QACR,cAAc,CAAC,KAAK,EAAE,WAAW,EAAA;AAC/B,YAAA,KAAK,CAAC,GAAG,GAAG,WAAW,CAAC,GAAG,CAAC,UAAU,IAAI,UAAU,CAAC,GAAG,CAAC,CAAC;SAC3D;QACD,UAAU,CAAC,KAAK,EAAE,UAAU,EAAA;AAC1B,YAAA,KAAK,CAAC,MAAM,GAAG,UAAU,CAAC,GAAG,CAAC,MAAM,IAAI,MAAM,CAAC,EAAY,CAAC,CAAC;SAC9D;QACD,OAAO,CAAC,KAAK,EAAE,IAAI,EAAA;AACjB,YAAA,KAAK,CAAC,IAAI,GAAG,IAAI,CAAC;SACnB;QACD,OAAO,CAAC,KAAK,EAAE,IAAI,EAAA;AACjB,YAAA,KAAK,CAAC,IAAI,GAAG,IAAI,CAAC;SACnB;QACD,qBAAqB,CAAC,KAAK,EAAE,WAAW,EAAA;AACtC,YAAA,KAAK,CAAC,kBAAkB,GAAG,WAAW,CAAC;SACxC;QACD,SAAS,CAAC,KAAK,EAAE,MAAM,EAAA;AACrB,YAAA,KAAK,CAAC,MAAM,GAAG,MAAM,CAAC;SACvB;AACF,KAAA;AACD,IAAA,OAAO,EAAE,EAAE;;;;;"}
|
|
1
|
+
{"version":3,"file":"module.js","sources":["../../../../../src/x-modules/url/store/module.ts"],"sourcesContent":["import { setQuery } from '../../../store/utils/query.utils';\nimport { urlParams } from './getters/url-params.getter';\nimport { initialUrlState } from './initial-state';\nimport { setParams } from './mutations/set-params.mutation';\nimport { UrlXStoreModule } from './types';\n\n/**\n * {@link XStoreModule} For the URL module.\n *\n * @internal\n */\nexport const urlXStoreModule: UrlXStoreModule = {\n state: () => ({\n ...initialUrlState,\n initialExtraParams: {}\n }),\n getters: {\n urlParams\n },\n mutations: {\n setParams,\n setQuery,\n setRelatedTags(state, relatedTags) {\n state.tag = relatedTags.map(relatedTag => relatedTag.tag);\n },\n setPrompt(state, prompt) {\n state.prompt = prompt;\n },\n setFilters(state, newFilters) {\n state.filter = newFilters.map(filter => filter.id as string);\n },\n setPage(state, page) {\n state.page = page;\n },\n setSort(state, sort) {\n state.sort = sort;\n },\n setInitialExtraParams(state, extraParams) {\n state.initialExtraParams = extraParams;\n },\n setScroll(state, scroll) {\n state.scroll = scroll;\n }\n },\n actions: {}\n};\n"],"names":[],"mappings":";;;;;AAMA;;;;AAIG;AACU,MAAA,eAAe,GAAoB;AAC9C,IAAA,KAAK,EAAE,OAAO;AACZ,QAAA,GAAG,eAAe;AAClB,QAAA,kBAAkB,EAAE,EAAE;KACvB,CAAC;AACF,IAAA,OAAO,EAAE;QACP,SAAS;AACV,KAAA;AACD,IAAA,SAAS,EAAE;QACT,SAAS;QACT,QAAQ;QACR,cAAc,CAAC,KAAK,EAAE,WAAW,EAAA;AAC/B,YAAA,KAAK,CAAC,GAAG,GAAG,WAAW,CAAC,GAAG,CAAC,UAAU,IAAI,UAAU,CAAC,GAAG,CAAC,CAAC;SAC3D;QACD,SAAS,CAAC,KAAK,EAAE,MAAM,EAAA;AACrB,YAAA,KAAK,CAAC,MAAM,GAAG,MAAM,CAAC;SACvB;QACD,UAAU,CAAC,KAAK,EAAE,UAAU,EAAA;AAC1B,YAAA,KAAK,CAAC,MAAM,GAAG,UAAU,CAAC,GAAG,CAAC,MAAM,IAAI,MAAM,CAAC,EAAY,CAAC,CAAC;SAC9D;QACD,OAAO,CAAC,KAAK,EAAE,IAAI,EAAA;AACjB,YAAA,KAAK,CAAC,IAAI,GAAG,IAAI,CAAC;SACnB;QACD,OAAO,CAAC,KAAK,EAAE,IAAI,EAAA;AACjB,YAAA,KAAK,CAAC,IAAI,GAAG,IAAI,CAAC;SACnB;QACD,qBAAqB,CAAC,KAAK,EAAE,WAAW,EAAA;AACtC,YAAA,KAAK,CAAC,kBAAkB,GAAG,WAAW,CAAC;SACxC;QACD,SAAS,CAAC,KAAK,EAAE,MAAM,EAAA;AACrB,YAAA,KAAK,CAAC,MAAM,GAAG,MAAM,CAAC;SACvB;AACF,KAAA;AACD,IAAA,OAAO,EAAE,EAAE;;;;;"}
|