@jobber/hooks 2.9.2-CJS-to-ESM.19 → 2.9.2-CJS-to-ESM.25
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/README.mdx +4 -0
- package/dist/index.cjs +806 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.js.map +1 -0
- package/dist/useAssert/index.cjs +53 -0
- package/dist/useAssert/index.cjs.map +1 -0
- package/dist/useAssert/index.js.map +1 -0
- package/dist/useBool/index.cjs +40 -0
- package/dist/useBool/index.cjs.map +1 -0
- package/dist/useBool/index.js.map +1 -0
- package/dist/useBreakpoints/index.cjs +138 -0
- package/dist/useBreakpoints/index.cjs.map +1 -0
- package/dist/useBreakpoints/index.js.map +1 -0
- package/dist/useCollectionQuery/index.cjs +389 -0
- package/dist/useCollectionQuery/index.cjs.map +1 -0
- package/dist/useCollectionQuery/index.js.map +1 -0
- package/dist/useFocusTrap/index.cjs +84 -0
- package/dist/useFocusTrap/index.cjs.map +1 -0
- package/dist/useFocusTrap/index.js.map +1 -0
- package/dist/useInView/index.cjs +51 -0
- package/dist/useInView/index.cjs.map +1 -0
- package/dist/useInView/index.js.map +1 -0
- package/dist/useIsMounted/index.cjs +49 -0
- package/dist/useIsMounted/index.cjs.map +1 -0
- package/dist/useIsMounted/index.js.map +1 -0
- package/dist/useLiveAnnounce/index.cjs +64 -0
- package/dist/useLiveAnnounce/index.cjs.map +1 -0
- package/dist/useLiveAnnounce/index.js.map +1 -0
- package/dist/useOnKeyDown/index.cjs +62 -0
- package/dist/useOnKeyDown/index.cjs.map +1 -0
- package/dist/useOnKeyDown/index.js.map +1 -0
- package/dist/usePasswordStrength/index.cjs +62 -0
- package/dist/usePasswordStrength/index.cjs.map +1 -0
- package/dist/usePasswordStrength/index.js.map +1 -0
- package/dist/useRefocusOnActivator/index.cjs +49 -0
- package/dist/useRefocusOnActivator/index.cjs.map +1 -0
- package/dist/useRefocusOnActivator/index.js.map +1 -0
- package/dist/useResizeObserver/index.cjs +84 -0
- package/dist/useResizeObserver/index.cjs.map +1 -0
- package/dist/useResizeObserver/index.js.map +1 -0
- package/dist/useSafeLayoutEffect/index.cjs +34 -0
- package/dist/useSafeLayoutEffect/index.cjs.map +1 -0
- package/dist/useSafeLayoutEffect/index.js.map +1 -0
- package/dist/useShowClear/index.cjs +52 -0
- package/dist/useShowClear/index.cjs.map +1 -0
- package/dist/useShowClear/index.js.map +1 -0
- package/package.json +22 -18
|
@@ -0,0 +1,389 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __create = Object.create;
|
|
3
|
+
var __defProp = Object.defineProperty;
|
|
4
|
+
var __defProps = Object.defineProperties;
|
|
5
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
6
|
+
var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
|
|
7
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
8
|
+
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
|
|
9
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
10
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
11
|
+
var __propIsEnum = Object.prototype.propertyIsEnumerable;
|
|
12
|
+
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
|
|
13
|
+
var __spreadValues = (a, b) => {
|
|
14
|
+
for (var prop in b || (b = {}))
|
|
15
|
+
if (__hasOwnProp.call(b, prop))
|
|
16
|
+
__defNormalProp(a, prop, b[prop]);
|
|
17
|
+
if (__getOwnPropSymbols)
|
|
18
|
+
for (var prop of __getOwnPropSymbols(b)) {
|
|
19
|
+
if (__propIsEnum.call(b, prop))
|
|
20
|
+
__defNormalProp(a, prop, b[prop]);
|
|
21
|
+
}
|
|
22
|
+
return a;
|
|
23
|
+
};
|
|
24
|
+
var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
|
|
25
|
+
var __commonJS = (cb, mod) => function __require() {
|
|
26
|
+
return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
|
|
27
|
+
};
|
|
28
|
+
var __export = (target, all) => {
|
|
29
|
+
for (var name in all)
|
|
30
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
31
|
+
};
|
|
32
|
+
var __copyProps = (to, from, except, desc) => {
|
|
33
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
34
|
+
for (let key of __getOwnPropNames(from))
|
|
35
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
36
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
37
|
+
}
|
|
38
|
+
return to;
|
|
39
|
+
};
|
|
40
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
41
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
42
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
43
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
44
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
45
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
46
|
+
mod
|
|
47
|
+
));
|
|
48
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
49
|
+
|
|
50
|
+
// ../formatters/dist/global.js
|
|
51
|
+
var require_global = __commonJS({
|
|
52
|
+
"../formatters/dist/global.js"(exports2) {
|
|
53
|
+
"use strict";
|
|
54
|
+
Object.defineProperty(exports2, "__esModule", { value: true });
|
|
55
|
+
exports2.global = void 0;
|
|
56
|
+
function getGlobal() {
|
|
57
|
+
if (typeof window !== "undefined") {
|
|
58
|
+
return window;
|
|
59
|
+
}
|
|
60
|
+
return global;
|
|
61
|
+
}
|
|
62
|
+
var glob = getGlobal();
|
|
63
|
+
exports2.global = glob;
|
|
64
|
+
}
|
|
65
|
+
});
|
|
66
|
+
|
|
67
|
+
// ../formatters/dist/config.js
|
|
68
|
+
var require_config = __commonJS({
|
|
69
|
+
"../formatters/dist/config.js"(exports2) {
|
|
70
|
+
"use strict";
|
|
71
|
+
Object.defineProperty(exports2, "__esModule", { value: true });
|
|
72
|
+
exports2.config = void 0;
|
|
73
|
+
var global_1 = require_global();
|
|
74
|
+
var configOverrides = (global_1.global.ATLANTIS_ENV || {}).config || {};
|
|
75
|
+
exports2.config = Object.freeze(Object.assign({ defaultCurrency: "USD", errorNotifier(message, error) {
|
|
76
|
+
console.error(message, error);
|
|
77
|
+
} }, configOverrides));
|
|
78
|
+
}
|
|
79
|
+
});
|
|
80
|
+
|
|
81
|
+
// ../formatters/dist/currency.js
|
|
82
|
+
var require_currency = __commonJS({
|
|
83
|
+
"../formatters/dist/currency.js"(exports2) {
|
|
84
|
+
"use strict";
|
|
85
|
+
Object.defineProperty(exports2, "__esModule", { value: true });
|
|
86
|
+
exports2.formatCurrency = void 0;
|
|
87
|
+
var config_1 = require_config();
|
|
88
|
+
function formatCurrency(amount, currency = config_1.config.defaultCurrency) {
|
|
89
|
+
return amount.toLocaleString("en", {
|
|
90
|
+
style: "currency",
|
|
91
|
+
currency
|
|
92
|
+
});
|
|
93
|
+
}
|
|
94
|
+
exports2.formatCurrency = formatCurrency;
|
|
95
|
+
}
|
|
96
|
+
});
|
|
97
|
+
|
|
98
|
+
// ../formatters/dist/CurrencyType.js
|
|
99
|
+
var require_CurrencyType = __commonJS({
|
|
100
|
+
"../formatters/dist/CurrencyType.js"(exports2) {
|
|
101
|
+
"use strict";
|
|
102
|
+
Object.defineProperty(exports2, "__esModule", { value: true });
|
|
103
|
+
}
|
|
104
|
+
});
|
|
105
|
+
|
|
106
|
+
// ../formatters/dist/index.js
|
|
107
|
+
var require_dist = __commonJS({
|
|
108
|
+
"../formatters/dist/index.js"(exports2) {
|
|
109
|
+
"use strict";
|
|
110
|
+
var __createBinding = exports2 && exports2.__createBinding || (Object.create ? function(o, m, k, k2) {
|
|
111
|
+
if (k2 === void 0)
|
|
112
|
+
k2 = k;
|
|
113
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
114
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
115
|
+
desc = { enumerable: true, get: function() {
|
|
116
|
+
return m[k];
|
|
117
|
+
} };
|
|
118
|
+
}
|
|
119
|
+
Object.defineProperty(o, k2, desc);
|
|
120
|
+
} : function(o, m, k, k2) {
|
|
121
|
+
if (k2 === void 0)
|
|
122
|
+
k2 = k;
|
|
123
|
+
o[k2] = m[k];
|
|
124
|
+
});
|
|
125
|
+
var __exportStar = exports2 && exports2.__exportStar || function(m, exports3) {
|
|
126
|
+
for (var p in m)
|
|
127
|
+
if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p))
|
|
128
|
+
__createBinding(exports3, m, p);
|
|
129
|
+
};
|
|
130
|
+
Object.defineProperty(exports2, "__esModule", { value: true });
|
|
131
|
+
__exportStar(require_currency(), exports2);
|
|
132
|
+
__exportStar(require_CurrencyType(), exports2);
|
|
133
|
+
__exportStar(require_config(), exports2);
|
|
134
|
+
}
|
|
135
|
+
});
|
|
136
|
+
|
|
137
|
+
// src/useCollectionQuery/index.ts
|
|
138
|
+
var useCollectionQuery_exports = {};
|
|
139
|
+
__export(useCollectionQuery_exports, {
|
|
140
|
+
useCollectionQuery: () => useCollectionQuery
|
|
141
|
+
});
|
|
142
|
+
module.exports = __toCommonJS(useCollectionQuery_exports);
|
|
143
|
+
|
|
144
|
+
// src/useCollectionQuery/useCollectionQuery.ts
|
|
145
|
+
var import_client = require("@apollo/client");
|
|
146
|
+
var import_lodash = require("lodash");
|
|
147
|
+
var import_react3 = require("react");
|
|
148
|
+
var import_formatters = __toESM(require_dist(), 1);
|
|
149
|
+
|
|
150
|
+
// src/useCollectionQuery/uniqueNodes.tsx
|
|
151
|
+
function uniqueNodes(nodes) {
|
|
152
|
+
const result = /* @__PURE__ */ new Map();
|
|
153
|
+
nodes.forEach((node) => {
|
|
154
|
+
result.set(`${node.__typename}-${node.id}`, node);
|
|
155
|
+
});
|
|
156
|
+
return Array.from(result.values());
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
// src/useCollectionQuery/uniqueEdges.tsx
|
|
160
|
+
function createEdge(node) {
|
|
161
|
+
return {
|
|
162
|
+
node,
|
|
163
|
+
cursor: "",
|
|
164
|
+
__typename: `${node.__typename}Edge`
|
|
165
|
+
};
|
|
166
|
+
}
|
|
167
|
+
function uniqueEdges(edges) {
|
|
168
|
+
const result = /* @__PURE__ */ new Map();
|
|
169
|
+
edges.forEach((edge) => {
|
|
170
|
+
result.set(
|
|
171
|
+
`${edge.__typename}-${edge.node.__typename}-${edge.node.id}`,
|
|
172
|
+
edge
|
|
173
|
+
);
|
|
174
|
+
});
|
|
175
|
+
return Array.from(result.values());
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
// src/useIsMounted/useIsMounted.ts
|
|
179
|
+
var import_react2 = require("react");
|
|
180
|
+
|
|
181
|
+
// src/useSafeLayoutEffect/useSafeLayoutEffect.ts
|
|
182
|
+
var import_react = require("react");
|
|
183
|
+
var useSafeLayoutEffect = (globalThis == null ? void 0 : globalThis.document) ? import_react.useLayoutEffect : import_react.useEffect;
|
|
184
|
+
|
|
185
|
+
// src/useIsMounted/useIsMounted.ts
|
|
186
|
+
function useIsMounted() {
|
|
187
|
+
const isMounted = (0, import_react2.useRef)(false);
|
|
188
|
+
useSafeLayoutEffect(() => {
|
|
189
|
+
isMounted.current = true;
|
|
190
|
+
return () => {
|
|
191
|
+
isMounted.current = false;
|
|
192
|
+
};
|
|
193
|
+
}, []);
|
|
194
|
+
return isMounted;
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
// src/useCollectionQuery/useCollectionQuery.ts
|
|
198
|
+
function useCollectionQuery({
|
|
199
|
+
query,
|
|
200
|
+
queryOptions,
|
|
201
|
+
getCollectionByPath,
|
|
202
|
+
subscription
|
|
203
|
+
}) {
|
|
204
|
+
var _a, _b;
|
|
205
|
+
const { data, loading, refetch, error, fetchMore, subscribeToMore } = (0, import_client.useQuery)(query, queryOptions);
|
|
206
|
+
const isMounted = useIsMounted();
|
|
207
|
+
const [loadingRefresh, setLoadingRefresh] = (0, import_react3.useState)(false);
|
|
208
|
+
const [loadingNextPage, setLoadingNextPage] = (0, import_react3.useState)(false);
|
|
209
|
+
const [hookError, setHookError] = (0, import_react3.useState)();
|
|
210
|
+
const loadingInitialContent = loading && !loadingRefresh && !loadingNextPage;
|
|
211
|
+
const isSearching = !!((_a = queryOptions == null ? void 0 : queryOptions.variables) == null ? void 0 : _a.searchTerm);
|
|
212
|
+
const refresh = (0, import_react3.useCallback)(() => {
|
|
213
|
+
if (loadingInitialContent || loadingRefresh) {
|
|
214
|
+
return;
|
|
215
|
+
}
|
|
216
|
+
setLoadingRefresh(true);
|
|
217
|
+
fetchMore({
|
|
218
|
+
// a workaround fix for the error described in this post
|
|
219
|
+
// https://github.com/apollographql/apollo-client/issues/7491#issuecomment-767985363
|
|
220
|
+
// These changes can be reverted once we can update to version 3.4
|
|
221
|
+
// (the current release candidate)
|
|
222
|
+
variables: {},
|
|
223
|
+
updateQuery: (prev, { fetchMoreResult }) => fetchMoreResult || prev
|
|
224
|
+
}).catch((err) => import_formatters.config.errorNotifier("Refetch Error", err)).finally(() => {
|
|
225
|
+
if (isMounted.current) {
|
|
226
|
+
setLoadingRefresh(false);
|
|
227
|
+
}
|
|
228
|
+
});
|
|
229
|
+
}, [
|
|
230
|
+
loadingInitialContent,
|
|
231
|
+
loadingRefresh,
|
|
232
|
+
setLoadingRefresh,
|
|
233
|
+
refetch,
|
|
234
|
+
isMounted
|
|
235
|
+
]);
|
|
236
|
+
const nextPage = (0, import_react3.useCallback)(() => {
|
|
237
|
+
var _a2;
|
|
238
|
+
if (loadingInitialContent || loadingRefresh || loadingNextPage) {
|
|
239
|
+
return;
|
|
240
|
+
}
|
|
241
|
+
const pageInfo = (_a2 = getCollectionByPath(data)) == null ? void 0 : _a2.pageInfo;
|
|
242
|
+
if (!pageInfo || !pageInfo.hasNextPage) {
|
|
243
|
+
return;
|
|
244
|
+
}
|
|
245
|
+
setLoadingNextPage(true);
|
|
246
|
+
setHookError(void 0);
|
|
247
|
+
fetchMore({
|
|
248
|
+
variables: {
|
|
249
|
+
cursor: pageInfo.endCursor
|
|
250
|
+
},
|
|
251
|
+
updateQuery: (prev, { fetchMoreResult }) => fetchMoreUpdateQueryHandler(prev, fetchMoreResult, getCollectionByPath)
|
|
252
|
+
}).catch((err) => {
|
|
253
|
+
import_formatters.config.errorNotifier("FetchMore Error", err);
|
|
254
|
+
setHookError(err);
|
|
255
|
+
}).finally(() => {
|
|
256
|
+
if (isMounted.current) {
|
|
257
|
+
setLoadingNextPage(false);
|
|
258
|
+
}
|
|
259
|
+
});
|
|
260
|
+
}, [
|
|
261
|
+
data,
|
|
262
|
+
loadingInitialContent,
|
|
263
|
+
loadingRefresh,
|
|
264
|
+
fetchMore,
|
|
265
|
+
loadingNextPage,
|
|
266
|
+
setLoadingNextPage,
|
|
267
|
+
getCollectionByPath,
|
|
268
|
+
isMounted
|
|
269
|
+
]);
|
|
270
|
+
(0, import_react3.useEffect)(
|
|
271
|
+
() => {
|
|
272
|
+
if (subscription == void 0)
|
|
273
|
+
return;
|
|
274
|
+
const subscriptionOptions = subscription.options || {};
|
|
275
|
+
setHookError(void 0);
|
|
276
|
+
return subscribeToMore(__spreadProps(__spreadValues({}, subscriptionOptions), {
|
|
277
|
+
document: subscription.document,
|
|
278
|
+
updateQuery: (prev, { subscriptionData }) => subscribeToMoreHandler(
|
|
279
|
+
isSearching,
|
|
280
|
+
prev,
|
|
281
|
+
getCollectionByPath,
|
|
282
|
+
subscriptionData == null ? void 0 : subscriptionData.data,
|
|
283
|
+
subscription.getNodeByPath
|
|
284
|
+
),
|
|
285
|
+
onError: (err) => {
|
|
286
|
+
import_formatters.config.errorNotifier("Subscribe to More Error", err);
|
|
287
|
+
setHookError(err);
|
|
288
|
+
}
|
|
289
|
+
}));
|
|
290
|
+
},
|
|
291
|
+
// Disabling this linter so we can force this only run once. If we didn't
|
|
292
|
+
// do this we would need to ensure subscription, subscribeToMore, and getNodeByPath
|
|
293
|
+
// all use useCallback.
|
|
294
|
+
[(_b = queryOptions == null ? void 0 : queryOptions.variables) == null ? void 0 : _b.searchTerm]
|
|
295
|
+
);
|
|
296
|
+
const combinedError = error || hookError;
|
|
297
|
+
return {
|
|
298
|
+
data,
|
|
299
|
+
error: combinedError,
|
|
300
|
+
refresh,
|
|
301
|
+
loadingRefresh,
|
|
302
|
+
nextPage,
|
|
303
|
+
loadingNextPage,
|
|
304
|
+
loadingInitialContent
|
|
305
|
+
};
|
|
306
|
+
}
|
|
307
|
+
function fetchMoreUpdateQueryHandler(prev, fetchMoreResult, getCollectionByPath) {
|
|
308
|
+
const nextCollection = getCollectionByPath(fetchMoreResult);
|
|
309
|
+
const output = (0, import_lodash.cloneDeep)(prev);
|
|
310
|
+
const outputCollection = getCollectionByPath(output);
|
|
311
|
+
if (outputCollection === void 0 || nextCollection === void 0) {
|
|
312
|
+
return output;
|
|
313
|
+
}
|
|
314
|
+
if (outputCollection.nodes && nextCollection.nodes) {
|
|
315
|
+
outputCollection.nodes = getUpdatedNodes(
|
|
316
|
+
outputCollection.nodes,
|
|
317
|
+
nextCollection.nodes
|
|
318
|
+
);
|
|
319
|
+
}
|
|
320
|
+
if (outputCollection.edges && nextCollection.edges) {
|
|
321
|
+
outputCollection.edges = getUpdatedEdges(
|
|
322
|
+
outputCollection.edges,
|
|
323
|
+
nextCollection.edges
|
|
324
|
+
);
|
|
325
|
+
}
|
|
326
|
+
Object.assign(outputCollection, __spreadValues({
|
|
327
|
+
pageInfo: (0, import_lodash.cloneDeep)(nextCollection.pageInfo)
|
|
328
|
+
}, getTotalCount(nextCollection.totalCount)));
|
|
329
|
+
return output;
|
|
330
|
+
}
|
|
331
|
+
function subscribeToMoreHandler(isSearching, prev, getCollectionByPath, subscriptionData, getNodeByPath) {
|
|
332
|
+
const node = getNodeByPath(subscriptionData);
|
|
333
|
+
const output = (0, import_lodash.cloneDeep)(prev);
|
|
334
|
+
const outputCollection = getCollectionByPath(output);
|
|
335
|
+
if (outputCollection == void 0 || node == void 0)
|
|
336
|
+
return output;
|
|
337
|
+
if (isAlreadyUpdated(outputCollection, node) || isSearching) {
|
|
338
|
+
return prev;
|
|
339
|
+
}
|
|
340
|
+
if (outputCollection.nodes) {
|
|
341
|
+
outputCollection.nodes = getUpdatedNodes(
|
|
342
|
+
outputCollection.nodes,
|
|
343
|
+
[node],
|
|
344
|
+
false
|
|
345
|
+
);
|
|
346
|
+
}
|
|
347
|
+
if (outputCollection.edges) {
|
|
348
|
+
outputCollection.edges = getUpdatedEdges(
|
|
349
|
+
outputCollection.edges,
|
|
350
|
+
[createEdge(node)],
|
|
351
|
+
false
|
|
352
|
+
);
|
|
353
|
+
}
|
|
354
|
+
Object.assign(outputCollection, __spreadValues({
|
|
355
|
+
pageInfo: (0, import_lodash.cloneDeep)(outputCollection.pageInfo)
|
|
356
|
+
}, getTotalCount(outputCollection.totalCount, 1)));
|
|
357
|
+
return output;
|
|
358
|
+
}
|
|
359
|
+
function getTotalCount(totalCount, additionalCount = 0) {
|
|
360
|
+
return totalCount !== void 0 ? { totalCount: totalCount + additionalCount } : {};
|
|
361
|
+
}
|
|
362
|
+
function isAlreadyUpdated(outputCollection, newNode) {
|
|
363
|
+
let edgesAlreadyUpdated = true;
|
|
364
|
+
let nodesAlreadyUpdated = true;
|
|
365
|
+
if (outputCollection.edges) {
|
|
366
|
+
edgesAlreadyUpdated = outputCollection.edges.some((edge) => {
|
|
367
|
+
return edge.node.id === newNode.id;
|
|
368
|
+
});
|
|
369
|
+
}
|
|
370
|
+
if (outputCollection.nodes) {
|
|
371
|
+
nodesAlreadyUpdated = outputCollection.nodes.some((node) => {
|
|
372
|
+
return node.id === newNode.id;
|
|
373
|
+
});
|
|
374
|
+
}
|
|
375
|
+
return edgesAlreadyUpdated && nodesAlreadyUpdated;
|
|
376
|
+
}
|
|
377
|
+
function getUpdatedEdges(prevEdges, nextEdges, appendToEnd = true) {
|
|
378
|
+
const newEdges = appendToEnd ? [...prevEdges, ...nextEdges] : [...nextEdges, ...prevEdges];
|
|
379
|
+
return uniqueEdges(newEdges);
|
|
380
|
+
}
|
|
381
|
+
function getUpdatedNodes(prevNodes, nextNodes, appendToEnd = true) {
|
|
382
|
+
const newNodes = appendToEnd ? [...prevNodes, ...nextNodes] : [...nextNodes, ...prevNodes];
|
|
383
|
+
return uniqueNodes(newNodes);
|
|
384
|
+
}
|
|
385
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
386
|
+
0 && (module.exports = {
|
|
387
|
+
useCollectionQuery
|
|
388
|
+
});
|
|
389
|
+
//# sourceMappingURL=index.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../formatters/dist/global.js","../../../formatters/dist/config.js","../../../formatters/dist/currency.js","../../../formatters/dist/CurrencyType.js","../../../formatters/dist/index.js","../../src/useCollectionQuery/index.ts","../../src/useCollectionQuery/useCollectionQuery.ts","../../src/useCollectionQuery/uniqueNodes.tsx","../../src/useCollectionQuery/uniqueEdges.tsx","../../src/useIsMounted/useIsMounted.ts","../../src/useSafeLayoutEffect/useSafeLayoutEffect.ts"],"sourcesContent":["\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.global = void 0;\nfunction getGlobal() {\n if (typeof window !== \"undefined\") {\n return window;\n }\n return global;\n}\nconst glob = getGlobal();\nexports.global = glob;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.config = void 0;\nconst global_1 = require(\"./global\");\nconst configOverrides = (global_1.global.ATLANTIS_ENV || {}).config || {};\nexports.config = Object.freeze(Object.assign({ defaultCurrency: \"USD\", errorNotifier(message, error) {\n console.error(message, error);\n } }, configOverrides));\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.formatCurrency = void 0;\nconst config_1 = require(\"./config\");\nfunction formatCurrency(amount, currency = config_1.config.defaultCurrency) {\n return amount.toLocaleString(\"en\", {\n style: \"currency\",\n currency: currency,\n });\n}\nexports.formatCurrency = formatCurrency;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n","\"use strict\";\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __exportStar = (this && this.__exportStar) || function(m, exports) {\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\n__exportStar(require(\"./currency\"), exports);\n__exportStar(require(\"./CurrencyType\"), exports);\n__exportStar(require(\"./config\"), exports);\n","export { useCollectionQuery } from \"./useCollectionQuery\";\n","import {\n ApolloError,\n DocumentNode,\n QueryHookOptions,\n SubscribeToMoreOptions,\n useQuery,\n} from \"@apollo/client\";\nimport { cloneDeep } from \"lodash\";\nimport { useCallback, useEffect, useState } from \"react\";\nimport { config } from \"@jobber/formatters\";\nimport { Node, uniqueNodes } from \"./uniqueNodes\";\nimport { Edge, createEdge, uniqueEdges } from \"./uniqueEdges\";\nimport { useIsMounted } from \"../useIsMounted\";\n\ninterface UseCollectionQueryArguments<TQuery, TSubscription> {\n /**\n * The graphQL query that fetches the collection\n */\n query: DocumentNode;\n\n /**\n * A list of options for us to pass into the apollo `useQuery` hook\n */\n queryOptions?: QueryHookOptions<TQuery>;\n\n /**\n * A function that returns the location where the {@link Collection} is located.\n *\n * The collection is the part of the result that needs to be paginated.\n */\n getCollectionByPath: GetCollectionByPathFunction<TQuery>;\n\n /**\n * A list of subscription options if you want to create a GraphQL\n * subscription to listen for more content.\n */\n subscription?: ListSubscription<TSubscription>;\n}\n\ninterface ListSubscription<TSubscription> {\n /**\n * The graphQL subscription that listens for more data. This query should\n * return a single Node that matches the data structure in\n * `getCollectionByPath<TQuery>(...).edges.node` and\n * `getCollectionByPath<TQuery>(...).nodes\n */\n document: DocumentNode;\n\n /**\n * A list of variables to pass into the apollo `subscribeToMore` function.\n */\n options?: Pick<SubscribeToMoreOptions<TSubscription>, \"variables\">;\n\n /**\n * A function that returns the location where the `Node` is located on the\n * `TSubscription` object.\n *\n * It should return a single Node that matches the data structure in\n * `getCollectionByPath<TQuery>(...).edges.node` and\n * `getCollectionByPath<TQuery>(...).nodes\n */\n getNodeByPath: GetNodeByPath<TSubscription>;\n}\n\ninterface Collection {\n edges?: Edge[];\n nodes?: Node[];\n pageInfo: {\n endCursor?: string | undefined;\n hasNextPage: boolean;\n [otherProperties: string]: unknown;\n };\n totalCount?: number;\n [otherProperties: string]: unknown;\n}\n\ninterface CollectionQueryResult<TQuery> {\n data: TQuery | undefined;\n error: ApolloError | undefined;\n loadingRefresh: boolean;\n loadingNextPage: boolean;\n loadingInitialContent: boolean;\n refresh(): void;\n nextPage(): void;\n}\n\ntype GetCollectionByPathFunction<TQuery> = (\n data: TQuery | undefined,\n) => Collection | undefined;\n\ntype GetNodeByPath<TSubscription> = (\n data: TSubscription | undefined,\n) => Node | undefined;\n\nexport function useCollectionQuery<TQuery, TSubscription = undefined>({\n query,\n queryOptions,\n getCollectionByPath,\n subscription,\n}: UseCollectionQueryArguments<\n TQuery,\n TSubscription\n>): CollectionQueryResult<TQuery> {\n const { data, loading, refetch, error, fetchMore, subscribeToMore } =\n useQuery<TQuery>(query, queryOptions);\n\n const isMounted = useIsMounted();\n const [loadingRefresh, setLoadingRefresh] = useState<boolean>(false);\n const [loadingNextPage, setLoadingNextPage] = useState<boolean>(false);\n const [hookError, setHookError] = useState<ApolloError | undefined>();\n const loadingInitialContent = loading && !loadingRefresh && !loadingNextPage;\n const isSearching = !!queryOptions?.variables?.searchTerm;\n\n const refresh = useCallback(() => {\n if (loadingInitialContent || loadingRefresh) {\n return;\n }\n\n setLoadingRefresh(true);\n\n fetchMore({\n // a workaround fix for the error described in this post\n // https://github.com/apollographql/apollo-client/issues/7491#issuecomment-767985363\n // These changes can be reverted once we can update to version 3.4\n // (the current release candidate)\n variables: {},\n updateQuery: (prev, { fetchMoreResult }) => fetchMoreResult || prev,\n })\n .catch(err => config.errorNotifier(\"Refetch Error\", err))\n .finally(() => {\n if (isMounted.current) {\n setLoadingRefresh(false);\n }\n });\n }, [\n loadingInitialContent,\n loadingRefresh,\n setLoadingRefresh,\n refetch,\n isMounted,\n ]);\n\n const nextPage = useCallback(() => {\n if (loadingInitialContent || loadingRefresh || loadingNextPage) {\n return;\n }\n\n const pageInfo = getCollectionByPath(data)?.pageInfo;\n\n if (!pageInfo || !pageInfo.hasNextPage) {\n return;\n }\n\n setLoadingNextPage(true);\n setHookError(undefined);\n\n fetchMore({\n variables: {\n cursor: pageInfo.endCursor,\n },\n updateQuery: (prev, { fetchMoreResult }) =>\n fetchMoreUpdateQueryHandler(prev, fetchMoreResult, getCollectionByPath),\n })\n .catch(err => {\n config.errorNotifier(\"FetchMore Error\", err);\n setHookError(err);\n })\n .finally(() => {\n if (isMounted.current) {\n setLoadingNextPage(false);\n }\n });\n }, [\n data,\n loadingInitialContent,\n loadingRefresh,\n fetchMore,\n loadingNextPage,\n setLoadingNextPage,\n getCollectionByPath,\n isMounted,\n ]);\n\n useEffect(\n () => {\n if (subscription == undefined) return;\n\n const subscriptionOptions = subscription.options || {};\n\n // Reset this state so we can handle errors from the subscription\n setHookError(undefined);\n\n return subscribeToMore<TSubscription>({\n ...subscriptionOptions,\n document: subscription.document,\n updateQuery: (prev, { subscriptionData }) =>\n subscribeToMoreHandler(\n isSearching,\n prev,\n getCollectionByPath,\n subscriptionData?.data,\n subscription.getNodeByPath,\n ),\n onError: err => {\n config.errorNotifier(\"Subscribe to More Error\", err);\n setHookError(err as ApolloError);\n },\n });\n },\n // Disabling this linter so we can force this only run once. If we didn't\n // do this we would need to ensure subscription, subscribeToMore, and getNodeByPath\n // all use useCallback.\n [queryOptions?.variables?.searchTerm],\n );\n\n const combinedError = error || hookError;\n\n return {\n data,\n error: combinedError,\n refresh,\n loadingRefresh,\n nextPage,\n loadingNextPage,\n loadingInitialContent,\n };\n}\n\n/**\n * The following method uses an `output` variable, and indirectly modifies it through the `outputCollection` variable.\n * This type of indirect modification is prone to bugs, but I couldn't think of a better way to write this code.\n *\n * Here's what I was balancing:\n * 1. We need to copy the structure of prev to ensure that when we're combining two objects, we're not losing properties\n * 2. We need to extract a key from an unknown path that's given to us by getCollectionByPath and then we need to modify\n * that, and ensure that it's properly set on the cloned output object.\n * 3. We want to keep the interface to this hook as simple and easy to use as possible\n *\n * The alternative approaches that were rejected:\n * 1. We replace the getCollectionByPath with a keyPath string. (Eg. \"data.conversation.message\") and then we use lodash\n * `get` and `set` which should remove all the object manipulation. But, this approach loses us the type safety that\n * getCollectionByPath gives us\n * 2. We could add a setCollection function to the list of arguments for this hook. This leaves us with type safety but\n * makes the `useCollectionQuery` interface more complicated by adding arguments\n */\nfunction fetchMoreUpdateQueryHandler<TQuery>(\n prev: TQuery,\n fetchMoreResult: TQuery | undefined,\n getCollectionByPath: GetCollectionByPathFunction<TQuery>,\n): TQuery {\n const nextCollection = getCollectionByPath(fetchMoreResult);\n const output = cloneDeep(prev);\n const outputCollection = getCollectionByPath(output);\n\n if (outputCollection === undefined || nextCollection === undefined) {\n return output;\n }\n\n if (outputCollection.nodes && nextCollection.nodes) {\n outputCollection.nodes = getUpdatedNodes(\n outputCollection.nodes,\n nextCollection.nodes,\n );\n }\n\n if (outputCollection.edges && nextCollection.edges) {\n outputCollection.edges = getUpdatedEdges(\n outputCollection.edges,\n nextCollection.edges,\n );\n }\n\n Object.assign(outputCollection, {\n pageInfo: cloneDeep(nextCollection.pageInfo),\n ...getTotalCount(nextCollection.totalCount),\n });\n\n return output;\n}\n\nfunction subscribeToMoreHandler<TQuery, TSubscription>(\n isSearching: boolean,\n prev: TQuery,\n getCollectionByPath: GetCollectionByPathFunction<TQuery>,\n subscriptionData: TSubscription | undefined,\n getNodeByPath: GetNodeByPath<TSubscription>,\n): TQuery {\n const node = getNodeByPath(subscriptionData);\n const output = cloneDeep(prev);\n const outputCollection = getCollectionByPath(output);\n\n if (outputCollection == undefined || node == undefined) return output;\n\n if (isAlreadyUpdated(outputCollection, node) || isSearching) {\n return prev;\n }\n\n if (outputCollection.nodes) {\n outputCollection.nodes = getUpdatedNodes(\n outputCollection.nodes,\n [node],\n false,\n );\n }\n\n if (outputCollection.edges) {\n outputCollection.edges = getUpdatedEdges(\n outputCollection.edges,\n [createEdge(node)],\n false,\n );\n }\n\n Object.assign(outputCollection, {\n pageInfo: cloneDeep(outputCollection.pageInfo),\n ...getTotalCount(outputCollection.totalCount, 1),\n });\n\n return output;\n}\n\ninterface TotalCountReturn {\n totalCount?: number;\n}\n\nfunction getTotalCount(\n totalCount: number | undefined,\n additionalCount = 0,\n): TotalCountReturn {\n return totalCount !== undefined\n ? { totalCount: totalCount + additionalCount }\n : {};\n}\n\nexport function isAlreadyUpdated(outputCollection: Collection, newNode: Node) {\n let edgesAlreadyUpdated = true;\n let nodesAlreadyUpdated = true;\n\n if (outputCollection.edges) {\n edgesAlreadyUpdated = outputCollection.edges.some(edge => {\n return edge.node.id === newNode.id;\n });\n }\n\n if (outputCollection.nodes) {\n nodesAlreadyUpdated = outputCollection.nodes.some(node => {\n return node.id === newNode.id;\n });\n }\n\n return edgesAlreadyUpdated && nodesAlreadyUpdated;\n}\n\nfunction getUpdatedEdges(\n prevEdges: Edge[],\n nextEdges: Edge[],\n appendToEnd = true,\n) {\n const newEdges = appendToEnd\n ? [...prevEdges, ...nextEdges]\n : [...nextEdges, ...prevEdges];\n\n return uniqueEdges(newEdges);\n}\n\nfunction getUpdatedNodes(\n prevNodes: Node[],\n nextNodes: Node[],\n appendToEnd = true,\n) {\n const newNodes = appendToEnd\n ? [...prevNodes, ...nextNodes]\n : [...nextNodes, ...prevNodes];\n\n return uniqueNodes(newNodes);\n}\n","export interface Node {\n id: unknown;\n __typename?: unknown;\n}\n\nexport function uniqueNodes(nodes: Node[]): Node[] {\n const result = new Map<string, Node>();\n nodes.forEach(node => {\n result.set(`${node.__typename}-${node.id}`, node);\n });\n\n return Array.from(result.values());\n}\n","import { Node } from \"./uniqueNodes\";\n\nexport interface Edge {\n __typename?: unknown;\n node: Node;\n cursor: string;\n}\n\nexport function createEdge(node: Node): Edge {\n return {\n node: node,\n cursor: \"\",\n __typename: `${node.__typename}Edge`,\n };\n}\n\nexport function uniqueEdges(edges: Edge[]): Edge[] {\n const result = new Map<string, Edge>();\n edges.forEach(edge => {\n result.set(\n `${edge.__typename}-${edge.node.__typename}-${edge.node.id}`,\n edge,\n );\n });\n\n return Array.from(result.values());\n}\n","import { useRef } from \"react\";\nimport { useSafeLayoutEffect } from \"../useSafeLayoutEffect\";\n\n/**\n * Why does this work?\n *\n * The following is from the react docs:\n * [The return function from `useLayoutEffect`] is the optional cleanup mechanism for effects.\n * Every effect may return a function that cleans up after it.\n *\n * When exactly does React clean up an effect? React performs the cleanup when the component unmounts.\n * The cleanup for useLayoutEffect is called after component unmounts and before before browser painting\n * the screen\n *\n * What does that mean for us? When this hook is initially loaded, we then trigger a `useLayoutEffect` that\n * sets the isMounted to true right after the component is mounted.\n * When the component unmounts, it calls the cleanup function that sets `isMounted` to false.\n * This `useLayoutEffect` hook will only be run once.\n */\nexport function useIsMounted(): { current: boolean } {\n const isMounted = useRef(false);\n\n useSafeLayoutEffect(() => {\n isMounted.current = true;\n\n return () => {\n isMounted.current = false;\n };\n }, []);\n\n return isMounted;\n}\n","import { useEffect, useLayoutEffect } from \"react\";\n\nexport const useSafeLayoutEffect = globalThis?.document\n ? useLayoutEffect\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,"sources":["../../../formatters/dist/global.js","../../../formatters/dist/config.js","../../../formatters/dist/currency.js","../../../formatters/dist/CurrencyType.js","../../../formatters/dist/index.js","../../src/useCollectionQuery/useCollectionQuery.ts","../../src/useCollectionQuery/uniqueNodes.tsx","../../src/useCollectionQuery/uniqueEdges.tsx","../../src/useIsMounted/useIsMounted.ts","../../src/useSafeLayoutEffect/useSafeLayoutEffect.ts"],"sourcesContent":["\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.global = void 0;\nfunction getGlobal() {\n if (typeof window !== \"undefined\") {\n return window;\n }\n return global;\n}\nconst glob = getGlobal();\nexports.global = glob;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.config = void 0;\nconst global_1 = require(\"./global\");\nconst configOverrides = (global_1.global.ATLANTIS_ENV || {}).config || {};\nexports.config = Object.freeze(Object.assign({ defaultCurrency: \"USD\", errorNotifier(message, error) {\n console.error(message, error);\n } }, configOverrides));\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.formatCurrency = void 0;\nconst config_1 = require(\"./config\");\nfunction formatCurrency(amount, currency = config_1.config.defaultCurrency) {\n return amount.toLocaleString(\"en\", {\n style: \"currency\",\n currency: currency,\n });\n}\nexports.formatCurrency = formatCurrency;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n","\"use strict\";\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __exportStar = (this && this.__exportStar) || function(m, exports) {\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\n__exportStar(require(\"./currency\"), exports);\n__exportStar(require(\"./CurrencyType\"), exports);\n__exportStar(require(\"./config\"), exports);\n","import {\n ApolloError,\n DocumentNode,\n QueryHookOptions,\n SubscribeToMoreOptions,\n useQuery,\n} from \"@apollo/client\";\nimport { cloneDeep } from \"lodash\";\nimport { useCallback, useEffect, useState } from \"react\";\nimport { config } from \"@jobber/formatters\";\nimport { Node, uniqueNodes } from \"./uniqueNodes\";\nimport { Edge, createEdge, uniqueEdges } from \"./uniqueEdges\";\nimport { useIsMounted } from \"../useIsMounted\";\n\ninterface UseCollectionQueryArguments<TQuery, TSubscription> {\n /**\n * The graphQL query that fetches the collection\n */\n query: DocumentNode;\n\n /**\n * A list of options for us to pass into the apollo `useQuery` hook\n */\n queryOptions?: QueryHookOptions<TQuery>;\n\n /**\n * A function that returns the location where the {@link Collection} is located.\n *\n * The collection is the part of the result that needs to be paginated.\n */\n getCollectionByPath: GetCollectionByPathFunction<TQuery>;\n\n /**\n * A list of subscription options if you want to create a GraphQL\n * subscription to listen for more content.\n */\n subscription?: ListSubscription<TSubscription>;\n}\n\ninterface ListSubscription<TSubscription> {\n /**\n * The graphQL subscription that listens for more data. This query should\n * return a single Node that matches the data structure in\n * `getCollectionByPath<TQuery>(...).edges.node` and\n * `getCollectionByPath<TQuery>(...).nodes\n */\n document: DocumentNode;\n\n /**\n * A list of variables to pass into the apollo `subscribeToMore` function.\n */\n options?: Pick<SubscribeToMoreOptions<TSubscription>, \"variables\">;\n\n /**\n * A function that returns the location where the `Node` is located on the\n * `TSubscription` object.\n *\n * It should return a single Node that matches the data structure in\n * `getCollectionByPath<TQuery>(...).edges.node` and\n * `getCollectionByPath<TQuery>(...).nodes\n */\n getNodeByPath: GetNodeByPath<TSubscription>;\n}\n\ninterface Collection {\n edges?: Edge[];\n nodes?: Node[];\n pageInfo: {\n endCursor?: string | undefined;\n hasNextPage: boolean;\n [otherProperties: string]: unknown;\n };\n totalCount?: number;\n [otherProperties: string]: unknown;\n}\n\ninterface CollectionQueryResult<TQuery> {\n data: TQuery | undefined;\n error: ApolloError | undefined;\n loadingRefresh: boolean;\n loadingNextPage: boolean;\n loadingInitialContent: boolean;\n refresh(): void;\n nextPage(): void;\n}\n\ntype GetCollectionByPathFunction<TQuery> = (\n data: TQuery | undefined,\n) => Collection | undefined;\n\ntype GetNodeByPath<TSubscription> = (\n data: TSubscription | undefined,\n) => Node | undefined;\n\nexport function useCollectionQuery<TQuery, TSubscription = undefined>({\n query,\n queryOptions,\n getCollectionByPath,\n subscription,\n}: UseCollectionQueryArguments<\n TQuery,\n TSubscription\n>): CollectionQueryResult<TQuery> {\n const { data, loading, refetch, error, fetchMore, subscribeToMore } =\n useQuery<TQuery>(query, queryOptions);\n\n const isMounted = useIsMounted();\n const [loadingRefresh, setLoadingRefresh] = useState<boolean>(false);\n const [loadingNextPage, setLoadingNextPage] = useState<boolean>(false);\n const [hookError, setHookError] = useState<ApolloError | undefined>();\n const loadingInitialContent = loading && !loadingRefresh && !loadingNextPage;\n const isSearching = !!queryOptions?.variables?.searchTerm;\n\n const refresh = useCallback(() => {\n if (loadingInitialContent || loadingRefresh) {\n return;\n }\n\n setLoadingRefresh(true);\n\n fetchMore({\n // a workaround fix for the error described in this post\n // https://github.com/apollographql/apollo-client/issues/7491#issuecomment-767985363\n // These changes can be reverted once we can update to version 3.4\n // (the current release candidate)\n variables: {},\n updateQuery: (prev, { fetchMoreResult }) => fetchMoreResult || prev,\n })\n .catch(err => config.errorNotifier(\"Refetch Error\", err))\n .finally(() => {\n if (isMounted.current) {\n setLoadingRefresh(false);\n }\n });\n }, [\n loadingInitialContent,\n loadingRefresh,\n setLoadingRefresh,\n refetch,\n isMounted,\n ]);\n\n const nextPage = useCallback(() => {\n if (loadingInitialContent || loadingRefresh || loadingNextPage) {\n return;\n }\n\n const pageInfo = getCollectionByPath(data)?.pageInfo;\n\n if (!pageInfo || !pageInfo.hasNextPage) {\n return;\n }\n\n setLoadingNextPage(true);\n setHookError(undefined);\n\n fetchMore({\n variables: {\n cursor: pageInfo.endCursor,\n },\n updateQuery: (prev, { fetchMoreResult }) =>\n fetchMoreUpdateQueryHandler(prev, fetchMoreResult, getCollectionByPath),\n })\n .catch(err => {\n config.errorNotifier(\"FetchMore Error\", err);\n setHookError(err);\n })\n .finally(() => {\n if (isMounted.current) {\n setLoadingNextPage(false);\n }\n });\n }, [\n data,\n loadingInitialContent,\n loadingRefresh,\n fetchMore,\n loadingNextPage,\n setLoadingNextPage,\n getCollectionByPath,\n isMounted,\n ]);\n\n useEffect(\n () => {\n if (subscription == undefined) return;\n\n const subscriptionOptions = subscription.options || {};\n\n // Reset this state so we can handle errors from the subscription\n setHookError(undefined);\n\n return subscribeToMore<TSubscription>({\n ...subscriptionOptions,\n document: subscription.document,\n updateQuery: (prev, { subscriptionData }) =>\n subscribeToMoreHandler(\n isSearching,\n prev,\n getCollectionByPath,\n subscriptionData?.data,\n subscription.getNodeByPath,\n ),\n onError: err => {\n config.errorNotifier(\"Subscribe to More Error\", err);\n setHookError(err as ApolloError);\n },\n });\n },\n // Disabling this linter so we can force this only run once. If we didn't\n // do this we would need to ensure subscription, subscribeToMore, and getNodeByPath\n // all use useCallback.\n [queryOptions?.variables?.searchTerm],\n );\n\n const combinedError = error || hookError;\n\n return {\n data,\n error: combinedError,\n refresh,\n loadingRefresh,\n nextPage,\n loadingNextPage,\n loadingInitialContent,\n };\n}\n\n/**\n * The following method uses an `output` variable, and indirectly modifies it through the `outputCollection` variable.\n * This type of indirect modification is prone to bugs, but I couldn't think of a better way to write this code.\n *\n * Here's what I was balancing:\n * 1. We need to copy the structure of prev to ensure that when we're combining two objects, we're not losing properties\n * 2. We need to extract a key from an unknown path that's given to us by getCollectionByPath and then we need to modify\n * that, and ensure that it's properly set on the cloned output object.\n * 3. We want to keep the interface to this hook as simple and easy to use as possible\n *\n * The alternative approaches that were rejected:\n * 1. We replace the getCollectionByPath with a keyPath string. (Eg. \"data.conversation.message\") and then we use lodash\n * `get` and `set` which should remove all the object manipulation. But, this approach loses us the type safety that\n * getCollectionByPath gives us\n * 2. We could add a setCollection function to the list of arguments for this hook. This leaves us with type safety but\n * makes the `useCollectionQuery` interface more complicated by adding arguments\n */\nfunction fetchMoreUpdateQueryHandler<TQuery>(\n prev: TQuery,\n fetchMoreResult: TQuery | undefined,\n getCollectionByPath: GetCollectionByPathFunction<TQuery>,\n): TQuery {\n const nextCollection = getCollectionByPath(fetchMoreResult);\n const output = cloneDeep(prev);\n const outputCollection = getCollectionByPath(output);\n\n if (outputCollection === undefined || nextCollection === undefined) {\n return output;\n }\n\n if (outputCollection.nodes && nextCollection.nodes) {\n outputCollection.nodes = getUpdatedNodes(\n outputCollection.nodes,\n nextCollection.nodes,\n );\n }\n\n if (outputCollection.edges && nextCollection.edges) {\n outputCollection.edges = getUpdatedEdges(\n outputCollection.edges,\n nextCollection.edges,\n );\n }\n\n Object.assign(outputCollection, {\n pageInfo: cloneDeep(nextCollection.pageInfo),\n ...getTotalCount(nextCollection.totalCount),\n });\n\n return output;\n}\n\nfunction subscribeToMoreHandler<TQuery, TSubscription>(\n isSearching: boolean,\n prev: TQuery,\n getCollectionByPath: GetCollectionByPathFunction<TQuery>,\n subscriptionData: TSubscription | undefined,\n getNodeByPath: GetNodeByPath<TSubscription>,\n): TQuery {\n const node = getNodeByPath(subscriptionData);\n const output = cloneDeep(prev);\n const outputCollection = getCollectionByPath(output);\n\n if (outputCollection == undefined || node == undefined) return output;\n\n if (isAlreadyUpdated(outputCollection, node) || isSearching) {\n return prev;\n }\n\n if (outputCollection.nodes) {\n outputCollection.nodes = getUpdatedNodes(\n outputCollection.nodes,\n [node],\n false,\n );\n }\n\n if (outputCollection.edges) {\n outputCollection.edges = getUpdatedEdges(\n outputCollection.edges,\n [createEdge(node)],\n false,\n );\n }\n\n Object.assign(outputCollection, {\n pageInfo: cloneDeep(outputCollection.pageInfo),\n ...getTotalCount(outputCollection.totalCount, 1),\n });\n\n return output;\n}\n\ninterface TotalCountReturn {\n totalCount?: number;\n}\n\nfunction getTotalCount(\n totalCount: number | undefined,\n additionalCount = 0,\n): TotalCountReturn {\n return totalCount !== undefined\n ? { totalCount: totalCount + additionalCount }\n : {};\n}\n\nexport function isAlreadyUpdated(outputCollection: Collection, newNode: Node) {\n let edgesAlreadyUpdated = true;\n let nodesAlreadyUpdated = true;\n\n if (outputCollection.edges) {\n edgesAlreadyUpdated = outputCollection.edges.some(edge => {\n return edge.node.id === newNode.id;\n });\n }\n\n if (outputCollection.nodes) {\n nodesAlreadyUpdated = outputCollection.nodes.some(node => {\n return node.id === newNode.id;\n });\n }\n\n return edgesAlreadyUpdated && nodesAlreadyUpdated;\n}\n\nfunction getUpdatedEdges(\n prevEdges: Edge[],\n nextEdges: Edge[],\n appendToEnd = true,\n) {\n const newEdges = appendToEnd\n ? [...prevEdges, ...nextEdges]\n : [...nextEdges, ...prevEdges];\n\n return uniqueEdges(newEdges);\n}\n\nfunction getUpdatedNodes(\n prevNodes: Node[],\n nextNodes: Node[],\n appendToEnd = true,\n) {\n const newNodes = appendToEnd\n ? [...prevNodes, ...nextNodes]\n : [...nextNodes, ...prevNodes];\n\n return uniqueNodes(newNodes);\n}\n","export interface Node {\n id: unknown;\n __typename?: unknown;\n}\n\nexport function uniqueNodes(nodes: Node[]): Node[] {\n const result = new Map<string, Node>();\n nodes.forEach(node => {\n result.set(`${node.__typename}-${node.id}`, node);\n });\n\n return Array.from(result.values());\n}\n","import { Node } from \"./uniqueNodes\";\n\nexport interface Edge {\n __typename?: unknown;\n node: Node;\n cursor: string;\n}\n\nexport function createEdge(node: Node): Edge {\n return {\n node: node,\n cursor: \"\",\n __typename: `${node.__typename}Edge`,\n };\n}\n\nexport function uniqueEdges(edges: Edge[]): Edge[] {\n const result = new Map<string, Edge>();\n edges.forEach(edge => {\n result.set(\n `${edge.__typename}-${edge.node.__typename}-${edge.node.id}`,\n edge,\n );\n });\n\n return Array.from(result.values());\n}\n","import { useRef } from \"react\";\nimport { useSafeLayoutEffect } from \"../useSafeLayoutEffect\";\n\n/**\n * Why does this work?\n *\n * The following is from the react docs:\n * [The return function from `useLayoutEffect`] is the optional cleanup mechanism for effects.\n * Every effect may return a function that cleans up after it.\n *\n * When exactly does React clean up an effect? React performs the cleanup when the component unmounts.\n * The cleanup for useLayoutEffect is called after component unmounts and before before browser painting\n * the screen\n *\n * What does that mean for us? When this hook is initially loaded, we then trigger a `useLayoutEffect` that\n * sets the isMounted to true right after the component is mounted.\n * When the component unmounts, it calls the cleanup function that sets `isMounted` to false.\n * This `useLayoutEffect` hook will only be run once.\n */\nexport function useIsMounted(): { current: boolean } {\n const isMounted = useRef(false);\n\n useSafeLayoutEffect(() => {\n isMounted.current = true;\n\n return () => {\n isMounted.current = false;\n };\n }, []);\n\n return isMounted;\n}\n","import { useEffect, useLayoutEffect } from \"react\";\n\nexport const useSafeLayoutEffect = globalThis?.document\n ? useLayoutEffect\n : useEffect;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AACA,WAAO,eAAe,SAAS,cAAc,EAAE,OAAO,KAAK,CAAC;AAC5D,YAAQ,SAAS;AACjB,aAAS,YAAY;AACjB,UAAI,OAAO,WAAW,aAAa;AAC/B,eAAO;AAAA,MACX;AACA,aAAO;AAAA,IACX;AACA,QAAM,OAAO,UAAU;AACvB,YAAQ,SAAS;AAAA;AAAA;;;ACVjB;AAAA;AAAA;AACA,WAAO,eAAe,SAAS,cAAc,EAAE,OAAO,KAAK,CAAC;AAC5D,YAAQ,SAAS;AACjB,QAAM,WAAW;AACjB,QAAM,mBAAmB,SAAS,OAAO,gBAAgB,CAAC,GAAG,UAAU,CAAC;AACxE,YAAQ,SAAS,OAAO,OAAO,OAAO,OAAO,EAAE,iBAAiB,OAAO,cAAc,SAAS,OAAO;AAC7F,cAAQ,MAAM,SAAS,KAAK;AAAA,IAChC,EAAE,GAAG,eAAe,CAAC;A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Q;AAAA,IAC7B,CAAC;AAAA,EACH;AAEA,SAAO,uBAAuB;AAChC;AAEA,SAAS,gBACP,WACA,WACA,cAAc,MACd;AACA,QAAM,WAAW,cACb,CAAC,GAAG,WAAW,GAAG,SAAS,IAC3B,CAAC,GAAG,WAAW,GAAG,SAAS;AAE/B,SAAO,YAAY,QAAQ;AAC7B;AAEA,SAAS,gBACP,WACA,WACA,cAAc,MACd;AACA,QAAM,WAAW,cACb,CAAC,GAAG,WAAW,GAAG,SAAS,IAC3B,CAAC,GAAG,WAAW,GAAG,SAAS;AAE/B,SAAO,YAAY,QAAQ;AAC7B;","names":["exports","useEffect","_a","useEffect"]}
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
|
|
20
|
+
// src/useFocusTrap/index.ts
|
|
21
|
+
var useFocusTrap_exports = {};
|
|
22
|
+
__export(useFocusTrap_exports, {
|
|
23
|
+
useFocusTrap: () => useFocusTrap
|
|
24
|
+
});
|
|
25
|
+
module.exports = __toCommonJS(useFocusTrap_exports);
|
|
26
|
+
|
|
27
|
+
// src/useFocusTrap/useFocusTrap.ts
|
|
28
|
+
var import_react = require("react");
|
|
29
|
+
function useFocusTrap(active) {
|
|
30
|
+
const ref = (0, import_react.useRef)(null);
|
|
31
|
+
function handleKeyDown(event) {
|
|
32
|
+
if (!(active && ref.current) || event.key !== "Tab") {
|
|
33
|
+
return;
|
|
34
|
+
}
|
|
35
|
+
const { firstElement, lastElement } = getElements(ref.current);
|
|
36
|
+
if (event.shiftKey) {
|
|
37
|
+
if (document.activeElement === firstElement) {
|
|
38
|
+
lastElement.focus();
|
|
39
|
+
event.preventDefault();
|
|
40
|
+
}
|
|
41
|
+
} else {
|
|
42
|
+
if (document.activeElement === lastElement) {
|
|
43
|
+
firstElement.focus();
|
|
44
|
+
event.preventDefault();
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
(0, import_react.useEffect)(() => {
|
|
49
|
+
if (active && ref.current) {
|
|
50
|
+
const { firstElement } = getElements(ref.current);
|
|
51
|
+
firstElement.focus();
|
|
52
|
+
ref.current.addEventListener("keydown", handleKeyDown);
|
|
53
|
+
}
|
|
54
|
+
return () => {
|
|
55
|
+
var _a;
|
|
56
|
+
(_a = ref.current) == null ? void 0 : _a.removeEventListener("keydown", handleKeyDown);
|
|
57
|
+
};
|
|
58
|
+
}, [active]);
|
|
59
|
+
return ref;
|
|
60
|
+
}
|
|
61
|
+
function getElements(ref) {
|
|
62
|
+
const focusables = [
|
|
63
|
+
"button",
|
|
64
|
+
"[href]",
|
|
65
|
+
"input",
|
|
66
|
+
"select",
|
|
67
|
+
"textarea",
|
|
68
|
+
'[tabindex]:not([tabindex="-1"])'
|
|
69
|
+
];
|
|
70
|
+
const elements = [
|
|
71
|
+
...ref.querySelectorAll(focusables.join(", "))
|
|
72
|
+
];
|
|
73
|
+
if (ref.getAttribute("tabindex") === "0") {
|
|
74
|
+
elements.unshift(ref);
|
|
75
|
+
}
|
|
76
|
+
const firstElement = elements[0];
|
|
77
|
+
const lastElement = elements[elements.length - 1];
|
|
78
|
+
return { firstElement, lastElement };
|
|
79
|
+
}
|
|
80
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
81
|
+
0 && (module.exports = {
|
|
82
|
+
useFocusTrap
|
|
83
|
+
});
|
|
84
|
+
//# sourceMappingURL=index.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/useFocusTrap/index.ts","../../src/useFocusTrap/useFocusTrap.ts"],"sourcesContent":["export { useFocusTrap } from \"./useFocusTrap\";\n","import { useEffect, useRef } from \"react\";\n\n/**\n * Traps the focus within the children of the ref element.\n *\n * @param active - Turns the focus trapping on or off. Also adds aria-hidden on the\n * body but not the dialog.\n *\n * @returns ref\n */\nexport function useFocusTrap<T extends HTMLElement>(active: boolean) {\n // There's an ongoing issue with useRef return type clashing with an element's\n // ref prop type. TLDR: Use null because useRef doesn't expect undefined.\n // https://github.com/DefinitelyTyped/DefinitelyTyped/issues/35572\n const ref = useRef<T>(null);\n\n function handleKeyDown(event: KeyboardEvent) {\n if (!(active && ref.current) || event.key !== \"Tab\") {\n return;\n }\n\n const { firstElement, lastElement } = getElements(ref.current);\n\n if (event.shiftKey) {\n if (document.activeElement === firstElement) {\n lastElement.focus();\n event.preventDefault();\n }\n } else {\n if (document.activeElement === lastElement) {\n firstElement.focus();\n event.preventDefault();\n }\n }\n }\n\n useEffect(() => {\n if (active && ref.current) {\n const { firstElement } = getElements(ref.current);\n firstElement.focus();\n ref.current.addEventListener(\"keydown\", handleKeyDown);\n }\n\n return () => {\n ref.current?.removeEventListener(\"keydown\", handleKeyDown);\n };\n }, [active]);\n\n return ref;\n}\n\nfunction getElements<T extends HTMLElement>(ref: T) {\n const focusables = [\n \"button\",\n \"[href]\",\n \"input\",\n \"select\",\n \"textarea\",\n '[tabindex]:not([tabindex=\"-1\"])',\n ];\n const elements = [\n ...ref.querySelectorAll<HTMLElement>(focusables.join(\", \")),\n ];\n\n // If the ref is focusable, ensure it's the first element to be focused.\n if (ref.getAttribute(\"tabindex\") === \"0\") {\n elements.unshift(ref);\n }\n\n const firstElement = elements[0];\n const lastElement = elements[elements.length - 1];\n\n return { firstElement, lastElement };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,mBAAkC;AAU3B,SAAS,aAAoC,QAAiB;AAInE,QAAM,UAAM,qBAAU,IAAI;AAE1B,WAAS,cAAc,OAAsB;AAC3C,QAAI,EAAE,UAAU,IAAI,YAAY,MAAM,QAAQ,OAAO;AACnD;AAAA,IACF;AAEA,UAAM,EAAE,cAAc,YAAY,IAAI,YAAY,IAAI,OAAO;AAE7D,QAAI,MAAM,UAAU;AAClB,UAAI,SAAS,kBAAkB,cAAc;AAC3C,oBAAY,MAAM;AAClB,cAAM,eAAe;AAAA,MACvB;AAAA,IACF,OAAO;AACL,UAAI,SAAS,kBAAkB,aAAa;AAC1C,qBAAa,MAAM;AACnB,cAAM,eAAe;AAAA,MACvB;AAAA,IACF;AAAA,EACF;AAEA,8BAAU,MAAM;AACd,QAAI,UAAU,IAAI,SAAS;AACzB,YAAM,EAAE,aAAa,IAAI,YAAY,IAAI,OAAO;AAChD,mBAAa,MAAM;AACnB,UAAI,QAAQ,iBAAiB,WAAW,aAAa;AAAA,IACvD;AAEA,WAAO,MAAM;AA3CjB;AA4CM,gBAAI,YAAJ,mBAAa,oBAAoB,WAAW;AAAA,IAC9C;AAAA,EACF,GAAG,CAAC,MAAM,CAAC;AAEX,SAAO;AACT;AAEA,SAAS,YAAmC,KAAQ;AAClD,QAAM,aAAa;AAAA,IACjB;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACA,QAAM,WAAW;AAAA,IACf,GAAG,IAAI,iBAA8B,WAAW,KAAK,IAAI,CAAC;AAAA,EAC5D;AAGA,MAAI,IAAI,aAAa,UAAU,MAAM,KAAK;AACxC,aAAS,QAAQ,GAAG;AAAA,EACtB;AAEA,QAAM,eAAe,SAAS,CAAC;AAC/B,QAAM,cAAc,SAAS,SAAS,SAAS,CAAC;AAEhD,SAAO,EAAE,cAAc,YAAY;AACrC;","names":[]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/useFocusTrap/useFocusTrap.ts"],"sourcesContent":["import { useEffect, useRef } from \"react\";\n\n/**\n * Traps the focus within the children of the ref element.\n *\n * @param active - Turns the focus trapping on or off. Also adds aria-hidden on the\n * body but not the dialog.\n *\n * @returns ref\n */\nexport function useFocusTrap<T extends HTMLElement>(active: boolean) {\n // There's an ongoing issue with useRef return type clashing with an element's\n // ref prop type. TLDR: Use null because useRef doesn't expect undefined.\n // https://github.com/DefinitelyTyped/DefinitelyTyped/issues/35572\n const ref = useRef<T>(null);\n\n function handleKeyDown(event: KeyboardEvent) {\n if (!(active && ref.current) || event.key !== \"Tab\") {\n return;\n }\n\n const { firstElement, lastElement } = getElements(ref.current);\n\n if (event.shiftKey) {\n if (document.activeElement === firstElement) {\n lastElement.focus();\n event.preventDefault();\n }\n } else {\n if (document.activeElement === lastElement) {\n firstElement.focus();\n event.preventDefault();\n }\n }\n }\n\n useEffect(() => {\n if (active && ref.current) {\n const { firstElement } = getElements(ref.current);\n firstElement.focus();\n ref.current.addEventListener(\"keydown\", handleKeyDown);\n }\n\n return () => {\n ref.current?.removeEventListener(\"keydown\", handleKeyDown);\n };\n }, [active]);\n\n return ref;\n}\n\nfunction getElements<T extends HTMLElement>(ref: T) {\n const focusables = [\n \"button\",\n \"[href]\",\n \"input\",\n \"select\",\n \"textarea\",\n '[tabindex]:not([tabindex=\"-1\"])',\n ];\n const elements = [\n ...ref.querySelectorAll<HTMLElement>(focusables.join(\", \")),\n ];\n\n // If the ref is focusable, ensure it's the first element to be focused.\n if (ref.getAttribute(\"tabindex\") === \"0\") {\n elements.unshift(ref);\n }\n\n const firstElement = elements[0];\n const lastElement = elements[elements.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@@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
|
|
20
|
+
// src/useInView/index.ts
|
|
21
|
+
var useInView_exports = {};
|
|
22
|
+
__export(useInView_exports, {
|
|
23
|
+
useInView: () => useInView
|
|
24
|
+
});
|
|
25
|
+
module.exports = __toCommonJS(useInView_exports);
|
|
26
|
+
|
|
27
|
+
// src/useInView/useInView.ts
|
|
28
|
+
var import_react = require("react");
|
|
29
|
+
function useInView() {
|
|
30
|
+
const ref = (0, import_react.useRef)(null);
|
|
31
|
+
const [isInView, setIsInView] = (0, import_react.useState)(false);
|
|
32
|
+
const handleIntersection = (0, import_react.useCallback)(
|
|
33
|
+
(entries) => setIsInView(entries[0].isIntersecting),
|
|
34
|
+
[setIsInView]
|
|
35
|
+
);
|
|
36
|
+
(0, import_react.useEffect)(() => {
|
|
37
|
+
if (!window.IntersectionObserver)
|
|
38
|
+
return;
|
|
39
|
+
const observer = new IntersectionObserver(handleIntersection);
|
|
40
|
+
ref.current && observer.observe(ref.current);
|
|
41
|
+
return () => {
|
|
42
|
+
ref.current && observer.unobserve(ref.current);
|
|
43
|
+
};
|
|
44
|
+
}, [handleIntersection, ref.current]);
|
|
45
|
+
return [ref, isInView];
|
|
46
|
+
}
|
|
47
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
48
|
+
0 && (module.exports = {
|
|
49
|
+
useInView
|
|
50
|
+
});
|
|
51
|
+
//# sourceMappingURL=index.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/useInView/index.ts","../../src/useInView/useInView.ts"],"sourcesContent":["export * from \"./useInView\";\n","import { RefObject, useCallback, useEffect, useRef, useState } from \"react\";\n\nexport function useInView<T extends Element>(): [RefObject<T>, boolean] {\n const ref = useRef<T>(null);\n const [isInView, setIsInView] = useState(false);\n\n const handleIntersection: IntersectionObserverCallback = useCallback(\n entries => setIsInView(entries[0].isIntersecting),\n [setIsInView],\n );\n\n useEffect(() => {\n if (!window.IntersectionObserver) return;\n\n const observer = new IntersectionObserver(handleIntersection);\n ref.current && observer.observe(ref.current);\n\n return () => {\n ref.current && observer.unobserve(ref.current);\n };\n }, [handleIntersection, ref.current]);\n\n return [ref, isInView];\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,mBAAoE;AAE7D,SAAS,YAAwD;AACtE,QAAM,UAAM,qBAAU,IAAI;AAC1B,QAAM,CAAC,UAAU,WAAW,QAAI,uBAAS,KAAK;AAE9C,QAAM,yBAAmD;AAAA,IACvD,aAAW,YAAY,QAAQ,CAAC,EAAE,cAAc;AAAA,IAChD,CAAC,WAAW;AAAA,EACd;AAEA,8BAAU,MAAM;AACd,QAAI,CAAC,OAAO;AAAsB;AAElC,UAAM,WAAW,IAAI,qBAAqB,kBAAkB;AAC5D,QAAI,WAAW,SAAS,QAAQ,IAAI,OAAO;AAE3C,WAAO,MAAM;AACX,UAAI,WAAW,SAAS,UAAU,IAAI,OAAO;AAAA,IAC/C;AAAA,EACF,GAAG,CAAC,oBAAoB,IAAI,OAAO,CAAC;AAEpC,SAAO,CAAC,KAAK,QAAQ;AACvB;","names":[]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/useInView/useInView.ts"],"sourcesContent":["import { RefObject, useCallback, useEffect, useRef, useState } from \"react\";\n\nexport function useInView<T extends Element>(): [RefObject<T>, boolean] {\n const ref = useRef<T>(null);\n const [isInView, setIsInView] = useState(false);\n\n const handleIntersection: IntersectionObserverCallback = useCallback(\n entries => setIsInView(entries[0].isIntersecting),\n [setIsInView],\n );\n\n useEffect(() => {\n if (!window.IntersectionObserver) return;\n\n const observer = new IntersectionObserver(handleIntersection);\n ref.current && observer.observe(ref.current);\n\n return () => {\n ref.current && observer.unobserve(ref.current);\n };\n }, [handleIntersection, ref.current]);\n\n return [ref, isInView];\n}\n"],"mappings":";AAAA,SAAoB,aAAa,WAAW,QAAQ,gBAAgB;AAE7D,SAAS,YAAwD;AACtE,QAAM,MAAM,OAAU,IAAI;AAC1B,QAAM,CAAC,UAAU,WAAW,IAAI,SAAS,KAAK;AAE9C,QAAM,qBAAmD;AAAA,IACvD,aAAW,YAAY,QAAQ,CAAC,EAAE,cAAc;AAAA,IAChD,CAAC,WAAW;AAAA,EACd;AAEA,YAAU,MAAM;AACd,QAAI,CAAC,OAAO;AAAsB;AAElC,UAAM,WAAW,IAAI,qBAAqB,kBAAkB;AAC5D,QAAI,WAAW,SAAS,QAAQ,IAAI,OAAO;AAE3C,WAAO,MAAM;AACX,UAAI,WAAW,SAAS,UAAU,IAAI,OAAO;AAAA,IAC/C;AAAA,EACF,GAAG,CAAC,oBAAoB,IAAI,OAAO,CAAC;AAEpC,SAAO,CAAC,KAAK,QAAQ;AACvB;","names":[]}
|