@shopware/composables 1.13.0 → 1.14.0

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.
@@ -1,4 +1,5 @@
1
1
  import { describe, expect, it } from "vitest";
2
+ import { ref } from "vue";
2
3
 
3
4
  import type { Schemas } from "#shopware";
4
5
 
@@ -6,15 +7,57 @@ import { useSetup } from "../_test";
6
7
  import CmsPage from "../mocks/CmsPage";
7
8
  import { useCmsSection } from "./useCmsSection";
8
9
 
10
+ const sectionWith = (sectionPosition: string) =>
11
+ ({
12
+ apiAlias: "cms_section",
13
+ type: "default",
14
+ blocks: [
15
+ {
16
+ apiAlias: "cms_block",
17
+ sectionPosition,
18
+ type: "text",
19
+ },
20
+ ],
21
+ }) as unknown as Schemas["CmsSection"];
22
+
9
23
  describe("useCmsSection", () => {
10
- it("search", async () => {
24
+ it("returns the blocks placed on the given position", () => {
11
25
  const section = CmsPage.cmsPage.sections?.[0];
12
26
 
13
- const { vm, injections } = useSetup(() =>
27
+ const { vm } = useSetup(() =>
14
28
  useCmsSection(section as unknown as Schemas["CmsSection"]),
15
29
  );
16
- injections.apiClient.invoke.mockResolvedValue({ data: {} });
17
- const block = await vm.getPositionContent("main");
18
- expect(block).toEqual(section?.blocks);
30
+
31
+ expect(vm.getPositionContent("main")).toEqual(section?.blocks);
32
+ });
33
+
34
+ it("returns an empty array for a position no block uses", () => {
35
+ const { vm } = useSetup(() => useCmsSection(sectionWith("main")));
36
+
37
+ expect(vm.getPositionContent("sidebar")).toEqual([]);
38
+ });
39
+
40
+ it("groups blocks of a replaced section", () => {
41
+ const first = sectionWith("main");
42
+ const content = ref(first);
43
+ const { vm } = useSetup(() => useCmsSection(content));
44
+
45
+ expect(vm.getPositionContent("main")).toHaveLength(1);
46
+
47
+ content.value = sectionWith("sidebar");
48
+
49
+ expect(vm.getPositionContent("main")).toEqual([]);
50
+ expect(vm.getPositionContent("sidebar")).toHaveLength(1);
51
+ // `section` is the value read when the composable was called
52
+ expect(vm.section).toEqual(first);
53
+ });
54
+
55
+ it("accepts a getter", () => {
56
+ const content = ref(sectionWith("main"));
57
+ const { vm } = useSetup(() => useCmsSection(() => content.value));
58
+
59
+ content.value = sectionWith("sidebar");
60
+
61
+ expect(vm.getPositionContent("sidebar")).toHaveLength(1);
19
62
  });
20
63
  });
@@ -1,3 +1,6 @@
1
+ import { toValue } from "vue";
2
+ import type { MaybeRefOrGetter } from "vue";
3
+
1
4
  import type { Schemas } from "#shopware";
2
5
 
3
6
  type ArrayElement<ArrayType extends readonly unknown[]> =
@@ -5,11 +8,14 @@ type ArrayElement<ArrayType extends readonly unknown[]> =
5
8
 
6
9
  type UseCmsSectionType = {
7
10
  /**
8
- * CMS section
11
+ * CMS section, as it was when the composable was called.
9
12
  */
10
13
  section: Schemas["CmsSection"];
11
14
  /**
12
- * Position of the section
15
+ * Blocks of the section placed on the given position.
16
+ *
17
+ * Reads the section on every call, so it follows a `ref` or getter passed as
18
+ * `content`.
13
19
  */
14
20
  getPositionContent(
15
21
  position: ArrayElement<Schemas["CmsSection"]["blocks"]>["sectionPosition"],
@@ -22,18 +28,18 @@ type UseCmsSectionType = {
22
28
  * @category CMS (Shopping Experiences)
23
29
  */
24
30
  export function useCmsSection<SECTION_TYPE extends Schemas["CmsSection"]>(
25
- content: SECTION_TYPE,
31
+ content: MaybeRefOrGetter<SECTION_TYPE>,
26
32
  ): UseCmsSectionType {
27
33
  function getPositionContent(
28
34
  position: ArrayElement<SECTION_TYPE["blocks"]>["sectionPosition"],
29
35
  ) {
30
- return content.blocks.filter(
36
+ return toValue(content).blocks.filter(
31
37
  (block) => block.sectionPosition === position,
32
38
  ) as Array<Schemas["CmsBlock"]>;
33
39
  }
34
40
 
35
41
  return {
36
- section: content,
42
+ section: toValue(content),
37
43
  getPositionContent,
38
44
  };
39
45
  }
@@ -3,6 +3,7 @@ import { describe, expect, it, vi } from "vitest";
3
3
  import type { Schemas } from "#shopware";
4
4
 
5
5
  import { useSetup } from "../_test";
6
+ import { useSessionContext } from "../useSessionContext/useSessionContext";
6
7
  import { useInternationalization } from "./useInternationalization";
7
8
  import type { RouteObject } from "./useInternationalization";
8
9
 
@@ -140,6 +141,159 @@ describe("useInternationalization", () => {
140
141
  );
141
142
  });
142
143
 
144
+ it("uses a sales channel domain when the preferred storefront URL is not configured there", async () => {
145
+ const { vm } = useSetup(
146
+ () => {
147
+ const session = useSessionContext();
148
+ const i18n = useInternationalization();
149
+ return {
150
+ setContext: session.setContext,
151
+ getStorefrontUrl: i18n.getStorefrontUrl,
152
+ };
153
+ },
154
+ {
155
+ shopware: {
156
+ devStorefrontUrl: "https://frontends-starter-template.vercel.app",
157
+ },
158
+ },
159
+ );
160
+
161
+ vm.setContext({
162
+ salesChannel: {
163
+ domains: [
164
+ {
165
+ url: "https://demo-frontends.shopware.store/figma",
166
+ languageId: "lang-en",
167
+ },
168
+ ],
169
+ languageId: "lang-en",
170
+ },
171
+ } as Schemas["SalesChannelContext"]);
172
+
173
+ expect(vm.getStorefrontUrl()).toBe(
174
+ "https://demo-frontends.shopware.store/figma",
175
+ );
176
+ });
177
+
178
+ it("keeps the preferred storefront URL when it matches a sales channel domain", async () => {
179
+ const preferred = "https://frontends-starter-template.vercel.app";
180
+ const { vm } = useSetup(
181
+ () => {
182
+ const session = useSessionContext();
183
+ const i18n = useInternationalization();
184
+ return {
185
+ setContext: session.setContext,
186
+ getStorefrontUrl: i18n.getStorefrontUrl,
187
+ };
188
+ },
189
+ {
190
+ shopware: { devStorefrontUrl: preferred },
191
+ },
192
+ );
193
+
194
+ vm.setContext({
195
+ salesChannel: {
196
+ domains: [{ url: preferred, languageId: "lang-en" }],
197
+ languageId: "lang-en",
198
+ },
199
+ } as Schemas["SalesChannelContext"]);
200
+
201
+ expect(vm.getStorefrontUrl()).toBe(preferred);
202
+ });
203
+
204
+ it("falls back to the first sales channel domain when no language domain matches", async () => {
205
+ const { vm } = useSetup(
206
+ () => {
207
+ const session = useSessionContext();
208
+ const i18n = useInternationalization();
209
+ return {
210
+ setContext: session.setContext,
211
+ getStorefrontUrl: i18n.getStorefrontUrl,
212
+ };
213
+ },
214
+ {
215
+ shopware: { devStorefrontUrl: "https://not-a-channel-domain.example" },
216
+ },
217
+ );
218
+
219
+ vm.setContext({
220
+ salesChannel: {
221
+ domains: [
222
+ { url: undefined, languageId: "lang-de" },
223
+ {
224
+ url: "https://demo-frontends.shopware.store/figma",
225
+ languageId: "lang-en",
226
+ },
227
+ ],
228
+ languageId: "lang-pl",
229
+ },
230
+ context: { languageIdChain: ["lang-fr"] },
231
+ } as Schemas["SalesChannelContext"]);
232
+
233
+ expect(vm.getStorefrontUrl()).toBe(
234
+ "https://demo-frontends.shopware.store/figma",
235
+ );
236
+ });
237
+
238
+ it("keeps the preferred URL when sales channel domains have no url", async () => {
239
+ const preferred = "https://frontends-starter-template.vercel.app";
240
+ const { vm } = useSetup(
241
+ () => {
242
+ const session = useSessionContext();
243
+ const i18n = useInternationalization();
244
+ return {
245
+ setContext: session.setContext,
246
+ getStorefrontUrl: i18n.getStorefrontUrl,
247
+ };
248
+ },
249
+ {
250
+ shopware: { devStorefrontUrl: preferred },
251
+ },
252
+ );
253
+
254
+ vm.setContext({
255
+ salesChannel: {
256
+ domains: [{ languageId: "lang-en" }],
257
+ languageId: "lang-de",
258
+ },
259
+ } as Schemas["SalesChannelContext"]);
260
+
261
+ expect(vm.getStorefrontUrl()).toBe(preferred);
262
+ });
263
+
264
+ it("treats a trailing slash as the same sales channel domain", async () => {
265
+ const { vm } = useSetup(
266
+ () => {
267
+ const session = useSessionContext();
268
+ const i18n = useInternationalization();
269
+ return {
270
+ setContext: session.setContext,
271
+ getStorefrontUrl: i18n.getStorefrontUrl,
272
+ };
273
+ },
274
+ {
275
+ shopware: {
276
+ devStorefrontUrl: "https://frontends-starter-template.vercel.app/",
277
+ },
278
+ },
279
+ );
280
+
281
+ vm.setContext({
282
+ salesChannel: {
283
+ domains: [
284
+ {
285
+ url: "https://frontends-starter-template.vercel.app",
286
+ languageId: "lang-en",
287
+ },
288
+ ],
289
+ },
290
+ } as Schemas["SalesChannelContext"]);
291
+
292
+ expect(vm.getStorefrontUrl()).toBe(
293
+ "https://frontends-starter-template.vercel.app",
294
+ );
295
+ });
296
+
143
297
  it("getStorefrontUrl without devStorefrontUrl and window", async () => {
144
298
  vi.spyOn(window, "location", "get").mockImplementation(
145
299
  () => ({}) as Location,
@@ -1,7 +1,7 @@
1
1
  import { urlIsAbsolute } from "@shopware/helpers";
2
2
  import type { Ref } from "vue";
3
3
 
4
- import { useContext, useShopwareContext } from "#imports";
4
+ import { useContext, useSessionContext, useShopwareContext } from "#imports";
5
5
  import type { Schemas, operations } from "#shopware";
6
6
 
7
7
  export type UseInternationalizationReturn = {
@@ -82,6 +82,7 @@ export function useInternationalization(
82
82
  pathResolver?: (path: string) => string,
83
83
  ): UseInternationalizationReturn {
84
84
  const { devStorefrontUrl, apiClient, cacheableReads } = useShopwareContext();
85
+ const { sessionContext } = useSessionContext();
85
86
 
86
87
  const _storeLanguages = useContext<Schemas["Language"][]>("swLanguages");
87
88
  const _storeCurrentLanguage = useContext<string>(
@@ -90,7 +91,25 @@ export function useInternationalization(
90
91
  const _storeCurrentPrefix = useContext<string>("swLanguagesCurrentPrefix");
91
92
 
92
93
  function getStorefrontUrl() {
93
- return devStorefrontUrl ?? window.location.origin ?? "";
94
+ const preferred = devStorefrontUrl ?? window.location.origin ?? "";
95
+ const domains = sessionContext?.value?.salesChannel?.domains ?? [];
96
+ if (!domains.length) return preferred;
97
+
98
+ const normalizedPreferred = preferred.replace(/\/$/, "");
99
+ const matchingDomain = domains.find(
100
+ (domain) => domain.url?.replace(/\/$/, "") === normalizedPreferred,
101
+ );
102
+ if (matchingDomain?.url) return matchingDomain.url;
103
+
104
+ const languageId =
105
+ sessionContext?.value?.context?.languageIdChain?.[0] ??
106
+ sessionContext?.value?.salesChannel?.languageId;
107
+ const languageDomain = domains.find(
108
+ (domain) => domain.languageId === languageId && domain.url,
109
+ );
110
+ if (languageDomain?.url) return languageDomain.url;
111
+
112
+ return domains.find((domain) => domain.url)?.url ?? preferred;
94
113
  }
95
114
 
96
115
  async function getAvailableLanguages() {
@@ -54,4 +54,23 @@ describe("useNotifications", () => {
54
54
  vm.pushSuccess("test");
55
55
  expect(vm.notifications.length).toBe(1);
56
56
  });
57
+
58
+ it("stores an optional action and keeps actionable toasts longer", () => {
59
+ const { vm } = useSetup(useNotifications);
60
+
61
+ vm.pushSuccess("Wooden Chair has been added to cart.", {
62
+ action: { label: "View cart", to: "/checkout/cart" },
63
+ });
64
+
65
+ expect(vm.notifications[0]?.action).toEqual({
66
+ label: "View cart",
67
+ to: "/checkout/cart",
68
+ });
69
+
70
+ vi.advanceTimersByTime(2500);
71
+ expect(vm.notifications.length).toBe(1);
72
+
73
+ vi.advanceTimersByTime(2500);
74
+ expect(vm.notifications.length).toBe(0);
75
+ });
57
76
  });
@@ -3,6 +3,16 @@ import type { ComputedRef, Ref } from "vue";
3
3
 
4
4
  type NotificationType = "info" | "warning" | "success" | "danger";
5
5
 
6
+ /**
7
+ * Optional CTA rendered next to a notification message (e.g. "View cart").
8
+ *
9
+ * @private
10
+ */
11
+ export type NotificationAction = {
12
+ label: string;
13
+ to: string;
14
+ };
15
+
6
16
  /**
7
17
  * @private
8
18
  */
@@ -10,6 +20,7 @@ export type Notification = {
10
20
  type: NotificationType;
11
21
  message: string;
12
22
  id: number;
23
+ action?: NotificationAction;
13
24
  };
14
25
 
15
26
  /**
@@ -22,6 +33,7 @@ export type NotificationOptions = {
22
33
  type?: NotificationType;
23
34
  timeout?: number;
24
35
  persistent?: boolean;
36
+ action?: NotificationAction;
25
37
  };
26
38
 
27
39
  /**
@@ -86,7 +98,7 @@ export function useNotifications(): UseNotificationsReturn {
86
98
  message: string,
87
99
  options: Required<Pick<NotificationOptions, "type">> & NotificationOptions,
88
100
  ) {
89
- const timeout = options.timeout || 2500;
101
+ const timeout = options.timeout || (options.action ? 5000 : 2500);
90
102
  const persistent = !!options.persistent;
91
103
  _notifications.value = _notifications.value || [];
92
104
 
@@ -95,6 +107,7 @@ export function useNotifications(): UseNotificationsReturn {
95
107
  id: messageId,
96
108
  type: options.type,
97
109
  message,
110
+ ...(options.action ? { action: options.action } : {}),
98
111
  });
99
112
  if (!persistent) {
100
113
  setTimeout(() => {
@@ -92,6 +92,30 @@ describe("useUser", () => {
92
92
  }),
93
93
  );
94
94
  expect(result).toEqual(registeredCustomer);
95
+ expect(refreshSessionContextSpy).toHaveBeenCalled();
96
+ expect(refreshCartSpy).toHaveBeenCalled();
97
+ });
98
+
99
+ it("register does not resolve before the cart refresh completes", async () => {
100
+ const { vm, injections } = useSetup(() => useUser());
101
+ injections.apiClient.invoke.mockResolvedValue({
102
+ data: { id: "reg-2", email: "test@test.testwwww" },
103
+ });
104
+
105
+ let cartRefreshCompleted = false;
106
+ refreshCartSpy.mockImplementationOnce(
107
+ () =>
108
+ new Promise((resolve) =>
109
+ setTimeout(() => {
110
+ cartRefreshCompleted = true;
111
+ resolve(undefined);
112
+ }, 0),
113
+ ),
114
+ );
115
+
116
+ await vm.register(REGISTRATION_DATA);
117
+
118
+ expect(cartRefreshCompleted).toBe(true);
95
119
  });
96
120
 
97
121
  it("register function with refresh", async () => {
@@ -193,6 +193,8 @@ export function useUser(): UseUserReturn {
193
193
  _user.value = data;
194
194
  }
195
195
  await refreshSessionContext();
196
+
197
+ await refreshCart();
196
198
  return data;
197
199
  }
198
200