@usereactify/search 3.4.3 → 3.6.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,7 +1,7 @@
1
1
  export declare const useAnalytics: () => {
2
2
  track: (event: TrackEvent) => Promise<import("axios").AxiosResponse<any, any> | undefined>;
3
3
  };
4
- export declare type TrackEvent = TrackEvent.SearchEvent | TrackEvent.ClickProductEvent;
4
+ export declare type TrackEvent = TrackEvent.SearchEvent | TrackEvent.ZeroResultsEvent | TrackEvent.ViewProductEvent | TrackEvent.ClickProductEvent;
5
5
  export declare namespace TrackEvent {
6
6
  interface SearchEvent {
7
7
  eventName: "search";
@@ -12,6 +12,24 @@ export declare namespace TrackEvent {
12
12
  searchTerm: string;
13
13
  }
14
14
  }
15
+ interface ZeroResultsEvent {
16
+ eventName: "zeroResults";
17
+ payload: ZeroResultsEvent.Payload;
18
+ }
19
+ namespace ZeroResultsEvent {
20
+ interface Payload {
21
+ searchTerm: string;
22
+ }
23
+ }
24
+ interface ViewProductEvent {
25
+ eventName: "viewProduct";
26
+ payload: ViewProductEvent.Payload;
27
+ }
28
+ namespace ViewProductEvent {
29
+ interface Payload {
30
+ elasticProduct: ElasticProduct;
31
+ }
32
+ }
15
33
  interface ClickProductEvent {
16
34
  eventName: "clickProduct";
17
35
  payload: ClickProductEvent.Payload;
@@ -41,6 +41,14 @@ function getTrackEvents(event) {
41
41
  },
42
42
  ];
43
43
  break;
44
+ case "viewProduct":
45
+ events = [
46
+ {
47
+ eventName,
48
+ payload: event.payload,
49
+ },
50
+ ];
51
+ break;
44
52
  case "clickProduct":
45
53
  events = [
46
54
  {
@@ -49,6 +57,14 @@ function getTrackEvents(event) {
49
57
  },
50
58
  ];
51
59
  break;
60
+ case "zeroResults":
61
+ events = [
62
+ {
63
+ eventName,
64
+ payload: event.payload,
65
+ },
66
+ ];
67
+ break;
52
68
  }
53
69
  return events;
54
70
  }
@@ -1,5 +1,4 @@
1
1
  import { Config } from "../types/config";
2
2
  export declare const useLiveConfig: (shopifyPermanentDomain: string) => {
3
- config: Config;
4
- configLoading: boolean;
3
+ config: Config | undefined;
5
4
  };
@@ -17,58 +17,48 @@ const react_1 = __importDefault(require("react"));
17
17
  const debug = require("debug")("reactify-search:useLiveConfig");
18
18
  // 5 minute cache expiry
19
19
  const CACHE_EXPIRY = 5 * 60 * 1000;
20
- const useLiveConfig = (shopifyPermanentDomain) => {
21
- // synchronously returns cached and non-expired config from session storage
22
- const cachedConfig = react_1.default.useMemo(() => {
23
- var _a;
24
- if (typeof window === "undefined") {
25
- return;
26
- }
27
- // skip checking cache if url search param "nocache" is set
28
- const skipCache = new URLSearchParams(window.location.href.split("?")[1]).get("nocache") !==
29
- null;
30
- if (skipCache) {
31
- debug("skipping cache");
32
- return;
33
- }
34
- const sessionConfig = JSON.parse((_a = window.sessionStorage.getItem("reactify-search:config")) !== null && _a !== void 0 ? _a : "null");
35
- if (sessionConfig) {
36
- const sessionConfigTtl = sessionConfig.expiresAt - Date.now();
37
- debug(`found ${sessionConfigTtl > 0 ? "cached" : "expired"} config`);
38
- if (sessionConfigTtl > 0) {
39
- debug(`config expires in ${(sessionConfigTtl / 1000).toFixed()} seconds`);
40
- return sessionConfig.config;
41
- }
42
- }
20
+ // synchronously returns cached and non-expired config from session storage
21
+ function getCachedConfig() {
22
+ var _a;
23
+ if (typeof window === "undefined") {
43
24
  return;
44
- }, []);
45
- const [config, setConfig] = react_1.default.useState(cachedConfig !== null && cachedConfig !== void 0 ? cachedConfig : {
46
- fields: [],
47
- filters: [],
48
- sort: [],
49
- curations: [],
50
- redirects: [],
51
- });
52
- const [configLoading, setConfigLoading] = react_1.default.useState(cachedConfig ? false : true);
53
- react_1.default.useEffect(() => {
54
- // fetch remote config if no cached config is found
55
- if (!cachedConfig) {
56
- (() => __awaiter(void 0, void 0, void 0, function* () {
57
- debug("fetching fresh config");
58
- setConfigLoading(true);
59
- const json = yield fetch(`https://config.search.reactify.app/?shop=${shopifyPermanentDomain}`).then((response) => response.json());
60
- setConfig(json.body);
61
- setConfigLoading(false);
62
- window.sessionStorage.setItem("reactify-search:config", JSON.stringify({
63
- expiresAt: new Date().getTime() + CACHE_EXPIRY,
64
- config: json.body,
65
- }));
66
- }))();
25
+ }
26
+ // skip checking cache if url search param "nocache" is set
27
+ const skipCache = new URLSearchParams(window.location.href.split("?")[1]).get("nocache") !==
28
+ null;
29
+ if (skipCache) {
30
+ debug("skipping cache");
31
+ return;
32
+ }
33
+ const sessionConfig = JSON.parse((_a = window.sessionStorage.getItem("reactify-search:config")) !== null && _a !== void 0 ? _a : "null");
34
+ if (sessionConfig) {
35
+ const sessionConfigTtl = sessionConfig.expiresAt - Date.now();
36
+ debug(`found ${sessionConfigTtl > 0 ? "cached" : "expired"} config`);
37
+ if (sessionConfigTtl > 0) {
38
+ debug(`config expires in ${(sessionConfigTtl / 1000).toFixed()} seconds`);
39
+ return sessionConfig.config;
67
40
  }
41
+ }
42
+ return;
43
+ }
44
+ const useLiveConfig = (shopifyPermanentDomain) => {
45
+ const [config, setConfig] = react_1.default.useState(getCachedConfig());
46
+ react_1.default.useEffect(() => {
47
+ const cachedConfig = getCachedConfig();
48
+ if (cachedConfig)
49
+ return;
50
+ (() => __awaiter(void 0, void 0, void 0, function* () {
51
+ debug("fetching fresh config");
52
+ const json = yield fetch(`https://config.search.reactify.app/?shop=${shopifyPermanentDomain}`).then((response) => response.json());
53
+ setConfig(json.body);
54
+ window.sessionStorage.setItem("reactify-search:config", JSON.stringify({
55
+ expiresAt: new Date().getTime() + CACHE_EXPIRY,
56
+ config: json.body,
57
+ }));
58
+ }))();
68
59
  }, [shopifyPermanentDomain]);
69
60
  return {
70
61
  config,
71
- configLoading,
72
62
  };
73
63
  };
74
64
  exports.useLiveConfig = useLiveConfig;
@@ -3,7 +3,6 @@ import type { Config, ConfigSort, ConfigFilter, ConfigCuration } from "./types/c
3
3
  declare type Context = {
4
4
  index: string;
5
5
  config: Config;
6
- configLoading: boolean;
7
6
  shopifyPermanentDomain: string;
8
7
  sortOption: ConfigSort | undefined;
9
8
  sortOptions: ConfigSort[];
@@ -34,8 +33,15 @@ declare type Props = {
34
33
  theme?: Theme;
35
34
  /** Array of additional component IDs managed outside of Reactify Search */
36
35
  additionalComponentIds?: string[];
36
+ /**
37
+ * Optional render function to display a component when the config is loading.
38
+ */
39
+ renderBooting?: () => JSX.Element | null;
37
40
  };
38
41
  export declare const Provider: React.FC<Props>;
42
+ export declare const ConfiguredProvider: React.FC<Omit<Props, "renderBooting"> & {
43
+ config: Config;
44
+ }>;
39
45
  export declare const useContext: () => Context;
40
46
  export interface Collection {
41
47
  id: number;
package/dist/provider.js CHANGED
@@ -1,9 +1,20 @@
1
1
  "use strict";
2
+ var __rest = (this && this.__rest) || function (s, e) {
3
+ var t = {};
4
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
5
+ t[p] = s[p];
6
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
7
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
8
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
9
+ t[p[i]] = s[p[i]];
10
+ }
11
+ return t;
12
+ };
2
13
  var __importDefault = (this && this.__importDefault) || function (mod) {
3
14
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
15
  };
5
16
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.useContext = exports.Provider = void 0;
17
+ exports.useContext = exports.ConfiguredProvider = exports.Provider = void 0;
7
18
  const react_1 = __importDefault(require("react"));
8
19
  const UtilityAuthenticatedReactiveBase_1 = require("./utility/UtilityAuthenticatedReactiveBase");
9
20
  const hooks_1 = require("./hooks");
@@ -14,9 +25,20 @@ const defaultCredentials = {
14
25
  password: "password",
15
26
  endpoint: "https://api.search.reactify.app",
16
27
  };
17
- const Provider = (props) => {
28
+ const Provider = (_a) => {
29
+ var { renderBooting } = _a, props = __rest(_a, ["renderBooting"]);
30
+ const { config } = (0, hooks_1.useLiveConfig)(props.shopifyPermanentDomain);
31
+ if (!config) {
32
+ if (renderBooting)
33
+ return renderBooting();
34
+ return null;
35
+ }
36
+ return react_1.default.createElement(exports.ConfiguredProvider, Object.assign({}, props, { config: config }));
37
+ };
38
+ exports.Provider = Provider;
39
+ const ConfiguredProvider = (props) => {
18
40
  var _a, _b;
19
- const { index, shopifyPermanentDomain, children, collection, instantSearch, filterStackId, noReactiveBase, additionalComponentIds, } = props;
41
+ const { index, config, children, collection, instantSearch, filterStackId, noReactiveBase, shopifyPermanentDomain, additionalComponentIds, } = props;
20
42
  const credentials = (_a = props.credentials) !== null && _a !== void 0 ? _a : defaultCredentials;
21
43
  const theme = (_b = props.theme) !== null && _b !== void 0 ? _b : {
22
44
  typography: {
@@ -34,7 +56,6 @@ const Provider = (props) => {
34
56
  react_1.default.useEffect(() => {
35
57
  debug("props", props);
36
58
  }, [props]);
37
- const { config, configLoading } = (0, hooks_1.useLiveConfig)(props.shopifyPermanentDomain);
38
59
  // @todo make this hackable with a prop
39
60
  // https://gitlab.com/reactifyapps/reactify-search-frontend/-/issues/1
40
61
  const searchQueryFromURL = react_1.default.useMemo(() => {
@@ -66,7 +87,6 @@ const Provider = (props) => {
66
87
  const contextValue = react_1.default.useMemo(() => ({
67
88
  index,
68
89
  config,
69
- configLoading,
70
90
  shopifyPermanentDomain,
71
91
  collection,
72
92
  credentials,
@@ -109,7 +129,7 @@ const Provider = (props) => {
109
129
  return (react_1.default.createElement(Context.Provider, { value: contextValue },
110
130
  react_1.default.createElement(UtilityAuthenticatedReactiveBase_1.UtilityAuthenticatedReactiveBase, null, children)));
111
131
  };
112
- exports.Provider = Provider;
132
+ exports.ConfiguredProvider = ConfiguredProvider;
113
133
  const useContext = () => react_1.default.useContext(Context);
114
134
  exports.useContext = useContext;
115
135
  const useSortState = (config, collection) => {
@@ -151,6 +171,7 @@ const useCuration = (config, collection, searchQuery) => react_1.default.useMemo
151
171
  const normalisedHandleOrSearchTerm = handleOrSearchTerm
152
172
  .toLowerCase()
153
173
  .trim();
174
+ const globalCuration = config.curations.find((curation) => curation.id === "global" && curation.type === type);
154
175
  const curation = config.curations.find((curation) => {
155
176
  var _a, _b;
156
177
  const normalisedSearchTerm = (_a = curation.searchTerm) === null || _a === void 0 ? void 0 : _a.toLowerCase().trim();
@@ -163,5 +184,5 @@ const useCuration = (config, collection, searchQuery) => react_1.default.useMemo
163
184
  normalisedHandleOrSearchTerm === normalisedCollectionHandle);
164
185
  return false;
165
186
  });
166
- return curation ? curation : undefined;
187
+ return curation ? curation : globalCuration ? globalCuration : undefined;
167
188
  }, [config, collection, searchQuery]);
@@ -5,7 +5,10 @@ declare type Props = {
5
5
  pagePosition: number;
6
6
  product: ElasticProduct;
7
7
  document: ElasticProduct;
8
- render?: (props: Omit<Props, "render"> & ReturnType<typeof useProductPrice>) => JSX.Element;
8
+ render?: (props: Omit<Props, "render"> & ReturnType<typeof useProductPrice> & {
9
+ itemRef: (node?: Element | null) => void;
10
+ handleClick: () => void;
11
+ }) => JSX.Element;
9
12
  };
10
13
  export declare const ResultCard: React.FC<Props>;
11
14
  export {};
@@ -16,15 +16,18 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
17
  exports.ResultCard = void 0;
18
18
  const react_1 = __importDefault(require("react"));
19
+ const react_intersection_observer_1 = require("react-intersection-observer");
19
20
  const hooks_1 = require("../hooks");
20
21
  const ResultCard = (_a) => {
21
22
  var { render } = _a, props = __rest(_a, ["render"]);
22
23
  const { product } = props;
23
24
  const productPrice = (0, hooks_1.useProductPrice)(product);
24
- if (render)
25
- return render(Object.assign(Object.assign({}, props), productPrice));
26
25
  const { formattedPrice, formattedCompareAtPrice, onSale } = productPrice;
27
26
  const { track } = (0, hooks_1.useAnalytics)();
27
+ const { ref, inView } = (0, react_intersection_observer_1.useInView)({
28
+ threshold: 0.5,
29
+ triggerOnce: true,
30
+ });
28
31
  const handleClick = react_1.default.useCallback(() => {
29
32
  track({
30
33
  eventName: "clickProduct",
@@ -36,7 +39,24 @@ const ResultCard = (_a) => {
36
39
  },
37
40
  });
38
41
  }, [track, product]);
39
- return (react_1.default.createElement("article", null,
42
+ const handleView = react_1.default.useCallback(() => {
43
+ track({
44
+ eventName: "viewProduct",
45
+ payload: {
46
+ elasticProduct: {
47
+ id: product.id,
48
+ title: product.title,
49
+ },
50
+ },
51
+ });
52
+ }, [track, product]);
53
+ react_1.default.useEffect(() => {
54
+ if (inView)
55
+ handleView();
56
+ }, [inView]);
57
+ if (render)
58
+ return render(Object.assign(Object.assign(Object.assign({}, props), productPrice), { itemRef: ref, handleClick }));
59
+ return (react_1.default.createElement("article", { ref: ref },
40
60
  react_1.default.createElement("a", { onClick: handleClick, href: `/products/${product.handle}` },
41
61
  product.image && react_1.default.createElement("img", { src: product.image, width: "100%" }),
42
62
  product.title),
@@ -14,7 +14,6 @@ declare type Props = {
14
14
  pageSize?: number;
15
15
  gridColumns?: number;
16
16
  listClassName?: string;
17
- renderBooting?: () => JSX.Element | null;
18
17
  renderLoading?: () => JSX.Element | null;
19
18
  renderNoResults?: () => JSX.Element | null;
20
19
  renderResultCard?: Parameters<typeof ResultCard>[0]["render"];
@@ -11,7 +11,7 @@ const ResultPagination_1 = require("./ResultPagination");
11
11
  const ResultCardCallout_1 = require("./ResultCardCallout");
12
12
  const ResultLoadMoreButton_1 = require("./ResultLoadMoreButton");
13
13
  const ResultPaginationNextPrev_1 = require("./ResultPaginationNextPrev");
14
- const provider_1 = require("../provider");
14
+ const __1 = require("../");
15
15
  const hooks_1 = require("../hooks");
16
16
  const elastic_1 = require("../types/elastic");
17
17
  const ResultList = (props) => {
@@ -23,10 +23,10 @@ const ResultList = (props) => {
23
23
  };
24
24
  exports.ResultList = ResultList;
25
25
  const ResultListInner = (props) => {
26
- const { gridColumns, renderError, renderAfter, renderBefore, renderBooting, renderLoading, listClassName, renderResults, renderNoResults, renderResultCard, renderLoadMoreButton, renderResultCardCallout, reactivesearchResultProps, } = props;
26
+ const { gridColumns, renderError, renderAfter, renderBefore, renderLoading, listClassName, renderResults, renderNoResults, renderResultCard, renderLoadMoreButton, renderResultCardCallout, reactivesearchResultProps, } = props;
27
27
  const filterStack = (0, hooks_1.useFilterStack)();
28
- const { instantSearch } = (0, hooks_1.useSearch)();
29
- const { configLoading } = (0, provider_1.useContext)();
28
+ const { instantSearch, searchQuery } = (0, hooks_1.useSearch)();
29
+ const { track } = (0, __1.useAnalytics)();
30
30
  const initialSearchHasRun = react_1.default.useMemo(() => "undefined" !==
31
31
  typeof reactivesearchResultProps.resultStats.numberOfResults, [reactivesearchResultProps]);
32
32
  const styleProp = react_1.default.useMemo(() => ({
@@ -34,11 +34,6 @@ const ResultListInner = (props) => {
34
34
  gridTemplateColumns: `repeat(${gridColumns !== null && gridColumns !== void 0 ? gridColumns : 4}, minmax(0, 1fr))`,
35
35
  }), [gridColumns]);
36
36
  const resultProps = react_1.default.useMemo(() => (Object.assign(Object.assign({}, reactivesearchResultProps), { products: reactivesearchResultProps.data.filter((document) => elastic_1.ElasticDocumentType.Product === document.type || !document.type), callouts: reactivesearchResultProps.data.filter((document) => elastic_1.ElasticDocumentType.Callout === document.type) })), [reactivesearchResultProps]);
37
- if (configLoading) {
38
- if (renderBooting)
39
- return renderBooting();
40
- return react_1.default.createElement("div", null, "Loading...");
41
- }
42
37
  if (reactivesearchResultProps.error) {
43
38
  if (renderError)
44
39
  return renderError({ error: reactivesearchResultProps.error });
@@ -52,6 +47,11 @@ const ResultListInner = (props) => {
52
47
  return react_1.default.createElement("div", null, "Loading...");
53
48
  }
54
49
  if (!reactivesearchResultProps.resultStats.numberOfResults) {
50
+ if (searchQuery)
51
+ track({
52
+ eventName: "zeroResults",
53
+ payload: { searchTerm: searchQuery },
54
+ });
55
55
  if (renderNoResults)
56
56
  return renderNoResults();
57
57
  return react_1.default.createElement("div", null, "No results");
@@ -12,6 +12,7 @@ const SensorSort = () => {
12
12
  const config = (0, hooks_1.useConfig)();
13
13
  const curation = (0, hooks_1.useCuration)();
14
14
  const collection = (0, hooks_1.useCollection)();
15
+ const globalCuration = (curation === null || curation === void 0 ? void 0 : curation.id) === "global";
15
16
  const { sortOption } = (0, hooks_1.useSort)();
16
17
  const searchQuery = react_1.default.useMemo(() => {
17
18
  if (typeof window === "undefined")
@@ -21,8 +22,14 @@ const SensorSort = () => {
21
22
  }, []);
22
23
  const { sort, query } = react_1.default.useMemo(() => {
23
24
  return {
24
- sort: buildSort({ config, curation, sortOption, collection }),
25
- query: buildQuery(curation),
25
+ sort: buildSort({
26
+ config,
27
+ curation,
28
+ sortOption,
29
+ collection,
30
+ globalCuration,
31
+ }),
32
+ query: buildQuery(curation, globalCuration),
26
33
  };
27
34
  }, [config, sortOption, curation]);
28
35
  react_1.default.useEffect(() => {
@@ -38,7 +45,7 @@ const SensorSort = () => {
38
45
  exports.SensorSort = SensorSort;
39
46
  const buildSort = (args) => {
40
47
  var _a;
41
- const { config, curation, sortOption, collection } = args;
48
+ const { config, curation, sortOption, collection, globalCuration } = args;
42
49
  debug("buildSortQuery.start", {
43
50
  config,
44
51
  curation,
@@ -63,22 +70,25 @@ const buildSort = (args) => {
63
70
  }
64
71
  const sorts = [];
65
72
  // show pins first
66
- sorts.push({
67
- "curations.position": {
68
- unmapped_type: "long",
69
- order: "asc",
70
- nested: {
71
- path: "curations",
72
- filter: {
73
- term: {
74
- [`curations.${"collection" === curation.type ? "collectionHandle" : "searchTerm"}.keyword`]: "collection" === curation.type
75
- ? curation.collectionHandle
76
- : (_a = curation.searchTerm) === null || _a === void 0 ? void 0 : _a.toLowerCase(),
73
+ if (!globalCuration)
74
+ sorts.push({
75
+ "curations.position": {
76
+ unmapped_type: "long",
77
+ order: "asc",
78
+ nested: {
79
+ path: "curations",
80
+ filter: {
81
+ term: {
82
+ [`curations.${"collection" === curation.type
83
+ ? "collectionHandle"
84
+ : "searchTerm"}.keyword`]: "collection" === curation.type
85
+ ? curation.collectionHandle
86
+ : (_a = curation.searchTerm) === null || _a === void 0 ? void 0 : _a.toLowerCase(),
87
+ },
77
88
  },
78
89
  },
79
90
  },
80
- },
81
- });
91
+ });
82
92
  if (0 < curation.boosting.groupings.length) {
83
93
  const groupings = curation.boosting.groupings.sort((a, b) => a.position > b.position ? 1 : -1);
84
94
  for (const grouping of groupings) {
@@ -137,9 +147,9 @@ function mapCollectionPositionSortClause(collection) {
137
147
  },
138
148
  ];
139
149
  }
140
- const buildQuery = (curation) => {
150
+ const buildQuery = (curation, globalCuration) => {
141
151
  var _a;
142
- if (!curation)
152
+ if (!curation || globalCuration)
143
153
  return undefined;
144
154
  return {
145
155
  bool: {
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@usereactify/search",
3
3
  "description": "React UI library for Reactify Search",
4
- "version": "3.4.3",
4
+ "version": "3.6.0",
5
5
  "license": "MIT",
6
6
  "main": "dist/index.js",
7
7
  "types": "dist/index.d.ts",
@@ -32,7 +32,8 @@
32
32
  "ahooks": "2.10.11",
33
33
  "axios": "0.26.1",
34
34
  "currency.js": "2.0.4",
35
- "debug": "4.3.2"
35
+ "debug": "4.3.2",
36
+ "react-intersection-observer": "9.1.0"
36
37
  },
37
38
  "peerDependencies": {
38
39
  "@appbaseio/reactivesearch": "^3.16.1",