UNPKG

1.91 kBJavaScriptView Raw
1"use strict";
2
3exports.__esModule = true;
4exports.valueMatcher = valueMatcher;
5exports.dataIndexOf = dataIndexOf;
6exports.dataItem = dataItem;
7exports.useAccessors = exports.dataText = exports.dataValue = void 0;
8
9var _react = require("react");
10
11const dataValue = (dataItem, field) => {
12 if (typeof field === 'function') return field(dataItem);
13 if (dataItem == null) return dataItem;
14 if (typeof field === 'string' && typeof dataItem === 'object' && field in dataItem) return dataItem[field];
15 return dataItem;
16};
17
18exports.dataValue = dataValue;
19
20const dataText = (dataItem, textField) => {
21 const value = dataValue(dataItem, textField);
22 return value == null ? '' : String(value);
23};
24/**
25 * I don't know that the shallow equal makes sense here but am too afraid to
26 * remove it.
27 */
28
29
30exports.dataText = dataText;
31
32function valueMatcher(a, b, dataKey) {
33 return dataValue(a, dataKey) === dataValue(b, dataKey);
34}
35
36function dataIndexOf(data, value, dataKey) {
37 const valueDataKey = dataValue(value, dataKey);
38 let idx = -1;
39
40 while (++idx < data.length) {
41 const datum = data[idx];
42 if (datum === value || dataValue(datum, dataKey) === valueDataKey) return idx;
43 }
44
45 return -1;
46}
47
48function dataItem(data, value, dataKey) {
49 const idx = dataIndexOf(data, value, dataKey); // This isn't strictly safe, but we want to allow items that aren't in the list
50
51 return idx !== -1 ? data[idx] : value;
52}
53
54const useAccessors = (textField, dataKey) => {
55 return (0, _react.useMemo)(() => ({
56 text: item => dataText(item, textField),
57 value: item => dataValue(item, dataKey),
58 indexOf: (data, value) => dataIndexOf(data, value, dataKey),
59 matches: (a, b) => valueMatcher(a, b, dataKey),
60 findOrSelf: (data, value) => dataItem(data, value, dataKey),
61 includes: (data, value) => dataIndexOf(data, value, dataKey) !== -1
62 }), [textField, dataKey]);
63};
64
65exports.useAccessors = useAccessors;
\No newline at end of file