@wix/headless-stores 0.0.58 → 0.0.59

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.
@@ -2,8 +2,14 @@ import { defineService, implementService } from '@wix/services-definitions';
2
2
  import { SignalsServiceDefinition, } from '@wix/services-definitions/core-services/signals';
3
3
  import { customizationsV3, productsV3, readOnlyVariantsV3 } from '@wix/stores';
4
4
  import { loadCategoriesListServiceConfig } from './categories-list-service.js';
5
- import { InventoryStatusType, parseUrlToSearchOptions, } from './products-list-search-service.js';
6
5
  export const DEFAULT_QUERY_LIMIT = 100;
6
+ import { SortType } from './../enums/sort-enums.js';
7
+ export { SortType } from './../enums/sort-enums.js';
8
+ /**
9
+ * Enumeration of inventory status types available for filtering.
10
+ * Re-exports the Wix inventory availability status enum values.
11
+ */
12
+ export const InventoryStatusType = productsV3.InventoryAvailabilityStatus;
7
13
  /**
8
14
  * Loads products list service configuration from the Wix Stores API for SSR initialization.
9
15
  * This function is designed to be used during Server-Side Rendering (SSR) to preload
@@ -471,3 +477,409 @@ function getAvailableProductOptions(aggregationData = [], customizations = []) {
471
477
  .filter((option) => option.choices.length > 0);
472
478
  return options;
473
479
  }
480
+ /**
481
+ * Parse URL and build complete search options with all filters, sort, and pagination.
482
+ * This function extracts search parameters, filters, sorting, and pagination from a URL
483
+ * and converts them into the format expected by the Wix Stores API.
484
+ *
485
+ * @param {string} url - The URL to parse search parameters from
486
+ * @param {Category[]} categoriesList - List of available categories for category slug resolution
487
+ * @param {productsV3.V3ProductSearch} [defaultSearchOptions] - Default search options to merge with parsed URL parameters
488
+ * @returns {Promise<{searchOptions: productsV3.V3ProductSearch, initialSearchState: InitialSearchState}>}
489
+ * Object containing both API-ready search options and UI-ready initial state
490
+ *
491
+ * @example
492
+ * ```tsx
493
+ * // Parse URL with filters, sort, and pagination
494
+ * const categories = await loadCategoriesListServiceConfig();
495
+ * const { searchOptions, initialSearchState } = await parseUrlToSearchOptions(
496
+ * 'https://example.com/products?sort=price:desc&Color=red,blue&minPrice=50',
497
+ * categories.categories
498
+ * );
499
+ *
500
+ * // Use searchOptions for API calls
501
+ * const products = await productsV3.searchProducts(searchOptions);
502
+ *
503
+ * // Use initialSearchState for UI initialization
504
+ * const filterState = initialSearchState.productOptions; // { colorId: ['red-id', 'blue-id'] }
505
+ * ```
506
+ */
507
+ export async function parseUrlToSearchOptions(url, categoriesList, customizations, defaultSearchOptions) {
508
+ const urlObj = new URL(url);
509
+ const searchParams = urlObj.searchParams;
510
+ // Build search options
511
+ const searchOptions = {
512
+ cursorPaging: {
513
+ limit: DEFAULT_QUERY_LIMIT,
514
+ },
515
+ ...defaultSearchOptions,
516
+ };
517
+ // Initialize search state for service
518
+ const initialSearchState = {};
519
+ // Extract category slug from URL path
520
+ // The category slug is always the last segment of the path
521
+ const pathSegments = urlObj.pathname.split('/').filter(Boolean);
522
+ let category = undefined;
523
+ if (pathSegments.length > 0) {
524
+ const lastSegment = pathSegments[pathSegments.length - 1];
525
+ // Check if the last segment matches any category in the categories list
526
+ category = categoriesList.find((cat) => cat.slug === lastSegment);
527
+ if (category) {
528
+ initialSearchState.category = category;
529
+ }
530
+ }
531
+ // Handle text search (q parameter)
532
+ const query = searchParams.get('q');
533
+ if (query) {
534
+ searchOptions.search = {
535
+ expression: query,
536
+ };
537
+ }
538
+ // Handle sorting
539
+ const sort = searchParams.get('sort');
540
+ if (sort) {
541
+ const sortType = convertUrlSortToSortType(sort);
542
+ if (sortType) {
543
+ initialSearchState.sort = sortType;
544
+ // Apply sort to search options
545
+ switch (sortType) {
546
+ case SortType.NAME_ASC:
547
+ searchOptions.sort = [
548
+ { fieldName: 'name', order: productsV3.SortDirection.ASC },
549
+ ];
550
+ break;
551
+ case SortType.NAME_DESC:
552
+ searchOptions.sort = [
553
+ { fieldName: 'name', order: productsV3.SortDirection.DESC },
554
+ ];
555
+ break;
556
+ case SortType.PRICE_ASC:
557
+ searchOptions.sort = [
558
+ {
559
+ fieldName: 'actualPriceRange.minValue.amount',
560
+ order: productsV3.SortDirection.ASC,
561
+ },
562
+ ];
563
+ break;
564
+ case SortType.PRICE_DESC:
565
+ searchOptions.sort = [
566
+ {
567
+ fieldName: 'actualPriceRange.minValue.amount',
568
+ order: productsV3.SortDirection.DESC,
569
+ },
570
+ ];
571
+ break;
572
+ case SortType.RECOMMENDED:
573
+ searchOptions.sort = [
574
+ {
575
+ fieldName: 'name',
576
+ order: productsV3.SortDirection.DESC,
577
+ },
578
+ ];
579
+ break;
580
+ }
581
+ }
582
+ }
583
+ // Handle pagination
584
+ const limit = searchParams.get('limit');
585
+ const cursor = searchParams.get('cursor');
586
+ if (limit || cursor) {
587
+ searchOptions.cursorPaging = {};
588
+ if (limit) {
589
+ const limitNum = parseInt(limit, 10);
590
+ if (!isNaN(limitNum) && limitNum > 0) {
591
+ searchOptions.cursorPaging.limit = limitNum;
592
+ initialSearchState.limit = limitNum;
593
+ }
594
+ }
595
+ if (cursor) {
596
+ searchOptions.cursorPaging.cursor = cursor;
597
+ initialSearchState.cursor = cursor;
598
+ }
599
+ }
600
+ // Handle filtering for search options
601
+ const filter = {};
602
+ const visible = searchParams.get('visible');
603
+ if (visible !== null) {
604
+ filter['visible'] = visible === 'true';
605
+ initialSearchState.visible = visible === 'true';
606
+ }
607
+ const productType = searchParams.get('productType');
608
+ if (productType) {
609
+ filter['productType'] = productType;
610
+ initialSearchState.productType = productType;
611
+ }
612
+ // Add category filter if found
613
+ if (category) {
614
+ filter['allCategoriesInfo.categories'] = {
615
+ $matchItems: [{ _id: { $in: [category._id] } }],
616
+ };
617
+ }
618
+ // Price range filtering
619
+ const minPrice = searchParams.get('minPrice');
620
+ const maxPrice = searchParams.get('maxPrice');
621
+ if (minPrice || maxPrice) {
622
+ initialSearchState.priceRange = {};
623
+ if (minPrice) {
624
+ const minPriceNum = parseFloat(minPrice);
625
+ if (!isNaN(minPriceNum)) {
626
+ filter['actualPriceRange.minValue.amount'] = { $gte: minPriceNum };
627
+ initialSearchState.priceRange.min = minPriceNum;
628
+ }
629
+ }
630
+ if (maxPrice) {
631
+ const maxPriceNum = parseFloat(maxPrice);
632
+ if (!isNaN(maxPriceNum)) {
633
+ filter['actualPriceRange.maxValue.amount'] = { $lte: maxPriceNum };
634
+ initialSearchState.priceRange.max = maxPriceNum;
635
+ }
636
+ }
637
+ }
638
+ const inventoryStatus = searchParams.get('inventoryStatus');
639
+ if (inventoryStatus) {
640
+ filter['inventory.availabilityStatus'] = {
641
+ $in: inventoryStatus.split(','),
642
+ };
643
+ }
644
+ // Parse product options from URL parameters
645
+ const reservedParams = [
646
+ 'minPrice',
647
+ 'maxPrice',
648
+ 'inventory_status',
649
+ 'inventoryStatus',
650
+ 'visible',
651
+ 'productType',
652
+ 'q',
653
+ 'limit',
654
+ 'cursor',
655
+ 'sort',
656
+ ];
657
+ const productOptionsById = {};
658
+ for (const [optionName, optionValues] of searchParams.entries()) {
659
+ if (reservedParams.includes(optionName))
660
+ continue;
661
+ // Find the option by name in customizations
662
+ const option = customizations.find((c) => c.name === optionName &&
663
+ c.customizationType ===
664
+ customizationsV3.CustomizationType.PRODUCT_OPTION);
665
+ if (option && option._id) {
666
+ const choiceValues = optionValues.split(',').filter(Boolean);
667
+ const choiceIds = [];
668
+ // Convert choice names to IDs
669
+ for (const choiceName of choiceValues) {
670
+ const choice = option.choicesSettings?.choices?.find((c) => c.name === choiceName);
671
+ if (choice && choice._id) {
672
+ choiceIds.push(choice._id);
673
+ }
674
+ }
675
+ if (choiceIds.length > 0) {
676
+ productOptionsById[option._id] = choiceIds;
677
+ }
678
+ }
679
+ }
680
+ if (Object.keys(productOptionsById).length > 0) {
681
+ initialSearchState.productOptions = productOptionsById;
682
+ // Add product option filter to search options
683
+ filter[`options.choicesSettings.choices.choiceId`] = {
684
+ $hasSome: Object.values(productOptionsById).flat(),
685
+ };
686
+ }
687
+ // Add filter to search options if any filters were set
688
+ if (Object.keys(filter).length > 0) {
689
+ searchOptions.filter = filter;
690
+ }
691
+ // Add aggregations for getting filter options
692
+ searchOptions.aggregations = [
693
+ {
694
+ name: 'minPrice',
695
+ fieldPath: 'actualPriceRange.minValue.amount',
696
+ type: 'SCALAR',
697
+ scalar: { type: 'MIN' },
698
+ },
699
+ {
700
+ name: 'maxPrice',
701
+ fieldPath: 'actualPriceRange.maxValue.amount',
702
+ type: 'SCALAR',
703
+ scalar: { type: 'MAX' },
704
+ },
705
+ {
706
+ name: 'optionNames',
707
+ fieldPath: 'options.name',
708
+ type: productsV3.SortType.VALUE,
709
+ value: {
710
+ limit: 20,
711
+ sortType: productsV3.SortType.VALUE,
712
+ sortDirection: productsV3.SortDirection.ASC,
713
+ },
714
+ },
715
+ {
716
+ name: 'choiceNames',
717
+ fieldPath: 'options.choicesSettings.choices.name',
718
+ type: productsV3.SortType.VALUE,
719
+ value: {
720
+ limit: 50,
721
+ sortType: productsV3.SortType.VALUE,
722
+ sortDirection: productsV3.SortDirection.ASC,
723
+ },
724
+ },
725
+ {
726
+ name: 'inventoryStatus',
727
+ fieldPath: 'inventory.availabilityStatus',
728
+ type: productsV3.SortType.VALUE,
729
+ value: {
730
+ limit: 10,
731
+ sortType: productsV3.SortType.VALUE,
732
+ sortDirection: productsV3.SortDirection.ASC,
733
+ },
734
+ },
735
+ ];
736
+ return { searchOptions, initialSearchState };
737
+ }
738
+ /**
739
+ * Convert SortType enum to URL format
740
+ */
741
+ function convertSortTypeToUrl(sortType) {
742
+ switch (sortType) {
743
+ case SortType.NAME_ASC:
744
+ return 'name';
745
+ case SortType.NAME_DESC:
746
+ return 'name:desc';
747
+ case SortType.PRICE_ASC:
748
+ return 'price';
749
+ case SortType.PRICE_DESC:
750
+ return 'price:desc';
751
+ case SortType.NEWEST:
752
+ return 'newest';
753
+ case SortType.RECOMMENDED:
754
+ return 'recommended';
755
+ default:
756
+ return 'name';
757
+ }
758
+ }
759
+ /**
760
+ * Convert URL sort format to SortType enum
761
+ */
762
+ export function convertUrlSortToSortType(urlSort) {
763
+ const sortParts = urlSort.split(':');
764
+ const field = sortParts[0]?.toLowerCase();
765
+ const order = sortParts[1]?.toLowerCase() === 'desc' ? 'desc' : 'asc';
766
+ switch (field) {
767
+ case 'name':
768
+ return order === 'desc' ? SortType.NAME_DESC : SortType.NAME_ASC;
769
+ case 'price':
770
+ return order === 'desc' ? SortType.PRICE_DESC : SortType.PRICE_ASC;
771
+ case 'newest':
772
+ case 'created':
773
+ return SortType.NEWEST;
774
+ case 'recommended':
775
+ return SortType.RECOMMENDED;
776
+ default:
777
+ return null;
778
+ }
779
+ }
780
+ /**
781
+ * Update URL with current search state (sort, filters, pagination)
782
+ */
783
+ //@ts-expect-error
784
+ function updateUrlWithSearchState(searchState) {
785
+ if (typeof window === 'undefined')
786
+ return;
787
+ const { sort, filters, customizations, catalogBounds, categorySlug } = searchState;
788
+ // Convert filter IDs back to human-readable names for URL
789
+ const humanReadableOptions = {};
790
+ for (const [optionId, choiceIds] of Object.entries(filters?.productOptions ?? {})) {
791
+ const option = customizations.find((c) => c._id === optionId);
792
+ if (option && option.name) {
793
+ const choiceNames = [];
794
+ for (const choiceId of choiceIds) {
795
+ const choice = option.choicesSettings?.choices?.find((c) => c._id === choiceId);
796
+ if (choice && choice.name) {
797
+ choiceNames.push(choice.name);
798
+ }
799
+ }
800
+ if (choiceNames.length > 0) {
801
+ humanReadableOptions[option.name] = choiceNames;
802
+ }
803
+ }
804
+ }
805
+ // Start with current URL parameters to preserve non-search parameters
806
+ const params = new URLSearchParams(window.location.search);
807
+ // Define search-related parameters that we manage
808
+ const searchParams = [
809
+ 'sort',
810
+ 'limit',
811
+ 'cursor',
812
+ 'minPrice',
813
+ 'maxPrice',
814
+ 'inventoryStatus',
815
+ 'visible',
816
+ 'productType',
817
+ // Product option names will be dynamically added below
818
+ // Note: category is NOT included here as it's handled in the URL path
819
+ ];
820
+ // Remove existing search parameters first
821
+ searchParams.forEach((param) => params.delete(param));
822
+ // Remove existing product option parameters (they have dynamic names)
823
+ for (const customization of customizations) {
824
+ if (customization.customizationType ===
825
+ customizationsV3.CustomizationType.PRODUCT_OPTION &&
826
+ customization.name) {
827
+ params.delete(customization.name);
828
+ }
829
+ }
830
+ // Add sort parameter (only if not default)
831
+ const urlSort = convertSortTypeToUrl(sort);
832
+ if (sort !== SortType.NAME_ASC) {
833
+ params.set('sort', urlSort);
834
+ }
835
+ // Add price range parameters only if they differ from catalog bounds
836
+ if (filters.priceRange?.min &&
837
+ filters.priceRange.min > catalogBounds.minPrice) {
838
+ params.set('minPrice', filters.priceRange.min.toString());
839
+ }
840
+ if (filters.priceRange?.max &&
841
+ filters.priceRange.max < catalogBounds.maxPrice) {
842
+ params.set('maxPrice', filters.priceRange.max.toString());
843
+ }
844
+ // Add inventory status parameters
845
+ if (filters.inventoryStatuses && filters.inventoryStatuses.length > 0) {
846
+ params.set('inventoryStatus', filters.inventoryStatuses.join(','));
847
+ }
848
+ // Add visibility filter (only if explicitly false, since true is default)
849
+ if (filters.visible === false) {
850
+ params.set('visible', 'false');
851
+ }
852
+ // Add product type filter
853
+ if (filters.productType) {
854
+ params.set('productType', filters.productType);
855
+ }
856
+ // Add product options as individual parameters (Color=Red,Blue&Size=Large)
857
+ for (const [optionName, values] of Object.entries(humanReadableOptions)) {
858
+ if (values.length > 0) {
859
+ params.set(optionName, values.join(','));
860
+ }
861
+ }
862
+ // Handle URL path construction with category
863
+ let baseUrl = window.location.pathname;
864
+ // If categorySlug is provided, replace the last path segment (which represents the category)
865
+ if (categorySlug) {
866
+ const pathSegments = baseUrl.split('/').filter(Boolean);
867
+ if (pathSegments.length > 0) {
868
+ // Replace the last segment with the new category slug
869
+ pathSegments[pathSegments.length - 1] = categorySlug;
870
+ baseUrl = '/' + pathSegments.join('/');
871
+ }
872
+ else {
873
+ // If no segments, just use the category slug
874
+ baseUrl = `/${categorySlug}`;
875
+ }
876
+ }
877
+ // Build the new URL
878
+ const newUrl = params.toString()
879
+ ? `${baseUrl}?${params.toString()}`
880
+ : baseUrl;
881
+ // Only update if URL actually changed
882
+ if (newUrl !== window.location.pathname + window.location.search) {
883
+ window.history.pushState(null, '', newUrl);
884
+ }
885
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wix/headless-stores",
3
- "version": "0.0.58",
3
+ "version": "0.0.59",
4
4
  "type": "module",
5
5
  "scripts": {
6
6
  "prebuild": "cd ../media && yarn build && cd ../ecom && yarn build",
@@ -62,6 +62,7 @@
62
62
  "@wix/auto_sdk_stores_read-only-variants-v-3": "^1.0.23",
63
63
  "@wix/ecom": "^1.0.1278",
64
64
  "@wix/essentials": "^0.1.24",
65
+ "@wix/headless-components": "0.0.1",
65
66
  "@wix/headless-ecom": "0.0.17",
66
67
  "@wix/headless-media": "^0.0.11",
67
68
  "@wix/headless-utils": "^0.0.1",