@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.
package/dist/index.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  import { pascalCase } from 'scule';
2
- import { computed, effectScope, reactive, markRaw, inject, ref, provide, unref, onMounted, watch, resolveComponent } from 'vue';
2
+ import { computed, toValue, effectScope, reactive, markRaw, inject, ref, provide, unref, onMounted, watch, resolveComponent } from 'vue';
3
3
  import { urlIsAbsolute, relativeUrlSlash, getSrcSetForMedia, getTranslatedProperty, getMainImageUrl, getListingFilters, isTechnicalPath, normalizePath, getRouteFromPathInfo, getProductTierPrices, buildUrlPrefix } from '@shopware/helpers';
4
4
  import { ApiClientError } from '@shopware/api-client';
5
5
  import { createSharedComposable, injectLocal, provideLocal, createInjectionState, syncRefs } from '@vueuse/core';
@@ -64,10 +64,11 @@ function useCmsElementImage(element) {
64
64
 
65
65
  function useCmsElementConfig(element) {
66
66
  const getConfigValue = (key) => {
67
- if (!element?.config) {
67
+ const config = toValue(element)?.config;
68
+ if (!config) {
68
69
  return void 0;
69
70
  }
70
- return element.config[key]?.source !== "mapped" && element.config[key]?.value;
71
+ return config[key]?.source !== "mapped" && config[key]?.value;
71
72
  };
72
73
  return {
73
74
  getConfigValue
@@ -533,7 +534,7 @@ const cmsAssociations = {
533
534
  function useCategorySearch() {
534
535
  const { apiClient, cacheableReads } = useShopwareContext();
535
536
  async function search(categoryId, options) {
536
- const associations = options?.withCmsAssociations ? cmsAssociations : {};
537
+ const associations = options?.withCmsAssociations ? cmsAssociations.associations : {};
537
538
  const criteria = {
538
539
  associations,
539
540
  ...options?.query
@@ -660,10 +661,12 @@ function useCheckout() {
660
661
 
661
662
  function useCmsBlock(content) {
662
663
  function getSlotContent(slotName) {
663
- return content.slots.find((slot) => slot.slot === slotName);
664
+ return toValue(content).slots.find(
665
+ (slot) => slot.slot === slotName
666
+ );
664
667
  }
665
668
  return {
666
- block: content,
669
+ block: toValue(content),
667
670
  getSlotContent
668
671
  };
669
672
  }
@@ -693,12 +696,12 @@ function useCmsMeta(entity) {
693
696
 
694
697
  function useCmsSection(content) {
695
698
  function getPositionContent(position) {
696
- return content.blocks.filter(
699
+ return toValue(content).blocks.filter(
697
700
  (block) => block.sectionPosition === position
698
701
  );
699
702
  }
700
703
  return {
701
- section: content,
704
+ section: toValue(content),
702
705
  getPositionContent
703
706
  };
704
707
  }
@@ -860,13 +863,27 @@ function useDefaultOrderAssociations() {
860
863
 
861
864
  function useInternationalization(pathResolver) {
862
865
  const { devStorefrontUrl, apiClient, cacheableReads } = useShopwareContext();
866
+ const { sessionContext } = useSessionContext();
863
867
  const _storeLanguages = useContext("swLanguages");
864
868
  const _storeCurrentLanguage = useContext(
865
869
  "swLanguagesCurrentLanguage"
866
870
  );
867
871
  const _storeCurrentPrefix = useContext("swLanguagesCurrentPrefix");
868
872
  function getStorefrontUrl() {
869
- return devStorefrontUrl ?? window.location.origin ?? "";
873
+ const preferred = devStorefrontUrl ?? window.location.origin ?? "";
874
+ const domains = sessionContext?.value?.salesChannel?.domains ?? [];
875
+ if (!domains.length) return preferred;
876
+ const normalizedPreferred = preferred.replace(/\/$/, "");
877
+ const matchingDomain = domains.find(
878
+ (domain) => domain.url?.replace(/\/$/, "") === normalizedPreferred
879
+ );
880
+ if (matchingDomain?.url) return matchingDomain.url;
881
+ const languageId = sessionContext?.value?.context?.languageIdChain?.[0] ?? sessionContext?.value?.salesChannel?.languageId;
882
+ const languageDomain = domains.find(
883
+ (domain) => domain.languageId === languageId && domain.url
884
+ );
885
+ if (languageDomain?.url) return languageDomain.url;
886
+ return domains.find((domain) => domain.url)?.url ?? preferred;
870
887
  }
871
888
  async function getAvailableLanguages() {
872
889
  const { data } = cacheableReads ? await apiClient.invoke("readLanguagesGet get /language") : await apiClient.invoke("readLanguages post /language");
@@ -1459,14 +1476,15 @@ function useNotifications() {
1459
1476
  return +`${(/* @__PURE__ */ new Date()).getTime()}${Math.random() * 1e3}`;
1460
1477
  }
1461
1478
  async function pushNotification(message, options) {
1462
- const timeout = options.timeout || 2500;
1479
+ const timeout = options.timeout || (options.action ? 5e3 : 2500);
1463
1480
  const persistent = !!options.persistent;
1464
1481
  _notifications.value = _notifications.value || [];
1465
1482
  const messageId = geterateId();
1466
1483
  _notifications.value.push({
1467
1484
  id: messageId,
1468
1485
  type: options.type,
1469
- message
1486
+ message,
1487
+ ...options.action ? { action: options.action } : {}
1470
1488
  });
1471
1489
  if (!persistent) {
1472
1490
  setTimeout(() => {
@@ -2413,6 +2431,7 @@ function useUser() {
2413
2431
  _user.value = data;
2414
2432
  }
2415
2433
  await refreshSessionContext();
2434
+ await refreshCart();
2416
2435
  return data;
2417
2436
  }
2418
2437
  async function logout() {
@@ -2823,18 +2842,22 @@ function resolveCmsComponent(content) {
2823
2842
  const type = content.apiAlias === "cms_block" ? "Block" : content.apiAlias === "cms_section" ? "Section" : "Element";
2824
2843
  const componentNameToResolve = pascalCase(`Cms-${type}-${componentName}`);
2825
2844
  try {
2826
- const resolvedComponent = resolveComponent(componentNameToResolve);
2845
+ const component = resolveComponent(componentNameToResolve);
2846
+ const resolvedComponent = typeof component !== "string" ? component : void 0;
2827
2847
  return {
2828
2848
  componentName,
2829
2849
  componentNameToResolve,
2830
- isResolved: resolvedComponent !== componentName,
2831
- resolvedComponent: typeof resolvedComponent !== "string" ? resolvedComponent : void 0
2850
+ isResolved: resolvedComponent !== void 0,
2851
+ resolvedComponent
2832
2852
  };
2833
2853
  } catch (e) {
2834
2854
  return {
2835
2855
  componentName,
2836
2856
  componentNameToResolve,
2837
2857
  resolvedComponent: void 0,
2858
+ /**
2859
+ * @deprecated Use `isResolved` instead. Kept so the error shape is unchanged.
2860
+ */
2838
2861
  resolved: false,
2839
2862
  isResolved: false,
2840
2863
  error: e.message
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@shopware/composables",
3
- "version": "1.13.0",
3
+ "version": "1.14.0",
4
4
  "description": "Shopware Frontends composables for Vue",
5
5
  "author": "Shopware",
6
6
  "repository": {
@@ -52,22 +52,23 @@
52
52
  "app.config.ts"
53
53
  ],
54
54
  "dependencies": {
55
- "@vueuse/core": "14.4.0",
55
+ "@vueuse/core": "15.0.0",
56
56
  "defu": "6.1.7",
57
57
  "scule": "1.3.0",
58
58
  "@shopware/helpers": "1.8.0",
59
- "@shopware/api-client": "1.6.0"
59
+ "@shopware/api-client": "1.7.0"
60
60
  },
61
61
  "devDependencies": {
62
62
  "@nuxt/kit": "4.5.2",
63
63
  "@typescript/native-preview": "7.0.0-dev.20260205.1",
64
- "@vitest/coverage-v8": "4.1.10",
65
- "@vue/test-utils": "2.4.11",
66
- "happy-dom": "20.11.1",
64
+ "@vitest/coverage-v8": "5.0.0",
65
+ "@vue/test-utils": "2.5.1",
66
+ "happy-dom": "20.14.5",
67
+ "pathe": "2.0.3",
67
68
  "typescript": "5.9.3",
68
69
  "unbuild": "3.6.1",
69
- "vitest": "4.1.10",
70
- "vue": "3.5.42",
70
+ "vitest": "5.0.0",
71
+ "vue": "3.5.43",
71
72
  "tsconfig": "0.0.0"
72
73
  },
73
74
  "scripts": {
@@ -1,9 +1,11 @@
1
1
  import { describe, expect, it } from "vitest";
2
+ import { ref } from "vue";
2
3
 
3
4
  import type {
4
5
  CmsElementBuyBox,
5
6
  CmsElementForm,
6
7
  CmsElementImage,
8
+ CmsElementText,
7
9
  } from "../types";
8
10
  import { useCmsElementConfig } from "./useCmsElementConfig";
9
11
 
@@ -149,6 +151,42 @@ describe("useCmsElementConfig", () => {
149
151
  expect(getConfigValue("defaultMailReceiver")).toEqual(false);
150
152
  expect(getConfigValue("mailReceiver")).toEqual(["first", "second"]);
151
153
  });
154
+
155
+ it("should not return the mapping path of a mapped value", () => {
156
+ const { getConfigValue } = useCmsElementConfig({
157
+ config: {
158
+ content: { source: "mapped", value: "category.name" },
159
+ },
160
+ } as unknown as CmsElementText);
161
+
162
+ expect(getConfigValue("content")).toBe(false);
163
+ });
164
+
165
+ it("should follow a ref passed as element", () => {
166
+ const element = ref({
167
+ config: { alignment: { source: "static", value: "flex-start" } },
168
+ } as unknown as CmsElementBuyBox);
169
+ const { getConfigValue } = useCmsElementConfig(element);
170
+
171
+ element.value = {
172
+ config: { alignment: { source: "static", value: "center" } },
173
+ } as unknown as CmsElementBuyBox;
174
+
175
+ expect(getConfigValue("alignment")).toBe("center");
176
+ });
177
+
178
+ it("should follow a getter passed as element", () => {
179
+ let element = {
180
+ config: { alignment: { source: "static", value: "flex-start" } },
181
+ } as unknown as CmsElementBuyBox;
182
+ const { getConfigValue } = useCmsElementConfig(() => element);
183
+
184
+ element = {
185
+ config: { alignment: { source: "static", value: "flex-end" } },
186
+ } as unknown as CmsElementBuyBox;
187
+
188
+ expect(getConfigValue("alignment")).toBe("flex-end");
189
+ });
152
190
  });
153
191
  });
154
192
  });
@@ -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
  import type { ElementConfig } from "../types";
@@ -5,22 +8,24 @@ import type { ElementConfig } from "../types";
5
8
  /**
6
9
  * Composable to get cms element config
7
10
  *
11
+ * `getConfigValue` reads the element on every call, so it follows a `ref` or
12
+ * getter passed as `element`.
13
+ *
8
14
  * @category CMS (Shopping Experiences)
9
15
  */
10
16
  export function useCmsElementConfig<
11
17
  T extends Omit<Schemas["CmsSlot"], "config"> & {
12
18
  config: Record<string, ElementConfig<unknown> | undefined>;
13
19
  },
14
- >(element: T) {
20
+ >(element: MaybeRefOrGetter<T>) {
15
21
  const getConfigValue = <ELEMENT_CONFIG extends keyof T["config"]>(
16
22
  key: ELEMENT_CONFIG,
17
23
  ): NonNullable<T["config"][ELEMENT_CONFIG]>["value"] => {
18
- if (!element?.config) {
24
+ const config = toValue(element)?.config;
25
+ if (!config) {
19
26
  return undefined as NonNullable<T["config"][ELEMENT_CONFIG]>["value"];
20
27
  }
21
- return (
22
- element.config[key]?.source !== "mapped" && element.config[key]?.value
23
- );
28
+ return config[key]?.source !== "mapped" && config[key]?.value;
24
29
  };
25
30
 
26
31
  return {
package/src/index.test.ts CHANGED
@@ -8,17 +8,30 @@ import CmsPage from "./mocks/CmsPage";
8
8
 
9
9
  vi.mock("vue");
10
10
  describe("resolveCmsComponent", () => {
11
- vi.spyOn(vue, "resolveComponent").mockImplementation((element) => element);
12
11
  it("should resolve a cms component", () => {
12
+ vi.spyOn(vue, "resolveComponent").mockImplementation(() => ({}));
13
13
  const section = CmsPage.cmsPage.sections?.[0];
14
14
  const block = section?.blocks?.[0];
15
15
 
16
16
  const result = resolveCmsComponent(block as unknown as Schemas["CmsBlock"]);
17
17
  expect(result.componentName).toBe("image-simple-grid");
18
18
  expect(result.componentNameToResolve).toBe("CmsBlockImageSimpleGrid");
19
+ expect(result.resolvedComponent).toEqual({});
19
20
  expect(result.isResolved).toBe(true);
20
21
  });
21
22
 
23
+ it("is not resolved when Vue hands the component name back", () => {
24
+ // resolveComponent returns the name it was given when nothing is registered
25
+ vi.spyOn(vue, "resolveComponent").mockImplementation((element) => element);
26
+ const section = CmsPage.cmsPage.sections?.[0];
27
+ const block = section?.blocks?.[0];
28
+
29
+ const result = resolveCmsComponent(block as unknown as Schemas["CmsBlock"]);
30
+ expect(result.componentNameToResolve).toBe("CmsBlockImageSimpleGrid");
31
+ expect(result.resolvedComponent).toBeUndefined();
32
+ expect(result.isResolved).toBe(false);
33
+ });
34
+
22
35
  it("getDefaultApiParams", () => {
23
36
  vi.spyOn(console, "error").mockImplementation(() => {});
24
37
  const result = getDefaultApiParams();
@@ -32,15 +45,20 @@ describe("resolveCmsComponent", () => {
32
45
  vi.spyOn(vue, "resolveComponent").mockImplementation(() => ({}));
33
46
  const result = resolveCmsComponent({
34
47
  apiAlias: "cms_section",
48
+ type: "sidebar",
35
49
  } as unknown as Schemas["CmsBlock"]);
50
+ expect(result.componentNameToResolve).toBe("CmsSectionSidebar");
36
51
  expect(result.isResolved).toBe(true);
37
52
  });
38
53
 
39
54
  it("cms custom component", () => {
55
+ vi.spyOn(vue, "resolveComponent").mockImplementation(() => ({}));
40
56
  const result = resolveCmsComponent({
41
57
  apiAlias: "cms_custom",
58
+ type: "text",
42
59
  } as unknown as Schemas["CmsBlock"]);
43
60
 
61
+ expect(result.componentNameToResolve).toBe("CmsElementText");
44
62
  expect(result.isResolved).toBe(true);
45
63
  });
46
64
 
package/src/index.ts CHANGED
@@ -80,20 +80,25 @@ export function resolveCmsComponent(
80
80
 
81
81
  const componentNameToResolve = pascalCase(`Cms-${type}-${componentName}`);
82
82
  try {
83
- const resolvedComponent = resolveComponent(componentNameToResolve);
83
+ const component = resolveComponent(componentNameToResolve);
84
+ // Vue returns the name it was given when nothing is registered under it.
85
+ const resolvedComponent =
86
+ typeof component !== "string" ? component : undefined;
84
87
 
85
88
  return {
86
89
  componentName,
87
90
  componentNameToResolve,
88
- isResolved: resolvedComponent !== componentName,
89
- resolvedComponent:
90
- typeof resolvedComponent !== "string" ? resolvedComponent : undefined,
91
+ isResolved: resolvedComponent !== undefined,
92
+ resolvedComponent,
91
93
  };
92
94
  } catch (e) {
93
95
  return {
94
96
  componentName,
95
97
  componentNameToResolve,
96
98
  resolvedComponent: undefined,
99
+ /**
100
+ * @deprecated Use `isResolved` instead. Kept so the error shape is unchanged.
101
+ */
97
102
  resolved: false,
98
103
  isResolved: false,
99
104
  error: (e as Error).message,
@@ -34,6 +34,7 @@ export type CmsBlockImageSimpleGrid = BlockType<
34
34
  export type CmsBlockImageSlider = BlockType<"imageSlider">;
35
35
  export type CmsBlockImageGallery = BlockType<"imageGallery">;
36
36
 
37
+ export type CmsBlockVideo = BlockType<"video">;
37
38
  export type CmsBlockYoutubeVideo = BlockType<"video">;
38
39
  export type CmsBlockVimeoVideo = BlockType<"video">;
39
40
 
@@ -69,6 +70,7 @@ export type CmsBlockTextOnImage = BlockType<"content">;
69
70
  export type CmsBlockSidebarFilter = BlockType<"content">;
70
71
  export type CmsBlockCategoryNavigation = BlockType<"content">;
71
72
 
73
+ export type CmsBlockCategoryHeading = BlockType<"content">;
72
74
  export type CmsBlockProductHeading = BlockType<TWO_COLUMNS>;
73
75
  export type CmsBlockProductThreeColumn = BlockType<THREE_COLUMNS>;
74
76
  export type CmsBlockProductListing = BlockType<"content">;
@@ -81,3 +83,13 @@ export type CmsBlockForm = BlockType<"content">;
81
83
  export type CmsBlockHtml = BlockType<"content">;
82
84
 
83
85
  export type CmsBlockImageGalleryBig = BlockType<"imageGallery">;
86
+
87
+ export type CmsBlockAppRenderer = BlockType<string> & {
88
+ type: "app-renderer";
89
+ customFields?: {
90
+ appBlockName?: string;
91
+ slotLayout?: {
92
+ grid?: string | null;
93
+ };
94
+ } | null;
95
+ };
@@ -10,6 +10,8 @@ export type DisplayMode =
10
10
  | Exclude<CSSProperties["objectFit"], undefined>
11
11
  | "standard";
12
12
 
13
+ export type MediaDisplayMode = "standard" | "stretch" | "cover";
14
+
13
15
  export type BoxLayout = "standard" | "image" | "minimal";
14
16
 
15
17
  export type VerticalAlign = "flex-start" | "center" | "flex-end" | "";
@@ -151,6 +153,41 @@ export type CmsElementImageGallery = Omit<Schemas["CmsSlot"], "config"> & {
151
153
  };
152
154
  };
153
155
 
156
+ // Video
157
+ type VideoElementConfig = {
158
+ media: ElementConfig<string | null>;
159
+ displayMode: ElementConfig<MediaDisplayMode>;
160
+ minHeight: ElementConfig<string | null>;
161
+ verticalAlign: ElementConfig<VerticalAlign | null>;
162
+ horizontalAlign: ElementConfig<VerticalAlign | null>;
163
+ ariaLabel: ElementConfig<string | null>;
164
+ autoPlay: ElementConfig<boolean>;
165
+ muted: ElementConfig<boolean>;
166
+ loop: ElementConfig<boolean>;
167
+ playsInline: ElementConfig<boolean>;
168
+ showControls: ElementConfig<boolean>;
169
+ showCover: ElementConfig<boolean>;
170
+ };
171
+
172
+ export type CmsElementVideo = Omit<Schemas["CmsSlot"], "config"> & {
173
+ type: "video";
174
+ config: VideoElementConfig;
175
+ data: {
176
+ mediaId: string | null;
177
+ url: string | null;
178
+ newTab: boolean | null;
179
+ ariaLabel: string | null;
180
+ apiAlias: "cms_video";
181
+ media:
182
+ | (Schemas["Media"] & {
183
+ extensions?: {
184
+ videoCoverMedia?: Schemas["Media"];
185
+ };
186
+ })
187
+ | null;
188
+ };
189
+ };
190
+
154
191
  // YouTube video
155
192
  type YouTubeVideoElementConfig = {
156
193
  end: ElementConfig<string>;
@@ -386,6 +423,21 @@ export type CmsElementProductName = Omit<Schemas["CmsSlot"], "config"> & {
386
423
  };
387
424
  };
388
425
 
426
+ // Category Name
427
+ type CategoryNameElementConfig = {
428
+ content: ElementConfig<string>;
429
+ verticalAlign?: ElementConfig<VerticalAlign | null>;
430
+ };
431
+
432
+ export type CmsElementCategoryName = Omit<Schemas["CmsSlot"], "config"> & {
433
+ type: "category-name";
434
+ config: CategoryNameElementConfig;
435
+ data: {
436
+ content: string | null;
437
+ apiAlias: "cms_text";
438
+ };
439
+ };
440
+
389
441
  // Manufacturer Logo
390
442
  export type CmsElementManufacturerLogo = Omit<Schemas["CmsSlot"], "config"> & {
391
443
  type: "manufacturer-logo";
@@ -5,24 +5,24 @@ import { useSetup } from "../_test";
5
5
  import ProductMocked from "../mocks/Product";
6
6
  import { useAddToCart } from "./useAddToCart";
7
7
 
8
- describe("useAddToCart", () => {
9
- vi.mock("../useCart/useCart.ts", () => ({
10
- useCart() {
11
- return {
12
- addProduct: () => ({}),
13
- cartItems: {
14
- value: [
15
- {
16
- referencedId: ProductMocked.id,
17
- good: true,
18
- quantity: 1,
19
- },
20
- ],
21
- },
22
- };
23
- },
24
- }));
8
+ vi.mock("../useCart/useCart.ts", () => ({
9
+ useCart() {
10
+ return {
11
+ addProduct: () => ({}),
12
+ cartItems: {
13
+ value: [
14
+ {
15
+ referencedId: ProductMocked.id,
16
+ good: true,
17
+ quantity: 1,
18
+ },
19
+ ],
20
+ },
21
+ };
22
+ },
23
+ }));
25
24
 
25
+ describe("useAddToCart", () => {
26
26
  it("add product to cart", async () => {
27
27
  const { vm } = await useSetup(() => useAddToCart(ref(ProductMocked)));
28
28
 
@@ -45,7 +45,7 @@ describe("useCategorySearch", () => {
45
45
  "sw-include-seo-urls": true,
46
46
  },
47
47
  body: {
48
- associations: cmsAssociations,
48
+ associations: cmsAssociations.associations,
49
49
  },
50
50
  }),
51
51
  );
@@ -79,7 +79,7 @@ describe("useCategorySearch", () => {
79
79
  },
80
80
  query: {
81
81
  _criteria: encodeForQuery({
82
- associations: cmsAssociations,
82
+ associations: cmsAssociations.associations,
83
83
  filter: [{ type: "equals", field: "active", value: true }],
84
84
  limit: 1,
85
85
  sort: [{ field: "name", order: "ASC" }],
@@ -46,7 +46,9 @@ export function useCategorySearch(): UseCategorySearchReturn {
46
46
  query?: Schemas["Criteria"];
47
47
  },
48
48
  ) {
49
- const associations = options?.withCmsAssociations ? cmsAssociations : {};
49
+ const associations = options?.withCmsAssociations
50
+ ? cmsAssociations.associations
51
+ : {};
50
52
  const criteria = {
51
53
  associations,
52
54
  ...options?.query,
@@ -1,27 +1,61 @@
1
1
  import { describe, expect, it } from "vitest";
2
+ import { ref } from "vue";
2
3
 
3
4
  import type { Schemas } from "#shopware";
4
5
 
5
6
  import { useSetup } from "../_test";
6
7
  import { useCmsBlock } from "./useCmsBlock";
7
8
 
9
+ const blockWith = (slot: string) =>
10
+ ({
11
+ apiAlias: "cms_block",
12
+ createdAt: "2020-08-06T06:26:23.880+00:00",
13
+ position: 0,
14
+ sectionId: "ri3n2ldk",
15
+ slots: [
16
+ {
17
+ slot,
18
+ },
19
+ ],
20
+ type: "page",
21
+ }) as unknown as Schemas["CmsBlock"];
22
+
8
23
  describe("composables - useCmsBlock", () => {
9
24
  it("get block data", () => {
10
- const mockData = {
11
- apiAlias: "cms_block",
12
- createdAt: "2020-08-06T06:26:23.880+00:00",
13
- position: 0,
14
- sectionId: "ri3n2ldk",
15
- slots: [
16
- {
17
- slot: "left-bottom",
18
- },
19
- ],
20
- type: "page",
21
- };
22
- const { vm } = useSetup(() => useCmsBlock(mockData as Schemas["CmsBlock"]));
25
+ const mockData = blockWith("left-bottom");
26
+ const { vm } = useSetup(() => useCmsBlock(mockData));
23
27
 
24
28
  expect(vm.block).toEqual(mockData);
25
29
  expect(vm.getSlotContent("left-bottom")).toEqual(mockData.slots[0]);
26
30
  });
31
+
32
+ it("returns undefined for a slot the block does not carry", () => {
33
+ const { vm } = useSetup(() => useCmsBlock(blockWith("left-bottom")));
34
+
35
+ expect(vm.getSlotContent("right-top")).toBeUndefined();
36
+ });
37
+
38
+ it("looks up slots on a replaced block", () => {
39
+ const first = blockWith("left-bottom");
40
+ const content = ref(first);
41
+ const { vm } = useSetup(() => useCmsBlock(content));
42
+
43
+ expect(vm.getSlotContent("left-bottom")).toBeDefined();
44
+
45
+ content.value = blockWith("right-top");
46
+
47
+ expect(vm.getSlotContent("left-bottom")).toBeUndefined();
48
+ expect(vm.getSlotContent("right-top")).toEqual(content.value.slots[0]);
49
+ // `block` is the value read when the composable was called
50
+ expect(vm.block).toEqual(first);
51
+ });
52
+
53
+ it("accepts a getter", () => {
54
+ const content = ref(blockWith("left-bottom"));
55
+ const { vm } = useSetup(() => useCmsBlock(() => content.value));
56
+
57
+ content.value = blockWith("right-top");
58
+
59
+ expect(vm.getSlotContent("right-top")).toEqual(content.value.slots[0]);
60
+ });
27
61
  });
@@ -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,18 @@ type ArrayElement<ArrayType extends readonly unknown[]> =
5
8
 
6
9
  export type UseCmsBlockReturn = {
7
10
  /**
8
- * Cms block content
11
+ * Cms block content, as it was when the composable was called.
9
12
  */
10
13
  block: Schemas["CmsBlock"];
11
14
  /**
12
- * Get slot content by slot name (identifier)
15
+ * Get slot content by slot name (identifier).
16
+ *
17
+ * Reads the block on every call, so it follows a `ref` or getter passed as
18
+ * `content`.
19
+ *
20
+ * A block does not have to carry every slot its layout allows: the lookup
21
+ * returns `undefined` at runtime for a slot that is not there, which the
22
+ * return type does not express yet. Guard on the result.
13
23
  * @example getSlotContent("main")
14
24
  */
15
25
  getSlotContent(slotName: string): ArrayElement<Schemas["CmsBlock"]["slots"]>;
@@ -21,16 +31,16 @@ export type UseCmsBlockReturn = {
21
31
  * @category CMS (Shopping Experiences)
22
32
  */
23
33
  export function useCmsBlock<BLOCK_TYPE extends Schemas["CmsBlock"]>(
24
- content: BLOCK_TYPE,
34
+ content: MaybeRefOrGetter<BLOCK_TYPE>,
25
35
  ): UseCmsBlockReturn {
26
36
  function getSlotContent(slotName: ArrayElement<BLOCK_TYPE["slots"]>["slot"]) {
27
- return content.slots.find((slot) => slot.slot === slotName) as ArrayElement<
28
- BLOCK_TYPE["slots"]
29
- >;
37
+ return toValue(content).slots.find(
38
+ (slot) => slot.slot === slotName,
39
+ ) as ArrayElement<BLOCK_TYPE["slots"]>;
30
40
  }
31
41
 
32
42
  return {
33
- block: content,
43
+ block: toValue(content),
34
44
  getSlotContent,
35
45
  };
36
46
  }